Skip to content

refactor(lynx): make validation a checked|trusted policy and delete the walk the boundary replaced - #165

Merged
Huxpro merged 4 commits into
new-lynxfrom
feat/lynx-validation-policy
Aug 26, 2026
Merged

Huxpro merged 4 commits into
new-lynxfrom
feat/lynx-validation-policy

Conversation

@Huxpro

@Huxpro Huxpro commented Aug 24, 2026

Copy link
Copy Markdown
Owner

Summary

Issue #156, slice 2. Validation stops being a fixed cost and becomes a policy,
and the integrity walk that slice 1 made unreachable is deleted rather than left
as decoration.

Stacked on #164 (slice 1), so this diff is slice 2 alone. It retargets to
new-lynx when #164 merges.

The deletion. Every message reaching a validator is now JSON.parse output.
JSON.parse output cannot have symbol keys, non-enumerable properties,
accessors, a foreign prototype, sparse holes, or cycles — so the branches that
refused those could not be taken. That is not a weaker check being removed; it
is a claim about where safety comes from that stopped being true. Safety comes
from the boundary now. What remains is schema.

  • record() goes from ~35 lines to 8: no cross-realm prototype probe, no symbol
    scan, no Reflect.ownKeys reconciliation.
  • assertWireValue loses the per-descent Set, the try/finally that unwound
    it, the symbol check, the dense-array own-name count, and the per-index
    descriptor triple.
  • assertTemplateArray is Array.isArray. assertTemplateScalarValues reads
    slots by index, retiring templateScalarIndexKey, its cache, and
    MAX_CACHED_TEMPLATE_SCALAR_INDEX.
  • commandRecord uses Object.keys and breaks out of the ordered-run scan
    instead of re-deriving key order.

One bound is kept rather than dropped. The sender's own development self-check
runs before the transport encodes, where the value is still a live object graph
and a cycle is exactly what a mistaken worklet capture produces. So the walk
carries the transport codec's own LYNX_MAX_WIRE_DEPTH: one integer compare
instead of a Set operation per composite, the same number the encoder enforces
a moment later, and a message naming where it gave up rather than a bare
RangeError.

The policy. createLynxRoot and installLynxMainThread take
validation: 'checked' | 'trusted', default checked.

development build production build
checked (default) full schema walk full schema walk
trusted full schema walk envelope only

trusted says the two threads ship together and the sender is this same
package. Production then checks the envelope — protocol, renderer, root,
version, discriminant, arity — and declines the O(commands × props) walk beneath
it. The envelope stays in both modes because it decides which root a commit
belongs to and which version it answers; skipping it would not be a trust
decision but a routing bug. Development runs the full checked walk under either
mode, so drift fails loudly where it is introduced rather than silently where it
is deployed.

A spelling neither mode implements is refused on both sides of the wire, not
quietly coerced: a typo resolving to checked would look like it worked, and one
resolving to trusted would drop validation nobody asked to drop.

The page-scoped data lifecycle receiver stays checked whatever a root chooses.
__RenderPage and friends outlive any one root and carry data the app did not
author.

Nothing after validation moves. The compact completion acknowledgement,
backpressure, lifetime and fault semantics are identical under both modes, and
that is asserted rather than asserted-about: the same mount → update → teardown
runs through both modes and the whole protocol trace on each thread is compared,
alongside the rendered HTML.

Measurements

protocol.ts, base 488f704e8 → head:

base after deletion head (deletion + policy)
total lines 2095 2015 2057
non-comment, non-blank 1851 1728 1741 (−110)

The policy adds 13 code lines and 42 total; the rest of the total-line figure is
the prose explaining why each deleted check was deletable.

Bundle size, benchmarks/lynx-bundle-size/run.mjs, base and head built in the
same window on the same host. Both artifacts carry identical visible and
background semantic checksums
at base and head, so this is a size delta on
functionally equal artifacts:

target metric base head Δ
preview main gzip 85 424 85 028 −396 (−0.46%)
preview background gzip 79 329 78 890 −439 (−0.55%)
preview bundle gzip 164 725 163 839 −886 (−0.54%)
preview main raw 205 650 204 259 −1 391 (−0.68%)
preview background raw 290 011 288 079 −1 932 (−0.67%)
IFR main gzip 91 607 91 278 −329 (−0.36%)
IFR bundle gzip 170 741 169 976 −765 (−0.45%)

Both threads shrink because protocol.ts is shared, and the reduction is
present under checked too — it is smaller code on the same path, not code that
trusted tree-shakes away.

The harness's own frozen gate (NO_WORKLET_BUDGET, calibrated on upstream main
ffadd397) fails at both base and head — base 85424 > 77286, head
85028 > 77286. That staleness is pre-existing on new-lynx, which the #66/#103
line has moved well past; this PR narrows the overshoot rather than causing it,
and recalibrating that ledger is not this PR's business.

Wire bytes are unchanged: no message shape, field, or ordering is touched.

Validation

Six red verifications, each seen failing and then restored:

# deliberate break result
1 assertWireValue loses the depth cap 2 protocol.test.ts tests red (stack exhaustion, no path named)
2 lynxValidationTraverses returns true unconditionally declines only the command walk red
3 if (!traverse) return; moved above the envelope checks keeps the envelope checked red
4 mode guard removed from transport.ts + main-thread.ts 3 validation-policy tests red
5 main thread gates complete on validation !== 'trusted' both integration tests time out (15 s / 10 s)
6 undefined encoded as null instead of the sentinel 3 protocol.test.ts tests red

Run on this head:

  • pnpm format:check — ran pnpm format:files:check packages/lynx .changeset/lynx-validation-policy.md, clean
  • pnpm typecheck — ran the three lynx projects (packages/lynx/tsconfig.json, tsconfig.testing.json, typetests/tsconfig.json), all clean
  • pnpm test — ran vitest run --project lynx
  • targeted tests: --project lynx, 41 files / 579 tests green; pnpm sync exit 0 with no generated changes

Not run repo-wide: pnpm format:check, pnpm typecheck, pnpm test across all
276 workspace projects. The diff is confined to @octanejs/lynx, and the three
scoped equivalents above cover every file it touches. Per #66 §2.3 the
rspeedy-plugin native-demo test fails pre-existing in this container.

Risk / follow-ups

