Skip to content

fix(icons): address PR #3 review findings - #4

Merged
yazdipour merged 2 commits into
masterfrom
fix/icon-cache-review
Nov 25, 2026
Merged

yazdipour merged 2 commits into
masterfrom
fix/icon-cache-review

Conversation

@yazdipour

@yazdipour yazdipour commented Nov 25, 2026 •

Copy link
Copy Markdown
Owner

Fixes the issues raised by the review bots on #3.

Changes

  • Stale icon on reused slug: icon cache (memory + disk) is keyed by channel identity instead of slug.
  • Refresh stores old icon: a fetched icon is cached only if its channel is still configured.
  • Concurrent fetches: per-channel lock coalesces simultaneous cache misses into one Telegram download.
  • Failed fetches retried every request: 5-minute backoff after a failed fetch.
  • Unbounded icon cache: icons of unconfigured channels are pruned on startup and config change (≤ one file per channel); icons over 2 MB are rejected.
  • Write failure aborts request: temp-file cleanup errors are ignored.
  • Duplicate sources: sources are deduplicated by channel (usernames case-insensitive); the config UI rejects duplicates; duplicate removed from config.example.yml.
  • README: icon_cache_dir nested under server: in both examples.

Notes

  • Existing slug-named icon files are pruned on first start and re-fetched once.
  • Duplicate entries in an existing config.yml now yield one source, so URLs like <slug>-2.json disappear.

Testing

  • Added tests/test_icon_cache.py (7 tests); full suite: 26 passed.

🤖 Generated with Claude Code

Summary by Sourcery

Harden channel icon caching and configuration handling against stale data, duplicate sources, failed downloads, and unbounded cache growth.

Bug Fixes:

  • Prevent stale icons when a slug is reassigned by keying icon state to channel identity and versioning icon URLs.
  • Avoid caching icons for channels removed or changed during refresh, coalesce concurrent downloads, and back off failed fetches for five minutes.
  • Bound and safely maintain the icon cache by pruning obsolete files, rejecting oversized icons, and tolerating cleanup failures.
  • Deduplicate configured channels across case-insensitive forms and update the configuration UI to reject and remove duplicates consistently.

Enhancements:

  • Align README examples and icon-cache behavior documentation with the current configuration and caching semantics.

Tests:

  • Add coverage for icon cache identity, concurrency, retries, pruning, write failures, configuration refreshes, URL invalidation, and duplicate-channel handling.

- Key icon cache (memory + disk) by channel, not slug, so a reused
  slug never serves the previous channel's icon
- Skip caching icons for channels removed while the fetch was in flight
- Coalesce concurrent fetches per channel behind a lock
- Back off 5 min after a failed fetch instead of retrying every request
- Prune icons of unconfigured channels on startup and config change;
  reject icons over 2 MB
- Ignore cleanup errors when an icon cache write fails
- Deduplicate sources by channel; reject duplicates in config UI
- Nest icon_cache_dir under server in README; drop duplicate example channel

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Define canonical channel identity and stable keys, then deduplicate sources so downstream source and icon state is based on distinct channels.

  • src/settings.py L123-137, L199, L205-207

API

Update source and channel-icon URL contracts with channel-based cache-busting, and make the configuration routes reject duplicate additions and remove all copies of a channel safely.

  • src/main.py L837-838, L856-866
  • src/source_builder.py L8, L50-52

Implementation

Implement channel-keyed icon caching, request coalescing, failed-fetch backoff, stale-source checks, size limits, and safe pruning and writes; review this together with the lifecycle and configuration-refresh hooks that manage the cache state.

  • src/main.py L79-87, L459-502, L526-591 (+6 small edits)

UI

Keep configuration UI rows aligned with the deduplicated source list so repeated or empty channel entries do not misalign displayed controls.

  • src/main.py L100-108

Configuration

Remove the duplicate channel from the example configuration and correct both README examples so icon_cache_dir is nested under server.

  • README.md L59, L100
  • config.example.yml L32 (removed lines)

Documentation

Document channel-based icon storage and pruning, oversized-icon rejection behavior, and the five-minute retry interval.

  • README.md L103

Tests

Add regression coverage for icon identity, concurrency, failures, pruning, URL versioning, and duplicate-channel behavior.

  • tests/test_icon_cache.py L1-244

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 25, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-25T22:29:57.397789Z efc836a PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: efc836a3a8

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/main.py Resolved
Comment thread src/settings.py Resolved

@sourcery-ai sourcery-ai 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.

Hey - I've found 13 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/main.py" line_range="482-483" />
<code_context>
+        if entry.name in keep:
+            continue
+        try:
+            if entry.is_file():
+                entry.unlink()
+        except OSError as exc:
+            logger.warning("Channel icon cache prune failed for %s: %s", entry.name, exc)
</code_context>
<issue_to_address>
**Unrelated files are deleted**

When the icon cache directory contains regular files not managed by the icon cache, `_prune_icon_cache` unlinks every regular file absent from the keep set, so a config refresh or startup deletes unrelated data in the directory.

Restrict pruning to filenames that match the icon cache’s naming scheme.
</issue_to_address>

### Comment 2
<location path="src/main.py" line_range="557-560" />
<code_context>
+
+        source_icon_retry_after.pop(channel, None)
+        # The config may have dropped this channel while Telegram was answering.
+        if _channel_still_configured(channel):
+            source_icon_caches[channel] = icon
+            _write_icon_cache(_icon_cache_path(channel), icon)
+        return icon


</code_context>
<issue_to_address>
**Removed channel icon is served**

When a channel is removed and its slug is reassigned while its icon download is in flight, `_source_channel_icon` returns the downloaded bytes even when `_channel_still_configured` rejects caching them, so the handler serves the removed channel’s icon at the reassigned slug.

Recheck that the channel still owns the slug before returning the downloaded icon.
</issue_to_address>

### Comment 3
<location path="src/main.py" line_range="550" />
<code_context>
+        return cached
+    if monotonic() < source_icon_retry_after.get(channel, 0.0):
         return None
-    icon = await telegram.download_channel_photo(source)
-    if icon:
-        source_icon_caches[source.slug] = icon
</code_context>
<issue_to_address>
**Telegram errors bypass icon backoff**

When `telegram.download_channel_photo` raises during connection setup, `_source_channel_icon` exits before setting `source_icon_retry_after`, so the icon endpoint propagates the error and repeats the failing Telegram call on every request instead of using backoff and the fallback path.

Catch download exceptions, set the retry deadline, and return the fallback path.
</issue_to_address>

### Comment 4
<location path="src/main.py" line_range="97" />
<code_context>
     for config_index, raw_source in enumerate(channels):
-        if not isinstance(raw_source, str) or not normalize_channel(raw_source):
+        channel = normalize_channel(raw_source) if isinstance(raw_source, str) else ""
+        if not channel or channel_identity(channel) in seen:
             continue
+        seen.add(channel_identity(channel))
</code_context>
<issue_to_address>
**Duplicate channel cannot be removed**

When an existing config contains duplicate entries for a channel and the user removes it through the config UI, `_source_config_rows` exposes only the first duplicate, while `config_remove_channel` deletes only that entry and counts duplicates separately. The channel remains configured and, when it is the only distinct channel, the last duplicate cannot be removed.

Remove every raw config entry with the selected channel identity and count distinct channel identities when enforcing the minimum.

Also at `src/settings.py:195`.
</issue_to_address>

### Comment 5
<location path="src/settings.py" line_range="195" />
<code_context>

         channel = normalize_channel(raw_source)
-        if not channel:
+        if not channel or channel_identity(channel) in seen_channels:
             continue
+        seen_channels.add(channel_identity(channel))
</code_context>
<issue_to_address>
**Invite link forms create duplicates**

When the same invite hash is configured as both `+<hash>` and `joinchat/<hash>`, `channel_identity` treats the two invite forms as different, so `_load_sources` creates duplicate sources and the config UI accepts both entries.

Canonicalize both invite-link forms to the same identity.

Also at `src/settings.py:123-125`, `src/main.py:804-805`.
</issue_to_address>

