Skip to content

Commit 1a0c899

Browse files
authored
Read the chat-index mark inside its write transaction and keep the read-only window out of the index (#2713)
Written-by: Dev Fixes #2711 Owner: Dev Reviewer: Reviewer ## What `core/src/host/chat-index.js` read a part's mark **outside** the transaction that inserts the rows, `lines` had no uniqueness, and the module neither checked `rt.readOnly()` nor had a writer guard — so two indexers over one home both read `through = -1` and every message came back twice, and a window another dsh keeps read-only still wrote `chat-index.sqlite`. - **The mark is read inside the write transaction.** `catchUp` re-reads `marks.through` under `BEGIN IMMEDIATE` and skips events at or below it, so the second writer's read sees the first one's commit. One part's catch-up per transaction, as before — no giant catch-up holding the lock. - **`UNIQUE(session, seq)` is enforced by the database.** `lines` is now a plain table with that constraint; the FTS5 table is contentless over it (`content='lines', content_rowid='id'`) kept in step by insert/delete triggers, and ranked queries join it for `rank`. Inserts are `INSERT OR IGNORE`: one statement cannot be raced by the next writer, while a check-then-insert would add a second place that can read a stale mark. `INDEX_VERSION` 3 → 4. - **A window that is not the home's writer does not write the index.** `rt.readOnly()` (the `home-lock` promise) decides: such a window opens `chat-index.sqlite` read-only and reads the rows the writer indexed — it adds none and never creates, repairs or chmods the file. A missing, damaged or older-version file answers null and `read_own_chat` scans the logs instead. - **Existing duplicates are repaired, not left to a manual path.** A version-3 file can already hold one row per writer, and no later catch-up removes it, so the version bump rebuilds it once (drop + lazy reindex from the logs) and logs how many lines were stored more than once. Chosen over "warn and document" because the doubled transcript is otherwise permanent. - Tests: `core/test/chat-index-writers.test.js` (real module, temp home, real SQLite, fake Session log) — two indexers that both pass the mark read before either commits, the serial control, a read-only window over an existing index (bytes and mtime unchanged), a read-only window while the writer is live, a home with no index, and a version-3 file already duplicated. `core/test/history.test.js`'s pinned `termQuery` SQL follows the joined schema. **Red without the change**, with the same test file on the base blob of `chat-index.js` (sha256 `9dd7a804…`): test 1 answers `[part 1 #0, #0, #1, #1, #2, #2]` — 6 lines for 3 source messages — and tests 3, 4, 5 and 6 fail on a read-only window writing the index, creating one where there is none, and leaving a version-3 file duplicated. Test 2 (the serial control) passes either way. `Ran at this tip:` (TZ=UTC; the seven blobs at `1cfda2379d3d0784510e990793d80a1f50803e79` were byte-compared with this working copy before the commands below ran) ``` $ cd core && node --import ./test/harness-resolve.mjs --test test/chat-index-writers.test.js \ test/history.test.js test/chat-anchors.test.js test/private-files.test.js test/install.test.js \ test/group-work.test.js test/steward.test.js test/archive-bot.test.js test/tool-schema.test.js # tests 76, pass 76, fail 0 $ cd core && npm run lint # oxlint: 0 errors, 87 pre-existing warnings; arch-docs exits 1 here only for want of git $ node core/scripts/build-client.mjs --check # ok (no output, exit 0) $ node scripts/ds-bot-patches.mjs check # ok: 10 patches apply in order; core/ equals ds-bot/ + patches/ds-bot/ $ node scripts/lint-plugins.mjs # ok: packed @flybot/workflow imported $ node .github/scripts/changelog.mjs check # ok: 5 fragment(s) in changelog.d/ are well formed ``` **Red re-checked here**: the same new test file against the base `chat-index.js` (sha256 `9dd7a80414e4485998c83b299c65b04040ea3469b56e28232a360bcc2bd7afef`) answers `tests 6, pass 1, fail 5` — while the tip blob answers `tests 6, pass 6`. `Not run`: full `npm run verify` (the task said not to), the rest of `core/test/`, the plugin suites, the smoke test, and `npm run arch-docs` / `ds-bot-patches.mjs generate` (both need git, which this box does not have) — `docs/subsystems/core-host.md` is updated in this change, and the new file went whole into `patches/ds-bot/files/`. No client change. ## Checkpoint <!-- flybot:checkpoint --> { "pr": 2713, "claim": "Dev", "issue": 2711, "summary": "Two chat-index indexers over one home read the same part mark before either committed, so every message was stored and returned twice, and a window the home lock keeps read-only still wrote chat-index.sqlite. The mark is now read inside the transaction that writes the rows, and lines carries UNIQUE(session, seq) so the database refuses a second row for one event. A read-only window opens the existing index read-only and adds nothing. An index the old build already duplicated is rebuilt once at start, and the log says how many lines it found.", "files": [ "core/src/host/chat-index.js", "core/test/chat-index-writers.test.js", "core/test/history.test.js", "docs/subsystems/core-host.md", "changelog.d/2711-chat-index-writer.fixed.md" ], "checks": { "ran": "cd core && node --import ./test/harness-resolve.mjs --test test/chat-index-writers.test.js test/history.test.js test/chat-anchors.test.js test/private-files.test.js test/install.test.js test/group-work.test.js test/steward.test.js test/archive-bot.test.js test/tool-schema.test.js; node scripts/ds-bot-patches.mjs check; node core/scripts/build-client.mjs --check; node scripts/lint-plugins.mjs; node .github/scripts/changelog.mjs check", "result": "green", "at": "1cfda2379d3d0784510e990793d80a1f50803e79" }, "next": "none — ready for review" } <!-- /flybot:checkpoint -->
1 parent da0588a commit 1a0c899

7 files changed

Lines changed: 835 additions & 49 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
`read_own_chat` no longer shows every message twice when a second window or a plugin activation indexes the same chat: the part's mark is read inside the transaction that writes the rows (so the second writer sees the first one's commit), and the index's `lines` table now refuses a second row for the same event. An index an older build already duplicated is rebuilt once from the Session logs on the next start, and the log says how many duplicated lines it found. A window another dsh keeps read-only now reads the existing `chat-index.sqlite` without creating, repairing or writing it, instead of writing the index behind the other window's back. See [#2711](https://github.com/ThinkFlowLab/FlyBot/issues/2711).

‎core/src/host/chat-index.js‎

Lines changed: 103 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ import { ANCHOR_LINE_MAX, HISTORY_PAGE, HISTORY_PAGES_MAX, HISTORY_TIMEOUT_MS, O
1313
import { ensurePrivateDir, tightenFile } from './private-files.js'
1414
import { excerpt } from './text.js'
1515

16-
const INDEX_VERSION = 3
16+
const INDEX_VERSION = 4
1717
const AROUND_LINES = 6
1818
const SEARCH_TERMS_MAX = 6
1919
const ANY_TERM_HITS = 50
@@ -27,40 +27,45 @@ const likeOf = term => `%${term.replace(/[\\%_]/g, char => `\\${char}`)}%`
2727
function termWhere(terms, sessions, hidden) {
2828
const long = terms.filter(term => [...term].length >= 3)
2929
const short = terms.filter(term => [...term].length < 3)
30-
const where = ['session IN (SELECT value FROM json_each(?))']
30+
const where = ['lines.session IN (SELECT value FROM json_each(?))']
3131
const args = [JSON.stringify(sessions)]
3232
if (hidden !== undefined) {
33-
where.push('NOT (session = ? AND seq >= ?)')
33+
where.push('NOT (lines.session = ? AND lines.seq >= ?)')
3434
args.push(hidden.session, hidden.from)
3535
}
3636
if (long.length > 0) {
37-
where.unshift('lines MATCH ?')
37+
where.unshift('lines_fts MATCH ?')
3838
args.unshift(long.map(term => `"${term.replace(/"/g, '""')}"`).join(' '))
3939
}
4040
for (const term of short) {
41-
where.push("text LIKE ? ESCAPE '\\'")
41+
where.push("lines.text LIKE ? ESCAPE '\\'")
4242
args.push(likeOf(term))
4343
}
4444
return { where, args, ranked: long.length > 0 }
4545
}
4646

47+
// The rows carry their own text and columns; a query with a long term is driven by the
48+
// FTS index over them, and one without it scans the rows alone.
49+
const LINE_COLUMNS = 'lines.text, lines.session, lines.seq, lines.time, lines.who'
50+
const linesFrom = ranked => (ranked ? 'lines_fts JOIN lines ON lines.id = lines_fts.rowid' : 'lines')
51+
4752
export function termQuery(terms, sessions, limit, hidden) {
4853
const { where, args, ranked } = termWhere(terms, sessions, hidden)
49-
return { sql: `SELECT text, session, seq, time, who FROM lines WHERE ${where.join(' AND ')} ORDER BY ${ranked ? 'rank' : 'time DESC'} LIMIT ${limit}`, args }
54+
return { sql: `SELECT ${LINE_COLUMNS} FROM ${linesFrom(ranked)} WHERE ${where.join(' AND ')} ORDER BY ${ranked ? 'rank' : 'lines.time DESC'} LIMIT ${limit}`, args }
5055
}
5156

5257
// How many lines the same query matches in all, so a capped read can say what it left out (#1906).
5358
export function termCountQuery(terms, sessions, hidden) {
54-
const { where, args } = termWhere(terms, sessions, hidden)
55-
return { sql: `SELECT COUNT(*) AS n FROM lines WHERE ${where.join(' AND ')}`, args }
59+
const { where, args, ranked } = termWhere(terms, sessions, hidden)
60+
return { sql: `SELECT COUNT(*) AS n FROM ${linesFrom(ranked)} WHERE ${where.join(' AND ')}`, args }
5661
}
5762

5863
// The same count where no line holds every term and the read falls back to the terms a
5964
// line has most of: one branch per term, unioned so a line matching two counts once (#1906).
6065
export function anyTermCountQuery(terms, sessions, hidden) {
6166
const branches = terms.map(term => termWhere([term], sessions, hidden))
6267
return {
63-
sql: `SELECT COUNT(*) AS n FROM (${branches.map(branch => `SELECT session, seq FROM lines WHERE ${branch.where.join(' AND ')}`).join(' UNION ')})`,
68+
sql: `SELECT COUNT(*) AS n FROM (${branches.map(branch => `SELECT lines.session, lines.seq FROM ${linesFrom(branch.ranked)} WHERE ${branch.where.join(' AND ')}`).join(' UNION ')})`,
6469
args: branches.flatMap(branch => branch.args),
6570
}
6671
}
@@ -72,6 +77,11 @@ export function install(rt) {
7277
let chatIndex
7378
let indexOpening
7479

80+
// One writer per home (`home-lock`): a window another dsh keeps read-only may show the
81+
// index the writer left, but it never creates, repairs or adds to it. `rt.readOnly()`
82+
// names the other host; its absence is what makes this one the writer.
83+
const readOnly = () => rt.readOnly() !== undefined
84+
7585
// A Session's events from newest to oldest, also for an archived part.
7686
async function* eventsBackwards(sessionId, signal, maxPages = HISTORY_PAGES_MAX) {
7787
const agent = await rt.resolveAgent(sessionId)
@@ -104,18 +114,29 @@ export function install(rt) {
104114
if (chatIndex !== undefined) return Promise.resolve(chatIndex)
105115
const opening = indexOpening ??= (async () => {
106116
let DatabaseSync
117+
const writable = !readOnly()
107118
try {
108119
({ DatabaseSync } = await import('node:sqlite'))
109-
await ensurePrivateDir(home)
120+
if (writable) await ensurePrivateDir(home)
110121
} catch (error) {
111122
rt.warn('ds-bot: no chat index, read_own_chat scans the logs: %s', error)
112123
return null
113124
}
125+
if (!writable) {
126+
// The writer's file, as it is: opening it read-only cannot make one, repair one or
127+
// change its modes. A missing or older file answers null, and the logs are read.
128+
try {
129+
return createIndex(new DatabaseSync(indexPath, { readOnly: true }), false)
130+
} catch (error) {
131+
rt.warn('ds-bot: this window is read-only and the chat index cannot be read, so read_own_chat scans the logs: %s', error)
132+
return null
133+
}
134+
}
114135
// A damaged file is rebuilt from the logs once.
115136
for (const fresh of [false, true]) {
116137
try {
117138
if (fresh) await unlink(indexPath).catch(() => { /* the index file may not exist yet */ })
118-
const index = createIndex(new DatabaseSync(indexPath))
139+
const index = createIndex(new DatabaseSync(indexPath), true)
119140
await hardenIndex().catch(error => rt.warn('ds-bot: the chat index could not be made private: %s', error))
120141
return index
121142
} catch (error) {
@@ -134,23 +155,61 @@ export function install(rt) {
134155
return opening
135156
}
136157

137-
function createIndex(db) {
158+
// The rows are a plain table so the database itself refuses a second row for one event
159+
// (#2711): `UNIQUE(session, seq)`. The FTS5 table is contentless over them and kept in
160+
// step by the triggers, so the text is stored once and a duplicate insert is a no-op
161+
// rather than a second search hit.
162+
const CREATE_SCHEMA = `
163+
CREATE TABLE lines (
164+
id INTEGER PRIMARY KEY,
165+
text TEXT NOT NULL,
166+
session TEXT NOT NULL,
167+
seq INTEGER NOT NULL,
168+
time INTEGER NOT NULL,
169+
who TEXT NOT NULL,
170+
UNIQUE(session, seq)
171+
);
172+
CREATE VIRTUAL TABLE lines_fts USING fts5(text, content='lines', content_rowid='id', tokenize = 'trigram');
173+
CREATE TRIGGER lines_insert AFTER INSERT ON lines BEGIN
174+
INSERT INTO lines_fts (rowid, text) VALUES (new.id, new.text);
175+
END;
176+
CREATE TRIGGER lines_delete AFTER DELETE ON lines BEGIN
177+
INSERT INTO lines_fts (lines_fts, rowid, text) VALUES ('delete', old.id, old.text);
178+
END;
179+
CREATE TABLE marks (session TEXT PRIMARY KEY, through INTEGER NOT NULL, keep INTEGER NOT NULL, sealed INTEGER NOT NULL, turn INTEGER NOT NULL);
180+
PRAGMA user_version = ${INDEX_VERSION};`
181+
182+
// How many rows an older index stored more than once. A build before #2711 could hold one
183+
// row per writer for the same event, and no later catch-up removed it, so the rebuild is
184+
// the repair; the count goes to the log, because a history that shrinks must say why.
185+
function duplicated(db) {
186+
const rows = db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'lines'").get()
187+
if (rows === undefined) return 0 // a fresh file has no rows yet
188+
return db.prepare('SELECT COUNT(*) AS n FROM (SELECT session, seq FROM lines GROUP BY session, seq HAVING COUNT(*) > 1)').get().n
189+
}
190+
191+
function createIndex(db, writable) {
138192
try {
139-
db.exec('PRAGMA journal_mode = WAL')
140-
if (db.prepare('PRAGMA user_version').get().user_version !== INDEX_VERSION) {
141-
db.exec(`
142-
DROP TABLE IF EXISTS lines;
143-
DROP TABLE IF EXISTS marks;
144-
CREATE VIRTUAL TABLE lines USING fts5(text, session UNINDEXED, seq UNINDEXED, time UNINDEXED, who UNINDEXED, tokenize = 'trigram');
145-
CREATE TABLE marks (session TEXT PRIMARY KEY, through INTEGER NOT NULL, keep INTEGER NOT NULL, sealed INTEGER NOT NULL, turn INTEGER NOT NULL);
146-
PRAGMA user_version = ${INDEX_VERSION};`)
193+
if (writable) db.exec('PRAGMA journal_mode = WAL')
194+
// A write that waits for another host's short transaction instead of failing.
195+
db.exec('PRAGMA busy_timeout = 5000')
196+
const version = db.prepare('PRAGMA user_version').get().user_version
197+
if (version !== INDEX_VERSION) {
198+
// A read-only window cannot rebuild the file, and a half-read old schema would be
199+
// worse than the logs; it answers null and `read_own_chat` scans them.
200+
if (!writable) throw new Error(`the chat index is version ${version}, not ${INDEX_VERSION}, and this window cannot rebuild it`)
201+
const copies = version === 0 ? 0 : duplicated(db)
202+
db.exec('DROP TABLE IF EXISTS lines; DROP TABLE IF EXISTS lines_fts; DROP TABLE IF EXISTS marks;')
203+
db.exec(CREATE_SCHEMA)
204+
if (copies > 0) rt.warn('ds-bot: rebuilt the chat index; %d line(s) were stored more than once by two writers (#2711)', copies)
147205
}
148206
return {
149207
db,
208+
writable,
150209
hardened: false,
151210
mark: db.prepare('SELECT through, keep, sealed, turn FROM marks WHERE session = ?'),
152211
setMark: db.prepare('INSERT OR REPLACE INTO marks (session, through, keep, sealed, turn) VALUES (?, ?, ?, ?, ?)'),
153-
insert: db.prepare('INSERT INTO lines (text, session, seq, time, who) VALUES (?, ?, ?, ?, ?)'),
212+
insert: db.prepare('INSERT OR IGNORE INTO lines (text, session, seq, time, who) VALUES (?, ?, ?, ?, ?)'),
154213
before: db.prepare('SELECT text, session, seq, time, who FROM lines WHERE session = ? AND seq < ? ORDER BY seq DESC LIMIT ?'),
155214
from: db.prepare('SELECT text, session, seq, time, who FROM lines WHERE session = ? AND seq >= ? ORDER BY seq LIMIT ?'),
156215
countAll: db.prepare('SELECT COUNT(*) AS n FROM lines WHERE session IN (SELECT value FROM json_each(?))'),
@@ -167,16 +226,18 @@ export function install(rt) {
167226
indexOpening = undefined
168227
}, 'ds-bot: chat index')
169228

170-
// Adds what a part said since its mark. Reads of one part wait for each other, so no
171-
// line is added twice.
229+
// Adds what a part said since its mark. Reads of one part wait for each other within this
230+
// installation; two installations over one home meet again inside the transaction below.
172231
const catchingUp = new Map()
173232
function catchUp(index, part) {
233+
// A read-only window adds nothing: it reads the rows the writer indexed.
234+
if (!index.writable || readOnly()) return Promise.resolve()
174235
const running = catchingUp.get(part.sessionId)
175236
if (running) return running
176237
const job = (async () => {
177-
const mark = index.mark.get(part.sessionId)
178-
if (mark?.sealed) return
179-
const through = mark?.through ?? -1
238+
const known = index.mark.get(part.sessionId)
239+
if (known?.sealed) return
240+
const through = known?.through ?? -1
180241
const events = []
181242
for await (const event of eventsBackwards(part.sessionId, AbortSignal.timeout(INDEX_TIMEOUT_MS), Infinity)) {
182243
if (event.seq <= through) break
@@ -185,13 +246,25 @@ export function install(rt) {
185246
if (events.length > 0 && events.at(-1).seq !== through + 1) throw new Error(`the history of ${part.sessionId} came back with a gap`)
186247
events.reverse()
187248
if (index !== chatIndex) return
188-
let keep = mark ? mark.keep === 1 : false
189-
let turn = mark?.turn ?? -1
190249
const seal = part.endedAt !== undefined && Date.now() - part.endedAt > SEAL_AFTER_MS
191-
index.db.exec('BEGIN')
250+
// The mark is read again inside the transaction that writes the rows: another writer
251+
// may have committed past the mark this pass fetched from, and the read has to see
252+
// that commit before it decides what to insert (#2711). The rows and the mark move
253+
// together, so an interrupted pass cannot leave the mark ahead of the index. The
254+
// statement is `INSERT OR IGNORE` and the table is UNIQUE(session, seq), so a mark
255+
// that was still stale is a no-op rather than a second line.
256+
index.db.exec('BEGIN IMMEDIATE')
192257
try {
193-
let last = through
258+
const mark = index.mark.get(part.sessionId)
259+
if (mark?.sealed) {
260+
index.db.exec('COMMIT')
261+
return
262+
}
263+
let keep = mark ? mark.keep === 1 : false
264+
let turn = mark?.turn ?? -1
265+
let last = mark?.through ?? -1
194266
for (const event of events) {
267+
if (event.seq <= last) continue
195268
last = event.seq
196269
if (event.type === 'turn/start') turn = event.seq
197270
const entry = rt.historyEntry(event, false)

0 commit comments

Comments
 (0)