Skip to content
Open
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
19 changes: 19 additions & 0 deletions src/acp-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import { pckAblations } from "./pck-probe.js";
import { getUnrecognizedPathStats } from "./server/observability.js";
import { ccrEnabled, ccrLoopConfig, contentStoreOf } from "./store.js";
import { coveredRefSpan } from "./decompress-shared.js";
import { readGenerationBoundary } from "./generation-boundary.js";
import { describeUncoveredRuns, formatProtectedMass, shortTokenCount, uncoveredAudit } from "./uncovered.js";
import { withoutTurnSeparators } from "./turn-separator.js";
import { forkAdoptionSkippedOf } from "./fork-adoption.js";
Expand Down Expand Up @@ -397,6 +398,24 @@ export function handleAcpStatus(args: Record<string, unknown>, ctx: AcpStatusCtx
}
}
}
// #5542: witnessed/detected generation boundary — the ref ledger restarted
// mid-conversation (persona fork or native-compaction rebase) or previous-
// generation residue was detected. Display-only, user-visible in tool
// output: the canonical surface saying "your old refs are dead and here is
// why", so the model stops retrying them and verifies execution tails.
try {
const genBnd = readGenerationBoundary(ctx.session);
if (genBnd) {
const genIso = new Date(genBnd.at).toISOString();
const why = genBnd.reason ?? "previous-generation ref residue detected in visible history";
const detailTxt = genBnd.detail ? ` ${genBnd.detail}.` : "";
const frontierTxt = genBnd.frontier ? ` Previous-generation frontier: ${genBnd.frontier}.` : "";
extra.push("");
extra.push(`GENERATION BOUNDARY — this session's ref ledger was reset mid-conversation (${why}, ${genIso}).${detailTxt}${frontierTxt} Refs above that frontier belong to the previous generation and are PERMANENTLY INERT here: compress/decompress targeting them always fails by design — do not retry variations. Any number at or below the frontier that exists in this report may point at a DIFFERENT message than before the boundary. If your last pre-boundary instruction involved executing steps (writes, commands, pushes, syncs, deploys), verify disk/git state before reporting completion.`);
}
} catch {
// Display-only; never break the status report.
}
if (breaker) {
extra.push("");
extra.push(`COMPRESS CIRCUIT BREAKER: ARMED — consecutiveFailures: ${breaker.n} / ${breaker.threshold}. Disarms on one substantial compress (a trivial one that saves almost nothing does not count) or ${breaker.decayMinutes} min without further failures.`);
Expand Down
10 changes: 10 additions & 0 deletions src/decompress-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { dirname, join, resolve as resolvePath } from "node:path";
import { tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import { blockContentSnapshot, markDirty, preCompactionArchiveOf, peekSession, findSessionByCanonicalId, type Session } from "./session.js";
import { readGenerationBoundary } from "./generation-boundary.js";
import { getStore } from "./persist.js";
import { ccrEnabled, contentStoreOf } from "./store.js";
import { safePrefix } from "./text-safe.js";
Expand Down Expand Up @@ -598,6 +599,15 @@ function resolveDerivedDecompress(
const header = `[Block ${blockId} content — ${count} item(s)${full ? ", full" : ""} · read-only from derived session ${anc.id} (#1333)]`;
return toolOk(`${header}\n${body}`);
}
// #5542: when this session's ledger was reset mid-conversation (witnessed
// or detected), a not-found is overwhelmingly a previous-generation id —
// say so explicitly instead of the bare "not found" that reads like a typo
// and invites retry loops on ids that can never resolve here.
const genBnd = readGenerationBoundary(ctx.session);
if (genBnd) {
const genIso = new Date(genBnd.at).toISOString();
return toolFail(`[Block ${blockId} not found] This session's ref/block ledger was reset mid-conversation (generation boundary since ${genIso}): ids minted before that boundary belong to the previous generation and are PERMANENTLY INERT under this session — decompress will always fail for them, do not retry variations. Recover context from surviving summaries (search_context) or re-derive from visible history.`);
}
return toolFail(`[Block ${blockId} not found]`);
}

Expand Down
90 changes: 80 additions & 10 deletions src/generation-boundary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,19 @@
// renders for the session's lifetime — static text, byte-stable across turns,
// prefix-cache safe after the (typically never-visible) one-time append.
//
// #5542 adds WITNESSED seeding: the two host-side split points where a new
// ref-ledger generation is born under an already-running conversation (a
// persona fork onto a suffixed session key, and the native-compaction rebase)
// call witnessGenerationReset AT THE MOMENT OF THE SPLIT. Residue detection
// alone is blind to exactly the worst case — a reset that cut off an execution
// tail discards the citing text too, so nothing ever triggers detection and
// the model reports completion of steps whose execution was lost, with zero
// trace of the reset anywhere user-visible. Witnessing makes the note ride
// from the first turn of the new generation, stamps the [acp-gen-reset] log
// marker at the split moment, and feeds the acp_status GENERATION BOUNDARY
// section. First-wins: the earliest boundary of a generation is the one the
// model must reason about.
//
// The note itself stays display-only and numberless: the frontier advances as
// the session allocates, and a fixed ceiling would go stale within turns —
// concrete ceilings stay with the reactive notes (beyondFrontierNote /
Expand All @@ -29,7 +42,8 @@
// needed, and annotating it without repairing it leaves compress rejecting every
// live ref for the rest of the session (#6061, #5589).

import { markDirty, markNativeCompactionBoundary, type Session } from "./session.js";
import { markDirty, markNativeCompactionBoundary, peekSession, type Session } from "./session.js";
import { getStore } from "./persist.js";
import type { CoreMessage } from "acp-kernel";

/** Session-metadata key for the one-shot detection record. */
Expand All @@ -48,20 +62,28 @@ const REF_CITATION_RE = /\bm(\d{4,})\b/g;
const BYREF_KEY_RE = /^m(\d+)$/;

interface GenerationBoundaryRecord {
/** First-detection time (ms epoch). */
/** First-detection/witness time (ms epoch). */
at: number;
/** This session's highest mapped ref at detection ("mNNNNN" or "" when none) — evidence anchor, log surface only. */
/** The previous generation's highest ref ("mNNNNN" or "" when none) — evidence anchor, log/display surface only. */
frontier: string;
/** Highest stale citation seen at detection — log surface only. */
maxStaleRef: string;
/** Highest stale citation seen at detection — log surface only. Absent on witnessed records (no residue scan ran). */
maxStaleRef?: string;
/** How the boundary came to be known ("persona-fork" / "native-compaction-rebase"); absent = residue-detected. */
reason?: string;
/** One-line human context for the witness (keys involved etc.) — display surface only. */
detail?: string;
}

export function readGenerationBoundary(session: Session): GenerationBoundaryRecord | undefined {
const raw = session.metadata?.[STORAGE_KEY];
if (!raw || typeof raw !== "object") return undefined;
const r = raw as Record<string, unknown>;
if (typeof r.at !== "number" || typeof r.frontier !== "string" || typeof r.maxStaleRef !== "string") return undefined;
return { at: r.at, frontier: r.frontier, maxStaleRef: r.maxStaleRef };
if (typeof r.at !== "number" || typeof r.frontier !== "string") return undefined;
const rec: GenerationBoundaryRecord = { at: r.at, frontier: r.frontier };
if (typeof r.maxStaleRef === "string") rec.maxStaleRef = r.maxStaleRef;
if (typeof r.reason === "string") rec.reason = r.reason;
if (typeof r.detail === "string") rec.detail = r.detail;
return rec;
}

/** Highest allocated mNNNNN number in the session's ref map (0 when empty).
Expand Down Expand Up @@ -142,7 +164,55 @@ export function detectGenerationBoundary(
return true;
}

/** #5542: witness a ref-ledger generation reset AT THE MOMENT IT HAPPENS. The
* two host-side split points call this (a persona fork onto a suffixed session
* key, and the native-compaction rebase) so the standing note rides from the
* FIRST turn of the new generation instead of waiting for residue detection —
* which never fires when the reset discarded the citing text too. First-wins:
* an already-recorded boundary (witnessed or detected) is never overwritten.
* Returns true when the record was seeded by this call. */
export function witnessGenerationReset(
session: Session,
witness: { reason: string; detail?: string; frontier: number },
log?: (level: string, msg: string) => void,
): boolean {
if (readGenerationBoundary(session)) return false;
const record: GenerationBoundaryRecord = {
at: Date.now(),
frontier: witness.frontier > 0 ? indexToRef(witness.frontier) : "",
reason: witness.reason,
};
if (witness.detail) record.detail = witness.detail;
(session.metadata ?? (session.metadata = {}))[STORAGE_KEY] = record;
markDirty(session);
log?.("info", `[${session.id}] [acp-gen-reset] ref-ledger generation reset witnessed (${witness.reason}${witness.detail ? ` — ${witness.detail}` : ""}; previous-generation frontier ${record.frontier || "unknown"}) — refs minted before this session's ledger are inert here; standing generation-boundary note active from this turn (#5542)`);
return true;
}

/** #5542: persona-fork variant of the witness, called from the conversation-
* resolution seam where a request lands on a FRESH suffixed-key session while
* its conversation id already owns a session. Witnesses only when there is a
* previous generation to lose: the forked session is still empty AND the raw
* session has minted refs (a fork born before any main turn — #2156 title-gen
* sidecar — has none). Returns true when the record was seeded. */
export function witnessForkedGeneration(
session: Session,
rawSessionId: string,
conversationKey: string,
log?: (level: string, msg: string) => void,
): boolean {
if (session.state.blocks.length > 0 || highestMappedIndex(session.state) > 0) return false;
const rawSess = peekSession(rawSessionId) ?? getStore().loadSync(rawSessionId) ?? undefined;
const rawFrontier = rawSess ? highestMappedIndex(rawSess.state) : 0;
if (rawFrontier <= 0) return false;
return witnessGenerationReset(session, {
reason: "persona-fork",
detail: `conversation ${rawSessionId} forked onto ${conversationKey}`,
frontier: rawFrontier,
}, log);
}

/** Standing model-visible note, appended to the ACP standing system block once
* detected. Static by design (see module header) — it must never embed moving
* values or the prefix cache breaks every allocation. */
export const GENERATION_BOUNDARY_NOTE = "Generation boundary: this conversation's message-ref ledger was reset mid-conversation (a model or upstream switch restarted refs at m00001). Refs quoted earlier in your visible history — tool results, summaries, your own earlier replies — may belong to the previous generation: some are permanently inert (compress/decompress targeting them always fails), and any number that happens to exist in the current ledger now points at a DIFFERENT message than before. Before calling compress, verify every ref you plan to target against the current acp_status report; do not trust refs quoted in older tool results or summaries.";
* detected OR witnessed. Static by design (see module header) — it must never
* embed moving values or the prefix cache breaks every allocation. */
export const GENERATION_BOUNDARY_NOTE = "Generation boundary: this conversation's message-ref ledger was reset mid-conversation (a model or upstream switch restarted refs at m00001). Refs quoted earlier in your visible history — tool results, summaries, your own earlier replies — may belong to the previous generation: some are permanently inert (compress/decompress targeting them always fails), and any number that happens to exist in the current ledger now points at a DIFFERENT message than before. Before calling compress, verify every ref you plan to target against the current acp_status report; do not trust refs quoted in older tool results or summaries. If your last instruction before this boundary involved EXECUTING steps (writing files, running commands, pushing, syncing, deploying), treat any earlier 'done'/'completed' report as UNVERIFIED — the execution tail may have been lost across the boundary while its planning and reporting survived in summaries. Check the real state (disk, git, remotes) before claiming completion.";
10 changes: 10 additions & 0 deletions src/server/handle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { bodyMightCarryImages, buildIncomingImageIndex, pruneRetrieveImgExports,
import { durableMessageToolPaths, withDurableProtection } from "../durable-message-guards.js";
import { biliToolsDeclaredOnWire, countBiliToolUses, declaresMcpBiliToolsOnWire, evaluateSelfHealRound, pluginLaneDegraded, pluginLaneRestore } from "../session-self-heal.js";
import { acquireInFlight, getSessionAsync, hasProcessedState, markDirty, peekSession, releaseInFlight, storeEffectiveConfig, tickPostRebuildAnchor, withSessionLock, type Session } from "../session.js";
import { witnessForkedGeneration } from "../generation-boundary.js";
import { buildCompressSystemPrompt } from "../compress-tool.js";
import { storeEffectiveSearchPlanAware } from "../decompress-shared.js";
import { externalSummaryEnabled, messageTimestampSections } from "../external-summary-surface.js";
Expand Down Expand Up @@ -2010,6 +2011,15 @@ async function handleRequest(
log("warn", `[window] model=${reqModelId} still unresolved after ${UNRESOLVED_MODEL_SESSION_THRESHOLD}+ sessions (no table/registry/configured/plugin evidence; anonymous default ${reqConfig.modelContextLimit} in force) — declare providers.<upstream>.models.${reqModelId}.context (and .output) to stop sizing against the guess (#5490)`);
}
if (designNamespaced && session.metadata.personaNamespace !== true) session.metadata.personaNamespace = true;
// #5542: a FRESH persona fork restarts the ref ledger at m00001 under a
// suffixed key while the model's visible history keeps citing the RAW
// session's refs — witness the generation reset at the split moment so
// the standing note, the [acp-gen-reset] marker and the acp_status
// GENERATION BOUNDARY section are live from the fork's first turn. The
// helper gates itself (fresh fork + raw session with minted refs).
if (personaForked && rawPersonaIdentity !== undefined) {
witnessForkedGeneration(session, rawPersonaIdentity, conversation, log);
}
let publicForkPrefix = false;
if (!countTokens && !responsesCompact && session.metadata.publicForkReceipt !== undefined) {
acquireInFlight(session);
Expand Down
10 changes: 10 additions & 0 deletions src/session.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createInitialState, defaultConfig, highestUsedIndex, indexToRef, type CompressionState, type Config, type CoreMessage, type MessageContentStore, type NudgeDecision } from "acp-kernel";
import { createHash } from "node:crypto";
import { log as loggerLog } from "./logger.js";
import { witnessGenerationReset } from "./generation-boundary.js";
import { getStore, effectiveFileStorageMode } from "./persist.js";
import { VERSION } from "./version.js";
import { maxSessions as knobMaxSessions, sessionWarmMax, sessionWarmMaxBytes, sessionResidentMaxBytes } from "./knobs.js";
Expand Down Expand Up @@ -1948,6 +1949,15 @@ export function reconcileNativeCompactionBoundary(session: Session): boolean {
rebasedAt: Date.now(),
};
markDirty(session);
// #5542: witness the reset at the rebase moment itself — the compacted
// resend starts a fresh m00001 ledger while the visible history keeps
// citing pre-compaction refs, so the standing note + [acp-gen-reset]
// marker go live from the next turn without waiting for residue detection.
witnessGenerationReset(session, {
reason: "native-compaction-rebase",
detail: "client-native compaction rebased the ACP state onto the compacted history",
frontier: highestBefore,
}, loggerLog);
return true;
}

Expand Down
Loading
Loading