diff --git a/.env.example b/.env.example
index e7bd39cb..fed372d4 100644
--- a/.env.example
+++ b/.env.example
@@ -355,8 +355,13 @@ ENABLE_LISTENER=true
# Batch sync alternative (expensive β prefer ENABLE_LISTENER instead)
SYNC_DELETIONS_EDITS=false
# Only re-check messages posted in the last N days (0 = every stored message).
-# Older posts are checked again only on a run with 0.
+# Older posts are checked again only on a run with 0, or by the rotation below.
SYNC_DELETIONS_EDITS_DAYS=0
+# With SYNC_DELETIONS_EDITS_DAYS above 0, also re-check up to this many OLDER
+# messages per run, rotating over the chats whose last full check is oldest, so
+# every stored message is re-checked over several runs (0 = off). Telegram takes
+# about 100 seconds per 1000 messages.
+SYNC_DELETIONS_EDITS_OLDER_PER_RUN=0
# Re-download missing or corrupted media files
VERIFY_MEDIA=false
diff --git a/docker-compose.yml b/docker-compose.yml
index 3b477a99..d8719bba 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -178,6 +178,7 @@ services:
# Batch sync alternative (expensive β prefer ENABLE_LISTENER instead)
SYNC_DELETIONS_EDITS: ${SYNC_DELETIONS_EDITS:-false}
SYNC_DELETIONS_EDITS_DAYS: ${SYNC_DELETIONS_EDITS_DAYS:-0}
+ SYNC_DELETIONS_EDITS_OLDER_PER_RUN: ${SYNC_DELETIONS_EDITS_OLDER_PER_RUN:-0}
VERIFY_MEDIA: ${VERIFY_MEDIA:-false}
INTERNAL_PUSH_SECRET: ${INTERNAL_PUSH_SECRET:-}
# Split containers: realtime pushes must target the viewer SERVICE, not
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index abae6806..dc9be2a6 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,9 @@ For upgrade instructions, see [Upgrading](#upgrading) at the bottom.
## [Unreleased]
+### Added
+- **Older messages can be re-checked a slice per run.** With `SYNC_DELETIONS_EDITS_DAYS` above 0, edits and deletions of older posts were caught only by a run with `SYNC_DELETIONS_EDITS_DAYS=0`. On a large archive that one run takes many hours, mostly waiting on Telegram's rate limit, and it grows with every chat. `SYNC_DELETIONS_EDITS_OLDER_PER_RUN=N` also re-checks up to N messages older than the window on each run, for each account, shared by its chats. Each request to Telegram counts as 100 of them, so a run makes at most N / 100 requests, rounded up. The chats whose last full check is oldest go first, and a large chat continues on the next run from the message where it stopped. When a chat's check reaches its oldest message, the time is recorded and the chat goes to the back of the line. A request that fails with an error other than a FloodWait is skipped and tried again on the chat's next check. So every archived message is re-checked over several runs, without one very long run and without changing `CHAT_IDS`. Telegram takes about 100 seconds per 1000 messages. The default, `0`, changes nothing. Migration 044 adds the progress to `sync_status`. See [Re-checking older messages over several runs](configuration/schedule.md#sync-rotation). Thanks to @Scalpinho for #641.
+
## [9.9.0] - 2026-11-23
A contact who deletes their Telegram account keeps the name the archive had, the viewer marks that account as deleted, and chat search finds a full name or an `@handle`. Migration 043 runs on start. Docker deployments only need the new pins.
diff --git a/docs/configuration/listener.md b/docs/configuration/listener.md
index 5491c09e..f1324313 100644
--- a/docs/configuration/listener.md
+++ b/docs/configuration/listener.md
@@ -42,7 +42,7 @@ A short network blip that the Telegram library reconnects by itself is covered t
Some things are not replayed:
- A restart after a one-shot command. Any command that connects with the same session (see [One client per session](../getting-started/telegram-login.md#one-client-per-session)) saves the current update state into it, so a listener started after it has nothing left to replay. Edits and deletions made before that are recorded only if `SYNC_DELETIONS_EDITS` is on (off by default).
-- A very long outage. When Telegram answers that too much was missed, for the account or for one chat (roughly 100 or more updates in one supergroup or channel), the listener drops that replay and logs a warning that contains `replay as too long`. It names neither the chat nor its id, unless `LOG_CHAT_TITLES=true`, which adds the channel's title and id: `replay as too long: "Demo News" (id -1001234567890) (pts AβB)`. With it on, remove them from logs before you paste them anywhere. New messages from the gap still arrive with the next backup. Edits and deletions in the gap come back only if `SYNC_DELETIONS_EDITS` is on (off by default), and with `SYNC_DELETIONS_EDITS_DAYS` above 0 only for messages posted inside that window, see [Checking only recent messages](schedule.md#sync-window). A message posted and deleted inside the gap cannot be recovered. The listener asks for the replay of every saved channel it has an access hash for as soon as the saved state is loaded, instead of 15 minutes later. A channel that Telegram rate-limits then (a FloodWait) is retried 15 minutes later, so on an account with many channels its gap can still grow past the limit.
+- A very long outage. When Telegram answers that too much was missed, for the account or for one chat (roughly 100 or more updates in one supergroup or channel), the listener drops that replay and logs a warning that contains `replay as too long`. It names neither the chat nor its id, unless `LOG_CHAT_TITLES=true`, which adds the channel's title and id: `replay as too long: "Demo News" (id -1001234567890) (pts AβB)`. With it on, remove them from logs before you paste them anywhere. New messages from the gap still arrive with the next backup. Edits and deletions in the gap come back only if `SYNC_DELETIONS_EDITS` is on (off by default), and with `SYNC_DELETIONS_EDITS_DAYS` above 0 only for messages posted inside that window, or later when [the rotation of older messages](schedule.md#sync-rotation) reaches them, see [Checking only recent messages](schedule.md#sync-window). A message posted and deleted inside the gap cannot be recovered. The listener asks for the replay of every saved channel it has an access hash for as soon as the saved state is loaded, instead of 15 minutes later. A channel that Telegram rate-limits then (a FloodWait) is retried 15 minutes later, so on an account with many channels its gap can still grow past the limit.
- A stop during the replay. `docker stop` while the replay runs can lose the updates still being handled; the library saves its state as it shuts down.
- Reactions. They carry no update counter, so a restart does not replay them; the reaction re-sweep (`REACTION_RESWEEP_DAYS`) covers them.
- Reactions you add from another device, which Telegram does not always push. See [Reactions](#reactions).
@@ -161,7 +161,7 @@ Every deletion event that had deletions blocked logs one warning with their mess
π‘οΈ Rate limiter blocked 3 deletion(s), not applied, message ids: 5011, 5012, 5013. SYNC_DELETIONS_EDITS is off, so they stay unrecorded; enable it for a backup run to record them
```
-The `SYNC_DELETIONS_EDITS` pass of the scheduled backup re-reads every archived message and records the deletions the listener blocked. With it off, nothing else records them. With [`SYNC_DELETIONS_EDITS_DAYS`](schedule.md#sync-window) above 0, the pass reads only messages posted in the last N days. A blocked deletion of an older post is recorded only by a full pass, with `SYNC_DELETIONS_EDITS_DAYS=0`, and the warning says so.
+The `SYNC_DELETIONS_EDITS` pass of the scheduled backup re-reads every archived message and records the deletions the listener blocked. With it off, nothing else records them. With [`SYNC_DELETIONS_EDITS_DAYS`](schedule.md#sync-window) above 0, the pass reads only messages posted in the last N days. A blocked deletion of an older post is recorded by a run with `SYNC_DELETIONS_EDITS_DAYS=0`, or, with [`SYNC_DELETIONS_EDITS_OLDER_PER_RUN`](schedule.md#sync-rotation) set, when the rotation of older messages reaches it. The warning says which.
`telegram-archive status --json` and `GET /api/status` show, per account, `deletions_blocked`, the deletions blocked since the listener last started, and `last_rate_limit_at`, when the limiter last tripped. The count starts again at 0 each time the listener starts, a watchdog restart included; `last_rate_limit_at` is kept across restarts. The shutdown summary logs the same count as **Deletions blocked (not applied)**.
diff --git a/docs/configuration/schedule.md b/docs/configuration/schedule.md
index 83924427..edcbf617 100644
--- a/docs/configuration/schedule.md
+++ b/docs/configuration/schedule.md
@@ -98,12 +98,13 @@ For each account, in order:
5. Refresh pinned messages, up to 100 per chat.
6. Re-check recent reactions, if the [reaction re-sweep](#reaction-re-sweep) is on.
7. Back up archived chats that the main loop did not already cover.
-8. Reconcile group-to-supergroup migrations.
-9. Refresh [forum topics and folders](#forum-topics-and-folders).
-10. Recalculate statistics.
-11. Retry failed media downloads. See [Media downloads](media.md).
-12. Verify media files, if `VERIFY_MEDIA` is on.
-13. Send pending media for [transcription](transcription.md).
+8. Re-check a slice of older messages, if [`SYNC_DELETIONS_EDITS_OLDER_PER_RUN`](#sync-rotation) is set.
+9. Reconcile group-to-supergroup migrations.
+10. Refresh [forum topics and folders](#forum-topics-and-folders).
+11. Recalculate statistics.
+12. Retry failed media downloads. See [Media downloads](media.md).
+13. Verify media files, if `VERIFY_MEDIA` is on.
+14. Send pending media for [transcription](transcription.md).
The run clears the "backup in progress" flag at the end, even when it fails.
@@ -126,7 +127,7 @@ Older messages are never read again by a normal run. Edits and deletions of mess
| Option | What it catches | Cost |
|--------|-----------------|------|
| [Real-time listener](listener.md) | Edits, deletions, new messages and reactions as they happen | A process that stays connected. |
-| [`SYNC_DELETIONS_EDITS`](#sync_deletions_edits) | Edits and deletions of every archived message, or of the last N days with [`SYNC_DELETIONS_EDITS_DAYS`](#sync-window) | Re-reads the whole archive, or the window, on every run. Telegram answers about 300 ids per 30 seconds, so a million messages take more than a day. |
+| [`SYNC_DELETIONS_EDITS`](#sync_deletions_edits) | Edits and deletions of every archived message, or of the last N days with [`SYNC_DELETIONS_EDITS_DAYS`](#sync-window), plus a slice of older messages per run with [`SYNC_DELETIONS_EDITS_OLDER_PER_RUN`](#sync-rotation) | Re-reads the whole archive, or the window and the slice, on every run. Telegram answers about 300 ids per 30 seconds, so a million messages take more than a day. |
| [`REACTION_RESWEEP_DAYS`](#reaction-re-sweep) | Reaction changes on recent messages | Up to 500 messages per chat per run, spaced out. |
| [`FILL_GAPS`](#gap-fill) | Messages missing between two archived messages | One scan of the stored ids per chat after each backup run. |
@@ -152,7 +153,46 @@ SYNC_DELETIONS_EDITS=true
SYNC_DELETIONS_EDITS_DAYS=14
```
-The window is a deliberate blind spot. Edits, deletions, poll, preview and reaction changes on older posts are not seen, including changes made while the archive was down. To catch them, run a full pass: set `SYNC_DELETIONS_EDITS_DAYS=0`, or unset it, and recreate the container. With Docker Compose that is `docker compose up -d`: `docker compose restart` keeps the old environment. The [`schedule`](#the-schedule-command) command runs one backup straight away on start. Set the window back once that run ends.
+The window is a deliberate blind spot. Edits, deletions, poll, preview and reaction changes on older posts are not seen, including changes made while the archive was down. There are two ways to catch them:
+
+- Re-check them a slice per run with [`SYNC_DELETIONS_EDITS_OLDER_PER_RUN`](#sync-rotation). No run takes much longer than the others.
+- Run one full check: set `SYNC_DELETIONS_EDITS_DAYS=0`, or unset it, and recreate the container. With Docker Compose that is `docker compose up -d`: `docker compose restart` keeps the old environment. The [`schedule`](#the-schedule-command) command runs one backup straight away on start. Set the window back once that run ends. On a large archive this one run takes many hours.
+
+#### Re-checking older messages over several runs {#sync-rotation}
+
+[`SYNC_DELETIONS_EDITS_OLDER_PER_RUN`](../reference/environment-variables.md#sync_deletions_edits_older_per_run) spreads the check of older messages over many runs. It works only with `SYNC_DELETIONS_EDITS=true` and `SYNC_DELETIONS_EDITS_DAYS` above 0.
+
+```bash
+SYNC_DELETIONS_EDITS=true
+SYNC_DELETIONS_EDITS_DAYS=14
+SYNC_DELETIONS_EDITS_OLDER_PER_RUN=20000
+```
+
+Each run still checks the window of every chat. After all chats are backed up, the run re-checks up to `SYNC_DELETIONS_EDITS_OLDER_PER_RUN` messages posted before the window. The number applies to each account on its own, and the accounts run one after another. Within an account, all its chats share it:
+
+1. The chats that never finished a full check go first. Then the chat whose last full check is oldest. In each of these two groups, a chat in the middle of a check goes before one that has not started. Otherwise the order is fixed by chat id, so a large chat can take many runs, and the next chat starts when it finishes. The whole archive takes the same number of runs in any order.
+2. In each chat, the check goes from the newest older message down, 100 ids per request. Each request counts as 100 messages of the budget, even when a small chat has fewer, because Telegram limits requests, not messages. So a run makes at most one request per 100 of the budget, rounded up, however many small chats it reaches.
+3. A chat that has more older messages than the run has left continues on the next run from the same message.
+4. When a chat's check reaches its oldest message, the time is recorded. The chat goes to the back of the line, and its next check starts again from the newest older message.
+5. A run visits each chat once at most. When every chat has had its turn, the rotation ends, even with budget left.
+
+Only the chats that this run backed up take part. A chat that leaves `CHAT_IDS` or is excluded keeps its place, and continues from there if it comes back. A chat added to the selection has never finished a check, so it goes first. Each account keeps its own progress per chat.
+
+The progress is saved after every request. If the run stops, for example after a crash, at most 100 messages are checked again. If Telegram asks for a longer wait than the [retry](#rate-limits-and-retries) allows, the rotation stops for this run, and the next run continues from the same message. Any other error skips that request's 100 messages, the same way the window pass does: the check carries on below them, the run log counts them, and the next pass of that chat tries them again. A database error for one chat keeps its progress, and the other chats still get the rest of the budget.
+
+The run log ends the step with one line, for example:
+
+```text
+Older-message rotation: re-checked 20000 older messages in 3 chat(s), 2 deleted, 5 updated; 1 chat(s) finished a pass, 40 of 120 have not finished one yet
+```
+
+When a request failed, the line adds `N skipped after errors, re-checked next pass`. The count "have not finished one yet" covers only the chats this run backs up. When it reaches 0, each of those chats has finished one check. Messages of a skipped request, and ids that a misaligned answer from Telegram left out, wait for that chat's next check. A message that leaves the window while its chat's check is under way, above the point the check has reached, waits for the next check of that chat. The window pass checked it until then.
+
+**How to size it.** Telegram takes about 100 seconds per 1000 messages, so 20,000 messages add about 35 minutes to a run for each account. Size it per account: to re-check an account's history once per period, divide its messages older than the window by the number of runs in that period, and use the largest result. `Total messages` at the end of a run counts every account together, so split it first. For example, an account with 1,500,000 older messages and one run a day re-checks every message once a month with about 50,000 per run, which adds about 85 minutes. With a run every 6 hours, 12,500 per run is enough, about 20 minutes each. Each account adds its own time, so two accounts that each use the whole budget take twice as long. An account with fewer older messages than the budget gets a full check on every run. Because a request counts as 100 (step 2), an archive with many small chats takes more runs per cycle than this division gives. The window's messages come on top of this.
+
+Deletions follow `DELETION_MODE`, the same as on a run with `SYNC_DELETIONS_EDITS_DAYS=0`. With `hard`, a message Telegram no longer returns is removed from the archive, and the rotation now reaches older messages on routine runs. A chat whose old history the account can no longer read, while the chat itself is still backed up, has those older messages marked deleted, or removed with `hard`. A group that hides its history from new members, left and joined again, is one example.
+
+Turning it off (`0`) stops the rotation and keeps the saved progress; turning it on again continues from there. With `SYNC_DELETIONS_EDITS_DAYS=0` every run already checks every message, so the rotation does not run.
### Reaction re-sweep
diff --git a/docs/design/deleted-messages.md b/docs/design/deleted-messages.md
index 9c2973c8..95f4812c 100644
--- a/docs/design/deleted-messages.md
+++ b/docs/design/deleted-messages.md
@@ -25,7 +25,7 @@ In short, we recommend C for the mark and H for finding the marked messages. [Th
Two paths can tell the archive that a message is gone. Both are off by default; the [settings reference](../reference/environment-variables.md#listen_deletions) has every flag named here.
- **The listener** (`LISTEN_DELETIONS=true`). While it runs, Telegram sends it an event for each deletion. In private chats and basic groups the event carries only message ids, not the chat, so the archive looks each id up in the account's chats and skips it when the id is in more than one. A mass-operation guard caps each chat at 10 deletions in 30 seconds (`MASS_OPERATION_THRESHOLD`, `MASS_OPERATION_WINDOW_SECONDS`): past that, the chat's deletions are dropped for the next 30 seconds.
-- **The sync** (`SYNC_DELETIONS_EDITS=true`). During a backup run it asks Telegram for every archived message of a chat, 100 at a time, or only those posted in the last `SYNC_DELETIONS_EDITS_DAYS` days. A message Telegram no longer returns is marked deleted. When Telegram's answer does not line up with the ids asked for, the batch marks nothing and the next run tries again.
+- **The sync** (`SYNC_DELETIONS_EDITS=true`). During a backup run it asks Telegram for every archived message of a chat, 100 at a time, or only those posted in the last `SYNC_DELETIONS_EDITS_DAYS` days, plus a slice of older ones per run with `SYNC_DELETIONS_EDITS_OLDER_PER_RUN`. A message Telegram no longer returns is marked deleted. When Telegram's answer does not line up with the ids asked for, the batch marks nothing and the next run tries again.
With `DELETION_MODE=soft`, the default, the row stays: `is_deleted` becomes 1 and `deleted_at` records the time. With `hard` the row is removed and there is nothing left to mark.
diff --git a/docs/design/edited-messages.md b/docs/design/edited-messages.md
index 165df0fd..6b5091a9 100644
--- a/docs/design/edited-messages.md
+++ b/docs/design/edited-messages.md
@@ -24,7 +24,7 @@ In short, we recommend A with G's tooltip wording for the mark, C for a quick lo
Two paths can tell the archive that a message changed. Both are off by default, so a default install records no edit to a message it has already archived.
- **The listener** (`ENABLE_LISTENER=true`, with `LISTEN_EDITS=true`, which is the default once the listener runs). Telegram sends it an event for each edit while it is connected. `on_message_edited` in [`listener.py`](../../telegram_archive/listener.py) reads the new text and Telegram's `edit_date` and hands them to `update_message_text` in [`db/adapter.py`](../../telegram_archive/db/adapter.py).
-- **The sync** (`SYNC_DELETIONS_EDITS=true`). During a backup run, `_sync_deletions_and_edits` in [`telegram_backup.py`](../../telegram_archive/telegram_backup.py) asks Telegram for every archived message (or those posted in the last `SYNC_DELETIONS_EDITS_DAYS` days), 100 at a time, and calls the same `update_message_text` for each one whose `edit_date` differs from the stored one.
+- **The sync** (`SYNC_DELETIONS_EDITS=true`). During a backup run, `_sync_deletions_and_edits` in [`telegram_backup.py`](../../telegram_archive/telegram_backup.py) asks Telegram for every archived message (or those posted in the last `SYNC_DELETIONS_EDITS_DAYS` days, plus a slice of older ones per run with `SYNC_DELETIONS_EDITS_OLDER_PER_RUN`), 100 at a time, and calls the same `update_message_text` for each one whose `edit_date` differs from the stored one.
A third, smaller path exists: a backup, gap fill or import that reads a message the archive already holds applies a changed text when its `edit_date` is the same as or newer than the stored one (`_should_apply_upsert_text`). Equal counts on purpose: the listener and the backup can deliver the same edit. A normal backup run never reads old messages again, so in practice this only matters for imports and gap fills.
diff --git a/docs/reference/environment-variables.md b/docs/reference/environment-variables.md
index 2a27e41b..95ca8fda 100644
--- a/docs/reference/environment-variables.md
+++ b/docs/reference/environment-variables.md
@@ -177,7 +177,8 @@ Feature page: [Schedule and backup tuning](../configuration/schedule.md).
| `BATCH_SIZE` | `100` | backup | Messages written per database batch. Not clamped. |
| `CHECKPOINT_INTERVAL` | `1` | backup | Save the chat's progress every N batches. Floored at 1. |
| `SYNC_DELETIONS_EDITS` | `false` | backup | Re-read every archived message each run to catch edits and deletions. Slow on large archives. `SYNC_DELETIONS_EDITS_DAYS` limits it to recent posts. Deletions follow `DELETION_MODE`. The mass-operation limit does not apply to it, and it never fires the event webhook. |
-| `SYNC_DELETIONS_EDITS_DAYS` | `0` | backup | Limit `SYNC_DELETIONS_EDITS` to messages posted in the last N days. `0` re-reads every archived message. Floored at 0. A non-number stops startup. Changes to older messages wait for a run with `0`. See [Checking only recent messages](../configuration/schedule.md#sync-window). |
+| `SYNC_DELETIONS_EDITS_DAYS` | `0` | backup | Limit `SYNC_DELETIONS_EDITS` to messages posted in the last N days. `0` re-reads every archived message. Floored at 0. A non-number stops startup. Changes to older messages wait for a run with `0`, or for `SYNC_DELETIONS_EDITS_OLDER_PER_RUN`. See [Checking only recent messages](../configuration/schedule.md#sync-window). |
+| `SYNC_DELETIONS_EDITS_OLDER_PER_RUN` | `0` | backup | With `SYNC_DELETIONS_EDITS=true` and `SYNC_DELETIONS_EDITS_DAYS` above 0, also re-check up to this many messages older than the window on each run, for each account. Each request to Telegram counts as 100, even when a chat has fewer. The chats whose last full check is oldest go first, and a chat resumes where the last run stopped. Every archived message is re-checked over several runs. Telegram takes about 100 seconds per 1000 messages. `0` turns it off. Floored at 0. A non-integer stops startup. Deletions follow `DELETION_MODE`. See [Re-checking older messages over several runs](../configuration/schedule.md#sync-rotation). |
| `FILL_GAPS` | `false` | backup | Run gap-fill after the startup backup and after each scheduled backup. The one-shot `backup` command never runs it. |
| `GAP_THRESHOLD` | `50` | backup | A gap is a jump between stored message ids larger than this. `fill-gaps --threshold` overrides it. |
| `DIALOG_FLOOD_SLEEP_THRESHOLD` | `60` | backup | While listing dialogs, the backup waits out a FloodWait of up to this many seconds. `0` fails at once. |
diff --git a/telegram_archive/alembic/versions/20261124_044_add_full_sync_rotation.py b/telegram_archive/alembic/versions/20261124_044_add_full_sync_rotation.py
new file mode 100644
index 00000000..bd37c394
--- /dev/null
+++ b/telegram_archive/alembic/versions/20261124_044_add_full_sync_rotation.py
@@ -0,0 +1,65 @@
+"""Track the rotating full deletion and edit pass per chat, on sync_status.
+
+With SYNC_DELETIONS_EDITS_DAYS above 0 a run re-checks only recent messages.
+SYNC_DELETIONS_EDITS_OLDER_PER_RUN (#641) re-checks older messages a slice per
+run, rotating over the chats whose last full pass is oldest. Two columns hold
+where each (account, chat) stands:
+
+- ``full_sync_cursor``: the pass has checked every older message with an id at
+ or above it and continues below it. NULL starts at the newest one.
+- ``full_sync_completed_at``: when the last pass reached the oldest message.
+ NULL means the chat never finished one, so it goes first.
+
+Both are progress bookkeeping, not observed archive state, and move in place.
+Nullable, no backfill: every existing chat starts as never completed.
+
+Idempotent in both directions: a create_all() database already has the columns
+from the model declarations, and the entrypoint stamping ladder stops at 018,
+so every later migration may meet a schema that already holds its objects.
+
+Revision ID: 044
+Revises: 043
+Create Date: 2026-11-24
+"""
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# The chain may be renumbered at merge time: these two lines are the only place.
+revision: str = "044"
+down_revision: str | None = "043"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+TABLE = "sync_status"
+COLUMNS: tuple[tuple[str, sa.types.TypeEngine], ...] = (
+ ("full_sync_cursor", sa.BigInteger()),
+ ("full_sync_completed_at", sa.DateTime()),
+)
+
+
+def _existing_columns(inspector: sa.Inspector) -> set[str] | None:
+ """Column names of sync_status, or None when the table is absent."""
+ if TABLE not in set(inspector.get_table_names()):
+ return None
+ return {c["name"] for c in inspector.get_columns(TABLE)}
+
+
+def upgrade() -> None:
+ existing = _existing_columns(sa.inspect(op.get_bind()))
+ if existing is None:
+ return
+ for name, type_ in COLUMNS:
+ if name not in existing:
+ op.add_column(TABLE, sa.Column(name, type_, nullable=True))
+
+
+def downgrade() -> None:
+ existing = _existing_columns(sa.inspect(op.get_bind()))
+ if existing is None:
+ return
+ for name, _type in COLUMNS:
+ if name in existing:
+ op.drop_column(TABLE, name)
diff --git a/telegram_archive/config.py b/telegram_archive/config.py
index 28127835..40381cfc 100644
--- a/telegram_archive/config.py
+++ b/telegram_archive/config.py
@@ -112,6 +112,25 @@ def sync_deletions_edits_window(config) -> float:
return days
+def sync_deletions_edits_older_budget(config) -> int:
+ """How many older messages the rotating full pass re-checks per run, or 0 when off.
+
+ SYNC_DELETIONS_EDITS_OLDER_PER_RUN (#641) only means something with
+ SYNC_DELETIONS_EDITS on and SYNC_DELETIONS_EDITS_DAYS above 0: with no window
+ every run already re-reads every message. Test doubles built on MagicMock
+ answer any attribute with a mock, which must read as 0, so a mock config
+ keeps today's behaviour.
+ """
+ if getattr(config, "sync_deletions_edits", False) is not True:
+ return 0
+ if sync_deletions_edits_window(config) <= 0:
+ return 0
+ budget = getattr(config, "sync_deletions_edits_older_per_run", 0)
+ if isinstance(budget, bool) or not isinstance(budget, int):
+ return 0
+ return max(0, budget)
+
+
def _parse_float_env(name: str, default: float) -> float:
"""os.getenv(name) as a finite float that FAILS BY NAME.
@@ -992,6 +1011,12 @@ def __init__(self):
# millions of messages takes days. 0 (default) re-reads every stored message.
self.sync_deletions_edits_days: float = max(0.0, _parse_float_env("SYNC_DELETIONS_EDITS_DAYS", 0.0))
+ # SYNC_DELETIONS_EDITS_OLDER_PER_RUN: with a window set, also re-check up to
+ # this many OLDER messages per run, rotating over the chats whose last full
+ # pass is oldest (#641). 0 (default) leaves older messages to a run with
+ # SYNC_DELETIONS_EDITS_DAYS=0, as before.
+ self.sync_deletions_edits_older_per_run: int = max(0, _parse_int_env("SYNC_DELETIONS_EDITS_OLDER_PER_RUN", 0))
+
# Media verification mode
# When enabled, checks all media files on disk and re-downloads missing/corrupted ones
# Useful for recovering from interrupted backups or deleted media files
@@ -1313,6 +1338,12 @@ def log_summary(self) -> None:
"SYNC_DELETIONS_EDITS enabled - this will check messages from the last "
f"{days:g} days for deletions/edits"
)
+ budget = sync_deletions_edits_older_budget(self)
+ if budget > 0:
+ logger.warning(
+ f"SYNC_DELETIONS_EDITS_OLDER_PER_RUN={budget} - each run also re-checks up to {budget} "
+ "older messages, rotating over the chats whose last full pass is oldest"
+ )
else:
logger.warning(
"SYNC_DELETIONS_EDITS enabled - this will check ALL messages for deletions/edits (expensive!)"
diff --git a/telegram_archive/db/adapter.py b/telegram_archive/db/adapter.py
index 7cd27f3b..cb190a3c 100644
--- a/telegram_archive/db/adapter.py
+++ b/telegram_archive/db/adapter.py
@@ -2935,12 +2935,24 @@ async def find_message_by_date(
return self._message_to_dict(message) if message else None
async def get_messages_sync_data(
- self, chat_id: int, *, account_id: int, since: datetime | None = None
+ self,
+ chat_id: int,
+ *,
+ account_id: int,
+ since: datetime | None = None,
+ before: datetime | None = None,
+ below_id: int | None = None,
+ limit: int | None = None,
) -> dict[int, str | None]:
"""Get message IDs and their edit dates for sync checking.
``since`` keeps only messages posted at or after it, highest id first
(SYNC_DELETIONS_EDITS_DAYS, #608). None returns every stored message.
+
+ ``before`` is the other side of that window: only messages posted
+ before it, highest id first, for the rotating full pass (#641).
+ ``below_id`` resumes that pass under its cursor (ids strictly below it)
+ and ``limit`` caps the slice to the run's remaining budget.
"""
async with self.db_manager.async_session_factory() as session:
# Exclude soft-deleted rows so sync doesn't re-check them. The is_(None) arm is
@@ -2953,17 +2965,76 @@ async def get_messages_sync_data(
)
)
if since is not None:
- stmt = stmt.where(Message.date >= since).order_by(Message.id.desc())
+ stmt = stmt.where(Message.date >= since)
+ if before is not None:
+ stmt = stmt.where(Message.date < before)
+ if below_id is not None:
+ stmt = stmt.where(Message.id < below_id)
+ # A filtered or capped read walks down from the newest id: a LIMIT
+ # with no order would return an arbitrary slice.
+ if since is not None or before is not None or below_id is not None or limit is not None:
+ stmt = stmt.order_by(Message.id.desc())
+ if limit is not None:
+ stmt = stmt.limit(limit)
result = await session.execute(stmt)
return {row.id: row.edit_date for row in result}
- async def get_unflagged_edit_ids(self, chat_id: int, *, account_id: int) -> set[int]:
+ async def get_full_sync_rotation(self, *, account_id: int) -> dict[int, tuple[int | None, datetime | None]]:
+ """``{chat_id: (full_sync_cursor, full_sync_completed_at)}`` of one account (#641).
+
+ Every sync_status row of the account; the caller keeps the chats its run
+ backs up. A chat with no row has never started a pass.
+ """
+ async with self.db_manager.async_session_factory() as session:
+ stmt = select(SyncStatus.chat_id, SyncStatus.full_sync_cursor, SyncStatus.full_sync_completed_at).where(
+ SyncStatus.account_id == account_id
+ )
+ result = await session.execute(stmt)
+ return {row.chat_id: (row.full_sync_cursor, row.full_sync_completed_at) for row in result}
+
+ @retry_on_locked()
+ async def save_full_sync_progress(
+ self, chat_id: int, *, account_id: int, cursor: int | None, completed_at: datetime | None = None
+ ) -> None:
+ """Move the rotating full pass of one chat (#641).
+
+ With ``completed_at`` None the pass is still running: ``cursor`` is the
+ lowest id it has checked, and the completion time stays as it is. With
+ ``completed_at`` set the pass reached the oldest message: it is recorded
+ and the cursor goes back to None, so the next pass starts at the top.
+ Upserts, so a chat archived before it had a sync_status row gets one
+ with the same zero counters a first backup would write.
+ """
+ async with self.db_manager.async_session_factory() as session:
+ values = {
+ "account_id": account_id,
+ "chat_id": chat_id,
+ "last_message_id": 0,
+ "message_count": 0,
+ "full_sync_cursor": None if completed_at is not None else cursor,
+ "full_sync_completed_at": completed_at,
+ }
+ insert = sqlite_insert if self._is_sqlite else pg_insert
+ stmt = insert(SyncStatus).values(**values)
+ set_ = {"full_sync_cursor": stmt.excluded.full_sync_cursor}
+ if completed_at is not None:
+ set_["full_sync_completed_at"] = stmt.excluded.full_sync_completed_at
+ stmt = stmt.on_conflict_do_update(index_elements=["account_id", "chat_id"], set_=set_)
+ await session.execute(stmt)
+ await session.commit()
+
+ async def get_unflagged_edit_ids(
+ self, chat_id: int, *, account_id: int, id_range: tuple[int, int] | None = None
+ ) -> set[int]:
"""IDs of a chat's messages with ``edit_date`` set and no ``edit_hide`` flag.
These rows were archived before migration 034 kept the flag. The sync
pass fills the flag for them from the message it already fetched when
the edit_date matches, so a reaction Telegram hid stops showing as an
edit. The set shrinks to nothing as the flags are filled.
+
+ ``id_range`` (lowest, highest), both inclusive, keeps only the ids of one
+ slice: the rotating older-message pass (#641) reads a slice, not the chat.
"""
async with self.db_manager.async_session_factory() as session:
stmt = select(Message.id).where(
@@ -2975,6 +3046,8 @@ async def get_unflagged_edit_ids(self, chat_id: int, *, account_id: int) -> set[
or_(Message.is_deleted == 0, Message.is_deleted.is_(None)),
)
)
+ if id_range is not None:
+ stmt = stmt.where(Message.id.between(id_range[0], id_range[1]))
result = await session.execute(stmt)
return {row.id for row in result}
diff --git a/telegram_archive/db/models.py b/telegram_archive/db/models.py
index 71b4ee47..41d4a56c 100644
--- a/telegram_archive/db/models.py
+++ b/telegram_archive/db/models.py
@@ -811,6 +811,14 @@ class SyncStatus(Base):
last_message_id: Mapped[int] = mapped_column(BigInteger, default=0)
last_sync_date: Mapped[datetime] = mapped_column(DateTime, default=utcnow_naive, server_default=func.now())
message_count: Mapped[int] = mapped_column(Integer, default=0)
+ # Rotating full pass of SYNC_DELETIONS_EDITS_OLDER_PER_RUN (#641). Progress
+ # bookkeeping, not observed archive state, so both move in place.
+ # full_sync_cursor: the current pass has checked every older message with an
+ # id at or above it and continues below it; NULL starts at the newest one.
+ # full_sync_completed_at: when the last pass reached the chat's oldest
+ # message; NULL for a chat that never finished one, which goes first.
+ full_sync_cursor: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
+ full_sync_completed_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
# Relationship
chat: Mapped[Chat] = relationship("Chat", back_populates="sync_status")
diff --git a/telegram_archive/listener.py b/telegram_archive/listener.py
index 6d46d3d9..dd62c126 100644
--- a/telegram_archive/listener.py
+++ b/telegram_archive/listener.py
@@ -35,7 +35,7 @@
from telethon.utils import get_peer_id
from .avatar_utils import avatar_photo_id, get_avatar_paths
-from .config import AccountConfig, Config, sync_deletions_edits_window
+from .config import AccountConfig, Config, sync_deletions_edits_older_budget, sync_deletions_edits_window
from .custom_emoji import CUSTOM_EMOJI_BATCH, fetch_custom_emoji
from .db import DatabaseAdapter, create_adapter
from .db.models import account_metadata_key
@@ -1542,7 +1542,13 @@ def _log_blocked_deletions(self, message_ids: list[int]) -> None:
keeps these messages as they were; only a deletion sweep records them.
"""
days = sync_deletions_edits_window(self.config)
- if self.config.sync_deletions_edits is True and days > 0:
+ if self.config.sync_deletions_edits is True and days > 0 and sync_deletions_edits_older_budget(self.config) > 0:
+ recovery = (
+ f"SYNC_DELETIONS_EDITS is on with SYNC_DELETIONS_EDITS_DAYS={days:g}, so the next backup "
+ f"records those posted in the last {days:g} days; older ones when the rotation "
+ "(SYNC_DELETIONS_EDITS_OLDER_PER_RUN) reaches them"
+ )
+ elif self.config.sync_deletions_edits is True and days > 0:
recovery = (
f"SYNC_DELETIONS_EDITS is on with SYNC_DELETIONS_EDITS_DAYS={days:g}, so the next backup "
f"records those posted in the last {days:g} days; older ones only on a full pass "
diff --git a/telegram_archive/scheduler.py b/telegram_archive/scheduler.py
index 998edcef..310c3f9d 100644
--- a/telegram_archive/scheduler.py
+++ b/telegram_archive/scheduler.py
@@ -919,7 +919,7 @@ async def main():
"""Main entry point for the scheduler."""
try:
# Load configuration
- from .config import Config, setup_logging, sync_deletions_edits_window
+ from .config import Config, setup_logging, sync_deletions_edits_older_budget, sync_deletions_edits_window
config = Config()
setup_logging(config)
@@ -962,7 +962,14 @@ async def main():
days = sync_deletions_edits_window(config)
if days > 0:
logger.warning(f"β οΈ SYNC_DELETIONS_EDITS: ENABLED (messages from the last {days:g} days)")
- logger.warning(" β Older messages are re-checked only on a run with SYNC_DELETIONS_EDITS_DAYS=0")
+ budget = sync_deletions_edits_older_budget(config)
+ if budget > 0:
+ logger.warning(
+ f" β Older messages are re-checked up to {budget} per account per run, rotating over the chats "
+ "(SYNC_DELETIONS_EDITS_OLDER_PER_RUN)"
+ )
+ else:
+ logger.warning(" β Older messages are re-checked only on a run with SYNC_DELETIONS_EDITS_DAYS=0")
else:
logger.warning("β οΈ SYNC_DELETIONS_EDITS: ENABLED")
logger.warning(" β Will re-check ALL messages for edits/deletions each run")
diff --git a/telegram_archive/telegram_backup.py b/telegram_archive/telegram_backup.py
index 9b2a7ded..9ac49083 100644
--- a/telegram_archive/telegram_backup.py
+++ b/telegram_archive/telegram_backup.py
@@ -44,7 +44,7 @@
from . import LOGIN_DOCS_URL
from .avatar_utils import avatar_photo_id, get_avatar_paths
-from .config import AccountConfig, Config, sync_deletions_edits_window
+from .config import AccountConfig, Config, sync_deletions_edits_older_budget, sync_deletions_edits_window
from .custom_emoji import CUSTOM_EMOJI_MAX_ATTEMPTS, CUSTOM_EMOJI_MAX_PER_RUN, fetch_custom_emoji
from .db import DatabaseAdapter, create_adapter
from .db.models import account_metadata_key
@@ -1669,6 +1669,20 @@ def dialog_sort_key(d):
# topics/folders/statistics cannot drop the cursor update.
await self._finalize_resweep_cycle()
+ # Rotating full deletion and edit pass over older messages (#641),
+ # only over the chats this run backed up. Its progress is saved per
+ # batch, and a failure here must never cost the run its folders/stats.
+ if sync_deletions_edits_older_budget(self.config) > 0:
+ rotation_entities: dict[int, object] = {}
+ for dialog in list(filtered_dialogs) + list(archived_to_backup):
+ dialog_chat_id = self._get_marked_id(dialog.entity)
+ if dialog_chat_id in backed_up_chat_ids:
+ rotation_entities.setdefault(dialog_chat_id, dialog.entity)
+ try:
+ await self._rotate_full_sync(rotation_entities)
+ except Exception as e:
+ logger.error(f"Older-message rotation failed (resumes next run): {describe_exception(e)}")
+
# Reconcile groupβsupergroup migrations (#228): warn (count-only)
# about tracked groups that migrated out of scope, and β when
# FOLLOW_CHAT_MIGRATIONS is on β adopt + capture the new supergroup.
@@ -3468,103 +3482,11 @@ async def _sync_deletions_and_edits(self, chat_id: int, entity):
batch_ids = local_ids[i : i + batch_size]
try:
- # Fetch current state from Telegram
- remote_messages = await call_with_flood_retry(self.client.get_messages, entity, ids=batch_ids)
-
- # Telethon buffers one entry per RETURNED message, and its own
- # comment warns Telegram "may decide to not send" invalid ids at
- # all on the non-channel path β one omission shifts every later
- # position, and a positional zip would overwrite message A's
- # text with message B's or hard-delete a live message. Trust
- # positions only when the response provably lines up; otherwise
- # key by id and treat unmatched ids as unknown β a destructive
- # write never rides an ambiguous signal.
- aligned = len(remote_messages) == len(batch_ids) and all(
- remote_msg is None or remote_msg.id == msg_id
- for msg_id, remote_msg in zip(batch_ids, remote_messages)
+ deleted, updated = await self._sync_message_batch(
+ chat_id, entity, batch_ids, local_messages, unflagged_ids
)
- if aligned:
- pairs = list(zip(batch_ids, remote_messages))
- else:
- remote_by_id = {m.id: m for m in remote_messages if m is not None}
- pairs = [(msg_id, remote_by_id.get(msg_id)) for msg_id in batch_ids]
- unmatched = len(batch_ids) - sum(1 for _, m in pairs if m is not None)
- logger.warning(
- f" β Sync response misaligned for a batch ({unmatched} of {len(batch_ids)} ids "
- "unmatched) β treating the unmatched ids as unknown this run, no deletions for them"
- )
-
- for msg_id, remote_msg in pairs:
- # Check for deletion
- if remote_msg is None:
- if not aligned:
- # Ambiguous: the id was omitted from a misaligned
- # response, not confirmed deleted. Retry next run.
- continue
- if getattr(self.config, "deletion_mode", "soft") == "soft":
- # mark_message_deleted defaults deleted_at to now(UTC); this path
- # doesn't broadcast, so no need to pass an explicit timestamp.
- await self.db.mark_message_deleted(chat_id, msg_id, account_id=self.account_id)
- else:
- await self.db.delete_message(chat_id, msg_id, account_id=self.account_id)
- total_deleted += 1
- continue
-
- # Check for edits. Telethon delivers tz-aware UTC datetimes
- # while the archive stores naive UTC β normalize before
- # comparing, otherwise every previously-edited message looks
- # changed on every sync pass and pays a pointless locked
- # update round-trip.
- remote_edit_date = remote_msg.edit_date
- if remote_edit_date is not None and remote_edit_date.tzinfo is not None:
- remote_edit_date = remote_edit_date.replace(tzinfo=None)
- local_edit_date = local_messages[msg_id]
-
- if remote_edit_date and remote_edit_date == local_edit_date and msg_id in unflagged_ids:
- # Same edit, archived before the flag was kept: fill the
- # flag only. Text, edit_date and versions stay as they are.
- await self.db.fill_edit_hide(
- chat_id,
- msg_id,
- remote_edit_date,
- message_edit_hide(remote_msg),
- account_id=self.account_id,
- )
- elif remote_edit_date and remote_edit_date != local_edit_date:
- # An edit may have replaced the photo or file: the old
- # media is kept as a version before the text moves, so
- # both carry the date the old state began.
- media_replaced = await self._keep_replaced_media(remote_msg, chat_id, "sync")
- # Update text and edit_date; count only edits the archive
- # actually accepted (the adapter re-checks under lock).
- outcome = await self._apply_edit(remote_msg, chat_id, "sync", media_changed=media_replaced)
- if outcome == "applied":
- total_updated += 1
- if media_replaced:
- await self._download_replaced_media(remote_msg, chat_id)
-
- # A poll's votes or closing, or a changed link preview, moves no
- # edit_date: the message is in hand, so its state is compared
- # with the newest kept on every pass.
- await self._keep_snapshots(remote_msg, chat_id, "sync")
-
- # Piggyback reaction reconcile (#221): the full message is already
- # in hand, so harvest its reactions at zero extra API cost. Skip
- # None (extraction failure) and min payloads (partial; may omit the
- # account's own reaction β false tombstone). PII: aggregate only.
- reactions_obj = getattr(remote_msg, "reactions", None)
- if not getattr(reactions_obj, "min", False):
- observed = extract_reactions(reactions_obj)
- if observed is not None:
- await self.db.reconcile_reactions(
- msg_id,
- chat_id,
- observed,
- mark_removed=True,
- account_id=self.account_id,
- source="backup",
- )
-
+ total_deleted += deleted
+ total_updated += updated
except Exception as e:
logger.error(f"Error syncing batch for chat: {describe_exception(e)}")
@@ -3575,6 +3497,237 @@ async def _sync_deletions_and_edits(self, chat_id: int, entity):
if total_deleted > 0 or total_updated > 0:
logger.info(f" β Sync result: {total_deleted} deleted, {total_updated} updated")
+ async def _rotate_full_sync(self, entities: dict[int, object]) -> None:
+ """Re-check a budgeted slice of OLDER messages, rotating over chats (#641).
+
+ With SYNC_DELETIONS_EDITS_DAYS above 0 the per-chat pass reads only the
+ window; older messages were re-checked only by a run with DAYS=0, which
+ on a large archive takes many hours. SYNC_DELETIONS_EDITS_OLDER_PER_RUN
+ spreads that full pass over runs: each run re-checks up to that many
+ messages posted before the window, shared across chats.
+
+ ``entities`` maps the chats this run backed up to their entity, so a chat
+ outside CHAT_IDS, excluded, skipped or forbidden is never touched. The
+ chats go in order of their last completed pass, never-completed first.
+ A chat resumes below its saved cursor, which moves after every batch, so
+ a crash or FloodWait loses one batch at most. A chat whose slice reaches
+ its oldest message records the completion and starts over at the top
+ next time. Each chat is visited once per run, so a budget larger than
+ the older messages of every chat gives each a full pass every run.
+ """
+ budget = sync_deletions_edits_older_budget(self.config)
+ if budget <= 0 or not entities:
+ return
+ # Taken after the per-chat window passes, so this bound is a little
+ # later than theirs: messages on the boundary are checked twice rather
+ # than not at all.
+ before = utcnow_naive() - timedelta(days=sync_deletions_edits_window(self.config))
+ state = await self.db.get_full_sync_rotation(account_id=self.account_id)
+
+ def rotation_order(chat_id: int) -> tuple:
+ # Never-completed chats first; within each group a chat in the middle
+ # of a pass goes before one that has not started, so a chat added to
+ # the selection cannot push a half-checked chat back.
+ cursor, completed_at = state.get(chat_id, (None, None))
+ return (completed_at is not None, cursor is None, completed_at or datetime.min, chat_id)
+
+ remaining = budget
+ checked = deleted = updated = chats_visited = failed = 0
+ completed_now: set[int] = set()
+ flood_stopped = False
+ for chat_id in sorted(entities, key=rotation_order):
+ if remaining <= 0:
+ break
+ entity = entities[chat_id]
+ cursor = state.get(chat_id, (None, None))[0]
+ limit = remaining
+ chats_visited += 1
+ try:
+ local_messages = await self.db.get_messages_sync_data(
+ chat_id, account_id=self.account_id, before=before, below_id=cursor, limit=limit
+ )
+ if local_messages:
+ logger.info(
+ f" β Older-message rotation: checking {len(local_messages)} older messages"
+ f"{chat_title_for_log(entity, self.config)}"
+ )
+ local_ids = list(local_messages)
+ unflagged_ids = await self.db.get_unflagged_edit_ids(
+ chat_id, account_id=self.account_id, id_range=(min(local_ids), max(local_ids))
+ )
+ for i in range(0, len(local_ids), 100):
+ batch_ids = local_ids[i : i + 100]
+ # Telegram limits requests, not ids: a short batch costs a
+ # full one, so many small chats cannot stretch a run past
+ # budget / 100 requests.
+ remaining -= max(len(batch_ids), 100)
+ try:
+ batch_deleted, batch_updated = await self._sync_message_batch(
+ chat_id, entity, batch_ids, local_messages, unflagged_ids
+ )
+ except (FloodWaitError, FloodPremiumWaitError) as e:
+ # Telegram wants a longer pause than the retry absorbs: the
+ # cursor stays above this batch and the rest waits a run.
+ logger.warning(
+ f" β Older-message rotation stopped for this run: {describe_exception(e)}; "
+ "it resumes at the same message next run"
+ )
+ flood_stopped = True
+ break
+ except Exception as e:
+ # Transient errors were already retried, so this one is
+ # likely to repeat. Like the window pass, skip the batch:
+ # the cursor moves past it and the next pass tries it
+ # again, so one bad batch cannot stall the chat.
+ logger.error(
+ f" β Older-message rotation: skipped a batch after an error: {describe_exception(e)}"
+ )
+ failed += len(batch_ids)
+ else:
+ checked += len(batch_ids)
+ deleted += batch_deleted
+ updated += batch_updated
+ await self.db.save_full_sync_progress(chat_id, account_id=self.account_id, cursor=batch_ids[-1])
+ if flood_stopped:
+ break
+ if len(local_messages) < limit:
+ # Fewer than asked for: the slice reached the chat's oldest message.
+ await self.db.save_full_sync_progress(
+ chat_id, account_id=self.account_id, cursor=None, completed_at=utcnow_naive()
+ )
+ completed_now.add(chat_id)
+ except Exception as e:
+ # A database error for one chat keeps its saved progress; the
+ # other chats still get the rest of the budget.
+ logger.error(
+ f" β Older-message rotation: error in a chat, its progress is kept: {describe_exception(e)}"
+ )
+
+ never_completed = sum(
+ 1 for chat_id in entities if state.get(chat_id, (None, None))[1] is None and chat_id not in completed_now
+ )
+ logger.info(
+ f"Older-message rotation: re-checked {checked} older messages in {chats_visited} chat(s), "
+ f"{deleted} deleted, {updated} updated; {len(completed_now)} chat(s) finished a pass, "
+ f"{never_completed} of {len(entities)} have not finished one yet"
+ + (f"; {failed} skipped after errors, re-checked next pass" if failed else "")
+ + ("; stopped early after a FloodWait" if flood_stopped else "")
+ )
+
+ async def _sync_message_batch(
+ self,
+ chat_id: int,
+ entity,
+ batch_ids: list[int],
+ local_messages: dict,
+ unflagged_ids: set[int],
+ ) -> tuple[int, int]:
+ """Check one batch of up to 100 stored ids against Telegram: ``(deleted, updated)``.
+
+ The body of the deletion and edit sync, shared by the per-chat pass and
+ the rotating full pass (#641). Raises when the fetch fails; the caller
+ decides whether to skip the batch or stop.
+ """
+ deleted = 0
+ updated = 0
+ # Fetch current state from Telegram
+ remote_messages = await call_with_flood_retry(self.client.get_messages, entity, ids=batch_ids)
+
+ # Telethon buffers one entry per RETURNED message, and its own
+ # comment warns Telegram "may decide to not send" invalid ids at
+ # all on the non-channel path β one omission shifts every later
+ # position, and a positional zip would overwrite message A's
+ # text with message B's or hard-delete a live message. Trust
+ # positions only when the response provably lines up; otherwise
+ # key by id and treat unmatched ids as unknown β a destructive
+ # write never rides an ambiguous signal.
+ aligned = len(remote_messages) == len(batch_ids) and all(
+ remote_msg is None or remote_msg.id == msg_id for msg_id, remote_msg in zip(batch_ids, remote_messages)
+ )
+ if aligned:
+ pairs = list(zip(batch_ids, remote_messages))
+ else:
+ remote_by_id = {m.id: m for m in remote_messages if m is not None}
+ pairs = [(msg_id, remote_by_id.get(msg_id)) for msg_id in batch_ids]
+ unmatched = len(batch_ids) - sum(1 for _, m in pairs if m is not None)
+ logger.warning(
+ f" β Sync response misaligned for a batch ({unmatched} of {len(batch_ids)} ids "
+ "unmatched) β treating the unmatched ids as unknown this run, no deletions for them"
+ )
+
+ for msg_id, remote_msg in pairs:
+ # Check for deletion
+ if remote_msg is None:
+ if not aligned:
+ # Ambiguous: the id was omitted from a misaligned
+ # response, not confirmed deleted. Retry next run.
+ continue
+ if getattr(self.config, "deletion_mode", "soft") == "soft":
+ # mark_message_deleted defaults deleted_at to now(UTC); this path
+ # doesn't broadcast, so no need to pass an explicit timestamp.
+ await self.db.mark_message_deleted(chat_id, msg_id, account_id=self.account_id)
+ else:
+ await self.db.delete_message(chat_id, msg_id, account_id=self.account_id)
+ deleted += 1
+ continue
+
+ # Check for edits. Telethon delivers tz-aware UTC datetimes
+ # while the archive stores naive UTC β normalize before
+ # comparing, otherwise every previously-edited message looks
+ # changed on every sync pass and pays a pointless locked
+ # update round-trip.
+ remote_edit_date = remote_msg.edit_date
+ if remote_edit_date is not None and remote_edit_date.tzinfo is not None:
+ remote_edit_date = remote_edit_date.replace(tzinfo=None)
+ local_edit_date = local_messages[msg_id]
+
+ if remote_edit_date and remote_edit_date == local_edit_date and msg_id in unflagged_ids:
+ # Same edit, archived before the flag was kept: fill the
+ # flag only. Text, edit_date and versions stay as they are.
+ await self.db.fill_edit_hide(
+ chat_id,
+ msg_id,
+ remote_edit_date,
+ message_edit_hide(remote_msg),
+ account_id=self.account_id,
+ )
+ elif remote_edit_date and remote_edit_date != local_edit_date:
+ # An edit may have replaced the photo or file: the old
+ # media is kept as a version before the text moves, so
+ # both carry the date the old state began.
+ media_replaced = await self._keep_replaced_media(remote_msg, chat_id, "sync")
+ # Update text and edit_date; count only edits the archive
+ # actually accepted (the adapter re-checks under lock).
+ outcome = await self._apply_edit(remote_msg, chat_id, "sync", media_changed=media_replaced)
+ if outcome == "applied":
+ updated += 1
+ if media_replaced:
+ await self._download_replaced_media(remote_msg, chat_id)
+
+ # A poll's votes or closing, or a changed link preview, moves no
+ # edit_date: the message is in hand, so its state is compared
+ # with the newest kept on every pass.
+ await self._keep_snapshots(remote_msg, chat_id, "sync")
+
+ # Piggyback reaction reconcile (#221): the full message is already
+ # in hand, so harvest its reactions at zero extra API cost. Skip
+ # None (extraction failure) and min payloads (partial; may omit the
+ # account's own reaction β false tombstone). PII: aggregate only.
+ reactions_obj = getattr(remote_msg, "reactions", None)
+ if not getattr(reactions_obj, "min", False):
+ observed = extract_reactions(reactions_obj)
+ if observed is not None:
+ await self.db.reconcile_reactions(
+ msg_id,
+ chat_id,
+ observed,
+ mark_removed=True,
+ account_id=self.account_id,
+ source="backup",
+ )
+
+ return deleted, updated
+
def _ensure_resweep_state(self) -> None:
"""Lazy-init the per-run re-sweep pacing/deferral state (#224).
diff --git a/tests/test_full_sync_rotation.py b/tests/test_full_sync_rotation.py
new file mode 100644
index 00000000..a3733262
--- /dev/null
+++ b/tests/test_full_sync_rotation.py
@@ -0,0 +1,664 @@
+"""The rotating full deletion and edit pass, SYNC_DELETIONS_EDITS_OLDER_PER_RUN (#641).
+
+With SYNC_DELETIONS_EDITS_DAYS above 0 a run re-checks only recent messages.
+The rotation re-checks older messages a budgeted slice per run, over the chats
+whose last full pass is oldest, resuming each chat under a saved cursor.
+
+The rotation runs on ``real_adapter``, so its queries and the sync_status
+bookkeeping are compiled and run by SQLite and PostgreSQL. Telegram is a small
+fake that answers ``get_messages`` by id and records every request.
+"""
+
+import asyncio
+import os
+import shutil
+import tempfile
+import unittest
+from datetime import datetime, timedelta
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+import pytest
+from telethon.errors import FloodWaitError
+from telethon.tl.types import User
+
+from telegram_archive import telegram_backup
+from telegram_archive.config import Config, sync_deletions_edits_older_budget
+from telegram_archive.message_utils import utcnow_naive
+from telegram_archive.telegram_backup import TelegramBackup
+
+# Invented chats. Obviously fake ids, no titles.
+CHAT_A = 641001
+CHAT_B = 641002
+CHAT_C = 641003
+DAYS = 30.0
+
+
+class FakeTelegram:
+ """Answers ``get_messages(entity, ids=...)`` in order, None for a gone id."""
+
+ def __init__(self, gone=(), fail_on_call=None, error=None):
+ self.calls: list[tuple[object, list[int]]] = []
+ self.gone = set(gone)
+ self.fail_on_call = fail_on_call
+ self.error = error
+
+ async def get_messages(self, entity, ids):
+ self.calls.append((entity, list(ids)))
+ if self.fail_on_call == len(self.calls):
+ raise self.error
+ return [None if i in self.gone else SimpleNamespace(id=i, edit_date=None, reactions=None) for i in ids]
+
+ def checked(self, entity=None) -> list[int]:
+ return [i for e, ids in self.calls if entity is None or e == entity for i in ids]
+
+
+def _backup(adapter, telegram, *, budget, account_id=1, days=DAYS, deletion_mode="soft"):
+ backup = TelegramBackup.__new__(TelegramBackup)
+ backup.account_id = account_id
+ backup.config = SimpleNamespace(
+ sync_deletions_edits=True,
+ sync_deletions_edits_days=days,
+ sync_deletions_edits_older_per_run=budget,
+ deletion_mode=deletion_mode,
+ log_chat_titles=False,
+ )
+ backup.db = adapter
+ backup.client = telegram
+ backup._keep_snapshots = AsyncMock()
+ return backup
+
+
+async def _seed(adapter, chat_id, *, older=(), recent=(), account_id=1):
+ """A private chat with ``older`` ids posted 100 days ago and ``recent`` ids 1 day ago."""
+ await adapter.upsert_chat({"id": chat_id, "type": "private", "first_name": "Sample"}, account_id=account_id)
+ now = utcnow_naive()
+ rows = [{"id": i, "chat_id": chat_id, "date": now - timedelta(days=100), "text": "t"} for i in older]
+ rows += [{"id": i, "chat_id": chat_id, "date": now - timedelta(days=1), "text": "t"} for i in recent]
+ if rows:
+ await adapter.insert_messages_batch(rows, account_id=account_id)
+
+
+async def _state(adapter, chat_id, account_id=1):
+ return (await adapter.get_full_sync_rotation(account_id=account_id)).get(chat_id, (None, None))
+
+
+@pytest.mark.asyncio
+async def test_the_slice_reads_only_older_messages_newest_first(real_adapter):
+ """The window is the per-chat pass's job; the rotation reads below it, highest id first."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 51), recent=range(51, 61))
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=1000)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ assert telegram.checked() == list(range(50, 0, -1))
+ assert [len(ids) for _, ids in telegram.calls] == [50]
+
+
+@pytest.mark.asyncio
+async def test_a_large_chat_resumes_from_its_cursor_then_wraps(real_adapter):
+ """250 older messages, 120 per run: two slices, a completing slice, then the top again."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 251))
+
+ run1 = FakeTelegram()
+ await _backup(real_adapter, run1, budget=120)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run1.checked() == list(range(250, 130, -1))
+ assert [len(ids) for _, ids in run1.calls] == [100, 20]
+ assert await _state(real_adapter, CHAT_A) == (131, None)
+
+ run2 = FakeTelegram()
+ await _backup(real_adapter, run2, budget=120)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run2.checked() == list(range(130, 10, -1))
+ assert await _state(real_adapter, CHAT_A) == (11, None)
+
+ run3 = FakeTelegram()
+ await _backup(real_adapter, run3, budget=120)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run3.checked() == list(range(10, 0, -1))
+ cursor, completed_at = await _state(real_adapter, CHAT_A)
+ assert cursor is None
+ assert completed_at is not None
+
+ run4 = FakeTelegram()
+ await _backup(real_adapter, run4, budget=120)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run4.checked() == list(range(250, 130, -1))
+
+
+@pytest.mark.asyncio
+async def test_a_slice_that_ends_exactly_on_the_oldest_completes_next_run_for_free(real_adapter):
+ await _seed(real_adapter, CHAT_A, older=range(1, 101))
+
+ await _backup(real_adapter, FakeTelegram(), budget=100)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert await _state(real_adapter, CHAT_A) == (1, None)
+
+ run2 = FakeTelegram()
+ await _backup(real_adapter, run2, budget=100)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run2.calls == []
+ cursor, completed_at = await _state(real_adapter, CHAT_A)
+ assert cursor is None and completed_at is not None
+
+
+@pytest.mark.asyncio
+async def test_the_budget_is_shared_across_chats(real_adapter):
+ """80 + 80 older messages and a budget of 200: one request each, and both chats finish."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 81))
+ await _seed(real_adapter, CHAT_B, older=range(1, 81))
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=200)._rotate_full_sync({CHAT_A: "entity-A", CHAT_B: "entity-B"})
+
+ assert len(telegram.checked("entity-A")) == 80
+ assert telegram.checked("entity-B") == list(range(80, 0, -1))
+ assert (await _state(real_adapter, CHAT_A))[1] is not None
+ assert (await _state(real_adapter, CHAT_B))[1] is not None
+
+
+@pytest.mark.asyncio
+async def test_each_request_costs_a_full_batch_of_budget(real_adapter):
+ """80 + 80 older messages and a budget of 120: the first chat's one request costs 100, the second gets 20."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 81))
+ await _seed(real_adapter, CHAT_B, older=range(1, 81))
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=120)._rotate_full_sync({CHAT_A: "entity-A", CHAT_B: "entity-B"})
+
+ assert len(telegram.checked("entity-A")) == 80
+ assert telegram.checked("entity-B") == list(range(80, 60, -1))
+ assert await _state(real_adapter, CHAT_B) == (61, None)
+
+
+@pytest.mark.asyncio
+async def test_many_small_chats_make_no_more_requests_than_the_budget_allows(real_adapter):
+ """Telegram limits requests, not ids: 30 chats of 3 older messages and a budget of 1000 make 10 requests."""
+ chats = {CHAT_A + n: f"entity-{n}" for n in range(30)}
+ for chat_id in chats:
+ await _seed(real_adapter, chat_id, older=range(1, 4))
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=1000)._rotate_full_sync(chats)
+
+ assert len(telegram.calls) == 10
+ state = await real_adapter.get_full_sync_rotation(account_id=1)
+ assert sum(1 for chat_id in chats if state.get(chat_id, (None, None))[1] is not None) == 10
+
+
+@pytest.mark.asyncio
+async def test_the_chat_whose_last_pass_is_oldest_goes_first_never_completed_before_all(real_adapter):
+ for chat_id in (CHAT_A, CHAT_B, CHAT_C):
+ await _seed(real_adapter, chat_id, older=range(1, 11))
+ now = utcnow_naive()
+ await real_adapter.save_full_sync_progress(CHAT_A, account_id=1, cursor=None, completed_at=now - timedelta(days=3))
+ await real_adapter.save_full_sync_progress(CHAT_C, account_id=1, cursor=None, completed_at=now - timedelta(days=9))
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=1000)._rotate_full_sync(
+ {CHAT_A: "entity-A", CHAT_B: "entity-B", CHAT_C: "entity-C"}
+ )
+
+ assert [entity for entity, _ in telegram.calls] == ["entity-B", "entity-C", "entity-A"]
+
+
+@pytest.mark.asyncio
+async def test_a_chat_in_the_middle_of_a_pass_goes_before_one_that_has_not_started(real_adapter):
+ """A chat added to the selection, with a lower id, must not push a half-checked chat back."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 301))
+ await _seed(real_adapter, CHAT_B, older=range(1, 301))
+ await real_adapter.save_full_sync_progress(CHAT_B, account_id=1, cursor=201)
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=100)._rotate_full_sync({CHAT_A: "entity-A", CHAT_B: "entity-B"})
+
+ assert telegram.checked() == list(range(200, 100, -1))
+ assert [entity for entity, _ in telegram.calls] == ["entity-B"]
+
+
+@pytest.mark.asyncio
+async def test_a_mid_pass_cursor_survives_while_the_completion_time_stays(real_adapter):
+ """Saving a cursor must not clear the last completion, or the chat would jump the queue."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 301))
+ earlier = utcnow_naive() - timedelta(days=5)
+ await real_adapter.save_full_sync_progress(CHAT_A, account_id=1, cursor=None, completed_at=earlier)
+
+ await _backup(real_adapter, FakeTelegram(), budget=100)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ cursor, completed_at = await _state(real_adapter, CHAT_A)
+ assert cursor == 201
+ assert completed_at == earlier.replace(microsecond=completed_at.microsecond)
+
+
+@pytest.mark.asyncio
+async def test_a_chat_with_no_older_messages_completes_without_a_request(real_adapter):
+ await _seed(real_adapter, CHAT_A, recent=range(1, 6))
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=50)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ assert telegram.calls == []
+ assert (await _state(real_adapter, CHAT_A))[1] is not None
+
+
+@pytest.mark.asyncio
+async def test_only_the_chats_handed_in_are_touched(real_adapter):
+ """A chat outside this run's selection keeps its state and costs nothing."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 11))
+ await _seed(real_adapter, CHAT_B, older=range(1, 11))
+ telegram = FakeTelegram()
+
+ await _backup(real_adapter, telegram, budget=1000)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ assert {entity for entity, _ in telegram.calls} == {"entity-A"}
+ assert await _state(real_adapter, CHAT_B) == (None, None)
+
+
+@pytest.mark.asyncio
+async def test_a_flood_wait_keeps_the_cursor_and_ends_the_runs_rotation(real_adapter):
+ await _seed(real_adapter, CHAT_A, older=range(1, 251))
+ await _seed(real_adapter, CHAT_B, older=range(1, 11))
+ flood = FloodWaitError(request=None, capture=telegram_backup.MAX_FLOOD_WAIT_SECONDS + 1)
+ telegram = FakeTelegram(fail_on_call=2, error=flood)
+
+ await _backup(real_adapter, telegram, budget=1000)._rotate_full_sync({CHAT_A: "entity-A", CHAT_B: "entity-B"})
+
+ assert await _state(real_adapter, CHAT_A) == (151, None)
+ assert telegram.checked("entity-B") == []
+ assert await _state(real_adapter, CHAT_B) == (None, None)
+
+ resumed = FakeTelegram()
+ await _backup(real_adapter, resumed, budget=1000)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert resumed.checked("entity-A")[0] == 150
+
+
+class PoisonTelegram(FakeTelegram):
+ """Fails every request that asks for ``poison``, the way a bug on one odd message would."""
+
+ def __init__(self, poison):
+ super().__init__()
+ self.poison = poison
+
+ async def get_messages(self, entity, ids):
+ if self.poison in ids:
+ self.calls.append((entity, list(ids)))
+ raise RuntimeError("boom")
+ return await super().get_messages(entity, ids)
+
+
+@pytest.mark.asyncio
+async def test_another_error_skips_the_batch_and_the_chat_carries_on(real_adapter):
+ """Like the window pass: the failed batch is skipped, the rest of the chat is still checked."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 251))
+ await _seed(real_adapter, CHAT_B, older=range(1, 11))
+ telegram = FakeTelegram(fail_on_call=2, error=RuntimeError("boom"))
+
+ await _backup(real_adapter, telegram, budget=1000)._rotate_full_sync({CHAT_A: "entity-A", CHAT_B: "entity-B"})
+
+ assert telegram.checked("entity-A") == list(range(250, 0, -1))
+ assert (await _state(real_adapter, CHAT_A))[1] is not None
+ assert len(telegram.checked("entity-B")) == 10
+ assert (await _state(real_adapter, CHAT_B))[1] is not None
+
+
+@pytest.mark.asyncio
+async def test_a_batch_that_always_fails_does_not_stall_the_chat_across_runs(real_adapter, caplog):
+ """A batch that fails on every run is passed over, so the pass reaches the chat's oldest message."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 501))
+
+ run1 = PoisonTelegram(poison=350)
+ await _backup(real_adapter, run1, budget=200)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert await _state(real_adapter, CHAT_A) == (301, None)
+
+ run2 = PoisonTelegram(poison=350)
+ await _backup(real_adapter, run2, budget=200)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run2.checked()[0] == 300
+ assert await _state(real_adapter, CHAT_A) == (101, None)
+
+ run3 = PoisonTelegram(poison=350)
+ with caplog.at_level("INFO", logger="telegram_archive.telegram_backup"):
+ await _backup(real_adapter, run3, budget=200)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run3.checked() == list(range(100, 0, -1))
+ assert (await _state(real_adapter, CHAT_A))[1] is not None
+
+ # The next pass starts at the top and asks for the failed batch again.
+ run4 = PoisonTelegram(poison=350)
+ await _backup(real_adapter, run4, budget=200)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert 350 in run4.checked()
+
+
+@pytest.mark.asyncio
+async def test_the_summary_counts_skipped_messages(real_adapter, caplog):
+ await _seed(real_adapter, CHAT_A, older=range(1, 201))
+
+ with caplog.at_level("INFO", logger="telegram_archive.telegram_backup"):
+ await _backup(real_adapter, PoisonTelegram(poison=150), budget=1000)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ assert "re-checked 100 older messages in 1 chat(s)" in caplog.text
+ assert "100 skipped after errors, re-checked next pass" in caplog.text
+
+
+@pytest.mark.asyncio
+async def test_a_database_error_in_one_chat_keeps_its_progress_and_the_next_chat_runs(real_adapter):
+ await _seed(real_adapter, CHAT_A, older=range(1, 251))
+ await _seed(real_adapter, CHAT_B, older=range(1, 11))
+ await real_adapter.save_full_sync_progress(CHAT_A, account_id=1, cursor=201)
+ backup = _backup(real_adapter, FakeTelegram(), budget=1000)
+ real_read = real_adapter.get_messages_sync_data
+
+ async def failing_read(chat_id, **kwargs):
+ if chat_id == CHAT_A:
+ raise RuntimeError("database gone for this chat")
+ return await real_read(chat_id, **kwargs)
+
+ with patch.object(real_adapter, "get_messages_sync_data", side_effect=failing_read):
+ await backup._rotate_full_sync({CHAT_A: "entity-A", CHAT_B: "entity-B"})
+
+ assert await _state(real_adapter, CHAT_A) == (201, None)
+ assert len(backup.client.checked("entity-B")) == 10
+ assert (await _state(real_adapter, CHAT_B))[1] is not None
+
+
+@pytest.mark.asyncio
+@pytest.mark.parametrize("deletion_mode", ["soft", "hard"])
+async def test_a_message_deleted_at_the_cursor_does_not_stall_the_pass(real_adapter, deletion_mode):
+ """The cursor is an id bound, not a row: the message under it may be gone next run."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 201))
+ telegram = FakeTelegram(gone={101})
+
+ await _backup(real_adapter, telegram, budget=100, deletion_mode=deletion_mode)._rotate_full_sync(
+ {CHAT_A: "entity-A"}
+ )
+ assert await _state(real_adapter, CHAT_A) == (101, None)
+ remaining = await real_adapter.get_messages_sync_data(CHAT_A, account_id=1)
+ assert 101 not in remaining
+
+ run2 = FakeTelegram()
+ await _backup(real_adapter, run2, budget=150)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run2.checked() == list(range(100, 0, -1))
+ assert (await _state(real_adapter, CHAT_A))[1] is not None
+
+
+@pytest.mark.asyncio
+async def test_each_account_keeps_its_own_rotation(real_adapter):
+ await _seed(real_adapter, CHAT_A, older=range(1, 201), account_id=1)
+ await _seed(real_adapter, CHAT_A, older=range(1, 201), account_id=2)
+
+ await _backup(real_adapter, FakeTelegram(), budget=100, account_id=1)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ assert await _state(real_adapter, CHAT_A, account_id=1) == (101, None)
+ assert await _state(real_adapter, CHAT_A, account_id=2) == (None, None)
+ run = FakeTelegram()
+ await _backup(real_adapter, run, budget=100, account_id=2)._rotate_full_sync({CHAT_A: "entity-A"})
+ assert run.checked()[0] == 200
+
+
+@pytest.mark.asyncio
+async def test_a_spent_budget_reads_no_further_chat(real_adapter):
+ """Once the budget is used up, the chats left over wait for the next run without a database read."""
+ for chat_id in (CHAT_A, CHAT_B, CHAT_C):
+ await _seed(real_adapter, chat_id, older=range(1, 101))
+ read_chats = []
+ real_read = real_adapter.get_messages_sync_data
+
+ async def counting_read(chat_id, **kwargs):
+ read_chats.append(chat_id)
+ return await real_read(chat_id, **kwargs)
+
+ with patch.object(real_adapter, "get_messages_sync_data", side_effect=counting_read):
+ await _backup(real_adapter, FakeTelegram(), budget=200)._rotate_full_sync(
+ {CHAT_A: "entity-A", CHAT_B: "entity-B", CHAT_C: "entity-C"}
+ )
+
+ assert read_chats == [CHAT_A, CHAT_B]
+ assert await _state(real_adapter, CHAT_C) == (None, None)
+
+
+@pytest.mark.asyncio
+async def test_recording_a_completion_clears_the_cursor(real_adapter):
+ """A finished pass starts the next one at the top, whatever cursor the caller hands in."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 11))
+ await real_adapter.save_full_sync_progress(CHAT_A, account_id=1, cursor=5)
+
+ await real_adapter.save_full_sync_progress(CHAT_A, account_id=1, cursor=3, completed_at=utcnow_naive())
+
+ cursor, completed_at = await _state(real_adapter, CHAT_A)
+ assert cursor is None
+ assert completed_at is not None
+
+
+@pytest.mark.asyncio
+async def test_a_chat_with_no_sync_status_row_gets_one(real_adapter):
+ """An imported chat may have messages and no sync_status row yet."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 151))
+
+ await _backup(real_adapter, FakeTelegram(), budget=100)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ assert await _state(real_adapter, CHAT_A) == (51, None)
+ assert await real_adapter.get_last_message_id(CHAT_A, account_id=1) == 0
+
+
+@pytest.mark.asyncio
+async def test_the_summary_counts_chats_without_naming_them(real_adapter, caplog):
+ await _seed(real_adapter, CHAT_A, older=range(1, 11))
+ await _seed(real_adapter, CHAT_B, older=range(1, 201))
+
+ with caplog.at_level("INFO", logger="telegram_archive.telegram_backup"):
+ await _backup(real_adapter, FakeTelegram(gone={5}), budget=200)._rotate_full_sync(
+ {CHAT_A: "entity-A", CHAT_B: "entity-B"}
+ )
+
+ assert (
+ "Older-message rotation: re-checked 110 older messages in 2 chat(s), 1 deleted, 0 updated; "
+ "1 chat(s) finished a pass, 1 of 2 have not finished one yet"
+ ) in caplog.text
+ assert str(CHAT_A) not in caplog.text and str(CHAT_B) not in caplog.text
+
+
+# --- Off means today's behaviour --------------------------------------------------
+
+
+@pytest.mark.asyncio
+async def test_a_capped_or_resumed_read_walks_down_from_the_newest_id(real_adapter):
+ """A LIMIT or an id bound with no window still reads the newest ids first, never an arbitrary slice."""
+ await _seed(real_adapter, CHAT_A, older=range(1, 11))
+
+ assert list(await real_adapter.get_messages_sync_data(CHAT_A, account_id=1, limit=3)) == [10, 9, 8]
+ assert list(await real_adapter.get_messages_sync_data(CHAT_A, account_id=1, below_id=5, limit=2)) == [4, 3]
+ assert list(await real_adapter.get_messages_sync_data(CHAT_A, account_id=1, below_id=4)) == [3, 2, 1]
+
+
+@pytest.mark.asyncio
+async def test_the_rotation_reads_unflagged_edits_of_its_slice_only(real_adapter):
+ """The edit-flag lookup covers the slice in hand, not every unflagged edit of a large chat."""
+ await _seed(real_adapter, CHAT_A)
+ edited_at = utcnow_naive() - timedelta(days=99)
+ old_date = utcnow_naive() - timedelta(days=100)
+ rows = [{"id": i, "chat_id": CHAT_A, "date": old_date, "text": "t", "edit_date": edited_at} for i in range(1, 301)]
+ await real_adapter.insert_messages_batch(rows, account_id=1)
+ assert len(await real_adapter.get_unflagged_edit_ids(CHAT_A, account_id=1)) == 300
+ assert await real_adapter.get_unflagged_edit_ids(CHAT_A, account_id=1, id_range=(201, 210)) == set(range(201, 211))
+
+ lookups = []
+ real_lookup = real_adapter.get_unflagged_edit_ids
+
+ async def spying_lookup(chat_id, **kwargs):
+ found = await real_lookup(chat_id, **kwargs)
+ lookups.append(found)
+ return found
+
+ with patch.object(real_adapter, "get_unflagged_edit_ids", side_effect=spying_lookup):
+ await _backup(real_adapter, FakeTelegram(), budget=100)._rotate_full_sync({CHAT_A: "entity-A"})
+
+ assert lookups == [set(range(201, 301))]
+
+
+class TestTheBudget(unittest.TestCase):
+ def test_it_is_zero_unless_sync_is_on_with_a_window(self):
+ on = SimpleNamespace(
+ sync_deletions_edits=True, sync_deletions_edits_days=14.0, sync_deletions_edits_older_per_run=500
+ )
+ self.assertEqual(sync_deletions_edits_older_budget(on), 500)
+ self.assertEqual(
+ sync_deletions_edits_older_budget(SimpleNamespace(**{**vars(on), "sync_deletions_edits": False})), 0
+ )
+ self.assertEqual(
+ sync_deletions_edits_older_budget(SimpleNamespace(**{**vars(on), "sync_deletions_edits_days": 0.0})), 0
+ )
+ self.assertEqual(
+ sync_deletions_edits_older_budget(SimpleNamespace(**{**vars(on), "sync_deletions_edits_older_per_run": 0})),
+ 0,
+ )
+ self.assertEqual(
+ sync_deletions_edits_older_budget(
+ SimpleNamespace(**{**vars(on), "sync_deletions_edits_older_per_run": -5})
+ ),
+ 0,
+ )
+
+ def test_a_mock_config_reads_as_off(self):
+ self.assertEqual(sync_deletions_edits_older_budget(MagicMock()), 0)
+ config = MagicMock()
+ config.sync_deletions_edits = True
+ config.sync_deletions_edits_days = 14.0
+ self.assertEqual(sync_deletions_edits_older_budget(config), 0)
+
+ def test_off_makes_no_database_call(self):
+ for budget, days, sync in ((0, 14.0, True), (500, 0.0, True), (500, 14.0, False)):
+ with self.subTest(budget=budget, days=days, sync=sync):
+ backup = TelegramBackup.__new__(TelegramBackup)
+ backup.account_id = 1
+ backup.config = SimpleNamespace(
+ sync_deletions_edits=sync,
+ sync_deletions_edits_days=days,
+ sync_deletions_edits_older_per_run=budget,
+ )
+ backup.db = AsyncMock()
+ backup.client = AsyncMock()
+ asyncio.run(backup._rotate_full_sync({CHAT_A: "entity-A"}))
+ self.assertEqual(backup.db.mock_calls, [])
+ self.assertEqual(backup.client.mock_calls, [])
+
+
+class TestTheSetting(unittest.TestCase):
+ def setUp(self):
+ self.temp_dir = tempfile.mkdtemp()
+
+ def tearDown(self):
+ shutil.rmtree(self.temp_dir, ignore_errors=True)
+
+ def _config(self, **env):
+ base = {"CHAT_TYPES": "private", "BACKUP_PATH": self.temp_dir, **env}
+ with patch.dict(os.environ, base, clear=True):
+ return Config()
+
+ def test_unset_is_off(self):
+ self.assertEqual(self._config().sync_deletions_edits_older_per_run, 0)
+
+ def test_parses_a_count(self):
+ self.assertEqual(
+ self._config(SYNC_DELETIONS_EDITS_OLDER_PER_RUN="20000").sync_deletions_edits_older_per_run, 20000
+ )
+
+ def test_negative_floored_at_zero(self):
+ self.assertEqual(self._config(SYNC_DELETIONS_EDITS_OLDER_PER_RUN="-5").sync_deletions_edits_older_per_run, 0)
+
+ def test_non_integer_stops_startup(self):
+ with self.assertRaisesRegex(ValueError, "SYNC_DELETIONS_EDITS_OLDER_PER_RUN must be an integer"):
+ self._config(SYNC_DELETIONS_EDITS_OLDER_PER_RUN="lots")
+
+ def test_banner_names_the_rotation_only_when_it_runs(self):
+ config = self._config(
+ SYNC_DELETIONS_EDITS="true", SYNC_DELETIONS_EDITS_DAYS="14", SYNC_DELETIONS_EDITS_OLDER_PER_RUN="20000"
+ )
+ with self.assertLogs("telegram_archive.config", level="WARNING") as logs:
+ config.log_summary()
+ self.assertIn("SYNC_DELETIONS_EDITS_OLDER_PER_RUN=20000", "\n".join(logs.output))
+
+ config = self._config(SYNC_DELETIONS_EDITS="true", SYNC_DELETIONS_EDITS_OLDER_PER_RUN="20000")
+ with self.assertLogs("telegram_archive.config", level="WARNING") as logs:
+ config.log_summary()
+ self.assertNotIn("SYNC_DELETIONS_EDITS_OLDER_PER_RUN", "\n".join(logs.output))
+
+
+# --- Wiring in backup_all ----------------------------------------------------------
+
+
+class TestBackupAllHandsInOnlyBackedUpChats(unittest.TestCase):
+ """The rotation sees exactly the chats this run backed up, regular and archived."""
+
+ def setUp(self):
+ from test_telegram_backup_extended import _make_backup
+
+ self.backup = _make_backup()
+ config = self.backup.config
+ config.whitelist_mode = False
+ config.priority_chat_ids = set()
+ config.verify_media = False
+ config.media_path = tempfile.mkdtemp()
+ for name in (
+ "global_include_ids",
+ "private_include_ids",
+ "groups_include_ids",
+ "channels_include_ids",
+ "global_exclude_ids",
+ "private_exclude_ids",
+ "groups_exclude_ids",
+ "channels_exclude_ids",
+ ):
+ setattr(config, name, set())
+ config.should_backup_chat = MagicMock(return_value=True)
+ config.sync_deletions_edits = True
+ config.sync_deletions_edits_days = 14.0
+ config.sync_deletions_edits_older_per_run = 500
+ self.backup.client.start = AsyncMock()
+ self.backup.client.get_me = AsyncMock(return_value=MagicMock(id=123))
+ self.backup.db.calculate_and_store_statistics = AsyncMock(
+ return_value={"chats": 1, "messages": 1, "media_files": 0, "total_size_mb": 0}
+ )
+ self.backup._backup_folders = AsyncMock()
+ self.backup._backup_forum_topics = AsyncMock()
+ self.backup._get_marked_id = MagicMock(side_effect=lambda e: e._test_id)
+ self.backup._rotate_full_sync = AsyncMock()
+
+ def tearDown(self):
+ shutil.rmtree(self.backup.config.media_path, ignore_errors=True)
+
+ def _dialog(self, test_id):
+ entity = MagicMock(spec=User)
+ entity._test_id = test_id
+ entity.id = test_id
+ entity.bot = False
+ return MagicMock(entity=entity, date=datetime(2024, 6, 1))
+
+ def test_a_failed_chat_is_left_out_and_an_archived_one_is_in(self):
+ from telethon.errors import ChannelPrivateError
+
+ ok, forbidden, archived = self._dialog(CHAT_A), self._dialog(CHAT_B), self._dialog(CHAT_C)
+
+ async def backup_dialog(dialog, is_archived=False):
+ if dialog is forbidden:
+ raise ChannelPrivateError(request=None)
+ return 0
+
+ self.backup._backup_dialog = AsyncMock(side_effect=backup_dialog)
+ self.backup._get_dialogs = AsyncMock(side_effect=[[ok, forbidden], [archived]])
+
+ asyncio.run(self.backup.backup_all())
+
+ self.backup._rotate_full_sync.assert_awaited_once()
+ entities = self.backup._rotate_full_sync.await_args.args[0]
+ self.assertEqual(entities, {CHAT_A: ok.entity, CHAT_C: archived.entity})
+
+ def test_off_never_calls_the_rotation(self):
+ self.backup.config.sync_deletions_edits_older_per_run = 0
+ self.backup._backup_dialog = AsyncMock(return_value=0)
+ self.backup._get_dialogs = AsyncMock(side_effect=[[self._dialog(CHAT_A)], []])
+
+ asyncio.run(self.backup.backup_all())
+
+ self.backup._rotate_full_sync.assert_not_awaited()
+
+ def test_a_rotation_failure_does_not_abort_the_run(self):
+ self.backup._rotate_full_sync = AsyncMock(side_effect=RuntimeError("boom"))
+ self.backup._backup_dialog = AsyncMock(return_value=0)
+ self.backup._get_dialogs = AsyncMock(side_effect=[[self._dialog(CHAT_A)], []])
+
+ asyncio.run(self.backup.backup_all())
+
+ self.backup._backup_folders.assert_awaited_once()
diff --git a/tests/test_listener_extended.py b/tests/test_listener_extended.py
index 62a9432c..81f1b8ac 100644
--- a/tests/test_listener_extended.py
+++ b/tests/test_listener_extended.py
@@ -3041,6 +3041,25 @@ async def test_the_log_names_the_window_when_the_sync_checks_recent_posts_only(s
assert "records those posted in the last 14 days" in caplog.text
assert "older ones only on a full pass (SYNC_DELETIONS_EDITS_DAYS=0)" in caplog.text
+ async def test_the_log_names_the_rotation_when_it_reaches_older_posts(self, caplog):
+ """#641: with SYNC_DELETIONS_EDITS_OLDER_PER_RUN older posts are not left to a DAYS=0 run."""
+ listener, handlers, _, config = _make_listener_with_handlers(
+ mass_operation_threshold=1, mass_operation_window_seconds=60
+ )
+ config.sync_deletions_edits = True
+ config.sync_deletions_edits_days = 14.0
+ config.sync_deletions_edits_older_per_run = 20000
+ event = MagicMock()
+ event.chat_id = -1001234567890
+ event.deleted_ids = [1, 2]
+
+ with caplog.at_level(logging.WARNING, logger="telegram_archive.listener"):
+ await handlers[events.MessageDeleted](event)
+
+ assert "records those posted in the last 14 days" in caplog.text
+ assert "older ones when the rotation (SYNC_DELETIONS_EDITS_OLDER_PER_RUN) reaches them" in caplog.text
+ assert "SYNC_DELETIONS_EDITS_DAYS=0" not in caplog.text
+
async def test_no_line_when_nothing_was_blocked(self, caplog):
_, handlers, _, _ = _make_listener_with_handlers()
event = MagicMock()
diff --git a/tests/test_log_chat_titles.py b/tests/test_log_chat_titles.py
index f15eee6d..dea5909e 100644
--- a/tests/test_log_chat_titles.py
+++ b/tests/test_log_chat_titles.py
@@ -308,7 +308,8 @@ def test_the_progress_lines_call_it_inline(self):
/ "telegram_archive"
/ "telegram_backup.py"
).read_text(encoding="utf-8")
- self.assertEqual(2, source.count("chat_title_for_log(entity, self.config)"), str(backup_path))
+ # The dialog loop, the archived loop and the full-pass rotation (#641).
+ self.assertEqual(3, source.count("chat_title_for_log(entity, self.config)"), str(backup_path))
tree = ast.parse(source)
hoisted = [
node.lineno
diff --git a/tests/test_migration_044.py b/tests/test_migration_044.py
new file mode 100644
index 00000000..08ad5828
--- /dev/null
+++ b/tests/test_migration_044.py
@@ -0,0 +1,132 @@
+"""Migration 044: the rotating full pass state on sync_status, added by inspector-guarded steps.
+
+The upgrade from 043 keeps every row and reads each chat as never having
+finished a pass. A re-run, and a create_all() database that already has the
+columns, change nothing; a second downgrade changes nothing either. Runs on
+SQLite and PostgreSQL. The revision ids are read from the migration module, so
+renumbering the chain at merge time changes only the migration file.
+"""
+
+import importlib.util
+import re
+from pathlib import Path
+
+import pytest
+import sqlalchemy as sa
+from alembic.migration import MigrationContext
+from alembic.operations import Operations
+from conftest import NO_POSTGRES_REASON
+from test_schema_parity import _build_alembic_schema
+
+from telegram_archive.db.models import Base
+
+_VERSIONS = Path(__file__).resolve().parent.parent / "telegram_archive" / "alembic" / "versions"
+
+spec = importlib.util.spec_from_file_location("migration_044", _VERSIONS / "20261124_044_add_full_sync_rotation.py")
+migration = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(migration)
+
+COLUMNS = ("full_sync_cursor", "full_sync_completed_at")
+
+
+def _run(conn, fn) -> None:
+ with Operations.context(MigrationContext.configure(conn)):
+ fn()
+
+
+def _has_columns(conn) -> dict[str, bool]:
+ names = {c["name"] for c in sa.inspect(conn).get_columns("sync_status")}
+ return {column: column in names for column in COLUMNS}
+
+
+def test_revision_chain_points_at_an_existing_revision_and_does_not_fork():
+ revisions = {}
+ for path in _VERSIONS.glob("*.py"):
+ source = path.read_text(encoding="utf-8")
+ rev = re.search(r'^revision: str = "([^"]+)"', source, re.M)
+ down = re.search(r'^down_revision: str \| None = "([^"]+)"', source, re.M)
+ if rev:
+ revisions[rev.group(1)] = down.group(1) if down else None
+ assert migration.down_revision in revisions
+ assert list(revisions.values()).count(migration.down_revision) == 1
+ assert list(revisions.values()).count(migration.revision) <= 1
+
+
+def test_it_no_ops_when_the_table_is_absent():
+ engine = sa.create_engine("sqlite://")
+ with engine.connect() as conn:
+ _run(conn, migration.upgrade)
+ _run(conn, migration.downgrade)
+ assert sa.inspect(conn).get_table_names() == []
+
+
+def test_a_create_all_schema_already_has_the_columns_and_upgrade_is_a_no_op():
+ engine = sa.create_engine("sqlite://")
+ with engine.begin() as conn:
+ Base.metadata.create_all(conn)
+ assert _has_columns(conn) == dict.fromkeys(COLUMNS, True)
+ _run(conn, migration.upgrade)
+ _run(conn, migration.upgrade)
+ assert _has_columns(conn) == dict.fromkeys(COLUMNS, True)
+
+
+def test_a_half_applied_upgrade_adds_only_the_missing_column():
+ engine = sa.create_engine("sqlite://")
+ with engine.begin() as conn:
+ conn.execute(sa.text("CREATE TABLE sync_status (account_id INTEGER, chat_id BIGINT, full_sync_cursor BIGINT)"))
+ _run(conn, migration.upgrade)
+ assert _has_columns(conn) == dict.fromkeys(COLUMNS, True)
+
+
+@pytest.fixture(params=("sqlite", "postgresql"))
+def database_urls(request, tmp_path, postgres_server_url, make_postgres_database) -> tuple[str, str]:
+ """(async url, sync url) of an empty database on each backend."""
+ if request.param == "postgresql":
+ if not postgres_server_url:
+ pytest.skip(NO_POSTGRES_REASON)
+ return make_postgres_database("telegram_archive_migration_044")
+ path = tmp_path / "archive.db"
+ return f"sqlite+aiosqlite:///{path}", f"sqlite:///{path}"
+
+
+def test_upgrade_from_043_keeps_rows_and_both_directions_are_idempotent(database_urls):
+ """Synchronous on purpose: Alembic's env.py runs its own event loop."""
+ async_url, sync_url = database_urls
+ _build_alembic_schema(async_url, migration.down_revision)
+ engine = sa.create_engine(sync_url)
+ try:
+ with engine.begin() as conn:
+ assert _has_columns(conn) == dict.fromkeys(COLUMNS, False)
+ conn.execute(
+ sa.text(
+ "INSERT INTO chats (account_id, id, ref, type, first_name, last_synced_message_id) "
+ "VALUES (1, 201, 'ref0044', 'private', 'Sample', 0)"
+ )
+ )
+ conn.execute(
+ sa.text(
+ "INSERT INTO sync_status (account_id, chat_id, last_message_id, message_count) "
+ "VALUES (1, 201, 77, 5)"
+ )
+ )
+
+ _build_alembic_schema(async_url, migration.revision)
+
+ with engine.begin() as conn:
+ assert _has_columns(conn) == dict.fromkeys(COLUMNS, True)
+ # A row from before the columns reads as never having finished a pass.
+ assert conn.execute(
+ sa.text(
+ "SELECT last_message_id, message_count, full_sync_cursor, full_sync_completed_at FROM sync_status"
+ )
+ ).all() == [(77, 5, None, None)]
+ _run(conn, migration.upgrade) # a re-run changes nothing
+ assert _has_columns(conn) == dict.fromkeys(COLUMNS, True)
+
+ with engine.begin() as conn:
+ _run(conn, migration.downgrade)
+ assert _has_columns(conn) == dict.fromkeys(COLUMNS, False)
+ _run(conn, migration.downgrade)
+ assert conn.execute(sa.text("SELECT last_message_id, message_count FROM sync_status")).all() == [(77, 5)]
+ finally:
+ engine.dispose()
diff --git a/tests/test_no_account_pii_in_logs.py b/tests/test_no_account_pii_in_logs.py
index 55099975..07bf82da 100644
--- a/tests/test_no_account_pii_in_logs.py
+++ b/tests/test_no_account_pii_in_logs.py
@@ -723,7 +723,8 @@ def test_a_raw_title_at_the_sanctioned_site_still_fails(self) -> None:
path = REPO / "telegram_archive" / "telegram_backup.py"
source = path.read_text(encoding="utf-8")
anchor = f"{TITLE_LOG_SINK}(entity, self.config)"
- self.assertEqual(2, source.count(anchor), "both sanctioned call sites must use the exact anchor")
+ # The dialog loop, the archived loop and the full-pass rotation (#641).
+ self.assertEqual(3, source.count(anchor), "every sanctioned call site must use the exact anchor")
self.assertEqual([], _violations_in_tree("telegram_archive/telegram_backup.py", ast.parse(source)))
for replacement in ("entity.title", "chat_title", "self._get_marked_id(entity) or entity.title"):
diff --git a/tests/test_scheduler.py b/tests/test_scheduler.py
index 7f978738..234ce114 100644
--- a/tests/test_scheduler.py
+++ b/tests/test_scheduler.py
@@ -1251,6 +1251,32 @@ async def test_main_banner_names_the_sync_window(self, caplog):
assert "SYNC_DELETIONS_EDITS: ENABLED (messages from the last 14 days)" in caplog.text
assert "re-check ALL messages" not in caplog.text
+ async def test_main_banner_names_the_rotation(self, caplog):
+ """#641: with a full-pass budget the banner says older messages rotate, not wait for DAYS=0."""
+ mock_config = MagicMock()
+ mock_config.schedule = "0 */6 * * *"
+ mock_config.backup_path = "/data/backups"
+ mock_config.download_media = True
+ mock_config.chat_types = ["private"]
+ mock_config.enable_listener = False
+ mock_config.sync_deletions_edits = True
+ mock_config.sync_deletions_edits_days = 14.0
+ mock_config.sync_deletions_edits_older_per_run = 20000
+
+ with (
+ caplog.at_level(logging.WARNING, logger="telegram_archive.scheduler"),
+ patch("telegram_archive.scheduler.signal.signal"),
+ patch("telegram_archive.config.Config", return_value=mock_config),
+ patch("telegram_archive.config.setup_logging"),
+ patch("telegram_archive.scheduler.BackupScheduler", return_value=AsyncMock()),
+ ):
+ from telegram_archive.scheduler import main
+
+ await main()
+
+ assert "Older messages are re-checked up to 20000 per account per run, rotating over the chats" in caplog.text
+ assert "only on a run with SYNC_DELETIONS_EDITS_DAYS=0" not in caplog.text
+
@pytest.mark.parametrize("days", [0.0, None])
async def test_main_banner_without_window_is_unchanged(self, caplog, days):
"""#608: DAYS=0 (or a MagicMock config with no number) keeps the ALL-messages banner."""
diff --git a/tests/test_shipped_defaults.py b/tests/test_shipped_defaults.py
index bc9bacbf..3662e1e6 100644
--- a/tests/test_shipped_defaults.py
+++ b/tests/test_shipped_defaults.py
@@ -113,3 +113,11 @@ def test_the_sync_window_matches_the_code(self):
self.assertEqual(float(_compose_default("SYNC_DELETIONS_EDITS_DAYS")), default)
self.assertEqual(float(_env_example_value("SYNC_DELETIONS_EDITS_DAYS")), default)
self.assertEqual(_reference_default("SYNC_DELETIONS_EDITS_DAYS"), "`0`")
+
+ def test_the_full_pass_budget_matches_the_code(self):
+ """SYNC_DELETIONS_EDITS_OLDER_PER_RUN (#641): 0, off, in all four places."""
+ default = _config().sync_deletions_edits_older_per_run
+ self.assertEqual(default, 0)
+ self.assertEqual(int(_compose_default("SYNC_DELETIONS_EDITS_OLDER_PER_RUN")), default)
+ self.assertEqual(int(_env_example_value("SYNC_DELETIONS_EDITS_OLDER_PER_RUN")), default)
+ self.assertEqual(_reference_default("SYNC_DELETIONS_EDITS_OLDER_PER_RUN"), "`0`")