Skip to content

test(ledger): add reservation void-in-mutex and concurrency test suites (ENG-36)#104

Merged
Connorbelez merged 2 commits intomainfrom
Connorbelez/eng36-reservation-tests
Mar 17, 2026
Merged

test(ledger): add reservation void-in-mutex and concurrency test suites (ENG-36)#104
Connorbelez merged 2 commits intomainfrom
Connorbelez/eng36-reservation-tests

Conversation

@Connorbelez
Copy link
Copy Markdown
Owner

@Connorbelez Connorbelez commented Mar 17, 2026

Extends reservation testing and adds comprehensive concurrency test suite

Extends reservation.test.ts with a void-in-mutex scenario that verifies voiding one reservation correctly restores available balance for subsequent reservations. Creates concurrency.test.ts covering sequential transfer contention, double-mint prevention, gap-free sequence numbering, and supply invariant preservation across interleaved operations including mixed reservation lifecycle + direct transfers.

Summary by CodeRabbit

  • Tests
    • Added comprehensive concurrency tests validating correct ledger behavior across concurrent transfers, idempotency, and sequence integrity.
    • Added reservation lifecycle tests ensuring proper balance restoration when reservations are voided.

…es (ENG-36)

Extends reservation.test.ts with a void-in-mutex scenario that verifies
voiding one reservation correctly restores available balance for subsequent
reservations. Creates concurrency.test.ts covering sequential transfer
contention, double-mint prevention, gap-free sequence numbering, and
supply invariant preservation across interleaved operations including
mixed reservation lifecycle + direct transfers.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@linear
Copy link
Copy Markdown

linear bot commented Mar 17, 2026

Copy link
Copy Markdown

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Sorry @Connorbelez, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai bot commented Mar 17, 2026

Warning

Rate limit exceeded

@Connorbelez has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 0 minutes and 49 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: c15494d1-8bb7-495a-bb1f-2e3e066aecc7

📥 Commits

Reviewing files that changed from the base of the PR and between b50e542 and f0f78a0.

📒 Files selected for processing (3)
  • convex/ledger/__tests__/concurrency.test.ts
  • convex/ledger/__tests__/reservation.test.ts
  • convex/ledger/__tests__/testUtils.ts
📝 Walkthrough

Walkthrough

Two test suites added to validate concurrency and reservation scenarios in the Mortgage Ownership Ledger. The concurrency tests verify serialization, idempotency, supply invariants, and sequence number integrity under interleaved operations. The reservation test validates balance restoration when pending reservations are voided.

Changes

Cohort / File(s) Summary
Concurrency Test Suite
convex/ledger/__tests__/concurrency.test.ts
Introduces comprehensive test harness and helpers (createTestHarness, asLedgerUser, getConvexErrorCode, typed mutation wrappers). Implements four test groups: T-080 (concurrent transfers with balance validation), T-081 (double-mint OCC serialization), T-082 (sequence number integrity), and T-083/T-083b (supply invariant under interleaved operations). Covers 571 new lines of test logic.
Reservation Test Enhancement
convex/ledger/__tests__/reservation.test.ts
Adds test case validating balance restoration when a pending reservation is voided. Tests sequence: mint → reserve → reserve → void first → reserve again. Verifies pendingCredits and available balance transitions. Note: test appears duplicated within the same describe block (77 new lines total).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 Locks and shares, concurrently bound,
Two tests now dance without a sound,
Voids restore what once was lost,
While sequences stay unglitched, at cost!
Invariants hold through tangled webs—
The ledger dreams, the rabbit treads. 🎪

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main changes: adding reservation void-in-mutex and concurrency test suites to the ledger tests.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch Connorbelez/eng36-reservation-tests
📝 Coding Plan
  • Generate coding plan for human review comments

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.

Copy link
Copy Markdown
Owner Author

This stack of pull requests is managed by Graphite. Learn more about stacking.

@Connorbelez Connorbelez marked this pull request as ready for review March 17, 2026 09:57
Copilot AI review requested due to automatic review settings March 17, 2026 09:57
@greptile-apps
Copy link
Copy Markdown

greptile-apps bot commented Mar 17, 2026

Greptile Summary

This PR extends the ledger test suite with a void-in-mutex scenario in reservation.test.ts and a brand-new concurrency.test.ts file covering four acceptance-criteria test groups (T-080 through T-083). The new tests verify sequential transfer contention, double-mint prevention, gap-free sequence numbering, and supply-invariant preservation across interleaved operations — all within convex-test's serialized execution model (true OCC conflicts are explicitly acknowledged as untestable in this harness).

Key findings:

  • The new reservation.test.ts test is logically correct — balance arithmetic, pendingCredits assertions, and the void → re-reserve flow all check out against the production voidReservation and reserveShares mutation implementations.
  • concurrency.test.ts duplicates getConvexErrorCode from reservation.test.ts but omits the regex string-fallback branch; this makes error-code extraction silently fragile if a ConvexError surfaces its code inside a plain string rather than a structured JSON field.
  • A comment in T-082 says "Redeem A 1,000" but the redeemShares call passes amount: 2_000, making the entry-count audit trail harder to follow.
  • All type definitions (ReserveSharesArgs, CommitReservationArgs, etc.) and helper functions are copied verbatim from reservation.test.ts; a shared test-utilities module would prevent future drift (the getConvexErrorCode divergence being an early symptom).

Confidence Score: 4/5

  • Safe to merge — changes are test-only with no production code impact; the main issue is a fragile getConvexErrorCode implementation that could produce confusing failures but not incorrect behaviour.
  • All changes are isolated to test files. The new reservation void-in-mutex test is logically sound. The concurrency tests are well-structured and the balance math is correct. The score is not 5 because: (1) the divergent getConvexErrorCode in concurrency.test.ts lacks the regex fallback present in reservation.test.ts, which could produce misleading test-failure messages under certain error-serialization scenarios; and (2) the copy-pasted boilerplate creates a maintainability liability that has already produced a drift.
  • Pay close attention to convex/ledger/__tests__/concurrency.test.ts — specifically the getConvexErrorCode helper (lines 89–116) and the misleading redeem comment (line 356).

Important Files Changed

Filename Overview
convex/ledger/tests/concurrency.test.ts New test file covering T-080 through T-083; contains a divergent (less robust) getConvexErrorCode that's missing the regex string fallback from reservation.test.ts, a misleading "1,000" comment where amount: 2_000 is used, and significant boilerplate duplication.
convex/ledger/tests/reservation.test.ts Adds one new test case ("void-in-mutex") that correctly exercises the void → re-reserve flow; logic, balance math, and assertions are all correct and consistent with the existing test patterns.

Sequence Diagram

sequenceDiagram
    participant Test
    participant Convex as convex-test harness
    participant Ledger as Ledger Mutations
    participant DB as Convex DB

    Note over Test,DB: T-083b: Reservation lifecycle mixed with direct transfer
    Test->>Convex: mintMortgage(m-inv-mixed)
    Convex->>Ledger: mintMortgage
    Ledger->>DB: INSERT TREASURY, POST MORTGAGE_MINTED

    Test->>Convex: issueShares(A=6000, B=4000)
    Convex->>Ledger: issueShares x2
    Ledger->>DB: POST SHARES_ISSUED x2

    Test->>Convex: t.run → reserveShares(A→C, 3000)
    Convex->>Ledger: reserveShares._handler
    Ledger->>DB: POST SHARES_RESERVED, PATCH A.pendingCredits+=3000

    Test->>Convex: transferShares(B→A, 1000)
    Convex->>Ledger: transferShares
    Ledger->>DB: POST SHARES_TRANSFERRED

    Test->>Convex: t.run → commitReservation(reservationId)
    Convex->>Ledger: commitReservation._handler
    Ledger->>DB: PATCH A.pendingCredits-=3000, POST SHARES_COMMITTED

    Test->>Convex: validateSupplyInvariant(m-inv-mixed)
    Convex-->>Test: {valid:true, total:10000n, treasuryBalance:0n}

    Note over Test,DB: Expected: A=4000, B=3000, C=3000, Treasury=0
Loading

Last reviewed commit: b50e542

Comment thread convex/ledger/__tests__/concurrency.test.ts Outdated
Comment thread convex/ledger/__tests__/concurrency.test.ts
Comment thread convex/ledger/__tests__/concurrency.test.ts Outdated
Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Adds additional ledger reservation lifecycle coverage and introduces a new concurrency-oriented test suite to validate serialization/idempotency behavior and invariants in the Mortgage Ownership Ledger.

Changes:

  • Extend reservation.test.ts with a “void within mutex” scenario to ensure voiding a reservation releases available balance for subsequent reservations.
  • Add concurrency.test.ts to cover sequential transfer contention, double-mint prevention, gap-free sequence numbering, and supply invariant checks across interleaved operations.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
