Repository navigation
feat(ebooks): decouple metadata enrichment from scans via a durable queue - #433
Conversation
|
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. |
📝 WalkthroughWalkthroughThis 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. ChangesEbook enrichment architecture
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
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
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>
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>
4e4136c to
bd97f3c
Compare
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>
|
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 One real defect, fixed in 84cd0ac (pushed to this branch): legacy-lane rows (priority Also noted: the 🤖 Generated with Claude Code |
There was a problem hiding this comment.
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 winTest 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
📒 Files selected for processing (26)
cmd/silo/main.godocs/superpowers/plans/2026-07-19-ebook-enrichment-architecture.mddocs/superpowers/specs/2026-07-20-ebook-backfill-automation-design.mdinternal/ebooks/enrichment.gointernal/ebooks/enrichment_queue.gointernal/ebooks/enrichment_queue_test.gointernal/ebooks/enrichment_test.gointernal/libraryingest/executor.gointernal/libraryingest/executor_test.gointernal/scanner/ebook.gointernal/scanner/ebook_scan.gointernal/scanner/ebook_test.gointernal/scanner/scanner.gointernal/scanner/scanner_test.gointernal/scantrigger/scantrigger.gointernal/scantrigger/scantrigger_test.gointernal/server/frontend.gointernal/server/frontend_test.gointernal/taskmanager/tasks/sync_ebook_metadata.gointernal/taskmanager/tasks/sync_ebook_metadata_test.gomigrations/ebook_enrichment_reconcile_cursor_test.gomigrations/sql/20260719090000_ebook_enrichment_jobs.sqlmigrations/sql/20260719173000_ebook_enrichment_reconcile_cursor.sqlweb/src/lib/reloadOnPreloadError.test.tsweb/src/lib/reloadOnPreloadError.tsweb/src/main.tsx
| 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. |
There was a problem hiding this comment.
🎯 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.
| ## 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. |
There was a problem hiding this comment.
📐 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.
| 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 | ||
| } |
There was a problem hiding this comment.
🩺 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.
| 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.
| 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); |
There was a problem hiding this comment.
🩺 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.
| 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
| 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")); |
There was a problem hiding this comment.
🎯 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.
| 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(); |
There was a problem hiding this comment.
🩺 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; fiRepository: 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))
PYRepository: 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:
- 1: https://vite.dev/guide/build
- 2: https://vite.dev/guide/troubleshooting
- 3: https://vitejs-vite.mintlify.app/concepts/build-production
- 4: https://paulau.dev/blog/handle-version-skew-after-new-deployment-with-vite-and-vue-router/
- 5: I can't figure out 'vite:preloadError' vitejs/vite#15897
- 6:
vite:preloadErrorEvent is not being caught by the router if the error is thrown from inside the event listener TanStack/router#4410 - 7: Do not show full screen error dialog for syntax errors and HMR vitejs/vite#13220
- 8: failed CSS preloads prevent loading dependencies vitejs/vite#18042
- 9: fix(preload): allow ignoring dep errors vitejs/vite#18046
🏁 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.tsRepository: 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
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.
FOR UPDATE SKIP LOCKEDclaims, lease tokens with expiry, priority lanes: 0 for new/refresh work, -100 for the legacy backlog).SILO_EBOOK_RATE_LIMIT_COOLDOWN) — provider RetryInfo hints are request-pacing advice, not queue horizons.SILO_EBOOK_BACKFILL_MAX_CLAIMS,SILO_EBOOK_BACKFILL_BATCH_DELAY) remain for gradual rollouts.protected_fields.<book>.opfsidecars; 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)
Notes for review
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.scantrigger.ResolveVanishedPathnow resolves vanished video files to an exact-file scan (previously a parent-subtree scan);reconcileVanishedFileIfNeeded+syncVanishedVideoQueuesreproduce the old mark-missing/sweep/queue-sync behavior for that path.result_datagains 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=1pnpm exec vitest run src/lib/reloadOnPreloadError.test.tsmake verify-local-paths;go build ./...,go vet,gofmtcleanAI-use disclosure
Implemented and reviewed with Claude Code (multi-agent review pass + TDD throughout).
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes