Adds architecture decision records for the media library scanning redesign

This commit is contained in:
BinaryAlley committed 2026-08-09 13:15:52 -07:00
1 parent 4d741be1ef
commit 7c7588dd7a
6 files changed
+276

No files matched your search

@@ -0,0 +1,45 @@
# Architecture Decision Record (ADR): 0004 - `LibraryScanSnapshots` Table and Database-Side Diff
## Status
**Accepted** (2026-08-08)
## Context
The media library scanning subsystem needs to compute, on every scan, which file system items are new, which are changed and which were deleted since the previous scan.
This approach has two fundamental problems at the target scale (millions of files):
1. **Memory**: loading the whole previous state into memory as Entity Framework tracked entities costs hundreds of megabytes to gigabytes, which risks out of memory crashes on long running scans.
2. **Accumulation**: `LibraryScanResults` stored one row per changed file per scan, growing unboundedly. The read query joined the whole accumulated table and grouped by path, degrading with every scan.
## Decision
A new table, `LibraryScanSnapshots`, keyed by `(LibraryId, Path)`, holds one row per media library item, representing the current state of every previously scanned media item. The previous state is therefore always available in the database, and the comparison between the files on disk and the previous state is performed with a single database-side diff (an `UPDATE ... FROM` in the staging results), instead of an in-memory join.
The `LibraryScanResults` table is retained for audit purposes only. It records one row per new, modified or deleted item per scan, with its status.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Memory bound | The previous state is never loaded wholesale into memory |
| Deletion handling | Snapshot items not present in the current scan are deleted and reported through `LibraryMediaItemDeletedDomainEvent` |
| Bounded table growth | The snapshot holds exactly one row per current media item |
| Incremental scans | Unchanged items are detected by size and last write time comparison, and are not re-hashed |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Snapshot staleness on failure | The snapshot swap is a single transaction, only committed when every scan job succeeded |
| Database-side diff portability| The diff uses `UPDATE ... FROM`, supported by SQLite 3.33 and newer |
## Alternatives Considered
### 1. Keep the in-memory dictionary, but make it compact
The previous state could be loaded as a `Dictionary<string, (ulong hash, long size, long ticks)>` with `AsNoTracking()` and compact struct values.
**Rejected**: It still keeps the peak memory proportional to the number of files, which is not safe at the target scale of millions of items.
### 2. History table with per-file tombstone rows
Deleted files would be marked with `LibraryScanFileStatus.Deleted` in `LibraryScanResults` and retained.
**Rejected**: It keeps stale rows around forever, contradicts the requirement of maintaining only a snapshot of the current state, and complicates the read path.
@@ -0,0 +1,43 @@
# Architecture Decision Record (ADR): 0005 - Permanent `LibraryScanStagingResults` Table, Cleaned per Scan
## Status
**Accepted** (2026-08-08)
## Context
The media library scan pipeline stages the file system items discovered during a scan before comparing them against the `LibraryScanSnapshots` table (ADR-0004). A staging store is needed that:
1. receives the discovered file system items in bounded batches,
2. is read by the diff, hash and metadata enrichment jobs,
3. is written by the discovery job and read by later jobs, which run in separate dependency injection scopes (see ADR-0001), hence on separate database connections.
A real SQLite `TEMP` table was considered, but SQLite `TEMP` tables are scoped to a single database connection. Because each media library scan job creates its own `AsyncServiceScope`, and therefore its own `LuminaDbContext` and connection (ADR-0001), a `TEMP` table created by the discovery job would be invisible to the diff job, which runs on a different connection. Making a `TEMP` table work would require pinning a single dedicated connection for the whole staging phase of a scan, a larger architectural carve-out.
## Decision
Use a permanent table, `LibraryScanStagingResults`, keyed by `(LibraryScanId, Path)`. Its rows are deleted at the end of the scan (as part of the snapshot swap transaction of the save job) and on scan failure or cancellation. Leftover rows of a crashed scan are inert, because every scan has a unique id, and can be purged by the audit cleanup job.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Connection safety | The table survives the per-job connection churn |
| Debuggability | The staging state can be inspected mid-scan |
| Cheap cleanup | Clearing is a single indexed `DELETE` per scan |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Leftover rows on process crash | They are inert (scan id is unique) and cleaned by the audit cleanup job |
| Extra table | Bounded at one row per discovered item per scan, cleared each scan |
## Alternatives Considered
### 1. SQLite `TEMP` table with a single pinned connection
The whole staging phase would hold one dedicated connection open, and all jobs would share it.
**Rejected**: It conflicts with the per-job scope model of ADR-0001, holds a database connection open for the entire scan duration, and makes the pipeline harder to compose and test.
### 2. In-memory staging (list of discovered items passed between jobs)
The discovery job would pass the full list of discovered items to the diff job.
**Rejected**: It brings back the unbounded memory problem that ADR-0004 eliminates. The staging table is what allows bounded, batched writes.
@@ -0,0 +1,50 @@
# Architecture Decision Record (ADR): 0006 - Dapper and SQLite WAL for Bulk Data Access in Scan Jobs
## Status
**Accepted** (2026-08-08)
## Context
The media library scan jobs perform bulk data operations that the Entity Framework Core change tracker is not suited for:
1. multi-row inserts of the discovered file system items into the staging results,
2. multi-row upserts of the scan snapshot,
3. indexed key-set paginated reads of the items that need hashing,
4. raw `DELETE` statements for pruning and clearing.
Bulk inserts through the EF Core change tracker are slow for hundreds of thousands of rows, because every entity is individually tracked and saved. At the target scale (millions of files), the scan pipeline needs a data access path that is not only fast, but also bounded in memory.
## Decision
Add the Dapper library to the DataAccess layer, and perform the bulk data operations of the scan jobs with parameterized raw SQL on a dedicated `Microsoft.Data.Sqlite` connection, derived from the connection string of the injected `LuminaDbContext`.
These operations never touch the Entity Framework change tracker. Reads that are not bulk (for example loading the media library entity) keep using EF Core, and bulk reads use unbuffered, key-set paginated queries to keep the peak memory bounded.
SQLite Write-Ahead Logging (`PRAGMA journal_mode=WAL`) and a busy timeout are enabled at API startup, so that the Entity Framework connection and the dedicated bulk connections of the scan jobs can access the database concurrently, without database locking errors.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Performance | Multi-row inserts and upserts are orders of magnitude faster than per-row EF Core inserts |
| Memory bound | Unbuffered, key-set paginated reads keep peak memory proportional to the batch size |
| Tracking safety | The bulk operations bypass the EF Core change tracker entirely |
| Concurrency | WAL allows one writer and multiple concurrent readers |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Raw SQL duplication | All raw SQL is confined to the two bulk repositories, behind the repository and unit of work abstractions |
| Concurrency errors | WAL and a busy timeout are enabled at startup, and the bulk operations run on dedicated connections |
| Layer integrity | Dapper is referenced only by the DataAccess layer |
## Alternatives Considered
### 1. EF Core `ExecuteSqlRaw` on the context connection
Bulk statements would run on the same connection as the tracked queries of the job.
**Rejected**: It couples the bulk operations to the lifetime of the EF Core context, and parameterized multi-row statements are considerably more verbose without a mapper.
### 2. Third party bulk library (for example EF Core bulk extensions)
A dedicated bulk extension library would abstract the raw SQL.
**Rejected**: Dapper is a small, widely adopted and dependency free mapper, and the amount of raw SQL is small and confined to two repositories. See the ADRs of the scan subsystem for the exact statements.
@@ -0,0 +1,49 @@
# Architecture Decision Record (ADR): 0007 - Opt-in Directory Fast Skip Using Directory Scan Fingerprints
## Status
**Accepted** (2026-08-08)
## Context
The default media library scan walks every directory and enumerates every file of the library on every scan. Even when unchanged files are not re-hashed (see `MediaLibraryScanDiffJob`), the walk itself is proportional to the total number of files. For libraries with tens of millions of files, the walk can dominate the scan duration.
A fast path that skips unchanged directories was considered. It is fundamentally based on directory metadata, which has two important limitations:
1. editing the contents of an existing file does not change the last write time of its containing directory,
2. a change deep inside a subtree does not propagate to the last write time of the ancestor directories.
Because of these limitations, the fast path can miss changes, and it must never be the default behavior of a scan.
## Decision
Add a `DirectoryScanFingerprints` table, keyed by `(LibraryId, Path)`, storing the last write time of each directory of a library. Add a `ShouldSkipUnchangedDirectoriesDuringScan` option to the `Library` aggregate, which is **off by default**.
When the option is enabled, the file system discovery job compares the last write time of every visited directory against the stored fingerprint. When they match, the entire subtree of that directory is skipped, and when they differ, or no fingerprint exists, the directory is walked and its fingerprint is updated.
The option is presented to the user with a descriptive text that explains its benefits and its risks, and it is documented here as well: the fast path relies on directory metadata, which does not change when existing files are edited, and does not propagate upward for changes that occur deep inside a subtree. It is only recommended for users that never modify existing files in place.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Scan duration | Unchanged subtrees are skipped with a single metadata stat per directory |
| User choice | The fast path is opt-in, the deterministic full walk remains the default |
| Existing behavior | Default scans keep the exact same semantics as before |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Missed in-place edits | Documented to the user, the option is off by default |
| Missed deep changes | Documented in this ADR and in the option description, the option is off by default |
| Coarse timestamp granularity | Some file systems store directory timestamps with a coarse resolution, documented as a limitation |
## Alternatives Considered
### 1. Full walk with per-file comparison only
No directory skipping at all; the walk enumerates every file, but only changed files are processed.
**Rejected as the default**: This is exactly the default behavior, but it does not reduce the cost of the walk itself.
### 2. Subtree-aggregate fingerprints
Store a fingerprint that aggregates the entire subtree of a directory, so any change anywhere bubbles up to the root.
**Rejected**: Computing a subtree aggregate requires walking the subtree, which defeats the purpose of the fast path.
@@ -0,0 +1,47 @@
# Architecture Decision Record (ADR): 0008 - Plugin Hook Points and the Media Library Scan Job Graph
## Status
**Accepted** (2026-08-08)
## Context
The media library scanning subsystem is meant to be modular: generic jobs, like the scan diff, hashing and results save jobs, are shared by all media library types, while media-type specific jobs, like the GoodReads metadata scrap job for books or a TMDB cover art job for movies, are decoupled and composed into a directed acyclic graph.
The job graph must remain fully capable of multi-parent relationships. Even though the default composition for books is linear (file system discovery, scan diff, hashing, optional metadata enrichment, scan results save), a plugin might inject jobs with several parents and children, and the base job model (`MediaLibraryScanJob` with `Parents`, `Children`, `AddChild` and `AddParent`) supports this.
Plugins should be injectable "at any sensible point" of the graph, not literally at any point. For example, a job that runs before the file system discovery has little meaning, because nothing is known about the library contents yet.
## Decision
Define named hook points for the scan job graph in `ScanJobHooks`: `AfterFileSystemDiscovery`, `AfterScanDiff`, `BeforeMetadataEnrichment`, `AfterMetadataEnrichment` and `BeforeScanResultsSave`.
Define the `IScanJobRegistry` interface, which maps a hook name to the plugin jobs registered at that hook. The media type scanners (for example `BookLibraryTypeScanner`) splice the plugin jobs returned by the registry into the graph at the corresponding hook points, preserving the parent-child relationships. The composition root of the plugin system provides the registry with the plugin job types; the default registry registers no plugin jobs.
The payload passing between jobs keeps the generic `ExecuteAsync<TInput>` contract. The core scan jobs are database-centric and ignore the payload, because they exchange the scan state through the staging and snapshot tables (ADR-0004, ADR-0005). Payload passing remains available for plugin jobs that need to exchange data in memory, and the runtime type switching that was used in the previous `HashComparerJob` is eliminated.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Modularity | Media-type specific jobs are composed per scanner |
| Extensibility | Plugins inject jobs at documented hook points |
| Multi-parent support | The base job model keeps full parent-child capabilities |
| Fail fast composition | Wrong payload wiring produces loud errors instead of silent no-ops |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Plugin job conflicts | Hook points are named and documented, the composition is validated when the graph is built |
| Payload contract misuse | Jobs that expect a payload fail loudly when the edge type does not match |
| Scope creep | Only the sensible hook points are defined, arbitrary injection is not supported |
## Alternatives Considered
### 1. Arbitrary injection at any junction, including before discovery
Allow plugins to attach anywhere in the graph without restriction.
**Rejected**: Several junctions are meaningless before the library contents are known. The named hook points cover the useful extension surface, and keep the composition understandable.
### 2. A full dataflow engine with typed edges between every pair of jobs
Rework the jobs into a generic pipeline engine where edges carry strongly typed channels.
**Rejected**: The database-centric jobs exchange state through the database, so a full in-memory typed dataflow engine would add complexity without benefit. The generic payload contract is retained for the plugin jobs that need it.
@@ -0,0 +1,42 @@
# Architecture Decision Record (ADR): 0009 - Failure Semantics of the Media Library Scan Jobs
## Status
**Accepted** (2026-08-08)
## Context
Media library scan jobs are launched in a fire-and-forget manner from the background job processor (`MediaLibraryScanJobProcessorJob`), because only the root jobs are placed on the in-memory queue, and they trigger their children recursively (see ADR-0001 and ADR-0008). The launch mechanism uses `FireAndForgetSafeAsync`, which observes the launched task but does not crash the queue consumer.
The scan jobs must report their failures through the existing eventual consistency mechanism, the `LibraryScanFailedDomainEvent`, whose handler marks the scan as failed, releases the scan processing resources and notifies the clients. The previous job implementations only published the failure event on a few specific error paths, so any other exception was silently swallowed, leaving the scan stuck in the `Running` state, leaking its cancellation source and progress entry.
## Decision
Keep the fire-and-forget launch mechanism. Every scan job wraps its execution in a catch-all that marks the job as `Failed` and publishes the `LibraryScanFailedDomainEvent`, carrying the exception message for diagnostics. `OperationCanceledException` keeps marking the job as `Canceled`.
The `LibraryScanFailedDomainEventHandler` and the `LibraryScanCancelledDomainEventHandler` now always release the scan processing resources, regardless of whether the scan was already marked as failed or cancelled by a concurrent job: the cancellation token source is removed from the cancellation tracker, the progress entry is removed from the progress tracker, and the staging results of the scan are cleared.
## Consequences
### Positive Outcomes
| Aspect | Benefit |
|-----------------------|-----------------------------------------------------------|
| Reliable failure | Every job failure is reported through the failure domain event |
| Resource cleanup | Cancellation sources, progress entries and staging rows are released on failure and cancellation |
| Eventual consistency | The handlers perform the cleanup, keeping the job code focused on scanning |
| Configurable actions | The failure event can drive further handlers (notifications, etc.) in the future |
### Risks and Tradeoffs
| Risk | Mitigation Strategy |
|-------------------------------|-------------------------------------------------------------------|
| Best-effort reporting | Failure reporting is wrapped defensively, so it never crashes the job processing |
| Duplicate cleanup | The cleanup operations are idempotent and tolerant of concurrent executions |
## Alternatives Considered
### 1. Await the whole job chain in the background processor
Change the processor to await the root job completion and observe its exceptions there.
**Rejected**: Awaiting long running job chains in the queue consumer would introduce blocking behavior in the processor.
### 2. Rethrow the exceptions to be swallowed by the fire-and-forget helper
Keep the current behavior of swallowing unexpected exceptions.
**Rejected**: It leaves scans stuck in the `Running` state and leaks resources, which the whole point of this decision is to fix.