Skip to content

Hold the rest of a large page's costs to its size, send each tab only the history it lacks, and fail superlinear growth daily - #5271

Merged
max-sixty merged 24 commits into
mainfrom
quadratic-audit
Nov 4, 2026
Merged

max-sixty merged 24 commits into
mainfrom
quadratic-audit

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

#5252 wrote the rule into root AGENTS.md, "Responsiveness": no cost of a large page grows faster than the page. It also fixed the paths that broke the rule worst. This PR fixes the rest of what measurement and review found, in the browser and on the server. It also sends each tab only the history it lacks, and adds a daily test that fails any cost whose growth passes n^1.5. Part of #5194.

Browser

Five steps walked one page-size collection for each member of another:

  • coverIn read every sibling's box for each margin pin. pinSeating now reads each parent's children once per pass, sorted by top, with a tree of the lowest bottom over each run. Each pin visits only the children that reach into its band.
  • The margin layout's last loop read positions after writing each row, which forced a layout per row. It now reads every row first, then writes. The merge with Move a quoted margin row with the page's scroll in the task that scrolls #5225 needed the same fix for its new subject field.
  • hearTargetChanges tested every row against every moved node. It now collects the moved nodes once and climbs from each row's target.
  • obligationHolding placed every obligation to find a node's. It now climbs the node's ancestors through an index of where obligations sit (namedPlaces).
  • claimPaintedRoots climbed from every scoped element. It now walks only the outermost painted roots.

On 512 questions (leaf-dev scaling asks, main and branch in one run), main-thread CPU went:

main this PR
click 680 ms 374 ms
keystroke 16 ms 8.5 ms
wheel step 45 ms 28 ms

The keystroke's growth exponent went from 1.96 to flat. On this loaded host one run can differ from the next by 2×. An earlier run measured clicks at 1.6 s on main and 0.6 s here.

Server

Each of these walked a collection once per member of another; each now reads it once per reading. The table gives CPU seconds before → after on generated pages:

Path Before → after
delivery batch: thread anchors, unsent work, batch_threads 9.83 → 0.29 at 6,400 threads
page_action_unsettled (PageSettlement) 3.94 → 0.24 at 3,200 asks; 25.2 → 0.08 for a board of 1,600 moved cards
previously_requested and conditional writes 11.7 → 0.05 at 800 conditionals
board columns (AuthoredOrders, replacing authored_positions) 3.43 → 0.04 at 800 boards
record_members 1.12 → 0.15 for 800 picked groups
thread questions (ThreadAnswers) 0.58 → 0.22 for 1,600 questions
leaf page state PAGE THREAD 1.79 → 0.49 for 1,600 messages

Every reading is byte-identical to the base on 28 pages, 13 of them copies of real pages: page_state(), delivery.batch_data, leaf page state at several limits, and two appends.

History tail

A click's answer used to carry the whole history, so a session's traffic grew with the square of its log. Now each answer carries browser.basis.key, and the tab sends the key of the reading it holds back as Leaf-Held-Basis. The server re-reads the history lists at that sequence within the same page transaction. It sends what is new or changed, plus since.dropped, and the browser completes the tail into a whole reading before anything adopts it (completeState). The server keeps no record of what each tab holds. A key it can't extend gets the whole answer.

state.schema.json drops receipts and coverage, which the browser now derives, and adds browser.basis.key and since. On 64 asks with 200 events, a click's answer goes from 664 KB to 30 KB. When the log has moved, the server spends 4.5–8 ms more per answer. No protocol bump: this changes the served state, not the log.

Daily test

tests/journeys/test_scaling.py measures each leaf-dev scaling axis at 8, 64, 128 and 256. It measures each size twice, interleaved, and keeps the lower reading. It fails a cost whose growth above the 8-section page fits an exponent past 1.5. Fitting the cost itself, as leaf-dev scaling first did, let fixed work hide growth: a click's 30 ms of fixed work plus 20/80/320 ms of quadratic work fitted 1.4. Fitting its growth gives 2.0.

The test scored 0/45 false alarms on real readings taken at load 50. It missed 14 of 36 injected 100 ms quadratics, where fitting the cost missed 24. leaf-dev scaling uses the same exponent and the same threshold. It measures the 8-section page every run, and its ! marker moves from 1.3 to 1.5.

Review and tests

Four Codex reviews re-ran their own cases against each commit's parent and found no behavioral difference. For the history tail, they covered undo, pickup, revision changes, two tabs, refusals, a restart and crossed answers. All of these pass:

  • model tests (1,886);
  • pnpm run check, including the runtime tests;
  • the margin, On me and key-scope browser tests;
  • the interact-server process tests;
  • the daily test, on all three axes.

Left out

  • Four scans that walk one widget's members or one thread's history per member, rather than the page. A move compares its column's order, a selection searches its picked values, a batch checks each summary against earlier ones, and a conditional's history scans state events per revision.
  • Button reflection, which rereads every declaration each frame. That costs 9.5 ms per keystroke at 512 sections and grows linearly.
  • A click on 512 threads still answers with about 1 MB, mostly threads, workflows and obligations sent whole. That grows linearly with the page.

This was written by Claude Code on behalf of max-sixty

Reading a page's state and admitting an event cost the square of the page in
four places, each a per-widget question answered by scanning the whole page:

- The obligation inventory scanned every coordinate of the projection for each
  obligation (`replayed_attrs`, `obligation_value`, provenance and
  registration). `StateProjection` becomes a frozen dataclass whose
  `actions_by_owner`, `desired_by_unit` and `classified_by_owner` indexes are
  built once per projection; `previously_requested` reads the record's own
  classified entries instead of the whole log.
- `markup_value` walked every element of the document for each attribute
  record it was asked about. `attribute_marks` reads every attribute record's
  marks in one pass (attribute → owner → ids), and `markup_value` takes it in
  place of `spk` and the registry. Its holders read it once: the obligation
  reducer, construction, stamping's report settlement, `answering_action` and
  `page_action_unsettled`. The position readers lose the `spk` they never used.