convex/ledger/__tests__/reservation.test.ts Adds a void-reservation test to confirm pending locks are released and available balance is restored.
convex/ledger/__tests__/concurrency.test.ts New suite validating sequentialized “would-be concurrent” behaviors, idempotency/serialization guards, sequence integrity, and supply invariants.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread convex/ledger/__tests__/concurrency.test.ts Outdated
Comment thread convex/ledger/__tests__/concurrency.test.ts Outdated
Copy link
Copy Markdown
Contributor

@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: 1

🧹 Nitpick comments (1)
convex/ledger/__tests__/concurrency.test.ts (1)

92-203: Consider extracting shared test utilities to reduce duplication.

The getConvexErrorCode function and typed wrappers (ReserveSharesMutation, CommitReservationMutation, etc.) are duplicated between this file and reservation.test.ts. Additionally, the implementations differ slightly — reservation.test.ts includes a regex fallback for error code extraction that this version lacks.

Extracting these to a shared module (e.g., __tests__/helpers.ts) would reduce maintenance burden and ensure consistent behavior.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@convex/ledger/__tests__/concurrency.test.ts` around lines 92 - 203, Extract
the duplicated test utilities into a shared test helper module (e.g.,
__tests__/helpers.ts): move getConvexErrorCode (include the regex fallback
present in reservation.test.ts), the typed types
ReserveSharesArgs/ReserveSharesResult/ReserveSharesMutation and
CommitReservationArgs/CommitReservationResult/CommitReservationMutation, the
casts reserveSharesMutation and commitReservationMutation, and the executor
helpers executeReserveShares and executeCommitReservation into that module; then
import and use those symbols in both concurrency.test.ts and reservation.test.ts
to replace the local duplicates so both tests share the exact same
implementation and behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@convex/ledger/__tests__/concurrency.test.ts`:
- Around line 412-420: The inline comment above the redeemShares call in the
concurrency.test (the auth.mutation(api.ledger.mutations.redeemShares, {...})
invocation) incorrectly states "Redeem A 1,000" while the payload sets amount:
2_000; update that comment to reflect the actual amount (2,000) so the comment
matches the call and avoids confusion.

---

Nitpick comments:
In `@convex/ledger/__tests__/concurrency.test.ts`:
- Around line 92-203: Extract the duplicated test utilities into a shared test
helper module (e.g., __tests__/helpers.ts): move getConvexErrorCode (include the
regex fallback present in reservation.test.ts), the typed types
ReserveSharesArgs/ReserveSharesResult/ReserveSharesMutation and
CommitReservationArgs/CommitReservationResult/CommitReservationMutation, the
casts reserveSharesMutation and commitReservationMutation, and the executor
helpers executeReserveShares and executeCommitReservation into that module; then
import and use those symbols in both concurrency.test.ts and reservation.test.ts
to replace the local duplicates so both tests share the exact same
implementation and behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 0a26517a-40cc-4cc3-a63e-172d936b913b

📥 Commits

Reviewing files that changed from the base of the PR and between 89255c3 and b50e542.

📒 Files selected for processing (2)
  • convex/ledger/__tests__/concurrency.test.ts
  • convex/ledger/__tests__/reservation.test.ts

Comment thread convex/ledger/__tests__/concurrency.test.ts Outdated
…review feedback

- Create testUtils.ts with shared helpers, typed mutation wrappers, and
  getConvexErrorCode (now includes regex string fallback for all error codes)
- Update reservation.test.ts and concurrency.test.ts to import from testUtils
- Fix misleading "Redeem A 1,000" comments (actual amount is 2,000)
- Fix mintAndIssueMultiple JSDoc to reflect that validation is in mutations

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@Connorbelez Connorbelez merged commit 0839279 into main Mar 17, 2026
1 of 3 checks passed
Connorbelez added a commit that referenced this pull request Apr 20, 2026
…es (ENG-36) (#104)

## Extends reservation testing and adds comprehensive concurrency test suite

Extends reservation.test.ts with a void-in-mutex scenario that verifies voiding one reservation correctly restores available balance for subsequent reservations. Creates concurrency.test.ts covering sequential transfer contention, double-mint prevention, gap-free sequence numbering, and supply invariant preservation across interleaved operations including mixed reservation lifecycle + direct transfers.



<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **Tests**
  * Added comprehensive concurrency tests validating correct ledger behavior across concurrent transfers, idempotency, and sequence integrity.
  * Added reservation lifecycle tests ensuring proper balance restoration when reservations are voided.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
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