Skip to content

fix(persistence): finish connection cleanup before a cancellation propagates - #1782

Merged
hidb4ai merged 9 commits into
oceanbase:masterfrom
guamiao:fix/cancelled-transaction-cleanup
Oct 12, 2026
Merged

hidb4ai merged 9 commits into
oceanbase:masterfrom
guamiao:fix/cancelled-transaction-cleanup

Conversation

@guamiao

@guamiao guamiao commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes #1780

Summary

Ensure that cancelling a SQLite transaction does not strand its connection or pool slot, and preserve transaction atomicity when SQLite interrupts an in-flight write.

This also integrates upstream changes without dropping the cancellation, storage-failure or recovery regression coverage.

Changes

Cancellation-safe transaction cleanup

  • Track SQLite cursors per connection and finalize them before retiring a cancelled transaction.
  • Make aiosqlite 0.22.1's stop() idempotent per connection, with independently shielded waiters. The shared driver class is not patched.
  • Keep failed-transaction cleanup in an owned task until rollback, connection close and transaction bookkeeping finish, including under repeated cancellation.
  • Let nested transactions retain their caller's connection ownership; keep normal exits in the caller's task to preserve shutdown ordering.

Atomicity and connection reuse

  • Reject a commit after an interrupted write instead of allowing later writes to commit after earlier writes were rolled back by SQLite.
  • Retain the original connection-info dictionary so an invalidated connection still reaches cleanup and preserves the original cancellation.
  • Clear interruption state at transaction boundaries, including cancellation during COMMIT, so it cannot affect the next borrower.

Regression tests and upstream integration

  • Integrate upstream f28f8edf, including completion-flush synchronization (fix(dsh): preserve unrelated user patches during setup #1799), the usage observation-window correction (fix(e2e): give the usage-record observation window the recorder's budget #1846) and bounded attempt retries (Fix/model usage attempt expiry #1838).
  • Wait for both the stalled recorder and the request's completion flush before cancelling the E2E request. Keep the five-second cancellation bound, both normal/storage-failure cases, settlement checks, persisted business content and the next request's usage increment.
  • Keep separate persistence tests for cancellation during actual SQL, rollback and connection close.
  • Apply the commit-lock regression's 40ms budget only to the deliberately blocked write. Verify that record has settled before testing recovery with the same recorder's normal budget. The original <0.5s assertion and connection-restoration checks remain; production timeout and retry rules are unchanged.

Verification

Validated commit: 1140bd71d79ffe6de8cdf4d91f35e9f23ea4bdff.

The committed source tree is identical to the locally validated tree. All 2044 tracked files matched before and after the final Linux runs.

Validation Result
Linux / Python 3.14.4, full unit suite 3486 passed, 126 skipped, no failures or errors
Linux / Python 3.14.4, full E2E suite 379 passed, 69 skipped, 4 default-deselected, no failures
Cancellation E2E, 20 independent processes normal 20/20, storage-failure 20/20
Linux / Python 3.12.3, related four-file suite 70 passed
Targeted and full lint, formatting and type checks All 7 checks passed
Windows / Python 3.13.12, updated recorder test file 27 passed

Additional controls:

  • Removing cursor cleanup alone makes the real-SQL cancellation regression fail during rollback with OperationalError: interrupted.
  • Removing the completion-flush wait makes the scheduling probe observe premature cancellation in both parameter cases.
  • A controlled 30ms delay in the recovery write reproduces the old 40ms-budget failure on both this branch and upstream. Giving only the recovery phase its normal budget succeeds with the same recorder and physical connection; the revised test also passes this control on Linux.

Earlier failed runs were retained. Missing Git/jq/build metadata and loopback proxy interference were corrected only in the isolated verification environment, followed by successful full-suite runs. No failing tests were removed, and no global proxy settings were changed.

Validation limits

  • Local Python is 3.14.4, not the earlier CI job's 3.14.7, which was unavailable locally. The local dependency-install launcher is uv 0.11.11, versus 0.10.12 in the CI action.
  • Real-backend, external-host, platform-specific and explicitly opt-in tests retain their existing skips. The four deselected cases are default ZCode host-acceptance cases.
  • Six LangGraph deprecation warnings remain in the unit suite.
  • These are local validation results; the new GitHub CI run must still be evaluated for this commit.

…pagates

Repeatedly cancelling a transaction could keep its pool slot checked out.
Two driver-level gaps combine. SQLAlchemy can drive both a graceful close
and a stop on the same aiosqlite connection, whose stop is not idempotent
and enqueues a second request behind a worker that already exited. And a
statement cancelled mid-await leaves its native cursor held by the exception
stack, so the rollback that follows fails with "Connection closed" and the
slot is never returned.

Close the cursor tracked for the connection before retiring it, make the
driver stop idempotent per connection, interrupt the statement SQLite is
still running, and finish the whole exit inside a managed task so a repeated
cancellation cannot strand the cleanup. Only the transaction that owns the
connection runs it, so a nested exit cannot close its caller's cursors. A
clean exit stays in the caller's task, which the seekdb shutdown ordering
depends on.

Without the cursor step the new regression fails: the only pool slot is
still checked out after the tenth cancelled transaction.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
@guamiao

guamiao commented Sep 29, 2026

Copy link
Copy Markdown
Contributor Author

CI is green on the first attempt (23/23). Worth noting: re-running the same
suite with the cursor finalisation disabled makes
test_repeated_transaction_cancellation_does_not_exhaust_the_pool[sql] fail,
so the regression test has real discriminating power — this isn't a
re-run-masked pass like the one on #1734.

guamiao and others added 3 commits September 29, 2026 16:04
…mitting part of it

Interrupting a SQLite statement rolls the whole native transaction back, so
writes that already reported success are gone while SQLAlchemy still trusts the
transaction. Keeping `is_disconnect = False` avoided discarding the connection
-- an in-memory StaticPool holds its entire database in it -- but it also let a
caller that caught the error keep writing and commit a partial result: insert
row 3, interrupt a long UPDATE, insert row 4, and only row 4 survives.

Record the interruption on the connection and refuse to commit when the
transaction exits, raising PendingRollbackError the way the unmodified baseline
does. The connection still returns to the pool, so an in-memory database
survives.

* `test_interrupted_write_cannot_commit_earlier_work[file|memory]` fails
  without the guard.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ransaction

The mark lives on the pooled connection, and the usage recorder runs its own
transaction without going through `AsyncDatabase.transaction()`, so an
interrupt recorded there was never consumed. It survived on the connection
until an unrelated transaction picked that connection up and raised
PendingRollbackError for a rollback it had nothing to do with -- which is how
this first showed up, as a topic-memory supervisor test failing on 3.11.

Clear any leftover mark when a transaction starts, so only an interrupt raised
inside it can fail it.

* `test_interrupt_marked_outside_the_transaction_does_not_fail_it` fails
  without the cleanup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
…ection

Two follow-ups from review.

`connection.info` re-resolves the DBAPI connection, so once a cancelled
statement invalidated it through SQLAlchemy's normal path, reading the
interruption mark from the failure path raised PendingRollbackError and skipped
the rest of `_finish_transaction()`. That left the transaction counted as active
and kept `database.close()` from finishing. Hold the info dict itself instead;
it stays usable after the connection is gone.

The mark was also only checked before COMMIT ran. A commit cancelled while in
flight records the mark afterwards, so it survived on the pooled connection and
failed the next borrower's transaction. Clear it in a `finally` around the exit,
which covers cancellation during COMMIT or ROLLBACK too.

* `test_invalidated_connection_still_reaches_transaction_cleanup` fails without
  the first part.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
The earlier fixes addressed review, but two of its requirements were only
verified indirectly.

Preserving the original cancellation: the invalidation test asserted that
cleanup ran, not that the caller still sees CancelledError. Cover that
directly.

Clearing the mark on a commit that is cancelled: the stale-mark test planted
the mark before the transaction started. Plant it from the commit event
instead, which is where an error handler records it when the commit itself is
interrupted -- after the transaction's own check. That fails without the
cleanup.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@guamiao
guamiao force-pushed the fix/cancelled-transaction-cleanup branch from aee8478 to 8998b91 Compare September 29, 2026 14:13
guamiao and others added 4 commits September 29, 2026 22:46
… receives

`plant_mark` was annotated `object` and then read `.info` off it, which `ty`
rejects: `Object of type object has no attribute info`. Name the SQLAlchemy
connection type the commit event actually passes.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Preserve the transaction cleanup and atomicity fixes while integrating upstream
usage handling. Synchronize request cancellation at the completion flush and
retain the storage-failure and recovery checks.

Limit the commit-lock regression's short write budget to the deliberately
blocked write. Verify recovery with the same recorder's normal budget without
changing production timeout or retry behavior.

Validated source tree: 1e24ec7
Linux Python 3.14.4: 3486 unit tests and 379 E2E tests passed.
Python 3.12.3: 70 related tests passed; all static checks passed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Integrate the family-scoped search work (oceanbase#1862), which adds an optional
consistent_snapshot to AsyncDatabase.transaction. The snapshot setup moves
into the split-out _transaction so the cancellation cleanup in transaction()
still owns the connection lifecycle unchanged.

Resolve the database.py conflict by keeping both: nested lookups gain the
upstream snapshot branch, while the outer transaction retains cursor
retirement, interruption-atomicity and commit-boundary cleanup.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Bring in the database-migration prototype (oceanbase#1771/oceanbase#1772), loopback proxy
bypass (oceanbase#1888), topic-memory window fixes (oceanbase#1842/oceanbase#1898) and related work.

Resolve three conflicts:
- database.py: keep the split transaction/_transaction so cancellation
  cleanup still owns the connection; adopt the upstream nested-snapshot
  comment.
- test_sqlite_profile.py: keep this branch's SyncConnection/event imports
  and its invalidation + commit-mark regression tests.
- test_topic_memory_generic_api.py: adopt upstream's reworked cancellation
  e2e (completion-flush rendezvous with busy_timeout_ms=100), which retains
  the cancellation, normal/storage-failure, settlement and recovery-usage
  assertions through the public flush boundary.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@guamiao

guamiao commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor Author

resolve conflicts

The windows job failure is unrelated to this PR's persistence changes. The log shows the real failure is a frontend test in desktop/ui/tests/memory.test.tsx — late save after a page switch preserves the new draft's navigation guard fails with TypeError: finish is not a function at line 370. That aborts pnpm before tauri build runs, so no NSIS bundle is produced and upload-artifact then reports the missing *-setup.exe.

finish is only assigned inside the async mockImplementationOnce callback (line 339), and the act() block at line 369–371 can call it before that assignment runs — so this looks like a timing flake in the test from #1663 (the same job is green on master).

A likely fix direction is to wait until finish is actually assigned before resolving it — e.g. poll with vi.waitFor(() => { if (typeof finish !== "function") throw new Error("not assigned"); }) right before the act() call. I haven't verified this locally, so treat it as a lead rather than a tested patch.

Could a maintainer re-run the failed job? I don't have write access to trigger a re-run myself.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LGTM

@hidb4ai
hidb4ai merged commit 329b4be into oceanbase:master Oct 12, 2026
29 of 30 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.

Cancelling a SQLite transaction can keep its pool slot checked out

2 participants