- `discussed_by` rebuilt its source and frame maps, and scanned every record
  for a section's enclosed obligations, for each thread. It now indexes the
  records once and returns the reading as a function of the anchor, which
  `discussed` and `thread_topics` apply to each thread.
- Revision activation's reanchoring walked every character twice per open
  thread (`section_span`). The passage parser records each id's character span
  as it writes (`Passages.spans`), which `resolve_quote`, `capture_anchor` and
  `_spoken` read.

Every reading is unchanged: `page_state()`, two appends (record and the state
after each), `delivery.batch_data` and a revision activation compare byte for
byte, clock and ids pinned, against the base on 12 synthetic pages up to
W=1600 and T=1600 and 11 real pages, once fields the environment sets are
removed (reading token, producer checkout, activation clock). The runtime
fixtures `tests/served_records.py` prints are identical too.

CPU seconds, base → this change, with the log-log slope over the three largest
sizes:

  unanswered asks, empty log (W0)  W=3200  read 3.28 → 0.051 (1.93 → 0.94)
                                           append 10.4 → 0.155 (2.12 → 1.10)
  widgets each picked once (WC)    W=1600  read 0.580 → 0.106 (1.83 → 1.03)
                                           append 1.61 → 0.247 (1.92 → 1.07)
  threads at W=400 (TW)            T=1600  read 0.487 → 0.117 (1.01 → 0.60)
                                           append 0.861 → 0.135 (0.78 → 0.46)
  plain option lists (P)           P=800   read 0.555 → 0.079 (1.21 → 0.14)
                                           append 1.26 → 0.186 (1.12 → 0.32)
  revision activation, TW pages    T=1600  23.2 → 1.06
Typing and clicking on a page with many questions no longer slows with the square of
its size. On a page of 128 sections, each an `lf-ask` of four options (7,200
elements), a keystroke took 1,103 ms of main-thread CPU and a click 2,706 ms; they now
take 11 ms and 145 ms. Loading it took 3,036 ms and now takes 1,412 ms. The fitted
exponents (log cost on log size, 32 to 128 sections) went from 2.07 to 0.41 for a
keystroke and from 1.77 to 0.55 for a click (`leaf-dev scaling asks --base`). This
is cost 1 of #5194.

Causes, each a walk of one page-size collection per member of another:

- The to-do stance's `at`, which the keys ask on every scope walk, about seven walks
  per keystroke, built On me's grouped list to find the to-do the user stands on.
  Grouping names each item's part of the page with `partOver`, which read every
  heading's rendered order: items × headings per walk. `doneTodo` now finds the stop
  among the items in page order, as a walk within a region already does, and asks
  only where the user stands on a place.
- `partOver` itself compared the node with every heading. The outline now keeps each
  container's headings in order, and `partOver` halves to the last one before the node
  on each ancestor, so On me's grouping costs items × depth × log headings.
- `obligationPlace` scanned the whole inventory for another obligation sharing its
  context, and its callers place every obligation, so `obligationHolding` and
  `obligationsIn` cost obligations². The contexts are now counted once per inventory.
- `paintKeysWithin` scanned every scoped element for each widget that painted, so a
  first paint cost widgets². It now records the painted root, and the frame resolves
  every root with one climb per scoped element.
- `holdSelection` read the page selection on every `setChildLists`, and in Chromium a
  selection read forces style, so each margin cluster's first paint restyled the page.
  A placement of nodes not yet in the document can't move a selection, so it no longer
  reads it.
- Each margin row's registration read the margin column, whose `getComputedStyle`
  forced style per row. The layout pass, which reads the column anyway, now observes it.
- The thread walk's availability sorted every open thread by rendered order to test
  whether any was open, on every input. It now asks whether any is.

Behavior is unchanged except where two stops stand at one place or nest, such as two
to-dos on one element: `doneTodo` now breaks that tie by page order, as
`currentLocationStop`'s header says, rather than by On me's order. The two orders
differ only under By kind and By <agent>.

Remaining, measured and not fixed here: margin pin seating (`coverIn`) reads every
sibling of the content for each pin, which is pins × sections per layout pass, and
grows past linear from about 256 sections on load, click and wheel.
Root AGENTS.md's Responsiveness section now says how costs may grow with a page:
an input's work depends on what it changes and never grows faster than the page;
loading and computing or applying a reading grow no faster than n log n. It names
the two shapes that break that, a walk of one page-size collection per member of
another, and a style or layout pass forced once per element. browser/AGENTS.md adds
that `getComputedStyle` forces style, and that in Chromium any read of the selection
does too (measured: 200 reads after a write on a 20,000-paragraph page took
2.3 s in Chromium and 0 ms in Firefox).

