Repository navigation
Conversation
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configuration
📒 Files selected for processing (7)
Included review availability: This review used your included allowance. Your plan provides up to 4 included reviews per hour; 1 remain after this review. 📝 WalkthroughWalkthroughAutoscan 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. ChangesAutoscan marker consistency
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
Suggested reviewers: Merge Risk: ⚪ Minimal · up to No new merge-blocking issue is established for the autoscan marker changes. Complete the planned validation before release. Security Architecture ReviewSecurity architecture risk: 🔵 Low · up to 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 Security review detailsSecurity Blast Radius
Trust Boundaries and Controls
Resilience and Maintainability Implications
Hardening Proposals
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
Full details: Docstring CoverageExplanation 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.)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
Validation task reference is incomplete: The PR lists Suggested replacement: Automated check: Macroscope check run agent (gpt-6-luna). No validation was performed. Posted via Macroscope — v1 validation impact |
| 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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
29756e2 to
3e9586c
Compare
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
Quick104
left a comment
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| // 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) || |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.goback. - 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.
There was a problem hiding this comment.
| // 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 || |
There was a problem hiding this comment.
Low, needs your call. The plugin only receives ResolvedConnection{BaseURL, APIKey}, but this check also fires on fields that leave that value unchanged:
kindnever 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,
Resolveignores the storedbase_url. The web Connections dialog in reuse mode sends nobase_url(ConnectionsPanel.tsx:245-249), so a connection created through the API with bothbase_urland a link loses its markers on its first unchanged save from the UI. Reuse-mode saves also re-derivekindfrom 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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| if err != nil { | ||
| return false, fmt.Errorf("read autoscan connection for marker advance: %w", err) | ||
| } | ||
| if kind != adv.Connection.Kind || |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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) { |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Fixed in 02d40a7: newRepositoryDBTest holds the shared setup, including the to_regclass skip, and both the marker and webhook tests use it.
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
| if err != nil { | ||
| slog.WarnContext(ctx, "autoscan: re-read source before poll failed", "component", "autoscan", "source_id", src.ID, "err", err) | ||
| return src, true |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| current, ok := s.currentPollSource(ctx, src) | ||
| if !ok { | ||
| continue | ||
| } | ||
| src = current |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
1 similar comment
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
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 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 |
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.
c81751e to
376c904
Compare
Silo Kody — review completeReview finished. Check the inline comments for findings and verify each suggestion against the code and tests. Reviewing changes in Silo
Review settingsReview OptionsThe following review options are enabled or disabled:
|
|
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 |
| current, ok := s.currentPollSource(ctx, src) | ||
| if !ok { | ||
| continue | ||
| } | ||
| src = current |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
| var connRow *Connection | ||
| if src.ConnectionID != nil { | ||
| resolved, cerr := s.resolveConnection(ctx, *src.ConnectionID) | ||
| row, resolved, cerr := s.resolveConnection(ctx, *src.ConnectionID) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
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
UpdateSourceclears the marker in the same statement whenconnection_idorsource_configchanges, so the next poll starts from now. Label, enabled, delivery mode, interval and rewrite changes keep it.UpdateConnectionruns 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.last_run_atandlast_erroralone, and the event records its starting marker with a note.Validation
gofmt,go vet,make lint-changed(0 issues), web lint, format check, build and budget, everyverify-*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-gofails only inplayback,jellycompat,transcodenode,api/handlersandapiv2tests that also fail on unmodifiedmainon this macOS host: hardware-probe tests whose fake ffmpeg is killed, transcode-session timing under full-suite load, andTestAdminResourceCapabilitiesAndScope. None of them exercise changed code.make test-webhad one failure under full-suite load (AdminUsersrow actions) that passes on its own. Linux CI is the authority for these.go vetand the tests of the packages it changes (apart fromTestAdminResourceCapabilitiesAndScopeabove); web PRs also pass the typecheck and the autoscan web tests. Every pair of the eleven PRs merges cleanly intomainin either order.Evidence
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, 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
AI Disclosure
mainat 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.UpdateConnectionnow 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.UpdateSourceclears the marker when the source switches connection or changes its source configuration; other edits keep it.Repository.AdvanceMarkerbecomes 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 returnErrNotFound.Service.PollOncere-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.Store.AdvanceMarkerinterface now takes aMarkerAdvancesnapshot 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.