Runtime¶
Runtime archive, deduplication, caching, and scheduling.
@domain runtime @see [[knowledge/architecture/runtime]]
SQLite-backed run archive for coalition evaluation history.
@domain runtime @see [[knowledge/architecture/runtime]] @tested-by [[tests/runtime/test_archive.py]]
- mllm_shap.runtime.archive.BASE_GENERATION_FILE = 'base_generation.txt'¶
Filename for the grand-coalition reference generation at the archive root.
- mllm_shap.runtime.archive.ARCHIVE_SCHEMA_VERSION: Final[int] = 4¶
SQLite
user_versionwritten by this release and required on load.
- mllm_shap.runtime.archive.MANIFEST_SCHEMA_VERSION: Final[int] = 4¶
Manifest
schema_versionwritten by this release and required on load.
- class mllm_shap.runtime.archive.ManifestPayloadSource(*args, **kwargs)[source]¶
Bases:
ProtocolManifest that serializes itself to the JSON stored as
manifest.json.
- mllm_shap.runtime.archive.check_manifest_schema_version(payload: Mapping[str, object]) None[source]¶
Refuse manifests written with a different schema version.
- Raises:
ManifestVersionError – If
schema_versionis missing or differs fromMANIFEST_SCHEMA_VERSION.
- mllm_shap.runtime.archive.read_manifest_payload(path: Path) Mapping[str, object][source]¶
Read
manifest.jsonand return its top-level JSON object.- Raises:
ArchiveCorruptError – If the file is not UTF-8 JSON or its root is not an object.
- class mllm_shap.runtime.archive.CoalitionRecord(record_id: int, snapshot_id: str, coalition_key: str, mask: PackedMask, absence_policy: str, model_id: str, generation_text: str, elapsed_ms: float, cache_hit: bool, logprobs: tuple[float, ...] | None = None)[source]¶
Bases:
objectOne persisted coalition evaluation row.
- mask: PackedMask¶
Packed coalition mask bytes and original bit length.
- class mllm_shap.runtime.archive.CoalitionRecordDraft(snapshot_id: str, coalition_key: str, mask: PackedMask, absence_policy: str, model_id: str, generation_text: str, elapsed_ms: float, cache_hit: bool, logprobs: tuple[float, ...] | None = None)[source]¶
Bases:
objectInput payload used when appending a coalition record.
- mask: PackedMask¶
Packed coalition mask bytes and original bit length.
- class mllm_shap.runtime.archive.RunArchive(root: Path, flush_every: int = 50, read_only: bool = False)[source]¶
Bases:
objectPersist coalition records, generation text included, to one SQLite file.
The database uses WAL journaling with
synchronous=NORMAL; rows are committed everyflush_everyappends and onclose().- classmethod open(root: Path, manifest: ManifestPayloadSource, flush_every: int = 50, on_exists: Literal['error', 'overwrite'] = 'error') Self[source]¶
Create a run archive directory and open its SQLite database.
An existing archive whose run did not finish (no completion marker) is replaced whatever
on_existssays, so a crashed run can be re-run.- Raises:
ArchiveExistsError – If
rootalready holds the archive of a finished run andon_existsis"error".
- classmethod load(root: Path) Self[source]¶
Open an existing run archive read-only, without writing any file.
- Raises:
ArchiveNotFoundError – If the manifest or the SQLite database is missing (a
FileNotFoundError).ArchiveCorruptError – If the manifest is not a JSON object or the database cannot be read.
ManifestVersionError – If the manifest or SQLite schema version is not the one written by this release.
- write_manifest(manifest: ManifestPayloadSource) None[source]¶
Write
manifesttomanifest.json, replacing the previous one.
- write_base_generation(text: str) None[source]¶
Persist the grand-coalition reference generation before coalition rows.
- append(draft: CoalitionRecordDraft) int[source]¶
Append one coalition record and return its archive identifier.
- property is_complete: bool¶
Return whether
mark_complete()ran for this archive.
- history_lazy() Iterator[CoalitionRecord][source]¶
Iterate coalition records one row at a time without bulk preloading.
Coalition deduplication keys and registry.
@domain runtime @see [[knowledge/architecture/runtime]] @tested-by [[tests/runtime/test_dedup.py]]
- mllm_shap.runtime.dedup.dedup_enabled(config: DedupConfig, generation: GenerationConfig) bool[source]¶
Return whether coalition deduplication should be active.
- mllm_shap.runtime.dedup.build_coalition_key(snapshot_id: str, player_ids: tuple[str, ...], mask_present: tuple[bool, ...], absence_policy: str, model_id: str, generation: GenerationConfig) str[source]¶
Build a stable SHA256 coalition key for deduplication.
- class mllm_shap.runtime.dedup.CoalitionDedupRegistry[source]¶
Bases:
objectTrack coalition keys that already required backend execution.
Hot LRU cache for coalition generation results.
@domain runtime @see [[knowledge/architecture/runtime]] @tested-by [[tests/runtime/test_store.py]]
- class mllm_shap.runtime.store.HotResultStore(maxsize: int | None = 128, _values: OrderedDict[str, tuple[str, tuple[float, ...] | None]]=<factory>)[source]¶
Bases:
objectIn-memory LRU store for recently generated coalition outputs.
Async coalition inference scheduling with deduplication.
@domain runtime @see [[knowledge/architecture/runtime]] @tested-by [[tests/runtime/test_scheduler.py]]
- mllm_shap.runtime.scheduler.GenerateFn¶
Async callable that returns the generated text, or a record carrying it and its token logprobs, for one snapshot.
alias of
Callable[[ConversationSnapshot],Awaitable[str|GenerationRecord]]
- class mllm_shap.runtime.scheduler.SchedulerMetrics(requested: int, executed: int, deduplicated: int, cache_hits: int, kv_cache_hits: int = 0, kv_cache_reused_tokens: int = 0)[source]¶
Bases:
objectCounters collected while executing coalition jobs.
- class mllm_shap.runtime.scheduler.CoalitionJob(coalition_key: str, snapshot_id: str, snapshot: ConversationSnapshot, absence_policy: str, mask_words: bytes, mask_n_bits: int, model_id: str, prefix_hash: str = '')[source]¶
Bases:
objectOne coalition evaluation request routed through the scheduler.
- snapshot: ConversationSnapshot¶
Conversation snapshot passed to the backend for generation.
- class mllm_shap.runtime.scheduler.InferenceScheduler(max_inflight: int, generation: GenerationConfig, store: HotResultStore, dedup: CoalitionDedupRegistry | None = None, archive: RunArchive | None = None, pending_limit: int | None = None, progress: CoalitionProgress | None = None)[source]¶
Bases:
objectExecute coalition jobs with bounded concurrency and optional deduplication.
- async run(jobs: Sequence[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str | GenerationRecord]]) SchedulerMetrics[source]¶
Execute coalition jobs and return scheduler counters.
- async run_iter(jobs: Iterable[CoalitionJob], generate: Callable[[ConversationSnapshot], Awaitable[str | GenerationRecord]], total: int | None = None) SchedulerMetrics[source]¶
Execute jobs from an iterable without creating all coroutines upfront.
Jobs run in one
asyncio.TaskGroup, with at mostpending_limittasks alive at a time. The first job failure cancels every other task and is re-raised as is (not wrapped in an exception group), so callers never observe partial success. Withtotalthe progress sink is told the cumulative planned count of all runs so far.
Optional synchronous progress callbacks for coalition execution.
@domain runtime @see [[knowledge/architecture/runtime]] @tested-by [[tests/runtime/test_progress.py]]
- class mllm_shap.runtime.progress.CoalitionProgress(*args, **kwargs)[source]¶
Bases:
ProtocolSync hooks notified as coalition jobs are planned and finished.
- class mllm_shap.runtime.progress.NullCoalitionProgress[source]¶
Bases:
objectNo-op progress sink used when callers omit a progress callback.
Performance summaries for explain pipeline runs.
@domain runtime @see [[knowledge/architecture/runtime]]
- class mllm_shap.runtime.metrics.PerfSummary(total_ms: float, generation_ms: float, scoring_ms: float, aggregation_ms: float)[source]¶
Bases:
objectWall-clock breakdown for one explain or reanalyze run.
Optional observability hooks for explain pipeline stages.
@domain runtime @see [[knowledge/architecture/runtime]] @tested-by [[tests/runtime/test_telemetry.py]]
- class mllm_shap.runtime.telemetry.SpanRecord(name: str, duration_ms: float)[source]¶
Bases:
objectOne completed pipeline stage span.
- class mllm_shap.runtime.telemetry.ObservabilitySink(*args, **kwargs)[source]¶
Bases:
ProtocolProtocol for recording explain pipeline stage spans.
- class mllm_shap.runtime.telemetry.NullObservabilitySink[source]¶
Bases:
objectNo-op observability sink used when telemetry is disabled.
- class mllm_shap.runtime.telemetry.InMemoryObservabilitySink(spans: list[SpanRecord] = <factory>)[source]¶
Bases:
objectCollect span records in memory for tests and diagnostics.
- spans: list[SpanRecord]¶
Prefix-cache storage for shared prompt token prefixes.
@domain runtime @see [[knowledge/architecture/runtime]] @tested-by [[tests/runtime/test_kv_cache.py]]
- mllm_shap.runtime.kv_cache.build_snapshot_prefix_hash(snapshot: ConversationSnapshot, player_set: PlayerSet, mask: CoalitionMask) str[source]¶
Hash the coalition prefix: the presence of every player except the last.
Coalitions of
snapshotthat differ only in the last player render the same text up to that player’s span, so they share a prompt prefix and run next to each other for KV-cache reuse. Nothing is re-tokenised.
- class mllm_shap.runtime.kv_cache.CroppableCache(*args, **kwargs)[source]¶
Bases:
ProtocolKV state that can be cut back to its first tokens (HF
DynamicCache).
- class mllm_shap.runtime.kv_cache.PrefixCacheManager(max_entries: int = 8)[source]¶
Bases:
objectKeep at most
max_entriesprefix KV states keyed by token-id tuple.- hits¶
Number of lookups that found a cached prefix.
- misses¶
Number of lookups that found nothing.
- longest_prefix(token_ids: Sequence[int]) tuple[Any | None, int][source]¶
Return the cached state sharing the longest token prefix with
token_ids.A stored key matches when it is a proper prefix of
token_ids, or, forCroppableCachestates, when it shares at least one leading token (the caller crops the state to the returned length). At least one token is always left to process. Walks every stored entry once.