`leaf-dev scaling [AXIS ...] [--sizes] [--base] [--profile]` is the check. It
generates pages along an axis (`asks`: sections each holding an `lf-ask`; `prose`:
headings and paragraphs; `threads`: comment threads over a fixed page), serves each
from the tree, and reads the renderer's main-thread CPU for the load, a click, a
keystroke and a wheel step, plus the server's time and bytes for each event a click
posts. It fits each cost's exponent over the largest sizes and marks one above 1.3.
`--profile` lists the functions whose time grew superlinearly between the smallest
and largest page. Three sessions had written this experiment as a throwaway script
(#5063, #5061, #5194).
…kup once

Fixes from review of the two earlier commits:

- `doneTodo` again reads the walk's stops in On me's order, so where two to-dos stand
  on one element under By <agent>, `x` ends the one On me and `m` select. It reads
  them only where some item on the user offers Done and the user stands on a place;
  every other keystroke returns at once. With the outline index, building the stops
  costs items × depth × log headings rather than items × headings.
- A root `paintKeysWithin` recorded is resolved before Leaf's mover moves a placed
  node (`installMoveKeys`, dom-move.js), so a control that leaves a painted root
  before the frame keeps its mark. Placing nodes not yet in the document resolves
  nothing, so a first paint still batches.
- `obligationPlace` asks the shared-context set's size and membership rather than
  copying it.
- `handed_over` reads the page's `(by_id, attribute_marks)` once for every page
  action it settles; `page_action_unsettled` had built both per action.
- `leaf-dev scaling` waits for each click's event answer, and reads CPU profiles
  through `profile.py`'s reader.
- browser/AGENTS.md: a Chromium selection read can force style, not always does.
… painted root

Review of the previous commit found that resolving every pending painted root before
any placed node moved brought back a scan of every scoped element per widget wherever
renders reorder retained children between paints: 16,256 scope visits for 128 roots
each reversing two children. Now a node about to move out of a painted root marks the
scoped elements it holds, a walk of the moving subtree only, and the frame resolves
the rest of the roots once as before.
# Conflicts:
#	browser/runtime/queue-walk.js
#	dist/kernel/kernel.json
#	dist/kernel/leaf.js
#	dist/kernel/runtime/bundle-data.js
#	dist/kernel/runtime/bundle-portable.js
# Conflicts:
#	dist/kernel/kernel.json
#	dist/kernel/runtime/bundle-portable.js
…de's obligation from its ancestors

On a page of 512 asks, `leaf-dev scaling asks` still grew a click by n^1.47, a
keystroke by n^1.37 and a wheel step by n^1.97. Profiles named five steps that walk
one of the page's collections for each member of another:

- `coverIn` read the boxes of every child of each ancestor it visited, once per
  pin, so a pass cost pins × siblings. `pinSeating` now reads each parent's
  children once per pass (`childIndex`), sorted by top with a tree of the lowest
  bottom over each run, and a pin's band visits only the children that reach into
  it. Nothing writes the DOM during seating, so one reading serves every pin.
- The last loop of `layoutMountedRows` read `scrollX`/`scrollY` and each row's
  target after writing the previous row's position, forcing a layout per row. It
  now reads every row's seat first and writes after.
- `hearTargetChanges` tested every row against every moved node. It now collects
  the moved nodes and their composed ancestors once and tests each row's target
  against that set.
- `obligationHolding` placed every obligation on the page to find the one holding
  a node. It now climbs the node's composed ancestors and looks their names up in
  an index of the obligations' places (`namedPlaces`), built once per inventory.
- `claimPaintedRoots` climbed from every scoped element to the root. It now walks
  only the outermost painted roots, with a per-pass memo of which nodes already
  stand in one.

At 512 sections on the asks axis, CPU per transition:

| | before | after |
|---|---|---|
| load | 9,648 ms | 5,583 ms |
| click | 1,616 ms | 614 ms |
| keystroke | 64 ms | 16 ms |
| wheel step | 178 ms | 49 ms |

The exponents over 128–512 went from 1.21/1.47/1.37/1.97 to 0.88/0.66/0.37/0.87.
The prose and threads axes are unchanged. Differential checks against the previous
code agreed on 15,810 obligation lookups, 10,000 cover bands and 256 scope walks.
A delivery batch cost the batch times the log in `unsent_at_messages`, which
gives each message about a playground the settings its preview showed. For each
message or edit in the batch it folded every thread over the log through that
message (`build_threads(events[: position + 1])`) to learn where the message's
thread stood then. Then, at each message about a widget, it listed the winner at
every coordinate on the page to keep the ones on that widget.

Both readings now come from walks of the log that answer at each input:

- Where a thread stands is the last event that placed it: its comment, a
  `reanchor`, or an agent's reply carrying `anchor`. `placed_thread` states that
  rule beside `thread_names`, and `validation.source`'s relocated-anchor advice
  now reads it too. No undo before an input can have withdrawn that event: the
  only placement an undo takes back is a reaction's opening comment, and
  admission keeps an input's thread in force. So a walk that records each
  thread's latest placement reads what the prefix fold read, including a
  reaction withdrawn after it was delivered.
- The unsent-work walk indexes each widget's coordinates in the order
  `InForce.winners` keeps them, so an input reads the coordinates of the widgets
  it is about rather than every coordinate on the page.

CPU seconds of `delivery.batch_data` over the newest n/16 user messages, base →
this change, in a fresh process each (the least of 3 runs before, of 7 after),
with the log-log slope over the three largest sizes:

  threads anchored beside widgets (A)    n=6400   10404 events, batch 400
                                         9.83 → 0.289 (2.33 → 0.96)
  threads anchored inside n/4 widgets    n=12800  20804 events, batch 800
  (A2)                                   43.6 → 0.754 (2.06 → 1.16)

Without the coordinate index, A2 at n=12800 takes 2.00 s (slope 1.42). The host
was loaded, and single readings varied by up to 30%.

Every reading is unchanged. `page_state()`, `delivery.batch_data` for a mixed
batch and for the newest 64 messages and edits, and two appends (a reply and an
action, each with its record and the state after it) compare byte for byte
against the base, with the clock, ids and hash seed pinned and the fields the
environment sets removed (reading token, producer checkout, activation and
snapshot clocks). The pages are 9 synthetic and 13 real ones. Two synthetic
pages repeat a playground journey (withdrawn reactions, edits, threads an agent
moved to another playground) in which 46 of the newest 64 messages carry unsent
work.
Reading a page's workflows cost its page actions in force times the page.
`page_action_unsettled`, asked once for each such action, scanned the whole log
for a later version's note. For an attribute record it regenerated every created
child on the page, sorting all of `desired`, to find the ones on its widget. For
a position record it read the owner's authored and folded orders again, two to
three passes over the document and a sort of `desired`, and searched them for its
unit. In `handed_over`, each frozen action rescanned its thread's messages for a
settling agent turn, and each thread scanned every failed response on the page.

`PageSettlement`, built at the first page action a reading weighs, holds what
every page action shares: the markup with its attribute marks, the children each
owner's creating actions supply, a cache of each position owner's placements, and
the notes' seqs with the newest revision stamped from each one on, so whether a
later version took an action in is a binary search. `recorded_state` stores an
owner's authored and folded orders in that cache as each unit's `Placement`. A
thread's settling agent turns (the inputs they answer and the newest one's seq)
are read once per thread, and a thread finds the failed responses it hands back
by looking up its own turns.

