Repository navigation
fix(icons): address PR #3 review findings - #4
Conversation
- 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>
Reviewer's GuideData structuresDefine canonical channel identity and stable keys, then deduplicate sources so downstream source and icon state is based on distinct channels.
APIUpdate 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.
ImplementationImplement 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.
UIKeep configuration UI rows aligned with the deduplicated source list so repeated or empty channel entries do not misalign displayed controls.
ConfigurationRemove the duplicate channel from the example configuration and correct both README examples so icon_cache_dir is nested under server.
DocumentationDocument channel-based icon storage and pruning, oversized-icon rejection behavior, and the five-minute retry interval.
TestsAdd regression coverage for icon identity, concurrency, failures, pruning, URL versioning, and duplicate-channel behavior.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
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
- 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>
Fixes the issues raised by the review bots on #3.
Changes
config.example.yml.icon_cache_dirnested underserver:in both examples.Notes
config.ymlnow yield one source, so URLs like<slug>-2.jsondisappear.Testing
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:
Enhancements:
Tests: