Fix single-column recency ordering and validate limits

Two more from Macroscope review:

- `ORDER BY COALESCE(...)` throws on a source down to one recency
  column. SQLite requires at least two arguments, so the pre-017 schema
  the column filter exists to support was exactly the case that aborted.
  Emit the column directly when only one survives the filter.
- `seedDevDatabase` accepted non-positive limits. Both are bound into
  `LIMIT ?`, where SQLite reads a negative as "no limit" — a caller
  bypassing the CLI flags silently got a full-table copy instead of the
  bounded one the options contract promises. Rejected before the target
  is touched, alongside the existing upper-bound check.

Both regression tests confirmed failing without their fix.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
This commit is contained in:
Theo BrowneandClaude Opus 5 committed 2026-07-26 20:38:49 -07:00
1 parent dba56bafa3
commit 8dee88913c
2 files changed
+127 -1

No files matched your search

+103
View File
@@ -571,6 +571,40 @@ describe("seedDevDatabase", () => {
);
});
// SQLite reads a negative LIMIT as "no limit", so an unchecked value turns a
// capped copy into a full-table one rather than failing.
for (const limits of [
{ threadLimit: 0, activityLimit: 10 },
{ threadLimit: -1, activityLimit: 10 },
{ threadLimit: 5, activityLimit: 0 },
{ threadLimit: 5, activityLimit: -1 },
]) {
it(`refuses threadLimit ${String(limits.threadLimit)} / activityLimit ${String(limits.activityLimit)}`, () => {
withDatabases(({ source, target }) => {
assert.throws(
() =>
seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
...limits,
seededAt: SEEDED_AT,
}),
DevSeedError,
);
// Rejected before the destructive transaction opened.
const projects = query<{ project_id: string }>(
target,
"SELECT project_id FROM projection_projects",
);
assert.deepStrictEqual(
projects.map((row) => row.project_id),
["stale"],
);
});
});
}
// A caller that bypasses the CLI flag would otherwise discover the ceiling
// only after the target had been emptied and the copy rolled back.
it("refuses a thread limit above the ceiling before touching the target", () => {
@@ -599,6 +633,75 @@ describe("seedDevDatabase", () => {
});
});
// Down to one recency column, the ordering expression cannot be a COALESCE:
// SQLite requires at least two arguments and throws otherwise, which would
// abort the seed on exactly the old schema the column filter exists to serve.
it("reads a source with only one recency column", () => {
const directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-dev-seed-1col-"));
const source = NodePath.join(directory, "source.sqlite");
const target = NodePath.join(directory, "target.sqlite");
try {
const database = new NodeSqlite.DatabaseSync(source);
// created_at alone: no updated_at, no archived_at, no latest_user_message_at.
database.exec(`CREATE TABLE projection_threads (
thread_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, title TEXT NOT NULL,
created_at TEXT NOT NULL, deleted_at TEXT)`);
// Matches the target's project columns; only the thread recency columns
// are being varied here.
database.exec(`CREATE TABLE projection_projects (
project_id TEXT PRIMARY KEY, title TEXT NOT NULL, workspace_root TEXT NOT NULL,
scripts_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
deleted_at TEXT)`);
database.exec(`CREATE TABLE projection_state (projector TEXT PRIMARY KEY,
last_applied_sequence INTEGER NOT NULL, updated_at TEXT NOT NULL)`);
database
.prepare(`INSERT INTO projection_projects VALUES ('p1','P','/repo','[]',?,?,NULL)`)
.run(SEEDED_AT, SEEDED_AT);
for (const thread of [
{ id: "old", at: "2026-07-10T00:00:00.000Z" },
{ id: "new", at: "2026-07-20T00:00:00.000Z" },
]) {
database
.prepare(`INSERT INTO projection_threads VALUES (?,?,?,?,NULL)`)
.run(thread.id, "p1", thread.id, thread.at);
}
database.close();
// The target mirrors the source's thread columns: this test varies the
// recency columns, and a target demanding one the source lacks would fail
// on the NOT NULL rather than on the ordering expression under test.
const targetDatabase = new NodeSqlite.DatabaseSync(target);
targetDatabase.exec(`CREATE TABLE projection_threads (
thread_id TEXT PRIMARY KEY, project_id TEXT NOT NULL, title TEXT NOT NULL,
created_at TEXT NOT NULL, deleted_at TEXT)`);
targetDatabase.exec(`CREATE TABLE projection_projects (
project_id TEXT PRIMARY KEY, title TEXT NOT NULL, workspace_root TEXT NOT NULL,
scripts_json TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL,
deleted_at TEXT)`);
targetDatabase.exec(`CREATE TABLE projection_state (projector TEXT PRIMARY KEY,
last_applied_sequence INTEGER NOT NULL, updated_at TEXT NOT NULL)`);
targetDatabase.close();
const summary = seedDevDatabase({
sourceDbPath: source,
targetDbPath: target,
threadLimit: 1,
activityLimit: 10,
seededAt: SEEDED_AT,
});
assert.equal(summary.threads, 1);
// Ordering still applies: the newer thread is the one kept.
const titles = query<{ title: string }>(target, "SELECT title FROM projection_threads");
assert.deepStrictEqual(
titles.map((row) => row.title),
["new"],
);
} finally {
NodeFS.rmSync(directory, { recursive: true, force: true });
}
});
it("reports a source with nothing to copy", () => {
withDatabases(
({ source, target }) => {
+24 -1
View File
@@ -321,6 +321,21 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
"Each thread costs one SQLite bound variable, and that is the engine's limit.",
);
}
// Both limits are bound straight into `LIMIT ?`, where SQLite reads a
// negative value as "no limit" — so a caller bypassing the CLI flags turns a
// capped copy into a full-table one, silently. The flags already reject this;
// enforcing it here keeps the options contract true of the function itself.
for (const [name, value] of [
["threadLimit", options.threadLimit],
["activityLimit", options.activityLimit],
] as const) {
if (!Number.isSafeInteger(value) || value < 1) {
throw new DevSeedError(
`${name} must be a positive integer, got ${String(value)}`,
"SQLite reads a negative LIMIT as unbounded, which would copy the whole table.",
);
}
}
let source: NodeSqlite.DatabaseSync;
try {
@@ -368,6 +383,14 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
const recencyColumns = ["latest_user_message_at", "updated_at", "created_at"].filter((column) =>
hasColumn(source, "projection_threads", column),
);
// SQLite's COALESCE requires at least two arguments, so a source down to a
// single recency column — the pre-migration-017 case this filter exists to
// support — would throw rather than degrade. `created_at` is NOT NULL from
// migration 005 on, so there is always at least one.
const recencyOrder =
recencyColumns.length > 1
? `COALESCE(${recencyColumns.join(", ")})`
: (recencyColumns[0] ?? "rowid");
const activeFilters = ["deleted_at", "archived_at"]
.filter((column) => hasColumn(source, "projection_threads", column))
.map((column) => `${column} IS NULL`);
@@ -376,7 +399,7 @@ export function seedDevDatabase(options: DevSeedOptions): DevSeedSummary {
.prepare(
`SELECT thread_id FROM projection_threads
${activeFilters.length > 0 ? `WHERE ${activeFilters.join(" AND ")}` : ""}
ORDER BY COALESCE(${recencyColumns.join(", ")}) DESC
ORDER BY ${recencyOrder} DESC
LIMIT ?`,
)
.all(options.threadLimit) as Array<{ thread_id: string }>