Skip to content

feat(server): messages nobody can reach are deleted, with a nightly safety net - #383

Open
Aizen93 wants to merge 8 commits into
developfrom
feat/unreachable-rows
Open

Aizen93 wants to merge 8 commits into
developfrom
feat/unreachable-rows

Conversation

@Aizen93

@Aizen93 Aizen93 commented Nov 28, 2026

Copy link
Copy Markdown
Owner

What was missing

A message of a direct conversation that lies at or below the clearing point of every remaining participant can be read, quoted, reported or downloaded by nobody, yet it stayed in the database with its reactions and attachment files. History-key backups whose conversation or secure channel no longer exists stayed too, counting against the account's backup cap.

Three further defects are fixed in the same change. The history-key listing read its page position from the cursor's row, so a page asked for after that row was removed came back empty. The orphan sweep's walk of the referenced attachment keys, and the four admin exports, paged the same way: a row deleted at a page boundary ended the walk there, leaving live attachment keys out of the referenced set or cutting an export short. And a report on a message deleted between the route's check and its insert answered 500.

What the code does now

  • The rule (utils/unreachableRows.ts). Every live side of the conversation (an account that still exists) must have a floor, or nothing of it is purged. The purge floor is the earlier floor of the live sides, the remaining side's when the other account is deleted. Rows at or below it go. The floor is one explicit CASE sub-select, written once and used by both statements that need it; never a function that skips a NULL.
  • One batch (at most 1,000 rows) is one transaction, retried after a deadlock:
    1. the conversation row FOR KEY SHARE SKIP LOCKED (a conversation held by a removal or an account deletion is left for later; nothing is waited for);
    2. the sides and their floors, read again through the typed client;
    3. the rows, oldest first, locked FOR UPDATE only when they are to be deleted;
    4. every row checked again in JavaScript against each live side's floor, through the visibility module's own function (one row a side can still see refuses the batch);
    5. the live attachment keys;
    6. one delete of exactly those rows.
  • What goes with a deleted row. Its reactions and attachment rows (cascade); files are deleted after the commit. A reply to it and a report on it lose their link (SET NULL); the report keeps its copy of the text. The conversation row is never written, nothing is announced, no unread count moves.
  • Right after the event. After the commit of a removal with clearHistory that kept the conversation, and of an account deletion or a hygiene batch that kept a conversation for the other person, the conversation is queued for the purge on a per-node serial chain: after the existing notices, never awaited, at most 50,000 rows per event.
  • A nightly job, unreachable-rows ("Unreachable messages", daily 04:45, switchable, under its own cluster lock), finds what that step left:
    • it walks the read rows that hold a floor and takes a conversation only while every live side has a floor and its oldest message lies at or below the purge floor (one ordered probe of the messages index per read row);
    • it removes the history-key backups of a scope that no longer exists: a conversation id that names no conversation, or ch: and an id that names no secure channel. Each such scope is read a second time through the typed client before anything of its page is deleted, and any other scope shape is never touched;
    • caps: 50,000 messages and 20,000 backup rows a night, counting included (capped).
  • One switch. The job starts in Count only. Both paths read its mode from the database each time: On deletes; Count only makes the nightly pass record what it would delete while the step after an event reads only the job's mode and deletes nothing; Off, or a mode that cannot be read, deletes and counts nothing. Count only locks no message row: each batch still takes the conversation row FOR KEY SHARE SKIP LOCKED, so a removal of that conversation waits at most for one batch's reads. A count that reaches a cap counts the same first rows again the next night.
  • History-key listing (GET /e2e/message-keys). The cursor is a position: a page is the caller's rows whose id is greater than it, in id order, whether or not the row it names still exists. A client that sends the last id of its page gets the page it got before.
  • The orphan sweep and the admin exports. The walk of the referenced attachment keys and the user, space, ban and IP-ban exports page by position too: each page is the rows whose id is greater than the last id of the page before, merged into the query's own filter. No guard of the sweep changed.
  • POST /reports. A report whose message is deleted between the route's check and its insert answers the route's 404 Message not found.

Visible once the job is On

  • A reply to a purged message is shown as a plain message, as after any deletion of a quoted message. Before, it showed the "Original message was deleted" line.
  • The message totals shown to administrators and on the public statistics drop.
  • With the flag account_deletion_keeps_conversations on, a conversation the purge emptied is deleted at a later account deletion of either side, as a conversation holding no message already is (with the flag off every conversation of a deleted account is deleted anyway).

Key files

  • apps/server/src/utils/unreachableRows.ts (its header holds the rule, the guard and the lock order against each writer of these tables)
  • apps/server/src/utils/jobs.ts (the job and jobModeNow)
  • apps/server/src/routes/dm.ts, apps/server/src/utils/accountDeletion.ts, apps/server/src/utils/registrationHygiene.ts (the step after the commit)
  • apps/server/src/routes/e2e.ts (the listing), apps/server/src/utils/orphanCleanup.ts, apps/server/src/routes/admin.ts (collectInBatches), apps/server/src/routes/reports.ts
  • docs/e2e-dm-spec.md §16.2 and §16.3

Migrations

None. A server older than this change has no such job and no such step. On a database without the Jobs tables the mode reads as the default, Count only, so nothing is deleted.

Tests

  • New: unreachableRows.test.ts (the rule's cases, the batch in both modes, the statements in the order they run, the guard, the retry, files after the commit, the caps, the step after an event) and unreachableRowsNightly.test.ts (the nightly pass against an in-memory model that reads the statements' text).
  • Extended: jobs.test.ts (ten jobs, jobModeNow), the removal, account-deletion and hygiene suites (the three call sites), e2e.test.ts (the listing), orphanCleanup.test.ts and admin-maintenance.test.ts (a row deleted at a page boundary no longer ends the walk; each export keeps its filter on every page), reports.test.ts, conversationSideReaders.test.ts, the admin AdminJobs.test.tsx.
  • New: meta/keysetPaging.test.ts, a source scan that fails when a server source hands a cursor option or skip: 1 to a Prisma read.
  • The statements and the module itself were also run against PostgreSQL 16: the rule's cases with a row exactly at a floor, both modes, time zones off UTC, the plans on volume data, and two-session runs against a removal, an account deletion, a report resolution, an edit of a visible reply, a second purge and a new message.
  • pnpm typecheck, pnpm lint and the server and admin unit suites pass on the branch.

To check by hand

  • On the Jobs page, "Unreachable messages" shows Count only. After a night, read its run: messages, files and conversations are what On would delete; skippedLocked is conversations busy, or deleted, at that moment; backups and backupScopes are the backups of scopes that no longer exist; otherShape is backup rows of another scope shape, never touched; capped: 1 means a nightly cap was reached. A run marked failed with UnreachableRowsGuardError means a check refused and nothing of that batch or page was deleted: it is to be understood before the job is switched On.
  • Switch it On as a superadmin: the next run deletes what it counted, up to the caps, and from then on a removal with history cleared by both people deletes those messages right away (one server log line with counts).

A message of a direct conversation that lies at or below the floor of
every live side can be read, quoted, reported or downloaded by nobody.
utils/unreachableRows.ts holds the one implementation of their deletion,
used by nothing yet.

The rule: every live side (a side whose account exists) must have a read
row with a floor, or nothing of the conversation is purged; the purge
floor is the smaller floor of the live sides, the other side's floor when
one side is a deleted account; a row at or below it goes. The floor is an
explicit CASE over the two sides, never a function that skips a NULL.

One batch of at most 1,000 rows is one transaction, retried whole after a
deadlock: the conversation row FOR KEY SHARE SKIP LOCKED (a row held by a
removal or an account deletion is left alone), the sides read through the
typed client, the rows read oldest first and locked in that order, every
row checked again in JavaScript against each live side's floor (one that a
side can still see refuses the batch), the live attachment keys, then one
delete of exactly those rows. Files are deleted after the commit. Count
mode runs the same reads and deletes nothing.
…backups

The job registry gains `unreachable-rows`, daily at 04:45 (after the
registration hygiene sweep, before the object-store backstop), switchable
and born in Count only: it records what it would delete and deletes
nothing until an administrator switches it On.

Each run takes its own cluster lock and, in the job's mode:
- walks the read rows with a floor by primary key, each conversation once,
  and applies the rule of utils/unreachableRows.ts to every conversation
  that holds a message at or below that floor, up to 50,000 rows a night;
- walks the history-key backups by (account, scope) and takes only the
  scopes of a known shape that name no conversation, or no secure channel
  for `ch:`. Every such scope is read again through the typed client before
  anything of the page is deleted, and one that exists refuses the run. A
  scope of another shape is counted and never touched. Up to 20,000 rows a
  night, deleted per pair in bounded statements.

The summary holds numbers only: conversations, messages, files,
skippedLocked, backups, backupScopes, otherShape and capped. A failing
step ends the run and is recorded as its failure; earlier batches stay
committed.
After the commit of the event that made messages unreachable, and after
its notices, the conversation is queued for the purge of
utils/unreachableRows.ts:
- a removal with clearHistory that raised a floor and kept the
  conversation (DELETE /dm/:id);
- an account deletion, for each conversation kept for the other person;
- each registration hygiene batch, the same.

The step never fails, delays or is awaited by its request. Events of one
node run one after the other, at most 50,000 rows each; nothing is
persisted, and what a restart or a full queue drops is the nightly pass's.
Each event reads the mode of the `unreachable-rows` job from the database
first, through jobModeNow (utils/jobs.ts), the rule a tick reads it by:
only On purges; Count only, Off and a mode that cannot be read send no
statement on messages (the mode read is the only one). No run is recorded
for an event; one that deleted something logs one line with counts only.
The page lists the server's registry as it is answered, with no job and
no summary key written out by hand, so the purge of unreachable messages
needs no change there. A test now holds what an administrator reads for
it before switching it On: the mode Count only, its daily slot, the Off
and On controls, the numbers of a count-mode run, and the confirmation
that sends On.
…age row

The rule's CASE is now one fragment of utils/unreachableRows.ts
(purgeFloorOf, a scalar sub-select) that the batch read and the nightly
walk both use, so the two cannot drift.

The nightly walk takes a conversation only while it can hold a row to
purge: every live side has a floor, and the conversation's oldest message
lies at or below the purge floor, read by one ordered probe of the
messages index. A conversation of two people that only one of them
cleared, or whose rows all lie between two floors, is no longer taken
every night. The walk still decides nothing: each batch's own transaction
does.

Count mode reads its batches without a lock on the message rows (FOR
UPDATE OF m belongs to mode On alone): a count writes nothing and makes no
other writer wait on a message row. It still takes the conversation row
FOR KEY SHARE SKIP LOCKED, as mode On does. A count walks by the id of the
last row it read, so that row, deleted before the next batch, ends that
conversation's count early.

The module's header says what a purge changes for a reader: a visible
reply to a purged row becomes a plain message, as after any deletion of a
quoted row. Its lock-order note now argues against the attachment expiry
(no common order exists: PostgreSQL ends one side, the purge runs again
whole, the expiry's next run marks what is left) and the report retention
(SKIP LOCKED: it never waits for the purge).

The test of the per-event cap serves a finite number of full batches, so
a missing cap fails the count of transactions instead of running on.
…rsor row

GET /e2e/message-keys treats its cursor as a position: a page holds the
caller's rows whose id is greater than the cursor, in id order, whether
or not the row the cursor names still exists. The listing no longer reads
its position from that row (Prisma's cursor), so a row removed between two
pages leaves the next page where it was, and a cursor naming another
account's row, or no row at all, returns the caller's own rows after that
position.

The rest of the route is unchanged: the cursor's validation, the scoping
by the caller's account, the page size, the one extra row that decides
nextCursor, the answer's shape.

The spec states both: the cursor is a position, and the server removes
the backups of a scope that no longer exists (the nightly job, once it
is switched On).
POST /reports reads the reported message, then inserts the report. When
the message is deleted between the two, the report's key to it
(reports_message_id_fkey) refuses the insert; the route answers that
refusal exactly as it answers a message that does not exist: 404
"Message not found", nothing written, nothing announced, the limiter
charged as for that answer.

The refusal is read through violatesForeignKey, by the constraint the
driver names. Any other refused key and any other error surface as
before, and the pending-report unique violation keeps its answer.
A walk over a table by id is a keyset: each page is the rows whose id
is greater than the last id of the page before, in id order. No walk
names a row with a Prisma cursor, which returns nothing when that row
has been deleted since the previous page.

The orphan sweep's walk of the referenced attachment keys and the four
admin exports (users, spaces, bans, IP bans) paged with a cursor on
the last row and skip: 1. A row deleted at a page boundary ended the
walk there: live attachment rows were left out of the referenced set
and their files looked unreferenced, and an export stopped short
without a sign.

Both now merge id: { gt: last } into the query's own where. The helper
of the exports hands each caller that fragment and no cursor; each
caller keeps its filter, select and id order.

A source scan (meta/keysetPaging.test.ts) fails when any server source
passes a cursor option or skip: 1 to a Prisma read. The behaviour tests
answer a cursor naming a missing row with nothing, delete the boundary
row after the first page, and check the filters of every export on
every page.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant