Divergences from python-diskcache
diskcache-oxide’s test suite is a conformance suite: the same black-box tests run against real diskcache 5.6.3 and against diskcache-oxide. Where they behave differently, it’s on purpose, and it’s written down here. Running one suite against two implementations turned out to be a bug detector pointed in both directions: most of the differences below are diskcache bugs the suite found, each with a reproduction in the repository’s upstream/ folder.
A divergence is never a way to skip a failing test. The full record, including test names and measurements, is tests/DIVERGENCES.md.
Summary
| Ref | Topic | diskcache 5.6.3 | diskcache-oxide |
|---|---|---|---|
| D-001 | Values | Pickles everything | msgpack or JSON with type tags; pickle opt-in; never unpickles unless opted in |
| D-002 | Database file | cache.db |
diskcache-oxide.sqlite |
| D-003 | Clock | time.time() |
Native; clock= to control it |
| D-004 | Keys | Anything picklable | str, bytes, int, float, bool, None and tuples of those; never pickled |
| D-005 | Minimum size_limit | None; tiny limits silently empty the cache | 1 MiB, else ValueError |
| D-006 | Empty-cache volume() | Its own value | A different value |
| D-007 | Timeout | Subclasses Exception |
Subclasses TimeoutError |
| D-008 | Top-level NaN | Reads back as None |
Round-trips |
| D-009 | Truthiness | Empty cache is falsy | Cache always truthy, NullCache falsy |
| D-010 | expire() | Can stop after 100 rows | Removes every expired entry |
| D-011 | clear() | Also deletes writes made while it runs | Removes only what existed when it started |
| D-012 | Fork during another thread’s write | Child’s writes stall for the timeout | Child can always write |
| D-013 | Missing value file | Miss, but the key still reads as present | Miss, and the row is removed |
| D-014 | expire=True, timeout=True |
Treated as 1 |
TypeError |
| D-015 | New directory permissions | Follow the umask | 0700 |
| D-016 | Reading a large value during an overwrite | Occasional spurious miss | Always the old or new value |
| D-017 | Connections and fds | One connection per thread | A bounded pool |
| D-018 | close() | Closes only the calling thread’s connection | Closes every connection |
| D-019 | Opening an existing cache, and reading | Opening writes to the database | Neither writes, unless the open changes settings; background maintenance writes when it has work, and hourly (maintenance_interval=0 for none) |
| D-020 | Forking inside your own transaction, or a cache call | Child stalls for the timeout | The child can’t use that cache: every call raises ForkedInsideTransactionError (a RuntimeError) at once |
| D-021 | directory | Optional (temp dir) | Required |
| D-022 | disk=, eviction_policy= |
Supported | No disk=; least-recently-stored or 'none', read on every write; LRU and LFU refused |
| D-023 | SQLite memory | 32 MiB cache + 64 MiB mmap per thread | 1 MiB per pooled connection |
| D-024 | WAL file size | Can grow past 1 GiB and stay there | Trimmed; checkpointed by maintenance, and by checkpoint() on demand |
| D-025 | A key iterator used by two threads at once | ValueError from the generator |
ValueError, from a native iterator with no send() or close() |
| D-026 | pop of a value it can’t read | Row is deleted, then the decode fails | Decodes first, so the row stays unless no build could read it |
| D-027 | A call behind a pending fork | Never waits: there’s no fork barrier | Waits within its timeout, then raises Timeout |
| D-028 | An outage on a single-key call | Cache raises; FanoutCache answers Timeout alone as a miss | Raises by default; durable=True answers it as a miss or False, and reports it |
| D-029 | with cache.transact() as tx: |
tx is None; a second handle’s transact() inside waits out the timeout |
tx is the cache; every handle on the directory joins the outer transaction |
| D-030 | A transaction on a second, busy cache | Waits for the timeout; retry=True loops on any OperationalError |
TransactionBusy at once; retry=True retries only Timeout |
| D-031 | Ending a transaction on another thread | “May not be shared between threads” | Allowed, within its timeout; the owner’s exit raises unless it committed |
| D-032 | FanoutCache shard count | Not recorded; a different shards= quietly misroutes keys |
Recorded in a manifest; a different shards= keeps it with a warning, or raises with raise_on_mismatch=True |
| D-033 | Which shard a key lives in | adler32; no iterkeys() | XXH3-64, frozen in the format; shard_of(key); iterkeys() merges the shards in sorted order |
| D-034 | A busy shard on a single-key call | Swallows Timeout (10 ms default); get swallows any OperationalError |
Raises Timeout; durable=True answers it as a miss and reports it |
| D-035 | clear(), expire(), cull() over the shards | Retries each shard forever | One timeout for the call; raises with failed_shards and removed |
| D-036 | size_limit | Divided as a float, no minimum; reads shard 0’s share | Split as integers, 1 MiB per shard minimum; reads back as the total |
| D-037 | max_connections |
One connection per thread per shard (264 fds at 64 threads) | A total across the shards; fds within 2 × max_connections + 2 × shards |
| D-038 | Cache and FanoutCache on each other’s directory | Quietly creates or reuses a database | LayoutMismatchError, creating nothing |
| D-039 | FanoutCache constructor and features | FanoutCache(path, 4); cache(), deque() and index() sub-collections, read() |
shards is keyword-only; no sub-collections or read(); tags, stats(), check() and the rest as on Cache |
| D-040 | FanoutCache.transact() | Locks every shard; tx is None |
transact(*, key) locks one shard and refuses other shards’ keys |
| D-041 | Your own types | A Disk subclass, or pickle |
register_type() per type; stored tagged, read by an allowlist; never pickled |
| D-042 | Large values’ folders | Two levels (65,536 folders); a folder goes with its last file | One level (at most 256); empty ones go at the last close, in clear(), and hourly by maintenance |
| D-043 | A large write after the cache’s folder was deleted | Re-creates the folders and succeeds | OSError; nothing is re-created |
| D-044 | Key equality | 1 and 1.0 are one key; True another |
1, 1.0 and True are three keys |
| D-045 | memoize(typed=True) |
Adds each argument’s class to the key | Adds each argument type’s name |
| D-046 | iterkeys() across key types | Numbers, then text, then bytes | str keys, then the other types in a fixed order |
| D-047 | retry= |
Positional; cache[k] retries forever |
Keyword-only; cache[k] raises Timeout |
| D-048 | A memoized function’s arguments | Anything picklable | Key types only, checked before the call |
| D-049 | stats() | Persisted and shared; get writes while on | Per process, in memory; get never writes |
| D-050 | check() | Warns on every empty folder and stray file; fixes a wrong size | Skips empty folders and files under an hour old; removes a wrong-size entry |
| D-051 | The coordination recipes | Work on any cache; throttle breaks after its bucket expires | Refuse NullCache and durable caches; throttle fixed; RLock owner has a nonce |
| D-052 | Tag equality | Numeric: evict(1) removes 1, 1.0 and True |
Exact type, as keys: three tags |
| D-053 | cull() under eviction_policy='none' |
Returns 0 after removing expired entries | Returns how many it removed |
| D-054 | A queue’s keys | Any key in the range: a float, 'user-9', another queue’s items |
Only keys of the queue’s exact shape |
| D-055 | peek(), peekitem() | Delete expired heads; hang on a missing value file | Write only what get would; pass over a missing file |
| D-056 | pull() | Deletes, then decodes: an unreadable item is lost | Decodes, then deletes: it stays queued |
| D-057 | push() past its range, a bad side |
Leaves the range, then IntegrityError; KeyError |
OverflowError; ValueError |
| D-058 | Windows: deleting or overwriting a large value while it’s being read | Leaks its file, outside size_limit | Removes it |
| D-059 | A directory holding another diskcache-oxide format | (no such thing) directory is the one passed | Opens diskcache-oxide-format-N inside it; directory says so |
| D-060 | len() and iteration |
Count and list expired entries until something removes them | Leave them out the moment they expire |
| D-061 | Between calls | Nothing happens: expired rows, an over-limit cache and stray files wait for a call | Background maintenance looks after every open cache, every 5 minutes by default |
| D-063 | An int past 4,300 digits, pickle=True |
Pickled and stored | ValueError from Python’s digit limit |
| D-064 | incr or decr with an infinity or a NaN | Adds it; a NaN result reads back as None and breaks the counter |
ValueError |
Safety
D-001: no pickle by default
diskcache pickles every value. diskcache-oxide stores str and bytes raw and everything else as msgpack or tagged JSON. A value the format can’t represent exactly raises TypeError at set() unless the cache was opened with pickle=True. A cache opened without it never unpickles: reading a pickled value written by a pickle=True peer raises UnsafeValueError and leaves the row alone. Unpickling runs code from whatever is in the cache directory, and silently pickling hides values that were never meant to be cached. See Serialization.
D-015: owner-only directories
A cache directory diskcache-oxide creates, and its value-file subdirectories, are 0700. On Windows there are no mode bits: a new directory inherits its parent’s access control list. Existing directories are never changed. Anyone who can write to a cache directory can poison the cache, and its contents (keys with IP addresses in them, for example) can be private.
D-021: directory is required
diskcache creates a temporary directory if you don’t give one. A cache directory is shared state and a security boundary, and an implicit temp directory is almost never what a multi-process app wants.
Correctness
D-008: NaN round-trips
In diskcache, set('k', float('nan')) succeeds but get('k') returns None, ignoring any default. In diskcache-oxide it’s a float like any other.
D-010: expire() removes everything that has expired
diskcache’s expire() works in chunks of 100, and when expired entries share one expiry time it stops after the first chunk. With 250 such entries, one call removes 100. diskcache-oxide removes all of them, still in chunks so writers can get in between.
D-011: clear() keeps concurrent writes
diskcache’s clear() keeps deleting until the cache is empty, including entries written while it runs. In a reproduction with 50,000 entries and a concurrent writer, it deleted 76,000 writes that had already succeeded, and its running time grew with the write rate. diskcache-oxide’s clear() removes only entries that existed when it started, and always finishes. evict(tag) is bounded the same way.
D-013 and D-016: large values under pressure
If a large value’s file disappears, diskcache returns the default but the key still reads as present in in and len. diskcache-oxide treats it as a miss and removes the orphaned row.
When one process overwrites a large value while others read it, diskcache occasionally returns the default for a key that was never deleted, which makes callers recompute a hot value for nothing. diskcache-oxide’s readers detect the overwrite and retry, so they always get a whole value, old or new.
D-014: no booleans for numbers
bool is an int subclass, so in diskcache expire=True is a one-second TTL and expire=False stores an already-expired entry. diskcache-oxide raises TypeError: a bool there is almost always an argument in the wrong position.
Processes and forks
D-012: forks while another thread writes
When a process forks while another of its threads is in a write transaction, diskcache’s child inherits a lock nobody in the child will release, and its first write stalls for the full timeout (60 seconds by default). Under a busy read/write load that hits 20-50% of forks. diskcache-oxide’s fork barrier waits for in-flight transactions before the fork, so the child can always write. See Concurrency and forks.
D-020: forking inside your own transaction
CPython won’t let a library stop a fork, and a transaction held by the forking thread itself can’t be waited for. In diskcache the child stalls behind it. In diskcache-oxide the child can’t use that cache at all: every call on it raises RuntimeError immediately, reads included, and the parent gets a RuntimeWarning. The same goes for a fork from code running inside a cache call that has its connection out, such as a pickle hook reading a small value. A child like that would otherwise run without the locks SQLite thinks it holds, reading stale data and losing its writes; Concurrency and forks has the details.
Transactions
D-030: TransactionBusy, and what retry=True retries
Inside one cache’s transaction, diskcache’s transact() on a second cache waits for its write lock until it times out, and retry=True loops on any sqlite3.OperationalError. When another thread holds that lock, diskcache-oxide raises TransactionBusy, a Timeout subclass, at once: that thread could be waiting for a lock this one holds, and no timeout setting fixes that. retry=True retries a plain Timeout and never TransactionBusy, and checks for Ctrl-C between attempts.
D-031: a transaction can end on another thread
diskcache says a transaction “may not be shared between threads”. In diskcache-oxide any thread may commit or roll back the owner’s transaction through its __exit__, within the transaction’s timeout. A commit that can’t run in time raises Timeout and rolls back, and the owner’s own exit afterwards raises TransactionAborted (a RuntimeError) unless the transaction committed, so a with block never exits cleanly when its writes are gone. An owner’s exit during another thread’s commit waits for the outcome.
Resources
D-017 and D-018: bounded connections
diskcache opens a connection for every thread that uses a cache, so 64 threads hold 131 files open in the cache directory, and close() closes only the calling thread’s connection. diskcache-oxide uses a pool per database file, at most max_connections (default 8), and the last close() closes every connection, so the directory is safe to move or delete afterwards.
D-019: opening doesn’t write
Opening an existing diskcache commits a write transaction even when nothing changed. diskcache-oxide’s open, and reads after it, never write, so a read-mostly worker doesn’t take the write lock just by opening its cache. Background maintenance (D-061) is the one writer you didn’t call: it writes when it has work, and once an hour per cache to coordinate the processes, even with none. For a read-only replica or a backup, pass maintenance_interval=0. Maintenance is off for a cache in a process only when every handle opened on it there asked for 0; an earlier handle that asked for an interval keeps it on until every handle on the cache has closed.
D-023: bounded SQLite memory
diskcache’s default is a 32 MiB page cache and a 64 MiB memory map per connection, with one connection per thread. diskcache-oxide’s sqlite_cache_size defaults to 256 pages (1 MiB) per pooled connection, so SQLite’s memory per directory stays around 8 MiB per process.
D-024: a WAL that shrinks
With readers in other processes, a burst of writes makes SQLite’s write-ahead log grow to fit the burst and stay that size: hundreds of MiB to over 1 GiB beside a database of a few MiB. diskcache-oxide trims the log whenever it resets (wal_size_limit), offers checkpoint() to empty it on demand, checkpoints a large log at close(), and can checkpoint automatically with wal_checkpoint='auto', which tries a few times in a row so that a reader in flight in another process doesn’t defeat it. Background maintenance (D-061) also checkpoints a log grown past half of wal_size_limit, in manual mode too. Its checkpoint never waits for readers: with busy readers in other processes it copies what it can each interval but doesn’t keep the log bounded, so auto or an explicit checkpoint() is still the answer there. See Storage and WAL.
API differences
- D-002: the database file is
diskcache-oxide.sqlite, so the two libraries never misread each other’s files. - D-003: the clock is read natively; pass
clock=to control it in tests. - D-004: keys are
str,bytes,int(64-bit),float,bool,None, or tuples of those, nested up to 32 deep. Only those exact types: a subclass (IntEnum,StrEnum, anamedtuple), alist, afrozensetor an int past 64 bits raisesTypeError, and a NaN raisesValueError. Keys are never pickled. - D-005: size_limit must be at least 1 MiB. In diskcache, a limit below the empty database’s size silently evicts every value, including the one just stored.
- D-006: an empty cache’s volume() differs, so a size_limit leaves slightly different room.
- D-007: Timeout subclasses
TimeoutError, soexcept TimeoutErrorcatches it too. - D-009:
bool(Cache)is always True andbool(NullCache)is False, soif cache:means “caching is on”. - D-022: there’s no
disk=and there won’t be: a PythonDiskclass would put Python code on every read and write;serializer=and register_type() cover what it was for.eviction_policy=is'least-recently-stored'(the default) or'none', stored in the cache and read inside every write, so a change made by one process applies to every other at its next write. Least-recently-used and least-frequently-used raiseValueError, because they make every get a write (see the roadmap). Tags are always indexed, so there’s notag_indexsetting. - D-041: a type the codec doesn’t know is registered per type with
register_type(cls, name=..., encode=..., decode=...)(a dataclass needs only a name), process-wide or per cache withtypes=. It’s stored as a tagged value and read back only where the name is registered, so nothing is imported by name; a registered type is never pickled; adecodeerror about the row is a CorruptValueError with yours as__cause__. See Your own types. - D-028:
Cache(..., durable=True)has no counterpart in diskcache. It answers an outage on a single-key call as a miss orFalse, and it can drop writes. Beginning a transaction, and anything inside one, still raises. See A cache that can’t take a request down. - D-042: a large value’s file sits one folder deep, in at most 256 folders. A delete removes only the file; the last close in a process removes folders left empty and untouched for 30 seconds, clear() removes the ones it emptied, and background maintenance (D-061) runs the same sweep hourly, on a FanoutCache’s shards too (their close skips it). Before this, empty folders were never removed and a long-lived cache could hold 65,536 of them, about 257 MiB on ext4. See Storage and WAL.
- D-043: if a cache’s folder is deleted while a process has it open, that process’s next large write raises
OSErrorinstead of re-creating the folder. Delete a cache’s folder only with every process stopped. - D-044: keys are compared by exact type:
1,1.0andTrueare three keys, as are0andFalse, while0.0and-0.0are one. diskcache compares through SQLite, so1and1.0are one key there. - D-045:
memoize(typed=True)adds each argument type’s name ('builtins.int') to the key, where diskcache adds the class itself, which can’t be a key without pickle. - D-046: iterkeys() gives every
strkey first, in code-point order, thenNone,False,True, ints, floats, bytes and tuples, each in value order;prefix=walksstrkeys only. It’s the order of the stored bytes, so it’s an index scan and the same across a FanoutCache’s shards. - D-047:
retry=is keyword-only and a strictbool, and retries only Timeout. Dict syntax never retries:cache[k]raises Timeout after timeout, where diskcache’s waits forever. - D-048: a memoized function’s arguments must be key types, checked before the function runs; leave out one that can’t be (a connection, a client) with
ignore=. - D-049: stats() counts hits and misses per process, in memory, so a get never writes. Every handle on a directory in one process shares the counts; other processes’ aren’t included, and a restart or a forked child starts at zero.
- D-050: check() doesn’t report empty value folders (normal on an open cache) and leaves files under an hour old alone, since a writer may own them. A value file of the wrong size was cut short by a crash, so
fix=Trueremoves its entry rather than correct the size and serve the short bytes. - D-051: the coordination recipes refuse a NullCache or
durable=Truecache, refuse to wait inside their own cache’s transaction, give RLock a per-process owner nonce, and fix throttle’s two bugs (upstream bugs 13 and 14). See Coordination. - D-052: tags are compared by exact type, as keys are:
1,1.0andTrueare three tags, and a tuple can be one. diskcache compares them through SQLite, so itsevict(1)removes all three and aTruetag reads back as1.tag=is keyword-only on set and add. - D-053: under
eviction_policy='none', cull() returns how many expired entries it removed; diskcache’s returns 0 (upstream bug 15). - D-054 to D-057: the queue calls. A queue’s items are only keys of its exact shape, so floats, ordinary keys that share the prefix and nested queues never mix in (upstream bugs 17 and 18); peek() and peekitem() write only what get would and never hang on a missing value file (bug 16); pull() decodes before it deletes, on every path, so an item this process can’t read stays queued; and push() raises
OverflowErrorrather than leave its range or overwrite a key. See Work queues. - D-058: on Windows, diskcache can’t delete a value file while any reader has it open (Python’s
open()doesn’t share delete) and ignores the failure, so the file stays with nothing pointing at it (upstream bug 19); one test left 154 files for 6 entries. diskcache-oxide’s readers allow the delete, so nothing leaks. - D-059: when a cache directory holds a cache in another diskcache-oxide format (after an upgrade or a rollback), the cache opens in the subdirectory
diskcache-oxide-format-Nwith a warning, and every later open uses it; directory reports where the cache really is. remove_old_formats() cleans up older formats once the old workers are gone. See Upgrading across a format change. - D-060: an expired entry leaves
len(), iterkeys(),iter()andreversed()the moment it expires, as it already left get andin. diskcache keeps counting and listing it until a set(), expire() or cull() removes its row. Nothing is written by the check: the row and its space, in volume(), stay until a set(), expire() or cull() removes them, or background maintenance does (D-061). - D-061: one thread per process removes expired entries, trims a cache left over its size limit, checkpoints a grown write-ahead log and clears stray temporary files, every
maintenance_interval(default 5 minutes, 0 for off), with the caches and the processes taking turns. It never waits for a lock and holds the write lock only for short chunks, so a request in the same process waits at most one chunk (about 130 µs for 100 small rows); a writer in another process can wait for a few chunks, never past the turn’s 50 ms. So an explicit expire() or cull() can return less than diskcache’s would, volume() changes between calls, and a cache held open for an hour is written once to coordinate, even with nothing to do. See Background maintenance. - D-062: the Django backend is diskcache-oxide’s own, not a port of
diskcache.DjangoCache:'BACKEND': 'diskcache_oxide.DjangoCache'withOPTIONSin Cache’s keyword names, a plain Cache unlessOPTIONS['shards'], a 1.0 s lock wait and errors that raise unless durable (diskcache’s is always a FanoutCache, 8 shards by default, and its writes retry a 10 ms wait silently, for as long as the lock is held), close() a no-op,MAX_ENTRIESrefused rather than ignored,pickle=Trueby default (Django caches responses and model instances), and incr the engine’s atomic one, so abool,Decimal,IntEnumor an int past 64 bits raisesTypeErrorwhere Django’s locmem backend adds it. Noread=,deque(),index(),cache(name), memoize or tag-index calls. See Django cache backend. - D-063: an int past Python’s int-to-str digit limit (4,300 digits by default,
sys.get_int_max_str_digits()), top-level or nested, raisesValueErrorat set even withpickle=True, where diskcache pickles it. Big ints are stored as decimal text, and only a type the format can’t hold or a lone surrogate inside a value falls back to pickle. Raising the interpreter’s limit lifts it. - D-064: incr and decr raise
ValueErrorfor adeltaordefaultthat is an infinity or a NaN. diskcache adds it, and a counter that reaches NaN that way is stored as NULL: it reads back asNone, and the next incr raisesTypeError. A counter that overflows still becomes an infinity, and stays readable. - D-025:
iter(cache)and iterkeys() return a native iterator, not a generator. Two threads callingnext()on the same one at once getValueErrorat once, as with a shared generator.
FanoutCache (D-032 to D-040)
These are covered together in FanoutCache: sharded caches, and listed against diskcache’s in Switching from python-diskcache.
- D-032: the shard count is part of where every key lives, so it’s recorded, and a different
shards=never changes it: the cache opens with the stored count and logs a warning, or raises LayoutMismatchError withraise_on_mismatch=True, instead of quietly losing data and atomicity. - D-033: the hash is fixed by its definition and part of the format, and
iterkeys(prefix=)gives FanoutCache the ordered listing Cache has. - D-034: a silently dropped write and a hang are both worse than an error the caller chose how to handle;
durable=Trueis that choice. - D-035: a maintenance job must finish in bounded time, and when it can’t, it must say what it did.
- D-036 and D-037: budgets (size, connections, file descriptors) follow configuration, not the number of threads or shards. With 8 shards and every thread touching every shard, diskcache’s FanoutCache holds 40 file descriptors at 1 thread, 152 at 8, 536 at 32 and 1,048 at 64; diskcache-oxide’s holds 32 at every count. Under a 256-descriptor limit (a macOS shell over ssh, many launchd jobs and containers) diskcache’s FanoutCache fails at 15 threads with
sqlite3.OperationalError: unable to open database file, and sooner once close() has left connections open (D-018). - D-038: a typo shouldn’t leave a directory that neither kind of cache can open, or a shard written behind the FanoutCache’s back.
- D-039: shards is keyword-only so that the second positional argument is timeout, as on Cache. The sub-collections and
read()would each need their own design across shards, so they aren’t copied from diskcache (see the roadmap). Everything else on Cache, apart from the queue calls, works on a FanoutCache too. - D-040: holding every shard’s lock would serialize the whole cache behind one transaction, which is what sharding exists to avoid.
diskcache-community
diskcache-community is an actively maintained fork of diskcache, and the conformance suite can run against it too. It has fixed some of the same bugs (D-012, D-018, D-019, and the 0700 directories of D-015) and keeps others (D-008, D-016, D-017). The full comparison is at the end of tests/DIVERGENCES.md.