Skip to content

fix(api): close v2 merge-prep gaps in demo gating, activity log, URL minting, ledger, and docs - #1064

Merged
Quick104 merged 38 commits into
apiv2from
fix/apiv2-merge-prep
Sep 13, 2026
Merged

Quick104 merged 38 commits into
apiv2from
fix/apiv2-merge-prep

Conversation

@Quick104

@Quick104 Quick104 commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #135

A pre-merge audit of the apiv2 branch found server-side gaps that would surface once the /api/v1 tombstone lands, plus ledger and doc debt:

  • Demo mode stopped blocking download mutations on /api/v2. The v1 guard blocks POST/DELETE under /api/v1/downloads; none of the v2 download operations carried DemoRestricted.
  • The activity log only knew v1 paths, so every v2 HLS segment fetch and v2 admin log poll wrote an audit row.
  • Several services still minted /api/v1 URLs (branding assets, offline download manifests, webhook-sync and autoscan receivers, plugin auth-provider icons) and v2 handlers rewrote them. The branding one was baked into the SPA shell's favicon link and PWA manifest with no rewrite at all.
  • 62 ledger rows were still proposed, 14 of them with a placeholder owner the gate refuses to ratify, and the sibling pins were 318 (apple) and 160 (android) commits stale.
  • Client docs and scripts still led with v1 paths, and docs/update-to-1.0.md had placeholders.

Approach

One commit per concern, merged into this branch:

  • fix(apiv2): DemoRestricted: true on createDownloads, deleteDownload, createDownloadSubscription, deleteDownloadSubscription, syncDownloadSubscription. PATCH stays open, matching v1's method list. The download capability document folds demo state into allowed, following the notification email verification precedent. New tests cover member denial, admin bypass, PATCH passthrough, and the capability flip. OpenAPI artifact and the system-info fixture regenerated.
  • fix(activitylog): v2 admin-log exclusion and v2 stream/transcode prefixes added; isStreamChunk was already shape-based. Table-driven tests for v1 and v2 side by side. The v1 request logger's blanket v2 skip is intentional because internal/apiv2/observe.go records v2 requests itself.
  • refactor(api): services mint v2 URLs; v2 handlers validate instead of translate. The v1 branding JSON, download manifest, webhook-sync, and autoscan responses now carry v2 URLs (the bridge serves both raw routes, and no v1 fixture pinned the old strings). Playback stream URL translation in playbackV2MediaURL is left alone: nothing in the planner mints v1-shaped URLs any more, and the function only normalizes.
  • chore(contracts): all 773 ledger rows ratified. Removed rows get owner Quick104 and a ratification sentence; exclusion rows mirror the one already-ratified exclusion. Sibling pins refreshed to the current apiv2 heads and consumer evidence rebuilt; the pinned-tree test now accepts the v2 operation's last static segment for clients that already spell the v2 path. extract_consumers.py escape-sequence warning fixed.
  • docs(api): scan-api.md rewritten for v2; downloads-api.md, admin-api.md, api-keys-api.md, images-api.md, catalog-api.md, playback-api.md, settings-api.md, auth-api.md, notifications-push-api.md make v2 primary with bridge notes; update-to-1.0.md integration checklist filled from the contract; k6 loadtest, silo-dev, the Docker wiki pages, and the Continuum migration script moved to v2 paths. Retained /api/v1/health probes untouched. The v1-capability-proposal issue template was not renamed: "v1" there means the 1.0 release scope per docs/architecture/v1-scope.md, not the API version.
  • Two follow-ups from review: v1 webhook-sync list/get used a second minting site and disagreed with create/rotate, now aligned; the contract doc records the widened segment rule.

Out of scope here: silo-apple and silo-android still have live v1 call sites (TopShelf, the non-sequenced playback bridge, and most of the Android network layer). Those are separate repositories; this PR refreshes the ledger's consumer evidence so the gap is recorded rather than hidden.

Validation

  • go build ./..., gofmt -l ., go vet ./...: clean.
  • golangci-lint run --new-from-merge-base=apiv2: one misspelling, fixed.
  • make test-go with SILO_TEST_DATABASE_URL set: the adminjob FK fixture, catalog and metadata Plex-table-drop tests, and two handlers DB tests fail identically on the apiv2 base; the database package times out under the parallel run and passes in isolation. Nothing on this branch changed those packages' behavior.
  • Web: pnpm run lint (0 errors), pnpm run format:check, pnpm run build, make test-web (575 files, 4258 tests passed).
  • Contract gates: verify-settings-bindings-all, verify-playback-fixtures, verify-route-inventory, verify-migration-ledger, verify-scenario-catalogs, verify-offline-routes, verify-apiv2-openapi, verify-apiv2-contract (BASE_REF=apiv2), verify-apiv2-fixtures, TestCommittedArtifactMatchesRouter, verify-local-paths: all pass.

Live verification on shared dev

After the first review round the branch was deployed to the shared development server and every api listener row in the migration ledger (702 rows, 45 sections) was exercised against the running v2 contract by ten independent verifier agents, each followed by an adversarial re-check. The route sweep found every v2 operation registered. 609 rows passed as-is; 20 confirmed defects were fixed on this branch, one per commit group:

  • Notification inbox and Apple push display rejected every real id: the inputs declared UUID format while delivery ids are ULIDs.
  • History browse under cursor paging timed out: the history keyset order was a correlated per-row subquery; it is now a joined projection of the history aggregate.
  • Admin section preview returned nothing when unscoped: an allocated empty slice was treated as "zero libraries" instead of nil.
  • Non-UUID path ids on diagnostics and autoscan operations produced 500 on both versions; the shared services now report not-found before the query.
  • Untyped service errors surfaced as 500 on direct download (unknown file), subtitle download (unknown provider), watch-provider API-key connect (rejected key), and request-integration options (unreachable integration); each now has a sentinel and a 4xx mapping.
  • Admin history-import user discovery and Plex login collapsed every failure to an undeclared 503; they now use the ratified status split.
  • Admin sessions returned 500 for limits 101 to 200 because the shared application capped at 100 while the contract allows 200; the application bound is raised.
  • Admin device summaries nulled last_updated for devices whose timestamp came from Postgres text formatting; the store now emits RFC3339.
  • API-key creation rejected two of the four advertised v2 scopes because it validated against the frozen v1 catalog; the v2 catalog is used and the 422 names the offending scope.
  • Manual collection sync returned 500; template-bundle apply dropped the per-entry reason.

The fixes were redeployed and each formerly failing request was re-run against the live server with the expected status.

One verifier ignored the fixture rules and deleted the shared dev server's Movies library catalog. Media on disk was untouched; the deletion job was stopped before the library row was removed, the library was re-enabled, and a full rescan was started and is repopulating it.

Risks

  • v1 JSON responses for branding, download manifests, webhook-sync, and autoscan now carry /api/v2 URLs. Bridge clients that fetch those URLs still work because the v2 raw routes are served alongside v1; a client that string-matches the /api/v1 prefix would not. No first-party client does.
  • Download capability allowed now reports false for non-admins in demo mode. Clients that gate the download UI on it will hide the action instead of receiving a 403.
  • The refreshed sibling pins credit v2 call sites back to v1 rows through the v2-alias rule, so ledger consumer counts moved. sweep_uncredited.py still reports 222 uncredited v2 hits for rows whose mapping is null; that needs its own pass.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.

AI Disclosure

  • Harness: Claude Code (T3 Code), Workflow tool orchestration
  • Tool(s): Claude Code
  • Model(s): claude-fable-5-1 (orchestration, audit, review), claude-opus-5 (implementation)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: each implementation branch was reviewed by an independent claude-fable-5-1 agent (first round) or claude-opus-5 agent (dev-verification fixes) against its task brief and the diff, checking for correctness, scope creep, v1 bridge regressions, and gate breakage. Findings: one duplicate v1 webhook-sync minting site (fixed), the contract doc lagging the widened segment rule (fixed), stale generated web types after a status-set change (fixed), a capability field doc note and doc precision nits (recorded). Live verification: ten Opus verifiers over 702 ledger rows, each serious finding re-checked by an Opus refuter; 20 confirmed and fixed, one refuted as operator error.

🤖 Generated with Claude Code

Quick104 and others added 12 commits September 13, 2026 02:47
The activity log middleware is mounted for the whole API router, but its
exclusion and stream-chunk lists only named /api/v1 paths. On /api/v2 that
logged one activity row per HLS segment, transcode manifest and subtitle
fetch, and logged the admin log viewer's own polling back into the log it
was reading.

Add the v2 admin log prefix to the exclusions and the v2 stream and
transcode prefixes to the stream list. Chunk detection already matches on
path shape (/segment/, /master.m3u8, /subtitles/), which is identical on
both majors, so it needed no change. The new table-driven tests pin the
behavior for v1 and v2 together, including that neighbouring paths such as
/api/v2/admin/stream-telemetry/parity stay logged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
v1 blocks POST and DELETE under /api/v1/downloads for non-admins when
demo.enabled is set, but the v2 download operations never declared
DemoRestricted, so demo deployments let a member create, delete and
monitor downloads through /api/v2.

Declare the flag on exactly the operations v1's prefix guard covers:
createDownloads, deleteDownload, createDownloadSubscription,
deleteDownloadSubscription and syncDownloadSubscription. PATCH is not in
v1's blocked method list, so reportDownloadStatus and
updateDownloadSubscription keep passing. The download capability document
now folds the demo answer into `allowed`, the same way notification email
verification does, so clients discover the restriction without attempting
a mutation.

Regenerated contracts/api/v2/openapi.json (x-silo-demo-restricted) and the
system-info fixture whose contract digest follows it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…pins

The migration ledger still carried 62 proposed rows: 14 /api/v1 removals whose
owner was the pending:#135 placeholder the gate refuses to ratify, and 48
documented exclusions (root catch-alls, plugin-proxy wildcards, /api/v2
delegations, operator /metrics). Ratify all of them: the removals now name
Quick104 and record the decision in notes, and the exclusions mirror the
already-ratified exclusion row, which records no owner because the schema
requires one only for removed, redesigned, and replaced rows. No disposition or
v2 mapping changed.

Repin the sibling source trees to the current silo-apple and silo-android
commits and rebuild the ledger through scripts/apiv2-ledger (extract, match,
build), so mechanical call sites match the trees the line numbers refer to.
Both clients have moved much of their traffic to /api/v2, so 102 sibling
credits fall away and 22 rows lose their last first-party consumer; curated
fields, manual sites, and follower sites are preserved verbatim. Six manual
sites moved at the new pins (the Apple rebrand renamed two files, downloads and
subtitle URL building moved to the v2 manifest path, the Android ebook read
path moved) and are re-resolved by hand in both the ledger and the seed table
in build_ledger.py. Three Android push sites whose path is a companion-object
constant gain path_literal_line 73.

The pinned-tree test asserted that a credited site mentions the v1 route's last
static path segment. match_consumers.py deliberately credits a client's v2 call
back to the v1 row it aliases, so a row whose v2 operation renamed the last
segment (status -> capabilities, capability -> capabilities) reported a correct
site as mis-credited. The assertion now accepts the row's own segment or its
mapped v2 operation's, and the synthetic unit test covers both outcomes. The
matching prose in docs/architecture/api-contract.md still describes the old
single-segment rule and needs a follow-up edit.

Also make the extract_consumers.py docstring raw so its escaped backtick no
longer raises a SyntaxWarning.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Branding assets, offline manifest asset refs, webhook-sync receivers,
autoscan delivery URLs and plugin auth-provider icons were all minted as
/api/v1 paths and then rewritten by the v2 projection. Two of those URLs
escape the API entirely — the SPA favicon link and PWA manifest bake the
branding path in, and the autoscan delivery URL is pasted into an external
Sonarr/Radarr instance — so nothing would rewrite them once the /api/v1
tombstone lands.

Each service now mints the v2 form, and the v2 handlers validate instead of
translating: the download manifest projection still refuses any reference
outside its own download prefix, and the auth-provider icon projection still
requires a local, non-traversing asset path that the proxy reports public.
The bridge release serves both namespaces, so the v1 responses carrying these
values keep resolving.

The playback planner is untouched: it mints session-relative paths
(/stream/..., /playback/transcode/...), not /api/v1 ones, so
playbackV2MediaURL keeps its defensive /api/v1 branch.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The native API contract makes /api/v2 the stable 1.0 surface and /api/v1 a
frozen alpha bridge, but the client-facing docs still led with v1 paths and
several scripts still called v1 routes. A reader following docs/scan-api.md or
docs/downloads-api.md would build an integration against a surface that
answers 410 Gone at 1.0.

Rewrite the affected docs so v2 leads and the v1 shape survives only in a
marked bridge section, taking every path, operation ID, status, and field from
contracts/api/v2/openapi.json and the migration ledger:

- scan-api.md is now a v2 integration guide that cross-links the scan control
  contract instead of restating it, and documents the autoscan webhook receiver.
- downloads-api.md, admin-api.md, api-keys-api.md, settings-api.md, and
  catalog-api.md put the v2 operations first and keep a short bridge note;
  settings moves its v1 reference to the end of the file.
- images, auth, playback, and notifications-push get proportional fixes.
- update-to-1.0.md replaces the placeholder integration table with the real v2
  receiver paths, records that plex-sync has no v2 receiver of its own and that
  webhook-sync is its successor, and keeps the release commands marked unknown.
- The capability proposal template asks for /api/v2 operations.
- scripts/silo-dev and the k6 load test call v2; the Continuum migration docs
  and script keep the retained /api/v1/health and /api/v1/ready probes with a
  note explaining why.

Related issue: #135

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The v1 list and get handlers still minted the retired /api/v1
webhook-sync receiver path while create and rotate returned the v2 one.
Also records the widened pinned-tree segment rule in the contract doc.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-09-13T06:42:10.207720Z b67b224 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@coderabbitai

coderabbitai Bot commented Sep 13, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Advanced

Run ID: 7af11cae-fd32-4963-8a4b-0436f92f78f6

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 4/5

The runtime changes appear sound, but the explicit documentation-consistency requirement must be satisfied before merging.

Findings

  1. P2 Provider icon docs conflict ▶

Reviews (1) · Last reviewed commit: "test(activitylog): fix misspelling flagg..."

Comment thread docs/auth-api.md Outdated
Comment on lines +188 to +191
Bootstrap generates provider icon URLs as
`/api/v1/plugins/{installation_id}/assets/...`. V2 provider discovery projects those
onto `/api/v2/plugin-content/plugins/{installation_id}/assets/...` only when the
matching provider installation has a public GET route descriptor. Descriptor selection must use the proxy's exact/wildcard precedence;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Provider icon docs conflict

This describes the opposite of the changed implementation. Bootstrap now mints /api/v2/plugin-content/plugins/{installation_id}/assets/... URLs, and v2 discovery validates and returns those URLs instead of projecting v1 URLs. The repository requires documentation to agree with the code, so this must be corrected before merging.

Suggested change
Bootstrap generates provider icon URLs as
`/api/v1/plugins/{installation_id}/assets/...`. V2 provider discovery projects those
onto `/api/v2/plugin-content/plugins/{installation_id}/assets/...` only when the
matching provider installation has a public GET route descriptor. Descriptor selection must use the proxy's exact/wildcard precedence;
Bootstrap generates provider icon URLs as
`/api/v2/plugin-content/plugins/{installation_id}/assets/...`. V2 provider discovery
validates those URLs only when the matching provider installation has a public GET
route descriptor. Descriptor selection must use the proxy's exact/wildcard precedence;

Context Used: CLAUDE.md (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reworded in a4c69e8 to match the code: bootstrap mints the versioned form, a manifest may still supply the legacy prefix, and discovery projects that onto the plugin-content mount after the public-route check.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9a813d8352

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +25 to 27
pluginAssets := plugins.ContentPrefix + "/plugins/"
if !strings.HasPrefix(provider.IconURL, pluginAssets) {
return provider.IconURL

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve projection of legacy provider icon URLs

When a plugin capability supplies the previously supported /api/v1/plugins/{installation_id}/assets/... icon URL, this early return now exposes that URL unchanged and skips the public-route check; cmd/silo/main.go still accepts icon_url directly from capability metadata, and docs/auth-api.md lines 188–195 still promise that such URLs are projected. Once the v1 tombstone is enabled, the pre-login icon request receives 410 Gone instead of reaching the v2 plugin-content route. Continue parsing, validating, and rewriting the legacy prefix in addition to accepting newly minted v2 URLs.

AGENTS.md reference: AGENTS.md:L193-L199

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a4c69e8: the v2 projection accepts both the versioned mount and the legacy /api/v1/plugins/{installation_id}/assets/... prefix, runs the same installation, traversal and public-route checks, and rewrites the legacy form onto /api/v2/plugin-content/.... Tests cover the projected, private, and other-installation legacy cases.

A capability manifest may still name its icon under /api/v1/plugins/;
runtime config mints the versioned form. Project the legacy shape onto
the plugin-content mount after the same public-route check so the icon
survives the v1 tombstone, and correct the auth-api doc paragraph.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a4c69e8357

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/downloads-api.md Outdated
| `bounded_subscription_sync` | Bounded subscription sync (§8.2) is available. |
| `revision` | Opaque revision of this capability document. |
| `state` | Support and configuration state, not health. |
| `allowed` | Whether the calling principal may use downloads at all. |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Gate download actions on the effective allowed field

For a non-admin using a demo-mode server, getDownloadCapability now sets allowed:false while leaving enabled, download_allowed, and quality_presets unchanged, but this guide still tells clients here and in the platform-specific checklist to gate only on enabled && download_allowed. Clients implementing the documented rule will continue exposing create/delete actions that always receive 403; update the guidance to include allowed.

AGENTS.md reference: AGENTS.md:L130-L138

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c0eca63: the capability table describes allowed as the effective answer (download permission and not refused by demo mode), the gating sentence and both platform checklists now say enabled && allowed.

Comment thread docs/downloads-api.md Outdated
| Collections | `{downloads: [...]}`, `{manifests: [...]}`, `{progress: [...]}` | `{items, page}` with opaque cursors |
| Creation | `202` with a bare row or `{downloads, skipped}` | `202` with `{items, skipped, page}` and revision guards |
| Status report | `PATCH` `{status}` answering `204` | `PATCH` `{status, updated_at, revision}` answering `200` with the entry |
| Manifest | `manifest_version: 2` with `/api/v1/...` asset URLs | `manifest_version: 3`, millisecond `generated_at`, `/api/v2/...` asset URLs, 1 MiB bound |

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Describe the bridge manifest URLs the builder emits

The bridge column now says v1 manifests contain /api/v1/... asset URLs, but the same commit changes the shared downloads.ManifestBuilder prefix to /api/v2/downloads/; GET /api/v1/downloads/{id}/manifest uses that builder without projecting the URLs back. Consequently bridge clients receive manifest_version:2 with v2 asset references, contrary to this migration table, so the documented wire behavior should match the implementation.

AGENTS.md reference: AGENTS.md:L101-L108

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in c0eca63: the bridge column now says v1 manifests carry /api/v2/... asset URLs because both versions share the manifest builder.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c0eca63e00

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread docs/scan-api.md Outdated
Comment on lines +32 to +33
Scan mutations also apply profile verification: send `X-Profile-Id`, and `X-Profile-Token` for a
PIN-protected profile.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Mark the scan profile headers as optional

For integrations using the recommended admin API key, this instruction incorrectly requires profile headers: ClassActingAdmin accepts an absent X-Profile-Id, and API-key authentication explicitly skips PIN verification. Following the guide with a secondary household profile causes the acting-admin gate to reject an otherwise valid admin request, while supplying X-Profile-Token for an API key is unnecessary; document that the profile is optional and, when a JWT caller supplies one, it must be the account's primary profile with PIN proof if locked.

AGENTS.md reference: AGENTS.md:L105-L106

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in fd391e2: the profile is documented as optional, API-key callers omit it, and a JWT caller that sends one must name the primary profile with a PIN token when locked.

Quick104 and others added 9 commits September 13, 2026 03:51
POST /api/v2/api-keys and POST /api/v2/admin/api-keys rejected libraries:read
and admin:sessions:summary:read even though the v2 scope catalog advertises
them: the shared creation method validated against the frozen v1 catalog.

Switch the canonical creation method to the full catalog and leave both v1
create transports on the v1 validator, so the frozen v1 catalog is unchanged.
Unknown scopes now return a 422 whose errors[] entry names the offending scope
at body.scopes, matching other v2 validation refusals.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
GET /api/v2/catalog?source=history timed out after 10s with 503 on a
dev-sized profile (~380k user_watch_history rows, 100k+ media items),
while the v1 offset path answered the same request in ~0.5s.

v2 always sets CursorPaging, which routes the history source through the
keyset resolver. There the source order term was a correlated subquery —
(SELECT watched_at FROM (<whole history aggregate>) personal_history
WHERE personal_history.display_id = mi.content_id) — and the membership
predicate wrapped the same aggregate in EXISTS. Because that expression
appears in ORDER BY, in the cursor key projection, and in the keyset seek
predicate, PostgreSQL cannot hoist it: the plan becomes a media_items scan
with a SubPlan that re-runs the DISTINCT ON over user_watch_history (plus
the episodes lookup and the hidden-items anti-join) once per candidate row.
Cost is rows-considered x history-size, which is why it degraded to a
timeout rather than a slow response.

The offset path already had the right shape: project history once as the
history_display CTE and JOIN it as history_source. This gives the cursor
path the same projection. QueryExecutor gains SourceCTE and SourceJoin
(rebound from SourceArgs like SourceWhere already was); the history source
sets them and orders by history_source.watched_at, so the aggregate is
evaluated exactly once per statement and the join is a plain hash/merge
join against the deduplicated display_id set. DISTINCT ON (display_id)
makes display_id unique, so the inner join filters identically to the
EXISTS it replaces — count and page stay consistent.

Cursor semantics are unchanged: the order stays (watched_at desc, then
content_id asc; asc when sort=date_viewed asc), the same two typed keys are
emitted and seeked, so cursors still round-trip.

Tests assert the generated SQL orders from the join, contains no subquery
in ORDER BY, reads user_watch_history exactly once, keeps the join for
non-history sorts and for the count query, and seeks on the joined key.
DB-backed tests were skipped: SILO_TEST_DATABASE_URL is not set in this
environment.

No v2 operation, input, response type, or status set changed, so the
committed OpenAPI artifact is untouched.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two administrative history-import operations threw their error away and
answered every failure with 503 dependency_unavailable, so a source that
does not exist, a source with no stored admin token, and a Plex password
the account holder mistyped were all reported as an outage.

listAdminHistoryImportExternalUsers now routes the DiscoverExternalUsers
failure through adminHistoryProblem, which keeps 404 for a missing source
and 409 for a source whose state does not permit the call; only a failure
no sentinel explains stays the fail-closed dependency problem, and the
operation declares the 409 it can now produce.

loginAdminHistoryImportPlex reuses historyImportProblem and the ratified
upstream split: a source server that answered below 500 is a validation
failure carrying its message, anything else is 503. The administrative
service returns the client's raw error where the personal seam converts
first, so adminHistoryUpstreamError performs that one conversion rather
than growing a second mapper.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Two administrator defects on /api/v2.

GET /api/v2/admin/sessions returned 500 for any limit between 101 and 200.
The shared LimitParam declares a maximum of 200, but the bounded loaders in
internal/api/handlers/playback_sessions.go rejected anything above 100, and the
v2 handler maps that application error to an internal-error problem.

Raised the application bound to 200 (MaxSessionPageLimit) rather than lowering
the declared v2 maximum to 100. The 100 was a plain guard against an unbounded
page request, not a measured performance ceiling: the frozen v1 bridge's Load
path already materializes and enriches the newest 200 observations on every
request, so the largest page a v2 caller may now ask for costs no more work than
v1 does today. Lowering the input instead would have made /admin/sessions the
one paged operation with a smaller maximum than the API-wide convention, for no
reason a client could discover. Requests above 200 stay a 422 from the declared
schema. The summary operation declares its own, smaller maximum of 100 and is
unchanged; it hit the same guard from LoadSummary, which now shares the bound.

GET /api/v2/admin/devices and /admin/devices/{user_id}/{device_id} reported
last_updated as null for every device whose timestamp came from the registry
rather than from a device setting. The Postgres store read last_seen_at as
Postgres text, so DeviceEntry.LastSeenAt carried a second, non-RFC3339 format
that the v2 projection could not parse. Fixed at the source: ListDevices now
scans the column as a timestamp and formats it RFC3339Nano, matching what
ListDeviceSettingsPage already does, so the registry timestamps and the
device-setting UpdatedAt values buildAdminDeviceSummaries merges finally share
one format. That also repairs the lexicographic newest-wins comparison in that
merge, which previously ordered the two formats against each other. v1 keeps a
timestamp string with the same meaning. deviceMetadataInstant also accepts the
Postgres renderings as a backstop, so an older raw value projects a time instead
of a null.

No v2 operation, input, response, or status set changed, so the committed
OpenAPI artifact is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The v2 notification path parameters declared format:"uuid", but
notification_deliveries.id is a text ULID minted by ulid.Make in
internal/notifications. Every real id therefore failed input validation
with 422 before reaching the service, breaking getNotification,
markNotificationRead, and getNotificationApplePushDisplay.

Drop the uuid format from NotificationItemInput.ID and
NotificationPushDisplayInput.DeliveryID, keeping minLength:"1". No
maxLength or ULID pattern is added: the column is free-form text and
tightening it would be a breaking contract narrowing for no gain.

Tests now use ULID fixtures and assert that a ULID id reaches the
handler (200 for a known row, 404 for an unknown one). The docs no
longer claim delivery IDs must be UUIDs. OpenAPI and fixtures regenerated.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
An admin id that is not a UUID reached Postgres and raised SQLSTATE 22P02,
so /api/v1 and /api/v2 answered 500 on a request that simply cannot match a
row. Every affected id column (client_diagnostic_reports.id,
autoscan_sources.id, autoscan_connections.id,
autoscan_webhook_endpoints.source_id) is a `uuid`, so a malformed id can only
ever miss.

Validate the id at the shared service layer, before the query, and return the
existing not-found error: diagnostics.Service.GetReport/DeleteReport return
diagnostics.ErrNotFound, and the autoscan repository returns
autoscan.ErrNotFound from the source, connection and webhook-endpoint lookups.
Both API surfaces already map those to 404 (and 204 for the v2 diagnostics
delete), so no handler or contract change is needed. A source write that binds
a malformed connection id maps to ErrNotFound too, matching how the existing
foreign-key violation for a missing connection is already reported.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Section preview returned nothing when library_ids was omitted: the wire
conversion built a non-nil empty slice, which the section fetcher reads as
"scoped to zero libraries" rather than unscoped. It now returns nil for an
absent or empty list, matching what v1 sends.

Syncing a manual collection answered 500. The catalog service now exports
ErrLibraryCollectionSyncModeUnsupported for a collection with no importable
source mode, and the v2 admin collection error mapper turns it into 422.

Applying a template bundle dropped the per-entry reason, the only explanation
a caller gets for a skipped or failed template. The three v2 template entry
types carry it again, projected from the shared v1 result.

The OpenAPI artifact and fixtures are regenerated; all three schema additions
are optional properties.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Quick104 and others added 12 commits September 13, 2026 05:19
Four v2 operations answered 500 for valid requests because the service
returned an untyped error the problem mappers could not classify. Each is
fixed where the condition is known, so the v1 bridge improves with it.

- Downloads: a media-file lookup that misses now maps scanner.ErrFileNotFound
  onto catalog.ErrItemNotFound, so an unknown file_id is 404 on direct
  download, its HEAD and proxy variants, and download creation.
- Subtitles: the manager reports an unregistered provider as
  subtitles.ErrUnknownProvider, which both subtitle download paths render as
  404 provider_not_found while real upstream failures stay 500.
- Watch providers: watchsync.ErrInvalidCredential gives built-in providers a
  transport-agnostic way to signal a rejected credential; mdblist wraps it for
  401/403, and the plugin-fault check recognizes it, so an API-key connect with
  a bad key is a 4xx.
- Requests: a router transport failure while listing integration options is
  reported as requests.ErrIntegrationUnreachable and rendered as 503
  dependency_unavailable; plugin validation results still pass through.

No v2 operation definition or status set changed, so the committed OpenAPI
artifact is unchanged.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The follow-up to the 503 collapse left three gaps. The web contract types
were not regenerated after listAdminHistoryImportExternalUsers gained 409,
so the generated schema disagreed with the committed OpenAPI artifact and
verify-apiv2-web-types would fail.

Discovery still answered 503 when the source server itself answered and
rejected the stored admin token. A source server that replies below 500
is a configuration problem the administrator fixes on the source, so that
is now 409; discovery is a GET, so it is a state conflict rather than a
body validation failure. Only a source server that could not answer stays
the dependency problem.

Plex sign-in failures that are neither an upstream status nor a
reachability error - plex.tv answering 200 with no token, the client rate
limiter refusing the call - reached serviceProblem and were reported as
500 internal_error, blaming Silo for a plex.tv anomaly. They report the
dependency again, while the ratified upstream split still decides the
cases it recognizes.

historyimport.UpstreamHTTPError lets a mapping test outside the package
build the error a source server produces; the client types that carry the
status are unexported.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
…2-merge-prep

# Conflicts:
#	contracts/api/v2/fixtures/get_system_info_ok.json
…v2-merge-prep

# Conflicts:
#	contracts/api/v2/fixtures/get_system_info_ok.json

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: d5fbfac0c1

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

import { check, group, sleep } from "k6";

const BASE_URL = (__ENV.BASE_URL || "http://localhost:8080/api/v1").replace(
const BASE_URL = (__ENV.BASE_URL || "http://localhost:8080/api/v2").replace(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Require a profile for the v2 section load test

After changing the default base to /api/v2, a run with a valid TOKEN but no PROFILE_ID no longer reaches any section handler: every home and library endpoint used below requires X-Profile-Id, while headers() still adds it only when the optional environment variable is present. Such a run records only 422 validation_failed responses instead of section performance, so require PROFILE_ID for this test and forward it unconditionally.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9507244: PROFILE_ID is required and X-Profile-Id is sent on every request (header name also corrected from X-Profile-ID).

Comment thread scripts/silo-dev Outdated
psql <sql> run one SQL statement against the Silo database
token print an access token for SILO_ADMIN_USER
api <path> [curl...] authenticated request against the API, e.g. api /api/v1/health
api <path> [curl...] authenticated request against the API, e.g. api /api/v2/catalog

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Include the required profile in the v2 API example

Following the new api /api/v2/catalog example fails because the helper injects only the bearer token, whereas GET /api/v2/catalog requires X-Profile-Id (and a profile token when that profile is PIN-locked). Either use an endpoint that works with account authentication alone or show/configure the required profile header so the advertised command succeeds.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9507244: the api helper resolves the admin's primary profile once and sends X-Profile-Id, so the advertised example works.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 9507244842

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

out.DeleteFailed = make([]AdminTemplateCollectionEntry, 0, len(v.DeleteFailed))
for _, e := range v.DeleteFailed {
out.DeleteFailed = append(out.DeleteFailed, AdminTemplateCollectionEntry{LibraryID: IDFromInt(int64(e.LibraryID)), LibraryName: e.LibraryName, CollectionID: ID(e.CollectionID), CollectionTitle: e.CollectionTitle})
out.DeleteFailed = append(out.DeleteFailed, AdminTemplateCollectionEntry{LibraryID: IDFromInt(int64(e.LibraryID)), LibraryName: e.LibraryName, CollectionID: ID(e.CollectionID), CollectionTitle: e.CollectionTitle, Reason: e.Reason})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Sanitize template failure reasons before projecting them

When a template apply encounters a repository, collection-create, or sync failure, internal/api/handlers/library_collections.go stores the raw err.Error() in these entries; copying Reason directly now exposes database, storage, or provider diagnostics through the v2 response and background-job result. The prior projection deliberately omitted this field, so map known conditions to stable public reason codes and use a generic reason for unexpected failures rather than forwarding arbitrary service errors.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a46fe9a: v2 passes through only the documented template reason codes and reports operation_failed for raw service errors; tests updated.

Comment thread internal/autoscan/repository.go Outdated
Comment on lines +1054 to +1055
if uuid.Validate(strings.TrimSpace(id)) == nil {
return nil

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Validate the exact UUID passed to PostgreSQL

For a path ID containing a valid UUID with URL-encoded leading or trailing whitespace, validation succeeds because it checks strings.TrimSpace(id), but the original untrimmed value is still passed to the UUID column query and PostgreSQL returns SQLSTATE 22P02, recreating the 500 this helper is meant to prevent. Validate the original string or normalize the value before every query; diagnostics.reportIDMisses contains the same trim-without-normalization problem.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a46fe9a: both guards validate the exact id that is bound, so a padded UUID is a not-found rather than a 22P02; the autoscan test now asserts that.

Comment thread scripts/silo-dev Outdated
Comment on lines +188 to +189
if [[ -n $profile_id ]]; then
curl -fsS -H "Authorization: Bearer $local_token" -H "X-Profile-Id: $profile_id" "$SILO_URL$path" "$@"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Support PIN-locked profiles in the API helper

After the new primary-profile lookup, an admin whose primary profile has a PIN still cannot use the advertised profile-scoped examples: the final request sends X-Profile-Id but not the required X-Profile-Token, so endpoints such as /api/v2/catalog return 403 profile_verification_required (docs/auth-api.md documents that PIN verification applies even to administrators). Accept a profile token/PIN configuration or avoid claiming the helper works for every primary profile.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in a46fe9a: the helper mints a profile token via verify-pin from SILO_ADMIN_PROFILE_PIN (documented in .silo-dev.env.example) and sends X-Profile-Token alongside X-Profile-Id.

Quick104 and others added 2 commits September 13, 2026 06:18
…ware dev helper

Template-bundle apply projected raw service error text into the reason
field; v2 now passes only the documented reason codes through and reports
operation_failed for anything else. The autoscan and diagnostics id guards
validated a trimmed copy but bound the original, so a padded UUID still
reached Postgres. The silo-dev api helper mints a profile token from
SILO_ADMIN_PROFILE_PIN when the primary profile is locked.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b67b22430e

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

if err := rows.Scan(&entry.ProfileID, &entry.DeviceID, &entry.DeviceName, &entry.DevicePlatform, &lastSeen); err != nil {
return nil, fmt.Errorf("scanning device: %w", err)
}
entry.LastSeenAt = lastSeen.UTC().Format(time.RFC3339Nano)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Use a lexically sortable device timestamp format

Formatting LastSeenAt with time.RFC3339Nano produces variable-width fractional seconds, but buildAdminDeviceSummaries, profile sorting, and v2 device pagination compare these values as strings. This misorders timestamps such as ...05Z and ...05.1Z—especially because canonical setting timestamps use second-precision RFC3339—and can report an older setting as the device's latest update. Use a fixed-width UTC representation or compare parsed time.Time values.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: buildAdminDeviceSummaries and the profile sort compare these as strings (internal/api/handlers/admin.go:1849, :1878, :1953), so variable-width fractional seconds can misorder against second-precision setting timestamps. This landed after the merge; tracking as a follow-up to emit a fixed-width UTC format (or compare parsed times) in ListDevices.

@Quick104
Quick104 merged commit 0416528 into apiv2 Sep 13, 2026
9 of 10 checks passed
@Quick104
Quick104 deleted the fix/apiv2-merge-prep branch September 13, 2026 07:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant