diff --git a/CHANGELOG.md b/CHANGELOG.md index 096d909..c638351 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ All notable changes to DoplarrChaptarr Rust are documented here. +## Unreleased + +### Fixed + +- A request for an author's second format now configures that format before + searching. Chaptarr initializes author settings one format per add, so an + author created by `/request book` carries no audiobook quality profile, + metadata profile, or root folder — and an unconfigured format is a + disabled one, whose searches the server empties silently while every + monitor and edition read-back still passes. The author gate write now + fills any missing setting for the requested format and verifies all three + on the read-back, failing closed rather than queueing a search that can + never return a release. Existing values are never overwritten. +- Add bodies now carry only the requested format's root folder. Chaptarr's + existing-author progressive fill collapses both roots into one + audiobook-preferring parameter, so a body carrying both could write the + audiobook path into an unset ebook root. + +The write path stays beta: these are fixture-proven only and need the new +mutation case 13 (sequential cross-format, both directions) against a +disposable instance — see `docs/chaptarr/RELEASE_CHECKLIST.md`. + ## 4.6.1-chaptarr.1 - 2026-08-28 Fixes the new-author request failure observed live on 2026-07-15. The old bot diff --git a/docs/chaptarr/COMPATIBILITY.md b/docs/chaptarr/COMPATIBILITY.md index 3f12176..6ade3de 100644 --- a/docs/chaptarr/COMPATIBILITY.md +++ b/docs/chaptarr/COMPATIBILITY.md @@ -268,6 +268,90 @@ name/path substring inference are gone. A root with `accessible: false` is never selectable. Do not expose a local root path in a Discord message or public issue report. +## Author settings are per-format and lazily initialized + +`POST /book` configures exactly one format per call, by design. The +controller keeps both formats' fields from the nested `author` +(`BookController.cs:1740-1779` nulls a side only when its quality profile id +is absent), but the add path then collapses to the single requested +`mediaType` — `CreateAudiobook = isAudiobook; CreateEbook = !isAudiobook` +(`AddBookService.cs:492-501`) — and every per-format assignment on the +persisted author is gated on those flags +(`AuthorLibraryService.cs:1700-1780`). The sibling format's five fields +(`{format}QualityProfileId`, `{format}MetadataProfileId`, +`{format}RootFolderPath`, `{format}MonitorExisting`, `{format}MonitorFuture`) +are accepted on the wire and silently discarded; they persist NULL, which +the model documents as "not configured for this media type yet" +(`Author.cs:42`). The intent is explicit repo-wide: the root-folder +defaulter refuses to fill the sibling (`AuthorLibraryService.cs:1845-1847`), +a fixture asserts the sibling stays null +(`AuthorLibraryServiceRootFolderInheritanceFixture.cs:370-393`), and the +first-party UI never sends sibling fields on an add — its "both formats" +option issues two sequential `POST /book` calls +(`frontend/src/Utilities/Author/getNewAuthor.js:66,90`, +`frontend/src/Store/Actions/searchActions.js:929-931`). Confirmed live +(production, 2026-08-29): a new author created by an ebook request persisted +only the ebook settings although the add body carried both formats'. + +An unconfigured format is a **disabled** format, with three consequences: + +- A `BookSearch` for a row of that format returns zero decisions when the + author has no quality profile for it — Debug log only, the command still + completes as an ordinary no-op + (`ReleaseSearchService.cs:106-113,154-166`). An acknowledged search is + therefore not proof the format is searchable. +- A missing metadata profile excludes that format's remote books at refresh + and **prunes unprotected local rows**, logged at Info: + `[METADATA-PROFILE] No {format} metadata profile configured for author + '…'. Treating {format}s as disabled …` + (`RefreshAuthorService.cs:697-704`). Edition-pinned books stay + un-prunable (`EditionPinPolicy.cs:20`). +- When the server resolves an add of that format to an existing local row, + it rejects the add with a validation error naming the missing metadata + profile (`AddBookService.cs:226-241`). + +Three server paths do configure a missing format later: + +- **The existing-author catalog add** (`POST /book` when the server has no + local row for the work, `AddBookService.cs:126-129`) progressively fills + the requested format's profiles and monitor fields, fill-only, never + overwriting (`AuthorLibraryService.cs:1044,1126-1137` → + `AuthorService.cs:677-765`). **Root-path landmine:** the call collapses + both roots into one parameter preferring audiobook + (`AuthorLibraryService.cs:1136-1137`), and the fill writes that single + value into whichever format it is configuring + (`AuthorService.cs:714-719,751-757`) — an ebook add whose body carries + both roots therefore writes the **audiobook** root into an unset + `EbookRootFolderPath`. **Every** add body must carry only the requested + format's root, the new-author body included: an add for an author the + server already has routes here regardless of what the client believed + (`AddBookService.cs:126-129` → `AuthorLibraryService.cs:1044`), so a + new-author body carrying both roots reaches the same collapse. +- **The local-row dedupe branch** fills both formats per-format-correctly, + each gated on that format's profile id and root both being present in + the body (`AddBookService.cs:186-224`), before the disabled-format + rejection above is evaluated. +- **`PUT /author/{id}`** applies per-format profile ids only when present + and positive — they can never be cleared this way — but copies **both + root paths unconditionally** (`Author.cs:278-308,329-330`): a body + omitting a configured root silently wipes it, and validation does not + catch a blank path (`AuthorService.cs:890-893`). The author write must + stay a full GET → mutate → PUT round-trip. When a root path is set and + that format's profiles are missing, the update auto-fills them from the + root folder's defaults (`AuthorService.cs:642,909-954`). + +Contract consequences: no client may assume the new-author body's +sibling-format settings persisted (they did not), and a sequential +cross-format request against an author created by the other format is safe +only through a path that actually configures the requested format. When the +requested-format row already exists locally, the pipeline performs no add, +so nothing on that path initializes the settings while every monitor and +edition read-back still passes and the acknowledged `BookSearch` is +silently empty. `GET /author/{id}` serializes the per-format profile ids +(`AuthorResource.cs:134-138`), so the author gate write is where the +requested format's settings are filled and verified (safe sequence step 9) +— the only step that can catch that vacuous success. + ## Book rows - `id` and `authorId` identify the local row and parent author; `mediaType` is @@ -569,12 +653,18 @@ every silent-write-prone step is more important than minimizing GETs. Short-circuit an available work or a fully consistent active request. A bare monitor flag is not proof a search was queued; partial state is carried forward for repair. -5. If the author is new, `POST /book` with both roots, all four per-format - profile ids, an explicit `mediaType`, every book-level monitor flag false, - only the requested format's `*MonitorFuture` gate true, and search-on-add - false. If the author exists but the work does not, post the selected work - with the local `authorId` and a neutral requested-format edition - placeholder (free-text lookup editions are never carried into writes). +5. Add bodies carry **only the requested format's root** and all four + per-format profile ids. A body carrying both roots routes the audiobook + root into an unset ebook root through the server's progressive fill, and + an add for an author the server already has reaches that fill whether or + not the client thought the author was new (see "Author settings are + per-format and lazily initialized"). If the author is new, `POST /book` + with that root, an explicit `mediaType`, every book-level monitor flag + false, only the requested format's `*MonitorFuture` gate true, and + search-on-add false. If the author exists but the work does not, post the + selected work with the local `authorId` and a neutral requested-format + edition placeholder (free-text lookup editions are never carried into + writes). 6. After any add, wait for the catalog to settle (see "Catalog settling"). 7. Resolve the target row: identity match (exact `foreignBookId`, title tier only when the selection has no work id), format-bound, multi-book titles @@ -584,8 +674,14 @@ every silent-write-prone step is more important than minimizing GETs. edition via `readingFormatId` (English preferred, junk demoted, projected edition honored). No usable edition stops with an actionable error and a log of what the server offered. -9. Read the author; enable and re-verify the requested format's - `*MonitorFuture` gate if needed. +9. Read the author; verify the requested format's quality profile id, + metadata profile id, and root folder path are configured, filling any + that are missing through the same full-resource `PUT /author/{id}` + (never a partial body — root paths copy unconditionally) and re-reading + them; then enable and re-verify the requested format's `*MonitorFuture` + gate if needed. Fail closed if a filled setting does not persist: an + unconfigured format silently empties every search and prunes unpinned + local rows on refresh. 10. Select the edition with `PUT /book/{id}` (complete body, `anyEditionOk: false`, exactly one `monitored: true, manualAdd: true` edition). diff --git a/docs/chaptarr/RELEASE_CHECKLIST.md b/docs/chaptarr/RELEASE_CHECKLIST.md index b439cc3..34c3945 100644 --- a/docs/chaptarr/RELEASE_CHECKLIST.md +++ b/docs/chaptarr/RELEASE_CHECKLIST.md @@ -73,6 +73,15 @@ Run each case once and inspect Chaptarr after every step: confirm it rejects ebook rows, never changes the author's monitor gates, and that with the gate closed its `searchForNewBook` search is filtered out while an explicit `POST /command BookSearch` is not. +13. Sequential cross-format on one author, both directions: create a new + author via `/request book` and later request an audiobook under it + (the same work and a different work), then mirror the direction with + another new author (`/request audiobook` first, `/request book` + second). Restart the bot between the first and second request at least + once. Chaptarr initializes author settings per format lazily + (`COMPATIBILITY.md`, "Author settings are per-format and lazily + initialized"), so the second request is what proves the + missing-format initialization path. For every case, verify: @@ -98,7 +107,23 @@ For every case, verify: mutation; - no code path queued `RefreshAuthor` at any point; - a sparse-metadata row was treated as ordinary requestable data, never as an - "unresolved placeholder". + "unresolved placeholder"; +- (case 13) after the first request the author record carries only that + format's settings — the sibling's profile ids and root keys are absent, + per the lazy-initialization contract; +- (case 13) after the second request the author's requested-format quality + profile id, metadata profile id, and root folder path read back equal to + the resolved configuration — in particular the ebook root equals the + configured **ebook** root, never the audiobook path (the + progressive-fill root collapse); +- (case 13) the first format's settings, monitored edition, and files are + unchanged, no duplicate author exists, and each request queued exactly + one acknowledged search. + +Assert case 13 against the author record (`GET /author/{id}`), not the +search outcome: on a zero-indexer instance an acknowledged `BookSearch` is +indistinguishable from one `ReleaseSearchService` silently empties for a +missing author quality profile. ## Sprint 1 write-path changes to prove live @@ -163,6 +188,27 @@ Nothing in this sprint graduates the write path out of beta; that requires this checklist's mutation proof against a disposable 0.9.936 instance — now recorded in `docs/chaptarr/canary/2026-08-28-0.9.936.md`. +## Cross-format sequential settings to prove live + +Open as of 2026-08-29. The 2026-08-28 canary's case 4 verified monitoring, +edition selection, and search acknowledgement on a cross-format second +request, but never read the author's per-format settings — and its +zero-indexer instance could not have surfaced the silent search-emptying +that a missing author quality profile causes. Source analysis +(`COMPATIBILITY.md`, "Author settings are per-format and lazily +initialized") has since established that Chaptarr persists only the +requested format's author settings per add, that a second-format request +heals settings only when it triggers an actual `POST /book` (the +progressive fill), and that the fill's single root parameter prefers the +audiobook path. The bot side has since landed: the author gate write fills +and read-back-verifies the requested format's quality profile, metadata +profile, and root folder (fail-closed), add bodies carry only the requested +format's root, and the canary driver now asserts both the requested +format's configuration and the sibling's settings being unchanged. All of +that is fixture-proven only. The next canary must run mutation case 13 in +both directions before any release claims the sequential cross-format +path. + ## Promotion record Save a sanitized release note with the versions, digest, cases run, results and diff --git a/docs/chaptarr/promotion/4.6.1-chaptarr.1.md b/docs/chaptarr/promotion/4.6.1-chaptarr.1.md index 5171739..b177399 100644 --- a/docs/chaptarr/promotion/4.6.1-chaptarr.1.md +++ b/docs/chaptarr/promotion/4.6.1-chaptarr.1.md @@ -45,6 +45,29 @@ No image or tag moves with this record. The previous production deployment target; the disposable canary instance was destroyed after the run and verified gone. +## Known issue found after publication (2026-08-29) + +The published build does not configure a second format's author settings. +Chaptarr initializes them one format per add, so an author created by +`/request book` carries no audiobook quality profile, metadata profile, or +root — and an unconfigured format is a disabled one, whose searches the +server empties silently. In this build a later `/request audiobook` for +that author heals the settings only when it triggers an actual `POST /book` +(the server's own progressive fill). When the audiobook row already exists +no add fires, every monitor and edition read-back still passes, and the +acknowledged `BookSearch` can never return a release. The same build also +sends both formats' roots in existing-author add bodies, which the server's +progressive fill can route into the wrong format's root. + +Neither is a regression from the Clojure bot and neither affects +single-format use, which is what the canary and the first production run +exercised. Fixed on `chaptarr-cross-format-settings` (author gate write +fills and verifies the requested format's settings, fail-closed; add bodies +carry only the requested format's root); the fix is fixture-proven only and +needs mutation case 13 live before the next release claims the sequential +cross-format path. Contract: `docs/chaptarr/COMPATIBILITY.md`, "Author +settings are per-format and lazily initialized". + ## Remaining before beta graduation (Elisha-only) - [ ] Read-only interaction proof (real Discord bot, real guild, diff --git a/docs/chaptarr/upstream-issues/progressive-settings-root-folder-collapse.md b/docs/chaptarr/upstream-issues/progressive-settings-root-folder-collapse.md new file mode 100644 index 0000000..3457720 --- /dev/null +++ b/docs/chaptarr/upstream-issues/progressive-settings-root-folder-collapse.md @@ -0,0 +1,69 @@ +# Existing-author progressive settings collapse both root folders into one parameter, preferring audiobook + +Verified against v0.9.936 (develop @ 423b1bb). + +## Summary + +Thanks for Chaptarr. We build a Discord request bot against the v1 API. When +`POST /api/v1/book` adds a work under an existing author through the catalog +path, `ApplyExistingAuthorProgressiveSettings` hands +`UpdateAuthorProgressiveSettings` a single root-folder path shared by both +formats, computed as `config.AudiobookRootFolderPath ?? +config.EbookRootFolderPath`. The progressive fill then writes that one value +into whichever format it is configuring. An ebook add whose nested `author` +carries both formats' root paths therefore persists the **audiobook** root +as the author's `EbookRootFolderPath`, and later ebook imports for that +author organize into the audiobook library. + +The inline comment acknowledges the collapse ("Single path param: prefer +audiobook path if present else ebook"). The dedupe branch in +`AddBookService` does not have the defect — it calls the same method once +per format and passes each format's own root. + +## Reproduction sketch + +1. An author exists configured for audiobooks only (created by an + audiobook-only add — the intended lazy per-format initialization). +2. `POST /api/v1/book?mediaType=ebook` for a work with no local row, the + nested `author` carrying `ebookQualityProfileId`, `ebookRootFolderPath`, + and — as a client reusing one author payload naturally does — the + audiobook fields as well. +3. `BuildRequestedBookMonitoringConfig` copies both roots into the config; + `CreateEbook = true`, `CreateAudiobook = false`. The per-format profile + arguments for audiobook are nulled by the `CreateAudiobook` gates, but + the shared root parameter is not gated and resolves to the audiobook + path. +4. Inside `UpdateAuthorProgressiveSettings`, the ebook block runs (its + quality profile id is present), finds `EbookRootFolderPath` unset, and + fills it with the shared parameter — the audiobook root. + +## Source citations (file:line, verified) + +- `src/NzbDrone.Core/Books/Services/AuthorLibraryService.cs:1126-1137` — + the call site; line 1137 collapses both roots with the + audiobook-preferring `??` under the "Single path param" comment. +- `src/NzbDrone.Core/Books/Services/AuthorService.cs:677-765` — + `UpdateAuthorProgressiveSettings`; the ebook block writes the shared + `rootFolderPath` parameter into `EbookRootFolderPath` at `:751-757` + (audiobook mirror at `:714-719`). +- `src/NzbDrone.Core/Books/Services/AddBookService.cs:492-512` — + `BuildRequestedBookMonitoringConfig` copies both formats' roots into the + config ungated, so the collapse point sees both. +- `src/NzbDrone.Core/Books/Services/AddBookService.cs:186-224` — the + dedupe branch calling the same method with each format's own root + (`:205`, `:222`), showing the intended per-format shape. + +## Suggested fix + +Pass both roots through — either two parameters or one call per format, as +the dedupe branch already does — and fill each format only from its own +root. + +## Workaround + +A client can avoid the wrong-root fill by sending only the requested +format's root path in every add body, so the `??` never has a sibling path +to prefer. It has to be every body, not just the ones the client believes +are for an existing author: an add for an author the server already has +routes through this same path whatever the client assumed +(`AddBookService.cs:126-129` → `AuthorLibraryService.cs:1044`). diff --git a/doplarr/src/bin/chaptarr_canary.rs b/doplarr/src/bin/chaptarr_canary.rs index afa1489..cc1b068 100644 --- a/doplarr/src/bin/chaptarr_canary.rs +++ b/doplarr/src/bin/chaptarr_canary.rs @@ -60,6 +60,13 @@ impl Format { } } + fn other_format(self) -> Format { + match self { + Format::Ebook => Format::Audiobook, + Format::Audiobook => Format::Ebook, + } + } + /// `readingFormatId` values per the compatibility contract: 2 = audio, /// 3 = ebook, 1 = physical (never selectable). fn reading_format_id(self) -> i64 { @@ -310,6 +317,28 @@ fn field_id(value: &Value) -> Option { value.get("id").and_then(Value::as_i64).filter(|id| *id > 0) } +fn field_profile(value: &Value, key: &str) -> Option { + value.get(key).and_then(Value::as_i64).filter(|id| *id > 0) +} + +/// One format's author-level settings. Chaptarr configures these per format +/// and omits them until that format's first add, and an unconfigured format +/// is a disabled one: its searches are silently emptied server-side. A +/// request that reports success while these are absent is a vacuous success, +/// which no monitor or edition read-back can catch. +#[derive(Debug, Clone, PartialEq)] +struct FormatSettings { + quality: Option, + metadata: Option, + root: String, +} + +impl FormatSettings { + fn configured(&self) -> bool { + self.quality.is_some() && self.metadata.is_some() && !self.root.trim().is_empty() + } +} + #[derive(Debug, Clone, PartialEq)] struct AuthorGates { name: String, @@ -317,6 +346,24 @@ struct AuthorGates { ebook_future: bool, audiobook_future: bool, add_options_present: bool, + ebook: FormatSettings, + audiobook: FormatSettings, +} + +impl AuthorGates { + fn settings(&self, format: Format) -> &FormatSettings { + match format { + Format::Ebook => &self.ebook, + Format::Audiobook => &self.audiobook, + } + } + + fn other_settings(&self, format: Format) -> &FormatSettings { + match format { + Format::Ebook => &self.audiobook, + Format::Audiobook => &self.ebook, + } + } } struct Snapshot { @@ -340,6 +387,16 @@ async fn take_snapshot(api: &RawApi) -> Result { ebook_future: field_bool(author, "ebookMonitorFuture"), audiobook_future: field_bool(author, "audiobookMonitorFuture"), add_options_present: author.get("addOptions").is_some(), + ebook: FormatSettings { + quality: field_profile(author, "ebookQualityProfileId"), + metadata: field_profile(author, "ebookMetadataProfileId"), + root: field_str(author, "ebookRootFolderPath"), + }, + audiobook: FormatSettings { + quality: field_profile(author, "audiobookQualityProfileId"), + metadata: field_profile(author, "audiobookMetadataProfileId"), + root: field_str(author, "audiobookRootFolderPath"), + }, }, ); let rows = api.get(&format!("/book?authorId={id}")).await?; @@ -589,6 +646,38 @@ async fn verify_request( "author addOptions is spent (settle latch observed)", ); + // Per-format settings: an acknowledged BookSearch proves nothing about + // them, because Chaptarr empties the search server-side when the + // author's requested-format quality profile is missing. On a + // zero-indexer instance that is indistinguishable from an ordinary + // no-op, so the author record is the only place this can be checked. + let requested_settings = gates.settings(format); + if expected_new_searches > 0 { + report.check( + requested_settings.configured(), + &format!( + "author {author_id} is configured for {format:?}: quality={:?} metadata={:?} root={}", + requested_settings.quality, + requested_settings.metadata, + if requested_settings.root.trim().is_empty() { + "MISSING" + } else { + "set" + } + ), + ); + } + // The other format's settings must survive untouched - including its + // root, which the server's progressive fill can overwrite with this + // format's path when an add body carries both roots. + if let Some(prior) = before.authors.get(&author_id) { + let other_now = gates.other_settings(format); + report.check( + other_now == prior.other_settings(format), + &format!("unrequested {:?} settings unchanged", format.other_format()), + ); + } + // Commands first: the new BookSearch names the target row. The // canonical row's title can legitimately differ from the lookup's // (drift normalization plus edition-driven retitling, both observed diff --git a/doplarr/src/providers/chaptarr.rs b/doplarr/src/providers/chaptarr.rs index 40ed522..4f698cd 100644 --- a/doplarr/src/providers/chaptarr.rs +++ b/doplarr/src/providers/chaptarr.rs @@ -800,6 +800,22 @@ impl Chaptarr { /// This full-resource PUT cannot re-arm or disarm the settle latch: /// the update path unconditionally restores the stored `AddOptions` /// (`AuthorResource.cs:571-573`, `AuthorService.cs:634-636`). + /// Enable the requested format's author gate, configuring the format + /// first when the author has never carried its settings. + /// + /// Chaptarr initializes author settings one format per add + /// (`AddBookService.cs:492-501`, `AuthorLibraryService.cs:1700-1780`), + /// so an author created by the other format's request reaches here + /// unconfigured - and an unconfigured format is a *disabled* format: + /// its searches are silently emptied (`ReleaseSearchService.cs:106-113`) + /// and its unpinned rows are pruned on refresh + /// (`RefreshAuthorService.cs:697-704`). Every monitor and edition + /// read-back still passes in that state, so this is the only step that + /// can catch it. + /// + /// The write stays a full GET-mutate-PUT round-trip: `PUT /author/{id}` + /// copies both root paths unconditionally (`Author.cs:329-330`), so a + /// partial body would wipe the format the author already had. async fn enable_author_format(&self, author_id: i64) -> Result<()> { let endpoint = format!("/author/{author_id}"); let mut author: Value = self.get(&endpoint, &[]).await?; @@ -807,12 +823,36 @@ impl Chaptarr { ChaptarrFormat::Ebook => "ebookMonitorFuture", ChaptarrFormat::Audiobook => "audiobookMonitorFuture", }; - if author.get(flag).and_then(Value::as_bool) == Some(true) { + let (quality_key, metadata_key, root_key) = format_setting_keys(self.format); + let s = &self.settings; + let (quality, metadata, root) = match self.format { + ChaptarrFormat::Ebook => (s.ebook_quality, s.ebook_metadata, &s.ebook_root), + ChaptarrFormat::Audiobook => { + (s.audiobook_quality, s.audiobook_metadata, &s.audiobook_root) + } + }; + // Fill-only, mirroring the server's own progressive semantics + // (`AuthorService.cs:677-765`): a profile or root already on the + // author was chosen deliberately and outranks this bot's config. + let missing_quality = positive_id(author.get(quality_key)).is_none(); + let missing_metadata = positive_id(author.get(metadata_key)).is_none(); + let missing_root = string_at(&author, root_key).trim().is_empty(); + let gate_open = author.get(flag).and_then(Value::as_bool) == Some(true); + if gate_open && !missing_quality && !missing_metadata && !missing_root { return Ok(()); } let object = author .as_object_mut() .context("Chaptarr returned an invalid author")?; + if missing_quality { + object.insert(quality_key.into(), json!(quality)); + } + if missing_metadata { + object.insert(metadata_key.into(), json!(metadata)); + } + if missing_root { + object.insert(root_key.into(), json!(root)); + } object.insert(flag.into(), Value::Bool(true)); object.insert("monitored".into(), Value::Bool(true)); self.send_json(Method::PUT, &endpoint, &author).await?; @@ -823,6 +863,15 @@ impl Chaptarr { format_name(self.format) ))); } + if positive_id(verified.get(quality_key)).is_none() + || positive_id(verified.get(metadata_key)).is_none() + || string_at(&verified, root_key).trim().is_empty() + { + bail!(UserFacingError(format!( + "Chaptarr did not keep this author's {} settings, so no search was queued.", + format_name(self.format) + ))); + } Ok(()) } @@ -832,7 +881,14 @@ impl Chaptarr { ChaptarrFormat::Ebook => &s.ebook_root, ChaptarrFormat::Audiobook => &s.audiobook_root, }; - json!({ + // Only the requested format's root is ever sent. A server-side add + // that lands on an existing author feeds both roots through one + // audiobook-preferring parameter + // (`AuthorLibraryService.cs:1136-1137` -> `AuthorService.cs:714,751`), + // so a body carrying both writes the audiobook path into an unset + // `EbookRootFolderPath`. The sibling format's settings are the + // server's to configure on that format's own first request. + let mut body = json!({ "title": item.book.title, "foreignBookId": item.book.foreign_book_id, "mediaType": format_name(self.format), @@ -852,8 +908,6 @@ impl Chaptarr { "ebookMetadataProfileId": s.ebook_metadata, "audiobookMetadataProfileId": s.audiobook_metadata, "rootFolderPath": chosen_root, - "ebookRootFolderPath": s.ebook_root, - "audiobookRootFolderPath": s.audiobook_root, "ebookMonitorFuture": self.format == ChaptarrFormat::Ebook, "audiobookMonitorFuture": self.format == ChaptarrFormat::Audiobook, "monitored": true, @@ -861,7 +915,10 @@ impl Chaptarr { "addOptions": {"monitor": "none", "searchForMissingBooks": false} }, "addOptions": {"searchForNewBook": false} - }) + }); + let (_, _, root_key) = format_setting_keys(self.format); + body["author"][root_key] = json!(chosen_root); + body } fn existing_author_book_body(&self, item: &ChaptarrItem, author: &Value) -> Result { @@ -925,7 +982,11 @@ impl Chaptarr { ChaptarrFormat::Ebook => &s.ebook_root, ChaptarrFormat::Audiobook => &s.audiobook_root, }; - Ok(json!({ + // Only the requested format's root is sent; see `new_author_body`. + // This is the body that actually reaches the server's progressive + // fill, so the sibling root's absence is what keeps an ebook request + // from writing the audiobook path into `EbookRootFolderPath`. + let mut body = json!({ "id": 0, "localBookId": null, "authorId": author_id, @@ -951,12 +1012,13 @@ impl Chaptarr { "ebookQualityProfileId": s.ebook_quality, "audiobookQualityProfileId": s.audiobook_quality, "ebookMetadataProfileId": s.ebook_metadata, - "audiobookMetadataProfileId": s.audiobook_metadata, - "ebookRootFolderPath": s.ebook_root, - "audiobookRootFolderPath": s.audiobook_root + "audiobookMetadataProfileId": s.audiobook_metadata }, "addOptions": {"searchForNewBook": false} - })) + }); + let (_, _, root_key) = format_setting_keys(self.format); + body["author"][root_key] = json!(chosen_root); + Ok(body) } async fn already_requested(&self, item: &ChaptarrItem) -> Result> { @@ -1079,6 +1141,25 @@ impl Chaptarr { } } +/// The author-level quality profile, metadata profile, and root folder keys +/// for one format. Chaptarr configures these per format and omits them until +/// that format's first add (`AuthorResource.cs:43-66`, `Author.cs:42`), so an +/// absent key means the format is unconfigured, not that the author is new. +fn format_setting_keys(format: ChaptarrFormat) -> (&'static str, &'static str, &'static str) { + match format { + ChaptarrFormat::Ebook => ( + "ebookQualityProfileId", + "ebookMetadataProfileId", + "ebookRootFolderPath", + ), + ChaptarrFormat::Audiobook => ( + "audiobookQualityProfileId", + "audiobookMetadataProfileId", + "audiobookRootFolderPath", + ), + } +} + fn command_references_book(command: &Value, book_ids: &[i64]) -> bool { [command.get("body"), Some(command)] .into_iter() @@ -1918,6 +1999,343 @@ mod tests { assert!(!body.to_string().contains("booksToMonitor")); } + fn ebook_only_author() -> Value { + // The shape Chaptarr persists for an author created by an ebook + // request: the add's audiobook fields are accepted and discarded + // (AddBookService.cs:492-501, AuthorLibraryService.cs:1700-1780), so + // the audiobook keys are absent entirely (nulls are omitted). + json!({ + "id": 7001, + "authorName": "Mara Vale", + "foreignAuthorId": "hc:author-1001", + "monitored": true, + "ebookMonitorFuture": true, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks" + }) + } + + fn author_with_both_formats() -> Value { + let mut author = ebook_only_author(); + let object = author.as_object_mut().unwrap(); + object.insert("audiobookMonitorFuture".into(), json!(true)); + object.insert("audiobookQualityProfileId".into(), json!(12)); + object.insert("audiobookMetadataProfileId".into(), json!(22)); + object.insert( + "audiobookRootFolderPath".into(), + json!("/library/audiobooks"), + ); + author + } + + #[tokio::test] + async fn a_missing_requested_format_setting_is_filled_and_verified_on_the_author_gate() { + // The sequential cross-format case: an author created by /request + // book carries no audiobook settings, and an unconfigured format is + // a disabled format - ReleaseSearchService.cs:106-113 silently + // empties its searches, so the gate write must carry the settings. + let responses = vec![ + ebook_only_author().to_string(), + "{}".to_string(), + author_with_both_formats().to_string(), + ]; + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Audiobook); + chaptarr.base_url = base_url; + + chaptarr.enable_author_format(7001).await.unwrap(); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + + let recorded = requests.lock().await; + let lines: Vec<_> = recorded + .iter() + .map(|request| request_line(request)) + .collect(); + assert_eq!( + lines, + vec![ + "GET /api/v1/author/7001 HTTP/1.1", + "PUT /api/v1/author/7001 HTTP/1.1", + "GET /api/v1/author/7001 HTTP/1.1", + ] + ); + let put = &recorded[1]; + assert!(put.contains("\"audiobookQualityProfileId\":12"), "{put}"); + assert!(put.contains("\"audiobookMetadataProfileId\":22"), "{put}"); + assert!( + put.contains("\"audiobookRootFolderPath\":\"/library/audiobooks\""), + "{put}" + ); + assert!(put.contains("\"audiobookMonitorFuture\":true"), "{put}"); + // PUT /author/{id} copies both root paths unconditionally + // (Author.cs:329-330), so the write stays a full round-trip: the + // ebook side the first request configured must survive intact. + assert!( + put.contains("\"ebookRootFolderPath\":\"/library/ebooks\""), + "{put}" + ); + assert!(put.contains("\"ebookQualityProfileId\":11"), "{put}"); + assert!(put.contains("\"ebookMetadataProfileId\":21"), "{put}"); + } + + #[tokio::test] + async fn requested_format_settings_that_do_not_persist_fail_closed() { + // The read-back is the only proof: an author gate can flip while the + // format stays unconfigured, and that combination reports success + // while every search it queues is silently empty. + let mut half_written = author_with_both_formats(); + half_written + .as_object_mut() + .unwrap() + .remove("audiobookMetadataProfileId"); + let responses = vec![ + ebook_only_author().to_string(), + "{}".to_string(), + half_written.to_string(), + ]; + let (base_url, _requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Audiobook); + chaptarr.base_url = base_url; + + let error = chaptarr.enable_author_format(7001).await.unwrap_err(); + assert!( + error + .downcast_ref::() + .is_some_and(|user| user.0.contains("audiobook settings")), + "expected a settings failure, got: {error:#}" + ); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + } + + #[tokio::test] + async fn a_fully_configured_author_needs_no_gate_write() { + let responses = vec![author_with_both_formats().to_string()]; + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Audiobook); + chaptarr.base_url = base_url; + + chaptarr.enable_author_format(7001).await.unwrap(); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + + let recorded = requests.lock().await; + assert_eq!(recorded.len(), 1); + } + + #[tokio::test] + async fn an_admin_chosen_profile_is_never_overwritten_by_the_gate_write() { + // Fill-only, mirroring the server's own progressive semantics: a + // profile someone set for this author deliberately outranks config. + let mut admin_chosen = ebook_only_author(); + admin_chosen + .as_object_mut() + .unwrap() + .insert("audiobookQualityProfileId".into(), json!(99)); + let mut verified = admin_chosen.clone(); + let object = verified.as_object_mut().unwrap(); + object.insert("audiobookMonitorFuture".into(), json!(true)); + object.insert("audiobookMetadataProfileId".into(), json!(22)); + object.insert( + "audiobookRootFolderPath".into(), + json!("/library/audiobooks"), + ); + let responses = vec![ + admin_chosen.to_string(), + "{}".to_string(), + verified.to_string(), + ]; + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Audiobook); + chaptarr.base_url = base_url; + + chaptarr.enable_author_format(7001).await.unwrap(); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + + let recorded = requests.lock().await; + let put = &recorded[1]; + assert!(put.contains("\"audiobookQualityProfileId\":99"), "{put}"); + assert!(!put.contains("\"audiobookQualityProfileId\":12"), "{put}"); + } + + #[tokio::test] + async fn a_second_format_request_configures_the_format_before_searching() { + // The sequential cross-format case end to end: the author was + // created by /request book, the audiobook row already exists, and no + // add fires - so the author gate write is the only step that can + // configure audiobooks. Without it every read-back below still + // passes and the acknowledged BookSearch is silently empty. + let audiobook_row = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "gr:work-1001", + "mediaType": "audiobook", + "monitored": false, + "audiobookMonitored": false, + "hasFiles": false, + "releaseDate": "2024-01-01", + "foreignEditionId": "hc:edition-2001" + }); + let monitored_row = json!({ + "id": 4101, + "authorId": 7001, + "title": "The Clockwork Orchard", + "foreignBookId": "gr:work-1001", + "mediaType": "audiobook", + "monitored": true, + "audiobookMonitored": true, + "hasFiles": false, + "releaseDate": "2024-01-01", + "foreignEditionId": "hc:edition-2001" + }); + let edition = json!({ + "id": 8201, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-2001", + "format": "Audible Audio", "readingFormatId": 2, + "isEbook": false, + "language": "eng", + "monitored": false, + "manualAdd": false + }); + let monitored_edition = json!({ + "id": 8201, + "bookId": 4101, + "title": "The Clockwork Orchard", + "foreignEditionId": "hc:edition-2001", + "format": "Audible Audio", "readingFormatId": 2, + "isEbook": false, + "language": "eng", + "monitored": true, + "manualAdd": true + }); + let responses = vec![ + // Resolve the server-associated row and its author. + audiobook_row.to_string(), + ebook_only_author().to_string(), + json!([audiobook_row.clone()]).to_string(), + "[]".to_string(), + // Settle: addOptions spent, commands quiet. + ebook_only_author().to_string(), + "[]".to_string(), + // Re-resolve under the lock; the row exists, so no add fires and + // nothing on this path configures audiobooks. + audiobook_row.to_string(), + ebook_only_author().to_string(), + json!([audiobook_row.clone()]).to_string(), + "[]".to_string(), + // Pocket resolution re-reads the author's rows and their editions. + json!([audiobook_row.clone()]).to_string(), + json!([edition]).to_string(), + // The author gate write is the only chance to configure the + // format before the search. + ebook_only_author().to_string(), + "{}".to_string(), + author_with_both_formats().to_string(), + "{}".to_string(), + "{}".to_string(), + monitored_row.to_string(), + json!([monitored_edition]).to_string(), + COMMAND_RESPONSE.to_string(), + ]; + let (base_url, requests, server) = mock_api(responses).await; + let mut chaptarr = backend(ChaptarrFormat::Audiobook); + chaptarr.base_url = base_url; + chaptarr.client = reqwest::Client::builder() + .timeout(Duration::from_secs(2)) + .build() + .unwrap(); + let mut item = lookup_item(); + item.existing_book_id = Some(4101); + + chaptarr + .request(Vec::new(), Box::new(item), 1234) + .await + .unwrap(); + timeout(Duration::from_secs(2), server) + .await + .expect("mock server should finish") + .unwrap(); + + let recorded = requests.lock().await; + let put = recorded + .iter() + .find(|request| request_line(request).starts_with("PUT /api/v1/author/7001")) + .expect("the second format must be configured on the author"); + assert!(put.contains("\"audiobookQualityProfileId\":12"), "{put}"); + assert!(put.contains("\"audiobookMetadataProfileId\":22"), "{put}"); + assert!( + put.contains("\"audiobookRootFolderPath\":\"/library/audiobooks\""), + "{put}" + ); + // The format the first request configured is carried through intact. + assert!( + put.contains("\"ebookRootFolderPath\":\"/library/ebooks\""), + "{put}" + ); + assert_eq!( + recorded + .iter() + .filter(|request| request_line(request).starts_with("POST /api/v1/command")) + .count(), + 1 + ); + } + + #[test] + fn add_bodies_send_only_the_requested_format_root_folder() { + // The server's existing-author progressive fill collapses both roots + // into one audiobook-preferring parameter + // (AuthorLibraryService.cs:1136-1137 -> AuthorService.cs:714,751), + // so a body carrying both roots writes the audiobook path into an + // unset EbookRootFolderPath. Only the requested format's root is + // ever sent; the sibling is the server's to configure on its own + // first request. + let item = lookup_item(); + let author: Value = serde_json::from_str(AUTHOR).unwrap(); + for (format, own_key, sibling_key, own_root) in [ + ( + ChaptarrFormat::Ebook, + "ebookRootFolderPath", + "audiobookRootFolderPath", + "/library/ebooks", + ), + ( + ChaptarrFormat::Audiobook, + "audiobookRootFolderPath", + "ebookRootFolderPath", + "/library/audiobooks", + ), + ] { + let chaptarr = backend(format); + for body in [ + chaptarr.new_author_body(&item), + chaptarr.existing_author_book_body(&item, &author).unwrap(), + ] { + let nested = &body["author"]; + assert_eq!(nested[own_key], own_root); + assert!( + nested.get(sibling_key).is_none(), + "sibling root leaked into the add body: {body}" + ); + assert_eq!(body["rootFolderPath"], own_root); + } + } + } + #[test] fn new_author_ebook_body_overrides_audiobook_lookup_projection() { let item = audiobook_projection_item(); @@ -2061,7 +2479,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": false, - "audiobookMonitorFuture": true + "audiobookMonitorFuture": true, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let audiobook = json!({ "id": 5101, @@ -2214,7 +2638,13 @@ mod tests { "foreignAuthorId": "gr:author-2001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let sparse_book = json!({ "id": 4199, @@ -2349,7 +2779,13 @@ mod tests { "foreignAuthorId": "hc:author-9001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let drifted_row = json!({ "id": 4101, @@ -2524,7 +2960,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": false, - "audiobookMonitorFuture": true + "audiobookMonitorFuture": true, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let mut author_settling = author.clone(); author_settling.as_object_mut().unwrap().insert( @@ -2588,7 +3030,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": false, - "audiobookMonitorFuture": true + "audiobookMonitorFuture": true, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let refresh_in_flight = json!([{ "name": "RefreshAuthor", @@ -2648,7 +3096,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let book = json!({ "id": 4101, @@ -2922,7 +3376,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": false, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let author_monitored = json!({ "id": 7001, @@ -2930,7 +3390,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); // The canonical row: every identity field differs from the lookup's // gr:work-1001 - the drift is the point. @@ -3101,7 +3567,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let responses = vec![ drifted_row.to_string(), @@ -3160,7 +3632,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": false, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let author_monitored = json!({ "id": 7001, @@ -3168,7 +3646,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let imported_book = json!({ "id": 4101, @@ -3301,7 +3785,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let canonical_monitored = json!({ "id": 4101, @@ -3384,7 +3874,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let unmonitored_book = json!({ "id": 4101, @@ -3556,7 +4052,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": false, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let author_monitored = json!({ "id": 7001, @@ -3564,7 +4066,13 @@ mod tests { "foreignAuthorId": "hc:author-1001", "monitored": true, "ebookMonitorFuture": true, - "audiobookMonitorFuture": false + "audiobookMonitorFuture": false, + "ebookQualityProfileId": 11, + "ebookMetadataProfileId": 21, + "ebookRootFolderPath": "/library/ebooks", + "audiobookQualityProfileId": 12, + "audiobookMetadataProfileId": 22, + "audiobookRootFolderPath": "/library/audiobooks" }); let book_unmonitored = json!({ "id": 4101,