history-processing.test.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516
  1. import { createHash } from 'node:crypto';
  2. import { CanonicalHistoryJsonlDataSource } from '../packages/local-runtime-v2/src/infra/file/canonical-history-jsonl.js';
  3. import { mkdtemp, rm, writeFile } from 'node:fs/promises';
  4. import { tmpdir } from 'node:os';
  5. import { join } from 'node:path';
  6. import { describe, expect, it, vi } from 'vitest';
  7. import { IncrementalSha256 } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/incremental-sha256.js';
  8. import { captureSemanticSnapshot } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/semantic-identity.js';
  9. import { DurableCanonicalHistoryStore } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/durable-canonical-history-store.js';
  10. import type { CanonicalHistoryChange } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/contracts.js';
  11. import { BpeTokenEstimator } from '../packages/agent-modules/context-manager/src/token-estimator.js';
  12. import { ensureCanonicalHistoryMaterialized } from '../packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-materializer.js';
  13. import { createSessionSystemCanonicalHistoryProvider } from '../packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-provider.js';
  14. import { createCanonicalHistoryFileAdapter } from '../packages/local-runtime-v2/src/service/session-system/sessions/representation/canonical-history.js';
  15. import {
  16. resolveSessionHistoryPaths,
  17. utcSessionHistoryRelativeDir,
  18. } from '../packages/local-runtime-v2/src/service/session-system/messages/history/session-history-paths.js';
  19. import type { SessionRecord } from '../packages/local-runtime-v2/src/service/session-system/sessions/repo/contract.js';
  20. describe('native incremental semantic hashing', () => {
  21. const inputs = ['', 'abc', '中文🙂', '\ud800', '\udc00', 'a'.repeat(8191) + '🙂tail'];
  22. for (const length of [55, 56, 63, 64, 65, 8191, 8192, 8193, 32769]) {
  23. inputs.push('x'.repeat(length), '中'.repeat(length));
  24. }
  25. it.each(inputs)('preserves UTF-8 hashing %#', (input) => {
  26. const hash = new IncrementalSha256();
  27. hash.update(input);
  28. expect(hash.digestHex()).toBe(createHash('sha256').update(input).digest('hex'));
  29. expect(() => hash.update('')).toThrow('finalized');
  30. expect(() => hash.digestHex()).toThrow('finalized');
  31. });
  32. it('preserves encoding boundaries between separate updates', () => {
  33. const hash = new IncrementalSha256();
  34. hash.update('\ud83d');
  35. hash.update('\ude42');
  36. expect(hash.digestHex()).toBe(
  37. createHash('sha256').update('\ud83d').update('\ude42').digest('hex'),
  38. );
  39. });
  40. });
  41. describe('semantic snapshots', () => {
  42. it('detaches and freezes eagerly but hashes only when identity is requested', () => {
  43. const hash = vi.spyOn(IncrementalSha256.prototype, 'update');
  44. try {
  45. const original = { messages: [{ text: 'before' }] };
  46. const snapshot = captureSemanticSnapshot(original);
  47. original.messages[0]!.text = 'after';
  48. expect(snapshot.value.messages[0]!.text).toBe('before');
  49. expect(Object.isFrozen(snapshot.value.messages[0])).toBe(true);
  50. expect(hash).not.toHaveBeenCalled();
  51. const reused = captureSemanticSnapshot(snapshot.value);
  52. expect(reused.value).toBe(snapshot.value);
  53. const wrapped = captureSemanticSnapshot({
  54. history: snapshot.value.messages,
  55. });
  56. expect(wrapped.value.history).toBe(snapshot.value.messages);
  57. expect(wrapped.value.history).toEqual(snapshot.value.messages);
  58. const fingerprint = snapshot.fingerprint;
  59. expect(hash).toHaveBeenCalled();
  60. hash.mockClear();
  61. expect(reused.fingerprint).toBe(fingerprint);
  62. expect(hash).not.toHaveBeenCalled();
  63. expect(captureSemanticSnapshot(original).fingerprint).not.toBe(fingerprint);
  64. } finally {
  65. hash.mockRestore();
  66. }
  67. });
  68. it('shares owned history through delivery wrappers and detaches other branches', () => {
  69. const history = captureSemanticSnapshot({
  70. messages: [{ text: 'body' }],
  71. }).value;
  72. const external = { nested: { id: 1 } };
  73. const delivered = captureSemanticSnapshot({
  74. committedMessages: history.messages,
  75. external,
  76. });
  77. const event = captureSemanticSnapshot({
  78. context: external,
  79. change: delivered.value,
  80. });
  81. external.nested.id = 2;
  82. expect(delivered.value.committedMessages).toBe(history.messages);
  83. expect(event.value.change).toBe(delivered.value);
  84. expect(event.value.context.nested.id).toBe(1);
  85. expect(event.value.change.external.nested.id).toBe(1);
  86. expect(Object.isFrozen(event.value.context.nested)).toBe(true);
  87. expect(event.fingerprint).toBe(
  88. captureSemanticSnapshot(structuredClone(event.value)).fingerprint,
  89. );
  90. });
  91. it('preserves aliases, sparse arrays and own __proto__ fields in owned wrappers', () => {
  92. const owned = captureSemanticSnapshot({ value: 'owned' }).value;
  93. const shared = { owned };
  94. const array = new Array(3);
  95. array[2] = shared;
  96. const input = { owned, a: shared, b: shared, array, ['__proto__']: shared };
  97. const snapshot = captureSemanticSnapshot(input);
  98. expect(snapshot.value.a).toBe(snapshot.value.b);
  99. expect(snapshot.value.a).toBe(snapshot.value.array[2]);
  100. expect(snapshot.value['__proto__']).toBe(snapshot.value.a);
  101. expect(0 in snapshot.value.array).toBe(false);
  102. expect(snapshot.value).toEqual(structuredClone(input));
  103. const cycle: Record<string, unknown> = { owned };
  104. cycle.self = cycle;
  105. expect(() => captureSemanticSnapshot(cycle)).toThrow('Cyclic');
  106. });
  107. it('uses native getter ordering and proxy rejection even beside owned values', () => {
  108. const owned = captureSemanticSnapshot({ text: 'owned' }).value;
  109. const shared = { value: 1 };
  110. const getter = vi.fn(() => {
  111. shared.value = 2;
  112. return shared;
  113. });
  114. const snapshot = captureSemanticSnapshot({
  115. owned,
  116. shared,
  117. get later() {
  118. return getter();
  119. },
  120. });
  121. expect(snapshot.value.shared).toBe(snapshot.value.later);
  122. expect(snapshot.value.shared.value).toBe(1);
  123. expect(getter).toHaveBeenCalledTimes(1);
  124. const trap = vi.fn();
  125. expect(() =>
  126. captureSemanticSnapshot({
  127. owned,
  128. proxy: new Proxy({}, { ownKeys: trap }),
  129. }),
  130. ).toThrow();
  131. expect(trap).not.toHaveBeenCalled();
  132. });
  133. it('does not trust externally frozen objects with mutable descendants', () => {
  134. const original = Object.freeze({ nested: { text: 'before' } });
  135. const snapshot = captureSemanticSnapshot(original);
  136. original.nested.text = 'after';
  137. expect(snapshot.value.nested.text).toBe('before');
  138. });
  139. it('preserves native rejection of proxies without invoking their traps', () => {
  140. const trap = vi.fn();
  141. const value = new Proxy({}, { ownKeys: trap });
  142. expect(() => captureSemanticSnapshot(value)).toThrow();
  143. expect(trap).not.toHaveBeenCalled();
  144. });
  145. it('preserves native enumeration when an accessor deletes another field', () => {
  146. const value = {
  147. get first() {
  148. delete this.second;
  149. return 'first';
  150. },
  151. second: 'deleted' as string | undefined,
  152. };
  153. expect(captureSemanticSnapshot(value).value).toEqual({ first: 'first' });
  154. });
  155. it.each([false, true])(
  156. 'preserves shared references across a mutating getter (getter first: %s)',
  157. (getterFirst) => {
  158. const makeInput = () => {
  159. const shared = { value: 1 };
  160. const getter = vi.fn(() => {
  161. shared.value = 2;
  162. return shared;
  163. });
  164. const nested = {
  165. get shared() {
  166. return getter();
  167. },
  168. };
  169. return {
  170. input: getterFirst ? { nested, shared } : { shared, nested },
  171. getter,
  172. };
  173. };
  174. const expected = structuredClone(makeInput().input);
  175. const { input, getter } = makeInput();
  176. const snapshot = captureSemanticSnapshot(input);
  177. expect(snapshot.value).toEqual(expected);
  178. expect(snapshot.value.shared).toBe(snapshot.value.nested.shared);
  179. expect(snapshot.fingerprint).toBe(captureSemanticSnapshot(expected).fingerprint);
  180. expect(getter).toHaveBeenCalledTimes(1);
  181. },
  182. );
  183. it('preserves shared references across a class instance normalized by native cloning', () => {
  184. const shared = { value: 1 };
  185. class Container {
  186. child = shared;
  187. }
  188. const snapshot = captureSemanticSnapshot({
  189. shared,
  190. nested: new Container(),
  191. });
  192. expect(snapshot.value.shared).toBe(snapshot.value.nested.child);
  193. expect(Object.getPrototypeOf(snapshot.value.nested)).toBe(Object.prototype);
  194. });
  195. it.each([new Date(), new Map(), new Uint8Array([1]), 1n])(
  196. 'rejects unsupported value-only payloads %#',
  197. (value) => {
  198. expect(() => captureSemanticSnapshot(value).value).toThrow();
  199. },
  200. );
  201. it('rejects cycles eagerly and accepts shared acyclic objects', () => {
  202. const cyclic: { self?: unknown } = {};
  203. cyclic.self = cyclic;
  204. expect(() => captureSemanticSnapshot(cyclic).value).toThrow('Cyclic');
  205. const shared = { value: 'same' };
  206. expect(captureSemanticSnapshot([shared, shared]).fingerprint).toBe(
  207. captureSemanticSnapshot([{ value: 'same' }, { value: 'same' }]).fingerprint,
  208. );
  209. });
  210. it('retains ordering, framing and special number distinctions', () => {
  211. const fingerprint = (value: unknown) => captureSemanticSnapshot(value).fingerprint;
  212. expect(fingerprint({ b: 2, a: 1 })).toBe(fingerprint({ a: 1, b: 2 }));
  213. expect(
  214. new Set(
  215. [
  216. undefined,
  217. null,
  218. NaN,
  219. Infinity,
  220. -Infinity,
  221. -0,
  222. 0,
  223. '',
  224. [],
  225. Array(1),
  226. [undefined],
  227. {},
  228. { a: undefined },
  229. ].map(fingerprint),
  230. ).size,
  231. ).toBe(13);
  232. expect(fingerprint(['ab', 'c'])).not.toBe(fingerprint(['a', 'bc']));
  233. });
  234. });
  235. describe('bounded token count reuse', () => {
  236. it('reuses text across detached histories and observes content edits and compaction', () => {
  237. const encode = vi.fn((text: string) => [...text]);
  238. const estimator = new BpeTokenEstimator(encode);
  239. const messages = [
  240. {
  241. role: 'user' as const,
  242. content: [{ type: 'text' as const, text: 'old' }],
  243. timestamp: 0,
  244. },
  245. ];
  246. expect(estimator.estimateMessages(messages)).toBe(7);
  247. expect(estimator.estimateMessages(structuredClone(messages))).toBe(7);
  248. expect(encode).toHaveBeenCalledTimes(1);
  249. messages[0]!.content[0]!.text = 'replacement';
  250. expect(estimator.estimateMessages(messages)).toBe(15);
  251. expect(estimator.estimateMessages([])).toBe(0);
  252. expect(estimator.estimateMessages([{ role: 'user', content: 'summary', timestamp: 1 }])).toBe(
  253. 11,
  254. );
  255. expect(encode).toHaveBeenCalledTimes(3);
  256. });
  257. it.each([256, 257, 300])(
  258. 'reuses detached histories above the former text budget (%i messages)',
  259. (count) => {
  260. const encode = vi.fn(() => [1]);
  261. const estimator = new BpeTokenEstimator(encode);
  262. const messages = Array.from({ length: count }, (_, i) => ({
  263. role: 'user' as const,
  264. content: String(i).padStart(8, '0') + 'x '.repeat(2044),
  265. timestamp: i,
  266. }));
  267. const first = estimator.estimateMessages(messages);
  268. encode.mockClear();
  269. expect(estimator.estimateMessages(structuredClone(messages))).toBe(first);
  270. expect(encode).not.toHaveBeenCalled();
  271. messages[0]!.content = 'changed ' + messages[0]!.content.slice(8);
  272. estimator.estimateMessages(messages);
  273. expect(encode).toHaveBeenCalledTimes(1);
  274. },
  275. );
  276. it('keeps distinct malformed UTF-16 strings separate in long-text keys', () => {
  277. const prefix = 'x '.repeat(256);
  278. const estimator = new BpeTokenEstimator((text) => (text.endsWith('\ud800') ? [1] : [1, 2]));
  279. expect(estimator.estimateTextTokens(prefix + '\ud800')).toBe(1);
  280. expect(estimator.estimateTextTokens(prefix + '\ud801')).toBe(2);
  281. });
  282. it('isolates different estimators and evicts least-recently-used text', () => {
  283. const encode = vi.fn((text: string) => [...text]);
  284. const estimator = new BpeTokenEstimator(encode);
  285. estimator.estimateTextTokens('old');
  286. for (let i = 0; i < 2048; i++) estimator.estimateTextTokens(`text ${i}`);
  287. encode.mockClear();
  288. estimator.estimateTextTokens('old');
  289. expect(encode).toHaveBeenCalledTimes(1);
  290. expect(new BpeTokenEstimator(() => [0]).estimateTextTokens('old')).toBe(1);
  291. });
  292. it('reuses large texts without retaining their bodies', () => {
  293. const encode = vi.fn(() => [1]);
  294. const estimator = new BpeTokenEstimator(encode);
  295. const first = 'a '.repeat(300_000);
  296. const second = 'b '.repeat(300_000);
  297. estimator.estimateTextTokens(first);
  298. estimator.estimateTextTokens(second);
  299. estimator.estimateTextTokens(first);
  300. expect(encode).toHaveBeenCalledTimes(2);
  301. });
  302. it('does not cache tokenizer failures', () => {
  303. const encode = vi
  304. .fn()
  305. .mockImplementationOnce(() => {
  306. throw new Error('transient');
  307. })
  308. .mockReturnValue([1]);
  309. const estimator = new BpeTokenEstimator(encode);
  310. expect(estimator.estimateTextTokens('中文')).toBe(6);
  311. expect(estimator.estimateTextTokens('中文')).toBe(1);
  312. });
  313. });
  314. describe('committed history read reuse', () => {
  315. it('reuses verified records for indexing while observing external changes and corruption', async () => {
  316. const dataDir = await mkdtemp(join(tmpdir(), 'mcode-history-reuse-'));
  317. const redundantRead = vi.spyOn(CanonicalHistoryJsonlDataSource.prototype, 'readActive');
  318. try {
  319. const session: SessionRecord = {
  320. sessionId: 'synthetic-session',
  321. agentName: 'test',
  322. workspaceDir: dataDir,
  323. runtime: 'pi-agent',
  324. sessionType: 'root',
  325. sessionKind: 'conversation',
  326. archived: false,
  327. status: 'idle',
  328. createdAtMs: 0,
  329. updatedAtMs: 0,
  330. historyRelativeDir: utcSessionHistoryRelativeDir('synthetic-session', 0),
  331. };
  332. const files = createCanonicalHistoryFileAdapter();
  333. const strictRead = vi.spyOn(files, 'readActiveStrict');
  334. const provider = createSessionSystemCanonicalHistoryProvider({
  335. dataDir,
  336. sessions: { get: async () => session },
  337. files,
  338. });
  339. await provider.initialize(session.sessionId);
  340. strictRead.mockClear();
  341. redundantRead.mockClear();
  342. expect((await provider.readActive(session.sessionId)).messages).toEqual([]);
  343. expect(strictRead).not.toHaveBeenCalled();
  344. const committed = await provider.append({
  345. sessionId: session.sessionId,
  346. turnId: 'turn-1',
  347. reason: 'messageDelta',
  348. messages: [{ role: 'user', content: 'first', timestamp: 1 }],
  349. operation: { id: 'append-1', kind: 'append' },
  350. });
  351. expect(committed.messages).toHaveLength(1);
  352. expect(strictRead).toHaveBeenCalledTimes(1);
  353. expect(redundantRead).not.toHaveBeenCalled();
  354. const paths = resolveSessionHistoryPaths(dataDir, session);
  355. const external = createCanonicalHistoryFileAdapter();
  356. await external.replace(paths.messages, [
  357. {
  358. message_id: 'msg-external-id',
  359. turn_id: 'turn-2',
  360. message: { role: 'user', content: 'edited', timestamp: 2 },
  361. },
  362. ]);
  363. expect((await provider.readActive(session.sessionId)).messages[0]).toMatchObject({
  364. content: 'edited',
  365. });
  366. await writeFile(paths.messages, '{invalid json}\n');
  367. await expect(provider.readActive(session.sessionId)).rejects.toThrow();
  368. await expect(
  369. provider.append({
  370. sessionId: session.sessionId,
  371. turnId: 'turn-3',
  372. reason: 'messageDelta',
  373. messages: [{ role: 'user', content: 'must not append', timestamp: 3 }],
  374. operation: { id: 'append-3', kind: 'append' },
  375. }),
  376. ).rejects.toThrow();
  377. } finally {
  378. redundantRead.mockRestore();
  379. await rm(dataDir, { recursive: true, force: true });
  380. }
  381. });
  382. it('checks migration target existence without reparsing and preserves legacy adapter fallback', async () => {
  383. const dataDir = await mkdtemp(join(tmpdir(), 'mcode-materialized-'));
  384. try {
  385. const sessionId = 'synthetic-session';
  386. const paths = resolveSessionHistoryPaths(dataDir, {
  387. sessionId,
  388. createdAtMs: 0,
  389. });
  390. const files = createCanonicalHistoryFileAdapter();
  391. const read = vi.spyOn(files, 'readTarget');
  392. const options = { sessionId, paths, files, nowMs: () => 0 };
  393. await ensureCanonicalHistoryMaterialized(options);
  394. const legacyHistory = {
  395. sources: {
  396. readLedgerSnapshot: vi.fn(async () => undefined),
  397. readSqliteRows: vi.fn(async () => []),
  398. readSqliteBlob: vi.fn(async () => []),
  399. },
  400. checkpoints: {
  401. getCheckpoint: async () => ({
  402. sessionId,
  403. migratedAtMs: 0,
  404. source: 'empty' as const,
  405. messageCount: 0,
  406. targetRevision: 'recorded',
  407. }),
  408. upsertCheckpoint: vi.fn(async () => {}),
  409. },
  410. };
  411. await ensureCanonicalHistoryMaterialized({ ...options, legacyHistory });
  412. expect(read).not.toHaveBeenCalled();
  413. expect(legacyHistory.sources.readLedgerSnapshot).not.toHaveBeenCalled();
  414. Object.defineProperty(files, 'targetExists', { value: undefined });
  415. await ensureCanonicalHistoryMaterialized({ ...options, legacyHistory });
  416. expect(read).toHaveBeenCalledTimes(1);
  417. await rm(paths.messages);
  418. await expect(
  419. ensureCanonicalHistoryMaterialized({ ...options, legacyHistory }),
  420. ).rejects.toThrow('missing after migration');
  421. } finally {
  422. await rm(dataDir, { recursive: true, force: true });
  423. }
  424. });
  425. it('retains disk reads for standalone appends and validates supplied prefix identities', async () => {
  426. const dataDir = await mkdtemp(join(tmpdir(), 'mcode-append-prefix-'));
  427. try {
  428. const source = new CanonicalHistoryJsonlDataSource({
  429. activePath: join(dataDir, 'messages.jsonl'),
  430. });
  431. await source.publishInitial([]);
  432. const first = {
  433. message_id: 'msg-first',
  434. turn_id: 'turn-first',
  435. message: { role: 'user', content: 'first', timestamp: 1 },
  436. };
  437. const second = {
  438. message_id: 'msg-second',
  439. turn_id: 'turn-second',
  440. message: { role: 'user', content: 'second', timestamp: 2 },
  441. };
  442. const read = vi.spyOn(source, 'readActive');
  443. await source.append([first]);
  444. expect(read).toHaveBeenCalledTimes(1);
  445. const verified = await source.readActiveStrict();
  446. read.mockClear();
  447. await expect(source.append([first], verified)).rejects.toThrow();
  448. await source.append([second], verified);
  449. expect(read).not.toHaveBeenCalled();
  450. expect((await source.readActiveStrict()).map((row) => row.message_id)).toEqual([
  451. 'msg-first',
  452. 'msg-second',
  453. ]);
  454. } finally {
  455. await rm(dataDir, { recursive: true, force: true });
  456. }
  457. });
  458. const change: CanonicalHistoryChange = {
  459. sessionId: 'synthetic-session',
  460. turnId: 'synthetic-turn',
  461. reason: 'messageDelta',
  462. messages: [],
  463. operation: { id: 'append-1', kind: 'append' },
  464. };
  465. it('uses the provider commit without a second read and still reads fresh on demand', async () => {
  466. const committed = { revision: 'r1', messages: [], identityVector: [] };
  467. const read = vi.fn(async () => ({
  468. revision: 'r2',
  469. messages: [],
  470. identityVector: [],
  471. }));
  472. const readActive = vi.fn(async () => committed);
  473. const store = new DurableCanonicalHistoryStore({
  474. read,
  475. readActive,
  476. append: async () => committed,
  477. replace: async () => committed,
  478. });
  479. const result = await store.append(change);
  480. committed.revision = 'mutated';
  481. expect(result.revision).toBe('r1');
  482. expect(readActive).not.toHaveBeenCalled();
  483. expect((await store.read('synthetic-session')).revision).toBe('r2');
  484. });
  485. it('retains legacy rereads and rejects invalid commits or write failures', async () => {
  486. const readActive = vi.fn(async () => ({
  487. revision: 'r1',
  488. messages: [],
  489. identityVector: [],
  490. }));
  491. const append = vi.fn<
  492. () => Promise<ReturnType<typeof readActive> extends Promise<infer T> ? T | void : never>
  493. >(async () => undefined);
  494. const store = new DurableCanonicalHistoryStore({
  495. read: readActive,
  496. readActive,
  497. append,
  498. replace: async () => undefined,
  499. });
  500. expect((await store.append(change)).revision).toBe('r1');
  501. expect(readActive).toHaveBeenCalledTimes(1);
  502. append.mockResolvedValueOnce({
  503. revision: '',
  504. messages: [],
  505. identityVector: [],
  506. });
  507. await expect(store.append(change)).rejects.toThrow();
  508. append.mockRejectedValueOnce(new Error('write failed'));
  509. await expect(store.append(change)).rejects.toThrow('write failed');
  510. expect(readActive).toHaveBeenCalledTimes(1);
  511. });
  512. });