Skip to content

NO-JIRA: monitor: record observed update/recreation counts on the stored object - #31496

Open
devapragadeesh wants to merge 1 commit into
openshift:mainfrom
devapragadeesh:fix-recorder-observed-counts
Open

NO-JIRA: monitor: record observed update/recreation counts on the stored object#31496
devapragadeesh wants to merge 1 commit into
openshift:mainfrom
devapragadeesh:fix-recorder-observed-counts

Conversation

@devapragadeesh

@devapragadeesh devapragadeesh commented Aug 9, 2026

Copy link
Copy Markdown

RecorderWriter.RecordResource is documented as:

Annotations are added to indicate number of updates and the number of recreates.

In practice neither monitor.openshift.io/observed-update-count nor
monitor.openshift.io/observed-recreation-count ever reaches the stored object, so the
recorded-resource artifacts carry no counts at all.

What's wrong

In pkg/monitor/recorder.go, toStore := obj.DeepCopyObject() is taken before the annotations are
computed, while newMetadata is meta.Accessor(obj) — an accessor over the caller's object. So
every SetAnnotations call writes into the argument and leaves toStore untouched.

Two consequences:

  1. The counts are always absent. Since the stored copy has no annotations, the next observation
    reads an empty observed-update-count, strconv.ParseInt fails, and the count is pinned at "1"
    forever — except it is never actually stored, so it reads back as "".
  2. The caller's object is mutated. The callers in pkg/monitortestlibrary/monitoring_store.go
    (AddFunc/UpdateFunc/DeleteFunc, lines 64/90/112) pass objects straight from an informer
    cache. Writing annotations into them modifies shared cache state.

Separately, at line 110 the recreation count was read from the update-count key:

existingRecreateCountStr := existingAnnotations[monitorapi.ObservedUpdateCountAnnotation]

so on every repeat observation observed-recreation-count was overwritten with the update count.

The fix

Take the metadata accessor over the stored copy, so the annotations land on the object that is
actually retained and the caller's object is left alone; and read the recreation count from its own
annotation.

The if newMetadata == nil branch is dropped: meta.Accessor never returns a nil accessor together
with a nil error, and the error case is already handled by the panic a few lines above, so that
branch was unreachable.

How it regressed

git log -S pins this down precisely:

  • 6a53f63 (Aug 2021, "track the final state of pods and events from e2e tests for later
    debugging") introduced the feature with newMetadata, _ := meta.Accessor(toStore) — the accessor
    was correctly taken over the stored copy. The recreation count was read from the update-count key
    from day one, though.
  • 4bdf8c0 (May 2022, "key resources by UID") needed the UID to build InstanceKey, so the
    accessor was hoisted above the DeepCopyObject() call and re-pointed at obj. That silently moved
    every SetAnnotations off the stored copy and onto the caller's object. The same commit put the
    UID into the key, which is what made the recreation-increment branch unreachable.

There is corroborating evidence checked into the repo: the fixture
pkg/monitortests/node/watchpods/podTest/simple/podData.json was captured in March 2022, i.e. after
the day-one recreation bug but before the May 2022 regression. It records
observed-update-count: "5" alongside observed-recreation-count: "4" — the recreation count
trailing the update count by exactly one, which is the precise signature of reading the recreation
count out of the update-count annotation.

Scope note

I deliberately did not change the UID-mismatch branch that increments the recreation count.
monitorapi.InstanceKey includes the UID, so a recreated object is stored under a different key
and the existingMetadata.GetUID() != newMetadata.GetUID() comparison can never be true on a
successful lookup. Making recreation counting actually work would mean changing the map key, which is
a design change rather than a bug fix — happy to follow up separately if maintainers want it.

Testing

Added pkg/monitor/recorder_test.go with table-driven cases covering the seeded counts, repeated
observations incrementing the update count, a recreated pod being tracked under its own key, and that
RecordResource does not mutate its argument.

Against main the new tests fail:

--- FAIL: TestRecordResourceObservedCounts/first_observation_seeds_the_counts
    recorder_test.go:77: expected update count "1", got ""
    recorder_test.go:80: expected recreation count "0", got ""
--- FAIL: TestRecordResourceDoesNotMutateInput
    recorder_test.go:94: expected the recorded object to be unmodified, got annotations
        map[monitor.openshift.io/observed-recreation-count:0 monitor.openshift.io/observed-update-count:1]

With the fix applied, the whole unit suite is green:

  • go test ./pkg/... — all 58 packages pass
  • go test -race ./pkg/monitor/... — pass
  • go build ./..., go vet ./pkg/monitor/..., gofmt -l — clean

No cluster is required for any of this.

…red object

RecordResource is documented to annotate each recorded resource with
observed-update-count and observed-recreation-count, but neither
annotation ever reaches the stored object.

The deep copy that gets stored is taken before the annotations are
computed, while the metadata accessor used to write them is built from
the caller's object. Every SetAnnotations call therefore mutates the
argument and leaves the stored copy untouched. Because the stored copy
carries no annotations, the next observation reads an empty
update-count, ParseInt fails, and the count resets to "1" forever.

Mutating the argument is a problem in its own right: the callers in
monitortestlibrary/monitoring_store.go hand in objects straight from an
informer cache, which must not be modified in place.

Separately, the recreation count was read from the update-count
annotation, so on every repeat observation the recreation count was
overwritten with the update count.

Take the accessor over the stored copy so the annotations land on it and
the caller's object is left alone, and read the recreation count from its
own annotation. The nil-metadata branch is dropped because meta.Accessor
never returns a nil accessor with a nil error; the error is already
handled by the panic above.

Adds unit tests covering the seeded counts, repeated observations, and
that the recorded object is not mutated.
@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Pipeline controller notification
This repo is configured to use the pipeline controller. Second-stage tests will be triggered either automatically or after lgtm label is added, depending on the repository configuration. The pipeline controller will automatically detect which contexts are required and will utilize /test Prow commands to trigger the second stage.

For optional jobs, comment /test ? to see a list of all defined jobs. To trigger manually all jobs from second stage use /pipeline required command.

This repository is configured in: automatic mode

@openshift-ci-robot openshift-ci-robot added the jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. label Aug 9, 2026
@openshift-ci-robot

Copy link
Copy Markdown

@devapragadeesh: This pull request explicitly references no jira issue.

Details

In response to this:

RecorderWriter.RecordResource is documented as:

Annotations are added to indicate number of updates and the number of recreates.

In practice neither monitor.openshift.io/observed-update-count nor
monitor.openshift.io/observed-recreation-count ever reaches the stored object, so the
recorded-resource artifacts carry no counts at all.

What's wrong

In pkg/monitor/recorder.go, toStore := obj.DeepCopyObject() is taken before the annotations are
computed, while newMetadata is meta.Accessor(obj) — an accessor over the caller's object. So
every SetAnnotations call writes into the argument and leaves toStore untouched.

Two consequences:

  1. The counts are always absent. Since the stored copy has no annotations, the next observation
    reads an empty observed-update-count, strconv.ParseInt fails, and the count is pinned at "1"
    forever — except it is never actually stored, so it reads back as "".
  2. The caller's object is mutated. The callers in pkg/monitortestlibrary/monitoring_store.go
    (AddFunc/UpdateFunc/DeleteFunc, lines 64/90/112) pass objects straight from an informer
    cache. Writing annotations into them modifies shared cache state.

Separately, at line 110 the recreation count was read from the update-count key:

existingRecreateCountStr := existingAnnotations[monitorapi.ObservedUpdateCountAnnotation]

so on every repeat observation observed-recreation-count was overwritten with the update count.

The fix

Take the metadata accessor over the stored copy, so the annotations land on the object that is
actually retained and the caller's object is left alone; and read the recreation count from its own
annotation.

The if newMetadata == nil branch is dropped: meta.Accessor never returns a nil accessor together
with a nil error, and the error case is already handled by the panic a few lines above, so that
branch was unreachable.

Scope note

I deliberately did not change the UID-mismatch branch that increments the recreation count.
monitorapi.InstanceKey includes the UID, so a recreated object is stored under a different key
and the existingMetadata.GetUID() != newMetadata.GetUID() comparison can never be true on a
successful lookup. Making recreation counting actually work would mean changing the map key, which is
a design change rather than a bug fix — happy to follow up separately if maintainers want it.

Testing

Added pkg/monitor/recorder_test.go with table-driven cases covering the seeded counts, repeated
observations incrementing the update count, a recreated pod being tracked under its own key, and that
RecordResource does not mutate its argument.

Against main the new tests fail:

--- FAIL: TestRecordResourceObservedCounts/first_observation_seeds_the_counts
   recorder_test.go:77: expected update count "1", got ""
   recorder_test.go:80: expected recreation count "0", got ""
--- FAIL: TestRecordResourceDoesNotMutateInput
   recorder_test.go:94: expected the recorded object to be unmodified, got annotations
       map[monitor.openshift.io/observed-recreation-count:0 monitor.openshift.io/observed-update-count:1]

With the fix applied, the whole unit suite is green:

  • go test ./pkg/... — all 58 packages pass
  • go test -race ./pkg/monitor/... — pass
  • go build ./..., go vet ./pkg/monitor/..., gofmt -l — clean

No cluster is required for any of this.

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the openshift-eng/jira-lifecycle-plugin repository.

@openshift-ci openshift-ci Bot added ready-for-human-review Indicates a PR has been reviewed by automated tools and is ready for human review needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. labels Aug 9, 2026
@openshift-ci

openshift-ci Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Hi @devapragadeesh. Thanks for your PR.

I'm waiting for a openshift member to verify that this patch is reasonable to test. If it is, they should reply with /ok-to-test on its own line. Until that is done, I will not automatically test new commits in this PR, but the usual testing commands by org members will still work.

Regular contributors should join the org to skip this step.

Once the patch is verified, the new status will be reflected by the ok-to-test label.

I understand the commands that are listed here.

Details

Instructions for interacting with me using PR comments are available here. If you have questions or suggestions related to my behavior, please file an issue against the kubernetes-sigs/prow repository.

@openshift-ci
openshift-ci Bot requested review from p0lyn0mial and sjenning August 9, 2026 09:49
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Walkthrough

RecordResource now updates annotations on a deep-copied stored object. Recreation counts use the recreation annotation. Tests cover observation counts, UID-based recreation, and input immutability.

Changes

Monitor recorder updates

Layer / File(s) Summary
Stored-copy annotation tracking
pkg/monitor/recorder.go
RecordResource reads metadata and recreation counts from the stored copy. It applies updated annotations to that copy before recording it.
Observation count and input isolation tests
pkg/monitor/recorder_test.go
Tests cover initial, repeated, and recreated pod observations. Tests also verify that input pods and annotations remain unchanged.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 15
✅ Passed checks (15 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
Stable And Deterministic Test Names ✅ Passed The PR adds standard Go tests only. Their Test and t.Run names are static descriptive strings with no dynamic values, timestamps, namespaces, pod names, or UUIDs.
Test Structure And Quality ✅ Passed The added tests use Go's testing.T, not Ginkgo; they create no cluster resources and make no Eventually/Consistently calls. The check's Ginkgo-specific requirements do not apply.
Microshift Test Compatibility ✅ Passed The PR changes only pkg/monitor Go code and adds standard testing.T tests; no new Ginkgo e2e tests, OpenShift APIs, namespaces, or MicroShift assumptions are present.
Single Node Openshift (Sno) Test Compatibility ✅ Passed The PR adds only standard Go unit tests in pkg/monitor/recorder_test.go; it adds no Ginkgo e2e tests or multi-node assumptions.
Topology-Aware Scheduling Compatibility ✅ Passed Not applicable: the commit changes only monitor recorder logic and tests; it adds no manifests, operators, controllers, workloads, or scheduling constraints.
Ote Binary Stdout Contract ✅ Passed The PR changes only monitor recording code and unit tests; AST and patch checks found no main, suite setup, stdout write, or logging change.
Ipv6 And Disconnected Network Test Compatibility ✅ Passed The PR adds only standard Go unit tests using testing.T and local Pod objects; no Ginkgo e2e tests, IPv4 assumptions, or external network access are present.
No-Weak-Crypto ✅ Passed The PR changes only recorder annotations and tests; the diff adds no MD5, SHA1, DES, RC4, Blowfish, ECB, custom crypto, or secret comparison.
Container-Privileges ✅ Passed The patch changes only Go source and tests; no container/Kubernetes manifests or privilege settings appear in the diff.
No-Sensitive-Data-In-Logs ✅ Passed The patch adds no production logging. Test diagnostics show only synthetic pod IDs, keys, and annotation counts; no passwords, tokens, PII, hostnames, or customer data.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: recording observed update and recreation counts on the stored object.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@openshift-ci

openshift-ci Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: devapragadeesh
Once this PR has been reviewed and has the lgtm label, please assign petr-muller for approval. For more information see the Code Review Process.

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. needs-ok-to-test Indicates a PR that requires an org member to verify it is safe to test. ready-for-human-review Indicates a PR has been reviewed by automated tools and is ready for human review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants