Skip to content

Add catalog search provider support and admin controls - #220

Merged
Quick104 merged 21 commits into
mainfrom
codex/search-provider-interface
Jun 26, 2026
Merged

Quick104 merged 21 commits into
mainfrom
codex/search-provider-interface

Conversation

@Quick104

@Quick104 Quick104 commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Add a pluggable catalog search provider with Meilisearch support and PostgreSQL fallback
  • Wire search index synchronization into item, metadata, scanner, and cleanup paths
  • Add admin settings UI, connection checks, and search status reporting for catalog search
  • Include a Meilisearch service in docker-compose.yml for local search testing

Testing

  • Not run (not requested)

Summary by CodeRabbit

  • New Features
    • Added catalog search settings and a live catalog search status endpoint in the admin UI, including sync/rebuild controls.
    • Enabled Meilisearch-backed catalog search indexing with scheduled outbox syncing and full rebuild support (with fallback/circuit breaker).
  • Bug Fixes
    • Strengthened Meilisearch settings normalization/validation (including semantic options) and improved Meilisearch connection-check behavior.
    • Improved catalog indexing event reliability for upserts/deletes/renames using transactional enqueueing; improved search pagination/total handling for interactive browsing.
  • UI/Performance
    • Capped scan-related real-time snapshots and activity display; reduced live-search navigation debounce latency.

@coderabbitai

coderabbitai Bot commented Jun 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds catalog search configuration and status models, Meilisearch-backed search and indexing infrastructure, write-path event enqueueing, admin endpoints for validation/status, task registration, and the admin settings UI.

Changes

Catalog search indexing

Layer / File(s) Summary
Settings and runtime models
internal/catalog/search_provider.go, internal/catalog/search_service.go, internal/catalog/encrypted_settings_repo.go, internal/config/restart_keys.go, migrations/sql/20260625193142_catalog_search_index_provider.sql, migrations/sql/20260625214538_add_meilisearch_index_tuning_settings.sql, migrations/sql/20260625222004_add_meilisearch_semantic_search_settings.sql, migrations/sql/20260625232900_repair_notification_content_seed_state.sql, internal/embeddingvectors/dimensions.go, internal/recommendations/embedding_lock.go, internal/recommendations/search_query_vector.go, internal/catalog/search_provider_test.go
Defines catalog search settings and runtime status models, selects the active search provider, marks the Meilisearch API key as sensitive, adds restart-required keys, seeds default settings and tables in migrations, and centralizes canonical embedding dimensions.
Meilisearch client and provider
internal/catalog/search_meilisearch_client.go, internal/catalog/search_meilisearch_provider.go
Implements the Meilisearch HTTP client, fallback search provider, circuit-breaker state, status reporting, semantic query embedding, and Meilisearch result hydration logic.
Search-index repository and worker
internal/catalog/search_index_repo.go, internal/catalog/search_indexer.go, internal/taskmanager/tasks/catalog_search_index.go, cmd/silo/main.go
Adds the event/state repository, Meilisearch sync/rebuild worker, task types, and startup registration for the catalog search indexing tasks.
Catalog search read-path wiring
internal/catalog/catalog_resolver.go, internal/api/handlers/items.go, internal/api/handlers/catalog.go, internal/catalog/detail.go, internal/scanner/file_repo.go, internal/api/router.go, internal/api/handlers/items_catalog_response_test.go
Wires the catalog search provider into resolver and handler construction, adds overlay-file projection helpers, and updates browse and search result assembly.
Search-index enqueueing on writes
internal/catalog/item_repo.go, internal/catalog/folder_repo.go, internal/catalog/library_repo.go, internal/metadata/..., internal/scanner/manga_scan.go, internal/scanner/podcast_scan.go, internal/catalog/orphan_cleanup.go, internal/catalog/person_repo.go, internal/catalogseed/service.go, internal/recommendations/repo.go
Enqueues search-index upsert, delete, and rename events from catalog writes, metadata renames, skeleton rebinds, scanner cleanup, embedding updates, seed imports, and orphan cleanup paths.
Admin search API
internal/api/handlers/admin.go, internal/api/handlers/admin_catalog_search.go, internal/api/handlers/admin_settings_checks.go, internal/api/router.go, internal/api/handlers/admin_settings_checks_test.go
Adds catalog search setting validation, connection checks, a status endpoint, and router wiring for admin search operations.
Admin and catalog UI
web/src/hooks/queries/..., web/src/lib/adminSettingsSearch.ts, web/src/pages/admin-settings/..., web/src/components/GlobalSearch.tsx, web/src/components/SearchBar.tsx, web/src/components/ServerActivity.tsx, web/src/pages/Catalog.tsx, web/src/pages/Catalog.test.tsx
Adds the admin search settings query hooks, settings navigation entry, layout registration, and search settings page, and updates catalog/global search UI requests and activity display.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~90+ minutes

Suggested labels

v1

Possibly related PRs

  • Silo-Server/silo-server#26: Both PRs modify the catalog browsing item response pipeline in internal/api/handlers/items.go, including overlay summary handling and response assembly.
  • Silo-Server/silo-server#128: Both PRs modify internal/api/handlers/admin.go and HandleUpdateSetting by extending admin settings update behavior.
  • Silo-Server/silo-server#131: Both PRs extend admin routing and settings plumbing in internal/api/router.go, including new admin endpoints and wiring.

Suggested labels

v1

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 4.44% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: adding catalog search provider support along with admin controls.
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 codex/search-provider-interface

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

@coderabbitai coderabbitai Bot added the v1.0 Silo v1 scope - auto-adds to the Silo v1 project label Jun 25, 2026

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 8

Caution

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

⚠️ Outside diff range comments (3)
internal/catalog/item_repo.go (1)

399-400: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make public item upserts enqueue in the same transaction.

Line 400 passes the pool into upsert, so the media item write can commit before Line 542 inserts the outbox event. If enqueueing fails, callers see an error after the item changed and the search index can miss the update. Wrap Upsert in a transaction and pass that tx to upsert.

Suggested fix
 func (r *ItemRepository) Upsert(ctx context.Context, item *models.MediaItem) error {
-	return r.upsert(ctx, r.pool, item)
+	tx, err := r.pool.Begin(ctx)
+	if err != nil {
+		return fmt.Errorf("begin item upsert tx: %w", err)
+	}
+	defer tx.Rollback(ctx) //nolint:errcheck
+
+	if err := r.upsert(ctx, tx, item); err != nil {
+		return err
+	}
+	if err := tx.Commit(ctx); err != nil {
+		return fmt.Errorf("commit item upsert tx: %w", err)
+	}
+	return nil
 }

Also applies to: 542-544

🤖 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 `@internal/catalog/item_repo.go` around lines 399 - 400, The public
ItemRepository.Upsert path is writing the media item through r.pool, which lets
the item commit before the outbox insert in upsert completes. Update Upsert to
open a transaction, pass that tx into r.upsert, and ensure the item write and
outbox enqueue in upsert use the same transaction so both succeed or fail
together. Keep the fix scoped around ItemRepository.Upsert and the outbox
insertion logic in upsert.
internal/scanner/manga_scan.go (2)

392-400: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Make duplicate manga cleanup use an atomic indexed delete.

The duplicate media_items row is deleted before the search delete event is inserted. If Line 399 fails, the duplicate can remain in the search index even though the DB row is gone. Wrap this delete plus enqueue in a transaction, or route it through a repository delete method that already does so.

