Repository navigation
Add catalog search provider support and admin controls - #220
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds 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. ChangesCatalog search indexing
Estimated code review effort🎯 5 (Critical) | ⏱️ ~90+ minutes Suggested labels
Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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 winMake 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. WrapUpsertin a transaction and pass that tx toupsert.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 winMake duplicate manga cleanup use an atomic indexed delete.
The duplicate
media_itemsrow 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 winKeep orphaned manga deletes and search events in one transaction.
The
DELETE ... RETURNINGstatement 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
📒 Files selected for processing (30)
cmd/silo/main.godocker-compose.ymlinternal/api/handlers/admin.gointernal/api/handlers/admin_catalog_search.gointernal/api/handlers/admin_settings_checks.gointernal/api/handlers/items.gointernal/api/router.gointernal/catalog/catalog_resolver.gointernal/catalog/encrypted_settings_repo.gointernal/catalog/folder_repo.gointernal/catalog/item_repo.gointernal/catalog/library_repo.gointernal/catalog/search_index_repo.gointernal/catalog/search_indexer.gointernal/catalog/search_meilisearch_client.gointernal/catalog/search_meilisearch_provider.gointernal/catalog/search_provider.gointernal/catalog/search_service.gointernal/config/restart_keys.gointernal/metadata/canonicalize.gointernal/metadata/provider_id_integrity.gointernal/metadata/service.gointernal/scanner/manga_scan.gointernal/taskmanager/tasks/catalog_search_index.gomigrations/sql/20260625193142_catalog_search_index_provider.sqlweb/src/hooks/queries/admin/settings.tsweb/src/hooks/queries/keys.tsweb/src/lib/adminSettingsSearch.tsweb/src/pages/admin-settings/AdminSettingsLayout.tsxweb/src/pages/admin-settings/SearchSettings.tsx
🔎 Code review — catalog search provider (max-effort pass)Automated multi-agent review (Claude Code The feature is well-architected — outbox + advisory locks, Postgres fallback, circuit breaker, schema versioning, opt-in via High severity1. 🟥 A best-effort cleanup now aborts the scan on a transient enqueue error 2. 🟥 Per-item enqueue subquery on the scan hot path (performance-first) 3. 🟦 Outbox poison-pill stalls all catalog-search indexing forever 4. 🟦 Circuit breaker never trips on 5xx / malformed responses — every search eats the full timeout 5. 🟦 The 800 ms search timeout is reused for bulk indexing 6. 🟦 Medium severity7. 🟥 8. 🟦 Non-atomic enqueues drop events on crash → permanently stale index 9. 🟦 10. 🟦 11. 12. 🟦 Admin status shows "Healthy" while 100% of searches fall back; fallback reason is dropped 13. 🟦 Every manga-chapter upsert generates a wasted Meili delete Low severity14. 🟦 15. Setting validation in Lower-severity cleanups (confirmed, not itemized above)
Refuted (checked, not a bug): negative-offset slice panic in 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. |
There was a problem hiding this comment.
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
📒 Files selected for processing (9)
docker-compose.ymlinternal/catalog/folder_repo.gointernal/catalog/library_repo.gointernal/catalog/search_index_repo.gointernal/catalog/search_indexer.gointernal/catalog/search_meilisearch_client.gointernal/catalog/search_meilisearch_provider.gointernal/metadata/canonicalize.gointernal/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
There was a problem hiding this comment.
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
📒 Files selected for processing (4)
docker-compose.ymlinternal/catalog/folder_repo.gointernal/catalog/library_repo.gointernal/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
There was a problem hiding this comment.
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 winSkip 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 onlen(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 winSurface status-query failures instead of showing endless skeletons.
When
useCatalogSearchStatus()errors, this branch still renders the loading state because it only checksstatusLoading || !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 liftRetire the previous active Meilisearch index after a successful rebuild.
Rebuildcreates 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 previousActiveIndexUIDand 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 liftAdd 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 winAvoid re-hardcoding the canonical embedding size in this test.
The production path now sources the dimension from
internal/embeddingvectors/dimensions.go; keeping3072here 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
📒 Files selected for processing (54)
cmd/silo/main.gointernal/api/handlers/admin.gointernal/api/handlers/admin_settings_checks_test.gointernal/api/handlers/catalog.gointernal/api/handlers/events_ws.gointernal/api/handlers/events_ws_test.gointernal/api/handlers/items.gointernal/api/handlers/items_catalog_response_test.gointernal/api/router.gointernal/autoscan/service.gointernal/autoscan/service_test.gointernal/catalog/catalog_resolver.gointernal/catalog/detail.gointernal/catalog/folder_delete_test.gointernal/catalog/folder_repo.gointernal/catalog/item_repo.gointernal/catalog/item_repo_test.gointernal/catalog/orphan_cleanup.gointernal/catalog/orphan_cleanup_test.gointernal/catalog/person_repo.gointernal/catalog/search_index_repo.gointernal/catalog/search_index_repo_test.gointernal/catalog/search_indexer.gointernal/catalog/search_meilisearch_client.gointernal/catalog/search_meilisearch_provider.gointernal/catalog/search_provider.gointernal/catalog/search_provider_test.gointernal/catalog/search_service.gointernal/catalogseed/service.gointernal/catalogseed/service_test.gointernal/config/restart_keys.gointernal/embeddingvectors/dimensions.gointernal/events/scan_registry.gointernal/events/scan_registry_test.gointernal/recommendations/embedding_lock.gointernal/recommendations/repo.gointernal/recommendations/search_query_vector.gointernal/scanner/file_repo.gointernal/scanner/manga_scan.gointernal/scanner/podcast_scan.gointernal/scanner/podcast_test.gointernal/scanqueue/repository.gointernal/scanqueue/service.gomigrations/sql/20260625214538_add_meilisearch_index_tuning_settings.sqlmigrations/sql/20260625222004_add_meilisearch_semantic_search_settings.sqlmigrations/sql/20260625232900_repair_notification_content_seed_state.sqlweb/src/components/GlobalSearch.tsxweb/src/components/SearchBar.tsxweb/src/components/ServerActivity.tsxweb/src/hooks/queries/admin/settings.tsweb/src/lib/adminSettingsSearch.tsweb/src/pages/Catalog.test.tsxweb/src/pages/Catalog.tsxweb/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
There was a problem hiding this comment.
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
📒 Files selected for processing (19)
internal/api/handlers/admin.gointernal/api/handlers/admin_settings_checks_test.gointernal/api/router.gointernal/autoscan/service.gointernal/autoscan/service_test.gointernal/catalog/folder_repo.gointernal/catalog/item_repo.gointernal/catalog/search_index_repo.gointernal/catalog/search_index_repo_test.gointernal/catalog/search_meilisearch_provider.gointernal/catalog/search_provider.gointernal/catalog/search_provider_test.gointernal/catalogseed/service.gointernal/catalogseed/service_test.gointernal/events/scan_registry.gointernal/events/scan_registry_test.goweb/src/components/GlobalSearch.test.tsxweb/src/components/GlobalSearch.tsxweb/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
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]>
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]>
…ider-interface feat(search): add provider interface with initial Meilisearch support
Summary
docker-compose.ymlfor local search testingTesting
Summary by CodeRabbit