# Errors and what to do about them Sooner or later a traceback ends in `diskcache_oxide`, and the question is whether it's your bug, an outage, or two processes disagreeing about what a directory is for. diskcache-oxide raises when something is wrong rather than guessing, and each exception is chosen so that `except` clauses you already have keep working: [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) is a `TimeoutError`, [TransactionAborted](../reference/TransactionAborted.md#diskcache_oxide.TransactionAborted) is a `RuntimeError`, [UnsafeValueError](../reference/UnsafeValueError.md#diskcache_oxide.UnsafeValueError) is a `TypeError`, [LayoutMismatchError](../reference/LayoutMismatchError.md#diskcache_oxide.LayoutMismatchError) is a `ValueError`. This page is the field guide: every exception, what it means, and what to do. The last section covers the log lines the library writes when it has been told not to raise, because then a log line is the only evidence you'll get. If you're starting from a symptom rather than an exception (every lookup misses, the disk keeps growing), see [Troubleshooting](troubleshooting.md). | Exception | Base classes | Where | |----|----|----| | [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) | `TimeoutError` (so `OSError`) | any call that waits for a lock or a fork | | [TransactionBusy](../reference/TransactionBusy.md#diskcache_oxide.TransactionBusy) | [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) | [transact()](../reference/Cache.transact.md#diskcache_oxide.Cache.transact) on a second cache | | [TransactionAborted](../reference/TransactionAborted.md#diskcache_oxide.TransactionAborted) | `RuntimeError` | a [transact()](../reference/Cache.transact.md#diskcache_oxide.Cache.transact) block that didn't commit | | [UnsafeValueError](../reference/UnsafeValueError.md#diskcache_oxide.UnsafeValueError) | `TypeError` | reading a pickled value without `pickle=True` | | [CorruptValueError](../reference/CorruptValueError.md#diskcache_oxide.CorruptValueError) | `ValueError` | reading a value no build could decode | | [ForeignValueError](../reference/ForeignValueError.md#diskcache_oxide.ForeignValueError) | [CorruptValueError](../reference/CorruptValueError.md#diskcache_oxide.CorruptValueError) | reading a value another version or host could decode | | [CorruptKeyError](../reference/CorruptKeyError.md#diskcache_oxide.CorruptKeyError) | [CorruptValueError](../reference/CorruptValueError.md#diskcache_oxide.CorruptValueError) | iterating over a stored key that can't be read | | [FormatMismatchError](../reference/FormatMismatchError.md#diskcache_oxide.FormatMismatchError) | `RuntimeError` | a database or manifest this version can't read, where the versioned subdirectory can't help | | [LayoutMismatchError](../reference/LayoutMismatchError.md#diskcache_oxide.LayoutMismatchError) | [FormatMismatchError](../reference/FormatMismatchError.md#diskcache_oxide.FormatMismatchError), `ValueError` | opening a directory as the wrong kind of cache | | [ForkedInsideTransactionError](../reference/ForkedInsideTransactionError.md#diskcache_oxide.ForkedInsideTransactionError) | `RuntimeError` | any call on a cache in a child process forked while a connection to it was open | | `TypeError`, `ValueError`, `KeyError`, `RuntimeError`, `OSError`, `OverflowError`, `AssertionError`, `MemoryError` | built-in | described below | | [UnknownFileWarning](../reference/UnknownFileWarning.md#diskcache_oxide.UnknownFileWarning) | `UserWarning` | a [check()](../reference/Cache.check.md#diskcache_oxide.Cache.check) finding, returned rather than issued (see below) | | [EmptyDirWarning](../reference/EmptyDirWarning.md#diskcache_oxide.EmptyDirWarning) | `UserWarning` | never raised or issued; kept for code that imports diskcache's name | # `TypeError` at [set()](../reference/Cache.set.md#diskcache_oxide.Cache.set): a value that can't be stored ``` text TypeError: values of type Episode can't be stored without pickle (only exact built-in types round-trip) ``` The value isn't one the msgpack or JSON format can represent exactly, so it's refused where it was created rather than three requests later when something reads it. Only exact built-in types round-trip: `str`, `bytes`, `int`, `float`, `bool`, `None`, `Decimal`, and `list`, `tuple`, `dict`, [set](../reference/Cache.set.md#diskcache_oxide.Cache.set), `frozenset`, `datetime` and `date` made of those. A dataclass, an ORM row, a `dict` subclass or a class of your own doesn't. Fix it in this order: 1. Register the type: `diskcache_oxide.register_type(Episode, name='tp.Episode')` for a dataclass, or with `encode=` and `decode=` functions for anything else (an `ObjectId`, a namedtuple, a `str` subclass). The value is stored without pickle and comes back as the type you stored. See [Your own types](serialization.md#your-own-types). 2. Or store a plain structure instead: a dict from a model's `model_dump()`, and rebuild the object on the way out. 3. If you really need arbitrary objects, open a separate cache for them with `Cache('/var/cache/my-app-objects', pickle=True)`. Don't turn `pickle=True` on for a cache that other code shares just to make the error go away: every reader of that directory then runs `pickle.loads` on whatever is written there. See [Serialization](serialization.md). A `str` holding a lone surrogate (`'\ud800'`, which can arrive from a JSON body or `surrogateescape` decoding) can't be stored as UTF-8. Nested inside a value it raises `UnicodeEncodeError` without pickle and is pickled with it, as diskcache does; as a top-level value it raises either way, as it does in diskcache. A registered type that still raises here is one whose `encode` function raised, or returned something the codec can't store, or a dataclass with a field it can't store. That raises even on a cache with `pickle=True`: a registered type is never pickled. # `TypeError` for keys and booleans ``` text TypeError: cache keys must be str, bytes, int, float, bool, None, or a tuple of those, not list TypeError: expire must be a number of seconds or None, not bool ``` Keys are `str`, `bytes`, `int` (64-bit), `float`, `bool`, `None`, or tuples of those. Only the exact types: a subclass such as an `IntEnum` or a `namedtuple`, a `list` or an int past 64 bits raises `TypeError`, and a NaN key raises `ValueError`, since it isn't equal to itself. Pass a tuple where you'd use a list. A memoized function's arguments follow the same rules, and the error names the argument. A `bool` where a number of seconds belongs (`expire=True`, `timeout=True`) is almost always an argument in the wrong position, so it's refused rather than treated as `1`, which is what diskcache does. # [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout): a lock or a fork outlasted [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout) ``` text diskcache_oxide.Timeout: timed out after 1 s waiting for a lock or a pending fork ``` The call waited the cache's [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout) (60 s by default, or the `timeout=` passed to that call) and gave up. Something held what it needed, and there are three suspects: - **Another writer held the write lock** that long. One process at a time commits to a database file, and a burst of writes, a [clear()](../reference/Cache.clear.md#diskcache_oxide.Cache.clear) from a maintenance script, or a long [transact()](../reference/Cache.transact.md#diskcache_oxide.Cache.transact) block holds it. Reads never wait for writers, so a [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) on a [get](../reference/Cache.get.md#diskcache_oxide.Cache.get) is one of the next two cases. - **A fork was pending.** Before a fork, every cache call in the process waits for in-flight writes and then for the fork itself, and that counts against [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout). A fork takes about a millisecond in a quiet process and tens to hundreds of milliseconds beside busy threads on a GIL build. A [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout) below that sees [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) during ordinary forks. See [How long a call waits for a fork](concurrency-and-forks.md#how-long-a-call-waits-for-a-fork). - **Reading a large value kept losing to overwrites** of the same key until [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout). Rare, and only on a key that's rewritten flat out. What to do: - **In a request path, catch it and skip the cache.** Give the cache a short [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout) (`Cache(path, timeout=1.0)`), and treat [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) as "don't cache this time": the value is a copy, and the request can go to the source of truth. [Sharing a cache across web workers](../recipes/web-workers.md) has the pattern. - **Give maintenance its own timeout.** [clear()](../reference/Cache.clear.md#diskcache_oxide.Cache.clear), [expire()](../reference/Cache.expire.md#diskcache_oxide.Cache.expire) and [cull()](../reference/Cache.cull.md#diskcache_oxide.Cache.cull) take `timeout=` for that call, and bound each chunk's wait, so an admin page can pass `clear(timeout=10)` on a cache whose requests use 1 second. There's nothing to schedule: background maintenance already removes expired entries, trims a cache over its limit and checkpoints the log, for every open cache. Call [expire()](../reference/Cache.expire.md#diskcache_oxide.Cache.expire), [cull()](../reference/Cache.cull.md#diskcache_oxide.Cache.cull), [clear()](../reference/Cache.clear.md#diskcache_oxide.Cache.clear) or [checkpoint()](../reference/Cache.checkpoint.md#diskcache_oxide.Cache.checkpoint) when you want it done now. - **Keep [transact()](../reference/Cache.transact.md#diskcache_oxide.Cache.transact) blocks short**, and never `await` inside one. - **If many processes write often, use a [`FanoutCache`](fanoutcache.md).** A plain [Cache](../reference/Cache.md#diskcache_oxide.Cache) has one write lock per directory, and eight workers that all write queue on it. Sharding gives each shard its own. - **Let the library answer it as a miss** with [`durable=True`](getting-started.md#a-cache-that-cant-take-a-request-down): single-key calls then return their miss value instead of raising, and the failure is counted and logged. Pair it with a small [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout), since it doesn't bound time on its own. - [checkpoint()](../reference/Cache.checkpoint.md#diskcache_oxide.Cache.checkpoint) never raises [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout): it returns `False` when other processes keep it busy. Call it again later, or at shutdown. # [TransactionBusy](../reference/TransactionBusy.md#diskcache_oxide.TransactionBusy): two caches in one transaction Inside one cache's [transact()](../reference/Cache.transact.md#diskcache_oxide.Cache.transact) block, beginning a transaction on a second cache whose write lock another thread holds raises [TransactionBusy](../reference/TransactionBusy.md#diskcache_oxide.TransactionBusy) at once instead of waiting. That thread could be waiting for the lock you hold, and then neither would ever finish. It's a [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) subclass, so existing handlers catch it, and `retry=True` never retries it. Nest the two caches in the same order everywhere in your app. When [TransactionBusy](../reference/TransactionBusy.md#diskcache_oxide.TransactionBusy) reaches you, leave the outer block, so your lock is released, and try the whole thing again. See [Transactions](transactions.md#two-caches-at-once-transactionbusy). # [TransactionAborted](../reference/TransactionAborted.md#diskcache_oxide.TransactionAborted): a block that didn't commit ``` text TransactionAborted: the write transaction was rolled back after an error; nothing in it can commit ``` A `with cache.transact():` block never exits cleanly when its writes are gone. This one comes from a write inside the block, or from the block's exit, after one of its operations failed in a way that left the transaction unusable (a full disk, an I/O error). ``` text TransactionAborted: the transaction did not commit: another thread or an earlier exit ended it, or it was rolled back after an error ``` This one comes from the block's exit, when the transaction had already ended without committing: another thread rolled it back, or an earlier [__exit__](../reference/Cache.__exit__.md#diskcache_oxide.Cache.__exit__) call on the same object ended it (including one made from inside the block's own operations, such as a pickle hook, which raises `RuntimeError` where it's called and rolls the transaction back when that operation returns). Either way nothing in the block was kept. Treat it as you would the original failure: log it, and run the block again if the work is idempotent. [TransactionAborted](../reference/TransactionAborted.md#diskcache_oxide.TransactionAborted) is a `RuntimeError`, so an `except RuntimeError` you already have still catches it; catch [TransactionAborted](../reference/TransactionAborted.md#diskcache_oxide.TransactionAborted) to handle this case alone. # [ForkedInsideTransactionError](../reference/ForkedInsideTransactionError.md#diskcache_oxide.ForkedInsideTransactionError): a cache that can't be used after a fork ``` text diskcache_oxide.ForkedInsideTransactionError: this cache can't be used in this process: it was forked while a connection to it was open (inside a transaction, or from a hook running inside a cache call); fork outside the transaction, or start the process with spawn or forkserver ``` This process is the child of a fork that happened while the forking thread had a connection to this cache open: inside its own [transact()](../reference/Cache.transact.md#diskcache_oxide.Cache.transact) block, or from code running inside a cache call while that call had its connection out, such as a pickle hook or a registered type's `decode` reading a small value. It also happens to the child of a plain `os.fork()` on one thread while another thread, inside its own transaction, was waiting to fork too. The parent is fine, and its transaction carries on and commits. In the child, every call on that cache raises this, reads included, for as long as the process lives, on a `durable=True` handle too. Other caches work, and [close()](../reference/Cache.close.md#diskcache_oxide.Cache.close) still does. It's a `RuntimeError`, so code that caught that keeps working. A [`Caches`](caches.md) lookup and a [durable](../reference/Cache.durable.md#diskcache_oxide.Cache.durable) Django alias raise it too when they'd have to open the cache in that child: no retry can help, so there's no [NullCache](../reference/NullCache.md#diskcache_oxide.NullCache) to fall back on. It's raised because the alternative is silent: a child like that holds none of the locks SQLite thinks it holds, so its reads could go stale and its writes could vanish. Don't fork from inside a transaction or a cache call: start worker processes before the block, or after it, or use the `spawn` or `forkserver` start method. See [Forking from inside your own transaction](concurrency-and-forks.md#forking-from-inside-your-own-transaction). ``` text diskcache_oxide.ForkedInsideTransactionError: this transaction was inherited across fork() and can't be used in the child ``` The same child, leaving the `with cache.transact():` block it was forked inside. Nothing in the block commits there; the parent's copy is the real one. # [UnsafeValueError](../reference/UnsafeValueError.md#diskcache_oxide.UnsafeValueError): a pickled value, read without `pickle=True` ``` text UnsafeValueError: this value was stored with pickle; open the cache with pickle=True to read it ``` Two openers of one directory disagree about what it's allowed to hold. A handle opened without `pickle=True` found a row that a `pickle=True` handle wrote, and refused to unpickle it, because unpickling runs whatever code the bytes describe. The row is left in place for the handle that can read it. This is a configuration mismatch, not damage, so it raises under every `on_decode_error` policy and under `durable=True` too. Decide which the directory is for. If it holds pickled objects on purpose, open every handle on it with `pickle=True`. If it shouldn't, find the writer that passed `pickle=True` and give it its own directory, then [clear()](../reference/Cache.clear.md#diskcache_oxide.Cache.clear) this one. It's a `TypeError`, like the error at [set()](../reference/Cache.set.md#diskcache_oxide.Cache.set) above, because both come from the same decision: what this cache is allowed to hold. # [CorruptValueError](../reference/CorruptValueError.md#diskcache_oxide.CorruptValueError) and [ForeignValueError](../reference/ForeignValueError.md#diskcache_oxide.ForeignValueError): a value that can't be decoded ``` text ForeignValueError: ... CorruptValueError: ... ``` [CorruptValueError](../reference/CorruptValueError.md#diskcache_oxide.CorruptValueError) means no build of diskcache-oxide could read the stored bytes: they're malformed, a pickled class has been removed since it was stored, or a [registered type's](serialization.md#your-own-types) `decode` function raised about the row (a dataclass row written before a field was removed, say), in which case your exception is its `__cause__`. [ForeignValueError](../reference/ForeignValueError.md#diskcache_oxide.ForeignValueError), its subclass, means this build can't read them but another might: a newer version wrote a mode or tag this one doesn't know, the value needs a time zone this host doesn't have, or it holds a registered type this process hasn't registered (the message names the tag: register it, at import time). By default a read raises these, as diskcache does. A cache holds copies, so most apps would rather treat them as a miss: - `Cache(..., on_decode_error='miss')` returns the default, logs a warning on the `diskcache_oxide` logger, and deletes a row no build could read. A foreign row is kept, since the build that wrote it can still read it. `durable=True` turns this on by default. - Pass a function instead to report it yourself: `on_decode_error=lambda key, exc: sentry.capture(exc)`. From a [Caches](../reference/Caches.md#diskcache_oxide.Caches) registry it's called as `(name, key, exc)`. - For a [ForeignValueError](../reference/ForeignValueError.md#diskcache_oxide.ForeignValueError) that keeps coming back, upgrade the older readers to the version that wrote the value, or stop the newer writer from sharing the directory. For a missing time zone, install the host's zone data. The full table of what each policy does with each failure is in [Reading damaged values](#reading-damaged-values), below. [CorruptKeyError](../reference/CorruptKeyError.md#diskcache_oxide.CorruptKeyError), another subclass, comes from iterating a cache (`for key in cache`, [iterkeys()](../reference/Cache.iterkeys.md#diskcache_oxide.Cache.iterkeys)) when a stored key's bytes are damaged, which takes a damaged database page or file. Iteration raises rather than skip the key. Run `cache.check()` to see what else is damaged, or delete the directory: a cache can always start cold. # Reading damaged values What each `on_decode_error` policy does with each kind of failure, for [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) (and, for the cases that apply to it, [get](../reference/Cache.get.md#diskcache_oxide.Cache.get)). The policies themselves are introduced in [Values that can't be read](getting-started.md#values-that-cant-be-read). [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) decodes the value before it deletes the row, so a value that another version or host might read survives it. This table is the usual path; the fallback described below it removes the row first. | What went wrong | `'raise'` | `'miss'` or a function | `durable=True`, with its default `'miss'` or a function | |----|----|----|----| | A foreign value | raises [ForeignValueError](../reference/ForeignValueError.md#diskcache_oxide.ForeignValueError), row kept | returns the default and reports, row kept | the same as `'miss'` | | [UnsafeValueError](../reference/UnsafeValueError.md#diskcache_oxide.UnsafeValueError) | raises, row kept | raises, row kept | raises, row kept | | An unreadable value (malformed bytes, a failing unpickle, a registered type's `decode` raising about the row) | deletes that version, then raises | deletes that version, returns the default and reports | the same as `'miss'` | | An unreadable value, and that delete fails | raises the delete's error, row kept | raises the delete's error, row kept | returns the default and reports both, row kept | | [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout), an I/O error or `RecursionError` from a pickle hook or a registered type's `decode` | raises, row kept | raises, row kept | returns the default, row kept, reported once per stored version | | `RecursionError` from a value too deep for this thread's stack | raises, row kept | raises, row kept | returns the default, row kept, reported once per stored version | | `MemoryError` or a `BaseException` from a pickle hook or a `decode` | raises, row kept | raises, row kept | raises, row kept | | The value decoded, and the delete fails | raises the delete's error, row kept | raises the delete's error, row kept | returns the default, never the value, row kept | `durable=True` with an explicit `on_decode_error='raise'` follows the `'raise'` column, except that when an unreadable value's delete fails it raises the decode error rather than the delete's. If that delete itself fails, for example with [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout), its error is raised under every policy with the decode error as its `__cause__`, unless `durable=True`, and the row stays. A value still goes to exactly one caller, because [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) deletes only the version it decoded. A [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) that loses that delete to another writer reads again, and after 8 losses it falls back to removing the row first and decoding afterwards, so it can't starve. If its [timeout](../reference/Cache.timeout.md#diskcache_oxide.Cache.timeout) has run out by the time it loses, it raises [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) instead: this [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) deletes nothing, and whatever the other writer left stays. There are two limits: - That fallback is the one place a failed decode can cost the value, because the row is already gone: a foreign value in a known mode, or any error from a pickle hook ([Timeout](../reference/Timeout.md#diskcache_oxide.Timeout), `MemoryError`, an I/O error). It's possible on a heavily overwritten key, since a [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) can lose while it queues for the write lock. How often it happens hasn't been measured yet. - Like [get](../reference/Cache.get.md#diskcache_oxide.Cache.get), [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) doesn't wait to clean up a row whose large value file has gone missing. It returns the default, and if the write lock is busy the row can stay until a later [pop](../reference/Cache.pop.md#diskcache_oxide.Cache.pop) or write removes it. # A cache in another format: a warning, not an error Since 0.3.5, a cache directory that holds a cache in another on-disk format doesn't raise. The cache opens in the subdirectory `diskcache-oxide-format-N` (N being this release's format) and logs a warning on the `diskcache_oxide` logger, once per process: ``` text /var/cache/my-app holds a cache made by an older diskcache-oxide (format 2), so this build (format 3) is using /var/cache/my-app/diskcache-oxide-format-3 instead; once no older process uses it, call remove_old_formats() or delete the old files there, keeping diskcache-oxide-format-3 ``` Later processes log it worded as "still holds" until the old files are removed. When the cache was made by a newer release (a rollback), the warning says so and suggests upgrading this process. Nothing needs fixing: it's how an upgrade across a format change works. See [Upgrading across a format change](../recipes/upgrading.md) for cleaning up. # [FormatMismatchError](../reference/FormatMismatchError.md#diskcache_oxide.FormatMismatchError): a database this version can't read ``` text FormatMismatchError: cache format version 4 is not supported (this build uses version 3) (in /var/cache/my-app/diskcache-oxide-format-3/diskcache-oxide.sqlite): it was made by a newer diskcache-oxide: upgrade this process ``` A database, or a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache) manifest, in a format this build doesn't know, where opening the versioned subdirectory can't help. Nothing is read or changed. You'll see it in two cases: - **Inside the versioned subdirectory itself.** Most often, the subdirectory was opened directly, from a saved `cache.directory`, by a release with another format. Open its parent directory instead: the original directory picks the right subdirectory for each release. If the parent fails too, `diskcache-oxide-format-3` holds a format something else put there: with every process using it stopped, delete that subdirectory and it's recreated empty. - **From 0.2.3 or earlier, meeting a cache made by a newer release.** Those releases don't know about the subdirectory. Upgrade the process, or point it at a different directory. # [LayoutMismatchError](../reference/LayoutMismatchError.md#diskcache_oxide.LayoutMismatchError): the wrong kind of cache for the directory ``` text LayoutMismatchError: this FanoutCache has 8 shards but shards=16 was requested; changing the count needs a new directory ``` The directory's layout doesn't match how it was opened: a plain [Cache](../reference/Cache.md#diskcache_oxide.Cache) on a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache) root or one of its shard directories, a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache) on a plain [Cache](../reference/Cache.md#diskcache_oxide.Cache)'s directory, or, with `raise_on_mismatch=True`, a `shards=` count that differs from the one the root records. (Without `raise_on_mismatch`, another count opens with the root's own and logs a warning, unless a [size_limit](../reference/Cache.size_limit.md#diskcache_oxide.Cache.size_limit) or `max_connections` that fits your count can't be split over the root's: then it raises `this FanoutCache has 8 shards but shards=4 was asked for, and its settings don't fit 8 shards: ...`, from a plain [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache) or a registry alike.) The refused open creates nothing, so a typo doesn't leave a directory neither kind can open. It's both a `ValueError` and a [FormatMismatchError](../reference/FormatMismatchError.md#diskcache_oxide.FormatMismatchError). Use the class the directory was created with, and for a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache) with `raise_on_mismatch=True` either leave [shards](../reference/FanoutCache.shards.md#diskcache_oxide.FanoutCache.shards) out (the stored count is used) or pass the stored one. A different shard count means a new directory: the count decides where every key lives, so it can't change in place. See [The layout and the hash](fanoutcache.md#the-layout-and-the-hash). In a [`Caches`](caches.md) registry, a lookup that hits a role mismatch returns a [NullCache](../reference/NullCache.md#diskcache_oxide.NullCache) and reports it like any failed open. Another shard count is not an error there: the registry opens the folder with the count on disk and logs a warning (below). It still fails with [LayoutMismatchError](../reference/LayoutMismatchError.md#diskcache_oxide.LayoutMismatchError), and so a [NullCache](../reference/NullCache.md#diskcache_oxide.NullCache), when a [size_limit](../reference/Cache.size_limit.md#diskcache_oxide.Cache.size_limit) or `max_connections` that fits the registered count is too small to split over the folder's count; delete the folder or raise the setting. # `RuntimeError`: the filesystem can't run SQLite in WAL mode ``` text RuntimeError: the cache requires WAL journal mode, but SQLite is using "delete" ``` SQLite refused write-ahead logging, which diskcache-oxide requires for readers and a writer to work at the same time. That happens on some FUSE mounts and other filesystems without the shared memory WAL needs. The cache has to live on a local disk: `/var/lib/`, or a Docker volume on the host's disk. Don't take a successful open as proof the filesystem is fine: on NFS, SMB, EFS or Azure Files SQLite usually accepts WAL and then its locks don't hold, which this check can't detect. See [Pick a directory](../recipes/web-workers.md#pick-a-directory). # `OSError` - **Too many open files (`errno` `EMFILE`) opening a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache)** (macOS and Linux; Windows has no `ulimit` on open files). Each shard takes about 4 file descriptors to open, so 256 shards need more than Linux's usual `ulimit -n` of 1,024. The message gives the shard count, the descriptors needed, the limit and how many are already open. Raise the limit, or use fewer shards; eight is plenty for most apps. A failed open leaves nothing behind. - **No hard links.** Creating a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache) manifest uses a hard link, so a filesystem without them (FAT, exFAT, SMB, some FUSE mounts) raises `OSError` saying so. Use a local disk. - **Disk full, or an I/O error.** The write didn't happen and the cache is unchanged. Under `durable=True` a single-key call answers it as a miss or `False` and logs it; otherwise it raises. [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) is an `OSError` too, so an `except OSError` around a cache call catches both. # `ValueError` - [size_limit](../reference/Cache.size_limit.md#diskcache_oxide.Cache.size_limit) below 1 MiB. In diskcache a tiny limit silently evicts every value, including the one just stored; here it's refused. For a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache) the total must be at least [shards](../reference/FanoutCache.shards.md#diskcache_oxide.FanoutCache.shards) MiB, since each shard needs 1 MiB. - `max_connections` below [shards](../reference/FanoutCache.shards.md#diskcache_oxide.FanoutCache.shards) on a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache). Each shard needs at least one connection. - A key on another shard inside `transact(key=...)`. The block covers one shard, and a call for a key elsewhere, reads included, can't be atomic with it. Check with [shard_of()](../reference/FanoutCache.shard_of.md#diskcache_oxide.FanoutCache.shard_of) that the keys share a shard, or keep them in one value. - A [Caches](../reference/Caches.md#diskcache_oxide.Caches) name that's taken, isn't a plain directory name, or would share a directory with another registered cache. - A `maintenance_interval` out of range: `maintenance_interval must be 0 (off), or from 1 to 86400 seconds (a day), got ...`, for NaN and infinity too. A `bool` or anything that isn't a number raises `TypeError` instead. - A nonzero `maintenance_interval` together with `clock=`: `maintenance_interval can't be used with clock=: ...`. The thread only knows the wall clock, so a cache with its own clock gets no maintenance; leave `maintenance_interval` out or pass 0. This is checked before the range. # [UnknownFileWarning](../reference/UnknownFileWarning.md#diskcache_oxide.UnknownFileWarning) and [EmptyDirWarning](../reference/EmptyDirWarning.md#diskcache_oxide.EmptyDirWarning) [check()](../reference/Cache.check.md#diskcache_oxide.Cache.check) returns what it found as a list of `warnings.WarningMessage` and issues nothing through `warnings`, so these never show up as warnings on their own. A file in the cache directory or a value folder that no entry names, and that's over an hour old, is reported as `unknown file: ...` with the category [UnknownFileWarning](../reference/UnknownFileWarning.md#diskcache_oxide.UnknownFileWarning); `check(fix=True)` removes it when it's in a value folder, under the write lock, so it waits for any open transaction (whose uncommitted entry may be the one that names the file) and raises [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout) if that transaction outlasts the timeout. An entry with a damaged column is reported as `damaged row N: its COLUMN is stored as TYPE`, and removed by `check(fix=True)`. Until then, an entry with a damaged file name, or a damaged size on a value stored in a file, reads as a miss; one with a damaged `mode`, `expire_time` or `store_seq` can raise `OSError` from calls on that key, and from [pull](../reference/Cache.pull.md#diskcache_oxide.Cache.pull), [peek](../reference/Cache.peek.md#diskcache_oxide.Cache.peek) or [peekitem](../reference/Cache.peekitem.md#diskcache_oxide.Cache.peekitem) when it's the entry they reach. A `store_seq` of 2^62 - 1 or more is reported as `an integer too large to be one`, and a `size` below 0 or above 2^48 as `an integer no size can be`. Damage to the cache's own bookkeeping row is reported as `damaged cache state: its COLUMN is stored as TYPE`: a stored total (`count`, `size`) of the wrong type, which `check(fix=True)` recounts, or a damaged next sequence number (`next_seq`), which makes every write raise `OSError` until `check(fix=True)` sets it past every entry's. [EmptyDirWarning](../reference/EmptyDirWarning.md#diskcache_oxide.EmptyDirWarning) is diskcache's warning for an empty folder. It's exported so code that imports it keeps working, but [check()](../reference/Cache.check.md#diskcache_oxide.Cache.check) never reports one: empty value folders are normal on an open cache, and `check(fix=True)` sweeps them. # `KeyError` - `cache[key]` and `del cache[key]` for a missing or expired key, as with a dict. Use [get()](../reference/Cache.get.md#diskcache_oxide.Cache.get) and [delete()](../reference/Cache.delete.md#diskcache_oxide.Cache.delete) for the "might not be there" cases. - `incr(key, default=None)` and `decr(key, default=None)` on a missing key. With the default `default=0`, a missing key starts counting from 0 instead. - Every `NullCache[key]`, since nothing is ever present. # From the coordination recipes and the queue calls - `TypeError: Lock needs a real cache`: [Lock](../reference/Lock.md#diskcache_oxide.Lock), [RLock](../reference/RLock.md#diskcache_oxide.RLock), [BoundedSemaphore](../reference/BoundedSemaphore.md#diskcache_oxide.BoundedSemaphore), [throttle](../reference/throttle.md#diskcache_oxide.throttle), [barrier](../reference/barrier.md#diskcache_oxide.barrier) and [Averager](../reference/Averager.md#diskcache_oxide.Averager) refuse a [NullCache](../reference/NullCache.md#diskcache_oxide.NullCache) and a `durable=True` cache, since with caching off every caller would hold the lock at once, and a durable cache could drop the write that releases it. Give them a cache of their own, opened without [durable](../reference/Cache.durable.md#diskcache_oxide.Cache.durable) (see [Coordination](coordination.md)). - `RuntimeError: Lock.acquire() would wait inside this thread's transaction`: a recipe that would have to wait while you hold a [transact()](../reference/Cache.transact.md#diskcache_oxide.Cache.transact) block on its own cache. Waiting there holds the write lock, so no other process could ever release what you're waiting for. Take the lock before the block. - `AssertionError` from [release()](../reference/Lock.md#diskcache_oxide.Lock.release) on an [RLock](../reference/RLock.md#diskcache_oxide.RLock) you don't hold, or a [BoundedSemaphore](../reference/BoundedSemaphore.md#diskcache_oxide.BoundedSemaphore) released more often than it was acquired. It's raised explicitly, so `python -O` doesn't strip it. - `OverflowError` from [push()](../reference/Cache.push.md#diskcache_oxide.Cache.push) after 500 trillion pushes to one end of a queue: it refuses rather than overwrite a key. A bad `side` raises `ValueError`. - [UnsafeValueError](../reference/UnsafeValueError.md#diskcache_oxide.UnsafeValueError), [ForeignValueError](../reference/ForeignValueError.md#diskcache_oxide.ForeignValueError) or [CorruptValueError](../reference/CorruptValueError.md#diskcache_oxide.CorruptValueError) from [pull()](../reference/Cache.pull.md#diskcache_oxide.Cache.pull). An item this process can't read stays at the front of the queue for one that can, and one that no build could read is removed; see [Work queues](../recipes/work-queues.md). # `MemoryError` It always raises, under `durable=True` too, including when SQLite runs out of memory. A [Caches](../reference/Caches.md#diskcache_oxide.Caches) lookup raises it as well, rather than handing out a [NullCache](../reference/NullCache.md#diskcache_oxide.NullCache). # Log lines, when the library was told not to raise These settings turn failures into log lines on the `diskcache_oxide` logger instead of exceptions. Make sure that logger reaches your logging setup, since the line is then the only signal. The library adds no handler of its own, so its records go wherever the root logger's do. One trap: `logging.config.dictConfig` defaults to `disable_existing_loggers: True`, and the `diskcache_oxide` logger exists from the moment the package is imported, so a config applied afterwards that doesn't name it silences it, and every durable outage report with it. Name it, and keep existing loggers: ``` python import logging.config logging.config.dictConfig({ 'version': 1, 'disable_existing_loggers': False, # the default True would silence diskcache_oxide 'formatters': {'plain': {'format': '%(asctime)s %(levelname)s %(name)s: %(message)s'}}, 'handlers': {'console': {'class': 'logging.StreamHandler', 'formatter': 'plain'}}, 'loggers': {'diskcache_oxide': {'level': 'INFO', 'handlers': ['console'], 'propagate': False}}, }) ``` With gunicorn, put the same dictionary in `logconfig_dict` in `gunicorn.conf.py` so the workers' logging and the library's go to one place. Records carry extra fields (the format-redirect warning has [directory](../reference/Cache.directory.md#diskcache_oxide.Cache.directory), `using`, `found` and `found_in`; a [FanoutCache](../reference/FanoutCache.md#diskcache_oxide.FanoutCache)'s shard-count warning `stored_shards` and `requested_shards`, and a registry's shard-count error [cache](../reference/DjangoCache.cache.md#diskcache_oxide.DjangoCache.cache), [directory](../reference/Cache.directory.md#diskcache_oxide.Cache.directory), `stored_shards` and `registered_shards`), which a structured formatter or Sentry picks up as attributes. - **`on_decode_error='miss'`** logs a warning for each stored version it couldn't read, once per cache handle, and deletes the row if no build could read it. - **`durable=True`** counts every swallowed failure in one of three groups and logs each group's first failure at once, then at most once a minute per cache handle, with counts by operation since its last line (`get: 1204, set: 37`). Busy (a [Timeout](../reference/Timeout.md#diskcache_oxide.Timeout)) logs at `WARNING`, failing (a full disk, an I/O error, a damaged database) at `ERROR`, and lost invalidations (any failed [delete](../reference/Cache.delete.md#diskcache_oxide.Cache.delete), whose entry can now be served stale) at `ERROR`. An outage that ends within the minute shows only its first failure until the next line, so each line says more may follow. [close()](../reference/Cache.close.md#diskcache_oxide.Cache.close) logs what's left. - **[Caches](../reference/Caches.md#diskcache_oxide.Caches)** logs `could not open cache 'pages' at /var/cache/my-app/pages; using a NullCache, retrying in 10 s` at `ERROR` with the traceback when a cache can't open. When the open merely timed out, it logs `cache 'pages' at /var/cache/my-app/pages is busy; using a NullCache, retrying in 1 s: ...` at `WARNING`, without a traceback, and retries after at most 1 s. Both are logged only when no `on_open_error=` is set; pass one to send them to Sentry instead. - **`FanoutCache(directory, shards=n)`** logs `FanoutCache at /var/cache/my-app/rate_limits has 8 shards but shards=16 was asked for; using the 8 it has. ...` at `WARNING`, once per process per folder and pair of counts, when the folder has another count than [shards](../reference/FanoutCache.shards.md#diskcache_oxide.FanoutCache.shards). Its record carries [directory](../reference/Cache.directory.md#diskcache_oxide.Cache.directory), `stored_shards` and `requested_shards`. Pass `raise_on_mismatch=True` to raise [LayoutMismatchError](../reference/LayoutMismatchError.md#diskcache_oxide.LayoutMismatchError) instead. - **[Caches](../reference/Caches.md#diskcache_oxide.Caches)** also logs `cache 'rate_limits' at /var/cache/my-app/rate_limits has 8 shards but is registered with shards=16; using the 8 on disk. To apply shards=16, delete /var/cache/my-app/rate_limits while no process has it open` at `WARNING` each time it opens a sharded cache whose folder has another count than the registration, and once per process `a FanoutCache is registered with a shard count its folder does not have` at `ERROR`, a constant message with the details in the record's [cache](../reference/DjangoCache.cache.md#diskcache_oxide.DjangoCache.cache), [directory](../reference/Cache.directory.md#diskcache_oxide.Cache.directory), `stored_shards` and `registered_shards` attributes, so an error tracker groups every worker's report into one issue. The cache works throughout; this one doesn't go through `on_open_error`, since the open succeeded. - **Background maintenance** never raises into your code. When a turn fails (an error, or work found without getting the write lock for 3 intervals running), the next single-key call on that cache logs `background maintenance failed on the cache at /var/cache/my-app/pages: ...` at `WARNING`, with [directory](../reference/Cache.directory.md#diskcache_oxide.Cache.directory) in the record. It's logged once per streak of failures, so a cache nobody calls never logs it, and a later successful turn ends the streak. `cache.maintenance_stats()` has the rest: `failures` counts every failure, not just the logged ones, and `last_error` holds the most recent failure's message. # If it looks like a bug in diskcache-oxide If you've read this far and the traceback still doesn't fit, it may be one. Open an [issue](https://github.com/mikeckennedy/diskcache-oxide/issues) with `diskcache_oxide.__version__`, [diskcache_oxide.sqlite_version()](../reference/sqlite_version.md#diskcache_oxide.sqlite_version), the interpreter (`python -VV` says whether it's free-threaded), the platform and filesystem, how many processes and threads share the directory, and the full traceback. Every deliberate difference from diskcache is listed in [Divergences](divergences.md), so check there first if the surprise is a behavior rather than an error.