Skip to content

LR-LIB-SMARTALBUM: albums.list answers at once from the counts the sidebar keeps (stacked on #2020) - #3387

Open
nledford wants to merge 3 commits into
storytold:mainfrom
nledford:perf-albums-list
Open

nledford wants to merge 3 commits into
storytold:mainfrom
nledford:perf-albums-list

Conversation

@nledford

@nledford nledford commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Part of #2020's smart-album counts. Stacked on #2020 (the lc-album-counts worker): this PR's own commit is the last one, LR-LIB-SMARTALBUM: albums.list answers at once from the counts the sidebar keeps.

Problem

albums.list (the control channel, and cmd_albums_list through MCP when connected to the app) counted every smart album's photos on the window's thread (AlbumTally::of) before it answered. On a library of 844,425 photos with 176 albums (91 smart) the window did not respond for about 79 s, and the request itself gave up after its 60 s limit. The sidebar already keeps these counts and counts them on a worker thread (#2020), so the same work was done twice, once of them on the UI thread.

Change

  • In the app, albums.list answers from the counts the sidebar keeps (Caches::album_counts_for_list, offered to the session with Session::offer_album_counts) and counts no smart album's photos itself. An album of chosen photos is counted from its list.
  • A smart album whose count is not of the library as it is now yet gets countPending: true, and its count is the count made before (0 if none). A new minute puts only the albums whose rules ask about "the last N days" (their own or through an album they test) behind; any other count behind the catalog (new rules, an edit to many photos, a library just opened) puts every smart album behind until the worker is done. Reply fields and shapes are otherwise unchanged. Documented in docs/control-protocol.md and docs/mcp.md, with a What's New entry.
  • With no window (lightcraft-cli run, the headless MCP server, a bare Session) there is no UI thread to stop, so crates/engine/src/album_counts.rs counts once on the calling thread, keeps the AlbumTally, follows edits to a few photos with AlbumTally::update and recounts for a new library or clock minute. Repeated calls no longer count every photo again, and its answers are never pending. It also sets the session clock for "in the last…" rules, which the command did not do before.

Not in this PR: a folder's count when a folder's photos are "the photos of the albums inside it" (#768): see Merging. A failed count (logged) is not retried until the library changes, and while a library has an "in the last…" album and a full count takes longer than a minute that album stays pending; both are #2020's behavior and are documented. album.createSmart and album.setRules still count the one album they touch.

How it was checked

Timings (albums.list over the control channel, alone in the app, a second connection pinging activity.list meanwhile; fresh APFS clone of a library copy of 844,425 photos with 176 albums, 85 of them folders and 91 smart, backups off, catalog format 11; the loads were 10–35 on the 1-minute average, runs above 40 discarded; 3 runs each, base and branch alternating). The measurement base is e423a99eea, which includes the catalog format 11 chain, #768 and #2020; the branch builds are that plus this commit, cherry-picked in a throwaway branch (it conflicts with #768 in albums.list and in the folder count; see Merging):

base e423a99eea base + this commit, folders as is base + this commit, folder counts from the kept counts
albums.list answer no answer in 60 s (request limit; window frozen ~79 s) 49.5–50.0 s 0.048–0.050 s
longest gap between pings no ping answered for 5 s (their limit) while it ran no ping answered for 5 s 0.048–0.093 s
asked again no answer (still frozen) 49.7–60.5 s 0.029–0.136 s
counts current on a later answer never after ~100 s after 28.4–29.7 s (the worker)

The middle column is what the two PRs do together if merged as they are: 85 of the 176 albums are folders, and in #768 a folder's count is a pass over every photo (Catalog::album_count on a folder), still made on the UI thread. The third column is the same build with a folder's count taken from the kept counts as well (folders report 0 there, as that build's tally leaves them out): that is the part #768 has to do, see Merging.

Merging

Checklist

  • No new panic path in non-test code: no unwrap / expect / panic!, no indexing or unchecked arithmetic on a number from a file, a person or an agent (get, checked_mul, NaN and char boundaries handled)
  • New text on screen goes through tr() and has its key in crates/ui-egui/locales/*.json; a new shortcut is free in docs/library-shortcuts.md (no text on screen)
  • The feature's rows in docs/parity-checklist.md and its entry in docs/gaps.md are updated, honestly (🟡 when it is partial), in the same commit
  • New code has a caller: no command, module or setting that nothing reaches yet
  • Every new image, icon or other asset has its entry in assets/ATTRIBUTION.md; no font or media files added
  • Ready to merge (otherwise open it as a draft)

Summary by CodeRabbit

  • New Features

    • Album listings now use cached counts when available, keeping smart-album results responsive in the desktop app. Counts being recalculated are marked as pending and may show the previous count until an updated result is ready.
    • Counts update after photo edits and changes to smart-album rules. Time-based rules are refreshed as needed.
    • In CLI and headless sessions, counts are calculated once, cached, and updated after edits.
  • Documentation

    • Added guidance on album counts and pending status across supported session types.

nledford and others added 3 commits October 28, 2026 07:11
… window while albums are counted

In a large library with smart albums, the frame after an edit the album
tally could not follow photo by photo counted every smart album over
every photo on the UI thread: seconds, during which the window froze.
Creating a keyword inside another one (and giving it to the selected
photos) was such an edit, because Op::SetKeyword was classed as a broad
op, so the view, the folder tree and the date groups were worked out
again too.

- The keyword list changes no photo and no rule, filter or sort reads
  it: Op::SetKeyword now records Aspects::KEYWORD_LIST instead of
  marking the catalog's change memory broad. The view and the albums'
  counts follow the edit from the photos it touched; only the keyword
  tree is made again.
- A count of every photo that is still needed (an album's rules or
  photos changed, an edit to more than 256 photos, a new minute with an
  "in the last…" rule, a library opened) runs on a worker thread over a
  copy of the catalog. The sidebar keeps the counts it showed (none
  before the first count, and none of another library) and follows the
  edits made meanwhile once the count is in. AlbumTally::update only
  follows now; the caller decides where to count whole.

Co-Authored-By: Claude <noreply@anthropic.com>
…debar keeps

`albums.list` counted every smart album's photos on the UI thread (`AlbumTally::of`) before it answered: with 176
albums in a library of 844,425 photos the window did not respond for about 79 s.

In the app the command now answers from the counts the sidebar keeps (counted on the `lc-album-counts` worker,
followed through edits to a photo or a few): an album of chosen photos is counted from its list, a smart album's count
is the kept one, and `countPending: true` says it is not of the catalog as it is now yet (the count made before, or 0).
A session with no window (the CLI, the headless MCP server) counts once, keeps the counts and follows edits.
@coderabbitai

coderabbitai Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review.

Recent review info
Run configuration
Commits

Reviewing files that changed from the base of the PR and between 5194cc2 and 9de9377.

Files selected for processing: 20
  • crates/catalog/src/lib.rs
  • crates/catalog/src/tally.rs
  • crates/catalog/src/tests.rs
  • crates/engine/src/album_counts.rs
  • crates/engine/src/cmd/query.rs
  • crates/engine/src/lib.rs
  • crates/engine/src/tests.rs
  • crates/engine/src/tests/album_counts.rs
  • crates/engine/src/tests/view_follow.rs
  • crates/ui-egui/src/caches.rs
  • crates/ui-egui/src/control.rs
  • crates/ui-egui/src/headless.rs
  • crates/ui-egui/src/lib.rs
  • crates/ui-egui/src/panels/left/albums.rs
  • crates/ui-egui/src/tests.rs
  • crates/ui-egui/src/tests/album_list.rs
  • docs/control-protocol.md
  • docs/mcp.md
  • docs/parity-checklist.md
  • docs/whats-new.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Walkthrough

The change adds separate tracking for keyword-list revisions and reusable album counts. Windowed sessions can return cached counts while recounts run, with freshness reported for smart albums. Sessions without a window cache local counts and update or recount them as catalog and time-based rules change.

Changes: Album count tracking and listing

Layer / File(s) Summary
Track keyword-list changes and tally updates
crates/catalog/src/lib.rs, crates/catalog/src/tally.rs, crates/catalog/src/tests.rs, crates/engine/src/tests/view_follow.rs
Keyword-list changes now have a separate revision aspect. Tally updates can return false without changing the tally, and tests cover keyword revision tracking and full-recount fallback.
Reuse counts in engine sessions
crates/engine/src/album_counts.rs, crates/engine/src/cmd/query.rs, crates/engine/src/lib.rs, crates/engine/src/tests/*
Sessions consume offered counts or reuse local tallies, updating them when possible and recounting when needed. albums.list returns count freshness for smart albums.
Cache counts and run background recounts
crates/ui-egui/src/caches.rs
The UI cache keys counts by library, catalog revision, and relevant minute. Native builds can recount on a worker thread. Results for another library are discarded, and failed recounts retain displayed counts.
Connect cached counts to listing and display
crates/ui-egui/src/control.rs, crates/ui-egui/src/headless.rs, crates/ui-egui/src/lib.rs, crates/ui-egui/src/panels/left/albums.rs, crates/ui-egui/src/tests/*, docs/control-protocol.md, docs/mcp.md, docs/parity-checklist.md, docs/whats-new.md
The control path offers cached counts during albums.list. Album rows can show unknown counts, and headless busy status includes active recounts. Tests and docs describe count freshness and windowed or headless behavior.

Priority: Normal

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

Change: Feature

Sequence Diagram(s)

sequenceDiagram
  participant Control
  participant Caches
  participant Session
  participant AlbumsList
  Control->>Caches: Request cached counts and freshness
  Caches-->>Control: Return counts and freshness
  Control->>Session: Offer counts
  Session->>AlbumsList: Run albums.list
  AlbumsList->>Session: Consume offered counts
  Control->>Session: Withdraw offered counts
Loading

Possibly related issues

  • storytold/lightcraft#2580 — The issue summary includes smart-album count optimization, and this change adds cached counts to the albums.list path.

Suggested reviewers: aiongg, echelon

Merge Risk: Low · up to 9de93

Chosen-photo album counts may briefly be missing or outdated in the sidebar. This is a bounded display issue, not a blocker to merging.

Security architecture risk: Low · up to 9de93

Background counting improves responsiveness and explicitly marks stale results. Library switches can, however, leave earlier counts running without tracking their resource use. The supported impact is limited to the local application; no expanded permission or data-access path was identified.

Retained concerns

  • Low · reliability · inferred: Library changes escape the recount concurrency bound. When a different library generation is requested, the previous job handle is discarded while its worker continues holding a catalog snapshot and counting. A replacement worker can then start, so repeated switches during long recounts can overlap resource-intensive scans that are no longer included in busy reporting. This is an introduced process-resource containment issue, not evidence of cross-library data disclosure; obsolete results are discarded and each scan normally terminates.
Security review details

Security Blast Radius

  • inferred — The supported containment concern affects CPU and memory within the application process. Triggering overlap requires changing libraries while counting is still running; repeated listings within one unchanged library remain constrained by the tracked active job.

Security Findings and Attack Paths

  • inferred — A user or existing control caller able to open libraries can switch while a long recount runs and request another listing, allowing obsolete recounts to overlap. The inspected switch guard blocks imports, not recounts. This supports a local availability concern, not a verified unauthenticated remote attack.

Trust Boundaries and Controls

  • observed — The count offer does not grant additional command authority: the wrapper still invokes the existing command route. Library mismatches discard cached counts and obsolete worker receivers, preventing old-library results from being published into the new library through this path.

Resilience and Maintainability Implications

  • observed — Worker disconnection clears the tracked job and records failure rather than leaving it permanently active. This protects result-state recovery, but the running-job indicator only considers the retained handle and therefore excludes detached old-library workers.

Hardening Proposals

  • proposed — Preserve worker ownership until completion and enforce a recount concurrency bound across library generations, or cooperatively cancel obsolete scans. Include outstanding obsolete work in resource and busy accounting.
Pre-merge checks: Passed 5
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly identifies the main change: albums.list uses counts retained by the sidebar to answer immediately. The stacked PR reference is additional context and does not obscure the change.
Docstring Coverage Passed Docstring coverage is 82.14% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentati…
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 82.14% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 28 functions across 16 files. (4 skipped: 4 unsupported.)

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Warning

Some tools did not complete. Review the errors below.

Clippy (1.99.0)

Clippy execution timed out

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

@eliets2 eliets2 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

First-pass review notes (automated; combined from specialist angles: tests). Please treat as suggestions and verify before acting.

What it does: This PR makes albums.list answer from the smart-album counts already kept by the sidebar instead of counting every smart album on the window thread, avoiding the ~79s freeze on large libraries; smart albums without a current count return countPending: true with their previous count, and headless use counts once on the calling thread and caches the result.

Logical units:

  • App path: albums.list uses Caches::album_counts_for_list / Session::offer_album_counts, counts chosen-photo albums from their list, and marks stale smart albums pending, including the minute-based rule for "last N days" albums.
  • Headless path: crates/engine/src/album_counts.rs counts once, caches AlbumTally, follows small edits with AlbumTally::update, recounts on new library or clock minute, never returns pending, and sets the session clock for "in the last…" rules.
  • Documentation: updates to docs/control-protocol.md, docs/mcp.md, and a What's New entry.

Findings: No usable consolidated finding can be extracted: the only tests input provided is truncated at "`crates", with no complete file, function, or concrete fix stated, so no finding is listed here rather than inventing one.

Overlaps: Stacked on #2020 (lc-album-counts worker), on which its pending and failed-count behavior depends; #768 (folder count from albums inside it) is explicitly not included; CI was run on the stack based on 59a5d00c60, not current main, with #2973's one-file clippy fix applied uncommitted and reverted.

Verdict: Unclear. (1) The tests finding is incomplete and cannot be acted on. (2) The change depends on stacked #2020, so it cannot be judged independently of that base. (3) Pending, failed-count-not-retried, and >1-minute full-count behavior are inherited from #2020 and documented, but no complete specialist finding confirms them.

@vangel76 vangel76 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.

Reviewed 9de93772. I checked the stacked count-reporting change, worker failure handling, and the API state. I found one pending result that never reaches a terminal state. The submitted branch currently conflicts with main.

Source review only. I did not build the project, run tests, or check CI.

None => {
self.album_count_scans += 1;
lightcraft_catalog::tally::AlbumTally::of(cat)
_ => CountsAge::Behind,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2. Report failure instead of leaving count clients polling indefinitely. A failed recount sets album_recount_failed and is not retried for the same library, revision, and minute. albums.list can still return countPending: true through CountsAge::Behind. A client waiting on static rules can keep polling with no way to tell the worker failed. Return a failed or unavailable state, or permit an explicit retry. Extend the worker-failure test to cover the API result.

@wanikhawar

Copy link
Copy Markdown
Contributor

CONFLICTING with main (lib.rs, tests.rs, control.rs and docs); please rebase.

Still open from vangel76's review: after a failed recount, album_counts_for_list keeps answering CountsAge::Behind, so albums.list returns countPending: true for good and a polling client can't tell the worker failed (rule 15). Please return a failed or unavailable state, or allow an explicit retry, and extend the worker-failure test to cover the albums.list result.

Also, in the headless path AlbumCounts::answer sets the global rules clock with rules::set_now as a side effect of listing albums. Please scope or restore it so a list call can't change how other rules evaluate.

This branch has not been deployed

No deployments
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.

4 participants