Skip to content

Read a page without validating its layer's registry, and load jsonschema only to validate - #5272

Merged
max-sixty merged 2 commits into
mainfrom
hook-import-speed
Nov 4, 2026
Merged

max-sixty merged 2 commits into
mainfrom
hook-import-speed

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

Every hook in a session holding a page, every fork step and every command that reads a page composed the page's layer vocabulary, and composing it validated the merged registry: a JSON Schema meta-check of each widget schema and a parse of every catalog example, 25–50 ms of each cold process, twice for a page whose revisions select different packages. That validation is why jsonschema, referencing, attrs, rpds, regress and jmespath sat on the hook path at all; moving their imports alone would have saved nothing.

Where the registry is validated

layer.compose_vocabulary, which every reader of a page uses, now merges the registries and stamps the result (registry.layer.merged_registry) and validates nothing. layer._composition, the full composition behind page init, page check, server start, export and package check, validates the registry as page init vendors it (validation.composition.incoming_registry). A page's package copy edited in place, or an installed package a stricter Leaf refuses, is then refused by page check and server start, naming the repair, while hooks and reads of the page go on, as #5059 made them for a broken sheet or module; layer-registry.md and validation.md say so. A candidate never activated, or whose own declarations differ from the active revision's, is still validated when it is read (registry.storage.read_page_registry).

Behavior that changes: a hook or read of a page whose registry stopped validating after page init reads on where it used to refuse with layer-unavailable. A registry broken in a way the stamping trips on fails the read with that error instead of the refusal.

The full composition validates the registry before it composes the vocabulary, since stamping and the widget-module check read each declaration as valid: a package declaration missing a verb's unit or a widget's x-upgrade is refused by name at page init, not with a KeyError.

registry/layer.py keeps the composition, merging and stamping; the checks of a vocabulary's layer facts and declarations move to registry/validation.py, beside the orchestration that calls them.

When jsonschema loads

registry/schema.py builds its format checkers, and points jsonschema's regular expressions at regress, on first use (_checkers), so a module importing it for aware_instant or json_value pays nothing. registry.contract.same_state_definition compares two recorded definitions itself, as the browser's sameStateDefinition does, rather than through jsonschema._utils.equal, a private helper that loaded the whole library for every page read (identical results on a product of JSON values, bools, ints, floats, lists and objects). jmespath (in data_contracts), registry.validation (in registry/page.py), validation.source (in vendoring) and http.client (in the bridge's client) load in the functions that use them, and the theme catalogue is read through json_validator rather than a module-level validator.

A Stop hook on a claimed page now loads 365 modules where it loaded 454.

Evidence

Each scenario as a whole python -m leaf process (no launcher; bin/leaf adds the same overhead to both arms) on a copy of a real 71-event page claimed in a throwaway state home, base (e2369b804) and candidate interleaved in random order, each run from the same restored snapshot, 9 runs per arm. Medians of wall time; CPU time (user+sys) moved the same way.

Base This change Base This change
Load 18–33 50–75
UserPromptSubmit 202 ms 139 ms 282 ms 170 ms
PostToolBatch, status check due 212 ms 145 ms 280 ms 163 ms
PostToolBatch, nothing pending 59 ms 56 ms 76 ms 67 ms
Stop 216 ms 150 ms 294 ms 194 ms
Clerk's fork prompt (hook --fork) 259 ms 167 ms 383 ms 214 ms
Held thread's fork prompt, without the hold check 200 ms 127 ms 260 ms 151 ms
page state 276 ms 206 ms 369 ms 266 ms
thread reply --ephemeral 205 ms 167 ms 266 ms 213 ms
PreToolUse 80 ms 71 ms 96 ms 85 ms
--root 43 ms 42 ms 54 ms 52 ms

Every scenario printed the same output in both arms and left the same page log and state files, apart from a duration field and the bridge records keyed by install path.

Tests

  • test_a_package_that_stops_composing_is_refused_where_the_page_is_served gains a registry case and stamps the page first, so its page state, run as a process of its own, reads an active revision; on the base the registry case fails at that read.
  • test_a_hook_reading_a_page_it_holds_loads_no_schema_validator runs a Stop hook on a stamped, claimed page in a fresh interpreter and finds none of jsonschema, referencing, regress or jmespath loaded; it fails on the base.
  • test_init_refuses_a_declaration_the_vocabulary_would_read_unchecked holds that ordering; it fails when the full composition validates after composing the vocabulary.
  • Tests of the moved checks name registry.validation.

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

…ema only to validate

Every hook in a session holding a page, every fork step and every command
that reads a page composed the page's layer vocabulary, and composing it
validated the merged registry: a JSON Schema meta-check of each widget
schema and a parse of every catalog example, 25–50 ms of each cold
process, twice for a page whose revisions select different packages.
That validation is why jsonschema, referencing, attrs, rpds, regress and
jmespath sat on the hook path at all; moving their imports alone would
have saved nothing.

### Where the registry is validated

`layer.compose_vocabulary`, which every reader of a page uses, now merges
the registries and stamps the result (`registry.layer.merged_registry`)
and validates nothing. `layer._composition`, the full composition behind
`page init`, `page check`, `server start`, export and `package check`,
validates the registry as `page init` vendors it
(`validation.composition.incoming_registry`). A page's package copy
edited in place, or an installed package a stricter Leaf refuses, is then
refused by `page check` and `server start`, naming the repair, while hooks
and reads of the page go on, as #5059 made them for a broken sheet or
module; `layer-registry.md` and `validation.md` say so. A candidate never
activated, or whose own declarations differ from the active revision's, is
still validated when it is read (`registry.storage.read_page_registry`).

Behavior that changes: a hook or read of a page whose registry stopped
validating after `page init` reads on where it used to refuse with
`layer-unavailable`. A registry broken in a way the stamping trips on
fails the read with that error instead of the refusal.

The full composition validates the registry before it composes the
vocabulary, since stamping and the widget-module check read each
declaration as valid: a package declaration missing a verb's `unit` or a
widget's `x-upgrade` is refused by name at `page init`, not with a
`KeyError`.

`registry/layer.py` keeps the composition, merging and stamping; the
checks of a vocabulary's layer facts and declarations move to
`registry/validation.py`, beside the orchestration that calls them.

### When jsonschema loads

`registry/schema.py` builds its format checkers, and points jsonschema's
regular expressions at regress, on first use (`_checkers`), so a module
importing it for `aware_instant` or `json_value` pays nothing.
`registry.contract.same_state_definition` compares two recorded
definitions itself, as the browser's `sameStateDefinition` does, rather
than through `jsonschema._utils.equal`, a private helper that loaded the
whole library for every page read (identical results on a product of
JSON values, bools, ints, floats, lists and objects). jmespath (in
`data_contracts`), `registry.validation` (in `registry/page.py`),
`validation.source` (in `vendoring`) and `http.client` (in the bridge's
client) load in the functions that use them, and the theme catalogue is
read through `json_validator` rather than a module-level validator.

A Stop hook on a claimed page now loads 365 modules where it loaded 454.

### Evidence

Each scenario as a whole `python -m leaf` process (no launcher; `bin/leaf`
adds the same overhead to both arms) on a copy of a real 71-event page
claimed in a throwaway state home, base (`e2369b804`) and candidate
interleaved in random order, each run from the same restored snapshot, 9
runs per arm. Medians of wall time; CPU time (user+sys) moved the same way.

| | Base | This change | Base | This change |
| --- | --- | --- | --- | --- |
| Load | 18–33 | | 50–75 | |
| UserPromptSubmit | 202 ms | 139 ms | 282 ms | 170 ms |
| PostToolBatch, status check due | 212 ms | 145 ms | 280 ms | 163 ms |
| PostToolBatch, nothing pending | 59 ms | 56 ms | 76 ms | 67 ms |
| Stop | 216 ms | 150 ms | 294 ms | 194 ms |
| Clerk's fork prompt (`hook --fork`) | 259 ms | 167 ms | 383 ms | 214 ms |
| Held thread's fork prompt, without the hold check | 200 ms | 127 ms | 260 ms | 151 ms |
| `page state` | 276 ms | 206 ms | 369 ms | 266 ms |
| `thread reply --ephemeral` | 205 ms | 167 ms | 266 ms | 213 ms |
| PreToolUse | 80 ms | 71 ms | 96 ms | 85 ms |
| `--root` | 43 ms | 42 ms | 54 ms | 52 ms |

Every scenario printed the same output in both arms and left the same
page log and state files, apart from a duration field and the bridge
records keyed by install path.

### Tests

- `test_a_package_that_stops_composing_is_refused_where_the_page_is_served`
  gains a registry case and stamps the page first, so its `page state`,
  run as a process of its own, reads an active revision; on the base the
  registry case fails at that read.
- `test_a_hook_reading_a_page_it_holds_loads_no_schema_validator` runs a
  Stop hook on a stamped, claimed page in a fresh interpreter and finds
  none of jsonschema, referencing, regress or jmespath loaded; it fails on
  the base.
- `test_init_refuses_a_declaration_the_vocabulary_would_read_unchecked`
  holds that ordering; it fails when the full composition validates after
  composing the vocabulary.
- Tests of the moved checks name `registry.validation`.
@max-sixty
max-sixty merged commit cfc2385 into main Nov 4, 2026
4 checks passed
@max-sixty
max-sixty deleted the hook-import-speed branch November 4, 2026 00:54
max-sixty added a commit that referenced this pull request Nov 4, 2026
#5272 made `registry.schema` cheap to import, loading jsonschema only to
validate, and moved `themes` onto `json_validator` itself. Both conflicts take
main's side. `aware_instant` stays in `registry.schema`, its home on main: this
branch had moved it to `state.py` only because importing `registry.schema` used
to load the schema engine. `interaction_log.interaction_time` and the Codex
transcript check now import it from there, and `sample_content`,
`served_state.queues` and `user_views` keep main's imports.
max-sixty added a commit that referenced this pull request Nov 4, 2026
…d titles (#5293)

Part of the 2026-11-03 sweep for duplicate implementations (#5291
changes how review and Tend look for them). Each question below was
answered in more than one place in `src/leaf/`, `hooks/` or the dev
commands, and the copies had drifted; each now has one home that every
caller uses.

- **Thread title limit.** `registry.kernel.title_limit()` reads the
kernel registry's `maxLength` on the `thread_title` event's `title`, and
`thread.fit_title` is the one fit: it collapses whitespace and cuts at a
word, ending in an ellipsis. The clerk and the page server's generated
titles (`thread_titles.write_title`) both use it, and the CLI's
`--title` help and `events.md` take the number from it. The six registry
copies of the title schema stay inline: no kind's record refers to
another's by `$ref`, and the protocol baseline compares a reference by
its text.
- **Path locks.** `locations.path_lock(*paths)` holds one lock per
`path_lock_key` under `/tmp/leaf-path-locks-<uid>`, taken in sorted
order. `package_write_lock` and file-binding saves both use it.
- **Initialized pages.** `event_log.initialized(page_dir)` says whether
a page's log is a file. The CLI's page argument, `page init`, reconnect
advice, `owned_pages`, the package gate, command timing and the dev
commands call it.
- **Log parse.** `event_log._stored_events` is the one parse of the log
(torn lines, seq by line number). `interaction_log.read_interactions`
reads through `read_stored_events` instead of splitting the log itself,
and each semantic row's `event` carries its `seq` in place of a separate
`event_seq`.
- **Claims directory.** `state.claims_home()` is the resolved `claims/`
that `service.claim_path`, `session_claims`, `standing_claims` and the
watch read.
- **Lock loop.** `state.flocked_descriptor(path, flags)` is the one loop
that locks, checks the path still names the file, retries, and unlocks
before closing; `flocked` and `leases.page_locked` use it.
- **Timestamps.** `interaction_log.interaction_time` and the Codex
transcript check parse Leaf's date-time format with
`registry.schema.aware_instant` instead of their own parsers; since
#5272, importing `registry.schema` no longer loads jsonschema.
- **Hook words.** `hooks/claude-code.ts` can import neither a Python
constant nor the page's modules, so its copies stay, and its tests now
hold them to their homes: the module test and the claude-code journey
read `harness.NUDGE_WORDS` and `reply_phases.LEAF_WAKE`. The band words'
comment no longer claims they are an All pages row's.

Behavior changes:

- A generated thread title over 80 characters, or broken over lines, was
refused at admission and left its thread untitled. It is now fitted and
written.
- A save to a bound file used to lock under `state_home()/files`, keyed
by the path as stored. It now locks in the machine-local directory,
keyed by the resolved path, case-folded on a case-insensitive volume, so
two Leafs with different state homes serialize their saves of one file.
The eval sandbox allows the new lock directory's name.
- A directory holding `events.jsonl` but no `layer.json` now counts as a
page for the package gate, so its page-owned paths are protected.
- A watch with no session used the unresolved claims directory, so on a
state home under a symlink, such as one in `/tmp` on macOS, it never
matched change notifications, which name resolved paths. It now does.
- `flocked` flushes what a block wrote before releasing the lock, and a
descriptor that lost its path is unlocked before it is closed.
- `page interactions --since` and `--until` refuse a time without the
`T` separator, as the format does.

Tests: `test_thread_titles` adds a generated title that is fitted rather
than refused, which failed before this change. `test_clerk`'s title test
drives a long title through the clerk's answer instead of the private
helper. `test_file_bindings` finds the save's lock under `PATH_LOCKS`,
and the package-lock journey observes `locations.flocked`.

> _This was written by Claude Code on behalf of max-sixty_
max-sixty added a commit that referenced this pull request Nov 4, 2026
…nd keep the caller's directory off its module path (#5304)

Two changes to Leaf's short-lived processes: tests that keep heavy
imports from returning to the hook path, and a fix that stops a
`leaf.py` in the agent's working directory from replacing Leaf.

### Each short-lived process has a dependency allowlist

Four tests each kept a hand-written list of modules a hook must not
import, so a dependency nobody listed, or one loaded through a new path,
crept onto the hook path unseen, as schema validation on every page read
did until #5272. Each kind of short-lived process now has an allowlist
of the runtime dependencies (`[project.dependencies]`) it may load, in
`tests/interact_support.py`:

- `EVERY_TURN_DEPENDENCIES` (click): a hook in a session holding no
page, `import leaf.hook_transport`, and a Codex tool hook with nothing
to offer.
- `READING_DEPENDENCIES` adds the markup, URL and Markdown parsers and
psutil: a Stop hook reading the page its session holds.
- `ADMITTING_DEPENDENCIES` adds jsonschema, referencing and regress: a
prompt hook delivering a comment, and `thread reply`, which match
handling clauses and admit events.

A test runs the process in a fresh interpreter (`fresh_imports`) and
fails on any runtime dependency outside its list, naming the chain of
Leaf lines that first imported it. Matching dependency names rather than
counting modules keeps the tests stable under refactors and Python
upgrades. The runtime dependencies come from the installed package's
metadata, so the tests keep no copy of `pyproject.toml`'s list. The
no-page test keeps its list of Leaf's own modules that page reading and
serving would pull in, since the allowlists cover dependencies only.

Planting `import jsonschema` at the top of `hook_transport` fails the
transport and Stop cases. Putting validation back on page reads fails
the Stop, prompt and reply cases, naming `leaf/layer.py ->
leaf/validation/composition.py -> leaf/registry/validation.py`.

### Leaf no longer imports from the caller's working directory

`bin/leaf` ran `uv run ... python -m leaf`, and `-m` puts the working
directory first on the module path. A hook runs in the agent's project,
so a `leaf.py` there ran in place of Leaf's hook, and the hook's exit
reported whatever that file did; Codex's review found it. Both launches
now pass `-P`, Python's flag for leaving that directory off the path.
`interaction_log.launched`, which recognises the launcher's uv by its
arguments, expects the flag, as do the two tests that state the
launcher's whole `uv run` command. The claimed-session test in
`tests/process/test_hook_gate.py` now runs its hooks from a directory
holding a `leaf.py` that exits with an error, and fails without `-P`.

A new test, `test_a_terminated_pages_follower_exits_with_its_signal`,
stops the pages follower through the real launcher with SIGTERM and
expects exit 143, which Leaf's Claude Code module reads as an ending
from outside rather than a failure to show the user.

### Tried and dropped

This branch first ran a claimed session's gated hooks without `uv run`,
first by continuing inside the claim gate's `-S` interpreter, then by
running `.venv/bin/python` behind a record of the lock files as of the
last sync. Medians at load 37–46: claimed hooks took 172 ms through uv,
146–151 ms on the venv's interpreter and 130–133 ms in-process. Both
versions were dropped. The saving, about 16 ms idle and 25 ms loaded per
claimed hook, didn't pay for interpreter tricks or for a second check of
environment freshness beside uv's. #5246 holds the change that would
remove most of a hook's cost, a resident process, now parked with the
`etc` label.

### Testing

The focused modules pass: `test_hook_gate`, `test_hook_registration`,
`test_codex_adapter`, `test_interact_claude_code_module`,
`test_session_lifecycle` and `test_interaction_log`, and
`test_interact_layer`'s shim dispatch test.

> _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