Skip to content

Used atomic query for updating repost count outside of manual updates #1172

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

mike182uk
Copy link
Member

ref https://linear.app/ghost/issue/PROD-2422

When concurrent announce / undo (announce) activities are processed for external posts, the repost count could become negative due to using stale in-memory values

Example:

  • Post does not exist in the db
  • We receive an announce and an undo for the post very close together
  • Both handlers try to create the post (as it does not exist)
  • One handler succeeds in creating the post and gets the result (a post with a repost count of 0)
  • The other handler fails gracefully (as we ignore duplicate inserts) and gets the same post, with a repost count of 0
  • announce handler adds repost and saves: 0 + 1 = 1
  • undo handler removes repost (which exists because announce has already saved), but calculates: 0 - 1 = -1

To resolve we use atomic SQL operations (repost_count + delta) for external posts when doing add/remove operations, preventing stale reads. Manual count updates via setRepostCount() are still preserved when the dirty flag is set

ref https://linear.app/ghost/issue/PROD-2422

When concurrent `announce` / `undo` (`announce`) activities are processed for
external posts, the repost count could become negative due to using stale in-memory
values

 Example:
 - Post does not exist in the db
 - We receive an `announce` and an `undo` for the post very close together
 - Both handlers try to create the post (as it does not exist)
 - One handler succeeds in creating the post and gets the result (a post with a repost count of 0)
 - The other handler fails gracefully (as we ignore duplicate inserts) and gets the same post, with a repost count of 0
 - `announce` handler adds repost and saves: 0 + 1 = 1
 - `undo` handler removes repost (which exists because `announce` has already saved),
 but calculates: 0 - 1 = -1

To resolve we use atomic SQL operations (repost_count + delta) for external posts when
doing add/remove operations, preventing stale reads. Manual count updates via
`setRepostCount()` are still preserved when the dirty flag is set
Copy link

coderabbitai bot commented Aug 7, 2025

Walkthrough

A new integration test was added to the KnexPostRepository test suite to verify the handling of concurrent updates to a post's repost count. The test simulates concurrent modifications by creating an original post and a clone, performing repost count changes on both, and asserting the correct final state in the database. Additionally, the logic for updating the repost count in KnexPostRepository was revised. The update introduces a flag to determine whether to use atomic SQL increment operations or direct assignment, based on whether the post is internal or if the repost count has been manually adjusted.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch PROD-2422-fix-repost-count-update

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

🧹 Nitpick comments (1)
src/post/post.repository.knex.integration.test.ts (1)

2338-2338: Consider using more specific assertions instead of deep equality.

The toEqual() comparison between Post objects might be fragile if the Post class contains methods, computed properties, or complex internal state that doesn't compare reliably.

Consider replacing the deep equality check with specific property assertions:

-        expect(postClone).toEqual(post);
+        expect(postClone.id).toBe(post.id);
+        expect(postClone.repostCount).toBe(post.repostCount);
+        expect(postClone.uuid).toBe(post.uuid);

This approach is more explicit about what properties should match and less likely to break due to internal object structure changes.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 37243cf and 8a8185d.

📒 Files selected for processing (2)
  • src/post/post.repository.knex.integration.test.ts (1 hunks)
  • src/post/post.repository.knex.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (6)
