Skip to content

fix(catalog): harden Meilisearch search integration - #291

Merged
Quick104 merged 1 commit into
mainfrom
fix/meilisearch-hardening
Jul 5, 2026
Merged

Quick104 merged 1 commit into
mainfrom
fix/meilisearch-hardening

Conversation

@Quick104

@Quick104 Quick104 commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Dedicated indexing timeout: the indexer client now uses a 2-minute timeout instead of reusing 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.
  • Index leak: rebuilds create <prefix>_rebuild_<ts> and swap a state pointer, but nothing ever deleted old indexes — every rebuild leaked a full catalog copy. The client gained DeleteIndex/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 as removed_indexes).
  • Hot-path DB load: Search() ran GetState + PendingCount (a COUNT(*)) 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_updates in the API is unchanged, just up to 3s stale.
  • Crash-window ordering: Rebuild marked 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.
  • Pagination: end-of-results is now detected only by a short page; estimatedTotalHits is an estimate and could truncate results.

Design / observability

  • Package-level EnqueueSearchIndex* helpers (metadata, scanner, catalogseed, …) re-queried server_settings inside every write transaction. The startup-resolved provider (restart-keyed, so immutable per process) is now latched via catalog.SetActiveSearchIndexProvider; unset falls back to the old query.
  • Dead-lettered outbox events (10 failed attempts → silently dropped, item stale until rebuild) are now counted and surfaced as dead_lettered_events in the admin status (additive field per v1 API rules) and as a warning row in the Search settings UI.
  • Removed unwired MeilisearchProviderConfig knobs (BatchSize/CandidateScanCap/DeepOffsetLimit/CircuitCooldown) — constants are now the single source, so maxTotalHits can't drift from the scan cap.
  • Deduplicated the manga-chapter exclusion predicate (was inlined 5×), gave the query-vector cache its own mutex, removed a redundant markFallback, and rebuild progress now reports a real percentage from an upfront eligible-document count.

Tests

  • Client: base-path joining + auth header, JSON/plain-text error decoding, task-failure surfacing, missing-index delete tolerance, list pagination.
  • coalesceSearchIndexEvents (rename → delete+upsert, last-op-wins) and staleCatalogSearchIndexUIDs (active/unrelated indexes never deleted) now have direct coverage.
  • Provider: state cache serves repeated searches from one fetch; a failed search invalidates it without tripping the circuit on 404.

Risk / behavior notes

  • Deleting the previous index right after the swap means an in-flight search holding the old UID can 404 → that request falls back to Postgres (404 does not trip the circuit) and the state cache invalidates. One-request blip, bounded.
  • index_pending_updates and the state row are now ≤3s stale on the search path.
  • Rebuild progress messages changed shape ("Indexed N of M catalog items").

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

    • Added a new “Dead-lettered Events” status indicator in admin search settings when retryable indexing events are exhausted.
    • Improved search indexing progress reporting and now shows when stale items remain until a rebuild.
    • Search indexing now cleans up old, superseded indexes more reliably.
  • Bug Fixes

    • Improved search reliability after failures and during rebuilds.
    • Reduced unnecessary backend lookups to make search status and indexing behavior more responsive.

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]>
@coderabbitai

coderabbitai Bot commented Jul 3, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds 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.

Changes

Meilisearch search index provider latching, rebuild cleanup, and dead-letter tracking

Layer / File(s) Summary
Active provider latch
internal/catalog/search_index_repo.go, cmd/silo/main.go, internal/api/router.go
Adds SetActiveSearchIndexProvider backed by an atomic.Value, consulted by shouldEnqueue; called from compat server startup and router wiring based on the resolved provider type.
Dead-letter counting
internal/catalog/search_index_repo.go, internal/catalog/search_service.go, internal/catalog/search_provider.go
Adds DeadLetterCount repository method, wires it into Status, and adds DeadLetteredEvents to CatalogSearchIndexStateStatus.
Meilisearch client index management
internal/catalog/search_meilisearch_client.go, internal/catalog/search_meilisearch_client_test.go
Adds DeleteIndex and ListIndexUIDs, fixes query-string handling in request URL construction, adds tests for errors, auth, pagination, and idempotent delete.
Rebuild progress and index cleanup
internal/catalog/search_indexer.go, internal/catalog/search_indexer_test.go, internal/catalog/semantic_coverage.go
Adds shared manga-chapter exclusion SQL, eligible-document counting, rebuildIndexingPercent, superseded-index cleanup after state update, RemovedIndexes stat, indexing timeout constant, and tests.
Meilisearch provider config and caching
internal/catalog/search_meilisearch_provider.go, internal/catalog/search_provider_test.go
Replaces tunable config fields with fixed constants, splits vector/index-state caching into dedicated mutexes with TTL-based state caching and invalidation on search failure, adjusts pagination and fallback logic, adds tests.
Admin UI dead-letter display
web/src/hooks/queries/admin/settings.ts, web/src/pages/admin-settings/SearchSettings.tsx
Adds dead_lettered_events to the frontend type and conditionally renders a status row for it.

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
Loading
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
Loading

Possibly related PRs

Suggested labels: v1

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: hardening the catalog Meilisearch search integration.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/meilisearch-hardening

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 Jul 3, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +355 to +362
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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

🧹 Nitpick comments (4)
cmd/silo/main.go (1)

2244-2251: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract 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), and internal/catalog/search_service.go's Status() (line 159). Consider a small exported helper in the catalog package, 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 | 🔵 Trivial

Consider 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 with idx_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 value

Cleanup stops at first delete failure instead of continuing.

cleanupSupersededMeilisearchIndexes returns immediately when a single DeleteIndex/WaitTask call 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 accurate RemovedIndexes count 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 win

Deduplicate concurrent index-state refreshes.

indexState() releases stateMu before the Postgres reads, so when the 3s TTL expires, a burst of searches can all miss the cache and issue the same GetState/PendingCount calls in parallel. Collapse the refresh path with singleflight or 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

📥 Commits

Reviewing files that changed from the base of the PR and between 3d82aa5 and 2f66eec.

📒 Files selected for processing (14)
  • cmd/silo/main.go
  • internal/api/router.go
  • internal/catalog/search_index_repo.go
  • internal/catalog/search_indexer.go
  • internal/catalog/search_indexer_test.go
  • internal/catalog/search_meilisearch_client.go
  • internal/catalog/search_meilisearch_client_test.go
  • internal/catalog/search_meilisearch_provider.go
  • internal/catalog/search_provider.go
  • internal/catalog/search_provider_test.go
  • internal/catalog/search_service.go
  • internal/catalog/semantic_coverage.go
  • web/src/hooks/queries/admin/settings.ts
  • web/src/pages/admin-settings/SearchSettings.tsx

@Quick104
Quick104 merged commit 8ab1f6b into main Jul 5, 2026
4 checks passed
@Quick104
Quick104 deleted the fix/meilisearch-hardening branch July 5, 2026 04:18
Quick104 added a commit to RXWatcher/silo-server that referenced this pull request Jul 10, 2026
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]>
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