← Back to Pull requests

[CONTP-2221] Prevent duplicate remote creates from stale cache #3719

Closed
unknown closed this pull request without merging on Nov 05, 2026 07:33 UTC
View on GitHub
unknown unknown commented on Nov 03, 2026 10:43 UTC
Author

What does this PR do?

Prevent DatadogMonitor and DatadogGenericResource reconciles from creating a second remote resource when the informer cache still contains an empty or older ID after a successful create.

Before each remote create, read the CR through mgr.GetAPIReader(). If the API server already has a different non-empty ID, skip creation and requeue after five seconds without writing stale status. Also skip creation for a deleted, deleting, or replaced CR. Recreation after a remote 404 remains allowed when the persisted ID still matches the resource being replaced. Keep the status-conflict preservation guard from #3654 as a backstop. Propagate pre-create Kubernetes read failures to controller-runtime without writing stale status.

Motivation

CONTP-2221

Previously, a cached empty ID could trigger another Datadog create even though the first ID had already been persisted. If the API accepted the duplicate, the status retry could replace the stored ID and orphan the first remote resource. #3654 protected against a failed duplicate create overwriting the ID; this change prevents the stale create itself.

This addresses the stale-read hazard described in the upstream controller guidance:

  • The controller-runtime FAQ on stale caches explains that cached information may be out of date and recommends deterministic names/optimistic locking or tracking previous actions to make creation safe.

  • The Kubernetes controller-runtime cache explainer, “Mistake 1: expecting read-after-write” says to “never rely on instant freshness.” Our previous cached-ID check followed by a non-idempotent remote create relied on exactly that freshness. Datadog-assigned IDs do not give us Kubernetes-style AlreadyExists protection for dashboards, notebooks, or SLOs, so the create path now checks the persisted ID directly.
  • Additional Notes

    The extra Kubernetes GET is limited to create/recreate paths. A repeated reconcile with the same stale snapshot keeps skipping safely until the cache catches up. This prevents duplicate creates when an ID is already persisted.

    Minimum Agent Versions

    Describe your test plan

  • Passed go test ./internal/controller/datadoggenericresource ./internal/controller/datadogmonitor and make lint.

  • Added unit coverage for stale empty IDs, stale IDs during remote-404 recreation, API-read failures, and missing/replaced/deleting CRs. Assert that read failures propagate and that skip/read-error paths perform zero status writes in both controllers. Existing remote-deletion and monitor update-time-404 tests pass.

  • Ran 99 successful checks in kind with the branch image and real Datadog APIs:

  • - Created 4 monitors, 6 dashboards, a notebook, and an SLO, with 12 rapid spec edits per CR; verified final remote payloads and exactly one remote resource per CR.
    - Explicitly invoked the branch reconciler code against live API reads with 24 stale snapshots: four resource types, empty-ID and deleted-old-ID cases, and three repeated attempts each. Every attempt requeued for five seconds and preserved persisted status. Natural stress did not trigger the stale-cache guard; these explicit replays exercised it deterministically.
    - Verified remote-deletion recovery, scheduled monitor polling and dashboard force-sync recovery without spec edits, three delete/recreate cycles each for monitors and dashboards, invalid-payload recovery, finalization after an out-of-band deletion, and preservation of all 12 active IDs across an operator restart.
    - Confirmed that identical direct API creates produce two distinct IDs for dashboards, notebooks, and SLOs; monitors rejected the second identical create.
    - Deleted all test CRs and the temporary namespace; all 33 created remote IDs returned 404 and final searches found no orphans.

    <details>
    <summary>2,000-resource load test: API-server overhead and concurrency limits</summary>

    Observed impact: during the initial create burst, average API-server CPU increased from 1.261 to 1.412 cores: approximately +12% relative to baseline, or +0.151 CPU core. This is a create-burst measurement, not a sustained 12% increase from having 2,000 managed resources. Steady-state CPU was approximately 0.37 cores in both versions.

    Concurrency matters: the test deliberately used 20 workers per controller (up to 40 active reconciles across the two controllers), versus the default 1 worker per controller. This is a burst-oriented stress configuration. The default-concurrency case was not benchmarked, so the 12% result should not be extrapolated to that configuration. The extra request count remains one GET per create/recreate attempt; lower concurrency spreads those requests over a longer interval. Peak CPU/RPS and total completion time at the default settings require a separate measurement; the observed percentage cannot simply be divided by 20.

    Setup

  • 1,000 DatadogMonitor CRs and 1,000 dashboard DatadogGenericResource CRs per run.

  • Baseline: e208d5a19, without this PR; candidate: 6c21e622b.

  • Four valid runs, two per version, ordered baseline / candidate / candidate / baseline.

  • Local kind cluster, Kubernetes v1.35.0, linux/arm64; Docker VM with 8 CPUs and approximately 31 GiB RAM.

  • Operator limit: 2 CPUs / 2 GiB RAM; DD_MONITOR_MAX_CONCURRENT_RECONCILES=20 and DD_GENERIC_RESOURCE_MAX_CONCURRENT_RECONCILES=20; 30-second requeues and 60-minute force-sync periods. One operator replica, with leader election disabled to exclude lease-acquisition delays.

  • A deterministic local Datadog API stub with 100 ms response latency and minimal monitor/dashboard payloads isolated Kubernetes overhead from external API latency and rate limits. These were 2,000 real Kubernetes CRs, not 2,000 real Datadog resources.

  • API-server counters, process CPU/RSS, request-duration histograms, and APF metrics scraped directly from /metrics at approximately one-second intervals.
  • Results — means over two runs per version:

    | Phase | API-server CPU, baseline (cores) | API-server CPU, candidate (cores) | Added Kubernetes GETs per run |
    | --- | ---: | ---: | ---: |
    | Initial creation | 1.261 | 1.412 | 2,000 |
    | Steady-state polling | 0.372 | 0.370 | 0 |
    | Ordinary spec updates | 1.315 | 1.212 | 0 |
    | Recreation after remote deletion | 1.346 | 1.380 | 2,000 |
    | Deletion/finalization | 1.103 | 1.092 | 0 |

  • Initial creation completed in 17.65 s → 18.05 s (approximately +2.3%). Recreation completed in 22.60 s → 22.14 s; run-to-run variation means this should not be interpreted as a speedup.

  • Initial-creation CR write latency, pooled histogram p95: 23.77 ms → 24.63 ms.

  • Candidate create-path GET latency: 1.84 ms mean / 6.35 ms histogram p95; peak added CR GET rate approximately 225 GET/s.

  • All valid runs had zero operator restarts, API-server 429s, 5xx responses, APF rejections, extra mock remote resources, or finalizer orphans.

  • API-server CPU includes background cluster traffic, including variable namespace reads. With only two repetitions per version, the CPU percentages are observed differences, not a precise isolated cost estimate. Raw request counts consistently confirmed that the added reads are confined to create/recreate paths.
  • </details>

    For QA, this addresses a race so it can't really be reproduced reliably. Instead, verify the whole lifecycle of creating, updating and deleting a resource works with no double-create/unexpected errors.

    Checklist

  • PR has at least one valid label: bug, enhancement, refactoring, documentation, tooling, and/or dependencies

  • PR has a milestone or the qa/skip-qa label

  • All commits are signed (see: [signing commits][1])
  • [1]: https://docs.github.com/en/authentication/managing-commit-signature-verification/signing-commits

    [CONTP-2221]: https://datadoghq.atlassian.net/browse/CONTP-2221

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: Mathew-Estafanous Review duration: 2690m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #3719"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%