Repository navigation
fix(catalog): harden Meilisearch search integration - #291
Conversation
Findings from a full review of the Meilisearch implementation: - Give the indexer its own 2m HTTP timeout instead of reusing the 800ms search-path timeout_ms, so large document uploads to a non-loopback Meilisearch stop timing out. - Delete superseded indexes after a rebuild (previous active + leftover <prefix>_rebuild_* partials); every rebuild previously leaked a full copy of the catalog on the Meilisearch instance. - Cache the index state row + pending count for 3s on the search hot path (was two Postgres round trips per search request); a failed search invalidates the cache immediately. - Swap the active-index pointer before marking outbox events processed so a crash between the two replays events instead of losing them. - End pagination only on a short page; estimatedTotalHits is an estimate and could truncate results. - Latch the startup-resolved provider process-wide so package-level enqueue helpers stop querying server_settings in write transactions. - Surface dead-lettered outbox events in the admin status + web UI. - Remove unwired provider config knobs, dedupe the manga-chapter exclusion predicate, split the vector cache onto its own mutex, real rebuild progress percentages, and expand client/coalesce test coverage. Co-Authored-By: Claude Fable 5 <[email protected]>
📝 WalkthroughWalkthroughAdds a process-wide latch for the active catalog search provider, dead-lettered event counting surfaced through repository/service/status/UI layers, Meilisearch client index management (delete/list), rebuild progress tracking with superseded-index cleanup, and simplified fixed-constant tuning with index-state caching in the Meilisearch search provider. ChangesMeilisearch search index provider latching, rebuild cleanup, and dead-letter tracking
Estimated code review effort: 4 (Complex) | ~60 minutes Sequence Diagram(s)sequenceDiagram
participant Rebuild
participant State
participant MeilisearchClient
Rebuild->>State: UpdateStateAfterRebuild(newIndex)
Rebuild->>State: MarkProcessedThrough(events)
Rebuild->>Rebuild: staleCatalogSearchIndexUIDs()
Rebuild->>MeilisearchClient: DeleteIndex(staleUID) for each stale
MeilisearchClient-->>Rebuild: RemovedIndexes count
sequenceDiagram
participant Search
participant IndexStateCache
participant MeilisearchStore
Search->>IndexStateCache: indexState(ctx)
alt cache valid (TTL)
IndexStateCache-->>Search: cached state, pending
else expired
IndexStateCache->>MeilisearchStore: GetState + PendingCount
MeilisearchStore-->>IndexStateCache: state, pending
IndexStateCache-->>Search: state, pending
end
Search->>Search: searchMeilisearch()
alt search fails
Search->>IndexStateCache: invalidateIndexState()
end
Possibly related PRs
Suggested labels: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2f66eecd40
ℹ️ About Codex in GitHub
Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| err := r.pool.QueryRow(ctx, ` | ||
| SELECT COUNT(*) | ||
| FROM catalog_search_index_events | ||
| WHERE provider = $1 | ||
| AND processed_at IS NOT NULL | ||
| AND attempts >= $2 | ||
| AND last_error <> '' | ||
| `, provider, searchIndexEventMaxAttempts).Scan(&count) |
There was a problem hiding this comment.
Count only unresolved dead-letter events
After an event reaches the retry limit, this query counts that processed row forever: a later successful rebuild (the UI's advertised remedy, "stale until rebuild") or a later successful upsert for the same content leaves the old dead-letter row untouched, so the admin warning never clears even though the index is current again. Scope the count to still-unresolved/latest events or clear dead-letter markers during rebuild so the status reflects items that are actually stale.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
🧹 Nitpick comments (4)
cmd/silo/main.go (1)
2244-2251: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winExtract the provider-kind-from-instance check into a shared helper.
This exact
if _, ok := provider.(*catalog.MeilisearchSearchProvider); ok { ... }pattern now appears in three places: here,internal/api/router.go(lines 464-467), andinternal/catalog/search_service.go'sStatus()(line 159). Consider a small exported helper in thecatalogpackage, e.g.catalog.ProviderKind(p CatalogSearchProvider) string, so all three call sites stay in sync if a new provider type is ever added.♻️ Proposed helper
// in internal/catalog/search_provider.go func ProviderKind(p CatalogSearchProvider) string { if _, ok := p.(*MeilisearchSearchProvider); ok { return SearchProviderMeilisearch } return SearchProviderPostgres }- activeSearchProvider := catalog.SearchProviderPostgres - if _, ok := compatSearchService.Provider().(*catalog.MeilisearchSearchProvider); ok { - activeSearchProvider = catalog.SearchProviderMeilisearch - } + activeSearchProvider := catalog.ProviderKind(compatSearchService.Provider())🤖 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 `@cmd/silo/main.go` around lines 2244 - 2251, The provider-kind detection is duplicated across the enqueue setup, router latch, and SearchService.Status, so extract the type-check into a shared catalog helper. Add an exported helper on the catalog package, such as ProviderKind for CatalogSearchProvider, that returns the correct search provider constant based on the concrete provider type, and update the call sites in main, router, and search_service to use it so future provider additions stay consistent.internal/catalog/search_index_repo.go (1)
345-368: 🎯 Functional Correctness | 🔵 TrivialConsider a dead-letter-specific index for this count. MarkProcessed/MarkProcessedThrough clear
last_error, so successful replays won’t stay counted. The query still runs on every admin status load and only lines up withidx_catalog_search_index_events_pending.🤖 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_index_repo.go` around lines 345 - 368, Add a dead-letter-oriented index for SearchIndexEventRepository.DeadLetterCount so this admin-status query is not scanning the same path as pending events. Update the catalog_search_index_events indexing strategy to support provider + processed_at IS NOT NULL + attempts >= searchIndexEventMaxAttempts + last_error <> '' and then keep DeadLetterCount using that index-friendly predicate; make sure MarkProcessed and MarkProcessedThrough behavior still leaves only real dead-letter rows counted.internal/catalog/search_indexer.go (1)
373-394: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low valueCleanup stops at first delete failure instead of continuing.
cleanupSupersededMeilisearchIndexesreturns immediately when a singleDeleteIndex/WaitTaskcall errors, skipping any remaining stale indexes for this run. This self-heals on the next rebuild's full sweep, so it's not a correctness bug, but continuing past a single failure would clean up more in one pass and give a more accurateRemovedIndexescount on transient errors (e.g., one index briefly locked).[reliability]
♻️ Optional: continue past individual delete failures
func cleanupSupersededMeilisearchIndexes(ctx context.Context, client *meilisearchClient, indexPrefix, activeUID, previousActiveUID string) (int, error) { uids, err := client.ListIndexUIDs(ctx) if err != nil { return 0, err } removed := 0 + var errs []error for _, uid := range staleCatalogSearchIndexUIDs(uids, indexPrefix, activeUID, previousActiveUID) { task, err := client.DeleteIndex(ctx, uid) if err != nil { - return removed, err + errs = append(errs, err) + continue } if err := client.WaitTask(ctx, task); err != nil { - return removed, err + errs = append(errs, err) + continue } removed++ } - return removed, nil + return removed, errors.Join(errs...) }🤖 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 373 - 394, cleanupSupersededMeilisearchIndexes currently aborts on the first DeleteIndex or WaitTask error, so one transient failure prevents later stale indexes from being removed. Update the loop in cleanupSupersededMeilisearchIndexes to continue iterating over staleCatalogSearchIndexUIDs after an individual failure, while still recording the first error to return at the end and keeping RemovedIndexes accurate for successfully deleted indexes.internal/catalog/search_meilisearch_provider.go (1)
220-248: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winDeduplicate concurrent index-state refreshes.
indexState()releasesstateMubefore the Postgres reads, so when the 3s TTL expires, a burst of searches can all miss the cache and issue the sameGetState/PendingCountcalls in parallel. Collapse the refresh path withsingleflightor an equivalent in-process dedupe so only one request repopulates the cache per expiry window.🤖 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_meilisearch_provider.go` around lines 220 - 248, indexState currently allows multiple concurrent cache misses to trigger duplicate Postgres refreshes because it unlocks stateMu before calling GetState and PendingCount. Update MeilisearchSearchProvider.indexState to collapse the refresh path with singleflight or similar in-process deduping so only one request repopulates the cached state per TTL window, while other callers wait and reuse the same result.
🤖 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.
Nitpick comments:
In `@cmd/silo/main.go`:
- Around line 2244-2251: The provider-kind detection is duplicated across the
enqueue setup, router latch, and SearchService.Status, so extract the type-check
into a shared catalog helper. Add an exported helper on the catalog package,
such as ProviderKind for CatalogSearchProvider, that returns the correct search
provider constant based on the concrete provider type, and update the call sites
in main, router, and search_service to use it so future provider additions stay
consistent.
In `@internal/catalog/search_index_repo.go`:
- Around line 345-368: Add a dead-letter-oriented index for
SearchIndexEventRepository.DeadLetterCount so this admin-status query is not
scanning the same path as pending events. Update the catalog_search_index_events
indexing strategy to support provider + processed_at IS NOT NULL + attempts >=
searchIndexEventMaxAttempts + last_error <> '' and then keep DeadLetterCount
using that index-friendly predicate; make sure MarkProcessed and
MarkProcessedThrough behavior still leaves only real dead-letter rows counted.
In `@internal/catalog/search_indexer.go`:
- Around line 373-394: cleanupSupersededMeilisearchIndexes currently aborts on
the first DeleteIndex or WaitTask error, so one transient failure prevents later
stale indexes from being removed. Update the loop in
cleanupSupersededMeilisearchIndexes to continue iterating over
staleCatalogSearchIndexUIDs after an individual failure, while still recording
the first error to return at the end and keeping RemovedIndexes accurate for
successfully deleted indexes.
In `@internal/catalog/search_meilisearch_provider.go`:
- Around line 220-248: indexState currently allows multiple concurrent cache
misses to trigger duplicate Postgres refreshes because it unlocks stateMu before
calling GetState and PendingCount. Update MeilisearchSearchProvider.indexState
to collapse the refresh path with singleflight or similar in-process deduping so
only one request repopulates the cached state per TTL window, while other
callers wait and reuse the same result.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro Plus
Run ID: ad13cedf-ccaf-44aa-a745-213083a43b62
📒 Files selected for processing (14)
cmd/silo/main.gointernal/api/router.gointernal/catalog/search_index_repo.gointernal/catalog/search_indexer.gointernal/catalog/search_indexer_test.gointernal/catalog/search_meilisearch_client.gointernal/catalog/search_meilisearch_client_test.gointernal/catalog/search_meilisearch_provider.gointernal/catalog/search_provider.gointernal/catalog/search_provider_test.gointernal/catalog/search_service.gointernal/catalog/semantic_coverage.goweb/src/hooks/queries/admin/settings.tsweb/src/pages/admin-settings/SearchSettings.tsx
Findings from a full review of the Meilisearch implementation: - Give the indexer its own 2m HTTP timeout instead of reusing the 800ms search-path timeout_ms, so large document uploads to a non-loopback Meilisearch stop timing out. - Delete superseded indexes after a rebuild (previous active + leftover <prefix>_rebuild_* partials); every rebuild previously leaked a full copy of the catalog on the Meilisearch instance. - Cache the index state row + pending count for 3s on the search hot path (was two Postgres round trips per search request); a failed search invalidates the cache immediately. - Swap the active-index pointer before marking outbox events processed so a crash between the two replays events instead of losing them. - End pagination only on a short page; estimatedTotalHits is an estimate and could truncate results. - Latch the startup-resolved provider process-wide so package-level enqueue helpers stop querying server_settings in write transactions. - Surface dead-lettered outbox events in the admin status + web UI. - Remove unwired provider config knobs, dedupe the manga-chapter exclusion predicate, split the vector cache onto its own mutex, real rebuild progress percentages, and expand client/coalesce test coverage. Co-authored-by: Claude Fable 5 <[email protected]>
Problem
A full review of the Meilisearch integration (client, provider, indexer, outbox repo, admin surface) found two operational defects, a hot-path performance issue, a crash-window ordering bug, and several smaller design inconsistencies. No linked issue — this came out of an ad-hoc code review of the subsystem; happy to split per-concern if preferred.
What changed
Functional fixes
catalog.search.meilisearch.timeout_ms(default 800ms). Document batches run up to 80MB; against a non-loopback Meilisearch, rebuilds/syncs would time out, and the only workaround loosened the interactive search path too.<prefix>_rebuild_<ts>and swap a state pointer, but nothing ever deleted old indexes — every rebuild leaked a full catalog copy. The client gainedDeleteIndex/ListIndexUIDs, and a successful rebuild now removes the previously active index plus leftover rebuild partials (prefix-scoped, so unrelated indexes on a shared instance are safe; best-effort, reported asremoved_indexes).Search()ranGetState+PendingCount(aCOUNT(*)) on every request. Both are now cached for 3s; a failed search invalidates the cache so a swapped-away index heals on the next request.index_pending_updatesin the API is unchanged, just up to 3s stale.Rebuildmarked outbox events processed before swapping the active-index pointer; a crash in between permanently lost those updates from the served index. Order is now swapped — a crash replays pending events into the new index as idempotent upserts.estimatedTotalHitsis an estimate and could truncate results.Design / observability
EnqueueSearchIndex*helpers (metadata, scanner, catalogseed, …) re-queriedserver_settingsinside every write transaction. The startup-resolved provider (restart-keyed, so immutable per process) is now latched viacatalog.SetActiveSearchIndexProvider; unset falls back to the old query.dead_lettered_eventsin the admin status (additive field per v1 API rules) and as a warning row in the Search settings UI.MeilisearchProviderConfigknobs (BatchSize/CandidateScanCap/DeepOffsetLimit/CircuitCooldown) — constants are now the single source, somaxTotalHitscan't drift from the scan cap.markFallback, and rebuild progress now reports a real percentage from an upfront eligible-document count.Tests
coalesceSearchIndexEvents(rename → delete+upsert, last-op-wins) andstaleCatalogSearchIndexUIDs(active/unrelated indexes never deleted) now have direct coverage.Risk / behavior notes
index_pending_updatesand the state row are now ≤3s stale on the search path.Verification
go build ./...,go vet, test suites for catalog/api/taskmanager/metadata/scanner/catalogseed/recommendations, golangci-lint (no new findings in touched files),cd web && pnpm run lint(0 errors),pnpm run format:check,tsc --noEmit,make verify-local-paths— all pass.AI-use disclosure
Reviewed, implemented, and verified by Claude Code (Claude Fable 5), directed and to be reviewed by @Quick.
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes