Skip to content

fix(correlation): correlate image pulls by image, not by stack-name token - #82

Merged
maxjb-xyz merged 7 commits into
mainfrom
fix/image-pull-wrong-stack-correlation
Jun 16, 2026
Merged

maxjb-xyz merged 7 commits into
mainfrom
fix/image-pull-wrong-stack-correlation

Conversation

@maxjb-xyz

@maxjb-xyz maxjb-xyz commented Jun 16, 2026 •

Copy link
Copy Markdown
Owner

Summary

Image-pull (and delete) events were correlated to the wrong stack when an image is used by services in multiple stacks. Root cause: the agent neutralizes a shared-image pull by setting Entry.Service to the image's short name (e.g. postgres), which lives in the same namespace as real compose-project (stack) names, and correlation.ScoreCauses matched pull candidates by bare service string equality — so the pull attached to any incident whose stack was merely named like the image.

This fix decouples pull correlation from the fragile Service token:

  • Entry.Image — new normalized image field, threaded through the type's custom JSON so it crosses the agent→server wire. The agent stamps it on container events (attrs["image"]) and image events (the pulled ref), normalized via normalizeImageRef (postgres:16, docker.io/library/postgres:16 → postgres).
  • Image-aware matching — ScoreCauses now matches docker pull/delete candidates by image ∈ {images the trigger stack actually runs} (derived from that stack's container entries via imagesForServices), instead of by service. A shared pull correlates to exactly the stacks that run the image, and never to an unrelated same-named stack. This also fixes tag/digest reference divergence for free.
  • Node scoping — docker/systemd-triggered correlation is now scoped to the trigger node (fixes the same compose project on two hosts bleeding together). Webhook-triggered correlation stays node-agnostic (Uptime Kuma / Watchtower entries carry the synthetic NodeName: "webhook"), preserving cross-host monitor→cause correlation.

Test Plan

  • go test ./... — shared 4 / agent 104 / server 470 pass; go vet ./... and go build ./... clean
  • New unit tests encode the bug directly:
    • TestScoreCauses_PullCorrelatesToStackThatRunsImage — shared pull attaches to a stack that runs the image
    • TestScoreCauses_PullDoesNotCorrelateToStackThatDoesNotRunImage — shared postgres pull does not attach to a same-named stack that runs redis
    • TestScoreCauses_ScopesToTriggerNode — candidates on a different node are excluded
    • TestBuildEntry_ImagePullSetsNormalizedImage / TestBuildEntry_ContainerEventSetsNormalizedImage — agent stamps normalized Image
  • Manual: with postgres:16 shared by two stacks, a pull no longer appears as a cause/context on an unrelated postgres-named stack's incident.

Migration note

The new image column + composite index idx_entries_service_image are added via GORM AutoMigrate. Existing rows get NULL image (graceful): a stack whose only container entries predate the migration won't correlate pulls until a fresh container event records a populated Image — strictly better than the prior mis-correlation.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Container image references now tracked in events for improved correlation.
    • Cause detection now correlates pull/delete events using actual container images rather than service tokens.
    • Webhook incident triggers now operate node-agnostic for consistent correlation across environments.
  • Tests

    • Comprehensive test coverage added for image normalization, correlation scoping, and cause matching behavior.

maxjb-xyz and others added 6 commits June 16, 2026 05:11
Adds Image string to the Entry struct, entryJSON wire type, MarshalJSON
literal, and UnmarshalJSON assignment so the field survives agent→server
JSON transport. Also adds a composite GORM index (idx_entries_service_image)
on Service+Image to support efficient pull-correlation queries.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Populate types.Entry.Image in both buildEntry (image and container
events) and buildCollapsedContainerEntry using the existing
normalizeImageRef helper, enabling image-based incident correlation.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
ScoreCauses now takes a node argument and filters candidates by node_name,
and matches pull/delete events by image (against images the trigger services
actually run) rather than by the synthetic service token — fixing false
correlations when a shared image name collides with a real stack name.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Update all external call sites of correlation.ScoreCauses to supply the
new node string parameter (3rd arg) introduced in the updated signature.
Rules.go passes the trigger entry's NodeName; webhook_uptime.go passes ""
to preserve cross-node matching for webhook triggers. Also adds a comment
to imagesForServices clarifying it is intentionally not time-windowed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Four rules_test.go tests set the webhook-down trigger's NodeName to "webhook"
(a monitor node), leaving the docker/systemd cause entries on a different infra
node. The new node-scoping in ScoreCauses (node_name = trigger OR node_name = '')
excluded those cross-node candidates, breaking correlation. Updated each trigger
entry to share the infra node so the scope matches — preserving the original
test intent while reflecting the intended node-scoped behavior.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Webhook entries always carry NodeName="webhook" (a synthetic, node-agnostic
value). Passing that as the node scope to ScoreCauses excluded all real
docker/systemd cause candidates (which live on actual agent nodes like
"media-node"). Fix by passing "" in handleMonitorDown and upgradeToConfirmed
so all hosts are searched when the trigger is a webhook-down event.

Revert the 4 masking NodeName changes from 4c410b2 that made tests pass by
aligning the down-trigger's node with the cause node; with the empty-node
fix in place, the realistic "webhook" trigger node now correctly finds
cross-host cause candidates.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@maxjb-xyz, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 40 minutes and 30 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: f9c90c83-5afd-49f6-8d60-8eb3571b0ced

📥 Commits

Reviewing files that changed from the base of the PR and between cddde12 and 7e87213.

📒 Files selected for processing (1)
  • shared/types/events.go
📝 Walkthrough

Walkthrough

Adds an Image field to types.Entry (with GORM composite index and JSON serialization). The Docker watcher populates this field from event attributes for image pull/delete and container events. ScoreCauses gains a node parameter and a new imagesForServices helper that scopes pull/delete correlation by discovered image names rather than service tokens. Webhook and incident rule handlers are updated to pass empty node names for node-agnostic correlation.

Changes

Entry.Image field, image-based correlation, and node-agnostic webhook handling

Layer / File(s) Summary
Entry.Image data contract: struct, JSON, GORM index
shared/types/events.go, shared/types/events_test.go
Adds Image string to Entry with a composite GORM index alongside Service, mirrors it in entryJSON, updates MarshalJSON/UnmarshalJSON, and adds a JSON round-trip test.
Docker watcher: populate Image on pull/delete/container entries
agent/internal/docker/watcher.go, agent/internal/docker/watcher_test.go
buildEntry resolves imageRef from event attributes (name → image → actor ID) for pull, delete, and image events and sets Entry.Image to normalizeImageRef(imageRef). buildCollapsedContainerEntry sets Entry.Image from attrs["image"]. Two new tests verify normalized image assignment.
ScoreCauses signature + imagesForServices helper
server/internal/correlation/score.go, server/internal/correlation/score_test.go, server/internal/correlation/correlation_test.go
Adds a node parameter to ScoreCauses and a new imagesForServices helper that fetches distinct images run by services (excluding pull/delete, not time-windowed). The candidate query conditionally matches pull/delete rows by image or falls back to service. Three new tests cover image-scoped pull correlation and node scoping; all existing call sites updated to new argument order.
Webhook/incident handlers: node-agnostic correlation
server/internal/correlation/correlation.go, server/internal/handlers/webhook_uptime.go, server/internal/incidents/rules.go
FindCause, the webhook down-event path, and three rules.go call sites (handleMonitorDown, openSuspectedIncident, upgradeToConfirmed) pass empty node strings so webhook-triggered correlation is not restricted to the synthetic "webhook" node name.

Sequence Diagram(s)

sequenceDiagram
  rect rgba(100, 149, 237, 0.5)
    Note over DockerWatcher,DB: Agent side — image capture
    DockerWatcher->>DockerWatcher: buildEntry / buildCollapsedContainerEntry
    DockerWatcher->>DB: persist Entry{Image: normalizeImageRef(...)}
  end
  rect rgba(144, 238, 144, 0.5)
    Note over IncidentRule,DB: Server side — image-scoped correlation
    IncidentRule->>ScoreCauses: services, node="", at, triggerComposeService
    ScoreCauses->>imagesForServices: services, node
    imagesForServices->>DB: SELECT DISTINCT image WHERE service IN services (excl. pull/delete)
    DB-->>imagesForServices: ["postgres"]
    imagesForServices-->>ScoreCauses: ["postgres"]
    ScoreCauses->>DB: pull/delete candidates WHERE image IN ["postgres"]
    DB-->>ScoreCauses: []CauseCandidate
    ScoreCauses-->>IncidentRule: scored & ranked causes
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • maxjb-xyz/blackbox#31: Both PRs modify buildEntry and buildCollapsedContainerEntry in agent/internal/docker/watcher.go to populate additional types.Entry fields from Docker event attributes.
  • maxjb-xyz/blackbox#16: Both PRs directly modify ScoreCauses in server/internal/correlation/score.go, adding parameters and changing how correlation candidates are queried.
  • maxjb-xyz/blackbox#46: Both PRs modify Entry's JSON marshal/unmarshal logic in shared/types/events.go, sharing the same serialization code paths.

Poem

From "docker.io/library/postgres:16" I strip and pare,
Just "postgres" remains — clean, precise, laid bare.
🐳 Pull events now find the stack that truly runs the image,
Webhook nodes shed their synthetic lineage.
imagesForServices queries deep, no clock to bind,
Correlation sharper now — leaving guesswork behind. 🎯

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing image pull correlation to match by actual image rather than by stack-name token.
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.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/image-pull-wrong-stack-correlation

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 and usage tips.

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

Actionable comments posted: 1

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

Inline comments:
In `@shared/types/events.go`:
- Line 13: Remove the redundant standalone index declaration from the Service
field in the events struct. The `index` tag on the Service field is redundant
since the composite index `idx_entries_service_image` already includes the
service column as its first element, which efficiently covers queries filtering
only by service. Keep only the composite index tag
`index:idx_entries_service_image,priority:1` and remove the `index` tag to
reduce storage overhead and index maintenance burden.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: bc3217c3-00a1-456c-93cc-1a3c146ae463

📥 Commits

Reviewing files that changed from the base of the PR and between 8a786db and cddde12.

📒 Files selected for processing (10)
  • agent/internal/docker/watcher.go
  • agent/internal/docker/watcher_test.go
  • server/internal/correlation/correlation.go
  • server/internal/correlation/correlation_test.go
  • server/internal/correlation/score.go
  • server/internal/correlation/score_test.go
  • server/internal/handlers/webhook_uptime.go
  • server/internal/incidents/rules.go
  • shared/types/events.go
  • shared/types/events_test.go

Comment thread shared/types/events.go Resolved
The composite idx_entries_service_image has service as its leading
column (priority:1), so it already covers service-only filters via
leftmost-prefix. The standalone index tag was redundant.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@maxjb-xyz
maxjb-xyz merged commit aa9fcdf into main Jun 16, 2026
4 checks passed
@maxjb-xyz
maxjb-xyz deleted the fix/image-pull-wrong-stack-correlation branch June 16, 2026 10:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant