Skip to content

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

Open
aloneangel45 wants to merge 2 commits into
C4illin:mainfrom
aloneangel45:fix/atomic-job-creation-returning-id
Open

aloneangel45 wants to merge 2 commits into
C4illin:mainfrom
aloneangel45:fix/atomic-job-creation-returning-id

Conversation

@aloneangel45

@aloneangel45 aloneangel45 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

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.

Written for commit 74034e0. Summary will update on new commits.

View guided diff

@github-actions github-actions Bot added the Fix label Nov 22, 2026

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="tests/pages/root.test.ts">

<violation number="1" location="tests/pages/root.test.ts:156">
P2: These concurrency tests cannot catch the bug they are meant to guard. Every handler runs its insert and id lookup synchronously, so the old `INSERT` + `SELECT` code would also pass. To exercise the race, the test needs a real interleaving, for example separate processes or connections against the same database file. At minimum, confirm the tests fail on the pre-PR root.tsx before relying on them as regression coverage.</violation>
</file>

Reply with feedback, questions, or to request a fix.

View guided diff | Re-trigger cubic

Comment thread tests/pages/root.test.ts
expect(jobsOf(user.id)).toHaveLength(1);
});

test("assigns distinct job IDs to concurrent requests sharing unauthenticated user 0", async () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These concurrency tests cannot catch the bug they are meant to guard. Every handler runs its insert and id lookup synchronously, so the old INSERT + SELECT code would also pass. To exercise the race, the test needs a real interleaving, for example separate processes or connections against the same database file. At minimum, confirm the tests fail on the pre-PR root.tsx before relying on them as regression coverage.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/pages/root.test.ts, line 156:

<comment>These concurrency tests cannot catch the bug they are meant to guard. Every handler runs its insert and id lookup synchronously, so the old `INSERT` + `SELECT` code would also pass. To exercise the race, the test needs a real interleaving, for example separate processes or connections against the same database file. At minimum, confirm the tests fail on the pre-PR root.tsx before relying on them as regression coverage.</comment>

<file context>
@@ -152,4 +152,31 @@ describe("GET / without accounts (ALLOW_UNAUTHENTICATED)", () => {
     expect(jobsOf(user.id)).toHaveLength(1);
   });
+
+  test("assigns distinct job IDs to concurrent requests sharing unauthenticated user 0", async () => {
+    setEnv({ ALLOW_UNAUTHENTICATED: true, UNAUTHENTICATED_USER_SHARING: true });
+    const existingIds = new Set(jobsOf("0").map((job) => job.id));
</file context>

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed the @cubic-dev-ai test coverage finding in commit 74034e0:

  • Added deterministic interleaved-insert regression tests in tests/pages/root.test.ts using a temporary SQLite AFTER INSERT ON jobs trigger (withConcurrentJobInsert, always dropped in finally) that inserts a competing job for the same user_id immediately after the handler's INSERT, covering both an authenticated user and shared anonymous user 0 (UNAUTHENTICATED_USER_SHARING: true).
  • Verified both new tests fail on pre-PR src/pages/root.tsx (the jobId cookie receives the competing racer row id instead of the handler's own inserted row id) and pass with INSERT ... RETURNING id.
  • Re-verified locally with bun fmt --check, bun x eslint src/pages/root.tsx tests/pages/root.test.ts, bun run lint:tsc (52 files), and bun test tests/pages/root.test.ts (all 16 test cases passed; on Windows only the shared afterAll rmSync cleanup in tests/preload.ts hits EBUSY due to the open module-level SQLite handle).

@cubic-dev-ai

cubic-dev-ai Bot commented Nov 22, 2026

Copy link
Copy Markdown
Contributor

Addressed the @cubic-dev-ai test coverage finding in commit 74034e0:

  • Added deterministic interleaved-insert regression tests in tests/pages/root.test.ts using a temporary SQLite AFTER INSERT ON jobs trigger (withConcurrentJobInsert, always dropped in finally) that inserts a competing job for the same user_id immediately after the handler's INSERT, covering both an authenticated user and shared anonymous user 0 (UNAUTHENTICATED_USER_SHARING: true).
  • Verified both new tests fail on pre-PR src/pages/root.tsx (the jobId cookie receives the competing racer row id instead of the handler's own inserted row id) and pass with INSERT ... RETURNING id.
  • Re-verified locally with bun fmt --check, bun x eslint src/pages/root.tsx tests/pages/root.test.ts, bun run lint:tsc (52 files), and bun test tests/pages/root.test.ts (all 16 test cases passed; on Windows only the shared afterAll rmSync cleanup in tests/preload.ts hits EBUSY due to the open module-level SQLite handle).

@aloneangel45 Good — that addresses the finding. The trigger-based tests are the ones that actually pin the bug: in-process concurrent GET / requests could never reproduce the race because the old code ran INSERT and SELECT back-to-back with no await between them on a single connection, so they always serialized. An AFTER INSERT trigger forces the competing row to exist inside the same statement, so the old SELECT ... ORDER BY id DESC deterministically returns the racer's id while RETURNING id returns the handler's own row. Per the SQLite docs, RETURNING only reports rows directly modified by the statement and ignores trigger side effects (lang_returning.html), so the fail-on-old/pass-on-new result is a genuine signal, not test noise.

Two small things worth being aware of, neither blocking:

  • The jobs[0]/jobs[1] ordering assertions depend on jobsOf returning ascending ids, which holds because the trigger inserts after the handler's row — fine, just an implicit assumption of the test.
  • As a side effect of moving the insert, cookies-disabled requests (missing jobId) no longer leave an orphan job row behind. That looks like an improvement, but it is a behavior change beyond the atomic-insert fix — worth calling out in the PR description if you haven't.

No further action needed on the original coverage finding.

Tip: get faster answers by chatting with cubic’s review copilot in the review UI

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Concurrency Race Condition in root.tsx Job Creation via ORDER BY id DESC

1 participant