📓 Common learnings
Learnt from: allouis
PR: TryGhost/ActivityPub#615
File: src/post/post.service.ts:254-278
Timestamp: 2025-05-05T07:34:59.855Z
Learning: The moderation check for the `repostByApId` method (using `moderationService.canInteractWithAccount()`) will be implemented in a separate commit, as part of the phased approach to adding moderation restrictions to reposts.
Learnt from: allouis
PR: TryGhost/ActivityPub#737
File: migrate/migrations/000054_populate-outboxes-table.up.sql:56-63
Timestamp: 2025-05-27T09:09:22.110Z
Learning: In the outboxes table migration for Ghost ActivityPub, the author_id field always refers to the author of the original post, not the person performing the outbox action. For reposts (outbox_type = 1), author_id should be posts.author_id (original author), while user_id captures who made the repost via the joins through accounts and users tables.
Learnt from: allouis
PR: TryGhost/ActivityPub#615
File: src/http/api/repost.ts:29-42
Timestamp: 2025-05-05T07:33:50.790Z
Learning: The PostService.repostByApId method currently only returns 'upstream-error', 'not-a-post', 'missing-author', and 'already-reposted' errors. The 'cannot-interact' error for moderation restrictions hasn't been implemented yet, though PR #615 is preparing the repost controller to handle such restrictions in the future.
📚 Learning: the moderation check for the `repostbyapid` method (using `moderationservice.caninteractwithaccount(...
Learnt from: allouis
PR: TryGhost/ActivityPub#615
File: src/post/post.service.ts:254-278
Timestamp: 2025-05-05T07:34:59.855Z
Learning: The moderation check for the `repostByApId` method (using `moderationService.canInteractWithAccount()`) will be implemented in a separate commit, as part of the phased approach to adding moderation restrictions to reposts.

Applied to files:

  • src/post/post.repository.knex.ts
  • src/post/post.repository.knex.integration.test.ts
📚 Learning: in the outboxes table migration for ghost activitypub, the author_id field always refers to the auth...
Learnt from: allouis
PR: TryGhost/ActivityPub#737
File: migrate/migrations/000054_populate-outboxes-table.up.sql:56-63
Timestamp: 2025-05-27T09:09:22.110Z
Learning: In the outboxes table migration for Ghost ActivityPub, the author_id field always refers to the author of the original post, not the person performing the outbox action. For reposts (outbox_type = 1), author_id should be posts.author_id (original author), while user_id captures who made the repost via the joins through accounts and users tables.

Applied to files:

  • src/post/post.repository.knex.ts
  • src/post/post.repository.knex.integration.test.ts
📚 Learning: the postservice.repostbyapid method currently only returns 'upstream-error', 'not-a-post', 'missing-...
Learnt from: allouis
PR: TryGhost/ActivityPub#615
File: src/http/api/repost.ts:29-42
Timestamp: 2025-05-05T07:33:50.790Z
Learning: The PostService.repostByApId method currently only returns 'upstream-error', 'not-a-post', 'missing-author', and 'already-reposted' errors. The 'cannot-interact' error for moderation restrictions hasn't been implemented yet, though PR #615 is preparing the repost controller to handle such restrictions in the future.

Applied to files:

  • src/post/post.repository.knex.ts
  • src/post/post.repository.knex.integration.test.ts
📚 Learning: in the tryghost/activitypub project, mysql automatically handles the `updated_at` column when updati...
Learnt from: allouis
PR: TryGhost/ActivityPub#583
File: src/account/account.repository.knex.ts:18-29
Timestamp: 2025-04-29T07:58:17.648Z
Learning: In the TryGhost/ActivityPub project, MySQL automatically handles the `updated_at` column when updating records, so there's no need to set it manually in update queries.

Applied to files:

  • src/post/post.repository.knex.ts
📚 Learning: in src/http/api/webhook.controller.ts, the handlepostunpublished, handlepostupdated, and handlepostd...
Learnt from: vershwal
PR: TryGhost/ActivityPub#1033
File: src/http/api/webhook.controller.ts:103-107
Timestamp: 2025-07-14T11:41:50.880Z
Learning: In src/http/api/webhook.controller.ts, the handlePostUnpublished, handlePostUpdated, and handlePostDeleted methods in PR #1033 are intentionally implemented as dummy APIs that return 200 status with null body. These are placeholder implementations to prevent URL errors while the actual backend logic will be built in upcoming PRs, following the incremental development approach used in this codebase.

Applied to files:

  • src/post/post.repository.knex.ts
  • src/post/post.repository.knex.integration.test.ts
🔇 Additional comments (6)
src/post/post.repository.knex.ts (3)

413-418: Excellent implementation of the atomic update logic!

The shouldUseAtomicUpdate flag correctly addresses the race condition issue described in the PR objectives. The logic properly distinguishes between:

  • Internal posts and external posts without manual modifications → use atomic SQL updates
  • External posts with manual modifications → preserve manual count while applying delta

The comments clearly explain the business reasoning.


436-437: Good addition for observability.

Including the shouldUseAtomicUpdate flag in the logging provides valuable debugging information to understand which update strategy is being applied in different scenarios.


443-454: Implementation correctly applies the atomic update strategy.

The conditional logic properly implements the two update strategies:

  • Atomic SQL increment for race condition prevention when shouldUseAtomicUpdate is true
  • Manual count preservation with delta application when false

The implementation is consistent with the like count update pattern used earlier in the file (lines 352-361), maintaining code consistency. The math for applying the delta (insertedRepostsCount - removedRepostsCount) is correct.

src/post/post.repository.knex.integration.test.ts (3)

2305-2357: Excellent test coverage for concurrent repost count updates!

This test effectively simulates the race condition scenario described in the PR objectives, where concurrent announce and undo activities could cause negative repost counts due to stale in-memory values. The test structure properly validates that atomic SQL operations prevent data corruption during concurrent updates.


2312-2336: Post clone creation is thorough and realistic.

The manual construction of the Post clone effectively simulates how concurrent handlers would have separate instances with identical initial state. The use of all constructor parameters ensures the clone has the same state as the original post before the concurrent modifications begin.


2349-2352: Proper validation of atomic update behavior.

The test correctly expects that the save operation should not throw an error despite the clone having a stale repost count of 0. This validates that the repository uses atomic SQL operations (likely UPDATE posts SET repost_count = repost_count - 1 WHERE id = ?) instead of direct assignment based on in-memory values.

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