fix(root): create new jobs atomically with RETURNING id
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 usingINSERT INTO jobs (user_id, date_created) VALUES (?, ?) RETURNING id. - Add regression tests in
tests/pages/root.test.tssending 10 concurrentGET /requests (for both shared anonymous user0and an authenticated user) and asserting 10 distinctjobIdcookies are issued.
Verification
bun fmt --check src/pages/root.tsx tests/pages/root.test.ts— passedbun x eslint src/pages/root.tsx tests/pages/root.test.ts— passedbun run lint:tsc— passed (52files)bun test tests/pages/root.test.ts— 14 test cases passed (on Windows, only the sharedafterAllrmSynctemp cleanup intests/preload.tshitsEBUSYdue 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.