8.3 KiB
8.3 KiB
type, status, project, date, tags
| type | status | project | date | tags | ||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| decision | accepted | MagNetFlix | 2026-10-29 |
|
ADR 002: Pipeline Invariants, Two-Stage Metadata, and Active Reconciliation
Context and Problem Statement
Following the initial architectural baseline established in ADR 001 and the implementation of the SQLite WAL engine, an interactive architectural review identified critical engineering gaps across several core subsystems:
- Protobuf Packaging & Build Reproducibility (
GAP-1): The stubs emitted bybufproducedModuleNotFoundError: No module named 'magnetflix'when imported due to nested package output paths, and generated stubs were excluded from git and static type checks. - Active-Job Concurrency (
GAP-2): Concurrent submissions for the same movie could race past application-level checks and insert duplicate active downloads due to the absence of a database-level uniqueness constraint. - Sanitizer Boundary Policy (
GAP-3): A documented contradiction existed between purging non-media files versus aborting the entire job if non-allowlisted files exist. Because ~95% of real-world torrents contain.nfoor.txtclutter, strict rejection causes widespread false-positive failures, while pure whitelisting ignores symlink/executable hazards. - Metadata Resolution Timing (
GAP-5): Fetching TMDB metadata only after download completion leaves the UI live dashboard blank during 30–60 minute downloads and wastes tens of gigabytes of bandwidth on invalid IMDb IDs. - Subtitle Relocation Collisions (
GAP-4): Hardcoding target subtitles to<Title> (<Year>).en.srtcorrupts non-SRT formats (.ass,.vtt) and causes silent overwrite collisions when multiple tracks exist. - Crash Recovery & Daemon State (
GAP-6): Simply marking SQLite rows asFAILEDon worker restart leaves orphaned torrent sessions actively downloading in the Transmission container and abandons scratch disks. - Async Concurrency & Blocking I/O (
GAP-7): Calling multi-gigabyteshutil.copy2transfers or synchronoustransmission-rpcrequests directly on Python's async event loop freezes gRPC RPCs and SSE streaming connections. - Pluggable SSO & Search Boundaries (
GAP-8): Hardcoding Authelia headers tightly coupled MagNetFlix to specific homelab infrastructure, and client-side scraping of undocumented IMDb endpoints created browser CORS and fragility risks.
Decision Outcome & Invariants
1. Dedicated Workspace Contracts Package (DEC-1)
- Stubs are generated once into a shared workspace package
services/contracts(module-name = "magnetflix"). - Both
workerandbffdepend onmagnetflix-contractsvia{ workspace = true }, allowing nativefrom magnetflix.v1 import pipeline_pb2, pipeline_pb2_grpcimports. - Generated stubs and
docs/api_spec.mdare committed to Git, enabling reproducible offline test and Docker builds.
2. Database Partial Unique Indexes & Normalized Info-Hash (DEC-2)
- Add an indexed column
info_hashtodownload_jobs, normalized to 40-character lowercase hex at ingestion (converting 32-character Base32urn:btih:hashes). - Add partial unique indexes in SQLite:
CREATE UNIQUE INDEX uq_download_jobs_active_imdb_id ON download_jobs (imdb_id) WHERE state NOT IN ('COMPLETED', 'FAILED'); CREATE UNIQUE INDEX uq_download_jobs_active_info_hash ON download_jobs (info_hash) WHERE info_hash IS NOT NULL AND state NOT IN ('COMPLETED', 'FAILED'); - Guaranteed engine-level deduplication: concurrent duplicate submissions (same active
imdb_idor same activeinfo_hash) fail withIntegrityError, mapped cleanly togrpc.StatusCode.ALREADY_EXISTS.
3. Two-Tier Sanitization Policy (DEC-3)
- Tier 1 (Hard Security Rejection): Immediate job abort to
FAILEDif the payload contains symbolic links (os.path.islink), hard links (st_nlink > 1), path traversal (..), special device nodes, or dangerous extensions (case-insensitive:.exe,.bat,.cmd,.sh,.scr,.vbs,.ps1,.lnk,.iso,.zip,.rar,.7z). - Tier 2 (Allowlist Extraction & Safe Discard): Extract allowlisted video (
.mkv,.mp4,.avi,.webm) and subtitles (.srt,.vtt,.sub,.ass). Safely ignore unlisted non-dangerous files (such as.nfo,.txt,.jpg,.sfv). Discard samples (< 100 MBor case-insensitive word-boundary"sample"token /Sampledirectory). Select the single largest remaining video file as the feature film.
4. Two-Stage Metadata Lifecycle (DEC-4)
- Stage 1 (Early Ingestion): Query TMDB API
/find/{imdb_id}?external_source=imdb_idat job submission/queueing time. Verify valid movie entity type; persisttitleandyearto SQLite immediately. Live UI and SSE streams display movie metadata from second 1. - Stage 2 (Post-Download Token Check): Compare cached
(title, year)tokens against primary video filename completely offline from SQLite without external network dependencies.
5. Multi-Track Subtitle Preservation, Path Sanitization & Two-Stage Atomic Swap (DEC-5)
- Deterministically sanitize
<Title>(stripping/replacing path-breaking characters such as/,\,:,*,?,",<,>,|, and..) before constructing directory and file paths. - Retain native allowlisted subtitle extensions (
.srt,.vtt,.sub,.ass). - Parse language and forced tags from filenames; omit the language tag if none is detected (
<SanitizedTitle> (<Year>).<ext>) and append disambiguation indices (<SanitizedTitle> (<Year>).en.1.srt) when multiple subtitles share tags to prevent overwrites. - Copy verified files across storage boundaries to
/media/movies/.staging_<job_id>/after checking free disk space. Pre-check destination existence, then atomically swap viaos.replace.
6. Active Reconciliation & Stalled Timeout (DEC-6)
- On worker startup, query all non-terminal SQLite jobs: transition state to
FAILED, actively call Transmission RPCremove_torrent(info_hash, delete_data=True)(with bounded startup retry/backoff while Transmission initializes), and purge scratch directories/data/staging/<job_id>/and/media/movies/.staging_<job_id>/. - Monitor swarm progress during
DOWNLOADING: auto-fail jobs with zero progress delta (unchanged downloaded bytes/progress or unresolved metadata) for 15 consecutive minutes.
7. Thread Offloading & In-Memory SSE Fan-Out (DEC-7)
- Dispatch blocking disk copies (
shutil.copy2) to a dedicated bounded relocation executor isolated from lightweighttransmission-rpccalls and directory scans so multi-GB transfers never starve swarm polling. - Database sessions are strictly short-lived (committed and closed before long I/O).
- Subscribe to the
asyncio.Queuepub/sub broker before reading the initial SQLite snapshot, using bounded per-subscriber queues with latest-state coalescing for connected gRPC/SSE streams.
8. Pluggable Identity Adapter & Server-Side Search (DEC-8)
- FastAPI BFF middleware reads identity headers via configurable environment variables (
AUTH_ENABLED,AUTH_HEADER_USER), failing closed with401 UnauthorizedwhenAUTH_ENABLED=trueand falling back tolocal_useronly whenAUTH_ENABLED=false. - Expose
GET /api/v1/movies/search?q=...proxying TMDB movie search server-side to eliminate CORS issues and undocumented third-party scraping, and support configurableCORS_ALLOWED_ORIGINSfor browser extension deployments. - Mount dual route bindings (
POST /api/v1/downloadsandPOST /download) with Pydantic aliases (magnet/magnet_uri,imdbid/imdb_id).
Consequences
Positive Consequences
- Guarantees 100% reproducible builds and eliminates
ModuleNotFoundErroracross all environments. - Protects the host and media library from malicious torrent payloads, path traversal, and partial writes.
- Eliminates zombie torrents and leaked staging disk space across container restarts.
- Maintains responsive gRPC and SSE streaming performance during multi-gigabyte disk transfers.
- Decouples MagNetFlix from specific reverse proxy or identity provider implementations.
Accepted Tradeoffs & Operational Costs
- Requires outbound TMDB API key access on both BFF (for movie search) and Worker (for metadata resolution).
- Requires temporary disk space on
/media/moviesto hold.staging_<job_id>/during cross-volume copying.