Skip to content

feat(rollup): bound the event store's assembled view and read cost - #61

Open
jonioliveira wants to merge 6 commits into
mainfrom
jonioliveira/bounded-event-store
Open

jonioliveira wants to merge 6 commits into
mainfrom
jonioliveira/bounded-event-store

Conversation

@jonioliveira

@jonioliveira jonioliveira commented Sep 7, 2026 •

Copy link
Copy Markdown
Collaborator

What and why

The local event store grows linearly and nothing trims it. Measured on the first
machine to install wake: 31,288 records from 1,420 transcripts over about six
weeks
, in one ~/.local/state/wake/events.ndjson. Three readers —
internal/report, internal/ui, internal/inventory — each call Entries(0)
and decode the whole file to answer a question about it, so that cost grows with
history even when the question is about last week.

Cheap now, a migration later: there is no installed base, and remote delivery is
opt-in and has never run anywhere (wake doctor reports remote delivery: off,
delivered through: 0), so there is no downstream consumer to protect.

Design adopted from headlong's sealed-block tiered rollup, described in
docs/research/what-to-adopt-from-other-tools.md §3.

What this bounds — and what it does not

It bounds the assembled view and the cost of reading it. It does not bound disk.

The spool is never modified or truncated. Store.Entries assigns Position by
counting decoded lines from the start of the file (internal/store/store.go:359-366),
so a position is an ordinal rather than a stored field — and the remote delivery
watermark is one of those positions (internal/remote/watermark.go:58: "Position
counts the records the spool held"). Trimming the spool would renumber every
position and leave that cursor indexing a different record, with nothing
downstream able to notice.

Pruning the spool needs a durable record identity that does not exist today, so
it is deliberately out of scope rather than merely unimplemented. The PR title
says what the mechanism delivers for the same reason #57 exists: a name that
claims more than the mechanism does is the defect.

The adaptation that matters: percentiles are not mergeable

The upstream note says to roll up "counts and percentiles". Counts roll up;
percentiles do not. p95 of a union is not derivable from the p95 of its
parts — that needs the distribution, which a stored percentile has already
discarded. A block holding percentile values could not seal tier 2 from the
tier-1 blocks below it without going back to the records, and "sealed once,
never recomputed" is the property the whole design rests on.

So latency is stored as fixed-boundary histogram buckets. Bucket counts are
integers, so merging is elementwise addition: associative, commutative, exact,
and independent of the order blocks are merged in. Percentiles are derived at
view-assembly time and never stored. The reduce stays arithmetic — no model
call, no network, no non-determinism — which is the property
internal/remote/otlp.go declares for its encoder.

TestMergeEqualsDirectReduce is the load-bearing test: merging N tier-1 blocks
must be byte-identical to reducing the same records directly. It was verified to
have teeth by making Merge take a max instead of a sum — it failed immediately
and precisely.

Drill-down: a summary is a pointer set

Each block retains one event_id per distinct (kind, name, outcome), ordered
by (timestamp, event_id), propagating upward on merge. A zero count answers
"skill X was never used"; any positive count still drills to an exact
invocation. One id per key also bounds a block by key cardinality rather than
event count, which is what keeps the higher tiers small.

Storage: pruning, and the bug it hid

Sealing every tier and keeping all of them does not bound anything — every tier
stays on disk forever and the summary grows linearly like the spool it
summarises. Measured at 31,288 records the unpruned directory was 3,474 blocks
and 10.8 MB against a 15 MB spool
, tier 1 alone accounting for 9.7 MB. A second
copy, not a summary.

So a seal writes only the blocks a bounded view would read, and removes anything
left over. Same history, 75 blocks and 230 KB — 1.5% of the spool.

Deciding what to write before writing it is the part that took two attempts,
and the first attempt is worth recording because CI was green over it: sealing
every complete range and pruning afterwards left each scan writing ~3,400 blocks
and deleting them again. Both headline claims above — "sealed once, never
recomputed" and "the cost of a scan is the new frontier" — were false while
nothing failed. Two numbers are needed and they are not the same: sealing stops
at the retention window's frontier, retention keeps what a view over the whole
store reads. TestSealIsIdempotentAtMeasuredScale is the guard, and it has to
run at measured scale — below 500 records the verbatim window covers everything
and the interaction cannot occur, which is exactly why every earlier
incrementality test missed it.

Retention is derived from the view's own selection walk rather than from a
separate rule about which blocks a coarser one supersedes. That is the
load-bearing structural decision and it was learned the hard way: with Prune
and Assemble each reasoning independently about what was needed, every fix to
one opened a hole in the other, and the symptom was a view that stalled at the
hole and reported 4% of history as though it were all of it
— a plausible wrong
number with no error anywhere. One walk now decides; a block is retained iff that
walk visits it. TestPrunedDirectoryStillCoversHistory and
TestCoverageHoldsAtEveryScale (1,000 / 11,000 / 31,288 records) are the guards.

Only derived blocks are removed. The spool is untouched, so a prune costs at most
a reseal.

Enablement

store.rollup_after (internal/config/keys.go:23) has existed since T002 with
the sentinel default never, inert by ADR-0014. It becomes the switch:

  • never — still enforces nothing. An install that has not set it behaves
    exactly as before
    , and writes nothing anywhere.
  • a duration — turns sealing on for events older than it.

The key stays a duration and is not reinterpreted as a count: how many events
fall in seven days varies per machine, so a duration cannot name a
position-range boundary. It governs only which events are eligible; the tiering
underneath stays count-based on positions.

Sealing builds forward from a floor recorded at the head when it was enabled,
snapped to a fanout boundary so no permanent coverage hole is left mid-block.
Backfilling earlier history is an explicit opt-in (BackfillRollups). With an
arithmetic reduce a 31k backfill is milliseconds, so the opt-in is now a policy
choice about touching a user's whole history rather than a cost one.

The floor is persisted beside the blocks, since nothing in the spool records when
the key was set. It is written even when there is nothing to seal — enabling on
an empty store records a floor of zero. Deferring that would put the floor above
everything appended in between, so nothing below it would ever seal. That was a
real bug, caught by TestSealIsIncrementalBuildingForward, and it would have
made rollups silently never seal anything on a fresh install.

Invalidation

Two independent defences, following the pattern readDeliveryState already uses
for a derived position across a schema bump:

  1. Store.Discard removes the derived directory. This lives on Store rather
    than at each caller because there are already two Discard call sites —
    the rebuild in internal/activation and the stale-schema drop in its
    boundary walk — and a third would silently keep stale summaries.
  2. Every block carries block_version and schema_version and is refused on
    mismatch, then resealed.

No SchemaVersion bump

The rule at the top of internal/record/record.go keys on the record
contract
. Versions 4 and 5 bumped without adding a field because they changed
how an event_id is derived; this adds no Record field and changes no
derivation — it adds a new derived artifact over unchanged records. Blocks carry
their own stamp instead.

This also makes #57 a non-event: its denied_policy → denied_by_harness_rule
rename with a 6→7 bump lands inside block contents, and the schema stamp
invalidates every block automatically. No rebase was needed (#57 is still open);
if it lands first, blocks reseal on the next scan.

OTLP payload untouched

git diff --stat internal/remote/ is empty. The frozen attribute-key literal
and the privacy allowlist that depends on it are untouched, so no golden
regeneration question arises. internal/remote tests pass unchanged.

Verification

  • make validate passes; make lint reports 0 issues.
  • make test-race clean.
  • Ratio about 1.5 test lines per code line, matching the repo.
  • Performance found and fixed while building: Seal called Entries(start) per
    missing block, and Entries decodes the whole spool each call — quadratic in
    history, worst exactly on the backfill this design promises to make cheap.
    Reading once and slicing took a 12k backfill from 75s to 12s; replacing
    atomicfile's per-block fsync with one directory sync per batch took it to
    0.38s. Blocks are derived and reproducible, so per-block durability bought
    nothing; atomicity is kept, since the rename is still atomic.
  • Steady state at 31,288 records, measured through the wired path rather
    than by calling Seal directly: backfill 370ms, repeat scan ~400ms, assemble
    100ms. The repeat-scan cost is dominated by sealableHead's full spool
    decode, not by sealing — the frontier is a property of timestamps and the
    store has no position-indexed answer to "which records are older than t".
    Documented at the function rather than left as a surprise.
  • What "the cost is the new frontier" does and does not mean. A repeated seal
    at an unchanged head is genuinely free — nothing written, nothing pruned, which
    is the case a hook-fired scan hits on every session end. A seal after the head
    advances
    is not free and was never going to be: the verbatim floor slides
    forward, blocks that were above it fall below, and the fine blocks in the newly
    covered region are written and then superseded by the coarser tier above them.
    Measured at about 106 blocks of work per 500 new positions, and flat — the
    same at 1,000 records as at 12,000. So the cost scales with how far the head
    moved rather than with how much history exists, which is the claim; it is not
    zero, and TestChurnIsBoundedByHowFarTheHeadMoved asserts the shape rather
    than leaving a reader to find the difference.

Four defects found after the first green CI run

All silent, none reachable by the tests that existed, all fixed in affa103
with guards that fail on the old code:

  1. Block churn — the frontier/head conflation above. Every scan resealed and
    repruned 3,456 blocks.
  2. A silent never-seal — sealableHead took the first record inside the
    retention window as the end of the sealable region, but positions are not
    time-ordered and the comment three lines above it said so. One recent record
    at a low position collapsed the frontier to zero, so nothing was ever sealed
    on that machine. Earlier tests seeded a uniform age and could not see it.
  3. A derived failure failing the command — the seal error was joined into
    Ingest's return, so wake ingest exited non-zero and skipped its
    "Imported N" line over a cache whose next scan retries anyway. Counted and
    exposed through RollupFailures instead, which satisfies errcheck's
    check-blank without failing a command whose records are already durable.
  4. A truncating quantile — uint64(q*1000) can land a hair below 950 for
    q=0.95, shifting the reported bucket down by one. Rounded now.

Worth stating plainly: a green CI run was not evidence of correctness for any of
these. Three of the four were found by re-reading the code and by an adversarial
review pass, not by a failing test.

Validated against real data

Synthetic fixtures choose their own key cardinality, and key cardinality is what
bounds a block — a generated spool with four skill names proves nothing about
real telemetry. So this was measured against a copy of a real 21.9 MB spool
of 32,032 records (read-only; writes went to t.TempDir(), and the live file's
mtime and size were unchanged afterwards):

Spool 21.9 MB, 32,032 records
Blocks retained 69, totalling 218 KB — 1.00% of the spool
A view reads 12 blocks + 502 records, not 32,032
Repeated seal 0 written, 0 pruned
Coverage complete, not truncated
Distinct (kind, name, outcome) keys 98

That last number is the one that matters: 98 keys across 32,032 invocations. A
block is bounded by key cardinality, so real telemetry — far more repetitive than
any fixture — is more economical than the synthetic numbers suggest.

TestAgainstRealSpool is opt-in via WAKE_TEST_SPOOL and skips when unset, so
no fixture is committed and CI is not gated.

It also confirmed the schema refusal against real data by accident: the live
spool is already at schema 7 from #57, and this build at 6 read a head of 0
rather than misinterpreting 32,032 records — which is what ADR-0007 asks for, and
a live demonstration that #57 landing simply invalidates blocks rather than
corrupting them.

Out of scope, reported rather than fixed

  • Rewiring the three Entries(0) readers onto the assembled view. This lands
    the subsystem and its API with tests first so the format is provable before
    anything depends on it; rewiring is a focused follow-up with its own
    before/after numbers.
  • AGENTS.md does not exist in this repo, though Makefile:77 cites it
    ("AGENTS.md points at this target"). Worked from CONTRIBUTING.md.
  • docs/adr/ does not exist either, while code across internal/ cites
    ADR-0004 … ADR-0036 — and those numbers collide with a different scheme
    elsewhere. Same class of dangling reference.
  • There is no wake config command, so store.rollup_after is set by
    editing config.toml by hand. That is pre-existing and true of all eight keys
    (T007 is referenced but unbuilt), so it is not changed here — but it is worth
    knowing that enabling this feature currently means editing a file.

Both left alone deliberately; @jonioliveira is opening a separate item.

jonioliveira and others added 6 commits September 7, 2026 18:14
The local spool grows linearly with history and nothing trims it: 31,288
records from 1,420 transcripts over six weeks on the first machine to install
wake. Every reader that answers a question about it decodes the whole file.

Add a tiered rollup of immutable blocks beside the spool. Tier k covers
Fanout^k positions; a block is sealed once, named by its range, and skipped if
present, so the cost of a scan is the new frontier rather than the history
behind it. A higher tier is merged from the tiers below it and never from
records.

The reduce is arithmetic, not a model call. Latency is stored as
fixed-boundary histogram buckets rather than percentiles: a percentile of a
union is not derivable from the percentiles of its parts, so storing values
would make a higher tier either wrong or dependent on re-reading source, which
would destroy the sealed-once property the design rests on. Bucket counts add
exactly, so merging is associative and commutative and a merged block is
byte-identical to a direct reduce over the same records.

Each block keeps one event id per (kind, name, outcome), so a summary stays a
queryable pointer set: a zero count answers "never used" and any positive
count drills to an exact invocation. One id per key bounds a block by key
cardinality rather than event count.

A seal also prunes blocks a bounded view would not use, and retention is
derived from the view's own selection walk rather than from a separate rule —
with the two reasoning independently, every fix to one opened a hole in the
other, and the symptom was a view that stalled and reported 4% of history as
though it were all of it. Unpruned, the summary cost 10.8 MB against a 15 MB
spool; pruned, 56 KB.

This bounds the assembled view and the cost of reading it, not disk. The spool
is never modified or truncated: a store position is an ordinal recomputed by
counting lines, and the remote delivery watermark is one of those positions,
so trimming would renumber them and leave that cursor indexing a different
record. Pruning the spool needs a durable record identity that does not exist
yet.

No SchemaVersion bump. The rule in internal/record keys on the record
contract, and this adds no Record field and changes no event_id derivation.
Blocks carry their own version stamp, and either that or the record schema
being foreign makes a block refused and resealed.

store.rollup_after, inert since T002, becomes the switch. "never" still
enforces nothing. Sealing builds forward from a persisted floor at the head
when it was enabled; backfilling earlier history is an explicit opt-in.
Discarding the spool now discards data derived from it, so a rebuild cannot
leave summaries of records that no longer exist.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Backfilled is what stops a later plain seal raising the floor again, so a
backfill that did not record it would be one a later run could silently undo.

A first run that is itself a backfill lowered the floor to zero without going
through the branch that raises an existing mark, and that path set the floor
without setting the flag. Found by re-reading the enablement logic rather than
by a failing test, so a regression guard comes with the fix.

Also replace the re-read that existed only to discover the snapping
WriteEnablement had applied. The snap is now one shared function, so the
in-memory floor and the stored one cannot disagree, and sealing is split into
sealFrom so the settled-floor path is shared rather than duplicated.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Three defects, all silent, none caught by a green CI run.

1. Retention was computed at the sealing frontier rather than at the spool
   head, so the selection walk never visited the blocks just above the
   frontier and a seal deleted the blocks it had itself just written. Every
   scan resealed and repruned 3,456 blocks at 31,288 records — the PR's two
   headline claims, "sealed once, never recomputed" and "the cost of a scan is
   the new frontier", were both false.

   Fixed by separating the two numbers, which are not the same: sealing stops
   at the retention window's frontier, retention keeps what a view over the
   whole store reads. And by deciding what to write before writing it, so a
   block that would be pruned is never written — higher tiers now merge through
   blocks held in memory rather than through files that exist to be deleted.
   The backfill got faster as a result: 5s to 0.47s at 31,288 records.

   Every incrementality test before this ran below 500 records, where the
   verbatim window covers everything and the interaction cannot occur, which is
   why the new guard is at measured scale.

2. sealableHead took the first record inside the retention window as the end of
   the sealable region, but positions are not time-ordered — the comment three
   lines above it said so. One recent record at a low position collapsed the
   frontier to zero, so nothing was ever sealed on that machine. Now it takes
   the lowest boundary any in-window record caps, which keeps the guarantee
   that nothing newer than the window is sealed while costing only the block
   the record falls in. Earlier tests seeded a uniform age and could not see
   it.

3. A seal error was joined into Ingest's return, so a derived cache's failure
   made `wake ingest` exit non-zero and skip its "Imported N" line — directly
   against the comment above it. It is counted and exposed through
   RollupFailures instead, which keeps errcheck's check-blank satisfied without
   failing a command whose records are already durable.

Also: Quantile scaled q with a truncating conversion, so 0.95 could land a hair
below 950 permille and shift the answer a whole bucket down. Rounded now.

The steady-state figure quoted in the PR body was measured by calling Seal
directly; through the wired path it is ~400ms at 31,288 records, dominated by
sealableHead's full spool decode. Documented where that cost lives rather than
quoting the flattering number.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
A repeated seal at an unchanged head is free, and the regression guard added in
affa103 asserts that. But a seal after the head advances is not free and was
never going to be: the verbatim floor slides forward, blocks that were above it
fall below, and the fine blocks in the newly covered region are written and
then superseded by the coarser tier above them.

Measured, that is about 106 blocks of work per 500 new positions — and flat:
the same at 1,000 records as at 12,000. So "the cost of a scan is the new
frontier" is true, but it is not "the cost is nothing", and a reader of these
numbers should not have to discover the difference themselves.

TestChurnIsBoundedByHowFarTheHeadMoved asserts the shape rather than the
constant: per-step work must not grow as history grows 24x, and a repeated seal
at the same head must cost exactly zero. Also drops an unused parameter from
plannedBlocks — lint's unused check covers functions, not parameters, so a dead
argument had been misleading about what the function reads.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…fault

Synthetic fixtures choose their own key cardinality, and key cardinality is
what bounds a block — a generated spool with four skill names says nothing
about whether this is economical on real telemetry.

Measured on a real 21.9 MB spool of 32,032 records: 69 blocks totalling 218 KB,
1.00% of the spool. A view read 12 blocks plus 502 records instead of decoding
32,032. A repeated seal wrote and pruned nothing. Coverage complete.

The number that matters: 98 distinct (kind, name, outcome) keys across all
32,032 invocations. Real telemetry is far more repetitive than the fixtures, so
the design is more economical on real data than the synthetic numbers suggest.

Reads only what WAKE_TEST_SPOOL points at and writes only into t.TempDir(), and
skips when the variable is unset, so no fixture is committed and CI is not
gated. The doc comment says to point it at a copy.

Incidentally confirmed the schema refusal against real data: the live spool is
already at schema 7 from #57, and this build at 6 read a head of 0 rather than
misinterpreting 32,032 records — which is the behaviour ADR-0007 asks for.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant