diff --git a/packages/albedo_sqlite/gleam.toml b/packages/albedo_sqlite/gleam.toml index bf49a2c8c..a1a8b5fbc 100644 --- a/packages/albedo_sqlite/gleam.toml +++ b/packages/albedo_sqlite/gleam.toml @@ -1,6 +1,6 @@ name = "albedo_sqlite" version = "0.1.0" -description = "SQLite in WAL mode for one writer: whether a connection is in a transaction, a pool of read-only connections that queues callbacks, and a checkpointer that backfills the WAL apart from commits" +description = "SQLite in WAL mode for one writer: whether a connection is in a transaction, a close that is complete when it returns, a pool of read-only connections that queues callbacks, and a checkpointer that backfills the WAL apart from commits" # The albedo repository's licence; see robot-docs/workspace-packages.md. licences = ["AGPL-3.0-only"] gleam = ">= 1.19.0" diff --git a/packages/albedo_sqlite/src/albedo_sqlite.gleam b/packages/albedo_sqlite/src/albedo_sqlite.gleam index b35836575..321de9fe4 100644 --- a/packages/albedo_sqlite/src/albedo_sqlite.gleam +++ b/packages/albedo_sqlite/src/albedo_sqlite.gleam @@ -1,6 +1,7 @@ //// What a SQLite connection reports about itself that sqlight does not -//// expose. A `sqlight.Connection` is esqlite's connection, so the binding -//// reads it directly. +//// expose, and a close that is complete when it returns. A +//// `sqlight.Connection` is esqlite's connection, so the binding reads it +//// directly. import sqlight @@ -8,3 +9,28 @@ import sqlight /// autocommit mode. @external(erlang, "esqlite3", "get_autocommit") pub fn autocommit(connection: sqlight.Connection) -> Bool + +/// Closes `connection` before it returns. Call it from the process that ran +/// the connection's queries, and use it instead of `sqlight.close`. +/// +/// esqlite finalizes a statement only when the garbage collector frees its +/// term, and `sqlight.query` leaves every statement to it. `sqlight.close` +/// calls `sqlite3_close_v2`, which keeps a connection with a statement not +/// yet finalized open until that statement is. The connection's file +/// handles and locks stay open meanwhile. If it is the database's last +/// connection, its checkpoint and its removal of the `-shm` and then the +/// `-wal` file run whenever a later collection or the process's exit frees +/// the statement. A reader of the files at that moment can find a log that +/// holds commits but has no index. +/// +/// A full collection of the calling process first frees each statement it +/// no longer references, so the close happens here. A statement the caller +/// still holds keeps the connection open, as before. sqlight never hands +/// one out. +pub fn close(connection: sqlight.Connection) -> Result(Nil, sqlight.Error) { + let _ = garbage_collect() + sqlight.close(connection) +} + +@external(erlang, "erlang", "garbage_collect") +fn garbage_collect() -> Bool diff --git a/packages/albedo_sqlite/src/albedo_sqlite/checkpoint.gleam b/packages/albedo_sqlite/src/albedo_sqlite/checkpoint.gleam index cc42a19ae..bd13e0542 100644 --- a/packages/albedo_sqlite/src/albedo_sqlite/checkpoint.gleam +++ b/packages/albedo_sqlite/src/albedo_sqlite/checkpoint.gleam @@ -7,6 +7,7 @@ //// process that started it exits. import albedo_clock +import albedo_sqlite import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/erlang/atom @@ -173,7 +174,7 @@ pub fn start( ) { Error(error) -> { - let _ = sqlight.close(db) + let _ = albedo_sqlite.close(db) Error(error.message) } Ok(_) -> { @@ -204,13 +205,13 @@ pub fn start( } Close(reply) -> { let _ = backfill(state.db) - let _ = sqlight.close(state.db) + let _ = albedo_sqlite.close(state.db) process.send(reply, Nil) actor.stop() } WriterStopped -> { let _ = backfill(state.db) - let _ = sqlight.close(state.db) + let _ = albedo_sqlite.close(state.db) actor.stop() } } @@ -304,7 +305,8 @@ pub fn owner(checkpoint: Checkpoint) -> process.Pid { pid } -/// Backfill what is left, close the connection, and stop. +/// Backfill what is left, close the connection, and stop. The connection is +/// closed when this returns. pub fn close(checkpoint: Checkpoint) -> Nil { let Checkpoint(subject) = checkpoint let reply = process.new_subject() diff --git a/packages/albedo_sqlite/src/albedo_sqlite/readers.gleam b/packages/albedo_sqlite/src/albedo_sqlite/readers.gleam index ae209da7c..801d37060 100644 --- a/packages/albedo_sqlite/src/albedo_sqlite/readers.gleam +++ b/packages/albedo_sqlite/src/albedo_sqlite/readers.gleam @@ -5,6 +5,7 @@ //// exits. import albedo_process +import albedo_sqlite import gleam/erlang/process.{type Subject} import gleam/int import gleam/list @@ -168,6 +169,7 @@ pub fn run(pool: Pool, run: fn(sqlight.Connection) -> a) -> Result(a, Nil) { } /// Run the callbacks already queued, then close every connection and stop. +/// Each connection is closed when this returns. /// A callback queued after `close` never runs, and its `run` answers /// `Error(Nil)` once the pool stops. The caller waits at most five seconds /// and crashes after that. @@ -200,7 +202,7 @@ fn start_reader(path: String) -> Result(Subject(ReaderMessage), String) { case sqlight.exec("PRAGMA query_only=ON; PRAGMA cache_size=-128", db) { Ok(_) -> Ok(actor.initialised(db) |> actor.returning(subject)) Error(error) -> { - let _ = sqlight.close(db) + let _ = albedo_sqlite.close(db) Error(error.message) } } @@ -214,7 +216,7 @@ fn start_reader(path: String) -> Result(Subject(ReaderMessage), String) { actor.continue(db) } Stop(reply) -> { - let _ = sqlight.close(db) + let _ = albedo_sqlite.close(db) process.send(reply, Nil) actor.stop() } diff --git a/packages/albedo_sqlite/test/albedo_sqlite_test.gleam b/packages/albedo_sqlite/test/albedo_sqlite_test.gleam index ec35ecee8..d8c9aa1e5 100644 --- a/packages/albedo_sqlite/test/albedo_sqlite_test.gleam +++ b/packages/albedo_sqlite/test/albedo_sqlite_test.gleam @@ -1,7 +1,9 @@ -//// `autocommit` follows a connection into and out of a transaction, the read -//// pool answers queued reads on read-only connections, and the checkpointer, which a writer's commits never wait on, leaves every -//// committed frame in the database file when it closes. Each runs against -//// a real database in a scratch directory the test removes. +//// `autocommit` follows a connection into and out of a transaction, `close` +//// is complete when it returns, the read pool answers queued reads on +//// read-only connections, and the checkpointer, which a writer's commits +//// never wait on, leaves every committed frame in the database file when it +//// closes. Each runs against a real database in a scratch directory the test +//// removes. import albedo_sqlite import albedo_sqlite/checkpoint @@ -28,10 +30,44 @@ pub fn autocommit_ends_inside_a_transaction_test() -> Nil { let assert False = albedo_sqlite.autocommit(connection) let assert Ok(Nil) = sqlight.exec("COMMIT", connection) let assert True = albedo_sqlite.autocommit(connection) - let assert Ok(Nil) = sqlight.close(connection) + let assert Ok(Nil) = albedo_sqlite.close(connection) Nil } +/// esqlite finalizes a statement only when the garbage collector frees it, +/// and `sqlight.close` leaves a connection with one outstanding open. The +/// heap here is large enough that the query cannot trigger a collection, so +/// its statement is still outstanding at the close. The close must still be +/// the database's last: it moves the log into the file and removes the +/// `-wal` and `-shm` files before it returns. +pub fn close_is_complete_with_a_statement_left_to_the_collector_test() -> Nil { + use path <- database + let min_heap_size = atom.create("min_heap_size") + let previous = process_flag(min_heap_size, 1_000_000) + let _ = garbage_collect() + // Loading a module collects the loading process's garbage, so the first + // round, which loads what it calls, may free the statement before the + // close. The second round runs with all of it loaded. + let _ = query_then_close(path <> ".load") + let left = query_then_close(path) + let _ = process_flag(min_heap_size, previous) + assert left == [] +} + +/// Queries a new WAL database at `path`, closes it, and answers which of its +/// `-wal` and `-shm` files are left. +fn query_then_close(path: String) -> List(String) { + let assert Ok(connection) = sqlight.open(path) + let assert Ok(Nil) = + sqlight.exec( + "PRAGMA journal_mode=WAL; CREATE TABLE items (n INTEGER); INSERT INTO items VALUES (1), (2), (3)", + connection, + ) + assert count(connection) == Ok(3) + let assert Ok(Nil) = albedo_sqlite.close(connection) + list.filter(["-wal", "-shm"], fn(suffix) { is_file(path <> suffix) }) +} + pub fn the_pool_reads_and_refuses_writes_test() -> Nil { use path <- database let assert Ok(writer) = sqlight.open(path) @@ -52,7 +88,7 @@ pub fn the_pool_reads_and_refuses_writes_test() -> Nil { }) readers.close(pool) assert readers.run(pool, fn(db) { count(db) }) == Error(Nil) - let _ = sqlight.close(writer) + let _ = albedo_sqlite.close(writer) Nil } @@ -71,8 +107,8 @@ pub fn closing_backfills_every_commit_test() -> Nil { // An immutable connection reads the database file alone, never the WAL. let assert Ok(file) = sqlight.open("file:" <> path <> "?immutable=1") assert count(file) == Ok(3) - let _ = sqlight.close(file) - let _ = sqlight.close(writer) + let _ = albedo_sqlite.close(file) + let _ = albedo_sqlite.close(writer) Nil } @@ -103,6 +139,15 @@ fn database(run: fn(String) -> Nil) -> Nil { Nil } +@external(erlang, "erlang", "process_flag") +fn process_flag(flag: Atom, value: Int) -> Int + +@external(erlang, "erlang", "garbage_collect") +fn garbage_collect() -> Bool + +@external(erlang, "filelib", "is_file") +fn is_file(path: String) -> Bool + @external(erlang, "erlang", "unique_integer") fn unique_integer(modifiers: List(Atom)) -> Int diff --git a/robot-docs/contributing.md b/robot-docs/contributing.md index 1015cf5fa..f8e2ca922 100644 --- a/robot-docs/contributing.md +++ b/robot-docs/contributing.md @@ -204,6 +204,15 @@ schedule. The stop callback runs on the writer and must not call the store. Keep resource shutdown within the store's lifecycle. See [`store.gleam`](../src/albedo/harness/sdk/store.gleam). +`store.close` returns once every connection of the store is closed, so the next +open or the [startup check](migrations.md#refusal) finds the database's files +final. Close a SQLite connection you open yourself with +[`albedo_sqlite.close`](workspace-packages.md), from the process that ran its +queries. Do not use `sqlight.close`. It leaves a connection open while a +statement waits for the garbage collector. If that is the database's last +connection, its close removes the `-shm` and `-wal` files later, while other +code may be reading them. + For schema changes, preserve the [foreign-key indexing rule](migrations.md#foreign-key-indexes). Unindexed child lookups can make deletion block the writer. diff --git a/robot-docs/migrations.md b/robot-docs/migrations.md index 50ade02f9..a3d4cace4 100644 --- a/robot-docs/migrations.md +++ b/robot-docs/migrations.md @@ -119,10 +119,18 @@ times. The read is bounded at 30 seconds. A read that takes longer is killed, and the check fails. -The read runs in a process of its own, and the check returns once that process -has exited. `sqlight.close` leaves a connection open until its statements are -garbage collected. A read-only connection left open makes SQLite refuse the -daemon's own writes to the same file. +The read closes its connection with +[`albedo_sqlite.close`](workspace-packages.md), which is complete when it +returns. A read-only connection left open makes SQLite refuse the daemon's own +writes to the same file. The read runs in a process of its own so the bound can +kill it, and the check returns once that process has exited. + +The check reads files that a store closed just before it, as +[`migration_test`](../test/harness/migration_test.gleam) does. `store.close` +returns once each of its connections is closed. The last of them moves the log +into the database and removes the `-shm` file and then the `-wal` file. A check +that ran between the two removals would find a log with commits but no index, +and refuse the home. [`migration_test`](../test/harness/migration_test.gleam) checks that the three files are byte-identical after the check, for a stopped home and for one whose diff --git a/robot-docs/workspace-packages.md b/robot-docs/workspace-packages.md index c8c84a9ab..53b19be9c 100644 --- a/robot-docs/workspace-packages.md +++ b/robot-docs/workspace-packages.md @@ -95,12 +95,18 @@ package's name, so the module `albedo_process/memo` is the atom [`albedo_sqlite.autocommit`](../packages/albedo_sqlite/src/albedo_sqlite.gleam) tells whether a connection is outside every transaction, binding the esqlite driver under sqlight, which the package declares for it. - `albedo_sqlite/readers` is a pool of `query_only` connections that runs queued - callbacks in arrival order, and `albedo_sqlite/checkpoint` backfills the WAL - on a connection of its own with passive checkpoints, never opening the `-shm` - file. Both stop with the process that started them, and a failed start is - gleam_otp's `actor.StartError`. The pool's process is labelled - `albedo_sqlite_readers`. + [`albedo_sqlite.close`](../packages/albedo_sqlite/src/albedo_sqlite.gleam) + closes a connection before it returns. esqlite finalizes a statement only when + the garbage collector frees it, and `sqlight.close` leaves a connection open + while one is outstanding, so `close` collects the calling process's garbage + first. Close every connection with it, from the process that ran its queries, + rather than with `sqlight.close`. `albedo_sqlite/readers` is a pool of + `query_only` connections that runs queued callbacks in arrival order, and + `albedo_sqlite/checkpoint` backfills the WAL on a connection of its own with + passive checkpoints, never opening the `-shm` file. Both stop with the process + that started them, and a failed start is gleam_otp's `actor.StartError`. Each + one's `close` returns once its connections are closed. The pool's process is + labelled `albedo_sqlite_readers`. - [`albedo_image`](../packages/albedo_image/src/albedo_image.gleam): what a canonical base64 PNG, JPEG or WebP says about itself. `inspect` reads its MIME type, dimensions and decoded size under a caller's byte limit and checks the diff --git a/src/albedo/daemon/server.gleam b/src/albedo/daemon/server.gleam index d57274cbe..fc121adef 100644 --- a/src/albedo/daemon/server.gleam +++ b/src/albedo/daemon/server.gleam @@ -55,6 +55,7 @@ import albedo/harness/worktree import albedo_clock import albedo_env import albedo_process/within +import albedo_sqlite import gleam/bit_array import gleam/bool import gleam/bytes_tree @@ -1020,7 +1021,7 @@ pub fn claim_home(home: String) -> Result(Nil, sqlight.Error) { { Ok(_) -> Ok(lifecycle.hold(connection)) Error(error) -> { - let _ = sqlight.close(connection) + let _ = albedo_sqlite.close(connection) Error(error) } } diff --git a/src/albedo/daemon/storage_cli.gleam b/src/albedo/daemon/storage_cli.gleam index 8799cfc0a..f418acbcd 100644 --- a/src/albedo/daemon/storage_cli.gleam +++ b/src/albedo/daemon/storage_cli.gleam @@ -4,6 +4,7 @@ import albedo/daemon/disk import albedo/daemon/server import albedo/harness/kernel/cell_storage import albedo/harness/sdk/store +import albedo_sqlite import gleam/dict import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode @@ -284,7 +285,7 @@ fn with_database( }), ) let outcome = run(connection) - let _ = sqlight.close(connection) + let _ = albedo_sqlite.close(connection) outcome } diff --git a/src/albedo/harness/sdk/migration.gleam b/src/albedo/harness/sdk/migration.gleam index 3b73848fe..9a6733b4c 100644 --- a/src/albedo/harness/sdk/migration.gleam +++ b/src/albedo/harness/sdk/migration.gleam @@ -9,6 +9,7 @@ import albedo/harness/sdk/store import albedo_file +import albedo_sqlite import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/erlang/atom @@ -98,7 +99,7 @@ fn read_as_found( alone(read_timeout_ms, fn() { use db <- result.try(open(database, options)) let recorded = read_record(db) - let _ = sqlight.close(db) + let _ = albedo_sqlite.close(db) recorded }) case read, attempts > 1 && read_only(database) != Ok(options) { @@ -141,7 +142,7 @@ pub fn back_up( use _ <- result.try(rename(partial, backup)) store.transaction(db, fn() { list.try_each(pending, record(db, _)) }) } - let _ = sqlight.close(db) + let _ = albedo_sqlite.close(db) done }) case copied { @@ -199,11 +200,11 @@ fn open( } /// Runs `use_home` in a process of its own and returns once that process is -/// gone. Closing a connection with statements not yet garbage collected -/// leaves it open until they are, and a connection left open makes SQLite -/// refuse or reorder the daemon's own writes to the same file. A process's -/// statements go with it. -/// One that takes longer than `timeout_ms` is killed, and the check fails. +/// gone. One that takes longer than `timeout_ms` is killed, and the check +/// fails. A connection left open makes SQLite refuse or reorder the daemon's +/// own writes to the same file. `use_home` closes its connection with +/// `albedo_sqlite.close`. A killed process's connection closes when the +/// process's exit frees it. fn alone( timeout_ms: Int, use_home: fn() -> Result(a, String), diff --git a/src/albedo/harness/sdk/store.gleam b/src/albedo/harness/sdk/store.gleam index 837544f25..e0ed6c75c 100644 --- a/src/albedo/harness/sdk/store.gleam +++ b/src/albedo/harness/sdk/store.gleam @@ -78,7 +78,7 @@ pub fn start(path: String, schema: String) -> Result(Store, actor.StartError) { } case prepared { Error(error) -> { - let _ = sqlight.close(db) + let _ = albedo_sqlite.close(db) Error(error) } Ok(resources) -> { @@ -171,7 +171,7 @@ fn close_connections( readers.close(connections.readers) checkpoint.close(connections.checkpoint) }) - let _ = sqlight.close(db) + let _ = albedo_sqlite.close(db) process.send(reply, Nil) actor.stop() } @@ -366,6 +366,10 @@ pub fn owner(store: Store) -> process.Pid { pid } +/// Stops the store's users, then closes its read pools, its checkpointer and +/// its writer, and returns once every connection is closed. A file database +/// with no other connection is then whole: its last close moved the log into +/// it and removed the `-wal` and `-shm` files. pub fn close(store: Store) -> Nil { let Store(subject, _, _) = store actor.call(subject, 5000, Close) diff --git a/test/daemon/migration_names_test.gleam b/test/daemon/migration_names_test.gleam index 329dfdbbb..a6caf4178 100644 --- a/test/daemon/migration_names_test.gleam +++ b/test/daemon/migration_names_test.gleam @@ -5,6 +5,7 @@ import albedo/daemon/migrations import albedo/daemon/registry import albedo/harness/extensions import albedo/harness/sdk/migration +import albedo_sqlite import gleam/list import gleeunit/should import sqlight @@ -26,7 +27,7 @@ pub fn a_retired_name_is_known_test() -> Nil { let path = temporary_database() let assert Ok(db) = sqlight.open(path) let assert Ok(_) = migration.record(db, "removed_extension_rewrite") - let assert Ok(_) = sqlight.close(db) + let assert Ok(_) = albedo_sqlite.close(db) migration.unknown(path, registry.known_migrations([], [])) |> should.equal(Ok(["removed_extension_rewrite"])) migration.unknown( diff --git a/test/daemon/store_test.gleam b/test/daemon/store_test.gleam index 1363707f0..c2fb944c1 100644 --- a/test/daemon/store_test.gleam +++ b/test/daemon/store_test.gleam @@ -1,7 +1,8 @@ //// Snapshot isolation and connection-owner death need gates inside store callbacks. //// HTTP tests cannot stop an individual connection owner or interleave snapshot reads, -//// nor read at the moment a store closes. Shutdown registration ordering needs a -//// suspended writer with queued runs and registrations, which HTTP cannot arrange. +//// nor read at the moment a store closes, nor look at its files the moment +//// `close` returns. Shutdown registration ordering needs a suspended writer +//// with queued runs and registrations, which HTTP cannot arrange. import albedo/harness/sdk/store import gleam/dynamic @@ -264,6 +265,35 @@ pub fn file_uri_uses_the_same_database_for_readers_test() -> Nil { cleanup(path) } +/// Each connection runs queries whose statements wait for the garbage +/// collector, and a connection closed with one outstanding stays open after +/// `sqlight.close`. `close` returns only once all of them are closed, so the +/// last close has already moved the log into the database and removed its +/// `-wal` and `-shm` files. The startup check for breaking migrations reads +/// those files next and refuses a log with commits but no index. +pub fn a_closed_store_leaves_only_its_database_file_test() -> Nil { + let path = temporary_database() + let assert Ok(database) = store.start(path, schema) + store.write(database, "INSERT INTO samples VALUES(2)", []) + |> should.equal(Ok(Nil)) + store.query(database, count) |> should.equal(Ok(2)) + store.snapshot(database, count) |> should.equal(Ok(2)) + store.read( + database, + "SELECT COUNT(*) FROM samples", + [], + decode.field(0, decode.int, decode.success), + ) + |> should.equal(Ok([2])) + store.close(database) + list.filter(["-wal", "-shm"], fn(suffix) { is_file(path <> suffix) }) + |> should.equal([]) + cleanup(path) +} + +@external(erlang, "filelib", "is_file") +fn is_file(path: String) -> Bool + /// A schema batch spans writer calls; HTTP cannot install synthetic failing DDL. pub fn schema_batch_rolls_back_a_failed_owner_and_nested_transaction_test() -> Nil { let assert Ok(database) = store.start(":memory:", schema) diff --git a/test/harness/migration_test.gleam b/test/harness/migration_test.gleam index 4287d6a75..c17475a4f 100644 --- a/test/harness/migration_test.gleam +++ b/test/harness/migration_test.gleam @@ -9,6 +9,7 @@ import albedo/harness/sdk/migration import albedo/harness/sdk/storage import albedo/harness/sdk/store import albedo_file +import albedo_sqlite import gleam/dynamic.{type Dynamic} import gleam/dynamic/decode import gleam/erlang/atom @@ -216,7 +217,7 @@ pub fn the_check_reads_a_crashed_homes_log_without_writing_test() -> Nil { let assert Ok(_) = copy(live <> suffix, unindexed <> suffix) let assert Ok(_) = copy(live <> suffix, unreadable <> suffix) }) - let _ = sqlight.close(writer) + let _ = albedo_sqlite.close(writer) cleanup(live) let before = files(crashed) migration.unknown(crashed, []) |> should.equal(Ok(["from_the_future"])) @@ -253,7 +254,7 @@ pub fn a_failed_backup_leaves_nothing_test() -> Nil { let path = temporary_database() let assert Ok(db) = sqlight.open(path) let assert Ok(_) = migration.record(db, "already_run") - let assert Ok(_) = sqlight.close(db) + let assert Ok(_) = albedo_sqlite.close(db) let backup = path <> ".backups/albedo-before-breaking-1.sqlite" albedo_file.ensure_parent(backup) // VACUUM INTO refuses a destination that is not empty. @@ -308,7 +309,7 @@ pub fn the_check_leaves_a_stopped_home_without_sidecars_test() -> Nil { "PRAGMA journal_mode=WAL; CREATE TABLE breaking_migrations(name TEXT PRIMARY KEY,recorded_at INTEGER NOT NULL); INSERT INTO breaking_migrations VALUES('from_the_future',0);", writer, ) - let assert Ok(_) = sqlight.close(writer) + let assert Ok(_) = albedo_sqlite.close(writer) let before = files(path) before |> list.map(fn(entry) { entry.1 })