Skip to content

🐛 fix(audit): suppress security scan lifecycle churn - #520

Merged
scttbnsn merged 1 commit into
dev/v1.6from
codex/v16-audit-churn
Jul 13, 2026
Merged

scttbnsn merged 1 commit into
dev/v1.6from
codex/v16-audit-churn

Conversation

@scttbnsn

@scttbnsn scttbnsn commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • keep security scan persistence and container SSE refreshes intact
  • emit generic container-update audit rows only for meaningful lifecycle, image, update, health, error, or policy transitions
  • scope transition state by persisted compose-aware identity with safe legacy fallback
  • prune orphaned state after 30 days and clear exact state on removal
  • document the v1.6 behavior in the changelog

Root cause

Scheduled security scans update security.scan.scannedAt. The store correctly emits dd:container-updated so the UI refreshes, but the audit subscriber treated every event as a lifecycle transition. A 50-container scan therefore wrote 50 unchanged container-update audit rows per cycle and broke the #321 store-size acceptance bound.

Verification

  • focused audit suite: 35 tests
  • audit/index integration: 17 tests
  • store/container integration: 256 tests
  • repository pre-push gate: green
    • backend and UI coverage: 100%
    • backend and UI builds: green
    • 88 script tests, 31 workflow tests, 37 website script tests
    • Biome, Qlty gate, UI typecheck, and Zizmor: green
  • independent two-pass implementation review: clean after compose-sibling and fleet-cap regressions were added

Acceptance impact

This addresses the audit-growth failure found in the superseded #321 operational run. The final 24-hour NAS acceptance remains intentionally last, after all v1.6 code is frozen.

✨ Added

  • Lifecycle-aware container audit deduplication cache using deterministic “lifecycle audit signatures”.
  • Compose/agent/watch-er scoped identity for dedupe, with safe legacy fallback.
  • Cache TTL pruning (30 days) and lifecycle cache cleanup on container removal.
  • v1.6 changelog documentation.
  • Expanded audit subscription test harness to fully register lifecycle handlers (added/updated/removed) and expose lifecycle handler payload helpers (including makeLifecyclePayload).

🔧 Changed

  • container-update audit insertion is now conditional: recorded only when lifecycle/image/update/health/error/update-policy/policy-related transitions actually change, suppressing “security-only” scheduled scan refresh churn.
  • Lifecycle state is seeded only after successful audit persistence for add/changed-update paths (prevents lifecycle state from being seeded on failed insertions).
  • container-updated details population was adjusted to avoid unnecessary/incorrect prior unconditional fields; status-derived transitions are tracked via signature comparison instead.
  • Lifecycle cache entries are pruned/cleared deterministically:
    • stale entries removed by TTL
    • orphaned lifecycle state cleared after 30 days
    • lifecycle state cleared when containers are removed
  • Expanded test coverage for:
    • suppression after lifecycle baseline (including partial baselines)
    • retry behavior on failed audit writes (failed insert can’t seed/suppress lifecycle state)
    • stable status transitions recorded while repeated security refreshes are suppressed
    • normalize update-policy list ordering before comparing lifecycle state
    • identity scoping (including sibling behavior) and legacy fallback safety
    • “fails open” behavior when identity cannot be derived
    • avoiding churn for very large fleets (>10k)

🐛 Fixed

  • Prevented unchanged container-update audit rows caused by scheduled security scans, while preserving security scan persistence and container SSE refresh behavior.
  • Ensured persistence-ordering correctness: lifecycle cache advances only after audit persistence succeeds (add/changed-update paths).
  • Failure-injection tests confirm lifecycle state can’t be seeded/suppressed by failed inserts.

🗑️ Removed

  • Unconditional generic container-update audit insertion behavior that caused audit churn.

⚠️ Breaking

  • None indicated.

🔒 Security

  • Keeps security scan persistence/SBOM-related state advancing without generating noisy generic audit rows during scheduled refreshes.

  • Confirm lifecycle cache identity derivation is consistent at all production call sites (and that the legacy fallback cannot merge unrelated containers).

  • Verify persistence-ordering fix remains correct under retries/failure injection (no lifecycle advancement on failed audit writes).

  • Validate TTL pruning and container-removal cleanup don’t accidentally evict still-relevant lifecycle state for sibling/compose scenarios.

  • Ensure dedupe behavior “fails open” only when identity truly can’t be derived, without reintroducing churn.

@vercel

vercel Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
drydock-website Ready Ready Preview, Comment Jul 13, 2026 8:51pm
drydockdemo-website Ready Ready Preview, Comment Jul 13, 2026 8:51pm

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

Review Change Stack

Important

Review skipped

No new commits to review since the last review.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 48acef29-62ab-4968-9e74-bc3d4056339c

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

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds in-memory, TTL-based container lifecycle audit state keyed by derived container identity. Lifecycle additions seed state, updates record audits only when normalized signatures change, and removals clear cached state. The implementation supports scoped identities, compose siblings, stale-state pruning, cache clearing, and fail-open behavior without stable identity. Tests now register lifecycle handlers and cover deduplication, transitions, policy normalization, cleanup, fleet size, and identity handling.

🚥 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
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch codex/v16-audit-churn

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
app/event/audit-subscriptions.ts (1)

376-412: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Commit changed lifecycle state only after the audit insert succeeds.

Both addition and changed-update paths advance the cache before insertAudit. If insertion throws, a later identical update can be suppressed even though no audit row was persisted.

Proposed ordering
-  setContainerLifecycleAuditState(identity, signature);
-  return { record: previousState?.signature !== signature, identity };
+  if (previousState?.signature === signature) {
+    setContainerLifecycleAuditState(identity, signature);
+    return { record: false, identity };
+  }
+  return { record: true, identity, signature };
   auditStore.insertAudit({ ... });
+  if (lifecycleUpdate.identity && lifecycleUpdate.signature) {
+    setContainerLifecycleAuditState(
+      lifecycleUpdate.identity,
+      lifecycleUpdate.signature,
+    );
+  }
   getAuditCounter()?.inc({ action: 'container-update' });

Move the container-added cache seed after its successful insertion as well.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/event/audit-subscriptions.ts` around lines 376 - 412, Move the
setContainerLifecycleAuditState call in the container-added registrar so it runs
only after auditStore.insertAudit completes successfully, matching the
container-updated path’s persistence ordering. Keep the identity-key calculation
and audit payload unchanged, and ensure failed inserts do not advance lifecycle
cache state.
🧹 Nitpick comments (1)
app/event/audit-subscriptions.test.ts (1)

612-949: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated payload builders across ~9 test cases.

Nearly identical baseline object literals (id/name/watcher/agent/status/image/result) and near-duplicate local factories (updateFor, siblingFor) are redefined in almost every test (e.g. Lines 614-623, 661-669, 697-705, 724-735, 796-806, 819-829, 850-860, 880-889, 907-915, 931-939). A single shared builder would cut this down significantly and reduce drift risk across scenarios.

♻️ Suggested shared helper
function makeLifecyclePayload(
  overrides: Partial<ContainerLifecycleEventPayload> = {},
): ContainerLifecycleEventPayload {
  return {
    id: 'container-1',
    name: 'web',
    watcher: 'docker',
    agent: 'edge-a',
    status: 'running',
    image: { name: 'library/nginx' },
    result: { tag: '1.27.0', digest: 'sha256:one' },
    ...overrides,
  } as unknown as ContainerLifecycleEventPayload;
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/event/audit-subscriptions.test.ts` around lines 612 - 949, Introduce a
shared makeLifecyclePayload helper for the repeated default lifecycle fields,
then replace the local baseline objects and simple updateFor/siblingFor builders
in the listed tests with helper calls and targeted overrides. Preserve each
test’s unique identity, compose, status, security, policy, and other
scenario-specific values while removing duplicated payload construction.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@app/event/audit-subscriptions.ts`:
- Around line 376-412: Move the setContainerLifecycleAuditState call in the
container-added registrar so it runs only after auditStore.insertAudit completes
successfully, matching the container-updated path’s persistence ordering. Keep
the identity-key calculation and audit payload unchanged, and ensure failed
inserts do not advance lifecycle cache state.

---

Nitpick comments:
In `@app/event/audit-subscriptions.test.ts`:
- Around line 612-949: Introduce a shared makeLifecyclePayload helper for the
repeated default lifecycle fields, then replace the local baseline objects and
simple updateFor/siblingFor builders in the listed tests with helper calls and
targeted overrides. Preserve each test’s unique identity, compose, status,
security, policy, and other scenario-specific values while removing duplicated
payload construction.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 029e0be9-dee4-4ea2-9e67-883f1bce0c66

📥 Commits

Reviewing files that changed from the base of the PR and between 817125a and c5e5315.

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

@scttbnsn
scttbnsn force-pushed the codex/v16-audit-churn branch from c5e5315 to a11e763 Compare July 13, 2026 20:49
@scttbnsn

Copy link
Copy Markdown
Contributor Author

Addressed both findings in a11e763:

  • Lifecycle cache state now advances only after audit persistence succeeds on both add and changed-update paths. Two failure-injection regressions prove a failed insert is retried and cannot seed/suppress state.
  • Added the shared makeLifecyclePayload helper and replaced the repeated lifecycle test fixtures/factories.

Validation: 312 focused integration tests, backend build, enforced pre-push gate, 100% app/UI coverage, and app/UI builds all pass. The isolated DinD operational smoke also held audits at 7 -> 7 and container-update at 0 across two on-demand refreshes and two scheduled cycles while scan/SBOM state advanced; no host socket was exposed and all smoke resources were removed.

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown

@scttbnsn Thanks, I'll re-review the PR including commit a11e763 to verify the persistence-ordering fix and the new makeLifecyclePayload helper.

✅ 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.

@scttbnsn
scttbnsn merged commit 8f3522f into dev/v1.6 Jul 13, 2026
5 checks passed
@scttbnsn
scttbnsn deleted the codex/v16-audit-churn branch July 13, 2026 20:52
scttbnsn added a commit that referenced this pull request Jul 15, 2026
## What

Fixes the bug that failed the v1.6.0-rc.1 24-hour store-size acceptance
run (Discussion #321 gate), plus two adjacent gaps found during the same
root-cause investigation.

1. **Slow-path rebuild digest stickiness**
(`docker-image-details-orchestration.ts`). A container whose stored doc
carries `.error` is rebuilt from scratch on the next cycle; the rebuild
reset `image.digest.value` to the raw local repo digest, discarding the
registry-reconciled manifest digest that `handleDigestWatch` recorded on
the last successful cycle. The rebuild now preserves the stored value
unless the repo digest genuinely changed (a real re-pull) — the same
stickiness the fast path (`refreshStoredContainerImageFields`) already
applies.
2. **`updatePolicyOverrides` preservation** (same file). The same
rebuild ran `applyDockerDeclarativeUpdatePolicy` on a fresh object,
stamping `updatePolicyOverrides: {}`; since the incoming doc then *has*
the key, the store merge keeps the empty object — silently destroying
user snoozes/skip-tags for any container that ever had a watch error.
Overrides are now seeded from the stored doc before declarative policy
is re-applied.
3. **Bounded transient-network retry** (`http-retry.ts`). `withRetry`
threw all response-less errors immediately, so registry timeouts/resets
never retried (only 429/503 did). Response-less errors with a transient
code (`ECONNABORTED`, `ETIMEDOUT`, `ECONNRESET`, `EAI_AGAIN`) now retry
up to `maxNetworkRetries` (default 2, also capped by `maxRetries`) with
exponential backoff.

## Why (the incident)

During run #1 of the 24h acceptance, Docker Hub tarpitted requests
intermittently. The failure margin was exactly ten audit rows written at
12:10:47: back-to-back errored cycles sent the redis fleet through the
slow-path rebuild, which flipped `image.digest.value` from the
reconciled `cd5f3…` to the raw `9d317…`. `image.digest.value` is not
among the store-level change detector's inputs, so the corrupting write
emitted nothing — but it changed the security scheduler's scan-group key
(keyed purely on `image.digest.value`), forcing a fresh Trivy scan whose
store write emitted, and the event payload carried the flipped digest
into the lifecycle audit signature (#520), producing one spurious
`container-update` row per container sharing the image. Live-doc
corroboration: `security.sbom.subjectDigest` still held `cd5f3…` while
`image.digest.value` read `9d317…`.

The retry fix reduces how often consecutive cycles error at all; the
digest fix removes the corruption for outages that outlast the retry
budget.

## Considered and deferred (will be filed as issues at rc.1 cut)

- The fast path's repair branch has the same blind `value` reset, but
only runs on already-broken image references — out of scope here.
- Errored docs repeat the full slow enumeration every cycle (2 extra
Docker inspects per container per cron) — perf only.
- Preserving `result` across error writes — must sequence *after* this
fix (a stale `result.digest` against a freshly-corrected
`image.digest.value` could flip `updateAvailable` spuriously).

## Tests

- Regression tests seed the real-lifecycle state the two earlier
forensic harnesses missed (stored `value` ≠ raw local digest), assert
the slow-path rebuild preserves digest value + overrides, and pin the
controls: a genuine re-pull still resets, local images still work,
brand-new containers unaffected.
- `withRetry` network-retry branches fully covered (retry-then-succeed,
budget exhaustion, `maxRetries` cap, non-retryable/missing/non-string
codes, empty code list, `retryDelayMs` override).
- Full app + UI gates green at 100% coverage.


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Changelog

- 🐛 Fixed watcher rebuilds preserving stored reconciled
`image.digest.value` and `updatePolicyOverrides` to prevent state
corruption after error-triggered rebuilds.
- ✨ Added bounded retries for response-less transient registry network
errors in `withRetry`, using exponential backoff (or `retryDelayMs`
override) and supporting retryable error `.code`s (e.g., `ECONNABORTED`,
`ETIMEDOUT`, `ECONNRESET`, `EAI_AGAIN`).
- ✨ Ensured network retries are budgeted independently from
HTTP-status/Axios retries (via a dedicated network retry counter), while
`maxRetries` still caps overall attempts.
- 🔧 Extended `withRetry` options with `retryableNetworkErrorCodes?:
string[]` and `maxNetworkRetries?: number`.
- ✨ Added/expanded regression tests for digest/policy preservation
behavior (including genuine re-pulls, local image scenarios, and new
containers) and for retry behavior across retryable/non-retryable
network errors and retry-delay overrides.

- Verify digest reconciliation logic correctly distinguishes “repo
digest unchanged” (preserve) vs “repo digest changed” (update) across
missing/undefined and local/repull scenarios.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
scttbnsn added a commit that referenced this pull request Aug 23, 2026