Skip to content

TRT-2814: Eliminate prow_job_runs_report_matview - #3828

Open
mstaeble wants to merge 1 commit into
openshift:mainfrom
mstaeble:TRT-2814-eliminate-job-runs-matview
Open

TRT-2814: Eliminate prow_job_runs_report_matview#3828
mstaeble wants to merge 1 commit into
openshift:mainfrom
mstaeble:TRT-2814-eliminate-job-runs-matview

Conversation

@mstaeble

@mstaeble mstaeble commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Summary

  • Replaces prow_job_runs_report_matview with a two-phase direct query in JobsRunsReportFromDB: Phase 1 paginates from base tables (prow_job_runs + prow_jobs), Phase 2 enriches the paginated page with test name arrays, pull request data, and annotations via errgroup.
  • Removes the matview definition and its entry from PostgresMatViews, eliminating a ~90-second refresh that blocked data loading.
  • Reads test_failures and test_flakes directly from stored columns on prow_job_runs (populated at insert time by the prow loader), eliminating the runtime subqueries the matview used to compute these counts.
  • Refactors pkg/filter to export FilterItemToSQL (column-expression based) and FilterFieldToSQL (type-aware with array/timestamp handling), replacing the unexported orFilterToSQL.
  • Adds sortable: false to test name columns in the frontend and returns ValidationError for unsortable sort fields.
  • Fixes ILIKE wildcard escaping globally: consolidates escapeLikeMetachars into an exported filter.EscapeLikeMetachars and applies it at all 12 ILIKE pattern construction sites (FilterItemToSQL, FilterFieldToSQL, andFilterToSQL, testNameFilterSQL). Previously, user-provided % and _ characters in filter values acted as ILIKE wildcards, causing unintended matches.

Key design decisions

  • Stored counts, not runtime aggregation: test_failures and test_flakes are read directly from prow_job_runs columns rather than computed via subqueries or CTEs. These columns are populated at insert time by the prow loader (TRT-2834), so no runtime aggregation is needed.
  • Conditional JOINs: PR join is added only when needed for filtering or sorting, split into filter-required (before COUNT) and sort-only (after COUNT) to avoid unnecessary work during pagination counting.
  • NULL-safe HasEntry: Uses COALESCE(col, '{}') to ensure NOT wrapping works correctly for NULL arrays.
  • Test name filtering: Uses EXISTS subqueries against prow_job_run_tests rather than array column filters, matching the previous matview behavior.

Test plan

  • Lint passes (make lint)
  • Unit tests pass (make test)
  • Integration tests pass (make integration) with 43 test functions covering:
    • Basic query, pagination, release filtering, timestamp windowing
    • Sorting by timestamp, test_failures, test_flakes, job name
    • All filter operators: =, !=, >, >=, <, <=, contains, startsWith, endsWith, hasEntry, hasEntryContaining, isEmpty, isNotEmpty
    • All filter dispatch paths: test name EXISTS, column aliases, generic filter
    • Fields: job, brief_name, cluster, overall_result, variants, timestamp (epoch), test_failures, test_flakes, failed/flaked/ran_test_names, pull_request_* fields
    • AND/OR link operators, NOT negation, cross-dispatch-path OR combinations
    • Pagination edge cases (beyond results, partial last page)
    • Enrichment: annotations, pull requests, test name arrays
    • Boundary conditions: report end exclusion, lookback window
    • Validation: unsortable field rejection
  • Independent code review found no correctness issues
  • Independent test coverage analysis verified all filter paths and operators are tested
  • Verified against staging database (20,446 runs for release 4.19)

Staging verification (sippy-staging, release 4.19)

All 10 checks passed against the staging PostgreSQL database with real production-scale data:

# Test Result
1 Basic paginated query (perPage=5, sort=timestamp desc) 20,446 total rows, correct fields (brief_name, variants, cluster, timestamp)
2 Pagination consistency (page 0 vs page 1) Stable TotalRows, zero overlap between pages
3 Job filter (job contains "aws") 6,307 results, all job names contain "aws"
4 NOT negation (NOT job contains "aws") 14,139 results, no job names contain "aws"
5 Test name filter + enrichment (failed_test_names contains "etcd") 177 results, failed_test_names populated with matching etcd tests
6 ILIKE escaping (e2e_aws vs e2e-aws) Literal underscore: 0 results. Hyphen: 5,164 results. Confirms escaping works.
7 Annotations enrichment 6/25 runs have annotations (e.g. release.openshift.io/architecture)
8 Sort by test_failures descending Correctly ordered: 650, 361, 324, 314, 302
9 Zero matching rows (job = "nonexistent-job-xyz") TotalRows=0, empty rows, no error
10 Sort by PR field doesn't inflate TotalRows Identical count (20,446) for sort-by-id and sort-by-pull_request_author

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Job run reports now support richer filtering and sorting, including test names, pull request fields, variants, timestamps, failures, and flakes.
    • Report results include relevant pull request metadata, annotations, and failed or flaked test names.
    • Negated filters, combined conditions, special-character searches, and pagination are handled more consistently.
    • Hidden test-name columns in the job runs table are no longer sortable.
  • Bug Fixes

    • Prevented duplicate job runs when multiple pull requests are linked.
    • Improved lookback boundary handling and filter-value matching.
  • Tests

    • Added comprehensive coverage for report filtering, sorting, pagination, enrichment, and edge cases.

@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 openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 25, 2026
@openshift-ci

openshift-ci Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Skipping CI for Draft Pull Request.
If you want CI signal for your change, please convert it to an actual PR.
You can still manually trigger a test run with /test all

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

openshift-ci-robot commented Jul 25, 2026

Copy link
Copy Markdown

@mstaeble: This pull request references TRT-2814 which is a valid jira issue.

Warning: The referenced jira issue has an invalid target version for the target branch this PR targets: expected the story to target the "5.0.0" version, but no target version was set.

Details

In response to this:

Summary

  • Replaces prow_job_runs_report_matview with a two-phase direct query in JobsRunsReportFromDB: Phase 1 paginates from base tables (prow_job_runs + prow_jobs), Phase 2 enriches the paginated page with test counts, test name arrays, pull request data, and annotations via errgroup.
  • Removes the matview definition and its entry from PostgresMatViews, eliminating a ~90-second refresh that blocked data loading.
  • Refactors pkg/filter to export FilterItemToSQL (column-expression based) and FilterFieldToSQL (type-aware with array/timestamp handling), replacing the unexported orFilterToSQL.
  • Adds sortable: false to test name columns in the frontend and returns ValidationError for unsortable sort fields.

Key design decisions

  • Conditional JOINs: Flake CTE and PR join are added only when needed for filtering or sorting, split into filter-required (before COUNT) and sort-only (after COUNT) to avoid unnecessary work during pagination counting.
  • NULL-safe HasEntry: Uses COALESCE(col, '{}') to ensure NOT wrapping works correctly for NULL arrays.
  • Test name filtering: Uses EXISTS subqueries against prow_job_run_tests rather than array column filters, matching the previous matview behavior.

Test plan

  • Lint passes (make lint)
  • Unit tests pass (make test)
  • Parity tested against old matview server with 17 test cases covering filters, sorts, and edge cases
  • Benchmarked on staging: direct query performs comparably to matview reads while eliminating refresh overhead
  • Independent code review found no correctness issues

🤖 Generated with Claude Code

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 commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

[APPROVALNOTIFIER] This PR is APPROVED

This pull-request has been approved by: mstaeble

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

The pull request process is described 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

@openshift-ci openshift-ci Bot added the approved Indicates a PR has been approved by an approver from all required OWNERS files. label Jul 25, 2026
@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@openshift-ci-robot Acknowledged. TRT-2814 needs its Jira target version set to 5.0.0 for this PR’s target branch.

@mstaeble

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai

coderabbitai Bot commented Jul 25, 2026

Copy link
Copy Markdown
Contributor

Walkthrough

The job-runs report now uses dynamic queries over base tables instead of a materialized view, supports expanded filter semantics, and concurrently enriches paginated rows with test names, pull requests, and annotations. Integration tests cover filtering, sorting, pagination, enrichment, and boundary cases.

Changes

Job runs reporting

Layer / File(s) Summary
Filter SQL contracts
pkg/filter/filterable.go, pkg/db/query/cumulative_query.go, pkg/db/query/cumulative_query_test.go
Adds reusable negation and field-aware SQL conversion for scalar, array, timestamp, and ILIKE filters, with centralized LIKE metacharacter escaping.
Dynamic report query
pkg/api/job_runs.go
Replaces the materialized-view path with base-table queries, conditional pull-request joins, rewritten test-name filters, pagination, sorting, and total-count handling.
Concurrent enrichment
pkg/api/job_runs.go
Enriches result rows concurrently with test-name arrays, pull-request metadata, and release-scoped annotations.
Report validation
test/integration/job_runs_report.go, test/integration/jobs_test.go
Adds seeded report fixtures and coverage for filtering, sorting, pagination, enrichment, negation, variants, and time boundaries.
Materialized-view cleanup
pkg/db/views.go, pkg/flags/postgres_benchmarking_test.go, sippy-ng/src/jobs/JobRunsTable.jsx
Removes the job-runs materialized view and benchmark, and disables sorting for hidden test-name columns.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant JobsRunsReportFromDB
  participant PostgreSQL
  participant errgroup
  JobsRunsReportFromDB->>PostgreSQL: Execute dynamic filtered and paginated query
  PostgreSQL-->>JobsRunsReportFromDB: Return base job-run rows and total count
  JobsRunsReportFromDB->>errgroup: Start concurrent enrichment tasks
  errgroup->>PostgreSQL: Query test names, pull requests, and annotations
  PostgreSQL-->>errgroup: Return enrichment data
  errgroup-->>JobsRunsReportFromDB: Complete enriched report rows
Loading

Possibly related PRs

  • openshift/sippy#3834: Adds stored flake-count data used by this report’s flake filtering and enrichment.

Suggested labels: lgtm

Suggested reviewers: smg247, xueqzhan


Caution

Pre-merge checks failed

Please resolve all errors before merging. Addressing warnings is optional.

  • Ignore

❌ Failed checks (1 error, 1 warning)

Check name Status Explanation Resolution
Sql Injection Prevention ❌ Error FAIL: FilterFieldToSQL formats user-supplied f.Field into SQL via %q with no whitelist/identifier escaping, so arbitrary filter fields can reach raw SQL. Whitelist allowed fields and map them to fixed SQL expressions, or quote identifiers with pq.QuoteIdentifier; never accept raw field strings in SQL builders.
Ipv6 And Disconnected Network Test Compatibility ⚠️ Warning New integration tests use testcontainers with docker.io/library/postgres:16, which can require public-registry access in disconnected CI. Mirror the Postgres image to an internal registry or offline cache (or skip in disconnected jobs) so the tests don't rely on docker.io.
✅ Passed checks (19 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main change: removing prow_job_runs_report_matview.
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.
Go Error Handling ✅ Passed No unsafe error handling found in the changed paths; the only blank identifier is the hardcoded version.NewVersion("4.12") constructor.
Excessive Css In React Should Use Styles ✅ Passed JobRunsTable.jsx only uses a few small inline style objects (max 4 properties); no excessive CSS or need for useStyles is evident.
Test Coverage For New Features ✅ Passed PASS: New query/filter logic has broad integration coverage plus unit tests for EscapeLikeMetachars, wildcard escaping, sorting, pagination, PRs, annotations, and variants.
Single Responsibility And Clear Naming ✅ Passed New code is split into narrowly named helpers (filter SQL, enrichment, escaping); the report method stays a top-level orchestrator.
Feature Documentation ✅ Passed No docs/features page covers the changed job-runs report/filter feature; the only feature doc is unrelated, so no required feature-doc update was missed.
Stable And Deterministic Test Names ✅ Passed No Ginkgo titles found; changed tests use static Test... funcs and literal subtest names, with table-driven names coming from fixed case lists.
Test Structure And Quality ✅ Passed PASS: These are standard testing.T integration tests, not Ginkgo; they use per-test DB clones with t.Cleanup, have no cluster waits, and the added subtests are focused.
Microshift Test Compatibility ✅ Passed Added tests are plain DB integration tests, not Ginkgo e2e, and reference no unsupported OpenShift APIs, namespaces, or HA assumptions.
Single Node Openshift (Sno) Test Compatibility ✅ Passed Added tests are plain DB integration tests, not Ginkgo e2e; they contain no multi-node/topology assumptions or SNO skip needs.
Topology-Aware Scheduling Compatibility ✅ Passed Only backend/query, filter, test, and UI files changed; no deployment manifests, controllers, or pod-scheduling constraints were introduced.
Ote Binary Stdout Contract ✅ Passed No stdout writes were added in main/init/TestMain or suite setup; only ordinary test/benchmark helper prints remain, and TestMain logs to stderr.
No-Weak-Crypto ✅ Passed Changed files contain no MD5/SHA1/DES/RC4/3DES/Blowfish/ECB usage, custom crypto, or secret/token comparisons.
Container-Privileges ✅ Passed No changed file adds privileged/hostPID/hostNetwork/hostIPC/SYS_ADMIN/allowPrivilegeEscalation; diff only touches query/filter/test/frontend code, not K8s manifests.
No-Sensitive-Data-In-Logs ✅ Passed No new or modified log statements in the diff expose secrets/PII; added code uses parameterized SQL and the new tests don't log data.
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 4

🧹 Nitpick comments (4)
pkg/api/job_runs.go (2)

151-175: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Use errgroup.WithContext and add context to enrichment errors.

Four independent queries fan out per request with no cancellation and no error context. When one fails, the others keep running to completion against the pool, and the caller receives a bare driver error with no indication of which enrichment failed. errgroup.WithContext plus a short fmt.Errorf("...: %w", err) per branch (or per helper) makes failures diagnosable and lets siblings abort early.

🤖 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 `@pkg/api/job_runs.go` around lines 151 - 175, The enrichment fan-out around
the errgroup in the job-run loading flow lacks cancellation and identifies no
failing enrichment. Replace the plain errgroup with errgroup.WithContext, pass
the derived context into each enrichment helper if supported, and wrap each
branch’s error with a short enrichment-specific fmt.Errorf using %w so sibling
queries cancel when one fails.

204-233: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add unit tests for the new pure helpers.

analyzeJobRunFilters, isTestNameField, and testNameFilterSQL are dependency-free and encode the join/dispatch decisions the whole refactor rests on; pkg/api/job_runs_test.go already exists. Table-driven cases (sort on test_flakes, sort on a PR column, mixed filter fields, each test-name operator) would lock in behavior without a database.

As per coding guidelines, "new Go functions and methods need unit tests".

🤖 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 `@pkg/api/job_runs.go` around lines 204 - 233, Add table-driven unit tests in
the existing pkg/api/job_runs_test.go for analyzeJobRunFilters, isTestNameField,
and testNameFilterSQL. Cover sorting by test_flakes, sorting by a pull-request
column, mixed filter fields, and every supported test-name operator, asserting
the expected helper outputs without database dependencies.

Source: Coding guidelines

pkg/filter/filterable.go (2)

148-151: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Unknown operator silently produces invalid SQL.

The default branch emits UnknownFilterOperator() as a SQL fragment. Callers (e.g. applyJobRunFilters in pkg/api/job_runs.go) splice this straight into the WHERE clause, so a bad operatorValue from the client surfaces as a Postgres "function does not exist" error / 500 rather than a 400 validation error. Consider returning an error (or an empty fragment the caller can reject) so the API can respond with ValidationError.

Note this is a behavior widening compared to andFilterToSQL, which simply ignores unknown operators.

🤖 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 `@pkg/filter/filterable.go` around lines 148 - 151, The default branch in the
filter-to-SQL conversion must reject unknown operators instead of returning the
invalid “UnknownFilterOperator()” SQL fragment. Update the relevant filter
conversion method and its callers, including applyJobRunFilters, to propagate
the validation error so invalid client operators produce a ValidationError/400
response; preserve handling for supported operators and the existing
andFilterToSQL behavior.

154-176: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add unit coverage for the new exported SQL generators.

FilterItemToSQL and FilterFieldToSQL now carry the negation/array/timestamp semantics that orFilterToSQL used to own, and they are consumed cross-package by pkg/api/job_runs.go. pkg/filter/filterable_test.go is the natural home for table-driven assertions on the emitted fragment + param per operator (especially OperatorHasEntry with Not, and OperatorIsNotEmpty, where the old optNot(!f.Not) inversion was replaced by WrapNot).

As per coding guidelines, "new Go functions and methods need unit tests".

🤖 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 `@pkg/filter/filterable.go` around lines 154 - 176, Add table-driven unit tests
in filterable_test.go covering the exported FilterItemToSQL and FilterFieldToSQL
methods, asserting both emitted SQL fragments and parameters for each operator.
Include array-aware negation for OperatorHasEntry with Not, timestamp handling
in FilterFieldToSQL, and the OperatorIsNotEmpty behavior using WrapNot rather
than the former optNot inversion. Reuse existing test conventions and cover
representative scalar, array, and timestamp cases.

Source: Coding guidelines

🤖 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 `@pkg/api/job_runs.go`:
- Around line 318-352: Reject unsupported operators instead of converting them
into SQL. In pkg/api/job_runs.go lines 318-352, update testNameFilterSQL to
handle only supported operators explicitly and return an error for unknown
values, propagating it to the existing 400 ValidationError path. In
pkg/filter/filterable.go lines 148-151, change FilterItemToSQL to return an
error or empty fragment with an ok indicator rather than
UnknownFilterOperator(), and update its callers to reject invalid operators as
client validation errors.
- Around line 305-311: Update the clause construction in the job-run query
around the filter.LinkOperatorOr branch so OR-joined clauses are explicitly
grouped in parentheses before passing them to q.Where. Preserve the existing AND
join behavior and argument ordering, ensuring subsequent release and timestamp
conditions cannot change the OR expression’s precedence.
- Around line 386-421: Update enrichJobRunsWithTestNames and its query to
populate the ran_test_names API field with all test names associated with each
job run, while retaining the existing failed and flaked name projections for
statuses 12 and 13. Ensure job runs with tests outside those statuses receive
their names so frontend results do not default to Pass.

In `@sippy-ng/src/jobs/JobRunsTable.jsx`:
- Around line 365-381: Update the sortField initialization or validation in the
JobRunsTable component so URL-provided fields that map to columns with sortable:
false fall back to the existing default sort field. Preserve valid sortable URL
values and use the column definitions as the source of truth, including
flaked_test_names and ran_test_names.

---

Nitpick comments:
In `@pkg/api/job_runs.go`:
- Around line 151-175: The enrichment fan-out around the errgroup in the job-run
loading flow lacks cancellation and identifies no failing enrichment. Replace
the plain errgroup with errgroup.WithContext, pass the derived context into each
enrichment helper if supported, and wrap each branch’s error with a short
enrichment-specific fmt.Errorf using %w so sibling queries cancel when one
fails.
- Around line 204-233: Add table-driven unit tests in the existing
pkg/api/job_runs_test.go for analyzeJobRunFilters, isTestNameField, and
testNameFilterSQL. Cover sorting by test_flakes, sorting by a pull-request
column, mixed filter fields, and every supported test-name operator, asserting
the expected helper outputs without database dependencies.

In `@pkg/filter/filterable.go`:
- Around line 148-151: The default branch in the filter-to-SQL conversion must
reject unknown operators instead of returning the invalid
“UnknownFilterOperator()” SQL fragment. Update the relevant filter conversion
method and its callers, including applyJobRunFilters, to propagate the
validation error so invalid client operators produce a ValidationError/400
response; preserve handling for supported operators and the existing
andFilterToSQL behavior.
- Around line 154-176: Add table-driven unit tests in filterable_test.go
covering the exported FilterItemToSQL and FilterFieldToSQL methods, asserting
both emitted SQL fragments and parameters for each operator. Include array-aware
negation for OperatorHasEntry with Not, timestamp handling in FilterFieldToSQL,
and the OperatorIsNotEmpty behavior using WrapNot rather than the former optNot
inversion. Reuse existing test conventions and cover representative scalar,
array, and timestamp cases.
🪄 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 YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: 87c0d531-857b-4583-a19c-e8b85ce1e8ae

📥 Commits

Reviewing files that changed from the base of the PR and between 1c5aaf7 and 1157298.

📒 Files selected for processing (5)
  • pkg/api/job_runs.go
  • pkg/db/views.go
  • pkg/filter/filterable.go
  • pkg/flags/postgres_benchmarking_test.go
  • sippy-ng/src/jobs/JobRunsTable.jsx
💤 Files with no reviewable changes (2)
  • pkg/db/views.go
  • pkg/flags/postgres_benchmarking_test.go

Comment thread pkg/api/job_runs.go
Comment thread pkg/api/job_runs.go Outdated
Comment thread pkg/api/job_runs.go
Comment thread sippy-ng/src/jobs/JobRunsTable.jsx
@mstaeble
mstaeble force-pushed the TRT-2814-eliminate-job-runs-matview branch 2 times, most recently from 59c83ec to d771bb9 Compare July 26, 2026 14:39
@mstaeble
mstaeble marked this pull request as ready for review July 26, 2026 15:00
@mstaeble mstaeble changed the title [WIP] TRT-2814: Eliminate prow_job_runs_report_matview TRT-2814: Eliminate prow_job_runs_report_matview Jul 26, 2026
@openshift-ci openshift-ci Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 26, 2026
@openshift-ci
openshift-ci Bot requested review from smg247 and xueqzhan July 26, 2026 15:00
@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Scheduling required tests:
/test e2e

@mstaeble

Copy link
Copy Markdown
Contributor Author

@coderabbitai resolve

@openshift-ci openshift-ci Bot added the ready-for-human-review Indicates a PR has been reviewed by automated tools and is ready for human review label Jul 26, 2026
@coderabbitai

coderabbitai Bot commented Jul 26, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Comments resolved and changes approved.

@mstaeble mstaeble changed the title TRT-2814: Eliminate prow_job_runs_report_matview [WIP] TRT-2814: Eliminate prow_job_runs_report_matview Jul 29, 2026
@mstaeble
mstaeble marked this pull request as draft July 29, 2026 16:04
@openshift-ci openshift-ci Bot added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 29, 2026
@mstaeble
mstaeble force-pushed the TRT-2814-eliminate-job-runs-matview branch 3 times, most recently from 9354237 to e1fb97c Compare July 29, 2026 22:21
@openshift-ci openshift-ci Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jul 29, 2026
@mstaeble
mstaeble force-pushed the TRT-2814-eliminate-job-runs-matview branch from e1fb97c to 42d55af Compare July 30, 2026 01:45
@openshift-ci openshift-ci Bot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jul 30, 2026
@mstaeble
mstaeble force-pushed the TRT-2814-eliminate-job-runs-matview branch from 42d55af to 11b0f66 Compare July 30, 2026 13:26
@mstaeble

Copy link
Copy Markdown
Contributor Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 30, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Full review finished.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
test/integration/job_runs_report_test.go (1)

22-25: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Prefix these package-level vars like the jr* helpers.

reportEnd and lookback are generic names in the shared integration package; the file already adopts a jr prefix for helpers to avoid collisions with component_readiness_test.go (Line 155). Same treatment here avoids a future redeclaration conflict.

🤖 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 `@test/integration/job_runs_report_test.go` around lines 22 - 25, Rename the
package-level variables reportEnd and lookback to use the existing jr-prefixed
naming convention, and update all references in the test accordingly. Preserve
their current time values and behavior while avoiding collisions with other
integration tests.
pkg/api/job_runs.go (1)

213-221: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use the v1.TestStatus* constants instead of literal 12/13.

The same codes are hardcoded again in enrichJobRunsWithTestNames (Lines 329-334), so the mapping is duplicated in three places. Deriving them from v1.TestStatusFailure / v1.TestStatusFlake keeps the report in sync if the enum ever changes.

♻️ Suggested change
 var testNameStatuses = map[string]int{
-	"ran_test_names":    0,
-	"failed_test_names": 12,
-	"flaked_test_names": 13,
+	"ran_test_names":    0,
+	"failed_test_names": int(v1.TestStatusFailure),
+	"flaked_test_names": int(v1.TestStatusFlake),
 }
🤖 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 `@pkg/api/job_runs.go` around lines 213 - 221, The testNameStatuses map uses
hardcoded status codes that should come from the v1 enum constants. Replace the
12 and 13 values with v1.TestStatusFailure and v1.TestStatusFlake, and update
the corresponding mappings in enrichJobRunsWithTestNames to reuse these
constants rather than duplicating literals.
🤖 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 `@pkg/api/job_runs.go`:
- Around line 368-379: The PR-resolution queries use nondeterministic DISTINCT
ON selection. In pkg/api/job_runs.go lines 368-379, extend the ORDER BY in the
Raw query with the same unique secondary ordering, such as
jrpp.prow_pull_request_id DESC; apply that identical ordering in the LEFT JOIN
DISTINCT ON subquery at lines 73-77 so both paths consistently select the same
PR.
- Around line 88-101: Update the job-runs query construction around the existing
count and join logic to always apply a deterministic order before LIMIT/OFFSET
pagination, including when no SortField is provided. Preserve the requested sort
direction and append the unique prow_job_runs.id column as a final tiebreaker
for every supported sort field, including timestamp, test_failures, and job.

---

Nitpick comments:
In `@pkg/api/job_runs.go`:
- Around line 213-221: The testNameStatuses map uses hardcoded status codes that
should come from the v1 enum constants. Replace the 12 and 13 values with
v1.TestStatusFailure and v1.TestStatusFlake, and update the corresponding
mappings in enrichJobRunsWithTestNames to reuse these constants rather than
duplicating literals.

In `@test/integration/job_runs_report_test.go`:
- Around line 22-25: Rename the package-level variables reportEnd and lookback
to use the existing jr-prefixed naming convention, and update all references in
the test accordingly. Preserve their current time values and behavior while
avoiding collisions with other integration tests.
🪄 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 YAML (base), Central YAML (inherited)

Review profile: CHILL

Plan: Pro Plus

Run ID: e702e4b6-2cef-47c8-9aaa-22117c92627e

📥 Commits

Reviewing files that changed from the base of the PR and between 1a9b0a3 and 11b0f66.

📒 Files selected for processing (9)
  • pkg/api/job_runs.go
  • pkg/db/query/cumulative_query.go
  • pkg/db/query/cumulative_query_test.go
  • pkg/db/views.go
  • pkg/filter/filterable.go
  • pkg/flags/postgres_benchmarking_test.go
  • sippy-ng/src/jobs/JobRunsTable.jsx
  • test/integration/job_runs_report_test.go
  • test/integration/jobs_test.go
💤 Files with no reviewable changes (2)
  • pkg/db/views.go
  • pkg/flags/postgres_benchmarking_test.go

Comment thread pkg/api/job_runs.go
Comment thread pkg/api/job_runs.go Outdated
@mstaeble
mstaeble force-pushed the TRT-2814-eliminate-job-runs-matview branch 2 times, most recently from 15fd099 to f18213b Compare July 30, 2026 13:53
@openshift-ci openshift-ci Bot added the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jul 30, 2026
@mstaeble
mstaeble force-pushed the TRT-2814-eliminate-job-runs-matview branch from f18213b to d189454 Compare July 31, 2026 13:16
@openshift-ci openshift-ci Bot removed the needs-rebase Indicates a PR cannot be merged because it has merge conflicts with HEAD. label Jul 31, 2026
Replace the materialized view with a two-phase direct query in
JobsRunsReportFromDB. Phase 1 paginates from prow_job_runs JOIN prow_jobs
with proper filtering and sorting. Phase 2 enriches the paginated IDs
with test names, PR data, and annotations via errgroup.

Key changes:
- Use stored test_flakes column (from TRT-2834) instead of runtime subquery
- Return ValidationError (400) for unsupported test name filter operators
- Wrap OR-joined filter clauses in parentheses for correct SQL precedence
- Add 20 integration tests covering pagination, sorting, filtering,
  enrichment, and error cases

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@mstaeble
mstaeble force-pushed the TRT-2814-eliminate-job-runs-matview branch from d189454 to 7cdc7cb Compare July 31, 2026 13:23
@mstaeble
mstaeble marked this pull request as ready for review July 31, 2026 15:24
@mstaeble mstaeble changed the title [WIP] TRT-2814: Eliminate prow_job_runs_report_matview TRT-2814: Eliminate prow_job_runs_report_matview Jul 31, 2026
@openshift-ci openshift-ci Bot removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label Jul 31, 2026
@openshift-ci
openshift-ci Bot requested a review from petr-muller July 31, 2026 15:24
@mstaeble

Copy link
Copy Markdown
Contributor Author

@coderabbitai resolve

@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor
✅ Action performed

Comments resolved and changes approved.

@openshift-merge-bot

Copy link
Copy Markdown
Contributor

Scheduling required tests:
/test e2e

@openshift-ci

openshift-ci Bot commented Jul 31, 2026

Copy link
Copy Markdown
Contributor

@mstaeble: all tests passed!

Full PR test history. Your PR dashboard.

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. I understand the commands that are listed here.

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

Labels

approved Indicates a PR has been approved by an approver from all required OWNERS files. jira/valid-reference Indicates that this PR references a valid Jira ticket of any type. 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