Skip to content

Send a click only the records it changed, and read again only what changed - #5307

Merged
max-sixty merged 11 commits into
mainfrom
agent-ad01ba32f5447933a
Nov 4, 2026
Merged

max-sixty merged 11 commits into
mainfrom
agent-ad01ba32f5447933a

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

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

A click on a page with 512 threads was answered with about 1 MB: the
history tail (#5271) left out the log and projection entries the tab
held, but every thread, workflow, obligation and On row came whole, and
the browser compared all of it again before adopting it. The answer
grew with the page, not with the click.

The page server now names each reading it serves by a digest of its
content (`browser.basis.key`) and remembers its last 16 readings. A
request naming one it remembers gets a `Tail`: the changes from that
reading, each at a path through its objects, with a named list (by
`id`, by event id, or strings) changed by the records it adds or
changes, the names it drops, and where each new or moved record goes.
The events after the held reading come as before, and the data keeps
its own version mechanism. The browser applies the changes to the
reading it named (`completeState`), copying only the objects on a
change's path, so every record the click left alone keeps the identity
it had, which is what lets the publisher skip it.

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 among
them, which also read the claim, the live stream and the clock, so the
same sequence can read two ways. Remembering what it served is what
lets those records travel as changes too; it also drops the second fold
each answer ran. A server that restarted, or a key it has forgotten,
answers whole, as before.

On the `threads` page at 512 threads a click's answer goes from 930 KB
to 4 KB; naming and diffing a reading costs the server about 9 ms
there, about what the second fold cost. `leaf page state`, exports and
published states are unchanged apart from carrying no key.
Every publication read every thread's record anew, and a click
publishes five times: the gesture, its POST's answer, the reading, and
the two steps that retire the gesture. Each reading also filtered every
workflow, obligation and to-do once per thread and per message, so on a
page of 512 threads one publication spent about 7 ms in
`readThreadRecords` and 4 ms more comparing the fresh records with the
last ones before it could keep them.

`threadRecordReader` now keeps each thread's record beside what it was
read from: the served thread, its workflows, obligations, to-dos and
unread versions, and its messages' workflows, words and frozen widgets'
state. A thread whose inputs are the very ones it read last keeps the
very record, which the publisher shares without comparing. The lists a
thread reads are grouped once per reading rather than filtered per
thread.

That holds because the inputs keep their identity when unchanged: the
publisher now shares the server's reading against the root before the
folds read it, so a record the answer left alone is the root's own
(the previous commit keeps it so in the answer itself); `foldThreads`
copies only the threads a gesture stands in rather than every thread;
and sharing a list keeps an item the prior list held anywhere, so a
record that moved because another was added before it is compared by
identity rather than by its contents.
Each refresh of the annotation inventory asked, for every row and twice
more for every group, which of its receipts was a workflow still in
progress by filtering every workflow on the page, so a click on a page
of 512 threads spent 13 to 26 ms there. `workflowReceipt` now looks each
receipt up by id in a selection of the workflows in progress, in their
published order, so the strongest is still the server's.

Also leave `release` out of the `Tail` schema, since the website adds it
to the reading before the server diffs it and so it rides in the patch;
build the published order a message's workflows sort by only for a
message that holds frozen widgets; and say in `thread/model.js` that a
reading still checks each kept record's inputs by identity.
The website's Worker decides whether an accepted event owes the hosted
agent a turn by finding the event's update obligation in the answer's
`activity.obligations`. Since the server answers a tab that names its
reading with only the changes since (`served_state/tail.py`), that list
no longer comes whole, and reading it threw, so no event would have
dispatched the agent. A new update is new since any reading the tab
held, so the Worker now finds it among the changes: in the list's
changed items, or in a value set at or above it.
…ts answer

A reply sent its whole thread back: the tail sent each changed record
whole, so one short reply answered 12.1, 38.6 and 144.7 KB after 8, 32
and 128 earlier replies. A record the held reading had is now patched
from within, by the same changes at paths from its own root, so a
thread one reply joined comes as that message and the thread fields it
changed. The browser applies them to the held record, which keeps every
other message the very object it was. That answer is now 2.6, 3.3 and
6.1 KB. What still grows is a fact of the reading itself: each of the
thread's earlier inputs' workflows now names the newest update, about
35 bytes each.

The server remembers each reading as the JSON of its parts, sharing one
copy with the reading before it wherever a part is unchanged, rather
than as a digest per record, so it can diff a changed record's fields.
The module header now says why it remembers at all: #5271 re-read the
history at the held sequence and kept no record of what each tab holds,
which was exact because it sent the claim-, clock- and stream-dependent
threads and workflows whole; remembering is what lets those travel as
changes too, and it reverses that statement.

A capture's readings, which a render check reads and leaf.page saves as
a published page's responses, one per revision, are no longer named or
remembered. Saving a page with more than 16 revisions pushed every tab's
reading out, so every answer after it was whole.

An accepted event's answer now names the event the log holds for it
and whether it owes the agent an answer (`needs_reply`, read from the
whole reading before it is cut to changes). leaf.page's Worker starts
the hosted agent's turn from that rather than parsing the state's
changes, which the previous commit had it do; the door takes no state
reader, and its callers that passed `dict` pass nothing.

`completeState` also keeps the held log when no event arrived, rather
than copying it on every answer.
…read changed

Updating one long thread read every message of it again, and each
message's reactions filtered the whole thread, so a reply to a thread
of 4,096 messages took about 16.8 million visits (7.4 ms in Node). The
thread reader now finds the agent's latest addressable message once and
groups the user's reactions by the message they answer, and keeps each
message's reading, and its reading with reactions, beside what it read.
A reply reads its own message and the one whose `latest` it moves:
0.7 ms at 4,096 messages.

A thread whose own inputs are unchanged keeps its record without
visiting its messages: its inputs now name the frozen widgets' state by
thread rather than each message's words and widgets, since a message's
captured words are prepared from the message itself and a workflow
stands in its message's thread.

`foldWidgetStates` cloned every widget's authored state on every
publication, so a frozen widget's state was a new object each time and
the thread inputs had to serialize it to compare. `widgetStateReader`
now keeps each widget's state where its authored state and the entries
in force on it are the same objects, which also spares the publisher
comparing every widget's state on the `asks` page.

Both readers, and the thread records before them, share one mechanism,
`kept.js`: a reading keyed by record that makes a record again only
where an input changed by identity. The pure folds may import it.
Naming a reading walked all of it a second time to hash it, encoding
each field and each record's name again, and remembered every string of
a list of names, such as a thread's memberships or the updates the
agent owes, as JSON of its own. Each object and list of records now
carries its digest, which an unchanged part keeps from the reading
before, so naming hashes only what changed; a field holding a scalar is
kept as itself, and a list of strings as its strings.

At 512 threads naming a reading and its changes takes about twice one
`json.dumps` of the reading. The first reading a process remembers holds
about 1.1 MB, and each later one about 15 KB, the parts that changed.
…d remember each page apart

A change inside a record from `false` to `0` never reached the tab. The
tail compared a remembered reading's parts by their JSON but a changed
record's fields with Python's `==`, which takes `False` for `0` and `1`
for `1.0`, so the patch left the field out while the tab adopted the
new key. There is now one comparison, the bytes each part contributes
to its holder's digest, and a changed record is diffed through the same
parts as the reading, which deletes the second, value-level diff. The
served-records tail cases gain `false, then 0`, which fails without
this.

A thread's `unread` was a list of `{message, version}`, which no name
keys, so reading one of 512 unread replies resent the other 511 (20.9
KB). It is now each message's unread content version by message id, so
reading one drops one key: about 660 bytes however many are unread. The
browser's thread records keep listing them, in their messages' order,
for every surface that reads them; semantic news reads the map
directly, which also stops it searching every message per unread one.
`leaf page state` still lists unread message ids.

Applying a list change placed each new or moved record with `indexOf`
and `splice`, so reversing 16,384 records took 889 ms. It now links each
placed record after the one it names and walks the list once: 0.4, 1.6
and 4.7 ms at 1,024, 4,096 and 16,384.

The 16 remembered readings were shared by every page a process serves,
so a multiplexed server's other pages, or a page's live samples, pushed
out the reading a tab held. Each page now keeps its own 16, for the 8
pages served most recently.
…field, and read one thread per acknowledgement

A revision update under a page root lost its prefix: the server named
and diffed the reading before addressing its URLs at the root, and the
addressing only rewrites a field called `url`, which a patch carries
under `value`. Under leaf.page's `/examples/…` or a live sample, the tab
completed `active.url` as `/revisions/…` and loaded the wrong route.
The reading is now addressed before it is named and compared, so the
patch carries the addressed URLs, and the answer goes out as it stands
rather than being addressed again, which would address its markup
twice.

A list of strings was digested as its members joined by NUL, so `[]`
and `[""]`, or `["a\u0000b"]` and `["a", "b"]`, read as the same, and a
widget answer moving from one to the other never reached the tab. Such
a list now carries its JSON, which the digest and the comparison read.

Applying a patch assigned each field, so a field named `__proto__` set
the object's prototype rather than its own field. The patch now defines
own fields through `defineOwn`, the helper `share` already used for the
same reason, now exported from the framework facade.

Every thread with something unread depended on the whole list of
versions this tab is marking read, so acknowledging one thread read
every unread thread's record again. Each now depends only on the
acknowledgements of its own unread messages.

Each is held by a test that fails without its fix: tail cases for `[]`
then `[""]` and for an object gaining `__proto__`, a website route test
under `/examples/decision`, and a thread reader test.
Addressing the whole reading at the page root before naming it also
addressed the whole log, so on a hosted page, an example or a live
sample every click parsed the markup of every message the session had
logged, to send one new event: 1,536 parses where main made 1,024 with
512 markup messages. The log travels apart from the reading, as the
events after the held one, so the reading is addressed before it is
named and compared, and only the events the answer sends after.

A website route test counts the parses: an answer naming the held
reading parses one fewer for each markup message in the log than the
whole answer does, where before the fix both parsed the same.
# Conflicts:
#	dist/kernel/kernel.json
#	dist/kernel/runtime/bundle-errors.js
#	dist/kernel/runtime/bundle-layer-client.js
#	dist/kernel/runtime/bundle-page-layout.js
@max-sixty
max-sixty merged commit 5423c81 into main Nov 4, 2026
4 checks passed
@max-sixty
max-sixty deleted the agent-ad01ba32f5447933a branch November 4, 2026 07:16
leaf-agent added a commit that referenced this pull request Nov 4, 2026
… state answers (#5321)

`test_a_failed_state_keeps_focus_in_the_open_versions_menu` had two
separate causes of failure, and this PR fixes both. Four other tests in
`test_render_pages.py` had the second cause and now get past it too.

- **The keyboard landing (#5039).** `g Shift+V` now focuses the Versions
view's first version, as #5039 made every view a key opens do ("the
Versions view's tests expected `g V` from the page to focus the view,
and now expect its first version"). The test still expected the
container to take focus and then pressed ArrowDown, so it failed at line
601. This takes the prior session's preserved commit from
`fix/versions-rollback-focus`: it removes those two lines and keeps the
check that the focused row survives the failed reading.
- **Partial state answers (#5307).** A tab now sends the reading it
holds in `Leaf-Held-Basis`, and the server replies with a `Tail` patch
instead of the whole reading. The tests that corrupt a state answer
append to
`state["browser"]["views"][…]["document"]["projection"]["entries"]`,
which a `Tail` doesn't have. Each handler raised `KeyError: 'browser'`,
so the page never logged the "read failed" the test waits for. The new
`fetch_whole_state` helper in `tests/render_harness.py` drops that
header, so the server sends the whole reading and the handler can
corrupt it as before. All five handlers now use it.

Neither change touches product code.

### Verification

Run locally with `uv run pytest`:

| Test | Current `main` | This branch |
|---|---|---|
| `test_a_failed_state_keeps_focus_in_the_open_versions_menu` | fails at
line 601 (Versions container inactive) | passes |
| `test_a_failed_agent_root_restores_the_focused_first_message_composer`
(2 cases) | `KeyError: 'browser'`, console wait times out | passes |
| `test_a_reply_notice_survives_a_failed_state_and_keeps_its_agent` |
`KeyError: 'browser'` | passes |
| `test_a_failed_resolution_restores_a_focused_inline_reply`,
`test_failed_resolve_candidate_restores_focused_reply` | `KeyError:
'browser'` | get past the handler, then fail expecting `Resolved` where
the page shows `1 new`. That separate cause is tracked in #5128. |

`test_render_floating_panel.py`'s `aged_state` also rewrites a state
answer (`state["now"]`). It doesn't index `browser`, and I didn't check
whether a `Tail` carries `now`, so it is unchanged here.

Closes #5191 — automated triage

---------

Co-authored-by: leaf-agent <[email protected]>
max-sixty added a commit that referenced this pull request Nov 4, 2026
…reaming reply hold no place

From the automated review of #5320:

- Every message the user had sent went into each view's undo list, so the
  list grew with the conversation, the panel's answered rows searched it
  once each, and their Undo could take back an older reply. A message with
  words is now listed only while it is the user's newest gesture, which is
  all `z` reaches; an older one is deleted by rewriting it to no words.
- The press's fold counted a reply still streaming as something standing
  on the message it answers, which the log can't, so taking that message
  back drew Deleted where the server's reading then removed it.
  `standingIn` skips provisional replies.

The candidate test now fetches the whole reading: since #5307 the held
request names the tab's reading and gets only the changes, which has no
`browser` key, and the test fails the same way on main.
leaf-agent added a commit that referenced this pull request Nov 4, 2026
…d state answers and deferred fault reports (#5334)

Every test in #5070 fails on main because three merged changes moved
contracts these tests still read the old way. Each repair updates only
the test, to the behavior its change intended. None moves product
behavior.

- **Control+Alt+r never pressed Latest (14 tests, plus the journey in
#5070's comment).** The test page's script listens for Control+Alt+r on
`window` and clicks the panel's Latest row notice. #5037 stops keys
typed into a Leaf field at the field so a page's bubble listeners never
hear them; its contract (`field-keys.js`) keeps capture listeners
hearing them. With an editor focused, the hook never ran, the revision
stayed deferred behind the composition, and `wait_for_revision(page, 2)`
timed out. The hook now listens in capture. Bisect: the composer case
passes at `1c38e1070` and times out at `8a4e213d0` (#5037).
-
**`test_a_mechanical_revision_failure_leaves_accepted_publication_ready`.**
It began as `StopIteration`, from the same missing press. With the press
fixed, it raised `KeyError: 'reading'`, because #5307 answers a tab that
names its held reading with a patch. The test now reads the new
reading's name from the patch's `["reading"]` change.
-
**`test_a_fresh_revision_caret_failure_does_not_strand_deferred_arrivals`.**
This one had a separate cause and was failing before #5037 with `assert
([])`. Bisecting over `7c1e4494ac..9a142d1` points to #4966, which
reports a fault in the next task. The test took the errors as soon as
the revision installed, so it now waits for the report with
`reported_browser_errors`.

Verification: all 16 tests listed in #5070 and
`tests/journeys/test_render_drafts.py::test_executable_revision_does_not_restore_a_new_draft_generation`
pass locally on this head (29 passed across `test_revisions.py` and the
two named tests). Before the change, the composer case failed on main
after its 120 s timeout.

Closes #5070 — automated triage

Co-authored-by: leaf-agent <[email protected]>
max-sixty added a commit that referenced this pull request Nov 4, 2026
…ne with it (#5320)

Undo no longer depends on whether the agent has seen a gesture or
answered it, and it now reaches the messages the user sends (the user's
decisions, 3 November 2026).

- `z` works the same before and after the agent reads a gesture. Before
this change, once a delivery had handed a gesture to the agent, the
first press only showed it, wherever it stood. Now only whether the user
can see the gesture's place decides that.
- A reaction can be taken back after something has answered it, and
after its thread is resolved.
- A comment or reply with words can be taken back too. This reverses the
26 August rule that a message with words is "said rather than unsaid".
`z` reaches a message only while it is the user's newest gesture, which
is also the only time the served undo list holds one, so no other
control can take back an older message. To delete an older message, the
user still saves it empty in the editor, and `z` can take that deletion
back.

## What taking a message back leaves

- If something stands on the message (a reply naming it, or a to-do
attached to its thread), it stays in place and reads Deleted.
`withdrawn.was` holds the words or mark it was sent with. Otherwise the
message leaves every reading, and a comment takes its thread with it.
- It is no longer a turn. Nothing is owed to it, it doesn't reopen its
thread, and its rewrites don't ask for answers. A new edit of it is
refused (`withdrawn-message`).
- Whatever the agent's answer settled stays settled. Before, settlement
looked only at the messages a thread still shows. Now `build_threads`
keeps a server-only history of every turn said in a thread and every
undo of one, and `events.settled_through` replays it. A turn taken back
before the answer drops out of the answer's batch, along with its
rewrites. One taken back after the answer leaves the batch settled.
`unanswered_turns` and the failed-answer rule in `workflows` both read
this. It also fixes an older bug: taking back an answered rewrite, or a
reaction an answer stands on, used to make the turns before it owed
again.
- A summary with prose is retired when a message it may report is taken
back.

`$events.protocol` goes to 41, one above main's 40, since a Leaf at 40
would refuse or crash on the new log.

## Where to look

- `src/leaf/events.py`: `UndoReading` (comments and replies are now
`undoable` in the kernel registry, so it has no special case for
messages), `build_threads`, `message_reading`, `settled_through`,
`unanswered_turns`.
- `browser/runtime/thread/model.js`: on the press, draws only that the
message's words or mark go. A message with words keeps its place as
Deleted until the server's reading says whether anything stands on it,
so one nothing answered reads Deleted for that moment and then goes.
`browser/runtime/undo.js`: names a message ("replied “…”", "commented
“…”") and shows it on the message itself.
- `src/leaf/events.md`, "Undo": the contract.

## Testing

- Model tests cover each case: the placeholder and its words, a rewrite
made before the withdrawal, the thread staying resolved, and nine
settlement sequences; each fix was checked by reverting it and watching
its case fail. They also cover a failed answer that comes back after an
unanswered retry is taken back.
- Runtime tests check what the press draws, and that it matches the
served reading where the message was answered.
- Browser tests check that `z` takes back a sent reply, and an answered
reaction, including the Deleted row in the press.
- Codex reviewed the change in five rounds; each round's findings are
fixed here.
-
`test_undo_waits_while_the_candidate_is_applying_then_reads_accepted_truth`
now fetches the whole reading. Since #5307, its held request gets only
the changes, which have no `browser` key, and the test fails the same
way on main.
- Not run: `leaf-dev journey`. Nothing yet checks that a real agent
undoes its own work when the user takes back a message it acted on.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Nov 5, 2026
…the page asks only for a reading it lacks (#5453)

An agent revises a page by saving `index.html` and then running `leaf
page stamp`. On main, each revision cost the open tab 3.4 state reads on
the corpus page, when two carry everything: one for the revision and one
for the stamp. Each extra read re-sent a reading the tab already had,
and held the page's log lock while the server built it. With this change
a revision costs two reads.

## Measured

`leaf-dev bench-latency --page corpus`, main (`3adac4668`) against this
branch at `6d3f8141d`. The runs were traced in the browser, and every
hold of the page's log lock was recorded on the server. 20 revisions per
arm, in four batches on 2026-11-05 between 00:08 and 00:32 PT, at a
one-minute load of 14–42. The commits after that change only what the
clock does after a failed read, which these runs never hit, and one
test, and merge main.

| per revision | main | this branch |
|---|---|---|
| state reads | 3.4 (3–4) | 2.0 (2 in every run) |
| state bytes, median | 184 KB | 87 KB |
| log-lock time in state reads and activation, median | 510 ms | 426 ms
|

- **Lock time:** main made 28 extra reads, each holding the log lock
17–303 ms (median 50), about 105 ms per revision. The source check
itself, about 400 ms, now runs in the news look that first sees the
save, instead of in the first state read.
- **Gestures:** over 20 comments and 20 card moves per arm, main read
again after 4 comments. This branch read again after 1 move. The trace's
timing suggests the look heard the gesture's news just as the gesture's
own answer arrived.
- **Startup** (`leaf-dev probe corpus --base`, `3adac4668` against
`288f7b7d3`, three rounds): by the time the page first shows the
server's state, both arms have made 527 requests (528 in one round of
main's). This branch loads 2,627 more bytes, all of it the larger
`state-feed.js` and `state-application.js` source modules.

## The server: news takes its token the way a state read does

`/api/news` stamped the page's files before activating a saved source.
`/api/state` activated it first, which writes the revision, and then
stamped. So after every save, the look named one reading and the state
read answered with another, and the next look asked again for the
reading the tab had just been handed.

Both now take their token through `LivePage._activated`: activate, then
stamp.
- **State read:** passes the transaction it holds.
- **News look:** stamps the page once under the log's lease
(`reading.page_readings`, which also gives the `source_readings` of
those stamps). If the held activation covers them
(`revisioning.held_activation`), it returns them, since activating would
change nothing they name. Otherwise it takes the transaction, activates
and stamps again.

A look at an unchanged page costs what it did on main: 1.35 ms against
1.40 ms on a built corpus page.

## The browser: compare news with the reading in hand

The look and the 2 s clock compared the news token with
`runtime.reading`, which moves only once an answer is adopted. A
revision's answer takes seconds to prepare on the corpus, so a look or
tick in that window asked again for a reading the page already had.

- **The reading in hand:** `state-application.js` keeps every answer
handed to `receiveState`, through any door, until its application
settles. `stateInHand()` returns the newest of those and the adopted
state, by when the server took it. The look asks only when the news
names a reading other than that one.
- **The read slot's queue:** it records which news a trailing read is
for. When the slot is given back, the trailing read is skipped if the
answer just handed in already names that news. A read the clock started
before a save can wait out the save's activation and answer with its
revision.
- **The clock:** it asks only with no read in flight, and only for one
of three reasons:
  - a failed read;
  - an activity transition the state in hand says has come due;
- the last look heard news naming another reading than the one the page
still holds.

It still needs that last check: a dropped answer leaves the page behind
the news with no change in the news.

## Calls you may reverse

- **`state_read` drops `with_token`** and always takes the token. A
comparison view (`/api/view`) now stamps the page's files once more than
before, and
`test_comparison_revision_reads_stay_inside_the_page_transaction` no
longer asserts that it doesn't.
- **A browser test #5307 broke is fixed here.**
`test_a_presence_read_crossing_freshness_returns_to_the_current_lease`
failed on main with `KeyError: 'listening'`, because its route read
`listening` from what is now a patch. It now asks for a whole answer,
and passes. Its page is unclaimed, so the lease it takes moves the files
part of the token, and the look repairs the crossing without the clock.
- **One rare extra read is left.** News shares one presence observation
for 2 s, while a state read observes presence afresh. On a claimed page,
a state read that catches a short-lived lease names a reading the news
never names, and the clock reads again on each tick until the news
observation expires, about 2 s. Letting the state read write its
observation into the news cache would remove it, but would delete
nothing, since dropped answers still need the clock.

## Not in this change

On the corpus page, a revision read straight after a reload was a whole
186 KB answer rather than a patch, in revision-only runs at `ecf4dc10d`,
even though the request carried `Leaf-Held-Basis`. The likely cause,
from a count and the code rather than a direct test: the page's 21 live
samples read state between the reload and the revision, and
`served_state/tail.py` remembers readings for only 8 pages (`PAGES`), so
the page's own reading is gone by then.

## Checks

On the branch merged with main at `7607555fc`:
- `pnpm run check` passes, including the 811 runtime tests and 88 Worker
tests.
- 105 Python tests on activation, readings, news and state answers pass,
by `-k` selection.
- 34 browser tests that read the news route or count state reads pass,
by node id.

Each new runtime and Python assertion fails on main's code.
`receiveState`'s in-hand bookkeeping has no unit test of its own: the
runtime test's feed stub models it, and the gesture counts above check
it end to end.

`test_status_changes_coalesce_behind_one_state_read` expected a trailing
read after an answer that already named the latest news, which is the
read this change removes. It now fulfils the first read with an answer
taken before the later writes, so the burst still queues one trailing
read.

Three browser tests fail here and fail the same way with this branch's
runtime and server files set back to `3adac4668`, so this change doesn't
cause them. A search found no open issue or pull request for them:
- `test_required_page_failure_retains_composer_seat_focus_and_caret`
- `test_a_reload_mid_flight_never_wedges_round_trip`
- `test_an_accepted_event_is_not_retried_when_its_state_cannot_render`

> _This was written by Claude Code on behalf of max-sixty_
leaf-agent added a commit that referenced this pull request Nov 5, 2026
…#5307 broke (#5520)

Six browser tests have failed on main since #5307 (`5423c8110`). None of
them caught a regression; each still expected the server's old answer
shape. #5307 meant for a tab that names its held reading in
`Leaf-Held-Basis` to receive only a patch against it
(`served_state.tail`), and for event answers to go out through
`_json_body` rather than `_json`. This PR keeps both of those and
updates the tests.

- Five tests read `reading` or `taken` straight off an event or state
answer. That answer is now a patch, so their route handler raised
`KeyError` and never fulfilled the request. The tests then waited out a
console message that never came, or hit `KeyError: 'taken'`. They now
fetch through the harness's existing `fetch_whole_state`, which drops
`Leaf-Held-Basis` so the server answers whole. #5321 used the same fix
for the tests #5307's predecessor broke. The helper now also passes
`Route.fetch` overrides, which the read-state test needs for its
rewritten `post_data`. One outbox test had inlined the same header
strip, and it now calls the helper too.
- `test_a_reload_mid_flight_never_wedges_round_trip` held the first
event answer by patching `PageEndpoint._json`, which that answer no
longer passes through. It now patches `_json_body`.

No product code changes. With `uv run pytest --run-main`, each of the
six fails on `be273426d` and passes on this branch, along with
`test_undo_waits_while_the_candidate_is_applying_then_reads_accepted_truth`,
which now uses the helper. The read-state and undo tests also pass after
rebasing onto `a6fefaa77`.

Closes #5477 — automated triage

Co-authored-by: leaf-agent <[email protected]>
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