Skills
A skill is a package of structured files that teaches an AI coding agent how to work with a specific tool or framework. Install it in your agent and it will be able to run commands, edit configuration, write content, and troubleshoot problems without step-by-step guidance from you.
Any agent — install with npx:
npx skills add https://mkennedy.codes/docs/diskcache-oxide/Codex / OpenCode
Tell the agent:
Fetch the skill file at https://mkennedy.codes/docs/diskcache-oxide/skill.md and follow the instructions.Manual — download the skill file:
curl -O https://mkennedy.codes/docs/diskcache-oxide/skill.mdOr browse the SKILL.md file.
SKILL.md
--- name: diskcache-oxide description: >- Use diskcache-oxide, a shared, durable disk cache for Python with a Rust engine, SQLite storage and python-diskcache's API, built for many threads, many worker processes and free-threaded CPython. Use when adding or configuring diskcache_oxide in an app (Cache, FanoutCache, NullCache, Caches), configuring Django's cache on it (DjangoCache), switching code from diskcache, choosing between Cache and FanoutCache or between raising, missing and switching caching off, writing tests around a cache, or when code raises Timeout, TransactionBusy, UnsafeValueError, CorruptValueError, LayoutMismatchError, FormatMismatchError, or "can't be stored without pickle". license: MIT compatibility: Requires CPython 3.14 or 3.15 (GIL or free-threaded) on macOS, Linux or Windows (x86_64). SQLite is bundled; no runtime dependencies. --- # diskcache-oxide A cache that is a directory: every thread and process that opens the same path shares one cache, and it survives restarts. It keeps python-diskcache's `Cache` API and rebuilds the engine in Rust on SQLite: reads in under a microsecond, writes atomic across processes, safe across `fork()`, no pickle unless asked for, bounded memory and disk. Measured against python-diskcache 5.6.3 (unmaintained: no commits since 2023) on the same machine: a cached `get` in 0.84 µs at p50 (0.47× diskcache's), and at 8 threads sharing one `Cache` about 710,000 operations a second where diskcache falls to 19,000; eight writing processes on a `FanoutCache` reach about 1.1 million a second. It is not data compatible with diskcache (it uses `diskcache-oxide.sqlite`, never `cache.db`). Errors an agent will meet: `TypeError` at `set()` for a value the formats can't represent, `Timeout` (a `TimeoutError`) when a lock stays busy, `UnsafeValueError` when a `pickle=False` cache reads a pickled row, `FormatMismatchError` only where a format change can't be handled (another format inside a `diskcache-oxide-format-N` subdirectory, or 0.2.3 and earlier meeting a newer cache), and `LayoutMismatchError` when a directory holds the other kind of cache. A cache directory holding another on-disk format isn't an error since 0.3.5: the cache opens in its versioned subdirectory with a warning. ## Install Install with `pip install diskcache-oxide` (CPython 3.14 or 3.15, GIL or free-threaded; wheels for macOS arm64, Linux x86_64/aarch64 and Windows x86_64, elsewhere a source build that needs the latest stable Rust). The import is `diskcache_oxide`. During 0.x a release that changes the on-disk format bumps the minor version. Since 0.3.5, a cache directory holding another format (older or newer) doesn't fail to open: the cache opens in the subdirectory `diskcache-oxide-format-N` (N = this release's format, 3 since 0.2.3), logs a `WARNING` on the `diskcache_oxide` logger once per process, and every later open uses that subdirectory; `directory` reports it. A `FanoutCache` moves as a whole. `cache.remove_old_formats()` (and `caches.remove_old_formats()`) removes caches in an older format from the directory, only files diskcache-oxide wrote, and returns what it removed; it does not check whether an old worker still runs, so call it only after every older worker has stopped (on Linux and macOS, a still-running old worker's cache can be corrupted). 0.2.3 and earlier still raise `FormatMismatchError` on a newer format, and 0.2.3 doesn't know the subdirectory: after a cleanup it creates its own format-3 cache at the root, which is safe but not shared with newer workers. ## Use ```python from diskcache_oxide import Cache # Open once per process and share it across threads; every worker opens the same path. # durable=True for rebuildable data: a busy lock, full disk or I/O error is a logged miss, never an exception. # One cache; an app with several uses the Caches registry below instead. cache = Cache('/var/lib/my-app/cache', timeout=1.0, durable=True) cache.set('episodes:popular', episodes, expire=300) # always give cached values an expire; False if dropped episodes = cache.get('episodes:popular') # None (or default=) on a miss or an outage ``` Default to `durable=True` for any cache of data the app can rebuild. Leave it off for state (sessions, job claims, locks, counters, queues), where a dropped write is a bug; there a busy write lock raises `Timeout` after `timeout`, which the caller handles. An app with several caches registers them once and looks them up by name; a cache that can't open comes back as a `NullCache` and is retried after 10 s. The recommended production setup: a durable registry for rebuildable data, and state (sessions, job claims, locks, queues) as plain caches opened directly, never through the registry (a `NullCache`'s `add()` always wins and its `push()` stores nothing) and never durable, under one directory the app owns: ```python caches = Caches('/var/lib/my-app/cache', durable=True, timeout=1.0) caches.register('pages', size_limit=2 * 2**30) caches['pages'].get('/about') coordination = Cache('/var/lib/my-app/state/coordination', timeout=3.0, eviction_policy='none') coordination.add('job:nightly', 1, expire=3600) # exactly one worker wins ``` Plain caches by default. A `FanoutCache` for one cache that several worker processes use heavily, reading or writing (a plain `Cache` slows past two or three processes even when they only read), many threads (8 or so) on free-threaded Python, or a write-heavy load: up to 4× faster (about 6× with 8 processes only reading), for about 10 MiB more memory per process. One worker process doesn't need it. In tests: `Cache(tmp_path / 'cache')` per test, `NullCache()` where caching must not interfere, and `Cache(tmp_path, clock=fake_clock)` to test expiry without sleeping. If tests patch `time.time`, pass `clock=lambda: time.time()`, since the cache reads the clock natively. A `clock=` handle gets no background maintenance, and a nonzero `maintenance_interval` with it raises `ValueError`; a cache's first turn comes at least one interval (5 minutes by default) after it opens, so short tests never see it. Django: `'BACKEND': 'diskcache_oxide.DjangoCache'` (`pip install 'diskcache-oxide[django]'`; Django 5.2, 6.0, 6.1). Two aliases, as for any app: pages and fragments on a durable one, sessions and counters on a plain, never-evicting one, in separate directories. `OPTIONS` takes `Cache`'s keyword names (`shards` makes it a `FanoutCache`); its defaults are a 1.0 s lock wait (`OPTIONS['timeout']`, not Django's `TIMEOUT`, which is the entry lifetime) and `pickle=True`. `MAX_ENTRIES`, `CULL_FREQUENCY`, diskcache's `SHARDS` and `DATABASE_TIMEOUT`, and a durable alias for the cache or cached_db session engine raise `ImproperlyConfigured`. Errors raise unless `durable`; `incr` raises `ValueError` and `clear()` `Timeout` even on a durable alias. Every instance shares one handle per directory per process; `close()` does nothing; in tests `override_settings(CACHES=...)` closes the handles, or call `diskcache_oxide.djangocache.close_all()`. A `cache_page` view that reads the session needs `@vary_on_cookie`. ```python CACHES = { 'default': { 'BACKEND': 'diskcache_oxide.DjangoCache', 'LOCATION': '/var/lib/my-site/cache/pages', 'TIMEOUT': 600, 'OPTIONS': {'durable': True, 'size_limit': 2 * 1024**3}, }, 'state': { 'BACKEND': 'diskcache_oxide.DjangoCache', 'LOCATION': '/var/lib/my-site/state/site', 'TIMEOUT': None, 'OPTIONS': {'eviction_policy': 'none'}, }, } SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'state' ``` ## Rules - Keys are `str`, `bytes`, `int` (64-bit), `float`, `bool`, `None`, or tuples of those, never pickled; a `list`, `dict`, object, subclass (`IntEnum`, `namedtuple`) or int past 64 bits is `TypeError`, a NaN `ValueError`. They compare by exact type: `1`, `1.0` and `True` are three keys. For a prefix scan use `str` keys with a trailing separator (`user:42:` so `user:4` doesn't match `user:42`): `prefix=` sees only `str` keys. - Values are exact built-ins only: `str`, `bytes`, `int`, `float`, `Decimal`, `bool`, `None`, and `list`, `tuple`, `dict`, `set`, `frozenset`, `datetime` and `date` made of those, all round-tripped exactly (tuples stay tuples, big ints and NaN survive). A dataclass, ORM row or `dict` subclass raises `TypeError` at `set()`. Register the type instead: `diskcache_oxide.register_type(Episode, name='app.Episode')` for a dataclass (fields stored, rebuilt with `Episode(**fields)`), or `register_type(ObjectId, name='bson.ObjectId', encode=str, decode=ObjectId)` for anything else, at import time in every process. The name is the tag on disk; a reader without the registration gets `ForeignValueError` and the row stays. A registered type is never pickled. If arbitrary objects are really needed, give them their own `Cache(dir, pickle=True)`. - A `pickle=False` cache never unpickles: reading a row a `pickle=True` handle wrote raises `UnsafeValueError` (a `TypeError`) and keeps the row. This is a configuration mistake, not damage, so it raises under every `on_decode_error` and `durable` setting. - `bool(cache)` means "caching is on" (`Cache` and `FanoutCache` are always truthy, `NullCache` is falsy). Never use `if cache:` for "is it empty"; use `len(cache)`. - `Timeout` subclasses `TimeoutError`. The default `timeout` is 60 s; in a request path use `timeout=1.0` and treat `Timeout` as "don't cache this time". A fork counts against `timeout`, and a fork hand-off can take tens to hundreds of milliseconds, so keep about a second in a pre-forking server. - `expire=True` and `timeout=True` raise `TypeError` (a bool there is an argument in the wrong position). `size_limit` under 1 MiB raises `ValueError`. `directory` is required. - Open a cache once per process and share it across threads. The same directory opened twice in one process shares one connection pool. Use `with Cache(...) as cache:` or call `close()`; a closed handle reopens on its next use. Forks need nothing from you: a fork barrier waits for other threads' writes and the child opens fresh connections. The one thing not to do is fork inside `with cache.transact():` or from code running inside a cache call (a pickle hook, a registered type's `decode`): that child can't use that cache when the connection was open at the fork (always inside a transaction, and in a hook decoding a small value), and every call on it then raises `ForkedInsideTransactionError` (a `RuntimeError`), reads included, even with `durable=True`. - `add()` is the claim primitive: one winner across processes. A `NullCache.add()` always returns True and a `durable=True` `add()` returns False on an outage, so keep job claims and locks on a plain handle in their own small directory, with an `expire`. - `incr()`/`decr()` are atomic across processes and keep the entry's existing expiry; `incr()` on a missing key starts from `default` (0) and creates an entry that never expires. For a windowed counter, `add(key, 0, expire=2 * window)` then `incr(key)`. `default=None` makes a missing key a `KeyError`. A `delta` or `default` that is an infinity or a NaN raises `ValueError`. - `iterkeys(prefix=...)` is an indexed range scan in sorted order, safe to delete from while iterating. Without a prefix it lists `str` keys first, then `None`, bools, ints, floats, bytes and tuples, each sorted. `iter(cache)` is insertion order. An entry leaves `get`, `in`, `len()` and iteration the moment it expires (D-060); its row and space go soon after, by a `set()`'s sweep or background maintenance (D-061: one thread per process, every `maintenance_interval` seconds, default 300, 0 for off; never with `clock=`), so there's no `expire()` to schedule. Check it with `maintenance_stats()`. Maintenance writes when it has work and once an hour per cache to coordinate, so a read-only replica or backup passes `maintenance_interval=0` to every handle: maintenance is off for a cache in a process only when every handle opened on it there asked for 0, and an earlier handle that asked for an interval keeps it on until every handle on the cache has closed. - `with cache.transact() as tx:` groups writes on the calling thread; `tx` is the cache itself. Commit on exit, roll back on an exception, a nested block joins the outer one, a block whose writes were lost raises `TransactionAborted` (a `RuntimeError`) at exit. Never `await` inside the block. Beginning a transaction on a second cache whose lock another thread holds raises `TransactionBusy` at once, and `retry=True` retries only `Timeout`. On a `FanoutCache`, `transact(key=k)` locks one shard, and inside it any call for a key on another shard, or over every shard (`len`, `volume`, iteration, `clear`, `expire`, `cull`, `checkpoint`), raises `ValueError`; a bare `transact()` there is a `TypeError`. - `durable=True` is "the cache can't take a request down", not database durability. On an outage a single-key call returns its miss value (`get` the default, `set` False, `incr` `default + delta`) and logs once a minute on the `diskcache_oxide` logger. It can drop writes, so a dropped `set` or `delete` serves stale data until the entry expires. `timeout` bounds waiting for a lock or a fork, not disk work: on a saturated disk a commit can still take seconds. The constructor, admin calls (`clear`, `expire`, `cull`, `checkpoint`, `len`, `volume`, iteration), transactions and bugs (`TypeError`, `UnsafeValueError`) still raise. Pair it with a small `timeout`. - `on_decode_error='miss'` (the default under `durable=True`) makes a value that can't be decoded a miss: the row is deleted and a warning logged. A row a newer version or another host might read (`ForeignValueError`) is a miss that keeps the row. A function in its place is called as `report(key, exc)`; from a `Caches` registry it is `report(name, key, exc)`. - `NullCache(invalidate=real)` forwards only removals (`delete`, `pop`, `clear`, `evict`, `iterkeys`) to the real cache. An overwriting `set` or a version-bump `incr` is dropped while caching is off, so invalidate by deleting. The queue calls are never forwarded. A `NullCache` never encodes values, so it accepts a value a real cache refuses with `TypeError`: don't test value types only against a `NullCache`. - On a `NullCache`, `push()` returns a key and stores nothing (the job is lost), `pull()`/`peek()` return the default, a memoized function runs every call, and `get(k, tag=True)` is `(default, None)`. Keep queues, claims and locks on a cache that's never switched off. - `Caches`: register every cache at startup, before handing any out. `caches[name]` reads a plain cache and `caches.fanout(name)` one registered with `shards=` (the other way is a `TypeError`). An unregistered name is a `KeyError` from both; `caches.get(name, default=None)` returns the plain cache or `default` instead (a registered cache that can't open is still a `NullCache`, never `default`). Passing `shards=` at all, even `shards=None`, registers a `FanoutCache`. A registered `shards=n` applies only to a new folder: an existing folder keeps its own count, and the registry logs a WARNING (and one ERROR per process) instead of failing; to change the count, delete the folder with every worker stopped. `disable()`/`enable()` change later lookups only. `@caches[name].memoize()` binds at import to whatever the lookup returned (a `NullCache` if the open failed, forever); look the cache up per call if that matters. Registry `stats()` gives `CacheStats` (count, volume, `error`, and `maintenance`, the cache's `maintenance_stats()` or None if it couldn't be read); hit/miss counts are `caches[name].stats()`. Locks, claims, sessions and queues are plain `Cache(...)`s opened directly, never registered: a registry hands out a `NullCache` when one can't open. - `FanoutCache` is for a cache several worker processes use heavily (reads too), many threads (8 or so) on free-threaded Python, or a write-heavy load. With 2 or 3 threads in one process a plain `Cache` is as fast or faster, on Linux especially. It costs about 10 MiB more memory per process than a plain `Cache`. `shards` is keyword-only (`FanoutCache(path, 4)` is `timeout=4`), the count is recorded and permanent for the directory (a different `shards=` keeps the stored count with a `WARNING`, or raises `LayoutMismatchError` with `raise_on_mismatch=True`), a plain `Cache` and a `FanoutCache` refuse each other's directories, `max_connections` and `size_limit` are totals (at least `shards` connections and `shards` MiB). - Cache directories must be on a local disk. SQLite's WAL mode is required: an open where SQLite declines WAL (some FUSE mounts) raises `RuntimeError` naming the journal mode, but NFS, SMB, EFS and Azure Files usually accept WAL and then corrupt, which can't be detected, so never use them (or a Kubernetes ReadWriteMany volume). New directories are created `0700` on Unix (on Windows they inherit the parent's permissions). A directory is a cache or a parent of caches, never both: never nest a cache inside another cache's directory. - After a big fill or `clear()`, call `cache.checkpoint()` so the write-ahead log is truncated; `close()` does it for a large log; `wal_checkpoint='auto'` is the opt-in for long-running writers. Background maintenance also checkpoints a log grown past half of `wal_size_limit`, every `maintenance_interval`, as far as readers in other processes let it (it never waits for them). Explicit `expire()`, `cull()`, `clear()` and `checkpoint()` calls are for when you want it done now, each with its own `timeout=`. - `@cache.memoize(name=None, typed=False, expire=None, tag=None, ignore=())` caches a function's results, with diskcache's key shape (`f.__cache_key__(*args, **kwargs)` gives it, for `cache.delete(...)`). Call it with parentheses. `ignore` is the fifth positional argument (after `tag`), so pass it by name. Every argument not in `ignore` must be a key type, or the call raises before the function runs; put connections and clients in `ignore`. `expire=0` never stores; `None` results are cached; `async def` is refused. On a `NullCache` it runs every call. - `retry=True` (keyword-only) on `get`, `set`, `add`, `delete`, `pop`, `touch`, `incr`, `decr`, `expire`, `cull`, `clear`, `evict` and the queue calls keeps retrying a `Timeout` until it gets through, even under `durable=True`. Use it for background jobs, not request paths. `cache[k]` never retries. `transact(retry=True)` sleeps between attempts. - Coordination: `Lock(cache, key, expire=...)`, `RLock`, `BoundedSemaphore(cache, key, value=n)`, `Averager`, `@throttle(cache, count, seconds)`, `@barrier(cache, Lock)` and `@memoize_stampede(cache, expire)`, from `diskcache_oxide`, atomic across processes. Use a small cache of their own (culling and `clear()` remove lock keys); give a `Lock` an `expire`. They raise `TypeError` on a `NullCache` or `durable=True` cache (`memoize_stampede` doesn't), and `RuntimeError` if they'd wait inside a `transact()` on their own cache. - `stats(enable=True, reset=False) -> (hits, misses)` counts `get` and `cache[k]` per process, in memory, never in the database; counting is off until the first `stats()` call turns it on. `check(fix=False, retry=False)` returns a list of `warnings.WarningMessage`; `fix=True` removes broken entries (a missing or wrong-size value file, a row with a damaged column) and old orphan files, then `VACUUM`s (slow on a big cache, needs temp space, blocks writers and forks, and waits for any open transaction). `reset('size_limit' | 'cull_limit' | 'eviction_policy', value)` persists a setting for every process, and without `value` reads the stored one. `reversed(cache)`, `pop(key, expire_time=True)`, and pickling a cache (it reopens the directory) work. - Tags: `set(k, v, tag='user:42')` (`tag=` is keyword-only, any key type, compared by exact type), `get(k, tag=True)` returns `(value, tag)`, and `evict('user:42')` removes every entry that had that tag when it started; an overwrite without `tag=` clears the tag, while `touch`, `incr` and `add` on a live key keep it. `memoize(tag=...)` tags every stored result. `1`, `1.0` and `True` are three tags. `eviction_policy='none'` (keyword-only, stored in the cache) never evicts for size: use it for locks, claims and anything that must not vanish, and give those entries an `expire`. `'least-recently-used'` and `'least-frequently-used'` raise `ValueError`. - Queues (`Cache` only, not `FanoutCache`): `push(value, prefix=None, side='back', expire=None, *, tag=None, retry=False)` returns the key; `pull(prefix=None, default=(None, None), side='front', *, expire_time=False, tag=False, retry=False)` returns `(key, value)`, or `(None, None)` when empty, and each item goes to exactly one caller; `peek(...)` the same without removing; `peekitem(last=True, ...)` the newest or oldest entry, `KeyError` when empty. Open a queue's cache with `eviction_policy='none'` (least-recently-stored would evict the queue's front) and use a prefix no other key starts with. `side` must be `'front'` or `'back'` (`ValueError`). - Not available yet, so don't generate calls to them: `Deque`, `Index`, `AsyncCache`, `FanoutCache.cache()`/`deque()`/`index()`, and `read()`/`read=`. LRU/LFU eviction and `disk=` aren't coming. ## Decision table | Need | Use | |---|---| | One process, or mostly reads | `Cache(directory)` | | One hot cache that many processes or free-threaded threads write at once | `FanoutCache(directory, shards=8)` | | Many caches in one app, an admin page, switching one off by name | `Caches(base_dir, timeout=1.0, ...)` then `register(name, ...)` | | Caching off in tests, local dev or while chasing a stale-data bug | `NullCache()`, or `NullCache(invalidate=real)` so deletes still land | | A cache outage must cost speed, never a request | `Cache(..., timeout=1.0, durable=True)` | | A value that can't be decoded should be a miss, not an exception | `on_decode_error='miss'` or `on_decode_error=report` | | Store a dataclass, an `ObjectId`, a namedtuple, a `str` subclass | `register_type(cls, name=..., encode=..., decode=...)`; a dataclass needs only `name=` | | Cache arbitrary objects | register the type; otherwise a separate `Cache(dir, pickle=True)` | | Inspect rows by hand in a SQLite browser | `serializer='json'` | | Several writes that must land together | `with cache.transact() as tx:`; on a `FanoutCache`, `transact(key=k)` | | Exactly one worker runs a scheduled job | `cache.add('job:x', os.getpid(), expire=interval - margin)` on a plain, never-null handle | | Per-client rate limit shared by every worker | `add(f'rate:{client}:{window_no}', 0, expire=2 * window)` then `incr(...) <= limit` | | Invalidate everything about one user or object | `set(..., tag='user:42')` then `evict('user:42')`; or `iterkeys(prefix='user:42:')` plus `delete`; or a generation number in the key | | Cache a function's results | `@cache.memoize(expire=...)`; `@memoize_stampede(cache, expire)` when a recompute is expensive and many callers miss at once | | A cross-process lock, semaphore or rate limit | `Lock`, `BoundedSemaphore`, `throttle` on a plain `Cache(dir, eviction_policy='none')`, not durable, never a `NullCache` | | A work queue shared by worker processes | `push(value, prefix='jobs')` / `pull(prefix='jobs')` on a `Cache(dir, eviction_policy='none')` (not a `FanoutCache`) | | Tests of expiry without sleeping; tests that patch `time.time` | `Cache(tmp_path, clock=fake)`; `clock=lambda: time.time()` | | A huge `-wal` file after a write burst | `cache.checkpoint()`, or `Cache(..., wal_checkpoint='auto')` | | Django's cache framework (`django.core.cache`, `cache_page`, `{% cache %}`, cache sessions) | `'BACKEND': 'diskcache_oxide.DjangoCache'`: durable alias for pages, plain one for sessions | | Type a function that accepts any cache | `CacheLike`; `TransactionalCacheLike` if it calls `transact()`; `ShardedCacheLike` for `transact(key=)` | ## API - `Cache(directory, timeout=None, *, size_limit=None, cull_limit=None, eviction_policy=None, serializer='msgpack', pickle=False, types=None, clock=None, max_connections=None, sqlite_cache_size=None, wal_size_limit=None, wal_checkpoint='manual', on_decode_error=None, durable=False, maintenance_interval=None)`: raises `ValueError`/`TypeError` for bad settings, `LayoutMismatchError` or `FormatMismatchError` for a directory this build can't use, `Timeout` if another process holds it locked. Defaults: `timeout` 60 s, `size_limit` 1 GiB, `cull_limit` 10, `max_connections` 8, `wal_size_limit` 64 MiB. - `get(key, default=None, *, expire_time=False, tag=False, retry=False)`, `set(key, value, expire=None, *, tag=None, retry=False) -> bool`, `add(key, value, expire=None, *, tag=None, retry=False) -> bool`, `delete(key, *, retry=False) -> bool`, `pop(key, default=None, *, expire_time=False, tag=False, retry=False)`, `touch(key, expire=None, *, retry=False) -> bool`, `incr(key, delta=1, default=0, *, retry=False)`, `decr(...)`, `memoize(name=None, typed=False, expire=None, tag=None, ignore=())`, `iterkeys(*, prefix=None, reverse=False)`, `expire(*, timeout=None, retry=False) -> int`, `clear(*, timeout=None, retry=False) -> int`, `evict(tag, *, timeout=None, retry=False) -> int`, `cull(*, timeout=None, retry=False) -> int`, `reset(key, value=ENOVAL)`, `stats(enable=True, reset=False)`, `check(fix=False, retry=False)`, `push`, `pull`, `peek`, `peekitem`, `volume() -> int`, `checkpoint(*, timeout=None) -> bool` (False when busy, never raises for that), `maintenance_stats() -> MaintenanceStats`, `close(*, checkpoint=True)`, `transact(retry=False)`; plus `cache[key]`, `cache[key] = value` (never expires), `del cache[key]`, `key in cache`, `len(cache)`, `iter(cache)`, `reversed(cache)`, `with`. Properties: `directory`, `timeout`, `size_limit`, `cull_limit`, `eviction_policy`, `enabled`, `durable`. - `FanoutCache(directory, timeout=None, *, shards=None, ..., raise_on_mismatch=False)` (a `shards=` that differs from the root's stored count keeps the stored count and logs a `WARNING`, or raises `LayoutMismatchError` with `raise_on_mismatch=True`; a root in another format redirects either way) with the same settings, single-key methods, `memoize`, `evict`, `stats`, `check`, `maintenance_stats` (shards' counts summed, the largest `interval`, `last_error` from the first shard in order that has one) and `reset` (a `size_limit` is split across shards), no queue calls, plus `shards`, `shard_of(key) -> int` and `transact(*, key, retry=False)`. Its `clear`/`expire`/`cull`/`checkpoint` share one `timeout` across the shards and, on failure, raise with `failed_shards` and `removed` attributes. - `remove_old_formats() -> list[str]` on `Cache` and `FanoutCache` (`[]` on `NullCache`): removes caches in an older on-disk format from the cache's directory and returns the paths removed. No check for other processes: call it only once every older worker has stopped. `directory` is where the cache really is (the versioned subdirectory after a format change); reopen with the original directory, not `directory`. - `NullCache(directory=None, timeout=None, *, ..., invalidate=None)`: accepts and ignores `Cache`'s settings; `get`/`pop` return the default, `set`/`add` return True, `incr` returns `default + delta`, everything else is 0, False or empty; `transact()` is a no-op yielding itself. - `Caches(base_dir, *, on_open_error=None, retry_open_after=10.0, **defaults)`: `register(name, *, directory=None, **settings)`, `caches[name]`, `get(name, default=None)`, `fanout(name)`, `disable(*names)`, `enable(*names)`, `enabled(name)`, `stats() -> dict[name, CacheStats]`, `clear(name, *, timeout=None)` (raises if it can't open), `expire_all(*, timeout=None)`, `remove_old_formats() -> dict[name, Optional[list[str]]]`, `close_all()`, `with`. - Protocols: `CacheLike`, `TransactionalCacheLike` (adds `transact(retry=False)` and `push`/`pull`/`peek`/`peekitem`), `ShardedCacheLike` (adds `transact(*, key, retry=False)`). `Cache` and `NullCache` are transactional; `FanoutCache` and `NullCache` are sharded. - `register_type(cls, *, name, encode=None, decode=None)`, `unregister_type(cls) -> bool`, `registered_types() -> dict[str, type]`, on the process-wide `registry: TypeRegistry`; `TypeRegistry()` with the same `register`/`unregister`/`registered` for one cache's `types=`. Own built-in types can't be registered (`ValueError`); one of `encode`/`decode` alone, a non-dataclass with neither, or a dataclass with an `InitVar` is `TypeError`. - Exceptions: `Timeout(TimeoutError)`, `TransactionBusy(Timeout)`, `TransactionAborted(RuntimeError)`, `UnsafeValueError(TypeError)`, `CorruptValueError(ValueError)`, `CorruptKeyError(CorruptValueError)` (iteration met a stored key it can't read), `ForeignValueError(CorruptValueError)`, `FormatMismatchError(RuntimeError)`, `LayoutMismatchError(FormatMismatchError, ValueError)`, `ForkedInsideTransactionError(RuntimeError)` (every call on a cache in a child forked while a connection to it was open; a `Caches` lookup and a durable Django alias raise it too). - Warnings from `check()`: `UnknownFileWarning`, `EmptyDirWarning`. Sentinels: `ENOVAL`, `UNKNOWN`. Types: `Key` (the key union), `Memoized`, `Memoizer`, `CacheStats`, `MaintenanceStats` (a `TypedDict`: `interval`, `turns`, `removed`, `failures`, `last_error`). Recipes: `Lock`, `RLock`, `BoundedSemaphore`, `Averager`, `throttle`, `barrier`, `memoize_stampede`. - `DjangoCache(location, params)`, Django's backend class, loaded lazily (not in `__all__`): Django's API plus `tag=` on `set`/`add`, `evict(tag)`, `pop(key, default=None, version=None)`, `expire()`, `cull()`, `stats()`, `maintenance_stats()`, `check(fix=False)`, and `cache` (the `Cache` underneath; its keys are `prefix:version:key`). `diskcache_oxide.djangocache.close_all()`. - `sqlite_version()`, `sqlite_compile_options()`, `BUNDLED_SQLITE_VERSION`, `__version__`. Logging goes to the `diskcache_oxide` logger. There is no CLI and no environment variable to configure. ## Reading an error ```text TypeError: values of type Episode can't be stored without pickle (only exact built-in types round-trip) ``` It is raised by `set()`, where the value was created, not by a later `get()`. Fix in this order: register the type (`register_type(Episode, name='app.Episode')`), or store a dict (a `model_dump()`), then, only if arbitrary objects are really required, open a separate `Cache(other_dir, pickle=True)` for them. A registered type that still raises has an `encode` that raised or returned something unstorable, or a field that is; that raises even with `pickle=True`. Don't add `pickle=True` to the shared cache to make the error go away: every reader of that directory then runs unpickle on whatever is written there. ```text diskcache_oxide.Timeout: timed out after 1 s waiting for a lock or a pending fork ``` Someone held the write lock (a `clear()` in a maintenance script, a long `transact()` block, a fork in flight) for longer than `timeout`. In a request, catch it and skip the cache. If it's common, raise `timeout`, run admin calls such as a big `clear()` from one place with their own `timeout=`, shorten transaction blocks, or move many writing processes to a `FanoutCache`. `durable=True` turns it into a miss for single-key calls. ## Resources - [Documentation](https://mkennedy.codes/docs/diskcache-oxide/), including [Getting started](https://mkennedy.codes/docs/diskcache-oxide/user-guide/getting-started.html), [Errors and what to do about them](https://mkennedy.codes/docs/diskcache-oxide/user-guide/errors.html), [Switching from diskcache](https://mkennedy.codes/docs/diskcache-oxide/user-guide/switching-from-diskcache.html), [Serialization](https://mkennedy.codes/docs/diskcache-oxide/user-guide/serialization.html), [NullCache](https://mkennedy.codes/docs/diskcache-oxide/user-guide/null-cache.html), [Caches](https://mkennedy.codes/docs/diskcache-oxide/user-guide/caches.html), [FanoutCache](https://mkennedy.codes/docs/diskcache-oxide/user-guide/fanoutcache.html), [Transactions](https://mkennedy.codes/docs/diskcache-oxide/user-guide/transactions.html), [Concurrency and forks](https://mkennedy.codes/docs/diskcache-oxide/user-guide/concurrency-and-forks.html), [Storage and WAL](https://mkennedy.codes/docs/diskcache-oxide/user-guide/storage-and-wal.html), [Performance](https://mkennedy.codes/docs/diskcache-oxide/user-guide/performance.html) and the [Recipes](https://mkennedy.codes/docs/diskcache-oxide/recipes/). For a user who is new to caching itself, point them at [New to caching? Start here](https://mkennedy.codes/docs/diskcache-oxide/user-guide/new-to-caching.html). - [llms.txt](https://mkennedy.codes/docs/diskcache-oxide/llms.txt), the API index, and [llms-full.txt](https://mkennedy.codes/docs/diskcache-oxide/llms-full.txt), every signature, docstring and guide page in one file. - [Source](https://github.com/mikeckennedy/diskcache-oxide) and [issues](https://github.com/mikeckennedy/diskcache-oxide/issues).