openfga icon indicating copy to clipboard operation
openfga copied to clipboard

fix(sqlite): make SQLTupleIterator concurrency-safe for Next and Head

Open Popie52 opened this issue 7 months ago • 9 comments

Description

What problem is being solved?

The SQLTupleIterator was vulnerable to thundering herd issues and race conditions during its lazy-loading phase. If Next() and Head() were called concurrently on an uninitialized iterator, it could trigger redundant database queries or leave the internal state (t.rows and t.firstRow) inconsistent or "half-initialized."

How is it being solved?

Implemented a dual-locking strategy to ensure idempotent initialization:

  • inFlight Mutex: Guards the actual database I/O to ensure only one fetch operation occurs, regardless of how many concurrent calls hit the iterator initially.
  • State Mutex (mu): Protects internal variables (fetched, rows, firstRow). By separating this from I/O locking, the iterator remains responsive—allowing operations like Stop() to execute without blocking on a slow database query.

What changes are made to solve it?

  • Atomic Initialization: Added inFlight mutex and a fetched flag to guarantee the database is hit exactly once.
  • Non-blocking I/O: Refined the locking strategy so the state mutex (mu) is released during the actual SQL query execution.
  • Race Fixes: Resolved synchronization issues between fetchBuffer, next(), and head() to prevent loss of the first record.
  • State Integrity: Ensured firstRow caching is safely handled to maintain consistency when switching between Head() and Next().

References

  • Follow-up: [Add issue link if applicable]

Review Checklist

  • [x] I have clicked on "allow edits by maintainers"
  • [ ] I have added documentation (not required for this change)
  • [x] The correct base branch is main
  • [x] I have added tests / verified behavior manually

Summary by CodeRabbit

  • New Features

    • Added a clear error (ErrIteratorRowsNotInitialized) when an iterator's result set isn't initialized before use.
  • Bug Fixes

    • Fixed race conditions during concurrent iteration and initialization using a dual-locking strategy.
    • Prevented duplicate initialization by making the fetch process idempotent.
    • Improved cleanup to close and clear underlying query results when iteration ends or is stopped.
    • Corrected first-row caching logic to avoid skipping records when calling Head() followed by Next().

Popie52 avatar Apr 27 '26 11:04 Popie52

CLA Signed

The committers listed above are authorized under a signed CLA.

  • :white_check_mark: login: Popie52 / name: Popie52 (059fe92000d8b6cb968d3f80da6cac2f040227ae, 0fe26a0f20210b306eb31e57adfbbd5bdc55c527, 67bc6ab995bb26af8c55785df3600ee221ea4f2d, c77311bef4411369066263e84bc8e29e68dee651)

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Added exported sentinel ErrIteratorRowsNotInitialized, a per-initialization inFlight mutex, and firstRow state. fetchBuffer now serializes initialization, prevents duplicate queries, replaces and closes prior rows, and resets firstRow. next, head, and Stop adjust locking, check initialization, close/nil rows on exhaustion/stop, and route unmarshal errors via t.handleSQLError. (45 words)

Changes

Iterator synchronization & exported sentinel

Layer / File(s) Summary
Data Shape / Sentinels
pkg/storage/sqlite/tuple_iterator.go
Added exported ErrIteratorRowsNotInitialized and new firstRow field (guarded) to SQLTupleIterator.
Concurrency / Initialization
pkg/storage/sqlite/tuple_iterator.go
Added inFlight mutex; fetchBuffer now serializes concurrent calls, checks/sets t.fetched to avoid duplicate queries, closes any existing t.rows before replacing, and resets t.firstRow.
Iteration Control / Error Handling
pkg/storage/sqlite/tuple_iterator.go
next and head unlock mu while calling fetchBuffer, re-check iterator state, return ErrIteratorRowsNotInitialized if t.rows remains nil, close and nil t.rows when exhaustion detected, store a copied firstRow in head, and route proto.Unmarshal failures through t.handleSQLError.
Stop / Teardown
pkg/storage/sqlite/tuple_iterator.go
Stop marks t.fetched = true, closes any active t.rows, and sets t.rows = nil.
Minor / Metadata
go.mod
Dependency/manifest update (unchanged logical behavior).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested reviewers

  • senojj

