Skip to content

[CRUI-124] fix: prevent concurrent duplicate open shift creation - #142

Merged
huytran2005 merged 4 commits into
mainfrom
bugfix/CRUI-124-fix-open-shift-concurrency-8968755668811305211
Nov 3, 2026
Merged

huytran2005 merged 4 commits into
mainfrom
bugfix/CRUI-124-fix-open-shift-concurrency-8968755668811305211

Conversation

@huytran2005

Copy link
Copy Markdown
Contributor

Problem statement and rationale

The CI build failed randomly in the PosConcurrencyIntegrationTest.testConcurrentChargesNeverExceedCreditLimit test case.
The test runs 10 threads, each executing a POS transaction. Inside PosTransactionService.processChargeTransaction (which is @Transactional), it delegates to PosShiftService.openShift to ensure a shift is open for the station. openShift utilized a ConcurrentHashMap with a synchronized block to ensure exactly one thread creates an open shift per station.
However, the synchronized block would complete and release its lock before the outer Spring @Transactional proxy could commit the new shift into the DB. This allowed a second thread to enter the lock, fail to find an open shift in the DB, and insert a duplicate. Subsequent reads threw IncorrectResultSizeDataAccessException (Query did not return a unique result).

Summary of code and test changes

  • Replaced the simple synchronized block with a ReentrantLock stored in the map.
  • Used TransactionSynchronizationManager.registerSynchronization inside PosShiftService.openShift() so that the thread creating the shift retains the lock until the underlying transaction commits or rolls back (afterCompletion).
  • This resolves the race condition while safely preventing deadlocks related to Propagation.REQUIRES_NEW within limited HikariCP connection pools.
  • Note: Removed scratchpad files created during exploration (test_lock.java, test_lock.class).

Verification commands executed and test results

Executed targeted integration test locally:

$ ./mvnw test -pl cruise-pos-service -Dtest=PosConcurrencyIntegrationTest
...
[INFO] Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 17.35 s -- in POS Concurrency & Credit Limit Enforcement Integration Tests
[INFO] BUILD SUCCESS

Executed full test suite:

$ ./mvnw -B verify --file pom.xml
...
[INFO] Tests run: 548, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS

Residual limitations or human review recommendations

The change depends on Spring's TransactionSynchronizationManager, which guarantees that callbacks run on the thread bounding the transaction. ReentrantLock expects unlocks on the locking thread, making this pairing perfectly safe for Spring declarative transactions. Ensure any future changes handling stationLocks correctly account for deferred unlocks if isSynchronizationActive() evaluates to false.

Fixes Run ID: 41425244669
Fixes commit: a3f203860609aa2639474f6a3551e8cdc0fa1f4d


PR created automatically by Jules for task 8968755668811305211 started by @huytran2005

- Modified `PosShiftService.openShift()` to use `ReentrantLock` instead of a plain Java object lock.
- Replaced the `synchronized` block with `ReentrantLock`.
- Used `TransactionSynchronizationManager.registerSynchronization()` to correctly defer `lock.unlock()` until `afterCompletion` (transaction commit/rollback).
- This prevents the race condition where `synchronized` block is released before the Spring proxy commits the newly created `PosShift`, resolving the `IncorrectResultSizeDataAccessException` observed in concurrent setups.
- Avoided using `Propagation.REQUIRES_NEW` to prevent HikariCP connection pool exhaustion when multiple active outer transactions are waiting.

Co-authored-by: huytran2005 <[email protected]>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai

coderabbitai Bot commented Nov 2, 2026 •

Copy link
Copy Markdown
Contributor

Important

Draft PR not reviewed

Draft PRs are not automatically reviewed by default.

  • Trigger a manual review

To automatically review draft PRs, update your CodeRabbit configuration:

reviews:
  auto_review:
    drafts: true
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Tip

🎯 Customize your risk assessments

Guide how CodeRabbit assesses merge risk and security architecture risk. Highlight sensitive changes and explain your security boundaries using Merge Risk Instructions and Security Risk Instructions in your review settings. Security architecture risk assessments require the Advanced plan or above.

✅ Automatic approvals, with your rules

Let CodeRabbit approve pull requests once required threads are resolved, pre-merge checks pass, and your risk limits are met. Enable Automatic approvals in review settings, with overrides for teams or file paths.

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

CodeRabbit Verify

  • Run CodeRabbit Verify to test the changes in this pull request.

google-labs-jules Bot and others added 3 commits November 2, 2026 10:43
- Modified `PosShiftService.openShift()` to use `ReentrantLock` instead of a plain Java object lock.
- Replaced the `synchronized` block with `ReentrantLock`.
- Used `TransactionSynchronizationManager.registerSynchronization()` to correctly defer `lock.unlock()` until `afterCompletion` (transaction commit/rollback).
- Addressed SonarQube rule java:S2222 (Locks should be released in a "finally" block) by ensuring that variable initializations are completely outside of the lock/try-catch structure according to best practices.
- Avoided using `Propagation.REQUIRES_NEW` to prevent HikariCP connection pool exhaustion when multiple active outer transactions are waiting.

Co-authored-by: huytran2005 <[email protected]>
- Modified `PosShiftService.openShift()` to use `ReentrantLock` instead of a plain Java object lock.
- Replaced the `synchronized` block with `ReentrantLock`.
- Used `TransactionSynchronizationManager.registerSynchronization()` to correctly defer `lock.unlock()` until `afterCompletion` (transaction commit/rollback).
- Addressed SonarQube rule java:S2222 (Locks should be released in a "finally" block) by ensuring that variable initializations are completely outside of the lock/try-catch structure according to best practices and adding a method-level warning suppression because standard unconditional `finally { lock.unlock(); }` is semantically incorrect here (as the unlock is deferred to the transaction manager).
- Avoided using `Propagation.REQUIRES_NEW` to prevent HikariCP connection pool exhaustion when multiple active outer transactions are waiting.

Co-authored-by: huytran2005 <[email protected]>
@huytran2005
huytran2005 marked this pull request as ready for review November 3, 2026 04:09
@sonarqubecloud

sonarqubecloud Bot commented Nov 3, 2026

Copy link
Copy Markdown

@huytran2005
huytran2005 merged commit a8cdc62 into main Nov 3, 2026
5 checks 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.

1 participant