Debug cache manager
IMPORTANT: CURRENTLY ONLY AVAILABLE IN THE BOOKKEEPING BRANCH
Overview
common.debug_cache_manager.DebugCacheManager retains recent diagnostic
messages in memory. During normal processing, messages can be written at
Prefect's DEBUG log level. If processing fails, the cached messages can be
replayed at INFO level so that they remain visible even when DEBUG logging is
disabled or filtered.
The manager can be used as a context manager. When an exception leaves the managed block, it automatically:
- writes the cached messages at INFO level,
- empties the cache,
- allows the original exception to continue propagating.
A normal context-manager exit does not flush the cache.
Basic usage
Create a named cache with a bounded size and use log_on_debug() for diagnostic
messages:
from common.debug_cache_manager import DebugCacheManager
with DebugCacheManager(
cache_name="article-import",
cache_size=200,
) as debug_cache:
debug_cache.log_on_debug("Starting article import")
debug_cache.log_on_debug("Reading source metadata")
process_articles()
The cache name identifies the group of messages when it is flushed. It should therefore describe the component or operation that owns the cache.
If process_articles() raises an exception, the two cached messages are logged
at INFO level before that exception continues propagating. If the block exits
normally, they are not replayed.
Cache-size behavior
cache_size controls how many messages are retained:
| Value | Behavior |
|---|---|
| Positive integer | Retain at most this many messages, discarding the oldest first. |
0 |
Retain an unlimited number of messages. |
None |
Normalize to 0 and retain an unlimited number of messages. |
| Negative integer | Raise ValueError. |
| Boolean or another type | Raise TypeError. |
The default is 20. For a bounded cache, messages are kept in insertion order.
When the configured limit is exceeded, the oldest message is removed so that a
failure report contains the most recent diagnostic context.
Memory recommendation
Using an unlimited cache size is not recommended. Every cached message and its timestamp remain in memory until entries are explicitly removed or the cache is flushed. A long-running flow or a high-volume loop can therefore consume an unbounded amount of memory.
Prefer a bounded cache of no more than a few hundred messages. This recommendation also applies when application code manages the cache manually. The built-in bound is safer than relying only on periodic cleanup because the bound is enforced whenever a message is added.
For example:
debug_cache = DebugCacheManager(
cache_name="metadata-sync",
cache_size=300,
)
If an unlimited cache is necessary, trim it frequently and retain only a few hundred entries:
debug_cache = DebugCacheManager(
cache_name="metadata-sync",
cache_size=0,
)
for record in records:
debug_cache.log_on_debug(f"Processing {record.identifier}")
debug_cache.drop_cache_entries(n_keep=300)
DEBUG output and caching
By default, log_on_debug() both sends the message to Prefect's DEBUG logger
and adds it to the cache:
debug_cache = DebugCacheManager(
cache_name="download",
cache_size=100,
)
debug_cache.log_on_debug("Requesting package")
Set suppress_debug_logs=True to skip the immediate DEBUG output. The messages
are still cached and will be available for a later INFO-level flush:
debug_cache = DebugCacheManager(
cache_name="download",
cache_size=100,
suppress_debug_logs=True,
)
Each cache entry contains the local timezone-aware time at which it was added and the supplied message object.
Flushing explicitly
Call flush_debug_log_cache_on_info() when cached context should be made
visible without waiting for a context-manager exception:
debug_cache.flush_debug_log_cache_on_info()
A successful flush logs:
- a start message containing the cache name and number of entries,
- every entry at INFO level with its index and original timestamp,
- an end message containing the cache name.
The method reports an empty cache at INFO level when there are no entries. In either case, the cache is empty after the method completes successfully.
Managing entries manually
Clear all entries
clear_cache() removes all cached messages without logging them:
debug_cache.clear_cache()
This is useful after a successful operation when the diagnostic context is no longer needed.
Retain only the newest entries
drop_cache_entries(n_keep=20) discards older entries and keeps the newest
n_keep messages:
debug_cache.drop_cache_entries(n_keep=200)
If the cache already contains n_keep messages or fewer, it remains unchanged.
Passing 0 clears it. A negative value raises ValueError; a Boolean or
non-integer value raises TypeError.
Context-manager behavior
The context manager is intended to preserve diagnostic context for abnormal exits:
with DebugCacheManager("package-validation", cache_size=100) as debug_cache:
debug_cache.log_on_debug("Validating manifest")
validate_manifest()
__enter__() returns the same manager instance. If an exception occurs,
__exit__() flushes and clears the cache, then returns False. Returning
False means that the manager does not suppress the exception.
If the block exits normally, __exit__() does not flush or clear the cache. The
caller can explicitly call clear_cache() or
flush_debug_log_cache_on_info() when either behavior is required before the
manager is reused.
API reference
DebugCacheManager(cache_name, cache_size=20, suppress_debug_logs=False)
Creates a cache manager.
Parameters
cache_name: str
Required non-empty name used to identify the cache in flush log messages. Whitespace-only names are rejected.
cache_size: int | None
Maximum number of retained messages. Positive values create a bounded cache;
0 and None create an unlimited cache. The default is 20.
suppress_debug_logs: bool
When True, messages are cached without being emitted immediately at DEBUG
level. The default is False.
log_on_debug(log_text)
Emits log_text at DEBUG level unless DEBUG output is suppressed, timestamps
the message, and adds it to the cache. If the cache is bounded, its oldest entry
is discarded when the limit is exceeded.
clear_cache()
Removes all cached entries without logging them.
drop_cache_entries(n_keep=20)
Keeps the newest n_keep entries and discards older entries. Passing 0 clears
the cache.
flush_debug_log_cache_on_info()
Writes the cache contents at INFO level, identifies the output with
cache_name, and empties the cache after a successful flush.
Current bookkeeping integration
BookkeepingHandler creates the manager with the cache name bookkeeping and
passes its configured debug_cache_size and suppress_debug_logs values:
self.debug_cache_manager = DebugCacheManager(
cache_name="bookkeeping",
cache_size=debug_cache_size,
suppress_debug_logs=suppress_debug_logs,
)
Bookkeeping operations add diagnostic context through
self.debug_cache_manager.log_on_debug(...). Other components should create
their own clearly named manager rather than reuse the bookkeeping cache name.
Operational considerations
- The cache exists only in process memory; it is not persisted across process termination.
- The implementation uses Prefect's run logger, so logging methods are intended
to be called from a context where
prefect.get_run_logger()is available. - Cached message objects remain referenced until they are discarded or flushed. Large message objects can consume significant memory even when the number of entries appears modest.
- Flushing promotes diagnostic content from DEBUG to INFO. Do not cache secrets, credentials, tokens, or sensitive payloads.
- Prefer a bounded size of a few hundred messages or fewer, selected according to the amount of diagnostic context required by the operation.