Skip to content

feat(ebooks): decouple metadata enrichment from scans via a durable queue - #433

Merged
Quick104 merged 35 commits into
Silo-Server:mainfrom
RXWatcher:fix/ebook-enrichment-architecture
Jul 23, 2026
Merged

Quick104 merged 35 commits into
Silo-Server:mainfrom
RXWatcher:fix/ebook-enrichment-architecture

Conversation

@RXWatcher

@RXWatcher RXWatcher commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Ebook library scans previously blocked on remote metadata providers: a synchronous retry loop inside the scan meant provider latency, outages, or rate limits stalled scanning, and interrupted runs lost their place. This PR decouples the two.

  • Scans are now file-only for ebook libraries: filesystem reconciliation, embedded EPUB/PDF metadata, local artwork, and identifier hints complete in seconds with no network calls.
  • Remote enrichment moves to a durable Postgres-backed queue (FOR UPDATE SKIP LOCKED claims, lease tokens with expiry, priority lanes: 0 for new/refresh work, -100 for the legacy backlog).
  • Per-outcome retry horizons: success re-checks in 90d, no-match in 30d, transient failures back off exponentially (capped 24h); rate-limited items honor Retry-After but never requeue below a 15m cooldown floor (SILO_EBOOK_RATE_LIMIT_COOLDOWN) — provider RetryInfo hints are request-pacing advice, not queue horizons.
  • The legacy backlog drains automatically: the backfill task ships a default 15-minute interval trigger, self-pacing via the cooldown + a zero-progress circuit breaker + a 4-minute execution budget. Canary knobs (SILO_EBOOK_BACKFILL_MAX_CLAIMS, SILO_EBOOK_BACKFILL_BATCH_DELAY) remain for gradual rollouts.
  • User-edited fields are protected from remote overwrite via protected_fields.
  • Operators can supply corrected metadata via <book>.opf sidecars; sidecar reads are fenced against symlink swaps (os.SameFile), corrected ISBNs replace stale provider ids on rescan, and sidecar edits trigger targeted rescans.

Migrations: 20260719090000_ebook_enrichment_jobs.sql, 20260719173000_ebook_enrichment_reconcile_cursor.sql.
Design docs: docs/superpowers/plans/2026-07-19-ebook-enrichment-architecture.md, docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md.

Production evidence (65k-book backlog, 2026-07-20)

  • Scans complete in seconds; enrichment runs unattended every 15 minutes.
  • First automated run: 100 claimed / 74 enriched / 17 no-match / 9 rate-deferred / 0 failed in 33s (with the metadata plugin narrowed to sanctioned API sources — see companion plugin PR).
  • Cooldown floor verified: rate-limited rows requeue at exactly +15m instead of +1s.

Notes for review

  • Contains the two commits from fix(web): recover from stale content-hashed chunks after deploys #434 (38d39726, cf1f0387) because this exact tip is deployed; once fix(web): recover from stale content-hashed chunks after deploys #434 merges I'll rebase them out.
  • Heads-up beyond the ebook framing: scantrigger.ResolveVanishedPath now resolves vanished video files to an exact-file scan (previously a parent-subtree scan); reconcileVanishedFileIfNeeded + syncVanishedVideoQueues reproduce the old mark-missing/sweep/queue-sync behavior for that path.
  • Task result_data gains additive JSON fields (claimed, deferred, discarded, …) inside the existing envelope; progress message strings changed format.

Tests

  • go test ./internal/ebooks ./internal/scanner ./internal/taskmanager/... ./internal/scantrigger ./internal/libraryingest ./internal/server -count=1
  • pnpm exec vitest run src/lib/reloadOnPreloadError.test.ts
  • make verify-local-paths; go build ./..., go vet, gofmt clean

AI-use disclosure

Implemented and reviewed with Claude Code (multi-agent review pass + TDD throughout).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Ebook metadata enrichment now runs through durable background processing with incremental sync and legacy backfill support.
    • Ebook scans can read metadata from adjacent OPF sidecar files while preserving existing local metadata.
    • Single-file ebook roots and additional ebook file formats are now supported.
    • Missing media paths are classified according to their library type for more precise rescans.
  • Bug Fixes

    • Missing frontend assets now return a proper 404 instead of the application shell.
    • Improved retry handling and protection against overwriting local ebook metadata.
    • The app can automatically recover from failed frontend chunk loads.

@RXWatcher

RXWatcher commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

Un-withdrawing — this is ready for review. Since opening, the queue has been running unattended in production: the legacy backlog is draining on the 15-minute trigger with deferrals near zero (≈1 day of backlog remaining as of 2026-07-21), and the PR body carries the production evidence. The stacking note still applies: this tip includes the two #434 commits and gets rebased once #434 merges.

@RXWatcher RXWatcher closed this Jul 20, 2026
@coderabbitai

coderabbitai Bot commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces a durable ebook enrichment queue with leased jobs, retry policies, reconciliation cursors, and scoped workers. Ebook scans enqueue enrichment work, generic ebook matching is skipped, scan classification becomes library-aware, and task management gains bounded incremental sync and legacy backfill execution.

Changes

Ebook enrichment architecture

Layer / File(s) Summary
Durable queue and database state
internal/ebooks/enrichment_queue.go, migrations/sql/*, migrations/*
Adds leased queue jobs, scoped lanes, retry transitions, reconciliation cursors, migration backfills, and supporting SQL tests.
Claimed enrichment lifecycle
internal/ebooks/enrichment.go, internal/ebooks/*_test.go
Processes claimed jobs concurrently with ownership checks, outcome aggregation, retry classification, metadata preservation, and provider-ID loading.
Scanner integration
internal/scanner/*, cmd/silo/main.go
Enqueues ebook work after indexing, reconciles missing enrichment, parses safe OPF sidecars, supports single-file roots, and wires the queue into the scanner.
Library-aware routing
internal/libraryingest/*, internal/scantrigger/*
Skips generic ebook matching and classifies vanished or requested media paths according to library type.
Sync and backfill tasks
internal/taskmanager/tasks/sync_ebook_metadata*, cmd/silo/main.go
Drains incremental work in bounded batches and adds a separately configured legacy backfill task with progress, pacing, cancellation, and circuit-break handling.
Frontend resilience
internal/server/frontend*, web/src/lib/reloadOnPreloadError*, web/src/main.tsx
Adds guarded reloads for preload failures and prevents missing asset requests from receiving the SPA shell.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Scanner
  participant EnrichmentQueue
  participant Enricher
  participant TaskManager
  participant PostgreSQL
  Scanner->>EnrichmentQueue: Enqueue indexed ebook
  TaskManager->>Enricher: RunLimited incremental or legacy scope
  Enricher->>EnrichmentQueue: Claim leased jobs
  EnrichmentQueue->>PostgreSQL: Load and update durable job state
  Enricher->>EnrichmentQueue: Complete, fail, release, or discard jobs
  TaskManager->>Enricher: Request next bounded batch
Loading

Possibly related PRs

Suggested labels: v1

Suggested reviewers: quick104

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 1.55% 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
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the core ebook change: moving metadata enrichment off scans into a durable queue.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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 20, 2026
@RXWatcher RXWatcher reopened this Jul 20, 2026
RXWatcher and others added 25 commits July 22, 2026 13:43
Close the symlink-swap window in the sidecar reader: os.Open follows
symlinks, so a leaf swapped between the Lstat gate and the open could pull
metadata from outside the library root. Reject unless the opened handle is
the exact file Lstat inspected, matching the image cache processor guard.

Replace a stale ISBN provider id on rescan instead of silently dropping it,
so sidecar ISBN corrections actually take effect; tolerate the ISBN already
belonging to another item so duplicate copies keep scanning.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
RXWatcher and others added 9 commits July 22, 2026 13:43
A claim whose enrichment surfaced context.Canceled while the sweep was
still live was released uncounted, leaving it immediately reclaimable and
invisible to the no-progress circuit breaker. Let it flow through the
failure path as a transient error so it backs off and is counted; genuine
sweep shutdown still releases via the existing ctx check.

Claims discarded because the item vanished are terminal, not retried, so
report them in a new discarded counter instead of inflating deferred, and
surface the count in task progress output.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
The ebook-metadata plugin attaches ~1s RetryInfo to ResourceExhausted
errors as request-pacing advice for its internal token bucket. Adopting
that hint verbatim as the queue horizon made rate-limited rows claimable
again immediately, so every backfill run re-claimed the same saturated
tail. Clamp rate-limited requeues to a 15m floor (SILO_EBOOK_RATE_LIMIT_COOLDOWN
to tune); hints above the floor are honored up to the existing 24h cap.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Give the backfill task a default 15-minute interval trigger. With the
rate-limit cooldown floor each run meets a fresh ready-set, a saturated
batch trips the zero-progress breaker, and an empty lane exits in
milliseconds, so the backlog drains at provider speed unattended. The
canary claim cap and batch delay keep their semantics, and operators can
retune or disable the trigger through the admin task UI.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
A /assets/ chunk from a previous build no longer exists after a deploy;
serving the SPA shell at that URL makes the browser fail dynamic imports
on a text/html module. Exclude /assets/ from the SPA fallback so the
miss surfaces as a 404 the client can react to.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
After a deploy, an open tab still references the previous build's
content-hashed chunks and the first lazy navigation dies with "Failed to
fetch dynamically imported module". Handle Vite's vite:preloadError by
reloading onto the current build, guarded to at most one reload per
minute so a persistently missing chunk cannot reload-loop.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Review feedback: window is shared across vitest tests, so repeated
installs accumulated listeners. The installer now returns a remover and
the tests detach in afterEach.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@RXWatcher
RXWatcher force-pushed the fix/ebook-enrichment-architecture branch from 4e4136c to bd97f3c Compare July 22, 2026 11:44
Scanner re-enqueues (priority 100) could silently promote pending legacy
backlog rows (priority -100) into the incremental lane via the enqueue
upsert's GREATEST, and the fail/release requeue branches hardcoded 100
regardless of the row's lane. A mass mtime shift or group-key-version
bump would have moved the entire legacy backlog out from under the
backfill task's pacing controls into the scheduled sync task.

Lane changes now happen only through terminal outcomes (complete or
discard); enqueue, fail, and release preserve a negative priority.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
@Quick104

Copy link
Copy Markdown
Contributor

Reviewed the full diff (queue core + migrations, scanner/taskmanager integration, and how this fits Silo's existing background-work architecture).

Overall: the approach is right. Postgres SKIP-LOCKED claim queues drained by taskmanager ticks are already the house pattern (metadata match/refresh debt, image cache jobs, download artifacts, notification outboxes, autoscan webhooks); ebook scans were the last subsystem doing provider I/O inline, and this aligns them. The claim query matches its partial indexes, every terminal transition is CAS-gated on claim_token, backoff math is capped and overflow-safe, the reconcile cursor uses keyset pagination, the migration follows the safe online-index pattern, the OPF sidecar Lstat→Open→os.SameFile fence closes the TOCTOU window, and the backfill circuit breaker can't spin hot or wedge.

One real defect, fixed in 84cd0ac (pushed to this branch): legacy-lane rows (priority -100) could be silently promoted into the incremental lane without a terminal outcome — the enqueue upsert's GREATEST(priority, EXCLUDED.priority) flipped any pending legacy row on re-enqueue (scanner always enqueues at 100), and the Fail/Release requeue branches hardcoded priority = 100. A mass mtime shift (NAS remount, backup restore) or an ebookGroupKeyVersion bump would have re-enqueued the whole ~65k legacy backlog straight into the 5-minute sync task, bypassing the backfill task's claim cap, batch delay, and cooldown pacing. The fix makes non-terminal transitions lane-preserving; Complete/Discard graduation to the incremental lane is unchanged. Added TestEnrichmentQueueKeepsLegacyLaneRowsUntilTerminalOutcome plus updated fragment assertions. go test ./internal/ebooks ./internal/taskmanager/tasks ./internal/scanner -count=1, go vet, gofmt all clean.

Also noted: the ResolveVanishedPath subtree→exact-file change affects video libraries, not just ebooks — traced it and the new reconcile path faithfully reproduces the old mark-missing/sweep/queue-sync behavior, so no change requested; added a heads-up bullet to the PR body. Merge should still wait for the #434 rebase so this stays one concern.

🤖 Generated with Claude Code

@Quick104
Quick104 merged commit c0b2e18 into Silo-Server:main Jul 23, 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: 6

🧹 Nitpick comments (1)
docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md (1)

67-74: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Test the existing-install upgrade path, not only DefaultTriggers().

The key rollout guarantee is that persisted task state with no triggers receives the default on upgrade, while an explicitly disabled trigger remains disabled. Add a manager-level regression test covering both cases; testing only DefaultTriggers() does not verify that behavior.

🤖 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 `@docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md` around
lines 67 - 74, Extend the Testing section to require a manager-level regression
test for the existing-install upgrade path, covering persisted task state with
no triggers receiving the default trigger and an explicitly disabled trigger
remaining disabled. Keep the existing DefaultTriggers() unit-test coverage, but
do not treat it as sufficient for validating upgrade behavior.
🤖 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 `@docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md`:
- Around line 76-81: Clarify the “Migrations and API surface” bullet in the Out
of scope section to state that no additional migrations or API changes are
required for the cooldown-floor and default-trigger additions, without implying
that the broader PR has none.
- Around line 60-65: Update the run-behavior description so rate-limited items
remain ineligible via next_attempt_at for at least the cooldown floor rather
than sleeping, and remove the claim that the next 15-minute run always sees a
fresh ready-set. Preserve the existing zero-progress circuit-breaker,
empty-ready-set, and unattended-draining behavior.

In `@internal/scanner/ebook.go`:
- Around line 96-107: Update the sidecar handling in parseEbookFile so
parseEbookOPFSidecar failures are logged and ignored after the primary ebook
parse succeeds, rather than returned. Continue sanitizing and returning the book
with its embedded metadata, while still applying sidecar metadata when parsing
succeeds.

In `@migrations/sql/20260719090000_ebook_enrichment_jobs.sql`:
- Around line 25-29: Update the constraints in the ebook_enrichment_state
migration to be added as NOT VALID, then validate each constraint separately
with ALTER TABLE ... VALIDATE CONSTRAINT. Preserve the existing status and
attempts predicates and constraint names while ensuring the validation occurs
outside the write-blocking constraint-add operation.

In `@web/src/lib/reloadOnPreloadError.test.ts`:
- Around line 38-60: Update the “reloads again once the guard window has passed”
test to clean up the first listener before the second installPreloadErrorReload
call. Reuse the existing cleanup entry or invoke it directly after the initial
event, so the later dispatch has only one active handler and preserves the
expected reload count.

In `@web/src/lib/reloadOnPreloadError.ts`:
- Around line 24-33: Update the handler around setItem and event.preventDefault
so storage failures cannot suppress vite:preloadError without reloading or
preserving the guard. Use a read-only or in-memory fallback when getItem/setItem
access fails, and only call event.preventDefault after the guard state has been
successfully recorded or safely tracked; keep reload() and the existing
reload-window behavior unchanged.

---

Nitpick comments:
In `@docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md`:
- Around line 67-74: Extend the Testing section to require a manager-level
regression test for the existing-install upgrade path, covering persisted task
state with no triggers receiving the default trigger and an explicitly disabled
trigger remaining disabled. Keep the existing DefaultTriggers() unit-test
coverage, but do not treat it as sufficient for validating upgrade behavior.
🪄 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: 587919d1-3497-4f1a-ad7a-25423f7f96e3

📥 Commits

Reviewing files that changed from the base of the PR and between 0a91444 and 84cd0ac.

📒 Files selected for processing (26)
  • cmd/silo/main.go
  • docs/superpowers/plans/2026-07-19-ebook-enrichment-architecture.md
  • docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md
  • internal/ebooks/enrichment.go
  • internal/ebooks/enrichment_queue.go
  • internal/ebooks/enrichment_queue_test.go
  • internal/ebooks/enrichment_test.go
  • internal/libraryingest/executor.go
  • internal/libraryingest/executor_test.go
  • internal/scanner/ebook.go
  • internal/scanner/ebook_scan.go
  • internal/scanner/ebook_test.go
  • internal/scanner/scanner.go
  • internal/scanner/scanner_test.go
  • internal/scantrigger/scantrigger.go
  • internal/scantrigger/scantrigger_test.go
  • internal/server/frontend.go
  • internal/server/frontend_test.go
  • internal/taskmanager/tasks/sync_ebook_metadata.go
  • internal/taskmanager/tasks/sync_ebook_metadata_test.go
  • migrations/ebook_enrichment_reconcile_cursor_test.go
  • migrations/sql/20260719090000_ebook_enrichment_jobs.sql
  • migrations/sql/20260719173000_ebook_enrichment_reconcile_cursor.sql
  • web/src/lib/reloadOnPreloadError.test.ts
  • web/src/lib/reloadOnPreloadError.ts
  • web/src/main.tsx

Comment on lines +60 to +65
Each 15-minute run claims what is ready under the execution budget and the
claim cap. Rate-limited items sleep at least the floor, so the next run meets
a fresh ready-set instead of the same saturated tail. A fully saturated batch
trips the existing zero-progress circuit breaker and ends the run early. An
empty ready-set makes the run exit in milliseconds. The backlog drains at
whatever pace the provider allows, unattended.

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.

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Describe deferral as queue ineligibility, not sleeping.

Rate-limited jobs are deferred via next_attempt_at; workers do not sleep for the cooldown. Also, a 15-minute interval does not guarantee a “fresh” ready-set if rows become eligible at the same boundary. Please use wording such as “remain ineligible for at least the floor.”

🤖 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 `@docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md` around
lines 60 - 65, Update the run-behavior description so rate-limited items remain
ineligible via next_attempt_at for at least the cooldown floor rather than
sleeping, and remove the claim that the next 15-minute run always sees a fresh
ready-set. Preserve the existing zero-progress circuit-breaker, empty-ready-set,
and unattended-draining behavior.

Comment on lines +76 to +81
## Out of scope

- Plugin-side changes to what `RetryInfo` the ebook-metadata plugin sends
(its 1s hint remains correct for in-process pacing).
- Any change to the scheduled priority-0 sync task.
- Migrations and API surface: none needed.

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.

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Scope the “no migrations/API” statement to this automation change.

The broader PR includes queue/cursor migrations and additive task-progress fields. As written, this line can be read as saying the overall feature requires neither migrations nor API changes. Clarify that no additional migrations or API changes are required specifically for the cooldown-floor and default-trigger additions.

🤖 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 `@docs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.md` around
lines 76 - 81, Clarify the “Migrations and API surface” bullet in the Out of
scope section to state that no additional migrations or API changes are required
for the cooldown-floor and default-trigger additions, without implying that the
broader PR has none.

Comment thread internal/scanner/ebook.go
Comment on lines +96 to 107
if err == nil {
if sidecarPath := ebookOPFSidecarPath(path); sidecarPath != "" {
sidecar, sidecarErr := parseEbookOPFSidecar(sidecarPath)
if sidecarErr != nil {
return book, sidecarErr
}
applyEbookSidecarMetadata(&book, sidecar)
}
}
book.sanitize()
return book, err
}

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.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

A malformed OPF sidecar now blocks indexing of an otherwise-valid ebook.

When the primary parse succeeds but parseEbookOPFSidecar fails (e.g. a hand-edited/corrupt .opf with malformed XML or an over-size file), parseEbookFile returns the sidecar error, which propagates through reconcileEbookFile and fails that file. The embedded metadata was already valid, so a bad optional sidecar shouldn't prevent the book from being indexed. Consider logging and continuing with the embedded metadata instead.

🛡️ Degrade gracefully on sidecar parse failure
 	if err == nil {
 		if sidecarPath := ebookOPFSidecarPath(path); sidecarPath != "" {
 			sidecar, sidecarErr := parseEbookOPFSidecar(sidecarPath)
 			if sidecarErr != nil {
-				return book, sidecarErr
+				slog.Warn("ebook: OPF sidecar parse failed; using embedded metadata",
+					"path", path, "sidecar", sidecarPath, "error", sidecarErr)
+			} else {
+				applyEbookSidecarMetadata(&book, sidecar)
 			}
-			applyEbookSidecarMetadata(&book, sidecar)
 		}
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err == nil {
if sidecarPath := ebookOPFSidecarPath(path); sidecarPath != "" {
sidecar, sidecarErr := parseEbookOPFSidecar(sidecarPath)
if sidecarErr != nil {
return book, sidecarErr
}
applyEbookSidecarMetadata(&book, sidecar)
}
}
book.sanitize()
return book, err
}
if err == nil {
if sidecarPath := ebookOPFSidecarPath(path); sidecarPath != "" {
sidecar, sidecarErr := parseEbookOPFSidecar(sidecarPath)
if sidecarErr != nil {
slog.Warn("ebook: OPF sidecar parse failed; using embedded metadata",
"path", path, "sidecar", sidecarPath, "error", sidecarErr)
} else {
applyEbookSidecarMetadata(&book, sidecar)
}
}
}
book.sanitize()
return book, err
}
🤖 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/ebook.go` around lines 96 - 107, Update the sidecar handling
in parseEbookFile so parseEbookOPFSidecar failures are logged and ignored after
the primary ebook parse succeeds, rather than returned. Continue sanitizing and
returning the book with its embedded metadata, while still applying sidecar
metadata when parsing succeeds.

Comment on lines +25 to +29
ALTER TABLE ebook_enrichment_state
ADD CONSTRAINT ebook_enrichment_state_status_check
CHECK (status IN ('pending', 'running', 'discarded')),
ADD CONSTRAINT ebook_enrichment_state_attempts_check
CHECK (attempts >= 0);

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Add these CHECK constraints as NOT VALID, then VALIDATE separately, to avoid a write-blocking full scan.

A plain ADD CONSTRAINT ... CHECK takes ACCESS EXCLUSIVE and scans the entire table before returning, blocking reads/writes for the duration. This migration seeds the full legacy backlog into ebook_enrichment_state, so the table can be large and this stalls concurrent traffic — contrary to the file's own "release its table lock before the potentially large backfill runs" intent. Since existing rows already satisfy both predicates (status/attempts defaults were just set), adding NOT VALID and validating afterward (which takes only SHARE UPDATE EXCLUSIVE) preserves correctness without blocking writes.

🛡️ Proposed fix
 ALTER TABLE ebook_enrichment_state
     ADD CONSTRAINT ebook_enrichment_state_status_check
-        CHECK (status IN ('pending', 'running', 'discarded')),
+        CHECK (status IN ('pending', 'running', 'discarded')) NOT VALID,
     ADD CONSTRAINT ebook_enrichment_state_attempts_check
-        CHECK (attempts >= 0);
+        CHECK (attempts >= 0) NOT VALID;
+
+ALTER TABLE ebook_enrichment_state
+    VALIDATE CONSTRAINT ebook_enrichment_state_status_check;
+ALTER TABLE ebook_enrichment_state
+    VALIDATE CONSTRAINT ebook_enrichment_state_attempts_check;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
ALTER TABLE ebook_enrichment_state
ADD CONSTRAINT ebook_enrichment_state_status_check
CHECK (status IN ('pending', 'running', 'discarded')),
ADD CONSTRAINT ebook_enrichment_state_attempts_check
CHECK (attempts >= 0);
ALTER TABLE ebook_enrichment_state
ADD CONSTRAINT ebook_enrichment_state_status_check
CHECK (status IN ('pending', 'running', 'discarded')) NOT VALID,
ADD CONSTRAINT ebook_enrichment_state_attempts_check
CHECK (attempts >= 0) NOT VALID;
ALTER TABLE ebook_enrichment_state
VALIDATE CONSTRAINT ebook_enrichment_state_status_check;
ALTER TABLE ebook_enrichment_state
VALIDATE CONSTRAINT ebook_enrichment_state_attempts_check;
🧰 Tools
🪛 Squawk (2.59.0)

[warning] 26-27: By default new constraints require a table scan and block writes to the table while that scan occurs. Use NOT VALID with a later VALIDATE CONSTRAINT call.

(constraint-missing-not-valid)


[warning] 28-29: By default new constraints require a table scan and block writes to the table while that scan occurs. Use NOT VALID with a later VALIDATE CONSTRAINT call.

(constraint-missing-not-valid)

🤖 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 `@migrations/sql/20260719090000_ebook_enrichment_jobs.sql` around lines 25 -
29, Update the constraints in the ebook_enrichment_state migration to be added
as NOT VALID, then validate each constraint separately with ALTER TABLE ...
VALIDATE CONSTRAINT. Preserve the existing status and attempts predicates and
constraint names while ensuring the validation occurs outside the write-blocking
constraint-add operation.

Source: Linters/SAST tools

Comment on lines +38 to +60
cleanups.push(installPreloadErrorReload(deps));
window.dispatchEvent(new Event("vite:preloadError"));
expect(reload).toHaveBeenCalledTimes(1);

// Post-reload page still hits the error seconds later: give up instead
// of reload-looping.
clock += 5_000;
cleanups.push(installPreloadErrorReload(deps));
window.dispatchEvent(new Event("vite:preloadError"));
expect(reload).toHaveBeenCalledTimes(1);
});

it("reloads again once the guard window has passed (a later deploy)", () => {
let clock = 1_000_000;
const { reload, deps } = harness(() => clock);

cleanups.push(installPreloadErrorReload(deps));
window.dispatchEvent(new Event("vite:preloadError"));
expect(reload).toHaveBeenCalledTimes(1);

clock += 10 * 60_000;
cleanups.push(installPreloadErrorReload(deps));
window.dispatchEvent(new Event("vite:preloadError"));

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.

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Clean up the first listener before installing another one.

The “later deploy” test keeps both handlers active. After the clock advances, one dispatched event invokes both handlers, so reload is called three times overall rather than the expected two. Reuse the original handler, or call its cleanup before the second installPreloadErrorReload call.

🤖 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/lib/reloadOnPreloadError.test.ts` around lines 38 - 60, Update the
“reloads again once the guard window has passed” test to clean up the first
listener before the second installPreloadErrorReload call. Reuse the existing
cleanup entry or invoke it directly after the initial event, so the later
dispatch has only one active handler and preserves the expected reload count.

Comment on lines +24 to +33
const handler = (event: Event) => {
const lastReloadAt = Number(getItem(GUARD_KEY) ?? 0);
if (now() - lastReloadAt < GUARD_WINDOW_MS) {
// We already reloaded moments ago and the chunk is still missing;
// let the failure surface instead of reload-looping.
return;
}
event.preventDefault();
setItem(GUARD_KEY, String(now()));
reload();

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.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
fd -a 'reloadOnPreloadError\.ts$' . || true

echo "== file content =="
if [ -f web/src/lib/reloadOnPreloadError.ts ]; then
  cat -n web/src/lib/reloadOnPreloadError.ts
fi

echo "== usages =="
rg -n "reloadOnPreloadError|preventDefault\\(\\)|sessionStorage|localStorage" web/src -g '*.ts' -g '*.tsx' | head -200

echo "== git diff stat =="
git diff --stat || true
if git diff -- web/src/lib/reloadOnPreloadError.ts | head -120; then true; fi

Repository: Silo-Server/silo-server

Length of output: 18888


🏁 Script executed:

#!/bin/bash
set -euo pipefail

# Read-only behavioral probe for the control flow: when getItem/throw and preventDefault/write ordering matter.
python3 - <<'PY'
from dataclasses import dataclass

GUARD_KEY = "x"
GUARD_WINDOW_MS = 5_000

`@dataclass`
class Event:
    prevented = False

def old(order):
    e = Event()
    def now():
        return 1000
    try:
        if order == "read_throw":
            raise StorageError("read")
    except:
        last_reload_at = 0
    else:
        last_reload_at = 0
    if now() - last_reload_at < GUARD_WINDOW_MS:
        return {
            "read_threw": order == "read_throw",
            "prevented": e.prevented,
            "setItem_called": order != "read_throw" and order != "write_throw",
            "reload_called": False,
        }

    if order == "write_throw":
        try:
            e.preventDefault()
            raise StorageError("write")
        except:
            return {
                "write_threw": order == "write_throw",
                "prevented": e.prevented,
                "reload_called": False,
            }
    e.preventDefault()
    return {
        "read_threw": order == "read_throw",
        "prevented": e.prevented,
        "reload_called": True,
    }

class StorageError(Exception):
    pass

for order in ["read_throw", "write_throw", "no_storage_throw"]:
    print(order, old(order))

def new(order):
    e = Event()
    def now():
        return 1000
    last_reload_at = None
    try:
        if order == "read_throw":
            raise StorageError("read")
        last_reload_at = 0
    except:
        return {
            "read_threw": order == "read_throw",
            "prevented": e.prevented,
            "reload_called": False,
        }
    if now() - last_reload_at < GUARD_WINDOW_MS:
        return {
            "read_threw": order == "read_throw",
            "prevented": e.prevented,
            "reload_called": False,
        }
    try:
        if order == "write_throw":
            raise StorageError("write")
    except:
        return {
            "write_threw": order == "write_throw",
            "prevented": e.prevented,
            "reload_called": False,
        }
    e.preventDefault()
    return {
        "read_threw": order == "read_throw",
        "prevented": e.prevented,
        "reload_called": True,
    }

for order in ["read_throw", "write_throw"]:
    print(order, new(order))
PY

Repository: Silo-Server/silo-server

Length of output: 626


🌐 Web query:

Vite dev server preload error preventDefault default error handling client reloading

💡 Result:

Vite provides the vite:preloadError event specifically to handle scenarios where dynamic imports fail, most commonly due to "version skew" after a new deployment (where the client attempts to load a chunk that has been removed from the server) [1][2][3]. How to use vite:preloadError: When a dynamic import fails, Vite dispatches a vite:preloadError event on the window object [1][4]. You can listen for this event and call event.preventDefault() to signal that the error has been handled [1][3]. If preventDefault() is called, the original error will not be rethrown [1][4]. Common Implementation Pattern: A frequent strategy is to listen for this event and trigger a page reload to force the browser to fetch the latest index.html and fresh assets [1][2][3]. window.addEventListener('vite:preloadError', (event) => { // Option: Reload the page to fetch the latest version window.location.reload; }); Important Considerations: 1. Version Skew Mitigation: To ensure this mechanism works effectively, ensure your index.html is served with Cache-Control: no-cache [1][3]. Without this, the browser may cache the old index.html, which continues to reference the deleted (old) chunk filenames [1][2]. 2. Event Location: This event listener should be registered early in the application lifecycle (e.g., in your entry file, such as main.tsx or index.jsx) to ensure it is active before any dynamic imports are triggered [5]. 3. Interaction with Routers: Some client-side routers (like Vue Router or TanStack Router) may have their own error handling mechanisms [6][4]. If you are using a router, you may need to integrate the vite:preloadError event with the router's global error handler to prevent the app from crashing while still allowing you to perform a graceful reload [4]. 4. HMR Overlay: If you are seeing frequent error overlays during development that you wish to suppress, note that this is different from preload errors. You can disable the Vite HMR overlay in your configuration if it becomes too intrusive [7]: // vite.config.js export default { server: { hmr: { overlay: false, }, }, }; If you encounter cases where preventDefault() does not stop a fatal crash, it may be due to how dependencies are bundled or specific framework behavior [8][9]. Vite updates have periodically refined this behavior to better allow ignoring these errors [9].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== preload error test file =="
cat -n web/src/lib/reloadOnPreloadError.test.ts

echo "== storage error helpers/usages =="
cat -n web/src/lib/tasteSeed.ts
cat -n web/src/utils/storage.ts

Repository: Silo-Server/silo-server

Length of output: 6928


Avoid suppressing vite:preloadError when session storage is unavailable.

setItem() can throw when storage is blocked and occurs after event.preventDefault(), which prevents Vite from rethrowing the error while reload() is never called. Keep event suppression after a persisted guard write, and use a read-only/in-memory fallback if storage access fails.

🤖 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/lib/reloadOnPreloadError.ts` around lines 24 - 33, Update the handler
around setItem and event.preventDefault so storage failures cannot suppress
vite:preloadError without reloading or preserving the guard. Use a read-only or
in-memory fallback when getItem/setItem access fails, and only call
event.preventDefault after the guard state has been successfully recorded or
safely tracked; keep reload() and the existing reload-window behavior unchanged.

Source: MCP tools

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

None yet

Development

Successfully merging this pull request may close these issues.

2 participants