Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/compress-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -580,10 +580,11 @@ async function handleCompress(args: CompressArgs, runtime: AcpRuntime, ctx: Exte
});
if (errors.length > 0) {
logError("compress", { sid: ctx.sessionManager.getSessionId(), event: "errors", count: errors.length, errors: errors.slice(0, 5) });
// #454 stopgap: ref-resolution failures on a declared fork host carry the
// live-entry drift signature (see mergeLiveEntries in runtime.ts) — the
// same defect class OMP is refused for. Attribute it to #459 in support
// logs so "does not exist" spam is not misread as model misbehavior.
// Residual drift signal (#454/#459): with content-stable live ids,
// ref-resolution failures on a declared fork host mean the host rewrote or
// shrank its in-flight view (see mergeLiveEntries in runtime.ts). Attribute
// it in support logs so "does not exist" spam is not misread as model
// misbehavior.
if (blocksCreated === 0 && isDeclaredForkHost() && !isPiHost(ctx.sessionManager)
&& /does not exist|cannot be anchored|is unknown|unknown refs/i.test(errors.join(" "))) {
logWarn("compress", { sid: ctx.sessionManager.getSessionId(), event: "fork-ref-drift-suspected", seeIssue: "#459", errors: errors.slice(0, 3) });
Expand Down
22 changes: 11 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -216,16 +216,15 @@ function wireSessionLifecycle(pi: ExtensionAPI, runtime: AcpRuntime, standDownIf
}
return;
}
// Declared fork hosts are admitted but carry a known limitation (#454):
// their in-process live-entries integration can drift the nudge's example
// refs from the session's real refs as the session grows, so compress
// calls may start failing with "does not exist in this session". Warn at
// admission instead of letting users discover it mid-session; root fix is
// tracked in #459. Log per session (support logs need the attribution),
// notify once per process like the refusal path above.
// Declared fork hosts are admitted with a caveat (#454/#459): live-tail
// refs are content-stable while the host's view grows append-only; a host
// that rewrites in-flight messages can still drift them, so warn at
// admission and point long sessions at the proxy. Log per session (support
// logs need the attribution), notify once per process like the refusal
// path above.
if (isDeclaredForkHost() && !isPiHost(ctx.sessionManager)) {
const sid = ctx.sessionManager.getSessionId();
logWarn("host", { event: "fork-host-admitted", sid, knownLimitation: "ref-drift", seeIssue: "#454", rootFix: "#459" });
logWarn("host", { event: "fork-host-admitted", sid, hardening: "#459", proxy: "billion-context" });
if (!forkWarned) {
forkWarned = true;
if (ctx.hasUI) ctx.ui.notify(FORK_HOST_WARNING_MESSAGE, "warning");
Expand Down Expand Up @@ -583,9 +582,10 @@ function wireContextTransform(pi: ExtensionAPI, runtime: AcpRuntime, standDownIf
const turnPolicy = resolveHostSession(runtime.adapter);
const turnKey = lastTurnBoundaryId(entries, turnPolicy) ?? sid;
// #453: the retry breaker keys off PERSISTED boundaries only — under fork
// hosts the merged `entries` carry volatile live-N ids for the not-yet-
// persisted tail, so `turnKey` churns between context fires and would
// reset failCount mid-episode (cap never latches, emergency-inject loops).
// hosts the merged `entries` carry content-addressed live-* ids (#459) for
// the not-yet-persisted tail, which can still churn when the host's view
// of a message drifts between context fires and would reset failCount
// mid-episode (cap never latches, emergency-inject loops).
const retryTurnKey = retryBreakerKey(ctx.sessionManager, turnPolicy) ?? sid;

// Compress-outcome tracking feeds ONLY the nudge circuit breaker below:
Expand Down
14 changes: 6 additions & 8 deletions src/omp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,14 @@ export const UNSUPPORTED_HOST_MESSAGE = [

/**
* Shown (and logged) when a session runs on a host that declared itself a
* Pi-compatible fork via PI_ACP_FORK_HOST (see ./host.ts). The declaration
* admits hosts whose in-process live-entries integration can drift the nudge's
* example refs from the session's real refs as the session grows, so compress
* calls may start failing with "does not exist in this session" (#454). Warn
* at admission instead of letting users discover it mid-session; root fix is
* tracked in #459, and long sessions on such hosts are safer on the proxy.
* Pi-compatible fork via PI_ACP_FORK_HOST (see ./host.ts). Live-tail refs are
* content-addressed and stable across context fires (#459), which assumes the
* host's view of the session grows append-only; a host that rewrites or
* shrinks in-flight messages can still drift refs, so long sessions on such
* hosts are safer on the proxy (it owns the ref coordinate space server-side).
*/
export const FORK_HOST_WARNING_MESSAGE = [
"[billion-context-pi] Running on a declared fork host (PI_ACP_FORK_HOST). Known limitation: live-tail refs can drift as the session grows, so compress calls may start failing with \"does not exist in this session\" (#454). Root fix tracked in #459.",
"For long sessions on this host, prefer the billion-context proxy — it runs compression server-side and owns the ref coordinate space:",
"[billion-context-pi] Running on a declared fork host (PI_ACP_FORK_HOST). Live-tail refs are content-stable (#459); if compress ever fails with \"does not exist in this session\", this host rewrites its in-flight view — prefer the billion-context proxy for long sessions:",
" npm install -g billion-context",
" bili omp",
].join("\n");
76 changes: 53 additions & 23 deletions src/runtime.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { ExtensionContext, SessionEntry, SessionMessageEntry } from "@earendil-works/pi-coding-agent";
import { createHash } from "node:crypto";
import { readFileSync } from "node:fs";
import {
createCore,
Expand All @@ -18,7 +19,7 @@ import { loadUserConfig, applyUserConfig } from "./user-config.js";
import { sanitizeSurfaceConfig } from "./surface.js";
import { ThrottleEpisode } from "./throttle-retry.js";
import { logInfo, logWarn, setDebugEnabled } from "./log.js";
import { findUniqueLongestRun, type MatchRange } from "./sequence-match.js";
import { findPositionalPrefixRun, findUniqueLongestRun, type MatchRange } from "./sequence-match.js";
import { OverflowEpisode } from "./overflow-selfheal.js";
import { lastTurnBoundaryId, type TurnBoundaryPolicy } from "./turn-boundary.js";
// pi exposes `sessionManager.buildContextEntries()`; omp (oh-my-pi) only has
Expand All @@ -44,12 +45,12 @@ export function isPiHost(sm: ExtensionContext["sessionManager"]): boolean {
}

/** #453: key for the compress-retry circuit breaker, derived from PERSISTED
* entries only. On fork hosts the live-merged tail carries volatile live-N
* ids that renumber between context fires (the not-yet-persisted current
* user message), so a breaker keyed on the merged view resets failCount
* mid-episode and never latches (#452 log: cap → inject loop). Persisted
* entry ids are immutable; this key changes only when a genuine new user
* message reaches the session log. pi-native hosts see no change. */
* entries only. Live-merged tail ids (content-addressed since #459) can still
* churn when the host's view of a not-yet-persisted message drifts, so a
* breaker keyed on the merged view could reset failCount mid-episode (#452
* log: cap → inject loop). Persisted entry ids are immutable; this key
* changes only when a genuine new user message reaches the session log.
* pi-native hosts see no change. */
export function retryBreakerKey(sm: ExtensionContext["sessionManager"], policy?: TurnBoundaryPolicy): string | undefined {
return lastTurnBoundaryId(readContextEntries(sm), policy);
}
Expand Down Expand Up @@ -178,17 +179,27 @@ export interface AcpRuntime {
// omp fires the context event before the current user message is persisted to
// the session branch, so merge event.messages (exact messages about to be sent,
// including the not-yet-persisted tail) with the persisted branch: matching
// messages keep their stable entry id, unmatched tail messages get `live-N`
// ids until persisted.
// messages keep their stable entry id, unmatched tail messages get
// content-addressed `live-<hash>` ids (#459) until persisted.
function mergeLiveEntries(entries: SessionEntry[], live: AgentMessage[], state: CompressionState, origins: LiveRefOrigin[]): SessionEntry[] {
const persisted = entries.filter((e): e is SessionMessageEntry => e.type === "message");
const liveIdentities = live.map(messageIdentity);
const persistedIdentities = persisted.map((entry) => messageIdentity(entry.message));
const persistedRange = findUniqueLongestRun<MatchKey>(persistedIdentities, normalizePersistedMatchKeys(persisted, persistedIdentities, live, liveIdentities));
const normalizedKeys = normalizePersistedMatchKeys(persisted, persistedIdentities, live, liveIdentities);
// #459: the unique matcher gives up on duplicate-heavy views (ambiguous best
// run), which previously stranded every live message and renumbered its
// volatile live-N id each fire; the tail-anchored prefix run recovers the
// alignment deterministically under append-only growth.
const persistedRange = findUniqueLongestRun<MatchKey>(persistedIdentities, normalizedKeys) ?? findPositionalPrefixRun<MatchKey>(persistedIdentities, normalizedKeys);
const originRange = findUniqueLongestRun(origins.map((origin) => origin.identity), liveIdentities);
// #459: occurrence rank of each identity across (persisted + unmatched live
// prefix). When a message gets persisted it moves from the live count into
// the persisted count, so every still-live duplicate keeps the same rank —
// its id stays put across fires.
const identityRanks = new Map<string, number>();
for (const identity of persistedIdentities) identityRanks.set(identity, (identityRanks.get(identity) ?? 0) + 1);
const out: SessionEntry[] = [];
const nextOrigins: LiveRefOrigin[] = [];
const usedIds = new Set<string>();
for (let i = 0; i < live.length; i++) {
const msg = live[i]!;
const entry = valueInRange(persisted, persistedRange, i);
Expand All @@ -199,23 +210,25 @@ function mergeLiveEntries(entries: SessionEntry[], live: AgentMessage[], state:
out.push(entry);
continue;
}
const id = origin?.rawId ?? nextLiveId(state, usedIds, i);
usedIds.add(id);
const identity = liveIdentities[i]!;
const rank = identityRanks.get(identity) ?? 0;
identityRanks.set(identity, rank + 1);
const id = origin?.rawId ?? stableLiveId(identity, rank);
out.push({ type: "message", id, parentId: null, timestamp: String(msg.timestamp ?? Date.now()), message: msg });
nextOrigins.push({ rawId: id, identity: liveIdentities[i]! });
nextOrigins.push({ rawId: id, identity });
}
origins.splice(0, origins.length, ...nextOrigins);
const unmatched = live.length - (persistedRange?.length ?? 0);
if (unmatched > 0) logInfo("runtime", { event: "merge-live-entries", live: live.length, unmatched });
return out;
}


function nextLiveId(state: CompressionState, used: Set<string>, index: number): string {
let id = `live-${index}`;
let suffix = index;
while (used.has(id) || state.messageRefs.byRaw[id] !== undefined) id = `live-${++suffix}`;
return id;
// #459: deterministic id for an unmatched live message — sha256 over its
// content identity plus occurrence rank, so the same logical message gets the
// same id on every context fire (and after a state rebuild) even when the
// unique matcher cannot align it.
function stableLiveId(identity: string, rank: number): string {
return `live-${createHash("sha256").update(`${identity}\u0000${rank}`).digest("hex").slice(0, 16)}`;
}

function migrateTaggedRef(state: CompressionState, message: AgentMessage, stableId: string): void {
Expand Down Expand Up @@ -557,10 +570,23 @@ export function createRuntime(adapter: AdapterConfig): AcpRuntime {
}
}

// #459: tools (compress/decompress/status/search) run stateFor WITHOUT the
// context event's live tail, while the nudge that told the model which refs
// to cite was rendered WITH it — on fork hosts getBranch() lags the live
// tail, so every model-built range touching the tail died with "does not
// exist" (#452 loop). Cache each session's last context-fire live tail and
// replay it on the tool path so both views agree. The map is process-local:
// a resumed session starts with an empty cache and the first context fire
// repopulates it before any tool can run.
const lastLiveBySession = new Map<string, AgentMessage[]>();

async function stateFor(ctx: ExtensionContext, liveMessages?: AgentMessage[]) {
const sm = ctx.sessionManager;
const sessionFile = sm.getSessionFile() ?? undefined;
const sessionId = sm.getSessionId();
const piHost = isPiHost(sm);
if (!piHost && liveMessages && liveMessages.length > 0) lastLiveBySession.set(sessionId, [...liveMessages]);
const live = piHost ? undefined : (liveMessages ?? lastLiveBySession.get(sessionId));
let state = await store.load(sessionFile, sessionId);
const entries = readContextEntries(sm);
// Issue #299 (ranxianglei/billion-context-pi#299): pi's importFromJsonl
Expand Down Expand Up @@ -592,15 +618,19 @@ export function createRuntime(adapter: AdapterConfig): AcpRuntime {
// buildContextEntries() is always current. Merge event.messages (the exact
// messages about to be sent, including the not-yet-persisted tail) with the
// persisted branch records on the omp path only.
if (!isPiHost(sm) && liveMessages && liveMessages.length > 0) {
if (!piHost && live && live.length > 0) {
const origins = store.getLiveRefOrigins(sessionFile, sessionId);
const merged = mergeLiveEntries(entries, liveMessages, state, origins);
const merged = mergeLiveEntries(entries, live, state, origins);
store.setLiveRefOrigins(sessionFile, sessionId, origins);
const coreMessages = entriesToCoreMessages(merged);
// #459: enforce byRaw ⊆ view-ids ∪ block-ids on the merged view too —
// without it, stale live-* refs from a shrunken/rewound host view linger
// in state and get cited into compress ranges (#452 cross-generation refs).
pruneOrphanRefs(state, coreMessages);
return { state, coreMessages, entries: merged };
}
const coreMessages = entriesToCoreMessages(entries);
if (liveMessages === undefined) pruneOrphanRefs(state, coreMessages);
if (live === undefined) pruneOrphanRefs(state, coreMessages);
return { state, coreMessages, entries };
}

Expand Down
21 changes: 21 additions & 0 deletions src/sequence-match.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,27 @@ export function findUniqueLongestRun<Key>(candidates: readonly Key[], live: read
: undefined;
}

// #459 fallback for hosts whose views contain duplicate content: the
// unique-longest-run matcher above gives up entirely when its best run is
// ambiguous, which strands every live message as unmatched and churns their
// ids. Under append-only growth the live view's matched head always aligns
// with the TAIL of the persisted branch (persisted only grows at the end), so
// anchor there: longest k such that live[0..k) === candidates[len-k..len).
// Deterministic by construction — one answer for a given pair of views.
export function findPositionalPrefixRun<Key>(candidates: readonly Key[], live: readonly Key[]): MatchRange | undefined {
if (candidates.length === 0 || live.length === 0) return undefined;
const max = Math.min(candidates.length, live.length);
for (let length = max; length > 0; length--) {
const candidateStart = candidates.length - length;
let ok = true;
for (let i = 0; i < length; i++) {
if (candidates[candidateStart + i] !== live[i]) { ok = false; break; }
}
if (ok) return { candidateStart, liveStart: 0, length };
}
return undefined;
}

function buildSuffixArray(sequence: readonly number[]): number[] {
const suffixArray = sequence.map((_, index) => index);
let ranks = [...sequence];
Expand Down
Loading
Loading