Skip to content

Research: one transaction per mutation across an invocation's callbacks #310

Closed

Description

@allisonmahmood

Part of #294.

Question

How can a mutation be one transaction when its handler runs in a separate execution service and reaches the company database only through callbacks to the hosting server? Establish: holding a Postgres transaction open on a pooled connection for the invocation's duration under the bounded per-company pools and PgBouncer constraints recorded in ADR-0009 and the Azure pooling research on #178; the cost of a held connection per in-flight mutation and the deadline that bounds it; alternatives that avoid holding one (Convex's optimistic concurrency with read and write sets replayed at commit, Durable Objects' storage transactions, a mutation that ships its writes as one batch at the end, Windmill's approach); what each does to the handler's programming model (can a mutation read its own writes, can it branch on a read); what happens on the execution service's timeout, crash or a lost callback; and how the runtime log's before-execution row interacts with rollback. Include what PGlite can and cannot reproduce locally.

Output: findings as the resolution comment on this ticket, with a recommended v1 mechanism and the deadline and pool budget it needs. Two models in parallel per the map's Notes.

Activity

  1. added
    wayfinder:research
    on Sep 19, 2026
  2. allisonmahmood commented on Sep 19, 2026

    @allisonmahmood
    OwnerAuthor

    Report A: Claude Opus 5 (full findings)

    R5 — One transaction per mutation across an invocation's callbacks

    Research for #310 (part of the tier 2 map, #294). Model: Opus 5. Date: 2026-09-19. Primary sources only; every claim carries its URL. Facts that could not be established from a primary source are under Open questions, not asserted.

    Summary

    Detail

    1. Holding a transaction open for the invocation

    What is allowed. Nothing in Postgres forbids a long transaction. A transaction is session state; the only requirement is that every statement arrives on the same session, which node-postgres states plainly ("You must use the same client instance for all statements within a transaction … Do not use transactions with the pool.query method") and which our adapter honours by reserving a client for the transaction's scope. So the mechanism works: the hosting server opens BEGIN on the first company-database callback of an invocation, serves each later callback on that same reserved client, and issues COMMIT when the handler returns.

    What that pins. Three things, not one. (a) A Postgres backend, from BEGIN to COMMIT, including all execution-service think time and every HTTP round trip. (b) A slot in the company's pool: ADR-0009 sets pool maximum 4 with fail-fast busy admission, so four in-flight mutations exhaust one company. (c) A specific application replica, because the reserved client lives inside that process's RcMap lease. Callbacks for an invocation must therefore be routed back to the replica that opened the transaction — sticky routing keyed by the invocation, or a single-replica deployment. This is a consequence of the same-session rule above rather than a documented product feature, and it is the largest hidden cost of the design.

    What is not allowed, later. Under PgBouncer transaction pooling, a held transaction is legal but occupies a server connection for its whole duration, which is exactly the case Azure's pooling pitch excludes ("uses Postgres connections only when needed"). With default_pool_size 50 on Azure (https://learn.microsoft.com/en-us/azure/postgresql/connectivity/concepts-pgbouncer) and Azure's own sizing advice of "conservative values by multiplying the vCores within the range of 2 to 5" (https://learn.microsoft.com/en-us/azure/postgresql/configure-maintain/concepts-limits), a company pool of 4–10 backends on D2 is what we would actually run, and long mutations would push waiting clients toward the 120 s query_wait_timeout disconnect (https://www.pgbouncer.org/config.html). PgBouncer also offers idle_transaction_timeout, default disabled, which "If a client has been in 'idle in transaction' state longer, it will be disconnected" — the pooler-side twin of the Postgres GUC. ADR-0009 already defers PgBouncer because the pinned adapter cancels via pg_cancel_backend(client.processID), so none of this binds v1; it binds the day we adopt 6432. Session-level features remain unavailable there (SET/RESET, LISTEN, PREPARE, session advisory locks are "Never" in transaction pooling, https://www.pgbouncer.org/features.html).

    Idle-in-transaction cost. Postgres explains the MVCC reason a stale transaction hurts: a row version "must not be deleted while it is still potentially visible to other transactions" (https://www.postgresql.org/docs/18/routine-vacuuming.html), and the wraparound emergency procedure begins with "End long-running open transactions" (same page). The Serializable performance guidance says it directly: "Don't leave connections dangling 'idle in transaction' longer than necessary" and "Keep transactions short and focused" (https://www.postgresql.org/docs/18/transaction-iso.html). Two-phase commit is not an escape: PREPARE TRANSACTION "is not intended for use in applications or interactive sessions", keeps its locks, and left hanging "will interfere with the ability of VACUUM to reclaim storage" (https://www.postgresql.org/docs/18/sql-prepare-transaction.html).

    The bounding deadline. Today PATCHY_RUNTIME_MUTATION_DEADLINE_MS defaults to 30,000 and runtime_calls.deadline_ms defaults to 30000, but Runtime.ts applies Effect.timeoutOrElse only when integration is true; a mutation's deadlineMs is passed to record and logged, never enforced. A held-transaction tier 2 needs the deadline enforced in three places at once: the invocation (fail the handler), the transaction (SET LOCAL transaction_timeout or idle_in_transaction_session_timeout so the backend dies even if our timer does not fire), and the lease (release the pool slot). The database-side timeout is the one that survives our own bugs; Postgres notes that if transaction_timeout is shorter than or equal to the other two, "the longer timeout is ignored" (https://www.postgresql.org/docs/18/runtime-config-client.html).

    2. Alternatives that avoid holding one

    Convex-style OCC with read and write sets. Reads run against a snapshot at a begin timestamp; the read set records exactly which index ranges were scanned; writes accumulate in a write set; at commit the committer assigns a commit timestamp and aborts if any write in the interval overlaps the read set, after which "the function runner … retries automatically" (https://stack.convex.dev/how-convex-works). The claim is true serializability, not snapshot isolation (https://docs.convex.dev/database/advanced/occ). Programming model: reads are real, so branching on a read works; the handler is written "as if [it] will always succeed"; the cost is determinism — no fetch, no ambient nondeterminism, because replay must produce the same transaction, which is why Convex splits actions out. Implementing the read-set machinery over Postgres ourselves is a database-engine project. The cheap approximation is to let Postgres be the validator: buffer writes, then at the end open one short REPEATABLE READ or SERIALIZABLE transaction, re-execute the reads the handler depended on, apply the writes, and retry on SQLSTATE 40001, which the docs require applications to handle anyway ("Applications using this level must be prepared to retry transactions due to serialization failures", https://www.postgresql.org/docs/18/transaction-iso.html). That is still replay, and still forbids side effects before commit.

    Durable Objects storage transactions. Cloudflare's answer to the same question was to delete the question: explicit transactions are obsolete on the SQLite backend, writes with no intervening await coalesce and are "submitted atomically", the input gate stops other events interleaving during a storage operation, and the output gate holds outgoing messages until the write is confirmed, discarding them and restarting the object if it fails (https://developers.cloudflare.com/durable-objects/api/storage-api/, https://blog.cloudflare.com/durable-objects-easy-fast-correct-choose-three/). Programming model: reads see own writes, branching is free, no retries are visible to the author — but only because the object is single-threaded and owns its storage. We cannot buy that on a shared company Postgres. What transfers is the output gate: the viewer must not be told a mutation succeeded before its commit is confirmed, and a failed commit must turn into an error, not a silent partial.

    Ship the writes as one batch at the end. The handler runs with no open transaction; reads are served by short single-statement queries; writes are buffered client-side and applied in one transaction at the end. This is DO write coalescing without the gates. Programming model damage: reads taken at different moments are not a consistent snapshot of each other, so a handler that reads, decides, and writes has a classic lost-update window unless the final batch re-validates. Reading your own writes requires the SDK to maintain an overlay of buffered writes over live reads; branching on such a read is only correct if the overlay is exact (deletes, partial updates, and range queries are where overlays quietly lie). The win is real: zero held connections, the commit is one short transaction, and the crash window shrinks to a single RPC.

    Windmill. Windmill does not attempt this. Its Postgres executor runs each parsed statement through the client with no BEGIN/COMMIT wrapper, so scripts are autocommit unless the author writes the transaction themselves, and flows are sequences of separately-scheduled steps with per-step retries rather than one transaction (https://raw.githubusercontent.com/windmill-labs/windmill/main/backend/windmill-worker/src/pg_executor.rs, https://www.windmill.dev/docs/getting_started/scripts_quickstart/sql). Worth recording as an existence proof that a successful platform in this space ships without invocation-level atomicity — and as a reminder of what that costs: every author who needs atomicity must know to ask for it.

    3. Failure handling: timeout, crash, lost callback

    With a held transaction, every failure mode collapses to one rule: whoever holds the transaction must roll it back, and if that party is gone, the database must. Execution-service timeout — the hosting server's deadline fires, rolls back, releases the lease, and answers the viewer with a terminal error. Execution-service crash or lost callback — identical, provided the deadline is a server-side timer that starts at BEGIN; without it the connection is pinned until idle_in_transaction_session_timeout or transaction_timeout terminates the backend, which is precisely their documented purpose. Hosting-server crash — the TCP session dies and Postgres rolls back; nothing is committed, which is the safe direction. The genuinely ambiguous case is a crash between COMMIT being sent and its acknowledgement; this is irreducible and is what outcome = 'unknown' already exists to express.

    With batch-at-the-end or OCC, an execution-service crash before the commit RPC costs nothing to clean up; there is no connection to reclaim. The ambiguity window narrows to the commit itself but does not close, and the retry that OCC makes attractive is only safe if the retried mutation is idempotent with respect to anything already applied. The clean way to buy that is a dedupe key written inside the same commit: the invocation's correlation id in a small company-side table, so a replayed commit is a primary-key conflict rather than a second charge. Note that runtime_calls cannot serve this purpose — it lives in the platform database, so it cannot be part of the company transaction.

    For all designs, one rule from the existing code should survive: Runtime.ts treats an interrupted invocation as unknown rather than failed ("Interruption includes a lost client or process shutdown: do not claim the write failed"). A held transaction makes interruption mean rollback in most cases, which is stronger, but the code should not start claiming certainty it does not have.

    4. The before-execution log row and rollback

    RuntimeLog.begin inserts a row with outcome = 'pending' and the invocation's deadline_ms before the handler runs; finish flips it to success/failure; readers compute 'unknown' for a pending row whose deadline has passed. Three properties matter for tier 2.

    First, the log is in the platform database (0006_runtime_baseline) and is written with the platform client, so a company-database rollback leaves the attempt recorded. That is the behaviour we want, and it matches the table's own comment that attribution is a snapshot, not a foreign key. The failure mode to guard against is a future refactor that writes the log inside the company transaction "for atomicity": that would erase the evidence of exactly the invocations most worth auditing.

    Second, the log's deadline must be the enforced deadline. 'unknown' is derived arithmetic, not an observation. If the transaction can outlive deadline_ms, a mutation can commit after its row already reads unknown, and the portal will have lied. So: enforce the mutation deadline, set the database-side timeout to the same value (or slightly below), and treat deadline_ms as a contract rather than a hint.

    Third, finish is a second, independent commit. A crash between the company commit and the log update leaves a pending row that ages into unknown even though the write landed. That is acceptable and already the design's stance; it is not made worse by anything proposed here.

    5. What PGlite can and cannot reproduce

    PGlite is real Postgres compiled to WASM — "simply Postgres in WASM", not a Linux VM (https://pglite.dev/docs/about) — reached through the engine's "single user mode" because Emscripten-compiled programs "cannot fork new processes", and its limitations list says "PGlite is single user/connection" (https://github.com/electric-sql/pglite). Its transaction callback commits on resolve and rolls back on reject (https://pglite.dev/docs/api). So it reproduces: SQL semantics, constraint and type behaviour, statement errors, rollback of a failed mutation, and the shape of the SDK's data calls.

    It cannot reproduce: pool exhaustion and the busy path (there is no pool), lock waiting or deadlock between sessions, serialization failures (no concurrent writer can exist), idle_in_transaction_session_timeout firing under contention, advisory-lock contention across sessions — ADR-0009 already says this layer "cannot prove multi-session locking behavior" — and anything about PgBouncer. The socket server's multiplexer offers multiple client connections over the single connection but warns "this is different from a normal Postgres installation, so not all use cases are guaranteed to work" (https://pglite.dev/docs/pglite-socket). Conclusion: the local dev loop can run tier 2 mutations happily, but every concurrency-shaped test — OCC retries, lease exhaustion, deadline enforcement — belongs on the embedded real Postgres that pnpm dev and the vitest template already use.

    Open questions

    • Does Convex let a mutation read its own uncommitted writes? Neither the mutation docs nor the OCC article states it; the architecture article describes the write set as a map of id to proposed value without saying reads consult it. Not established.
    • Convex's OCC retry count and backoff. Not documented on the OCC page or the limits page.
    • Is SET LOCAL safe under PgBouncer transaction pooling? The feature matrix marks SET/RESET "Never"; the FAQ and config pages say nothing about SET LOCAL. Transaction-scoped settings should be fine by the same reasoning ADR-0009 applies to pg_advisory_xact_lock, but that is an inference.
    • Azure Flexible Server defaults for idle_in_transaction_session_timeout and transaction_timeout, and whether the server major version we run supports transaction_timeout at all (it is a recent parameter). Not established from the Azure parameter docs fetched.
    • Measured numbers. No primary source gives the cost of one held backend on D2, nor a p50/p95 for a realistic tier 2 mutation. Both need a spike, per the map's rule about measuring rather than benchmarking empty handlers.
    • Sticky routing. Whether the execution service and hosting server will be co-located or routable per invocation is settled on the execution-service ticket, not here; the held-transaction recommendation depends on it.
    • Windmill's transaction behaviour was established from main in its repository, not from a released tag or from documentation; the docs are silent.

    Recommended v1 mechanism

    Hold one company-database transaction open for the invocation, bounded hard. It is the only option that keeps the programming model obvious — read your own writes, branch on a read, no determinism rule, no replay, no read-set machinery, no overlay that can lie — and "a mutation is one transaction" becomes literally true rather than approximately true. For a two-person team this is the smallest thing that makes the correct behaviour unsurprising, and it is the only option whose implementation is "open the transaction on the first callback, commit on return".

    The deadline it needs: 10 seconds, enforced in three places. Wrap the mutation in Effect.timeoutOrElse like integrations already are; set a transaction-scoped Postgres timeout at the same 10 s so the backend dies even if our fiber does not; keep runtime_calls.deadline_ms equal to the enforced value so 'unknown' stays honest. Ten seconds, not thirty: Convex allows one second of user code per mutation, and every second here is a Postgres backend, its row locks and one of four company slots. Keep PATCHY_RUNTIME_MUTATION_DEADLINE_MS as the knob; lower its default for tier 2 mutations.

    The pool budget it needs: the existing one, stated as a product limit. Four concurrent mutations per company (ADR-0009's pool maximum), fail-fast busy beyond that, 200 backends across replicas — under a quarter of GP D2's 844 user connections, so the fleet is not near a Postgres limit even with every retained pool saturated. Callbacks must be routed back to the replica holding the lease. Do not adopt PgBouncer for this path; ADR-0009 already defers it, and a held transaction removes most of its value anyway.

    The trade-off, stated. A held transaction puts a Postgres backend and its row locks under the control of patch code for up to the deadline, and caps a company at four simultaneous mutations. A slow handler blocks other viewers touching the same rows, and connection-level head-of-line blocking becomes a product-visible busy. We accept that because tier 2 is "hosted while a viewer has the patch open" — human-paced, single-digit concurrency per company — and because the failure is loud and bounded rather than silent and partial. If measurement shows the four-slot cap or the lock-hold time biting, the migration path is batch-at-the-end with a commit-time read-set re-check and 40001 retries: strictly more machinery, a weaker programming model, and a decision to take with data rather than in advance.


    Verification pass (2026-09-19). Every source cited above was re-opened and the quoted strings confirmed verbatim: the four PostgreSQL 18 pages (client config timeouts, explicit locking, transaction isolation, routine vacuuming, PREPARE TRANSACTION), both PgBouncer pages, both Azure pages (D2 = 844 user connections; "conservative values by multiplying the vCores within the range of 2 to 5"), node-postgres, both Effect source files at the pinned commit 2600f62, the four Convex pages and the Stack article, both Cloudflare pages, Windmill's pg_executor.rs on main (a keyword search confirms BEGIN, COMMIT, ROLLBACK and transaction( are all absent), and the PGlite README, About, API, socket-server and multi-tab pages. One correction was made during verification: the "single user mode" and "single user/connection" statements are in the PGlite README, not on the About page, and the citations above now say so. No other claim changed.

  3. allisonmahmood commented on Sep 19, 2026

    @allisonmahmood
    OwnerAuthor

    Report B: astra via omp, with tools (full findings, including Expansion 1 requested by the charting session)

    One transaction across execution-service callbacks

    Research for #310. Recommendations below are proposed settings, not measured production limits.

    Summary

    • Recommend a host-owned Postgres transaction for v1. The execution service sends authorized callbacks; it never owns a database connection. Effect already reserves one connection for a transaction. PgClient SqlClient
    • Every callback must enter the same transaction scope. Today's table handlers acquire their own company leases, so wrapping only the initial HTTP request would not provide this guarantee. Table operations
    • Preserve ordinary sequential code, including branching on reads and reading uncommitted own writes. Choose SERIALIZABLE explicitly; Postgres defaults to READ COMMITTED, which allows successive reads to change. Isolation
    • A held transaction occupies one backend even while patch code computes or awaits a callback. PgBouncer transaction pooling cannot share that backend until the transaction ends. Pooling
    • Start with a proposed five-second invocation budget, two held mutations per company and sixteen overall. These are conservative admission settings, not measured capacity. Existing pools have four permits and a 200-backend retained-maxima budget. Pool implementation
    • The current mutation deadline is not enforcement: Runtime applies its timeout wrapper only to integrations. Expired pending audit entries merely read as unknown. Dispatcher Log
    • Keep direct connections initially, but correct the old rationale: rc.115 uses protocol cancellation, not the rc.112 SQL cancellation examined in Research: a Postgres database per company on Azure, pooling and budgets #178. Named prepared statements now also need attention before enabling PgBouncer. Dependency pin Driver Prior research
    • Convex validates optimistic read dependencies and retries a conflicting mutation. It does not simply replay stale writes at commit. Recreating that behavior is a database-concurrency project. Convex
    • Durable Objects provide transactions over an object's own storage, not over Patchy's company Postgres. Their programming model is useful precedent, not a portable replacement for this transaction. Storage
    • Shipping one final write batch shortens connection occupancy but cannot transparently preserve arbitrary JavaScript read/write interleaving. Neon explicitly separates non-interactive HTTP transactions from interactive sessions. Neon
    • Windmill runs flow steps as separate jobs; a workflow's error handler is not a rollback of earlier committed steps. Windmill flows Error handling
    • Keep the audit attempt outside the company transaction. Rollback must preserve evidence of the attempt; uncertain commit outcomes must remain unknown rather than invite replay. Production logging Protocol
    • PGlite can exercise SQL commit/rollback and handler behavior locally, but cannot establish production multi-session contention, pool exhaustion or PgBouncer correctness. PGlite ADR

    Detail

    Holding one transaction across callbacks

    This extends the company-database model, not the execution-runtime survey. The prior investigations cover isolation choices, Daytona and Azure pooling; the current map fixes handler-shaped, credential-free execution beside the host, with Azure now and AWS later. This report retains that boundary. Prior art Daytona Azure research Map

    Proposed ownership is one hosting process, one invocation coordinator and one scoped company lease. After authorization and a committed audit-begin row, the coordinator enters an outer withTransaction, runs all callbacks there, validates the handler's result, then commits before reporting success. Effect's transaction service carries the reserved connection in its context and rolls back on failure or interruption. Independent HTTP fibers do not inherit that context merely because their requests carry the same identifier. SqlClient source

    Route callbacks to the owning coordinator through an authenticated internal channel. Bind its unguessable invocation capability to company, patch, immutable version, principal and deadline. Process callbacks in order; reject duplicates, late messages and work after finalization. Any callback SQL or transport failure marks the invocation abort-only, even if patch code catches the error. Keep SQL credentials and COMMIT/ROLLBACK commands inaccessible to patch code. One coordinator loop inside the transaction avoids exporting a connection whose scope has already ended. These are proposed protocol rules, derived from the connection-ownership requirement. PgClient source Map

    The implementation seam matters. TableOperations.withTable currently calls withCompany, and inserts open an operation-level transaction. Tier 2 needs the existing validated table executor under the invocation's supplied company/transaction capability, not another public runtime request or another lease. Otherwise it either commits each callback separately or consumes another pool permit while holding the first. Table operations Company leases

    Connection cost, pool budgets and deadlines

    ADR-0009 sets a registry ceiling of 100 pools, four connections per pool, minimum zero, 60-second idle TTL and a default retained-maxima budget of 200 per process. Consequently only fifty four-slot pools fit that budget, even when most are idle. Placement has a separate two-connection pool; administration and provisioning need additional headroom. Retaining a lease for an invocation does not replace these accounting rules. ADR Implementation

    One active mutation consumes one permit and one reserved backend throughout its database transaction. Connection occupancy grows with callback round trips and handler computation, not just SQL time. An illustrative steady workload of twenty mutations/second holds about two connections at a 100-ms mean transaction duration, but about one hundred at five seconds. These are occupancy calculations, not benchmarks. Azure charges per server, not per held transaction; memory, locks and throughput are the practical cost. Idle transactions can also prevent vacuum from removing dead tuples. Billing Connection resources Transaction timeouts

    Proposed initial admission is two held mutations per company and sixteen per hosting process, with immediate busy when unavailable. Two slots remain outside the mutation allowance in each four-slot pool, though other operations can still fill them. Start with one owning process. Before adding replicas, divide a fleet retained-backend budget of 200 and held-mutation budget of sixteen explicitly; do not multiply both defaults silently. For example, two replicas get 100 retained backends and eight held mutations each. Company caps remain per replica unless routing supplies single-company ownership. Existing fail-fast permits

    Require sum(retained/draining pool maxima) + H < available user connections. As a proposed starting allocation, reserve H=64 for platform, placement, admin, provisioning and cancellation connections, but verify their configured maxima actually fit it. Then 200+64=264; Azure's documented D2 defaults provide 844 user slots, not a guarantee of throughput or the live configuration. Read the actual reserved settings before rollout. ADR Azure limits

    Proposed timing policy, measured from host admission before dispatch:

    Control Initial limit Purpose
    Invocation 5 s total Includes acquisition, callbacks, computation and commit; no reset per callback
    Transaction Remaining invocation budget + 1 s, at most 6 s PostgreSQL 17+ server-side backstop
    SQL statement Smaller of 2 s and remaining budget Bounds execution and lock waiting
    Lock acquisition Smaller of 500 ms and statement budget Fails contested interactive work promptly
    Idle in transaction 2 s Reclaims stalled execution between callbacks

    These limits deliberately reject long computation and slow multi-round-trip handlers. PostgreSQL distinguishes statement, transaction, lock and idle-in-transaction timeouts; one cannot substitute for another. Azure documents transaction_timeout for PostgreSQL 17. Apply transaction settings with SET LOCAL, not URL parameters: Patchy's current SQL wrapper rejects unsupported parameters, including URL timeout options. Postgres controls Azure controls SET LOCAL SQL wrapper

    A deadline stops new callbacks and commit admission, then initiates cancellation and rollback. It is not proof that cleanup finished within one extra second. Keep permits charged until cleanup completes; discard a broken connection. If COMMIT may already have reached Postgres, return unknown rather than promise rollback. Cancellation protocol Transaction finalization

    PgBouncer holds a backend for the whole transaction; statement pooling forbids multi-statement transactions. Azure defaults to fifty backends per database/user pair and a 600-second backend idle timeout, so changing ports would not solve held-transaction pressure or preserve the current aggregate budget automatically. PgBouncer Azure pooling

    There is an important correction to the prior research. ADR-0009 still describes pg_cancel_backend(client.processID), but the checkout pins rc.115, whose native driver sends CancelRequest with the protocol PID and secret. It also enables named preparation by default. Keep the operational decision to use direct connections, but treat the old cancellation blocker as historical. Before any PgBouncer adoption, test cancellation, reuse after rollback and prepared statements; use prepare: false or verified protocol-prepared-statement support. This report has not run those tests. ADR Pin Driver Compatibility

    Alternatives that avoid a held Postgres connection

    Convex optimistic concurrency

    Convex executes against a begin-timestamp snapshot, buffers writes, and records index ranges read. Its committer checks intervening writes against those dependencies, then applies the buffered writes or discards them and reruns the mutation on a newer snapshot. This is validation plus whole-handler retry, not replay of old reads and writes. Range tracking matters: a newly inserted matching row can invalidate a scan even if no previously returned row changed. Architecture OCC

    Handlers can branch on reads and read their own writes. Mutations must be deterministic and cannot call third-party APIs. A worker failure before commit leaves only an uncommitted proposal, but a lost final response still requires the platform's outcome protocol. Writing data Mutations

    For Patchy, reproducing this without a held transaction would require snapshot/version history, a pending-write overlay, predicate tracking, atomic validation/application and whole-handler re-execution. Row-version checks alone miss absent rows and range changes. This is an engineering inference from Convex's design, not an API that PostgreSQL exposes. It is too much machinery for the proposed v1. Architecture

    Durable Objects storage transactions

    A Durable Object's transactional storage belongs to that object. SQLite-backed objects support synchronous SQL and transactionSync(callback), which rolls back on throw and forbids asynchronous callbacks. Async transaction groups storage operations; writes without intervening awaits can coalesce automatically. Reads and branches can use local storage, including its own pending writes. Storage API KV semantics

    Input gates pause other events during storage I/O; output gates delay outgoing messages until prior writes persist. An arbitrary external await is not a transaction boundary covering remote systems. Therefore an HTTP callback into company Postgres does not join the object's SQLite transaction. Adopting the product relocates data; borrowing its single-owner scheduling still leaves Patchy needing a real Postgres transaction or an optimistic engine. Storage boundary Gates

    One final batch

    The handler can gather inputs, then submit an ordered batch that the broker executes in one short transaction. SQL inside that batch can read earlier batch writes. The remote JavaScript handler cannot inspect an intermediate batch result and choose the next statement without another round trip. Neon's HTTP transaction accepts an array or a non-async array-building function; interactive transactions instead require its session-capable WebSocket API. Neon

    Earlier callback reads are outside the final transaction. Even a SERIALIZABLE final batch cannot retrospectively protect those reads. Supporting arbitrary branching and read-own-writes before submission needs an overlay and validated read dependencies, returning to OCC. A batch is a good explicit bulk-write operation, not a transparent implementation of arbitrary mutations. This follows from the two APIs' transaction boundaries. Neon Isolation

    Windmill

    Windmill executes flow steps as individual jobs and passes previous results into later steps, including JavaScript branch predicates. Its SQL docs support multiple statements; the inspected PostgreSQL executor iterates statements on one client without adding an outer transaction around that loop. Explicit BEGIN/COMMIT in one script is a source-level possibility, not a documented cross-step transaction contract. Flows SQL Executor

    Later steps can observe committed prior writes and branch on their results, but this is not read-own-writes inside one uncommitted workflow transaction. Error handlers run after exhausted step retries; compensation would be another operation, not rollback. No primary source reviewed establishes shared-transaction or timeout-rollback guarantees across flow steps. Windmill does not solve Patchy's callback transaction ownership. Flows Error handler

    What the handler can express

    A held Postgres transaction allows read → branch → write → read, with the last read seeing its own writes. READ COMMITTED provides atomic commit but not a stable invocation-wide view. Recommend SERIALIZABLE for mutation data and an explicit conflict result when Postgres aborts. A serializable guarantee requires compatible treatment of all relevant writers, including any retained tier-1 path touching those tables; marking only the new wrapper serializable is insufficient. Isolation Application consistency

    For v1, do not automatically retry handlers. If retries are later added for confirmed 40001 or 40P01 aborts, re-run the entire handler in a fresh transaction, including the reads and branches, within the original deadline. Never retry only its last statement or reuse a stale write list. Do not retry an unknown commit outcome. PostgreSQL explicitly requires the complete decision logic to be repeated. Retry guidance

    Proposed mutation authority is company-table operations only, including authorized same-company shared-table reads on that transaction. External integrations and blob I/O belong in actions, with separately committed mutations. They are not part of one company's Postgres transaction. The existing file design deliberately performs blob I/O outside company leases; calling the whole handler atomic must not silently broaden that guarantee. ADR Map

    Execution timeout, crash or lost callback

    Failure Proposed behavior
    Handler throws, exceeds deadline or worker crashes Close callback admission; cancel SQL; roll back; reject later callbacks
    Callback request/reply is lost Abort through the trusted execution wrapper or host deadline; never silently resend a write
    Callback arrives twice or after completion Reject it, rather than execute outside the original transaction
    Host crashes before COMMIT Open transaction rolls back when Postgres detects connection termination; server timeouts cover a silent broken link
    Connection fails during COMMIT or final reply is lost Outcome can be unknown; no automatic replay
    Database fails over Original transaction cannot resume on a fresh connection; distinguish a confirmed abort from an uncertain commit

    These rules separate worker liveness from database liveness. Killing the worker does not close the host's database connection. PostgreSQL rolls back open transactions on connection termination, but a disconnect or cancellation is not a receipt proving what happened to an already-sent command. Keep commit and timeout transitions serialized in the coordinator. Protocol Azure restart behavior

    Before-execution logging and rollback

    Today RuntimeProduction calls log.begin before execution, skips finalization on interruption, and maps a failed finish to UnknownOutcome. RuntimeLog presents expired pending rows as unknown without rewriting them. Its default thirty-second deadline is audit metadata; the dispatcher only applies the timeout wrapper to integration calls. Tier 2 therefore needs real deadline enforcement, not just a different deadline field. Production Log Dispatcher

    Keep one invocation attempt durably committed in the platform database before dispatch. If logging fails, do not execute. Do not insert that row inside the company transaction: rollback would erase the attempt. Finalize failure after a confirmed abort and success after a confirmed company commit. A callback's successful INSERT is not a successful mutation; defer any child success status until the outer outcome is known. Current ordering Separate databases

    The two databases cannot atomically commit the company write and platform success update under this design. A crash between them leaves unknown, which is honest. Recommend retaining that behavior for v1. If product requirements later demand recoverable outcomes, store an invocation receipt in the same company transaction and reconcile the platform log from it. An absent receipt proves nothing until the original transaction has conclusively ended; it is not permission to replay. This is a proposed extension, not an existing guarantee. ADR Protocol

    What PGlite can reproduce locally

    PGlite's transaction(async tx => ...) commits when the callback resolves and rolls back when it rejects. This can check sequential SQL, constraints, read-own-writes, branching and multi-operation rollback. It also supports persisted local data. Patchy's adapter uses one directory/connection with fsync disabled, so successful local persistence is not production crash-durability evidence. API Project ADR

    PGlite is explicitly single-user/single-connection. Multiple JavaScript callers do not create competing Postgres backends. It cannot reproduce cross-session locks, deadlocks, SERIALIZABLE conflicts, pool saturation, PgBouncer routing or network failover. The broker can simulate dropped callbacks and enforce its own deadline locally, but database-side timeout/cancellation parity is unestablished. Use real Postgres for those checks. Limitations ADR

    What each candidate cannot do

    Candidate Missing capability
    Held Postgres transaction Cannot release its backend between callbacks, span independent databases/blobs, or prove a lost COMMIT failed. Pooling Protocol ADR
    Convex-style OCC Cannot safely apply a stale write set without dependency validation; retries cannot contain irreversible external effects. OCC
    Durable Objects Cannot make external company Postgres part of its private storage transaction; transactionSync cannot await callbacks. Storage
    Final batch Cannot preserve arbitrary remote read/branch/write interleaving without additional concurrency machinery. Neon
    Windmill flow No established cross-step SQL rollback contract; an error handler does not undo earlier commits. Architecture Errors
    PGlite Cannot validate multi-session or pooled production behavior. Limitations

    Open questions

    • The actual production PostgreSQL major version, connection settings, replica count and non-company pool maxima were not inspected. The proposed 6-second database backstop requires PostgreSQL 17+ and verified settings. Timeouts Azure
    • No source establishes Patchy's callback latency, transaction-duration distribution, per-backend memory cost or throughput at the proposed caps. Measure realistic CRM handlers before increasing them. Azure connection caveats
    • rc.115 changes the PgBouncer compatibility question. Cancellation under load, prepared-statement reuse and finalizer behavior through Azure's pooler remain untested. Driver Azure pooler
    • Decide whether an unknown outcome is sufficient operationally, or whether a durable company-side receipt is required. The current log cannot prove a company commit after the host loses contact. Production logging ADR
    • Windmill's native SQL timeout cleanup and cross-step transaction behavior lack a documented guarantee. PGlite's database-side deadline behavior must be checked against the pinned local build, not assumed from its SQL compatibility. Executor PGlite

    Recommendation for Patchy

    Adopt a host-owned, directly connected, SERIALIZABLE Postgres transaction for short database-only mutations. For a two-person startup, keep execution credential-free and route ordered callbacks to the owning transaction loop. Use the proposed five-second total budget, two mutation slots per company, sixteen overall, existing four-slot pools and a fleet retained-maxima budget of 200 plus explicit non-company headroom. Preserve the independently committed audit attempt and truthful unknown outcomes. These choices extend existing ownership and accounting rather than add a second database or transaction engine. Map ADR Transaction implementation

    The trade-off is lower concurrency and visible conflict/busy errors in exchange for ordinary imperative handlers and a small implementation. Move slow or externally effectful work to actions; do not stretch transaction deadlines to accommodate it. Azure/AWS portability and the credit constraints favor this incremental design over adopting Cloudflare storage or rebuilding Convex's concurrency machinery. Credits on another execution vendor do not remove the database ownership problem. Map Convex Durable Objects

    Before rollout, the follow-on prototype should demonstrate read-own-writes, conditional concurrent updates, rollback after a lost callback, rejection after deadline, host death before commit, unknown after a lost commit reply, and bounded admission on real Postgres. PGlite is the developer check, not evidence for those multi-session and network guarantees. No live cloud systems were accessed and no runtime benchmark was run for this report. PGlite limitations Protocol

    Verification: every cited source was reopened and checked against the claim. Patchy source citations use checkout commit ef3e790d5b924932fa4161000a4c395e6b84ae7b; vendor sources were checked on 2026-09-19. The repository remained read-only.

    Expansion 1

    This section supersedes the earlier retry and two-slot recommendations.

    Callback errors and savepoints

    Per-callback savepoints are necessary only if Patchy promises SQL-error catch-and-continue. That contract requires SAVEPOINT before the callback, RELEASE on success, or ROLLBACK TO then RELEASE before continuing after failure. Catching the JavaScript rejection cannot repair an aborted SQL transaction; RELEASE alone is illegal there. Rollback Release

    The pinned Effect implementation does nest withTransaction using savepoints, but nested success executes Effect.void, not RELEASE; nested failure rolls back to the savepoint. Therefore it is not the complete bounded-lifetime wrapper described above. Successful callback savepoints can accumulate until outer completion. Pinned source

    An explicit wrapper adds two control statements on success, three on recovered failure. Awaiting each separately adds corresponding host-to-Postgres exchanges, not executor-to-host callbacks. PostgreSQL also allocates a subxid when a subtransaction writes and records its parent in pg_subtrans. Its documented cache holds 64 open subxids per backend; beyond that, additional lookups increase storage I/O. This is not a limit of 64 callbacks or a universal milliseconds-per-savepoint figure. Benchmark latency on the intended connection topology. Subtransactions Release

    Keep the abort-only rule instead: the first failed callback terminates that mutation attempt, even if the handler catches it. Reject further callbacks and never commit that attempt. Do not add per-callback savepoints or preserve redundant nested wrappers merely to mask errors. This is the smaller agent contract; expected business alternatives should be successful operation results rather than rescued SQL exceptions.

    Automatic serialization retries

    I revise the earlier no-automatic-retry recommendation. With database-only handlers, SERIALIZABLE plus a host-owned retry loop is a smaller correctness model for agents than teaching every handler conditional updates and locking.

    A READ COMMITTED lost-update example follows directly from PostgreSQL's update rules: two handlers read counter 0, each computes 1, then each executes UPDATE counter SET value=1 WHERE id=7. The second updater waits if necessary, rechecks its still-matching predicate and overwrites with 1; both commit, losing an increment. SET value=value+1 solves that particular case, not arbitrary read-dependent, multi-row invariants. READ COMMITTED also permits successive reads to disagree. Isolation

    SERIALIZABLE pays for read/write-dependency tracking, predicate-lock memory and discarded/repeated work. SIReadLock predicate locks do not block or cause deadlocks; ordinary write locks still can. Deadlocks Coarse relation locks, including those from sequential scans or memory-driven lock promotion, increase false-positive serialization failures. There is no workload-independent overhead percentage. PostgreSQL explicitly recommends retrying the complete transaction, including application decisions, for 40001. Isolation Retry guidance

    Proposed policy: re-invoke the entire handler with the same inputs and version in a fresh transaction after a confirmed 40001, including one returned by COMMIT. Allow three total attempts within the original five-second deadline, not three retries or five seconds each. Fence callbacks by attempt, finish rollback before restarting, and expose only the committed attempt's result. Exhaustion returns conflict; deadline exhaustion returns timeout. Do not retry domain errors, arbitrary unique violations or unknown commit outcomes. Pinned Effect turns commit errors into defects through Effect.orDie, so inspect the full exit/cause for the confirmed SQLSTATE, not only the typed error channel. Retry guidance Pinned source

    SDK skill sentence: "Write mutations as database-only read/branch/write handlers; Patchy retries the whole handler on serialization conflicts up to three total attempts within its deadline, and a failed callback ends the current attempt even if caught."

    Company slots

    The two-slot cap was an unmeasured read-headroom policy, not a correctness requirement. I withdraw it. Start with all four existing permits available to mutations and fail-fast busy, without another mutation-specific per-company limiter. Callbacks must reuse their invocation's lease. The trade-off is that four mutations can make same-company reads return busy too. Admission source

    Compare caps two and four in the spike at identical offered load, with independent-row writes, a contended counter, and concurrent reactive reads. Measure committed logical mutations/second, attempts/commit, final conflicts, read/write busy rates, read/write end-to-end p95/p99 including retries, deadline failures, backend occupancy and database CPU/I/O. Include slow callbacks and multiple companies. Keep four only if useful throughput improves without unacceptable read failures or retry amplification; otherwise two buys measured read headroom. Set the read-latency and refusal targets before running the comparison.

    Verification: all sources cited here were reopened; costs are source-derived, not benchmark measurements.

  4. allisonmahmood commented on Sep 19, 2026

    @allisonmahmood
    OwnerAuthor

    Resolution

    Two reports ran in parallel (Opus and astra with tools, full text above), then the charting session sent astra back for three points neither had covered (savepoints per callback, SERIALIZABLE with automatic re-invocation, the slot count). This is the merge with the session's own checks and opinion.

    The v1 mechanism: one host-owned transaction per mutation, bounded hard

    Both reports land here independently. The execution service never owns a database connection; the hosting server opens a company-database transaction on the mutation's first callback, every later callback joins it, and it commits on return. Reasons: it is the only option where "a mutation is one transaction" is literally true; the handler reads its own writes and branches on reads with no determinism rule, no replay, no read-set machinery; and the implementation is "open on first callback, commit on return" over the transaction scope Effect's PgClient already reserves.

    • Every callback must join the same transaction scope. Astra's finding: today's table handlers acquire their own company leases per operation, so wrapping only the invocation is not enough; the lease is reused by the invocation, and callbacks are routed back to the replica holding it.
    • Deadline: five seconds total per mutation, enforced in three places: the fiber timeout, a transaction-scoped Postgres timeout so the backend dies even if the fiber does not, and deadline_ms in the log equal to what is enforced. Convex allows one second of user code; thirty is what the config allows today. Slow or externally effectful work belongs in actions.
    • Slots: the existing four per company, fail-fast busy, no mutation-specific limiter. Astra withdrew its two-slot proposal as unmeasured; the spike compares two and four at identical offered load with a contended counter and concurrent reactive reads before anyone raises the number. Connections are not scarce at our size (200-backend fleet budget against 844 on GP D2); held time and row locks are.
    • Isolation: SERIALIZABLE, with Patchy re-invoking the whole handler on a confirmed 40001, up to three total attempts within the original five-second deadline, callbacks fenced by attempt, only the committed attempt's result exposed. Astra revised its position to this after the expansion: with database-only handlers, SERIALIZABLE plus a host-owned retry is a smaller correctness model for agents than teaching every handler conditional updates. READ COMMITTED lets an agent write the classic lost update without noticing. Not retried: domain errors, unique violations, unknown commit outcomes. One detail for the build: the pinned Effect turns commit errors into defects through Effect.orDie, so the SQLSTATE must be read from the full cause.
    • Abort-only errors, no savepoints per callback. Postgres aborts the whole transaction on any statement error, and catching the JavaScript rejection cannot repair it. Rather than a SAVEPOINT/RELEASE pair around every callback (the pinned Effect nests withTransaction as savepoints but never releases on success), the rule is: the first failed callback ends that attempt even if the handler catches it; later callbacks are refused; the attempt never commits. Expected business outcomes are returned results, not rescued exceptions.
    • The log row stays outside the blast radius. RuntimeLog.begin writes the pending row through the platform client, a different database from the company transaction, so rollback cannot erase the attempt; a lost commit reply stays unknown, never a replay.

    Two things the reports found in the repo

    Rejected alternatives, and why they stay in the pocket

    Convex-style optimistic concurrency (read and write sets validated at commit, deterministic handlers, replay) is a database-concurrency project; batch-at-the-end cannot preserve arbitrary read-branch-write interleaving; Durable Objects transact over their own storage, not our Postgres, though their output gate (never acknowledge before commit) is copied; Windmill has no invocation-level transaction at all. The named fallback if measurement shows the held backend or the four-slot cap biting is batch-at-the-end with a commit-time read-set check.

    What the spike must show, on real Postgres

    Read-own-writes and branching; a contended counter under two writers committing correct totals through retries; rollback after a lost callback; rejection after the deadline with the backend gone; host death before commit; unknown after a lost commit reply; busy at the slot cap; and the two-versus-four comparison. PGlite is single-connection and rehearses semantics only, never contention.

    The SDK skill sentence, astra's wording: Write mutations as database-only read, branch and write handlers; Patchy retries the whole handler on serialization conflicts up to three total attempts within its deadline, and a failed callback ends the current attempt even if caught.

    Merged by Claude Fable 5.1 via Claude Code, 2026-09-19.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    wayfinder:research

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions