Skip to content

fix: use range queries for long AMP pod history - #554

Open
Iro-engin wants to merge 2 commits into
robusta-dev:mainfrom
Iro-engin:codex/fix-amp-long-owner-query
Open

Iro-engin wants to merge 2 commits into
robusta-dev:mainfrom
Iro-engin:codex/fix-amp-long-owner-query

Conversation

@Iro-engin

Copy link
Copy Markdown

Description

Fixes an issue where Pod owner lookups failed when using --eks-managed-prom with a history duration of 32 days or more.

To address the --history_duration 960 (40 days) case reported in Issue #522, Pod owner lookups now use range queries when querying 32 days or more of history with Amazon Managed Service for Prometheus (AMP).

The existing behavior is preserved for non-AMP Prometheus backends and for AMP queries with a history duration of less than 32 days.

Fixes #522

What was changed

Long-term Pod owner queries for AMP

Added _query_historical_series() to centralize historical Pod owner lookups.

The query type is selected as follows:

  • AMP with less than 32 days of history: continue using instant queries
  • AMP with 32 days or more of history: use query_range
  • Non-AMP Prometheus backends: continue using instant queries

Range queries use last_over_time() and evaluate the history at one-hour intervals.

The PromQL window and the query_range step use the same one-hour value. When the requested history duration is not evenly divisible by the step, the number of evaluation points is rounded up so that the full requested period is covered.

This logic is applied to the following owner lookups:

  • ReplicaSets owned by Deployments or Rollouts
  • ReplicationControllers owned by DeploymentConfigs
  • Jobs owned by CronJobs
  • Pods associated with their owners

Centralized AMP-specific limits

AMP-specific limits are now defined in prometheus_utils.py:

  • Threshold for switching from instant queries to range queries: 32 days
  • Maximum query duration: 95 days
  • Range query step: 1 hour

This avoids duplicating AMP-specific values across multiple implementation points.

The PromQL window and range query step are also derived from the same value to prevent them from becoming inconsistent in the future.

History duration adjustment above 95 days

When AMP is enabled and history_duration exceeds 95 days, it is adjusted to 95 days (2,280 hours) before metric collection begins.

A warning is logged when this adjustment is applied.

The adjusted history duration is used consistently across the entire collection process, including Pod owner, CPU, and memory queries.

This prevents cases where owner lookups use a 95-day history while other metrics continue using the originally requested duration.

The existing AMP-specific step adjustment remains part of the same processing flow.

Step conversion

Changed step conversion from timedelta.seconds to timedelta.total_seconds().

This ensures that steps of one day or longer are converted correctly instead of wrapping at the day boundary.

For example, a one-day step is now correctly passed as 86400s.

Type annotations

Updated the return types of query() and query_range() to list[dict] to match their actual responses.

Why

The existing implementation queried historical Pod owner data using an instant query with a range selector such as:

kube_replicaset_owner{...}[32d]

AMP cannot retrieve the required long-term lookback using this approach once the history duration reaches the relevant limit.

Instead of simply limiting the history duration to 32 days, this change switches to a range query only when AMP is used with a history duration of 32 days or more.

The change is intentionally limited to AMP-specific cases so that existing short-duration queries and non-AMP Prometheus backends keep their current behavior.

For requests exceeding AMP's 95-day maximum query duration, the history duration is normalized before collection begins rather than being limited independently in individual queries.

This keeps the history period consistent across Pod owner, CPU, memory, and other metric collection.

Behavior and compatibility

Non-AMP Prometheus backends

Existing instant queries continue to be used.

The AMP-specific 32-day and 95-day limits introduced by this change do not apply, so existing behavior is unchanged.

AMP with less than 32 days of history

Instant queries continue to be used as before.

AMP with 32 to 95 days of history

Pod owner history is queried using range queries, covering the requested duration at one-hour intervals.

AMP with more than 95 days of history

history_duration is adjusted to 95 days (2,280 hours), and a warning is logged.

The adjusted duration is used consistently across Pod owner, CPU, and memory collection.

Configuration

No new CLI options or configuration fields were added.

There are no changes to the existing values or configuration file formats.

Testing

The following cases are covered by tests:

  • AMP with a 40-day history uses a range query
  • AMP with less than 32 days continues to use instant queries
  • Non-AMP environments continue to use instant queries even for long history durations
  • Range queries are used for Deployment / ReplicaSet / Pod owner lookups
  • The PromQL window and range query step use the same one-hour value
  • The full requested history duration is covered by the range query
  • Boundary conditions around 32 days and 95 days
  • History durations around step boundaries
  • A one-day step is passed as 86400s
  • history_duration is adjusted to 95 days only when it exceeds the limit, with a warning logged when the adjustment occurs

Test results

The same steps used by the regular push CI were reproduced in a Linux environment.

Environment:

  • Linux
  • Python 3.10.22

Commands:

pip install --upgrade pip
pip install -r requirements.txt
pip install -e .
pip install pytest
pytest

Result:

72 passed

Additional checks:

  • macOS + Python 3.10: 72 tests passed
  • pip check: passed
  • git diff --check: passed
  • Black check for changed files: passed

Integration testing against an actual Amazon Managed Service for Prometheus environment has not been performed.

Avoid unsupported instant queries with 32-day lookbacks when discovering historical pod owners in Amazon Managed Prometheus.

Assisted-by: OpenAI Codex
Signed-off-by: yongdadaoye <[email protected]>
@CLAassistant

CLAassistant commented Oct 7, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 645746c2-9cda-44d7-af02-078ca789f5b3
📥 Commits

Reviewing files that changed from the base of the PR and between d4fb269 and 5230315.

📒 Files selected for processing: 4
  • robusta_krr/core/integrations/prometheus/metrics_service/prometheus_metrics_service.py
  • robusta_krr/core/runner.py
  • tests/test_prometheus_metrics_service.py
  • tests/test_runner.py
🚧 Files skipped from review as they are similar to previous changes: 4
  • tests/test_runner.py
  • tests/test_prometheus_metrics_service.py
  • robusta_krr/core/runner.py
  • robusta_krr/core/integrations/prometheus/metrics_service/prometheus_metrics_service.py

Included review availability: This review used your included allowance. Your plan provides up to 8 included reviews per hour; 7 remain after this review.

Walkthrough

AMP historical-series lookups now use range queries for lookbacks of at least 32 days, with one-hour steps and a 95-day query cap. Runner also caps AMP history duration and adjusts timeframe duration when the step count exceeds 11,000.

Changes

AMP Historical Queries

Layer / File(s) Summary
Historical-query selection and owner lookups
robusta_krr/core/integrations/prometheus/prometheus_utils.py, robusta_krr/core/integrations/prometheus/metrics_service/prometheus_metrics_service.py, tests/test_prometheus_metrics_service.py
Adds AMP query thresholds and a shared historical-series helper. AMP queries at or above 32 days use range queries with one-hour steps, capped at 95 days. Owner and related-pod history lookups use the helper. Tests cover query selection, range coverage, and step formatting.
Runner history and timeframe limits
robusta_krr/core/runner.py, tests/test_runner.py
Adds AMP-specific history capping and timeframe adjustment when the step count exceeds 11,000. The run path calls the adjustment method, and tests cover history durations around the 95-day limit.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~20 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant load_pods
  participant historical_series_helper
  participant query_range
  participant AMP
  load_pods->>historical_series_helper: Request owner history
  historical_series_helper->>query_range: Send historical query with period and step
  query_range->>AMP: Submit range query
  AMP-->>query_range: Return series results
  query_range-->>historical_series_helper: Return query results
  historical_series_helper-->>load_pods: Return historical series
Loading
Merge Risk: ⚪ Minimal · up to 52303

The AMP query change appears ready for normal merge checks. No actionable risk was identified in the historical lookups or history cap.

Security architecture risk: 🔵 Low · up to d4fb2

Long-history queries retain the existing authentication and workload selectors, with explicit duration and evaluation-step limits. No introduced security regression was established. End-to-end request behavior and reuse after interrupted scans remain incompletely verified.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The changed retrieval path operates against the same configured Prometheus backend and credential authority as before. Namespace and configured cluster-label selectors remain in the owner and pod-status queries; the inspected changes do not establish expanded cross-namespace, cross-cluster, or cross-account authority.

Trust Boundaries and Controls

  • observed — Instant and range wrappers obtain their client through the same get_prometheus path. Existing configured headers and authentication remain attached to that client, with no alternate unauthenticated transport introduced by the historical-query helper.

Resilience and Maintainability Implications

  • inferred — Normalization is idempotent for unchanged AMP settings and contains no await, preventing same-event-loop interleaving within the adjustment itself. Together with adjustment-before-collection ordering, this supports consistent query bounds on the normal scan path, but does not establish safety under external configuration mutation or concurrent Runner reuse.
Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title clearly and concisely describes the main change: using range queries for long AMP pod history.
Description check Passed The description directly explains the AMP range-query change, history limits, affected lookups, testing, and compatibility behavior.
Linked Issues check Passed Directly linked issue #522 requires that AMP Pod owner lookups use range queries for long histories, because AMP rejects instant queries with a 32d to 95d lookback. The whole-PR diff (merge base 6b26d…
Out of Scope Changes check Passed All changed areas connect to the AMP long-history behavior in #522, or are small supporting changes disclosed in the PR description:

- prometheus_utils.py: adds the AMP constants (32d minimum, 95d …
Docstring Coverage Passed Docstring coverage is 81.82% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 22 functions across 5 files.
Full details: Linked Issues check

Explanation

Directly linked issue #522 requires that AMP Pod owner lookups use range queries for long histories, because AMP rejects instant queries with a 32d to 95d lookback. The whole-PR diff (merge base 6b26df8 to head 5230315) shows the following:

  • _query_historical_series() in prometheus_metrics_service.py routes to query_range when settings.eks_managed_prom is set and period &gt;= AMP_QUERY_RANGE_MIN_PERIOD (32 days). Otherwise it issues the previous instant query, with last_over_time added only when use_last_over_time=True.
  • The range query uses last_over_time({selector}[3600s]) with step=1h. The window and step share one value.
  • evaluation_count = ceil(min(period, 95d) / 1h) and start = end - (evaluation_count - 1)h. The earliest window therefore reaches back to at least end - period, so the full requested period is covered.
  • load_pods routes the ReplicaSet (Deployment/Rollout), ReplicationController (DeploymentConfig), Job (CronJob), and related Pod owner lookups through this helper.

The 40-day case from the issue (--history_duration 960) takes the range path. The 95-day cap matches the AMP limit cited in the issue. I did not inspect the test file, so test coverage is taken from the PR description and the change summary, not from source.

Full details: Out of Scope Changes check

Explanation

All changed areas connect to the AMP long-history behavior in #522, or are small supporting changes disclosed in the PR description:

  • prometheus_utils.py: adds the AMP constants (32d minimum, 95d maximum, 1h step) used by the helper and runner.
  • prometheus_metrics_service.py: the helper and the owner lookup call sites implement the requirement. The query/query_range return annotations are type-only. The total_seconds() step fix corrects step serialization for steps of one day or longer. It is adjacent to range-query step handling and applies to all query_range callers. It is a small behavior fix, not an unrelated change.
  • runner.py: _adjust_amp_query_limits() caps AMP history_duration at 95 hours-equivalent (2280h) with a warning. This keeps owner, CPU, and memory collection on the same period, which the AMP 95-day limit requires. It also moves the existing AMP timeframe step-count adjustment into the same method without changing its logic. Both branches apply only when eks_managed_prom is set.
  • Tests: the PR description and summary list tests for the new behavior. I did not inspect the test files.

No change was found that lacks a connection to #522 or to the AMP limits it describes.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

Copy link
Copy Markdown
Author

Hi maintainers, a gentle follow-up on this fix for #522. Could someone take a look when you have a chance?

I've addressed CodeRabbit's docstring coverage warning in 5230315. CodeRabbit now reports 81.82% coverage (above the 80% threshold), and all five of its pre-merge checks pass. This follow-up only adds docstrings; it does not change the query logic.

Validation on macOS with Python 3.10: pytest -q — 72 passed; Black checks for the changed files and git diff --check also passed. Testing against a live AMP instance remains outstanding, as noted in the PR description.

The PR has no merge conflicts and is awaiting the required maintainer review. I'd appreciate your feedback, including whether you'd like any additional validation before approval. Thank you!

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.

AWS Managed Prometheus (AMP) rejects instant queries with >31d lookback range

2 participants