Skip to content

Transactions across zones: postgres error zones, ZoneField, memory rollback (v1.36.0) - #213

Merged
gmpassos merged 4 commits into
masterfrom
fix/postgres-tx-statement-error-zone
Nov 24, 2026
Merged

gmpassos merged 4 commits into
masterfrom
fix/postgres-tx-statement-error-zone

Conversation

@gmpassos

@gmpassos gmpassos commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

What

A follow-up to #212 (still 1.36.0, not released yet). Stress-testing transactions across zones found three bugs, two of them older than #212.

  1. DBPostgreSQLAdapter: an error lost across error zones. APIRequest.payloadBytes: the request body exactly as received (v1.36.0) #212 runs a cached statement in the driver's runTx callback zone (the postgres 3.7 deadlock fix). When the caller is in another error zone (each API call has its own), Dart doesn't deliver that Future's error to it. A failing statement (stale 0A000, a constraint) then left the caller waiting forever. The outcome is now forwarded to a Completer of the caller's zone, as Transaction._runInZone already does.

  2. ZoneField: a zone forked inside a transaction didn't see it (pre-existing). contextZone only matched the context zone itself. Code in a runZoned / runZonedGuarded inside a transaction had two problems:

    • its repository operations ran outside the transaction, each committed on its own and kept when the transaction aborted;
    • its executeBlock opened a new transaction instead of joining the running one.

    contextZone now walks the zone's ancestors (an identity Set), as zoneValues are inherited.

  3. Memory adapters: an aborted transaction reverted concurrent commits (pre-existing). This affected both DBSQLMemoryAdapter and DBObjectMemoryAdapter. A rollback restored the tables to their versions from when the transaction began, which also reverted what concurrent transactions committed meanwhile. With 12 concurrent transactions, half aborted, 1 of 18 committed writes survived.

    • Each context now records the MapHistory versions its writes create, along with their IDs. A rollback reverts only those, with MapHistory.revertVersions from map_history 1.0.8 (revertVersions: revert only some operations; consolidate/rollback fixes (v1.0.8) gmpassos/map_history#2).
    • A later write by another transaction to the same entry is kept, whichever wrote first. A first attempt with an undo log restored the value from before the transaction's first write, which lost that later write (a lost update).
    • Every table write goes through _putTableEntry / _removeTableEntry. These record only versions a write actually created: a remove of an absent ID creates none, and reading version there would capture another transaction's write.

Review of #212 (as merged)

  • payloadAsBytes: a String JSON payload was encoded twice. APIRequest.post(payload: '{"a":1}', payloadMimeType: 'application/json') gave "{\"a\":1}". A String is now taken as the JSON text. Other values are encoded with the library's Json encoder (entities, DateTime, toJson), not dart:convert's, which fell back to toString (not JSON).
  • A chunked body with no Content-Type was not read (pre-existing). There was no payload nor payloadBytes, so a webhook signature couldn't be verified. It is now read as text/plain.
  • A compressed body that isn't decompressed was decoded as text (pre-existing). That gave garbage text, and for JSON a decoding error logged at SEVERE with no payload. It is now passed as bytes (application/octet-stream).
  • The invalid-JSON log gives the body length before trimming and doesn't cut a surrogate pair.
  • Docs:
    • payloadAsBytes makes a copy on each call;
    • a binary payload shares its buffer with payloadBytes;
    • _resolvePayloadBytes and _runStatement say who uses them.

Review of this PR

  • Memory adapters consolidated a transaction before its commit was final. Both the SQL and the object adapter consolidated in the transaction's closer, and the commit can still fail after it: for example, an operation added late fails with "Not all operations finished".
    • The cancel that followed then did nothing on the SQL side, because the writes had already been forgotten, so they stayed in the table.
    • On the object side, revertVersions could throw for versions already consolidated.
    • Consolidation now happens only once the commit is final, in resolveTransactionResult, and the closer does nothing. An open transaction's versions are therefore never consolidated.
  • Fire-and-forget work now joins the transaction. This follows from item 2. It covers things like an audit log written in a runZonedGuarded inside a transaction: such work is reverted on abort, and it can fail the commit if it's added late.
    • New Transaction.runDetached (on top of ZoneField.runDetached) runs it apart, in its own transaction, as before.
    • The CHANGELOG warns about this change.
  • An aborted insert's ID could be reused. This was introduced by the revert in this PR, which reset the next-ID counter. The counter now behaves like a database sequence.
  • The consolidation queue was never emptied (pre-existing). This was in both memory adapters, and the queue grew for the life of the process.
  • Content-Encoding was case-sensitive when decompressing (pre-existing): GZIP threw "Unknown Content-Encoding".
  • An empty chunked body is again no body (null).
  • The payloadAsBytes docs now say a binary payload is not a copy: it's the same buffer as payloadBytes.

Each fix has a test:

  • a cancel after the closer reverts the writes, in both memory adapters;
  • an aborted insert's ID is not reused;
  • Transaction.runDetached works on every adapter;
  • ZoneField.runDetached;
  • Content-Encoding in any case, and an empty chunked body.

Putting back the old closer consolidation, or the counter reset, makes these tests fail.

Behavior changes

  • A compressed body with decompressPayload off: bytes, not text (above).
  • Code in a zone forked inside a transaction now joins it (item 2).
  • A Transaction().execute started there is refused ("Already executing a Transaction"), as it already was in the transaction's own zone, instead of running a separate transaction.
  • API call zones are forked from the field's root zone, not from the current one, so they stay separate as before.

Tests

runAdapterTests runs these for every adapter (memory, directory, SQLite, MySQL, PostgreSQL):

  • Transactions across zones:
    • operations from other error zones, run sequentially, concurrently and in nested zones;
    • an error from another zone aborts the transaction;
    • nested blocks from other zones join it, and roll back together on abort;
    • a sub-transaction of another executor (the object adapter) run from another zone.
  • Stress:
    • 12 concurrent transactions, half aborted;
    • 6 levels of nested blocks across alternating zones, committed and aborted at the deepest;
    • 20 interleaved concurrent operations with repeated reads and updates;
    • a failing branch among concurrent operations;
    • concurrent sub-transactions, committed and aborted;
    • a new transaction inside another one's zone is refused;
    • memory adapters only: two transactions write the same entity (SQL) or object (object adapter), one of them aborts, and the committed value survives. This runs in both write orders, with both aborting, and over 4 rounds of 6 concurrent pairs. A real database locks the row, so this interleaving can't happen there.
      • To check that these tests catch the bug, I temporarily put back the old semantics: the undo log for the SQL adapter, the rollback for the object adapter. Both tests failed, with the committed 2 back to 0.
  • PostgreSQL: a cached statement in a transaction called from another error zone, for both its result and its stale 0A000 error. It hangs without the fix.
  • ZoneField: forked zones at any depth, the nearest context zone, async continuations, and disposal.

The test helper now uses executeOrError and rethrows. execute returns null when aborted, which would also hide a failed expect inside the block.

Local results:

Suite Result
PostgreSQL 240 ✓
MySQL 225 ✓
memory 376 ✓
directory 188 ✓
SQLite 315 ✓
unit (-x docker -x concurrency) 2774 ✓
concurrency 86 ✓
ensure_build ✓

🤖 Generated with Claude Code

…llback (v1.36.0)

- DBPostgreSQLAdapter: a cached statement run in the runTx callback's zone
  forwards its outcome to the caller's zone when they are different error
  zones (Dart doesn't deliver a Future's error across error zones: a failing
  statement left the caller waiting forever).
- ZoneField.contextZone: a zone forked from a context zone, at any depth,
  is inside it. Code in a zone forked inside a transaction now sees it: its
  operations join the transaction instead of committing apart, and
  executeBlock joins it instead of opening a new one.
- DBSQLMemoryAdapter: a rolled back transaction reverts only its own writes
  (an undo log per context), not the tables to their versions when it
  began, which also reverted concurrent transactions' commits.
- Tests for every adapter: transactions across zones and error zones,
  nested blocks, sub-transactions, and stress cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 99.23664% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 95.97%. Comparing base (eb8b709) to head (5e1171b).

Files with missing lines Patch % Lines
lib/src/bones_api_entity_db_object_memory.dart 96.96% 1 Missing ⚠️
Additional details and impacted files
@@           Coverage Diff           @@
##           master     #213   +/-   ##
=======================================
  Coverage   95.96%   95.97%           
=======================================
  Files          75       75           
  Lines       25964    26035   +71     
=======================================
+ Hits        24917    24987   +70     
- Misses       1047     1048    +1     
Flag Coverage Δ
unittests 95.97% <99.23%> (+<0.01%) ⬆️

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

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

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

gmpassos and others added 3 commits November 24, 2026 02:35
…ssed bodies, log preview

- payloadAsBytes: a String payload with a JSON MIME type is the JSON text
  (not encoded again, which quoted it); others encoded with the library's
  Json encoder (entities, DateTime, toJson). Documents the copy per call.
- APIServer: reads a chunked body with no Content-Type; passes a compressed
  body that isn't decompressed as bytes (octet-stream), not as garbage text;
  the JSON error log gives the body length before trimming and doesn't cut
  a surrogate pair.
- Docs: _resolvePayloadBytes (shared buffer), _runStatement (who calls it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ry.revertVersions (v1.36.0)

- DBSQLMemoryAdapter: each context records the MapHistory versions its
  writes create (and their IDs); a rollback reverts only those. Replaces
  the undo log, which restored an entry's value from before the
  transaction's first write and so lost a later write of another
  transaction to the same entry.
- DBObjectMemoryAdapter: the same for a canceled transaction, instead of
  rolling the tables back to their versions when it began (which reverted
  concurrent transactions' commits).
- Writes go through _putTableEntry / _removeTableEntry, which record only
  versions a write actually created.
- map_history: ^1.0.8.
- Tests: concurrent writes to the same entity/object with one transaction
  aborted, in both orders and many concurrent rounds.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…D sequence, fixes (v1.36.0)

- Memory adapters (SQL and object): a transaction is consolidated only once
  its commit is final (resolveTransactionResult), not in its closer, which
  runs before the commit can still fail: the cancel then found its writes
  forgotten (SQL) or already consolidated (object: revertVersions threw).
- Memory adapters: the consolidation queue is emptied after consolidating
  (it grew for the life of the process).
- DBSQLMemoryAdapter: a rollback no longer resets the next-ID counter (as a
  sequence): an aborted insert's ID isn't given again.
- New Transaction.runDetached / ZoneField.runDetached: work inside a
  transaction that must not join it (fire-and-forget, e.g. an audit log),
  now that forked zones join it. CHANGELOG warns about that change.
- APIServer: Content-Encoding in any case; an empty chunked body is no body.
- Docs: payloadAsBytes returns a binary payload as is (not a copy);
  _inAnotherErrorZone's users.
- Tests for each, and the commit test pins the context disposed on commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@gmpassos
gmpassos merged commit 6a30d36 into master Nov 24, 2026
11 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