history-processing.test.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. import { createHash } from 'node:crypto';
  2. import { mkdtemp, rm, writeFile } from 'node:fs/promises';
  3. import { tmpdir } from 'node:os';
  4. import { join } from 'node:path';
  5. import { describe, expect, it, vi } from 'vitest';
  6. import { IncrementalSha256 } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/incremental-sha256.js';
  7. import { captureSemanticSnapshot } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/semantic-identity.js';
  8. import { DurableCanonicalHistoryStore } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/durable-canonical-history-store.js';
  9. import type { CanonicalHistoryChange } from '../packages/local-runtime-v2/src/service/turn-system/agent-host/history/contracts.js';
  10. import { BpeTokenEstimator } from '../packages/agent-modules/context-manager/src/token-estimator.js';
  11. import { createSessionSystemCanonicalHistoryProvider } from '../packages/local-runtime-v2/src/service/session-system/messages/history/canonical-history-provider.js';
  12. import { createCanonicalHistoryFileAdapter } from '../packages/local-runtime-v2/src/service/session-system/sessions/representation/canonical-history.js';
  13. import {
  14. resolveSessionHistoryPaths,
  15. utcSessionHistoryRelativeDir,
  16. } from '../packages/local-runtime-v2/src/service/session-system/messages/history/session-history-paths.js';
  17. import type { SessionRecord } from '../packages/local-runtime-v2/src/service/session-system/sessions/repo/contract.js';
  18. describe('native incremental semantic hashing', () => {
  19. const inputs = ['', 'abc', '中文🙂', '\ud800', '\udc00', 'a'.repeat(8191) + '🙂tail'];
  20. for (const length of [55, 56, 63, 64, 65, 8191, 8192, 8193, 32769]) {
  21. inputs.push('x'.repeat(length), '中'.repeat(length));
  22. }
  23. it.each(inputs)('preserves UTF-8 hashing %#', (input) => {
  24. const hash = new IncrementalSha256();
  25. hash.update(input);
  26. expect(hash.digestHex()).toBe(createHash('sha256').update(input).digest('hex'));
  27. expect(() => hash.update('')).toThrow('finalized');
  28. expect(() => hash.digestHex()).toThrow('finalized');
  29. });
  30. it('preserves encoding boundaries between separate updates', () => {
  31. const hash = new IncrementalSha256();
  32. hash.update('\ud83d');
  33. hash.update('\ude42');
  34. expect(hash.digestHex()).toBe(
  35. createHash('sha256').update('\ud83d').update('\ude42').digest('hex'),
  36. );
  37. });
  38. });
  39. describe('semantic snapshots', () => {
  40. it('detaches and freezes eagerly but hashes only when identity is requested', () => {
  41. const hash = vi.spyOn(IncrementalSha256.prototype, 'update');
  42. try {
  43. const original = { messages: [{ text: 'before' }] };
  44. const snapshot = captureSemanticSnapshot(original);
  45. original.messages[0]!.text = 'after';
  46. expect(snapshot.value.messages[0]!.text).toBe('before');
  47. expect(Object.isFrozen(snapshot.value.messages[0])).toBe(true);
  48. expect(hash).not.toHaveBeenCalled();
  49. const reused = captureSemanticSnapshot(snapshot.value);
  50. expect(reused.value).toBe(snapshot.value);
  51. const wrapped = captureSemanticSnapshot({
  52. history: snapshot.value.messages,
  53. });
  54. expect(wrapped.value.history).not.toBe(snapshot.value.messages);
  55. expect(wrapped.value.history).toEqual(snapshot.value.messages);
  56. const fingerprint = snapshot.fingerprint;
  57. expect(hash).toHaveBeenCalled();
  58. hash.mockClear();
  59. expect(reused.fingerprint).toBe(fingerprint);
  60. expect(hash).not.toHaveBeenCalled();
  61. expect(captureSemanticSnapshot(original).fingerprint).not.toBe(fingerprint);
  62. } finally {
  63. hash.mockRestore();
  64. }
  65. });
  66. it('does not trust externally frozen objects with mutable descendants', () => {
  67. const original = Object.freeze({ nested: { text: 'before' } });
  68. const snapshot = captureSemanticSnapshot(original);
  69. original.nested.text = 'after';
  70. expect(snapshot.value.nested.text).toBe('before');
  71. });
  72. it('preserves native rejection of proxies without invoking their traps', () => {
  73. const trap = vi.fn();
  74. const value = new Proxy({}, { ownKeys: trap });
  75. expect(() => captureSemanticSnapshot(value)).toThrow();
  76. expect(trap).not.toHaveBeenCalled();
  77. });
  78. it('preserves native enumeration when an accessor deletes another field', () => {
  79. const value = {
  80. get first() {
  81. delete this.second;
  82. return 'first';
  83. },
  84. second: 'deleted' as string | undefined,
  85. };
  86. expect(captureSemanticSnapshot(value).value).toEqual({ first: 'first' });
  87. });
  88. it.each([false, true])(
  89. 'preserves shared references across a mutating getter (getter first: %s)',
  90. (getterFirst) => {
  91. const makeInput = () => {
  92. const shared = { value: 1 };
  93. const getter = vi.fn(() => {
  94. shared.value = 2;
  95. return shared;
  96. });
  97. const nested = {
  98. get shared() {
  99. return getter();
  100. },
  101. };
  102. return { input: getterFirst ? { nested, shared } : { shared, nested }, getter };
  103. };
  104. const expected = structuredClone(makeInput().input);
  105. const { input, getter } = makeInput();
  106. const snapshot = captureSemanticSnapshot(input);
  107. expect(snapshot.value).toEqual(expected);
  108. expect(snapshot.value.shared).toBe(snapshot.value.nested.shared);
  109. expect(snapshot.fingerprint).toBe(captureSemanticSnapshot(expected).fingerprint);
  110. expect(getter).toHaveBeenCalledTimes(1);
  111. },
  112. );
  113. it('preserves shared references across a class instance normalized by native cloning', () => {
  114. const shared = { value: 1 };
  115. class Container {
  116. child = shared;
  117. }
  118. const snapshot = captureSemanticSnapshot({ shared, nested: new Container() });
  119. expect(snapshot.value.shared).toBe(snapshot.value.nested.child);
  120. expect(Object.getPrototypeOf(snapshot.value.nested)).toBe(Object.prototype);
  121. });
  122. it.each([new Date(), new Map(), new Uint8Array([1]), 1n])(
  123. 'rejects unsupported value-only payloads %#',
  124. (value) => {
  125. expect(() => captureSemanticSnapshot(value).value).toThrow();
  126. },
  127. );
  128. it('rejects cycles eagerly and accepts shared acyclic objects', () => {
  129. const cyclic: { self?: unknown } = {};
  130. cyclic.self = cyclic;
  131. expect(() => captureSemanticSnapshot(cyclic).value).toThrow('Cyclic');
  132. const shared = { value: 'same' };
  133. expect(captureSemanticSnapshot([shared, shared]).fingerprint).toBe(
  134. captureSemanticSnapshot([{ value: 'same' }, { value: 'same' }]).fingerprint,
  135. );
  136. });
  137. it('retains ordering, framing and special number distinctions', () => {
  138. const fingerprint = (value: unknown) => captureSemanticSnapshot(value).fingerprint;
  139. expect(fingerprint({ b: 2, a: 1 })).toBe(fingerprint({ a: 1, b: 2 }));
  140. expect(
  141. new Set(
  142. [
  143. undefined,
  144. null,
  145. NaN,
  146. Infinity,
  147. -Infinity,
  148. -0,
  149. 0,
  150. '',
  151. [],
  152. Array(1),
  153. [undefined],
  154. {},
  155. { a: undefined },
  156. ].map(fingerprint),
  157. ).size,
  158. ).toBe(13);
  159. expect(fingerprint(['ab', 'c'])).not.toBe(fingerprint(['a', 'bc']));
  160. });
  161. });
  162. describe('bounded token count reuse', () => {
  163. it('reuses text across detached histories and observes content edits and compaction', () => {
  164. const encode = vi.fn((text: string) => [...text]);
  165. const estimator = new BpeTokenEstimator(encode);
  166. const messages = [
  167. {
  168. role: 'user' as const,
  169. content: [{ type: 'text' as const, text: 'old' }],
  170. timestamp: 0,
  171. },
  172. ];
  173. expect(estimator.estimateMessages(messages)).toBe(7);
  174. expect(estimator.estimateMessages(structuredClone(messages))).toBe(7);
  175. expect(encode).toHaveBeenCalledTimes(1);
  176. messages[0]!.content[0]!.text = 'replacement';
  177. expect(estimator.estimateMessages(messages)).toBe(15);
  178. expect(estimator.estimateMessages([])).toBe(0);
  179. expect(estimator.estimateMessages([{ role: 'user', content: 'summary', timestamp: 1 }])).toBe(
  180. 11,
  181. );
  182. expect(encode).toHaveBeenCalledTimes(3);
  183. });
  184. it('isolates different estimators and evicts least-recently-used text', () => {
  185. const encode = vi.fn((text: string) => [...text]);
  186. const estimator = new BpeTokenEstimator(encode);
  187. estimator.estimateTextTokens('old');
  188. for (let i = 0; i < 2048; i++) estimator.estimateTextTokens(`text ${i}`);
  189. encode.mockClear();
  190. estimator.estimateTextTokens('old');
  191. expect(encode).toHaveBeenCalledTimes(1);
  192. expect(new BpeTokenEstimator(() => [0]).estimateTextTokens('old')).toBe(1);
  193. });
  194. it('bounds retained text independently of entry count', () => {
  195. const encode = vi.fn(() => [1]);
  196. const estimator = new BpeTokenEstimator(encode);
  197. const first = 'a '.repeat(300_000);
  198. const second = 'b '.repeat(300_000);
  199. estimator.estimateTextTokens(first);
  200. estimator.estimateTextTokens(second);
  201. estimator.estimateTextTokens(first);
  202. expect(encode).toHaveBeenCalledTimes(3);
  203. });
  204. it('does not cache tokenizer failures', () => {
  205. const encode = vi
  206. .fn()
  207. .mockImplementationOnce(() => {
  208. throw new Error('transient');
  209. })
  210. .mockReturnValue([1]);
  211. const estimator = new BpeTokenEstimator(encode);
  212. expect(estimator.estimateTextTokens('中文')).toBe(6);
  213. expect(estimator.estimateTextTokens('中文')).toBe(1);
  214. });
  215. });
  216. describe('committed history read reuse', () => {
  217. it('reuses verified records for indexing while observing external changes and corruption', async () => {
  218. const dataDir = await mkdtemp(join(tmpdir(), 'mcode-history-reuse-'));
  219. try {
  220. const session: SessionRecord = {
  221. sessionId: 'synthetic-session',
  222. agentName: 'test',
  223. workspaceDir: dataDir,
  224. runtime: 'pi-agent',
  225. sessionType: 'root',
  226. sessionKind: 'conversation',
  227. archived: false,
  228. status: 'idle',
  229. createdAtMs: 0,
  230. updatedAtMs: 0,
  231. historyRelativeDir: utcSessionHistoryRelativeDir('synthetic-session', 0),
  232. };
  233. const files = createCanonicalHistoryFileAdapter();
  234. const strictRead = vi.spyOn(files, 'readActiveStrict');
  235. const provider = createSessionSystemCanonicalHistoryProvider({
  236. dataDir,
  237. sessions: { get: async () => session },
  238. files,
  239. });
  240. await provider.initialize(session.sessionId);
  241. strictRead.mockClear();
  242. expect((await provider.readActive(session.sessionId)).messages).toEqual([]);
  243. expect(strictRead).not.toHaveBeenCalled();
  244. const committed = await provider.append({
  245. sessionId: session.sessionId,
  246. turnId: 'turn-1',
  247. reason: 'messageDelta',
  248. messages: [{ role: 'user', content: 'first', timestamp: 1 }],
  249. operation: { id: 'append-1', kind: 'append' },
  250. });
  251. expect(committed.messages).toHaveLength(1);
  252. expect(strictRead).toHaveBeenCalledTimes(1);
  253. const paths = resolveSessionHistoryPaths(dataDir, session);
  254. const external = createCanonicalHistoryFileAdapter();
  255. await external.replace(paths.messages, [
  256. {
  257. message_id: 'msg-external-id',
  258. turn_id: 'turn-2',
  259. message: { role: 'user', content: 'edited', timestamp: 2 },
  260. },
  261. ]);
  262. expect((await provider.readActive(session.sessionId)).messages[0]).toMatchObject({
  263. content: 'edited',
  264. });
  265. await writeFile(paths.messages, '{invalid json}\n');
  266. await expect(provider.readActive(session.sessionId)).rejects.toThrow();
  267. } finally {
  268. await rm(dataDir, { recursive: true, force: true });
  269. }
  270. });
  271. const change: CanonicalHistoryChange = {
  272. sessionId: 'synthetic-session',
  273. turnId: 'synthetic-turn',
  274. reason: 'messageDelta',
  275. messages: [],
  276. operation: { id: 'append-1', kind: 'append' },
  277. };
  278. it('uses the provider commit without a second read and still reads fresh on demand', async () => {
  279. const committed = { revision: 'r1', messages: [], identityVector: [] };
  280. const read = vi.fn(async () => ({
  281. revision: 'r2',
  282. messages: [],
  283. identityVector: [],
  284. }));
  285. const readActive = vi.fn(async () => committed);
  286. const store = new DurableCanonicalHistoryStore({
  287. read,
  288. readActive,
  289. append: async () => committed,
  290. replace: async () => committed,
  291. });
  292. const result = await store.append(change);
  293. committed.revision = 'mutated';
  294. expect(result.revision).toBe('r1');
  295. expect(readActive).not.toHaveBeenCalled();
  296. expect((await store.read('synthetic-session')).revision).toBe('r2');
  297. });
  298. it('retains legacy rereads and rejects invalid commits or write failures', async () => {
  299. const readActive = vi.fn(async () => ({
  300. revision: 'r1',
  301. messages: [],
  302. identityVector: [],
  303. }));
  304. const append = vi.fn<
  305. () => Promise<ReturnType<typeof readActive> extends Promise<infer T> ? T | void : never>
  306. >(async () => undefined);
  307. const store = new DurableCanonicalHistoryStore({
  308. read: readActive,
  309. readActive,
  310. append,
  311. replace: async () => undefined,
  312. });
  313. expect((await store.append(change)).revision).toBe('r1');
  314. expect(readActive).toHaveBeenCalledTimes(1);
  315. append.mockResolvedValueOnce({
  316. revision: '',
  317. messages: [],
  318. identityVector: [],
  319. });
  320. await expect(store.append(change)).rejects.toThrow();
  321. append.mockRejectedValueOnce(new Error('write failed'));
  322. await expect(store.append(change)).rejects.toThrow('write failed');
  323. expect(readActive).toHaveBeenCalledTimes(1);
  324. });
  325. });