1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Stopped writing once SQLite rolled a batch back

- SQLite may roll a whole transaction back by itself (a full disk, an
  I/O error, out of memory). The writes after it then ran outside any
  transaction, each committed alone, while the batch failed and every
  write was answered ServerError: a retried push stored twice
- Every Batch operation after is refused now (Error::RolledBack,
  Batch::is_rolled_back), the batch fails, nothing in it stored; the
  server's writer stops running the group there
- batch.rs nothing_runs_once_sqlite_rolled_back (a ROLLBACK standing in
  for SQLite's); docs (storage.md) and revamp.md (step 18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 23:41:04 +01:00
parent 8ebac633d0
commit a6ade535d0
6 changed files with 113 additions and 2 deletions
+1 -1
View File
@@ -362,7 +362,7 @@ fn refusal(error: bakashrot_storage::Error) -> RequestRefused {
Error::UnknownName(_) => ErrorCode::UnknownName,
Error::TooBig(_) => ErrorCode::TooBig,
Error::Query(_) => ErrorCode::QueryFailed,
Error::Sqlite(_) | Error::Unusable(_) => {
Error::Sqlite(_) | Error::Unusable(_) | Error::RolledBack => {
warn!("the database: {error}");
return server_error("the database failed");
}
+5
View File
@@ -196,6 +196,11 @@ fn write(writer: &mut Writer, group: Vec<(Write, oneshot::Sender<Outcome>)>) {
let mut outcomes = Vec::with_capacity(group.len());
let committed = writer.batch(|batch| {
for (write, _) in &group {
// SQLite rolled the group back (a full disk...): the batch
// fails, every write in it is refused below, none stored.
if batch.is_rolled_back() {
break;
}
outcomes.push(write.run(batch).map_err(refusal));
}
Ok(())
+82
View File
@@ -26,6 +26,12 @@ impl Writer {
/// rolled back otherwise. Each operation of a [`Batch`] is all or
/// nothing on its own, so `write` may go on after one fails: many
/// pushes in one batch are a group commit, one disk flush for all.
///
/// Unless SQLite rolled the whole transaction back by itself (it may,
/// on a full disk, an I/O error, out of memory): then every operation
/// after is refused ([`Error::RolledBack`], they'd be written outside
/// the transaction, one at a time), and so is the batch: nothing in it
/// was stored.
pub fn batch<T>(&mut self, write: impl FnOnce(&mut Batch<'_>) -> Result<T>) -> Result<T> {
let mut batch = Batch {
transaction: self
@@ -33,6 +39,7 @@ impl Writer {
.transaction_with_behavior(TransactionBehavior::Immediate)?,
};
let value = write(&mut batch)?;
batch.check_open()?;
batch.transaction.commit()?;
Ok(value)
}
@@ -52,9 +59,24 @@ impl Batch<'_> {
/// which it returns. Without a savepoint, the hot path: a push that
/// fails leaves at most its topic and node's (empty) stream.
pub fn push(&mut self, topic: &str, node: &str, pushed_at: u64, data: &str) -> Result<u64> {
self.check_open()?;
Ok(insert_pushed(&self.transaction, topic, node, pushed_at, data)?.0)
}
/// Whether SQLite rolled the transaction back by itself: nothing more
/// may run in it.
pub fn is_rolled_back(&self) -> bool {
self.transaction.is_autocommit()
}
/// [`Error::RolledBack`] once rolled back.
fn check_open(&self) -> Result<()> {
match self.is_rolled_back() {
false => Ok(()),
true => Err(Error::RolledBack),
}
}
/// Stores a pushed message with its attachment, an upload all of whose
/// parts came ([`Batch::write_part`] said so) and whose SHA-256 the
/// caller checked: the attachment is then `ready`.
@@ -302,6 +324,9 @@ impl Batch<'_> {
/// Runs one operation all or nothing (a savepoint), so the batch can go
/// on after it fails.
fn atomic<T>(&mut self, operation: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
// Outside a transaction, a savepoint would start one of its own,
// committed when released.
self.check_open()?;
let savepoint = self.transaction.savepoint()?;
let value = operation(&savepoint)?;
savepoint.commit()?;
@@ -421,3 +446,60 @@ pub(crate) fn clean_up(db: &Connection) -> Result<()> {
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
/// SQLite may roll a whole transaction back by itself (a full disk, an
/// I/O error): what came after ran outside it, each committed alone,
/// while the batch failed and every write was answered as failed.
#[test]
fn nothing_runs_once_sqlite_rolled_back() {
let connection = Connection::open_in_memory().unwrap();
connection
.execute_batch(include_str!("schema_v9.sql"))
.unwrap();
let mut writer = Writer::new(connection);
let outcome = writer.batch(|batch| {
assert_eq!(batch.push("logs", "kitchen", 1, "a")?, 1);
assert!(!batch.is_rolled_back());
// What SQLite does on its own, sometimes, on those errors.
batch.transaction.execute_batch("ROLLBACK")?;
assert!(batch.is_rolled_back());
let refused = |result: Result<_>| matches!(result, Err(Error::RolledBack));
assert!(refused(batch.push("logs", "kitchen", 2, "b")));
assert!(refused(batch.push("other", "garage", 3, "c")));
assert!(refused(batch.start_upload(5, &[0; 32]).map(|_| 0)));
assert!(refused(batch.delete_before("logs", 10, 10).map(|_| 0)));
assert!(refused(batch.purge_attachments(10).map(|_| 0)));
Ok(())
});
assert!(matches!(outcome, Err(Error::RolledBack)), "{outcome:?}");
let count = |writer: &Writer, table: &str| -> i64 {
writer
.connection
.query_row(&format!("SELECT count(*) FROM {table}"), [], |row| {
row.get(0)
})
.unwrap()
};
// Nothing stored: neither before the rollback nor after it.
assert_eq!(
(
count(&writer, "data"),
count(&writer, "streams"),
count(&writer, "attachments")
),
(0, 0, 0)
);
// The next batch goes on as usual.
assert_eq!(
writer
.batch(|batch| batch.push("logs", "kitchen", 4, "d"))
.unwrap(),
1
);
assert_eq!(count(&writer, "data"), 1);
}
}
+7
View File
@@ -55,12 +55,19 @@ pub enum Error {
TooBig(String),
/// A client's query that failed or isn't read-only: `QueryFailed`.
Query(String),
/// SQLite rolled the batch's transaction back by itself (disk full,
/// an I/O error...): nothing in it is stored, and nothing more runs in
/// it (it would be written outside the transaction): `ServerError`.
RolledBack,
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Sqlite(error) => write!(f, "database: {error}"),
Error::RolledBack => f.write_str(
"database: the transaction was rolled back after a failure, nothing in it stored",
),
Error::Unusable(what)
| Error::Invalid(what)
| Error::NotFound(what)
+11
View File
@@ -73,6 +73,17 @@ operation of a `Batch` is all or nothing on its own (a savepoint), so a
batch goes on after one fails: the server queues pushes and stores them
together, one disk flush for all.
Except when SQLite rolls the whole transaction back by itself, which it
may on a full disk, an I/O error or out of memory (`Batch::is_rolled_back()`).
What came after then ran outside any transaction, each operation
committed alone, while the batch failed and every write in it was
answered as failed: a retried push stored twice. Since 2026-11-19 every
operation after is refused (`Error::RolledBack`) and so is the batch:
nothing in it is stored, every write answered `ServerError`
(`nothing_runs_once_sqlite_rolled_back` in `batch.rs`, a `ROLLBACK`
standing in for SQLite's). The server's writer stops running the group
there.
| Operation | What |
|---|---|
| `push(topic, node, pushed_at, data)` | the next id of its stream, which it returns; the stream is made if new |
+7 -1
View File
@@ -239,6 +239,12 @@ Also decided (2026-11-13):
push returning the previous one's id). `set_answer_timeout()` /
`answer_timeout()` (30 s by default); `is_open()` always blocking
again. The DLL already dropped its client on those.
- **Nothing written outside a transaction SQLite rolled back:** on a
full disk, an I/O error or out of memory, SQLite may roll a whole
batch back by itself; the writes after it then committed one at a
time while all were answered `ServerError` (retried, stored twice).
Every `Batch` operation after is refused now (`Error::RolledBack`),
the batch fails, nothing in it stored; the writer stops the group.
- **Schema v9, not compatible with v8** (2026-11-13): old databases aren't
opened, their data isn't carried over (the real-life tests start empty).
`docs/storage.md`:
@@ -462,7 +468,7 @@ by hand.
| 15 | Filtered lists | `ListNames`' `topics` and `nodes` filters (protocol 8): server, client, `BakaShrot_ListNames` (`A`/`W`), Python, C#, PureBasic, `bakashrot list --topics/--nodes` | `end_to_end.rs` `names` (patterns, case, permissions), `exports.rs`, `check_bakashrot.py`, the NUnit tests | Decided 2026-11-19 | Done 2026-11-19 |
| 16 | The DLL's enumerations | `GetNamesListAsJson`, `GetQueryResultAsJson`; `EnumerateNames` / `EnumerateQuery`, `Next...`, their getters, `CloseEnum` (`enumerations.rs`); `ListTopics` / `ListNodes` dropped; PureBasic's example on them; C#'s `EnumerateTopics` / `EnumerateNodes` / `EnumerateQuery` (`IEnumerable`, asked at each `foreach`) | `exports.rs` `enumerations` (names, query rows and nulls, several at once, bad and closed handles, freed with the client); the NUnit `Enumerations` test | Decided 2026-11-19 | Done 2026-11-19 |
| 17 | `SyncState` in pages | `SyncStateRequest.after`, `SyncState.more`, `MAX_HEADS_PER_PACKET` (protocol 8); `heads_after` in storage; both ends of replication | `packets.rs` `the_biggest_sync_state_fits` and the page rules; `storage.rs` heads in pages; `end_to_end.rs` `sync_state_in_pages` (full and partial pages, the lists in the first only, a cursor in another case or not stored, pairs a peer doesn't take skipped, exactly a page, a pattern refused) and `replication_across_pages` (only what's after a head of the second page sent); each part broken on purpose once, every test caught it | Decided 2026-11-19 | Done 2026-11-19 |
| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout` | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-19 |
| 18 | Fixes from a read of the code | The server requiring ALPN; retention ages capped at 100 years; `Ping` / `Pong` (protocol 8) with `BakaShrot_Ping`, Python's and C#'s `ping`, pings in the follows and the replication links; `idle_database_connections` and idle connections closed; a damaged copy told from a failed read-back; the Rust client closing a connection left out of step, `set_answer_timeout`; nothing written once SQLite rolled a batch back | `end_to_end.rs` `certificates_refused` (no ALPN: closed), `pings`, `no_idle_database_connections`; `config.rs` the cap, `retention_cutoff`, the key; the server's `pools_keep_few_and_close_the_idle` and `only_a_copy_read_whole_or_missing_a_part_is_damaged` (with `replication` for the damaged copy still dropped); the client's `failures.rs` (a fake server: late, wrong, cut answers and parts) and `revoked_certificates_are_dropped`; storage's `nothing_runs_once_sqlite_rolled_back`; `packets.rs` samples and bytes; `exports.rs`, `check_bakashrot.py`, the NUnit `Closing` | Decided 2026-11-19 | Done 2026-11-19 |
Each step ends with its tests passing and its docs updated (the crate's
docs, `docs/`, this file's status), then a commit when the owner