Poem

🐇 I hopped through rows with careful cheer,
Locked the fetch so only one could peer,
Closed old windows, copied the sight,
Sent stray errors to be handled right,
Now iteration hums, steady and clear.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately describes the main change: making SQLTupleIterator concurrency-safe for Next and Head methods through synchronization improvements.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • [ ] Create PR with unit tests

[!TIP]

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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

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

coderabbitai[bot] avatar Apr 27 '26 11:04 coderabbitai[bot]

Thank you for the pull request! Please address the AI comments; I confirmed that they are all accurate.

senojj avatar Apr 27 '26 13:04 senojj

Ok

Popie52 avatar Apr 27 '26 13:04 Popie52

Codecov Report

:white_check_mark: All modified and coverable lines are covered by tests. :white_check_mark: Project coverage is 84.83%. Comparing base (c9e5428) to head (f8ee349). :warning: Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #3089      +/-   ##
==========================================
+ Coverage   80.20%   84.83%   +4.63%     
==========================================
  Files         196        5     -191     
  Lines       21684     1061   -20623     
==========================================
- Hits        17390      900   -16490     
+ Misses       3533      119    -3414     
+ Partials      761       42     -719     
Flag Coverage Δ
matrix 84.83% <ø> (ø)
storage ?
unit ?

Flags with carried forward coverage won't be shown. Click here to find out more.

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.

:rocket: New features to boost your workflow:
  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

codecov[bot] avatar May 04 '26 13:05 codecov[bot]

@senojj can you have a look at the code now

Popie52 avatar May 07 '26 13:05 Popie52

@Popie52 I'm not quite sure I follow the intent of the additional locking within fetchBuffer. Could you add more to your PR description regarding how you think your solution is solving the state problem.

Additionally, these "tuple iterators" are not necessarily multiple-consumer data structures. They are primarily used within SPSC scenarios. Is there a specific bug that you are addressing?

senojj avatar May 07 '26 14:05 senojj

@senojj

Addition of additional locking and state problem: Problem: concurrent calls (Next()/ Head()) can left to half initialized state Solution: inFlight lock for atomic initialization

SPSC scenario: for this the logic is that if single consumer tries for very fast Next() or Head() calls or concurrent routines so lead to race conditions

Solution: defensive design

Specific bugs: no, proactively addressing potential race conditions during lazy initialization to ensure stable iterator under any call pattern

Popie52 avatar May 07 '26 15:05 Popie52

Addition of additional locking and state problem: Problem: concurrent calls (Next()/ Head()) can left to half initialized state Solution: inFlight lock for atomic initialization

@Popie52 fetchBuffer is currently only called from behind a mutually exclusive lock in next and head. How is your proposed change strengthening the synchronization? Could you explain the order of events that lead to a race condition, and how your changes address it?

senojj avatar May 07 '26 16:05 senojj

This PR has had no human activity for 90 days, so it has been marked lifecycle/stale.

This is automated backlog grooming, not a judgment on the work.

What happens next, unless there is activity:

  • In 30 days, it will move to lifecycle/closing-soon
  • 30 days after that, it will be closed

To keep it open, push a commit or leave a comment, and the clock will reset. For work that should not auto-close, such as an RFC or long-running experiment, ask a maintainer to add lifecycle/frozen.

curfew-marathon avatar Aug 08 '26 01:08 curfew-marathon

This PR has had no human activity for 30 days since being marked lifecycle/stale, so it has now been marked lifecycle/closing-soon.

It will be closed in 30 days unless there is new activity.

If the work still matters, this is the moment to say so: leave a comment, push a commit, or ask a maintainer to add lifecycle/frozen if it should be kept open long-term.

If this work is no longer being pursued, no action is needed.

curfew-marathon avatar Sep 12 '26 15:09 curfew-marathon