Skip to content

fix: prune messages with NOT EXISTS and keyset paging - #113

Merged
cardmagic merged 2 commits into
mainfrom
fix/message-pruner-not-exists
Dec 2, 2026
Merged

cardmagic merged 2 commits into
mainfrom
fix/message-pruner-not-exists

Conversation

@cardmagic

Copy link
Copy Markdown
Owner

Summary

 prunable
-  id NOT IN (SELECT message_id FROM ready_messages)
-  id NOT IN (... claimed_messages / dead_letters / dead_letters.retried_message_id)
-  id NOT IN (SELECT message_id FROM effects    WHERE status != 'completed')   -- full scan
-  id NOT IN (SELECT message_id FROM broadcasts WHERE status != 'delivered')   -- full scan
+  NOT EXISTS (SELECT 1 FROM <each of the six> WHERE message_id = messages.id [AND status ...])  -- index probe

 prune_relation
   loop
-    ids = relation.limit(batch_size).pluck(:id)
+    ids = relation.where(id > last_id).order(:id).limit(batch_size).pluck(:id)
     break if ids.empty?
     delete ids
+    break if ids.size < batch_size
+    last_id = ids.last

The status != lists could not use an index, so SQLite scanned all of effects and broadcasts on every batch, and the loop re-ran that query once more after the last batch. No migration and no behavior change: the same messages are pruned.

Evidence

  • Before: synthetic SQLite (3.54.1), 1M messages, 1.5M effects, 1.5M broadcasts, 25k old messages blocked by pending effects. Candidate query per 1000-row batch: 365, 271, 282, 227, 228, 225 ms (EXPLAIN QUERY PLAN: SCAN of effects and broadcasts).
    After: 31, 5.8, 4.8, 3.2, 2.9, 2.9 ms (SEARCH ... (message_id=?) on both). The first batch still walks the 25k blocked rows once; later batches resume after them.
  • New test/integration/message_pruner_test.rb: compares the pruned set with the old NOT IN query for all 64 combinations of the six guards, covers effect/broadcast statuses, a retried dead letter, batch boundaries (0–7 prunable rows at batch size 3), query counts, and the cursor. A SQLite-only test asserts both tables are searched by message_id and not scanned. Against the old code, four of the nine fail.
  • bundle exec rake (test, standard, rubocop, rbs, steep, brakeman) is green locally on Ruby 3.3 and SQLite. Postgres and MySQL run in CI.

Merge Danger

Door: two-way

Blast Radius: MessagePruner only (#prune and #preview)

MessagePruner#prunable guarded each message with six NOT IN subqueries.
The effects (status != 'completed') and broadcasts (status != 'delivered')
lists cannot use an index, so SQLite scanned both tables for every batch,
and #prune_relation re-ran the whole query for every batch, including the
final empty one.

Rewrite the six guards as correlated NOT EXISTS, which probe the existing
message_id indexes, and page by id so each batch resumes after the last.
A batch shorter than batch_size ends the loop without another query.

Tests compare against the previous NOT IN query for every combination of
guards, cover batch boundaries and the query count, and assert on SQLite
that effects and broadcasts are searched by message_id.
@greptile-apps

greptile-apps Bot commented Dec 2, 2026 •

Copy link
Copy Markdown

Confidence Score: 5/5RetriggerView in Greptile

[Medium impact] The PR appears safe to merge, with both previous findings addressed and no new actionable issues found.

Summary

The PR replaces message-retention guards with correlated NOT EXISTS queries and pages deletion batches by message ID.

  • Message pruning checks each safety rule against the current message.
  • Message pruning moves through candidates by increasing ID.

Reviews (2) · Last reviewed commit: "test: make the pruner plan and cursor ch..." · Reviewed by Greptile

Comment thread lib/solid_objects/message_pruner.rb Resolved
Comment thread lib/solid_objects/message_pruner.rb Outdated
Comment on lines +61 to +70
# @rbs () -> Array[[ActiveRecord::Relation[untyped], Symbol]]
def reference_guards
[
[ ReadyMessage.all, :message_id ],
[ ClaimedMessage.all, :message_id ],
[ DeadLetter.all, :message_id ],
[ DeadLetter.where.not(retried_message_id: nil), :retried_message_id ],
[ Effect.where.not(status: "completed"), :message_id ],
[ Broadcast.where.not(status: "delivered"), :message_id ]
]

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 One-use helper adds indirection

reference_guards only returns an array and has one caller. Readers must jump between two methods to understand one query, and the new signature hides the row types behind untyped. This violates the repository directives to inline small functions used once and avoid untyped where real types exist. Satisfy these requirements before merging.

Before:

reference_guards.reduce(Message.all) do |messages, (references, column)|

After:

[
  [ ReadyMessage.all, :message_id ],
  [ ClaimedMessage.all, :message_id ],
  [ DeadLetter.all, :message_id ],
  [ DeadLetter.where.not(retried_message_id: nil), :retried_message_id ],
  [ Effect.where.not(status: "completed"), :message_id ],
  [ Broadcast.where.not(status: "delivered"), :message_id ]
].reduce(Message.all) do |messages, (references, column)|

Inline the array in prunable, keep its existing @rbs signature, and regenerate the signatures.

Context Used: # De-AI Code Review In this review, suggest simplifying this code by removing "AI slop": Remove: - Comments that restate what the code already shows - Docstrings that just repeat the function signature - Defensive code for impossible scenarios ... (source)

Prompt To Fix With AI
This is a comment left during a code review.
Path: lib/solid_objects/message_pruner.rb
Line: 61-70

Comment:
**One-use helper adds indirection**

`reference_guards` only returns an array and has one caller. Readers must jump between two methods to understand one query, and the new signature hides the row types behind `untyped`. This violates the repository directives to inline small functions used once and avoid `untyped` where real types exist. Satisfy these requirements before merging.

Before:
```ruby
reference_guards.reduce(Message.all) do |messages, (references, column)|
```

After:
```ruby
[
  [ ReadyMessage.all, :message_id ],
  [ ClaimedMessage.all, :message_id ],
  [ DeadLetter.all, :message_id ],
  [ DeadLetter.where.not(retried_message_id: nil), :retried_message_id ],
  [ Effect.where.not(status: "completed"), :message_id ],
  [ Broadcast.where.not(status: "delivered"), :message_id ]
].reduce(Message.all) do |messages, (references, column)|
```

Inline the array in `prunable`, keep its existing `@rbs` signature, and regenerate the signatures.

**Context Used:** # De-AI Code Review  In this review, suggest simplifying this code by removing "AI slop":  **Remove:** - Comments that restate what the code already shows - Docstrings that just repeat the function signature - Defensive code for impossible scenarios ... ([source](https://app.greptile.com/custom-context?memory=instruction-0))

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Inlined the guard list into prunable in ecbea5a and regenerated the signatures.

The SQLite plan assertion depended on whatever statistics earlier tests
left behind. Seed 3,000 effects and broadcasts and ANALYZE inside
restoring_sqlite_statistics, like the effect recovery plan test. MySQL
clients inline the id cursor instead of binding it, so read it from the
SQL when there are no binds.

Inline the guard list in MessagePruner#prunable.
@context7

context7 Bot commented Dec 2, 2026

Copy link
Copy Markdown

Docs7 for cardmagic/solid-objects-ruby

Result Status Action
Deployment ➖ Not used —
Content review ✅ Passed. No problems found. —

Commit ecbea5a

@cardmagic

Copy link
Copy Markdown
Owner Author

@greptileai review

@cardmagic
cardmagic merged commit 038af6b into main Dec 2, 2026
44 checks passed
@cardmagic
cardmagic deleted the fix/message-pruner-not-exists branch December 2, 2026 00:45
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.

1 participant