Deliberately out of scope, to be filed as their own PR on this train:

  • The lifecycle walk. lifecycle-data.ts (snapshotLynxLifecycleData,
    lifecycleRecordEntries, ownEnumerableDataNames) and main-thread.ts's
    lifecycleRecord/lifecycleTuple/lifecycleBooleanOption still carry the
    same now-unreachable checks — symbol scans, cross-realm prototype probes,
    descriptor reads. All five callers sit downstream of localizeLynxHostValue
    or decodeLynxTransportValue, so the branches are dead for the same reason.
    Left here because the path is cold (per page-data update, not per node),
    because Lynx transport: receiver-local JSON values, checked|trusted validation, conformance transport #156 slice 2's stated deliverable is protocol.ts, and because
    keeping it out preserves a clean protocol.ts line delta for Execution plan (#58): complete L2, then drive L4→L6 — full context handoff #66's L2 gate.

  • The codec reads accessors twice. prepare's copy-on-write returns the
    original composite when nothing needed escaping, so JSON.stringify walks it
    again and an accessor's second answer is what crosses. Documented on the
    codec rather than paid for: the receiver is handed JSON.parse output either
    way so it cannot be shown two values, and the same check would fire on every
    engine-provided composite reaching localizeLynxHostValue, where a fresh read
    is expected.

  • Per-batch memoization on the decoded receive path. lastTemplateProgram,
    validatedTemplatePrograms, validatedStaticProps and validatedTemplateShapes
    key on object identity, which JSON.parse no longer preserves across messages.
    They still work within a batch; across batches they now always miss.

Where this meets delta-protocol v2: v2 already shrinks what a commit carries, so
trusted's saving is proportionally smaller on a v2 update batch than on a
first-screen batch. The two compose — v2 reduces the number of props walked,
trusted decides whether to walk them — and neither subsumes the other.

Provenance

  • An agent produced this diff (agent-authored)

Generated by Claude Code

claude added 2 commits August 24, 2026 23:25
The receive-boundary validator refused hostile prototypes, symbol fields,
accessors, non-enumerable properties, sparse arrays and cycles. Every one of
those existed to survive a *hostile composite*: a value built on the other
thread that could answer the validator one way and the host driver another.

Since the transport owns encoding (#156 slice 1), every message reaching a
validator is `JSON.parse` output, which can express none of them. A check whose
failing branch cannot be reached is not a weaker check — it is a claim about
where safety comes from that is no longer true. Safety comes from the boundary;
what is left for these functions is schema.

Gone: `record`'s `Reflect.ownKeys` walk and descriptor triple, `assertWireValue`'s
symbol check and per-descent cycle `Set`, `assertTemplateArray`'s density count,
`assertTemplateScalarValues`'s canonical decimal-key table and per-slot
descriptor read-back, and the integrity half of `commandRecord`'s fused walk.
Slots are read as slots and keys as keys.

One bound is replaced rather than dropped. The sender's development self-check
runs on the live object graph *before* the transport encodes it, so a cycle is
still reachable there, and recursing into one gives a `RangeError` naming
nothing — worse than the report it replaced. `assertWireValue` now carries the
codec's own depth limit, which is exported for the purpose so the two cannot
disagree about which payload is carryable.

The tests that pinned each deleted check are rewritten to pin what actually
answers the question now: the boundary normalizes a hole into an explicit
`undefined`, resolves an accessor, drops a symbol field and a non-index
property, defeats an `ownKeys` proxy by walking arrays by index, and refuses a
foreign-prototype object at the sender. The codec's copy-on-write means an
accessor is read twice and its second answer travels, which is documented where
it happens and pinned where it is observable.

Co-Authored-By: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
`createLynxRoot` and `installLynxMainThread` now take
`validation: 'checked' | 'trusted'`, defaulting to `checked`. A spelling
neither implements is refused rather than quietly falling back: a typo
resolving to `checked` would look like it worked, and one resolving to
`trusted` would drop validation nobody asked to drop.

`checked` walks a message against the schema. `trusted` says the two
threads ship together and the sender is this same package, so a
production build checks the envelope -- protocol, renderer, root,
version, discriminant, arity -- and declines the O(commands x props)
walk beneath it. The envelope stays in both modes because it is what
decides which root a commit belongs to and which version it answers;
skipping it would not be a trust decision but a routing bug.

A development build runs the full `checked` walk under either mode, so
drift fails loudly where it is introduced rather than silently where it
is deployed.

Neither mode changes what happens after validation. The compact
completion acknowledgement, backpressure, lifetime and fault semantics
are identical, and that is asserted by running the same mount, update
and teardown through both modes and comparing the whole protocol trace
on each thread plus the rendered HTML.

The page-scoped data lifecycle receiver stays `checked` whatever a root
chooses: `__RenderPage` and friends outlive any one root and carry data
the app did not author.

Co-Authored-By: Claude <[email protected]>
Claude-Session: https://claude.ai/code/session_019RsC3U39kUuLKajZANeTVy
Huxpro and others added 2 commits August 25, 2026 23:44
- The dev send-side self-check refuses symbol-keyed record fields again:
  invisible to Object.keys, so the codec's value refusals never see one
  and JSON drops it without a trace — the one silent-loss shape left
  after the boundary took over. Red-verified; the checked receive walk
  skips the probe since JSON.parse output cannot carry one.
- exactKeys' comment now derives its exactness from the transport
  boundary instead of a guarantee this train deleted from record().
- resolveLynxValidationMode is the single spelling guard for both ends
  of the wire.
- The shared-depth comment stops claiming the two walks cut off at the
  same level; they share a budget, counted from different roots.

Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01YHfFsy9CLaRovTFH8pTGyY
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants