Skip to content

Read-write SQL execution ​

Status: M006 execution half — local implementation and fixture evidence recorded; not accepted. Read-write is enabled since the user approved A15 on 2026-11-17 (see Gates): MySQL/MariaDB over Direct and SSH, PostgreSQL over Direct; PostgreSQL over SSH stays read-only. Follow-up pass 2026-10-29: PostgreSQL session check and checked COMMIT, PostgreSQL statement_timeout (revised 2026-10-29 to fire before the client deadline), in-flight interrupt handling, resultsWithheld, per-owner bounds, and lost-COMMIT/ROLLBACK fixtures at n = 50 on all three network engines. Every limit below is PROPOSED, implemented as a working default under the user's 2026-10-26 continuation instruction and awaiting review. Read-write over SSH was enabled for MySQL/MariaDB by the same approval; PostgreSQL over SSH is refused before network access. Live MySQL/MariaDB/PostgreSQL table listing, columns, indexes, foreign keys and read-only Browse run through the M003 read-only path (renderer services/liveSchema.ts); the catalog is re-read after DDL. Live CRUD (services/liveMutations.ts) generates single-row statements addressed by the primary key and runs them as read-write jobs, so it is available only when the read-write gate is enabled (on in builds since A15); its exact statements are fixture-verified on all three engines (test:execution). SQLite catalogs and advanced object management remain pending. The desktop app has no mock profiles; the browser demo remains mock-only. On 2026-11-17 the user also approved D025-11 to D025-13 and the ExecutionLimits values as implemented (A16); items below still marked PROPOSED predate that approval. M006 remains open with recorded engineering gaps.

Read-write is the default access for desktop live connections on the enabled routes; Read-only connection is a saved per-connection opt-out. The M003 read-only path (read-only safety) is unchanged and serves read-only connections, PostgreSQL over SSH, and catalog/Browse reads.

Access mode ​

Native gate (implemented, ON since A15, 2026-11-17). With the gate off, The desktop host refuses access: read_write with UNSUPPORTED_CAPABILITY ("Read-write SQL is disabled in this build pending safety approval") for every engine and route, before any Keychain lookup or network I/O. The gate is the single constant READ_WRITE_SQL_ENABLED (now true) (apps/desktop/src-tauri/src/lib.rs), carried in HostServices.read_write_sql. Only trusted host code can enable it: tests inject it through app_builder_with; there is no renderer input or environment variable for it. HostInfo.readWriteSql reports the gate; with it off the UI locks Read-only connection on. The renderer only mirrors the host. The runtime service (stoneql-runtime) itself is not gated, so the fixture harness and unit tests exercise it directly. Everything below describes behaviour once the gate is enabled.

  • Read-only (opt-in per connection, and always for PostgreSQL over SSH): read_only_query only, with the engine-enforced read-only boundary. Job and transaction commands are refused (UNSUPPORTED_CAPABILITY).
  • Read-write (default for MySQL/MariaDB over Direct or SSH and PostgreSQL over Direct): a connection without Read-only connection ticked; that choice is saved with the profile (readOnly: true), the access itself is derived at connect time and never stored. A PROD-tagged profile needs the "PROD — I understand" acknowledgement before connecting read-write. That acknowledgement, and the confirmation shown before running scripts containing DELETE, UPDATE, DROP, TRUNCATE, ALTER, REPLACE, RENAME, GRANT or REVOKE, are UX safeguards, not authorization. Database privileges decide what is allowed.
  • The environment tag is not sent to the native host; there is no host-side PROD check.

Jobs ​

submit_job starts a script now or refuses it. Nothing is queued: while a read-write handle runs a job or holds a transaction, another job, a read-only query on that handle or a new transaction gets BUSY. A refused request was never sent.

  1. The script is split into statements client-side (splitter) and checked against the policy. A refusal rejects the whole script before anything is sent.
  2. Outside a transaction, the job opens a dedicated physical connection from the handle's verified options (same TLS identity). It is never taken from or returned to a pool, and is closed when the job ends. Session state (SET, USE, temporary tables, locks) therefore cannot reach another job or the read-only path.
  3. Statements run one at a time and stop at the first that does not succeed. MySQL/MariaDB, PostgreSQL and SQLite statements are prepared, so results use the reviewed lossless binary decoders; MySQL statements that cannot be prepared (USE, routine DDL, LOCK TABLES; error 1295) use the text protocol with server-rendered text values.
    • SQLite single statement (R-1, implemented and unit-tested). SQLx's SQLite driver runs every statement in the text it is given (it keeps preparing the tail SQLite leaves), so before a statement is sent the runtime checks with SQLite itself that the text is exactly one statement: for every ; that has text after it, the prefix up to it is prepared (never executed). The statement runs only if each prefix fails with a parse error (incomplete input inside a trigger body, an unterminated token, a syntax error), which depends only on the text. A prefix that prepares, or fails for another reason, refuses the statement (failed, nothing sent, later statements not sent; inside a transaction the lease becomes rollback-only). Statements with a NUL byte or more than 256 ; are refused. Conservative effect: a ; inside a comment refuses the statement.
  4. Results stream in bounded pages. The worker parks while two unread pages are buffered, without reading the database stream (backpressure). fetch_job long-polls up to 1 s for the next page. A finished job is released after its final page.
  5. After an interrupt (cancel, deadline, close) no further page is delivered, even if the consumer frees a slot; the statement is only driven to its end. Every statement whose rows, pages or result sets were read but not delivered reports resultsWithheld: true (B-11), and the renderer marks that statement's result sets truncated and says the rows shown are incomplete. This matters when a statement still completes after the interrupt: MySQL's killed SLEEP() returns success, and a last statement that completes within the grace period leaves the job succeeded.

Multiple result sets (scripts, PostgreSQL CALL) are kept in order with their statement index. MySQL/MariaDB CALL is refused in read-write scripts (see policy).

Outcomes ​

Each statement reports exactly one status: not_run (never sent), succeeded or failed (the server replied), or unknown. The job reports one outcome:

OutcomeMeaning
succeededEvery statement returned a server success and the session's transaction state matched afterwards (session check). Outside a transaction each success is committed (autocommit).
failedThe server rejected a statement (confirmed failure), or StoneQL refused a SQLite statement that is not exactly one statement. Earlier statements keep their status; later ones were not sent. Constraint kind (unique, foreign_key, not_null, check) and SQLSTATE are reported; database message text is withheld because it can contain row values. On MySQL non-transactional tables (MyISAM) a rejected multi-row statement can leave partial rows.
cancelledStopped before a statement was sent: nothing ran after the request.
unknownA statement was sent and then interrupted, lost or abandoned. Its effects cannot be excluded, even when its end was observed. A server-terminated session (PostgreSQL SQLSTATE class 08 or 57P*, MySQL/MariaDB 1053/1927) also counts as lost, not as a statement failure. Also unknown when every statement replied but the session's transaction state did not match afterwards, or could not be checked within 2 s.

Separately, cancellation is none, requested (cancel or deadline raised) or confirmed (the work was observed to stop), and serverCancelSent records that a best-effort server interrupt was delivered. None of these says that effects were undone. Nothing is retried automatically, including reads.

Session transaction state ​

Implemented (R-3, PostgreSQL added 2026-10-29); MySQL/MariaDB checks verified on real 8.4.6 and 11.4.8 fixtures, PostgreSQL on a real 17.6 fixture, SQLite in unit tests. After every job whose outcome is not already unknown, before its connection is discarded or returned to the lease, the runtime checks the server session:

