You are not logged in Log in Join
You are here: Home » Members » Toby Dickenson » cache » 1 » cPickleCache.c » View File

Log in
Name

Password

 

cPickleCache.c

File details
Size
27 K
File type
text/plain

File contents

/*****************************************************************************
  
  Zope Public License (ZPL) Version 1.0
  -------------------------------------
  
  Copyright (c) Digital Creations.  All rights reserved.
  
  This license has been certified as Open Source(tm).
  
  Redistribution and use in source and binary forms, with or without
  modification, are permitted provided that the following conditions are
  met:
  
  1. Redistributions in source code must retain the above copyright
     notice, this list of conditions, and the following disclaimer.
  
  2. Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions, and the following disclaimer in
     the documentation and/or other materials provided with the
     distribution.
  
  3. Digital Creations requests that attribution be given to Zope
     in any manner possible. Zope includes a "Powered by Zope"
     button that is installed by default. While it is not a license
     violation to remove this button, it is requested that the
     attribution remain. A significant investment has been put
     into Zope, and this effort will continue if the Zope community
     continues to grow. This is one way to assure that growth.
  
  4. All advertising materials and documentation mentioning
     features derived from or use of this software must display
     the following acknowledgement:
  
       "This product includes software developed by Digital Creations
       for use in the Z Object Publishing Environment
       (http://www.zope.org/)."
  
     In the event that the product being advertised includes an
     intact Zope distribution (with copyright and license included)
     then this clause is waived.
  
  5. Names associated with Zope or Digital Creations must not be used to
     endorse or promote products derived from this software without
     prior written permission from Digital Creations.
  
  6. Modified redistributions of any form whatsoever must retain
     the following acknowledgment:
  
       "This product includes software developed by Digital Creations
       for use in the Z Object Publishing Environment
       (http://www.zope.org/)."
  
     Intact (re-)distributions of any official Zope release do not
     require an external acknowledgement.
  
  7. Modifications are encouraged but must be packaged separately as
     patches to official Zope releases.  Distributions that do not
     clearly separate the patches from the original work must be clearly
     labeled as unofficial distributions.  Modifications which do not
     carry the name Zope may be packaged in any form, as long as they
     conform to all of the clauses above.
  
  
  Disclaimer
  
    THIS SOFTWARE IS PROVIDED BY DIGITAL CREATIONS ``AS IS'' AND ANY
    EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
    PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL DIGITAL CREATIONS OR ITS
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
    LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
    USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
    ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
    OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
    OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
    SUCH DAMAGE.
  
  
  This software consists of contributions made by Digital Creations and
  many individuals on behalf of Digital Creations.  Specific
  attributions are listed in the accompanying credits file.
  
 ****************************************************************************/
static char cPickleCache_doc_string[] = 
"Defines the PickleCache used by ZODB Connection objects.\n"
"\n"
"$Id$\n";

#define ASSIGN(V,E) {PyObject *__e; __e=(E); Py_XDECREF(V); (V)=__e;}
#define UNLESS(E) if(!(E))
#define UNLESS_ASSIGN(V,E) ASSIGN(V,E) UNLESS(V)
#define OBJECT(O) ((PyObject*)O)

#define DONT_USE_CPERSISTENCECAPI
#include "cPersistence.h"
#include <time.h>
#include <stddef.h>

#undef Py_FindMethod

/* changes of interest:

   * cache values can no longer be persistant classes, only instances of such classes.
     I think this breaks ZClasses.

   * cache objects must have a correct _p_oid attribute. this is now enforced.

   * cache.cache_data is now a copy of the cache dict, to prevent changes
     to our underlying data

   * cache_size now controls the number of non-ghost items. This is
     a better measure of memory usage, but you probably want to
     use a number 10 times smaller than under the previous
     implementation.

   * all persistent extension classes must be changed to
     use the PER_GHOSTIFY macro rather than assign to
     cPersistent_GHOST_STATE

*/

static PyObject *py_reload, *py__p_jar, *py__p_changed;

/* define this for extra debugging checks. */
/* #define MUCH_RING_CHECKING 1 */

#if 1
#define ENGINE_NOISE(A) printf(A)
#else
#define ENGINE_NOISE(A) ((void)A)
#endif

/* the layout of this struct is the same as the start of ccobject_head in cPersistence.c */
typedef struct {
  PyObject_HEAD
  CPersistentRing ring_home;
  int non_ghost_count;
  PyObject *data;
  PyObject *jar;
  PyObject *setklassstate;
  int cache_size;
  int ring_lock;
  int cache_drain_resistance;
} ccobject;

staticforward PyTypeObject Cctype;


staticforward int check_ring(ccobject *self,const char *context);
staticforward int cc_ass_sub(ccobject *self, PyObject *key, PyObject *v);

/* ---------------------------------------------------------------- */

static cPersistentObject *object_from_oid(ccobject *self,PyObject *key)
/* somewhat of a replacement for PyDict_GetItem(self->data....
   however this returns a *new* reference */
{
    PyObject *v = PyDict_GetItem(self->data, key);
    if(!v) return NULL;

    Py_INCREF(v);

    return (cPersistentObject *)v;
}

/*
static int 
gc_item(ccobject *self, PyObject *key, PyObject *v, long now, int dt)
{

  if (v && key)
    {
      if(v->ob_refcnt <= 1)
	{
          return cc_ass_sub(self,key,0);
	}

      if (dt && 
	  (! PyExtensionClass_Check(v)) &&
	  ((cPersistentObject*)v)->jar==self->jar / * I'm paranoid * / &&
	  ((cPersistentObject*)v)->state==cPersistent_UPTODATE_STATE
	  )
	{
	  if (now > dt)
	    {
	      / * We have a cPersistent object that hasn't been used in
		 a while.  Reinitialize it, hopefully freeing it's
		 state.
	      * /
	      if (PyObject_SetAttr(v,py__p_changed,Py_None) < 0)
		PyErr_Clear();
	    }
	}
    }
  return 0;
}
*/

static int
fullgc(ccobject *self, int dt)
{/*
  PyObject *key, *v;
  int i;
  long now;

  if (self->cache_size < 1) return 0;
  if ((i=PyDict_Size(self->data)) < 1) return 0;

  now=((long)(time(NULL)/3))%65536;
  if (dt < 0) dt=0;
  else dt /= 3;

  for(i=0; PyDict_Next(self->data, &i, &key, &v); )
    if(gc_item(self,key,v,now,dt) < 0) return -1;
  self->position=0;

  if(now-self->last_check > 1) update_stats(self, now);
           */
  return 0;
}

static int
reallyfullgc(ccobject *self, int dt)
{
/*  PyObject *key, *v;
  int i, l, last;
  time_t now;

  if (self->cache_size < 1) return 0;
  if((last=PyDict_Size(self->data)) < 0) return -1;

  now=((long)(time(NULL)/3))%65536;
  if (dt < 0) dt=0;
  else dt /= 3;

  / * First time through should get refcounts to 1 * /
  for(i=0; PyDict_Next(self->data, &i, &key, &v); )
    if(gc_item(self,key,v,now,dt) < 0) return -1;

  if((l=PyDict_Size(self->data)) < 0) return -1;
  while(l < last)
    {
      for(i=0; PyDict_Next(self->data, &i, &key, &v); )
	if(gc_item(self,key,v,now,dt) < 0) return -1;
      last=l;
      if((l=PyDict_Size(self->data)) < 0) return -1;
    }

  if(now-self->last_check > 1) update_stats(self, now);

  self->position=0;*/
  return 0;
}

static cPersistentObject *object_from_ring(ccobject *self,CPersistentRing *here)
{
    /* Given a position in the LRU ring, return a borrowed
    reference to the object at that point in the ring. The caller is
    responsible for ensuring that this ring position really does
    correspond to a persistent object, although the debugging
    version will double-check this. */

    PyObject *object = (PyObject *)(((void *)here)-offsetof(cPersistentObject,ring));

#ifdef MUCH_RING_CHECKING
    if(!PyExtensionInstance_Check(object))
    {
        PyErr_SetString(PyExc_RuntimeError,"Unexpectedly encountered non-ExtensionClass object in scan_gc_item");
        return NULL;
    }
    if(!(((PyExtensionClass*)(object->ob_type))->class_flags & PERSISTENT_TYPE_FLAG))
    {
        PyErr_SetString(PyExc_RuntimeError,"Unexpectedly encountered non-persistent object in scan_gc_item");
        return NULL;
    }
    if(((cPersistentObject*)object)->jar!=self->jar)
    {
        PyErr_SetString(PyExc_RuntimeError,"Unexpectedly encountered object from a different jar in scan_gc_item");
        return NULL;
    }
    if(((cPersistentObject*)object)->cache!=(PyObject *)self)
    {
        PyErr_SetString(PyExc_RuntimeError,"Unexpectedly encountered broken ring in scan_gc_item");
        return NULL;
    }
#endif
    return (cPersistentObject *)object;
}

static int
scan_gc_items(ccobject *self,int target)
{
    PyObject *object;
    int error;
    CPersistentRing placeholder;

    CPersistentRing *here = self->ring_home.next;
    while(1)
    {
        if(check_ring(self,"mid-gc")) return -1;

        if(here==&self->ring_home)
        {
            /* back to the home poisition and found nothing to collect. stop looking */
            return 0;
        }

        /* At this point we know that the ring only contains nodes from
        persistent objects, plus our own home node. We can safely
        assume this is a persistent object now we know it is not the home */
        object = (PyObject *)object_from_ring(self,here);
        if(!object) return -1;

        if(object->ob_refcnt <= 1)
        {
            /* An unreferenced object. Remove it from the cache.
            this is nice to do, it decreases the total population count,
            but probably doesnt gain us very much because most of these
            objects will already have been ghosted. */

            PyObject *key = ((cPersistentObject*)object)->oid;

#ifdef MUCH_RING_CHECKING
            cPersistentObject *object_again = object_from_oid(self, key);
            if(!object_again)
            {
                return 1;
            }
            if(object_again!=(cPersistentObject*)object)
            {
                Py_DECREF(object_again);
                PyErr_SetString(PyExc_RuntimeError,"wrong key in scan_gc_item");
                return 1;
            }
            Py_DECREF(object_again);
#endif

            ENGINE_NOISE("U");

            /* removing things from the cache may cause the lru order
            of some persistent object to shuffle, therefore we temporarily
            insert a position marker. */
            placeholder.next = here->next;
            placeholder.prev = here;
            here->next->prev = &placeholder;
            here->next       = &placeholder;

            error = cc_ass_sub(self,key,0);

            /* unlink the placeholder */
            placeholder.next->prev=placeholder.prev;
            placeholder.prev->next=placeholder.next;

            here = placeholder.next;

            if(error)
                return 1; /* problem */
        }
        else if(self->non_ghost_count<=target)
        {
            /* we are small enough */
            return 0;
        }
        else if(((cPersistentObject*)object)->state==cPersistent_UPTODATE_STATE)
        {
            /* deactivate it. This is the main memory saver. */

            ENGINE_NOISE("G");

            /* add a placeholder */
            placeholder.next = here->next;
            placeholder.prev = here;
            here->next->prev = &placeholder;
            here->next       = &placeholder;

            error = PyObject_SetAttr(object,py__p_changed,Py_None);

            /* unlink the placeholder */
            placeholder.next->prev=placeholder.prev;
            placeholder.prev->next=placeholder.next;

            here = placeholder.next;

            if(error)
                return 1; /* problem */
        }
        else
        {
            ENGINE_NOISE(".");

            here = here->next;
        }
    }
}


static int
maybegc(ccobject *self)
{
    int starting_size = self->non_ghost_count;

    int target_size = self->cache_size;

    if(self->cache_drain_resistance>=1)
    {
        /* This cache will gradually drain down to a small size. Check
           a (small) number of objects proportional to the current size */

        int target_size_2 = starting_size - 1 - starting_size/self->cache_drain_resistance;
        if(target_size_2<target_size)
            target_size = target_size_2;
    }

    return scan_gc_items(self,target_size);
}



static PyObject *
cc_full_sweep(ccobject *self, PyObject *args)
{
  int dt=0;
  UNLESS(PyArg_ParseTuple(args, "|i", &dt)) return NULL;
  UNLESS(-1 != fullgc(self,dt)) return NULL;
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
cc_reallyfull_sweep(ccobject *self, PyObject *args)
{
  int dt=0;
  UNLESS(PyArg_ParseTuple(args, "|i", &dt)) return NULL;
  UNLESS(-1 != reallyfullgc(self,dt)) return NULL;
  Py_INCREF(Py_None);
  return Py_None;
}

static PyObject *
cc_incrgc(ccobject *self, PyObject *args)
{
  int n=1;

  UNLESS (PyArg_ParseTuple(args, "|i",&n)) return NULL;

  if(self->ring_lock)
  {
      Py_INCREF(Py_None);
      return Py_None;
  }

  if(check_ring(self,"pre-incrgc")) return NULL;
  self->ring_lock = 1;
  if(maybegc(self) < 0)
  {
      self->ring_lock = 0;
      return NULL;
  }
  self->ring_lock = 0;
  if(check_ring(self,"post-incrgc")) return NULL;
  ENGINE_NOISE("\n");

  Py_INCREF(Py_None);
  return Py_None;
}

static void
_invalidate(ccobject *self, PyObject *key)
{
    PyObject *v=(PyObject *)object_from_oid(self, key);

    if(!v)
    {
        /* shouldnt this be an error? for now Ill follow Jims lead */
        PyErr_Clear();
    }
    else
    {
        if(PyObject_DelAttr(v,py__p_changed) < 0)
            PyErr_Clear();
        Py_DECREF(v);
    }
}

static PyObject *
cc_invalidate(ccobject *self, PyObject *args)
{
  PyObject *inv, *key, *v;
  int i;
  
  if (PyArg_ParseTuple(args, "O!", &PyDict_Type, &inv)) {
    for (i=0; PyDict_Next(inv, &i, &key, &v); ) 
      if (key==Py_None)
	{ /* Eek some nitwit invalidated everything! */
	  for (i=0; PyDict_Next(self->data, &i, &key, &v); )
	    _invalidate(self, key);
	  break;
	}
      else
	_invalidate(self, key);
    PyDict_Clear(inv);
  }
  else {
    PyErr_Clear();
    UNLESS (PyArg_ParseTuple(args, "O", &inv)) return NULL;
    if (PyString_Check(inv))
      _invalidate(self, inv);
    else if (inv==Py_None)	/* All */
      for (i=0; PyDict_Next(self->data, &i, &key, &v); )
	_invalidate(self, key);
    else {
      int l;

      PyErr_Clear();
      if ((l=PyObject_Length(inv)) < 0) return NULL;
      for(i=l; --i >= 0; )
	{
	  UNLESS (key=PySequence_GetItem(inv, i)) return NULL;
	  _invalidate(self, key);
	  Py_DECREF(key);
	}
      PySequence_DelSlice(inv, 0, l);
    }
  }

  Py_INCREF(Py_None);
  return Py_None;
}
  
  
static PyObject *
cc_get(ccobject *self, PyObject *args)
{
  PyObject *r, *key, *d=0;

  UNLESS (PyArg_ParseTuple(args,"O|O", &key, &d)) return NULL;

  UNLESS (r=(PyObject *)object_from_oid(self, key))
    {
      if (d) 
	{
	  PyErr_Clear();
	  r=d;
          Py_INCREF(r);
	}
      else
	{
	  PyErr_SetObject(PyExc_KeyError, key);
	  return NULL;
	}
    }

  return r;
}

static PyObject *
cc_items(ccobject *self, PyObject *args)
{
    PyObject *l;
    CPersistentRing *here;

    if(!PyArg_ParseTuple(args,"")) return NULL;

    if(self->ring_lock)
    {
        PyErr_SetString(PyExc_ValueError,".items() is unavailable during garbage collection");
        return NULL;
    }

    if(check_ring(self,"pre-cc_items")) return NULL;

    l = PyList_New(0);
    if(!l) return NULL;

    here = self->ring_home.next;
    while(here!=&self->ring_home)
    {
        cPersistentObject *object = object_from_ring(self,here);
        PyObject *v;
        if(!object)
        {
            Py_DECREF(l);
            return NULL;
        }
        v=PyObject_CallMethod(l,"append","((OO))",object->oid,object);
        if(!v)
        {
            Py_DECREF(l);
            return NULL;
        }
        Py_DECREF(v);
        here = here->next;
    }

    return l;
}


static struct PyMethodDef cc_methods[] = {
  {"items", (PyCFunction)cc_items, METH_VARARGS,
   "List (oid, object) pairs, as 2-tuples. This implementation\n"
   "orders pairs with the most recently accessed objects last\n"
   },
  {"full_sweep", (PyCFunction)cc_full_sweep, METH_VARARGS,
   "full_sweep([age]) -- Perform a full sweep of the cache\n\n"
   "Make a single pass through the cache, removing any objects that are no\n"
   "longer referenced, and deactivating enough objects to bring\n"
   "the cache under its size limit\n"
   "The optional 'age' parameter is ignored.\n"
   },
  {"minimize",	(PyCFunction)cc_reallyfull_sweep, METH_VARARGS,
   "minimize([age]) -- Remove as many objects as possible\n\n"
   "Make multiple passes through the cache, removing any objects that are no\n"
   "longer referenced, and deactivating enough objects to bring the"
   " cache under its size limit\n"
   "The option 'age' parameter is ignored.\n"
   },
  {"incrgc", (PyCFunction)cc_incrgc, METH_VARARGS,
   "incrgc([n]) -- Perform incremental garbage collection\n\n"
   "Some other implementations support an optional parameter 'n' which\n"
   "indicates a repetition count; this value is ignored.\n"},
  {"invalidate", (PyCFunction)cc_invalidate, METH_VARARGS,
   "invalidate(oids) -- invalidate one, many, or all ids"},
  {"get", (PyCFunction)cc_get, METH_VARARGS,
   "get(key [, default]) -- get an item, or a default"},
  {NULL,		NULL}		/* sentinel */
};

static ccobject *
newccobject(PyObject *jar, int cache_size, int cache_age)
{
  ccobject *self;
  
  UNLESS(self = PyObject_NEW(ccobject, &Cctype)) return NULL;
  self->setklassstate=self->jar=NULL;
  if((self->data=PyDict_New()))
    {
      self->jar=jar; 
      Py_INCREF(jar);
      UNLESS (self->setklassstate=PyObject_GetAttrString(jar, "setklassstate"))
	return NULL;
      self->cache_size=cache_size;
      self->non_ghost_count=0;
      self->cache_drain_resistance=0;
      self->ring_lock=0;
      self->ring_home.next = &self->ring_home;
      self->ring_home.prev = &self->ring_home;
      return self;
    }
  Py_DECREF(self);
  return NULL;
}

static void
cc_dealloc(ccobject *self)
{
  Py_XDECREF(self->data);
  Py_XDECREF(self->jar);
  Py_XDECREF(self->setklassstate);
  PyMem_DEL(self);
}

static PyObject *
cc_getattr(ccobject *self, char *name)
{
  PyObject *r;

  if(check_ring(self,"getattr")) return NULL;

  if(*name=='c')
    {
      if(strcmp(name,"cache_age")==0)
	return PyInt_FromLong(0);   /* this cache does not use this value */
      if(strcmp(name,"cache_size")==0)
	return PyInt_FromLong(self->cache_size);
      if(strcmp(name,"cache_drain_resistance")==0)
	return PyInt_FromLong(self->cache_drain_resistance);
      if(strcmp(name,"cache_non_ghost_count")==0)
	return PyInt_FromLong(self->non_ghost_count);
      if(strcmp(name,"cache_data")==0)
	{
	  /* now a copy of our data; the ring is too fragile */
	  return PyDict_Copy(self->data);
	}
    }
  if((*name=='h' && strcmp(name, "has_key")==0) ||
     /*(*name=='i' && strcmp(name, "items")==0) || */      /* not any more; we have our own implementation */
     (*name=='k' && strcmp(name, "keys")==0)
     )
    return PyObject_GetAttrString(self->data, name);

  if((r=Py_FindMethod(cc_methods, (PyObject *)self, name)))
    return r;
  PyErr_Clear();
  return PyObject_GetAttrString(self->data, name);
}

static int
cc_setattr(ccobject *self, char *name, PyObject *value)
{
  if(value)
    {
      int v;

      if(strcmp(name,"cache_age")==0)
	{
	  /* this cache doesnt use the age */
	  return 0;
	}

      if(strcmp(name,"cache_size")==0)
	{
	  UNLESS(PyArg_Parse(value,"i",&v)) return -1;
	  self->cache_size=v;
	  return 0;
	}

      if(strcmp(name,"cache_drain_resistance")==0)
	{
	  UNLESS(PyArg_Parse(value,"i",&v)) return -1;
	  self->cache_drain_resistance=v;
	  return 0;
	}
    }
  PyErr_SetString(PyExc_AttributeError, name);
  return -1;
}

static int
cc_length(ccobject *self)
{
  return PyObject_Length(self->data);
}
  
static PyObject *
cc_subscript(ccobject *self, PyObject *key)
{
  PyObject *r;

  if(check_ring(self,"__getitem__")) return NULL;

  UNLESS (r=(PyObject *)object_from_oid(self, key))
  {
    PyErr_SetObject(PyExc_KeyError, key);
    return NULL;
  }

  return r;
}

static int
cc_ass_sub(ccobject *self, PyObject *key, PyObject *v)
{
    int result;
    if(v)
    {
        if(PyExtensionInstance_Check(v) &&
           (((PyExtensionClass*)(v->ob_type))->class_flags & PERSISTENT_TYPE_FLAG) &&
	   (v->ob_type->tp_basicsize >= sizeof(cPersistentObject))
	  )
        {
            if(PyObject_Cmp(key,((cPersistentObject*)v)->oid,&result))
            {
                return 1;
            }
            if(result)
            {
                PyErr_SetString(PyExc_ValueError,"key must be the same as the object's oid attribute");
                return 1;
            }
            if(((cPersistentObject*)v)->cache)
            {
                if(((cPersistentObject*)v)->cache==(PyObject *)self)
                {
                    /* This object is already one of ours, which is ok.
                    It would be very strange if someone was trying to register the
                    same object under a different key */
                    cPersistentObject *object_again = object_from_oid(self, key);
                    if(!object_again)
                    {
                        PyErr_SetString(PyExc_RuntimeError,"missing object in cc_ass_sub");
                        return 1;
                    }
                    else if(object_again!=(cPersistentObject *)v)
                    {
                        Py_DECREF(object_again);
                        PyErr_SetString(PyExc_ValueError,"Can not re-register object under a different oid");
                        return 1;
                    }
                    else
                    {
                        /* re-register under the same oid - no work needed */
                        Py_DECREF(object_again);
                        return 0;
                    }
                }
                else
                {
                    /* This object is already in a different cache. */
                    PyErr_SetString(PyExc_ValueError, "Cache values may only be in one cache.");
                    return -1;
                }
            }
            else
            {
                if(check_ring(self,"pre-setitem")) return -1;
                if(PyDict_SetItem(self->data, key, v)) return -1;

                /* insert this new object into the ring just behind the home position */
                Py_INCREF(self);
                ((cPersistentObject*)v)->cache = (PyObject *)self;
                ((cPersistentObject*)v)->ring.next = &self->ring_home;
                ((cPersistentObject*)v)->ring.prev = self->ring_home.prev;
                self->ring_home.prev->next = &((cPersistentObject*)v)->ring;
                self->ring_home.prev = &((cPersistentObject*)v)->ring;
                if(((cPersistentObject*)v)->state>=0)
                  self->non_ghost_count++;
                if(check_ring(self,"post-setitem")) return -1;
                return 0;
            }
        }
        else
        {
            PyErr_SetString(PyExc_ValueError, "Cache values must be persistent objects.");
            return -1;
        }
    }
    else
    {
        /* unlink this item from the ring */
        if(check_ring(self,"pre-delitem")) return -1;

        v = (PyObject *)object_from_oid(self,key);
        if(!v) return -1;

        if(((cPersistentObject*)v)->state>=0)
            self->non_ghost_count--;

        Py_DECREF(((cPersistentObject*)v)->cache);
        ((cPersistentObject*)v)->cache = NULL;
        ((cPersistentObject*)v)->ring.next->prev = ((cPersistentObject*)v)->ring.prev;
        ((cPersistentObject*)v)->ring.prev->next = ((cPersistentObject*)v)->ring.next;
        ((cPersistentObject*)v)->ring.prev = NULL;
        ((cPersistentObject*)v)->ring.next = NULL;

        Py_DECREF(v);

        if(PyDict_DelItem(self->data, key))
        {
            PyErr_SetString(PyExc_RuntimeError,
                           "unexpectedly couldnt remove key in cc_ass_sub");
            return -1;
        }

        if(check_ring(self,"post-delitem")) return -1;

        return 0;
    }
}

static int _check_ring(ccobject *self,char *context)
{

    CPersistentRing *here = &(self->ring_home);
    int expected = 1+PyDict_Size(self->data);
    int total = 0;
    int non_ghost_count = 0;
    do
    {
        if(++total>(expected+10)) return 3;            /* ring too big, by a large margin */
        if(!here->next) return 4;                      /* various linking problems */
        if(!here->prev) return 5;
        if(!here->next->prev) return 7;
        if(!here->prev->next) return 8;
        if(here->prev->next!=here) return 9;
        if(here->next->prev!=here) return 10;
        if(!self->ring_lock)
        {
            /* if the ring is unlocked then it only contains persistent objects */
            if(here!=&self->ring_home)
            {
                cPersistentObject *object = object_from_ring(self,here);
                if(!object) return 12;
                if(object->state!=cPersistent_GHOST_STATE)
                    ++non_ghost_count;
            }
        }
        here = here->next;
    }
    while(here!=&self->ring_home);

    if(self->ring_lock)
    {
        if(total<expected) return 6;       /* ring too small; too big is ok when locked */
    }
    else
    {
        if(total!=expected) return 6;      /* ring size wrong */
        if(non_ghost_count!=self->non_ghost_count)
            return 11;      /* bad ghost accounting */
    }


    return 0;
}

static int check_ring(ccobject *self,const char *context)
{
#ifdef MUCH_RING_CHECKING
    int code=_check_ring(self,context);
    if(code)
    {
        PyErr_Format(PyExc_RuntimeError,"broken ring (code %d) in %s, size %d",code,context,PyDict_Size(self->data));
        return code;
    }
#endif
    return 0;
}


static PyMappingMethods cc_as_mapping = {
  (inquiry)cc_length,		/*mp_length*/
  (binaryfunc)cc_subscript,	/*mp_subscript*/
  (objobjargproc)cc_ass_sub,	/*mp_ass_subscript*/
};

static PyTypeObject Cctype = {
  PyObject_HEAD_INIT(NULL)
  0,				/*ob_size*/
  "cPickleCache",		/*tp_name*/
  sizeof(ccobject),		/*tp_basicsize*/
  0,				/*tp_itemsize*/
  /* methods */
  (destructor)cc_dealloc,	/*tp_dealloc*/
  (printfunc)0,			/*tp_print*/
  (getattrfunc)cc_getattr,	/*tp_getattr*/
  (setattrfunc)cc_setattr,	/*tp_setattr*/
  (cmpfunc)0,			/*tp_compare*/
  (reprfunc)0,   		/*tp_repr*/
  0,				/*tp_as_number*/
  0,				/*tp_as_sequence*/
  &cc_as_mapping,		/*tp_as_mapping*/
  (hashfunc)0,			/*tp_hash*/
  (ternaryfunc)0,		/*tp_call*/
  (reprfunc)0,  		/*tp_str*/

  /* Space for future expansion */
  0L,0L,0L,0L,
  ""
};

static PyObject *
cCM_new(PyObject *self, PyObject *args)
{
  int cache_size=100, cache_age=1000;
  PyObject *jar;

  UNLESS(PyArg_ParseTuple(args, "O|ii", &jar, &cache_size, &cache_age))
      return NULL;
  return (PyObject*)newccobject(jar, cache_size,cache_age);
}

static struct PyMethodDef cCM_methods[] = {
  {"PickleCache",(PyCFunction)cCM_new,	METH_VARARGS, ""},
  {NULL,		NULL}		/* sentinel */
};

void
initcPickleCache(void)
{
  PyObject *m, *d;
  char *rev="$Revision$";

  Cctype.ob_type=&PyType_Type;

  UNLESS(ExtensionClassImported) return;

  m = Py_InitModule4("cPickleCache", cCM_methods, cPickleCache_doc_string,
		     (PyObject*)NULL, PYTHON_API_VERSION);

  d = PyModule_GetDict(m);

  py_reload=PyString_FromString("reload");
  py__p_jar=PyString_FromString("_p_jar");
  py__p_changed=PyString_FromString("_p_changed");

  if(!strncmp(rev,"$Revision: ",11))
    PyDict_SetItemString(d,"__version__",
                         PyString_FromStringAndSize(rev+11,strlen(rev+11)-2));
  else
    PyDict_SetItemString(d,"__version__",
                         PyString_FromString("0.0"));
}