fix(root): create new jobs atomically with RETURNING id

AL
3h ago
+75-10

Fixes #720

Problem

In src/pages/root.tsx, when a request arrived without a jobId cookie, a new row was inserted into jobs and then fetched in a separate query:

db.query("INSERT INTO jobs (user_id, date_created) VALUES (?, ?)").run(...);
const newJobId = db.query("SELECT id FROM jobs WHERE user_id = ? ORDER BY id DESC").get(user.id).id;

Under concurrent GET / requests sharing the same user_id (such as anonymous user 0 when UNAUTHENTICATED_USER_SHARING=true, or multiple simultaneous tabs for an authenticated user), both requests could insert rows and read back the same latest id.

Fix

  • Guard job creation with if (!jobId) and insert + return the newly created row ID atomically in a single statement using INSERT INTO jobs (user_id, date_created) VALUES (?, ?) RETURNING id.
  • Add regression tests in tests/pages/root.test.ts sending 10 concurrent GET / requests (for both shared anonymous user 0 and an authenticated user) and asserting 10 distinct jobId cookies are issued.

Verification

  • bun fmt --check src/pages/root.tsx tests/pages/root.test.ts — passed
  • bun x eslint src/pages/root.tsx tests/pages/root.test.ts — passed
  • bun run lint:tsc — passed (52 files)
  • bun test tests/pages/root.test.ts — 14 test cases passed (on Windows, only the shared afterAll rmSync temp cleanup in tests/preload.ts hits EBUSY due to the open module-level SQLite handle)

Summary by cubic

Fixes #720 by making job creation atomic so concurrent requests no longer collide on the same job ID.

Previously, GET / inserted a job row and then fetched the latest ID in a separate query, which let simultaneous requests for the same user read back the same ID. Now the insert returns the new ID directly via RETURNING id, so each request gets its own job.

Regression tests now cover both nondeterministic and deterministic races: 10 concurrent GET / requests for the shared anonymous user and an authenticated user each receive distinct job IDs, and a TEMP TRIGGER that forcibly interleaves another insert proves each request it keeps its own job ID.