Skip to content

ISSUE #30151 - Incident Grouping Endpoint - #30367

Merged
TeddyCr merged 23 commits into
open-metadata:mainfrom
TeddyCr:ISSUE-30151
Jul 29, 2026
Merged

TeddyCr merged 23 commits into
open-metadata:mainfrom
TeddyCr:ISSUE-30151

Conversation

@TeddyCr

@TeddyCr TeddyCr commented Jul 22, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes #30151

I worked on the Incident Manager "Grouped Incidents" backend because the incident manager redesign needs incidents normalized into triageable groups (by table, test definition, or test-case owner) instead of a flat alert list, and the existing APIs could neither serve the grouped view nor scale to catalogs with deep incident history.

New API surface

  • GET /v1/dataQuality/testCases/testCaseIncidentStatus/incidentGroups — distinct open incidents grouped by table, testDefinition, or owner. Each group carries the full row the UI renders: incidentCount, most-critical severity, triage-ranked status (Assigned > Ack > New), current assignees + assigneeCount, firstSeen/lastSeen, and an 8-bucket trend with a Rising/Falling/Steady direction (the "recurring" signal). Filters: open statuses, current assignee, test case, domain, and a createdAt/updatedAt date range; sortable and paginated with opaque cursors.
  • Drill-down filters on the existing incident list endpoint: testDefinition, owner (direct user/team owner of the test case), and a repaired assignee — so every group row can open its exact incident population.
  • PUT /v1/dataQuality/testCases/testCaseIncidentStatus/bulk — bulk status/severity changes for up to 100 incidents per call (the UI's "Set status / Set severity on selection"), following the platform's BulkOperationResult pattern with per-entry validation, authorization, and success/failure detail.
  • failureSummary denormalized onto every incident record at write time (failed result → incident task payload → sync handler), so incident listings can show the failure reason without a per-incident result lookup (no N+1).

Fixes shipped along the way (all found by tests or scale-testing this feature)

  • The incident-groups cursor was emitted Base64-encoded but the endpoint only accepted a plain int offset — cursors now round-trip opaquely like the sibling list endpoint.
  • Time-series listings without a startTs/endTs reported paging.total: 0 (the count query evaluated timestamp BETWEEN NULL AND NULL), which also suppressed the after cursor. Fixed in EntityTimeSeriesRepository for all time-series entities.
  • The incident list's assignee filter silently returned nothing: the generic assignee param had been repurposed by the task listing (name-hash → ASSIGNED_TO relationships). The incident list now maps it to a column comparison (incidentAssignee).
  • docker/mysql/Dockerfile_mysql was pinned to the discontinued mysql/mysql-server:latest (frozen at 8.0.32, which crash-loops on a purge-thread FK assertion on case-insensitive filesystems). Swapped to the maintained mysql:8.0.

Type of change:

  • New feature

High-level design:

Query architecture. An incident is a stateId chain of status records in test_case_resolution_status_time_series. The grouping query reduces the chain in a chain CTE (GROUP BY stateId over the new (stateId, timestamp) index for first/last timestamps) and joins back on the last timestamp for the current status/assignee/severity — deliberately avoiding ROW_NUMBER/MIN/MAX window functions, which materialize three buffered passes over the whole table at scale. One SQL round-trip serves the entire page: the group total rides on COUNT(*) OVER () and the per-group trend timestamps ride on JSON_ARRAYAGG/JSON_AGG (chosen over GROUP_CONCAT/STRING_AGG because JSON aggregates have no group_concat_max_len-style cap that would silently truncate a large group's trend). Trend bucketing and direction stay in Java (TestCaseResolutionStatusRepository), keeping the SQL dialect-free.

Layering. All SQL lives in CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO — the CTE templates, the dialect-specific @Define expressions (severityExpr, assigneesExpr, createdAtAgg, dimension joins), and the parts assembly that splices ListFilter output into the right sub-query. The repository holds only orchestration and business mapping (rank→status, trend buckets, entity-reference resolution); the resource holds request parsing/auth. addOriginEntityFQNJoin moved from the repository into the DAO to complete the separation.

Write-time denormalization. failureSummary is captured when a failed test result opens an incident: the result text travels through getOrCreateIncident into the Task payload's existing failureReason field, and IncidentTcrsSyncHandler stamps it onto every TCRS record of the chain. Read paths never join to test results. Records predating the change are not backfilled (the field is optional).

Bulk endpoint. One-pass shape borrowed from EntityResource.processBulkRequest: all referenced test cases resolve via a single findEntityByNames batch and the caller reference resolves once; the per-entry loop then authorizes and creates with zero lookups. Synchronous by design — the caller is an interactive selection capped at 100 entries that needs inline per-entry results; the async/202 path can be added if a bot-scale consumer appears.

Alternatives considered and rejected

  • Embedding incident lists inside group rows: unbounded nested payloads needing their own pagination; the drill-down filters make each group's population addressable instead.
  • Window-function CTE (original implementation): measured 3× slower per execution at 100k+ rows and ran three times per request (count + page + trend); replaced as above (measured ~10× end-to-end on the groups endpoint).
  • STRAIGHT_JOIN hints for the chain join: measured slower than the optimizer's plan; SQL stays hint-free and portable.
  • Incident summary rollup table: the right long-term answer for O(open-incidents) reads at any history depth (and would also fix the pre-existing latest=true slow path), but it is a migration + dual-write + backfill feature of its own; deliberately left as follow-up.

Migrations / rollout. Additive only: 2.1.0 native migrations add four indexes — (stateId, timestamp), (entityFQNHash, timestamp), and (assignee, timestamp) on the time-series table, and (id) on test_case (which predates the PRIMARY KEY(id) convention; the relationship join had no index target). New schema fields are optional; no data migration. The mysql:8.0 image swap affects fresh dev environments on next image build; volumes initialized by 8.0.32 upgrade in place.

Tests:

Use cases covered

  • Incident manager groups by table, test definition, and owner with correct open-incident counts (resolved chains and deleted test cases excluded; a co-owned test case's incident counts once per owner but never twice within a group)
  • Group rows render severity (most critical), status rollup, assignees, first/last seen, and trend sparkline data; a single-incident group reads Steady with all activity in the first bucket
  • Group filters: open statuses (Resolved rejected with 400), current assignee, single test case, domain, createdAt/updatedAt date ranges; count-sorted ascending/descending
  • Cursor pagination walks every group exactly once, forward and backward, with exact before/after arithmetic and correct behavior past the end of the list
  • Drill-down listings scoped by test definition, by direct owner (user or team), and by assignee — including latest=true — with 404 on unknown filter targets
  • Bulk status change applies per-entry with partial-success reporting; the applied entry appends to the incident chain
  • A failed test result opens an incident whose records carry the denormalized failure text
  • Unranged incident listings report real totals and working pagination cursors

Unit tests

  • Files updated: openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepositoryTest.java (15 tests; join-builder tests follow the helper to its new DAO location)

Backend integration tests

  • I added integration tests in openmetadata-integration-tests/ for new/changed API endpoints.
  • Files added/updated: openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java — 27 tests covering everything under "Use cases" above, run green on both PostgreSQL and MySQL (the SQL uses dialect-specific aggregate/JSON expressions, so both matter). New behaviors were RED-verified: each test was shown to fail with the feature toggled off (null aggregates, unfiltered result sets, 405 on the bulk path, missing failure summary, total=0 paging) before going green.

Ingestion integration tests

  • Not applicable (sample-data fixture updates only; no connector logic changes).

Playwright (UI) tests

  • Not applicable (backend + generated TS models only; UI implementation is a follow-up PR).

Manual testing performed

  1. Started the local stack (docker/development, MySQL) with the branch build; verified the 2.1.0 migrations create all four new indexes on a fresh volume.
  2. Generated a synthetic catalog via API + SQL (800 tables, ~2,000 test cases, 200 users, 60 test definitions, 200k incident records / ~17k open incidents in realistic chains) and probed every endpoint with curl.
  3. Measured on the running server at 200k records: groups 0.57–1.37 s for all three dimensions (vs 4.4–5.4 s for the original window-CTE implementation at half that volume), drill-down filters 40–144 ms, cursor page 2 at 697 ms with stable totals.
  4. Verified cursor round-tripping (paging.after → offset), totals without time ranges, the repaired assignee filter (2.1 s → 40 ms after its index), and Rising/Falling/Steady trend variety across groups with different incident time profiles.

UI screen recording / screenshots:

Not applicable.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: I updated the migration scripts or explained why it is not needed.
  • For UI changes: I attached a screen recording and/or screenshots above. (Not applicable — no UI changes.)
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.
  • The issue properly describes why the new feature is needed, what's the goal, and how we are building it.
  • I have updated the documentation. (API documentation is carried by the OpenAPI annotations on the new endpoints; no separate docs page yet.)
  • I have added tests around the new logic.

Greptile Summary

This PR adds grouped incident management for data quality failures. The main changes are:

  • New grouped-incident and bulk-update API endpoints.
  • Incident filtering, cursor pagination, trends, and failure summaries.
  • A materialized incident summary table with MySQL and PostgreSQL migrations.
  • Updated SDK models, generated types, sample data, and integration tests.

Confidence Score: 5/5

The latest changes look safe to merge.

  • No distinct blocking issue remains within the scope of this follow-up review.
  • The updated incident summary path addresses the previously reported grouping behavior.

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java Adds incident-summary persistence and grouped incident queries.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java Adds grouped-result mapping and coordinated incident history updates.
openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java Exposes grouped incident, drill-down filtering, and bulk update operations.
bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql Adds indexes and the MySQL incident summary table.
bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql Adds indexes and the PostgreSQL incident summary table.

Reviews (11): Last reviewed commit: "chore: fix migration" | Re-trigger Greptile

Context used (3)

  • Context used - openmetadata-ui-core-components/CLAUDE.md (source)
  • Context used - CLAUDE.md (source)
  • Context used - AGENTS.md (source)

@TeddyCr
TeddyCr requested review from a team as code owners July 22, 2026 23:53
Copilot AI review requested due to automatic review settings July 22, 2026 23:53

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

The linked issue has a description and all required Shipping project fields set. Thanks!

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Jul 22, 2026
Copilot AI review requested due to automatic review settings July 22, 2026 23:55

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions

github-actions Bot commented Jul 22, 2026 •

Copy link
Copy Markdown
Contributor

🔴 Playwright Results — 3 test failure(s)

✅ 4527 passed · ❌ 3 failed · 🟡 29 flaky · ⏭️ 102 skipped

Shard Passed Failed Flaky Skipped
🟡 Shard 1 436 0 4 16
✅ Shard 2 11 0 0 0
🔴 Shard 3 821 1 9 8
🔴 Shard 4 809 2 4 25
🟡 Shard 5 829 0 4 5
🟡 Shard 6 829 0 3 46
🟡 Shard 7 792 0 5 2

Genuine Failures (failed on all attempts)

❌ Features/ContextCenterMemories.spec.ts › clearing search restores the unfiltered list (shard 3)
�[31mTest timeout of 180000ms exceeded.�[39m
❌ Features/OntologyExplorerRdf.spec.ts › term Relations Graph requests /rdf/glossary/graph scoped to the selected term (glossaryTermId) when RDF is enabled (shard 4)
�[31mTest timeout of 60000ms exceeded.�[39m
❌ Features/OntologyExplorerRdf.spec.ts › glossary Relations Graph calls /rdf/glossary/graph when RDF is enabled and renders nodes from the response (shard 4)
Error: GET /rdf/glossary/graph must be called on the glossary Relations Graph when RDF is enabled

�[2mexpect(�[22m�[31mreceived�[39m�[2m).�[22mtoBe�[2m(�[22m�[32mexpected�[39m�[2m) // Object.is equality�[22m

Expected: �[32mtrue�[39m
Received: �[31mfalse�[39m
🟡 29 flaky test(s) (passed on retry)
  • Features/TeamsHierarchy.spec.ts › Add teams in hierarchy (shard 1, 1 retry)
  • Flow/TestConnectionModal.spec.ts › failure state shows Edit Connection button and Retry Test button (shard 1, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab IS visible for supported type: chart (shard 1, 1 retry)
  • Flow/SearchRBAC.spec.ts › the browse tree only shows the asset-type categories a user can access (shard 1, 1 retry)
  • Features/BulkEditEntity.spec.ts › Glossary (shard 3, 1 retry)
  • Features/BulkEditEntity.spec.ts › Glossary Term (Nested) (shard 3, 1 retry)
  • Features/Container.spec.ts › expand / collapse should not appear after updating nested fields for container (shard 3, 1 retry)
  • Features/ContextCenterArchive.spec.ts › file in deleted folder is absent from search and not added to archive (shard 3, 1 retry)
  • Features/ContextCenterArticles.spec.ts › Article listing search filters, clears, and shows empty state (shard 3, 1 retry)
  • Features/ContextCenterArticles.spec.ts › Article edit persistence and unsaved title behavior are correct (shard 3, 1 retry)
  • Features/ContextCenterArticles.spec.ts › description: switching articles does not bleed unsaved content into next article (shard 3, 1 retry)
  • Features/ContextCenterMemories.spec.ts › editing memory type persists after save (shard 3, 1 retry)
  • Features/DataQuality/CertificationFilter.spec.ts › Certification filter narrows both table- and testCase-index queries via the flat field path (shard 3, 1 retry)
  • Features/ImpactAnalysis.spec.ts › Verify node depth display in table level impact analysis (shard 4, 1 retry)
  • Features/SearchExport.spec.ts › Export queues a background job and downloads from the jobs tray (shard 4, 1 retry)
  • Features/SearchSeparation/SearchSeparationSuite.ts › SearchIndexApp recreate reindex preserves searchable separation (shard 4, 1 retry)
  • Features/Table.spec.ts › should persist page size (shard 4, 1 retry)
  • Flow/CustomizeWidgets.spec.ts › Activity Feed Widget (shard 5, 1 retry)
  • Flow/ExploreDiscovery.spec.ts › Should display domain and owner of deleted asset in suggestions when showDeleted is on (shard 5, 1 retry)
  • Flow/PersonaDeletionUserProfile.spec.ts › User profile loads correctly before and after persona deletion (shard 5, 1 retry)
  • Pages/DataContracts.spec.ts › Contract Status badge should be visible on condition if Contract Tab is present/hidden by Persona (shard 5, 1 retry)
  • Pages/Entity.spec.ts › Domain Propagation (shard 6, 1 retry)
  • Pages/Entity.spec.ts › Domain Propagation (shard 6, 1 retry)
  • Pages/Entity.spec.ts › Certification Add Remove (shard 6, 1 retry)
  • Pages/Lineage/DataAssetLineage.spec.ts › verify create lineage for entity - Topic (shard 7, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify Impact Analysis service filter selection (shard 7, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab is NOT visible for pipelineService in platform lineage (shard 7, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab is NOT visible for apiService in platform lineage (shard 7, 1 retry)
  • Pages/TasksUIFlow.spec.ts › Create and reject tag task for Topic via UI (shard 7, 1 retry)

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

@github-actions

github-actions Bot commented Jul 23, 2026 •

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 65%
65.73% (76896/116982) 49.59% (46182/93124) 50.82% (13910/27371)

-- the approvedById guard in 2.0.0).

-- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups)
SET @ddl = (

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@TeddyCr btw I avoid the queries like this. It assumes the db user configured for OM will have permissions on information_schema.

@@ -1,4 +1,4 @@
FROM mysql/mysql-server:latest
FROM mysql:8.0

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@TeddyCr is this on purpose

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

yes, mysql/mysql-server:latest this one is not maintained anymore, it was updated 3 years ago
image

Copilot AI review requested due to automatic review settings July 24, 2026 17:17

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Jul 24, 2026
harshach
harshach previously approved these changes Jul 24, 2026
Copilot AI review requested due to automatic review settings July 25, 2026 04:34

Copilot AI 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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Jul 25, 2026
@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

@gitar-bot

gitar-bot Bot commented Jul 29, 2026

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 2 resolved / 3 findings

Adds the grouped incident backend for the redesigned Incident Manager, including incident group endpoints, bulk updates, failure summaries, and necessary database indexes. Consider adding an id tie-breaker to getLatestRecordBatchInternal to prevent non-deterministic results when timestamps tie.

💡 Edge Case: getLatestRecordBatch query lacks the MAX(id) tie-breaker

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java:10357-10369

The new getLatestRecordBatchInternal in CollectionDAO joins each entityFQNHash back on MAX(timestamp) with no id tie-breaker, unlike the incident-groups CTE which this same commit hardened with MAX(t.id) precisely to avoid two records sharing a chain's max timestamp both entering the result. If two records for one FQN share the max timestamp (possible for seeded/imported data, as the tie-break IT itself demonstrates), the query returns duplicate rows and the caller in TestCaseRepository.fetchAndSetTestCaseResultsAndIncidents non-deterministically picks whichever lands last in the map — so the resolved 'latest result' / 'ongoing incident' for that test case can flip between runs. Impact is limited because the API forces per-FQN monotonic timestamps, but the two latest-record paths now behave inconsistently. Consider adding the same deterministic MAX(id) tie-break to this batch query for parity.

✅ 2 resolved
✅ Performance: Missing (assignee, timestamp) index the assignee filter relies on

📄 bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql:541-552 📄 bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql:464-475 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java:497-500
The PR description states the migration adds four indexes including (assignee, timestamp) on test_case_resolution_status_time_series, and that the repaired assignee filter improved from 2.1s to 40ms "after its index". However both schemaChanges.sql files only add three indexes: (stateId, timestamp), (entityFQNHash, timestamp), and test_case(id). The assignee generated column (added in 1.3.0) has no index, so the repaired incidentAssignee filter (assignee = :incidentAssignee) on the flat list and the groups endpoint will fall back to a full scan — the exact slow path the PR claims to fix. Add the missing index.

✅ Performance: Per-group entity resolution is an N+1 over the page

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java:712-726 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java:788-802
toIncidentGroup calls resolveIncidentGroupEntity for every group in the page, and each invocation issues a separate getEntityReferenceByName/getEntityReferenceById lookup. With the default limit of 10 this is negligible, but limit is bounded at 1,000,000, so a large page performs one DB round-trip per group. Consider batch-resolving the entity references (e.g. a single findByIds/findByNames per group type) before mapping.

🤖 Prompt for agents
Code Review: Adds the grouped incident backend for the redesigned Incident Manager, including incident group endpoints, bulk updates, failure summaries, and necessary database indexes. Consider adding an id tie-breaker to getLatestRecordBatchInternal to prevent non-deterministic results when timestamps tie.

1. 💡 Edge Case: getLatestRecordBatch query lacks the MAX(id) tie-breaker
   Files: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java:10357-10369

   The new `getLatestRecordBatchInternal` in CollectionDAO joins each entityFQNHash back on `MAX(timestamp)` with no `id` tie-breaker, unlike the incident-groups CTE which this same commit hardened with `MAX(t.id)` precisely to avoid two records sharing a chain's max timestamp both entering the result. If two records for one FQN share the max timestamp (possible for seeded/imported data, as the tie-break IT itself demonstrates), the query returns duplicate rows and the caller in TestCaseRepository.fetchAndSetTestCaseResultsAndIncidents non-deterministically picks whichever lands last in the map — so the resolved 'latest result' / 'ongoing incident' for that test case can flip between runs. Impact is limited because the API forces per-FQN monotonic timestamps, but the two latest-record paths now behave inconsistently. Consider adding the same deterministic `MAX(id)` tie-break to this batch query for parity.

Options

Display: compact → Showing less information.

Comment with these commands to change the behavior for this request:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar | Powered by Gitar — free for open source

This branch was previously deployed

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

Labels

Ingestion safe to test Add this label to run secure Github workflows on PRs

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add endpoint to group test case incidents by Table, Test Definition, or Owner with counts

5 participants