Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,9 @@ ENABLE_LISTENER=false
# LISTEN_REACTIONS=false # Capture reactions in real-time (opt-in). Best-effort and
# # aggregate-only; the scheduled backup reconciles regardless.
# REACTION_DEBOUNCE_SECONDS=1.5 # Coalesce reaction bursts on the same message
# REACTION_RESWEEP_DAYS=0 # Re-check last N days/chat each sweep to recover your own
# # reactions (0=disabled; self-reactions are not reliably pushed).
# REACTION_RESWEEP_MAX_PER_CHAT=500 # Cap messages re-checked per chat/sweep (~5 API calls)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

# Mass operation protection (only applies when ENABLE_LISTENER=true)
# MASS_OPERATION_THRESHOLD=10
Expand Down
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,8 @@ The **Scope** column shows whether each variable applies to the backup scheduler
| `LISTEN_CHAT_ACTIONS` | `true` | B | Track chat photo, title, and member changes |
| `LISTEN_REACTIONS` | `false` | B | Capture reactions in real-time (opt-in). Best-effort and aggregate-only (per-emoji counts); the scheduled backup reconciles reactions regardless |
| `REACTION_DEBOUNCE_SECONDS` | `1.5` | B | Coalesce a burst of reaction updates on the same message into one write |
| `REACTION_RESWEEP_DAYS` | `0` | B | Re-check the last N days of messages per chat on every scheduled sweep to recover your own reactions (`0` disables). See [Reactions made by your own account](#reactions-made-by-your-own-account) |
| `REACTION_RESWEEP_MAX_PER_CHAT` | `500` | B | Cap on messages re-checked per chat per sweep (≈5 API calls/chat/sweep at the default) |
| `MASS_OPERATION_THRESHOLD` | `10` | B | Max operations per chat before rate limiting triggers |
| `MASS_OPERATION_WINDOW_SECONDS` | `30` | B | Sliding window for counting operations (seconds) |
| `MASS_OPERATION_BUFFER_DELAY` | `2.0` | B | Deprecated compatibility setting; operations are rate-limited, not buffered |
Expand Down Expand Up @@ -395,6 +397,12 @@ LISTEN_NEW_MESSAGES: "true" # Save new messages instantly (default: true)

**Alternative — batch sync:** set `SYNC_DELETIONS_EDITS=true` to check ALL backed-up messages on each scheduled run. This is expensive and slow, and uses the same `DELETION_MODE` behavior for deleted messages.

#### Reactions made by your own account

Telegram does not reliably push reaction updates for the archive account's **own** reactions — the ones you add from another device — to the archive's session. To close that gap, the listener additionally harvests reactions carried on edit events (Telegram delivers some reaction changes as edits), and new messages are checked for reactions the moment they arrive.

For reactions on **older** messages, set `REACTION_RESWEEP_DAYS=N`: on every scheduled sweep the backup re-checks the last N days of messages per chat and reconciles their current reactions. It is bounded by `REACTION_RESWEEP_MAX_PER_CHAT` (default 500, ≈5 API calls per chat per sweep) and defaults to `0` (disabled). Self-reactions on messages older than the sweep's incremental window are captured only by this re-sweep, so enable it if you react to your own older messages and want those counts archived.

### Mass Operation Protection

When the listener is enabled and `LISTEN_DELETIONS=true`, a sliding-window rate limiter limits mass deletion damage:
Expand Down
148 changes: 148 additions & 0 deletions alembic/versions/20260719_019_delete_phantom_chat_action_rows.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""Delete historical phantom chat-action rows written by the pre-fix listener (#222).

The old listener wrote junk "service message" rows into ``messages`` with
fabricated wall-clock IDs and a broken classifier that stamped ``raw_data`` with
seven curated event names (``photo_changed``, ``photo_removed``,
``title_changed``, ``user_joined``, ``user_left``, ``user_added``,
``user_kicked``). The listener fix switched to real Telegram IDs and the shared
``service_action_type()`` sweep vocabulary, so those seven names are no longer
emitted. This migration deletes every historical row carrying one of them.

Safety invariant: this DELETE is safe iff the listener never again emits the 7
legacy ``action_type`` names (it now uses the ``service_action_type()``
vocabulary, which is provably disjoint from these names) and the ``action_type``
IN-list filter below is never broadened. The seven names are the *entire*
identity of a phantom row: forensics across the full lifetime of both production
databases proved they never appear on a legitimate row, so there is no id or
``service_type`` condition here — real-world phantoms exist with low ids and
without a ``service_type`` key, so either boundary would be unsafe.

``raw_data`` is a TEXT column holding a JSON string that has never been parsed by
a migration and can contain malformed JSON (the adapter defends against that at
read time). The match is therefore parse-free ``LIKE`` on the raw text: a
``->>`` / ``::jsonb`` / ``json_extract`` predicate would be a type error on the
PostgreSQL TEXT column and would crash on malformed rows. Two serialization eras
are covered per name — the spaced form ``json.dumps`` emits today
(``"action_type": "user_joined"``) and a compact form
(``"action_type":"user_joined"``). Underscores in the names are escaped
(``!_`` with ``ESCAPE '!'``) so ``LIKE`` matches them literally instead of as its
single-character wildcard, pinning the match to the exact seven strings. ``LIKE``
is case-sensitive on PostgreSQL and case-insensitive for ASCII on SQLite; that is
harmless here because the JSON is always lower-case exactly as listed.

Revision ID: 019
Revises: 018
Create Date: 2026-07-19
"""

import logging
from collections.abc import Sequence

import sqlalchemy as sa

from alembic import op

revision: str = "019"
down_revision: str | None = "018"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None

logger = logging.getLogger("alembic.runtime.migration")

# The 7 legacy curated event names the broken classifier fabricated. This IN-list
# is the entire identity of a phantom row — do NOT broaden it (see module docstring).
_LEGACY_ACTION_TYPES = (
"photo_changed",
"photo_removed",
"title_changed",
"user_joined",
"user_left",
"user_added",
"user_kicked",
)

# Child tables whose rows reference (message_id, chat_id). reactions has no
# ON DELETE CASCADE, and on SQLite PRAGMA foreign_keys may be OFF so the media /
# message_versions cascades cannot be relied on either — so all three are deleted
# explicitly, on both engines, before the messages rows.
_CHILD_TABLES = ("reactions", "media", "message_versions")


def _phantom_predicate() -> str:
"""Build the parse-free WHERE predicate identifying phantom rows.

References ``messages.raw_data``; valid verbatim both as a ``messages`` filter
and inside ``SELECT id, chat_id FROM messages WHERE ...`` for the child deletes.
"""
clauses: list[str] = []
for name in _LEGACY_ACTION_TYPES:
escaped = name.replace("_", "!_") # !_ + ESCAPE '!' => literal underscore
# spaced form (json.dumps default): "action_type": "name"
clauses.append(f"""raw_data LIKE '%"action_type": "{escaped}"%' ESCAPE '!'""")
# compact form (older era): "action_type":"name"
clauses.append(f"""raw_data LIKE '%"action_type":"{escaped}"%' ESCAPE '!'""")
return "raw_data IS NOT NULL AND (" + " OR ".join(clauses) + ")"


_PHANTOM_PREDICATE = _phantom_predicate()


def upgrade() -> None:
conn = op.get_bind()
inspector = sa.inspect(conn)

tables = set(inspector.get_table_names())
# Fresh database mid-bootstrap (create_all has not populated messages yet):
# nothing to clean. Naturally idempotent otherwise — a re-run deletes 0 rows.
if "messages" not in tables:
return

subquery = f"SELECT id, chat_id FROM messages WHERE {_PHANTOM_PREDICATE}"

# Delete dependent rows first. Observed dependent-row count on phantoms in
# production is zero, but a single stray child row would make the messages
# DELETE raise and crash-loop the container at startup, so this is explicit.
child_counts = {name: 0 for name in _CHILD_TABLES}
for child in _CHILD_TABLES:
if child in tables:
result = conn.execute(sa.text(f"DELETE FROM {child} WHERE (message_id, chat_id) IN ({subquery})"))
child_counts[child] = result.rowcount

result = conn.execute(sa.text(f"DELETE FROM messages WHERE {_PHANTOM_PREDICATE}"))
deleted = result.rowcount

# Invalidate the cached statistics blob so dashboard message / per-chat counts
# stop including the deleted phantoms. It is the only persisted aggregate that
# counts messages: the "cached_stats" key in the metadata key-value table
# (written by adapter.calculate_and_store_statistics). "stats_calculated_at"
# must go WITH it: the viewer's lifespan hook only runs the immediate initial
# recompute when that marker is absent (src/web/main.py), so dropping the blob
# alone would leave the dashboard showing zeros for up to a day until the
# scheduled recompute. Deleting both makes the next viewer start recompute
# fresh stats right away. Per-chat stats (get_chat_stats) are computed on
# the fly behind a 60-second in-memory web-layer cache that expires on its
# own, so they need no action here.
# Idempotent: a re-run deletes 0 rows.
if "metadata" in tables:
conn.execute(sa.text("DELETE FROM metadata WHERE \"key\" IN ('cached_stats', 'stats_calculated_at')"))

# Counts only — never chat IDs, message text, or user IDs (PII).
logger.info(
"Migration 019: deleted %d phantom chat-action message rows "
"(children removed: %d reactions, %d media, %d message_versions)",
deleted,
child_counts["reactions"],
child_counts["media"],
child_counts["message_versions"],
)


def downgrade() -> None:
"""No-op: intentionally irreversible.

The deleted rows were fabricated junk (phantom chat-action rows with
wall-clock IDs) that never corresponded to a real Telegram message, so there
is no source of truth to restore them from. Re-applying ``upgrade`` is safe
and idempotent.
"""
pass
2 changes: 2 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,8 @@ services:
# LISTEN_CHAT_ACTIONS: ${LISTEN_CHAT_ACTIONS:-true}
# LISTEN_REACTIONS: ${LISTEN_REACTIONS:-false}
# REACTION_DEBOUNCE_SECONDS: ${REACTION_DEBOUNCE_SECONDS:-1.5}
# REACTION_RESWEEP_DAYS: ${REACTION_RESWEEP_DAYS:-0}
# REACTION_RESWEEP_MAX_PER_CHAT: ${REACTION_RESWEEP_MAX_PER_CHAT:-500}
Comment on lines +84 to +85

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Pass the resweep variables into the container.

These entries are commented out, so Docker Compose will not inject REACTION_RESWEEP_DAYS or REACTION_RESWEEP_MAX_PER_CHAT from .env. src/config.py will silently use 0 and 500, leaving resweeping disabled for .env-based deployments.

-      # REACTION_RESWEEP_DAYS: ${REACTION_RESWEEP_DAYS:-0}
-      # REACTION_RESWEEP_MAX_PER_CHAT: ${REACTION_RESWEEP_MAX_PER_CHAT:-500}
+      REACTION_RESWEEP_DAYS: ${REACTION_RESWEEP_DAYS:-0}
+      REACTION_RESWEEP_MAX_PER_CHAT: ${REACTION_RESWEEP_MAX_PER_CHAT:-500}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
# REACTION_RESWEEP_DAYS: ${REACTION_RESWEEP_DAYS:-0}
# REACTION_RESWEEP_MAX_PER_CHAT: ${REACTION_RESWEEP_MAX_PER_CHAT:-500}
REACTION_RESWEEP_DAYS: ${REACTION_RESWEEP_DAYS:-0}
REACTION_RESWEEP_MAX_PER_CHAT: ${REACTION_RESWEEP_MAX_PER_CHAT:-500}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@docker-compose.yml` around lines 84 - 85, Uncomment the REACTION_RESWEEP_DAYS
and REACTION_RESWEEP_MAX_PER_CHAT environment entries in the Docker Compose
environment configuration so Compose injects the .env values while retaining
defaults of 0 and 500.


# Mass operation protection (only applies when ENABLE_LISTENER=true)
# MASS_OPERATION_THRESHOLD: ${MASS_OPERATION_THRESHOLD:-10}
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "telegram-archive"
version = "7.23.0"
version = "7.24.0"
description = "Automated Telegram backup with Docker. Performs incremental backups of messages and media on a configurable schedule."
readme = "README.md"
requires-python = ">=3.14"
Expand Down
6 changes: 6 additions & 0 deletions scripts/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -277,6 +277,9 @@ if has_tables and not has_alembic:
has_push_subs = cur.fetchone()[0]

# Determine which version to stamp based on existing schema
# Migration 019 is a data-only cleanup (deletes phantom chat-action rows) with
# no detectable schema artifact, so it is intentionally absent from this ladder;
# alembic upgrade head always runs it (idempotent) after stamping at 018.
if has_018_reaction_removed_at and has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete:
stamp_version = '018'
elif has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete:
Expand Down Expand Up @@ -456,6 +459,9 @@ if has_tables and not has_alembic:
has_push_subs = cur.fetchone() is not None

# Determine which version to stamp based on existing schema
# Migration 019 is a data-only cleanup (deletes phantom chat-action rows) with
# no detectable schema artifact, so it is intentionally absent from this ladder;
# alembic upgrade head always runs it (idempotent) after stamping at 018.
if has_018_reaction_removed_at and has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete:
stamp_version = '018'
elif has_017_chat_id_id_index and has_016_download_attempts and has_015_message_versions and has_014_soft_delete:
Expand Down
2 changes: 1 addition & 1 deletion src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,4 +2,4 @@
Telegram Backup Automation - Main Package
"""

__version__ = "7.23.0"
__version__ = "7.24.0"
12 changes: 12 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -332,6 +332,18 @@ def __init__(self):
# snapshot, so keeping only the latest within the window is loss-free.
self.reaction_debounce_seconds = max(0.1, float(os.getenv("REACTION_DEBOUNCE_SECONDS", "1.5")))

# REACTION_RESWEEP_DAYS: bounded reaction re-sweep window (#221). Telegram does
# not reliably push reaction updates for the archive account's OWN reactions
# (made from another device) to this session, and the scheduled sweep only
# revisits messages inside its incremental window. When >0, each scheduled
# sweep re-checks the last N days of messages per chat and reconciles their
# current aggregate. DEFAULT 0 (disabled) — opt-in, small extra API cost.
self.reaction_resweep_days: float = max(0.0, float(os.getenv("REACTION_RESWEEP_DAYS", "0")))

# REACTION_RESWEEP_MAX_PER_CHAT: cap on messages re-checked per chat per sweep
# (fetched newest-first in batches of 100 → ceil(cap/100) requests/chat/sweep).
self.reaction_resweep_max_per_chat: int = max(1, int(os.getenv("REACTION_RESWEEP_MAX_PER_CHAT", "500")))

# Note: LISTEN_ALBUMS removed - albums are automatically handled via grouped_id
# in the NewMessage handler. The viewer groups messages by grouped_id.

Expand Down
17 changes: 17 additions & 0 deletions src/db/adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -764,6 +764,23 @@ async def get_messages_sync_data(self, chat_id: int) -> dict[int, str | None]:
result = await session.execute(stmt)
return {row.id: row.edit_date for row in result}

async def get_message_ids_since(self, chat_id: int, cutoff: datetime, limit: int) -> list[int]:
"""Return the newest message IDs in a chat dated at or after ``cutoff`` (#221).

Used by the bounded reaction re-sweep to recover self-reactions Telegram
never pushed to this session. Newest-first (highest id) and capped at
``limit`` so the caller re-checks the most recent window at a fixed cost.
"""
async with self.db_manager.async_session_factory() as session:
stmt = (
select(Message.id)
.where(and_(Message.chat_id == chat_id, Message.date >= cutoff))
.order_by(Message.id.desc())
.limit(limit)
)
result = await session.execute(stmt)
return [row.id for row in result]

async def get_chat_id_for_message(self, message_id: int) -> int | None:
"""
Look up the chat_id for a message by its ID.
Expand Down
6 changes: 6 additions & 0 deletions src/db/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,18 +110,24 @@ async def init(self) -> None:
# Engine configuration differs by database type
if self._is_sqlite:
# SQLite: Use NullPool for better async compatibility
# hide_parameters: DB errors must never embed bound values (message
# text, chat ids) in logs — PII rule.
self.engine = create_async_engine(
self.database_url,
echo=os.getenv("DB_ECHO", "false").lower() == "true",
poolclass=NullPool,
hide_parameters=True,
)
# Set up SQLite-specific pragmas
self._setup_sqlite_pragmas()
else:
# PostgreSQL: Use connection pooling
# hide_parameters: DB errors must never embed bound values (message
# text, chat ids) in logs — PII rule.
self.engine = create_async_engine(
self.database_url,
echo=os.getenv("DB_ECHO", "false").lower() == "true",
hide_parameters=True,
poolclass=AsyncAdaptedQueuePool,
pool_size=5,
max_overflow=10,
Expand Down
Loading
Loading