Skip to content

[Request]: Evaluate conditional state transitions and result-aware idempotency beyond store CRUD #835

Closed

Description

@jimhoyd

Problem or use case

The unfamiliar-app authoring evaluation associated with #832/#833 repeatedly generates domain-owned state machinery:

  • Consent/capture coordination: expected consent version, cancel pending captures on consent/membership change, requester-scoped retry keys and current-result replay.
  • Scheduling: exclusive half-open intervals, expected booking revision, cancellation/rescheduling, original creation fingerprint retained after later changes.
  • Simulated credits (contract under evaluation): a hold moves value between available/held balances, then commit/cancel affects multiple records while preserving conservation.

The generated scheduling candidate keeps separate Maps for calendars, bookings and keys, a promise queue, and write-then-rename persistence. The conventional control independently implements similar state and retry logic. This is repeated plumbing evidence, not proof of demand for a particular API. Initial delivery outcomes are mixed and several are invalid/time-limited; do not read this as a benchmark win.

Existing #426/#429 primitives are useful but insufficient for these contracts. Store already implements single-record ETag/If-Match conditional writes, including StoreExports.update(..., {ifMatch}); it does not implement transactions across records/collections. Its retained idempotency keys return 409 idempotency_duplicate, whereas these contracts require payload-sensitive replay of the current entity, scoped to the authenticated requester and domain resource. An inconsistent limitations paragraph incorrectly denied optimistic concurrency; #836 tracks that documentation correction. The proposed work must reuse existing conditional writes rather than recreate them.

Actual route shape still needed custom code:

/api/calendars/{id}/bookings:
  methods: [POST]
  auth: true
  request:
    body:
      required: true
      maxBytes: 16384
      contentTypes: [application/json]
      format: json
  function: {source: functions/bookings-create.mjs}

The function performs normalization/authorization, then custom code serializes overlap detection, retry-key claim, record creation and durable persistence. Merely exposing current CRUD methods to that function cannot make the group atomic.

Proposed behavior and alternatives

Evaluate the smallest extension-owned contract that can support a reviewed conditional mutation with expected revision and result-aware idempotency, composed with native principal identity. Do not begin by adding camera/scheduling/ledger-specific recipes or a general YAML programming language.

Use the three independent contracts as counterexamples when deciding scope. Compare a bounded store mutation capability, a narrow trusted host transaction API, and continuing with application-owned storage. Explicitly refuse unsupported multi-record/backend semantics rather than implying that a sequence of CRUD calls is atomic.

Before implementation, specify: authorization ordering; key scope/fingerprint/replay after later changes; conflict/no-mutation behavior; persistence failure rollback; migration/retention limits; operator capabilities; one-process vs multi-process guarantees; and sandbox/target support. Keep provider settings outside project route YAML and core independent of store. Trusted callbacks must not be described as sandboxed.

Proof should cover racing same-key calls, expected-revision conflict, rejected interval move retaining its old slot, restart with original retry history, and conservation for the simulated-credit example. Measure eliminated custom plumbing and edit effort as well as HTTP correctness. This is a design evaluation request, not an approved broad transaction language or production guarantee.

Activity

  1. jimhoyd commented on Sep 28, 2026

    @jimhoyd
    CollaboratorAuthor

    The ecosystem reuse audit in #841 adds a concrete implementation alternative for this decision: replace the collection JSON persistence engine with SQLite-backed transactions before building multi-record atomicity on top of it.

    At inspected main a996f0d88394e83be9cca17f9793b10c50aabf1c, packages/store/src/collection.ts keeps record/index maps in process and writes whole collection state using temporary files, fsync and rename. Auth/audit/abuse already use node:sqlite. This is source evidence, not a claim that current store persistence is incorrect.

    Compare direct parameterized SQL against a query builder only if multiple dialects warrant one. Preserve or explicitly migrate owner scope, ETags, quotas and retry semantics; domain changes and their audit outbox must share the same database transaction where atomicity is claimed. Test the existing scheduling/conservation counterexamples, cross-collection rollback, races, restart and data migration. A remote PostgREST/Postgres profile is a separate deployment choice, not automatic parity.

    The user explicitly permits retiring existing implementations in favor of compatibility/reuse. Treat the JSON engine as replaceable and avoid a permanent compatibility wrapper that recreates its entire persistence model. No database replacement or compatibility prototype has been run yet. Keep this work in #835 rather than duplicating the transaction issue.

  2. jimhoyd commented on Sep 28, 2026

    @jimhoyd
    CollaboratorAuthor

    Scope alignment with #841: this remains the authoritative application transaction/idempotency issue. Evaluate SQLite engine transactions and existing driver/query tooling instead of expanding custom file transactions. Use the owner-private request/reviewer approval scenario in #843 as the first concrete fixture; exercise conditional transitions, concurrency, result-aware idempotency and app audit atomicity where required. Upstream auth owns its own tables; do not promise a transaction across separate provider databases. One locally runnable app and no historical data/API compatibility are the planning constraints. Forward initialization is still required. #829 legacy export expansion is on hold; no parity facade is mandated.

  3. jimhoyd commented on Sep 28, 2026

    @jimhoyd
    CollaboratorAuthor

    The #843 proof gives this issue its first concrete fixture (PR: #848). What it does now, with direct parameterized node:sqlite in app/lib/requests.mjs:

    • The one transition is UPDATE requests SET status='approved' ... WHERE id=? AND status='pending' AND owner_id<>?. Three concurrent approvals give exactly one 200 and two 409s; a reviewer cannot approve their own request (403); a non-reviewer gets 403 before any read.
    • The review permission is an application table (reviewers(user_id)) keyed by Better Auth's opaque user id. Identity and permission are separate stores; there is no cross-database transaction and none is claimed.
    • Not implemented: idempotency keys or result replay, expected-revision checks, multi-record transactions, audit evidence for the approval, restart/crash tests. Single process only (in-process SQLite handle, WAL, busy_timeout).

    That is intentionally the minimum; this issue still owns the transition/idempotency design and should replace the ad hoc SQL rather than grow it.

  4. jimhoyd commented on Sep 28, 2026

    @jimhoyd
    CollaboratorAuthor

    First slice is up for review in #858. The store now persists in node:sqlite, and every API write is one BEGIN IMMEDIATE transaction covering the idempotency claim, If-Match, quotas, the record and its audit-outbox event (trigger-injected failure rolls both back). The JSON engine is deleted. store_idempotency is shaped so a result column can hold a replay result. Next slice here: result-aware idempotency (payload fingerprint, requester scope, current-result replay) and a bounded conditional multi-record transition, proved against the #843 approval, scheduling and credit-conservation counterexamples.

  5. jimhoyd commented on Sep 28, 2026

    @jimhoyd
    CollaboratorAuthor

    Slice 2 is up for review in #862:

    • result-aware retries: a request fingerprint, principal scope and current-record replay, with 422 idempotency_key_reused for the same key on a different request
    • declarative transitions with If-Match and transitionOnly fields
    • StoreExports.transaction() for synchronous multi-record host work, proved on the approval, scheduling-move and credit-conservation counterexamples

    The design and its limits are in docs/STORE.md. The proof keeps its SQL because it needs a reviewer role the store doesn't have; that gap and the other follow-ups are in #863.

  6. jimhoyd commented on Sep 29, 2026

    @jimhoyd
    CollaboratorAuthor

    Closing: the evaluation and its first contract are delivered on main.

    Each counterexample has a test in packages/store/test:

    • racing retries, in one process and across connections (retries.test.ts);
    • a stale If-Match (transitions.test.ts, sqlite.test.ts);
    • a refused overlapping move keeps its slot, and credit conservation holds with rollback including the audit outbox (transaction.test.ts);
    • a restart keeps retry history (retries.test.ts).

    Not built and documented: the declarative interval constraint and transfer, retries for host transactions, supported multi-process serving, and the edit-effort measurement. These moved to #902. Passing CI is not an independent security review.

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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions