Skip to content

Commit 3919a2c

Browse files
committed
fix(server): return OpenCode records in message-time order
CodeRabbit flagged that rowid paging returned insertion order, and a backfilled or clock-adjusted message can hold a later rowid with an earlier time_created. Records are now sorted by time_created with rowid as the tie breaker before returning, keeping the paging cursor and its loop yields. Model: openrouter/z-ai/glm-5.3-flash. Harness: OpenCode (T3 Code).
1 parent d88472a commit 3919a2c

2 files changed

Lines changed: 32 additions & 6 deletions

File tree

‎apps/server/src/usage/opencodeUsageStore.test.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,26 @@ describe("readOpenCodeUsageRecords", () => {
126126
expect(read.records.at(-1)?.timestampMs).toBe(base + 1200);
127127
});
128128

129+
it("orders records by message time, not insertion order", async () => {
130+
const dbPath = NodePath.join(dir, "opencode.db");
131+
const database = createMessageStore(dbPath);
132+
const insert = database.prepare(
133+
"INSERT INTO message (id, session_id, time_created, data) VALUES (?, ?, ?, ?)",
134+
);
135+
// A backfilled message lands later in the table than an older instant.
136+
const late = assistantRow({ createdMs: 5_000 });
137+
const backfilled = assistantRow({ createdMs: 2_000, input: 10 });
138+
insert.run("msg_late", late.sessionId, late.createdMs, late.data);
139+
insert.run("msg_backfill", backfilled.sessionId, backfilled.createdMs, backfilled.data);
140+
database.close();
141+
142+
const read = await readOpenCodeUsageRecords(dbPath, 0);
143+
144+
expect(read.kind).toBe("ok");
145+
if (read.kind !== "ok") return;
146+
expect(read.records.map((record) => record.timestampMs)).toEqual([2_000, 5_000]);
147+
});
148+
129149
it("reports a store that was never created as missing", async () => {
130150
const read = await readOpenCodeUsageRecords(NodePath.join(dir, "absent.db"), 0);
131151
expect(read.kind).toBe("missing");

‎apps/server/src/usage/opencodeUsageStore.ts‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -63,10 +63,13 @@ function yieldToEventLoop(): Promise<void> {
6363
*
6464
* Pages walk `rowid`, which is the table's B-tree key, so each page is a
6565
* direct seek rather than a rescan; `time_created` carries no index and is
66-
* filtered per row. A row whose payload no longer parses (an older or newer
67-
* OpenCode writing an unexpected shape) is skipped individually, mirroring how
68-
* the JSONL parsers treat unrecognised lines, so one odd row cannot blank out
69-
* the provider.
66+
* filtered per row. Insertion order is not chronological — a backfilled or
67+
* clock-adjusted message can hold a later `rowid` with an earlier
68+
* `time_created` — so the returned records are ordered by `time_created` with
69+
* `rowid` as the tie breaker. A row whose payload no longer parses (an older
70+
* or newer OpenCode writing an unexpected shape) is skipped individually,
71+
* mirroring how the JSONL parsers treat unrecognised lines, so one odd row
72+
* cannot blank out the provider.
7073
*/
7174
export async function readOpenCodeUsageRecords(
7275
dbPath: string,
@@ -92,7 +95,7 @@ export async function readOpenCodeUsageRecords(
9295
const selectPage = database.prepare(
9396
"SELECT rowid, session_id, data, time_created FROM message WHERE rowid > ? ORDER BY rowid LIMIT ?",
9497
);
95-
const records: UsageRecord[] = [];
98+
const parsed: { readonly rowid: number; readonly record: UsageRecord }[] = [];
9699
let lastRowid = 0;
97100
for (;;) {
98101
const rows = selectPage.all(lastRowid, PAGE_SIZE) as unknown as readonly {
@@ -110,11 +113,14 @@ export async function readOpenCodeUsageRecords(
110113
row.data,
111114
typeof row.session_id === "string" ? row.session_id : "",
112115
);
113-
if (record !== null) records.push(record);
116+
if (record !== null) parsed.push({ rowid: row.rowid, record });
114117
}
115118
if (rows.length < PAGE_SIZE) break;
116119
await yieldToEventLoop();
117120
}
121+
const records = parsed
122+
.toSorted((a, b) => a.record.timestampMs - b.record.timestampMs || a.rowid - b.rowid)
123+
.map((entry) => entry.record);
118124
return { kind: "ok", records };
119125
} catch (error) {
120126
return { kind: "failed", message: failureMessage(error) };

0 commit comments

Comments
 (0)