Forráskód Böngészése

perf: reuse long-history token counts and owned snapshots (#254)

SaladDay 2 hónapja
szülő
commit
6d79b10e2f

+ 1 - 1
docs/performance-ci.md

@@ -17,7 +17,7 @@ revisions build separately, then run serially on one `macos-15` runner with Node
 | --- | --- | --- |
 | `startup` | 1 tool round, minimal body | Startup and shutdown |
 | `upstream-100` | 100 rounds × approximately 4 KiB, 64-character chunks, zero delay | Original [harness-perf-benchmark](https://github.com/KonghaYao/harness-perf-benchmark) workload |
-| `history-300` | 300 rounds × approximately 8 KiB | History growth beyond the 1,048,576 UTF-16-unit token cache budget |
+| `history-300` | 300 rounds × approximately 8 KiB | History growth beyond the original 1,048,576 UTF-16-unit token cache budget |
 
 The upstream commit is pinned in `scripts/perf/config.json` and the workflow.
 Its generator, mock, sampler and CPU accounting run without source edits.

+ 19 - 17
packages/agent-modules/context-manager/src/token-estimator.ts

@@ -47,6 +47,7 @@
 
 import type { AgentMessage } from '@earendil-works/pi-agent-core';
 import { Buffer } from 'node:buffer';
+import { createHash } from 'node:crypto';
 import { countTokens as countO200kBase } from 'gpt-tokenizer/model/gpt-4o';
 import type { ContextCompactionSummaryMessage } from './types.js';
 
@@ -199,15 +200,14 @@ function getLastAssistantUsageInfo(
   return undefined;
 }
 
-const MAX_CACHED_TEXT_UNITS = 1_048_576;
+const MAX_INLINE_CACHE_KEY_UNITS = 256;
 const MAX_CACHED_TEXT_ENTRIES = 2_048;
 
 export class BpeTokenEstimator implements TokenEstimator {
   private readonly countExactTokens: (text: string) => number;
-  // Content keys remain valid across detached histories, edits and model
-  // projections. Bound retained UTF-16 text as well as entry count.
+  // Bounded content keys survive detached histories without retaining long
+  // message bodies. Hash UTF-16 units so lone surrogates stay distinct.
   private readonly textTokens = new Map<string, number>();
-  private cachedTextUnits = 0;
 
   /**
    * @param encoder Override the default o200k_base tokenizer. Tests inject
@@ -229,10 +229,14 @@ export class BpeTokenEstimator implements TokenEstimator {
 
   estimateTextTokens(text: string): number {
     if (!text) return 0;
-    const cached = this.textTokens.get(text);
+    const key =
+      text.length <= MAX_INLINE_CACHE_KEY_UNITS
+        ? `text:${text}`
+        : `sha256:${createHash('sha256').update(text, 'utf16le').digest('hex')}`;
+    const cached = this.textTokens.get(key);
     if (cached !== undefined) {
-      this.textTokens.delete(text);
-      this.textTokens.set(text, cached);
+      this.textTokens.delete(key);
+      this.textTokens.set(key, cached);
       return cached;
     }
     try {
@@ -241,16 +245,11 @@ export class BpeTokenEstimator implements TokenEstimator {
       }
       const tokens = this.countExactTokens(text);
       if (!Number.isFinite(tokens) || tokens < 0) return estimateTextTokensUpperBound(text);
-      if (text.length <= MAX_CACHED_TEXT_UNITS) {
-        while (this.textTokens.size >= MAX_CACHED_TEXT_ENTRIES || this.cachedTextUnits + text.length > MAX_CACHED_TEXT_UNITS) {
-          const oldest = this.textTokens.keys().next().value;
-          if (oldest === undefined) break;
-          this.textTokens.delete(oldest);
-          this.cachedTextUnits -= oldest.length;
-        }
-        this.textTokens.set(text, tokens);
-        this.cachedTextUnits += text.length;
+      if (this.textTokens.size >= MAX_CACHED_TEXT_ENTRIES) {
+        const oldest = this.textTokens.keys().next().value;
+        if (oldest !== undefined) this.textTokens.delete(oldest);
       }
+      this.textTokens.set(key, tokens);
       return tokens;
     } catch {
       return estimateTextTokensUpperBound(text);
@@ -314,7 +313,10 @@ export class BpeTokenEstimator implements TokenEstimator {
         return tokens;
       }
       case 'bashExecution': {
-        const m = message as AgentMessage & { command?: string; output?: string };
+        const m = message as AgentMessage & {
+          command?: string;
+          output?: string;
+        };
         tokens += this.estimateTextTokens(m.command ?? '');
         tokens += this.estimateTextTokens(m.output ?? '');
         return tokens;

+ 11 - 5
packages/local-runtime-v2/src/infra/file/canonical-history-jsonl.ts

@@ -244,8 +244,7 @@ interface MinimalNativeCompactionSummary extends Record<string, unknown> {
 }
 
 export type CanonicalHistoryMessage =
-  | TimestampedCanonicalHistoryMessage
-  | MinimalNativeCompactionSummary;
+  TimestampedCanonicalHistoryMessage | MinimalNativeCompactionSummary;
 
 export interface CanonicalTurnConfigTool extends Record<string, unknown> {
   readonly tool_name: string;
@@ -431,10 +430,15 @@ export class CanonicalHistoryJsonlDataSource {
     return { status, records: await this.readActive() };
   }
 
-  async append(records: readonly CanonicalHistoryEnvelope[]): Promise<void> {
+  async append(
+    records: readonly CanonicalHistoryEnvelope[],
+    verifiedActive?: readonly CanonicalHistoryEnvelope[],
+  ): Promise<void> {
     const appended = decodeRecords(records);
     if (appended.length === 0) return;
-    const active = await this.readActive();
+    // The Session owner may pass its strict read from this same write lane.
+    // Other callers keep the existing disk read; no history survives between operations.
+    const active = verifiedActive ?? (await this.readActive());
     assertCanonicalHistoryAppend(active, appended);
     await appendJsonl(this.options.activePath, appended);
   }
@@ -473,7 +477,9 @@ export class CanonicalHistoryJsonlDataSource {
       const existing = await readStrictEnvelopeFile(snapshotPath);
       if (revisionOfNormalized(existing) !== revision) throw new Error('revision differs');
     } catch (error) {
-      throw new Error(`Canonical history snapshot conflict: ${snapshotPath}`, { cause: error });
+      throw new Error(`Canonical history snapshot conflict: ${snapshotPath}`, {
+        cause: error,
+      });
     }
     return status;
   }

+ 10 - 3
packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-materializer.ts

@@ -64,20 +64,21 @@ interface MaterializedHistory {
 export async function ensureCanonicalHistoryMaterialized(
   options: CanonicalHistoryMaterializerOptions,
 ): Promise<void> {
-  const target = await options.files.readTarget(options.paths.messages);
   if (!options.legacyHistory) {
-    if (target === undefined) await options.files.publishInitial(options.paths.messages, []);
+    if (!(await targetExists(options)))
+      await options.files.publishInitial(options.paths.messages, []);
     return;
   }
 
   const checkpoint = await options.legacyHistory.checkpoints.getCheckpoint(options.sessionId);
   if (checkpoint) {
-    if (target === undefined) {
+    if (!(await targetExists(options))) {
       throw new Error(`Canonical history target is missing after migration: ${options.sessionId}`);
     }
     return;
   }
 
+  const target = await options.files.readTarget(options.paths.messages);
   const selected = await selectLegacySource(options);
   const normalized = normalizeSelectedHistory(options.sessionId, selected.records);
   const materialized =
@@ -103,6 +104,12 @@ export async function ensureCanonicalHistoryMaterialized(
   });
 }
 
+async function targetExists(options: CanonicalHistoryMaterializerOptions): Promise<boolean> {
+  return options.files.targetExists
+    ? options.files.targetExists(options.paths.messages)
+    : (await options.files.readTarget(options.paths.messages)) !== undefined;
+}
+
 async function selectLegacySource(options: CanonicalHistoryMaterializerOptions): Promise<{
   readonly source: CanonicalHistoryMigrationSource;
   readonly records: readonly CanonicalHistoryEnvelope[];

+ 1 - 1
packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-provider.ts

@@ -434,7 +434,7 @@ async function appendWithInterruptedToolRoundRecovery(input: {
     await input.files.replaceActive(input.path, recovery.records);
     return;
   }
-  await input.files.append(input.path, input.appended);
+  await input.files.append(input.path, input.appended, input.existing);
 }
 
 function appendEnvelopes(change: SessionCanonicalHistoryChange): CanonicalHistoryEnvelope[] {

+ 8 - 1
packages/local-runtime-v2/src/service/session-system/sessions/representation/canonical-history-contract.ts

@@ -13,6 +13,8 @@ export {
 } from '../../../../infra/file/canonical-history.js';
 
 export interface CanonicalHistoryFileAdapter {
+  /** Existence-only migration probe; callers still validate records before using them. */
+  targetExists?(path: string): Promise<boolean>;
   readTarget(path: string): Promise<readonly CanonicalHistoryEnvelope[] | undefined>;
   readTargetStrict(path: string): Promise<readonly CanonicalHistoryEnvelope[] | undefined>;
   readActive(path: string): Promise<readonly CanonicalHistoryEnvelope[]>;
@@ -23,7 +25,12 @@ export interface CanonicalHistoryFileAdapter {
     path: string,
     records: readonly CanonicalHistoryEnvelope[],
   ): Promise<CanonicalHistoryPublication>;
-  append(path: string, records: readonly CanonicalHistoryEnvelope[]): Promise<void>;
+  /** verifiedActive must be read in the same serialized operation, never cached across writes. */
+  append(
+    path: string,
+    records: readonly CanonicalHistoryEnvelope[],
+    verifiedActive?: readonly CanonicalHistoryEnvelope[],
+  ): Promise<void>;
   replace(path: string, records: readonly CanonicalHistoryEnvelope[]): Promise<void>;
   replaceActive(path: string, records: readonly CanonicalHistoryEnvelope[]): Promise<void>;
   publishSnapshot(

+ 9 - 2
packages/local-runtime-v2/src/service/session-system/sessions/representation/canonical-history.ts

@@ -20,6 +20,9 @@ export function createCanonicalHistoryFileAdapter(
 class JsonlCanonicalHistoryFileAdapter implements CanonicalHistoryFileAdapter {
   constructor(private readonly options: CreateCanonicalHistoryFileAdapterOptions) {}
 
+  async targetExists(path: string) {
+    return exists(path);
+  }
   async readTarget(path: string) {
     if (!(await exists(path))) return undefined;
     return this.source(path).readActive();
@@ -43,8 +46,12 @@ class JsonlCanonicalHistoryFileAdapter implements CanonicalHistoryFileAdapter {
   async publishInitial(path: string, records: readonly CanonicalHistoryEnvelope[]) {
     return this.source(path).publishInitial(records);
   }
-  async append(path: string, records: readonly CanonicalHistoryEnvelope[]) {
-    await this.source(path).append(records);
+  async append(
+    path: string,
+    records: readonly CanonicalHistoryEnvelope[],
+    verifiedActive?: readonly CanonicalHistoryEnvelope[],
+  ) {
+    await this.source(path).append(records, verifiedActive);
   }
   async replace(path: string, records: readonly CanonicalHistoryEnvelope[]) {
     await this.source(path).replace(records);

+ 70 - 3
packages/local-runtime-v2/src/service/turn-system/agent-host/history/semantic-identity.ts

@@ -1,3 +1,4 @@
+import { types } from 'node:util';
 import { IncrementalSha256 } from './incremental-sha256.js';
 
 export interface SemanticSnapshot<T> {
@@ -15,12 +16,15 @@ const fingerprints = new WeakMap<object, string>();
  * encoded payload size.
  */
 export function captureSemanticSnapshot<T>(value: T): SemanticSnapshot<T> {
-  // Clone an external graph in one operation: independent subtree clones can
-  // change aliasing and getter order. Reuse only an already-owned root.
+  // Native cloning preserves external getters and aliases. Data-only wrappers
+  // can instead share descendants already detached and frozen by this module.
   const snapshot =
     typeof value === 'object' && value !== null && ownedValues.has(value)
       ? value
-      : freezeSemanticValue(structuredClone(value), new WeakSet<object>());
+      : freezeSemanticValue(
+          cloneOwnedWrapper(value) ?? structuredClone(value),
+          new WeakSet<object>(),
+        );
   let fingerprint: string | undefined;
   return {
     value: snapshot,
@@ -41,6 +45,69 @@ export function captureSemanticSnapshot<T>(value: T): SemanticSnapshot<T> {
   };
 }
 
+const NATIVE_CLONE_REQUIRED = Symbol('native-clone-required');
+
+function plainDataDescriptors(value: object): PropertyDescriptorMap | undefined {
+  // Inspecting a Proxy would invoke traps that native structuredClone rejects.
+  if (types.isProxy(value)) return undefined;
+  const prototype = Object.getPrototypeOf(value);
+  if (
+    prototype !== Object.prototype &&
+    prototype !== null &&
+    !(Array.isArray(value) && prototype === Array.prototype)
+  )
+    return undefined;
+  const descriptors = Object.getOwnPropertyDescriptors(value);
+  if (Object.values(descriptors).some((d) => d.enumerable && !('value' in d))) return undefined;
+  return descriptors;
+}
+
+function cloneOwnedWrapper<T>(value: T): T | undefined {
+  if (typeof value !== 'object' || value === null) return undefined;
+  const descriptors = plainDataDescriptors(value);
+  if (
+    !descriptors ||
+    !Object.values(descriptors).some(
+      (d) =>
+        d.enumerable && typeof d.value === 'object' && d.value !== null && ownedValues.has(d.value),
+    )
+  )
+    return undefined;
+
+  const copies = new WeakMap<object, object>();
+  const clone = (node: unknown): unknown => {
+    if (typeof node !== 'object' || node === null) {
+      if (node !== null && !['undefined', 'string', 'boolean', 'number'].includes(typeof node)) {
+        throw NATIVE_CLONE_REQUIRED;
+      }
+      return node;
+    }
+    if (ownedValues.has(node)) return node;
+    const previous = copies.get(node);
+    if (previous) return previous;
+    const fields = node === value ? descriptors : plainDataDescriptors(node);
+    if (!fields) throw NATIVE_CLONE_REQUIRED;
+    const copy = Array.isArray(node) ? new Array(fields.length!.value as number) : {};
+    copies.set(node, copy);
+    for (const [key, field] of Object.entries(fields)) {
+      if (!field.enumerable) continue;
+      Object.defineProperty(copy, key, {
+        value: clone(field.value),
+        enumerable: true,
+        writable: true,
+        configurable: true,
+      });
+    }
+    return copy;
+  };
+  try {
+    return clone(value) as T;
+  } catch (error) {
+    if (error === NATIVE_CLONE_REQUIRED) return undefined;
+    throw error;
+  }
+}
+
 /**
  * Measures the streamed semantic representation without cloning or building
  * a canonical string. Used only for already-detached replay results.

+ 192 - 5
test/history-processing.test.ts

@@ -1,4 +1,5 @@
 import { createHash } from 'node:crypto';
+import { CanonicalHistoryJsonlDataSource } from '../packages/local-runtime-v2/src/infra/file/canonical-history-jsonl.js';
 import { mkdtemp, rm, writeFile } from 'node:fs/promises';
 import { tmpdir } from 'node:os';
 import { join } from 'node:path';
@@ -8,6 +9,7 @@ import { captureSemanticSnapshot } from '../packages/local-runtime-v2/src/servic
 import { DurableCanonicalHistoryStore } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/durable-canonical-history-store.js';
 import type { CanonicalHistoryChange } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/contracts.js';
 import { BpeTokenEstimator } from '../packages/agent-modules/context-manager/src/token-estimator.js';
+import { ensureCanonicalHistoryMaterialized } from '../packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-materializer.js';
 import { createSessionSystemCanonicalHistoryProvider } from '../packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-provider.js';
 import { createCanonicalHistoryFileAdapter } from '../packages/local-runtime-v2/src/service/session-system/sessions/representation/canonical-history.js';
 import {
@@ -53,7 +55,7 @@ describe('semantic snapshots', () => {
       const wrapped = captureSemanticSnapshot({
         history: snapshot.value.messages,
       });
-      expect(wrapped.value.history).not.toBe(snapshot.value.messages);
+      expect(wrapped.value.history).toBe(snapshot.value.messages);
       expect(wrapped.value.history).toEqual(snapshot.value.messages);
       const fingerprint = snapshot.fingerprint;
       expect(hash).toHaveBeenCalled();
@@ -65,6 +67,71 @@ describe('semantic snapshots', () => {
       hash.mockRestore();
     }
   });
+  it('shares owned history through delivery wrappers and detaches other branches', () => {
+    const history = captureSemanticSnapshot({
+      messages: [{ text: 'body' }],
+    }).value;
+    const external = { nested: { id: 1 } };
+    const delivered = captureSemanticSnapshot({
+      committedMessages: history.messages,
+      external,
+    });
+    const event = captureSemanticSnapshot({
+      context: external,
+      change: delivered.value,
+    });
+    external.nested.id = 2;
+    expect(delivered.value.committedMessages).toBe(history.messages);
+    expect(event.value.change).toBe(delivered.value);
+    expect(event.value.context.nested.id).toBe(1);
+    expect(event.value.change.external.nested.id).toBe(1);
+    expect(Object.isFrozen(event.value.context.nested)).toBe(true);
+    expect(event.fingerprint).toBe(
+      captureSemanticSnapshot(structuredClone(event.value)).fingerprint,
+    );
+  });
+  it('preserves aliases, sparse arrays and own __proto__ fields in owned wrappers', () => {
+    const owned = captureSemanticSnapshot({ value: 'owned' }).value;
+    const shared = { owned };
+    const array = new Array(3);
+    array[2] = shared;
+    const input = { owned, a: shared, b: shared, array, ['__proto__']: shared };
+    const snapshot = captureSemanticSnapshot(input);
+    expect(snapshot.value.a).toBe(snapshot.value.b);
+    expect(snapshot.value.a).toBe(snapshot.value.array[2]);
+    expect(snapshot.value['__proto__']).toBe(snapshot.value.a);
+    expect(0 in snapshot.value.array).toBe(false);
+    expect(snapshot.value).toEqual(structuredClone(input));
+    const cycle: Record<string, unknown> = { owned };
+    cycle.self = cycle;
+    expect(() => captureSemanticSnapshot(cycle)).toThrow('Cyclic');
+  });
+  it('uses native getter ordering and proxy rejection even beside owned values', () => {
+    const owned = captureSemanticSnapshot({ text: 'owned' }).value;
+    const shared = { value: 1 };
+    const getter = vi.fn(() => {
+      shared.value = 2;
+      return shared;
+    });
+    const snapshot = captureSemanticSnapshot({
+      owned,
+      shared,
+      get later() {
+        return getter();
+      },
+    });
+    expect(snapshot.value.shared).toBe(snapshot.value.later);
+    expect(snapshot.value.shared.value).toBe(1);
+    expect(getter).toHaveBeenCalledTimes(1);
+    const trap = vi.fn();
+    expect(() =>
+      captureSemanticSnapshot({
+        owned,
+        proxy: new Proxy({}, { ownKeys: trap }),
+      }),
+    ).toThrow();
+    expect(trap).not.toHaveBeenCalled();
+  });
   it('does not trust externally frozen objects with mutable descendants', () => {
     const original = Object.freeze({ nested: { text: 'before' } });
     const snapshot = captureSemanticSnapshot(original);
@@ -101,7 +168,10 @@ describe('semantic snapshots', () => {
             return getter();
           },
         };
-        return { input: getterFirst ? { nested, shared } : { shared, nested }, getter };
+        return {
+          input: getterFirst ? { nested, shared } : { shared, nested },
+          getter,
+        };
       };
       const expected = structuredClone(makeInput().input);
       const { input, getter } = makeInput();
@@ -117,7 +187,10 @@ describe('semantic snapshots', () => {
     class Container {
       child = shared;
     }
-    const snapshot = captureSemanticSnapshot({ shared, nested: new Container() });
+    const snapshot = captureSemanticSnapshot({
+      shared,
+      nested: new Container(),
+    });
     expect(snapshot.value.shared).toBe(snapshot.value.nested.child);
     expect(Object.getPrototypeOf(snapshot.value.nested)).toBe(Object.prototype);
   });
@@ -184,6 +257,31 @@ describe('bounded token count reuse', () => {
     );
     expect(encode).toHaveBeenCalledTimes(3);
   });
+  it.each([256, 257, 300])(
+    'reuses detached histories above the former text budget (%i messages)',
+    (count) => {
+      const encode = vi.fn(() => [1]);
+      const estimator = new BpeTokenEstimator(encode);
+      const messages = Array.from({ length: count }, (_, i) => ({
+        role: 'user' as const,
+        content: String(i).padStart(8, '0') + 'x '.repeat(2044),
+        timestamp: i,
+      }));
+      const first = estimator.estimateMessages(messages);
+      encode.mockClear();
+      expect(estimator.estimateMessages(structuredClone(messages))).toBe(first);
+      expect(encode).not.toHaveBeenCalled();
+      messages[0]!.content = 'changed ' + messages[0]!.content.slice(8);
+      estimator.estimateMessages(messages);
+      expect(encode).toHaveBeenCalledTimes(1);
+    },
+  );
+  it('keeps distinct malformed UTF-16 strings separate in long-text keys', () => {
+    const prefix = 'x '.repeat(256);
+    const estimator = new BpeTokenEstimator((text) => (text.endsWith('\ud800') ? [1] : [1, 2]));
+    expect(estimator.estimateTextTokens(prefix + '\ud800')).toBe(1);
+    expect(estimator.estimateTextTokens(prefix + '\ud801')).toBe(2);
+  });
   it('isolates different estimators and evicts least-recently-used text', () => {
     const encode = vi.fn((text: string) => [...text]);
     const estimator = new BpeTokenEstimator(encode);
@@ -194,7 +292,7 @@ describe('bounded token count reuse', () => {
     expect(encode).toHaveBeenCalledTimes(1);
     expect(new BpeTokenEstimator(() => [0]).estimateTextTokens('old')).toBe(1);
   });
-  it('bounds retained text independently of entry count', () => {
+  it('reuses large texts without retaining their bodies', () => {
     const encode = vi.fn(() => [1]);
     const estimator = new BpeTokenEstimator(encode);
     const first = 'a '.repeat(300_000);
@@ -202,7 +300,7 @@ describe('bounded token count reuse', () => {
     estimator.estimateTextTokens(first);
     estimator.estimateTextTokens(second);
     estimator.estimateTextTokens(first);
-    expect(encode).toHaveBeenCalledTimes(3);
+    expect(encode).toHaveBeenCalledTimes(2);
   });
   it('does not cache tokenizer failures', () => {
     const encode = vi
@@ -220,6 +318,7 @@ describe('bounded token count reuse', () => {
 describe('committed history read reuse', () => {
   it('reuses verified records for indexing while observing external changes and corruption', async () => {
     const dataDir = await mkdtemp(join(tmpdir(), 'mcode-history-reuse-'));
+    const redundantRead = vi.spyOn(CanonicalHistoryJsonlDataSource.prototype, 'readActive');
     try {
       const session: SessionRecord = {
         sessionId: 'synthetic-session',
@@ -243,6 +342,7 @@ describe('committed history read reuse', () => {
       });
       await provider.initialize(session.sessionId);
       strictRead.mockClear();
+      redundantRead.mockClear();
       expect((await provider.readActive(session.sessionId)).messages).toEqual([]);
       expect(strictRead).not.toHaveBeenCalled();
       const committed = await provider.append({
@@ -254,6 +354,7 @@ describe('committed history read reuse', () => {
       });
       expect(committed.messages).toHaveLength(1);
       expect(strictRead).toHaveBeenCalledTimes(1);
+      expect(redundantRead).not.toHaveBeenCalled();
       const paths = resolveSessionHistoryPaths(dataDir, session);
       const external = createCanonicalHistoryFileAdapter();
       await external.replace(paths.messages, [
@@ -268,6 +369,92 @@ describe('committed history read reuse', () => {
       });
       await writeFile(paths.messages, '{invalid json}\n');
       await expect(provider.readActive(session.sessionId)).rejects.toThrow();
+      await expect(
+        provider.append({
+          sessionId: session.sessionId,
+          turnId: 'turn-3',
+          reason: 'messageDelta',
+          messages: [{ role: 'user', content: 'must not append', timestamp: 3 }],
+          operation: { id: 'append-3', kind: 'append' },
+        }),
+      ).rejects.toThrow();
+    } finally {
+      redundantRead.mockRestore();
+      await rm(dataDir, { recursive: true, force: true });
+    }
+  });
+  it('checks migration target existence without reparsing and preserves legacy adapter fallback', async () => {
+    const dataDir = await mkdtemp(join(tmpdir(), 'mcode-materialized-'));
+    try {
+      const sessionId = 'synthetic-session';
+      const paths = resolveSessionHistoryPaths(dataDir, {
+        sessionId,
+        createdAtMs: 0,
+      });
+      const files = createCanonicalHistoryFileAdapter();
+      const read = vi.spyOn(files, 'readTarget');
+      const options = { sessionId, paths, files, nowMs: () => 0 };
+      await ensureCanonicalHistoryMaterialized(options);
+      const legacyHistory = {
+        sources: {
+          readLedgerSnapshot: vi.fn(async () => undefined),
+          readSqliteRows: vi.fn(async () => []),
+          readSqliteBlob: vi.fn(async () => []),
+        },
+        checkpoints: {
+          getCheckpoint: async () => ({
+            sessionId,
+            migratedAtMs: 0,
+            source: 'empty' as const,
+            messageCount: 0,
+            targetRevision: 'recorded',
+          }),
+          upsertCheckpoint: vi.fn(async () => {}),
+        },
+      };
+      await ensureCanonicalHistoryMaterialized({ ...options, legacyHistory });
+      expect(read).not.toHaveBeenCalled();
+      expect(legacyHistory.sources.readLedgerSnapshot).not.toHaveBeenCalled();
+      Object.defineProperty(files, 'targetExists', { value: undefined });
+      await ensureCanonicalHistoryMaterialized({ ...options, legacyHistory });
+      expect(read).toHaveBeenCalledTimes(1);
+      await rm(paths.messages);
+      await expect(
+        ensureCanonicalHistoryMaterialized({ ...options, legacyHistory }),
+      ).rejects.toThrow('missing after migration');
+    } finally {
+      await rm(dataDir, { recursive: true, force: true });
+    }
+  });
+  it('retains disk reads for standalone appends and validates supplied prefix identities', async () => {
+    const dataDir = await mkdtemp(join(tmpdir(), 'mcode-append-prefix-'));
+    try {
+      const source = new CanonicalHistoryJsonlDataSource({
+        activePath: join(dataDir, 'messages.jsonl'),
+      });
+      await source.publishInitial([]);
+      const first = {
+        message_id: 'msg-first',
+        turn_id: 'turn-first',
+        message: { role: 'user', content: 'first', timestamp: 1 },
+      };
+      const second = {
+        message_id: 'msg-second',
+        turn_id: 'turn-second',
+        message: { role: 'user', content: 'second', timestamp: 2 },
+      };
+      const read = vi.spyOn(source, 'readActive');
+      await source.append([first]);
+      expect(read).toHaveBeenCalledTimes(1);
+      const verified = await source.readActiveStrict();
+      read.mockClear();
+      await expect(source.append([first], verified)).rejects.toThrow();
+      await source.append([second], verified);
+      expect(read).not.toHaveBeenCalled();
+      expect((await source.readActiveStrict()).map((row) => row.message_id)).toEqual([
+        'msg-first',
+        'msg-second',
+      ]);
     } finally {
       await rm(dataDir, { recursive: true, force: true });
     }