astrocyte keeps one SQLite ledger at <data home>/cortexkit/astrocyte/store.db.
The schema is the MIGRATIONS chain in crates/astrocyte-core/src/store.rs,
currently version 81. A schema change appends a migration; an applied
migration is never edited. A binary refuses to serve a store whose schema is
ahead of its own chain (test: store_ahead_of_binary_refuses_startup_by_name).
Connection initialization checks JSON, triggers and partial indexes, verifies foreign-key enforcement, and sets a 5000 ms busy timeout. The report connection copies that timeout without running the table-creating probes.
| Table | Holds | Writes |
|---|---|---|
usage_event |
Each row records one usage event per producer reference and lineage, its admission selection (auth_selection), the paying credential (resolved_credential) when reported, and its pricing projection. |
insert; three projection columns, see below |
measurement |
Each row records one immutable event quantity for a role and unit. | insert only |
broca_segment_evidence |
Each row preserves the fact id, run id and ingest time of a BROCA segment whose usage is billed through attempts instead. It has no ledger call. | insert only, once per fact |
broca_segment_measurement |
Each row preserves a marked segment's quantity in the same roles and units as ledger measurements. | insert only, once per segment, role and unit |
broca_attempt_detail |
Each row keeps a BROCA call's attempt identifiers, original share index, outcome and HTTP status, response counts, tier, speed, pricing mode and segment link. Usage lives in the call's ledger measurements. | insert only, once per call |
broca_empty_attempt |
Each row reserves the fact ID of an attempt with no eligible shares; there is no ledger event for it. | insert only, once per attempt |
broca_empty_attempt_conflict |
Each row preserves a distinct redelivery that would add a share to a previously all-skipped attempt. | insert only, once per contradiction |
broca_scope_stamp |
Each row preserves the daemon-stamped agent, agent run or flow and the BROCA export fact kind for an existing ledger call. Unstamped calls have no row. The stamp is attribution evidence, not a ledger or pricing field. | insert only, once per call; dirties the attribution hour |
broca_scope_backfill |
The singleton tracks how far a one-time read of retained BROCA exports has filled stamps for accepted ledger deliveries, and whether it caught up to the reader's committed cursor. Rejected or conflicting deliveries do not supply stamps. An uncorrected call requires an exact basis match. When a call has a basis_correction charge row, the delivery must match the basis recorded before the first correction, not the corrected basis. If no earlier basis was recorded, the backfill compares the delivery without its basis. |
advances with each backfill page; stops on completion |
media_caller |
Each row holds caller evidence for a Colliculus ledger call: the app's stated agent_id and the daemon-relayed device as JSON. Either may be absent, but not both. Without a matching publisher fact, the stated agent supplies only alfonso. Device is not a grouping dimension, and neither value changes pricing or permissions. |
insert only, once per call; dirties the attribution hour |
broca_segment_check_state |
The singleton stores the last segment checked against its attempt shares, plus a separate cursor and ceiling for the one-time upgrade recheck. | advances with checked batches |
broca_segment_mismatch |
Each row preserves a differing segment and attempt quantity (including whether each side reported it), the role and unit, and the check time. When the attempt sum exceeds the integer range, over_range is set and the sum is NULL. |
insert only, once per segment, role and unit |
broca_segment_recheck |
Queues already-checked segments whose attempt shares have changed. | derived queue |
broca_segment_current_mismatch |
Lists the segments still differing at their most recent comparison. The original differences remain in broca_segment_mismatch. |
derived |
step_detail |
Each row records the finish reason or context window a harness reader saw for one event, for cache diagnostics. | insert only, once per event |
step_detail_late |
Each row queues detail for a previously recorded event using an increasing ID that is not reused when the queue empties. | insert; delete completed entries in the transaction that appends to the feed and advances step_feed_state.late_detail_high_water |
step_message |
Each row records the host's own message id for a newly recorded event, for joining live feed rows within their harness and session. Old events are not backfilled. | insert only, once per event |
cache_step_sequence |
Each row maps a ledger event to a durable cache cursor. | insert |
cache_read_session |
Each row names a producer's session with a dated cache-read step and records the cursor of its first positive read. | derived; a measurement trigger inserts it and lowers the cursor |
cache_read_step |
Each row locates one dated step of a session that carries a plain cache-read measurement, zero reads included. | derived; a measurement trigger inserts it |
step_feed |
Each row is one emission of a served cache step for usage.steps.read; the newest row for a harness and step wins. |
insert; rows older than 24 hours are deleted |
step_feed_state |
The row records the cache cursor the feed has caught up to and the newest feed cursor retention deleted. | one row |
step_evidence |
Each row retains a step's runner identity, provider and model, first feed cursor, indexed live ordering and cache witnesses, and the optional runner-event facts used to explain prompt-cache rewrites (facts that only the runner's live event carries) under (harness, step_ref). |
upsert; bounded 30-day retention |
step_digest |
Each row interns one distinct tool or system digest used by retained evidence. | insert; delete after its last reference expires or changes |
step_cause |
Each row records a changed explanation for one step identity; the newest key wins, including a null correction to no cause. | append only; kept forever |
chargeability_transition |
Each row records the one terminal settlement of an event's chargeability. | insert only |
quarantine_evidence |
Each row preserves a referring event's quantities that contradict its target. | insert |
rejected_delivery |
Each row preserves a distinct redelivery payload that differs from the stored event. | insert |
redelivery_log |
Each row records an identical redelivery pushed by a peer. | insert |
adjustment |
Each row records a signed write-off, restatement, repricing, refund or goodwill adjustment. | insert |
priced_charge |
Each row records a charge-chain entry for a measurement and the origin of the pricing act. | insert only |
pricing_pending |
Each row identifies an event with a measurement that has no current charge head. | queue |
pricing_selection_state |
The row tracks subscription-plan generations, the last generation whose history has been repriced, and the last completed pricing queue check. | one row |
account_subscription |
Each row declares an effective-dated subscription plan for a provider account. | insert; close once |
credential_subscription |
Each row declares an effective-dated subscription plan for a vault credential that has no account id, recorded only by vault-plan reconciliation. | insert; close once |
vault_plan_history |
Each row preserves a vault record's changed plan key, raw provider and tier, optional account, source, effective time and observation time. | insert only, including unknown-plan changes |
vault_plan_seed |
The singleton marks completion of the committed config's one-time plan-history import. | insert once |
statement |
Each row records a vendor statement identity. | insert only |
statement_line |
Each row preserves immutable statement line content and its current match projection. | insert; match projection |
match_attempt |
Each row records a statement-line match attempt and the amounts captured for that attempt. | insert only |
statement_import |
Each row records CSV import provenance and its content digest for idempotency. | insert only |
desired_config |
The row records the committed desired-configuration generation. | one row |
source_runtime |
Each row records a producer's cursor, lineage, last successful drain and pending disclosure. OpenCode stores its file identity in file_identity. |
upsert |
media_feed_cursor |
The row records colliculus's committed unsigned feed sequence, last seen feed id, skipped-local count and pending_ack flag for an identified feed. |
upsert with each page or feed reset; clear the flag after acknowledgment |
thalamus_payer_cursor |
The row records the payer store incarnation and committed sequence. | upsert with each mirror page |
thalamus_payer_session |
Each row preserves the declared owner of a THALAMUS session. | insert once per harness and session |
thalamus_payer_record |
Each row preserves one payer attempt, including its original usage JSON, after THALAMUS deletes its copy. | insert only |
thalamus_payer_first_seen |
Each row preserves when a transcript call first waited for its payer when its reported time was absent or in the future. | insert once per event |
thalamus_payer_coverage |
Each row identifies one payer coverage exception, so replay cannot count it twice. | insert once per kind and identity |
set_aside_record |
Each row records an unreadable producer record by source and locator, including its reason and observation times. | upsert |
declared_store_cursor |
Each row records the durable read position of one store that another module declared, per source and on-disk layout. OpenCode stores its file identity in file_identity. |
upsert; deleted when the store is no longer declared |
read_watermark |
Each row records a reader source's read watermark, the time before which everything in its declared stores is recorded. | upsert that only moves forward |
capacity_runtime |
The row records whether the capacity axis is disabled, configured but unavailable, or active. | upsert |
capacity_window |
Each row records a provider account's latest QTA quota window. | upsert |
capacity_observation |
Each row records the latest capacity observation for an identity. | upsert |
capacity_provider_reading |
Each row records the latest capacity reading for a provider without account attribution. | upsert |
window_sample |
Each row preserves a capacity-window observation and its breakdown for a provider, account and pool. | insert; delete only under the quota retention rule |
multiplier_observation |
Each row records a daily subscription multiplier observation or an operator recompute that supersedes an earlier observation. | insert only |
multiplier_provider_day |
Records that a quota provider's complete set of multiplier observations for a UTC day was written, even if the set was empty. | insert only |
credential_window_sample |
Source-instant quota history for readings without an account, identified by provider, vault credential and pool. | insert; delete only under the quota retention rule |
quota_reset_period |
Rebuildable quota history index: for each provider, account or credential, and pool, stores each reset as a UTC epoch millisecond and the earliest reading that reported it. | insert or lower earliest instant |
quota_retention_cursor |
Each row records the exclusive end of the latest UTC hour thinned for one quota stream. | upsert with a completed stream-hour |
attribution_fact |
Each row preserves one publisher's verbatim fact and indexed subject, parent, workload, task and project evidence. | insert only; corrections append with supersedes |
placement_fact |
Each row preserves entorhinal's dated project-to-workspace placement and verbatim fact. | insert only; corrections append with supersedes |
attribution_cursor |
Each row checkpoints one publisher's read name, opaque cursor, through position and last committed read time. | upsert with a changed committed page |
attribution_session_ref |
Each row files one session fact under the session_ref computed from its runner, harness and session, so resolution can find the fact by that name through an index. Migration 59 fills it in Rust for facts stored earlier, in the migration's own transaction. |
insert only, beside its fact |
attribution_parent_session_ref |
Each row indexes the computed session_ref of a fact's session parent, so linking a parent alias invalidates cached child attribution. Migration 66 backfills the references in Rust and marks child attribution hours affected by existing computed aliases for rebuild, in the same transaction that creates the table. |
insert only, beside its fact |
session_alias |
Each row preserves a runner/harness-qualified pair of a ledger's recorded session and another published name for it. | insert only |
summary_value |
Each row assigns an exact stored string an integer identifier, with identifier zero reserved for null. | Builders insert new values. |
summary_hour |
Each row records an hour's persistent revision, published revision, format, event count and time extrema. | Triggers advance revisions, and publication records a completed build. |
summary_dirty_hour |
Each row identifies an hour that needs a fresh reduction from base rows. | Triggers insert dirty keys, and successful publication removes them. |
summary_cell |
Each row holds dimension-keyed event and measurement counters, exact money sums and reason maps for one hour. | Rebuilds replace these rows. |
summary_quantity |
Each row holds exact quantities for a cell, role, unit and exponent, including covered population, observation counts and stated-quantity counts. | Rebuilds replace these rows. |
summary_money |
Each row holds current-head or adjustment contributions in their actual currency, together with a presence count. | Rebuilds replace these rows. |
summary_cost_frequency |
Each row counts an exact current-head value in the dated, complete, currency-known work-class sample. | Rebuilds replace these rows. |
summary_run_cell |
Each row stores step counts, token totals and presence, and current-charge cost maps for one run key, provider and model, and hour. | The existing hourly rebuild and audit replace these rows. |
summary_audit_state |
The row records the independent audit's cursor, next start time and progress statistics. | The audit updates this row. |
rate_era |
Each row caches one served rate-key segment, including absent and refused intervals, separately from ledger prices. | Refresher publication replaces changed timelines. |
rate_model |
Each row records a fetched catalog version and current alias target or a plan provider's public API-card target (its API twin); an index finds referring models. | The refresher discovers new models incrementally and re-reads them on catalog advances. |
rate_cache_state |
The singleton records fusiform's rates version (its catalog version from a fusiform too old to serve one), cache generation, call-discovery cursor and twin configuration. | The refresher updates this row. |
rate_dirty_hour |
Each row queues a summary-backed hour holding a model whose timeline or reference changed. | Rate publication inserts keys for the model and its referrers; valuation maintenance consumes them. |
valuation_state |
The singleton records synchronized rate, valuation-config and plan-record generations. | Valuation maintenance and plan-record triggers update it. |
valuation_hour |
Each row records an hour's revision, three built generations and independent valuation state. | Ledger and plan triggers invalidate hours; valuation publication completes them. |
valuation_cell |
Each row splits a summary key by plan member and subscription ledger record, retaining recorded counters, quantities and currency sums alongside the cell's list value and unvalued reasons. The list value is stored unrounded, in the valuer's numerator units (ListValue in valuation.rs), and is rounded to whole nanodollars only when a report serves it. |
Valuation rebuilds replace these rows without changing spend summaries. |
attribution_hour |
Each row tracks an independent attribution revision and completion marks for that revision and the existing summary/valuation hour revisions. | Builders publish completion marks; attribution changes can invalidate only these projections. |
attribution_cell |
Each row aggregates an hour, currency, attribution tuple, provider and model, retaining counters, exact quantities with presence counts, recorded currency sums and the exact metered subtotal before charge bases are combined. | The summary pass replaces these rows from its existing ledger read. |
attribution_valuation_cell |
Each row adds the plan member and immutable plan record to an attribution key and retains the recorded payload, exact list numerator and unvalued reasons. | The valuation pass replaces these rows from its existing ledger read. |
Migration 78 marks built valuation hours for rebuild if they contain a Colliculus call with media selectors and a cache-write or reasoning token measurement. The rebuild applies the corrected list valuation for those tokens. The migration leaves ledger facts and spend summaries unchanged.
The payer store's incarnation identifies one database history. THALAMUS changes
it when the database is replaced or restored, so a reader starts again at the
lowest sequence instead of skipping a newly reused sequence number. The mirror
keeps attempt identities across incarnations to prevent duplicate calls.
Schema 81 adds a partial index on thalamus_payer_record by harness, session
and recorded time for keep-warm rows (test: schema_v81_indexes_existing_keep_warms).
The attribution tuple is (alfonso, parent_alfonso, workload, project_id, workspace).
alfonso identifies the owning agent; parent_alfonso identifies the agent that
owns the launching subject, which can differ from the child's owner.
Calls write the all-null tuple, represented by value id zero, only when no
publisher fact, BROCA stamp or media caller record supplies attribution. Task
remains in publisher facts but is not part of this projection because it can
be unique per run. Ordinary summary and valuation keys and summary format 6
are unchanged. Migration 58 only adds tables:
it preserves every existing row, including ordinary report caches. The summary
and valuation backlog builders fill the new projections. When an hour's ordinary
summary or valuation is stale, its pass builds both projections from one ledger
read; when it is current, the pass writes only attribution cells. Attribution
grouping and filtering use these split keys, with bounded hour reductions while
stale, leaving ordinary report rows and keys unchanged. The public attribution project dimension is
project_id; legacy project remains the ledger's recorded folder.
Scheduled full refreshes page prefrontal, basal and magic-context's
attribution.read and entorhinal's placement.read, committing each page with
its opaque cursor. Routes and event wakes use the current prefrontal module
ID; facts and cursors keep the stored publisher key prefrontal-core. A terminal
null next retains the request cursor; unchanged
replays open no write transaction. Refusals and missing publishers leave cursor
and health unchanged. Invalid facts, naming violations, cross-publisher subject
claims and changed bodies for known identifiers go to set_aside_record, whose
per-source counts appear in ledger coverage. Workload names contain lowercase
letters, digits, underscores and hyphens, at most 64 bytes; task names also allow
dot-separated components, at most 128 bytes. Missing runners are never inferred
from a harness. A runner-less session subject is set aside; a runner-less parent
keeps the fact but is separately counted and cannot supply a parent Alfonso.
An attribution correction's known supersedes target must have the same
publisher and exact published subject; placements require the same publisher
and exact project_id. Otherwise the correction is set aside with reason
supersedes_other_subject. An unknown target keeps the correction pending;
the reference is checked when that target arrives. A later-disproved claim
remains as immutable evidence but no longer participates in resolution, is
counted in coverage, and dirties the hours it used to own.
The existing THALAMUS roots readers append OpenCode shared-store session/ref
pairs and Claude Code owner-session/host-UUID/ref pairs. Resolution looks up only
the subjects, alias components and projects a build or report asks about, through
their indexes, and remembers each answer for that build or report, so its cost
follows the distinct subjects in the hour, not the stored history. A call matches its
BROCA run, then session, then flow. A fact's own session and the shared runner
crate's session_ref meet the ledger session and its aliases. Reference inputs
remain exactly as published; only lookup runner labels normalise
thalamus-harness to thalamus, and host harness spellings need not agree.
Each subject's newest unsuperseded fact wins. Parent ownership comes from that
parent's own winning fact, and placement is selected at the call's occurrence
time, so a project move splits an otherwise unchanged session.
Committing facts, aliases or placements advances only attribution_hour.revision
for potentially affected ledger hours. Session, run and flow invalidation uses
the existing context/time indexes; placement uses the project's fact subjects
from its effective time, including a superseded placement's earlier window.
Ordinary summary and valuation revisions do not change. Stale attribution reads
reduce only their affected hours; cached reads seek the split tables' primary
keys. List values and subscription fee allocation reuse the ordinary arithmetic
and unfiltered subscription-pool day totals.
attribution_cell and attribution_valuation_cell are rowid tables. Each keeps
its logical composite primary key enforced by a unique index. Their larger
local records reduce JSON payload overflow compared with WITHOUT ROWID
indexes. These physical choices change neither key values nor payload bytes,
and do not change either ordinary cache table. A query-plan test checks that
replacing one summary hour uses its unique index, not a table scan.
Triggers abort the change with the trigger's name as the error. "Insert only" in the table above means both of these exist:
usage_event_no_delete,measurement_no_update,measurement_no_deletechargeability_transition_no_update,chargeability_transition_no_deletepriced_charge_no_update,priced_charge_no_deleteadjustment_no_update,adjustment_no_deletestatement_no_update,statement_no_delete,statement_line_no_deletematch_attempt_no_update,match_attempt_no_deletestatement_import_no_update,statement_import_no_deletemultiplier_observation_no_update,multiplier_observation_no_deleteaccount_subscription_no_delete,credential_subscription_no_deletestep_detail_no_update,step_detail_no_deleteattribution_fact_no_update,attribution_fact_no_deleteplacement_fact_no_update,placement_fact_no_deletesession_alias_no_update,session_alias_no_deleteattribution_session_ref_no_update,attribution_session_ref_no_deleteattribution_parent_session_ref_no_update,attribution_parent_session_ref_no_delete
Each of these tables also has a BEFORE INSERT trigger named
<table>_insert_once. The same protection applies to step_feed, whose rows
cannot be updated but can be deleted for retention.
The triggers refuse an insert that collides with an existing unique identity,
including secondary and partial unique indexes and hidden rowids. This stops
both INSERT OR REPLACE and REPLACE INTO from silently deleting the old row
and inserting new content. SQLite normally skips delete triggers for those
implicit deletions when recursive_triggers is off. The insert-once guards
work even for an external writer with that default setting; connections do not
need to enable recursive triggers.
A duplicate insert raises ABORT even with INSERT OR IGNORE or
ON CONFLICT DO NOTHING. Ledger redelivery and other idempotent writes must
look up the existing identity before inserting, as the ingest and statement
paths already do. Mutable queues, cursors, capacity observations and hourly
summary tables retain their existing conflict handling. Migration 31 adds only
triggers and does not rewrite stored rows. Tests named <table>_refuses_replace
exercise both replacement spellings and compare every stored column before
and after each refusal.
usage_event_update_guard lets exactly three columns of an event move, all
projections the ledger maintains: pricing_generation advances by one per
pricing act, charge_basis changes only together with that step (a basis
correction), and currency moves from null to one value once. Every
producer field, including runner, auth_selection, resolved_credential, flow_ref and BROCA's
charge-basis provenance, is write-once. statement_line_update_guard keeps line content
fixed while the match projection moves. account_subscription_update_guard
and credential_subscription_update_guard allow one change: closing an open
plan.
A correction to any of these tables is a new row, never an edit. Tests:
usage_event_delete_is_refused_without_effect,
measurement_delete_is_refused_without_effect,
chargeability_transition_delete_is_refused_without_effect,
priced_charge_update_and_delete_are_refused_without_effect,
statement_content_and_history_are_immutable_without_effect,
storage_update_and_delete_guards_preserve_subscription_history,
schema_v13_provenance_columns_start_null_and_are_immutable,
schema_v26_adds_a_null_flow_ref_keeps_every_row_and_guards_it,
schema_v46_adds_a_null_resolved_credential_and_guards_it.
usage_event.runner (schema 50) is nullable TEXT: broca, thalamus or
colliculus identifies the runner that ran the call; null means unmanaged.
The recording reader sets the label, including thalamus for a local harness
session declared by Thalamus. Push ingest leaves it null. The value is
write-once, including null: later declarations or redeliveries never change
it, and a different computed runner on redelivery is not a contradiction.
Migration 50 labels historical BROCA, Thalamus-harness and Colliculus producer
rows directly. Other producers receive thalamus only when their producer and
session match a harness and session in thalamus_payer_session or
thalamus_payer_record, or their producer and producer reference match a
harness and non-null step_ref in thalamus_payer_record. The reference match
also covers Claude Code calls stored under an owner session instead of the
payer's native session. Matching the harness prevents a session id shared by
different harnesses from mislabelling a call. All other historical calls remain
null. Deleting payer history cannot erase a recorded label.
usage_event.resolved_credential (schema 46) is nullable TEXT, carried
verbatim from a BROCA session fact's resolved_credential_id: the vault
credential that paid, which can differ from the admission routing name in
auth_selection. Missing values remain null, never a copy of auth_selection.
Other producers and existing rows remain null; no rows are backfilled. Like
auth_selection, a stored null accepts a later value on redelivery without
changing the row. A stored value contradicted by a different or absent value
goes to rejected_delivery.
usage_event.flow_ref (schema 26) names the BROCA flow a batch call was made
in. A BROCA batch fact sets exactly one of run_ref and flow_ref: a call
made inside a run stores the run and a null flow_ref. Every other
event, including every event recorded before schema 26, has a null
flow_ref. Schema 26 added the column without rewriting any row and recreated
usage_event_update_guard with flow_ref listed beside run_ref. A
redelivery whose flow_ref differs from the stored one is a contradiction and
goes to rejected_delivery, like any other payload field.
step_detail (schema 27) holds what a harness reader keeps beside an event
for cache diagnostics: OpenCode's finish, Pi's stopReason and Codex's
model_context_window. It is a side table because redelivery compares every
usage_event field: a reader that began storing a new event field would make
every event it recorded earlier look contradicted. A row is written in the
transaction that records its event, only when a field is present. An exact
re-read may add the row an older event lacks; it never changes a row, and
the table is never part of the redelivery comparison. Claude Code and Oh My Pi
keep their stop reason in usage_event.terminal_status. Schema 27 also adds
the index usage_event_session_time on (session, occurred_at_ms) for the
cache-diagnostics reads. Tests: step_detail_refuses_update_and_delete,
a_redelivery_adds_missing_step_detail_but_never_changes_it.
When an exact re-read adds detail for an already published call, the feed
consumes the queue entry as it appends the updated step and advances its
late-detail cursor. A failed append leaves the entry for retry. The underlying
step_detail row remains when the queue entry is deleted.
cache_step_sequence supplies a durable commit-order cursor for ledger events.
Migration 28 seeds existing events with cursor = event_key. The event insert
trigger allocates later cursors from an AUTOINCREMENT sequence. Migration 33
removes abandoned BROCA diagnostic storage and rebuilds the cursor table with
only event keys. It preserves every cursor and the sequence high water, even
when that high water exceeds every surviving cursor. The migration refuses
stores containing BROCA diagnostic cursor rows rather than discarding them.
BROCA steps will arrive from its step log. The cursor mapping is separate from
spend and survives process restarts.
cache_read_session and cache_read_step (migration 44) are a derived
projection of cache-read facts that usage_event, measurement and
cache_step_sequence already hold. After every commit that touches a
session, and for usage.cache.steps and usage.cache.sessions, cache
diagnostics need two facts about the session: the last step before a point
that reported a cache read (the verdict baseline), and whether a dated step
ever read a positive number of cached tokens, or did so at or below a cursor.
Read from the ledger, both walked the session's whole history when it had no
such step. cache_read_step holds one row per dated step with a
cache_read measurement of exponent 0, zero reads included, keyed by session,
time and event key, so the baseline is one backwards seek. cache_read_session
holds one row per producer and session with such a step, and
first_positive_cursor is the smallest cursor of a step whose measurement is
above zero, or NULL. The cache_read_projection trigger on measurement
insert maintains both, so a late measurement for an old event or a step with
an old time is covered. An event's producer, session and time never change and
measurements are insert-only, so no other write can change the projection.
The migration backfills both tables from the ledger; on a synthetic store of
2.05 million calls with a cache read each, that took about 31 seconds. A future
migration that rebuilds measurement must recreate the trigger. No index is
added to usage_event, measurement or priced_charge. Tests:
projection_reads_serve_exactly_what_the_ledger_walks_served,
the_projection_migration_backfills_what_the_trigger_maintains,
a_session_without_cache_reads_costs_the_same_whatever_its_history.
step_feed (schema 29) is the live step feed. After each commit, astrocyte
recomputes the served rows of each session that gained or changed steps and
appends the rows whose served fields differ from the newest row stored for
the same (harness, step_ref), in a transaction of its own. feed_cursor is
an AUTOINCREMENT key, so cursors grow in commit order, survive restarts and
are never reused. row_json is the row without its cursor and event-only
evidence; reads join the retained evidence and newest stored cause.
step_feed_no_update refuses updates; rows committed more than 24 hours ago
are deleted, at most 1,000 per append. step_feed_state holds the cache
cursor the feed has caught up to, so a crash between a commit and its feed
append is caught up on the next commit, and pruned_through, the newest
deleted feed cursor, below which a read is refused cursor_expired.
Migration 29 starts the feed at the store's current cache cursor, so an
upgraded store does not replay its history.
Migration 32 adds the (harness, session, feed_cursor) index so filtered live
reads seek directly to a session's rows rather than scanning the feed.
Migration 51 adds step_evidence, step_digest and step_cause without a
backfill. Step events are not replayed, so their facts must survive the feed's
one-day window and a durable row replacing a runner hint. Evidence expires
30 days from when the step first reached the feed, even if the event evidence
arrives after a file-only row. Each append considers only the oldest
1,000 evidence keys and deletes expired rows in that batch, never scanning
all retained evidence to discover that nothing expired. Indexed delete/update
triggers reclaim only the old row's tool/system digest keys when their last
reference is gone. Digests are not copied into feed JSON. File-only rows keep
an empty evidence object and an unknown runner identity, preserving their first
feed cursor without inventing facts.
Migration 52 backfills ordering keys from retained evidence and each identity's
latest feed row, creating empty placeholders for feed-only identities. Rewrite
neighbours seek the (harness, session, runner, order_ms, first_feed_cursor)
index, where order_ms is request start when known and occurrence time otherwise.
Null runners compare only with other null runners. Steps a runner marks
warm_up (keep-warm requests it sent itself) stay in the chain like any other
step, because they refresh the cache the next step reads.
Separate indexes locate the latest earlier runner-only step, the latest earlier
cache report, and any positive cache read for the session's cache verdict.
These three witnesses span runners and use occurrence time, with equal times
resolved by the latest emission cursor. Feed insert triggers maintain the
source, occurrence time, cache flags and latest cursor even for corrections or
file replacements. Deleting the latest feed row clears its live cursor, removing
the identity from all live comparison indexes without deleting its retained
evidence. Evidence and its ordering keys share the bounded 30-day prune. If a
recent feed replacement outlives the original event evidence, that bounded
deletion restores only an empty, unknown-runner placeholder from the retained
feed rows, anchored to the latest feed commit. Its first cursor falls back to
the minimum retained feed cursor, as for a row without event evidence.
The shared cortexkit-usage-steps function computes rewrite causes at feed
append or replacement. It compares distinct steps in the same harness/session
and runner, warm-ups included, by request start (occurrence time when unknown),
then first feed cursor. For expiry, the newest positive cache read among the
eight latest mirrored Thalamus keep-warms in the gap between the steps in the
same harness and session substitutes its recorded time for the previous step's
finish time. Unknown runner identities compare only with other
unknown runner identities. A late insertion or replacement also rejudges the
following step. When late evidence changes a step's runner or request start,
the successor at its old comparison position is rejudged too. step_cause
appends only when the computed cause changes;
null records a correction to no cause. Its no_update, no_delete and
insert_once guards refuse editing, deletion and replacement by either the
integer primary key or its rowid alias, even with recursive triggers disabled.
Causes are kept forever after evidence and feed rows expire. Cache-history
reads join causes by (harness, step_ref) and never infer them from the ledger.
Tests: rewrite_recorded_replacement_keeps_evidence_and_cause,
rewrite_cause_survives_evidence_and_feed_pruning,
rewrite_evidence_pruning_is_bounded_at_two_history_sizes,
rewrite_previous_step_is_scoped_to_runner_even_with_shared_host_session,
rewrite_late_step_recomputes_its_successor.
declared_store_cursor and read_watermark (schema 30) serve harness stores
that another module declares, which today are the private OpenCode data
folders of the sessions thalamus-harness runs (see the
contract). Such a source has one
source_runtime row for all its stores, so each store keeps its own durable
cursor in declared_store_cursor, keyed by source key, the store's canonical
folder path and its layout (opencode-1 or opencode-2). The lineage,
consumed_ordinal and high_water_ordinal columns mean what they mean in
source_runtime. A cursor row is written in the same transaction as the
events its page recorded, and it is deleted once its folder is erased or is
no longer declared, because a new session always gets a new folder.
Schema 80 adds sweep_mark_rowid and sweep_mark_id to both
source_runtime and declared_store_cursor. They hold the OpenCode 2
reader's verified sweep mark: every rowid at or below sweep_mark_rowid was
listed by a completed maintenance sweep, and sweep_mark_id is the message
stored at that rowid. The reader trusts the mark only while the same message
still has that rowid, which rejects a store whose rowids were renumbered. The
mark is written with the cursor of each full page. Rows that existed before
schema 80 have no mark until their next completed sweep sets it; the upgrade
replays nothing. Other sources leave both columns empty. Test:
schema_v80_adds_an_empty_sweep_mark_and_keeps_cursors.
read_watermark holds one row per reader source. watermark_ms is the
greater of the stored value and the start of the source's latest complete pass
over every declared store minus 60 seconds. It is written only in the
transaction that records that pass, after every store's own transaction has
committed. Because the writer keeps the greater value, the watermark never
decreases, so neither a restart nor a clock that stepped back can lower it. updated_at_ms is when a complete
pass last confirmed it. No row means no complete pass yet. Excluding the
source in harness_ingest, or the roots file disappearing, leaves the row
unchanged. Tests: the_watermark_is_set_only_after_the_pass_commits,
the_watermark_never_goes_backwards_across_a_restart,
the_watermark_is_none_before_the_first_complete_pass.
An event's natural key is (producer, producer_lineage, producer_ref).
event_id is the SHA-256 of the key's canonical JSON. producer_lineage is
optional and its absence is part of the key's shape: an absent lineage omits
the field, so it never equals an empty-string lineage. A lineage separates
reference spaces that restart (a rebuilt producer store); a producer whose
references are already stable sends none. producer_ref is stored verbatim.
Neither auth_selection nor resolved_credential is part of the identity.
Uniqueness is enforced through event_id: ingest's only writer stores the
hash of the key and never an id supplied by its caller, so UNIQUE(event_id)
refuses a second event with the same key. The table's
UNIQUE(producer, producer_lineage, producer_ref) also holds for keys with a
lineage; it does not for keys without one, because SQLite treats nulls as
distinct. Schema 25 dropped the partial index that used to duplicate that
check.
A second delivery of an existing key is compared with the stored payload. An
identical payload is an exact redelivery and changes nothing (a pushed one
adds a redelivery_log row; a file re-read adds none). A different payload is
written to rejected_delivery and the stored event stays. Tests:
identity_hash_bytes_match_persisted_format,
schema_v25_keeps_lineage_absent_keys_unique_through_the_derived_event_id,
lineage_absent_and_empty_string_lineage_are_distinct_stored_events,
same_identity_different_payload_is_quarantined_without_overwrite,
read_exact_redelivery_writes_no_redelivery_log_row.
prior_event_ref names an earlier event of the same producer and lineage.
When the referring event's quantities agree with its target, the pair settles
chargeability; a contradicting quantity becomes quarantine_evidence. A
reference whose target has not arrived waits for it.
A measurement is (event_id, role, unit) with kind, source and a
quantity quantity_units × 10^quantity_exponent (exponent -9 to 0). Both
quantity parts are present or both are absent. An absent quantity means the
producer reported the role but no usable number; it never prices and is never
zero. Token roles are disjoint: input, cache_read, cache_write,
output, reasoning. How each harness's counters map onto them is in
harness readers.
Observed measurements are never priced and are reported as observed_only
when they are the only measurements on an event, or in runs' unpriced counts.
charge_basis is one of:
| Basis | Meaning | Pricing |
|---|---|---|
metered_api |
Billed per token at list price | Catalog rate; priced or unpriced |
subscription_included |
Covered by a subscription plan | covered at zero when a plan is in force at the event's instant; else unpriced with no_subscription_in_force. An event with an account matches account plans by that account. An event whose account_ref is NULL matches credential plans on its provider by its paying credential, resolved_credential when recorded and otherwise auth_selection, compared exactly; an event with neither is never covered. |
unknown |
The producer cannot say who paid | unpriced with charge_basis_unknown |
Transcripts alone leave the basis unknown, because they do not say how the
call was paid for. A matching payer fact can set the basis before the first
write. A pricing act that examines an event with no occurred_at_ms
records undated_event. The automatic pass skips calls whose basis is unknown.
A metered event whose model the catalog does not cover is stored unpriced with
no_catalog_coverage, including when the catalog refuses the dated read
without identifying a history boundary. Fusiform can extend its history
backwards, so catalog_pre_history requires a status read in the pricing pass
or a dated refusal that puts the event before the history start. Only
Fusiform's own history-boundary refusal counts: the no_coverage code, whose
stated history start is later than the event's instant. A bad_request, or a
refusal whose text merely mentions a history start, leaves the event queued. A
cached boundary by itself cannot finish the event. The pass checks outside the ledger
transaction and can share one catalog.status reread across events. If the
reread fails or spends the pass's time budget, the events stay queued. After a
successful reread, later passes use dated reads without repeating the status
request until a status poll sees a changed history start or rates version.
BROCA states a basis per fact, and callers of spend.event.ingest state it in
the request. An operator changes an event's basis with spend.basis.correct; see
operations.
Each billed measurement can have one chain of priced_charge rows. A row's outcome is
priced (has currency and charge_nanos), covered (zero, with the
plan's currency) or unpriced (has unpriced_reason and no money). The
origin names the act that wrote it: pricing_pass, operator_reprice,
basis_correction, or unattributed for rows written before origins were
recorded. Every row carries the event's pricing_generation and
charge_basis at the time it was written (trigger
priced_charge_matches_event_generation_and_basis).
A later row names the local integer charge_key it replaces in supersedes.
A scalar FK and priced_charge_supersedes_same_measurement insert trigger require
an existing predecessor on the same (event_key, role, unit), even when FKs are
deferred. supersedes is unique, so a chain never forks. Event digests remain
TEXT served identities and dedup keys; every child stores the local event_key.
Charge digests are not stored. The first charge in the sequence has supersedes IS NULL; the partial
index priced_charge_one_chain_root allows one such row per measurement.
The current head is the row no other row supersedes:
SELECT * FROM priced_charge pc
WHERE NOT EXISTS (SELECT 1 FROM priced_charge child WHERE child.supersedes = pc.charge_key)supersedes IS NULL selects each chain's original, not its head. Every
report, the verdict and pricing read heads with NOT EXISTS. Tests:
only_the_charge_nothing_supersedes_counts_toward_verdict_and_total,
basis_correction_supersedes_every_head_preserving_every_prior_column,
mixed_reprice_preserves_priced_head_and_supersedes_only_unpriced_head.
pricing_pending holds calls of known basis with billed measurements that have no head.
An event is queued in the transaction that records it and dequeued in the
transaction that heads its last measurement. A periodic reconciliation
re-checks the queue against the full ledger. Its final chunk commits
pricing_selection_state.last_queue_reconcile_completed_ms in the same
transaction as its queue changes. Startup waits until 24 hours after that
completion; no completion, an overdue completion or a future completion starts
the check immediately. An interrupted pass leaves the last completion unchanged
and starts again from the beginning after a restart.
For each account or credential stream, retention keeps every quota reading
until its UTC hour has been over for more than 30 days. It then keeps the last
reading of that hour and every reading referenced by quota_reset_period as a
period's first reading. The refresher thins older hours in small transactions
on full ticks; a late reading inserted behind the stream's cursor is left as
is. Older quota-history buckets therefore count retained readings and show the
peak among them, and a multiplier recompute uses the same thinned history.
Recorded multiplier observations are not changed. Deleted rows free pages for
reuse within the SQLite file, but do not shrink it. Shrinking the file would
require an offline VACUUM, which retention does not run.
window_sample and credential_window_sample store nullable model_scope
(all or subset) with each new reading. After migration 68, a null value
means the reading stated no recognized scope. Readings fetched before the
migration keep null in storage. At measurement time, missing scope on pre-cut
readings and missing catalog provider can be filled from later readings. See
the inheritance rules for when the
same login or other logins can supply those facts. No readings are backfilled.
multiplier_observation retains window_pool_key and window_minutes. The
stored key is a named slot or a length-prefixed extra-window key; the report's
pool_id is the slot name or the raw extra-window ID. The pool columns are:
| Column | Meaning |
|---|---|
pool_scope |
all, subset or unknown on new rows; null identifies the historical lineage. |
catalog_provider |
The catalog provider agreed on by the pool's readings, or null when no single provider is established. It can differ from quota_provider. |
pool_models |
JSON array of provider/model catalog IDs in the served subset list, or null when no list applies. |
pool_models_at_ms |
The subset lookup's plan.prices instant, including when the list is missing; null for other scopes. It is the observation's interval_end_ms. |
pool_member_models |
JSON array of raw provider/model IDs of calls admitted to a subset via suffix removal or an alias. It can be set only when pool_models is set. |
An observation's unique row ID is observation_id; supersedes points to its
predecessor. A chain's head is the row no other row supersedes. Migration 68
keeps two lineages, with one original per key in each:
- Historical rows (
pool_scope IS NULL) use(quota_provider, observation_day, plan), with a nullable plan. An existing correction may have a differentwindow_pool_keyfrom its parent. - Pool rows (
pool_scope IS NOT NULL) use(quota_provider, observation_day, plan, window_pool_key). The plan is required and a correction stays in the same pool. Recomputing a historical day starts a new pool chain rather than superseding a historical row. If a pool drops out of a recomputed day's set, apool_retiredrow supersedes its head without deleting history.
Corrections cannot cross lineages. The checks against reusing an observation
ID or superseding the same parent twice apply across the whole table, including
under INSERT OR REPLACE.
multiplier_provider_day is append-only and keyed by (quota_provider, observation_day), with recorded_at_ms recording the first write. The daily
stage or a recompute writes the marker and the complete provider-day set in the
same transaction. A recompute keeps the existing marker and reconciles the set
by appending observations. An empty set still has a marker, so it can advance
that provider's latest report without carrying older pools forward.
A billed measurement with no current charge head and a recorded basis of
unknown is already unpriced with reason charge_basis_unknown; it is not
waiting for a price. Automatic pricing does not store a row for this decision.
A stored head always wins, including a head appended by basis correction or
operator repricing. spend.charge.explain reports the headless decision as a
derived_charge sourced from the call's recorded charge basis, with no pricing
generation or catalog metadata.
Migration 64 removes isolated charge_basis_unknown declines on calls whose
recorded basis is still unknown, and removes those calls from the pricing
queue. Charges linked to a predecessor or successor are preserved. The migration
restores the delete guard in the same transaction. It does not vacuum the store;
compaction runs separately while the module is offline.
Token rates retain the implicit denominator of one million tokens. Their keys are
rate.<role> followed by zero or more distinct <selector>.<value> pairs, in any
order. Repeated selectors and empty segments are refused. Token roles are input,
output, cache_read, cache_write, reasoning, input_audio, output_audio,
cached_input_audio, input_image, output_image, and output_video. The image
and video token roles price only at their own keys; an absent key is no_rate,
never another role's price. A token rate must not state per.
The token above_context.<threshold> selector tests prompt size;
its threshold must be a whole number. mode.<name> requires a stated non-standard
mode and never falls back. ttl accepts only 5m, 30m, 1h, 12h, or 24h.
Each cache_write measurement with unit token_cache_<lifetime> selects its own
ttl.<lifetime> row, combined with any applicable mode or context tier. Selection
matches the complete condition set regardless of pair order. A missing lifetime
row is no_rate, never a fallback to another lifetime or plain rate.cache_write.
A plain token write still uses the plain rate (or its stated mode). Other
token-rate selectors must match the selectors recorded by the media producer;
an unmatched selector never falls back to the base rate.
Without a stored mode, multiplier rows count mode_unrecorded_tokens and
base_rate_tier_untested_tokens. A served rate.reasoning billed as rate.output
uses the selected output rate, including mode and context tiers where supported,
unless an applicable reasoning variant states its own verdict. Without that
rule, reasoning needs its own rate; if none applies it is unpriced. Ledger
coverage and whole-event rate_tiered refusals precede selection.
A served rate.cache_write billed as rate.input uses the selected input rate
for plain writes unless an applicable cache-write variant states its own verdict.
A tier rule must name the same-tier input key, and lifetime-tagged writes still
require a matching lifetime price.
Unit rates use rate.<role>.per_<unit> followed by zero or more selector/value
pairs. The closed unit list is second, character, image, request, and result
(a search engine's results, as in rate.output.per_result).
Request billing uses only rate.request.per_request. Selector names cannot repeat.
A unit measurement matches both role and unit, and every stated selector must
match the served selector set regardless of pair order. An unserved selector
leaves the measurement unpriced; it never selects the base rate. Producer-stated
media selectors are stored in usage_event.media_facts.selectors and copied
into each measurement's pricing plan. Pricing treats speed_mode as a mode
selector: fast selects mode.fast, while standard and default select the
base mode.
Every priced unit rate needs a positive per denominator. The increment and
minimum_quantity states on unit and token rates distinguish unknown,
established none, and a quantum or minimum quantity. A quantum rounds usage
up to its next multiple; a minimum then raises the resulting quantity if needed.
Unknown and none leave that quantity unchanged. Quantity rules use exact decimal
arithmetic, including fractional seconds, before the amount is calculated as
quantity times rate divided by the denominator through the single money rounding
site.
The charge's catalog_entry retains fact_key and the original rate value.
For unit charges it also records per. For unit charges and token charges with
a stated quantum or minimum it records increment, minimum_quantity,
raw_quantity, and priced_quantity. Both quantities have units and exponent
members, representing units times ten to the exponent. This preserves the gap
between measured and billed usage, including uncertainty about rounding rules.
A sourced catalog fact override is retained under fact_override. The subscription multiplier
values only token measurements and ignores unit-rate facts beside token rates.
Money is a signed 64-bit integer count of nanounits (10^-9) of the row's currency: nanodollars for USD. Corrections are signed deltas, so a total can be negative.
A catalog rate states its own exponent: a hand-kept row may give $30 per
million tokens as units 30, exponent 0. Pricing restates the rate exactly at
nano scale before using it, so rate_units and rate_exponent on a charge are
always in nanounits (rate_exponent 9); the served value stays in
catalog_entry. A measured minimum charge is restated with it. A rate finer than
one nanounit per unit cannot be held exactly and stays unpriced with
arithmetic_out_of_range; the subscription multiplier leaves such a rate
unpriced too. Arithmetic is checked in 128 bits. An overflow is a data error:
the measurement is stored unpriced with arithmetic_out_of_range, never
wrapped or capped. There is one rounding site, round_nano_num in
crates/astrocyte-core/src/money.rs, which rounds half to even. No
floating-point value touches money. Tests: round_half_even_midpoints,
round_negative_midpoints_are_even_too,
signed_consumption_is_checked_after_refunds_cancel_large_heads.
priced_charge amounts and rates are never negative (trigger
priced_charge_nonnegative); signed movement lives in adjustment. An
adjustment's currency must equal its event's
(adjustment_currency_matches_event). Adjustment reasons are write_off,
vendor_restatement, our_repricing, refund, goodwill; origins are
statement, correction_ingest, and operator in the schema.
An event starts unresolved, which has no row. One transition moves it to a
terminal state, and the schema ties each state to who may set it:
to_state |
resolved_by |
|---|---|
billed |
later_record, statement |
written_off |
correction, operator |
unbillable |
operator |
The primary key on event_id makes the transition happen at most once.
Stale hours rebuild in the background without waiting for the daily audit.
Migration 34 adds summary_run_cell at (kind, hour_number, run_key, provider, model), with typed step/token/count columns and exact currency/reason maps.
It shares the existing hour revisions, dirty triggers, reducer, publication row
budget and audit; summary format 2 requires rebuilding old hours before reuse.
The key/time index supports whole-key totals and batched fallback maxima; the
activity index supports newest-first list candidates. Run and flow detail also
have partial (run_ref, occurred_at_ms) and (flow_ref, occurred_at_ms) base
indexes. The relation is disposable, including its undated partition. Runs costs
exclude adjustments and covered/unpriced/pending money; output tokens include
reasoning on each event only when output was reported. See the Runs subsection
of module surface.
Migration 43 adds indexes so that repeated reads follow the work they serve
rather than all recorded history. The partial index summary_hour_stale on
summary_hour(kind, hour_number) holds only the hours that were not built at
their current revision or were built in a format other than 2, so run detail
finds hours that need a fresh reduction without reading every hour. A query
that names a different format cannot use the index and reads the table
instead. statement_import_by_statement on statement_import(statement_id)
lets an import count its own statement's earlier imports, which its import
ordinal needs, without reading the import log of every statement. The partial
index account_subscription_closed_end on account_subscription(provider, account_ref, effective_to_ms), restricted to closed versions, lets the overlap
check seek the closed versions that end after a new plan's start. The same
migration replaces the account_subscription_no_overlap trigger with an
equivalent condition split into an open-version test and a closed-version test,
so that each test can use an index; it refuses exactly the intervals the
previous trigger refused.
Migration 47 adds credential_subscription, the plan ledger for vault
credentials that have no account id, such as API keys. Its columns are those of
account_subscription with credential_ref in place of account_ref, and it
repeats every guard that table has for the new key: one open interval per
(provider, credential_ref), the overlap trigger split into open and closed
version tests with its credential_subscription_closed_end index, insert-once,
an update guard that allows only closing an open plan, and no delete. The
overlap trigger is created after the insert-once trigger, so an overlapping
plan is refused as an overlap.
The migration leaves account_subscription and every stored row unchanged.
Test: schema_v47_adds_an_empty_guarded_credential_ledger_and_changes_no_rows.
Migration 50 advances the shared spend/Run summary format to 6 and adds
runner and the derived host harness to the spend summary cell key. Host
harness is the event's harness for thalamus-harness rows and its producer
otherwise; it is not another ledger column. The migration recreates only summary_cell,
summary_quantity and summary_money, and the stale-hour index. Hour
revisions, ledger rows, dirty triggers and run cells remain intact; old-format
hours use the ledger until the background rebuild republishes format 6.
Migration 49 advances the shared spend/Run summary format to 5. It adds
summary_quantity.stated_observations, counting only measurements with a stated
quantity, beside observations, which still counts every measurement. Unknown
quantities contribute no units, and their observations are kept in the
scale-zero cell; the stated count distinguishes them from a measured zero.
The migration recreates only summary_cell, summary_quantity and
summary_money, and rebuilds the stale-hour index for format 5. It retains
hour revisions, ledger rows, dirty triggers and run cells. Old-format hours,
including their run cells, remain unreadable as summaries until the prioritized
background rebuild republishes the whole hour at format 5. The report can
therefore serve stated lower bounds and unknown-quantity counts without a new
ledger scan for clean hours. Test:
schema_v49_discards_ambiguous_quantity_cache_not_ledger_or_hour_metadata.
Migration 48 advances summaries to format 4 and adds the hidden
summary_cell.paying_credential dimension to the cell's unique key. It interns
COALESCE(resolved_credential, auth_selection) only for subscription-included
events whose account_ref is NULL; every other event uses the dictionary's
NULL value (id 0). Spend-report groupings do not change. Clean subscription
cells can match credential plans exactly without reducing their hours from
the ledger, unless a matching plan or billing-period boundary cuts the hour.
The migration discards only summary_cell, summary_quantity and
summary_money rows and recreates those tables with their keys, foreign keys
and checks. It retains hour metadata and the ledger dirty-hour triggers, and
recreates summary_hour_stale with
built_revision IS NOT revision OR format_version IS NOT 4. Old-format hours
stay on the ledger until the prioritized background rebuild publishes format 4.
Tests: schema_v48_discards_only_old_cells_and_preserves_stale_hours_and_dirty_triggers,
format_three_payer_cells_are_never_served_before_rebuild,
credential_covered_clean_hours_reduce_zero_ledger_hours.
Migration 24 adds derived summary tables beside the ledger; it does not delete usage events, measurements, charge history or adjustments. It creates empty summary storage and marks every existing UTC hour, including the undated partition, dirty so that the refresher can build history in the background. Reports remain exact while that work is incomplete because they can still read the original rows.
A summary cell is keyed by its UTC hour, producer, provider, model, account, auth selection, charge basis, work class, project and event currency. Hours use floor division, including for timestamps before the Unix epoch. Undated events have a separate partition rather than being assigned to the epoch or to their recording time. The string dictionary preserves stored values without trimming, case folding or aliasing; null has identifier zero, while an empty string has its own positive identifier.
The cell payload records event and measurement populations, reason maps and money sums. Quantities are kept separately by role, unit and observed decimal exponent, with missing quantities distinguished from stated zero. These are raw measurement quantities, not a claim that summing overlapping token roles gives one disjoint billed-token count. Money and quantity sums use checked i128 arithmetic and are stored as decimal text, so SQLite never coerces them through floating point. Presence counts preserve a genuine zero contribution and its currency instead of treating it as absent. Contributions in different currencies are never added together.
The event-priced count is determined before aggregation: an event needs at least one billed measurement, a current head for every billed measurement, and no blocking declined quantity. An examined, declined measurement whose stated quantity is zero does not block that report verdict. A declined measurement with an absent or nonzero quantity still blocks, as does any billed measurement that has no current head. Budget uncertainty is a separate count because its existing rule is no heads or any unpriced head, even when the declined quantity is zero. For populations too large to prove that SQLite's signed limb sums cannot overflow, the verdict keeps its original SQL path and error behavior.
Work-class percentiles use exact value frequencies, not fixed bins or averages of hourly percentiles. Only dated, complete events with a known currency enter the sample, and their value is the sum of their current priced heads before adjustments. The reader merges frequencies and selects the same nearest rank as the base-row report. Signed adjustments change spend and budget consumption, but they do not change that head-only cost distribution.
Event insertion, pricing-header updates, adjustment insertion and chargeability transitions mark the affected event's original hour dirty and advance its persistent revision in the same SQLite transaction. An adjustment is attributed to the usage event's occurrence hour, not to the adjustment's own timestamp. Basis corrections, explicit repricing and subscription coverage backfill use the same header-update path, so changes to heads, currency, reasons or the metered subtotal invalidate the old cells together. A chargeability transition is conservatively marked even though a transition alone does not remove money from the existing consumption reports.
There is no dirty write for each measurement or charge row. Measurements are
inserted with their new event, and every production caller of
pricing::insert_charge first updates the event header in
pricing::commit_reprice_in_tx. The existing
priced_charge_matches_event_generation_and_basis guard rejects a head that
does not agree with the header's generation and basis, but it does not prove
that the header changed in the same transaction. Every future charge-writing
path must preserve that header-first transaction sequence. A refused write or a
rolled-back savepoint rolls back its dirty mark as well as its facts.
SummaryMaintenance reads at most 5,000 events per source chunk in a short read
snapshot. It keeps a fresh staged reduction across chunks only while the hour's
revision remains unchanged. Publication takes the ordered writer transaction,
checks the revision again, replaces all derived rows for that hour and removes
the dirty key atomically. The persistent revision survives dirty-key removal,
so a later write cannot be mistaken for the revision that a builder read
earlier. No stored money, count or quantity total is maintained by applying
deltas to the previous summary.
The refresher runs this work after normal ingestion, pricing and pricing-queue reconciliation. Refresh and audit share a 1.5-second soft maintenance allowance: at least one chunk can run, and the observed slowest chunk guides whether another will fit. This is not a hard elapsed-time guarantee for a slow SQLite statement. Stop checks and SQLite interruption bound shutdown work, while persistent failures back off for an hour. A build that exceeds the 50,000-row publication ceiling stays dirty and continues to use live aggregation rather than publishing a partial answer.
A report reads the manifest, dirty keys, summary rows and required base rows in one caller-owned SQLite snapshot. It uses summaries only for complete, clean whole hours whose published revision and format match. Dirty hours, missing summaries and hours that cross a local-calendar or subscription-plan boundary use the original event timestamps and base-row logic. This includes fractional timezone offsets, daylight-saving changes and arbitrary plan effective times. The two sources are disjoint, so no event is counted twice. When dirty coverage is broad, or a derived value cannot be used safely, the reader retains the original full base-row path.
Subscription plans and costs, ingest freshness, set-aside evidence and current capacity are still read live rather than being frozen into the cube. Rate staleness combines the exact minimum current-head resolution time with the request's clock. Multiplier pace, multiplier reports and recomputes, and per-event charge explanation keep their existing paths; raw hourly token sums cannot replace their per-event valuation rules or history reads.
The audit compares fresh reductions from base rows with published summaries, independently of the dirty queue. It walks both base and manifest hours, so it can discover an unmarked new hour that has no summary manifest. It also compares counts, money, quantities, exact frequencies and metadata, treating malformed derived data as a rebuild request rather than as zero money. A mismatch in a clean hour is marked dirty before a warning is logged, allowing later reports to use base rows while the refresher repairs it.
The audit persists its cursor and progress statistics, and its next pass starts a day after the previous pass completes. A pass re-reads the whole ledger, so it runs daily rather than hourly to keep its disk reads small. A full pass can take many ticks, so this is a daily interval between passes, not a promise to finish the whole ledger every day. Transactional invalidation keeps normal reports exact at every snapshot; the audit is a backstop for a missed mark and cannot make an earlier stale reply retroactively exact.
The implementation is in crates/astrocyte-core/src/report/hourly.rs, and the
refresher schedules it from crates/astrocyte-module/src/refresher.rs. The
original reducers remain available for fallback and byte-equivalence tests.
Migration 37 adds nullable usage_event.media_facts, a JSON object containing
producer-stated selectors and optional failure. These facts are immutable and
participate in exact-redelivery comparison. The existing update guard keeps all
its conditions; a companion guard rejects changes to the new member. Existing
rows retain NULL and are not rewritten. Pricing copies the stored selectors into
each measurement plan, removing speed_mode into the established mode path so
fast selects mode.fast while standard and default select the base mode.
media_feed_cursor stores colliculus's committed through_seq and cumulative
skipped_local count. Sequence numbers are decimal text to preserve the feed's
unsigned 64-bit range. The cursor, local-work count, events and set-aside evidence
commit together before acknowledgement. Local counters increase only for entries
beyond the current feed cursor. The cursor survives source exclusion or absence;
removing a source's runtime row never discards committed feed progress.
spend.ledger.coverage.skipped_local_by_source is always a map, empty when no local
work was skipped. Both the direct and hourly coverage paths load these counters
live; they are not spend events or priced-charge rows. The migration rehearsal
runs the SQL on an empty store and on a store through schema 36 with an existing
event, verifies that no rows were rewritten, and checks both immutability guards.
Migration 73 adds nullable media_feed_cursor.feed_id. The reader adopts the
first reported identity without moving existing progress. Later resets update
the id and zero the cursor in the same transaction, before reading the feed
from zero. Legacy replies leave the last known id intact.
When a page from an identified feed needs acknowledgment, migration 74 lets
the reader commit media_feed_cursor.pending_ack with through_seq and
feed_id. The flag survives a restart. The reader retries only after a new
read confirms the same feed id and a head at or beyond through_seq. Success
clears the flag for that id and sequence; a feed reset discards it. Legacy
replies without a feed identity have no durable pending acknowledgment.
Migration 75 saves the already-checked BROCA segment cursor as the ceiling for
a one-time recheck. Maintenance revisits that prefix in bounded batches with
a separate cursor, without adding its segments to broca_segment_recheck.
The ordinary queue still processes late attempts independently. The recheck
can disclose a missed mismatch without rewriting recorded quantities.
The migration rebuilds step_detail_late with AUTOINCREMENT, preserving
pending entries above the saved late-detail cursor and never reusing IDs when
the queue empties. It also marks built valuation hours dirty if they contain
dated Colliculus usage with stored selectors and a positive token quantity.
Rebuilding those hours refreshes valuations and attribution without changing
ordinary spend summaries or recorded charges.