EngineCheckExpected outside a transactionExpected inside a lease
MySQL, MariaDBSELECT @@autocommit, then SET TRANSACTION READ WRITE (refused with ER 1568 exactly while a transaction is active; it only sets the next transaction's access mode on a connection that is never reused)autocommit 1 and SET TRANSACTION acceptedER 1568
SQLiteBEGIN (rolled back at once when it succeeds)accepted"cannot start a transaction within a transaction"
PostgreSQLSAVEPOINT stoneql_state, released at once when it succeeds (no side effect: no transaction id is assigned, nothing is written)refused with SQLSTATE 25P01 (no transaction block)accepted; or refused with 25P02 (aborted block), which matches only after a job with a failed statement (the lease is rollback-only anyway)

A mismatch, error or timeout makes the job unknown. Inside a lease it also marks the lease diverged: it becomes rollback-only, and ending it sends neither COMMIT nor ROLLBACK; the connection is discarded and the end is unknown with commitSent: false, rollbackSent: false. Nothing runs on a lease session between a job's check and COMMIT/ROLLBACK, so the end itself is not re-checked (a check there would also replace the COMMIT as the first statement a lost reply can hit). Known conservative case: a MySQL deadlock (ER 1213) rolls back the whole transaction, so the lease is reported diverged and its end unknown even though the server rolled it back.

The UI's success text is "N statements executed successfully (autocommit)" or "(in the open transaction)"; it no longer says "(committed)".

Cancellation and deadlines ​

On cancel, statement deadline (default 30 s, maximum 300 s) or job deadline (600 s), the runtime sends a best-effort server interrupt and keeps driving the statement for up to 1.5 s:

EngineInterruptObserved end
MySQL, MariaDBKILL QUERY <connection id> over a separate short-lived connection (1 s connect bound)Error 1317, or the statement's normal completion
PostgreSQLpg_cancel_backend(<pid>) over a separate connectionSQLSTATE 57014
SQLiteProgress-handler interrupt flagSQLITE_INTERRUPT

The client connection is abandoned only after the interrupt was attempted, so a MySQL autocommit write is not left running merely because the client dropped its socket. If the statement does not end within the grace period, the connection is discarded and cancellation stays requested.

  • Interrupt still in flight (L-8). If the KILL/pg_cancel_backend has not answered by the end of the grace period it may still reach the session later and hit whatever runs next on it. The connection is then never used again: outside a lease it is discarded, and a lease ends unknown (connection_lost, neither COMMIT nor ROLLBACK sent). A job that sent any statement is then unknown. An interrupt that answered is harmless: a KILL QUERY on an idle MySQL 8.4.6 / MariaDB 11.4.8 session and a pg_cancel_backend on an idle PostgreSQL 17.6 backend did not affect the next statement (probed on disposable containers). Residual: pg_cancel_backend returns once the signal is sent, so a signal handled after the next command was read could still cancel it; after any interrupt the lease is rollback-only, so that command is the session check or ROLLBACK, and either failing is reported unknown.
  • PostgreSQL server timeout before the client deadline (L-3, PROPOSED; safety contract 5.3 ordering). Every PostgreSQL job first sets the session statement_timeout to its statement deadline minus a 1 s margin (at most half the deadline, never 0, which PostgreSQL treats as "no timeout"): 29 s for the 30 s default, 2 s for 3 s, 500 ms for 1 s. A statement that runs too long is therefore normally ended by the server with SQLSTATE 57014 and its error arrives before the client deadline. That statement is reported failed (no interrupt was sent, cancellation none) with deadlineExceeded set, because PostgreSQL reports it as an error before any commit of it started (PostgreSQL disables statement_timeout before it commits a statement's transaction, per its source; a timeout during commit is not exercised by the fixture) and the session check then confirms the transaction state: outside a lease the statement did not commit; inside a lease the block is aborted and the lease becomes rollback-only, and a later ROLLBACK is reported only as the server confirms it. deadlineExceeded now also covers this server timeout (no contract shape change; PROPOSED) and is set only when the server's error says "statement timeout" and the statement ran at least the server timeout, so with a non-English lc_messages a real server timeout is reported as a plain failed 57014; another 57014 (for example an administrator's pg_cancel_backend) is a plain failure. The client deadline, interrupt and grace period stay as the backstop for a statement the server timeout did not end (for example after a script's own SET statement_timeout = 0, which PostgreSQL does not refuse) and for a reply that never arrives; that path is reported unknown as before. The margin covers the error's network/tunnel latency and the server's interrupt-check latency; it is a working default awaiting approval. If the SET is refused or the session is lost, no user statement is sent and the job is failed; in a lease the block may be aborted, so the lease becomes rollback-only (or ends unknown when the session is gone). The read-only path is unchanged (SET LOCAL statement_timeout equal to its 3 s deadline, D012). MySQL/MariaDB have no server timeout: max_execution_time applies to SELECT only and MariaDB max_statement_time was not evaluated.

Transactions ​

begin_transaction opens a lease: one dedicated physical connection with an open transaction, scoped to the owner and handle. The lease holds the handle exclusively.

  • Scripts submitted with the lease ID run on that connection. If any statement fails or is interrupted, the lease becomes rollback-only: further statements and COMMIT are refused (CONFLICT), ROLLBACK is accepted.
  • end_transaction commits or rolls back and always discards the connection. committed/rolled_back are reported only when the server confirmed COMMIT/ROLLBACK on a lease whose session state matched after every job. On PostgreSQL and SQLite a COMMIT refused with a database error aborts the transaction, so ROLLBACK follows and is reported as rolled back only if confirmed. On MySQL/MariaDB that abort is not proven, so a refused COMMIT is unknown (commitSent: true, no ROLLBACK sent; fixture: ER 1290 under read_only). Everything else is unknown, with commitSent and rollbackSent saying whether COMMIT or ROLLBACK was ever attempted (set just before sending, so a connection lost before the bytes left still reports it; neither says the server received it).
  • PostgreSQL COMMIT (R-10). A plain COMMIT on an aborted transaction block is answered OK with command tag ROLLBACK, which SQLx reports as success. StoneQL therefore sends SAVEPOINT stoneql_commit; COMMIT as one simple-query message: on an aborted block the savepoint fails (25P02), PostgreSQL skips the rest of the message, and the ROLLBACK that follows is reported only if confirmed; outside a block (25P01) COMMIT never runs and no ROLLBACK is sent (PostgreSQL would answer it OK with a warning), so the end is unknown. Being one message, COMMIT is still the first statement a lost reply can hit.
  • Outcomes are recorded before anything is sent. Every end path (user request, expiry, disconnect, handle expiry, renderer reload, shutdown, lost connection) records unknown for the lease, with the sent facts, at the moment the lease is removed and again just before COMMIT or ROLLBACK is sent. Only a server confirmation replaces that record. A release cut off by its 5 s bound therefore leaves unknown, never a missing outcome.
  • A lease idle for 60 s, or open for 15 min, is rolled back (reason: expired). Disconnect, renderer reload, handle expiry and shutdown interrupt running jobs and roll back open leases (2 s rollback deadline, 5 s overall bound; reason: closed). A lost lease connection ends it with unknown/connection_lost, commitSent: false, rollbackSent: false.
  • end_transaction on a lease that already ended returns the recorded outcome on every later call (unknown while an end is still in progress) and sends nothing; it is never a second COMMIT. Resolved ended outcomes (committed, rolled_back), and acknowledged unknown ones, are kept per owner: the newest 32 of each owner, so one owner's ends never evict another's, and at most 256 across all owners (the oldest goes first). An evicted outcome is answered FORBIDDEN, which the renderer reports as "treat as unknown" (R-6). Unresolved unknown outcomes are never evicted; see Unknown outcomes.
  • Disconnect and handle expiry remove the handle from the registry before releasing its work (the same order as reset and shutdown). A job or transaction submitted concurrently either is released by the close or is refused (FORBIDDEN); it never runs untracked. A job interrupted before it opened its connection never opens one. The order is tested deterministically: with the lease connection held, the release is parked while the registry is inspected (B-1).
  • The per-owner transaction count is reserved atomically before the lease connection is opened, so concurrent begin_transaction calls on different handles never exceed 2 (L-4).
  • The renderer waits up to 20 s for end_transaction (the native worst case is COMMIT 10 s + ROLLBACK 2 s + close 2 s). If that wait times out on a commit, it reports "commit outcome unknown", not a cancellation. Disconnecting with an open transaction asks first and then shows the recorded outcome.

Statement splitting ​

Statements are split on ; outside quotes, identifiers and comments. The splitter never rewrites statement text.

  • MySQL/MariaDB: '…'/"…" strings with backslash escapes, backtick identifiers, # and -- comments; /*! … */ executable comments are lexed as code. The client DELIMITER directive is honoured for routine bodies, as in the mysql CLI and phpMyAdmin.
  • PostgreSQL: $tag$…$tag$ dollar quoting, E'' escapes, nested block comments; SQL-standard BEGIN ATOMIC … END bodies stay whole.
  • SQLite: […] and backtick identifiers; a CREATE [TEMP] TRIGGER body ends only at ; END ;, as in SQLite's grammar and sqlite3_complete, so begin/end used as identifiers cannot move the boundary. The splitter is not the authority: the runtime's single-statement check is.
  • At most 100 statements and 64 KiB per script.

Statement policy ​

Refused before anything is sent (UNSUPPORTED_SQL, with the statement index known to the runtime):

  • Transaction control anywhere: BEGIN (including MariaDB BEGIN NOT ATOMIC), START TRANSACTION, COMMIT/ROLLBACK (including AND CHAIN/RELEASE), END, ABORT, XA, PREPARE TRANSACTION, and any SET statement that names autocommit in any position, case, quoting (`autocommit`, "autocommit"), comment layout or scope (SESSION, GLOBAL, @@session.). The scan covers every word of the statement, not a leading window. Use the transaction controls.
  • MySQL/MariaDB wrappers, in and out of a transaction (R-2): MariaDB SET STATEMENT … FOR <statement> (whatever the inner statement); compound statements outside a stored program (CASE, IF, LOOP, WHILE, REPEAT, FOR, and any statement starting with a label name:); and CALL, because a procedure can SET autocommit, START TRANSACTION, COMMIT or PREPARE internally (R-3). PostgreSQL CALL is unchanged.
  • MySQL/MariaDB PREPARE, EXECUTE (including MariaDB EXECUTE IMMEDIATE), DEALLOCATE PREPARE/DROP PREPARE, in and out of a transaction, also inside the wrappers above: the prepared text (for example COMMIT, DDL or SET autocommit) would be invisible to this policy.
  • MySQL/MariaDB statements that contain a further ; outside a BEGIN … END body under a custom DELIMITER. SQLx enables multi-statements, so a text-protocol fallback would otherwise run the hidden statement unchecked. Routine bodies in CREATE PROCEDURE/FUNCTION/TRIGGER/EVENT are still accepted outside a transaction.
  • Savepoints (SAVEPOINT, RELEASE, ROLLBACK TO): not offered in this slice.
  • Inside a MySQL/MariaDB transaction, an allowlist of leading keywords replaces the earlier implicit-commit denylist. Accepted: SELECT, WITH, VALUES, TABLE, SHOW, DESCRIBE/DESC, EXPLAIN (reads); INSERT, UPDATE, DELETE, REPLACE (transactional row changes); USE (changes only the default schema); CREATE TEMPORARY TABLE/DROP TEMPORARY TABLE (documented as not committing implicitly); and SET whose every assignment target is a user variable @name (no comments allowed in it). None commits implicitly or changes autocommit, and a stored function or trigger they invoke cannot COMMIT (the server refuses it). The statement must not contain ; anywhere. Everything else is refused, including DDL, LOCK, SET TRANSACTION, SET SESSION …, SET NAMES, HANDLER, DO, LOAD, MariaDB ANALYZE <statement>. PostgreSQL DDL is transactional and allowed.
  • SQLite: ATTACH, DETACH and VACUUM INTO, which reach files outside the granted database.
  • Residual (documented, covered by the session check): outside a transaction, a MySQL/MariaDB routine-DDL statement whose BEGIN … END nesting the splitter misjudges (for example begin used as an alias) could, on the text-protocol fallback, run a further statement unchecked. The prepared protocol rejects multi-statement text (ER 1064, checked on both servers), so this needs a statement the server refuses to prepare (ER 1295) as a whole; any transaction state it leaves is caught by the session check.

Read-write SQLite connections open the granted file without SQLITE_OPEN_READONLY/query_only, keep trusted_schema=OFF, cell_size_check=ON, mmap_size=0, re-verify the canonical grant at every open and wait up to 5 s on locks. SQLite may create -journal/-wal/-shm files beside the database.

Unknown outcomes: retention, acknowledgement and reload ​

Implemented (M006 blocker 3, safety contract 4.5); values PROPOSED. An unknown outcome means the server may or may not have applied the work, so the runtime keeps it until the user explicitly acknowledges it. It never turns an unknown into success or rollback.

  • What is kept. Every lease end whose outcome is unknown, and every job whose outcome is unknown (recorded by the job worker before the job's final update is visible, independently of the job record). Each record is SQL-free: the lease or job id, the connection's engine and database or SQLite file name (at most 128 characters), when it was recorded, and the facts already reported (reason, commitSent, rollbackSent; for a job the statement count, the zero-based index of the unknown statement, whether it ran in a transaction, cancellation, serverCancelSent, deadlineExceeded). No statement text, values, driver messages, host names, user names or credentials.
  • Never silently evicted. The 32-per-owner and 256-overall bounds apply only to resolved or acknowledged records. Unacknowledged unknown records are exempt and stay queryable by end_transaction. Job records are still released after the final page, after 300 s, or by a reset; the unknown outcome is not stored there.
  • Acknowledgement. acknowledge_outcome (owner-scoped, idempotent while the record exists) hides one record from the unresolved list and makes it evictable like a resolved one. It never changes the recorded outcome: end_transaction on that lease still returns the same unknown. If a still-concluding lease end records a different unknown (for example COMMIT now attempted), it must be acknowledged again. An unknown id, or another owner's, is FORBIDDEN.
  • Cap. At 16 unacknowledged unknown outcomes per owner (MAX_UNRESOLVED_OUTCOMES_PER_OWNER, PROPOSED), new jobs and new transactions are refused with UNRESOLVED_OUTCOMES before anything is sent ("acknowledge the unknown outcomes listed first"). Nothing is dropped to make room. Committing or rolling back an already open transaction is still allowed. Work admitted before the cap can still add its own outcome, so an owner holds at most 16 + 2 (open leases) + 8 (job records) unacknowledged records, plus any job a reset detached that is still ending (each bounded by its deadlines). Memory is therefore bounded per owner; the desktop host has one owner per app process.
  • Reload. The desktop host's runtime owner is created once per app process and is not rotated when a reload rotates the renderer session (host_info). list_unresolved_outcomes therefore returns the previous session's unresolved outcomes to the new renderer, and the UI lists them above every workspace until each is acknowledged. A reset (confirmed reload) also releases every job record, so the native reload guard (Connections::has_active_work: an open lease or a job record of the owner) no longer needs host-side job tracking.
  • Late outcomes after a reload (F-3). A reset waits at most RELEASE_BOUND (5 s) for interrupted jobs. A job still running then is detached: its record is released (it no longer holds reload) but it can still record an unknown after the new renderer has listed. UnresolvedOutcomes.pending counts the owner's detached jobs that have not finished; it is counted before the outcomes are read, and a job records its unknown before it is marked finished, so pending: 0 means the list is complete. While pending is above 0 the renderer lists again every second, without user action, and stops at 0 (each detached job ends within its job deadline) or on a listing error.
  • Renderer crash (F-2, macOS and Linux). When the web content process terminates (WKWebView on macOS, WebKitGTK web-process-terminated on Linux), the host does not use Tauri's default immediate reload (the reload guard would refuse it while work is active, leaving a blank window). Its handler (renderer_lost) ends the renderer session exactly as a confirmed reload's rotation does — session revoked, leases rolled back with recorded outcomes, jobs interrupted and released — and then reloads. The new renderer lists the unknown outcomes as above. Windows has no such hook (WebView2) in this build: the user restarts the app.
  • Restart (quit or crash). The desktop host keeps the unresolved records in a durable journal (below) and restores them at the next start, marked restored ("before a restart"). Closing StoneQL with live work still asks first; an outcome the server did not confirm is listed at the next start.

Durable journal (proposed, not approved) ​

Implemented for the user's 2026-10-29 instruction and shipped in v0.1.0-beta.1; approved 2026-11-17 (D025-13, A16). The heading keeps its original wording so existing links stay valid. The runtime (crates/stoneql-runtime/src/execution/journal.rs) owns the journal; the desktop host only names its directory, so the runtime stays host-independent. Registries without a journal (runtime tests, the fixture harness's main registry) stay in memory as before; the desktop host always requires one.

  • Location. <app data dir>/outcome-journal/ from Tauri's path resolver (macOS: ~/Library/Application Support/me.thixpin.stoneql/outcome-journal/). Opened once, at the first renderer bootstrap (host_info), before any session exists, so nothing can list or admit work before the records are restored. Tests always inject a temporary directory (HostServices.outcome_journal).
  • Files. unknown-outcomes.journal (the snapshot), unknown-outcomes.lock (advisory flock, held while the app runs: a second running StoneQL reports in_use and fails closed), transient unknown-outcomes.journal.tmp, and unknown-outcomes.journal.damaged-<unix seconds>-<random> for a damaged journal set aside.
  • Permissions and file safety. The directory is created 0700 (and its parent synced) and every file 0600 at creation (the umask can only narrow them). The directory is then opened O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC and validated by descriptor (fstat: a directory owned by the effective uid, no group/other bits); every later operation is relative to that descriptor (openat, renameat, linkat, unlinkat, fstatat through nix 0.31.3, which was already in the lockfile; no unsafe), so swapping the directory path afterwards cannot redirect a read or write. The lock file and journal are opened O_NOFOLLOW | O_NONBLOCK | O_NOCTTY | O_CLOEXEC and validated by descriptor (a regular file of the effective uid, no group/other bits): a symlink is refused (ELOOP), a FIFO, socket, device or directory is refused at once without blocking. Anything else is insecure and nothing is read or written. The temporary file is created O_CREAT | O_EXCL | O_NOFOLLOW after removing any leftover (a planted symlink is removed, never followed). O_NONBLOCK stays set on the regular files, where reads and writes ignore it.
  • Format (version 1). UTF-8 lines: a header {"format":"stoneql-unknown-outcomes","records":N,"version":1}, then one line per record <CRC-32 of the JSON, 8 hex> <JSON>, then end <CRC-32 of every preceding byte>. A record holds id (the lease or job id, the stable outcome id), recordedAt (Unix seconds), engine, database, inFlight, and exactly one of transaction (always unknown, with reason, commitSent, rollbackSent), job (statement count, unknown statement index, in transaction, cancellation, server cancel sent, deadline exceeded) or damage. Never SQL, parameters, values, driver messages, hosts, user names, profile names, paths or credentials (the host never receives a profile id; the database name is the only connection reference). Bounded: it holds only unacknowledged unknown outcomes (at most the 16 cap plus work admitted before it, the same bound as in memory) and in-flight work (≤ 2 leases and 8 jobs per owner); resolved and acknowledged outcomes are removed from it at once, so the 32/256 retention stays an in-memory rule. Files over 4 MiB are treated as damaged.
  • Atomic, durable writes. Every change rewrites the whole snapshot: a new temporary file (O_EXCL, O_NOFOLLOW, 0600) → sync_all (F_FULLFSYNC on macOS) → rename over the journal → sync_all on the directory. A crash leaves the previous or the new snapshot, never a mix; a leftover temporary file is ignored and replaced.
  • Write-ahead ordering.
    1. Transaction: an in-flight record (unknown, closed, nothing sent) is written before the lease's connection is opened and BEGIN is sent. A crash while it is open is restored as "still open when StoneQL quit or crashed".
    2. End: the existing "unknown recorded before send" points (take_lease, then conclude) now return whether the record is durable. COMMIT is written only after its unknown with commitSent: true is on disk. A crash between sending COMMIT and the confirmation is therefore restored with commitSent: true. A confirmed committed/rolled_back end removes the record; a crash before that removal shows the end again as unknown (errs toward showing).
    3. Job: statement 0's in-flight record (unknownStatement: 0) is written at submission, before the job exists; each later statement's record is written before that statement is sent. A crash is restored as "statement N may have been sent; the ones before it were sent". The final unknown facts replace it before the job's final update is visible; any other outcome removes it.
    4. Acknowledgement: the record is removed durably before success is reported; if that fails nothing changes, in memory or on disk (still listed, OUTCOME_JOURNAL_UNAVAILABLE), and the failed acknowledgement never becomes durable later through another write.
    5. Every journal change (insert, replace, acknowledgement) is written first and only then applied to the journal's in-memory state; after a failed write memory keeps the last durable state. The exception is removing the record of work whose outcome is now known (a job that did not end unknown, a confirmed lease end, or work refused before anything was sent): it is applied in memory even if the write fails and completes with the next successful write, so resolved work is never written back and restored as an unknown outcome (until then a restart would still show it, erring toward showing). A failed newer fact (for example rollbackSent after ROLLBACK was attempted) therefore leaves the previous, still unknown, record on disk. If the failure came after the rename (directory fsync), the file may already hold the new state; the next successful write restores the in-memory state. A crash during the removal shows it again; an acknowledged outcome is never resurrected as acknowledged-but-lost, and an unacknowledged one is never dropped.
  • Restore. Records are restored for the host's owner of the new run, oldest first, with their ids and facts unchanged, restored: true and, for in-flight records, appExited: true. They count toward the 16 cap and are never evicted until acknowledged. end_transaction on a restored lease id returns its recorded end and sends nothing. After a restart an acknowledged outcome no longer exists (FORBIDDEN on a repeated acknowledgement).
  • Fail closed. New jobs and transactions are refused before anything is sent with OUTCOME_JOURNAL_UNAVAILABLE (additive error code) while the journal is not opened, insecure, in use, of another version, damaged and not set aside, or after a failed write (for example a full disk: admission first retries the write, so a freed disk recovers without a restart). UnresolvedOutcomes.journal (additive) names the problem (not_opened, unavailable, insecure, in_use, unsupported_version, damaged_not_preserved, write_failed) and the UI shows it above the workspaces. Read-only queries are unaffected. For an open lease, COMMIT is refused (lease left open, nothing sent) while the journal reports a problem (it first retries a failed write, so COMMIT works again once the disk is freed); if the write fails only at the COMMIT itself, COMMIT is never sent and the lease is rolled back instead (reported rolled_back with commitSent: false, and the UI says COMMIT was not sent). ROLLBACK is always allowed, and the automatic rollbacks (disconnect, expiry, reload, shutdown) always run: a lost ROLLBACK reply with COMMIT never sent cannot hide applied transaction work, and refusing it would only keep locks longer; its record is kept in memory and written with the next successful write.
  • Damage. A journal that is not exactly as written (truncated, bit flips, garbage, empty, oversized) is never deleted, truncated or overwritten: it is preserved as unknown-outcomes.journal.damaged-… by a hard link (linkat, never replacing an existing file or following a symlink; it must name the inode that was read, checked before and after linking; a copy linked by an earlier start is reused), the directory is synced, and the damaged file stays at the journal path until a durable snapshot carrying the report atomically replaces it, so a crash or a failed rewrite in between is detected again at the next start. The records whose checksums verify are restored, and a journalDamage entry (records that could not be recovered, the preserved file name) is listed until acknowledged; while it is unacknowledged new read-write work is refused. If it cannot be linked it is left in place and nothing is written (damaged_not_preserved). A journal of another format version is left untouched (unsupported_version). To recover from those, quit StoneQL and move the file out of the folder after inspecting it.
  • Costs (measured 2026-10-29, macOS ARM, local APFS SSD). Each write is three fsyncs (file F_FULLFSYNC, rename, directory), synchronous on the calling thread and under the journal lock: one at a transaction's begin, up to three at its end (unknown recorded, COMMIT/ROLLBACK attempted, final outcome), one per statement and one when a job ends. Snapshot write p50/p95/max over 200 writes: 1 record (400 B) 6.99/8.04/12.01 ms; 16 records (5.2 KB) 9.97/12.00/17.29 ms; 26 records, the per-owner bound (8.5 KB) 10.87/12.97/14.94 ms. submit_job admission with 8 concurrent submitters (25 jobs each, SELECT 1): 0.02/0.13/0.27 ms without a journal, 72.1/88.0/104.2 ms with it (writes serialize on the journal lock). list_unresolved_outcomes: 0.04 ms idle, but 11.0/184.8/337.7 ms while another thread writes back to back (it waits for the journal lock, which the writer re-acquires first); acknowledge_outcome 14.1/16.1/16.1 ms. Rerun: cargo test --locked -p stoneql-runtime --lib perf_journal -- --ignored --nocapture. Not redesigned (no asynchronous persistence).
  • Limits. Unix (flock/openat) on macOS and Linux; a separate Windows port (execution/journal/windows.rs: reparse-point refusal, the directory held open without delete sharing, LockFileEx, temp file and rename) enables read-write on Windows with two accepted gaps: no ownership/ACL check, and no directory fsync or write-through rename, so the rename is not guaranteed to survive a power loss. Same-user processes can still read or replace the files (as with other per-user data); components above the journal directory are resolved normally (only the final component is opened no-follow). Wrong-owner refusal is unit-tested against a different uid, not with a real foreign file (needs root). Where hard links are unsupported a damaged journal cannot be preserved and stays in place (fails closed). The lock is advisory: only StoneQL honours it. A .damaged-* copy whose report was acknowledged stays in the folder (never deleted); copies are not otherwise rescanned at startup. npm run desktop:smoke and desktop:run use the production path and create the journal folder in the developer's app data directory; automated tests always use temporary directories.

SQL import (M007 d5, MySQL/MariaDB) ​

Approved scope (A20, 2026-11-16): MySQL and MariaDB read-write handles; the host refuses other engines with UNSUPPORTED_CAPABILITY. Commands: pick_import_file (native open dialog → one-shot, session-scoped grant naming the canonical regular file; revoked on renderer reset), start_sql_import (handle + grant) and sql_import_status; cancel with cancel_job.

  • One snapshot. start_sql_import consumes the grant, checks that the path is still the same canonical regular file, refuses it above the file limit from its size, and reads it once. The runtime validates that buffer (UTF-8, size, statement count, per-statement size, script::check_one with no lease plus USE and LOAD DATA/XML LOCAL refusals) with the job splitter (split_each, which yields statements with their byte ranges, so only one statement's words are held). A refusal names the statement number and line and nothing is sent. The import then runs from the same buffer and ranges: the file is never read again.
  • Execution. A job record with compact counters (no per-statement reports): admission, the handle's exclusive work permit, write-ahead journaling of every statement, cancel/KILL grace, release on disconnect, renderer reset and reload protection are the job path's. Statements run one at a time under autocommit on a never-pooled connection; result sets are driven to their end and discarded. It stops at the first failure (index, line, SQLSTATE/constraint). A statement interrupted or cut off is unknown and recorded in the unknown-outcome journal; the R-3 session-state check applies at the end. The final status (done) releases the record.
  • Limits (as shipped in v0.1.0-beta.1 / 970ade2): file 1024 MiB, statement 16 MiB, 1,000,000 statements, 300 s per statement, 2 h per import. On 2026-11-17 lower values were approved (100,000 statements, 15 MiB per statement, 1 GiB per file); the code does not apply them yet. The renderer waits up to 120 s for start_sql_import (read + validation).
  • Benchmark (npm run bench:sql-import; release build on Apple M5, Docker MySQL 8.4.6 / MariaDB 11.4.8 with 1 GiB memory caps, journal attached): reading takes ~0.2 s and validating ~1.7 s per GiB; client peak RSS ≈ file size + ~30 MiB; large statements (1–4 MiB) import at 27–35 MiB/s (1 GiB in 29–38 s); 64 KiB statements at ~6.5 MiB/s; 1 KiB statements at ~115–118 statements/s, of which ~7.7 ms per statement is the durable write-ahead journal (~1,000–1,340 statements/s without it). Statements just under 16 MiB succeeded on both servers (MariaDB's default max_allowed_packet is 16 MiB). In one run the MySQL container was OOM-killed by its 1 GiB memory cap during the 1 GiB import after earlier cases; the case passed in a fresh container.

Limits ​

All values are defined once in ExecutionLimits (crates/stoneql-runtime/src/execution.rs). They were written as PROPOSED; on 2026-11-17 the user approved them as implemented at 970ade2 (A16), except the SQL import statement limits, for which lower values were approved but are not implemented yet (see above).

LimitValue
Running jobs per handle / queue depth1 / 0 (BUSY)
Job records per owner (running + unread)8; finished records released after 300 s (B-7). This also bounds buffered bytes per owner: a record holds at most 2 unread pages plus the page its worker is about to send, so typically 8 × 3 × 256 KiB = 6 MiB, and 24 MiB when single rows fill 1 MiB pages. No separate byte cap.
Open transactions1 per handle, 2 per owner
Statements / script size100 / 64 KiB
Statement deadline30 s default, 300 s maximum
Job deadline600 s
Rows per result set1,000 default, 100,000 maximum
Bytes per result set / per job1 MiB / 4 MiB serialized rows; later sets truncated and flagged
Result sets per job16 (further sets reported without data)
Result metadata256 KiB per result set
Page500 rows or 256 KiB; 2 buffered pages
Fetch long-poll1 s
Abandoned consumer60 s parked on a full buffer → interrupted
Cancel grace / cancel connect1.5 s / 1 s
Lease idle / maximum lifetime60 s / 15 min
Ended-lease outcomes kept32 per owner, 256 overall (resolved or acknowledged only; unacknowledged unknown outcomes are never evicted)
Unacknowledged unknown outcomes per owner16 (restored ones included), then new jobs and transactions are refused (UNRESOLVED_OUTCOMES) until some are acknowledged (PROPOSED)
Unknown-outcome journal4 MiB read limit; holds only unacknowledged unknown and in-flight records (PROPOSED)
PostgreSQL statement_timeoutstatement deadline − 1 s (at most half the deadline; never 0)
COMMIT / ROLLBACK deadline10 s / 2 s
Release on close/reset/shutdown5 s overall
SQLite read-write busy timeout5 s

The handle lifetime (3600 s) is still defined in two places (desktop NativeSession and the expires_after_seconds reply); not changed here.

Verification ​

CommandCovers
npm run rust:testSplitter/policy units (autocommit anywhere, PREPARE/EXECUTE, custom-DELIMITER smuggling, MariaDB SET STATEMENT/compound/CALL refusals, in-lease allowlist, SQLite trigger begin/end identifiers); R-1 text with more than one SQLite statement never runs, in and out of a lease (including the review's trigger input fed past the splitter); R-3 a diverged SQLite session is unknown and its lease end sends nothing; release cut off by its 5 s bound records unknown (disconnect, reset, shutdown); unknown recorded before COMMIT/ROLLBACK is sent; disconnect racing submit/begin (60 rounds); removal-before-release order for disconnect and handle expiry (B-1, held lease connection); concurrent begins never exceed 2 leases per owner (L-4); an interrupt still in flight never leaves its lease connection in use (L-8, test-only stalled interrupt); the 9th undrained job is refused (B-7); resolved ended outcomes kept per owner (R-6); unacknowledged unknown outcomes (lease ends and jobs) survive eviction pressure from this and other owners, acknowledgement hides without changing the outcome and is owner-scoped and idempotent, the unresolved cap refuses new jobs and transactions without dropping anything, and a job unknown survives the reset that releases its record (P3); rows read after an interrupt flagged resultsWithheld (B-11); SQLite owner isolation, BUSY, constraint failures, exact values, cancel/deadline (5 latency samples < 2 s), commit/rollback/rollback-only, close and expiry rollback, 100 lease/fault cycles with no session-state leak, backpressure buffer bound
npm run desktop:testNative gate: production builds have the gate on (A15; the test asserts it); a host built with the gate off refuses read_write for MySQL, MariaDB, PostgreSQL, SSH and SQLite before Keychain/network and reports readWriteSql: false. With the gate enabled by test injection: job and transaction commands through the Tauri handlers on SQLite (strict decoding, ownership, BUSY, cancel, commit/rollback, repeat end returns the recorded outcome, disconnect and reload rollback queryable by lease id); an unknown job from one renderer session is listed to the next session after the reload rotation (and a third), never to another app instance (owner), until acknowledged; acknowledgement is idempotent and cannot carry an outcome
npm run test:executionDisposable TLS MySQL 8.4.6, MariaDB 11.4.8 and PostgreSQL 17.6 fixtures, each with a test-owned loopback fault relay (tools/tcp-fault-relay.mjs) and a server statement log (MySQL/MariaDB general_log; PostgreSQL csvlog with log_statement = all for the writer role only). All three engines: 30 blocked-UPDATE cancels (interrupt delivered, connection discarded, executed once), bulk INSERT…SELECT cancel, failed interrupt connection (PostgreSQL: the server statement_timeout ends the abandoned statement before the client deadline), lost COMMIT/ROLLBACK replies at n = 50 for sever_on_reply (Contract 7.1) and sever (7.2) plus n = 3 drop_s2c (each waits out the 10 s COMMIT deadline), never re-sent. MySQL/MariaDB: COMMIT refused with ER 1290 under read_only is unknown with no ROLLBACK. PostgreSQL: server statement_timeout before the client deadline (10 autocommit samples timed against the deadline, in-lease timeout → rollback-only with the aborted block observed on the server and a confirmed ROLLBACK, cancel before the timeout, client-deadline backstop after SET statement_timeout = 0, an external pg_cancel_backend not reported as a deadline, no writer session left in a transaction); session check and checked COMMIT on real sessions (healthy, aborted, outside a block; plain COMMIT on an aborted block answered OK as the positive control). Also: exact values, scripts and procedure result sets, DDL partial outcome, unique/FK failures, commit/rollback/rollback-only, connection killed mid-transaction, a lost-COMMIT unknown (sever_on_reply) still listed and queryable after 288 confirmed lease ends (more than both retention bounds; the oldest confirmed end evicted), every other unknown checked as listed before the harness acknowledges it, 100 cancel samples (p50/p95/max), statement deadline, 100 fault/transaction cycles with session-state probes and server session count back to baseline, backpressure, real 60 s lease expiry. MySQL/MariaDB also: SET STATEMENT … FOR COMMIT/CREATE TABLE/PREPARE, CASE … COMMIT; END CASE, CASE … SET …; END CASE and CALL of procedures doing SET autocommit = 0/START TRANSACTION refused in and out of a lease with zero general-log rows (all command types); the runtime's session check reports a mismatch for real sessions left by those procedures (whose INSERT reported 1 row and was gone after close) and for a transaction committed behind a lease; and MySQL's killed SLEEP() reported succeeded with its row flagged withheld. Reports in artifacts/m006/ (ignored); copies in .ref/planning/m006-evidence/execution/
npm run test:browserRead-write UI in both themes against a stubbed host: gate off shows the option disabled; failed job never says "executed successfully"; disconnect with an open transaction confirms and shows its outcome; unknown outcomes recorded before a confirmed reload are listed after it, stay through further reloads and disappear only when each is acknowledged; an unknown a detached job records after the new renderer listed appears without user action and polling stops when nothing is pending; outcomes from before a restart are labelled so (and an open transaction or running job interrupted by the exit described as such), apart from those before a reload; a damaged-journal entry and a journal write failure are shown and cleared
Journal (npm run rust:test, desktop:test, test:execution)Runtime execution::journal::tests (CRC check value; round trip with modes 0700/0600; truncation at every byte offset never accepted and never inventing a record; every single-bit flip rejected; truncated/flipped/garbage/empty/oversized journals preserved byte-for-byte (hard link, never replacing an existing file) with verified records restored and the damage reported across restarts; another version left untouched; a torn temporary write leaves the previous snapshot; an injected full-disk failure reported and healed by the next write; group/world-accessible directory or file, symlinked file or directory, wrong uid, wrong file types refused untouched; a second open is in_use; symlinks, FIFOs (bounded by a 5 s timeout), sockets and directories at the journal or lock path refused promptly with their targets untouched; a symlink at the temporary path removed, never followed; a directory path swapped after validation never written; a journal swapped after it was read never preserved in its place; a failed put or removal changes nothing in memory or on disk and never becomes durable later; a rewrite failing after the damaged journal was preserved (planted directory at the temporary path) leaves the damage detected at every later start with its verified records restored, one preserved copy reused; read-only directory fails closed without destroying records; a child process SIGKILLed mid-write 12 times always leaves an intact snapshot) and execution::tests::j1…j11 (crash and restart restores an open lease, a lost-COMMIT end and an unknown job with unchanged ids and facts; acknowledgement durable before reported, a failed one changes nothing across restarts; restored outcomes count toward the cap and are never evicted; unusable journal refuses jobs and transactions before anything is sent while read-only queries work, and recovers after the disk is freed; COMMIT refused while the journal fails and never sent if the write fails at COMMIT, its commitSent record on disk before COMMIT is sent; a statement is never sent unless journaled; a canary scan of all journal files finds no SQL, values, identifiers or paths; a damaged journal refuses new work until acknowledged, also when the rewrite after preserving it failed; a failed acknowledgement stays unacknowledged across later writes and a restart, while a failed removal of resolved work completes with the next successful write and is not restored after a restart). Desktop reload_guard.rs restart test (journal shared by app instances: the second instance while the first runs fails closed with in_use; restart on the crash image restores the open transaction and the unknown job with the same facts; acknowledgement persists across a further restart). Fixture unknownOutcomeRetention.journalRestart (all three engines: a lost-COMMIT unknown journaled, the registry dropped without shutdown, a new registry restores it with unchanged facts)
npm test (liveJobs.test.ts)A statement with resultsWithheld marks its result sets truncated and the notice says the rows shown are incomplete; autocommit success says "(autocommit)", never "(committed)"; unknown with every statement succeeded is described as a session-state mismatch; unknown transaction ends say COMMIT/ROLLBACK "may have been sent"

Gates ​

  • Read-write gate: on in builds (READ_WRITE_SQL_ENABLED = true) since the user approved A15 on 2026-11-17: Direct for every network engine, and SSH for MySQL/MariaDB. Changing it is a reviewed code change, not a setting.
  • SSH: read-write over SSH is enabled for MySQL/MariaDB (A15); for PostgreSQL it is refused before any network access (and before Keychain resolution in the desktop host), in both the runtime and the desktop host. Cancel connections need a forwarding channel and the tunnel admits four (pool, job or lease connection and cancel use at most three). With every forward busy the cancel connection is refused at once and the job ends cancellation: requested with an unknown outcome within the grace period, its connection discarded; a discarded connection releases its forward immediately. Fixture-tested (npm run test:ssh); enabling PostgreSQL read-write over SSH is a separate user decision.
  • On 2026-11-17 the user approved D025-11 to D025-13 and the ExecutionLimits values as implemented (A16), and the additive v1 contract versioning for these DTOs (D003); the approved SQL import statement limits are not implemented yet (see above).
  • Measured on macOS ARM only; Linux/Windows and GUI-driven native runs are unexecuted.
  • Receive bounds: 2 MiB per packet (MySQL/MariaDB) and, since A8 (2026-11-16), 2 MiB per backend message (PostgreSQL); SQLite has no network messages.
  • MySQL KILL QUERY on SLEEP() returns success rather than an error; such a statement reports succeeded, with resultsWithheld because its row was read after the interrupt.
  • When the cancel connection cannot be opened, the statement is abandoned after the 1.5 s grace and reported unknown with cancellation requested. Fixture evidence shows the server keeps running such a statement (MySQL and MariaDB did not notice the dropped client), so it may still apply later; the UI says so. PostgreSQL's server statement_timeout ends it server-side before the client deadline (fixture: 5 s deadline, 4 s server timeout); MySQL/MariaDB have no server timeout.

StoneQL v0.1.0-beta.3 · Public beta for macOS, Windows and Linux · Keep backups and verify important changes on the server.