Skip to content

fix(questions): make addQuestionToSession atomic and bounded - #1472

Closed
ionfwsrijan wants to merge 1 commit into
Canopus-Labs:mainfrom
ionfwsrijan:fix/1453-add-question-atomic
Closed

fix(questions): make addQuestionToSession atomic and bounded#1472
ionfwsrijan wants to merge 1 commit into
Canopus-Labs:mainfrom
ionfwsrijan:fix/1453-add-question-atomic

Conversation

@ionfwsrijan

Copy link
Copy Markdown
Contributor

Problem

addQuestionToSession performed two writes that were not atomic:

const createdQuestions = await Question.insertMany(questions.map(...)); // write 1
session.questions.push(...createdQuestions.map((q) => q._id));          // memory
await session.save();                                                   // write 2
  1. If session.save() failed (or the connection dropped between the
    writes), the Question documents were already inserted but never linked —
    permanently orphaned rows no API path surfaces.
  2. Two concurrent addQuestionToSession calls each loaded the session,
    pushed their own IDs, and save()d; the later save() overwrote the
    earlier push, silently dropping one batch's linkage.
  3. questions had no upper bound per request.

Fix

backend/controllers/questionController.jsaddQuestionToSession now
runs entirely inside a mongoose.startSession() transaction (mirroring
createSession / deleteSession), and the linkage is an atomic $push:

  • The session ownership check, Question.insertMany, and the session update
    commit or roll back together — a failed session update can no longer leave
    orphaned questions.
  • Linkage uses Session.updateOne({ _id }, { $push: { questions: { $each: ids } } })
    instead of read-modify-write + save(), so concurrent adds both persist
    without losing a batch.
  • Input/ownership errors map to 400/404/403 explicitly.

backend/Input_validators/ValidateQuestions.js — the questions array is
now capped at max(50) per request.

Files changed

  • backend/controllers/questionController.js - transactional
    addQuestionToSession with atomic $push linkage.
  • backend/Input_validators/ValidateQuestions.js - questions capped at 50.
  • backend/tests/questionController.ownership.unit.test.js - rewrote with a
    Module._load shim (the previous vi.mock could not intercept the CJS
    controller's require() calls; it was already failing 5/5 on
    origin/main).

Testing

npx vitest run tests/questionController.ownership.unit.test.js - 6/6 pass:

  • 403 cross-user write: no insert, no linkage update.
  • 201 happy path: insertMany once; linkage via $push: { questions: { $each } }
    (no session.save()).
  • Linkage update failure -> 500; both writes run inside one withTransaction,
    so no orphaned questions are possible.
  • 404 when the session does not exist.
  • 400 for invalid/missing input.
  • questionBank.unit.test.js still passes (6/6).

Related

Closes #1453

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@ionfwsrijan, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 3 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 026608c0-d8c8-465e-9eb3-f3fcb11f2287

📥 Commits

Reviewing files that changed from the base of the PR and between 8acb5b8 and 979b3e6.

📒 Files selected for processing (3)
  • backend/Input_validators/ValidateQuestions.js
  • backend/controllers/questionController.js
  • backend/tests/questionController.ownership.unit.test.js

Comment @coderabbitai help to get the list of available commands.

throw new Error("INVALID_INPUT");
}

const session = await Session.findById(sessionId).session(mongoSession);
// this update commit or roll back together inside the transaction, so a
// failed session update can never leave orphaned questions.
await Session.updateOne(
{ _id: sessionId },
@github-actions github-actions Bot added the rate-limited Closed automatically: contributor rate limit reached label Aug 6, 2026
@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown

Thank you for your contribution!

To keep reviews manageable and maintain repository quality, contributors may have a maximum of 3 open Issues and 3 open Pull Requests at any given time.

Please wait until one of your existing submissions is reviewed or closed before opening additional ones.

If you believe this was closed by mistake, feel free to contact the maintainers.

@github-actions github-actions Bot closed this Aug 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

rate-limited Closed automatically: contributor rate limit reached

Projects

None yet

Development

Successfully merging this pull request may close these issues.

addQuestionToSession is not atomic — inserted questions can be orphaned when the session update fails

2 participants