okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
11.8 KiB191 linesraw
1/** Chats as files in the data folder: big chats, restart, a full disk, a refused write, a crash in the middle of a write, two windows. */
2import test from 'node:test';
3import assert from 'node:assert/strict';
4import { mkdtempSync, rmSync, readdirSync, readFileSync, writeFileSync, statSync, existsSync } from 'node:fs';
5import { tmpdir } from 'node:os';
6import { join } from 'node:path';
7import { createChatStore, realIo, validChatId, storeFailure } from '../server/chat-store.mjs';
8
9const scratch = () => mkdtempSync(join(tmpdir(), 'strata-chats-'));
10const chat = (id, n, len, extra = {}) => ({
11  id, title: `Chat ${id}`, createdAt: `2026-11-0${(id.charCodeAt(0) % 8) + 1}T10:00:00.000Z`, updatedAt: `2026-11-04T10:00:0${n % 10}.000Z`, workspace: 'C:/w', tokensIn: 0, tokensOut: 0,
12  messages: Array.from({ length: n }, (_, i) => ({ id: `${id}-m${i}`, role: i % 2 ? 'assistant' : 'user', content: `${id}:${i}:` + String.fromCharCode(97 + (i % 26)).repeat(len) })),
13  ...extra,
14});
15const text = (session) => JSON.stringify(session);
16const readChat = async (store, id) => JSON.parse(await store.read(id));
17const files = (dir) => readdirSync(join(dir, 'chats')).sort();
18
19test('ids: only plain names, nothing that climbs out of the folder or names a device or a reserved file', () => {
20  for (const ok of ['s_ab12cd34', 'chat-1', 'legacy_0', 'a.b']) assert.ok(validChatId(ok), ok);
21  for (const bad of ['', '..', '../x', 'a/b', 'a\\b', '.hidden', 'con', 'NUL', 'index', 'import', 'conflicts', 'x'.repeat(200), null, 5]) assert.ok(!validChatId(bad), String(bad));
22});
23
24test('more than 10 MB of chats: every chat is saved whole, listed, and read back byte for byte after a restart (twice)', async () => {
25  const dir = scratch();
26  try {
27    const chats = ['a', 'b', 'c', 'd'].map((id) => chat(id, 12, 140_000));   // 4 x 1.7 MB ... plus one very large one
28    chats.push({ ...chat('e', 4, 10), messages: [{ id: 'e-0', role: 'assistant', content: 'q'.repeat(4_000_000), tools: [{ name: 'read', result: 'y'.repeat(3_000_000) }] }] });
29    const total = chats.reduce((n, c) => n + text(c).length, 0);
30    assert.ok(total > 10_000_000, `fixture is ${total} characters`);
31    let store = createChatStore({ dir });
32    for (const c of chats) await store.save(c.id, text(c));
33    for (let restart = 1; restart <= 2; restart++) {
34      store = createChatStore({ dir });   // a new host process
35      assert.deepEqual(store.list().chats.map((c) => c.id).sort(), ['a', 'b', 'c', 'd', 'e']);
36      for (const c of chats) {
37        const back = await readChat(store, c.id);
38        assert.equal(JSON.stringify(back.session), text(c), `chat ${c.id} after restart ${restart}`);
39        await store.save(c.id, JSON.stringify(back.session));   // saved again unchanged
40      }
41    }
42    assert.equal((await readChat(store, 'a')).rev, 3, 'rev counts the saves');
43  } finally { rmSync(dir, { recursive: true, force: true }); }
44});
45
46test('the files: one per chat, a version field, an index, no stray temporary files', async () => {
47  const dir = scratch();
48  try {
49    const store = createChatStore({ dir });
50    await store.save('s_one', text(chat('s_one', 2, 10)));
51    await store.save('s_two', text(chat('s_two', 2, 10)));
52    assert.deepEqual(files(dir), ['index.json', 's_one.json', 's_two.json']);
53    const file = JSON.parse(readFileSync(join(dir, 'chats', 's_one.json'), 'utf8'));
54    assert.deepEqual([file.v, file.rev, file.session.id], [1, 1, 's_one']);
55    const index = JSON.parse(readFileSync(join(dir, 'chats', 'index.json'), 'utf8'));
56    assert.equal(index.v, 1); assert.deepEqual(index.chats.map((c) => c.id).sort(), ['s_one', 's_two']);
57    if (process.platform !== 'win32') {
58      assert.equal(statSync(join(dir, 'chats')).mode & 0o777, 0o700, 'the folder is owner-only');
59      assert.equal(statSync(join(dir, 'chats', 's_one.json')).mode & 0o777, 0o600, 'the chat file is owner-only');
60      assert.equal(statSync(join(dir, 'chats', 'index.json')).mode & 0o777, 0o600);
61    }
62  } finally { rmSync(dir, { recursive: true, force: true }); }
63});
64
65test('a crash in the middle of a write loses nothing older: the chat keeps its last whole version, the half file is removed at the next start', async () => {
66  const dir = scratch();
67  try {
68    let store = createChatStore({ dir });
69    const first = chat('s_x', 6, 5_000);
70    await store.save('s_x', text(first));
71    const bigger = chat('s_x', 12, 5_000);
72    // The process dies after half of the new text reached the temporary file: the write throws and nothing after it (cleanup) runs.
73    const crashing = createChatStore({ dir, io: { ...realIo,
74      async writeFile(path, data) { await realIo.writeFile(path, data.slice(0, Math.floor(data.length / 2))); throw Object.assign(new Error('killed'), { code: 'EIO' }); },
75      async unlink() { throw new Error('process is gone'); } } });
76    await assert.rejects(crashing.save('s_x', text(bigger)));
77    assert.ok(files(dir).some((n) => /\.tmp-/.test(n)), 'the crash left its temporary file');
78    store = createChatStore({ dir });   // restart
79    assert.ok(!files(dir).some((n) => /\.tmp-/.test(n)), 'the half-written file is removed at start');
80    const back = await readChat(store, 's_x');
81    assert.equal(back.rev, 1);
82    assert.equal(JSON.stringify(back.session), text(first), 'the older version is whole');
83  } finally { rmSync(dir, { recursive: true, force: true }); }
84});
85
86test('a full disk: the save is refused with a disk-full error, the older version stays, and the next save works when there is room', async () => {
87  const dir = scratch();
88  try {
89    let full = false;
90    const store = createChatStore({ dir, io: { ...realIo, async writeFile(path, data) { if (full) throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' }); return realIo.writeFile(path, data); } } });
91    const v1 = chat('s_d', 3, 100);
92    await store.save('s_d', text(v1));
93    full = true;
94    await assert.rejects(store.save('s_d', text(chat('s_d', 9, 100))), (e) => e.code === 'disk-full' && e.status === 507);
95    assert.equal(JSON.stringify((await readChat(store, 's_d')).session), text(v1));
96    assert.ok(!files(dir).some((n) => /\.tmp-/.test(n)), 'no half file stays');
97    full = false;
98    const v3 = chat('s_d', 9, 100);
99    assert.equal((await store.save('s_d', text(v3))).rev, 2, 'the failed save did not use a revision');
100    assert.equal(JSON.stringify((await readChat(store, 's_d')).session), text(v3));
101  } finally { rmSync(dir, { recursive: true, force: true }); }
102});
103
104test('a refused write (permission) is reported as such and changes nothing', async () => {
105  const dir = scratch();
106  try {
107    const store = createChatStore({ dir, io: { ...realIo, async writeFile() { throw Object.assign(new Error('access denied'), { code: 'EACCES' }); } } });
108    await assert.rejects(store.save('s_p', text(chat('s_p', 1, 1))), (e) => e.code === 'permission' && e.status === 403);
109    assert.equal(store.list().chats.length, 0);
110    assert.equal(storeFailure(Object.assign(new Error('x'), { code: 'EPERM' })).code, 'permission');
111    assert.equal(storeFailure(Object.assign(new Error('x'), { code: 'ENOSPC' })).code, 'disk-full');
112  } finally { rmSync(dir, { recursive: true, force: true }); }
113});
114
115test('two windows: each saves its own chats and neither removes the other\'s; the same chat saved from an older copy keeps the displaced version', async () => {
116  const dir = scratch();
117  try {
118    const store = createChatStore({ dir });
119    // window A and window B, same host
120    const a1 = await store.save('s_a', text(chat('s_a', 2, 10)), { baseRev: null });
121    const b1 = await store.save('s_b', text(chat('s_b', 2, 10)), { baseRev: null });
122    assert.deepEqual(store.list().chats.map((c) => c.id).sort(), ['s_a', 's_b']);
123    // both windows loaded s_a at rev 1; A saves a longer chat, then B saves from its older copy
124    const fromA = chat('s_a', 6, 10), fromB = chat('s_a', 4, 10, { title: 'edited in B' });
125    const savedA = await store.save('s_a', text(fromA), { baseRev: a1.rev });
126    assert.equal(savedA.conflict, false);
127    const savedB = await store.save('s_a', text(fromB), { baseRev: a1.rev });   // B still thinks rev 1
128    assert.equal(savedB.conflict, true);
129    assert.equal(JSON.stringify((await readChat(store, 's_a')).session), text(fromB), 'the later save is the chat');
130    const kept = readdirSync(join(dir, 'chats', 'conflicts'));
131    assert.equal(kept.length, 1);
132    assert.equal(JSON.parse(readFileSync(join(dir, 'chats', 'conflicts', kept[0]), 'utf8')).session.messages.length, 6, 'window A\'s version is kept');
133    assert.ok(b1.rev === 1 && (await readChat(store, 's_b')).rev === 1, 'the other chat is untouched');
134  } finally { rmSync(dir, { recursive: true, force: true }); }
135});
136
137test('saves of one host never overlap, in any order they arrive', async () => {
138  const dir = scratch();
139  try {
140    const store = createChatStore({ dir });
141    const done = await Promise.all(Array.from({ length: 30 }, (_, i) => store.save(`s_${i % 3}`, text(chat(`s_${i % 3}`, 1 + (i % 7), 50)))));
142    assert.deepEqual(done.map((d) => d.rev).sort((a, b) => a - b), Array.from({ length: 30 }, (_, i) => Math.floor(i / 3) + 1).sort((a, b) => a - b));
143    assert.equal(store.list().chats.length, 3);
144    for (const c of store.list().chats) JSON.parse(await store.read(c.id));   // every file is whole JSON
145  } finally { rmSync(dir, { recursive: true, force: true }); }
146});
147
148test('the index is rebuilt from the files when it is lost, damaged or behind; an unreadable chat file is reported and left alone', async () => {
149  const dir = scratch();
150  try {
151    const store = createChatStore({ dir });
152    await store.save('s_1', text(chat('s_1', 2, 10)));
153    await store.save('s_2', text(chat('s_2', 2, 10)));
154    writeFileSync(join(dir, 'chats', 'index.json'), '{"v":1,"chats":[');   // damaged
155    writeFileSync(join(dir, 'chats', 's_bad.json'), '{"v":1,"rev":1,"session":{"id":"s_bad","mess');
156    const again = createChatStore({ dir });
157    assert.deepEqual(again.list().chats.map((c) => c.id).sort(), ['s_1', 's_2']);
158    assert.deepEqual(again.list().damaged, ['s_bad']);
159    assert.equal(readFileSync(join(dir, 'chats', 's_bad.json'), 'utf8').startsWith('{"v":1'), true, 'left as it is');
160    rmSync(join(dir, 'chats', 'index.json'));   // lost
161    assert.equal(createChatStore({ dir }).list().chats.length, 2);
162  } finally { rmSync(dir, { recursive: true, force: true }); }
163});
164
165test('a chat is refused when it does not match its id or is not JSON; delete removes the file and tolerates a chat that is gone', async () => {
166  const dir = scratch();
167  try {
168    const store = createChatStore({ dir });
169    await assert.rejects(store.save('s_a', text(chat('s_other', 1, 1))), (e) => e.status === 400);
170    await assert.rejects(store.save('s_a', '{nope'), (e) => e.status === 400);
171    await assert.rejects(store.save('../evil', text(chat('../evil', 1, 1))), (e) => e.status === 400);
172    await store.save('s_a', text(chat('s_a', 1, 1)));
173    assert.deepEqual(await store.remove('s_a'), { id: 's_a', removed: true });
174    assert.deepEqual(await store.remove('s_a'), { id: 's_a', removed: false });
175    assert.ok(!existsSync(join(dir, 'chats', 's_a.json')));
176    assert.equal(createChatStore({ dir }).list().chats.length, 0);
177  } finally { rmSync(dir, { recursive: true, force: true }); }
178});
179
180test('import: only chats the host does not have are taken, the ones it has are left alone, a bad one is reported', async () => {
181  const dir = scratch();
182  try {
183    const store = createChatStore({ dir });
184    await store.save('s_have', text(chat('s_have', 2, 10, { title: 'on the host' })));
185    const result = await store.importMany([chat('s_have', 5, 10, { title: 'in the browser' }), chat('s_new', 3, 10), { id: '../x' }, { nope: true }]);
186    assert.deepEqual(result.imported, ['s_new']);
187    assert.deepEqual(result.skipped, ['s_have']);
188    assert.equal(result.failed.length, 2);
189    assert.equal((await readChat(store, 's_have')).session.title, 'on the host');
190  } finally { rmSync(dir, { recursive: true, force: true }); }
191});