### Comment 6
<location path="src/main.py" line_range="552" />
<code_context>
+
+        icon = await telegram.download_channel_photo(source)
+        if not icon or len(icon) > ICON_MAX_BYTES:
+            source_icon_retry_after[channel] = monotonic() + ICON_RETRY_SECONDS
+            return None
+
</code_context>
<issue_to_address>
**Re-added channel stays without an icon**

When a channel is removed during an icon download, the download fails, and the channel is re-added before the retry deadline, the failed request writes `source_icon_retry_after[channel]` after the refresh removed the entry. The re-added channel then skips fetching and serves the fallback icon until the deadline expires.

Only write the retry deadline if the channel is still configured after the download fails.
</issue_to_address>

### Comment 7
<location path="src/main.py" line_range="539" />
<code_context>
-        _write_icon_cache(path, icon)
-    return icon
+
+    lock = source_icon_locks.setdefault(channel, asyncio.Lock())
+    async with lock:
+        # Another request may have fetched it while this one waited.
</code_context>
<issue_to_address>
**Case changes trigger duplicate downloads**

When a username’s capitalization changes while an icon fetch is in flight and another request arrives, `source_icon_locks` uses the raw channel string as its key, so the requests acquire different locks and download the same channel photo concurrently.

Key `source_icon_locks` by `channel_identity(channel)`.
</issue_to_address>

### Comment 8
<location path="src/main.py" line_range="540" />
<code_context>
-    return icon
+
+    lock = source_icon_locks.setdefault(channel, asyncio.Lock())
+    async with lock:
+        # Another request may have fetched it while this one waited.
+        cached = _cached_channel_icon(channel)
</code_context>
<issue_to_address>
**Stale icon locks accumulate**

When distinct channels are repeatedly added, requested, and removed, `source_icon_locks.setdefault` retains a lock for every requested channel, but `_runtime_refresh` prunes only icon and retry state. The global lock map grows for the lifetime of the process.

Prune locks for removed channels during `_runtime_refresh` without removing locks that are still in use.

Also at `src/main.py:36`, `src/main.py:73-75`, `src/main.py:539`.
</issue_to_address>

### Comment 9
<location path="src/main.py" line_range="515" />
<code_context>
-    # Icons are fetched once and kept forever (memory, then disk). Only successful
-    # fetches are stored, so a failed attempt is retried on the next request.
-    cached = source_icon_caches.get(source.slug)
+def _cached_channel_icon(channel: str) -> bytes | None:
+    cached = source_icon_caches.get(channel)
     if isinstance(cached, bytes):
</code_context>
<issue_to_address>
**Case changes miss memory cache**

When a configured username changes casing across a refresh and `icon_cache_dir` is empty, `source_icon_caches.get(channel)` and refresh cleanup use the raw channel string rather than `channel_identity`; a case-only username change leaves the old entry behind and misses it under the new spelling. With disk storage disabled, the service downloads the same channel icon again instead of reusing the memory cache.

Use `channel_identity(channel)` consistently for in-memory cache, retry, and refresh-pruning keys.

Also at `src/main.py:74`.
</issue_to_address>

### Comment 10
<location path="src/main.py" line_range="458" />
<code_context>
+def _icon_cache_key(channel: str) -> str:
+    # Keyed by channel identity, not slug: a slug can be reassigned to another
+    # channel when the config changes, and must never inherit the old icon.
+    return sha256(channel_identity(channel).encode("utf-8")).hexdigest()[:32]
+
+
</code_context>
<issue_to_address>
**Browsers keep stale reused-slug icons**

When a client has cached an icon and its channel’s slug is reassigned to another channel within 24 hours, the channel-hashed disk path does not change the slug-based icon URL, and `_icon_response` still advertises a 24-hour public cache. A browser that cached the old channel’s icon continues displaying it after the slug is reassigned, despite the server returning the new channel’s icon.

Avoid long-lived caching for slug-based icon URLs or include a channel-specific version in the public URL.
</issue_to_address>

### Comment 11
<location path="src/main.py" line_range="476" />
<code_context>
+    keep = {f"{_icon_cache_key(source.channel)}{ICON_CACHE_SUFFIX}" for source in settings.sources}
+    try:
+        entries = list(cache_dir.iterdir())
+    except OSError:
+        return
+    for entry in entries:
</code_context>
<issue_to_address>
**Prune failures go unnoticed**

When the cache directory temporarily cannot be listed while stale icon files are present, `_prune_icon_cache` silently returns when listing the cache directory fails, leaving icons for removed channels on disk; repeated channel churn then defeats the stated disk-cache bound without an operator-visible warning.

Log the directory-listing failure and make pruning retryable so stale files are eventually removed.
</issue_to_address>

### Comment 12
<location path="tests/test_icon_cache.py" line_range="59-62" />
<code_context>
+        old, new = _source("oldchannel"), _source("newchannel")
+        fake = FakeTelegram({"oldchannel": b"OLD", "newchannel": b"NEW"})
+        with patch.object(main_module, "telegram", fake):
+            self._use(old)
+            self.assertEqual(await main_module._source_channel_icon(old), b"OLD")
+            self._use(new)
+            self.assertEqual(await main_module._source_channel_icon(new), b"NEW")
+
+    async def test_concurrent_misses_share_one_download(self):
</code_context>
<issue_to_address>
**Disabled caching goes unnoticed**

When the implementation stops using the icon caches but still downloads the requested channel’s icon, `test_reused_slug_does_not_inherit_previous_channel_icon` checks only the returned bytes at lines 60 and 62. An implementation that skips memory and disk caching but downloads each icon afresh returns `OLD` and `NEW`, so the test passes without exercising whether a reused slug can inherit a cached icon.

Assert that a same-channel request uses its cached icon, and verify that the changed channel does not reuse the prior channel’s cache entry.
</issue_to_address>

### Comment 13
<location path="tests/test_icon_cache.py" line_range="102-107" />
<code_context>
+        main_module._prune_icon_cache()
+        self.assertEqual(list(cache_dir.iterdir()), [kept])
+
+    def test_write_failure_with_failing_cleanup_does_not_raise(self):
+        path = Path(self.tmpdir.name) / "icon.img"
+        with patch.object(Path, "write_bytes", side_effect=OSError("disk full")), patch.object(
+            Path, "unlink", side_effect=OSError("busy")
+        ):
+            main_module._write_icon_cache(path, b"ICON")
+
+
</code_context>
<issue_to_address>
**Missing cache writes go unnoticed**

When `_write_icon_cache` is changed to return without attempting a write, `test_write_failure_with_failing_cleanup_does_not_raise` only calls `_write_icon_cache` at line 107 and checks implicitly that it raises nothing. Replacing the function with a no-op passes, even though icons are never written to disk.

Assert that the write was attempted and that the cleanup failure does not escape the call.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 12 findings to address first, and on startup and config refresh, _prune_icon_cache unlinks every regular file in the configured icon-cache directory whose name is not a current channel cache key, including files that are not icon-cache entries. Reverting stops future deletions but cannot restore files already removed.

Blocking findings: src/main.py:483, src/main.py:560, src/main.py:550, src/main.py:97, src/settings.py:195, and 7 more


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/main.py Resolved
Comment thread src/main.py Resolved
Comment thread src/main.py Resolved
Comment thread src/main.py Resolved
Comment thread src/settings.py Resolved
Comment thread src/main.py Resolved
Comment thread src/main.py Resolved
Comment thread src/main.py Resolved
Comment thread tests/test_icon_cache.py Resolved
Comment thread tests/test_icon_cache.py Resolved
- Prune only icon-cache file names, never unrelated files in a shared dir
- Log when the icon cache dir cannot be listed during pruning
- Remove all duplicates of a channel at once; count distinct channels
  for the at-least-one check
- Treat +<hash> and joinchat/<hash> as the same invite
- Catch Telegram errors during icon download and apply the backoff
- Serve and record nothing if the slug moved to another channel
  during the download
- Key icon cache, locks and backoff by channel identity; drop idle
  locks of removed channels on config change
- Version source icon URLs by channel so browsers refetch after a
  slug is reassigned
- Tighten icon cache tests

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@yazdipour
yazdipour merged commit d60679e into master Nov 25, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant