mjdi docsv0.10.0latest
Cache statistics (P1-16)
Container[registry, traced=False, collect_stats=True] (and the scopes
Source: mjdi/docs/cache-statistics.md
Container[registry, traced=False, collect_stats=True] (and the scopes
it creates) maintains cache-activity counters. Statistics are
disabled by default; counter increments compile away in the default
specialization, and the counters never affect cache behavior — they
observe it.
var app = Container[type_of(reg), False, True]()
app.set_value[Cfg](Cfg("db"))
_ = app.resolve[UserService]() # constructs + caches
_ = app.resolve[UserService]() # served from the cache
print(app.stats_report())
# hits=1 misses=1 constructions=3 insertions=1 releases=0 factory_runs=0 scope_creations=0
var snapshot = app.stats_snapshot() # a copyable CacheStats value
print(snapshot.hits, snapshot.constructions)
app.reset_stats() # clears the counters (trace log unaffected)
The counters
| Counter | Counts |
|---|---|
hits | cache lookups served from a filled singleton/scoped slot (copies of canonical instances handed out) |
misses | cache lookups that found the slot empty (each leads to a construction + insertion) |
constructions | service constructions through the Injectable contract (plus linear constructions) |
insertions | canonical instances stored into cache slots |
releases | canonical instances released by close() / close_scope() |
factory_runs | factory provider executions |
scope_creations | scopes created by this container (container-owned counter) |
Scope of the counters
- Container-level and scope-level: scopes carry their own
counters for resolutions inside them (
scope.stats_report()). - Per-provider statistics are not represented: one counter set per
owner covers all providers. Per-provider counters would require
per-descriptor runtime state in every registry chain node (comptime
keying of mutable arrays is not expressible on the supported
compiler); the per-service facts are observable through
tracing (
construct:/cache-hit:events carry the service name) — a documented limitation, not a hidden gap. reset_stats()clears exactly the counters; the trace log is unaffected (andTraceLog.resetclears the log alone).
Thread-safety
Containers and scopes are single-threaded by contract (see Concurrency), so the counters need no synchronization.
Testing with statistics
Statistics are the precise way to pin lifetime behavior without ad-hoc
counters — assert_stats_line(container, "insertions=0") is the
one-line proof that a transient override never caches. See
Testing and examples/testing_patterns.
Related
- Lifecycle tracing — the event-log sibling.
- Performance benchmarks — the measured overhead of every specialization.