🤖 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 `@internal/scanner/manga_scan.go` around lines 392 - 400, The duplicate manga
cleanup in mangaScan is not atomic because the DELETE from media_items happens
before catalog.EnqueueSearchIndexDelete, so a failure in the enqueue step can
leave the search index stale. Update the cleanup path in the manga scan flow to
use a single transactional delete-and-enqueue operation, or replace the inline
Exec call with a repository method that already wraps both actions in one
transaction. Keep the logic centered around the mangaScan duplicate-series
cleanup block and the catalog.EnqueueSearchIndexDelete call so the DB row
removal and index deletion succeed or fail together.

178-208: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Keep orphaned manga deletes and search events in one transaction.

The DELETE ... RETURNING statement commits before Lines 205-208 enqueue events. If an enqueue fails, the manga row is already deleted and the external search document can remain stale. Begin a transaction, run the DELETE through it, enqueue with that tx, then commit.

🤖 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 `@internal/scanner/manga_scan.go` around lines 178 - 208, The orphaned manga
cleanup in mangaScan should be made transactional so the delete and search-index
event enqueue succeed or fail together. Update the logic around the DELETE ...
RETURNING flow in scanOrphanedManga to begin a transaction, execute the delete
through that transaction, call catalog.EnqueueSearchIndexDelete with the same tx
handle, and only commit after all enqueue calls succeed; roll back on any error
so deleted rows and search events stay consistent.
🤖 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 `@docker-compose.yml`:
- Around line 38-41: The Meilisearch service is currently configured with
MEILI_MASTER_KEY defaulting to empty, which can publish an unauthenticated
instance when the search profile is enabled. Update the service definition for
the search/Meilisearch entry in docker-compose.yml so it requires a non-empty
MEILI_MASTER_KEY before the container can start or be published, and reference
the existing environment and ports settings for the search service to enforce
this requirement.

In `@internal/catalog/folder_repo.go`:
- Around line 568-573: The orphan cleanup path in the catalog repository is
enqueueing search index deletes for every candidate ID once any row is removed,
even though the DELETE can skip some IDs after re-checking the invariant. Update
the deletion flow in the relevant folder repository method to use DELETE ...
RETURNING content_id and iterate only over the returned IDs when calling
EnqueueSearchIndexDelete, so only actually deleted rows are enqueued. Keep the
delete and enqueue work in the same per-batch transaction in the repository code
path.

In `@internal/catalog/library_repo.go`:
- Around line 520-526: The orphan delete path in LibraryRepo should enqueue
search-index removals only for rows actually deleted, not for every ID in
orphanIDs. Update the DELETE in the catalog cleanup flow to use DELETE RETURNING
mi.content_id, then iterate over that returned set and call
EnqueueSearchIndexDelete only for those IDs before commit. Keep the logic
localized around the existing orphan cleanup in LibraryRepo so the enqueue step
is driven by the DELETE RETURNING result rather than deletedItems > 0.

In `@internal/catalog/search_indexer.go`:
- Around line 89-100: Serialize SyncOutbox and Rebuild by using the same
advisory lock key so they cannot overlap; the current separate lock constants
allow sync to update the old ActiveIndexUID while rebuild switches to a new
index. Update the locking logic in the search indexer paths that acquire the
advisory lock to use one shared maintenance lock symbol, and ensure Rebuild
holds that same lock for its full execution just like SyncOutbox does before
proceeding.

In `@internal/catalog/search_meilisearch_client.go`:
- Around line 174-200: `WaitTask` currently loops on `c.do` without any overall
wait limit, so a task that stays `enqueued` or `processing` can block
indefinitely when the caller’s context has no deadline. Update `WaitTask` to
enforce a total polling deadline or timeout in addition to the per-request
timeout, using the existing `ctx`, `ticker`, and `c.do` flow so the method
returns once the overall wait budget is exceeded.

In `@internal/catalog/search_meilisearch_provider.go`:
- Around line 264-266: The circuit-breaker classification in the search
Meilisearch provider is treating caller cancellations the same as timeouts;
update the logic in the error-handling path that checks errors.Is(err,
context.DeadlineExceeded) and errors.Is(err, context.Canceled) so
context.Canceled is not considered a circuit-opening failure. Keep only genuine
upstream timeout/availability failures opening the circuit, and preserve
caller-cancellation handling as a non-circuit event.

In `@internal/metadata/canonicalize.go`:
- Around line 102-107: The rename flow in canonicalize.go is splitting the
content-id move and the search rename enqueue into separate commits, so a
failure in EnqueueSearchIndexRename can leave state inconsistent. Update the
rename path in the relevant canonicalization function to perform
silo_rename_content_id and the catalog enqueue together within the same
transaction/context, using the existing s.dbPool-based flow so both operations
succeed or fail atomically.

In `@internal/metadata/service.go`:
- Around line 4388-4401: The fallback delete in the media item cleanup path is
not atomic because the `media_items` deletion happens before
`catalog.EnqueueSearchIndexDelete`, so a failure in the enqueue step can leave
the row removed without a corresponding search delete event. Update the
`service.go` delete flow around the `Exec` call and `EnqueueSearchIndexDelete`
so they run in a single transactional unit, using the same `s.dbPool`/`ctx`
path, and only commit once both the delete and outbox enqueue succeed.

---

Outside diff comments:
In `@internal/catalog/item_repo.go`:
- Around line 399-400: The public ItemRepository.Upsert path is writing the
media item through r.pool, which lets the item commit before the outbox insert
in upsert completes. Update Upsert to open a transaction, pass that tx into
r.upsert, and ensure the item write and outbox enqueue in upsert use the same
transaction so both succeed or fail together. Keep the fix scoped around
ItemRepository.Upsert and the outbox insertion logic in upsert.

In `@internal/scanner/manga_scan.go`:
- Around line 392-400: The duplicate manga cleanup in mangaScan is not atomic
because the DELETE from media_items happens before
catalog.EnqueueSearchIndexDelete, so a failure in the enqueue step can leave the
search index stale. Update the cleanup path in the manga scan flow to use a
single transactional delete-and-enqueue operation, or replace the inline Exec
call with a repository method that already wraps both actions in one
transaction. Keep the logic centered around the mangaScan duplicate-series
cleanup block and the catalog.EnqueueSearchIndexDelete call so the DB row
removal and index deletion succeed or fail together.
- Around line 178-208: The orphaned manga cleanup in mangaScan should be made
transactional so the delete and search-index event enqueue succeed or fail
together. Update the logic around the DELETE ... RETURNING flow in
scanOrphanedManga to begin a transaction, execute the delete through that
transaction, call catalog.EnqueueSearchIndexDelete with the same tx handle, and
only commit after all enqueue calls succeed; roll back on any error so deleted
rows and search events stay consistent.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: ad31a503-82c5-49db-85e4-53996792d9f2

📥 Commits

Reviewing files that changed from the base of the PR and between e20f002 and fa9ea0b.

📒 Files selected for processing (30)
  • cmd/silo/main.go
  • docker-compose.yml
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_catalog_search.go
  • internal/api/handlers/admin_settings_checks.go
  • internal/api/handlers/items.go
  • internal/api/router.go
  • internal/catalog/catalog_resolver.go
  • internal/catalog/encrypted_settings_repo.go
  • internal/catalog/folder_repo.go
  • internal/catalog/item_repo.go
  • internal/catalog/library_repo.go
  • internal/catalog/search_index_repo.go
  • internal/catalog/search_indexer.go
  • internal/catalog/search_meilisearch_client.go
  • internal/catalog/search_meilisearch_provider.go
  • internal/catalog/search_provider.go
  • internal/catalog/search_service.go
  • internal/config/restart_keys.go
  • internal/metadata/canonicalize.go
  • internal/metadata/provider_id_integrity.go
  • internal/metadata/service.go
  • internal/scanner/manga_scan.go
  • internal/taskmanager/tasks/catalog_search_index.go
  • migrations/sql/20260625193142_catalog_search_index_provider.sql
  • web/src/hooks/queries/admin/settings.ts
  • web/src/hooks/queries/keys.ts
  • web/src/lib/adminSettingsSearch.ts
  • web/src/pages/admin-settings/AdminSettingsLayout.tsx
  • web/src/pages/admin-settings/SearchSettings.tsx

Comment thread docker-compose.yml Resolved
Comment thread internal/catalog/folder_repo.go Resolved
Comment thread internal/catalog/library_repo.go Resolved
Comment thread internal/catalog/search_indexer.go Resolved
Comment thread internal/metadata/canonicalize.go Resolved
Comment thread internal/metadata/service.go Resolved
@Quick104

Copy link
Copy Markdown
Contributor Author

🔎 Code review — catalog search provider (max-effort pass)

Automated multi-agent review (Claude Code /code-review max) against PR head fa9ea0b3: 10 independent finder angles → per-finding verification → gap sweep. AI-generated — please apply your own judgment. Links point at the reviewed commit.

The feature is well-architected — outbox + advisory locks, Postgres fallback, circuit breaker, schema versioning, opt-in via profiles: [search]. The items below are the sharp edges. Config labels: 🟥 default (postgres) = affects every deployment on merge, even ones that never touch Meilisearch; 🟦 meili-only = only once an admin enables Meilisearch.


High severity

1. 🟥 A best-effort cleanup now aborts the scan on a transient enqueue error
internal/scanner/manga_scan.go#L399 · same shape in internal/metadata/service.go#L4398
The enqueue runs INSERT … SELECT … WHERE EXISTS(server_settings…) on every call — it inserts 0 rows under Postgres but still executes. Pre-change, the duplicate-manga cleanup logged and returned (winner, nil); now a transient DB error (conn reset, serialization failure) on that statement propagates and aborts findOrCreateMangaSeries and the scan — on the default provider.
Fix: keep this path best-effort (log, don't propagate), or gate the enqueue on an in-process "meili active" flag.

2. 🟥 Per-item enqueue subquery on the scan hot path (performance-first)
internal/catalog/item_repo.go#L542 → internal/catalog/search_index_repo.go#L74
upsert() (every scanner's per-item write path) issues an extra INSERT … WHERE EXISTS (SELECT 1 FROM server_settings WHERE key='catalog.search.provider' AND lower(value)='meilisearch') per item. A 300k-item scan = 300k extra round-trips + a server_settings probe each, all inserting nothing when provider=postgres.
Fix: cache the provider flag in-process (refresh on the existing settings-change path); make EnqueueUpsert a no-op when not Meilisearch, and drop the per-row WHERE EXISTS for an unconditional INSERT when it is.

3. 🟦 Outbox poison-pill stalls all catalog-search indexing forever
internal/catalog/search_indexer.go#L140 (and the other MarkFailed paths)
On any per-batch error, MarkFailed(ctx, ids, err) is called on the entire 500-event batch and the function returns without MarkProcessed. There's no max-attempts and no dead-letter; ListPending is ORDER BY id ASC LIMIT 500, so one permanently-rejected document (lowest id, always in the first 500) re-fails the whole batch every drain and starves every later event indefinitely.
Fix: per-event error isolation, an attempts cap that quarantines poison events, and partial-progress MarkProcessed.

4. 🟦 Circuit breaker never trips on 5xx / malformed responses — every search eats the full timeout
internal/catalog/search_meilisearch_provider.go#L271
shouldTripCircuit only trips on deadline/cancel/net.Error/401/403. A reachable-but-broken Meili (503, 429, or a JSON-decode failure) returns false, so the breaker stays closed and every catalog search re-hits Meili and pays up to the 800 ms timeout before falling back to Postgres — sustained latency on a user-facing hot path, exactly what the breaker should prevent.
Fix: trip on 5xx/429 and on decode failures (anything that isn't a clean 4xx query error).

5. 🟦 The 800 ms search timeout is reused for bulk indexing
internal/catalog/search_meilisearch_client.go#L96 (client built in search_indexer.go loadClient)
The indexer builds its client with settings.Timeout (default 800 ms, only clamped >0), and that single http.Client.Timeout applies to every request including AddDocuments of up to 500 documents. A large/slow batch POST exceeds 800 ms → context deadline exceeded → fails the batch, and via #3 the index can never drain or rebuild at the default timeout.
Fix: a separate, generous timeout (or ctx-only) for indexing/WaitTask vs. the user-facing search query timeout.

6. 🟦 folder_repo/library_repo enqueue a delete for every candidate id when the guarded DELETE spared some
internal/catalog/folder_repo.go#L568 · internal/catalog/library_repo.go#L520
The DELETE has a NOT EXISTS re-check (a concurrent scan may have re-attached a content_id to another library — see the comment at folder_repo.go:547). But the enqueue loop fires for all ids/orphanIDs whenever deleted > 0 (a count, not a per-id check), so a still-existing, still-visible item gets removed from the Meili index.
Fix: DELETE … RETURNING content_id and enqueue only the returned ids (the pattern manga_scan now uses).


Medium severity

7. 🟥 Delete & UpdateMetadata wrapped in transactions solely to carry the enqueue
internal/catalog/item_repo.go#L831 · #L1507
Both were single r.pool.Exec calls; now each does Begin/Commit (+ the no-op enqueue) on every call even when Meilisearch is off — 2 extra round-trips each on the default config.
Fix: keep the single-statement path when the cached provider isn't Meilisearch.

8. 🟦 Non-atomic enqueues drop events on crash → permanently stale index
internal/scanner/manga_scan.go#L206 · internal/catalog/folder_repo.go#L570 · internal/metadata/canonicalize.go#L105
Here the mutation commits and the enqueue runs separately on the bare pool — unlike the atomic sites (item_repo.go:874, library_repo.go:522, provider_id_integrity.go, rebindItemToExistingItem). A crash between commit and enqueue loses the delete/rename event forever; no periodic reconcile, only manual rebuild.
Fix: enqueue inside the same transaction as the mutation at every site — the abstraction should own this, not each caller.

9. 🟦 Rebuild never advances last_processed_event_id, so pre-rebuild events replay onto the fresh index
internal/catalog/search_indexer.go#L265
Rebuild snapshots the DB into a new index but doesn't mark pending events processed. The next SyncOutbox replays them — mostly idempotent, except a stale delete event for a content_id recreated/indexed during the rebuild will, on replay, delete the live document.
Fix: advance last_processed_event_id to the max event id captured by the snapshot (and mark those processed) on rebuild completion.

10. 🟦 Rebuild leaks Meilisearch indexes unboundedly
internal/catalog/search_indexer.go#L227
Each rebuild creates <index>_rebuild_<unixts> and flips active_index_uid to it, but the prior index is never dropped (the client has no DeleteIndex). Every manual rebuild leaves a full copy of the catalog behind in Meili.
Fix: delete the previous active index after a successful swap (or sweep *_rebuild_* older than the active one).

11. /items?search= total silently becomes approximate with no total_exact signal
internal/api/handlers/items.go#L257
browseResponse exposes total/has_more but no total_exact. When Meili is active, result.Total is the approximation offset+page+1 (TotalExact:false), so the existing field's meaning changes for clients. /catalog already surfaces total_exact (catalog.go:57); /items doesn't. Per the repo's v1 rule ("never … repurpose … an existing endpoint"), signal it rather than silently changing semantics.
Fix: add total_exact to browseResponse (additive) from result.TotalExact.

12. 🟦 Admin status shows "Healthy" while 100% of searches fall back; fallback reason is dropped
internal/catalog/search_meilisearch_provider.go#L288 + catalog_resolver.go
Status() defaults Healthy:true/closed and only flips when the circuit is open — which (per #4) never happens on 5xx. So the Search Settings panel reads green while every query is silently served by Postgres. Compounding it, fallbackSearch sets result.FallbackReason but the resolver copies only Items/Total/HasMore/TotalExact and discards it — no log, metric, or field for silent degradation.
Fix: derive health from recent call outcomes (not just circuit state), and surface/log FallbackReason.

13. 🟦 Every manga-chapter upsert generates a wasted Meili delete
internal/catalog/search_indexer.go#L147
Chapters are upserted as media_items (→ EnqueueUpsert), but LoadDocumentsByIDs/LoadDocumentsAfter exclude any manga_chapters.chapter_content_id. So each chapter's upsert is "not found" → appended to deleteIDs → a DeleteDocuments task for an id never indexed, every sync.
Fix: skip enqueue for chapter rows (non-indexable by construction).


Low severity

14. 🟦 WaitTask's taskUID == 0 sentinel collides with Meilisearch's first real task
internal/catalog/search_meilisearch_client.go#L175
0 means "no task created," but Meili task UIDs are 0-indexed, so on a fresh instance Rebuild's first CreateIndex returns taskUid 0 and WaitTask(0) returns immediately without waiting. Currently masked by Meili's FIFO task processing, but fragile.
Fix: use -1 (or *int64 / (uid, ok)) for "no task" instead of 0.

15. Setting validation in admin.go duplicates CatalogSearchSettingsFromMap
internal/api/handlers/admin.go#L2143
The inline provider/URL/index/timeout/strategy validation re-encodes rules already in search_provider.go CatalogSearchSettingsFromMap — which the connection-check path already calls (admin_settings_checks.go:131). Two copies will drift.
Fix: validate by building the candidate map and calling CatalogSearchSettingsFromMap.


Lower-severity cleanups (confirmed, not itemized above)
  • Dead code: EnqueueSearchIndexUpsert (search_index_repo.go:90) and ErrSearchProviderFallback (search_provider.go:31) are unused; the four MeilisearchProviderConfig knobs (BatchSize/CandidateScanCap/DeepOffsetLimit/CircuitCooldown) are never set by any caller; the if provider == nil fallback in resolveDirectSearchSource is unreachable.
  • Unused index: idx_catalog_search_index_events_content_id is never queried (write overhead only); the pending index can't serve ORDER BY id past the available_at range predicate.
  • Reuse: compactNonEmptyStrings, the JSON-over-HTTP do(), the advisory-lock helper, and the MarkFailed backoff SQL each duplicate existing patterns (literaryworks / embeddings / scanqueue / movie_match_queue); frontend formatStatusDate duplicates lib/date.
  • Altitude: provider selection is decided per-row in SQL and startup-bound in restart_keys.go (two sources of truth); the manga-exclusion NOT EXISTS SQL and the default-status struct are each duplicated; the task-link triples are hand-written in three places.
  • Minor: WaitTask polls a fixed 100 ms with no backoff; rebuild progress is pinned at 25% for the whole indexing loop.

Refuted (checked, not a bug): negative-offset slice panic in searchMeilisearch — Offset is clamped to >=0 in catalog_parser.go:54.


Suggested priority: the 🟥 default-config items (#1, #2, #7) land on every deployment the moment this merges; #1 + #3 + #4 + #6 are the highest-risk for anyone who enables Meilisearch.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 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 `@internal/catalog/library_repo.go`:
- Around line 526-528: The delete enqueue path in the reconciler is doing one
`EnqueueSearchIndexDelete` call per `deletedContentIDs` item, causing repeated
SQL round trips. Refactor the loop in `library_repo.go` to use a batch enqueue
helper that takes the full `deletedContentIDs` slice and inserts all deletes in
one statement, keeping the existing transaction/error handling around the batch
call.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: dcd7edbe-685b-49e3-952c-9536d10db8ef

📥 Commits

Reviewing files that changed from the base of the PR and between fa9ea0b and a842155.

📒 Files selected for processing (9)
  • docker-compose.yml
  • internal/catalog/folder_repo.go
  • internal/catalog/library_repo.go
  • internal/catalog/search_index_repo.go
  • internal/catalog/search_indexer.go
  • internal/catalog/search_meilisearch_client.go
  • internal/catalog/search_meilisearch_provider.go
  • internal/metadata/canonicalize.go
  • internal/metadata/service.go
🚧 Files skipped from review as they are similar to previous changes (7)
  • docker-compose.yml
  • internal/metadata/service.go
  • internal/catalog/folder_repo.go
  • internal/catalog/search_meilisearch_provider.go
  • internal/catalog/search_meilisearch_client.go
  • internal/catalog/search_index_repo.go
  • internal/catalog/search_indexer.go

Comment thread internal/catalog/library_repo.go Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 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 `@internal/catalog/search_index_repo.go`:
- Around line 68-80: The best-effort INSERT in EnqueueDeletes can leave a
transaction aborted when execer is a transaction and
isSearchIndexSchemaUnavailable(err) suppresses a 42P01 error. Update the
EnqueueDeletes path in search_index_repo.go to recover transactional state
before swallowing missing-schema errors, either by running the INSERT under a
savepoint when execer supports transactions or by only suppressing 42P01 for
non-transaction execers. Make sure FolderRepository.DeleteWithStats can still
commit successfully after calling EnqueueDeletes.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b4af699f-6e98-4abe-8841-04cf27e23acc

📥 Commits

Reviewing files that changed from the base of the PR and between a842155 and 9eb9104.

📒 Files selected for processing (4)
  • docker-compose.yml
  • internal/catalog/folder_repo.go
  • internal/catalog/library_repo.go
  • internal/catalog/search_index_repo.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • docker-compose.yml
  • internal/catalog/library_repo.go

Comment thread internal/catalog/search_index_repo.go Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 12

Caution

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

⚠️ Outside diff range comments (4)
internal/scanner/podcast_scan.go (1)

59-83: 🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

Skip destructive reconciliation after partial scan failures.

Line 82 still reconciles missing files after sibling/root failures. Paths from failed shows are absent from seenPaths, so Lines 253-269 can mark/delete their existing files as missing when any other show succeeded. Gate reconciliation on len(failures) == 0, or restrict it to successfully parsed show subtrees.

Proposed guard
-	if err := s.reconcilePodcastMissingFiles(ctx, folder, reconcileRoots, seenPaths, len(seenPaths) > 0); err != nil {
-		slog.Warn("podcast scan: missing-file reconcile failed", "folder_id", folder.ID, "error", err)
+	if len(failures) == 0 {
+		if err := s.reconcilePodcastMissingFiles(ctx, folder, reconcileRoots, seenPaths, len(seenPaths) > 0); err != nil {
+			slog.Warn("podcast scan: missing-file reconcile failed", "folder_id", folder.ID, "error", err)
+		}
+	} else {
+		slog.Warn("podcast scan: skipping missing-file reconcile after partial failures",
+			"folder_id", folder.ID,
+			"failures", len(failures),
+		)
 	}

Also applies to: 253-269

🤖 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 `@internal/scanner/podcast_scan.go` around lines 59 - 83, The podcast scan
currently continues into missing-file reconciliation even after some sibling
shows fail, which can cause files from failed shows to be treated as missing.
Update the reconciliation flow in podcast_scan.go around reconcilePodcastShow
and reconcilePodcastMissingFiles so the destructive missing-file pass is skipped
whenever failures were recorded, or otherwise limited to only successfully
scanned subtrees. Use the existing symbols s.reconcilePodcastShow, failures,
seenPaths, and s.reconcilePodcastMissingFiles to apply the guard consistently.
web/src/pages/admin-settings/SearchSettings.tsx (1)

36-37: 🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Surface status-query failures instead of showing endless skeletons.

When useCatalogSearchStatus() errors, this branch still renders the loading state because it only checks statusLoading || !status. That makes the new admin status panel look stuck instead of telling the user the fetch failed.

Suggested fix
-  const { data: status, isLoading: statusLoading } = useCatalogSearchStatus();
+  const {
+    data: status,
+    isLoading: statusLoading,
+    error: statusError,
+  } = useCatalogSearchStatus();
...
-          {statusLoading || !status ? (
+          {statusLoading ? (
             <div className="space-y-3 py-3">
               <Skeleton className="h-5 w-56" />
               <Skeleton className="h-5 w-72" />
               <Skeleton className="h-5 w-48" />
             </div>
+          ) : statusError ? (
+            <div className="py-3 text-sm text-destructive" role="alert">
+              Failed to load catalog search status.
+            </div>
           ) : (
             <div className="divide-border divide-y">

Also applies to: 202-209

🤖 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 `@web/src/pages/admin-settings/SearchSettings.tsx` around lines 36 - 37, The
admin search status panel is treating failed `useCatalogSearchStatus()` requests
as loading because `SearchSettings` only branches on `statusLoading || !status`,
so it never surfaces an error state. Update the render logic around
`useCatalogSearchStatus` and the status-panel branch in `SearchSettings` to
explicitly check for query failure and show an error/failed state instead of the
skeleton. Use the existing status-related symbols (`status`, `statusLoading`,
and the new admin status panel branch) to route errors to a visible message or
fallback, while keeping the loading skeleton only for the actual loading case.
internal/catalog/search_indexer.go (2)

246-306: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Retire the previous active Meilisearch index after a successful rebuild.

Rebuild creates a new timestamped index and swaps state to it, but the old active index is never deleted. Repeated rebuilds will accumulate duplicate document/vector storage; capture the previous ActiveIndexUID and delete it after the state update succeeds.

🤖 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 `@internal/catalog/search_indexer.go` around lines 246 - 306, Capture the
current active index UID before assigning the new rebuild UID in Rebuild, then
after i.events.UpdateStateAfterRebuild succeeds, delete the previous Meilisearch
index if it exists. Use the existing ActiveIndexUID and buildIndexUID values to
ensure the old index is retired only after the new state is committed, and keep
the cleanup tied to the same success path as the rebuild flow.

127-155: 🩺 Stability & Availability | 🟠 Major | 🏗️ Heavy lift

Add a dead-letter or attempt ceiling for poison events.

A permanent failure in one pending event causes the whole fetched batch to be marked failed and retried later, so later events can stall indefinitely behind it. After a bounded number of attempts, quarantine the bad event or mark it terminally skipped so the outbox can keep progressing.

🤖 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 `@internal/catalog/search_indexer.go` around lines 127 - 155, The batch
handling in search_indexer.go can be blocked by a single poison event because
SearchIndexTask.Run marks the entire fetched set failed and retries it forever.
Update the flow around ListPending, MarkFailed, and LoadDocumentsByIDs to track
per-event attempts and stop retrying a bad event after a bounded ceiling, either
by moving it to a dead-letter/quarantine state or marking it terminally skipped.
Keep the rest of the pending events progressing so one permanent failure does
not stall later events.
🧹 Nitpick comments (1)
internal/catalog/search_provider_test.go (1)

176-177: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Avoid re-hardcoding the canonical embedding size in this test.

The production path now sources the dimension from internal/embeddingvectors/dimensions.go; keeping 3072 here reintroduces the split contract this PR is removing.

Proposed change
 import (
 	"context"
 	"encoding/json"
 	"errors"
 	"reflect"
 	"strings"
 	"testing"
+
+	"github.com/Silo-Server/silo-server/internal/embeddingvectors"
 )
-	if len(req.Vector) != 3072 {
-		t.Fatalf("vector len = %d, want 3072", len(req.Vector))
+	if len(req.Vector) != embeddingvectors.CanonicalDimensions {
+		t.Fatalf("vector len = %d, want %d", len(req.Vector), embeddingvectors.CanonicalDimensions)
 	}
🤖 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 `@internal/catalog/search_provider_test.go` around lines 176 - 177, The test in
search_provider_test.go is still hardcoding the embedding size, which recreates
the split contract. Update the vector length assertion in the req.Vector check
to use the canonical dimension source from
internal/embeddingvectors/dimensions.go instead of the literal value, so the
test stays aligned with the production embedding dimension.
🤖 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 `@internal/api/handlers/admin.go`:
- Around line 2217-2223: The semantic_ratio validation in the admin settings
handler still allows NaN because strconv.ParseFloat accepts it and the current
range check in the catalog.SearchSettingMeilisearchSemanticRatio branch does not
catch it. Update the validation in admin.go to explicitly reject NaN before
formatting and storing req.Value, using the existing ParseFloat/range check path
and the writeError response for invalid input.

In `@internal/api/handlers/events_ws.go`:
- Around line 419-435: The realtime scan snapshot in events_ws.go is now capped
but still serialized as a plain []evt.ScanRun, so consumers cannot tell it was
truncated. Update the snapshot contract around the existing runs assembly and
marshalJSON call to include an overflow/total indicator from the active scan
sources, or adjust the ServerActivity.tsx consumer to treat the count as a lower
bound instead of an exact total. Use the existing
h.persistedScans.ListActiveSnapshot and h.scans.ListActiveLimit flow to locate
where the truncation metadata should be added.

In `@internal/autoscan/service.go`:
- Around line 204-213: The autoscan batching logic in `service.go` still exceeds
the configured cap after `collapseTargetsToLibraryScans` deduplicates targets,
so the limit is not actually enforced. Update the `targets` processing in the
autoscan poll path to reapply `maxAutoscanTargetsPerPoll` after collapsing,
either by chunking the overflow into multiple polls or by deferring marker
advancement until the remaining work is drained; make the same fix in the
related poll path referenced by the same batch handling so
`collapseTargetsToLibraryScans`, `maxAutoscanTargetsPerPoll`, and the marker
update stay consistent.

In `@internal/catalog/folder_repo.go`:
- Around line 746-750: The orphan cleanup in folder_repo.go is building
imageDirs from orphanIDs before the guarded DELETE re-check, so non-deleted rows
can still be included. Update the provisional ID deletion flow around
deleteOrphanedProvisionalIDsByContentIDSQL and the related orphan cleanup path
to derive image paths/dirs only from rows actually returned by DELETE ...
RETURNING, or from attemptDeletedIDs after the delete succeeds. Ensure
downstream cleanup only uses the confirmed deleted IDs from the delete attempt.

In `@internal/catalog/item_repo.go`:
- Around line 406-407: The upsert flow in itemRepo.upsert now mixes the
media-item write with the search-index enqueue, so outbox insert failures can
still abort PostgreSQL fallback installs. Update the enqueue path in r.upsert
(and the repository wiring around it) to skip the Meilisearch outbox work when
the fallback provider is active, or otherwise treat enqueue errors as non-fatal
only for the fallback provider. Keep the main item upsert behavior unchanged and
use the existing provider check/selection logic near itemRepo and r.upsert to
gate the enqueue.
- Around line 1208-1212: The search ordering in item_repo.go now ignores
phrase_rank even though it is still computed and bound in the CTE, so update the
query in the item repository ranking flow to either reintroduce phrase_rank into
the ORDER BY in the main SELECT or remove the unused phrase-rank calculation
entirely. Use the relevant SQL assembly in the item repository method that
builds dataSQL, along with the CTEs that produce the ranking columns, to keep
the ranking logic and the computed fields consistent.

In `@internal/catalog/orphan_cleanup.go`:
- Around line 220-222: The orphan cleanup flow in Cleanup should not fail when
search indexing is disabled or unavailable; the unconditional
EnqueueSearchIndexDeletes call is causing the transaction to abort. Update the
logic around the existing enqueue path in orphan_cleanup.go to gate it by the
active search provider (or otherwise isolate the error) so optional Meilisearch
outbox writes do not block orphan deletion; use the existing Cleanup and
EnqueueSearchIndexDeletes symbols to locate the fix.

In `@internal/catalog/search_index_repo.go`:
- Around line 64-70: The INSERT in createSearchIndexEvents is swallowing
isSearchIndexSchemaUnavailable(err) without clearing the aborted state when
execer is a transaction. Update this path so transactional execers run the
best-effort insert under a savepoint and roll back to it on 42P01, or otherwise
only suppress the missing-schema error for non-transactional execers; use the
execer path around execer.Exec in search_index_repo.go to distinguish the
behavior.

In `@internal/catalog/search_meilisearch_provider.go`:
- Around line 329-333: The `MeilisearchSearchProvider.shouldUseSemanticSearch`
guard is incorrectly disabling semantic search whenever
`CatalogSearchRequest.SkipTotal` is true, which blocks hybrid search in the main
interactive search paths. Remove the `req.SkipTotal` check from this decision
unless there is a specific Meilisearch limitation that must still be guarded.
Keep the existing `p == nil` and `p.config.SemanticEnabled` checks, and preserve
the query-length threshold based on `normalizeCatalogSearchQueryForVector` and
`strings.Fields`.

In `@internal/catalogseed/service.go`:
- Around line 392-394: Move the search-index enqueue in the non-empty import
flow so it runs after the file and library link imports, not before them, in the
catalog seed transaction. Update the ID collection used by
Catalog.EnqueueSearchIndexUpserts and catalogSeedSearchUpsertIDs to include the
content IDs affected by media_files and media_item_libraries changes, then
enqueue once at the end so skipped items with newly imported child/link data are
indexed.

In `@internal/events/scan_registry.go`:
- Around line 68-78: ListActiveLimit in ScanRegistry is applying the limit
during map iteration, which yields an arbitrary subset because r.entries is a
map. Update the method to first collect all active ScanRun values
(accepted/running), then sort them by a stable field already present on ScanRun,
and only after sorting apply the limit slice. Keep the change localized to
ScanRegistry.ListActiveLimit so the returned snapshot is deterministic.

In `@web/src/components/GlobalSearch.tsx`:
- Around line 159-163: The preview query in GlobalSearch is opting out of exact
totals with include_total=false, but the UI still uses previewQuery.data.total
as if it were exact. Update the GlobalSearch preview rendering logic to avoid
showing an exact “Showing top X of Y” count in preview mode, or clearly mark the
count as approximate when using fetchCatalogPage with PREVIEW_LIMIT and
include_total=false. Use the existing previewQuery and searchState flow to
locate and adjust the copy.

---

Outside diff comments:
In `@internal/catalog/search_indexer.go`:
- Around line 246-306: Capture the current active index UID before assigning the
new rebuild UID in Rebuild, then after i.events.UpdateStateAfterRebuild
succeeds, delete the previous Meilisearch index if it exists. Use the existing
ActiveIndexUID and buildIndexUID values to ensure the old index is retired only
after the new state is committed, and keep the cleanup tied to the same success
path as the rebuild flow.
- Around line 127-155: The batch handling in search_indexer.go can be blocked by
a single poison event because SearchIndexTask.Run marks the entire fetched set
failed and retries it forever. Update the flow around ListPending, MarkFailed,
and LoadDocumentsByIDs to track per-event attempts and stop retrying a bad event
after a bounded ceiling, either by moving it to a dead-letter/quarantine state
or marking it terminally skipped. Keep the rest of the pending events
progressing so one permanent failure does not stall later events.

In `@internal/scanner/podcast_scan.go`:
- Around line 59-83: The podcast scan currently continues into missing-file
reconciliation even after some sibling shows fail, which can cause files from
failed shows to be treated as missing. Update the reconciliation flow in
podcast_scan.go around reconcilePodcastShow and reconcilePodcastMissingFiles so
the destructive missing-file pass is skipped whenever failures were recorded, or
otherwise limited to only successfully scanned subtrees. Use the existing
symbols s.reconcilePodcastShow, failures, seenPaths, and
s.reconcilePodcastMissingFiles to apply the guard consistently.

In `@web/src/pages/admin-settings/SearchSettings.tsx`:
- Around line 36-37: The admin search status panel is treating failed
`useCatalogSearchStatus()` requests as loading because `SearchSettings` only
branches on `statusLoading || !status`, so it never surfaces an error state.
Update the render logic around `useCatalogSearchStatus` and the status-panel
branch in `SearchSettings` to explicitly check for query failure and show an
error/failed state instead of the skeleton. Use the existing status-related
symbols (`status`, `statusLoading`, and the new admin status panel branch) to
route errors to a visible message or fallback, while keeping the loading
skeleton only for the actual loading case.

---

Nitpick comments:
In `@internal/catalog/search_provider_test.go`:
- Around line 176-177: The test in search_provider_test.go is still hardcoding
the embedding size, which recreates the split contract. Update the vector length
assertion in the req.Vector check to use the canonical dimension source from
internal/embeddingvectors/dimensions.go instead of the literal value, so the
test stays aligned with the production embedding dimension.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 879f4e38-126a-4745-8b4b-0e37fa3bec4c

📥 Commits

Reviewing files that changed from the base of the PR and between 9eb9104 and d68e83c.

📒 Files selected for processing (54)
  • cmd/silo/main.go
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_settings_checks_test.go
  • internal/api/handlers/catalog.go
  • internal/api/handlers/events_ws.go
  • internal/api/handlers/events_ws_test.go
  • internal/api/handlers/items.go
  • internal/api/handlers/items_catalog_response_test.go
  • internal/api/router.go
  • internal/autoscan/service.go
  • internal/autoscan/service_test.go
  • internal/catalog/catalog_resolver.go
  • internal/catalog/detail.go
  • internal/catalog/folder_delete_test.go
  • internal/catalog/folder_repo.go
  • internal/catalog/item_repo.go
  • internal/catalog/item_repo_test.go
  • internal/catalog/orphan_cleanup.go
  • internal/catalog/orphan_cleanup_test.go
  • internal/catalog/person_repo.go
  • internal/catalog/search_index_repo.go
  • internal/catalog/search_index_repo_test.go
  • internal/catalog/search_indexer.go
  • internal/catalog/search_meilisearch_client.go
  • internal/catalog/search_meilisearch_provider.go
  • internal/catalog/search_provider.go
  • internal/catalog/search_provider_test.go
  • internal/catalog/search_service.go
  • internal/catalogseed/service.go
  • internal/catalogseed/service_test.go
  • internal/config/restart_keys.go
  • internal/embeddingvectors/dimensions.go
  • internal/events/scan_registry.go
  • internal/events/scan_registry_test.go
  • internal/recommendations/embedding_lock.go
  • internal/recommendations/repo.go
  • internal/recommendations/search_query_vector.go
  • internal/scanner/file_repo.go
  • internal/scanner/manga_scan.go
  • internal/scanner/podcast_scan.go
  • internal/scanner/podcast_test.go
  • internal/scanqueue/repository.go
  • internal/scanqueue/service.go
  • migrations/sql/20260625214538_add_meilisearch_index_tuning_settings.sql
  • migrations/sql/20260625222004_add_meilisearch_semantic_search_settings.sql
  • migrations/sql/20260625232900_repair_notification_content_seed_state.sql
  • web/src/components/GlobalSearch.tsx
  • web/src/components/SearchBar.tsx
  • web/src/components/ServerActivity.tsx
  • web/src/hooks/queries/admin/settings.ts
  • web/src/lib/adminSettingsSearch.ts
  • web/src/pages/Catalog.test.tsx
  • web/src/pages/Catalog.tsx
  • web/src/pages/admin-settings/SearchSettings.tsx
✅ Files skipped from review due to trivial changes (6)
  • migrations/sql/20260625222004_add_meilisearch_semantic_search_settings.sql
  • migrations/sql/20260625214538_add_meilisearch_index_tuning_settings.sql
  • internal/events/scan_registry_test.go
  • migrations/sql/20260625232900_repair_notification_content_seed_state.sql
  • internal/embeddingvectors/dimensions.go
  • internal/autoscan/service_test.go
🚧 Files skipped from review as they are similar to previous changes (8)
  • internal/config/restart_keys.go
  • web/src/lib/adminSettingsSearch.ts
  • cmd/silo/main.go
  • web/src/hooks/queries/admin/settings.ts
  • internal/api/router.go
  • internal/scanner/manga_scan.go
  • internal/catalog/catalog_resolver.go
  • internal/catalog/search_meilisearch_client.go

Comment thread internal/api/handlers/admin.go Resolved
Comment thread internal/api/handlers/events_ws.go Resolved
Comment thread internal/autoscan/service.go Resolved
Comment thread internal/catalog/folder_repo.go Resolved
Comment thread internal/catalog/item_repo.go Resolved
Comment thread internal/catalog/search_index_repo.go Resolved
Comment thread internal/catalogseed/service.go Resolved
Comment thread internal/events/scan_registry.go Resolved
Comment thread web/src/components/GlobalSearch.tsx Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 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 `@internal/catalog/search_index_repo.go`:
- Around line 150-183: The provider availability check in
searchIndexProviderEnabled and searchIndexProviderEnabledTx is still fatal when
activeProviderKnown is false, because the EnqueueSearchIndex* paths can hit
querySearchIndexProviderEnabled and return transient server_settings read errors
to callers. Make the check best-effort by handling non-schema lookup failures
locally in these helpers, either by logging and treating the provider as
unavailable so enqueue is skipped, or by ensuring the repo is constructed with a
cached provider via WithActiveProvider to avoid the query path.
🪄 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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a4742f41-ca9f-47ef-b954-807f93ec826d

📥 Commits

Reviewing files that changed from the base of the PR and between d68e83c and f89c112.

📒 Files selected for processing (19)
  • internal/api/handlers/admin.go
  • internal/api/handlers/admin_settings_checks_test.go
  • internal/api/router.go
  • internal/autoscan/service.go
  • internal/autoscan/service_test.go
  • internal/catalog/folder_repo.go
  • internal/catalog/item_repo.go
  • internal/catalog/search_index_repo.go
  • internal/catalog/search_index_repo_test.go
  • internal/catalog/search_meilisearch_provider.go
  • internal/catalog/search_provider.go
  • internal/catalog/search_provider_test.go
  • internal/catalogseed/service.go
  • internal/catalogseed/service_test.go
  • internal/events/scan_registry.go
  • internal/events/scan_registry_test.go
  • web/src/components/GlobalSearch.test.tsx
  • web/src/components/GlobalSearch.tsx
  • web/src/components/ServerActivity.tsx
🚧 Files skipped from review as they are similar to previous changes (10)
  • internal/api/handlers/admin_settings_checks_test.go
  • internal/events/scan_registry.go
  • internal/catalog/folder_repo.go
  • web/src/components/ServerActivity.tsx
  • internal/api/router.go
  • internal/catalog/search_provider_test.go
  • internal/api/handlers/admin.go
  • internal/catalog/search_provider.go
  • internal/catalog/item_repo.go
  • internal/catalog/search_meilisearch_provider.go

Comment thread internal/catalog/search_index_repo.go Resolved
Quick104 and others added 13 commits June 25, 2026 22:43
Establish how semantic vector "coverage" is counted: current-model
embeddings over embed-eligible items, per media type, from Postgres.

- Move the embed-eligibility predicate to a single source of truth in
  embeddingvectors.ItemEligibilityWhereClause; recommendations now
  delegates to it (output byte-identical).
- Add catalogSemanticCoverageByType (per-type eligible/vectorized) and
  define the coverageQuerier interface in catalog. Both numerator and
  denominator apply the eligibility predicate, so vectorized never
  exceeds eligible (C1 guarantee) even with a stale embedding on a
  now-unmatched item.
- countCatalogSearchVectorDocuments now takes a coverageQuerier and a
  model, applies the eligibility + model filter, and is the per-type
  numerator summed across types. Update all four callers (pass "").
- Add idx_media_item_embeddings_model (CONCURRENTLY, self-healing
  guard) so the model filter does not scan the embeddings table.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add recommendations.Engine.ActiveEmbeddingModel, which reads the
embedding lock from server_settings and returns the locked model (or ""
when no lock is established). Define the catalog
CatalogSemanticModelProvider interface so a later task can scope vector
coverage checks to the active model; the recommendations Engine already
satisfies it. No wiring yet (Task 4 injects recEngine as this provider).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add the in-memory coverage gate the search hot path will consult to
decide whether semantic results may be served for a set of item types.

The tracker reads an atomic.Pointer snapshot with no DB and no lock on
the read path, refreshes single-flight under a mutex on a 2-minute
ticker, and applies per-type hysteresis (enable 0.90 / disable 0.80,
holding the previous latch inside the band) to avoid flapping. It
collapses to not-ready when the active embedding model changes so a
stale latch cannot leak across models, and fails safe: a not-yet-
computed snapshot reports not-ready (never panics), and a model-lookup
or count-query error retains the last-good snapshot instead of
publishing zeros.

Refresh counts through the existing catalogSemanticCoverageByType via an
injectable fetch seam, so the behavior is unit-testable with canned
counts and a fake model provider (no pgx.Rows faking). Reuses the
Task-1 coverageQuerier and extends catalogTypeCoverage with Ratio/Ready,
filled by the pure computeCoverageSnapshot helper. Adds the
SemanticCoverageGate interface beside the other provider interfaces;
Task 4 wires the gate and starts the refresher.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Wire the semantic-coverage building blocks together so the Meilisearch
provider only goes hybrid once the active embedding model covers enough of
the requested item types.

- Add Coverage SemanticCoverageGate to MeilisearchProviderConfig and consult
  it in buildMeilisearchSearchRequest after the wordcount check; when
  not-ready, record "semantic_not_ready: <reason>" as a diagnostic fallback
  and stay keyword-only (shouldUseSemanticSearch's bool contract unchanged).
- Build and own a semanticCoverageTracker in
  NewCatalogSearchServiceFromSettings, but only when semantic is enabled and
  a real pool is present. Derive the model provider via a panic-safe comma-ok
  helper (semanticModelProvider) so a nil or non-implementing vectorizer
  degrades to a not-ready gate instead of asserting a nil interface.
- Add StartCoverageRefresh and call it from NewRouter on deps.AppContext so
  the refresher runs for the process lifetime.

Coverage == nil preserves today's behavior exactly; existing hybrid and
SkipTotal tests stay green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add per-query search observability to /api/v1/catalog. The internal
CatalogSearchResult now carries Mode + SemanticUsed alongside the existing
Provider + FallbackReason; all four are plumbed through CatalogResult (which
previously dropped them in resolveDirectSearchSource) and exposed as an
additive, omitempty search_diagnostics object on the catalog response.

Two correctness points:
- For Meilisearch, Mode/SemanticUsed are derived from the POST-downgrade
  request (baseSearchReq.Hybrid != nil) at the end of searchMeilisearch, so a
  hybrid->keyword self-downgrade reports mode="keyword", semantic_used=false.
- search_diagnostics is emitted iff a provider search actually ran
  (result.Provider != ""), which naturally omits browse, preview,
  non-relevance-sort q=, and group=work paths (none set Provider).

API additive-only: existing response fields keep declaration order and stay
byte-stable; only the new omitempty field is added.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Add a rate-limited Meilisearch embedder capability check and surface a
semantic-coverage block in the admin search status.

Capability validation confirms the active index declares the configured
embedder with source="userProvided" and dimensions matching the canonical
embedding dimension, then runs a unit-vector hybrid probe to confirm the
index accepts the request shape. The whole path (GetSettings + evaluate +
probe) is cached for 5m and NEVER trips the circuit, marks a fallback, or
modifies unhealthyUntil, so a misconfigured embedder cannot take keyword
search down. The pure evaluator (evaluateEmbedderSettings) is unit-tested
across missing/wrong-source/wrong-dimensions/ok with distinct reasons.

The admin status gains a Semantic block read entirely from the in-memory
coverage snapshot (Snapshot + CoverageReady) with no new DB query in
Status(); document_count/vector_document_count are unchanged (additive
only). buildSemanticStatus is pure and unit-tested (nil snapshot and a
populated, deterministically-sorted snapshot).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…tale passes

EmbedAll previously ran the full text-staleness CTE on every page, paying
five item_people LATERAL joins per eligible row just to detect whether an
item's canonical text had drifted - even when the real work was embedding
brand-new (missing) items during active backfill.

Restructure EmbedAll into two passes:

- Pass 1 (cheap): drain missing/model-stale items via the repurposed
  ItemsNeedingEmbedding query (single LEFT JOIN, no LATERAL), paged by a
  content_id cursor so a failed/skipped item is retried next run instead of
  stalling the page.
- Pass 2 (expensive): only once Pass 1 fully drains, run one bounded
  ListEmbeddingTextCandidates scan (LIMIT embeddingTextStaleQuotaPerRun=200)
  to re-embed text-drifted items. Re-embedding refreshes canonical_text, so
  handled rows drop out next run - no Pass 2 cursor needed.

Coverage-first tradeoff (documented in EmbedAll): under steady state Pass 1
drains every run so text-stale items stay fresh; only under pathological
continuous heavy ingest does Pass 2 get skipped, deliberately prioritizing
covering new items over re-embedding changed ones.

Supporting changes:
- ItemsNeedingEmbedding gains an afterID cursor + ORDER BY; SQL extracted to
  buildItemsNeedingEmbeddingSQL for a cheap-shape unit test (no item_people /
  LATERAL).
- Add an `embedder` interface seam (Engine.embClient) so EmbedAll is testable
  with a fake; *embeddings.Client still satisfies it.
- Extract embedBatch to DRY both passes, preserving quota/billing early-return,
  single-item fallback, ensureEmbeddingLock-before-upsert, and skip-on-store-error.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…h admin

Render the new `semantic` block from the admin catalog-search status
endpoint in the Search Settings page: semantic readiness (with
disabled reason), overall vector coverage %, coverage-updated
timestamp, embedder capability, and a compact per-type coverage list.
Reuses the existing StatusRow/FieldGroup/Badge patterns and adds a
formatPercent helper; keeps the existing Vectorized Documents row.

The TS `semantic?` field is optional and the whole block is guarded so
a new frontend talking to an older backend during rollout degrades
gracefully.

Part of the hybrid-semantic-search hardening work (Task 8).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
… reconcile

Completes the search-provider-interface wiring that the catalog hardening
commits already call into:

- Skip the transactional search-index-event write path when Meilisearch is
  not the active provider (ItemRepository.WithActiveSearchProvider /
  SearchIndexEventRepository.disabledByActiveProvider).
- Dead-letter catalog_search_index_events after 10 attempts instead of
  retrying forever.
- Track the rebuild high-water mark (MaxEventID / MarkProcessedThrough) and
  persist last_processed_event_id in UpdateStateAfterRebuild so a rebuild
  reconciles events enqueued during the rebuild.
- Validate (read-only) the embedding lock when embedding a search query
  instead of establishing/mutating it.
- Surface total_exact on the legacy /items browse response.
- Wire the active catalog search provider into the scanner and item repo at
  startup.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Extract listPodcastShowAudioFiles and record each show's audio paths in
seenPaths during ScanPodcastFolder so reconciliation does not treat
still-present episodes as removed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
catalogSearchMeilisearchSchemaVersion hashed the embedder, canonical dimensions, and index types but not SemanticEnabled. Because attachDocumentVectors omits _vectors when semantic is off, toggling semantic on without a full rebuild left previously indexed (and incrementally synced) documents without vectors while the Postgres coverage gate still reported the type "ready" — silently degrading hybrid ranking until a manual rebuild.

Folding SemanticEnabled into the schema version makes a toggle diverge from the stored version, so the provider falls back to keyword, sync skips, the admin status surfaces the schema mismatch, and a rebuild is required to restore hybrid — consistent with how embedder and index-type changes already behave.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@Quick104
Quick104 merged commit 5319a07 into main Jun 26, 2026
1 check passed
@Quick104
Quick104 deleted the codex/search-provider-interface branch June 26, 2026 13:32
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
…ider-interface

feat(search): add provider interface with initial Meilisearch support
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

v1.0 Silo v1 scope - auto-adds to the Silo v1 project

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant