Skip to content

fix(agent): stop the watcher snapshot pruning on an empty container list - #929

Merged
scttbnsn merged 3 commits into
dev/v1.7from
fix/v1.7-agent-snapshot-prune
Sep 2, 2026
Merged

scttbnsn merged 3 commits into
dev/v1.7from
fix/v1.7-agent-snapshot-prune

Conversation

@scttbnsn

@scttbnsn scttbnsn commented Aug 29, 2026 •

Copy link
Copy Markdown
Contributor

Closes the half of #565 that was still open after #743. The reporter has hit this four times now, across rc.8, v1.6.0 GA, and again on 2026-08-27.

What was happening

AgentClient has four entry points that ingest a container list. Three of them refuse to prune when that list comes back empty. handleWatcherSnapshotEvent(), which handles the dd:watcher-snapshot server-sent event, never got the guard.

handshake()                    :1115   guarded
watch()                        :2378   guarded
handleContainerSync()          :2425   guarded
handleWatcherSnapshotEvent()   :1551   not guarded

A reconnecting agent legitimately reports zero containers on this path. filterPendingDiscoveries() only bypasses the discovery-settling delay for container ids already in the agent's own local store, and the restart that caused the reconnect just reset that store. So every genuinely running container is held back on the first cycle, getContainers() returns [] without throwing, and the snapshot goes out. By the code's own definition that's a clean cycle, not a failure, which is why nothing suppressed it.

Why the loss was permanent

With an empty incoming list, pruneOldContainers() computes an empty identity-key set, so replacementExpected is false for every record and deleteContainer() runs without it. stashUpdatePolicyForReplacement() only fires when replacementExpected === true, so the one recovery mechanism never ran and updatePolicyOverrides went with nothing to restore from.

That's why #743 didn't cover this. #743 made the stash survive a process restart. On this path nothing was ever stashed.

Proven before it was fixed

Drove the real AgentClient against a real in-memory store, with the two guarded paths as controls:

CONTROL  handshake() with 0 containers  -> override preserved
CONTROL  watch() with 0 containers      -> override preserved
REPRO    dd:watcher-snapshot with 0     -> record deleted outright
   before: updatePolicy { maturityMode: 'mature', maturityMinAgeDays: 5 }
   after:  undefined

One test had frozen the bug in place

'should prune all containers for a watcher when a watcher snapshot is empty' asserted exactly the behaviour that was eating people's settings. It came in with the v1.5.0 mega-PR (#196), written from the implementation rather than from intent, before the zero-container ambiguity was understood. It's inverted here, not extended. Worth flagging in review since a flipped assertion is the kind of thing that deserves a second look.

What this deliberately doesn't do

The broader fix would be to always stash the policy on any delete rather than only on replacementExpected. The cache already exists and is keyed agent::watcher::name with a TTL, so it would work. Rejected as the fix here: it changes deletion semantics for every removal path in the repo, and a genuinely removed container whose name is reused inside the TTL would resurrect a stale policy. Worth raising separately as defence in depth.

canMutateContainer's unconditional upsert when no store record exists is real but sits on the single-container event path, not bulk ingestion, so it's a different concern and isn't touched here.

Tests

Four added. One in AgentClient.container-reconcile.test.ts against the real store asserting the override survives a zero snapshot, and three in AgentClient.test.ts: zero-after-connect warns and doesn't prune, non-empty still prunes (the overcorrection guard), and a first-ever zero snapshot before any handshake neither warns nor prunes.

584 tests pass across both files. AgentClient.ts at 100% statements, branches, functions and lines.

Changelog

  • 🐛 Fixed handleWatcherSnapshotEvent() to preserve containers and updatePolicy overrides on zero-container snapshots after agent reconnection.
  • 🔧 Changed pruning to run only for non-empty watcher snapshots.
  • 🔧 Added warn-once behavior after a prior successful connection.
  • 🔧 Preserved no-warning behavior for the initial zero-container snapshot.
  • ✨ Added regression coverage for state preservation, warning behavior, and non-empty snapshot pruning.
  • 🔧 Updated existing tests to verify that policy overrides remain intact.
  • 🔧 584 relevant tests pass. AgentClient.ts has 100% coverage.

Concerns

  • Confirm that the warning uses the project’s standard logging utility and warn-once convention.
  • Confirm that zero-container snapshots cannot represent a valid intentional removal event.

The still-open half of #565. AgentClient has four entry points that
ingest a container list and three of them already refuse to prune when
that list is empty. handleWatcherSnapshotEvent, which handles the
dd:watcher-snapshot server-sent event, never got the guard.

A reconnecting agent legitimately reports zero containers on this path.
filterPendingDiscoveries only bypasses the discovery-settling delay for
ids already in the agent's own local store, and the restart that caused
the reconnect just reset that store, so every running container is held
back on the first cycle. An empty list then makes every stored container
look like a real removal: deleteContainer runs without
replacementExpected, stashUpdatePolicyForReplacement never fires, and
the user's maturity policy override goes with nothing to restore from.
That is why #743 didn't cover this. It made the stash survive a process
restart, and on this path nothing was ever stashed.

An existing test asserted the broken behaviour outright. It was written
from the implementation in 1.5.0, before the ambiguity was understood,
so it is inverted here rather than extended.
@vercel

vercel Bot commented Aug 29, 2026

Copy link
Copy Markdown

Deployment failed for project drydock-website with the following error:

Resource is limited - try again in 24 hours (more than 100, code: "api-deployments-free-per-day").

Learn More: https://vercel.com/codeswhat?upgradeToPro=build-rate-limit

@coderabbitai

coderabbitai Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Team

Run ID: 6d5256db-ec5a-4d7f-a2a4-2d7ab88b66ea

📥 Commits

Reviewing files that changed from the base of the PR and between 52f61fb and 864d43f.

⛔ Files ignored due to path filters (1)
  • CHANGELOG.md is excluded by !CHANGELOG.md
📒 Files selected for processing (2)
  • app/agent/AgentClient.test.ts
  • app/agent/AgentClient.ts

Included review availability: Your plan provides up to 2 included reviews per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

handleWatcherSnapshotEvent now preserves existing containers when a watcher snapshot is empty. After a prior connection, it logs a warning. Non-empty snapshots still prune stale containers. Tests cover warning behavior, container retention, normal pruning, first-ever empty snapshots, and update-policy preservation.

Merge Risk: 🔵 Low · up to 864d4

The change prevents empty watcher snapshots from deleting container state and losing settings. A genuinely empty watcher may retain stale records until a later non-empty snapshot, so the PR is mergeable with explicit owner awareness or follow-up for an authoritative-empty signal or expiry.

🚥 Pre-merge checks | ✅ 2
✅ Passed checks (2 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.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/v1.7-agent-snapshot-prune

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.

@codecov

codecov Bot commented Aug 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@scttbnsn

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Aug 29, 2026 •

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@vercel

vercel Bot commented Sep 2, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
drydock-website Ready Ready Preview Sep 2, 2026 8:46pm UTC
drydockdemo-website Ready Ready Preview Sep 2, 2026 8:46pm UTC

@biggest-littlest biggest-littlest left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Empty-snapshot guard with the test corrected; CI green after the base merges.

@ALARGECOMPANY ALARGECOMPANY left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Empty-snapshot guard with the test corrected; CI green after the base merges.

@scttbnsn
scttbnsn merged commit 5481c7b into dev/v1.7 Sep 2, 2026
33 of 34 checks passed
@scttbnsn
scttbnsn deleted the fix/v1.7-agent-snapshot-prune branch September 2, 2026 21:11
scttbnsn added a commit that referenced this pull request Sep 3, 2026
* fix(updates): preserve healthy self-update after cleanup failure (#951)

(cherry picked from commit a0a75be)

* fix(qa): four findings from the rc.6 QA sweep (#928)

* fix(qa): four findings from the rc.6 QA sweep

Found by re-running the three QA lanes that came back empty last time,
with verifiers prompted to refute rather than confirm.

The Trivy supply-chain advisory named a version and quoted a digest the
image stopped shipping: it said 0.72.0 and sha256:cffe3f51 while the
image ships 0.73.0 from sha256:7cced7ca. That page's whole job is
telling a reader how to verify what they run, so following its own
instruction produced a mismatch. A coupling test now reads the
Dockerfile pin and fails when the page disagrees. The dated correction
paragraphs keep their historical framing rather than being restamped.

The site had no not-found page at all, so an unknown docs slug fell
through to Next's bare fallback with no header, footer or way back.

The audit log's free-text search filters only the page already fetched,
because the API has no full-text parameter, but the count was rendered
against the server's full total. "2/500" read as "2 of your 500
matched" when it meant "2 of the 50 here". It now counts against the
page and says so.

The servers detail panel never re-resolved its selection after a
refetch, so its own Refresh button updated the row behind it while the
panel kept the snapshot from when it was clicked. Agents and containers
already do this re-lookup.

* fix(ui): trim the audit search query before filtering and counting

(cherry picked from commit e1e88e6)

* fix(compose): gate pulled images before replacement (#952)

* fix(compose): gate pulled images before replacement

* fix(security): keep deferred signature verification on unbound compose dry-runs

* docs(changelog): describe the compose preflight scope accurately

(cherry picked from commit 0e30166)

* fix(agent): stop the watcher snapshot pruning on an empty container list (#929)

The still-open half of #565. AgentClient has four entry points that
ingest a container list and three of them already refuse to prune when
that list is empty. handleWatcherSnapshotEvent, which handles the
dd:watcher-snapshot server-sent event, never got the guard.

A reconnecting agent legitimately reports zero containers on this path.
filterPendingDiscoveries only bypasses the discovery-settling delay for
ids already in the agent's own local store, and the restart that caused
the reconnect just reset that store, so every running container is held
back on the first cycle. An empty list then makes every stored container
look like a real removal: deleteContainer runs without
replacementExpected, stashUpdatePolicyForReplacement never fires, and
the user's maturity policy override goes with nothing to restore from.
That is why #743 didn't cover this. It made the stash survive a process
restart, and on this path nothing was ever stashed.

An existing test asserted the broken behaviour outright. It was written
from the implementation in 1.5.0, before the ambiguity was understood,
so it is inverted here rather than extended.

(cherry picked from commit 5481c7b)

* fix(debug): redact provider-specific notification credentials (#953)

(cherry picked from commit ca092f0)

* fix(config): stop parsing DD_AGENT_ALLOW_INSECURE_SECRET as an agent (#954)

* fix(config): stop parsing DD_AGENT_ALLOW_INSECURE_SECRET as an agent

* test(configuration): tear down the agent env fixture in afterEach

(cherry picked from commit 0a38d76)

* test(agent): cover legacy lookup.url label and agent lookupUrl precedence (forward-port of #956)

Requested subject was 105 chars; the commit-msg hook caps subjects at 100,
so "agent-reported lookupUrl" is shortened to "agent lookupUrl".

Tests copied verbatim from 256ae05 (#956). None of that commit's code was
picked: dev/v1.8 already carries the #948 implementation via 1c01828.

* fix(watcher): re-resolve a stored unknown registry on refresh (#955)

* fix(watcher): re-resolve a stored unknown registry on refresh

* test(watcher): assert the repaired registry name and the no-match fallback

(cherry picked from commit 33a8f6f)
scttbnsn added a commit that referenced this pull request Sep 3, 2026
* fix(config): stop parsing DD_AGENT_ALLOW_INSECURE_SECRET as an agent (#954)

* fix(config): stop parsing DD_AGENT_ALLOW_INSECURE_SECRET as an agent

* test(configuration): tear down the agent env fixture in afterEach

(cherry picked from commit 0a38d76)

* fix(watcher): re-resolve a stored unknown registry on refresh

Backport of PR #955 (open on the v1.7 line at the time of the backport),
squashing the code fix and its follow-up test rewrite into one commit.

(cherry picked from commit 89a4afa)
(cherry picked from commit d96ca5b)

* fix(updates): preserve healthy self-update after cleanup failure (#951)

(cherry picked from commit a0a75be)

* fix(agent): stop the watcher snapshot pruning on an empty container list (#929)

The still-open half of #565. AgentClient has four entry points that
ingest a container list and three of them already refuse to prune when
that list is empty. handleWatcherSnapshotEvent, which handles the
dd:watcher-snapshot server-sent event, never got the guard.

A reconnecting agent legitimately reports zero containers on this path.
filterPendingDiscoveries only bypasses the discovery-settling delay for
ids already in the agent's own local store, and the restart that caused
the reconnect just reset that store, so every running container is held
back on the first cycle. An empty list then makes every stored container
look like a real removal: deleteContainer runs without
replacementExpected, stashUpdatePolicyForReplacement never fires, and
the user's maturity policy override goes with nothing to restore from.
That is why #743 didn't cover this. It made the stash survive a process
restart, and on this path nothing was ever stashed.

An existing test asserted the broken behaviour outright. It was written
from the implementation in 1.5.0, before the ambiguity was understood,
so it is inverted here rather than extended.

(cherry picked from commit 5481c7b)

* fix(debug): redact provider-specific notification credentials (#953)

Hand-ported to the v1.6 matcher, which has no
PROVIDER_SPECIFIC_SENSITIVE_ENV_FIELDS mechanism yet. The map and its
lookup are introduced here with the four provider entries v1.7 carries,
wired into isSensitiveKey after the existing env-style segment rules so
DD_NOTIFICATION_ROCKETCHAT_*_PARSE_URLS and a bare parse.urls flag stay
readable. The provider segment is matched anywhere in the key, so the
legacy DD_TRIGGER_ prefix resolves identically.

(cherry picked from commit ca092f0)

* fix(compose): gate pulled images before replacement (#952)

Hand-ported to v1.6. The only substantive deviation is the mutation
loop's ordering: v1.7 walks it in dependency-graph order via
sortMappingsByDependencyOrder (#219), which v1.6 does not have, so
orderedMappings is the discovery-order list on this line and both the
preflight and the mutation loop walk it. Everything else — the identity
capture, the fail-closed binding policy, the compose-file-once preflight,
and the watcher's hybrid repo:tag@digest parsing fix that makes the
pinned reference readable — is the v1.7 change unchanged.

(cherry picked from commit 0e30166)

* build(deps): refresh security dependency pins on v1.6

Pin fast-uri 4.1.3 and qs 6.16.0 in app and ui, jq 1.8.2-r0 in the
image, and lift the pin-floor test to match. Bump artillery to 2.0.34
in e2e so its fake-data plugin resolves @faker-js/faker 10.5.0
(CVE-2026-73231). The qlty OSV gate blocked the v1.6 backport push on
these advisories.

(cherry picked from commit 45259ae)

* ci(release): suppress zizmor self-repository on the local action refs

zizmor 1.30 flags the two ./.github/actions/wait-for-successful-branch-ci references in release-cut.yml as low-severity self-repository findings and fails the pre-push gate. The $/ syntax it suggests is not something a release workflow should adopt without a dry run, so mark the two lines as intentional instead.
scttbnsn added a commit that referenced this pull request Sep 3, 2026
…962)

* fix(updates): preserve healthy self-update after cleanup failure (#951)

(cherry picked from commit a0a75be)

* fix(qa): four findings from the rc.6 QA sweep (#928)

* fix(qa): four findings from the rc.6 QA sweep

Found by re-running the three QA lanes that came back empty last time,
with verifiers prompted to refute rather than confirm.

The Trivy supply-chain advisory named a version and quoted a digest the
image stopped shipping: it said 0.72.0 and sha256:cffe3f51 while the
image ships 0.73.0 from sha256:7cced7ca. That page's whole job is
telling a reader how to verify what they run, so following its own
instruction produced a mismatch. A coupling test now reads the
Dockerfile pin and fails when the page disagrees. The dated correction
paragraphs keep their historical framing rather than being restamped.

The site had no not-found page at all, so an unknown docs slug fell
through to Next's bare fallback with no header, footer or way back.

The audit log's free-text search filters only the page already fetched,
because the API has no full-text parameter, but the count was rendered
against the server's full total. "2/500" read as "2 of your 500
matched" when it meant "2 of the 50 here". It now counts against the
page and says so.

The servers detail panel never re-resolved its selection after a
refetch, so its own Refresh button updated the row behind it while the
panel kept the snapshot from when it was clicked. Agents and containers
already do this re-lookup.

* fix(ui): trim the audit search query before filtering and counting

(cherry picked from commit e1e88e6)

* fix(compose): gate pulled images before replacement (#952)

* fix(compose): gate pulled images before replacement

* fix(security): keep deferred signature verification on unbound compose dry-runs

* docs(changelog): describe the compose preflight scope accurately

(cherry picked from commit 0e30166)

* fix(agent): stop the watcher snapshot pruning on an empty container list (#929)

The still-open half of #565. AgentClient has four entry points that
ingest a container list and three of them already refuse to prune when
that list is empty. handleWatcherSnapshotEvent, which handles the
dd:watcher-snapshot server-sent event, never got the guard.

A reconnecting agent legitimately reports zero containers on this path.
filterPendingDiscoveries only bypasses the discovery-settling delay for
ids already in the agent's own local store, and the restart that caused
the reconnect just reset that store, so every running container is held
back on the first cycle. An empty list then makes every stored container
look like a real removal: deleteContainer runs without
replacementExpected, stashUpdatePolicyForReplacement never fires, and
the user's maturity policy override goes with nothing to restore from.
That is why #743 didn't cover this. It made the stash survive a process
restart, and on this path nothing was ever stashed.

An existing test asserted the broken behaviour outright. It was written
from the implementation in 1.5.0, before the ambiguity was understood,
so it is inverted here rather than extended.

(cherry picked from commit 5481c7b)

* fix(debug): redact provider-specific notification credentials (#953)

(cherry picked from commit ca092f0)

* fix(config): stop parsing DD_AGENT_ALLOW_INSECURE_SECRET as an agent (#954)

* fix(config): stop parsing DD_AGENT_ALLOW_INSECURE_SECRET as an agent

* test(configuration): tear down the agent env fixture in afterEach

(cherry picked from commit 0a38d76)

* test(agent): cover legacy lookup.url label and agent lookupUrl precedence (forward-port of #956)

Requested subject was 105 chars; the commit-msg hook caps subjects at 100,
so "agent-reported lookupUrl" is shortened to "agent lookupUrl".

Tests copied verbatim from 256ae05 (#956). None of that commit's code was
picked: dev/v1.8 already carries the #948 implementation via 1c01828.

* fix(watcher): re-resolve a stored unknown registry on refresh (#955)

* fix(watcher): re-resolve a stored unknown registry on refresh

* test(watcher): assert the repaired registry name and the no-match fallback

(cherry picked from commit 33a8f6f)

* docs(changelog): restore missing v1.7.0-rc.7 section

* docs(changelog): add v1.7.0-rc.7 link reference

* docs(changelog): add PR #949 dependency advisory bump

* docs(readme): update provider counts for Portainer action trigger

* docs(readme): note v1.8 auth work in roadmap table

* docs(updates): restore v1.7.0-rc.7 highlights and fix v1.6.0-rc.8 trigger list

* docs(triggers): document Portainer PULLTIMEOUT variable

* docs(quickstart): update release candidate example tag to rc.7

* docs(changelog): drop the doubled blank line the base merge left

* test(changelog): expect the rc.7 comparison link on v1.8

The forward-port restored the 1.7.0-rc.7 section and its link reference but the chain test still expected Unreleased to compare against rc.6. Take the test as it is on dev/v1.7.

* chore(release): prepare v1.7.0-rc.7 (#943)

(cherry picked from commit 1831fcd)

* docs(changelog): keep the rc.7 section identical to dev/v1.7

The restored 1.7.0-rc.7 section had picked up the ten post-rc.7 soak-fix bullets that belong under Unreleased on this line, so they appeared twice. Take the section verbatim from dev/v1.7; Unreleased keeps the forward-ported bullets.

This branch was successfully deployed

2 active deployments
Preview – drydock-website — 864d43f5 Deployed Sep 2, 2026 by vercel[bot]
Preview – drydockdemo-website — 864d43f5 Deployed Sep 2, 2026 by vercel[bot]
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.

3 participants