You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Design: tree-shaped prefix affinity — forked branches inherit the shared prefix's compression state #629
Anonymous prefix affinity (#309/#316/#499, src/prefix-affinity.ts) resolves header-less clients by longest-prefix match over an append-only hash chain (h_i = sha256(h_{i-1} || msg_i)). It deliberately mirrors vLLM/SGLang radix prefix caching at the identity layer.
Current fork semantics (documented in the file header): when a request's history diverges from every stored chain, it forks into a brand-new session with zero compression state. The discarded parent candidates are recorded in lineage (parents[], reason: "forked"|"truncated") — but lineage is UI/debug only, never used for matching or state inheritance (MIN_FORK_PREFIX = 3, comment says so explicitly).
The gap
A fork (user edits history, rewinds, or two parallel conversations share a common opening) throws away every compression block anchored inside the shared prefix:
the parent session may have folded 100K tokens of that prefix into blocks;
the forked branch re-sends the same bytes raw and must re-compress from scratch (nudge starts at ~0% accumulated);
after compression, the branch's blocks duplicate the parent's coverage over identical content.
This is the classic radix-tree property that prefix-affinity stops short of: identity is content-addressed, but compression state is not — it lives per session (kernel StateStore, blocks owned by one session id).
Proposal (discussion)
Make the fold state effectively tree-shaped so a fork inherits the folds anchored inside its shared prefix:
On fork detection (existing lineage machinery), copy/adopt the parent session's blocks whose effectiveMessageIds fall entirely inside the shared prefix (items 0..lcp-1) into the new session, remapping anchors.
Keep per-session ownership for persistence — this is a one-time adoption at fork time, not shared live state (avoids two branches mutating one block).
Reuse the existing per-item hash chain as the prefix-addressing mechanism (MAX_STORED_ITEMS = 128 currently caps it — may need raising or a separate block-anchor index keyed by item hash).
[bot] 🏷 Picked this up as a design review (not yet implementing — see recommendation at the end). Duplicate screen first: no existing issue/PR proposes tree-shaped affinity or fork-state inheritance; the closest neighbours are #319 (the existing fork-lineage machinery this builds on, closed) and #619 (spawn point, orthogonal decode-fail scope in PR #622). Not a duplicate.
Bottom line up front
The design is sound, and it's more feasible than the issue assumes — two of the three "hard parts" (anchor remapping, kernel adoption API) turn out to be unnecessary. But the affected population is narrower than the open questions imply, so I recommend measure-first + ship-gated rather than building it blind. Details below.
1. The problem is real — but who actually forks?
Fork-inheritance can only help anonymous clients (no client-provided identity), because that's the only path through prefixAffinity.resolve() (src/server.ts:1263if (!clientProvided)). Clients that carry a stable id never reach the fork branch:
codex → body.session_id
opencode → x-session-affinity
omp → prompt_cache_key (session id derives from it, src/server.ts:1347-1359)
So two of the three frequency examples in the open questions — "omp rewind" and "codex /compact-adjacent flows" — are largely out of scope: those clients hold one stable session and don't fork through prefix-affinity at all. The real population is pi-without-x-acp-session, dsh web, and generic header-less harnesses, and even then only when they (a) grow long enough to compress and (b) edit/rewind/regenerate mid-history.
Also worth noting: the rolling-window "client dropped its oldest messages" case does not fork — tail-window reattach (#316, src/prefix-affinity.ts:207-249) reattaches to the same session, so no state is lost there. Only true mid-history divergence (edited middle message) creates the zero-state fork this issue targets. That's a genuine but small slice.
When it does hit, the benefit is large though — it's exactly the #351 failure mode (458K-token history resent raw and re-compressed from scratch). So: low frequency, high per-event value.
2. The core design choice is correct — affirming it
Copy-on-fork (one-time adoption, per-session ownership preserved) is the right call over the alternative "true radix tree" (content-addressed shared blocks that sessions reference). Shared live blocks reintroduce exactly the hazard the proposal wants to avoid: two branches mutating one block (deactivation / tier promotion / orphan-GC in one branch silently corrupts the other). One-time copy keeps ownership clean. Agreed.
3. Feasibility is better than stated — two "hard parts" dissolve
(a) No anchor remapping needed. This is the big one. Raw message ids are deterministic content fingerprints — acp-kernel/wire/message-id.d.ts: deriveMessageId(role, contentType, text, {toolCallId, toolName}) = SHA-256 of identity, and the duplicate-cluster _N suffix is "counting from 0 in arrival order… two passes over the same content produce the same cluster numbering (deterministic)." A byte-identical fork prefix therefore yields identical raw ids to the parent's prefix.
Refs (mNNNNN) align too: acp-kernel/refs.d.tsassignRefs assigns them by arrival index from a fresh nextIndex=0 over the incoming list. A fork re-sending the same prefix gets the same refs the parent assigned. So an adopted block's effectiveMessageIdsand its startRef/endRef both line up with no remap, in the common append-only case.
(b) No kernel change needed. The kernel already runs "state pre-seeded with blocks → reconcile against incoming" on every restart: disk restore (src/persist.tsbuildSession → mergeState) loads blocks/messageRefs/tokenSnapshot into a Session, then processTurn/syncBlocks reconciles them against the incoming history. Fork adoption constructs the identical shape (a filtered copy of the parent's blocks + a counter bump) and rides the exact same code path. mergeState (src/persist.ts:129-140) is literally the construction recipe. So the "Kernel support needed: block adoption/remap API" open question resolves to none — all new code lives in billion-context.
4. Simplification: don't key off lcp / the 128 cap
The proposal frames adoption as "blocks whose effectiveMessageIds fall inside items 0..lcp-1," and flags MAX_STORED_ITEMS = 128 as a cap that may need raising. You don't need positional lcp at all: the proxy has already parsed the fork's full incoming history, so compute the set of incoming raw ids and adopt any parent block whose anchors are a subset of it. Raw-id-set membership is exact at any depth — immune to the 128-item cap (positional LCP is best-effort past 128, but set membership isn't). The existing lineage/lcp machinery is then used only to identify which parent session to draw blocks from, not to bound the adoption.
5. Correctness constraints the proposal under-specifies (this is the real work)
Closure-safety for tier 2/3. A T2/T3 block carries directBlockIds → child blocks → their effectiveMessageIds. Adopt a block only if its entire transitive closure is in-prefix. Otherwise a distilled summary would cover content the fork diverged on — silent semantic corruption. The "entirely inside the shared prefix" rule must apply to the closure, not just the top block's direct ids.
ID counters. Bump the child's nextBlockId/nextRunId past the parent's max so newly compressed ranges in the fork don't collide with adopted blockIds/runIds.
What must NOT inherit (confirms your open question): nudge state, stats (lastInputTokens/contextTokens/compressCreditTokens), messageRefs (rebuilt by assignRefs), and per-session metadata — notably outputBudgetHighWater ([bug] bili dsh 长会话中 max_output_tokens 被压到 ≤200,主请求被误判为 side request 并绕过压缩 #546restoreOutputBudget, src/server.ts:659-678), learnedContextLimit(s), nativeCompaction* boundaries, lastCompress. Inherit onlyblocks (+ their blockContents entries); optionally tokenSnapshot (keyed by ref → preserves provider prefix-cache stability across the fork) and absorbed records whose callMessageId/resultMessageId are in-prefix.
Both compression modes (AGENTS.md §6). Anonymous clients are inherently proxy mode (no x-bili-plugin header), so inherited blocks are always acp_summary carriers and the child is also proxy mode — safe. State this explicitly in the impl so a future plugin-mode client can't accidentally adopt proxy-created blocks whose tool-call carrier isn't in its history.
6. Safety — holds
Adopting reveals nothing new: to discover the parent, the fork must present the shared prefix byte-for-byte (the #286/#309 possession argument), and we only adopt summaries of bytes the fork itself sent. Even if the "parent" is a different user's templated opening, the fork inherits only summaries of content it possessed. Unchanged.
Recommendation (my stance, not a menu)
Given (i) the population is narrower than the open questions suggest, (ii) per-event value is high but frequency is unmeasured, and (iii) the implementation is well-scoped but has real closure-safety subtleties across both modes — I'd sequence it as:
Measure first (cheap, zero-risk): extend the existing fork log line (src/server.ts:1283-1285) with a counter of forks where the parent had ≥1 adoptable in-prefix block plus the tokens that would have been saved. One line; tells us within a week or two whether the slice is worth it.
Ship gated: implement adoption behind a config flag (default off), validated in production against the counter, then flip default-on. Scope is one new module + a hook at the fork-detection site (src/server.ts:1307-1317, right where lineage is already written to session.metadata) + tests covering both modes and the T2/T3 closure case.
If you'd rather skip the telemetry and build it now regardless of frequency, the design above is ready to implement and I'll proceed on your sign-off — but I'd want your call on the measure-first step since the affected-client assumption in the issue needs correcting before we size the effort.
Happy to draft the measurement one-liner as a standalone PR either way, since it's useful independent of the decision.
Feasibility dig (post kernel v0.0.57): host-only, no kernel API needed
Verified three load-bearing facts on current master:
1. Message ids are content-addressed and session-independent (acp-kernelsrc/wire/message-id.ts): deriveMessageId = "h_" + sha256(role|contentType|toolCallId|toolName|text) + deterministic within-pass cluster suffix _N for duplicates. A byte-identical history replay converted in a different session produces the same ids in the same order. So parent-block anchors (effectiveMessageIds/directMessageIds) resolve natively against the fork's replay — no remapping needed at all (the issue's "block adoption/remap API" guess is unnecessary).
2. assignRefs is idempotent over pre-seeded maps (acp-kernelsrc/refs.ts:69 — if (map.byRaw[message.id]) continue;) and allocateFreeRef skips taken refs. Copying the parent's messageRefs entries for covered ids into the fork's fresh state is safe: existing refs are kept verbatim (summary citations like m00042 stay valid — same prefix, same arrival order → same ref numbers), new messages allocate after the highest copied ref. Kernel invariant "ids never reused" holds.
3. The existence proof already ships: the #401 restore path reloads a persisted state (blocks + messageRefs) and the next request replays the FULL raw history — the standard fold path prunes it back to the folded wire. Fork adoption is the same shape: seed state at creation, let the existing machinery do the rest.
Concrete design (Phase 1, ~host-only)
Hook: at anonymous session creation (via: "new" with lineage.reason: "forked"), after protocol conversion produces CoreMessages, before first prepare.
Kernel-level LCP: compare the fork's originalMessages id list against the parent's lastMessages snapshot id list (both h_*, exact equality) — not the affinity itemHashes (those hash wire JSON, a different canonical form; and they cap at MAX_STORED_ITEMS = 128).
Adopt from the parent (in-memory store, else SessionStore disk): the transitive closure of active blocks whose effectiveMessageIds ⊆ LCP id-set (criterion automatically handles nested directBlockIds), plus their blockContents, plus messageRefs entries for all covered ids, plus state.nextBlockId (never re-issue blockIds).
Result: the fork's first wire is already folded over the shared prefix → byte-stable with the parent's folded prefix → upstream prefix-cache hit + no re-compress + no duplicated block coverage.
Safety argument
Adoption cannot misattribute: a block is only adopted when every id it covers is present, in order, in the fork's actual replay. Coverage-by-exact-ids is the same mechanism the restore path trusts. Worst case with a weak fork guess (distinct conversation sharing a templated head): only the genuinely-shared preamble blocks get adopted — content the requester demonstrably holds (#286/#309 argument).
Limitations (accepted for Phase 1)
Fork detection needs the parent within the trailing-128-item window (MAX_STORED_ITEMS); ancient-history rewinds won't detect. Divergence is usually recent.
Memory: blockContents are copied (per-session ownership, issue point 2); bounded by the parent's existing cache.
Implementation sketch: new src/fork-adopt.ts (~150 lines) + hook at anonymous-session creation in the prepare path + tests (adoption matrix incl. nested blocks / cursor safety / metadata non-inheritance; e2e: fork replay produces the already-folded wire with valid refs). No kernel change required.
[bot] 🏷 Validated against the pinned kernel — all three load-bearing facts hold (note: this worktree pins acp-kernel 0.0.54, your dig cites master at 0.0.57; I verified via the .d.ts on 0.0.54 and the semantics are identical). Agreed with the overall shape: host-only, no kernel API, copy-on-fork. Four corrections/refinements before I build, two of which change a load-bearing detail:
1. Don't gate adoption on parent.lastMessages — use set-membership instead.src/session.ts:117-123 (lastMessagesFolded): a boot-restored or disk-reloaded parent stores a bounded, folded+truncatedlastMessages whose ids "no longer align with the state ranges." Comparing id lists against it produces a wrong boundary exactly in the case you'd most want it (parent survived a restart). Robust predicate: adopt parent block B iff B.effectiveMessageIds ⊆ {fork's incoming CoreMessage ids} (the fork's id set comes free post-conversion — new Set(msgs.map(m => m.id)), the exact pattern already at server.ts:1836). Needs only the fork's incoming ids + the parent's state.blocks. Side benefits: immune to MAX_STORED_ITEMS=128, and it captures more valid adoptions than positional LCP — a block sitting after a mid-prefix edit that the fork still holds byte-identically (LCP stops at the edit point and misses it). Keep lineage.sharedPrefix for logging/UI only, not as the gate.
2. The hook must run pre-processTurn, not post-prepare.core.processTurn executes inside each prepare* — e.g. anthropic server.ts:1817, immediately after originalMessages = msgs at :1805. Seeding blocks after prepare returns would be too late: the first wire is already unfolded. So the seed lands between originalMessages = msgs and processTurn, in all three prepare fns (anthropic/openai/responses); the logic lives once in src/fork-adopt.ts.
3. Exclusion list += nudge; bump nextRunId too.nudge (baseline/anchors) encodes the parent's growth trajectory — must stay fresh. You listed stats/outputBudgetHighWater(#546)/learnedCompatRoles(#552)/pluginAgent; add nudge. Also bump nextRunId alongside nextBlockId (runIds are allocated per compress and would otherwise collide). Skip absorbed records in Phase 1 (keeps scope tight).
4. Copy tokenSnapshot entries for covered refs (keyed by ref, same subset selection as messageRefs) → keeps the provider prefix-cache stable across the fork. Cheap, optional, but consistent.
One conscious choice to flag rather than let it look like a bug: set-membership may adopt a block physically located after a divergence point when the fork still possesses those bytes. That's safe (the fork demonstrably holds them — the #286/#309 possession argument) and strictly more beneficial than LCP. Deliberate, not accidental.
Parent access: peekSession(parentId) in-memory, else a detached SessionStore.loadSync read (never inserted into the pool); graceful no-op if the parent isn't found anywhere.
Plan: host-only, gated behind an env flag (default-on, opt-out) so ops can disable it; tests cover T2/T3 closure-safety, ref-cursor gap-fill, metadata non-inheritance, folded-parent fallback, and no-parent skip; e2e asserts a fork replay emits an already-folded wire with valid refs. No kernel change. Building now — PR link to follow.
Implementation ready in #1055 (branch 2026-09-20_fork-block-adoption, rebased on master 615a496).
Fork detection mints the child session, then copy-adopts each parent block whose effectiveMessageIds are fully present in the forked request (blocks straddling the edit are left behind), seeding byRaw/byRef/blockContents from the parent — parent state untouched.
Kernel id-never-reused contract preserved: no renumbering, seeding only pre-registers ids the child would register anyway.
Gated behind forkAdoption (default off).
E2E test drives a real proxy: grow → proxy-mode compress → middle-edit fork → child carries the parent's block id + summary; disabled-mode scenario asserts zero-state fork.
Pre-flight: typecheck ✅ / npm test 2079✅ / build ✅
Human merge please (feat + persistence seeding, not auto-merge eligible per AGENTS.md §7.4).
Verified the actual state independently (didn't take the summary at face value) — #1055 is ready for human merge. Nothing blocking found; I made no changes.
PR state
Open, not draft · mergeable: true, mergeable_state: clean
Base master @ 615a496 == current master head → rebased on the live tip, not stale
Single commit, +521 / −0, 4 files — matches the described scope exactly
CI (all 8 completed/success)
build-artifact · test ubuntu@22 & ubuntu@24 · test windows@22 & windows@24 · version-guard · real-codex-vs-fake-upstream (zero tokens) · codex CODEX_HOME overlay + bili MCP registration
Scope vs. #629 design (floors 3–6) — all load-bearing constraints honored
Gate is raw-id set-membership (effectiveMessageIds.every(id => incoming.has(id))), position-free → immune to the 128 cap, and naturally rejects blocks straddling the edit point.
T2/T3 closure-safety: tier children ride along via directBlockIds; a tier block is adopted only if its whole message closure is present.
Bumps bothnextBlockId and nextRunId past the parent's max (no id re-issue).
Copy-on-fork via structuredClone; parent session never mutated (test asserts parent block count unchanged after fork).
Exclusion list correct — seeds only blocks/blockContents/messageRefs(+tokenSnapshot); nudge/stats/absorbed/outputBudget stay fresh-session.
Kernel id-never-reused contract preserved: seeding pre-registers only ids the child would register anyway (same prefix → same arrival order → same refs); assignRefs cursor lands above them.
Runs once, first request only (stats.requests === 0), before prepare*/processTurn; wrapped in try/catch that degrades to fresh state.
Default off (forkAdoption / BILI_FORK_ADOPTION=1); logs the adoptable inventory even when disabled = the measure-first telemetry floor 3 asked for.
Tests — real-proxy driver (grow → proxy-mode compress → middle-edit fork): asserts child carries the parent's block id + summaries and the parent is untouched; plus a disabled-mode scenario asserting a zero-state fork.
One scoping note for the merge decision: v1 covers openai + anthropic anonymous forks; responses/google log-skip (a perf loss, not a correctness risk — they're always proxy-mode too). Fine for a gated, default-off ship.
Confirmed not auto-merge eligible per §7.4 (it's a feat: + adds a config surface + persistence seeding) — so this stays a human merge, as you noted. Go ahead whenever you're ready.
Activity
ranxianglei commentedon Sep 7, 2026
[bot] 🏷 Picked this up as a design review (not yet implementing — see recommendation at the end). Duplicate screen first: no existing issue/PR proposes tree-shaped affinity or fork-state inheritance; the closest neighbours are #319 (the existing fork-lineage machinery this builds on, closed) and #619 (spawn point, orthogonal decode-fail scope in PR #622). Not a duplicate.
Bottom line up front
The design is sound, and it's more feasible than the issue assumes — two of the three "hard parts" (anchor remapping, kernel adoption API) turn out to be unnecessary. But the affected population is narrower than the open questions imply, so I recommend measure-first + ship-gated rather than building it blind. Details below.
1. The problem is real — but who actually forks?
Fork-inheritance can only help anonymous clients (no client-provided identity), because that's the only path through
prefixAffinity.resolve()(src/server.ts:1263if (!clientProvided)). Clients that carry a stable id never reach the fork branch:body.session_idx-session-affinityprompt_cache_key(session id derives from it,src/server.ts:1347-1359)So two of the three frequency examples in the open questions — "omp rewind" and "codex
/compact-adjacent flows" — are largely out of scope: those clients hold one stable session and don't fork through prefix-affinity at all. The real population is pi-without-x-acp-session, dsh web, and generic header-less harnesses, and even then only when they (a) grow long enough to compress and (b) edit/rewind/regenerate mid-history.Also worth noting: the rolling-window "client dropped its oldest messages" case does not fork — tail-window reattach (#316,
src/prefix-affinity.ts:207-249) reattaches to the same session, so no state is lost there. Only true mid-history divergence (edited middle message) creates the zero-state fork this issue targets. That's a genuine but small slice.When it does hit, the benefit is large though — it's exactly the #351 failure mode (458K-token history resent raw and re-compressed from scratch). So: low frequency, high per-event value.
2. The core design choice is correct — affirming it
Copy-on-fork (one-time adoption, per-session ownership preserved) is the right call over the alternative "true radix tree" (content-addressed shared blocks that sessions reference). Shared live blocks reintroduce exactly the hazard the proposal wants to avoid: two branches mutating one block (deactivation / tier promotion / orphan-GC in one branch silently corrupts the other). One-time copy keeps ownership clean. Agreed.
3. Feasibility is better than stated — two "hard parts" dissolve
(a) No anchor remapping needed. This is the big one. Raw message ids are deterministic content fingerprints —
acp-kernel/wire/message-id.d.ts:deriveMessageId(role, contentType, text, {toolCallId, toolName})= SHA-256 of identity, and the duplicate-cluster_Nsuffix is "counting from 0 in arrival order… two passes over the same content produce the same cluster numbering (deterministic)." A byte-identical fork prefix therefore yields identical raw ids to the parent's prefix.Refs (
mNNNNN) align too:acp-kernel/refs.d.tsassignRefsassigns them by arrival index from a freshnextIndex=0over the incoming list. A fork re-sending the same prefix gets the same refs the parent assigned. So an adopted block'seffectiveMessageIdsand itsstartRef/endRefboth line up with no remap, in the common append-only case.(b) No kernel change needed. The kernel already runs "state pre-seeded with blocks → reconcile against incoming" on every restart: disk restore (
src/persist.tsbuildSession→mergeState) loadsblocks/messageRefs/tokenSnapshotinto aSession, thenprocessTurn/syncBlocksreconciles them against the incoming history. Fork adoption constructs the identical shape (a filtered copy of the parent's blocks + a counter bump) and rides the exact same code path.mergeState(src/persist.ts:129-140) is literally the construction recipe. So the "Kernel support needed: block adoption/remap API" open question resolves to none — all new code lives in billion-context.4. Simplification: don't key off
lcp/ the 128 capThe proposal frames adoption as "blocks whose
effectiveMessageIdsfall inside items0..lcp-1," and flagsMAX_STORED_ITEMS = 128as a cap that may need raising. You don't need positionallcpat all: the proxy has already parsed the fork's full incoming history, so compute the set of incoming raw ids and adopt any parent block whose anchors are a subset of it. Raw-id-set membership is exact at any depth — immune to the 128-item cap (positional LCP is best-effort past 128, but set membership isn't). The existing lineage/lcpmachinery is then used only to identify which parent session to draw blocks from, not to bound the adoption.5. Correctness constraints the proposal under-specifies (this is the real work)
directBlockIds→ child blocks → theireffectiveMessageIds. Adopt a block only if its entire transitive closure is in-prefix. Otherwise a distilled summary would cover content the fork diverged on — silent semantic corruption. The "entirely inside the shared prefix" rule must apply to the closure, not just the top block's direct ids.nextBlockId/nextRunIdpast the parent's max so newly compressed ranges in the fork don't collide with adoptedblockIds/runIds.nudgestate,stats(lastInputTokens/contextTokens/compressCreditTokens),messageRefs(rebuilt byassignRefs), and per-session metadata — notablyoutputBudgetHighWater([bug] bili dsh 长会话中 max_output_tokens 被压到 ≤200,主请求被误判为 side request 并绕过压缩 #546restoreOutputBudget,src/server.ts:659-678),learnedContextLimit(s),nativeCompaction*boundaries,lastCompress. Inherit onlyblocks(+ theirblockContentsentries); optionallytokenSnapshot(keyed by ref → preserves provider prefix-cache stability across the fork) andabsorbedrecords whosecallMessageId/resultMessageIdare in-prefix.x-bili-pluginheader), so inherited blocks are alwaysacp_summarycarriers and the child is also proxy mode — safe. State this explicitly in the impl so a future plugin-mode client can't accidentally adopt proxy-created blocks whose tool-call carrier isn't in its history.6. Safety — holds
Adopting reveals nothing new: to discover the parent, the fork must present the shared prefix byte-for-byte (the #286/#309 possession argument), and we only adopt summaries of bytes the fork itself sent. Even if the "parent" is a different user's templated opening, the fork inherits only summaries of content it possessed. Unchanged.
Recommendation (my stance, not a menu)
Given (i) the population is narrower than the open questions suggest, (ii) per-event value is high but frequency is unmeasured, and (iii) the implementation is well-scoped but has real closure-safety subtleties across both modes — I'd sequence it as:
src/server.ts:1283-1285) with a counter of forks where the parent had ≥1 adoptable in-prefix block plus the tokens that would have been saved. One line; tells us within a week or two whether the slice is worth it.src/server.ts:1307-1317, right wherelineageis already written tosession.metadata) + tests covering both modes and the T2/T3 closure case.If you'd rather skip the telemetry and build it now regardless of frequency, the design above is ready to implement and I'll proceed on your sign-off — but I'd want your call on the measure-first step since the affected-client assumption in the issue needs correcting before we size the effort.
Happy to draft the measurement one-liner as a standalone PR either way, since it's useful independent of the decision.
ranxianglei commentedon Sep 7, 2026
Feasibility dig (post kernel v0.0.57): host-only, no kernel API needed
Verified three load-bearing facts on current master:
1. Message ids are content-addressed and session-independent (
acp-kernelsrc/wire/message-id.ts):deriveMessageId = "h_" + sha256(role|contentType|toolCallId|toolName|text)+ deterministic within-pass cluster suffix_Nfor duplicates. A byte-identical history replay converted in a different session produces the same ids in the same order. So parent-block anchors (effectiveMessageIds/directMessageIds) resolve natively against the fork's replay — no remapping needed at all (the issue's "block adoption/remap API" guess is unnecessary).2.
assignRefsis idempotent over pre-seeded maps (acp-kernelsrc/refs.ts:69—if (map.byRaw[message.id]) continue;) andallocateFreeRefskips taken refs. Copying the parent'smessageRefsentries for covered ids into the fork's fresh state is safe: existing refs are kept verbatim (summary citations likem00042stay valid — same prefix, same arrival order → same ref numbers), new messages allocate after the highest copied ref. Kernel invariant "ids never reused" holds.3. The existence proof already ships: the #401 restore path reloads a persisted state (blocks + messageRefs) and the next request replays the FULL raw history — the standard fold path prunes it back to the folded wire. Fork adoption is the same shape: seed state at creation, let the existing machinery do the rest.
Concrete design (Phase 1, ~host-only)
via: "new"withlineage.reason: "forked"), after protocol conversion produces CoreMessages, before firstprepare.originalMessagesid list against the parent'slastMessagessnapshot id list (bothh_*, exact equality) — not the affinity itemHashes (those hash wire JSON, a different canonical form; and they cap atMAX_STORED_ITEMS = 128).SessionStoredisk): the transitive closure of active blocks whoseeffectiveMessageIds⊆ LCP id-set (criterion automatically handles nesteddirectBlockIds), plus theirblockContents, plusmessageRefsentries for all covered ids, plusstate.nextBlockId(never re-issue blockIds).outputBudgetHighWater([bug] bili dsh 长会话中 max_output_tokens 被压到 ≤200,主请求被误判为 side request 并绕过压缩 #546),learnedCompatRoles(billion-context: 400 Bad Request when codex sendsrole: "developer"messages — request a request-body compat transform hook #552),pluginAgentstickiness — all stay fresh-session. (Answers the issue's open question.)Safety argument
Adoption cannot misattribute: a block is only adopted when every id it covers is present, in order, in the fork's actual replay. Coverage-by-exact-ids is the same mechanism the restore path trusts. Worst case with a weak fork guess (distinct conversation sharing a templated head): only the genuinely-shared preamble blocks get adopted — content the requester demonstrably holds (#286/#309 argument).
Limitations (accepted for Phase 1)
MAX_STORED_ITEMS); ancient-history rewinds won't detect. Divergence is usually recent.Implementation sketch: new
src/fork-adopt.ts(~150 lines) + hook at anonymous-session creation in the prepare path + tests (adoption matrix incl. nested blocks / cursor safety / metadata non-inheritance; e2e: fork replay produces the already-folded wire with valid refs). No kernel change required.ranxianglei commentedon Sep 7, 2026
[bot] 🏷 Validated against the pinned kernel — all three load-bearing facts hold (note: this worktree pins acp-kernel 0.0.54, your dig cites master at 0.0.57; I verified via the
.d.tson 0.0.54 and the semantics are identical). Agreed with the overall shape: host-only, no kernel API, copy-on-fork. Four corrections/refinements before I build, two of which change a load-bearing detail:1. Don't gate adoption on
parent.lastMessages— use set-membership instead.src/session.ts:117-123(lastMessagesFolded): a boot-restored or disk-reloaded parent stores a bounded, folded+truncatedlastMessageswhose ids "no longer align with the state ranges." Comparing id lists against it produces a wrong boundary exactly in the case you'd most want it (parent survived a restart). Robust predicate: adopt parent blockBiffB.effectiveMessageIds ⊆ {fork's incoming CoreMessage ids}(the fork's id set comes free post-conversion —new Set(msgs.map(m => m.id)), the exact pattern already atserver.ts:1836). Needs only the fork's incoming ids + the parent'sstate.blocks. Side benefits: immune toMAX_STORED_ITEMS=128, and it captures more valid adoptions than positional LCP — a block sitting after a mid-prefix edit that the fork still holds byte-identically (LCP stops at the edit point and misses it). Keeplineage.sharedPrefixfor logging/UI only, not as the gate.2. The hook must run pre-
processTurn, not post-prepare.core.processTurnexecutes inside eachprepare*— e.g. anthropicserver.ts:1817, immediately afteroriginalMessages = msgsat:1805. Seeding blocks afterpreparereturns would be too late: the first wire is already unfolded. So the seed lands betweenoriginalMessages = msgsandprocessTurn, in all three prepare fns (anthropic/openai/responses); the logic lives once insrc/fork-adopt.ts.3. Exclusion list +=
nudge; bumpnextRunIdtoo.nudge(baseline/anchors) encodes the parent's growth trajectory — must stay fresh. You listed stats/outputBudgetHighWater(#546)/learnedCompatRoles(#552)/pluginAgent; addnudge. Also bumpnextRunIdalongsidenextBlockId(runIds are allocated per compress and would otherwise collide). Skipabsorbedrecords in Phase 1 (keeps scope tight).4. Copy
tokenSnapshotentries for covered refs (keyed by ref, same subset selection asmessageRefs) → keeps the provider prefix-cache stable across the fork. Cheap, optional, but consistent.One conscious choice to flag rather than let it look like a bug: set-membership may adopt a block physically located after a divergence point when the fork still possesses those bytes. That's safe (the fork demonstrably holds them — the #286/#309 possession argument) and strictly more beneficial than LCP. Deliberate, not accidental.
Parent access:
peekSession(parentId)in-memory, else a detachedSessionStore.loadSyncread (never inserted into the pool); graceful no-op if the parent isn't found anywhere.Plan: host-only, gated behind an env flag (default-on, opt-out) so ops can disable it; tests cover T2/T3 closure-safety, ref-cursor gap-fill, metadata non-inheritance, folded-parent fallback, and no-parent skip; e2e asserts a fork replay emits an already-folded wire with valid refs. No kernel change. Building now — PR link to follow.
ranxianglei commentedon Sep 20, 2026
Implementation ready in #1055 (branch
2026-09-20_fork-block-adoption, rebased on master 615a496).effectiveMessageIdsare fully present in the forked request (blocks straddling the edit are left behind), seedingbyRaw/byRef/blockContentsfrom the parent — parent state untouched.forkAdoption(default off).npm test2079✅ / build ✅Human merge please (feat + persistence seeding, not auto-merge eligible per AGENTS.md §7.4).
ranxianglei commentedon Sep 20, 2026
Verified the actual state independently (didn't take the summary at face value) — #1055 is ready for human merge. Nothing blocking found; I made no changes.
PR state
mergeable: true,mergeable_state: cleanmaster @ 615a496== current master head → rebased on the live tip, not staleCI (all 8 completed/success)
build-artifact · test ubuntu@22 & ubuntu@24 · test windows@22 & windows@24 · version-guard · real-codex-vs-fake-upstream (zero tokens) · codex CODEX_HOME overlay + bili MCP registration
Scope vs. #629 design (floors 3–6) — all load-bearing constraints honored
effectiveMessageIds.every(id => incoming.has(id))), position-free → immune to the 128 cap, and naturally rejects blocks straddling the edit point.directBlockIds; a tier block is adopted only if its whole message closure is present.nextBlockIdandnextRunIdpast the parent's max (no id re-issue).structuredClone; parent session never mutated (test asserts parent block count unchanged after fork).assignRefscursor lands above them.stats.requests === 0), beforeprepare*/processTurn; wrapped in try/catch that degrades to fresh state.forkAdoption/BILI_FORK_ADOPTION=1); logs the adoptable inventory even when disabled = the measure-first telemetry floor 3 asked for.Tests — real-proxy driver (grow → proxy-mode compress → middle-edit fork): asserts child carries the parent's block id + summaries and the parent is untouched; plus a disabled-mode scenario asserting a zero-state fork.
One scoping note for the merge decision: v1 covers
openai+anthropicanonymous forks;responses/googlelog-skip (a perf loss, not a correctness risk — they're always proxy-mode too). Fine for a gated, default-off ship.Confirmed not auto-merge eligible per §7.4 (it's a
feat:+ adds a config surface + persistence seeding) — so this stays a human merge, as you noted. Go ahead whenever you're ready.中文摘要:独立核对了 #1055 的真实状态(PR 干净可合并、基于最新 master、8 项 CI 全绿、diff 范围与描述一致、代码满足讨论中所有正确性约束、默认关闭),未发现阻塞问题,无需改动;因属 feat + 持久化播种,按 §7.4 不满足自动合并条件,请人工合并。
test: pin fork-adoption seeded-ref mapping and id-cursor inheritance (#…
docs: document BILI_FORK_ADOPTION and fix env-precedence comment (#629)
ranxianglei commentedon Sep 20, 2026
review这个 #1055 是否合理 是由有回归问题 影响面
ranxianglei commentedon Sep 20, 2026
Review of #1055 — focused on 合理性 / 回归风险 / 影响面. Bottom line: 设计合理,无阻塞性回归,影响面收敛在「匿名 openai/anthropic 客户端中途 fork」这一条窄路径上;默认关闭时对线上零行为变化。可合并。 Details below.
1. 合理性(sound)
核心正确性建立在两个已被证明的前提上,而非新假设:
buildSession → mergeState:先灌 blocks/messageRefs/tokenSnapshot,再让processTurn对 incoming 做 reconcile)完全同构。恢复路径是生产验证过的,fork-adoption 只是把「全量恢复」换成「按 incoming-id 集合过滤的子集」。E2E(真实代理 grow→compress→middle-edit fork,子会话携带父 block id + summary 且 ref 有效)实证了这条 reconcile 路径成立。安全兜底充分:默认关闭、copy-on-fork(
structuredClone,父会话全程只读、test 断言父 block 数不变)、try/catch 降级为 fresh state(任何异常 = 退回今天的零状态行为,不会 break fork 请求本身)、首次请求才跑。我额外核对了最易翻车的点 ——
stats.requests === 0守卫的时序:hook 在src/server.ts:1406,而所有++session.stats.requests都在 L2099/2263/2475/2633/2966(即 hook 之后)。所以守卫确实只在首个请求命中一次,且不依赖脆弱的调用顺序(与 E2E 通过一致)。T2/T3 闭包安全(directBlockIds传递收集)、nextBlockId+nextRunId双 bump、排除清单完整(nudge/stats/absorbed/outputBudget 均不继承)也都逐条对上 floor 3–6 的设计约束。2. 回归风险
structuredClone(parsed)+ 协议转换来算可继承清单(用于度量日志),父被逐出时还可能触发一次loadSync磁盘读。这是 floor 3「先度量再放量」策略有意保留的成本,且 fork 本身低频(本 issue 前提即 low frequency)。不改 wire、不改 session 状态。可接受;见下方可选优化。acp_summary载体,子会话也是 proxy 模式,一致。plugin 模式 / 稳定身份客户端(codex/opencode/omp)根本到不了这个分支,零影响。responses/google 匿名 fork 在 v1 log-skip(仅少收益,非正确性问题)。3. 影响面(blast radius)
config.ts新增可选字段(默认 off,纯增量、无 schema 破坏);fork-adoption.ts全新隔离模块;server.ts+23 行一个受守卫的 hook;tests/fork-adoption.test.ts新增。单 commit +521/−0,diff 干净、每行都服务于本 PR。markDirty→ 正常落盘(重启不丢继承状态),格式不变。可选(非阻塞)
默认关闭时那笔「clone+转换(+可能 loadSync)」纯为打一行度量日志。若想进一步降本,可在 clone 前先
peekSession(parentId)判断父是否有 active block,无则提前返回省掉转换。但这是低频路径上的微优化,且会改动一个已绿、待合并的干净 PR,收益很小 —— 我不强行塞 commit,留给你决定要不要合进来或后续单独提。结论:合理、无回归、影响面可控,CI 全绿且基于最新 master,符合合并条件(feat + 持久化播种,按 §7.4 走人工合并)。
中文摘要:审核了 #1055 的合理性/回归/影响面——实现复用了已验证的磁盘恢复路径且默认关闭、异常降级为原行为,未发现阻塞性回归(仅默认关闭时为度量日志多一次 clone+转换的低频开销,属有意设计),影响面收敛在匿名 openai/anthropic 中途 fork 这一窄路径、稳定身份客户端零影响,CI 全绿基于最新 master,可以人工合并。
Merge pull request #1055 from ranxianglei/2026-09-20_fork-block-adoption
feat: adopt parent compression blocks on anonymous fork detection (ra…
fix: drop mid-chain adoption from anonymous prefix affinity (#1115)
fix: identified resume-forks adopt the parent's compression blocks by…
feat: simhash chain-alignment adoption for anonymous affinity (ranxia…
test: prove anonymous fork block-adoption on anthropic/responses/goog…
fix: drop mid-chain adoption from anonymous prefix affinity (ranxiang…
fix(gate): force chunked corpus reads at t1 + accept fresh-start fork…
test(dsh): pin the two remaining bare-marker guard fixtures to the em…