repositories / will

will

owned by bugabinga

fix: search all retained memory in recall

e60c1696a32892b0fa0b8d465121fb0af4ea7129

Oliver Jan Krylow <oliver@bugabinga.net> ·

SSH signature · not checked

Browse filesCompare with HEAD

Push filtering into hot SQLite queries, scan every overlapping archive segment, and merge both tiers under one deterministic newest-first order. Keep Unicode case matching identical across hot and archived data.

Changed files (2)

+271 / −28 text lines

Diff layout

src/service/ops.int.test.ts

Modified

+136 / −0 text lines

4747 assert.equal((since[0]?.payload as { note: string }).note, 'payload-a')
4848})
50test('recall searches beyond the newest page in hot data and archives', async () => {
51 const { ops } = await freshOps()
52 const recent = Array.from({ length: 20 }, (_, i) =>
53 audit(`noise-${i}`, `2026-09-${String(i + 1).padStart(2, '0')}T00:00:00Z`),
54 )
55 ops.ingestAudit([
56 audit('cold-needle', '2026-01-01T00:00:00Z', 'forgotten-audit'),
57 audit('hot-needle', '2026-08-01T00:00:00Z', 'remembered-audit'),
58 ...recent,
59 ])
60 ops.ingestChat([
61 {
62 id: 'chat-cold-needle',
63 chatId: -100,
64 messageId: 1,
65 direction: 'in',
66 ts: '2024-01-01T00:00:00Z',
67 senderName: 'old friend',
68 text: 'remember this phrase',
69 },
70 ...recent.map((_, i) => ({
71 id: `chat-noise-${i}`,
72 chatId: -100,
73 messageId: i + 2,
74 direction: 'in' as const,
75 ts: `2026-08-${String(i + 1).padStart(2, '0')}T00:00:00Z`,
76 text: 'routine chatter',
77 })),
78 ])
80 const hot = await ops.recall({ kind: 'audit', q: 'remembered-audit', limit: 2 })
81 assert.deepEqual(
82 (hot.rows as { id: string }[]).map((r) => r.id),
83 ['hot-needle'],
84 )
86 await ops.archiveCycle()
87 const coldAudit = await ops.recall({ kind: 'audit', q: 'forgotten-audit', limit: 2 })
88 assert.deepEqual(
89 (coldAudit.rows as { id: string }[]).map((r) => r.id),
90 ['cold-needle'],
91 )
92 assert.equal(coldAudit.cold, true)
93 const coldChat = await ops.recall({ kind: 'chat', q: 'remember this phrase', limit: 2 })
94 assert.deepEqual(
95 (coldChat.rows as { id: string }[]).map((r) => r.id),
96 ['chat-cold-needle'],
97 )
98 assert.equal(coldChat.cold, true)
99})
101test('recall orders overlapping archives and late hot rows globally', async () => {
102 const { ops } = await freshOps()
103 ops.ingestAudit([
104 audit('jan-01', '2026-01-01T00:00:00Z', 'shared-needle'),
105 audit('jan-30', '2026-01-30T00:00:00Z', 'shared-needle'),
106 ])
107 await ops.archiveCycle()
108 ops.ingestAudit([audit('jan-15', '2026-01-15T00:00:00Z', 'shared-needle')])
109 await ops.archiveCycle()
110 ops.ingestAudit([audit('late-jan-02', '2026-01-02T00:00:00Z', 'shared-needle')])
112 const result = await ops.recall({ kind: 'audit', q: 'shared-needle', limit: 1 })
113 assert.equal((result.rows[0] as { id: string }).id, 'jan-30')
114 assert.equal(result.cold, true)
115})
117test('recall has identical Unicode case matching before and after archival', async () => {
118 const { ops } = await freshOps()
119 ops.ingestAudit([
120 audit('kind-unicode', '2026-01-01T00:00:00Z', 'ÄPFEL'),
121 audit('ÖL', '2026-01-02T00:00:00Z'),
122 ])
123 ops.ingestChat([
124 {
125 id: 'chat-unicode',
126 chatId: -100,
127 messageId: 1,
128 direction: 'in',
129 ts: '2024-01-01T00:00:00Z',
130 senderName: 'ÄNNE',
131 text: 'GRÜSSE',
132 },
133 ])
135 for (const query of [
136 { kind: 'audit' as const, q: 'äpfel', id: 'kind-unicode' },
137 { kind: 'audit' as const, q: 'öl', id: 'ÖL' },
138 { kind: 'chat' as const, q: 'änne', id: 'chat-unicode' },
139 { kind: 'chat' as const, q: 'grüsse', id: 'chat-unicode' },
140 ]) {
141 const hot = await ops.recall({ kind: query.kind, q: query.q, limit: 2 })
142 assert.equal((hot.rows[0] as { id: string }).id, query.id)
143 }
145 await ops.archiveCycle()
146 for (const query of [
147 { kind: 'audit' as const, q: 'äpfel', id: 'kind-unicode' },
148 { kind: 'audit' as const, q: 'öl', id: 'ÖL' },
149 { kind: 'chat' as const, q: 'änne', id: 'chat-unicode' },
150 { kind: 'chat' as const, q: 'grüsse', id: 'chat-unicode' },
151 ]) {
152 const cold = await ops.recall({ kind: query.kind, q: query.q, limit: 2 })
153 assert.equal((cold.rows[0] as { id: string }).id, query.id)
154 assert.equal(cold.cold, true)
155 }
156})
158test('recall tie ordering is limit-prefix consistent before and after archival', async () => {
159 const { ops } = await freshOps()
160 const ts = '2026-01-01T00:00:00Z'
161 ops.ingestAudit([audit('z', ts, 'tie'), audit('a', ts, 'tie')])
162 ops.ingestChat([
163 { id: 'z', chatId: -100, messageId: 1, direction: 'in', ts, text: 'tie' },
164 { id: 'a', chatId: -100, messageId: 2, direction: 'in', ts, text: 'tie' },
165 ])
167 const assertOrder = async (kind: 'audit' | 'chat') => {
168 const one = await ops.recall({ kind, q: 'tie', limit: 1 })
169 const two = await ops.recall({ kind, q: 'tie', limit: 2 })
170 assert.deepEqual(
171 (one.rows as { id: string }[]).map((r) => r.id),
172 ['z'],
173 )
174 assert.deepEqual(
175 (two.rows as { id: string }[]).map((r) => r.id),
176 ['z', 'a'],
177 )
178 }
179 await assertOrder('audit')
180 await assertOrder('chat')
181 await ops.archiveCycle()
182 await assertOrder('audit')
183 await assertOrder('chat')
184})
50186test('chat ingest is idempotent and hide tombstones', async () => {
51187 const { ops } = await freshOps()
52188 const msg: ChatMessageIn = {

src/service/ops.ts

Modified

+135 / −28 text lines

279279 const coldFill = async <T>(
280280 kind: 'audit' | 'chat',
281 until: string | undefined,
281 range: { since?: string; until?: string },
282282 seen: Set<string>,
283283 budget: number,
284284 mapRecord: (r: ArchivedRecord) => T,
285 matches: (r: ArchivedRecord) => boolean = () => true,
285286 ): Promise<T[]> => {
286287 const segments = (await listSidecars(dirs.archiveDir, kind)).map((s) => ({
287288 ...s.sidecar,
288289 zstPath: s.zstPath,
289290 }))
290 const overlapping = segmentsOverlapping(segments, until ? { until } : {}).sort((a, b) =>
291 const overlapping = segmentsOverlapping(segments, range).sort((a, b) =>
291292 b.firstTs.localeCompare(a.firstTs),
292293 )
293294 const out: T[] = []
294295 outer: for (const seg of overlapping) {
295 const records = await readSegment(seg.zstPath, () => true, BATCH_LIMIT)
296 const records = await readSegment(seg.zstPath, matches, BATCH_LIMIT)
296297 const mapped = records
297298 .map(mapRecord)
298299 .sort((a, b) => (b as { ts: string }).ts.localeCompare((a as { ts: string }).ts))
307308 return out
308309 }
311 const coldSearch = async <T extends { id: string; ts: string }>(
312 kind: 'audit' | 'chat',
313 range: { since?: string; until?: string },
314 seen: Set<string>,
315 mapRecord: (r: ArchivedRecord) => T,
316 matches: (r: ArchivedRecord) => boolean,
317 ): Promise<T[]> => {
318 const segments = (await listSidecars(dirs.archiveDir, kind)).map((s) => ({
319 ...s.sidecar,
320 zstPath: s.zstPath,
321 }))
322 const out: T[] = []
323 for (const seg of segmentsOverlapping(segments, range)) {
324 for (const record of await readSegment(seg.zstPath, matches, BATCH_LIMIT)) {
325 if (seen.has(record.id)) continue
326 seen.add(record.id)
327 out.push(mapRecord(record))
328 }
329 }
330 return out.sort((a, b) => b.ts.localeCompare(a.ts) || b.id.localeCompare(a.id))
331 }
333 const newestFirst = (a: { id: string; ts: string }, b: { id: string; ts: string }) =>
334 b.ts.localeCompare(a.ts) || Buffer.compare(Buffer.from(b.id), Buffer.from(a.id))
336 db.function('unicode_lower', { deterministic: true }, (value) =>
337 String(value ?? '').toLowerCase(),
338 )
310340 const ops = {
311341 ingestAudit(events: AuditEvent[]): IngestResult {
312342 let accepted = 0
544574 const until = hot.length > 0 ? hot[hot.length - 1]?.ts : undefined
545575 const cold = await coldFill<TimelineRow>(
546576 'audit',
547 until,
577 until === undefined ? {} : { until },
548578 new Set(hot.map((r) => r.id)),
549579 limit - hot.length,
550580 (r) => {
588618 const until = hot.length > 0 ? hot[hot.length - 1]?.ts : undefined
589619 const cold = await coldFill<ChatViewRow>(
590620 'chat',
591 until,
621 until === undefined ? {} : { until },
592622 new Set(hot.map((r) => r.id)),
593623 limit - hot.length,
594624 (r) => {
602632 async recall(query: RecallQuery): Promise<RecallResponse> {
603633 const limit = Math.min(query.limit ?? 50, 500)
604 const q = query.q?.toLowerCase()
634 const q = query.q?.toLowerCase() || undefined
635 const range: { since?: string; until?: string } = {}
636 if (query.since !== undefined) range.since = query.since
637 if (query.until !== undefined) range.until = query.until
605638 switch (query.kind) {
606639 case 'audit': {
607 const page = await ops.timeline({ limit: limit * 2 })
608 const rows = page.rows.filter(
609 (r) =>
610 (!query.since || r.ts >= query.since) &&
611 (!query.until || r.ts <= query.until) &&
612 (!q ||
613 r.kind.toLowerCase().includes(q) ||
614 JSON.stringify(r.payload).toLowerCase().includes(q)),
640 const hot = (
641 db
642 .prepare(
643 `SELECT * FROM audit_events
644 WHERE (? IS NULL OR ts >= ?) AND (? IS NULL OR ts <= ?)
645 AND (? IS NULL OR instr(unicode_lower(kind), ?) > 0 OR instr(unicode_lower(payload), ?) > 0)
646 ORDER BY ts DESC, id DESC LIMIT ?`,
647 )
648 .all(
649 query.since ?? null,
650 query.since ?? null,
651 query.until ?? null,
652 query.until ?? null,
653 q ?? null,
654 q ?? null,
655 q ?? null,
656 limit,
657 ) as unknown as AuditRowDb[]
658 ).map((r) => auditDbToRow(r))
659 const cold = await coldSearch<TimelineRow>(
660 'audit',
661 range,
662 new Set(hot.map((r) => r.id)),
663 (r) => {
664 const rec = r.record as {
665 kind: string
666 sessionId?: string
667 provenance?: TimelineRow['provenance']
668 payload?: unknown
669 }
670 return {
671 id: r.id,
672 ts: r.ts,
673 kind: rec.kind,
674 sessionId: rec.sessionId,
675 provenance: rec.provenance,
676 payload: rec.payload,
677 archived: true,
678 } satisfies TimelineRow
679 },
680 (r) => {
681 const rec = r.record as { kind: string; payload?: unknown }
682 return (
683 (!q ||
684 rec.kind.toLowerCase().includes(q) ||
685 JSON.stringify(rec.payload ?? null)
686 .toLowerCase()
687 .includes(q)) &&
688 (!query.since || r.ts >= query.since) &&
689 (!query.until || r.ts <= query.until)
690 )
691 },
615692 )
616 return { rows: rows.slice(0, limit), cold: page.cold }
693 const rows = [...hot, ...cold].sort(newestFirst).slice(0, limit)
694 return { rows, cold: rows.some((r) => r.archived === true) }
617695 }
618696 case 'chat': {
619 const page = await ops.chatPage(
620 query.until === undefined
621 ? { limit: limit * 2 }
622 : { limit: limit * 2, before: query.until },
697 const hidden = hiddenMessageIds()
698 const hot = (
699 db
700 .prepare(
701 `SELECT * FROM chat_messages
702 WHERE (? IS NULL OR ts >= ?) AND (? IS NULL OR ts <= ?)
703 AND (? IS NULL OR instr(unicode_lower(text), ?) > 0
704 OR instr(unicode_lower(sender_name), ?) > 0)
705 AND NOT EXISTS (
706 SELECT 1 FROM tombstones WHERE tombstones.message_id = chat_messages.message_id
707 )
708 ORDER BY ts DESC, id DESC LIMIT ?`,
709 )
710 .all(
711 query.since ?? null,
712 query.since ?? null,
713 query.until ?? null,
714 query.until ?? null,
715 q ?? null,
716 q ?? null,
717 q ?? null,
718 limit,
719 ) as unknown as ChatRowDb[]
720 ).map((r) => chatDbToRow(r, false))
721 const cold = await coldSearch<ChatViewRow>(
722 'chat',
723 range,
724 new Set(hot.map((r) => r.id)),
725 (r) => ({ ...(r.record as ChatViewRow), archived: true, hidden: false }),
726 (r) => {
727 const rec = r.record as ChatViewRow
728 return (
729 !hidden.has(rec.messageId) &&
730 (!q ||
731 (rec.text ?? '').toLowerCase().includes(q) ||
732 (rec.senderName ?? '').toLowerCase().includes(q)) &&
733 (!query.since || r.ts >= query.since) &&
734 (!query.until || r.ts <= query.until)
735 )
736 },
623737 )
624 const rows = page.rows.filter(
625 (r) =>
626 !r.hidden &&
627 (!query.since || r.ts >= query.since) &&
628 (!q ||
629 (r.text ?? '').toLowerCase().includes(q) ||
630 (r.senderName ?? '').toLowerCase().includes(q)),
631 )
632 return { rows: rows.slice(0, limit), cold: page.cold }
738 const rows = [...hot, ...cold].sort(newestFirst).slice(0, limit)
739 return { rows, cold: rows.some((r) => r.archived === true) }
633740 }
634741 case 'deploy': {
635742 const rows = db