Skip to content

fix: archive chat actions with real IDs and capture own-account reactions (#221, #222) - #223

Merged
GeiserX merged 6 commits into
mainfrom
ai/issues-221-222
Jul 19, 2026
Merged

GeiserX merged 6 commits into
mainfrom
ai/issues-221-222

Conversation

@GeiserX

@GeiserX GeiserX commented Jul 19, 2026 •

Copy link
Copy Markdown
Owner

Fixes #221 and #222.

#222 — phantom chat-action rows with fabricated IDs

Root cause (present in every release v5.3.1 → v7.23.0):

  • The on_chat_action classifier's second branch (photo is None and not new_photo) was a catch-all that labeled every non-photo chat action (joins, leaves, title changes) as photo_removed — the user_joined/user_left/user_added/user_kicked/title_changed branches were dead code (0 rows with those labels exist across 2.95M messages in two production DBs). Genuine photo removals were misclassified as photo_changed.
  • Rows were written with a fabricated ID: -int(time.time() * 1000) % 2147483647 — a positive 31-bit value that decrements 1/ms and wraps every ~24.8 days, interleaving real message IDs (production forensics found fabricated IDs as low as 22M in chats whose real IDs are in the hundreds). One join produces ~2 ChatAction events (Telethon builds one from UpdateChatParticipantAdd and one from the MessageService, dispatched as parallel tasks), hence ~2 phantom rows per join.

The fix:

  • Service rows are written only when the event carries a real MessageService (event.action_message), using its real id/date/sender, classified via the shared service_action_type() sweep vocabulary. Participant-only sync updates (no service message) write no row — matching Telegram's own UI. events.NewMessage skips MessageService, so this handler remains the only real-time source of service rows.
  • Photo semantics fixed per Telethon source: new_photo=True, photo=None → removed; photo=Photo → changed.
  • A new shared service_message_text() helper generates the human-readable text for both the listener and the scheduled sweep (sweep-archived service rows previously stored empty text and rendered as blank pills).
  • Migration 019 deletes all historical phantom rows: parse-free LIKE matching of the 7 legacy action_type names on the TEXT raw_data column (both JSON serialization eras, escaped underscores, no id/service_type conditions — forensics found real phantoms with low IDs and without the service_type key). Dependent reactions/media/message_versions rows are deleted explicitly first (the reactions FK has no cascade). Invalidates cached_stats + stats_calculated_at so the viewer recomputes correct counts immediately on next start. Data-only migration: intentionally absent from the entrypoint stamp ladders (documented there) so alembic upgrade head always runs it; naturally idempotent. Validated against a full copy of a production DB: deletes exactly the 422 forensically-confirmed phantoms out of 1.78M rows.

#221 — reactions by the archive's own account never captured live

Telegram does not reliably push UpdateMessageReactions to the archive's session for reactions made by the same account from another device. Mitigations, all preserving the #220 aggregate-only model:

  • Edit harvest: Telegram delivers some reaction changes as genuine edit events (Telethon #4635, maintainer-confirmed). The edit handler now feeds reaction snapshots carried on edit payloads into the shared reaction debounce buffer — before the text-noop early return, so reaction-only edits (unchanged text) still reconcile without bumping edit_date (the [Bug]: **Title:** Reactions are only captured by the scheduled backup, never by the real-time listener #219 phantom-edit guard is untouched). min payloads are skipped (documented to omit the current user's own reactions — reconciling one could falsely tombstone a just-added self-reaction). New messages arriving with reactions attached are harvested the same way.
  • Bounded re-sweep (opt-in): REACTION_RESWEEP_DAYS=N re-checks the last N days of messages per chat on every scheduled sweep via batched messages.getMessagesReactions (100 ids/request, get_messages fallback for rejected chunks), capped by REACTION_RESWEEP_MAX_PER_CHAT (default 500 ≈ 5 requests/chat/sweep). Default 0 (disabled). Only ids echoed back are reconciled — absence is never treated as "zero reactions".
  • Piggyback: SYNC_DELETIONS_EDITS=true already fetches full messages and discarded their reactions; they are now reconciled at zero extra API cost.
  • Docs: README section "Reactions made by your own account" documents the limitation and both knobs.

Testing

Summary by CodeRabbit

  • New Features

    • Added optional reaction “resweep” to recover self-reaction counts with configurable lookback days and per-chat caps.
    • Improved reaction capture by buffering edit/new-message reaction vectors and reconciling reactions during sync.
    • Enhanced service-message text rendering (joins, member changes, title edits, photo updates).
  • Bug Fixes

    • Improved chat-action archiving using the real Telegram service message metadata.
    • Better preservation/synthesis of service text during historical backups and reaction reconciliation.
  • Documentation

    • Documented new environment variables and how/when to use resweep settings.
  • Tests

    • Added coverage for reaction resweep, chat-action handling, and migration 019 behavior.
  • Chores

    • Improved DB engine logging safety (hide bound parameters) and clarified entrypoint migration stamping.

GeiserX added 3 commits July 19, 2026 16:16
… classification (#222)

The chat-action classifier's photo-is-None branch swallowed every
non-photo action as photo_removed, and rows were written with
wall-clock-derived synthetic ids (~2 phantom rows per join/leave).
Service rows are now written only when the event carries a real
MessageService (real id/date), tagged with the shared sweep
vocabulary via service_action_type, with human-readable text
generated by a new shared service_message_text helper used by both
the listener and the backfill sweep. Participant-only syncs write
no message row.
Parse-free LIKE cleanup of the 7 legacy listener action_type names on
the TEXT raw_data column (spaced + compact JSON forms, escaped
underscores, no id or service_type condition per production forensics).
Dependent reactions/media/message_versions rows are deleted explicitly
first since the reactions FK has no cascade and SQLite may run without
foreign_keys. Invalidates cached_stats AND stats_calculated_at so the
viewer recomputes correct counts on next start. Data-only migration:
intentionally absent from the entrypoint stamp ladders (documented in
both), so alembic upgrade head always runs it.
…ounded resweep (#221)

Telegram does not reliably push UpdateMessageReactions for the archive
account's own reactions (made from another device) to the archive's
session. Close the gap three ways: harvest reaction snapshots carried
on edit events and on newly-arriving messages into the shared debounce
buffer (min payloads skipped - they omit the current user's own
reactions); piggyback reaction reconciliation onto the existing
SYNC_DELETIONS_EDITS full-message fetch at zero extra API cost; and add
an opt-in bounded re-sweep (REACTION_RESWEEP_DAYS, default off, capped
by REACTION_RESWEEP_MAX_PER_CHAT) that re-checks recent messages per
chat each scheduled sweep via batched GetMessagesReactionsRequest with
a get_messages fallback. Documents the limitation in the README.
@coderabbitai

coderabbitai Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@GeiserX, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 23 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 873df19d-5359-49c9-8371-4cd9c96e99a5

📥 Commits

Reviewing files that changed from the base of the PR and between d06ddc0 and 79beb25.

📒 Files selected for processing (3)
  • .env.example
  • pyproject.toml
  • src/__init__.py
📝 Walkthrough

Walkthrough

Adds bounded reaction resweeping and real-time buffering, refactors Telegram service-action persistence and text rendering, validates migration 019 cleanup, and hides database query parameters in engine logs.

Changes

Reaction recovery

Layer / File(s) Summary
Reaction resweep configuration and query contract
.env.example, README.md, docker-compose.yml, src/config.py, src/db/adapter.py
Adds resweep settings, documentation, clamping, and a bounded recent-message ID query.
Real-time reaction buffering
src/listener.py, tests/test_listener_reactions.py
Buffers reaction snapshots from edits and new messages while skipping minimized payloads and disabled listeners.
Bounded reaction reconciliation
src/telegram_backup.py, tests/test_reaction_resweep.py, tests/test_telegram_backup.py, tests/test_telegram_backup_extended.py
Adds optional per-chat resweeps, chunked API reconciliation, fallback fetching, and edit-sync reconciliation.

Service-message handling

Layer / File(s) Summary
Service-action classification and rendering
src/message_utils.py, src/listener.py, tests/test_listener_chat_actions.py, tests/test_listener_extended.py
Renders curated service text and persists chat actions using real Telegram message metadata.
Backup service-message text synthesis
src/telegram_backup.py, tests/test_telegram_backup_extended.py
Synthesizes missing service text while preserving existing text and ordinary messages.

Migration and database safety

Layer / File(s) Summary
Migration cleanup validation
scripts/entrypoint.sh, tests/test_migration_019.py
Documents migration 019 stamping behavior and tests cleanup, metadata handling, idempotency, missing-table behavior, and downgrade behavior.
Database error parameter redaction
src/db/base.py
Enables bound-parameter hiding for SQLite and PostgreSQL engines.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is detailed but does not follow the required template and omits the checklist sections. Rewrite it to match the template, including Summary, Type of Change, Database Changes, checklists, Testing, Security, and Deployment Notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 16.39% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the main changes: real IDs for chat actions and own-account reaction capture.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch ai/issues-221-222

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

Copy link
Copy Markdown

🐳 Dev images published!

  • drumsergio/telegram-archive:dev
  • drumsergio/telegram-archive-viewer:dev

The dev/test instance will pick up these changes automatically (Portainer GitOps).

To test locally:

docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev

@codecov

codecov Bot commented Jul 19, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 89.72973% with 19 lines in your changes missing coverage. Please review.
✅ Project coverage is 93.50%. Comparing base (80bb0ac) to head (79beb25).
⚠️ Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
src/telegram_backup.py 87.87% 12 Missing ⚠️
src/message_utils.py 86.20% 4 Missing ⚠️
src/listener.py 93.87% 3 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            Coverage Diff             @@
##             main     #223      +/-   ##
==========================================
- Coverage   93.58%   93.50%   -0.08%     
==========================================
  Files          27       27              
  Lines        7873     8007     +134     
==========================================
+ Hits         7368     7487     +119     
- Misses        505      520      +15     
Files with missing lines Coverage Δ
src/__init__.py 100.00% <100.00%> (ø)
src/config.py 93.71% <100.00%> (+0.03%) ⬆️
src/db/adapter.py 90.94% <100.00%> (+0.03%) ⬆️
src/db/base.py 99.31% <ø> (ø)
src/listener.py 96.74% <93.87%> (+0.13%) ⬆️
src/message_utils.py 83.62% <86.20%> (+0.29%) ⬆️
src/telegram_backup.py 95.31% <87.87%> (-0.58%) ⬇️
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
tests/test_listener_chat_actions.py (1)

377-409: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Assertions are correct; same TestCase inconsistency as above.

Logic and assertions for service_message_text all check out against the implementation. These are sync tests so they run fine under plain pytest, but for consistency apply the same unittest.TestCase conversion suggested for TestChatActionHandler above.

🤖 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 `@tests/test_listener_chat_actions.py` around lines 377 - 409, Convert
TestServiceMessageText to inherit from unittest.TestCase, matching the existing
TestChatActionHandler test style. Preserve all current test methods, inputs, and
assertions for service_message_text unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with 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.

Inline comments:
In @.env.example:
- Around line 195-197: Update the REACTION_RESWEEP_DAYS comment in the
environment example to describe Telegram self-reactions as “not reliably pushed”
rather than “never pushes,” matching the wording used in README.md and runtime
documentation.

In `@docker-compose.yml`:
- Around line 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.

---

Nitpick comments:
In `@tests/test_listener_chat_actions.py`:
- Around line 377-409: Convert TestServiceMessageText to inherit from
unittest.TestCase, matching the existing TestChatActionHandler test style.
Preserve all current test methods, inputs, and assertions for
service_message_text unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 2222ba85-b9b7-4b5b-9058-c3ebe4b1dd79

📥 Commits

Reviewing files that changed from the base of the PR and between 80bb0ac and 1a9243a.

⛔ Files ignored due to path filters (1)
  • alembic/versions/20260719_019_delete_phantom_chat_action_rows.py is excluded by !alembic/versions/**
📒 Files selected for processing (16)
  • .env.example
  • README.md
  • docker-compose.yml
  • scripts/entrypoint.sh
  • src/config.py
  • src/db/adapter.py
  • src/listener.py
  • src/message_utils.py
  • src/telegram_backup.py
  • tests/test_listener_chat_actions.py
  • tests/test_listener_extended.py
  • tests/test_listener_reactions.py
  • tests/test_migration_019.py
  • tests/test_reaction_resweep.py
  • tests/test_telegram_backup.py
  • tests/test_telegram_backup_extended.py
💤 Files with no reviewable changes (1)
  • tests/test_listener_extended.py

Comment thread .env.example Resolved
Comment thread docker-compose.yml
Comment on lines +84 to +85
# REACTION_RESWEEP_DAYS: ${REACTION_RESWEEP_DAYS:-0}
# REACTION_RESWEEP_MAX_PER_CHAT: ${REACTION_RESWEEP_MAX_PER_CHAT:-500}

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.

…eaction buffer

Review-panel fixes: the sweep's synthesized add/kick service texts named
the acting admin instead of the affected user — the subject is now
resolved from the local users table (API fallback) and degrades to
'Someone', never the wrong name; self-adds read 'joined the group'.
Reaction snapshots are buffered through a shared helper that treats a
missing reactions object as no-information (never an authoritative
empty snapshot) and uses setdefault semantics in the new-message
handler, whose awaits opened a window where a fresher live-reaction
snapshot could be clobbered (reproduced). DB engines now set
hide_parameters so error logs never embed bound values (PII). Stale
vocabulary comments updated; regression tests added for all of it.
@GeiserX

GeiserX commented Jul 19, 2026

Copy link
Copy Markdown
Owner Author

Ran an 8-perspective review panel (logic, architecture, security/PII, simplicity, tests, concurrency, data-integrity, error-handling) over the full diff, with adversarial verification of every critical/high finding. Results, addressed in d06ddc0:

Fixed

  • Wrong subject in synthesized service texts (high, confirmed): the sweep named the acting admin ("Mod was removed…") instead of the affected user for ChatAddUser/ChatDeleteUser, and the upsert text gates would have frozen that wrong attribution permanently — including retroactively backfilling every historical blank service row. The subject is now resolved from the local users table (API fallback), degrading to "Someone …" when unknown, never to the wrong name. Self-adds read "joined the group". One shipped test had encoded the bug as expected behavior; rewritten plus 5 new cases.
  • Reaction-buffer stale-snapshot race (confirmed, reproduced): on_new_message's awaits opened a window where its event-time snapshot could clobber a fresher one buffered by the live reaction handler. Harvesting now goes through a single helper: a missing reactions object is treated as no-information (never an authoritative empty snapshot), and the new-message producer uses setdefault so a fresher live snapshot always wins. Regression tests simulate the interleaving.
  • PII hardening: SQLAlchemy engines now set hide_parameters=True so DB error logs never embed bound values (message text, chat ids); silent actor-lookup failures now log the exception class.
  • Stale comments claiming the listener/sweep action vocabularies "differ by design" (they were unified by this PR) corrected; migration comment about stats caching corrected (per-chat stats sit behind a self-expiring 60s web cache).
  • Test gaps closed: rate-limited edits still harvest reactions; joins don't trigger the chat-metadata refresh; real-wired reply_to_top_id/reply_to_msg_id/is_outgoing asserted; resweep per-request id slices asserted; the days=0 test now tests what its name says.

Declined (with evidence)

  • Combine the migration's 4 LIKE scans into one temp-table pass: measured on a full copy of a 1.78M-row production DB — the entire migration ran in under ~2s, one time. Not worth cross-engine temp-table complexity.
  • Resweep MSG_ID_INVALID "retries through the full flood budget": factually wrong — call_with_flood_retry retries only FloodWaitError; any other RPC error re-raises immediately and triggers the fallback at once.
  • Rolling-upgrade window (old listener writing phantoms after 019 ran): compose deployments stop the old container before starting the new one, so the window doesn't exist there; anyone who somehow hits it can re-run the idempotent cleanup (alembic downgrade 018 && alembic upgrade head). A regression test pins that the fixed listener can never emit the legacy names.
  • Freshness/versioning for reconcile_reactions across its 3 callers: reconciles are full-snapshot and idempotent; a lost race is corrected by the next observation. Versioning was deliberately rejected in the [Bug]: **Title:** Reactions are only captured by the scheduled backup, never by the real-time listener #219/feat(reactions): real-time reaction capture with retain-on-removal (#219) #220 design as unnecessary for an aggregate model.
  • Pre-filtering resweep reconciles against a batched read: real but bounded (opt-in feature, ≤500 row-locked no-op reconciles per chat per sweep). Noted as a follow-up optimization if anyone runs it at large scale.

Full suite: 2253 passed; ruff clean. Migration re-validated unchanged against the production copy (predicate untouched by this round).

@GeiserX

GeiserX commented Jul 19, 2026

Copy link
Copy Markdown
Owner Author

CodeRabbit round addressed:

  • .env.example wording — fixed in the latest commit: "self-reactions are not reliably pushed" (aligned with the README and the implementation's treatment of delivery as unreliable rather than impossible).
  • Uncommenting the resweep env lines in docker-compose.yml — declined: every optional listener knob in this compose file is a commented ${VAR:-default} documentation line by convention (LISTEN_REACTIONS, REACTION_DEBOUNCE_SECONDS, the MASS_OPERATION_* block). Users uncomment what they enable, as the README documents. Uncommenting only the resweep pair would break that convention while its master switch stays commented.
  • unittest.TestCase conversion for the new test classes — declined for the same reason as in feat(reactions): real-time reaction capture with retain-on-removal (#219) #220: the reaction/listener test files deliberately use pytest-style classes matching their direct siblings (test_listener_reactions.py, test_reactions_realtime.py); converting one class would make the file internally inconsistent.

@github-actions

Copy link
Copy Markdown

🐳 Dev images published!

  • drumsergio/telegram-archive:dev
  • drumsergio/telegram-archive-viewer:dev

The dev/test instance will pick up these changes automatically (Portainer GitOps).

To test locally:

docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
tests/test_telegram_backup_extended.py (1)

3600-3605: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Add type hints and reset reply_to on mocked message.

As per path instructions for tests, you must set msg.reply_to = None when using mock objects for Telegram messages to prevent false-positive topic filtering. Furthermore, as per coding guidelines, function signatures require type hints.

💻 Proposed fix
-    def _service_message(self, msg_id, action, *, sender_first, sender_id, text=""):
+    def _service_message(self, msg_id: int, action: object, *, sender_first: str, sender_id: int, text: str = "") -> object:
         msg = _make_message(msg_id, text=text)
+        msg.reply_to = None
         msg.sender = SimpleNamespace(first_name=sender_first, last_name=None, title=None)
         msg.sender_id = sender_id
         msg.action = action
         return msg
🤖 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 `@tests/test_telegram_backup_extended.py` around lines 3600 - 3605, Update the
test helper _service_message with type hints for its parameters and return
value, using the file’s established annotation conventions. Before returning the
mocked message, explicitly set msg.reply_to to None so topic filtering cannot
produce false positives.

Sources: Coding guidelines, Path instructions

🧹 Nitpick comments (1)
tests/test_telegram_backup_extended.py (1)

3607-3608: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add return type hints to test methods.

As per coding guidelines, use type hints for function signatures. Please apply a -> None return type hint to this test method and all other test methods in this class.

💻 Proposed fix
-    def test_empty_service_text_is_generated(self):
+    def test_empty_service_text_is_generated(self) -> None:
         msg = self._service_message(700, MessageActionChatJoinedByLink(inviter_id=0), sender_first="Dana", sender_id=55)
🤖 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 `@tests/test_telegram_backup_extended.py` around lines 3607 - 3608, Add the ->
None return annotation to test_empty_service_text_is_generated and every other
test method in the same test class, leaving their parameters and implementations
unchanged.

Source: Coding guidelines

🤖 Prompt for all review comments with 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.

Inline comments:
In `@tests/test_telegram_backup_extended.py`:
- Around line 3594-3598: Update setUp to configure the mock backup config’s
should_skip_topic attribute as MagicMock(return_value=False), preventing truthy
mock behavior in tests. Add an explicit return type annotation to the setUp
method signature, preserving its existing setup logic.

---

Outside diff comments:
In `@tests/test_telegram_backup_extended.py`:
- Around line 3600-3605: Update the test helper _service_message with type hints
for its parameters and return value, using the file’s established annotation
conventions. Before returning the mocked message, explicitly set msg.reply_to to
None so topic filtering cannot produce false positives.

---

Nitpick comments:
In `@tests/test_telegram_backup_extended.py`:
- Around line 3607-3608: Add the -> None return annotation to
test_empty_service_text_is_generated and every other test method in the same
test class, leaving their parameters and implementations unchanged.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8c907233-fea3-4bc2-8935-c38d7e4b460b

📥 Commits

Reviewing files that changed from the base of the PR and between 1a9243a and d06ddc0.

⛔ Files ignored due to path filters (1)
  • alembic/versions/20260719_019_delete_phantom_chat_action_rows.py is excluded by !alembic/versions/**
📒 Files selected for processing (8)
  • src/db/base.py
  • src/listener.py
  • src/message_utils.py
  • src/telegram_backup.py
  • tests/test_listener_chat_actions.py
  • tests/test_listener_reactions.py
  • tests/test_reaction_resweep.py
  • tests/test_telegram_backup_extended.py
🚧 Files skipped from review as they are similar to previous changes (6)
  • src/message_utils.py
  • tests/test_listener_reactions.py
  • src/listener.py
  • src/telegram_backup.py
  • tests/test_reaction_resweep.py
  • tests/test_listener_chat_actions.py

Comment on lines +3594 to +3598
def setUp(self):
self.backup = _make_backup()
# Subject resolution defaults: unknown everywhere -> "Someone ..." texts.
self.backup.db.get_user_by_id = AsyncMock(return_value=None)
self.backup.client.get_entity = AsyncMock(side_effect=RuntimeError("unavailable"))

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 | 🟡 Minor | ⚡ Quick win

Mock should_skip_topic and add a return type hint.

As per path instructions for tests, you must set config.should_skip_topic = MagicMock(return_value=False) on mock configs to prevent false truthiness. Additionally, as per coding guidelines, use type hints for function signatures.

💻 Proposed fix
-    def setUp(self):
+    def setUp(self) -> None:
         self.backup = _make_backup()
+        self.backup.config.should_skip_topic = MagicMock(return_value=False)
         # Subject resolution defaults: unknown everywhere -> "Someone ..." texts.
         self.backup.db.get_user_by_id = AsyncMock(return_value=None)
         self.backup.client.get_entity = AsyncMock(side_effect=RuntimeError("unavailable"))
📝 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
def setUp(self):
self.backup = _make_backup()
# Subject resolution defaults: unknown everywhere -> "Someone ..." texts.
self.backup.db.get_user_by_id = AsyncMock(return_value=None)
self.backup.client.get_entity = AsyncMock(side_effect=RuntimeError("unavailable"))
def setUp(self) -> None:
self.backup = _make_backup()
self.backup.config.should_skip_topic = MagicMock(return_value=False)
# Subject resolution defaults: unknown everywhere -> "Someone ..." texts.
self.backup.db.get_user_by_id = AsyncMock(return_value=None)
self.backup.client.get_entity = AsyncMock(side_effect=RuntimeError("unavailable"))
🤖 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 `@tests/test_telegram_backup_extended.py` around lines 3594 - 3598, Update
setUp to configure the mock backup config’s should_skip_topic attribute as
MagicMock(return_value=False), preventing truthy mock behavior in tests. Add an
explicit return type annotation to the setUp method signature, preserving its
existing setup logic.

Sources: Coding guidelines, Path instructions

@github-actions

Copy link
Copy Markdown

🐳 Dev images published!

  • drumsergio/telegram-archive:dev
  • drumsergio/telegram-archive-viewer:dev

The dev/test instance will pick up these changes automatically (Portainer GitOps).

To test locally:

docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev

1 similar comment
@github-actions

Copy link
Copy Markdown

🐳 Dev images published!

  • drumsergio/telegram-archive:dev
  • drumsergio/telegram-archive-viewer:dev

The dev/test instance will pick up these changes automatically (Portainer GitOps).

To test locally:

docker pull drumsergio/telegram-archive:dev
docker pull drumsergio/telegram-archive-viewer:dev

@GeiserX
GeiserX merged commit 8927b5e into main Jul 19, 2026
8 checks passed
@GeiserX
GeiserX deleted the ai/issues-221-222 branch July 19, 2026 15:24
GeiserX added a commit that referenced this pull request Jul 28, 2026
…ions (#221, #222) (#223)

* fix(listener): archive chat actions with real message ids and correct classification (#222)

The chat-action classifier's photo-is-None branch swallowed every
non-photo action as photo_removed, and rows were written with
wall-clock-derived synthetic ids (~2 phantom rows per join/leave).
Service rows are now written only when the event carries a real
MessageService (real id/date), tagged with the shared sweep
vocabulary via service_action_type, with human-readable text
generated by a new shared service_message_text helper used by both
the listener and the backfill sweep. Participant-only syncs write
no message row.

* fix(db): migration 019 purges phantom chat-action rows (#222)

Parse-free LIKE cleanup of the 7 legacy listener action_type names on
the TEXT raw_data column (spaced + compact JSON forms, escaped
underscores, no id or service_type condition per production forensics).
Dependent reactions/media/message_versions rows are deleted explicitly
first since the reactions FK has no cascade and SQLite may run without
foreign_keys. Invalidates cached_stats AND stats_calculated_at so the
viewer recomputes correct counts on next start. Data-only migration:
intentionally absent from the entrypoint stamp ladders (documented in
both), so alembic upgrade head always runs it.

* feat(reactions): capture own-account reactions via edit harvest and bounded resweep (#221)

Telegram does not reliably push UpdateMessageReactions for the archive
account's own reactions (made from another device) to the archive's
session. Close the gap three ways: harvest reaction snapshots carried
on edit events and on newly-arriving messages into the shared debounce
buffer (min payloads skipped - they omit the current user's own
reactions); piggyback reaction reconciliation onto the existing
SYNC_DELETIONS_EDITS full-message fetch at zero extra API cost; and add
an opt-in bounded re-sweep (REACTION_RESWEEP_DAYS, default off, capped
by REACTION_RESWEEP_MAX_PER_CHAT) that re-checks recent messages per
chat each scheduled sweep via batched GetMessagesReactionsRequest with
a get_messages fallback. Documents the limitation in the README.

* fix(review): name the affected user in service texts and harden the reaction buffer

Review-panel fixes: the sweep's synthesized add/kick service texts named
the acting admin instead of the affected user — the subject is now
resolved from the local users table (API fallback) and degrades to
'Someone', never the wrong name; self-adds read 'joined the group'.
Reaction snapshots are buffered through a shared helper that treats a
missing reactions object as no-information (never an authoritative
empty snapshot) and uses setdefault semantics in the new-message
handler, whose awaits opened a window where a fresher live-reaction
snapshot could be clobbered (reproduced). DB engines now set
hide_parameters so error logs never embed bound values (PII). Stale
vocabulary comments updated; regression tests added for all of it.

* docs(env): soften self-reaction wording per review

* chore: bump version to 7.24.0
GeiserX added a commit that referenced this pull request Oct 2, 2026
…ions (#221, #222) (#223)

* fix(listener): archive chat actions with real message ids and correct classification (#222)

The chat-action classifier's photo-is-None branch swallowed every
non-photo action as photo_removed, and rows were written with
wall-clock-derived synthetic ids (~2 phantom rows per join/leave).
Service rows are now written only when the event carries a real
MessageService (real id/date), tagged with the shared sweep
vocabulary via service_action_type, with human-readable text
generated by a new shared service_message_text helper used by both
the listener and the backfill sweep. Participant-only syncs write
no message row.

* fix(db): migration 019 purges phantom chat-action rows (#222)

Parse-free LIKE cleanup of the 7 legacy listener action_type names on
the TEXT raw_data column (spaced + compact JSON forms, escaped
underscores, no id or service_type condition per production forensics).
Dependent reactions/media/message_versions rows are deleted explicitly
first since the reactions FK has no cascade and SQLite may run without
foreign_keys. Invalidates cached_stats AND stats_calculated_at so the
viewer recomputes correct counts on next start. Data-only migration:
intentionally absent from the entrypoint stamp ladders (documented in
both), so alembic upgrade head always runs it.

* feat(reactions): capture own-account reactions via edit harvest and bounded resweep (#221)

Telegram does not reliably push UpdateMessageReactions for the archive
account's own reactions (made from another device) to the archive's
session. Close the gap three ways: harvest reaction snapshots carried
on edit events and on newly-arriving messages into the shared debounce
buffer (min payloads skipped - they omit the current user's own
reactions); piggyback reaction reconciliation onto the existing
SYNC_DELETIONS_EDITS full-message fetch at zero extra API cost; and add
an opt-in bounded re-sweep (REACTION_RESWEEP_DAYS, default off, capped
by REACTION_RESWEEP_MAX_PER_CHAT) that re-checks recent messages per
chat each scheduled sweep via batched GetMessagesReactionsRequest with
a get_messages fallback. Documents the limitation in the README.

* fix(review): name the affected user in service texts and harden the reaction buffer

Review-panel fixes: the sweep's synthesized add/kick service texts named
the acting admin instead of the affected user — the subject is now
resolved from the local users table (API fallback) and degrades to
'Someone', never the wrong name; self-adds read 'joined the group'.
Reaction snapshots are buffered through a shared helper that treats a
missing reactions object as no-information (never an authoritative
empty snapshot) and uses setdefault semantics in the new-message
handler, whose awaits opened a window where a fresher live-reaction
snapshot could be clobbered (reproduced). DB engines now set
hide_parameters so error logs never embed bound values (PII). Stale
vocabulary comments updated; regression tests added for all of it.

* docs(env): soften self-reaction wording per review

* chore: bump version to 7.24.0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Listener never captures reactions made by the archive's own account

1 participant