Skip to content

fix(autoscan): reset poll markers when a source's upstream changes - #1935

Merged
Quick104 merged 4 commits into
Silo-Server:mainfrom
Rhainland:fix/autoscan-reset-marker-on-source-change
Oct 7, 2026
Merged

Quick104 merged 4 commits into
Silo-Server:mainfrom
Rhainland:fix/autoscan-reset-marker-on-source-change

Conversation

@Rhainland

@Rhainland Rhainland commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Related issue: #1230
Validation tasks: none (#1231 C3 and #1232 C1, not yet run, cover the source edit and poll path)

A polling source keeps its poll marker (the plugin's continuation token for one upstream) when its server changes. Reproduced with the Sonarr/Radarr plugin: a source bound to Sonarr polled once, was switched to Radarr in Edit, and the next poll sent Sonarr's marker to Radarr, which replayed a Radarr import from before the switch. Depending on the marker format it can also skip history. The same happens when a saved connection is pointed at a different server.

Approach

  • UpdateSource clears the marker in the same statement when connection_id or source_config changes, so the next poll starts from now. Label, enabled, delivery mode, interval and rewrite changes keep it.
  • UpdateConnection runs in a transaction and clears the markers of the sources bound to the connection when the upstream the plugin is handed changes: the linked Requests integration when there is one, otherwise the base URL. Name, kind and API-key changes keep them. Editing the linked Requests integration itself does not reset markers; that needs a change in the Requests update path and is left for a follow-up.
  • Both v1 and v2 updates go through these repository methods.
  • A poll cycle re-reads each source just before polling it, so an edit made earlier in the cycle is not sent the old marker. The marker advance is a compare-and-swap against the rows the poll read; a skipped advance stores nothing, leaves last_run_at and last_error alone, and the event records its starting marker with a note.

Validation

  • DB tests: switching, unbinding and changing config clear the marker; label, interval, rewrite, disable and unchanged saves keep it; a connection base URL change clears every bound source's marker, an API-key, name or kind change does not, and sources on other connections are untouched. The clearing cases fail without the change.
  • On a local Docker build with Sonarr v4 and Radarr v6: after switching a source from Sonarr to Radarr the marker was cleared and the first poll reported 0 changes without replaying the earlier Radarr import; editing the Sonarr connection's URL cleared both bound sources' markers, and changing only its API key kept them.
  • Full gate from CONTRIBUTING.md on a branch combining all eleven [v1] Autoscan #1230 PRs: build, gofmt, go vet, make lint-changed (0 issues), web lint, format check, build and budget, every verify-* target and the router artifact test pass. DB-backed tests for the touched packages (autoscan, scanqueue, scanner, libraryingest, taskmanager, scantrigger, adminjob) pass against a freshly migrated database.
  • make test-go fails only in playback, jellycompat, transcodenode, api/handlers and apiv2 tests that also fail on unmodified main on this macOS host: hardware-probe tests whose fake ffmpeg is killed, transcode-session timing under full-suite load, and TestAdminResourceCapabilitiesAndScope. None of them exercise changed code. make test-web had one failure under full-suite load (AdminUsers row actions) that passes on its own. Linux CI is the authority for these.
  • Each PR on its own builds and passes go vet and the tests of the packages it changes (apart from TestAdminResourceCapabilitiesAndScope above); web PRs also pass the typecheck and the autoscan web tests. Every pair of the eleven PRs merges cleanly into main in either order.

Evidence

Before After
before-activity-poll-after-switch after-activity-poll-after-switch

Each pair shows Activity → Polls after the same steps: a Sonarr / Radarr polling source bound to Sonarr polls once (lower row, 0 changes), Radarr imports a movie, the source is switched to the Radarr server, and Run now polls it about 75 seconds later (upper row). Before, that first poll replays the Radarr import and queues a scan; after, it reports 0 changes. The Source column names the source's current server, so both rows say "via Radarr".

Surface and build: web admin, Libraries → Autoscan → Activity → Polls, desktop width (the panel is 1392 CSS px wide, captured at 2x); before 7d4b831 (main), after c81751e (PR head, merged onto main 7d4b831).

Phone width (390×844, mobile emulation), the same steps, poll details expanded:

Before After
before-activity-poll-after-switch-phone after-activity-poll-after-switch-phone

Before, the first poll after the switch (upper card) reports 1 change and links a scan of the Radarr import; after, it reports 0 changes and no scan. Surface and build: web admin, Activity → Polls mobile cards; before 74158b4 (main), after 376c904 (PR head). Sonarr v4 and Radarr v6 in Docker, Sonarr & Radarr Autoscan plugin 0.1.2, synthetic media file.

Risks

After such an edit, changes between the last poll and the save are not replayed; that is the documented "start from now" behavior for a new marker. A poll already running during the save cannot write the old upstream's marker back: the marker advance is a compare-and-swap against the poll's snapshot. An edit landing in the milliseconds between a source's re-read and its plugin call can still send the old marker once; the compare-and-swap then refuses to store the result.

Checklist

  • I read and can explain the complete diff.
  • This pull request addresses one concern.
  • The Evidence section shows every change a user can see, or says there is none.

AI Disclosure

  • Harness: Claude Code (running in T3 Code)
  • Tool(s): Claude Code (Bash, Read, Edit, Write, sub-agents, Playwright browser automation, T3 Code device control), OpenAI Codex CLI (review only), GitHub CLI, Docker, Sonarr, Radarr
  • Model(s): claude-opus-5-5; review: gpt-6.1-sol and gpt-6-astra (Codex CLI)
  • Involvement: Fully AI-generated, human verified
  • Adversarial review: Three independent reviews of the combined [v1] Autoscan #1230 diff against main at medium effort (a Claude Code review agent on claude-opus-5-5, and Codex CLI with gpt-6.1-sol and gpt-6-astra) checked that the comparisons use the old row values and that the connection update locks the row. No findings.

Note

Reset poll markers when an autoscan source's upstream changes

  • Repository.UpdateConnection now runs in a transaction: it compares the old and new effective upstream (linked Requests integration, else stored base URL) and clears markers for all sources bound to the connection when that upstream changes. Metadata-only edits (name, kind, API key) keep markers.
  • Repository.UpdateSource clears the marker when the source switches connection or changes its source configuration; other edits keep it.
  • Repository.AdvanceMarker becomes a compare-and-swap: a poll stores its next marker only if the source marker, connection binding, source configuration, and effective upstream still match the snapshot the poll took. Stale advances return false and leave the row untouched; unknown sources still return ErrNotFound.
  • Service.PollOnce re-reads each source right before polling it, skipping sources that are missing, disabled, converted to webhook, or unreadable. A rejected marker advance finishes the event with a not-stored note instead of an error. See service.go and repository.go.
  • Behavioral Change: Store.AdvanceMarker interface now takes a MarkerAdvance snapshot and returns a stored/not-stored boolean; stale polls can no longer restore markers cleared by upstream or source edits. Admin API docs for marker resets added in admin-api.md.

Macroscope summarized 376c904.

@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e5656b62-ff8f-4957-87e8-af625e9cb6d3
📥 Commits

Reviewing files that changed from the base of the PR and between 3e9586c and c81751e.

📒 Files selected for processing (7)
  • docs/admin-api.md
  • internal/autoscan/connection_upstream_test.go
  • internal/autoscan/repository.go
  • internal/autoscan/repository_source_marker_test.go
  • internal/autoscan/service.go
  • internal/autoscan/service_test.go
  • internal/autoscan/webhook_endpoint_test.go

Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review.


📝 Walkthrough

Walkthrough

Autoscan source and connection updates now clear poll markers for selected changes. Polling re-reads each source before use and submits a source and connection snapshot with its next marker. The repository skips marker writes when the current state differs from that snapshot.

Changes

Autoscan marker consistency

Layer / File(s) Summary
Reset markers on source and connection changes
internal/autoscan/repository.go, internal/autoscan/repository_source_marker_test.go, internal/autoscan/connection_upstream_test.go, docs/admin-api.md
Connection upstream changes clear markers for bound sources. Source connection binding or stored configuration changes clear that source’s marker. Tests and documentation cover reset and preservation cases.
Poll the current source state
internal/autoscan/service.go, internal/autoscan/service_test.go, internal/autoscan/webhook_endpoint_test.go
PollOnce re-reads sources before polling and skips sources that are missing, unreadable, disabled, or using webhook mode. Polling uses the current source row and retains its connection row for marker validation.
Condition marker advancement on poll snapshot
internal/autoscan/repository.go, internal/autoscan/service.go, internal/autoscan/repository_source_marker_test.go, internal/autoscan/service_test.go
The service passes the source and connection snapshot with the next marker. The repository skips the write when the source or relevant connection state changed. Tests cover stale and repeated advances, missing sources, and invalid connection snapshots.

Priority: ⬇️ Low

Estimated code review effort: 4 (Complex) | ~40 minutes

Change: Bug fix

Sequence Diagram(s)

sequenceDiagram
  participant PollOnce
  participant Repository
  participant Database
  PollOnce->>Repository: Submit MarkerAdvance snapshot
  Repository->>Database: Compare source and connection state
  Database-->>Repository: Return match status
  Repository-->>PollOnce: Return whether marker was stored
Loading

Suggested reviewers: quick104

Merge Risk: ⚪ Minimal · up to c8175

No new merge-blocking issue is established for the autoscan marker changes. Complete the planned validation before release.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 3e958

The change improves protection against stale poll markers without establishing a new external access path. Remaining uncertainty concerns edit-and-revert sequences and provider-specific token behavior, rather than a demonstrated new security vulnerability.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • observed — A connection identity edit invalidates markers for every source bound to that connection, rather than only the source currently polling. The reset predicate is restricted to that connection ID; the database test checks that sources on another connection retain their markers.

Trust Boundaries and Controls

  • observed — The inspected HTTP interfaces reach service operations rather than AdvanceMarker directly. Webhook input is token-validated before ingestion, and the webhook consume path does not request poll-marker advancement. The new persistence contract therefore does not itself give webhook callers direct marker-write authority.

Resilience and Maintainability Implications

  • inferred — Snapshot equality does not record intervening edits. If a poll begins with a NULL marker and source or connection identity changes from A to B and back to A, the final predicates can accept its old next marker. The revert test starts with a non-NULL marker and does not resolve this case. The parent writer was unconditional, so this residual limitation is not evidence of increased security exposure from the PR; provider-dependent replay or omission remains uncertain.
  • observed — Enqueueing and marker persistence were already separate steps in the parent revision. Provider errors, enqueue failures, and transient resolution errors hold advancement; enqueue failure attempts claim release. These controls limit partial failures but do not establish atomic rollback or complete replay idempotency.

Hardening Proposals

  • proposed — If invalidation must survive edit-and-revert sequences, use a monotonic invalidation generation captured by polls and checked during advancement, including when the marker is already NULL. Validate the NULL-start sequence for both source and connection edits.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 73.08% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 6 files. (1 skipped: … Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the main change: resetting autoscan poll markers when a source’s upstream changes.
Description check ✅ Passed The description explains the marker-reset behavior, polling safeguards, validation, and risks covered by the changeset.
Full details: Docstring Coverage

Explanation

Docstring coverage is 73.08% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 26 functions across 6 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

@silo-kody

silo-kody Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@macroscopeapp

macroscopeapp Bot commented Oct 4, 2026

Copy link
Copy Markdown

Validation task reference is incomplete: The PR lists changes #1231 C3, but it also changes the source/connection update path covered by Autoscan Web admin C1. That UI writes through UpdateSource and UpdateConnection; changing source configuration, its connection, or a connection’s upstream identity can change the next poll and the activity/queue/result inspected in C1. Both task cases currently say Not run, so no recorded result is available to invalidate or unblock.

Suggested replacement:
Validation tasks: changes #1231 C3; changes #1232 C1

Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed.

Posted via Macroscope — v1 validation impact

Comment on lines +206 to +209
if _, err := tx.Exec(ctx, `
UPDATE autoscan_sources
SET marker = NULL, updated_at = now()
WHERE connection_id = $1 AND marker IS NOT NULL`, c.ID); err != 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.

kody code-review Bug high

Race condition: an in-flight poll's unconditional AdvanceMarker write can overwrite the NULL reset after a poll reads the old connection/marker, causing the next poll to send the old upstream's stale token to the newly selected connection and invalidating the reset guarantee. Add an optimistic generation/identity check to AdvanceMarker that matches the source's connection/config generation with the poll snapshot, or serialize marker advancement with source/connection updates.

if _, err := tx.Exec(ctx, `
			UPDATE autoscan_sources
			SET marker = NULL, updated_at = now()
			WHERE connection_id = $1 AND marker IS NOT NULL`, c.ID); err != nil {
			return Connection{}, fmt.Errorf("reset autoscan source markers: %w", err)
		}
		// AdvanceMarker must also reject a poll snapshot taken before this reset.
Prompt for LLM

File internal/autoscan/repository.go:

Line 206 to 209:

Race condition: an in-flight poll's unconditional AdvanceMarker write can overwrite the NULL reset after a poll reads the old connection/marker, causing the next poll to send the old upstream's stale token to the newly selected connection and invalidating the reset guarantee. Add an optimistic generation/identity check to AdvanceMarker that matches the source's connection/config generation with the poll snapshot, or serialize marker advancement with source/connection updates.

Suggested Code:

if _, err := tx.Exec(ctx, `
			UPDATE autoscan_sources
			SET marker = NULL, updated_at = now()
			WHERE connection_id = $1 AND marker IS NOT NULL`, c.ID); err != nil {
			return Connection{}, fmt.Errorf("reset autoscan source markers: %w", err)
		}
		// AdvanceMarker must also reject a poll snapshot taken before this reset.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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 3e9586c: the marker advance is now a compare-and-swap. It writes only if the source's marker, connection and stored configuration still match what the poll started with, and, when the poll used a connection, that connection's kind, base URL and linked integration are unchanged (read FOR SHARE, same lock order as UpdateConnection). A stale advance is skipped without failing the poll, so the next poll starts from the reset. DB tests cover config change, connection switch, connection repoint with and without a starting marker, and the unchanged cases; they fail with the check disabled.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Understood. No action was taken.

@Rhainland
Rhainland force-pushed the fix/autoscan-reset-marker-on-source-change branch from 29756e2 to 3e9586c Compare October 4, 2026 20:58
@silo-kody

silo-kody Bot commented Oct 4, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Quick104 Quick104 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Code review of 3e9586c, with nine inline comments.

The two medium findings:

  • A connection repointed during a poll cycle can still receive the old marker once, before the compare-and-swap rejects the write (service.go:209).
  • Editing a linked Requests integration's URL keeps stale markers (repository.go:204). The docs call this intended, so it needs your call.

The rest are low severity or nits. One of them, the CephFS save case, affects only CephFS sources.

Validation: #1231 C1-C3 and #1232 C1 have not been run, so Validation tasks: changes #1231 C3 names a case with no recorded pass. none would be accurate, optionally with a note that this touches the C3 area.

Not verified: I did not run the DB-backed tests. The CephFS save and mid-cycle replay findings are traced from the code, not reproduced.

AI disclosure: written by claude-opus-5-5 in Claude Code via T3 Code (/silo code-review).

conn = resolved
connRow = &row
}
changes, next, perr := s.provider.PollChanges(ctx, src.PluginID, src.CapabilityID, marker, conn, src.SourceConfig)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium. The compare-and-swap added after the earlier thread stops a stale marker from being stored, but the poll can still send that marker once. marker comes from the ListEnabledSources snapshot taken at the start of the cycle (lines 174-177), while the connection is read fresh at line 192. Sources are polled one after another, so the gap is the time spent on every source ahead of this one: seconds, or longer when an earlier upstream is slow.

Trigger: S holds marker M from Sonarr A. During the cycle, before S's turn, an admin changes the connection's base URL to Sonarr B, and UpdateConnection clears S's marker. At S's turn this line calls PollChanges with M against B, consumeSourceChanges enqueues B's changes relative to M, and only then does AdvanceMarker refuse the write. That is one occurrence of the replay this PR fixes, and the Risks section doesn't mention it.

Repair: after resolveConnection, re-read the source with s.store.GetSource and skip it for this cycle (or use the fresh row) when Marker, ConnectionID or SourceConfig differ from the snapshot. That costs one indexed read per polled source, and the CAS still covers the short gap that remains.

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 02d40a7: each source is re-read with GetSource just before its event and plugin call, and polled from the current row (skipped if it was removed, disabled or switched to webhook). A test covers a marker reset after the list was read. The CAS still covers the short gap that remains, and the PR's Risks section now says so.

Comment thread internal/autoscan/repository.go Outdated
// marker refer to a different upstream, so they restart from now, matching
// UpdateSource. Rotating only the API key or renaming keeps them.
if out.Kind != oldKind ||
!equalOptionalString(out.RequestIntegrationID, oldIntegrationID) ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Medium, needs your call. A connection linked to a Requests integration takes its base URL and API key from the integration (ConnectionResolver.Resolve, connection.go:45-49), not from this row. If an admin edits the integration's URL in the Requests admin, every bound source now talks to a different server, but nothing clears their markers: the Requests update path never touches autoscan_sources, and this comparison only sees the connection row. The check in AdvanceMarker (line 617) has the same blind spot, so a poll in flight during that edit also stores the old server's marker.

Trigger: connection C links integration X (Sonarr A), and source S holds a marker from A. The admin changes X's URL to Sonarr B. The next poll sends A's marker to B, which is the replay this PR fixes for direct connections.

The docs added in this PR say editing the linked integration does not reset markers, so this may be deliberate. Options: clear bound sources' markers when the Requests integration's base URL changes, or compare the effective upstream the plugin receives (the integration's URL when linked, the row's otherwise) instead of the row's fields. If it stays out of scope, a follow-up issue would keep it tracked.

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.

Keeping it out of this PR, as the doc says. Resetting on an integration URL edit has to happen in the Requests update path (requests.UpdateIntegration and UpdateIntegrationConditional), which would then write autoscan_sources from the Requests domain or need a hook between the two packages; comparing the resolved URL in AdvanceMarker alone would only cover a poll in flight, not the stored marker. This PR covers the edits made on the autoscan side; the integration edit is a follow-up. With c81751e the comparison here now uses the effective upstream, so a linked connection resets exactly when its link changes.

label = $8,
marker = CASE
WHEN connection_id IS DISTINCT FROM $2::uuid
OR source_config IS DISTINCT FROM $7::jsonb

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Low. The PR says label, enable, interval and rewrite edits keep the marker, but the web editor resends source_config on all of those saves after rebuilding it. fullBody() in SourcesPanel.tsx (around line 878) runs the draft through serializeConfigValues, which fills in descriptor defaults, and sourceConfigForEdit folds the legacy CephFS movie_nested_paths/tv_nested_paths keys into *_flat_paths. When the stored row differs from that rebuilt map, this IS DISTINCT FROM clears the marker on what the admin sees as a label or enable change.

Triggers, all CephFS (the arr plugin has no source config form, so Sonarr and Radarr sources are unaffected):

  • The operator cleared Exclusions, so the key isn't stored. The next enable toggle or label edit sends the default from compat.go back.
  • Rows written by migration 172 that lack exclusions, still hold the nested-path keys, or have untrimmed values.

Impact is small: the CephFS plugin diffs against its own stored roots, so a reset mostly re-delivers a pending batch. Only the cleared-Exclusions case repeats; the others happen once per row. Repair: have the editor send source_config only when the config form itself changed. The DB test's "unchanged save keeps marker" case round-trips an already-normalized map, so a test with the UI-shaped payload would catch this.

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.

Not changing this here. The fix belongs in the web editor (send source_config only when the config form changed), and #1929 rewrites that editor; as you note, it only affects CephFS sources and a reset there re-delivers at most a pending batch. I'd take it as a follow-up on top of #1929.

Comment thread internal/autoscan/repository.go Outdated
// kind, or another linked Requests integration) makes every bound source's
// marker refer to a different upstream, so they restart from now, matching
// UpdateSource. Rotating only the API key or renaming keeps them.
if out.Kind != oldKind ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Low, needs your call. The plugin only receives ResolvedConnection{BaseURL, APIKey}, but this check also fires on fields that leave that value unchanged:

  • kind never reaches the plugin and isn't validated. Correcting a mislabelled Sonarr connection to Radarr with the same URL clears every bound marker.
  • On a linked connection, Resolve ignores the stored base_url. The web Connections dialog in reuse mode sends no base_url (ConnectionsPanel.tsx:245-249), so a connection created through the API with both base_url and a link loses its markers on its first unchanged save from the UI. Reuse-mode saves also re-derive kind from the integration list.

Impact: changes made between the last poll and the save are never scanned. Nothing is replayed. Repair: compare the effective upstream (the integration's URL when linked, otherwise the row's base_url) instead of kind and the raw column. If kind is meant to select plugin behavior later, keeping it here is reasonable.

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 c81751e: connectionUpstream.differsFrom, used by both UpdateConnection and the AdvanceMarker check, now compares the effective upstream that ConnectionResolver.Resolve hands the plugin: the linked Requests integration when there is one (blank treated as no link, as Resolve does), otherwise the row's base_url. kind is no longer part of it, since it never reaches the plugin, and a linked row's stored base_url is ignored. Linking, unlinking or switching the integration still resets. A unit test covers the linked cases, the DB test now expects a kind change to keep markers, and the admin API doc says which edits reset.

if !exists {
return false, fmt.Errorf("%w: source %s", ErrNotFound, adv.SourceID)
}
return false, nil

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Low. The skip paths (lines 612, 620 and here) return without stamping last_run_at or clearing last_error. The old AdvanceMarker always did both once a window was consumed. The poll has still enqueued its scans and finishes its event as success.

Trigger: a source has last_error from polling a wrong URL, and the admin fixes the connection while a poll is running. The source keeps showing "needs attention" in the Sources panel next to a successful event. Because last_run_at wasn't stamped, PollOnce (service.go:172) also polls it again on the next tick regardless of its interval. That is bounded to one extra poll per racing edit.

Repair: on the skip path, stamp last_run_at and clear last_error without touching the marker, or document that a skipped advance leaves both as they were.

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.

Kept the behavior and documented it in 02d40a7 (docs and the AdvanceMarker comment). Leaving last_run_at unstamped is deliberate: the source then polls its new upstream on the next tick and establishes its new marker sooner, instead of waiting a full interval while changes go unscanned.

})
return result, aerr
}
if !advanced {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Low. When the advance is skipped, the code below still finishes the event with MarkerAfter: opts.NextMarker (line 410) and, for an unresolved window, the "advanced past them" message. The event row then records an advance to the old upstream's next marker while the source's stored marker is NULL. Nothing reads marker_after back today, so the effect stays in event history, but an admin investigating a missed or repeated import sees a marker the source never held and nothing saying its window was dropped.

Repair: when !advanced, record opts.Marker (or an empty marker) as MarkerAfter and note in the event message that the marker was not stored.

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 02d40a7: a skipped advance records the starting marker as marker_after, drops the "advanced past them" wording, and notes that the source changed during the poll and its marker was not stored.

Comment thread internal/autoscan/repository.go Outdated
if err != nil {
return false, fmt.Errorf("read autoscan connection for marker advance: %w", err)
}
if kind != adv.Connection.Kind ||

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit. This is the same kind, base URL and Requests link comparison as UpdateConnection at line 203. A small helper used by both, for example connectionUpstreamChanged, would keep the reset and this check from drifting when a field is added to the upstream identity.

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 02d40a7: connectionUpstream.differsFrom is used by both UpdateConnection and AdvanceMarker.

// the source state the poll read from. The marker is only valid for that
// state: a different starting marker, connection binding, source_config, or
// connection upstream means an admin reset the marker while the poll ran.
type MarkerAdvance struct {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit. SourceID, FromMarker, ConnectionID and SourceConfig all come from the source snapshot, and Connection.ID repeats ConnectionID. PollOnce keeps them consistent today. A future caller that sets ConnectionID without Connection would skip the connection check entirely (the adv.Connection != nil guard). Passing the source snapshot and the connection row, and deriving the rest, removes that way to build an inconsistent advance.

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 02d40a7: MarkerAdvance now carries the polled Source row, its Connection row and NextMarker, and the rest is derived. An advance for a bound source without that connection's row returns an error instead of skipping the check (new DB test).

// newSourceMarkerDBTest connects to SILO_TEST_DATABASE_URL (skipping when unset)
// and returns a repository, two connections, and a poll source bound to the
// first one with a stored marker.
func newSourceMarkerDBTest(t *testing.T) (context.Context, *Repository, Source, Connection) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Nit. This repeats the DSN, pool and cipher setup from newWebhookDBTest in webhook_endpoint_test.go but leaves out its to_regclass check, so against an unmigrated database these tests fail in CreateConnection where the webhook tests skip. CI migrates first, so only local runs are affected. One shared helper in the package would cover both.

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 02d40a7: newRepositoryDBTest holds the shared setup, including the to_regclass skip, and both the marker and webhook tests use it.

@silo-kody

silo-kody Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@Rhainland

Copy link
Copy Markdown
Contributor Author

From the review summary: the description's Validation tasks line is now none, since #1231 C3 and #1232 C1 have no recorded pass; it notes that both cases cover this area for their first run.

Comment thread internal/autoscan/service.go Outdated
Comment on lines +671 to +673
if err != nil {
slog.WarnContext(ctx, "autoscan: re-read source before poll failed", "component", "autoscan", "source_id", src.ID, "err", err)
return src, true

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

Replayed or skipped history can occur in internal/autoscan/service.go because a transient GetSource failure after a connection edit causes polling to use the stale listed row, sending the old upstream's marker to the newly resolved upstream. Skip the source on refresh failure instead of falling back; AdvanceMarker runs only after consuming the plugin's response and cannot prevent this error.

if err != nil {
		slog.WarnContext(ctx, "autoscan: re-read source before poll failed", "component", "autoscan", "source_id", src.ID, "err", err)
		return Source{}, false
	}
Prompt for LLM

File internal/autoscan/service.go:

Line 671 to 673:

Replayed or skipped history can occur in internal/autoscan/service.go because a transient GetSource failure after a connection edit causes polling to use the stale listed row, sending the old upstream's marker to the newly resolved upstream. Skip the source on refresh failure instead of falling back; AdvanceMarker runs only after consuming the plugin's response and cannot prevent this error.

Suggested Code:

if err != nil {
		slog.WarnContext(ctx, "autoscan: re-read source before poll failed", "component", "autoscan", "source_id", src.ID, "err", err)
		return Source{}, false
	}

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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 ca4cdc1: a failed re-read now skips the source for this cycle instead of polling the listed row; last_run_at is untouched, so the next cycle retries it. A test covers the read failure.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Thanks—that addresses the reported issue. Skipping the source on a failed re-read prevents polling with the stale listed marker, and leaving last_run_at untouched preserves retry eligibility for the next cycle. The read-failure test covers the regression path.

Based on your description of ca4cdc1b9, I consider this suggestion addressed.

Comment on lines +180 to +184
current, ok := s.currentPollSource(ctx, src)
if !ok {
continue
}
src = current

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

Premature polling occurs in internal/autoscan/service.go because PollOnce replaces the listed source with the refreshed row without rechecking LastRunAt and PollIntervalSeconds, allowing a poll that is not due after a concurrent poll finishes after listing or the interval increases. Move the interval eligibility check after the refresh and calculate elapsed time there to preserve the documented per-source polling floor.

Prompt for LLM

File internal/autoscan/service.go:

Line 180 to 184:

Premature polling occurs in internal/autoscan/service.go because PollOnce replaces the listed source with the refreshed row without rechecking LastRunAt and PollIntervalSeconds, allowing a poll that is not due after a concurrent poll finishes after listing or the interval increases. Move the interval eligibility check after the refresh and calculate elapsed time there to preserve the documented per-source polling floor.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

Not changing this. The interval check has always used the row listed at the start of the cycle, so a poll by another process after the listing, or an interval raised mid-cycle, could already cause one early poll before this PR; the re-read doesn't widen that. The early poll starts from the current marker, and the marker compare-and-swap keeps two overlapping polls from both storing one.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Agreed—the stale interval eligibility check is pre-existing behavior, not a regression introduced by this PR. The re-read refreshes the marker and upstream context without introducing that scheduling window.

The compare-and-swap prevents competing polls from both advancing the same marker snapshot; it does not prevent overlapping plugin calls or enforce the polling interval, but those are separate concerns.

I withdraw this suggestion as a required fix for #1935. Rechecking eligibility after the refresh would be optional scheduling hardening, not a blocker for this marker-reset change.

@silo-kody

silo-kody Bot commented Oct 5, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

1 similar comment
@silo-kody

silo-kody Bot commented Oct 6, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

Quick104 commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

Silo's pull request guidance changed today (#2016). A PR that changes what a user sees now needs before-and-after evidence in its Evidence section, and a PR with no visible change says Evidence: none, no user-visible change. This PR was opened before the rule existed, so it hasn't had a chance to meet it yet.

Missing here: Before-and-after Autoscan Activity screenshots, or poll-event API excerpts, for the first poll after switching a source's server; or the line 'Evidence: none, no user-visible change' if you judge it invisible.

The rules are in Show visible changes, and the PR template shows the Evidence section layout. I've converted this PR to draft for now. Mark it ready for review once the Evidence section is filled in.


Generated by Claude Code

@Quick104
Quick104 marked this pull request as draft October 6, 2026 19:25
@Rhainland
Rhainland marked this pull request as ready for review October 6, 2026 20:46
A poll source kept its stored marker when an administrator switched its
connection. The marker is the plugin's continuation token for one
upstream, so after moving a source from Sonarr to Radarr the plugin read
Radarr history from Sonarr's position and replayed an import from before
the switch. A marker from another upstream can equally skip history. The
same happens when a connection is repointed at another server.

UpdateSource now clears the marker in the same UPDATE when the bound
connection or the source_config changes. Label, enabled, delivery mode,
interval and path rewrite edits keep it.

UpdateConnection now clears the markers of every source bound to the
connection, in the same transaction, when its kind, base URL or linked
Requests integration changes. Name and API key edits keep them.

Both the v2 and frozen v1 updates go through these repository calls, and
an empty marker tells the plugin to start from now.
…vances

- Re-read each source just before polling it, so a marker reset earlier
  in the cycle is not sent to the new upstream.
- When the marker advance is skipped, record the starting marker as the
  event's marker_after with a note instead of claiming an advance, and
  document that last_run_at and last_error stay as they were.
- Build MarkerAdvance from the polled source and connection rows, reject
  a bound source's advance without its connection row, and share the
  upstream comparison between UpdateConnection and AdvanceMarker.
- Share the DB test setup with the webhook tests, including the skip on
  an unmigrated database.
…eam changes

Compare what the plugin is handed: the linked Requests integration when
there is one, otherwise the row's base URL. A kind relabel or a save that
leaves a linked row's stored base URL different no longer clears bound
sources' markers.
@Rhainland
Rhainland force-pushed the fix/autoscan-reset-marker-on-source-change branch from c81751e to 376c904 Compare October 7, 2026 10:31
@silo-kody

silo-kody Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Silo Kody — review complete

Review finished. Check the inline comments for findings and verify each suggestion against the code and tests.

Reviewing changes in Silo
  • Include the related issue, expected behavior, and validation steps in the PR description.
  • For API changes, describe the effect on Apple and Android clients and Jellyfin compatibility.
  • For plugin changes, identify the affected SDK contract, plugin, and catalog entry.
  • Follow this repository's AGENTS.md and CONTRIBUTING.md.
  • Request another review with @kody start-review in a PR comment.
  • React with 👍 or 👎 to give feedback on individual suggestions.
Review settings
Review Options

The following review options are enabled or disabled:

Options Enabled
Bug ✅
Performance ✅
Security ✅
Business Logic ❌

@macroscopeapp

macroscopeapp Bot commented Oct 7, 2026

Copy link
Copy Markdown

The poll outcome in Autoscan → Activity → Polls (zero changes/no queued scan versus a replay that queues a scan) is visible in the phone-width card layout too; add before-and-after phone-width captures of the same flow and identify the viewport for the current pair to complete the web-admin evidence.

Automated check: Macroscope check run agent (gpt-6-luna). Evidence was not reviewed for correctness.

Posted via Macroscope — Visible change evidence

Comment on lines +203 to +207
current, ok := s.currentPollSource(ctx, src)
if !ok {
continue
}
src = current

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

Premature polling occurs because the interval check uses the listed row before src = current replaces it with a refreshed row whose interval or last_run_at may have changed. Recheck eligibility using the refreshed source and current time before creating the event so an increased interval or a poll completed since listing enforces the documented polling floor.

src = current
if !ignoreIntervals {
	interval := time.Duration(settings.DefaultPollIntervalSeconds) * time.Second
	if src.PollIntervalSeconds != nil {
		interval = time.Duration(*src.PollIntervalSeconds) * time.Second
	}
	if src.LastRunAt != nil && time.Since(*src.LastRunAt) < interval {
		continue
	}
}
Prompt for LLM

File internal/autoscan/service.go:

Line 203 to 207:

Premature polling occurs because the interval check uses the listed row before src = current replaces it with a refreshed row whose interval or last_run_at may have changed. Recheck eligibility using the refreshed source and current time before creating the event so an increased interval or a poll completed since listing enforces the documented polling floor.

Suggested Code:

src = current
if !ignoreIntervals {
	interval := time.Duration(settings.DefaultPollIntervalSeconds) * time.Second
	if src.PollIntervalSeconds != nil {
		interval = time.Duration(*src.PollIntervalSeconds) * time.Second
	}
	if src.LastRunAt != nil && time.Since(*src.LastRunAt) < interval {
		continue
	}
}

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

Same answer as the earlier thread on this line: the interval check has always used the row listed at the start of the cycle, so a poll finishing elsewhere after the listing, or an interval raised mid-cycle, could already cause one early poll before this PR, and the re-read does not widen that window. The early poll starts from the current marker, and the compare-and-swap in AdvanceMarker keeps two overlapping polls from both storing a result. Rechecking eligibility on the refreshed row is scheduling hardening outside this marker-reset fix.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Agreed. The stale interval check is pre-existing, and the re-read does not widen that scheduling window. I overstated it as a high-severity regression introduced by this PR.

The refreshed marker and AdvanceMarker compare-and-swap address this PR’s marker-reset concern. They do not prevent overlapping upstream calls, but they protect against storing results from stale snapshots. Rechecking eligibility would be separate scheduling hardening—not a blocker for this fix.

Comment on lines +224 to +226
var connRow *Connection
if src.ConnectionID != nil {
resolved, cerr := s.resolveConnection(ctx, *src.ConnectionID)
row, resolved, cerr := s.resolveConnection(ctx, *src.ConnectionID)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

kody code-review Bug high

Mixed upstream snapshots occur when UpdateConnection commits its upstream change and marker reset after currentPollSource reads the old marker but before resolveConnection reads the new connection, causing PollChanges to send the old upstream's token to the new server and consume its response before AdvanceMarker rejects the write. Read the source marker and connection identity from a consistent database snapshot before invoking the plugin.

Prompt for LLM

File internal/autoscan/service.go:

Line 224 to 226:

Mixed upstream snapshots occur when UpdateConnection commits its upstream change and marker reset after currentPollSource reads the old marker but before resolveConnection reads the new connection, causing PollChanges to send the old upstream's token to the new server and consume its response before AdvanceMarker rejects the write. Read the source marker and connection identity from a consistent database snapshot before invoking the plugin.

Talk to Kody by mentioning @kody

Was this suggestion helpful? React with 👍 or 👎 to help Kody learn from this interaction.

​

​

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.

Not changing this; it is the residual gap the Risks section already names. A consistent snapshot of the source and connection would not close it: the same UpdateConnection can commit a moment later, while PollChanges is in flight, and the plugin call then talks to an upstream whose marker was just reset. Closing that fully would mean holding a lock on the source and connection across a network call to the upstream, which would block admin edits on a slow server. What matters is that the old upstream's marker is never stored against the new one: AdvanceMarker re-checks the marker, connection, config and effective upstream under FOR SHARE (3e9586c, c81751e) and skips the write, so the next poll starts from the reset. The one-time cost is a batch of scans of paths the new upstream reported, which the scan queue resolves against the library like any other change.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Understood—I won’t push this as a required change given the explicitly accepted race and the cost of holding locks across network calls.

One distinction remains: a consistent snapshot would prevent pairing the old source marker with the newly resolved upstream. It would not prevent a coherently captured poll from continuing after an admin edit. Those are different races, so the proposed snapshot fix addresses the former without eliminating the latter.

The AdvanceMarker checks you describe protect the persistence invariant: a stale poll cannot restore the old marker after the reset. They do not undo the plugin call or any scans already queued from its response.

Given that the one-time polling side effects are accepted, this is an intentional tradeoff rather than a blocking high-severity finding. I’d only clarify the Risks section to explicitly name the mixed-snapshot case: one poll can send the previous upstream’s marker to the newly resolved upstream, but its marker advance will be rejected.

@Quick104
Quick104 merged commit 82bed8a into Silo-Server:main Oct 7, 2026
28 checks passed
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.

2 participants