Skip to content

Fix race condition in setXP causing stale document overwrites#12

Merged
Abadima merged 3 commits into
LTSfrom
copilot/sub-pr-10-again
Jan 26, 2026
Merged

Fix race condition in setXP causing stale document overwrites#12
Abadima merged 3 commits into
LTSfrom
copilot/sub-pr-10-again

Conversation

Copilot AI commented Jan 26, 2026

Copy link
Copy Markdown
Contributor

Information

findOneAndUpdate returns the pre-update document by default. Mutating and calling save() on this stale document overwrites the XP value just set in the database.

Changes:

  • Calculate level before database operation
  • Update xp and level atomically in single findOneAndUpdate call
  • Return both xp and level (consistent with setLevel, addXP)

Before:

const user = await levels.findOneAndUpdate(
  { user: userID, guild: guildID },
  { xp: xp },  // Update xp
  { upsert: true }
);  // Returns pre-update document

const lvl = Math.floor(0.1 * Math.sqrt(xp));
if (user.level !== lvl) {
  user.level = lvl;
  await user.save();  // Overwrites xp with stale value
}

After:

const lvl = Math.floor(0.1 * Math.sqrt(xp));

await levels.findOneAndUpdate(
  { user: userID, guild: guildID },
  { xp: xp, level: lvl },  // Atomic update
  { upsert: true }
);

return { xp, level: lvl };

Issue Related

Addresses feedback from PR #10: #10 (comment)

Checks

  • Does the package work as intended?

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@codacy-production

codacy-production Bot commented Jan 26, 2026

Copy link
Copy Markdown

Codacy's Analysis Summary

2 new issues (≤ 0 medium issue)
0 new security issue (≤ 0 issue)
0 complexity
0 duplications

Review Pull Request in Codacy →

AI Reviewer available: add the codacy-review label to get contextual insights without leaving GitHub.

Copilot AI and others added 2 commits January 26, 2026 05:01
Co-authored-by: Abadima <39747270+Abadima@users.noreply.github.com>
Co-authored-by: Abadima <39747270+Abadima@users.noreply.github.com>
Copilot AI changed the title [WIP] Address feedback from PR #10 on merging LTS to Latest Fix race condition in setXP causing stale document overwrites Jan 26, 2026
Copilot AI requested a review from Abadima January 26, 2026 05:03
@Abadima
Abadima marked this pull request as ready for review January 26, 2026 05:06
@Abadima
Abadima merged commit 44e681f into LTS Jan 26, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants