Repository navigation
Releases
diskcache-oxide 0.5.8
No format change: caches made by 0.3.5 and later open as they are. One behavior change, for a child process forked at the wrong moment, and fixes from the same review as 0.4.7 that touch the engine's core.
Changed
- A child forked inside a transaction, or from inside a cache call that has its connection out, can't use that cache at all. Every call on it in that child raises the new
ForkedInsideTransactionError, aRuntimeError, at once, reads included, for the life of the process, on adurable=Truehandle too;close()still works, other caches are unaffected, and on aFanoutCacheonly the shard involved is refused. Before, a child forked insidewith cache.transact():could still read, and one forked from a pickle hook or adecodefunction reading a small value inside a call could read and write. Both were unsafe: such a child holds none of the file locks SQLite believes it holds, so once the parent closed, its reads went stale and itssetcalls returnedTrueand were lost, with no error and nothing forcheck()to find. Fork before or after the block, or start workers withspawnorforkserver(D-020; see Concurrency and forks). The child logs one warning on thediskcache_oxidelogger naming the directories. - A
Cacheslookup and adurable=TrueDjango alias raiseForkedInsideTransactionErrorin such a child, where any other failed open hands out aNullCacheand retries. No retry can help that child, and a silentNullCachewould hide a fork in the wrong place for the life of the worker. incranddecrraiseValueErrorfor adeltaordefaultthat is an infinity or a NaN (D-064). A counter that reached NaN was stored with no value, sogetraisedCorruptValueErrorand the nextincrraisedTypeError. A counter left that way by an earlier version stays unreadable until it's overwritten or deleted.- The error
this database can't be written in a process forked inside a transactionis gone: that child now gets the error above for every call.
Fixed
- Another library's before-fork hook that used a cache (one registered before
diskcache_oxidewas imported, so it runs after ours) left its connection open across the fork, and the child then lost its writes once the parent closed. A connection given back between the fork hooks is closed now, and that child works. - A child forked while another thread was leaving the forking thread's transaction (
__exit__called from a second thread) kept a lock level nothing could release:os.fork()from another thread of that child hung, and leaving the block there waited out the timeout. It raisesRuntimeErrorat once now, and later forks go ahead. - One row with a damaged
filenameorsizecolumn (the wrong SQLite type, as a bad page or an edit by hand leaves it) made everyget,delete,clear()andcheck(fix=True)that reached it raiseOSError: Invalid column type, and once it was the oldest row, everysetthat had to evict. A row with a damagedfilename, or a damagedsizeon a value stored in a file, reads as a miss and is removed like any other, andcheck()reports a row with a wrong-typedmode,size,store_seq,expire_timeorfilename(damaged row N: its COLUMN is stored as TYPE), whichfix=Trueremoves. - One row with a damaged
store_seqcolumn decided every later sequence number. Text or a BLOB there gave each later write on any key the same number, soclear()could return 0 and leave entries behind, andpopand the queue calls lost their exactly-once footing; a large REAL made everyset,expire(),cull()andclear()raise. The next number is worked out from the sound ones only now, so such a row affects only the calls that reach it (by its key, or as the head of a queue) untilcheck(fix=True)removes it.check()also reports astore_seqof 2^62 - 1 or more as damaged. - A damaged next sequence number in the cache's one
staterow (text, a BLOB, a REAL, or 2^62 or more) wasn't reported bycheck()and wasn't repaired, and with a fractional REAL thereincron a stored number wrote that REAL into the entry's own row, after which reading the entry raised. Every write fails withOSErroron such a cache now,clear(),evict,expire()andcull()still run, andcheck()reports it (damaged cache state: its COLUMN is stored as TYPE);check(fix=True)sets the number past every entry's. Deleting an entry whose own number was the last one below 2^62 left the cache unwritable with nothing to repair it;check()reports that entry as damaged andfix=Truerepairs both. check()raisedOSErrorinstead of reporting when a stored total (countorsizeinstate) was of another type, or when an entry'ssizewas an integer large enough to overflow the sum, and removing an entry with a hugely negativesizeturned the stored total into a REAL that every latervolume(),setandcheck()raised on. Asizebelow 0 or above 2^48 is a damaged column now: it counts as 0,check()reports it, andfix=Trueremoves the entry and recounts the totals.check()also missed an entry whose stored file name was the empty string, and entries sharing one file name beyond the first 512.- In a child that can't use a cache after a fork (see Changed), several calls didn't say so. Opening a
FanoutCachethere withsize_limit,cull_limitoreviction_policywrote those settings to the shards ahead of the one it couldn't use, for every process, and then raised; no shard is touched now. A call on a handle the child had closed reopened it, with a new connection on the file, before raising.Cache.evict(None)returned 0, andremove_old_formats()ran. Leaving the inheritedwith cache.transact():block raisedTransactionAborted, or returned quietly on an exception, when another thread had rolled the transaction back just before the fork. And in another library'safter_in_childhook registered beforediskcache_oxidewas imported,stats()answered, leaving the block could wait out the timeout, andFanoutCache.clear()could empty some shards before raising. All of these raiseForkedInsideTransactionErrorat once now, and change nothing. - A
Cachesregistry or adurable=TrueDjango alias that had failed to open a cache in the parent kept serving thatNullCachein a forked child for the rest of the parent's retry window (up to 10 seconds). A child starts without its parent's failed opens now: it opens the cache itself, or raisesForkedInsideTransactionErrorif it can't use it. - A pickle hook or a registered type's
decodethat called a cache its process couldn't use after a fork had itsRuntimeErrorread as a value that can't be decoded, so the read deleted the row it was reading from a healthy cache, or answered a miss. The error passes through as itself now and the row stays. check(fix=True)could remove the value file of a transaction held open for over an hour in another process, which then committed an entry with no file. It removes a file no entry names only under the write lock now, so it waits for that transaction (and raisesTimeoutif it outlasts the timeout).- With a
types=registry on a handle, a value of a class registered only in the global registry was stored under the global name and read back through the handle's own registration of that name, as another class.setraisesTypeErrorfor it now. - Background maintenance's checkpoint read "another connection is checkpointing" as "everything is copied" and went on to reset the write-ahead log under the write lock, where the whole copy could then run and hold up writers.
check(fix=True)could wait about twice itstimeout: theVACUUMat its end and the checkpoint after it each got the full time.
diskcache-oxide 0.4.7
No format change: caches made by 0.3.5 and later open as they are. Fixes from a bug, race and security review of 0.4.6.
Fixed
DjangoCache.delete_manyunderdurable=Trueno longer stops at a missing key once the batch has run for half a lock wait, which left every key after it undeleted on a healthy cache (with the default 1.0 s lock wait, any missing key after the first half second of a long batch; with a lock wait of 0, the first missing key).set_manyhad the same flaw for a key that failed at once: it and every key after it were returned as not stored without being tried. Both now stop only at a call that itself waited half a lock wait, which is what a held lock looks like, and with a lock wait of 0 they try every key.pull()on atimeout=0handle withon_decode_error='miss'raisedTimeoutafter removing an unreadable item from the front of the queue, although nothing held the lock, and so did any handle whose timeout ran out just as the item was removed. It now goes on to the next item, as documented; only a puller that loses a race with no time left raisesTimeout.check(fix=True)removed the row of a value whose file it couldn't look at, as if the file were missing: a value folder without permission, or any other error from the file system, cost a whole entry and left its file behind as an orphan. Only a file that isn't there counts as missing now, as for a read; any other error ends the check with thatOSError, and nothing is removed.remove_old_formats()on an oldFanoutCacheroot removed a shard's database when it couldn't tell its format: an empty file (which a process creating the shard holds for a moment), a database with no format stamp, or a file that isn't a database. It now leaves and reports them, as it always has for a plain cache, and as its documentation said.- With
serializer='json', a dict with non-strkeys nested 43 or more deep (each inside the last) was stored bysetand then couldn't be read back:getraisedCorruptValueError, or withon_decode_error='miss'deleted it as a miss.setnow raisesTypeErrorfor it, as for any value nested too deep, from 41 levels. msgpack was never affected.
diskcache-oxide 0.4.6
No format change: caches made by 0.3.5 open as they are.
A Django cache backend. 'BACKEND': 'diskcache_oxide.DjangoCache' runs Django's cache framework on diskcache-oxide: the low-level API, the per-view and per-site cache, template fragments and the cache session engines, with every worker process sharing one cache on disk and add() and incr() atomic across processes. It passes Django's own cache tests (BaseCacheTests, the middleware, template-response and i18n tests, and the cache and cached_db session tests) from the source of Django 5.2, 6.0 and 6.1, on Python 3.14 and 3.14t, and 6.1 on 3.15 and 3.15t. OPTIONS takes Cache's keywords by their own names, and shards makes the alias a FanoutCache. Its defaults differ from Cache's where Django needs them to: a 1.0 s lock wait, and pickle=True, since Django caches responses, SafeStrings and model instances. Errors raise unless OPTIONS['durable'] is set; a durable alias for the cache or cached_db session engine is refused. See the new Django cache backend page.
Added
diskcache_oxide.DjangoCache, loaded on first use, soimport diskcache_oxidestill never imports Django. Beyond Django's API it hastag=onsetandadd,evict(tag),pop,expire(),cull(),stats(),maintenance_stats(),check()andcache, theCacheunderneath;diskcache_oxide.djangocache.close_all()releases every handle it opened (it runs by itself whenoverride_settingschangesCACHES).- The
djangoextra,pip install 'diskcache-oxide[django]', which asks for Django 5.2 or newer. examples/django/, a Django project on two aliases (pages durable, sessions and counters plain) under gunicorn, with its tests.
Fixed
- A value holding a lone surrogate inside it, such as
{'q': '\ud800'}(one can arrive in a JSON body and end up in a session), is now pickled underpickle=True, as diskcache stores it, instead of raisingUnicodeEncodeErroratset. Without pickle it still raises, and a lone surrogate in a top-levelstrstill raises either way, as it does in diskcache. Values the serializer could already store are written exactly as before.
Documentation
- An "Example apps" section: walkthroughs of the FastAPI example (
examples/webapp) and the Django example (examples/django), file by file. - The Django page has measured numbers: reads, writes, worker processes and threads against diskcache's backend and Django's own
FileBasedCache,DatabaseCacheandLocMemCache(bench/django.py), and whyagethops to a thread though the read is faster than the hop. - Corrected: a plain
Cacheslowing past two or three worker processes isn't the write lock. It happens with no writes at all (bench/read_procs.py: 836k ops/s at 2 processes, 296k at 8), most likely SQLite's shared-memory read lock.FanoutCacheis now recommended for a cache several worker processes use heavily, reading or writing, not only one they write to; one worker process doesn't need it. - A lone surrogate and an int past Python's 4,300-digit limit are documented: the first falls back to pickle inside a value, the second always raises (D-063).
diskcache-oxide 0.3.5
Upgrades across a format change no longer fail. A cache directory that holds a cache in another on-disk format (made by an older release, or by a newer one before a rollback) now opens a new, empty cache in its subdirectory diskcache-oxide-format-N, N being this release's format (3), instead of raising FormatMismatchError, and logs a warning on the diskcache_oxide logger once per process. Of the other format's cache, only its format is read, and its contents are never changed (if that read is the last connection to close on it, SQLite may checkpoint its write-ahead log into the database file, which changes no data). Once the subdirectory exists, every later open uses it. A FanoutCache moves as a whole. This release keeps format 3, so caches made by 0.2.3 open where they are, warm; a cache still at format 2 (0.1.2) opens diskcache-oxide-format-3 beside it. See "Upgrading across a format change" in the recipes.
Caches look after themselves. One small thread per process now does each open cache's housekeeping in the background, every 5 minutes by default: it removes expired entries and their files, trims a cache left over size_limit (cull_limit entries at a time; never under eviction_policy='none' or with cull_limit=0), checkpoints a write-ahead log grown past half of wal_size_limit, and hourly clears temporary files a killed writer left and empty value folders, FanoutCache shards included. There's no longer an expire() to schedule. The caches in a process take turns across the interval, and the processes sharing a cache take turns through two new rows in its settings table (no format change: older releases ignore them). It never waits for a lock and holds the write lock only for short chunks, so requests don't notice it, and it stops for every os.fork() and starts again after, so Python never warns about forking a multi-threaded process. A cache opened with clock= gets none. Pass maintenance_interval=0 for a cache this process must never write, such as a read-only replica: even a tidy cache is written once an hour to coordinate the processes (D-061).
Added
-
maintenance_interval=onCache,FanoutCache,CachesandCaches.register: seconds between background maintenance turns for the cache in this process (default 300, 0 for off, 1 second to a day). Per process, not stored in the cache; the shortest any open handle asked for wins. -
maintenance_stats()onCache,FanoutCacheandNullCache, returning aMaintenanceStatsdict (interval,turns,removed,failures,last_error);Caches.stats()carries it asCacheStats.maintenance. A failure is also logged once per streak, as a WARNING on thediskcache_oxidelogger, by the next single-key call on the cache. -
Caches.get(name, default=None): the named plain cache ascaches[name]returns it, ordefaultwhen no cache by that name is registered, so a check and a lookup are one call (if (pages := caches.get('pages')) is None: ...). A registered cache that can't open or is disabled still comes back as aNullCache. -
remove_old_formats()onCache,FanoutCacheandNullCache(where it returns[]), and onCachesfor every registered cache: removes caches in an older format from the cache's directory, only files diskcache-oxide wrote, never following links, never a newer or the current format, and returns what it removed. It doesn't check whether an older worker still uses those files: call it once they've all stopped. -
Windows on x86_64, with wheels for CPython 3.14, 3.14t, 3.15 and 3.15t. The API and the on-disk format are the same; caches made on macOS or Linux aren't affected. Windows has no
fork(), so the fork guarantees are Unix-only. Getting started has a new Windows section: an open cache's directory can't be deleted, new directories inherit their parent's permissions, and a value file another program holds past about 50 ms of retries is left untilcheck(fix=True)removes it, an hour after it was written. SQLite uses its own Win32 mutexes there (_sqlite_mutex_status()reports'native').
Changed
-
The
CacheLikeprotocol gainedmaintenance_stats(), so a hand-written fake checked withisinstance(x, CacheLike)needs it too. -
An explicit
expire()orcull()can return less than it did, since background maintenance may have removed the rows first, andvolume()and the write-ahead log's size can change between calls. -
A cache directory holding another on-disk format opens the
diskcache-oxide-format-Nsubdirectory with a warning instead of raisingFormatMismatchError(D-059).FormatMismatchErroris now raised only for another format inside that subdirectory.directoryonCacheandFanoutCachereports where the cache really is, the subdirectory after such a move; a pickled handle keeps the directory as passed and resolves it again. ACachesregistry no longer hands out aNullCachefor a format change. -
A plain
Cacheopened on aFanoutCacheshard directory in an older format raisesLayoutMismatchError, as it always did for a current one, rather thanFormatMismatchError. -
FanoutCache(directory, shards=n)on a root that records another count no longer raises: it opens with the stored count and logs aWARNINGonce per process. The new keywordraise_on_mismatch=Truerestores theLayoutMismatchError, andCaches.register(..., raise_on_mismatch=True)turns it into an open failure (a reportedNullCache). A root in another on-disk format redirects to its versioned subdirectory either way. TheLayoutMismatchErrorfor settings that don't fit the stored count now saysshards=n was asked forrather thanis registered with, since a plainFanoutCacheraises it too. -
len(),iterkeys(),iter()andreversed()leave out an entry the moment it expires, asgetandinalready did, onCacheandFanoutCache(D-060). Before, an expired entry was counted and listed until aset(),expire()orcull()removed its row, so a cache that's mostly read could report entries nobody could read. Nothing is written by the check; the rows and their space, involume(), still go only when something removes them, so a scheduledexpire()is still how a mostly-read cache frees space.len()now also counts the expired rows not yet removed, through the expiry index, so it costs a little more while such rows are waiting.
Fixed
import diskcache_oxideno longer callsos.register_at_forkwhere it doesn't exist.- A value file that hits a full quota (
EDQUOT) now raisesOSErrorwitherrno.ENOSPC, as a full disk does, since a full disk is recognized by the error's kind rather than one Unix error number. iter(cache)(and aFanoutCache's, shard by shard) could yield a key twice: one deleted and stored again while the walk ran got a newer row, which the walk met again at its end. It now stops at the newest row when it began, as diskcache's does, so a key stored meanwhile isn't yielded and a re-stored one is yielded once. Found by the 24-hour soak, 8.5 hours in.iter(cache)andreversed(cache)no longer sort the whole table for every page of keys. Without SQLite statistics, the planner read insertion order through the key index and sorted it, so walking a large cache took time in proportion to its size for every 512 keys (about 2 s for 200,000 entries on an M5 Max, now 22 ms); each page now seeks on the row id.
Documentation
- An example app in
examples/webapp: a FastAPI app with gunicorn, a background worker and Docker Compose, built the way the docs recommend, with tests that run it as real processes. Every page shows which cache reads served it. - One recommended production setup throughout the docs: a durable
Cachesregistry withtimeout=1.0for data that can be rebuilt, and state (sessions, job claims, locks, queues) in plain caches opened directly, with eviction off, under one/var/lib/my-appdirectory. The Caches guide explains why state never goes through the registry. - New pages: Docker and Compose (volumes, a fixed UID, ownership, Kubernetes, disk sizing, backups, cleanup after a format change) and Troubleshooting (start from the symptom).
- Corrected: the docs no longer claim network filesystems are detected at open. SQLite can't tell, so keep caches on a local disk.
- Also new: a keyword table and the state-copying loop in Switching from diskcache, Windows notes in Getting started, a Prometheus collector in Monitoring, a
dictConfigthat keeps thediskcache_oxidelogger, and API reference sections for types, memoize, coordination and every error.
Wheels: macOS arm64, Linux (manylinux_2_28) aarch64 and x86_64, and Windows x86_64, for CPython 3.14, 3.14t, 3.15 and 3.15t, profile-guided. Checksums are in SHA256SUMS. Full changes: CHANGELOG.md, v0.2.3...v0.3.5.
diskcache-oxide 0.2.3
Delete your caches when you upgrade. This release changes the on-disk format (format 3, for tags and the eviction policy). Opening a cache made by 0.1.2 raises FormatMismatchError, naming the database: stop every process using the cache, delete its directory (a FanoutCache's whole root, never one shard), and it's recreated empty on the next open. 0.1.2 refuses a format-3 cache the same way, and neither version writes anything into the other's. A 0.1.2 worker still running when its cache is deleted and recreated can't change the new one either: once it opens the new file, its writes, deletes and maintenance calls fail with "no such table" (only a touch gets through), because format 3 renames the table they all use.
Added
- Keys of every native type:
bytes,int(64-bit),float,bool,None, and tuples of those, nested up to 32 deep, besidestr. They're never pickled and compare by exact type, so1,1.0andTrueare three keys.iterkeys()listsstrkeys first, then the other types in a fixed order;iterkeys(prefix=...)listsstrkeys only. A FanoutCache routes every key type. Type checkers seediskcache_oxide.Key. memoize(name=None, typed=False, expire=None, tag=None, ignore=())onCache,FanoutCacheandNullCache, as diskcache's, with the same keys, sof.__cache_key__(...)returns the tuple diskcache would. Every argument must be a key type, checked before the function runs;typed=Truestores type names.MemoizedandMemoizertype the wrapper.CorruptKeyError, aCorruptValueError, raised by iteration that meets a stored key it can't read (a damaged page or file); it never skips one.reversed(cache),pop(key, expire_time=True), a read-onlydurableattribute, andreset(key, value)to read or persistsize_limit,cull_limitandeviction_policy(aFanoutCachesplits asize_limittotal across its shards), onCache,FanoutCacheandNullCache.- Pickling a
CacheorFanoutCache: it reopens the directory with the options the handle was opened with, in another process too. ATypeRegistrypickles (the global one by reference). stats(enable=True, reset=False): hit and miss counts ofget, per process and in memory, so agetnever writes.check(fix=False, retry=False): the database and value files against each other, as diskcache's, in short steps;fix=Trueremoves entries whose files are missing or cut short and old orphan files, sweeps empty folders, corrects the totals andVACUUMs.UnknownFileWarningandEmptyDirWarning.- The coordination recipes
Lock,RLock,BoundedSemaphore,Averager,throttle,barrierandmemoize_stampede, as diskcache's, refusing aNullCacheordurable=Truecache, withthrottle's two diskcache bugs fixed. See the new Coordination guide page. - Tags:
tag=(keyword-only) onsetandadd, any key type, compared by exact type, andtag=Trueongetandpop, returning diskcache's(value, tag)and(value, expire_time, tag)tuples.evict(tag, *, timeout=None, retry=False)onCache,FanoutCacheandNullCacheremoves every entry with that tag stored before the call, in chunks likeclear().memoize(tag=...)and the recipes'tag=tag what they store. An overwrite withouttag=leaves the entry untagged;addon a live key,touchandincrkeep its tag. eviction_policy='least-recently-stored'(the default) or'none'onCacheandFanoutCache, stored in the cache and read inside every write, so a change from one process applies to all at their next write. Under'none'nothing is evicted for size, expired entries are still removed, andcull()returns how many it removed.'least-recently-used'and'least-frequently-used'raiseValueError. A read-onlyeviction_policyattribute.- The queue calls
push,pull,peekandpeekitemonCacheandNullCache, with diskcache's signatures and return shapes (expire_time=,tag=,retry=keyword-only). Each item goes to exactly one puller across every process;pulldecodes before it deletes, so an item this process can't read stays queued;peekandpeekitemnever write. A queue's items are only keys of its exact shape, andpushraisesOverflowErrorrather than overwrite a key. See the new Work queues recipe. ENOVALandUNKNOWN, diskcache's sentinels.retry=True(keyword-only) onget,set,add,delete,pop,touch,incr,decr,expire,cull,clearandevict: this cache's ownTimeoutis retried until the call gets through, even on adurable=Truehandle; one raised by your code (a hook, aclock) is not. A retriedexpire,cull,clearorevictreturns everything it removed.
Changed
- Iterating a cache is typed
Iterator[Key]rather thanIterator[str], since keys can now be other types;iterkeys(prefix=...)is stillIterator[str]. Type-checked code that treats every iterated key as astrneeds a narrowing (isinstance(key, str)). - The
TypeErrorfor a key of the wrong type now names the types that are accepted. TransactionalCacheLikegainedpush,pull,peekandpeekitem(notCacheLike:FanoutCachehas no queue calls).CacheLikegainedmemoize,stats,check,reset,evict,durable,eviction_policyand__reversed__,getandpoptheirtag=(andpopitsexpire_time=), andsetandaddtheirs; a fake typed against it needs them too.transact(retry=True)sleeps between attempts instead of retrying at once, so atimeout=0cache doesn't spin.
Wheels: macOS arm64 and Linux (manylinux_2_28) aarch64 and x86_64, for CPython 3.14, 3.14t, 3.15 and 3.15t, profile-guided. Checksums are in SHA256SUMS. Full changes: CHANGELOG.md, v0.1.2...v0.2.3.