CPU seconds of `page_state()`, base → this change, in a fresh process each (the
least of 3 runs before, of 7 after), with the log-log slope over the three
largest sizes:

  n single-choice asks, each picked once     n=3200  3.94 → 0.239 (2.20 → 1.17)
  (owed page actions; 3230 events)
  one board of n cards, each moved once      n=1600  25.2 → 0.084 (2.86 → 1.26)

After the change, the owed picks' profile holds no per-action term: the folds
over the log (`state_projection`, the obligation inventory, parsing the log)
take the time. The host was loaded, and single readings varied by up to 30%.

Not fixed: n boards of three cards with one move each still cost the boards
times the page (n=800: 4.50 → 4.24 s, slope 2.0). `authored_positions` finds an
owner's columns by asking every column on the page for its owner, and
`state_projection` (through `move_absorbed`), `recorded_state` and
`folded_positions` each call it once per owner. An index of every owner's
containers, read in one pass over the document, would remove that term for all
of them.

Every reading is unchanged. `page_state()`, `delivery.batch_data` for a mixed
batch and for the newest 64 messages and edits, and two appends (a reply and an
action, each with its record and the state after it) compare byte for byte
against the base, with the clock, ids and hash seed pinned and the fields the
environment sets removed, on 9 synthetic and 13 real pages. Two synthetic pages
repeat a journey through owed and unowed picks, a pick of an option the user
added, board moves, draft edits, a version stamped midway, frozen picks settled
by a reply or a later agent turn, and failed responses, with and without a user
turn after them; one more moves every card of a 100-card board. The runtime
fixtures `tests/served_records.py` prints are identical too.
…rites

Reading a page whose package declares a value record named in an `x-awaits`
`when` cost those widgets' writes times the log. `previously_requested`, which
registers an ask that a value write opened between revisions, folded the whole
log prefix through each such write (`state_projection` over every event with
`seq <= write`) to read the element's attributes as they stood then.

That prefix fold takes its floors and withdrawals from the whole log, so it
admits exactly the actions the whole log's fold holds in force. The two differ
only in reports: a note settles a report on every prefix through the note. So one
walk of the entries at the element's unit reads each prefix by the rule
`state_projection` builds `desired` by: a coordinate stands at its newest action
in force so far, else at its newest report no note so far has settled.

- `StateProjection.classified_by_unit` indexes the entries the walk reads. It
  replaces `classified_by_owner`, which only this reading used.
- `events.report_settled_at` gives each report the seq of the first note that
  settled it, beside `report_settlements`; both read the settling notes through
  one generator.
- `previously_requested` no longer takes the log, document or vocabulary, and
  the inventory caches the settlement seqs per revision instead of prefix folds.
- `state_projection`'s docstring names this second reader of its rule.

No bundled package declares such a record, so the cost is reachable only through
a package that does, as the tests' `lf-conditional` fixture does.

CPU seconds of `page_state()` for n `lf-conditional` widgets, each opened and then
closed by the user, base → this change, in a fresh process each (the least of 3
runs before, of 7 after), with the log-log slope over the three largest sizes:

  n=800  1600 events  11.67 → 0.050 (1.89 → 0.97)

Every reading is unchanged. `page_state()`, `delivery.batch_data` and two
appends compare byte for byte against the base, with the clock, ids and hash seed
pinned and the fields the environment sets removed, on 9 synthetic and 13 real
pages. One synthetic page holds 16 user-written and 16 agent-reported
conditionals, with undos, a version that retracts one (`restated`), and reports
a version overrules and so settles. On it, a variant that ignores settlement
registers the four overruled reports and differs from the base; this change does
not. The runtime fixtures `tests/served_records.py` prints are identical too.
… work passes n^1.5

`tests/journeys/test_scaling.py` measures each `leaf-dev scaling` axis at 64, 128
and 256 on every daily run, and fails a cost whose exponent passes SUPERLINEAR.

The command's exponent fitted each cost itself, so fixed work hid growth. A click's
30 ms of fixed work plus 20/80/320 ms of quadratic work fitted 1.4 over 64-256, and
the gate passed 320 ms of added work per click. Every run now also measures a page of
BASE (8). Each exponent fits a cost's growth above that page's cost: linear growth
fits 1.07, n log n 1.25 and quadratic 2.0. A cost that grows by less than its floor
above BASE (10 ms, 50 ms for the server's elapsed time, 10 KB) has no exponent, since
what it grew is noise. SUPERLINEAR moves from 1.3 to 1.5, halfway between linear and
quadratic, and the command and the gate share it.

The gate measures each size twice, interleaved, and takes the lower reading. Three
such pairs of every cost on every axis, measured on this host at load 50, scored:

| statistic | false alarms | 100 ms quadratic missed | 400 ms missed |
|---|---|---|---|
| exponent of the cost (before) | 0/45 | 24/36 | 15/36 |
| exponent of growth over 64-256 increments | 9/45 | 7/36 | 2/36 |
| exponent of growth above n=32 | 1/45 | 6/36 | 5/36 (n log n alarms 20/36) |
| exponent of growth above n=8 (this) | 0/45 | 14/36 | 6/36 |

The misses that remain are a quadratic smaller than a cost's linear growth at 256,
such as 400 ms beside the asks load's 1.4 s. At these sizes that reads as n log n.
…ate stops growing with the log

A tab that already holds the page's state is now sent only what happened
since: the events after the reading it holds, and the projection and undo
entries those events added or changed. On a page of 64 sections, each an
`lf-ask` of four options, a click's `POST /api/event` answer was 27 KB with
an empty log and 664 KB after 200 events; it is now 26 KB and 30 KB, or
61 KB where 20 of those events were comments, whose threads and workflows
are page content. What the tab assembles is exactly the whole answer, so
nothing it draws changes. Part of #5194, its cost 3.

### What grew with the log

At fixed content, each part of `page_state()` by event count (bytes, 64
asks; every tenth event a comment, the rest picks):

| part                      | no events | 200 events | per event |
| ------------------------- | --------: | ---------: | --------: |
| `events`                  |         2 |    112,555 |       563 |
| `browser.receipts`        |         2 |    112,555 |       563 |
| view `document.projection` |       53 |    145,709 |       728 |
| view `undo`               |         2 |    116,117 |       581 |
| view `coverage`           |         2 |    116,117 |       581 |
| view `thread.threads`     |         2 |     16,123 |        81 |
| `workflows`               |         2 |      9,332 |        47 |
| everything else           |    23,619 |     32,054 |        42 |

The first five are one record per event, each embedding the whole event
(a projection entry also its verb's schema). The rest hold what the page
holds: threads, workflows, obligations and queues grow with the comments,
not with picks.

### The design

Each part is handled by what it is:

- **`receipts`** was `events` filtered to those carrying an `attempt`, and
  **`coverage`** each widget event and undo joined to the coordinate the
  view's projections give it. Both are gone from the wire. The browser
  selects receipts from the log it holds, and `logCoverage`
  (framework/application.js) derives coverage from the log and the view's
  entries, for the applied stamp and `foldProjection`'s terminal entries.
  A whole answer is a third smaller for it.
- **`events`** is append-only, so a tail is the events after the held
  sequence.
- **Projection entries and `undo`** are history too, but an old entry can
  change: an undo withdraws an action (`stands` turns false, and it leaves
  the undo list), a pickup marks gestures `picked_up`, and the undo head
  moves. So the answer sends each entry that is new or differs from the
  held one, by event id, and `since.dropped` names, per view and list, the
  held entries the list no longer holds. The browser keeps the rest and
  orders by event (log order; newest first for `undo`).

Every answer's `browser.basis.key` names its reading: the log sequence, the
active revision and the viewed revisions. A request sends it back as
`Leaf-Held-Basis`, beside `Leaf-Data-Version`, and an answer that can
extend it carries `since` (`served_state/tail.py`). The server doesn't
remember what it sent: within the same page transaction it reads the
history lists again at the held sequence (`PageRead.through`) and diffs.
That is exact because those lists depend only on the log through that
sequence, the immutable revision documents, and the active and viewed
revisions the key names; bound data, presence and the clock never reach
them. A key naming another active revision, a view the answer has and the
tab lacks, a sequence past the log, or nothing parseable gets the whole
answer, as do a fresh tab and leaf.page's stored and static states.

In the browser, `completeState` (layer-client.js) replaces `completeData`
at the three places an answer is read (the state feed, a gesture's POST, a
bookkeeping POST). Each captures what it holds before asking
(`heldReading`), since a newer reading can be adopted while a request is
out. The publisher still adopts one complete reading at a time, and
nothing downstream sees a tail. An answer extending a reading the request
didn't name throws, which the feed reports as a fault.

Recomputing the held lists costs a second fold when the log moved: on the
64-ask page at 200 events a whole answer takes 6.7 ms of server time and a
tail one event behind 11.2 ms; on the 512-thread page, 13.3 ms and 21.2 ms.
A read where the log didn't move, such as one after an activity change,
skips it. A memo of the last served lists would remove the second fold,
at the cost of server-side state; this leaves it out.

### Sizes after

Event answer per click, 64 asks:

| events in the log | before | after, picks only | after, with comments |
| ----------------: | -----: | ----------------: | -------------------: |
|                 0 |  27 KB |             26 KB |                26 KB |
|               200 | 664 KB |             30 KB |                61 KB |

`leaf-dev scaling threads --sizes 128,256,512 --base quadratic-audit`,
event answer at 128/256/512 threads: 313/617/1227 KB before, 255/508/1014
KB after. There the log was a sixth of the answer: the rest is each
thread's record (494 KB at 512), its workflow (224 KB), obligations (119
KB) and queue rows (67 KB), which every answer still sends whole.

In Chromium, a probe holding 40 events of history clicked seven options
and pressed `z`: each event answer was 22 KB, against 227 KB growing to
248 KB on the base, and the tab's adopted reading equalled a fresh whole
read at the same sequence (seq 91).

### Contract

`state.schema.json` drops `browser.receipts` and each view's `coverage`,
adds `browser.basis.key` and the answer's `since`, and says which lists a
tail leaves partial. `browser/AGENTS.md`, "One writer for each fact", says
an answer naming a held reading is completed before the publisher adopts
it. `http.py`'s `page_state`, `served_state/page.py` and `tail.py` state
the server's side; `layer-client.js` the browser's. No protocol bump: the
served state never leaves one Leaf.

### Checks

- `tests/runtime/state-tail.test.mjs`: for five server-written cases
  (`served_records.py`, `tail_cases`: a pick after a pick, an undo of an
  older pick, a pickup, several events at once, nothing new), completing
  the tail from the held reading equals the whole answer. Ignoring
  `dropped` fails two of them.
- `tests/model/test_model_folds.py`: a tail holds only the events and
  entries since (an undo resends the withdrawn entry and drops it from
  undo), and an answer the held reading can't extend is whole.
- `tests/process/test_interact_server.py`: an accepted action's answer to
  a request naming the prior reading carries only that action.
- `pnpm run check` (763 runtime tests, type check, committed bundles,
  Worker), and the model and process modules that read served state.
- Browser: smoke, `projection/test_activity.py`,
  `test_render_application_boundary.py`, `projection/test_widget_actions.py`,
  `drafts/test_revisions.py`, `startup/test_readiness.py` and
  `test_render_outbox.py` pass (163), except 18 failures and 2 teardown
  errors that the merge base without this change shows the same way on
  this Mac: the executable-revision tests in `drafts/test_revisions.py`
  time out waiting for revision 2, and
  `test_widget_controller_owns_presentation_across_values_and_lifetimes`
  sees an extra render-failure report.
A page of many boards cost the boards times the page. `authored_positions`
found one owner's columns by asking every column on the page for its owner
(`recorded_owner`), and `state_projection` (through `move_absorbed`),
`recorded_state` and `folded_positions` each called it once per owner, the last
twice. `folded_positions` also sorted every coordinate in `desired`, whatever its
owner, for each owner it folded, and moved each unit by searching every column's
list for it.

`AuthoredOrders` reads where one version's markup puts every position owner's
units in one pass: each container's owner once, then each unit under its
container. `of(owner, record)` answers what `authored_positions` answered, and
the per-owner scan is gone. Every caller builds the index once for the document
it reads:

- `state_projection` builds it when the log holds a move whose `among` it must
  check, and `move_absorbed` reads it.
- `PageSettlement` keeps it in its markup, so `recorded_state` reads the owner's
  authored order from it and folds on the same document, which was its only use.
- The obligation reducer keeps it beside its attribute marks, and
  `obligation_value` takes it in place of the vocabulary.
- `construction`, the dev command `record-demo`, the model tests and
  `tests/served_records.py` build one for their document; admission's
  `event_meaning` and `stale_move_error` build one per document they compare.

`folded_positions` reads the owner's coordinates through a new
`StateProjection.desired_by_owner` and keeps each unit's container in a map
rather than moving it between lists.

CPU seconds of `page_state()`, base → this change, in a fresh process each (the
least of 5 runs), with the log-log slope over the three largest sizes:

  n boards of three cards, one moved on each   n=800   3.43 → 0.038 (1.64 → 0.91)
  one board of n cards, each moved once        n=1600  0.058 → 0.056 (1.07 → 1.03)

Every reading is unchanged. `page_state()`, `delivery.batch_data`, `leaf page
state` for the page and for its first and last messages carrying markup, and two
appends compare byte for byte against the base, with the clock, ids and hash seed
pinned and the fields the environment sets removed, on 12 synthetic and 13 real
pages. The synthetic pages include 100 boards with a move each, and 12 boards
whose second version writes half of their moves into the markup, absorbing
them, before more moves land. The runtime fixtures `tests/served_records.py`
prints are identical too.
`leaf page state PAGE <message>` cost a message's option groups times the
message. `construction` called `record_members` once for each widget with an
attribute record, and each call asked every element of the message for its
recording owner (`recorded_owner`), found where moves in force put units
(`projected_action_holders`) and regenerated every created child, to keep the
ones of that one widget.

`record_members` now returns every owner's members of one attribute record from
one such pass. `construction` reads it once per attribute and looks each widget
up; admission's member check (`event_contracts`) reads its widget's entry.

CPU seconds of `leaf page state PAGE <message>` for one agent message holding n
option groups, each picked once, base → this change, in a fresh process each
(the least of 5 runs), with the log-log slope over the three largest sizes:

  n=800  801 events  1.12 → 0.145 (1.83 → 1.06)

Every reading is unchanged. `page_state()`, `delivery.batch_data`, `leaf page
state` for the page and for its first and last messages carrying markup, and two
appends compare byte for byte against the base, with the clock, ids and hash seed
pinned and the fields the environment sets removed, on 12 synthetic and 13 real
pages, one of them the message of 100 picked groups. The runtime fixtures
`tests/served_records.py` prints are identical too.
A delivery whose messages are about a widget cost those messages times every
coordinate the widget had ever had. At each such message, `unsent_at_messages`
read the winner at each of the widget's coordinates, withdrawn and emptied ones
included, and asked each winner whether its verb records unsent work.

The walk now keeps, for each widget, the coordinates whose winner records unsent
work and that winner, updated at each step that moves a winner (an admit, an undo,
or a note's retraction, each of which `InForce` reports as a `Change`). A message
reads only the work it carries, sorted into the order `InForce.winners` keeps,
so its cost grows with what it carries. Each winner is asked about unsent work
once, when it takes its coordinate.

CPU seconds of `delivery.batch_data` for one board of n cards, each moved and
the move undone, then n comments on a card delivered together, base → this
change, in a fresh process each (the least of 7 runs), with the log-log slope
over the three largest sizes:

  n=3200  9600 events, batch 3200  0.860 → 0.320 (1.76 → 1.48)

The rest of the slope is `batch_threads`, which the next change reads through
indexes.

Every reading is unchanged. `page_state()`, `delivery.batch_data`, `leaf page
state` for the page and for its first and last messages carrying markup, and two
appends compare byte for byte against the base, with the clock, ids and hash seed
pinned and the fields the environment sets removed, on 12 synthetic and 13 real
pages. Two synthetic pages deliver 46 of 64 and 16 of 22 messages carrying
unsent work, from playgrounds tuned, undone and retuned. The review's edge-case
probe of `unsent_at_messages` (reactions withdrawn after delivery, coordinates
withdrawn or retracted and then taken again, a detached thread's edit) prints
the same result. The runtime fixtures `tests/served_records.py` prints are
identical too.
A delivery of many messages in many threads cost the threads times the batch.
`batch_threads` collected the threads the batch lands in by checking a list for
each one, and for each thread it scanned the whole batch for actions on its
widgets and every message's markup for the widgets those actions name, to pin
the message that sent each.

The threads are now collected in a dict in the same order. One pass over the
batch finds the widgets its actions name in each thread, and one pass over the
markup finds the messages declaring each id, so each thread reads only its own.

CPU seconds of `delivery.batch_data` for one board of n cards, each moved and
the move undone, then n comments on a card delivered together, before → this
change, in a fresh process each (the least of 7 runs), with the log-log slope
over the three largest sizes:

  n=3200  9600 events, batch 3200  0.320 → 0.175 (1.48 → 1.20)

From the base before the previous change: 0.860 → 0.175 (1.76 → 1.20).

Every reading is unchanged. `page_state()`, `delivery.batch_data`, `leaf page
state` for the page and for its first and last messages carrying markup, and two
appends compare byte for byte against the base, with the clock, ids and hash seed
pinned and the fields the environment sets removed, on 12 synthetic and 13 real
pages, including deliveries that carry frozen widgets' actions and the messages
that sent them. The runtime fixtures `tests/served_records.py` prints are
identical too.
A conditional ask's earlier requests cost its writes times the coordinates at
its unit. At each of the element's value writes, `previously_requested` copied
every coordinate standing at the unit, other owners' included, and overlaid
every value record among them, sorted by seq, to read the attributes `when`
names.

An attribute reads the newest value write standing at any of its coordinates,
and that is its newest write no note has settled: a newer write at a coordinate
is a newer write of its attribute, and an action in force is never settled. So
the walk keeps each attribute's value writes in log order, drops settled reports
from the top as it reaches them, and reads each attribute `when` names from the
newest write left. A write costs its push and the attributes `when` names.
`replayed_attrs` takes back the overlay loop the previous version shared.

CPU seconds of `previously_requested` for n owners each writing a coordinate at
the conditional's unit, then n conditional writes that never match, base → this
change, the least of 5 runs, with the log-log slope over the three largest
sizes:

  n=800  1600 events  0.0415 → 0.0006 (2.04 → 0.87)

Every reading is unchanged. `page_state()`, `delivery.batch_data`, `leaf page
state` and two appends compare byte for byte against the base, with the clock,
ids and hash seed pinned and the fields the environment sets removed, on 12
synthetic and 13 real pages. One synthetic page holds 16 user-written and 16
agent-reported conditionals with undos, a version's retraction, and reports a
version overrules and so settles. The review's randomized probe, 200 logs of
writes, undos, settling notes and revisions on a conditional with two value
records (183 admitted), reads the same obligations. The runtime fixtures
`tests/served_records.py` prints are identical too.
Reading a page whose threads ask many questions cost the questions times the
thread. `thread_obligation_readings`, for each question asked in a thread (a
message carrying `obligation`, or a widget frozen in a message), found the
asking message by scanning the thread, scanned on from it for the user's
answer, computed the turn the agent owes the whole thread
(`unanswered_agent_turn`), and scanned every open to-do on the page for one on
the thread.

`ThreadAnswers` reads each thread once for all its questions: where each message
stands, the user's messages in words in order, each message's first reaction
whose token settles it, and the turn the agent owes. A question's answer is the
earlier of the first words after it, found by bisection, and its first settling
reaction. The newest open to-do on each thread is read once from the to-dos.

CPU seconds of `page_state()` for one thread of n agent messages, each holding
an option group the user picked, base → this change, in a fresh process each
(the least of 7 runs), with the log-log slope over the three largest sizes:

  n=1600  3200 events  0.578 → 0.222 (1.49 → 1.02)

Every reading is unchanged. `page_state()`, `delivery.batch_data`, `leaf page
state` for the page and for its first and last messages carrying markup, and two
appends compare byte for byte against the base, with the clock, ids and hash seed
pinned and the fields the environment sets removed, on 14 synthetic and 13 real
pages. One synthetic page asks in words in 16 threads, answered by words, a
settling reaction, a reaction that settles nothing followed by words, or not at
all, with frozen groups picked or not, user turns after them and open to-dos on
some threads. The runtime fixtures `tests/served_records.py` prints are identical
too.
The kernel is rebuilt from the merged sources. #5225 added each row's `subject` to the
margin layout's final loop, reading `scrollX` there. That loop now reads the window's
scroll once before it writes any row, so the subject reads that value too, as the
loop's other coordinates do. Reading `scrollX` after a row's write would lay the page
out again, once per row.
…fold

`leaf page state PAGE <thread> --limit N` cost the messages shown times the
thread. For every message carrying markup, `constructed_content` read the whole
thread's fold: it regenerated every created child and sorted every coordinate to
keep the message's own, and its `record_members` found where moves put units
(`projected_action_holders`) and listed created children over every coordinate.
`retirement_outcomes` ran over every action in force twice per message, once for
the message's passages and once inside the construction.

The page state now reads `retirement_outcomes` once for the thread and passes it
to `page_passages` and to `constructed_content`, which takes it as `outcomes`.
`constructed_content` reads only its message's part of the fold, through the
projection's indexes, which are built once per reading:

- created children from `desired_by_owner`, over the message's own elements and
  the children they create in turn, the only owners that can stand in it;
- the state on each of its units from `desired_by_unit`, sorted by seq.

`projected_action_holders` and `record_members` read only the units and owners
of the document they are given, the same way, which serves the page's own
document as well.

CPU seconds of `leaf page state PAGE <thread> --limit N` for one thread of n
agent messages, each holding an option group the user picked, with N above n,
base → this change, in a fresh process each (the least of 5 runs), with the
log-log slope over the three largest sizes:

  n=1600  3200 events  1.79 → 0.49 (1.65 → 1.05)

One message holding 800 picked groups is unchanged: 0.179 → 0.160 s.

Every reading is unchanged. `page_state()`, `delivery.batch_data`, `leaf page
state` for the page and for its first and last messages carrying markup, each
at the default limit, at 2 and above the thread's length, and two appends
compare byte for byte against the base, with the clock, ids and hash seed pinned
and the fields the environment sets removed, on 15 synthetic and 13 real pages.
One synthetic thread of 8 messages holds an option group, a board and a draft in
each, then options added and picked, cards moved and drafts rewritten; another
is 100 messages long. The runtime fixtures `tests/served_records.py` prints are
identical too.

@leaf-agent leaf-agent left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new daily test failed in this PR's own test job (run). test_no_cost_grows_faster_than_the_page[threads] errored before it measured anything, with It looks like you are using Playwright Sync API inside the asyncio loop. leaf_dev.browser.headless_shell() opens a second sync_playwright() driver. The xdist worker that ran [threads] (gw0) had just run test_site, so it already held the session _playwright driver, which tests/conftest.py describes as "The one Playwright driver a worker may hold". The asks and prose axes passed only because their worker hadn't started that driver yet. So whether the test runs depends on how xdist schedules it, in this job and in the daily run it was written for, and the PR description's "the daily test, on all three axes" pass holds only for a worker with no driver open.

Taking the suite's shared browser fixes it. The suggestions use browser.unwatched, which skips WatchedBrowser's per-page instrumentation so it doesn't count toward the measured CPU.

Everything else holds up. The tail completion is held to the server's whole answer by state-tail.test.mjs. earlier() re-derives work because PageRead.through builds a new instance, and the extra projection is small next to the rest of an answer. The focused model tests (test_model_folds, test_interact_document, test_recorded_state) and pnpm run test:runtime pass on the merged tree.

Comment thread tests/journeys/test_scaling.py Resolved
Comment thread tests/journeys/test_scaling.py Resolved
…browser tests

On #5271's `test` job, `test_scaling.py[threads]` failed with "It looks like you are
using Playwright Sync API inside the asyncio loop". The test started its own driver
through `leaf_dev.browser.headless_shell`, and that worker already held the suite's
driver (`_playwright`, "the one Playwright driver a worker may hold") from an
earlier browser test. Running a pins test and then the scaling test on one worker
fails the same way in 3 s.

The test now measures on the `browser` fixture, so its pages are also checked for
browser errors like every other journey's. The same pair of tests now passes.
@max-sixty
max-sixty merged commit 13f885f into main Nov 4, 2026
4 checks passed
@max-sixty
max-sixty deleted the quadratic-audit branch November 4, 2026 01:23
max-sixty added a commit that referenced this pull request Nov 4, 2026
…anged (#5307)

A click on a page with many threads now costs about what the click
changed. On the `threads` page of `leaf-dev scaling` at 512 threads,
main against this branch in one unprofiled run:

| | main | this branch |
|---|---|---|
| click, main-thread CPU | 269 ms | 74 ms |
| growth exponent of the click | 1.87 | 0.56 |
| bytes per answer | 1,013 KB | 4.2 KB |

The rule this serves, from the adopted text of root `AGENTS.md`,
"Responsiveness": "work that a pass would redo for the whole page, such
as a layout, a scan of the page's controls or a derivation of every
record, runs only for the change that makes it necessary, which its
owner records when the change happens. Neither an input's work nor the
bytes it moves grows with how long the session has run."

## The server sends only what changed

The page server names each reading it serves by a digest of its content
(`browser.basis.key`) and remembers each page's last 16 readings. A tab
names the reading it holds in `Leaf-Held-Basis`; where the server
remembers it, the answer is a `Tail`: the events logged since, and a
patch of changes at paths through the reading. A list of records named
by `id`, by event id or by its own strings changes by the records it
adds, the changes inside each record it held (so one reply sends its
message and the thread fields it changed), the names it drops, and where
each new or moved record goes. A thread's `unread` versions are now a
map by message, so reading one drops one key. A restarted server, or a
key it has forgotten, answers whole.

This reverses #5271's "the server keeps no record of what each tab
holds". #5271 re-read the history at the held sequence, which was exact
because it sent everything else whole. The threads and workflows also
read the claim, the clock and the live stream, so the same log sequence
can read two ways; remembering what was served is what lets those
records travel as changes too. It also drops the second fold each answer
ran. A reading is remembered as the JSON of its records and the values
of its fields, sharing each unchanged part with the reading before:
about 1.1 MB for the first reading of a 512-thread page and 15 KB for
each later one. Captures (render checks and leaf.page's saved responses)
are neither named nor remembered.

An accepted event's answer now names the event and whether it owes the
agent an answer (`needs_reply`), which leaf.page's Worker reads to start
the hosted agent's turn, rather than reading the state.

## The browser reads again only what changed

`completeState` applies the patch to the reading the tab named, copying
only the objects on a change's path, so every record the click left
alone keeps its identity. The publisher shares the server's reading
before the folds read it, and the folds keep what they read:
`threadRecordReader` keeps each thread's record and each message's
reading, `widgetStateReader` keeps each widget's folded state, and both
use one small primitive, `kept.js`. `foldThreads` copies only the
threads a gesture touches, and `share` keeps a list item the prior list
held anywhere. A reply to a 4,096-message thread reads in 0.7 ms rather
than 7.4 ms, and the margin's workflow receipts are looked up by id
rather than by scanning every workflow per row.

## Left for later

- Each new user message rebinds every open workflow in its thread to the
newest update, so the answer to one more reply after 8 / 64 / 512
consecutive user messages is 2.5 / 5.5 / 30.2 KB. Main does the same;
the fix changes workflows' served shape.
- A changed thread is remembered whole in each reading and parsed back
to diff it: 16 readings of a 4,096-message thread hold about 25 MiB, and
the diff takes about 30 ms. Keeping a record's own lists of records,
such as a thread's messages, as named lists of their own would share
unchanged messages.
- The browser still walks the whole event history on each click: about 1
ms at 4,096 logged comments and 35 ms at 16,384 widget actions, mostly
`logCoverage` on every publication and the receipt index on adoption.
Main has the same cost.

## Checks

Four Codex reviews; the last found nothing open in this branch's code.
`pnpm run check`, the model fold, interact-contract, read-state,
interact-server and website-server tests pass. The served-records tail
cases hold the browser's completion to the server's whole answer,
including `false` then `0`, `[]` then `[""]`, an object gaining
`__proto__`, a session claiming the page, and a reply to a long thread.

> _This was written by Claude Code on behalf of max-sixty_
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.

2 participants