Store, Sync, main: a deleted text stays deleted

imsd keeps a received text until an app deletes it, and a delete can be
refused (polkit, for a session that is not the active one) or time out:
the List after the next start would carry the text again and the app
would import it again (within a run Sync's own record of what it
imported keeps it out). And a deleted row is a tombstone whose bytes
stay in the file until it is rewritten.

The store gains a second table, erased.cdb: the imsd ids of received
texts the user deleted while imsd may still hold their copies, its
format held by the build as the first table's is. Erase and
EraseConversation remember the id before the row goes (a crash between
the two leaves a remembered id, never a text that comes back; a
remembering the store refuses refuses the delete), ImsdIds folds the
remembered ids in, so Sync's `known` keeps a List from importing them,
and ForgetErased drops the ids a List no longer carries — of those
remembered before that List was sent: an id remembered while it was in
flight waits for the next (FetchList's `before` snapshot). Sync's Erase
and EraseConversation go to the store; Fail and the Send continuation
check that the row still exists, so a text deleted while its Send is in
flight takes no late word, and a late answer for a deleted message finds
no row and is logged. main compacts both files at start when either
holds deleted rows or bytes an update or a delete orphaned (a state
reason replaced by another can leave some, so a start after a send may
rewrite both with nothing deleted), and opens the store again on what is
there if the rewrite failed: a deleted text's bytes leave the files at
the next start (a resident instance keeps them until then — nothing
holds a row id across the rewrite but the app itself).

Tested: tests/Store — the remembered ids across a reopen and as known, a
deleted sent text's id not remembered, the ids imsd no longer lists
forgotten, the bytes of deleted texts and forgotten ids gone after the
Compact and a reopen while the kept ones stay, a forgotten id alone
enough for a Compact, the second file private and rewritten with the
first; tests/Sync — a message deleted while it is sending (its late
answers write nothing and are logged), a received text imported,
remembered when deleted and forgotten when no longer listed, a text
signalled while a List is in flight kept by the List sent before the
delete — which forgets the id remembered before it went out — and
forgotten by the next, and a state for another client's text leaving
every message alone.
This commit is contained in:
Jorijn van der Graaf 2026-11-01 18:11:01 +01:00
commit 53bc4797bc
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
5 changed files with 242 additions and 23 deletions

View file

@ -2,15 +2,17 @@
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
ImsdMessages:Store — the app's message database, one Crafter.DB table.
ImsdMessages:Store — the app's message database: a Crafter.DB table of
the messages (messages.cdb) and one of the imsd ids of received texts the
user deleted while imsd may still hold their copies (erased.cdb).
The table has no ordered column on purpose: Crafter.DB enforces the order on
every write, and a List() import after a restart can carry an older stamp
than the last row. SMS volumes make a scan free, so conversations are
derived from a scan (ImsdMessages:Model) and a conversation's messages are
sorted here. One Table per file: a second MessageStore on the same
sorted here. One MessageStore per directory: a second one on the same
directory, in this process or another, throws Crafter::DB::LockedError —
on a lock file beside the table, held for the store's life, since the
on a lock file beside the tables, held for the store's life, since a
table's own lock moves with the file a Compact replaces.
Every change a call answers as made is flushed before the call returns:
@ -70,6 +72,19 @@ namespace ImsdMessages {
inline constexpr Crafter::DB::Column<&MessageRow::imsdId> imsdIdColumn{};
// A received text the user deleted while imsd may still hold its copy
// (a delete it refused or that timed out): its imsd id, so a later List
// does not import it; dropped once imsd no longer lists it.
struct ErasedRow {
ImsdId imsdId;
static constexpr std::uint32_t version = 1;
};
// Held by the build as MessageRow's format is.
static_assert(Crafter::DB::Layout<ErasedRow>::rowSize == 65);
static_assert(Crafter::DB::Layout<ErasedRow>::fingerprint == 0xad3324d2c7d75ee0);
// One MessageStore per directory, held for its life on a file nothing
// renames: the table's own lock sits on its file's inode, which a
// Compact replaces (a new file renamed over the old), so a second opener
@ -154,8 +169,8 @@ namespace ImsdMessages {
export namespace ImsdMessages {
class MessageStore {
public:
// Opens or creates <dir>/messages.cdb (a directory it creates 0700,
// the file 0600). Throws Crafter::DB::LockedError when another
// Opens or creates <dir>/messages.cdb and erased.cdb (a directory it
// creates 0700, the files 0600). Throws Crafter::DB::LockedError when another
// MessageStore holds it. Every write but a Compact is caught here: one the
// store refuses (Crafter.DB's IOError — the disk full, the file system
// read-only) answers nullopt (Add), false or 0 (a count) — a row Add
@ -169,7 +184,7 @@ export namespace ImsdMessages {
// rewrites a written page in place (ext4, f2fs: the phone's); a
// copy-on-write one (btrfs) can refuse the rewrite of a mapped page
// with SIGBUS, which no gate sees — Crafter.DB maps its files.
explicit MessageStore(const std::filesystem::path& dir) : lock(dir), table(dir / "messages.cdb") {}
explicit MessageStore(const std::filesystem::path& dir) : lock(dir), table(dir / "messages.cdb"), erased(dir / "erased.cdb") {}
std::function<void(bool refused, std::string_view why)> onWriteState;
@ -245,23 +260,72 @@ export namespace ImsdMessages {
}
bool Erase(std::uint64_t id) {
bool erased = false;
// The id first, the row after: a crash between the two leaves a
// remembered id, never a text that comes back — and a remembering
// the store refuses refuses the delete.
if (const std::optional<Message> m = Get(id); m && m->direction == Direction::Incoming && !m->imsdId.empty() && !RememberErased(m->imsdId)) return false;
bool gone = false;
if (!Write([&] {
erased = table.Erase(id);
if (erased) table.Flush();
gone = table.Erase(id);
if (gone) table.Flush();
}))
return false;
return erased;
return gone;
}
std::uint64_t EraseConversation(std::string_view conversation) {
std::uint64_t erased = 0;
if (!Write([&] {
erased = table.EraseIf([&](Crafter::DB::Row<MessageRow> row) { return row[&MessageRow::conversation] == conversation; });
if (erased > 0) table.Flush();
// The ids first, the rows after, as Erase does: a crash between
// the two leaves a remembered id, never a text that comes back.
// One append and one flush for all of them.
std::vector<ErasedRow> remembered;
for (Crafter::DB::Row<MessageRow> row : table) {
if (row[&MessageRow::conversation] != conversation) continue;
const ImsdId id = row[&MessageRow::imsdId];
if (row[&MessageRow::direction] == Direction::Incoming && !id.View().empty()) remembered.push_back(ErasedRow{ id });
}
if (!remembered.empty() && !Write([&] {
erased.Append(std::span<const ErasedRow>(remembered));
erased.Flush();
}))
return 0;
return erased;
std::uint64_t gone = 0;
if (!Write([&] {
gone = table.EraseIf([&](Crafter::DB::Row<MessageRow> row) { return row[&MessageRow::conversation] == conversation; });
if (gone > 0) table.Flush();
}))
return 0;
return gone;
}
// The imsd ids of received texts the user deleted, kept until imsd no
// longer lists them: a List does not import them again, and imsd's
// copy is deleted once this session may (at the next List imsd admits
// or after its restart, when polkit refused). False when the store
// refused the write.
bool RememberErased(std::string_view imsdId) {
if (!FitsImsdId(imsdId)) return false; // past imsd's bound: no row carries it
return Write([&] {
erased.Append(ErasedRow{ ImsdId(imsdId) });
erased.Flush();
});
}
std::unordered_set<std::string> ErasedImsdIds() const {
std::unordered_set<std::string> ids;
for (Crafter::DB::Row<ErasedRow> row : erased) ids.emplace(row[&ErasedRow::imsdId].View());
return ids;
}
// Drops the remembered ids a List no longer carries — of those
// remembered before that List was sent (`before`): an id remembered
// while it was in flight belongs to a text its answer could not
// carry, and waits for the next.
void ForgetErased(const std::unordered_set<std::string>& listed, const std::unordered_set<std::string>& before) {
if (before.empty()) return; // nothing to forget: no write, no word on the store's state
Write([&] {
const std::uint64_t gone = erased.EraseIf([&](Crafter::DB::Row<ErasedRow> row) { const std::string id(row[&ErasedRow::imsdId].View()); return before.contains(id) && !listed.contains(id); });
if (gone > 0) erased.Flush();
});
}
// The row with that imsd id: unique across imsd's runs (ImsdId), so
@ -273,9 +337,10 @@ export namespace ImsdMessages {
return std::nullopt;
}
// Every imsd id on record.
// Every imsd id on record: the stored texts' and the deleted ones'
// imsd still holds.
std::unordered_set<std::string> ImsdIds() const {
std::unordered_set<std::string> ids;
std::unordered_set<std::string> ids = ErasedImsdIds();
for (Crafter::DB::Row<MessageRow> row : table) {
const ImsdId id = row[&MessageRow::imsdId];
if (!id.View().empty()) ids.emplace(id.View());
@ -327,21 +392,38 @@ export namespace ImsdMessages {
}
// The files' length: what a write that needed room grew.
std::uint64_t Length() const noexcept { return table.Stats().fileLength; }
std::uint64_t Length() const noexcept { return table.Stats().fileLength + erased.Stats().fileLength; }
bool refused = false; // a write was refused and none has grown a file since
public:
// Through the gate: a flush that fails at the end of a run is told,
// not thrown.
void Flush() { Write([&] { table.Flush(); }); }
void Flush() {
Write([&] {
table.Flush();
erased.Flush();
});
}
// Rewrites the file without tombstones; row ids change, so only at
// start or after a delete with nothing holding ids.
void Compact() { table.Compact(); }
// Rewrites both files without tombstones; the messages' row ids
// change, so only at start or after a delete with nothing holding
// ids (nothing holds an erased id).
void Compact() {
table.Compact();
erased.Compact();
}
// Deleted rows, or the bytes an update or a delete orphaned, still in
// either file: what a Compact would drop.
bool HasDeleted() const noexcept {
const auto garbage = [](const auto& s) { return s.liveCount < s.slotCount || s.heapGarbage > 0; };
return garbage(table.Stats()) || garbage(erased.Stats());
}
private:
DirectoryLock lock; // before the table: taken first, released last
DirectoryLock lock; // before the tables: taken first, released last
Crafter::DB::Table<MessageRow> table;
Crafter::DB::Table<ErasedRow> erased;
};
}

View file

@ -319,6 +319,12 @@ export namespace ImsdMessages {
// taken, the caller keeps it (a row id is never this).
static constexpr std::uint64_t kNotStored = ~std::uint64_t{0};
// The user's deletes: the rows go. What imsd answers later for a
// deleted message finds no row and is logged.
void Erase(std::uint64_t id) { store.Erase(id); }
void EraseConversation(std::string_view conversation) { store.EraseConversation(conversation); }
// A failed message of ours goes again — without the failed attempt's
// imsd id: a row's imsd id names its current attempt (imsd forgets a
// failed submission's parts, so no word of the old one is due).
@ -349,6 +355,10 @@ export namespace ImsdMessages {
}
void Fail(std::uint64_t id, std::string_view reason) {
if (!store.Get(id)) {
listener.OnLog(std::format("message {} failed after it was deleted: {}", id, reason));
return;
}
store.SetState(id, MessageState::Failed, reason);
Changed(id);
}
@ -365,6 +375,10 @@ export namespace ImsdMessages {
Fail(id, result.error().message);
return;
}
if (!store.Get(id)) {
listener.OnLog(std::format("imsd took message {} as {} after it was deleted", id, *result));
return;
}
// imsd's id names the row for its words: in place, which a
// full disk does not refuse (the row's Add fit).
if (!store.SetImsdId(id, *result)) listener.OnLog(std::format("imsd's id for message {} was not recorded: {}", id, *result));
@ -422,7 +436,7 @@ export namespace ImsdMessages {
return;
}
listInFlight = true;
bus.List([this](ListResult result) {
bus.List([this, before = store.ErasedImsdIds()](ListResult result) {
listInFlight = false;
if (!result) {
// Announced at every failure: the listener's 30 s refresh
@ -446,11 +460,17 @@ export namespace ImsdMessages {
status.undeletable = 0;
listener.OnStatus(status);
}
std::unordered_set<std::string> listed;
for (const ReceivedMessage& r : *result) listed.insert(r.imsdId);
// A held text this answer carries is imsd's to keep after
// all; the rest of them are tried again below.
for (const ReceivedMessage& r : *result) held.erase(r.imsdId);
for (const ReceivedMessage& r : *result) Import(r);
RetryHeld();
// A deleted text imsd no longer holds needs no memory — among
// those remembered before this List went out: one deleted
// while it was in flight is a text this answer predates.
store.ForgetErased(listed, before);
}
if (listAgain) {
listAgain = false;