Repository navigation
feat(rollup): bound the event store's assembled view and read cost - #61
Open
jonioliveira wants to merge 6 commits into
Open
jonioliveira wants to merge 6 commits into
jonioliveira wants to merge 6 commits into
Conversation
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 callEntries(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 doctorreportsremote delivery: off,delivered through: 0), so there is no downstream consumer to protect.Design adopted from
headlong's sealed-block tiered rollup, described indocs/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.EntriesassignsPositionbycounting 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: "Positioncounts 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.
p95of a union is not derivable from thep95of itsparts — 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.godeclares for its encoder.TestMergeEqualsDirectReduceis the load-bearing test: merging N tier-1 blocksmust be byte-identical to reducing the same records directly. It was verified to
have teeth by making
Mergetake a max instead of a sum — it failed immediatelyand precisely.
Drill-down: a summary is a pointer set
Each block retains one
event_idper distinct(kind, name, outcome), orderedby
(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.
TestSealIsIdempotentAtMeasuredScaleis the guard, and it has torun 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
Pruneand
Assembleeach reasoning independently about what was needed, every fix toone 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.
TestPrunedDirectoryStillCoversHistoryandTestCoverageHoldsAtEveryScale(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 withthe sentinel default
never, inert by ADR-0014. It becomes the switch:never— still enforces nothing. An install that has not set it behavesexactly as before, and writes nothing anywhere.
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 anarithmetic 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 havemade rollups silently never seal anything on a fresh install.
Invalidation
Two independent defences, following the pattern
readDeliveryStatealready usesfor a derived position across a schema bump:
Store.Discardremoves the derived directory. This lives onStoreratherthan at each caller because there are already two
Discardcall sites —the rebuild in
internal/activationand the stale-schema drop in itsboundary walk — and a third would silently keep stale summaries.
block_versionandschema_versionand is refused onmismatch, then resealed.
No SchemaVersion bump
The rule at the top of
internal/record/record.gokeys on the recordcontract. Versions 4 and 5 bumped without adding a field because they changed
how an
event_idis derived; this adds noRecordfield and changes noderivation — 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_rulerename 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 literaland the privacy allowlist that depends on it are untouched, so no golden
regeneration question arises.
internal/remotetests pass unchanged.Verification
make validatepasses;make lintreports 0 issues.make test-raceclean.SealcalledEntries(start)permissing block, and
Entriesdecodes the whole spool each call — quadratic inhistory, 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 to0.38s. Blocks are derived and reproducible, so per-block durability bought
nothing; atomicity is kept, since the rename is still atomic.
than by calling
Sealdirectly: backfill 370ms, repeat scan ~400ms, assemble100ms. The repeat-scan cost is dominated by
sealableHead's full spooldecode, 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.
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
TestChurnIsBoundedByHowFarTheHeadMovedasserts the shape ratherthan 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
affa103with guards that fail on the old code:
repruned 3,456 blocks.
sealableHeadtook the first record inside theretention 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.
Ingest's return, sowake ingestexited non-zero and skipped its"Imported N" line over a cache whose next scan retries anyway. Counted and
exposed through
RollupFailuresinstead, which satisfieserrcheck'scheck-blankwithout failing a command whose records are already durable.uint64(q*1000)can land a hair below 950 forq=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'smtime and size were unchanged afterwards):
(kind, name, outcome)keysThat 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.
TestAgainstRealSpoolis opt-in viaWAKE_TEST_SPOOLand skips when unset, sono 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
Entries(0)readers onto the assembled view. This landsthe 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.mddoes not exist in this repo, thoughMakefile:77cites it("AGENTS.md points at this target"). Worked from
CONTRIBUTING.md.docs/adr/does not exist either, while code acrossinternal/citesADR-0004 … ADR-0036 — and those numbers collide with a different scheme
elsewhere. Same class of dangling reference.
wake configcommand, sostore.rollup_afteris set byediting
config.tomlby 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.