From 187ca10826f43d1dd473b006b1c9be8475b053e5 Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Wed, 22 Jul 2026 10:33:18 -0700 Subject: [PATCH 01/13] feat: added incident group endpoint --- .../native/2.0.0/mysql/schemaChanges.sql | 13 + .../native/2.0.0/postgres/schemaChanges.sql | 13 + .../sample_data/tests/testCaseResults.json | 86 +- .../sample_data/tests/testSuites.json | 96 +++ .../ingestion/source/database/sample_data.py | 46 +- .../it/tests/IncidentGroupsIT.java | 764 ++++++++++++++++++ .../TestCaseResolutionStatusService.java | 23 + .../service/jdbi3/CollectionDAO.java | 195 ++++- .../service/jdbi3/ListFilter.java | 89 +- .../TestCaseResolutionStatusRepository.java | 95 ++- .../TestCaseResolutionStatusResource.java | 207 ++++- ...estCaseResolutionStatusRepositoryTest.java | 15 +- .../schema/tests/testCaseIncidentGroup.json | 49 ++ .../generated/tests/testCaseIncidentGroup.ts | 52 ++ 14 files changed, 1687 insertions(+), 56 deletions(-) create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java create mode 100644 openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json create mode 100644 openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts diff --git a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql index 33a8ac0c0821..3d9ef43467bd 100644 --- a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql @@ -537,3 +537,16 @@ SET json = JSON_INSERT( WHERE serviceType = 'DatabricksPipeline' AND JSON_EXTRACT(json, '$.connection.config.token') IS NOT NULL AND NOT JSON_CONTAINS_PATH(json, 'one', '$.connection.config.authType'); + +-- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp); + +-- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list +-- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all +-- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp); + +-- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, +-- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and +-- id-based lookups fall back to full scans. +ALTER TABLE test_case ADD INDEX idx_test_case_id (id); diff --git a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql index e8cbc760d2b5..8e1f7300950a 100644 --- a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql @@ -460,3 +460,16 @@ SET json = jsonb_set( WHERE serviceType = 'DatabricksPipeline' AND json #> '{connection,config,token}' IS NOT NULL AND NOT jsonb_exists(json #> '{connection,config}', 'authType'); + +-- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) +CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_state_id ON test_case_resolution_status_time_series (stateId, timestamp); + +-- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list +-- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all +-- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. +CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_fqn_ts ON test_case_resolution_status_time_series (entityFQNHash, timestamp); + +-- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, +-- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and +-- id-based lookups fall back to full scans. +CREATE INDEX IF NOT EXISTS idx_test_case_id ON test_case (id); diff --git a/ingestion/examples/sample_data/tests/testCaseResults.json b/ingestion/examples/sample_data/tests/testCaseResults.json index 97748427ae3f..68867563e572 100644 --- a/ingestion/examples/sample_data/tests/testCaseResults.json +++ b/ingestion/examples/sample_data/tests/testCaseResults.json @@ -830,7 +830,7 @@ ] }, { - "name": "not_null_customers_customer_id", + "name": "customer_id.not_null_customers_customer_id", "tableFqn": "postgres_sample.jaffle_shop.public.customers", "results": [ { "result": "0 null values found in column customer_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "nullCount", "value": "0" }] }, @@ -841,7 +841,7 @@ ] }, { - "name": "unique_customers_customer_id", + "name": "customer_id.unique_customers_customer_id", "tableFqn": "postgres_sample.jaffle_shop.public.customers", "results": [ { "result": "0 duplicate values found in column customer_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] }, @@ -863,7 +863,7 @@ ] }, { - "name": "not_null_orders_order_id", + "name": "order_id.not_null_orders_order_id", "tableFqn": "postgres_sample.jaffle_shop.public.orders", "results": [ { "result": "0 null values found in column order_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "nullCount", "value": "0" }] }, @@ -874,7 +874,7 @@ ] }, { - "name": "unique_orders_order_id", + "name": "order_id.unique_orders_order_id", "tableFqn": "postgres_sample.jaffle_shop.public.orders", "results": [ { "result": "0 duplicate values found in column order_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] }, @@ -885,7 +885,7 @@ ] }, { - "name": "accepted_values_orders_status", + "name": "status.accepted_values_orders_status", "tableFqn": "postgres_sample.jaffle_shop.public.orders", "results": [ { "result": "Found 5 values not in set: [placed, shipped, completed, return_pending, returned]", "testCaseStatus": "Failed", "testResultValues": [{ "name": "forbiddenCount", "value": "5" }] }, @@ -896,7 +896,7 @@ ] }, { - "name": "relationships_orders_customer_id", + "name": "customer_id.relationships_orders_customer_id", "tableFqn": "postgres_sample.jaffle_shop.public.orders", "results": [ { "result": "0 null values found in column customer_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "nullCount", "value": "0" }] }, @@ -907,7 +907,7 @@ ] }, { - "name": "not_null_stg_customers_customer_id", + "name": "customer_id.not_null_stg_customers_customer_id", "tableFqn": "postgres_sample.jaffle_shop.public.stg_customers", "results": [ { "result": "0 null values found in column customer_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "nullCount", "value": "0" }] }, @@ -918,7 +918,7 @@ ] }, { - "name": "unique_stg_customers_customer_id", + "name": "customer_id.unique_stg_customers_customer_id", "tableFqn": "postgres_sample.jaffle_shop.public.stg_customers", "results": [ { "result": "0 duplicate values found in column customer_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] }, @@ -927,6 +927,76 @@ { "result": "0 duplicate values found in column customer_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] }, { "result": "0 duplicate values found in column customer_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] } ] + }, + { + "name": "table_row_count_to_be_between", + "tableFqn": "sample_data.ecommerce_db.shopify.dim_customer", + "results": [ + { "result": "Found 642 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Failed", "testResultValues": [{ "name": "rowCount", "value": "642" }], "maxBound": 10000, "minBound": 1000 }, + { "result": "Found 787 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Failed", "testResultValues": [{ "name": "rowCount", "value": "787" }], "maxBound": 10000, "minBound": 1000 }, + { "result": "Found 1204 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Success", "testResultValues": [{ "name": "rowCount", "value": "1204" }], "maxBound": 10000, "minBound": 1000 }, + { "result": "Found 812 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Failed", "testResultValues": [{ "name": "rowCount", "value": "812" }], "maxBound": 10000, "minBound": 1000 }, + { "result": "Found 1198 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Success", "testResultValues": [{ "name": "rowCount", "value": "1198" }], "maxBound": 10000, "minBound": 1000 }, + { "result": "Found 1150 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Success", "testResultValues": [{ "name": "rowCount", "value": "1150" }], "maxBound": 10000, "minBound": 1000 }, + { "result": "Found 903 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Failed", "testResultValues": [{ "name": "rowCount", "value": "903" }], "maxBound": 10000, "minBound": 1000 }, + { "result": "Found 1132 rows vs. the expected range [1000, 10000].", "testCaseStatus": "Success", "testResultValues": [{ "name": "rowCount", "value": "1132" }], "maxBound": 10000, "minBound": 1000 } + ] + }, + { + "name": "email.column_values_to_match_regex", + "tableFqn": "sample_data.ecommerce_db.shopify.dim_customer", + "results": [ + { "result": "Found 1180 value(s) matching regex pattern vs 1204 value(s) in the column.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "likeCount", "value": "1180" }] }, + { "result": "Found 1102 value(s) matching regex pattern vs 1204 value(s) in the column.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "likeCount", "value": "1102" }] }, + { "result": "Found 1204 value(s) matching regex pattern vs 1204 value(s) in the column.", "testCaseStatus": "Success", "testResultValues": [{ "name": "likeCount", "value": "1204" }] }, + { "result": "Found 954 value(s) matching regex pattern vs 1204 value(s) in the column.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "likeCount", "value": "954" }] }, + { "result": "Found 1198 value(s) matching regex pattern vs 1198 value(s) in the column.", "testCaseStatus": "Success", "testResultValues": [{ "name": "likeCount", "value": "1198" }] }, + { "result": "Found 1204 value(s) matching regex pattern vs 1204 value(s) in the column.", "testCaseStatus": "Success", "testResultValues": [{ "name": "likeCount", "value": "1204" }] }, + { "result": "Error computing ColumnValuesToMatchRegex for email - database error", "testCaseStatus": "Aborted", "testResultValues": [{ "name": "likeCount", "value": "None" }] }, + { "result": "Found 1204 value(s) matching regex pattern vs 1204 value(s) in the column.", "testCaseStatus": "Success", "testResultValues": [{ "name": "likeCount", "value": "1204" }] } + ] + }, + { + "name": "order_id.column_values_to_be_unique", + "tableFqn": "sample_data.ecommerce_db.shopify.fact_order", + "results": [ + { "result": "Found 23 duplicate values in column order_id", "testCaseStatus": "Failed", "testResultValues": [{ "name": "duplicateCount", "value": "23" }] }, + { "result": "Found 12 duplicate values in column order_id", "testCaseStatus": "Failed", "testResultValues": [{ "name": "duplicateCount", "value": "12" }] }, + { "result": "Found 7 duplicate values in column order_id", "testCaseStatus": "Failed", "testResultValues": [{ "name": "duplicateCount", "value": "7" }] }, + { "result": "0 duplicate values found in column order_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] }, + { "result": "0 duplicate values found in column order_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] }, + { "result": "Found 3 duplicate values in column order_id", "testCaseStatus": "Failed", "testResultValues": [{ "name": "duplicateCount", "value": "3" }] }, + { "result": "0 duplicate values found in column order_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] }, + { "result": "0 duplicate values found in column order_id", "testCaseStatus": "Success", "testResultValues": [{ "name": "duplicateCount", "value": "0" }] } + ] + }, + { + "name": "total_price.column_value_max_to_be_between", + "tableFqn": "sample_data.ecommerce_db.shopify.fact_order", + "results": [ + { "result": "Found max=12500 vs. the expected min=100, max=5000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "maxValue", "value": "12500" }], "maxBound": 5000, "minBound": 100 }, + { "result": "Found max=8900 vs. the expected min=100, max=5000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "maxValue", "value": "8900" }], "maxBound": 5000, "minBound": 100 }, + { "result": "Found max=7549 vs. the expected min=100, max=5000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "maxValue", "value": "7549" }], "maxBound": 5000, "minBound": 100 }, + { "result": "Found max=4890 vs. the expected min=100, max=5000.", "testCaseStatus": "Success", "testResultValues": [{ "name": "maxValue", "value": "4890" }], "maxBound": 5000, "minBound": 100 }, + { "result": "Found max=4321 vs. the expected min=100, max=5000.", "testCaseStatus": "Success", "testResultValues": [{ "name": "maxValue", "value": "4321" }], "maxBound": 5000, "minBound": 100 }, + { "result": "Found max=6100 vs. the expected min=100, max=5000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "maxValue", "value": "6100" }], "maxBound": 5000, "minBound": 100 }, + { "result": "Found max=3980 vs. the expected min=100, max=5000.", "testCaseStatus": "Success", "testResultValues": [{ "name": "maxValue", "value": "3980" }], "maxBound": 5000, "minBound": 100 }, + { "result": "We expect `max` to be informed on the profiler for ColumnValueMaxToBeBetween max=None.", "testCaseStatus": "Aborted", "testResultValues": [{ "name": "maxValue", "value": "None" }] } + ] + }, + { + "name": "net_sales.column_values_to_be_between", + "tableFqn": "sample_data.ecommerce_db.shopify.fact_sale", + "results": [ + { "result": "Found min=-250, max=8790 vs. the expected min=0, max=10000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "minValue", "value": "-250" }, { "name": "maxValue", "value": "8790" }], "maxBound": 10000, "minBound": 0 }, + { "result": "Found min=-1043, max=9120 vs. the expected min=0, max=10000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "minValue", "value": "-1043" }, { "name": "maxValue", "value": "9120" }], "maxBound": 10000, "minBound": 0 }, + { "result": "Found min=0, max=9540 vs. the expected min=0, max=10000.", "testCaseStatus": "Success", "testResultValues": [{ "name": "minValue", "value": "0" }, { "name": "maxValue", "value": "9540" }], "maxBound": 10000, "minBound": 0 }, + { "result": "Found min=-87, max=12040 vs. the expected min=0, max=10000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "minValue", "value": "-87" }, { "name": "maxValue", "value": "12040" }], "maxBound": 10000, "minBound": 0 }, + { "result": "Found min=12, max=8730 vs. the expected min=0, max=10000.", "testCaseStatus": "Success", "testResultValues": [{ "name": "minValue", "value": "12" }, { "name": "maxValue", "value": "8730" }], "maxBound": 10000, "minBound": 0 }, + { "result": "Found min=0, max=9210 vs. the expected min=0, max=10000.", "testCaseStatus": "Success", "testResultValues": [{ "name": "minValue", "value": "0" }, { "name": "maxValue", "value": "9210" }], "maxBound": 10000, "minBound": 0 }, + { "result": "Found min=-430, max=8020 vs. the expected min=0, max=10000.", "testCaseStatus": "Failed", "testResultValues": [{ "name": "minValue", "value": "-430" }, { "name": "maxValue", "value": "8020" }], "maxBound": 10000, "minBound": 0 }, + { "result": "Found min=5, max=8880 vs. the expected min=0, max=10000.", "testCaseStatus": "Success", "testResultValues": [{ "name": "minValue", "value": "5" }, { "name": "maxValue", "value": "8880" }], "maxBound": 10000, "minBound": 0 } + ] } ] } \ No newline at end of file diff --git a/ingestion/examples/sample_data/tests/testSuites.json b/ingestion/examples/sample_data/tests/testSuites.json index 568782a79ec4..72789be0c8ff 100644 --- a/ingestion/examples/sample_data/tests/testSuites.json +++ b/ingestion/examples/sample_data/tests/testSuites.json @@ -569,6 +569,102 @@ "resolutions": {} } ] + }, + { + "testSuiteName": "sample_data.ecommerce_db.shopify.dim_customer.testSuite", + "executableEntityReference": "sample_data.ecommerce_db.shopify.dim_customer", + "testSuiteDescription": "Data quality tests for the customer dimension table", + "scheduleInterval": "0 4 * * *", + "testCases": [ + { + "name": "table_row_count_to_be_between", + "description": "customer dimension should have between 1000 and 10000 rows", + "entityLink": "<#E::table::sample_data.ecommerce_db.shopify.dim_customer>", + "testDefinitionName": "tableRowCountToBeBetween", + "owners": ["amber_green0"], + "parameterValues": [ + { "name": "minValue", "value": "1000" }, + { "name": "maxValue", "value": "10000" } + ], + "resolutions": { + "sequenceOne": [ + { "testCaseResolutionStatusType": "Ack", "severity": "Severity2" }, + { "testCaseResolutionStatusType": "Assigned", "severity": "Severity2", "assignee": "amber_green0" } + ] + } + }, + { + "name": "column_values_to_match_regex", + "description": "customer email must be a valid email address", + "entityLink": "<#E::table::sample_data.ecommerce_db.shopify.dim_customer::columns::email>", + "testDefinitionName": "columnValuesToMatchRegex", + "owners": ["amber_green0", "adam_rodriguez9"], + "parameterValues": [ + { "name": "regex", "value": "^[\\w.+-]+@[\\w-]+\\.[\\w.]+$" } + ], + "resolutions": {} + } + ] + }, + { + "testSuiteName": "sample_data.ecommerce_db.shopify.fact_order.testSuite", + "executableEntityReference": "sample_data.ecommerce_db.shopify.fact_order", + "testSuiteDescription": "Data quality tests for the order fact table", + "scheduleInterval": "0 3 * * *", + "testCases": [ + { + "name": "column_values_to_be_unique", + "description": "order_id must be unique across all orders", + "entityLink": "<#E::table::sample_data.ecommerce_db.shopify.fact_order::columns::order_id>", + "testDefinitionName": "columnValuesToBeUnique", + "owners": ["alexander_jackson5"], + "parameterValues": [], + "resolutions": { + "sequenceOne": [ + { "testCaseResolutionStatusType": "Ack", "severity": "Severity1" }, + { "testCaseResolutionStatusType": "Assigned", "severity": "Severity1", "assignee": "alexander_jackson5" }, + { "testCaseResolutionStatusType": "Resolved", "severity": "Severity1", "resolver": "alexander_jackson5" } + ] + } + }, + { + "name": "column_value_max_to_be_between", + "description": "total_price should stay within the expected bounds", + "entityLink": "<#E::table::sample_data.ecommerce_db.shopify.fact_order::columns::total_price>", + "testDefinitionName": "columnValueMaxToBeBetween", + "owners": ["alexander_jackson5", "amy_stephens4"], + "parameterValues": [ + { "name": "minValueForMaxInCol", "value": "100" }, + { "name": "maxValueForMaxInCol", "value": "5000" } + ], + "resolutions": {} + } + ] + }, + { + "testSuiteName": "sample_data.ecommerce_db.shopify.fact_sale.testSuite", + "executableEntityReference": "sample_data.ecommerce_db.shopify.fact_sale", + "testSuiteDescription": "Data quality tests for the sale fact table", + "scheduleInterval": "30 3 * * *", + "testCases": [ + { + "name": "column_values_to_be_between", + "description": "net_sales should be within the expected range", + "entityLink": "<#E::table::sample_data.ecommerce_db.shopify.fact_sale::columns::net_sales>", + "testDefinitionName": "columnValuesToBeBetween", + "owners": ["ana_mckay7"], + "parameterValues": [ + { "name": "minValue", "value": "0" }, + { "name": "maxValue", "value": "10000" } + ], + "resolutions": { + "sequenceOne": [ + { "testCaseResolutionStatusType": "Ack", "severity": "Severity3" }, + { "testCaseResolutionStatusType": "Assigned", "severity": "Severity3", "assignee": "ana_mckay7" } + ] + } + } + ] } ] } \ No newline at end of file diff --git a/ingestion/src/metadata/ingestion/source/database/sample_data.py b/ingestion/src/metadata/ingestion/source/database/sample_data.py index 12b57577b39a..6d4e1a53b912 100644 --- a/ingestion/src/metadata/ingestion/source/database/sample_data.py +++ b/ingestion/src/metadata/ingestion/source/database/sample_data.py @@ -2386,6 +2386,14 @@ def ingest_logical_test_suite( yield Either(right=OMetaLogicalTestSuiteSample(test_suite=test_suite, test_cases=test_cases)) + def _get_test_case_owners(self, test_case: dict) -> EntityReferenceList | None: + owners = [] + for owner_name in test_case.get("owners", []): + user: User | None = self.metadata.get_by_name(User, fqn=owner_name) + if user: + owners.append(EntityReference(id=user.id.root, type="user")) + return EntityReferenceList(owners) if owners else None + def ingest_test_case(self) -> Iterable[Either[OMetaTestCaseSample]]: """Ingest test cases""" for test_suite in self.tests_suites["tests"]: @@ -2403,6 +2411,7 @@ def ingest_test_case(self) -> Iterable[Either[OMetaTestCaseSample]]: TestCaseParameterValue(**param_values) for param_values in test_case["parameterValues"] ], useDynamicAssertion=test_case.get("useDynamicAssertion", False), + owners=self._get_test_case_owners(test_case), ) # type: ignore ) yield Either(right=test_case_req) @@ -2457,27 +2466,30 @@ def ingest_test_case_results(self) -> Iterable[Either[OMetaTestCaseResultsSample """Iterate over all the testSuite and testCase and ingest them""" for test_case_results in self.tests_case_results["testCaseResults"]: table_fqn = test_case_results.get("tableFqn", "sample_data.ecommerce_db.shopify.dim_address") + test_case_fqn = f"{table_fqn}.{test_case_results['name']}" case = self.metadata.get_by_name( TestCase, - f"{table_fqn}.{test_case_results['name']}", + test_case_fqn, fields=["testSuite", "testDefinition"], ) - if case: - for days, result in enumerate(test_case_results["results"]): - test_case_result_req = OMetaTestCaseResultsSample( - test_case_results=TestCaseResult( - timestamp=Timestamp(int((datetime.now() - timedelta(days=days)).timestamp() * 1000)), - testCaseStatus=result["testCaseStatus"], - result=result["result"], - testResultValue=[ - TestResultValue.model_validate(res_value) for res_value in result["testResultValues"] - ], - minBound=result.get("minBound"), - maxBound=result.get("maxBound"), - ), - test_case_name=case.fullyQualifiedName.root, - ) - yield Either(right=test_case_result_req) + if not case: + logger.warning(f"Test case {test_case_fqn} not found. Skipping its sample results.") + continue + for days, result in enumerate(test_case_results["results"]): + test_case_result_req = OMetaTestCaseResultsSample( + test_case_results=TestCaseResult( + timestamp=Timestamp(int((datetime.now() - timedelta(days=days)).timestamp() * 1000)), + testCaseStatus=result["testCaseStatus"], + result=result["result"], + testResultValue=[ + TestResultValue.model_validate(res_value) for res_value in result["testResultValues"] + ], + minBound=result.get("minBound"), + maxBound=result.get("maxBound"), + ), + test_case_name=case.fullyQualifiedName.root, + ) + yield Either(right=test_case_result_req) if test_case_results.get("failedRowsSample"): self.metadata.ingest_failed_rows_sample( case, diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java new file mode 100644 index 000000000000..6a1973432eb9 --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java @@ -0,0 +1,764 @@ +package org.openmetadata.it.tests; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Base64; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import org.openmetadata.it.bootstrap.SharedEntities; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.schema.api.data.CreateDatabase; +import org.openmetadata.schema.api.data.CreateDatabaseSchema; +import org.openmetadata.schema.api.data.CreateTable; +import org.openmetadata.schema.api.domains.CreateDomain; +import org.openmetadata.schema.api.teams.CreateUser; +import org.openmetadata.schema.api.tests.CreateTestCase; +import org.openmetadata.schema.api.tests.CreateTestCaseResolutionStatus; +import org.openmetadata.schema.api.tests.CreateTestDefinition; +import org.openmetadata.schema.entity.data.Database; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.entity.domains.Domain; +import org.openmetadata.schema.entity.teams.User; +import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.TestDefinition; +import org.openmetadata.schema.tests.TestPlatform; +import org.openmetadata.schema.tests.type.Assigned; +import org.openmetadata.schema.tests.type.IncidentGroupBy; +import org.openmetadata.schema.tests.type.Resolved; +import org.openmetadata.schema.tests.type.TestCaseFailureReasonType; +import org.openmetadata.schema.tests.type.TestCaseIncidentGroup; +import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; +import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; +import org.openmetadata.schema.type.Column; +import org.openmetadata.schema.type.ColumnDataType; +import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.TestDefinitionEntityType; +import org.openmetadata.schema.utils.JsonUtils; +import org.openmetadata.sdk.client.OpenMetadataClient; +import org.openmetadata.sdk.exceptions.OpenMetadataException; +import org.openmetadata.sdk.models.ListParams; +import org.openmetadata.sdk.models.ListResponse; + +/** + * Integration tests for GET /v1/dataQuality/testCases/testCaseIncidentStatus/incidentGroups. + * + *

Fixture layout (all names are timestamp-unique so concurrent suites cannot interfere): + * + *

+ */ +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +public class IncidentGroupsIT { + + private static final String GROUP_BY_TABLE = "table"; + private static final String GROUP_BY_TEST_DEFINITION = "testDefinition"; + private static final String GROUP_BY_OWNER = "owner"; + private static final String MAX_LIMIT = "1000000"; + + private OpenMetadataClient client; + private Table tableA; + private Table tableB; + private User userA; + private User userB; + private TestDefinition tableDefinition; + private TestDefinition columnDefinition; + private Domain domain; + private TestCase testCase1; + private TestCase testCase2; + private TestCase testCase3; + private TestCase testCase4; + private User pagerUser; + private List pagerTableFqns; + + @BeforeAll + void setup() throws Exception { + client = SdkClients.adminClient(); + long ts = System.currentTimeMillis(); + String schemaFqn = createSchema(ts); + tableA = createTable(schemaFqn, "incident_groups_table_a_" + ts); + tableB = createTable(schemaFqn, "incident_groups_table_b_" + ts); + userA = createUser("incident_groups_user_a_" + ts); + userB = createUser("incident_groups_user_b_" + ts); + tableDefinition = + createTestDefinition("incident_groups_table_def_" + ts, TestDefinitionEntityType.TABLE); + columnDefinition = + createTestDefinition("incident_groups_column_def_" + ts, TestDefinitionEntityType.COLUMN); + domain = createDomain("incident_groups_domain_" + ts); + + testCase1 = + createTestCase( + "incident_groups_case_1", + tableLink(tableA), + tableDefinition, + List.of(userA.getEntityReference())); + testCase2 = + createTestCase( + "incident_groups_case_2", + columnLink(tableA), + columnDefinition, + List.of(userA.getEntityReference(), userB.getEntityReference())); + testCase3 = + createTestCase( + "incident_groups_case_3", + tableLink(tableB), + tableDefinition, + List.of(userB.getEntityReference())); + testCase4 = + createTestCase("incident_groups_case_4", tableLink(tableB), tableDefinition, List.of()); + assignDomain(testCase1, domain); + + createStatus(testCase1, TestCaseResolutionStatusTypes.New, null); + createStatus(testCase2, TestCaseResolutionStatusTypes.New, null); + createStatus( + testCase2, + TestCaseResolutionStatusTypes.Assigned, + new Assigned().withAssignee(userA.getEntityReference())); + createStatus(testCase3, TestCaseResolutionStatusTypes.New, null); + createStatus(testCase4, TestCaseResolutionStatusTypes.New, null); + createStatus( + testCase4, + TestCaseResolutionStatusTypes.Resolved, + new Resolved() + .withTestCaseFailureReason(TestCaseFailureReasonType.FalsePositive) + .withTestCaseFailureComment("resolved by incident groups IT")); + + createPagerFixture(ts, schemaFqn); + } + + private void createPagerFixture(long ts, String schemaFqn) throws Exception { + pagerUser = createUser("incident_groups_pager_" + ts); + TestDefinition pagerDefinition = + createTestDefinition("incident_groups_pager_def_" + ts, TestDefinitionEntityType.TABLE); + pagerTableFqns = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Table pagerTable = createTable(schemaFqn, "incident_groups_page_" + i + "_" + ts); + TestCase pagerCase = + createTestCase( + "incident_groups_page_case_" + i, tableLink(pagerTable), pagerDefinition, List.of()); + createStatus(pagerCase, TestCaseResolutionStatusTypes.New, null); + createStatus( + pagerCase, + TestCaseResolutionStatusTypes.Assigned, + new Assigned().withAssignee(pagerUser.getEntityReference())); + pagerTableFqns.add(pagerTable.getFullyQualifiedName()); + } + pagerTableFqns = pagerTableFqns.stream().sorted().toList(); + } + + @Test + void testGroupByTableCountsAndResolvedExclusion() throws Exception { + List groups = fetchGroups(groupParams(GROUP_BY_TABLE)); + + TestCaseIncidentGroup groupA = findGroup(groups, tableA.getFullyQualifiedName()); + assertEquals(2, groupA.getIncidentCount(), "table and column level incidents on table A"); + assertEquals(IncidentGroupBy.Table, groupA.getGroupBy()); + assertEquals(tableA.getId(), groupA.getId()); + assertEquals(tableA.getName(), groupA.getName()); + + TestCaseIncidentGroup groupB = findGroup(groups, tableB.getFullyQualifiedName()); + assertEquals(1, groupB.getIncidentCount(), "resolved incident on table B must be excluded"); + } + + @Test + void testGroupByTestDefinitionCounts() throws Exception { + List groups = fetchGroups(groupParams(GROUP_BY_TEST_DEFINITION)); + + TestCaseIncidentGroup tableDefGroup = + findGroup(groups, tableDefinition.getFullyQualifiedName()); + assertEquals( + 2, + tableDefGroup.getIncidentCount(), + "open incidents on case 1 and 3; resolved case 4 excluded"); + assertEquals(IncidentGroupBy.TestDefinition, tableDefGroup.getGroupBy()); + assertEquals(tableDefinition.getId(), tableDefGroup.getId()); + + TestCaseIncidentGroup columnDefGroup = + findGroup(groups, columnDefinition.getFullyQualifiedName()); + assertEquals(1, columnDefGroup.getIncidentCount()); + } + + @Test + void testGroupByOwnerDoesNotDoubleCount() throws Exception { + List groups = fetchGroups(groupParams(GROUP_BY_OWNER)); + + TestCaseIncidentGroup groupUserA = findGroup(groups, userA.getFullyQualifiedName()); + assertEquals( + 2, + groupUserA.getIncidentCount(), + "case 2's two status records and two owners must count as a single incident"); + assertEquals(IncidentGroupBy.Owner, groupUserA.getGroupBy()); + assertEquals(userA.getId(), groupUserA.getId()); + + TestCaseIncidentGroup groupUserB = findGroup(groups, userB.getFullyQualifiedName()); + assertEquals(2, groupUserB.getIncidentCount(), "case 2 (co-owned) and case 3 incidents"); + } + + @Test + void testStatusFilterNarrows() throws Exception { + Map assignedParams = groupParams(GROUP_BY_TABLE); + assignedParams.put("status", TestCaseResolutionStatusTypes.Assigned.value()); + List assignedGroups = fetchGroups(assignedParams); + assertEquals(1, findGroup(assignedGroups, tableA.getFullyQualifiedName()).getIncidentCount()); + assertGroupAbsent(assignedGroups, tableB.getFullyQualifiedName()); + + Map newParams = groupParams(GROUP_BY_TABLE); + newParams.put( + "status", + TestCaseResolutionStatusTypes.New.value() + + "," + + TestCaseResolutionStatusTypes.Ack.value()); + List newGroups = fetchGroups(newParams); + assertEquals(1, findGroup(newGroups, tableA.getFullyQualifiedName()).getIncidentCount()); + assertEquals(1, findGroup(newGroups, tableB.getFullyQualifiedName()).getIncidentCount()); + } + + @Test + void testAssigneeFilterMatchesCurrentAssignee() throws Exception { + Map params = groupParams(GROUP_BY_TABLE); + params.put("assignee", userA.getName()); + List groups = fetchGroups(params); + + assertEquals(1, findGroup(groups, tableA.getFullyQualifiedName()).getIncidentCount()); + assertGroupAbsent(groups, tableB.getFullyQualifiedName()); + } + + @Test + void testTestCaseFqnFilterScopesToOneTestCase() throws Exception { + Map params = groupParams(GROUP_BY_TABLE); + params.put("testCaseFQN", testCase3.getFullyQualifiedName()); + ListResponse response = + client.testCaseResolutionStatuses().listIncidentGroups(params); + + assertEquals(1, response.getData().size()); + assertEquals(1, response.getPaging().getTotal()); + List groups = convertGroups(response); + assertEquals(1, findGroup(groups, tableB.getFullyQualifiedName()).getIncidentCount()); + } + + @Test + void testDateFieldRangeFiltersDistinctIncidents() throws Exception { + List records = fetchStatuses(testCase2); + long createdAt = + records.stream().mapToLong(TestCaseResolutionStatus::getTimestamp).min().orElseThrow(); + long updatedAt = + records.stream().mapToLong(TestCaseResolutionStatus::getTimestamp).max().orElseThrow(); + assertTrue(updatedAt > createdAt, "the Assigned record must be later than the New record"); + + assertEquals( + 1, + fetchGroups(dateRangeParams("createdAt", createdAt, createdAt)).size(), + "incident opened exactly at createdAt must match a createdAt range"); + assertTrue( + fetchGroups(dateRangeParams("createdAt", updatedAt, null)).isEmpty(), + "a createdAt range starting after the incident opened must exclude it"); + assertEquals( + 1, + fetchGroups(dateRangeParams("updatedAt", updatedAt, updatedAt)).size(), + "the same range must match when applied to updatedAt"); + assertTrue( + fetchGroups(dateRangeParams("updatedAt", null, createdAt)).isEmpty(), + "an updatedAt range ending before the last status change must exclude it"); + } + + @Test + void testDomainFilter() throws Exception { + Map params = groupParams(GROUP_BY_TABLE); + params.put("domain", domain.getFullyQualifiedName()); + List groups = fetchGroups(params); + + assertEquals( + 1, + findGroup(groups, tableA.getFullyQualifiedName()).getIncidentCount(), + "only case 1 is in the domain; case 2's incident must not count"); + assertGroupAbsent(groups, tableB.getFullyQualifiedName()); + } + + @Test + void testSortTypeOrdersByIncidentCount() throws Exception { + Map ascParams = groupParams(GROUP_BY_TABLE); + ascParams.put("sortType", "asc"); + assertSorted(fetchGroups(ascParams), true); + + Map descParams = groupParams(GROUP_BY_TABLE); + descParams.put("sortType", "desc"); + assertSorted(fetchGroups(descParams), false); + } + + @Test + void testPagination() throws Exception { + Map params = groupParams(GROUP_BY_TABLE); + params.put("limit", "1"); + ListResponse response = + client.testCaseResolutionStatuses().listIncidentGroups(params); + + assertEquals(1, response.getData().size()); + assertTrue(response.getPaging().getTotal() >= 2, "at least our two table groups exist"); + } + + // Walks the assignee-scoped pager population (5 single-incident groups, tied counts, so the + // ordering falls to the groupKey tiebreak) with limits that split it into uneven pages. + @Test + void testPaginationWalkVisitsEveryGroupOnce() throws Exception { + assertPaginationWalk(2); + assertPaginationWalk(3); + } + + @Test + void testPaginationOffsetBeyondTotalReturnsEmptyPage() throws Exception { + ListResponse response = fetchPagerPage(2, encodeOffset(100)); + + assertTrue(convertGroups(response).isEmpty()); + assertNull(response.getPaging().getAfter(), "no next page past the end of the list"); + assertEquals(pagerTableFqns.size(), response.getPaging().getTotal()); + } + + // The `before`/`after` cursors are opaque Base64-encoded offsets; the walk passes them back + // verbatim as `offset` (the real client contract) and only decodes them to check arithmetic. + private void assertPaginationWalk(int limit) throws Exception { + int total = pagerTableFqns.size(); + List visited = new ArrayList<>(); + Set seen = new HashSet<>(); + String offsetCursor = null; + String lastPageCursor = null; + int expectedOffset = 0; + boolean morePages = true; + + while (morePages) { + ListResponse response = fetchPagerPage(limit, offsetCursor); + List groups = convertGroups(response); + boolean lastPage = expectedOffset + limit >= total; + + assertEquals(total, response.getPaging().getTotal(), "total must be stable on every page"); + assertEquals( + lastPage ? total - expectedOffset : limit, + groups.size(), + "every page but the last must hold exactly 'limit' groups (limit=" + limit + ")"); + if (expectedOffset == 0) { + assertNull(response.getPaging().getBefore(), "first page has no previous cursor"); + } else { + assertEquals( + Math.max(0, expectedOffset - limit), decodeOffset(response.getPaging().getBefore())); + } + if (lastPage) { + assertNull(response.getPaging().getAfter(), "last page has no next cursor"); + } else { + assertEquals(expectedOffset + limit, decodeOffset(response.getPaging().getAfter())); + } + for (TestCaseIncidentGroup group : groups) { + assertTrue( + seen.add(group.getFullyQualifiedName()), + "group repeated across pages: " + group.getFullyQualifiedName()); + visited.add(group.getFullyQualifiedName()); + } + + lastPageCursor = offsetCursor; + morePages = response.getPaging().getAfter() != null; + if (morePages) { + offsetCursor = response.getPaging().getAfter(); + expectedOffset += limit; + } + } + + assertEquals( + pagerTableFqns, + visited, + "forward walk must visit every group exactly once, ordered by groupKey (limit=" + + limit + + ")"); + assertBackwardWalk(limit, lastPageCursor); + } + + private void assertBackwardWalk(int limit, String lastPageCursor) throws Exception { + Set seen = new HashSet<>(); + String cursor = lastPageCursor; + boolean morePages = true; + + while (morePages) { + ListResponse response = fetchPagerPage(limit, cursor); + for (TestCaseIncidentGroup group : convertGroups(response)) { + assertTrue( + seen.add(group.getFullyQualifiedName()), + "group repeated across backward pages: " + group.getFullyQualifiedName()); + } + cursor = response.getPaging().getBefore(); + morePages = cursor != null; + } + + assertEquals( + new HashSet<>(pagerTableFqns), + seen, + "backward walk must visit the same groups as the forward walk (limit=" + limit + ")"); + } + + private ListResponse fetchPagerPage(int limit, String offsetCursor) + throws Exception { + Map params = new LinkedHashMap<>(); + params.put("groupBy", GROUP_BY_TABLE); + params.put("assignee", pagerUser.getName()); + params.put("limit", String.valueOf(limit)); + if (offsetCursor != null) { + params.put("offset", offsetCursor); + } + return client.testCaseResolutionStatuses().listIncidentGroups(params); + } + + private static String encodeOffset(int offset) { + return Base64.getEncoder() + .encodeToString(String.valueOf(offset).getBytes(StandardCharsets.UTF_8)); + } + + private static int decodeOffset(String cursor) { + return Integer.parseInt(new String(Base64.getDecoder().decode(cursor), StandardCharsets.UTF_8)); + } + + @Test + void testDbListStatusInFilter() throws Exception { + ListParams params = + new ListParams() + .withLimit(10) + .addFilter("testCaseFQN", testCase2.getFullyQualifiedName()) + .addFilter( + "testCaseResolutionStatusType", + TestCaseResolutionStatusTypes.New.value() + + "," + + TestCaseResolutionStatusTypes.Assigned.value()); + ListResponse response = + client.testCaseResolutionStatuses().list(params); + assertEquals( + 2, response.getData().size(), "both records of the incident chain match the IN filter"); + } + + // The repository only takes the latest-per-test-case branch when a time range is given. + @Test + void testDbListLatestWithStatusFilter() throws Exception { + String endTs = String.valueOf(System.currentTimeMillis() + 60_000); + ListParams matching = + new ListParams() + .withLimit(10) + .withLatest(true) + .addFilter("startTs", "0") + .addFilter("endTs", endTs) + .addFilter("testCaseFQN", testCase2.getFullyQualifiedName()) + .addFilter( + "testCaseResolutionStatusType", + TestCaseResolutionStatusTypes.New.value() + + "," + + TestCaseResolutionStatusTypes.Assigned.value()); + ListResponse response = + client.testCaseResolutionStatuses().list(matching); + assertEquals( + 1, + response.getData().size(), + "only the latest record of the test case matches the status IN filter"); + + ListParams nonMatching = + new ListParams() + .withLimit(10) + .withLatest(true) + .addFilter("startTs", "0") + .addFilter("endTs", endTs) + .addFilter("testCaseFQN", testCase2.getFullyQualifiedName()) + .addFilter("testCaseResolutionStatusType", TestCaseResolutionStatusTypes.New.value()); + assertTrue( + client.testCaseResolutionStatuses().list(nonMatching).getData().isEmpty(), + "the latest record is Assigned, so a New filter must exclude the test case"); + } + + @Test + void testDbListTestDefinitionFilterScopesToDefinition() throws Exception { + List tableDefStatuses = + listStatuses( + new ListParams() + .withLimit(100) + .addFilter("testDefinition", tableDefinition.getFullyQualifiedName())); + assertEquals( + Set.of( + testCase1.getFullyQualifiedName(), + testCase3.getFullyQualifiedName(), + testCase4.getFullyQualifiedName()), + statusTestCaseFqns(tableDefStatuses), + "all records of the table definition's test cases and nothing else"); + + List columnDefStatuses = + listStatuses( + new ListParams() + .withLimit(100) + .addFilter("testDefinition", columnDefinition.getFullyQualifiedName())); + assertEquals( + Set.of(testCase2.getFullyQualifiedName()), + statusTestCaseFqns(columnDefStatuses), + "only case 2 uses the column definition"); + } + + // latest=true + open statuses must return exactly the incident population the + // groupBy=testDefinition endpoint counts for that definition (case 4's latest is Resolved). + @Test + void testDbListLatestWithTestDefinitionFilterMatchesGroupCount() throws Exception { + String endTs = String.valueOf(System.currentTimeMillis() + 60_000); + ListParams params = + new ListParams() + .withLimit(100) + .withLatest(true) + .addFilter("startTs", "0") + .addFilter("endTs", endTs) + .addFilter("testDefinition", tableDefinition.getFullyQualifiedName()) + .addFilter( + "testCaseResolutionStatusType", + TestCaseResolutionStatusTypes.New.value() + + "," + + TestCaseResolutionStatusTypes.Ack.value() + + "," + + TestCaseResolutionStatusTypes.Assigned.value()); + List statuses = listStatuses(params); + + Set openIncidentCases = statusTestCaseFqns(statuses); + assertEquals( + Set.of(testCase1.getFullyQualifiedName(), testCase3.getFullyQualifiedName()), + openIncidentCases); + + TestCaseIncidentGroup tableDefGroup = + findGroup( + fetchGroups(groupParams(GROUP_BY_TEST_DEFINITION)), + tableDefinition.getFullyQualifiedName()); + assertEquals(tableDefGroup.getIncidentCount(), openIncidentCases.size()); + } + + @Test + void testDbListUnknownTestDefinitionRejected() { + ListParams params = + new ListParams() + .withLimit(10) + .addFilter("testDefinition", "incident_groups_unknown_def_" + System.nanoTime()); + OpenMetadataException error = + assertThrows( + OpenMetadataException.class, () -> client.testCaseResolutionStatuses().list(params)); + assertEquals(404, error.getStatusCode()); + } + + @Test + void testResolvedStatusRejected() { + Map params = groupParams(GROUP_BY_TABLE); + params.put("status", TestCaseResolutionStatusTypes.Resolved.value()); + OpenMetadataException error = + assertThrows( + OpenMetadataException.class, + () -> client.testCaseResolutionStatuses().listIncidentGroups(params)); + assertEquals(400, error.getStatusCode()); + } + + @Test + void testInvalidGroupByRejected() { + Map params = groupParams("invalidDimension"); + OpenMetadataException error = + assertThrows( + OpenMetadataException.class, + () -> client.testCaseResolutionStatuses().listIncidentGroups(params)); + assertEquals(400, error.getStatusCode()); + } + + @Test + void testMissingGroupByRejected() { + Map params = new LinkedHashMap<>(); + params.put("limit", MAX_LIMIT); + OpenMetadataException error = + assertThrows( + OpenMetadataException.class, + () -> client.testCaseResolutionStatuses().listIncidentGroups(params)); + assertEquals(400, error.getStatusCode()); + } + + private String createSchema(long ts) throws Exception { + Database database = + client + .databases() + .create( + new CreateDatabase() + .withName("incident_groups_db_" + ts) + .withService(SharedEntities.get().MYSQL_SERVICE.getFullyQualifiedName())); + return client + .databaseSchemas() + .create( + new CreateDatabaseSchema() + .withName("incident_groups_schema_" + ts) + .withDatabase(database.getFullyQualifiedName())) + .getFullyQualifiedName(); + } + + private Table createTable(String schemaFqn, String name) throws Exception { + return client + .tables() + .create( + new CreateTable() + .withName(name) + .withDatabaseSchema(schemaFqn) + .withColumns( + List.of(new Column().withName("id").withDataType(ColumnDataType.BIGINT)))); + } + + private User createUser(String name) throws Exception { + return client.users().create(new CreateUser().withName(name).withEmail(name + "@example.com")); + } + + private TestDefinition createTestDefinition(String name, TestDefinitionEntityType entityType) + throws Exception { + return client + .testDefinitions() + .create( + new CreateTestDefinition() + .withName(name) + .withDescription("Incident groups IT definition") + .withEntityType(entityType) + .withTestPlatforms(List.of(TestPlatform.OPEN_METADATA))); + } + + private Domain createDomain(String name) throws Exception { + return client + .domains() + .create( + new CreateDomain() + .withName(name) + .withDomainType(CreateDomain.DomainType.AGGREGATE) + .withDescription("Incident groups IT domain")); + } + + private TestCase createTestCase( + String name, String entityLink, TestDefinition definition, List owners) + throws Exception { + CreateTestCase request = + new CreateTestCase() + .withName(name) + .withEntityLink(entityLink) + .withTestDefinition(definition.getFullyQualifiedName()); + if (!owners.isEmpty()) { + request.withOwners(owners); + } + return client.testCases().create(request); + } + + private void assignDomain(TestCase testCase, Domain assignedDomain) throws Exception { + TestCase fetched = client.testCases().get(testCase.getId().toString(), "owners,domains"); + fetched.setDomains(List.of(assignedDomain.getEntityReference())); + client.testCases().update(fetched.getId().toString(), fetched); + } + + private void createStatus(TestCase testCase, TestCaseResolutionStatusTypes type, Object details) + throws Exception { + CreateTestCaseResolutionStatus request = + new CreateTestCaseResolutionStatus() + .withTestCaseResolutionStatusType(type) + .withTestCaseReference(testCase.getFullyQualifiedName()); + if (details != null) { + request.withTestCaseResolutionStatusDetails(details); + } + client.testCaseResolutionStatuses().create(request); + } + + private String tableLink(Table table) { + return "<#E::table::" + table.getFullyQualifiedName() + ">"; + } + + private String columnLink(Table table) { + return "<#E::table::" + table.getFullyQualifiedName() + "::columns::id>"; + } + + private Map groupParams(String groupBy) { + Map params = new LinkedHashMap<>(); + params.put("groupBy", groupBy); + params.put("limit", MAX_LIMIT); + return params; + } + + private Map dateRangeParams(String dateField, Long startTs, Long endTs) { + Map params = groupParams(GROUP_BY_TABLE); + params.put("testCaseFQN", testCase2.getFullyQualifiedName()); + params.put("dateField", dateField); + if (startTs != null) { + params.put("startTs", String.valueOf(startTs)); + } + if (endTs != null) { + params.put("endTs", String.valueOf(endTs)); + } + return params; + } + + private List fetchGroups(Map params) throws Exception { + return convertGroups(client.testCaseResolutionStatuses().listIncidentGroups(params)); + } + + private List convertGroups(ListResponse response) { + List groups = new ArrayList<>(); + for (Object item : response.getData()) { + groups.add(JsonUtils.convertValue(item, TestCaseIncidentGroup.class)); + } + return groups; + } + + private List fetchStatuses(TestCase testCase) throws Exception { + return listStatuses( + new ListParams().withLimit(100).addFilter("testCaseFQN", testCase.getFullyQualifiedName())); + } + + private List listStatuses(ListParams params) throws Exception { + ListResponse response = + client.testCaseResolutionStatuses().list(params); + List statuses = new ArrayList<>(); + for (Object item : response.getData()) { + statuses.add(JsonUtils.convertValue(item, TestCaseResolutionStatus.class)); + } + return statuses; + } + + private Set statusTestCaseFqns(List statuses) { + return statuses.stream() + .map(status -> status.getTestCaseReference().getFullyQualifiedName()) + .collect(Collectors.toSet()); + } + + private TestCaseIncidentGroup findGroup( + List groups, String fullyQualifiedName) { + Optional group = + groups.stream() + .filter(candidate -> fullyQualifiedName.equals(candidate.getFullyQualifiedName())) + .findFirst(); + assertTrue(group.isPresent(), "expected a group for " + fullyQualifiedName); + return group.orElseThrow(); + } + + private void assertGroupAbsent(List groups, String fullyQualifiedName) { + assertTrue( + groups.stream() + .noneMatch(candidate -> fullyQualifiedName.equals(candidate.getFullyQualifiedName())), + "expected no group for " + fullyQualifiedName); + } + + private void assertSorted(List groups, boolean ascending) { + for (int i = 1; i < groups.size(); i++) { + int previous = groups.get(i - 1).getIncidentCount(); + int current = groups.get(i).getIncidentCount(); + assertTrue( + ascending ? previous <= current : previous >= current, + "groups must be sorted by incidentCount " + (ascending ? "ascending" : "descending")); + } + } +} diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java index e077d51b82f7..05b6a3164501 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java @@ -7,6 +7,7 @@ import org.openmetadata.schema.tests.type.Assigned; import org.openmetadata.schema.tests.type.Resolved; import org.openmetadata.schema.tests.type.Severity; +import org.openmetadata.schema.tests.type.TestCaseIncidentGroup; import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; import org.openmetadata.schema.utils.ResultList; @@ -106,6 +107,23 @@ public ListResponse searchList(ListParams params) return new ListResponse<>(result); } + /** + * List open incident counts grouped by a dimension (table, testDefinition, or owner). + * + * @param queryParams Query parameters; `groupBy` is required + * @return List of incident groups with counts + */ + public ListResponse listIncidentGroups(Map queryParams) + throws OpenMetadataException { + String path = BASE_PATH + "/incidentGroups"; + if (queryParams != null && !queryParams.isEmpty()) { + path += "?" + buildQueryString(queryParams); + } + ResultList result = + httpClient.execute(HttpMethod.GET, path, null, getIncidentGroupResultListType()); + return new ListResponse<>(result); + } + // =================================================================== // CREATE OPERATIONS // =================================================================== @@ -157,6 +175,11 @@ private Class> getResultListType() { return (Class>) (Class) ResultList.class; } + @SuppressWarnings("unchecked") + private Class> getIncidentGroupResultListType() { + return (Class>) (Class) ResultList.class; + } + // =================================================================== // FLUENT API BUILDER // =================================================================== diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index 2dd4ba93c964..a0f65c973dc8 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -164,6 +164,8 @@ import org.openmetadata.schema.tests.TestCase; import org.openmetadata.schema.tests.TestDefinition; import org.openmetadata.schema.tests.TestSuite; +import org.openmetadata.schema.tests.type.IncidentGroupBy; +import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; import org.openmetadata.schema.type.ChangeEvent; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.EventType; @@ -187,6 +189,7 @@ import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlQuery; import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlUpdate; import org.openmetadata.service.jdbi3.oauth.OAuthRecords; +import org.openmetadata.service.resources.databases.DatasourceConfig; import org.openmetadata.service.resources.events.subscription.TypedEvent; import org.openmetadata.service.resources.feeds.MessageParser.EntityLink; import org.openmetadata.service.resources.tags.TagLabelUtil; @@ -10396,8 +10399,9 @@ default List listWithOffset( outerFilter.addQueryParam("assignee", assignee); String condition = filter.getCondition(); - condition = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, condition); + condition = addOriginEntityFQNJoin(filter, condition); + String outerCondition = outerFilter.getCondition(); return listWithOffset( getTimeSeriesTableName(), filter.getQueryParams(), @@ -10407,11 +10411,11 @@ default List listWithOffset( offset, startTs, endTs, - filter.getQueryParams(), - outerFilter.getCondition()); + outerFilter.getQueryParams(), + outerCondition); } String condition = filter.getCondition(); - condition = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, condition); + condition = addOriginEntityFQNJoin(filter, condition); return listWithOffset( getTimeSeriesTableName(), filter.getQueryParams(), @@ -10425,7 +10429,7 @@ default List listWithOffset( @Override default int listCount(ListFilter filter, Long startTs, Long endTs, boolean latest) { String condition = filter.getCondition(); - condition = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, condition); + condition = addOriginEntityFQNJoin(filter, condition); return latest ? listCount( getTimeSeriesTableName(), @@ -10440,7 +10444,7 @@ default int listCount(ListFilter filter, Long startTs, Long endTs, boolean lates @Override default List listWithOffset(ListFilter filter, int limit, int offset) { String condition = filter.getCondition(); - condition = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, condition); + condition = addOriginEntityFQNJoin(filter, condition); return listWithOffset( getTimeSeriesTableName(), filter.getQueryParams(), condition, limit, offset); } @@ -10448,7 +10452,7 @@ default List listWithOffset(ListFilter filter, int limit, int offset) { @Override default int listCount(ListFilter filter) { String condition = filter.getCondition(); - condition = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, condition); + condition = addOriginEntityFQNJoin(filter, condition); return listCount(getTimeSeriesTableName(), filter.getQueryParams(), condition); } @@ -10484,6 +10488,183 @@ default int listCount(ListFilter filter) { + ")", connectionType = POSTGRES) int deleteOrphanedRecords(@Bind("limit") int limit); + + // An incident is a stateId chain; the latest record (rn = 1) carries its current status and + // assignee, while createdAt/updatedAt are the chain's first/last record timestamps. + String INCIDENT_GROUPS_CTE = + """ + WITH incident AS ( + SELECT stateId, entityFQNHash, testCaseResolutionStatusType, assignee, + ROW_NUMBER() OVER (PARTITION BY stateId ORDER BY timestamp DESC) AS rn, + MIN(timestamp) OVER (PARTITION BY stateId) AS createdAt, + MAX(timestamp) OVER (PARTITION BY stateId) AS updatedAt + FROM test_case_resolution_status_time_series + + ) + """; + + @SqlQuery( + INCIDENT_GROUPS_CTE + + """ + SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateId) AS incidentCount + FROM incident i + INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash + + AND i.rn = 1 AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE + GROUP BY + ORDER BY incidentCount , groupKey + LIMIT :limit OFFSET :offset + """) + @RegisterRowMapper(TestCaseIncidentGroupCountMapper.class) + List listIncidentGroups( + @Define("incidentCond") String incidentCond, + @Define("groupKey") String groupKey, + @Define("groupType") String groupType, + @Define("groupByCols") String groupByCols, + @Define("dimensionJoin") String dimensionJoin, + @Define("cond") String cond, + @Define("sortOrder") String sortOrder, + @BindMap Map params, + @Bind("limit") int limit, + @Bind("offset") int offset); + + @SqlQuery( + INCIDENT_GROUPS_CTE + + """ + SELECT COUNT(DISTINCT ) + FROM incident i + INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash + + AND i.rn = 1 AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE + """) + int countIncidentGroups( + @Define("incidentCond") String incidentCond, + @Define("groupKey") String groupKey, + @Define("dimensionJoin") String dimensionJoin, + @Define("cond") String cond, + @BindMap Map params); + + // if originEntityFQN is present, we need to join with test_case table + static String addOriginEntityFQNJoin(ListFilter filter, String condition) { + String result = condition; + if ((filter.getQueryParam("originEntityFQN") != null) + || (filter.getQueryParam("include") != null)) { + result = + """ + INNER JOIN (SELECT entityFQN AS testCaseEntityFQN,fqnHash AS testCaseHash, deleted FROM test_case) tc \ + ON entityFQNHash = testCaseHash + """ + + condition; + } + return result; + } + + default IncidentGroupPage listIncidentGroups( + IncidentGroupBy groupBy, ListFilter filter, String sortOrder, int limit, int offset) { + IncidentGroupSqlParts sqlParts = buildIncidentGroupSqlParts(groupBy, filter); + IncidentGroupDimension dimension = sqlParts.dimension(); + int total = + countIncidentGroups( + sqlParts.scopeCondition(), + dimension.groupKey(), + dimension.join(), + sqlParts.condition(), + sqlParts.params()); + List counts = + listIncidentGroups( + sqlParts.scopeCondition(), + dimension.groupKey(), + dimension.groupType(), + dimension.groupByCols(), + dimension.join(), + sqlParts.condition(), + sortOrder, + sqlParts.params(), + limit, + offset); + return new IncidentGroupPage(counts, total); + } + + private static IncidentGroupSqlParts buildIncidentGroupSqlParts( + IncidentGroupBy groupBy, ListFilter filter) { + Map params = new HashMap<>(); + String scopeCondition = buildIncidentGroupScopeCondition(filter, params); + String condition = filter.getCondition(); + params.putAll(filter.getQueryParams()); + params.put("resolvedStatus", TestCaseResolutionStatusTypes.Resolved.value()); + return new IncidentGroupSqlParts( + scopeCondition, condition, IncidentGroupDimension.from(groupBy), params); + } + + // Pushes the test case scope into the CTE so incidents are ranked over a single FQN's + // records, and removes it from the filter so ListFilter does not re-apply it in the outer + // condition. + private static String buildIncidentGroupScopeCondition( + ListFilter filter, Map params) { + String result = ""; + String testCaseFQNHash = filter.getQueryParam("entityFQNHash"); + if (!nullOrEmpty(testCaseFQNHash)) { + filter.removeQueryParam("entityFQNHash"); + params.put("testCaseFQNHash", testCaseFQNHash); + result = "WHERE entityFQNHash = :testCaseFQNHash"; + } + return result; + } + + record IncidentGroupPage(List counts, int total) {} + + record IncidentGroupSqlParts( + String scopeCondition, + String condition, + IncidentGroupDimension dimension, + Map params) {} + + record IncidentGroupDimension( + String groupKey, String groupType, String groupByCols, String join) { + + static IncidentGroupDimension from(IncidentGroupBy groupBy) { + return switch (groupBy) { + case Table -> forTable(); + case TestDefinition -> forRelationship( + CONTAINS, String.format("er.fromEntity = '%s'", Entity.TEST_DEFINITION)); + case Owner -> forRelationship( + OWNS, String.format("er.fromEntity IN ('%s', '%s')", Entity.USER, Entity.TEAM)); + }; + } + + // test_case.entityFQN is column-level for column test cases, so the origin table FQN is + // extracted from the entityLink (<#E::table::fqn> or <#E::table::fqn::columns::col>) + // instead. + private static IncidentGroupDimension forTable() { + String tableFqn = + Boolean.TRUE.equals(DatasourceConfig.getInstance().isMySQL()) + ? "TRIM(TRAILING '>' FROM SUBSTRING_INDEX(SUBSTRING_INDEX(tc.entityLink, '::', 3), '::', -1))" + : "TRIM(TRAILING '>' FROM SPLIT_PART(tc.entityLink, '::', 3))"; + return new IncidentGroupDimension( + tableFqn, String.format("'%s'", Entity.TABLE), tableFqn, ""); + } + + private static IncidentGroupDimension forRelationship( + Relationship relation, String fromEntityCondition) { + String join = + String.format( + "INNER JOIN entity_relationship er ON er.toId = tc.id AND er.relation = %d " + + "AND %s AND er.toEntity = '%s'", + relation.ordinal(), fromEntityCondition, Entity.TEST_CASE); + return new IncidentGroupDimension( + "er.fromId", "er.fromEntity", "er.fromId, er.fromEntity", join); + } + } + } + + record TestCaseIncidentGroupCount(String groupKey, String groupType, int incidentCount) {} + + class TestCaseIncidentGroupCountMapper implements RowMapper { + @Override + public TestCaseIncidentGroupCount map(ResultSet rs, StatementContext ctx) throws SQLException { + return new TestCaseIncidentGroupCount( + rs.getString("groupKey"), rs.getString("groupType"), rs.getInt("incidentCount")); + } } interface TestCaseResultTimeSeriesDAO extends EntityTimeSeriesDAO { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java index 5fb5fdbbcf8d..6c8f2b7e4041 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java @@ -66,6 +66,10 @@ public String getCondition(String tableName) { conditions.add(getTierCondition(tableName)); conditions.add(getEntityFQNHashCondition()); conditions.add(getTestCaseResolutionStatusType()); + conditions.add(getTestDefinitionCondition()); + conditions.add(getIncidentAssigneeCondition()); + conditions.add(getIncidentDomainCondition()); + conditions.add(getIncidentDateRangeCondition()); conditions.add(getDirectoryCondition(tableName)); conditions.add(getSpreadsheetCondition(tableName)); conditions.add(getFileTypeCondition(tableName)); @@ -439,9 +443,88 @@ private String getNotificationTemplateCondition() { private String getTestCaseResolutionStatusType() { String testFailureStatus = queryParams.get("testCaseResolutionStatusType"); - return testFailureStatus == null - ? "" - : "testCaseResolutionStatusType = :testCaseResolutionStatusType"; + String result = ""; + if (!nullOrEmpty(testFailureStatus)) { + String inCondition = + buildIndexedBindParams("testCaseResolutionStatusType", testFailureStatus); + result = String.format("testCaseResolutionStatusType IN (%s)", inCondition); + } + return result; + } + + // Scopes the test_case_resolution_status_time_series listing to the test cases contained in + // a test definition; testDefinitionId is only set by TestCaseResolutionStatusResource#list. + private String getTestDefinitionCondition() { + String testDefinitionId = queryParams.get("testDefinitionId"); + String result = ""; + if (!nullOrEmpty(testDefinitionId)) { + result = + String.format( + "entityFQNHash IN (SELECT tdtc.fqnHash FROM test_case tdtc " + + "INNER JOIN entity_relationship tder ON tder.toId = tdtc.id " + + "WHERE tder.fromId = :testDefinitionId AND tder.fromEntity = '%s' " + + "AND tder.toEntity = '%s' AND tder.relation = %d)", + Entity.TEST_DEFINITION, Entity.TEST_CASE, Relationship.CONTAINS.ordinal()); + } + return result; + } + + // The incident grouping query (TestCaseResolutionStatusRepository#listIncidentGroups) ranks + // test_case_resolution_status_time_series records per stateId in a CTE aliased {@code i} + // (rn = 1 is the incident's latest record; createdAt/updatedAt are its first/last record + // timestamps) and joins test_case as {@code tc}. The incident* query params below are only set + // by TestCaseResolutionStatusResource#listIncidentGroups, mirroring how originEntityFQN pairs + // with the join added by TestCaseResolutionStatusTimeSeriesDAO#addOriginEntityFQNJoin. + private String getIncidentAssigneeCondition() { + String assignee = queryParams.get("incidentAssignee"); + return nullOrEmpty(assignee) ? "" : "assignee = :incidentAssignee"; + } + + private String getIncidentDomainCondition() { + String domainId = queryParams.get("incidentDomainId"); + String result = ""; + if (!nullOrEmpty(domainId)) { + result = + String.format( + "EXISTS (SELECT 1 FROM entity_relationship dr WHERE dr.fromId = :incidentDomainId " + + "AND dr.fromEntity = 'domain' AND dr.relation = %d " + + "AND dr.toId = tc.id AND dr.toEntity = 'testCase')", + Relationship.HAS.ordinal()); + } + return result; + } + + private String getIncidentDateRangeCondition() { + String start = queryParams.get("incidentStartTs"); + String end = queryParams.get("incidentEndTs"); + List clauses = new ArrayList<>(); + if (!nullOrEmpty(start) || !nullOrEmpty(end)) { + String column = getIncidentDateColumn(queryParams.get("incidentDateField")); + if (!nullOrEmpty(start)) { + clauses.add(String.format("%s >= %s", column, Long.parseLong(start))); + } + if (!nullOrEmpty(end)) { + clauses.add(String.format("%s <= %s", column, Long.parseLong(end))); + } + } + return String.join(" AND ", clauses); + } + + private String getIncidentDateColumn(String dateField) { + String defaulted = + dateField == null + ? TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_CREATED_AT + : dateField; + return switch (defaulted) { + case TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_CREATED_AT -> "i.createdAt"; + case TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_UPDATED_AT -> "i.updatedAt"; + default -> throw new IllegalArgumentException( + String.format( + "Invalid dateField '%s'. Must be one of [%s, %s]", + dateField, + TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_CREATED_AT, + TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_UPDATED_AT)); + }; } public String getIncludeCondition(String tableName) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java index de5e7009b82f..f024ac7aafd9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java @@ -4,6 +4,9 @@ import static org.openmetadata.schema.type.EventType.ENTITY_UPDATED; import static org.openmetadata.service.Entity.INGESTION_BOT_NAME; import static org.openmetadata.service.Entity.getEntityReferenceByName; +import static org.openmetadata.service.util.jdbi.JdbiUtils.getAfterOffset; +import static org.openmetadata.service.util.jdbi.JdbiUtils.getBeforeOffset; +import static org.openmetadata.service.util.jdbi.JdbiUtils.getOffset; import jakarta.json.JsonPatch; import jakarta.ws.rs.core.Response; @@ -23,9 +26,11 @@ import org.openmetadata.schema.entity.tasks.Task; import org.openmetadata.schema.tests.TestCase; import org.openmetadata.schema.tests.type.Assigned; +import org.openmetadata.schema.tests.type.IncidentGroupBy; import org.openmetadata.schema.tests.type.Metric; import org.openmetadata.schema.tests.type.Resolved; import org.openmetadata.schema.tests.type.Severity; +import org.openmetadata.schema.tests.type.TestCaseIncidentGroup; import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; import org.openmetadata.schema.type.EntityReference; @@ -45,6 +50,7 @@ import org.openmetadata.service.resources.feeds.MessageParser; import org.openmetadata.service.search.SearchListFilter; import org.openmetadata.service.util.EntityUtil; +import org.openmetadata.service.util.FullyQualifiedName; import org.openmetadata.service.util.RestUtil; import org.openmetadata.service.util.incidentSeverityClassifier.IncidentSeverityClassifierInterface; @@ -53,6 +59,10 @@ public class TestCaseResolutionStatusRepository extends EntityTimeSeriesRepository { public static final String TIME_TO_RESPONSE = "timeToResponse"; public static final String TIME_TO_RESOLUTION = "timeToResolution"; + public static final String INCIDENT_DATE_FIELD_CREATED_AT = "createdAt"; + public static final String INCIDENT_DATE_FIELD_UPDATED_AT = "updatedAt"; + public static final String INCIDENT_SORT_TYPE_ASC = "asc"; + public static final String INCIDENT_SORT_TYPE_DESC = "desc"; public TestCaseResolutionStatusRepository() { super( @@ -434,21 +444,6 @@ public void inferIncidentSeverity(TestCaseResolutionStatus incident) { incident.setSeverity(severity); } - public static String addOriginEntityFQNJoin(ListFilter filter, String condition) { - // if originEntityFQN is present, we need to join with test_case table - if ((filter.getQueryParam("originEntityFQN") != null) - || (filter.getQueryParam("include") != null)) { - condition = - """ - INNER JOIN (SELECT entityFQN AS testCaseEntityFQN,fqnHash AS testCaseHash, deleted FROM test_case) tc \ - ON entityFQNHash = testCaseHash - """ - + condition; - } - - return condition; - } - protected static UUID getOrCreateIncident(TestCase testCase, String updatedBy) { TaskRepository taskRepository = (TaskRepository) Entity.getEntityRepository(Entity.TASK); @@ -649,4 +644,74 @@ public TestCaseResolutionStatus getLatestRecordForStateId(UUID stateId) { .max((a, b) -> Long.compare(a.getTimestamp(), b.getTimestamp())) .orElse(records.get(records.size() - 1)); } + + public ResultList listIncidentGroups( + IncidentGroupBy groupBy, ListFilter filter, String sortType, int limit, String offset) { + int offsetInt = getOffset(offset); + CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO dao = + (CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO) timeSeriesDao; + CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO.IncidentGroupPage page = + dao.listIncidentGroups(groupBy, filter, incidentGroupSortOrder(sortType), limit, offsetInt); + List groups = + page.counts().stream().map(count -> toIncidentGroup(groupBy, count)).toList(); + return new ResultList<>( + groups, + getBeforeOffset(offsetInt, limit), + getAfterOffset(offsetInt, limit, page.total()), + page.total()); + } + + private static String incidentGroupSortOrder(String sortType) { + return switch (sortType == null ? INCIDENT_SORT_TYPE_DESC : sortType) { + case INCIDENT_SORT_TYPE_ASC -> "ASC"; + case INCIDENT_SORT_TYPE_DESC -> "DESC"; + default -> throw new IllegalArgumentException( + String.format( + "Invalid sortType '%s'. Must be one of [%s, %s]", + sortType, INCIDENT_SORT_TYPE_ASC, INCIDENT_SORT_TYPE_DESC)); + }; + } + + private static TestCaseIncidentGroup toIncidentGroup( + IncidentGroupBy groupBy, CollectionDAO.TestCaseIncidentGroupCount count) { + TestCaseIncidentGroup group = + new TestCaseIncidentGroup().withGroupBy(groupBy).withIncidentCount(count.incidentCount()); + EntityReference reference = resolveIncidentGroupEntity(count); + if (reference != null) { + group + .withId(reference.getId()) + .withName(reference.getName()) + .withDisplayName(reference.getDisplayName()) + .withFullyQualifiedName(reference.getFullyQualifiedName()); + } else { + setFallbackIncidentGroupIdentity(group, count); + } + return group; + } + + private static EntityReference resolveIncidentGroupEntity( + CollectionDAO.TestCaseIncidentGroupCount count) { + EntityReference result = null; + try { + result = + Entity.TABLE.equals(count.groupType()) + ? Entity.getEntityReferenceByName(Entity.TABLE, count.groupKey(), Include.ALL) + : Entity.getEntityReferenceById( + count.groupType(), UUID.fromString(count.groupKey()), Include.ALL); + } catch (EntityNotFoundException e) { + LOG.debug( + "Incident group {} '{}' could not be resolved", count.groupType(), count.groupKey()); + } + return result; + } + + private static void setFallbackIncidentGroupIdentity( + TestCaseIncidentGroup group, CollectionDAO.TestCaseIncidentGroupCount count) { + if (Entity.TABLE.equals(count.groupType())) { + List fqnParts = List.of(FullyQualifiedName.split(count.groupKey())); + group.withName(fqnParts.getLast()).withFullyQualifiedName(count.groupKey()); + } else { + group.withName(count.groupKey()); + } + } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java index f57a52bf6693..26ea0b708e6e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java @@ -1,5 +1,8 @@ package org.openmetadata.service.resources.dqtests; +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; +import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; + import io.swagger.v3.oas.annotations.ExternalDocumentation; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; @@ -28,14 +31,20 @@ import jakarta.ws.rs.core.SecurityContext; import jakarta.ws.rs.core.UriInfo; import java.io.IOException; +import java.util.ArrayList; import java.util.List; import java.util.UUID; +import java.util.stream.Collectors; +import java.util.stream.Stream; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.api.tests.CreateTestCaseResolutionStatus; import org.openmetadata.schema.tests.TestCase; +import org.openmetadata.schema.tests.type.IncidentGroupBy; +import org.openmetadata.schema.tests.type.TestCaseIncidentGroup; import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; import org.openmetadata.schema.utils.ResultList; @@ -80,13 +89,17 @@ public static class TestCaseResolutionStatusResultList /* Required for serde */ } + public static class TestCaseIncidentGroupResultList extends ResultList { + /* Required for serde */ + } + @GET @Operation( operationId = "getTestCaseResolutionStatus", summary = "List the test case failure statuses", description = "Get a list of all the test case failure statuses, optionally filtered by `startTs` and `endTs` of the status creation, " - + "status, assignee, and test case id. " + + "status, assignee, test case id, and the test definition of the test case. " + "Use cursor-based pagination to limit the number of " + "entries in the list using `limit` and `before` or `after` query params.", responses = { @@ -154,7 +167,13 @@ public ResultList list( String originEntityFQN, @Parameter(description = "Filter incidents by domain", schema = @Schema(type = "String")) @QueryParam("domain") - String domain) { + String domain, + @Parameter( + description = + "Filter incidents by the test definition of their test case, by name or fully qualified name", + schema = @Schema(type = "String")) + @QueryParam("testDefinition") + String testDefinition) { ResourceContextInterface testCaseResourceContext = getTestCaseResourceContext(testCaseFQN); ResourceContextInterface entityResourceContext = buildEntityResourceContext(testCaseFQN, testCaseId, originEntityFQN); @@ -169,10 +188,140 @@ public ResultList list( filter.addQueryParam("entityFQNHash", FullyQualifiedName.buildHash(testCaseFQN)); filter.addQueryParam("originEntityFQN", originEntityFQN); filter.addQueryParam("domain", domain); + UUID testDefinitionId = resolveFilterEntityId(Entity.TEST_DEFINITION, testDefinition); + if (testDefinitionId != null) { + filter.addQueryParam("testDefinitionId", testDefinitionId.toString()); + } return repository.list(offset, startTs, endTs, limitParam, filter, latest); } + @GET + @Path("/incidentGroups") + @Operation( + operationId = "listTestCaseIncidentGroups", + summary = "List open incident counts grouped by a dimension", + description = + "Get the number of distinct open incidents grouped by `table`, `testDefinition`, or `owner`. " + + "Resolved incidents are never included. Optionally filter by open statuses, current " + + "assignee, test case, domain, and a date range applied to the incident's `createdAt` " + + "or `updatedAt` timestamp. Use `limit` and the `paging.before`/`paging.after` cursors " + + "as the `offset` query param to paginate the groups.", + responses = { + @ApiResponse( + responseCode = "200", + description = "List of incident groups with counts", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = TestCaseIncidentGroupResultList.class))) + }) + public ResultList listIncidentGroups( + @Context SecurityContext securityContext, + @Parameter( + description = "Dimension to group incidents by", + required = true, + schema = @Schema(implementation = IncidentGroupBy.class)) + @QueryParam("groupBy") + String groupBy, + @Parameter( + description = + "Filter incidents by their current open status. Repeatable or comma-separated; `Resolved` is rejected.", + schema = @Schema(implementation = TestCaseResolutionStatusTypes.class)) + @QueryParam("status") + List statuses, + @Parameter( + description = "Filter incidents by their current assignee", + schema = @Schema(type = "String")) + @QueryParam("assignee") + String assignee, + @Parameter(description = "Test case fully qualified name", schema = @Schema(type = "String")) + @QueryParam("testCaseFQN") + String testCaseFQN, + @Parameter( + description = "Incident timestamp the `startTs`/`endTs` range applies to", + schema = + @Schema( + type = "string", + allowableValues = { + TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_CREATED_AT, + TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_UPDATED_AT + })) + @QueryParam("dateField") + @DefaultValue(TestCaseResolutionStatusRepository.INCIDENT_DATE_FIELD_CREATED_AT) + String dateField, + @Parameter( + description = "Filter incidents after the given start timestamp", + schema = @Schema(type = "number")) + @QueryParam("startTs") + Long startTs, + @Parameter( + description = "Filter incidents before the given end timestamp", + schema = @Schema(type = "number")) + @QueryParam("endTs") + Long endTs, + @Parameter(description = "Filter incidents by domain", schema = @Schema(type = "String")) + @QueryParam("domain") + String domain, + @Parameter(description = "Limit the number of groups returned. (1 to 1000000, default = 10)") + @DefaultValue("10") + @QueryParam("limit") + @Min(value = 0, message = "must be greater than or equal to 0") + @Max(value = 1000000, message = "must be less than or equal to 1000000") + int limit, + @Parameter( + description = + "Returns the list of groups at the offset. Use the `paging.before`/`paging.after` " + + "cursor from a previous response", + schema = @Schema(type = "string")) + @QueryParam("offset") + String offset, + @Parameter( + description = "Sort type for the incident count", + schema = + @Schema( + type = "string", + allowableValues = { + TestCaseResolutionStatusRepository.INCIDENT_SORT_TYPE_ASC, + TestCaseResolutionStatusRepository.INCIDENT_SORT_TYPE_DESC + })) + @QueryParam("sortType") + @DefaultValue(TestCaseResolutionStatusRepository.INCIDENT_SORT_TYPE_DESC) + String sortType) { + IncidentGroupBy groupByDimension = parseIncidentGroupBy(groupBy); + List statusFilters = parseIncidentStatuses(statuses); + + ResourceContextInterface testCaseResourceContext = getTestCaseResourceContext(testCaseFQN); + ResourceContextInterface entityResourceContext = + buildEntityResourceContext(testCaseFQN, null, null); + List requests = + buildViewAuthRequests(testCaseResourceContext, entityResourceContext); + authorizer.authorizeRequests(securityContext, requests, AuthorizationLogic.ANY); + + ListFilter filter = new ListFilter(null); + if (!statusFilters.isEmpty()) { + filter.addQueryParam( + "testCaseResolutionStatusType", + statusFilters.stream() + .map(TestCaseResolutionStatusTypes::value) + .collect(Collectors.joining(","))); + } + filter.addQueryParam("incidentAssignee", assignee); + filter.addQueryParam("entityFQNHash", FullyQualifiedName.buildHash(testCaseFQN)); + UUID domainId = resolveFilterEntityId(Entity.DOMAIN, domain); + if (domainId != null) { + filter.addQueryParam("incidentDomainId", domainId.toString()); + } + filter.addQueryParam("incidentDateField", dateField); + if (startTs != null) { + filter.addQueryParam("incidentStartTs", String.valueOf(startTs)); + } + if (endTs != null) { + filter.addQueryParam("incidentEndTs", String.valueOf(endTs)); + } + return repository.listIncidentGroups(groupByDimension, filter, sortType, limit, offset); + } + @GET @Path("/stateId/{stateId}") @Operation( @@ -545,6 +694,60 @@ protected static List buildEditAuthRequests( testCaseResourceContext)); } + private static IncidentGroupBy parseIncidentGroupBy(String groupBy) { + IncidentGroupBy result; + if (nullOrEmpty(groupBy)) { + throw new IllegalArgumentException("Query parameter 'groupBy' is required"); + } + try { + result = IncidentGroupBy.fromValue(groupBy); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException( + String.format( + "Invalid groupBy '%s'. Must be one of %s", + groupBy, Stream.of(IncidentGroupBy.values()).map(IncidentGroupBy::value).toList())); + } + return result; + } + + private static List parseIncidentStatuses(List statuses) { + List result = new ArrayList<>(); + for (String statusParam : listOrEmpty(statuses)) { + for (String value : statusParam.split(",")) { + result.add(parseIncidentStatus(value.trim())); + } + } + return result; + } + + private static TestCaseResolutionStatusTypes parseIncidentStatus(String value) { + TestCaseResolutionStatusTypes result; + try { + result = TestCaseResolutionStatusTypes.fromValue(value); + } catch (IllegalArgumentException e) { + throw new IllegalArgumentException(String.format("Invalid status '%s'", value)); + } + if (result == TestCaseResolutionStatusTypes.Resolved) { + throw new IllegalArgumentException( + String.format( + "Status '%s' is not allowed; incident groups only count open incidents", + TestCaseResolutionStatusTypes.Resolved.value())); + } + return result; + } + + private static UUID resolveFilterEntityId(String entityType, String name) { + UUID entityId = null; + if (!nullOrEmpty(name)) { + EntityReference result = + Entity.getEntityReferenceByName(entityType, name, Include.NON_DELETED); + if (!nullOrEmpty(result)) { + entityId = result.getId(); + } + } + return entityId; + } + protected static ResourceContextInterface buildEntityResourceContext( String testCaseFQN, UUID testCaseId, String originEntityFQN) { if (testCaseFQN != null) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepositoryTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepositoryTest.java index bed26db6b0f2..bd6680bb4d5d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepositoryTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepositoryTest.java @@ -38,7 +38,9 @@ void testAddOriginEntityFQNJoin_withOriginEntityFQN() { ListFilter filter = new ListFilter(); filter.addQueryParam("originEntityFQN", "test.table"); - String result = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, "WHERE 1=1"); + String result = + CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO.addOriginEntityFQNJoin( + filter, "WHERE 1=1"); assertTrue(result.contains("INNER JOIN")); assertTrue(result.contains("test_case")); @@ -50,7 +52,9 @@ void testAddOriginEntityFQNJoin_withInclude() { ListFilter filter = new ListFilter(); filter.addQueryParam("include", "non-deleted"); - String result = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, "WHERE 1=1"); + String result = + CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO.addOriginEntityFQNJoin( + filter, "WHERE 1=1"); assertTrue(result.contains("INNER JOIN")); assertTrue(result.contains("test_case")); @@ -63,7 +67,9 @@ void testAddOriginEntityFQNJoin_withDefaultFilter() { // Since include is always set by default, the JOIN is always added ListFilter filter = new ListFilter(); - String result = TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, "WHERE 1=1"); + String result = + CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO.addOriginEntityFQNJoin( + filter, "WHERE 1=1"); // With default ListFilter, JOIN is added because include is set to NON_DELETED assertTrue(result.contains("INNER JOIN")); @@ -76,7 +82,8 @@ void testAddOriginEntityFQNJoin_preservesCondition() { filter.addQueryParam("originEntityFQN", "test.table"); String result = - TestCaseResolutionStatusRepository.addOriginEntityFQNJoin(filter, "WHERE status = 'Open'"); + CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO.addOriginEntityFQNJoin( + filter, "WHERE status = 'Open'"); assertTrue(result.contains("WHERE status = 'Open'")); } diff --git a/openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json b/openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json new file mode 100644 index 000000000000..aa7a24592831 --- /dev/null +++ b/openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json @@ -0,0 +1,49 @@ +{ + "$id": "https://open-metadata.org/schema/tests/testCaseIncidentGroup.json", + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "TestCaseIncidentGroup", + "description": "Aggregated count of open test case incidents for a given grouping dimension.", + "javaType": "org.openmetadata.schema.tests.type.TestCaseIncidentGroup", + "type": "object", + "definitions": { + "incidentGroupBy": { + "description": "Dimension used to group test case incidents.", + "javaType": "org.openmetadata.schema.tests.type.IncidentGroupBy", + "type": "string", + "enum": ["table", "testDefinition", "owner"], + "javaEnums": [ + {"name": "Table"}, + {"name": "TestDefinition"}, + {"name": "Owner"} + ] + } + }, + "properties": { + "groupBy": { + "description": "Dimension the incidents are grouped by.", + "$ref": "#/definitions/incidentGroupBy" + }, + "id": { + "description": "Unique identifier of the entity the group represents.", + "$ref": "../type/basic.json#/definitions/uuid" + }, + "name": { + "description": "Name of the entity the group represents.", + "type": "string" + }, + "displayName": { + "description": "Display name of the entity the group represents.", + "type": "string" + }, + "fullyQualifiedName": { + "description": "Fully qualified name of the entity the group represents.", + "$ref": "../type/basic.json#/definitions/fullyQualifiedEntityName" + }, + "incidentCount": { + "description": "Number of distinct open incidents in the group.", + "type": "integer" + } + }, + "required": ["groupBy", "name", "incidentCount"], + "additionalProperties": false +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts new file mode 100644 index 000000000000..062b8773e040 --- /dev/null +++ b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts @@ -0,0 +1,52 @@ +/* + * Copyright 2026 Collate. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Aggregated count of open test case incidents for a given grouping dimension. + */ +export interface TestCaseIncidentGroup { + /** + * Display name of the entity the group represents. + */ + displayName?: string; + /** + * Fully qualified name of the entity the group represents. + */ + fullyQualifiedName?: string; + /** + * Dimension the incidents are grouped by. + */ + groupBy: IncidentGroupBy; + /** + * Unique identifier of the entity the group represents. + */ + id?: string; + /** + * Number of distinct open incidents in the group. + */ + incidentCount: number; + /** + * Name of the entity the group represents. + */ + name: string; +} + +/** + * Dimension the incidents are grouped by. + * + * Dimension used to group test case incidents. + */ +export enum IncidentGroupBy { + Owner = "owner", + Table = "table", + TestDefinition = "testDefinition", +} From 1b7dc45f717f00d19271190f98c43cdab9b423e3 Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Wed, 22 Jul 2026 14:00:17 -0700 Subject: [PATCH 02/13] feat: added owner, status, assignee, severiuty and bucket for client metrics --- .../it/tests/IncidentGroupsIT.java | 204 +++++++++++++++++- .../TestCaseResolutionStatusService.java | 14 ++ .../handlers/IncidentTcrsSyncHandler.java | 8 + .../service/jdbi3/CollectionDAO.java | 162 +++++++++++--- .../jdbi3/EntityTimeSeriesRepository.java | 8 +- .../service/jdbi3/ListFilter.java | 31 ++- .../TestCaseResolutionStatusRepository.java | 88 +++++++- .../jdbi3/TestCaseResultRepository.java | 3 +- .../TestCaseResolutionStatusMapper.java | 11 +- .../TestCaseResolutionStatusResource.java | 169 ++++++++++++++- .../schema/tests/testCaseIncidentGroup.json | 49 +++++ .../tests/testCaseResolutionStatus.json | 4 + .../generated/tests/testCaseIncidentGroup.ts | 74 +++++++ .../tests/testCaseResolutionStatus.ts | 6 + 14 files changed, 786 insertions(+), 45 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java index 6a1973432eb9..29ba66dc4f0b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java @@ -1,11 +1,15 @@ package org.openmetadata.it.tests; +import static org.awaitility.Awaitility.await; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import java.nio.charset.StandardCharsets; +import java.time.Duration; import java.util.ArrayList; import java.util.Base64; import java.util.HashSet; @@ -27,6 +31,7 @@ import org.openmetadata.schema.api.teams.CreateUser; import org.openmetadata.schema.api.tests.CreateTestCase; import org.openmetadata.schema.api.tests.CreateTestCaseResolutionStatus; +import org.openmetadata.schema.api.tests.CreateTestCaseResult; import org.openmetadata.schema.api.tests.CreateTestDefinition; import org.openmetadata.schema.entity.data.Database; import org.openmetadata.schema.entity.data.Table; @@ -37,15 +42,20 @@ import org.openmetadata.schema.tests.TestPlatform; import org.openmetadata.schema.tests.type.Assigned; import org.openmetadata.schema.tests.type.IncidentGroupBy; +import org.openmetadata.schema.tests.type.IncidentTrendDirection; import org.openmetadata.schema.tests.type.Resolved; +import org.openmetadata.schema.tests.type.Severity; import org.openmetadata.schema.tests.type.TestCaseFailureReasonType; import org.openmetadata.schema.tests.type.TestCaseIncidentGroup; import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; +import org.openmetadata.schema.tests.type.TestCaseStatus; +import org.openmetadata.schema.type.ApiStatus; import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.TestDefinitionEntityType; +import org.openmetadata.schema.type.api.BulkOperationResult; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; import org.openmetadata.sdk.exceptions.OpenMetadataException; @@ -90,12 +100,13 @@ public class IncidentGroupsIT { private TestCase testCase4; private User pagerUser; private List pagerTableFqns; + private String schemaFqn; @BeforeAll void setup() throws Exception { client = SdkClients.adminClient(); long ts = System.currentTimeMillis(); - String schemaFqn = createSchema(ts); + schemaFqn = createSchema(ts); tableA = createTable(schemaFqn, "incident_groups_table_a_" + ts); tableB = createTable(schemaFqn, "incident_groups_table_b_" + ts); userA = createUser("incident_groups_user_a_" + ts); @@ -134,7 +145,7 @@ void setup() throws Exception { testCase2, TestCaseResolutionStatusTypes.Assigned, new Assigned().withAssignee(userA.getEntityReference())); - createStatus(testCase3, TestCaseResolutionStatusTypes.New, null); + createStatus(testCase3, TestCaseResolutionStatusTypes.New, null, Severity.Severity2); createStatus(testCase4, TestCaseResolutionStatusTypes.New, null); createStatus( testCase4, @@ -556,6 +567,186 @@ void testDbListUnknownTestDefinitionRejected() { assertEquals(404, error.getStatusCode()); } + @Test + void testGroupAggregates() throws Exception { + List groups = fetchGroups(groupParams(GROUP_BY_TABLE)); + + TestCaseIncidentGroup groupA = findGroup(groups, tableA.getFullyQualifiedName()); + assertEquals( + TestCaseResolutionStatusTypes.Assigned, + groupA.getStatus(), + "case 2's Assigned outranks case 1's status in the triage order"); + assertEquals(List.of(userA.getName()), groupA.getAssignees()); + assertEquals(1, groupA.getAssigneeCount()); + assertTrue(groupA.getFirstSeen() <= groupA.getLastSeen()); + assertEquals( + 2, + groupA.getTrend().stream().mapToInt(Integer::intValue).sum(), + "trend buckets must add up to the incident count"); + assertNotNull(groupA.getTrendDirection()); + + TestCaseIncidentGroup groupB = findGroup(groups, tableB.getFullyQualifiedName()); + assertEquals(TestCaseResolutionStatusTypes.New, groupB.getStatus()); + assertEquals(Severity.Severity2, groupB.getSeverity(), "case 3's explicit severity"); + assertEquals(0, groupB.getAssigneeCount()); + assertEquals( + List.of(1, 0, 0, 0, 0, 0, 0, 0), + groupB.getTrend(), + "a single open incident lands in the first bucket"); + assertEquals(IncidentTrendDirection.Steady, groupB.getTrendDirection()); + } + + @Test + void testDbListOwnerFilterScopesToOwner() throws Exception { + assertEquals( + Set.of(testCase1.getFullyQualifiedName(), testCase2.getFullyQualifiedName()), + statusTestCaseFqns( + listStatuses(new ListParams().withLimit(100).addFilter("owner", userA.getName()))), + "user A directly owns cases 1 and 2"); + assertEquals( + Set.of(testCase2.getFullyQualifiedName(), testCase3.getFullyQualifiedName()), + statusTestCaseFqns( + listStatuses(new ListParams().withLimit(100).addFilter("owner", userB.getName()))), + "user B directly owns cases 2 and 3"); + } + + @Test + void testDbListUnknownOwnerRejected() { + ListParams params = + new ListParams() + .withLimit(10) + .addFilter("owner", "incident_groups_unknown_owner_" + System.nanoTime()); + OpenMetadataException error = + assertThrows( + OpenMetadataException.class, () -> client.testCaseResolutionStatuses().list(params)); + assertEquals(404, error.getStatusCode()); + } + + @Test + void testBulkCreateStatuses() throws Exception { + CreateTestCaseResolutionStatus ackCase1 = + new CreateTestCaseResolutionStatus() + .withTestCaseReference(testCase1.getFullyQualifiedName()) + .withTestCaseResolutionStatusType(TestCaseResolutionStatusTypes.Ack); + CreateTestCaseResolutionStatus unknownCase = + new CreateTestCaseResolutionStatus() + .withTestCaseReference("incident_groups_missing_case_" + System.nanoTime()) + .withTestCaseResolutionStatusType(TestCaseResolutionStatusTypes.Ack); + + BulkOperationResult result = + client.testCaseResolutionStatuses().bulkCreate(List.of(ackCase1, unknownCase)); + + assertEquals(ApiStatus.PARTIAL_SUCCESS, result.getStatus()); + assertEquals(2, result.getNumberOfRowsProcessed()); + assertEquals(1, result.getNumberOfRowsPassed()); + assertEquals(1, result.getNumberOfRowsFailed()); + assertEquals( + TestCaseResolutionStatusTypes.Ack, + fetchStatuses(testCase1).getFirst().getTestCaseResolutionStatusType(), + "the bulk entry must append an Ack record to case 1's incident chain"); + } + + @Test + void testFailedResultDenormalizesFailureSummary() throws Exception { + long ts = System.currentTimeMillis(); + String failureText = "Expected 48210 rows, found 47006"; + Table summaryTable = createTable(schemaFqn, "incident_groups_summary_" + ts); + TestDefinition summaryDefinition = + createTestDefinition("incident_groups_summary_def_" + ts, TestDefinitionEntityType.TABLE); + TestCase summaryCase = + createTestCase( + "incident_groups_summary_case_" + ts, + tableLink(summaryTable), + summaryDefinition, + List.of()); + + CreateTestCaseResult failedResult = + new CreateTestCaseResult() + .withTimestamp(System.currentTimeMillis()) + .withTestCaseStatus(TestCaseStatus.Failed) + .withResult(failureText); + client.testCaseResults().create(summaryCase.getFullyQualifiedName(), failedResult); + + await() + .atMost(Duration.ofSeconds(30)) + .untilAsserted( + () -> { + List statuses = fetchStatuses(summaryCase); + assertFalse(statuses.isEmpty(), "the failed result must open an incident"); + assertEquals( + failureText, + statuses.getFirst().getFailureSummary(), + "the incident record must carry the denormalized failure text"); + }); + } + + // Without a startTs/endTs range the data query skips the timestamp clause but the count query + // used to keep it, evaluating BETWEEN NULL AND NULL — total came back 0 and no after-cursor was + // ever emitted, so unranged listings could not paginate. + @Test + void testDbListPagingWithoutTimeRange() throws Exception { + ListParams firstPage = + new ListParams().withLimit(1).addFilter("testCaseFQN", testCase2.getFullyQualifiedName()); + ListResponse first = + client.testCaseResolutionStatuses().list(firstPage); + + assertEquals(2, first.getPaging().getTotal(), "case 2 has a two-record chain"); + assertEquals(1, first.getData().size()); + assertNotNull(first.getPaging().getAfter(), "a second page must be reachable"); + + ListParams secondPage = + new ListParams() + .withLimit(1) + .addFilter("testCaseFQN", testCase2.getFullyQualifiedName()) + .addFilter("offset", first.getPaging().getAfter()); + ListResponse second = + client.testCaseResolutionStatuses().list(secondPage); + + assertEquals(2, second.getPaging().getTotal()); + assertEquals(1, second.getData().size()); + assertNull(second.getPaging().getAfter(), "two records, so page two is the last page"); + Set ids = new HashSet<>(); + ids.add( + JsonUtils.convertValue(first.getData().getFirst(), TestCaseResolutionStatus.class) + .getId() + .toString()); + ids.add( + JsonUtils.convertValue(second.getData().getFirst(), TestCaseResolutionStatus.class) + .getId() + .toString()); + assertEquals(2, ids.size(), "the two pages must return distinct records"); + } + + // The `assignee` param used to fall through to ListFilter's task-oriented condition, which + // hashes the name and matches ASSIGNED_TO relationship targets — never a time-series record + // id — so the DB list silently returned nothing for any assignee. + @Test + void testDbListAssigneeFilter() throws Exception { + List records = + listStatuses(new ListParams().withLimit(100).addFilter("assignee", userA.getName())); + assertEquals( + Set.of(testCase2.getFullyQualifiedName()), + statusTestCaseFqns(records), + "only case 2 has a record assigned to user A"); + assertEquals( + TestCaseResolutionStatusTypes.Assigned, + records.getFirst().getTestCaseResolutionStatusType()); + + String endTs = String.valueOf(System.currentTimeMillis() + 60_000); + List latest = + listStatuses( + new ListParams() + .withLimit(100) + .withLatest(true) + .addFilter("startTs", "0") + .addFilter("endTs", endTs) + .addFilter("assignee", userA.getName())); + assertEquals( + Set.of(testCase2.getFullyQualifiedName()), + statusTestCaseFqns(latest), + "latest-per-test-case filtering must also honor the assignee"); + } + @Test void testResolvedStatusRejected() { Map params = groupParams(GROUP_BY_TABLE); @@ -664,6 +855,12 @@ private void assignDomain(TestCase testCase, Domain assignedDomain) throws Excep private void createStatus(TestCase testCase, TestCaseResolutionStatusTypes type, Object details) throws Exception { + createStatus(testCase, type, details, null); + } + + private void createStatus( + TestCase testCase, TestCaseResolutionStatusTypes type, Object details, Severity severity) + throws Exception { CreateTestCaseResolutionStatus request = new CreateTestCaseResolutionStatus() .withTestCaseResolutionStatusType(type) @@ -671,6 +868,9 @@ private void createStatus(TestCase testCase, TestCaseResolutionStatusTypes type, if (details != null) { request.withTestCaseResolutionStatusDetails(details); } + if (severity != null) { + request.withSeverity(severity); + } client.testCaseResolutionStatuses().create(request); } diff --git a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java index 05b6a3164501..45b3a4764780 100644 --- a/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java +++ b/openmetadata-sdk/src/main/java/org/openmetadata/sdk/services/tests/TestCaseResolutionStatusService.java @@ -1,6 +1,7 @@ package org.openmetadata.sdk.services.tests; import com.fasterxml.jackson.databind.JsonNode; +import java.util.List; import java.util.Map; import java.util.UUID; import org.openmetadata.schema.api.tests.CreateTestCaseResolutionStatus; @@ -10,6 +11,7 @@ import org.openmetadata.schema.tests.type.TestCaseIncidentGroup; import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; +import org.openmetadata.schema.type.api.BulkOperationResult; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.models.ListParams; @@ -65,6 +67,18 @@ public ListResponse list(ListParams params) return new ListResponse<>(result); } + /** + * Bulk create resolution statuses — e.g. assign or resolve a selection of incidents at once. + * + * @param createRequests One create request per incident, up to 100 per call + * @return Per-entry success/failure results + */ + public BulkOperationResult bulkCreate(List createRequests) + throws OpenMetadataException { + return httpClient.execute( + HttpMethod.PUT, BASE_PATH + "/bulk", createRequests, BulkOperationResult.class); + } + /** * Get a resolution status by state ID. * diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/IncidentTcrsSyncHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/IncidentTcrsSyncHandler.java index 0e7eac31da4a..d6e2429add09 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/IncidentTcrsSyncHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/IncidentTcrsSyncHandler.java @@ -29,6 +29,7 @@ import org.openmetadata.schema.type.TaskCategory; import org.openmetadata.schema.type.TaskEntityType; import org.openmetadata.schema.type.TaskResolution; +import org.openmetadata.schema.type.TestCaseResolutionPayload; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.TestCaseResolutionStatusRepository; @@ -155,6 +156,7 @@ private static void syncStage(Task task) { .withTestCaseReference(task.getAbout()) .withTimestamp(task.getUpdatedAt()) .withUpdatedAt(task.getUpdatedAt()) + .withFailureSummary(extractFailureReason(task)) .withUpdatedBy( task.getUpdatedBy() != null ? EntityUtil.getEntityReference(Entity.USER, task.getUpdatedBy()) @@ -176,6 +178,12 @@ private static void syncStage(Task task) { } } + private static String extractFailureReason(Task task) { + TestCaseResolutionPayload payload = + JsonUtils.convertValue(task.getPayload(), TestCaseResolutionPayload.class); + return payload != null ? payload.getFailureReason() : null; + } + private static Object buildDetailsForStage(TestCaseResolutionStatusTypes type, Task task) { return switch (type) { case Assigned -> { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index a0f65c973dc8..8278345de36a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -10391,12 +10391,12 @@ default List listWithOffset( // We'll first get the values, remove then from `filter` and then create `outerFilter` String testCaseResolutionStatusType = filter.getQueryParam("testCaseResolutionStatusType"); filter.removeQueryParam("testCaseResolutionStatusType"); - String assignee = filter.getQueryParam("assignee"); - filter.removeQueryParam("assignee"); + String assignee = filter.getQueryParam("incidentAssignee"); + filter.removeQueryParam("incidentAssignee"); ListFilter outerFilter = new ListFilter(null); outerFilter.addQueryParam("testCaseResolutionStatusType", testCaseResolutionStatusType); - outerFilter.addQueryParam("assignee", assignee); + outerFilter.addQueryParam("incidentAssignee", assignee); String condition = filter.getCondition(); condition = addOriginEntityFQNJoin(filter, condition); @@ -10489,28 +10489,43 @@ default int listCount(ListFilter filter) { connectionType = POSTGRES) int deleteOrphanedRecords(@Bind("limit") int limit); - // An incident is a stateId chain; the latest record (rn = 1) carries its current status and - // assignee, while createdAt/updatedAt are the chain's first/last record timestamps. + // An incident is a stateId chain. `chain` folds each stateId to its first/last timestamps + // over the (stateId, timestamp) index and `incident` joins back on the last timestamp to + // pick the chain's latest record, which carries the current status/assignee/severity. This + // replaces ROW_NUMBER/MIN/MAX window functions, which materialized three buffered passes + // over the whole table at scale. String INCIDENT_GROUPS_CTE = """ - WITH incident AS ( - SELECT stateId, entityFQNHash, testCaseResolutionStatusType, assignee, - ROW_NUMBER() OVER (PARTITION BY stateId ORDER BY timestamp DESC) AS rn, - MIN(timestamp) OVER (PARTITION BY stateId) AS createdAt, - MAX(timestamp) OVER (PARTITION BY stateId) AS updatedAt + WITH chain AS ( + SELECT stateId, MIN(timestamp) AS createdAt, MAX(timestamp) AS updatedAt FROM test_case_resolution_status_time_series + GROUP BY stateId + ), + incident AS ( + SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, + AS severity, c.createdAt, c.updatedAt + FROM chain c + INNER JOIN test_case_resolution_status_time_series t + ON t.stateId = c.stateId AND t.timestamp = c.updatedAt ) """; @SqlQuery( INCIDENT_GROUPS_CTE + """ - SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateId) AS incidentCount + SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateId) AS incidentCount, + MIN(i.severity) AS severity, + MIN(CASE i.testCaseResolutionStatusType WHEN 'Assigned' THEN 1 WHEN 'Ack' THEN 2 ELSE 3 END) AS statusRank, + AS assignees, + COUNT(DISTINCT i.assignee) AS assigneeCount, + MIN(i.createdAt) AS firstSeen, + MAX(i.updatedAt) AS lastSeen, + COUNT(*) OVER () AS totalGroups FROM incident i INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash - AND i.rn = 1 AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE + AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE GROUP BY ORDER BY incidentCount , groupKey LIMIT :limit OFFSET :offset @@ -10518,6 +10533,8 @@ SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateI @RegisterRowMapper(TestCaseIncidentGroupCountMapper.class) List listIncidentGroups( @Define("incidentCond") String incidentCond, + @Define("severityExpr") String severityExpr, + @Define("assigneesExpr") String assigneesExpr, @Define("groupKey") String groupKey, @Define("groupType") String groupType, @Define("groupByCols") String groupByCols, @@ -10535,15 +10552,36 @@ SELECT COUNT(DISTINCT ) FROM incident i INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash - AND i.rn = 1 AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE + AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE """) int countIncidentGroups( @Define("incidentCond") String incidentCond, + @Define("severityExpr") String severityExpr, @Define("groupKey") String groupKey, @Define("dimensionJoin") String dimensionJoin, @Define("cond") String cond, @BindMap Map params); + @SqlQuery( + INCIDENT_GROUPS_CTE + + """ + SELECT AS groupKey, i.createdAt AS createdAt + FROM incident i + INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash + + AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE + AND IN () + """) + @RegisterRowMapper(IncidentGroupCreatedAtMapper.class) + List listIncidentGroupCreatedAt( + @Define("incidentCond") String incidentCond, + @Define("severityExpr") String severityExpr, + @Define("groupKey") String groupKey, + @Define("dimensionJoin") String dimensionJoin, + @Define("cond") String cond, + @BindMap Map params, + @BindList("groupKeys") List groupKeys); + // if originEntityFQN is present, we need to join with test_case table static String addOriginEntityFQNJoin(ListFilter filter, String condition) { String result = condition; @@ -10563,16 +10601,11 @@ default IncidentGroupPage listIncidentGroups( IncidentGroupBy groupBy, ListFilter filter, String sortOrder, int limit, int offset) { IncidentGroupSqlParts sqlParts = buildIncidentGroupSqlParts(groupBy, filter); IncidentGroupDimension dimension = sqlParts.dimension(); - int total = - countIncidentGroups( - sqlParts.scopeCondition(), - dimension.groupKey(), - dimension.join(), - sqlParts.condition(), - sqlParts.params()); List counts = listIncidentGroups( sqlParts.scopeCondition(), + severityExpr(), + assigneesExpr(), dimension.groupKey(), dimension.groupType(), dimension.groupByCols(), @@ -10582,7 +10615,57 @@ default IncidentGroupPage listIncidentGroups( sqlParts.params(), limit, offset); - return new IncidentGroupPage(counts, total); + // The page query carries the group total via COUNT(*) OVER (); the standalone count only + // runs for an empty page past the end of the list, where no row carries the total. + int total; + if (!counts.isEmpty()) { + total = counts.getFirst().totalGroups(); + } else if (offset == 0) { + total = 0; + } else { + total = + countIncidentGroups( + sqlParts.scopeCondition(), + severityExpr(), + dimension.groupKey(), + dimension.join(), + sqlParts.condition(), + sqlParts.params()); + } + return new IncidentGroupPage(counts, total, fetchIncidentCreatedAt(sqlParts, counts)); + } + + private Map> fetchIncidentCreatedAt( + IncidentGroupSqlParts sqlParts, List counts) { + Map> result = new HashMap<>(); + if (!counts.isEmpty()) { + List groupKeys = counts.stream().map(TestCaseIncidentGroupCount::groupKey).toList(); + List rows = + listIncidentGroupCreatedAt( + sqlParts.scopeCondition(), + severityExpr(), + sqlParts.dimension().groupKey(), + sqlParts.dimension().join(), + sqlParts.condition(), + sqlParts.params(), + groupKeys); + for (IncidentGroupCreatedAt row : rows) { + result.computeIfAbsent(row.groupKey(), key -> new ArrayList<>()).add(row.createdAt()); + } + } + return result; + } + + private static String severityExpr() { + return Boolean.TRUE.equals(DatasourceConfig.getInstance().isMySQL()) + ? "json_unquote(json_extract(json, '$.severity'))" + : "json ->> 'severity'"; + } + + private static String assigneesExpr() { + return Boolean.TRUE.equals(DatasourceConfig.getInstance().isMySQL()) + ? "GROUP_CONCAT(DISTINCT i.assignee)" + : "STRING_AGG(DISTINCT i.assignee, ',')"; } private static IncidentGroupSqlParts buildIncidentGroupSqlParts( @@ -10611,7 +10694,10 @@ private static String buildIncidentGroupScopeCondition( return result; } - record IncidentGroupPage(List counts, int total) {} + record IncidentGroupPage( + List counts, + int total, + Map> createdAtByGroupKey) {} record IncidentGroupSqlParts( String scopeCondition, @@ -10657,13 +10743,41 @@ private static IncidentGroupDimension forRelationship( } } - record TestCaseIncidentGroupCount(String groupKey, String groupType, int incidentCount) {} + record TestCaseIncidentGroupCount( + String groupKey, + String groupType, + int incidentCount, + String severity, + int statusRank, + String assignees, + int assigneeCount, + long firstSeen, + long lastSeen, + int totalGroups) {} class TestCaseIncidentGroupCountMapper implements RowMapper { @Override public TestCaseIncidentGroupCount map(ResultSet rs, StatementContext ctx) throws SQLException { return new TestCaseIncidentGroupCount( - rs.getString("groupKey"), rs.getString("groupType"), rs.getInt("incidentCount")); + rs.getString("groupKey"), + rs.getString("groupType"), + rs.getInt("incidentCount"), + rs.getString("severity"), + rs.getInt("statusRank"), + rs.getString("assignees"), + rs.getInt("assigneeCount"), + rs.getLong("firstSeen"), + rs.getLong("lastSeen"), + rs.getInt("totalGroups")); + } + } + + record IncidentGroupCreatedAt(String groupKey, long createdAt) {} + + class IncidentGroupCreatedAtMapper implements RowMapper { + @Override + public IncidentGroupCreatedAt map(ResultSet rs, StatementContext ctx) throws SQLException { + return new IncidentGroupCreatedAt(rs.getString("groupKey"), rs.getLong("createdAt")); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityTimeSeriesRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityTimeSeriesRepository.java index d5aed3c7480e..d9e6cc1e2d87 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityTimeSeriesRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityTimeSeriesRepository.java @@ -235,7 +235,13 @@ public ResultList listWithOffset( Long endTs, boolean latest, boolean skipErrors) { - int total = timeSeriesDao.listCount(filter, startTs, endTs, latest); + // Mirror the data query's branching in listWithOffsetInternal: without a time range the + // ranged count would evaluate `timestamp BETWEEN NULL AND NULL`, reporting total = 0 for a + // non-empty listing and suppressing the after-cursor. + int total = + (startTs != null && endTs != null) + ? timeSeriesDao.listCount(filter, startTs, endTs, latest) + : timeSeriesDao.listCount(filter); return listWithOffsetInternal( offset, filter, limitParam, startTs, endTs, latest, skipErrors, total); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java index 6c8f2b7e4041..0370cfac6785 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ListFilter.java @@ -67,6 +67,7 @@ public String getCondition(String tableName) { conditions.add(getEntityFQNHashCondition()); conditions.add(getTestCaseResolutionStatusType()); conditions.add(getTestDefinitionCondition()); + conditions.add(getTestCaseOwnerCondition()); conditions.add(getIncidentAssigneeCondition()); conditions.add(getIncidentDomainCondition()); conditions.add(getIncidentDateRangeCondition()); @@ -469,12 +470,30 @@ private String getTestDefinitionCondition() { return result; } - // The incident grouping query (TestCaseResolutionStatusRepository#listIncidentGroups) ranks - // test_case_resolution_status_time_series records per stateId in a CTE aliased {@code i} - // (rn = 1 is the incident's latest record; createdAt/updatedAt are its first/last record - // timestamps) and joins test_case as {@code tc}. The incident* query params below are only set - // by TestCaseResolutionStatusResource#listIncidentGroups, mirroring how originEntityFQN pairs - // with the join added by TestCaseResolutionStatusTimeSeriesDAO#addOriginEntityFQNJoin. + // Scopes the test_case_resolution_status_time_series listing to the test cases directly owned + // by a user or team (owners inherited from the table are resolved at read time and are not + // visible to SQL); testCaseOwnerId is only set by TestCaseResolutionStatusResource#list. + private String getTestCaseOwnerCondition() { + String testCaseOwnerId = queryParams.get("testCaseOwnerId"); + String result = ""; + if (!nullOrEmpty(testCaseOwnerId)) { + result = + String.format( + "entityFQNHash IN (SELECT tcotc.fqnHash FROM test_case tcotc " + + "INNER JOIN entity_relationship tcoer ON tcoer.toId = tcotc.id " + + "WHERE tcoer.fromId = :testCaseOwnerId AND tcoer.fromEntity IN ('%s', '%s') " + + "AND tcoer.toEntity = '%s' AND tcoer.relation = %d)", + Entity.USER, Entity.TEAM, Entity.TEST_CASE, Relationship.OWNS.ordinal()); + } + return result; + } + + // The incident grouping query (TestCaseResolutionStatusRepository#listIncidentGroups) reduces + // test_case_resolution_status_time_series records to one latest row per stateId in a CTE + // aliased {@code i} (createdAt/updatedAt are the chain's first/last record timestamps) and + // joins test_case as {@code tc}. The incident* query params below are only set by + // TestCaseResolutionStatusResource (incidentAssignee also by the flat list, where it compares + // the record's assignee column — the generic "assignee" param belongs to the task listing). private String getIncidentAssigneeCondition() { String assignee = queryParams.get("incidentAssignee"); return nullOrEmpty(assignee) ? "" : "assignee = :incidentAssignee"; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java index f024ac7aafd9..1c8a553aaadb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java @@ -1,5 +1,6 @@ package org.openmetadata.service.jdbi3; +import static org.openmetadata.common.utils.CommonUtil.listOrEmpty; import static org.openmetadata.common.utils.CommonUtil.nullOrEmpty; import static org.openmetadata.schema.type.EventType.ENTITY_UPDATED; import static org.openmetadata.service.Entity.INGESTION_BOT_NAME; @@ -14,6 +15,8 @@ import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -27,6 +30,7 @@ import org.openmetadata.schema.tests.TestCase; import org.openmetadata.schema.tests.type.Assigned; import org.openmetadata.schema.tests.type.IncidentGroupBy; +import org.openmetadata.schema.tests.type.IncidentTrendDirection; import org.openmetadata.schema.tests.type.Metric; import org.openmetadata.schema.tests.type.Resolved; import org.openmetadata.schema.tests.type.Severity; @@ -63,6 +67,7 @@ public class TestCaseResolutionStatusRepository public static final String INCIDENT_DATE_FIELD_UPDATED_AT = "updatedAt"; public static final String INCIDENT_SORT_TYPE_ASC = "asc"; public static final String INCIDENT_SORT_TYPE_DESC = "desc"; + private static final int TREND_BUCKET_COUNT = 8; public TestCaseResolutionStatusRepository() { super( @@ -444,7 +449,8 @@ public void inferIncidentSeverity(TestCaseResolutionStatus incident) { incident.setSeverity(severity); } - protected static UUID getOrCreateIncident(TestCase testCase, String updatedBy) { + protected static UUID getOrCreateIncident( + TestCase testCase, String updatedBy, String failureReason) { TaskRepository taskRepository = (TaskRepository) Entity.getEntityRepository(Entity.TASK); Task existing = @@ -456,10 +462,11 @@ protected static UUID getOrCreateIncident(TestCase testCase, String updatedBy) { return existing.getId(); } - return createIncidentTask(testCase, updatedBy); + return createIncidentTask(testCase, updatedBy, failureReason); } - private static UUID createIncidentTask(TestCase testCase, String updatedBy) { + private static UUID createIncidentTask( + TestCase testCase, String updatedBy, String failureReason) { TaskRepository taskRepository = (TaskRepository) Entity.getEntityRepository(Entity.TASK); TestCase fullTestCase = @@ -482,7 +489,10 @@ private static UUID createIncidentTask(TestCase testCase, String updatedBy) { .withType(TaskEntityType.TestCaseResolution) .withStatus(TaskEntityStatus.Open) .withAbout(fullTestCase.getEntityReference()) - .withPayload(new TestCaseResolutionPayload().withTestCaseResolutionStatusId(taskId)) + .withPayload( + new TestCaseResolutionPayload() + .withTestCaseResolutionStatusId(taskId) + .withFailureReason(failureReason)) .withCreatedBy(updatedByRef) .withAssignees(assignees) .withCreatedAt(System.currentTimeMillis()) @@ -653,7 +663,12 @@ public ResultList listIncidentGroups( CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO.IncidentGroupPage page = dao.listIncidentGroups(groupBy, filter, incidentGroupSortOrder(sortType), limit, offsetInt); List groups = - page.counts().stream().map(count -> toIncidentGroup(groupBy, count)).toList(); + page.counts().stream() + .map( + count -> + toIncidentGroup( + groupBy, count, page.createdAtByGroupKey().get(count.groupKey()))) + .toList(); return new ResultList<>( groups, getBeforeOffset(offsetInt, limit), @@ -673,9 +688,24 @@ private static String incidentGroupSortOrder(String sortType) { } private static TestCaseIncidentGroup toIncidentGroup( - IncidentGroupBy groupBy, CollectionDAO.TestCaseIncidentGroupCount count) { + IncidentGroupBy groupBy, + CollectionDAO.TestCaseIncidentGroupCount count, + List incidentCreatedAt) { TestCaseIncidentGroup group = - new TestCaseIncidentGroup().withGroupBy(groupBy).withIncidentCount(count.incidentCount()); + new TestCaseIncidentGroup() + .withGroupBy(groupBy) + .withIncidentCount(count.incidentCount()) + .withStatus(statusFromRank(count.statusRank())) + .withAssigneeCount(count.assigneeCount()) + .withFirstSeen(count.firstSeen()) + .withLastSeen(count.lastSeen()); + if (count.severity() != null) { + group.withSeverity(Severity.fromValue(count.severity())); + } + if (!nullOrEmpty(count.assignees())) { + group.withAssignees(List.of(count.assignees().split(","))); + } + setIncidentTrend(group, incidentCreatedAt); EntityReference reference = resolveIncidentGroupEntity(count); if (reference != null) { group @@ -689,6 +719,50 @@ private static TestCaseIncidentGroup toIncidentGroup( return group; } + private static TestCaseResolutionStatusTypes statusFromRank(int statusRank) { + return switch (statusRank) { + case 1 -> TestCaseResolutionStatusTypes.Assigned; + case 2 -> TestCaseResolutionStatusTypes.Ack; + default -> TestCaseResolutionStatusTypes.New; + }; + } + + private static void setIncidentTrend(TestCaseIncidentGroup group, List incidentCreatedAt) { + List timestamps = listOrEmpty(incidentCreatedAt); + if (!timestamps.isEmpty()) { + long min = Collections.min(timestamps); + long max = Collections.max(timestamps); + List buckets = bucketIncidentCreatedAt(timestamps, min, max); + group.withTrend(buckets).withTrendDirection(trendDirection(buckets, max > min)); + } + } + + private static List bucketIncidentCreatedAt(List timestamps, long min, long max) { + int[] buckets = new int[TREND_BUCKET_COUNT]; + long span = max - min; + for (long timestamp : timestamps) { + int bucket = span == 0 ? 0 : (int) ((timestamp - min) * TREND_BUCKET_COUNT / span); + buckets[Math.min(bucket, TREND_BUCKET_COUNT - 1)]++; + } + return Arrays.stream(buckets).boxed().toList(); + } + + private static IncidentTrendDirection trendDirection(List buckets, boolean hasSpan) { + IncidentTrendDirection result = IncidentTrendDirection.Steady; + if (hasSpan) { + int half = TREND_BUCKET_COUNT / 2; + int firstHalf = buckets.subList(0, half).stream().mapToInt(Integer::intValue).sum(); + int lastHalf = + buckets.subList(half, TREND_BUCKET_COUNT).stream().mapToInt(Integer::intValue).sum(); + if (lastHalf > firstHalf) { + result = IncidentTrendDirection.Rising; + } else if (lastHalf < firstHalf) { + result = IncidentTrendDirection.Falling; + } + } + return result; + } + private static EntityReference resolveIncidentGroupEntity( CollectionDAO.TestCaseIncidentGroupCount count) { EntityReference result = null; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResultRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResultRepository.java index 67a870193c0c..37c1fec2055c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResultRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResultRepository.java @@ -267,7 +267,8 @@ private void setTestCaseResultIncidentId( TestCaseResult testCaseResult, TestCase testCase, String updatedBy) { if (TestCaseStatus.Failed.equals(testCaseResult.getTestCaseStatus())) { UUID incidentStateId = - TestCaseResolutionStatusRepository.getOrCreateIncident(testCase, updatedBy); + TestCaseResolutionStatusRepository.getOrCreateIncident( + testCase, updatedBy, testCaseResult.getResult()); testCaseResult.setIncidentId(incidentStateId); } else { testCaseResult.setIncidentId(null); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusMapper.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusMapper.java index 72628ae6c72c..2b51f2bdf725 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusMapper.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusMapper.java @@ -4,6 +4,7 @@ import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.tests.TestCase; import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.service.Entity; import org.openmetadata.service.mapper.EntityTimeSeriesMapper; @@ -17,13 +18,19 @@ public TestCaseResolutionStatus createToEntity( Entity.getEntityByName(Entity.TEST_CASE, create.getTestCaseReference(), null, Include.ALL); User userEntity = Entity.getEntityByName(Entity.USER, user, null, Include.ALL); + return createToEntity(create, userEntity.getEntityReference(), testCaseEntity); + } + + /** Variant for bulk callers that have already resolved the test case and the caller. */ + public TestCaseResolutionStatus createToEntity( + CreateTestCaseResolutionStatus create, EntityReference updatedBy, TestCase testCase) { return new TestCaseResolutionStatus() .withTimestamp(System.currentTimeMillis()) .withTestCaseResolutionStatusType(create.getTestCaseResolutionStatusType()) .withTestCaseResolutionStatusDetails(create.getTestCaseResolutionStatusDetails()) - .withUpdatedBy(userEntity.getEntityReference()) + .withUpdatedBy(updatedBy) .withUpdatedAt(System.currentTimeMillis()) - .withTestCaseReference(testCaseEntity.getEntityReference()) + .withTestCaseReference(testCase.getEntityReference()) .withSeverity(create.getSeverity()); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java index 26ea0b708e6e..dc564a53f670 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java @@ -21,6 +21,7 @@ import jakarta.ws.rs.GET; import jakarta.ws.rs.PATCH; import jakarta.ws.rs.POST; +import jakarta.ws.rs.PUT; import jakarta.ws.rs.Path; import jakarta.ws.rs.PathParam; import jakarta.ws.rs.Produces; @@ -32,7 +33,9 @@ import jakarta.ws.rs.core.UriInfo; import java.io.IOException; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.UUID; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -44,12 +47,18 @@ import org.openmetadata.schema.tests.type.TestCaseIncidentGroup; import org.openmetadata.schema.tests.type.TestCaseResolutionStatus; import org.openmetadata.schema.tests.type.TestCaseResolutionStatusTypes; +import org.openmetadata.schema.type.ApiStatus; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.MetadataOperation; +import org.openmetadata.schema.type.api.BulkOperationResult; +import org.openmetadata.schema.type.api.BulkResponse; import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.CatalogExceptionMessage; +import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.ListFilter; +import org.openmetadata.service.jdbi3.TestCaseRepository; import org.openmetadata.service.jdbi3.TestCaseResolutionStatusRepository; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.resources.EntityTimeSeriesResource; @@ -57,6 +66,7 @@ import org.openmetadata.service.search.SearchListFilter; import org.openmetadata.service.search.SearchSortFilter; import org.openmetadata.service.security.AuthRequest; +import org.openmetadata.service.security.AuthorizationException; import org.openmetadata.service.security.AuthorizationLogic; import org.openmetadata.service.security.Authorizer; import org.openmetadata.service.security.policyevaluator.OperationContext; @@ -78,6 +88,8 @@ public class TestCaseResolutionStatusResource extends EntityTimeSeriesResource { public static final String COLLECTION_PATH = "/v1/dataQuality/testCases/testCaseIncidentStatus"; + private static final int MAX_BULK_CREATE_SIZE = 100; + private static final String MAX_BULK_CREATE_SIZE_TEXT = "100"; private final TestCaseResolutionStatusMapper mapper = new TestCaseResolutionStatusMapper(); public TestCaseResolutionStatusResource(Authorizer authorizer) { @@ -173,7 +185,13 @@ public ResultList list( "Filter incidents by the test definition of their test case, by name or fully qualified name", schema = @Schema(type = "String")) @QueryParam("testDefinition") - String testDefinition) { + String testDefinition, + @Parameter( + description = + "Filter incidents by a direct owner (user or team name) of their test case", + schema = @Schema(type = "String")) + @QueryParam("owner") + String owner) { ResourceContextInterface testCaseResourceContext = getTestCaseResourceContext(testCaseFQN); ResourceContextInterface entityResourceContext = buildEntityResourceContext(testCaseFQN, testCaseId, originEntityFQN); @@ -184,7 +202,9 @@ public ResultList list( ListFilter filter = new ListFilter(include); filter.addQueryParam("testCaseResolutionStatusType", testCaseResolutionStatusType); - filter.addQueryParam("assignee", assignee); + // "incidentAssignee" compares the record's assignee column; the generic "assignee" param is + // owned by the task listing and would hash-match ASSIGNED_TO relationships instead. + filter.addQueryParam("incidentAssignee", assignee); filter.addQueryParam("entityFQNHash", FullyQualifiedName.buildHash(testCaseFQN)); filter.addQueryParam("originEntityFQN", originEntityFQN); filter.addQueryParam("domain", domain); @@ -192,6 +212,10 @@ public ResultList list( if (testDefinitionId != null) { filter.addQueryParam("testDefinitionId", testDefinitionId.toString()); } + UUID testCaseOwnerId = resolveOwnerFilterId(owner); + if (testCaseOwnerId != null) { + filter.addQueryParam("testCaseOwnerId", testCaseOwnerId.toString()); + } return repository.list(offset, startTs, endTs, limitParam, filter, latest); } @@ -436,6 +460,135 @@ public Response create( testCaseResolutionStatus.getTestCaseReference().getFullyQualifiedName()); } + @PUT + @Path("/bulk") + @Operation( + operationId = "bulkCreateTestCaseResolutionStatus", + summary = "Bulk create test case failure statuses", + description = + "Create a new failure status for multiple test case incidents in one operation — e.g. " + + "assigning or resolving a selection of incidents at once, up to a limit of " + + MAX_BULK_CREATE_SIZE_TEXT + + " per request. Each entry is validated and authorized exactly like a single " + + "create; the BulkOperationResult reports per-entry success or failure.", + responses = { + @ApiResponse( + responseCode = "200", + description = "Bulk operation results", + content = + @Content( + mediaType = "application/json", + schema = @Schema(implementation = BulkOperationResult.class))) + }) + public Response bulkCreate( + @Context UriInfo uriInfo, + @Context SecurityContext securityContext, + @Valid List createRequests) { + if (listOrEmpty(createRequests).size() > MAX_BULK_CREATE_SIZE) { + throw new IllegalArgumentException( + String.format( + "Bulk request size %d exceeds the maximum of %d entries", + createRequests.size(), MAX_BULK_CREATE_SIZE)); + } + Map testCasesByFqn = prefetchTestCases(createRequests); + EntityReference updatedBy = + Entity.getEntityReferenceByName( + Entity.USER, securityContext.getUserPrincipal().getName(), Include.ALL); + List successes = new ArrayList<>(); + List failures = new ArrayList<>(); + for (CreateTestCaseResolutionStatus createRequest : listOrEmpty(createRequests)) { + processBulkEntry( + securityContext, + createRequest, + testCasesByFqn.get(createRequest.getTestCaseReference()), + updatedBy, + successes, + failures); + } + return Response.ok(buildBulkResult(listOrEmpty(createRequests).size(), successes, failures)) + .build(); + } + + // Resolves every referenced test case in one query so the per-entry loop never has to fetch; + // entries whose FQN is absent from the map fail individually with a not-found message. + private static Map prefetchTestCases( + List createRequests) { + List fqns = + listOrEmpty(createRequests).stream() + .map(CreateTestCaseResolutionStatus::getTestCaseReference) + .filter(fqn -> !nullOrEmpty(fqn)) + .distinct() + .toList(); + Map result = new HashMap<>(); + if (!fqns.isEmpty()) { + TestCaseRepository testCaseRepository = + (TestCaseRepository) Entity.getEntityRepository(Entity.TEST_CASE); + for (TestCase testCase : testCaseRepository.getDao().findEntityByNames(fqns, Include.ALL)) { + result.put(testCase.getFullyQualifiedName(), testCase); + } + } + return result; + } + + private void processBulkEntry( + SecurityContext securityContext, + CreateTestCaseResolutionStatus createRequest, + TestCase testCase, + EntityReference updatedBy, + List successes, + List failures) { + try { + if (testCase == null) { + throw new EntityNotFoundException( + CatalogExceptionMessage.entityNotFound( + Entity.TEST_CASE, createRequest.getTestCaseReference())); + } + MessageParser.EntityLink entityLink = + MessageParser.EntityLink.parse(testCase.getEntityLink()); + ResourceContextInterface testCaseResourceContext = + TestCaseResourceContext.builder().name(testCase.getFullyQualifiedName()).build(); + ResourceContextInterface entityResourceContext = + TestCaseResourceContext.builder().entityLink(entityLink).build(); + authorizer.authorizeRequests( + securityContext, + buildEditAuthRequests(testCaseResourceContext, entityResourceContext), + AuthorizationLogic.ANY); + + TestCaseResolutionStatus status = mapper.createToEntity(createRequest, updatedBy, testCase); + repository.createNewRecord(status, testCase.getFullyQualifiedName()); + successes.add(new BulkResponse().withRequest(createRequest)); + } catch (AuthorizationException e) { + failures.add( + new BulkResponse() + .withRequest(createRequest) + .withMessage("Permission denied: " + e.getMessage()) + .withStatus(Response.Status.FORBIDDEN.getStatusCode())); + } catch (Exception e) { + failures.add( + new BulkResponse() + .withRequest(createRequest) + .withMessage(e.getMessage()) + .withStatus(Response.Status.BAD_REQUEST.getStatusCode())); + } + } + + private static BulkOperationResult buildBulkResult( + int processed, List successes, List failures) { + ApiStatus status = ApiStatus.SUCCESS; + if (successes.isEmpty() && !failures.isEmpty()) { + status = ApiStatus.FAILURE; + } else if (!failures.isEmpty()) { + status = ApiStatus.PARTIAL_SUCCESS; + } + return new BulkOperationResult() + .withStatus(status) + .withNumberOfRowsProcessed(processed) + .withNumberOfRowsPassed(successes.size()) + .withNumberOfRowsFailed(failures.size()) + .withSuccessRequest(successes) + .withFailedRequest(failures); + } + @PATCH @Path("/{id}") @Operation( @@ -748,6 +901,18 @@ private static UUID resolveFilterEntityId(String entityType, String name) { return entityId; } + private static UUID resolveOwnerFilterId(String owner) { + UUID result = null; + if (!nullOrEmpty(owner)) { + try { + result = resolveFilterEntityId(Entity.USER, owner); + } catch (EntityNotFoundException e) { + result = resolveFilterEntityId(Entity.TEAM, owner); + } + } + return result; + } + protected static ResourceContextInterface buildEntityResourceContext( String testCaseFQN, UUID testCaseId, String originEntityFQN) { if (testCaseFQN != null) { diff --git a/openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json b/openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json index aa7a24592831..345a36f7070f 100644 --- a/openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json +++ b/openmetadata-spec/src/main/resources/json/schema/tests/testCaseIncidentGroup.json @@ -16,6 +16,17 @@ {"name": "TestDefinition"}, {"name": "Owner"} ] + }, + "incidentTrendDirection": { + "description": "Direction of the group's incident-creation trend, comparing the second half of the `trend` buckets against the first half.", + "javaType": "org.openmetadata.schema.tests.type.IncidentTrendDirection", + "type": "string", + "enum": ["Rising", "Falling", "Steady"], + "javaEnums": [ + {"name": "Rising"}, + {"name": "Falling"}, + {"name": "Steady"} + ] } }, "properties": { @@ -42,6 +53,44 @@ "incidentCount": { "description": "Number of distinct open incidents in the group.", "type": "integer" + }, + "severity": { + "description": "Most critical severity across the group's open incidents (Severity1 is the most critical). Absent when no incident in the group has a severity.", + "$ref": "./testCaseResolutionStatus.json#/definitions/severities" + }, + "status": { + "description": "Most actionable current status across the group's open incidents, in the order Assigned > Ack > New.", + "$ref": "./testCaseResolutionStatus.json#/definitions/testCaseResolutionStatusTypes" + }, + "assignees": { + "description": "Distinct names of the current assignees of the group's open incidents.", + "type": "array", + "items": { + "type": "string" + } + }, + "assigneeCount": { + "description": "Number of distinct current assignees across the group's open incidents.", + "type": "integer" + }, + "firstSeen": { + "description": "Timestamp at which the earliest open incident in the group was opened.", + "$ref": "../type/basic.json#/definitions/timestamp" + }, + "lastSeen": { + "description": "Timestamp of the most recent status change across the group's open incidents.", + "$ref": "../type/basic.json#/definitions/timestamp" + }, + "trend": { + "description": "Number of incidents opened in each of 8 equal time buckets spanning `firstSeen` to `lastSeen`.", + "type": "array", + "items": { + "type": "integer" + } + }, + "trendDirection": { + "description": "Direction of the incident-creation trend for the group.", + "$ref": "#/definitions/incidentTrendDirection" } }, "required": ["groupBy", "name", "incidentCount"], diff --git a/openmetadata-spec/src/main/resources/json/schema/tests/testCaseResolutionStatus.json b/openmetadata-spec/src/main/resources/json/schema/tests/testCaseResolutionStatus.json index e3e929861f41..f4349ce256b5 100644 --- a/openmetadata-spec/src/main/resources/json/schema/tests/testCaseResolutionStatus.json +++ b/openmetadata-spec/src/main/resources/json/schema/tests/testCaseResolutionStatus.json @@ -89,6 +89,10 @@ "description": "Severity failure for the test associated with the resolution.", "$ref": "#/definitions/severities" }, + "failureSummary": { + "description": "Human-readable summary of the test failure that opened the incident, denormalized from the failed test case result so incident listings do not need a per-incident result lookup.", + "type": "string" + }, "metrics": { "description": "List of metrics associated with the test case resolution.", "type": "array", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts index 062b8773e040..d19899d76a97 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts @@ -14,10 +14,22 @@ * Aggregated count of open test case incidents for a given grouping dimension. */ export interface TestCaseIncidentGroup { + /** + * Number of distinct current assignees across the group's open incidents. + */ + assigneeCount?: number; + /** + * Distinct names of the current assignees of the group's open incidents. + */ + assignees?: string[]; /** * Display name of the entity the group represents. */ displayName?: string; + /** + * Timestamp at which the earliest open incident in the group was opened. + */ + firstSeen?: number; /** * Fully qualified name of the entity the group represents. */ @@ -34,10 +46,33 @@ export interface TestCaseIncidentGroup { * Number of distinct open incidents in the group. */ incidentCount: number; + /** + * Timestamp of the most recent status change across the group's open incidents. + */ + lastSeen?: number; /** * Name of the entity the group represents. */ name: string; + /** + * Most critical severity across the group's open incidents (Severity1 is the most + * critical). Absent when no incident in the group has a severity. + */ + severity?: Severities; + /** + * Most actionable current status across the group's open incidents, in the order Assigned + * > Ack > New. + */ + status?: TestCaseResolutionStatusTypes; + /** + * Number of incidents opened in each of 8 equal time buckets spanning `firstSeen` to + * `lastSeen`. + */ + trend?: number[]; + /** + * Direction of the incident-creation trend for the group. + */ + trendDirection?: IncidentTrendDirection; } /** @@ -50,3 +85,42 @@ export enum IncidentGroupBy { Table = "table", TestDefinition = "testDefinition", } + +/** + * Most critical severity across the group's open incidents (Severity1 is the most + * critical). Absent when no incident in the group has a severity. + * + * Test case resolution status type. + */ +export enum Severities { + Severity1 = "Severity1", + Severity2 = "Severity2", + Severity3 = "Severity3", + Severity4 = "Severity4", + Severity5 = "Severity5", +} + +/** + * Most actionable current status across the group's open incidents, in the order Assigned + * > Ack > New. + * + * Test case resolution status type. + */ +export enum TestCaseResolutionStatusTypes { + Ack = "Ack", + Assigned = "Assigned", + New = "New", + Resolved = "Resolved", +} + +/** + * Direction of the incident-creation trend for the group. + * + * Direction of the group's incident-creation trend, comparing the second half of the + * `trend` buckets against the first half. + */ +export enum IncidentTrendDirection { + Falling = "Falling", + Rising = "Rising", + Steady = "Steady", +} diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts index 6036fc02e524..d8c5c3ec04be 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts @@ -14,6 +14,12 @@ * Schema to capture test case resolution status. */ export interface TestCaseResolutionStatus { + /** + * Human-readable summary of the test failure that opened the incident, denormalized from + * the failed test case result so incident listings do not need a per-incident result + * lookup. + */ + failureSummary?: string; /** * Unique identifier of this failure instance */ From ed67f290e6fdd33ce6d289b414df2b9f79a1bca3 Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Wed, 22 Jul 2026 16:53:35 -0700 Subject: [PATCH 03/13] feat: added owner, status, assignee, severiuty and bucket for client metrics --- PR_DESCRIPTION.md | 99 +++++++++++++++++++ .../mysql/postDataMigrationSQLScript.sql | 16 --- .../native/2.0.0/mysql/schemaChanges.sql | 13 --- .../postgres/postDataMigrationSQLScript.sql | 16 --- .../native/2.0.0/postgres/schemaChanges.sql | 13 --- .../mysql/postDataMigrationSQLScript.sql | 16 +++ .../native/2.1.0/mysql/schemaChanges.sql | 18 ++++ .../postgres/postDataMigrationSQLScript.sql | 16 +++ .../native/2.1.0/postgres/schemaChanges.sql | 18 ++++ docker/mysql/Dockerfile_mysql | 2 +- .../service/jdbi3/CollectionDAO.java | 68 +++---------- .../TestCaseResolutionStatusRepository.java | 13 ++- 12 files changed, 190 insertions(+), 118 deletions(-) create mode 100644 PR_DESCRIPTION.md create mode 100644 bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql create mode 100644 bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql create mode 100644 bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql create mode 100644 bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql diff --git a/PR_DESCRIPTION.md b/PR_DESCRIPTION.md new file mode 100644 index 000000000000..1c53a3f2871b --- /dev/null +++ b/PR_DESCRIPTION.md @@ -0,0 +1,99 @@ + + +### 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: +- [x] 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: a new 2.1.0 native migration adds 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 +- [x] 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.0.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: +- [x] I have read the [**CONTRIBUTING**](https://docs.open-metadata.org/developers/contribute) document. +- [x] My PR title is `Fixes : ` +- [x] My PR is linked to a GitHub issue via `Fixes #` above. +- [x] I have commented on my code, particularly in hard-to-understand areas. +- [x] 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.) +- [x] I have added tests (unit / integration / Playwright as applicable) and listed them above. + + +- [x] 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.) +- [x] I have added tests around the new logic. diff --git a/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql index fa8fac174e1e..9ae0da0bca66 100644 --- a/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql @@ -260,19 +260,3 @@ SET json = JSON_REMOVE(json, '$.appConfiguration.moduleConfiguration.dataQuality WHERE extension LIKE 'app.version.%' AND json->>'$.name' = 'DataInsightsApplication' AND JSON_EXTRACT(json, '$.appConfiguration.moduleConfiguration.dataQuality') IS NOT NULL; - --- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support -UPDATE policy_entity -SET json = JSON_ARRAY_APPEND( - json, - '$.rules', - JSON_OBJECT( - 'name', 'AutoClassificationBotRule-Allow-Topic', - 'description', 'Allow adding tags and sample data to the topics', - 'resources', JSON_ARRAY('Topic'), - 'operations', JSON_ARRAY('EditAll', 'ViewAll'), - 'effect', 'allow' - ) -) -WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = 'AutoClassificationBotPolicy' - AND NOT JSON_CONTAINS(json, JSON_OBJECT('name', 'AutoClassificationBotRule-Allow-Topic'), '$.rules'); diff --git a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql index 3d9ef43467bd..33a8ac0c0821 100644 --- a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql @@ -537,16 +537,3 @@ SET json = JSON_INSERT( WHERE serviceType = 'DatabricksPipeline' AND JSON_EXTRACT(json, '$.connection.config.token') IS NOT NULL AND NOT JSON_CONTAINS_PATH(json, 'one', '$.connection.config.authType'); - --- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp); - --- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list --- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all --- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp); - --- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, --- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and --- id-based lookups fall back to full scans. -ALTER TABLE test_case ADD INDEX idx_test_case_id (id); diff --git a/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql index 1945ca65fe3b..57d135529ed3 100644 --- a/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql @@ -256,19 +256,3 @@ SET json = jsonb_set( WHERE extension LIKE 'app.version.%' AND json::jsonb ->> 'name' = 'DataInsightsApplication' AND jsonb_exists(json::jsonb #> '{appConfiguration,moduleConfiguration}', 'dataQuality'); - --- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support -UPDATE policy_entity -SET json = jsonb_set( - json::jsonb, - '{rules}', - (json->'rules') || jsonb_build_object( - 'name', 'AutoClassificationBotRule-Allow-Topic', - 'description', 'Allow adding tags and sample data to the topics', - 'resources', jsonb_build_array('Topic'), - 'operations', jsonb_build_array('EditAll', 'ViewAll'), - 'effect', 'allow' - ) -) -WHERE json->>'name' = 'AutoClassificationBotPolicy' - AND NOT (json->'rules') @> jsonb_build_array(jsonb_build_object('name', 'AutoClassificationBotRule-Allow-Topic')); diff --git a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql index 8e1f7300950a..e8cbc760d2b5 100644 --- a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql @@ -460,16 +460,3 @@ SET json = jsonb_set( WHERE serviceType = 'DatabricksPipeline' AND json #> '{connection,config,token}' IS NOT NULL AND NOT jsonb_exists(json #> '{connection,config}', 'authType'); - --- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) -CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_state_id ON test_case_resolution_status_time_series (stateId, timestamp); - --- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list --- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all --- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. -CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_fqn_ts ON test_case_resolution_status_time_series (entityFQNHash, timestamp); - --- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, --- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and --- id-based lookups fall back to full scans. -CREATE INDEX IF NOT EXISTS idx_test_case_id ON test_case (id); diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql new file mode 100644 index 000000000000..4ff2f1d8b411 --- /dev/null +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql @@ -0,0 +1,16 @@ + +-- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support +UPDATE policy_entity +SET json = JSON_ARRAY_APPEND( + json, + '$.rules', + JSON_OBJECT( + 'name', 'AutoClassificationBotRule-Allow-Topic', + 'description', 'Allow adding tags and sample data to the topics', + 'resources', JSON_ARRAY('Topic'), + 'operations', JSON_ARRAY('EditAll', 'ViewAll'), + 'effect', 'allow' + ) +) +WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = 'AutoClassificationBotPolicy' + AND NOT JSON_CONTAINS(json, JSON_OBJECT('name', 'AutoClassificationBotRule-Allow-Topic'), '$.rules'); diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql new file mode 100644 index 000000000000..ebc179f82adc --- /dev/null +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql @@ -0,0 +1,18 @@ +-- Incident Manager grouped incidents - OpenMetadata 2.1.0 + +-- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp); + +-- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list +-- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all +-- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp); + +-- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, +-- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and +-- id-based lookups fall back to full scans. +ALTER TABLE test_case ADD INDEX idx_test_case_id (id); + +-- The incident list's assignee filter compares the generated assignee column, which had no +-- index and full-scanned the timeline at scale. +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_assignee (assignee, timestamp); diff --git a/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql new file mode 100644 index 000000000000..633bdf75f944 --- /dev/null +++ b/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql @@ -0,0 +1,16 @@ + +-- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support +UPDATE policy_entity +SET json = jsonb_set( + json::jsonb, + '{rules}', + (json->'rules') || jsonb_build_object( + 'name', 'AutoClassificationBotRule-Allow-Topic', + 'description', 'Allow adding tags and sample data to the topics', + 'resources', jsonb_build_array('Topic'), + 'operations', jsonb_build_array('EditAll', 'ViewAll'), + 'effect', 'allow' + ) +) +WHERE json->>'name' = 'AutoClassificationBotPolicy' + AND NOT (json->'rules') @> jsonb_build_array(jsonb_build_object('name', 'AutoClassificationBotRule-Allow-Topic')); diff --git a/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql new file mode 100644 index 000000000000..81d4b78e78cc --- /dev/null +++ b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql @@ -0,0 +1,18 @@ +-- Incident Manager grouped incidents - OpenMetadata 2.1.0 + +-- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) +CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_state_id ON test_case_resolution_status_time_series (stateId, timestamp); + +-- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list +-- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all +-- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. +CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_fqn_ts ON test_case_resolution_status_time_series (entityFQNHash, timestamp); + +-- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, +-- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and +-- id-based lookups fall back to full scans. +CREATE INDEX IF NOT EXISTS idx_test_case_id ON test_case (id); + +-- The incident list's assignee filter compares the generated assignee column, which had no +-- index and full-scanned the timeline at scale. +CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_assignee ON test_case_resolution_status_time_series (assignee, timestamp); diff --git a/docker/mysql/Dockerfile_mysql b/docker/mysql/Dockerfile_mysql index f2fee8fca08a..8efdfab3fcf2 100644 --- a/docker/mysql/Dockerfile_mysql +++ b/docker/mysql/Dockerfile_mysql @@ -1,4 +1,4 @@ -FROM mysql/mysql-server:latest +FROM mysql:8.0 WORKDIR /docker-entrypoint-initdb.d COPY docker/mysql/mysql-script.sql . RUN chmod -R 775 /docker-entrypoint-initdb.d \ No newline at end of file diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index a6f25732dd3f..c66c313adcdf 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -10516,6 +10516,7 @@ SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateI COUNT(DISTINCT i.assignee) AS assigneeCount, MIN(i.createdAt) AS firstSeen, MAX(i.updatedAt) AS lastSeen, + AS incidentCreatedAt, COUNT(*) OVER () AS totalGroups FROM incident i INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash @@ -10530,6 +10531,7 @@ List listIncidentGroups( @Define("incidentCond") String incidentCond, @Define("severityExpr") String severityExpr, @Define("assigneesExpr") String assigneesExpr, + @Define("createdAtAgg") String createdAtAgg, @Define("groupKey") String groupKey, @Define("groupType") String groupType, @Define("groupByCols") String groupByCols, @@ -10557,26 +10559,6 @@ int countIncidentGroups( @Define("cond") String cond, @BindMap Map params); - @SqlQuery( - INCIDENT_GROUPS_CTE - + """ - SELECT AS groupKey, i.createdAt AS createdAt - FROM incident i - INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash - - AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE - AND IN () - """) - @RegisterRowMapper(IncidentGroupCreatedAtMapper.class) - List listIncidentGroupCreatedAt( - @Define("incidentCond") String incidentCond, - @Define("severityExpr") String severityExpr, - @Define("groupKey") String groupKey, - @Define("dimensionJoin") String dimensionJoin, - @Define("cond") String cond, - @BindMap Map params, - @BindList("groupKeys") List groupKeys); - // if originEntityFQN is present, we need to join with test_case table static String addOriginEntityFQNJoin(ListFilter filter, String condition) { String result = condition; @@ -10601,6 +10583,7 @@ default IncidentGroupPage listIncidentGroups( sqlParts.scopeCondition(), severityExpr(), assigneesExpr(), + createdAtAggExpr(), dimension.groupKey(), dimension.groupType(), dimension.groupByCols(), @@ -10627,28 +10610,7 @@ default IncidentGroupPage listIncidentGroups( sqlParts.condition(), sqlParts.params()); } - return new IncidentGroupPage(counts, total, fetchIncidentCreatedAt(sqlParts, counts)); - } - - private Map> fetchIncidentCreatedAt( - IncidentGroupSqlParts sqlParts, List counts) { - Map> result = new HashMap<>(); - if (!counts.isEmpty()) { - List groupKeys = counts.stream().map(TestCaseIncidentGroupCount::groupKey).toList(); - List rows = - listIncidentGroupCreatedAt( - sqlParts.scopeCondition(), - severityExpr(), - sqlParts.dimension().groupKey(), - sqlParts.dimension().join(), - sqlParts.condition(), - sqlParts.params(), - groupKeys); - for (IncidentGroupCreatedAt row : rows) { - result.computeIfAbsent(row.groupKey(), key -> new ArrayList<>()).add(row.createdAt()); - } - } - return result; + return new IncidentGroupPage(counts, total); } private static String severityExpr() { @@ -10663,6 +10625,12 @@ private static String assigneesExpr() { : "STRING_AGG(DISTINCT i.assignee, ',')"; } + private static String createdAtAggExpr() { + return Boolean.TRUE.equals(DatasourceConfig.getInstance().isMySQL()) + ? "JSON_ARRAYAGG(i.createdAt)" + : "JSON_AGG(i.createdAt)"; + } + private static IncidentGroupSqlParts buildIncidentGroupSqlParts( IncidentGroupBy groupBy, ListFilter filter) { Map params = new HashMap<>(); @@ -10689,10 +10657,7 @@ private static String buildIncidentGroupScopeCondition( return result; } - record IncidentGroupPage( - List counts, - int total, - Map> createdAtByGroupKey) {} + record IncidentGroupPage(List counts, int total) {} record IncidentGroupSqlParts( String scopeCondition, @@ -10748,6 +10713,7 @@ record TestCaseIncidentGroupCount( int assigneeCount, long firstSeen, long lastSeen, + String incidentCreatedAt, int totalGroups) {} class TestCaseIncidentGroupCountMapper implements RowMapper { @@ -10763,19 +10729,11 @@ public TestCaseIncidentGroupCount map(ResultSet rs, StatementContext ctx) throws rs.getInt("assigneeCount"), rs.getLong("firstSeen"), rs.getLong("lastSeen"), + rs.getString("incidentCreatedAt"), rs.getInt("totalGroups")); } } - record IncidentGroupCreatedAt(String groupKey, long createdAt) {} - - class IncidentGroupCreatedAtMapper implements RowMapper { - @Override - public IncidentGroupCreatedAt map(ResultSet rs, StatementContext ctx) throws SQLException { - return new IncidentGroupCreatedAt(rs.getString("groupKey"), rs.getLong("createdAt")); - } - } - interface TestCaseResultTimeSeriesDAO extends EntityTimeSeriesDAO { @Override default String getTimeSeriesTableName() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java index cc0281ee1b65..7eb02fa6d765 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java @@ -686,10 +686,7 @@ public ResultList listIncidentGroups( dao.listIncidentGroups(groupBy, filter, incidentGroupSortOrder(sortType), limit, offsetInt); List groups = page.counts().stream() - .map( - count -> - toIncidentGroup( - groupBy, count, page.createdAtByGroupKey().get(count.groupKey()))) + .map(count -> toIncidentGroup(groupBy, count, parseIncidentCreatedAt(count))) .toList(); return new ResultList<>( groups, @@ -741,6 +738,14 @@ private static TestCaseIncidentGroup toIncidentGroup( return group; } + private static List parseIncidentCreatedAt(CollectionDAO.TestCaseIncidentGroupCount count) { + List result = List.of(); + if (!nullOrEmpty(count.incidentCreatedAt())) { + result = Arrays.asList(JsonUtils.readValue(count.incidentCreatedAt(), Long[].class)); + } + return result; + } + private static TestCaseResolutionStatusTypes statusFromRank(int statusRank) { return switch (statusRank) { case 1 -> TestCaseResolutionStatusTypes.Assigned; From 1f2bdac73075c56edf7ab06bac76b2b647cc55eb Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Wed, 22 Jul 2026 16:56:15 -0700 Subject: [PATCH 04/13] empty commit for CI trigger From 8e2aba18905a57dd011fc077704d40ca20fe79ce Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Thu, 23 Jul 2026 10:27:12 -0700 Subject: [PATCH 05/13] feat: remove n+1 in entity ref. retrieval when resolving group references --- .../native/2.1.0/mysql/schemaChanges.sql | 71 ++++++- .../it/tests/IncidentGroupsIT.java | 197 +++++++++++++++++- .../service/jdbi3/CollectionDAO.java | 29 ++- .../TestCaseResolutionStatusRepository.java | 102 ++++++--- .../TestCaseResolutionStatusResource.java | 4 +- 5 files changed, 362 insertions(+), 41 deletions(-) diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql index ebc179f82adc..0f8ba8b0a3b8 100644 --- a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql @@ -1,18 +1,81 @@ -- Incident Manager grouped incidents - OpenMetadata 2.1.0 +-- MySQL has no `ADD INDEX IF NOT EXISTS`, and environments that ran pre-release builds may +-- already carry these indexes, so each ADD INDEX is guarded via information_schema (mirrors +-- the approvedById guard in 2.0.0). -- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp); +SET @ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'test_case_resolution_status_time_series' + AND index_name = 'idx_test_case_resolution_status_state_id' + ), + 'SELECT 1', + 'ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp)' + ) +); +PREPARE stmt FROM @ddl; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; -- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list -- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all -- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp); +SET @ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'test_case_resolution_status_time_series' + AND index_name = 'idx_test_case_resolution_status_fqn_ts' + ), + 'SELECT 1', + 'ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp)' + ) +); +PREPARE stmt FROM @ddl; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; -- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, -- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and -- id-based lookups fall back to full scans. -ALTER TABLE test_case ADD INDEX idx_test_case_id (id); +SET @ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'test_case' + AND index_name = 'idx_test_case_id' + ), + 'SELECT 1', + 'ALTER TABLE test_case ADD INDEX idx_test_case_id (id)' + ) +); +PREPARE stmt FROM @ddl; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; -- The incident list's assignee filter compares the generated assignee column, which had no -- index and full-scanned the timeline at scale. -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_assignee (assignee, timestamp); +SET @ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.statistics + WHERE table_schema = DATABASE() + AND table_name = 'test_case_resolution_status_time_series' + AND index_name = 'idx_test_case_resolution_status_assignee' + ), + 'SELECT 1', + 'ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_assignee (assignee, timestamp)' + ) +); +PREPARE stmt FROM @ddl; +EXECUTE stmt; +DEALLOCATE PREPARE stmt; diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java index 29ba66dc4f0b..ad66f99d1b73 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java @@ -8,7 +8,11 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import io.dropwizard.db.DataSourceFactory; import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.PreparedStatement; import java.time.Duration; import java.util.ArrayList; import java.util.Base64; @@ -18,11 +22,13 @@ import java.util.Map; import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.openmetadata.it.bootstrap.SharedEntities; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; import org.openmetadata.it.util.SdkClients; import org.openmetadata.schema.api.data.CreateDatabase; import org.openmetadata.schema.api.data.CreateDatabaseSchema; @@ -61,6 +67,7 @@ import org.openmetadata.sdk.exceptions.OpenMetadataException; import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.models.ListResponse; +import org.openmetadata.service.util.FullyQualifiedName; /** * Integration tests for GET /v1/dataQuality/testCases/testCaseIncidentStatus/incidentGroups. @@ -84,7 +91,7 @@ public class IncidentGroupsIT { private static final String GROUP_BY_TABLE = "table"; private static final String GROUP_BY_TEST_DEFINITION = "testDefinition"; private static final String GROUP_BY_OWNER = "owner"; - private static final String MAX_LIMIT = "1000000"; + private static final String MAX_LIMIT = "1000"; private OpenMetadataClient client; private Table tableA; @@ -747,6 +754,194 @@ void testDbListAssigneeFilter() throws Exception { "latest-per-test-case filtering must also honor the assignee"); } + // Pins the invariant that a status transition never loses the denormalized failure reason: + // the latest record after a bulk Ack must still carry the summary captured when the failed + // result opened the incident (whether stamped from the task payload or inherited from the + // chain's prior record in storeInternal/syncFromTask). + @Test + void testBulkTransitionPreservesFailureSummary() throws Exception { + long ts = System.currentTimeMillis(); + String failureText = "Bulk chain summary " + ts; + Table summaryTable = createTable(schemaFqn, "incident_groups_bulk_summary_" + ts); + TestDefinition summaryDefinition = + createTestDefinition( + "incident_groups_bulk_summary_def_" + ts, TestDefinitionEntityType.TABLE); + TestCase summaryCase = + createTestCase( + "incident_groups_bulk_summary_case_" + ts, + tableLink(summaryTable), + summaryDefinition, + List.of()); + client + .testCaseResults() + .create( + summaryCase.getFullyQualifiedName(), + new CreateTestCaseResult() + .withTimestamp(System.currentTimeMillis()) + .withTestCaseStatus(TestCaseStatus.Failed) + .withResult(failureText)); + await() + .atMost(Duration.ofSeconds(30)) + .untilAsserted( + () -> + assertFalse( + fetchStatuses(summaryCase).isEmpty(), + "the failed result must open an incident")); + + BulkOperationResult result = + client + .testCaseResolutionStatuses() + .bulkCreate( + List.of( + new CreateTestCaseResolutionStatus() + .withTestCaseReference(summaryCase.getFullyQualifiedName()) + .withTestCaseResolutionStatusType(TestCaseResolutionStatusTypes.Ack))); + assertEquals(ApiStatus.SUCCESS, result.getStatus()); + + await() + .atMost(Duration.ofSeconds(30)) + .untilAsserted( + () -> { + TestCaseResolutionStatus latest = fetchStatuses(summaryCase).getFirst(); + assertEquals( + TestCaseResolutionStatusTypes.Ack, latest.getTestCaseResolutionStatusType()); + assertEquals( + failureText, + latest.getFailureSummary(), + "the status transition must not lose the denormalized failure reason"); + }); + } + + // The public API cannot produce two records with an identical timestamp (storeInternal forces + // per-FQN monotonicity), so the tie shape is seeded straight into the suite's database and + // asserted through the API — pinning the MAX(id) tie-breaker in the incident CTE. Without it, + // both tied records enter the aggregates: two assignees and a double-counted trend point for a + // single incident. + @Test + void testDuplicateMaxTimestampTieBreak() throws Exception { + long ts = System.currentTimeMillis(); + Table tieTable = createTable(schemaFqn, "incident_groups_tie_" + ts); + TestDefinition tieDefinition = + createTestDefinition("incident_groups_tie_def_" + ts, TestDefinitionEntityType.TABLE); + TestCase tieCase = + createTestCase( + "incident_groups_tie_case_" + ts, tableLink(tieTable), tieDefinition, List.of()); + + String stateId = UUID.randomUUID().toString(); + long tieTimestamp = ts - 3_600_000; + insertStatusRecords( + tieCase, + List.of( + seededRecord(stateId, tieTimestamp - 60_000, TestCaseResolutionStatusTypes.New, null), + seededRecord( + stateId, + tieTimestamp, + TestCaseResolutionStatusTypes.Assigned, + "incident_groups_tie_assignee_a_" + ts), + seededRecord( + stateId, + tieTimestamp, + TestCaseResolutionStatusTypes.Assigned, + "incident_groups_tie_assignee_b_" + ts))); + + Map params = groupParams(GROUP_BY_TABLE); + params.put("testCaseFQN", tieCase.getFullyQualifiedName()); + TestCaseIncidentGroup group = findGroup(fetchGroups(params), tieTable.getFullyQualifiedName()); + + assertEquals(1, group.getIncidentCount()); + assertEquals( + 1, group.getAssigneeCount(), "only the tie-broken latest record's assignee may count"); + assertEquals(1, group.getAssignees().size()); + assertEquals( + 1, + group.getTrend().stream().mapToInt(Integer::intValue).sum(), + "the tied incident must enter the trend exactly once"); + } + + // 60 distinct assignee names exceed GROUP_CONCAT's default 1024-char cap; the JSON aggregate + // must deliver every name complete. Seeded via the database for speed and determinism. + @Test + void testAssigneeDenseGroupIsNotTruncated() throws Exception { + long ts = System.currentTimeMillis(); + Table denseTable = createTable(schemaFqn, "incident_groups_dense_" + ts); + TestDefinition denseDefinition = + createTestDefinition("incident_groups_dense_def_" + ts, TestDefinitionEntityType.TABLE); + TestCase denseCase = + createTestCase( + "incident_groups_dense_case_" + ts, tableLink(denseTable), denseDefinition, List.of()); + + List records = new ArrayList<>(); + for (int i = 0; i < 60; i++) { + String stateId = UUID.randomUUID().toString(); + long chainStart = ts - (i + 2) * 3_600_000L; + records.add(seededRecord(stateId, chainStart, TestCaseResolutionStatusTypes.New, null)); + records.add( + seededRecord( + stateId, + chainStart + 60_000, + TestCaseResolutionStatusTypes.Assigned, + String.format("incident_groups_dense_assignee_number_%02d_%d", i, ts))); + } + insertStatusRecords(denseCase, records); + + Map params = groupParams(GROUP_BY_TABLE); + params.put("testCaseFQN", denseCase.getFullyQualifiedName()); + TestCaseIncidentGroup group = + findGroup(fetchGroups(params), denseTable.getFullyQualifiedName()); + + assertEquals(60, group.getIncidentCount()); + assertEquals(60, group.getAssigneeCount()); + assertEquals(60, group.getAssignees().size(), "no aggregation cap may drop assignees"); + assertTrue( + group.getAssignees().stream() + .allMatch(name -> name.matches("incident_groups_dense_assignee_number_\\d{2}_\\d+")), + "every assignee name must arrive complete, never truncated mid-name"); + } + + private TestCaseResolutionStatus seededRecord( + String stateId, long timestamp, TestCaseResolutionStatusTypes type, String assigneeName) { + TestCaseResolutionStatus record = + new TestCaseResolutionStatus() + .withId(UUID.randomUUID()) + .withStateId(UUID.fromString(stateId)) + .withTimestamp(timestamp) + .withUpdatedAt(timestamp) + .withTestCaseResolutionStatusType(type); + if (assigneeName != null) { + record.withTestCaseResolutionStatusDetails( + new Assigned() + .withAssignee( + new EntityReference() + .withId(UUID.randomUUID()) + .withType("user") + .withName(assigneeName))); + } + return record; + } + + private void insertStatusRecords(TestCase testCase, List records) + throws Exception { + DataSourceFactory dataSource = + TestSuiteBootstrap.createApplicationConfigCopy().getDataSourceFactory(); + boolean postgres = dataSource.getUrl().contains("postgresql"); + String insert = + "INSERT INTO test_case_resolution_status_time_series (entityFQNHash, jsonSchema, json) " + + (postgres ? "VALUES (?, ?, ?::jsonb)" : "VALUES (?, ?, ?)"); + String fqnHash = FullyQualifiedName.buildHash(testCase.getFullyQualifiedName()); + try (Connection connection = + DriverManager.getConnection( + dataSource.getUrl(), dataSource.getUser(), dataSource.getPassword()); + PreparedStatement statement = connection.prepareStatement(insert)) { + for (TestCaseResolutionStatus record : records) { + statement.setString(1, fqnHash); + statement.setString(2, "testCaseResolutionStatus"); + statement.setString(3, JsonUtils.pojoToJson(record)); + statement.addBatch(); + } + statement.executeBatch(); + } + } + @Test void testResolvedStatusRejected() { Map params = groupParams(GROUP_BY_TABLE); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index 7be13aa9b862..8fd95a30117f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -10499,10 +10499,12 @@ default int listCount(ListFilter filter) { int deleteOrphanedRecords(@Bind("limit") int limit); // An incident is a stateId chain. `chain` folds each stateId to its first/last timestamps - // over the (stateId, timestamp) index and `incident` joins back on the last timestamp to - // pick the chain's latest record, which carries the current status/assignee/severity. This - // replaces ROW_NUMBER/MIN/MAX window functions, which materialized three buffered passes - // over the whole table at scale. + // over the (stateId, timestamp) index, `latestRecord` picks exactly one record per chain at + // the last timestamp — MAX(id) is an arbitrary but deterministic tie-breaker, without which + // two records sharing the chain's max timestamp would both enter the aggregates (stale + // assignees, double-counted trend points) — and `incident` loads that record's current + // status/assignee/severity. This replaces ROW_NUMBER/MIN/MAX window functions, which + // materialized three buffered passes over the whole table at scale. String INCIDENT_GROUPS_CTE = """ WITH chain AS ( @@ -10511,12 +10513,18 @@ SELECT stateId, MIN(timestamp) AS createdAt, MAX(timestamp) AS updatedAt GROUP BY stateId ), - incident AS ( - SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, - AS severity, c.createdAt, c.updatedAt + latestRecord AS ( + SELECT c.stateId, c.createdAt, c.updatedAt, MAX(t.id) AS latestId FROM chain c INNER JOIN test_case_resolution_status_time_series t ON t.stateId = c.stateId AND t.timestamp = c.updatedAt + GROUP BY c.stateId, c.createdAt, c.updatedAt + ), + incident AS ( + SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, + AS severity, l.createdAt, l.updatedAt + FROM latestRecord l + INNER JOIN test_case_resolution_status_time_series t ON t.id = l.latestId ) """; @@ -10633,10 +10641,13 @@ private static String severityExpr() { : "json ->> 'severity'"; } + // JSON aggregates instead of GROUP_CONCAT/STRING_AGG: the 1024-char group_concat_max_len + // default would truncate an assignee-dense group mid-name. MySQL's JSON_ARRAYAGG cannot take + // DISTINCT, so the array may carry nulls and duplicates — the repository dedupes on parse. private static String assigneesExpr() { return Boolean.TRUE.equals(DatasourceConfig.getInstance().isMySQL()) - ? "GROUP_CONCAT(DISTINCT i.assignee)" - : "STRING_AGG(DISTINCT i.assignee, ',')"; + ? "JSON_ARRAYAGG(i.assignee)" + : "JSON_AGG(i.assignee)"; } private static String createdAtAggExpr() { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java index 1de50b1df3d4..7058d0de76ed 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java @@ -17,10 +17,12 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.stream.Collectors; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import org.jdbi.v3.sqlobject.transaction.Transaction; @@ -236,19 +238,29 @@ public void storeInternal( // If there is an unresolved incident update the state ID recordEntity.setStateId(lastIncident.getStateId()); // If the last incident had a severity assigned and the incoming incident does not, inherit - // the old severity + // the old severity; same for the denormalized failure summary so the chain's latest record + // never loses the failure reason on a status transition. recordEntity.setSeverity( recordEntity.getSeverity() == null ? lastIncident.getSeverity() : recordEntity.getSeverity()); + recordEntity.setFailureSummary( + recordEntity.getFailureSummary() == null + ? lastIncident.getFailureSummary() + : recordEntity.getFailureSummary()); } else if (lastIncident != null && isReopeningStatus(recordEntity)) { - // Ack/Assigned/Resolved after a Resolved incident reopens it: reuse the stateId and severity - // so the timeline stays contiguous. New is excluded — a new failure starts a fresh incident. + // Ack/Assigned/Resolved after a Resolved incident reopens it: reuse the stateId, severity, + // and failure summary so the timeline stays contiguous. New is excluded — a new failure + // starts a fresh incident. recordEntity.setStateId(lastIncident.getStateId()); recordEntity.setSeverity( recordEntity.getSeverity() == null ? lastIncident.getSeverity() : recordEntity.getSeverity()); + recordEntity.setFailureSummary( + recordEntity.getFailureSummary() == null + ? lastIncident.getFailureSummary() + : recordEntity.getFailureSummary()); } setResolutionMetrics(lastIncident, recordEntity); @@ -672,12 +684,20 @@ public void syncFromTask(TestCaseResolutionStatus recordEntity, String recordFQN recordEntity.setUpdatedAt(incomingTimestamp); } - // Inherit severity from the previous record for this stateId if the caller didn't set one - if (recordEntity.getSeverity() == null && recordEntity.getStateId() != null) { + // Inherit severity and failure summary from the previous record for this stateId if the + // caller didn't set them (e.g. tasks created before the payload carried a failure reason) + if ((recordEntity.getSeverity() == null || recordEntity.getFailureSummary() == null) + && recordEntity.getStateId() != null) { TestCaseResolutionStatus priorForStateId = getLatestRecordForStateId(recordEntity.getStateId()); - if (priorForStateId != null && priorForStateId.getSeverity() != null) { - recordEntity.setSeverity(priorForStateId.getSeverity()); + if (priorForStateId != null) { + if (recordEntity.getSeverity() == null && priorForStateId.getSeverity() != null) { + recordEntity.setSeverity(priorForStateId.getSeverity()); + } + if (recordEntity.getFailureSummary() == null + && priorForStateId.getFailureSummary() != null) { + recordEntity.setFailureSummary(priorForStateId.getFailureSummary()); + } } } @@ -727,9 +747,16 @@ public ResultList listIncidentGroups( (CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO) timeSeriesDao; CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO.IncidentGroupPage page = dao.listIncidentGroups(groupBy, filter, incidentGroupSortOrder(sortType), limit, offsetInt); + Map references = resolveIncidentGroupEntities(page.counts()); List groups = page.counts().stream() - .map(count -> toIncidentGroup(groupBy, count, parseIncidentCreatedAt(count))) + .map( + count -> + toIncidentGroup( + groupBy, + count, + parseIncidentCreatedAt(count), + references.get(count.groupKey()))) .toList(); return new ResultList<>( groups, @@ -752,7 +779,8 @@ private static String incidentGroupSortOrder(String sortType) { private static TestCaseIncidentGroup toIncidentGroup( IncidentGroupBy groupBy, CollectionDAO.TestCaseIncidentGroupCount count, - List incidentCreatedAt) { + List incidentCreatedAt, + EntityReference reference) { TestCaseIncidentGroup group = new TestCaseIncidentGroup() .withGroupBy(groupBy) @@ -764,11 +792,11 @@ private static TestCaseIncidentGroup toIncidentGroup( if (count.severity() != null) { group.withSeverity(Severity.fromValue(count.severity())); } - if (!nullOrEmpty(count.assignees())) { - group.withAssignees(List.of(count.assignees().split(","))); + List assignees = parseAssignees(count.assignees()); + if (!assignees.isEmpty()) { + group.withAssignees(assignees); } setIncidentTrend(group, incidentCreatedAt); - EntityReference reference = resolveIncidentGroupEntity(count); if (reference != null) { group .withId(reference.getId()) @@ -781,6 +809,18 @@ private static TestCaseIncidentGroup toIncidentGroup( return group; } + private static List parseAssignees(String assigneesJson) { + List result = List.of(); + if (!nullOrEmpty(assigneesJson)) { + result = + Arrays.stream(JsonUtils.readValue(assigneesJson, String[].class)) + .filter(assignee -> !nullOrEmpty(assignee)) + .distinct() + .toList(); + } + return result; + } + private static List parseIncidentCreatedAt(CollectionDAO.TestCaseIncidentGroupCount count) { List result = List.of(); if (!nullOrEmpty(count.incidentCreatedAt())) { @@ -833,19 +873,31 @@ private static IncidentTrendDirection trendDirection(List buckets, bool return result; } - private static EntityReference resolveIncidentGroupEntity( - CollectionDAO.TestCaseIncidentGroupCount count) { - EntityReference result = null; - try { - result = - Entity.TABLE.equals(count.groupType()) - ? Entity.getEntityReferenceByName(Entity.TABLE, count.groupKey(), Include.ALL) - : Entity.getEntityReferenceById( - count.groupType(), UUID.fromString(count.groupKey()), Include.ALL); - } catch (EntityNotFoundException e) { - LOG.debug( - "Incident group {} '{}' could not be resolved", count.groupType(), count.groupKey()); - } + private static Map resolveIncidentGroupEntities( + List counts) { + Map result = new HashMap<>(); + Map> keysByType = + counts.stream() + .collect( + Collectors.groupingBy( + CollectionDAO.TestCaseIncidentGroupCount::groupType, + Collectors.mapping( + CollectionDAO.TestCaseIncidentGroupCount::groupKey, Collectors.toList()))); + keysByType.forEach( + (groupType, groupKeys) -> { + EntityDAO entityDAO = Entity.getEntityRepository(groupType).getDao(); + if (Entity.TABLE.equals(groupType)) { + for (EntityReference reference : + entityDAO.findReferencesByFqns(groupKeys, Include.ALL)) { + result.put(reference.getFullyQualifiedName(), reference); + } + } else { + List ids = groupKeys.stream().map(UUID::fromString).toList(); + for (EntityReference reference : entityDAO.findReferencesByIds(ids, Include.ALL)) { + result.put(reference.getId().toString(), reference); + } + } + }); return result; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java index dc564a53f670..20c2d4006e04 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java @@ -287,11 +287,11 @@ public ResultList listIncidentGroups( @Parameter(description = "Filter incidents by domain", schema = @Schema(type = "String")) @QueryParam("domain") String domain, - @Parameter(description = "Limit the number of groups returned. (1 to 1000000, default = 10)") + @Parameter(description = "Limit the number of groups returned. (1 to 1000, default = 10)") @DefaultValue("10") @QueryParam("limit") @Min(value = 0, message = "must be greater than or equal to 0") - @Max(value = 1000000, message = "must be less than or equal to 1000000") + @Max(value = 1000, message = "must be less than or equal to 1000") int limit, @Parameter( description = From c84239c24164189e09b5ce56ec11ae08de40dcb5 Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Thu, 23 Jul 2026 11:07:40 -0700 Subject: [PATCH 06/13] feat: ignore optional argumewnt static check error --- .../src/metadata/ingestion/source/database/sample_data.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ingestion/src/metadata/ingestion/source/database/sample_data.py b/ingestion/src/metadata/ingestion/source/database/sample_data.py index 6d4e1a53b912..259cc6187483 100644 --- a/ingestion/src/metadata/ingestion/source/database/sample_data.py +++ b/ingestion/src/metadata/ingestion/source/database/sample_data.py @@ -2391,7 +2391,7 @@ def _get_test_case_owners(self, test_case: dict) -> EntityReferenceList | None: for owner_name in test_case.get("owners", []): user: User | None = self.metadata.get_by_name(User, fqn=owner_name) if user: - owners.append(EntityReference(id=user.id.root, type="user")) + owners.append(EntityReference(id=user.id.root, type="user")) # pyright: ignore[reportCallIssue] return EntityReferenceList(owners) if owners else None def ingest_test_case(self) -> Iterable[Either[OMetaTestCaseSample]]: @@ -2486,10 +2486,10 @@ def ingest_test_case_results(self) -> Iterable[Either[OMetaTestCaseResultsSample ], minBound=result.get("minBound"), maxBound=result.get("maxBound"), - ), + ), # pyright: ignore[reportCallIssue] test_case_name=case.fullyQualifiedName.root, ) - yield Either(right=test_case_result_req) + yield Either(right=test_case_result_req, left=None) if test_case_results.get("failedRowsSample"): self.metadata.ingest_failed_rows_sample( case, From 2a7063dc926766e6591832a981364b5879ca1cee Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Thu, 23 Jul 2026 13:18:04 -0700 Subject: [PATCH 07/13] feat: address comments and fix failing integration tests --- .../it/tests/IncidentPaginationIT.java | 55 +++++++++++++++---- .../generated/tests/testCaseIncidentGroup.ts | 10 ++-- .../tests/testCaseResolutionStatus.ts | 3 +- 3 files changed, 49 insertions(+), 19 deletions(-) diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentPaginationIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentPaginationIT.java index e27f9edd7c60..494731e072a0 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentPaginationIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentPaginationIT.java @@ -50,6 +50,7 @@ public class IncidentPaginationIT { private OpenMetadataClient client; private List testCases; private String databaseSchemaFqn; + private String tableFqn; @BeforeAll public void setup() throws Exception { @@ -74,6 +75,7 @@ public void setup() throws Exception { .getFullyQualifiedName(); Table table = createTestTable(); + tableFqn = table.getFullyQualifiedName(); String testDefFqn = client .testDefinitions() @@ -153,7 +155,12 @@ private void recreateIncidentStatuses() { @Test public void testPaginationFirstPage() throws Exception { - ListParams params = new ListParams().withLimit(PAGE_SIZE).withOffset(0).withLatest(true); + ListParams params = + new ListParams() + .withLimit(PAGE_SIZE) + .withOffset(0) + .withLatest(true) + .addFilter("originEntityFQN", tableFqn); ListResponse response = client.testCaseResolutionStatuses().searchList(params); @@ -161,20 +168,29 @@ public void testPaginationFirstPage() throws Exception { assertNotNull(response); assertEquals( PAGE_SIZE, response.getData().size(), "First page should return " + PAGE_SIZE + " results"); - assertTrue( - response.getPaging().getTotal() >= TEST_DATA_SIZE, - "Total should be at least " + TEST_DATA_SIZE); + assertEquals( + TEST_DATA_SIZE, + response.getPaging().getTotal(), + "Scoped total must be exactly the fixture size"); } @Test public void testPaginationSecondPage() throws Exception { ListParams firstPageParams = - new ListParams().withLimit(PAGE_SIZE).withOffset(0).withLatest(true); + new ListParams() + .withLimit(PAGE_SIZE) + .withOffset(0) + .withLatest(true) + .addFilter("originEntityFQN", tableFqn); ListResponse firstPage = client.testCaseResolutionStatuses().searchList(firstPageParams); ListParams secondPageParams = - new ListParams().withLimit(PAGE_SIZE).withOffset(PAGE_SIZE).withLatest(true); + new ListParams() + .withLimit(PAGE_SIZE) + .withOffset(PAGE_SIZE) + .withLatest(true) + .addFilter("originEntityFQN", tableFqn); ListResponse secondPage = client.testCaseResolutionStatuses().searchList(secondPageParams); @@ -197,21 +213,31 @@ public void testPaginationSecondPage() throws Exception { @Test public void testPaginationLastPage() throws Exception { - ListParams params = new ListParams().withLimit(PAGE_SIZE).withOffset(0).withLatest(true); + ListParams params = + new ListParams() + .withLimit(PAGE_SIZE) + .withOffset(0) + .withLatest(true) + .addFilter("originEntityFQN", tableFqn); ListResponse firstPage = client.testCaseResolutionStatuses().searchList(params); int total = firstPage.getPaging().getTotal(); int lastPageOffset = ((total - 1) / PAGE_SIZE) * PAGE_SIZE; ListParams lastPageParams = - new ListParams().withLimit(PAGE_SIZE).withOffset(lastPageOffset).withLatest(true); + new ListParams() + .withLimit(PAGE_SIZE) + .withOffset(lastPageOffset) + .withLatest(true) + .addFilter("originEntityFQN", tableFqn); ListResponse lastPage = client.testCaseResolutionStatuses().searchList(lastPageParams); assertNotNull(lastPage); - assertTrue( - lastPage.getData().size() > 0 && lastPage.getData().size() <= PAGE_SIZE, - "Last page should have between 1 and " + PAGE_SIZE + " results"); + assertEquals( + total - lastPageOffset, + lastPage.getData().size(), + "Scoped last page must hold exactly the remainder of the fixture"); } @Test @@ -229,7 +255,12 @@ public void testBackwardsCompatibilityNoParams() throws Exception { @Test public void testOffsetBeyondResults() throws Exception { - ListParams params = new ListParams().withLimit(PAGE_SIZE).withOffset(10000).withLatest(true); + ListParams params = + new ListParams() + .withLimit(PAGE_SIZE) + .withOffset(10000) + .withLatest(true) + .addFilter("originEntityFQN", tableFqn); ListResponse response = client.testCaseResolutionStatuses().searchList(params); diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts index d19899d76a97..abd8d55eee02 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseIncidentGroup.ts @@ -60,8 +60,8 @@ export interface TestCaseIncidentGroup { */ severity?: Severities; /** - * Most actionable current status across the group's open incidents, in the order Assigned - * > Ack > New. + * Most actionable current status across the group's open incidents, in the order Assigned > + * Ack > New. */ status?: TestCaseResolutionStatusTypes; /** @@ -101,13 +101,13 @@ export enum Severities { } /** - * Most actionable current status across the group's open incidents, in the order Assigned - * > Ack > New. + * Most actionable current status across the group's open incidents, in the order Assigned > + * Ack > New. * * Test case resolution status type. */ export enum TestCaseResolutionStatusTypes { - Ack = "Ack", + ACK = "Ack", Assigned = "Assigned", New = "New", Resolved = "Resolved", diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts index d8c5c3ec04be..6727cf471931 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCaseResolutionStatus.ts @@ -16,8 +16,7 @@ export interface TestCaseResolutionStatus { /** * Human-readable summary of the test failure that opened the incident, denormalized from - * the failed test case result so incident listings do not need a per-incident result - * lookup. + * the failed test case result so incident listings do not need a per-incident result lookup. */ failureSummary?: string; /** From 3d3d047dc321a0ba1741d3931594ec15e4f4fe7f Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Thu, 23 Jul 2026 13:26:07 -0700 Subject: [PATCH 08/13] feat: revert pre existing migrations to 2.0 --- .../2.0.0/mysql/postDataMigrationSQLScript.sql | 16 ++++++++++++++++ .../postgres/postDataMigrationSQLScript.sql | 16 ++++++++++++++++ .../2.1.0/mysql/postDataMigrationSQLScript.sql | 16 ---------------- .../postgres/postDataMigrationSQLScript.sql | 16 ---------------- 4 files changed, 32 insertions(+), 32 deletions(-) delete mode 100644 bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql delete mode 100644 bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql diff --git a/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql index 9ae0da0bca66..fa8fac174e1e 100644 --- a/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.0.0/mysql/postDataMigrationSQLScript.sql @@ -260,3 +260,19 @@ SET json = JSON_REMOVE(json, '$.appConfiguration.moduleConfiguration.dataQuality WHERE extension LIKE 'app.version.%' AND json->>'$.name' = 'DataInsightsApplication' AND JSON_EXTRACT(json, '$.appConfiguration.moduleConfiguration.dataQuality') IS NOT NULL; + +-- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support +UPDATE policy_entity +SET json = JSON_ARRAY_APPEND( + json, + '$.rules', + JSON_OBJECT( + 'name', 'AutoClassificationBotRule-Allow-Topic', + 'description', 'Allow adding tags and sample data to the topics', + 'resources', JSON_ARRAY('Topic'), + 'operations', JSON_ARRAY('EditAll', 'ViewAll'), + 'effect', 'allow' + ) +) +WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = 'AutoClassificationBotPolicy' + AND NOT JSON_CONTAINS(json, JSON_OBJECT('name', 'AutoClassificationBotRule-Allow-Topic'), '$.rules'); diff --git a/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql index 57d135529ed3..1945ca65fe3b 100644 --- a/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql +++ b/bootstrap/sql/migrations/native/2.0.0/postgres/postDataMigrationSQLScript.sql @@ -256,3 +256,19 @@ SET json = jsonb_set( WHERE extension LIKE 'app.version.%' AND json::jsonb ->> 'name' = 'DataInsightsApplication' AND jsonb_exists(json::jsonb #> '{appConfiguration,moduleConfiguration}', 'dataQuality'); + +-- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support +UPDATE policy_entity +SET json = jsonb_set( + json::jsonb, + '{rules}', + (json->'rules') || jsonb_build_object( + 'name', 'AutoClassificationBotRule-Allow-Topic', + 'description', 'Allow adding tags and sample data to the topics', + 'resources', jsonb_build_array('Topic'), + 'operations', jsonb_build_array('EditAll', 'ViewAll'), + 'effect', 'allow' + ) +) +WHERE json->>'name' = 'AutoClassificationBotPolicy' + AND NOT (json->'rules') @> jsonb_build_array(jsonb_build_object('name', 'AutoClassificationBotRule-Allow-Topic')); diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql deleted file mode 100644 index 4ff2f1d8b411..000000000000 --- a/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql +++ /dev/null @@ -1,16 +0,0 @@ - --- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support -UPDATE policy_entity -SET json = JSON_ARRAY_APPEND( - json, - '$.rules', - JSON_OBJECT( - 'name', 'AutoClassificationBotRule-Allow-Topic', - 'description', 'Allow adding tags and sample data to the topics', - 'resources', JSON_ARRAY('Topic'), - 'operations', JSON_ARRAY('EditAll', 'ViewAll'), - 'effect', 'allow' - ) -) -WHERE JSON_UNQUOTE(JSON_EXTRACT(json, '$.name')) = 'AutoClassificationBotPolicy' - AND NOT JSON_CONTAINS(json, JSON_OBJECT('name', 'AutoClassificationBotRule-Allow-Topic'), '$.rules'); diff --git a/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql deleted file mode 100644 index 633bdf75f944..000000000000 --- a/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql +++ /dev/null @@ -1,16 +0,0 @@ - --- Add Topic permissions to AutoClassificationBotPolicy for messaging auto-classification support -UPDATE policy_entity -SET json = jsonb_set( - json::jsonb, - '{rules}', - (json->'rules') || jsonb_build_object( - 'name', 'AutoClassificationBotRule-Allow-Topic', - 'description', 'Allow adding tags and sample data to the topics', - 'resources', jsonb_build_array('Topic'), - 'operations', jsonb_build_array('EditAll', 'ViewAll'), - 'effect', 'allow' - ) -) -WHERE json->>'name' = 'AutoClassificationBotPolicy' - AND NOT (json->'rules') @> jsonb_build_array(jsonb_build_object('name', 'AutoClassificationBotRule-Allow-Topic')); From 44e28bfce0c1195899837243e925712e4c76c443 Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Thu, 23 Jul 2026 13:47:57 -0700 Subject: [PATCH 09/13] feat: address first pass review --- .../java/org/openmetadata/service/jdbi3/CollectionDAO.java | 3 +-- .../resources/dqtests/TestCaseResolutionStatusResource.java | 4 ---- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index 8fd95a30117f..3245665cb6a4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -10503,8 +10503,7 @@ default int listCount(ListFilter filter) { // the last timestamp — MAX(id) is an arbitrary but deterministic tie-breaker, without which // two records sharing the chain's max timestamp would both enter the aggregates (stale // assignees, double-counted trend points) — and `incident` loads that record's current - // status/assignee/severity. This replaces ROW_NUMBER/MIN/MAX window functions, which - // materialized three buffered passes over the whole table at scale. + // status/assignee/severity. String INCIDENT_GROUPS_CTE = """ WITH chain AS ( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java index 20c2d4006e04..65597c505738 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/dqtests/TestCaseResolutionStatusResource.java @@ -202,8 +202,6 @@ public ResultList list( ListFilter filter = new ListFilter(include); filter.addQueryParam("testCaseResolutionStatusType", testCaseResolutionStatusType); - // "incidentAssignee" compares the record's assignee column; the generic "assignee" param is - // owned by the task listing and would hash-match ASSIGNED_TO relationships instead. filter.addQueryParam("incidentAssignee", assignee); filter.addQueryParam("entityFQNHash", FullyQualifiedName.buildHash(testCaseFQN)); filter.addQueryParam("originEntityFQN", originEntityFQN); @@ -509,8 +507,6 @@ public Response bulkCreate( .build(); } - // Resolves every referenced test case in one query so the per-entry loop never has to fetch; - // entries whose FQN is absent from the map fail individually with a not-found message. private static Map prefetchTestCases( List createRequests) { List fqns = From aa91e3f290e25f5135e8c6a8e95bdd86e069bcc9 Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Thu, 23 Jul 2026 21:42:29 -0700 Subject: [PATCH 10/13] feat: move endpoint data to summary table --- .../mysql/postDataMigrationSQLScript.sql | 28 +++ .../native/2.1.0/mysql/schemaChanges.sql | 19 ++ .../postgres/postDataMigrationSQLScript.sql | 28 +++ .../native/2.1.0/postgres/schemaChanges.sql | 19 ++ .../it/tests/IncidentGroupsIT.java | 40 ++++ .../service/jdbi3/CollectionDAO.java | 204 ++++++++---------- .../TestCaseResolutionStatusRepository.java | 38 +++- .../ui/src/generated/tests/testCase.ts | 5 + 8 files changed, 267 insertions(+), 114 deletions(-) create mode 100644 bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql create mode 100644 bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql new file mode 100644 index 000000000000..fab3d4b6b023 --- /dev/null +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/postDataMigrationSQLScript.sql @@ -0,0 +1,28 @@ +-- Backfill test_case_incident from existing history: fold each stateId chain to its +-- first/last timestamps, pick the latest record (MAX(id) tie-break, matching the read +-- query this table replaces), and upsert one summary row per incident. Idempotent. +INSERT INTO test_case_incident (stateId, entityFQNHash, testCaseResolutionStatusType, assignee, severity, createdAt, updatedAt, latestRecordId) +WITH chain AS ( + SELECT stateId, MIN(timestamp) AS createdAt, MAX(timestamp) AS updatedAt + FROM test_case_resolution_status_time_series + GROUP BY stateId +), +latestRecord AS ( + SELECT c.stateId, c.createdAt, c.updatedAt, MAX(t.id) AS latestId + FROM chain c + INNER JOIN test_case_resolution_status_time_series t + ON t.stateId = c.stateId AND t.timestamp = c.updatedAt + GROUP BY c.stateId, c.createdAt, c.updatedAt +) +SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, + JSON_UNQUOTE(JSON_EXTRACT(t.json, '$.severity')), l.createdAt, l.updatedAt, t.id +FROM latestRecord l +INNER JOIN test_case_resolution_status_time_series t ON t.id = l.latestId +WHERE t.entityFQNHash IS NOT NULL +ON DUPLICATE KEY UPDATE + testCaseResolutionStatusType = VALUES(testCaseResolutionStatusType), + assignee = VALUES(assignee), + severity = VALUES(severity), + test_case_incident.createdAt = LEAST(test_case_incident.createdAt, VALUES(createdAt)), + updatedAt = VALUES(updatedAt), + latestRecordId = VALUES(latestRecordId); diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql index 0f8ba8b0a3b8..9c54dfa91a20 100644 --- a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql @@ -79,3 +79,22 @@ SET @ddl = ( PREPARE stmt FROM @ddl; EXECUTE stmt; DEALLOCATE PREPARE stmt; + +-- Incident summary table: one row per incident (stateId chain), maintained at write time so +-- state-shaped reads (incidentGroups) are O(open incidents) instead of folding full history. +-- Column names deliberately mirror the time-series table so ListFilter conditions apply verbatim. +CREATE TABLE IF NOT EXISTS test_case_incident ( + stateId varchar(36) NOT NULL, + entityFQNHash varchar(768) CHARACTER SET ascii COLLATE ascii_bin NOT NULL, + testCaseResolutionStatusType varchar(36) NOT NULL, + assignee varchar(256) DEFAULT NULL, + severity varchar(36) DEFAULT NULL, + createdAt bigint unsigned NOT NULL, + updatedAt bigint unsigned NOT NULL, + latestRecordId varchar(36) NOT NULL, + PRIMARY KEY (stateId), + INDEX idx_tci_status_fqn (testCaseResolutionStatusType, entityFQNHash), + INDEX idx_tci_fqn (entityFQNHash), + INDEX idx_tci_assignee (assignee, testCaseResolutionStatusType), + INDEX idx_tci_updated (updatedAt) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; diff --git a/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql b/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql new file mode 100644 index 000000000000..541e4865b74e --- /dev/null +++ b/bootstrap/sql/migrations/native/2.1.0/postgres/postDataMigrationSQLScript.sql @@ -0,0 +1,28 @@ +-- Backfill test_case_incident from existing history: fold each stateId chain to its +-- first/last timestamps, pick the latest record (MAX(id) tie-break, matching the read +-- query this table replaces), and upsert one summary row per incident. Idempotent. +INSERT INTO test_case_incident (stateId, entityFQNHash, testCaseResolutionStatusType, assignee, severity, createdAt, updatedAt, latestRecordId) +WITH chain AS ( + SELECT stateId, MIN(timestamp) AS createdAt, MAX(timestamp) AS updatedAt + FROM test_case_resolution_status_time_series + GROUP BY stateId +), +latestRecord AS ( + SELECT c.stateId, c.createdAt, c.updatedAt, MAX(t.id) AS latestId + FROM chain c + INNER JOIN test_case_resolution_status_time_series t + ON t.stateId = c.stateId AND t.timestamp = c.updatedAt + GROUP BY c.stateId, c.createdAt, c.updatedAt +) +SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, + t.json ->> 'severity', l.createdAt, l.updatedAt, t.id +FROM latestRecord l +INNER JOIN test_case_resolution_status_time_series t ON t.id = l.latestId +WHERE t.entityFQNHash IS NOT NULL +ON CONFLICT (stateId) DO UPDATE SET + testCaseResolutionStatusType = EXCLUDED.testCaseResolutionStatusType, + assignee = EXCLUDED.assignee, + severity = EXCLUDED.severity, + createdAt = LEAST(test_case_incident.createdAt, EXCLUDED.createdAt), + updatedAt = EXCLUDED.updatedAt, + latestRecordId = EXCLUDED.latestRecordId; diff --git a/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql index 81d4b78e78cc..b2a7cba4663f 100644 --- a/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/postgres/schemaChanges.sql @@ -16,3 +16,22 @@ CREATE INDEX IF NOT EXISTS idx_test_case_id ON test_case (id); -- The incident list's assignee filter compares the generated assignee column, which had no -- index and full-scanned the timeline at scale. CREATE INDEX IF NOT EXISTS idx_test_case_resolution_status_assignee ON test_case_resolution_status_time_series (assignee, timestamp); + +-- Incident summary table: one row per incident (stateId chain), maintained at write time so +-- state-shaped reads (incidentGroups) are O(open incidents) instead of folding full history. +-- Column names deliberately mirror the time-series table so ListFilter conditions apply verbatim. +CREATE TABLE IF NOT EXISTS test_case_incident ( + stateId varchar(36) NOT NULL, + entityFQNHash varchar(768) NOT NULL, + testCaseResolutionStatusType varchar(36) NOT NULL, + assignee varchar(256) DEFAULT NULL, + severity varchar(36) DEFAULT NULL, + createdAt bigint NOT NULL, + updatedAt bigint NOT NULL, + latestRecordId varchar(36) NOT NULL, + PRIMARY KEY (stateId) +); +CREATE INDEX IF NOT EXISTS idx_tci_status_fqn ON test_case_incident (testCaseResolutionStatusType, entityFQNHash); +CREATE INDEX IF NOT EXISTS idx_tci_fqn ON test_case_incident (entityFQNHash); +CREATE INDEX IF NOT EXISTS idx_tci_assignee ON test_case_incident (assignee, testCaseResolutionStatusType); +CREATE INDEX IF NOT EXISTS idx_tci_updated ON test_case_incident (updatedAt); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java index ad66f99d1b73..d83be4edfd51 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java @@ -939,6 +939,46 @@ private void insertStatusRecords(TestCase testCase, List> 'severity'" : "JSON_UNQUOTE(JSON_EXTRACT(t.json, '$.severity'))"; + String upsertTail = + postgres + ? "ON CONFLICT (stateId) DO UPDATE SET " + + "testCaseResolutionStatusType = EXCLUDED.testCaseResolutionStatusType, " + + "assignee = EXCLUDED.assignee, severity = EXCLUDED.severity, " + + "createdAt = LEAST(test_case_incident.createdAt, EXCLUDED.createdAt), " + + "updatedAt = EXCLUDED.updatedAt, latestRecordId = EXCLUDED.latestRecordId" + : "ON DUPLICATE KEY UPDATE " + + "testCaseResolutionStatusType = VALUES(testCaseResolutionStatusType), " + + "assignee = VALUES(assignee), severity = VALUES(severity), " + + "test_case_incident.createdAt = LEAST(test_case_incident.createdAt, VALUES(createdAt)), " + + "updatedAt = VALUES(updatedAt), latestRecordId = VALUES(latestRecordId)"; + String backfill = + "INSERT INTO test_case_incident (stateId, entityFQNHash, testCaseResolutionStatusType, " + + "assignee, severity, createdAt, updatedAt, latestRecordId) " + + "WITH chain AS (SELECT stateId, MIN(timestamp) AS createdAt, MAX(timestamp) AS updatedAt " + + " FROM test_case_resolution_status_time_series WHERE entityFQNHash = ? GROUP BY stateId), " + + "latestRecord AS (SELECT c.stateId, c.createdAt, c.updatedAt, MAX(t.id) AS latestId " + + " FROM chain c INNER JOIN test_case_resolution_status_time_series t " + + " ON t.stateId = c.stateId AND t.timestamp = c.updatedAt " + + " GROUP BY c.stateId, c.createdAt, c.updatedAt) " + + "SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, " + + severityExpr + + ", l.createdAt, l.updatedAt, t.id " + + "FROM latestRecord l INNER JOIN test_case_resolution_status_time_series t ON t.id = l.latestId " + + upsertTail; + try (PreparedStatement statement = connection.prepareStatement(backfill)) { + statement.setString(1, fqnHash); + statement.executeUpdate(); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index 03c9adc3e41b..d61a3a627400 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -10370,7 +10370,50 @@ List listTestCaseResolutionForEntityFQNHash( @SqlUpdate( "DELETE FROM test_case_resolution_status_time_series WHERE entityFQNHash = :entityFQNHash") - void delete(@BindFQN("entityFQNHash") String entityFQNHash); + void deleteRecords(@BindFQN("entityFQNHash") String entityFQNHash); + + @SqlUpdate("DELETE FROM test_case_incident WHERE entityFQNHash = :entityFQNHash") + void deleteIncidents(@BindFQN("entityFQNHash") String entityFQNHash); + + default void delete(String entityFQNHash) { + deleteRecords(entityFQNHash); + deleteIncidents(entityFQNHash); + } + + // The record's chain state, projected at write time. `createdAt` only ever moves down + // (LEAST) so replays or out-of-order syncs cannot shrink an incident's lifetime. + @ConnectionAwareSqlUpdate( + value = + "INSERT INTO test_case_incident (stateId, entityFQNHash, testCaseResolutionStatusType, " + + "assignee, severity, createdAt, updatedAt, latestRecordId) " + + "VALUES (:stateId, :entityFQNHash, :statusType, :assignee, :severity, " + + ":timestamp, :timestamp, :recordId) " + + "ON DUPLICATE KEY UPDATE " + + "testCaseResolutionStatusType = VALUES(testCaseResolutionStatusType), " + + "assignee = VALUES(assignee), severity = VALUES(severity), " + + "createdAt = LEAST(createdAt, VALUES(createdAt)), " + + "updatedAt = VALUES(updatedAt), latestRecordId = VALUES(latestRecordId)", + connectionType = MYSQL) + @ConnectionAwareSqlUpdate( + value = + "INSERT INTO test_case_incident (stateId, entityFQNHash, testCaseResolutionStatusType, " + + "assignee, severity, createdAt, updatedAt, latestRecordId) " + + "VALUES (:stateId, :entityFQNHash, :statusType, :assignee, :severity, " + + ":timestamp, :timestamp, :recordId) " + + "ON CONFLICT (stateId) DO UPDATE SET " + + "testCaseResolutionStatusType = EXCLUDED.testCaseResolutionStatusType, " + + "assignee = EXCLUDED.assignee, severity = EXCLUDED.severity, " + + "createdAt = LEAST(test_case_incident.createdAt, EXCLUDED.createdAt), " + + "updatedAt = EXCLUDED.updatedAt, latestRecordId = EXCLUDED.latestRecordId", + connectionType = POSTGRES) + void upsertIncident( + @Bind("stateId") String stateId, + @BindFQN("entityFQNHash") String entityFQNHash, + @Bind("statusType") String statusType, + @Bind("assignee") String assignee, + @Bind("severity") String severity, + @Bind("timestamp") long timestamp, + @Bind("recordId") String recordId); @SqlQuery( "SELECT json FROM " @@ -10498,59 +10541,37 @@ default int listCount(ListFilter filter) { connectionType = POSTGRES) int deleteOrphanedRecords(@Bind("limit") int limit); - // An incident is a stateId chain. `chain` folds each stateId to its first/last timestamps - // over the (stateId, timestamp) index, `latestRecord` picks exactly one record per chain at - // the last timestamp — MAX(id) is an arbitrary but deterministic tie-breaker, without which - // two records sharing the chain's max timestamp would both enter the aggregates (stale - // assignees, double-counted trend points) — and `incident` loads that record's current - // status/assignee/severity. - String INCIDENT_GROUPS_CTE = + // Groups are served from the write-time incident summary (one row per stateId chain), + // so the read is O(open incidents) regardless of history depth. Column names mirror the + // time-series table, letting ListFilter's incident conditions apply verbatim under alias i. + String INCIDENT_GROUPS_FROM = """ - WITH chain AS ( - SELECT stateId, MIN(timestamp) AS createdAt, MAX(timestamp) AS updatedAt - FROM test_case_resolution_status_time_series - - GROUP BY stateId - ), - latestRecord AS ( - SELECT c.stateId, c.createdAt, c.updatedAt, MAX(t.id) AS latestId - FROM chain c - INNER JOIN test_case_resolution_status_time_series t - ON t.stateId = c.stateId AND t.timestamp = c.updatedAt - GROUP BY c.stateId, c.createdAt, c.updatedAt - ), - incident AS ( - SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, - AS severity, l.createdAt, l.updatedAt - FROM latestRecord l - INNER JOIN test_case_resolution_status_time_series t ON t.id = l.latestId - ) + FROM test_case_incident i + INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash + + AND i.testCaseResolutionStatusType IN () AND tc.deleted = FALSE """; - @SqlQuery( - INCIDENT_GROUPS_CTE - + """ - SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateId) AS incidentCount, - MIN(i.severity) AS severity, - MIN(CASE i.testCaseResolutionStatusType WHEN 'Assigned' THEN 1 WHEN 'Ack' THEN 2 ELSE 3 END) AS statusRank, - AS assignees, - COUNT(DISTINCT i.assignee) AS assigneeCount, - MIN(i.createdAt) AS firstSeen, - MAX(i.updatedAt) AS lastSeen, - AS incidentCreatedAt, - COUNT(*) OVER () AS totalGroups - FROM incident i - INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash - - AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE - GROUP BY - ORDER BY incidentCount , groupKey - LIMIT :limit OFFSET :offset - """) + // statusRank maps the triage order Assigned > Ack > New so MIN() yields the most + // actionable current status; severity strings sort Severity1 < ... < Severity5 with + // Severity1 most critical, so MIN() yields the group's most critical severity. + @SqlQuery( + "SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateId) AS incidentCount, " + + "MIN(i.severity) AS severity, " + + "MIN(CASE i.testCaseResolutionStatusType WHEN 'Assigned' THEN 1 WHEN 'Ack' THEN 2 ELSE 3 END) AS statusRank, " + + " AS assignees, " + + "COUNT(DISTINCT i.assignee) AS assigneeCount, " + + "MIN(i.createdAt) AS firstSeen, " + + "MAX(i.updatedAt) AS lastSeen, " + + " AS incidentCreatedAt, " + + "COUNT(*) OVER () AS totalGroups " + + INCIDENT_GROUPS_FROM + + "GROUP BY " + + "ORDER BY incidentCount , groupKey " + + "LIMIT :limit OFFSET :offset") @RegisterRowMapper(TestCaseIncidentGroupCountMapper.class) List listIncidentGroups( - @Define("incidentCond") String incidentCond, - @Define("severityExpr") String severityExpr, + @Define("openStatuses") String openStatuses, @Define("assigneesExpr") String assigneesExpr, @Define("createdAtAgg") String createdAtAgg, @Define("groupKey") String groupKey, @@ -10563,18 +10584,9 @@ List listIncidentGroups( @Bind("limit") int limit, @Bind("offset") int offset); - @SqlQuery( - INCIDENT_GROUPS_CTE - + """ - SELECT COUNT(DISTINCT ) - FROM incident i - INNER JOIN test_case tc ON tc.fqnHash = i.entityFQNHash - - AND i.testCaseResolutionStatusType <> :resolvedStatus AND tc.deleted = FALSE - """) + @SqlQuery("SELECT COUNT(DISTINCT ) " + INCIDENT_GROUPS_FROM) int countIncidentGroups( - @Define("incidentCond") String incidentCond, - @Define("severityExpr") String severityExpr, + @Define("openStatuses") String openStatuses, @Define("groupKey") String groupKey, @Define("dimensionJoin") String dimensionJoin, @Define("cond") String cond, @@ -10597,21 +10609,36 @@ INNER JOIN (SELECT entityFQN AS testCaseEntityFQN,fqnHash AS testCaseHash, delet default IncidentGroupPage listIncidentGroups( IncidentGroupBy groupBy, ListFilter filter, String sortOrder, int limit, int offset) { - IncidentGroupSqlParts sqlParts = buildIncidentGroupSqlParts(groupBy, filter); - IncidentGroupDimension dimension = sqlParts.dimension(); + IncidentGroupDimension dimension = IncidentGroupDimension.from(groupBy); + // getCondition() first: building conditions registers indexed bind params (e.g. the + // status IN placeholders) on the filter, which the params snapshot must include. + String condition = filter.getCondition(); + Map params = new HashMap<>(filter.getQueryParams()); + // Positive IN over the open statuses instead of `<> Resolved`: the negative predicate + // cannot drive idx_tci_status_fqn and degrades to a scan of every summary row ever + // created, defeating the O(open incidents) purpose of this table. + List openStatusBinds = new ArrayList<>(); + int openStatusIndex = 0; + for (TestCaseResolutionStatusTypes status : TestCaseResolutionStatusTypes.values()) { + if (status != TestCaseResolutionStatusTypes.Resolved) { + String bind = "openStatus" + openStatusIndex++; + params.put(bind, status.value()); + openStatusBinds.add(":" + bind); + } + } + String openStatuses = String.join(", ", openStatusBinds); List counts = listIncidentGroups( - sqlParts.scopeCondition(), - severityExpr(), + openStatuses, assigneesExpr(), createdAtAggExpr(), dimension.groupKey(), dimension.groupType(), dimension.groupByCols(), dimension.join(), - sqlParts.condition(), + condition, sortOrder, - sqlParts.params(), + params, limit, offset); // The page query carries the group total via COUNT(*) OVER (); the standalone count only @@ -10624,22 +10651,11 @@ default IncidentGroupPage listIncidentGroups( } else { total = countIncidentGroups( - sqlParts.scopeCondition(), - severityExpr(), - dimension.groupKey(), - dimension.join(), - sqlParts.condition(), - sqlParts.params()); + openStatuses, dimension.groupKey(), dimension.join(), condition, params); } return new IncidentGroupPage(counts, total); } - private static String severityExpr() { - return Boolean.TRUE.equals(DatasourceConfig.getInstance().isMySQL()) - ? "json_unquote(json_extract(json, '$.severity'))" - : "json ->> 'severity'"; - } - // JSON aggregates instead of GROUP_CONCAT/STRING_AGG: the 1024-char group_concat_max_len // default would truncate an assignee-dense group mid-name. MySQL's JSON_ARRAYAGG cannot take // DISTINCT, so the array may carry nulls and duplicates — the repository dedupes on parse. @@ -10655,40 +10671,8 @@ private static String createdAtAggExpr() { : "JSON_AGG(i.createdAt)"; } - private static IncidentGroupSqlParts buildIncidentGroupSqlParts( - IncidentGroupBy groupBy, ListFilter filter) { - Map params = new HashMap<>(); - String scopeCondition = buildIncidentGroupScopeCondition(filter, params); - String condition = filter.getCondition(); - params.putAll(filter.getQueryParams()); - params.put("resolvedStatus", TestCaseResolutionStatusTypes.Resolved.value()); - return new IncidentGroupSqlParts( - scopeCondition, condition, IncidentGroupDimension.from(groupBy), params); - } - - // Pushes the test case scope into the CTE so incidents are ranked over a single FQN's - // records, and removes it from the filter so ListFilter does not re-apply it in the outer - // condition. - private static String buildIncidentGroupScopeCondition( - ListFilter filter, Map params) { - String result = ""; - String testCaseFQNHash = filter.getQueryParam("entityFQNHash"); - if (!nullOrEmpty(testCaseFQNHash)) { - filter.removeQueryParam("entityFQNHash"); - params.put("testCaseFQNHash", testCaseFQNHash); - result = "WHERE entityFQNHash = :testCaseFQNHash"; - } - return result; - } - record IncidentGroupPage(List counts, int total) {} - record IncidentGroupSqlParts( - String scopeCondition, - String condition, - IncidentGroupDimension dimension, - Map params) {} - record IncidentGroupDimension( String groupKey, String groupType, String groupByCols, String join) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java index 7058d0de76ed..8e90ff51baa9 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java @@ -294,10 +294,43 @@ public void storeInternal( default -> throw new IllegalArgumentException( String.format("Invalid status %s", recordEntity.getTestCaseResolutionStatusType())); } + persistRecord(recordFQN, recordEntity); + } + + // Single persistence choke point for both write paths (legacy storeInternal and + // task-driven syncFromTask): the immutable log insert plus the write-time projection of the + // chain's current state into test_case_incident, in the same transaction. The summary upsert + // must live here and not in only one path — API-created records (incl. bulk) never pass + // through syncFromTask, and task-driven records never pass through storeInternal's insert. + private void persistRecord(String recordFQN, TestCaseResolutionStatus recordEntity) { EntityReference testCaseReference = recordEntity.getTestCaseReference(); recordEntity.withTestCaseReference(null); timeSeriesDao.insert(recordFQN, entityType, JsonUtils.pojoToJson(recordEntity)); recordEntity.withTestCaseReference(testCaseReference); + ((CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO) timeSeriesDao) + .upsertIncident( + recordEntity.getStateId().toString(), + recordFQN, + recordEntity.getTestCaseResolutionStatusType().value(), + extractAssigneeName(recordEntity), + recordEntity.getSeverity() != null ? recordEntity.getSeverity().value() : null, + recordEntity.getTimestamp(), + recordEntity.getId().toString()); + } + + // Details arrive as a typed Assigned from internal callers but as a raw map from the API + // DTO (schema oneOf -> Object), so convert by declared status type instead of instanceof. + private static String extractAssigneeName(TestCaseResolutionStatus recordEntity) { + String result = null; + if (recordEntity.getTestCaseResolutionStatusType() == TestCaseResolutionStatusTypes.Assigned + && recordEntity.getTestCaseResolutionStatusDetails() != null) { + Assigned assigned = + JsonUtils.convertValue(recordEntity.getTestCaseResolutionStatusDetails(), Assigned.class); + if (assigned != null && assigned.getAssignee() != null) { + result = assigned.getAssignee().getName(); + } + } + return result; } @Override @@ -710,10 +743,7 @@ public void syncFromTask(TestCaseResolutionStatus recordEntity, String recordFQN recordEntity.getStateId(), recordFQN); - EntityReference testCaseReference = recordEntity.getTestCaseReference(); - recordEntity.withTestCaseReference(null); - timeSeriesDao.insert(recordFQN, entityType, JsonUtils.pojoToJson(recordEntity)); - recordEntity.withTestCaseReference(testCaseReference); + persistRecord(recordFQN, recordEntity); storeRelationship(recordEntity); postCreate(recordEntity); diff --git a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts index 58ca0e49a51a..577f93f80c12 100644 --- a/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts +++ b/openmetadata-ui/src/main/resources/ui/src/generated/tests/testCase.ts @@ -356,6 +356,11 @@ export interface TableData { * Schema to capture test case resolution status. */ export interface TestCaseResolutionStatus { + /** + * Human-readable summary of the test failure that opened the incident, denormalized from + * the failed test case result so incident listings do not need a per-incident result lookup. + */ + failureSummary?: string; /** * Unique identifier of this failure instance */ From fd497a918fada0356bd7ee30a49be03bf36e67ed Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Fri, 24 Jul 2026 09:55:53 -0700 Subject: [PATCH 11/13] feat: address comments --- .../native/2.1.0/mysql/schemaChanges.sql | 68 ++----------------- .../it/tests/IncidentGroupsIT.java | 53 ++++++--------- .../service/jdbi3/CollectionDAO.java | 28 ++++---- .../TestCaseResolutionStatusRepository.java | 15 ++-- 4 files changed, 44 insertions(+), 120 deletions(-) diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql index 9c54dfa91a20..025997c7a94d 100644 --- a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql @@ -4,81 +4,21 @@ -- the approvedById guard in 2.0.0). -- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) -SET @ddl = ( - SELECT IF( - EXISTS ( - SELECT 1 - FROM information_schema.statistics - WHERE table_schema = DATABASE() - AND table_name = 'test_case_resolution_status_time_series' - AND index_name = 'idx_test_case_resolution_status_state_id' - ), - 'SELECT 1', - 'ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp)' - ) -); -PREPARE stmt FROM @ddl; -EXECUTE stmt; -DEALLOCATE PREPARE stmt; +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp) -- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list -- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all -- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. -SET @ddl = ( - SELECT IF( - EXISTS ( - SELECT 1 - FROM information_schema.statistics - WHERE table_schema = DATABASE() - AND table_name = 'test_case_resolution_status_time_series' - AND index_name = 'idx_test_case_resolution_status_fqn_ts' - ), - 'SELECT 1', - 'ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp)' - ) -); -PREPARE stmt FROM @ddl; -EXECUTE stmt; -DEALLOCATE PREPARE stmt; +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp) -- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, -- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and -- id-based lookups fall back to full scans. -SET @ddl = ( - SELECT IF( - EXISTS ( - SELECT 1 - FROM information_schema.statistics - WHERE table_schema = DATABASE() - AND table_name = 'test_case' - AND index_name = 'idx_test_case_id' - ), - 'SELECT 1', - 'ALTER TABLE test_case ADD INDEX idx_test_case_id (id)' - ) -); -PREPARE stmt FROM @ddl; -EXECUTE stmt; -DEALLOCATE PREPARE stmt; +ALTER TABLE test_case ADD INDEX idx_test_case_id (id) -- The incident list's assignee filter compares the generated assignee column, which had no -- index and full-scanned the timeline at scale. -SET @ddl = ( - SELECT IF( - EXISTS ( - SELECT 1 - FROM information_schema.statistics - WHERE table_schema = DATABASE() - AND table_name = 'test_case_resolution_status_time_series' - AND index_name = 'idx_test_case_resolution_status_assignee' - ), - 'SELECT 1', - 'ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_assignee (assignee, timestamp)' - ) -); -PREPARE stmt FROM @ddl; -EXECUTE stmt; -DEALLOCATE PREPARE stmt; +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_assignee (assignee, timestamp) -- Incident summary table: one row per incident (stateId chain), maintained at write time so -- state-shaped reads (incidentGroups) are O(open incidents) instead of folding full history. diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java index d83be4edfd51..1c0e9675d104 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/IncidentGroupsIT.java @@ -944,41 +944,28 @@ private void insertStatusRecords(TestCase testCase, List> 'severity'" : "JSON_UNQUOTE(JSON_EXTRACT(t.json, '$.severity'))"; - String upsertTail = - postgres - ? "ON CONFLICT (stateId) DO UPDATE SET " - + "testCaseResolutionStatusType = EXCLUDED.testCaseResolutionStatusType, " - + "assignee = EXCLUDED.assignee, severity = EXCLUDED.severity, " - + "createdAt = LEAST(test_case_incident.createdAt, EXCLUDED.createdAt), " - + "updatedAt = EXCLUDED.updatedAt, latestRecordId = EXCLUDED.latestRecordId" - : "ON DUPLICATE KEY UPDATE " - + "testCaseResolutionStatusType = VALUES(testCaseResolutionStatusType), " - + "assignee = VALUES(assignee), severity = VALUES(severity), " - + "test_case_incident.createdAt = LEAST(test_case_incident.createdAt, VALUES(createdAt)), " - + "updatedAt = VALUES(updatedAt), latestRecordId = VALUES(latestRecordId)"; - String backfill = - "INSERT INTO test_case_incident (stateId, entityFQNHash, testCaseResolutionStatusType, " - + "assignee, severity, createdAt, updatedAt, latestRecordId) " - + "WITH chain AS (SELECT stateId, MIN(timestamp) AS createdAt, MAX(timestamp) AS updatedAt " - + " FROM test_case_resolution_status_time_series WHERE entityFQNHash = ? GROUP BY stateId), " - + "latestRecord AS (SELECT c.stateId, c.createdAt, c.updatedAt, MAX(t.id) AS latestId " - + " FROM chain c INNER JOIN test_case_resolution_status_time_series t " - + " ON t.stateId = c.stateId AND t.timestamp = c.updatedAt " - + " GROUP BY c.stateId, c.createdAt, c.updatedAt) " - + "SELECT t.stateId, t.entityFQNHash, t.testCaseResolutionStatusType, t.assignee, " - + severityExpr - + ", l.createdAt, l.updatedAt, t.id " - + "FROM latestRecord l INNER JOIN test_case_resolution_status_time_series t ON t.id = l.latestId " - + upsertTail; - try (PreparedStatement statement = connection.prepareStatement(backfill)) { - statement.setString(1, fqnHash); - statement.executeUpdate(); + java.nio.file.Path migrationFile = + java.nio.file.Path.of( + "..", + "bootstrap", + "sql", + "migrations", + "native", + "2.1.0", + postgres ? "postgres" : "mysql", + "postDataMigrationSQLScript.sql"); + if (!java.nio.file.Files.exists(migrationFile)) { + migrationFile = java.nio.file.Path.of("bootstrap").resolve(migrationFile.subpath(1, 8)); + } + String backfill = java.nio.file.Files.readString(migrationFile); + try (java.sql.Statement statement = connection.createStatement()) { + statement.executeUpdate(backfill); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index d61a3a627400..fa7e98d5399a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -10380,8 +10380,6 @@ default void delete(String entityFQNHash) { deleteIncidents(entityFQNHash); } - // The record's chain state, projected at write time. `createdAt` only ever moves down - // (LEAST) so replays or out-of-order syncs cannot shrink an incident's lifetime. @ConnectionAwareSqlUpdate( value = "INSERT INTO test_case_incident (stateId, entityFQNHash, testCaseResolutionStatusType, " @@ -10415,6 +10413,21 @@ void upsertIncident( @Bind("timestamp") long timestamp, @Bind("recordId") String recordId); + @Transaction + default void insertRecordWithIncident( + String recordFQN, + String jsonSchema, + String json, + String stateId, + String statusType, + String assignee, + String severity, + long timestamp, + String recordId) { + insert(recordFQN, jsonSchema, json); + upsertIncident(stateId, recordFQN, statusType, assignee, severity, timestamp, recordId); + } + @SqlQuery( "SELECT json FROM " + "(SELECT id, json, testCaseResolutionStatusType, assignee, ROW_NUMBER() OVER(PARTITION BY ORDER BY timestamp DESC) AS row_num " @@ -10541,9 +10554,6 @@ default int listCount(ListFilter filter) { connectionType = POSTGRES) int deleteOrphanedRecords(@Bind("limit") int limit); - // Groups are served from the write-time incident summary (one row per stateId chain), - // so the read is O(open incidents) regardless of history depth. Column names mirror the - // time-series table, letting ListFilter's incident conditions apply verbatim under alias i. String INCIDENT_GROUPS_FROM = """ FROM test_case_incident i @@ -10552,9 +10562,6 @@ default int listCount(ListFilter filter) { AND i.testCaseResolutionStatusType IN () AND tc.deleted = FALSE """; - // statusRank maps the triage order Assigned > Ack > New so MIN() yields the most - // actionable current status; severity strings sort Severity1 < ... < Severity5 with - // Severity1 most critical, so MIN() yields the group's most critical severity. @SqlQuery( "SELECT AS groupKey, AS groupType, COUNT(DISTINCT i.stateId) AS incidentCount, " + "MIN(i.severity) AS severity, " @@ -10610,13 +10617,8 @@ INNER JOIN (SELECT entityFQN AS testCaseEntityFQN,fqnHash AS testCaseHash, delet default IncidentGroupPage listIncidentGroups( IncidentGroupBy groupBy, ListFilter filter, String sortOrder, int limit, int offset) { IncidentGroupDimension dimension = IncidentGroupDimension.from(groupBy); - // getCondition() first: building conditions registers indexed bind params (e.g. the - // status IN placeholders) on the filter, which the params snapshot must include. String condition = filter.getCondition(); Map params = new HashMap<>(filter.getQueryParams()); - // Positive IN over the open statuses instead of `<> Resolved`: the negative predicate - // cannot drive idx_tci_status_fqn and degrades to a scan of every summary row ever - // created, defeating the O(open incidents) purpose of this table. List openStatusBinds = new ArrayList<>(); int openStatusIndex = 0; for (TestCaseResolutionStatusTypes status : TestCaseResolutionStatusTypes.values()) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java index 8e90ff51baa9..a88439ae3bbe 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java @@ -297,20 +297,17 @@ public void storeInternal( persistRecord(recordFQN, recordEntity); } - // Single persistence choke point for both write paths (legacy storeInternal and - // task-driven syncFromTask): the immutable log insert plus the write-time projection of the - // chain's current state into test_case_incident, in the same transaction. The summary upsert - // must live here and not in only one path — API-created records (incl. bulk) never pass - // through syncFromTask, and task-driven records never pass through storeInternal's insert. private void persistRecord(String recordFQN, TestCaseResolutionStatus recordEntity) { EntityReference testCaseReference = recordEntity.getTestCaseReference(); recordEntity.withTestCaseReference(null); - timeSeriesDao.insert(recordFQN, entityType, JsonUtils.pojoToJson(recordEntity)); + String recordJson = JsonUtils.pojoToJson(recordEntity); recordEntity.withTestCaseReference(testCaseReference); ((CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO) timeSeriesDao) - .upsertIncident( - recordEntity.getStateId().toString(), + .insertRecordWithIncident( recordFQN, + entityType, + recordJson, + recordEntity.getStateId().toString(), recordEntity.getTestCaseResolutionStatusType().value(), extractAssigneeName(recordEntity), recordEntity.getSeverity() != null ? recordEntity.getSeverity().value() : null, @@ -318,8 +315,6 @@ private void persistRecord(String recordFQN, TestCaseResolutionStatus recordEnti recordEntity.getId().toString()); } - // Details arrive as a typed Assigned from internal callers but as a raw map from the API - // DTO (schema oneOf -> Object), so convert by declared status type instead of instanceof. private static String extractAssigneeName(TestCaseResolutionStatus recordEntity) { String result = null; if (recordEntity.getTestCaseResolutionStatusType() == TestCaseResolutionStatusTypes.Assigned From 025705f699b519847222872c033cde83dd8f1fbd Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Fri, 24 Jul 2026 10:17:35 -0700 Subject: [PATCH 12/13] feat: address comments --- .../service/jdbi3/CollectionDAO.java | 15 ------- .../TestCaseResolutionStatusRepository.java | 40 +++++++++++++------ 2 files changed, 27 insertions(+), 28 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java index fa7e98d5399a..1fbcff83f957 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java @@ -10413,21 +10413,6 @@ void upsertIncident( @Bind("timestamp") long timestamp, @Bind("recordId") String recordId); - @Transaction - default void insertRecordWithIncident( - String recordFQN, - String jsonSchema, - String json, - String stateId, - String statusType, - String assignee, - String severity, - long timestamp, - String recordId) { - insert(recordFQN, jsonSchema, json); - upsertIncident(stateId, recordFQN, statusType, assignee, severity, timestamp, recordId); - } - @SqlQuery( "SELECT json FROM " + "(SELECT id, json, testCaseResolutionStatusType, assignee, ROW_NUMBER() OVER(PARTITION BY ORDER BY timestamp DESC) AS row_num " diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java index a88439ae3bbe..f8e1c9ff2a8a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseResolutionStatusRepository.java @@ -302,17 +302,33 @@ private void persistRecord(String recordFQN, TestCaseResolutionStatus recordEnti recordEntity.withTestCaseReference(null); String recordJson = JsonUtils.pojoToJson(recordEntity); recordEntity.withTestCaseReference(testCaseReference); - ((CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO) timeSeriesDao) - .insertRecordWithIncident( - recordFQN, - entityType, - recordJson, - recordEntity.getStateId().toString(), - recordEntity.getTestCaseResolutionStatusType().value(), - extractAssigneeName(recordEntity), - recordEntity.getSeverity() != null ? recordEntity.getSeverity().value() : null, - recordEntity.getTimestamp(), - recordEntity.getId().toString()); + DeadlockRetry.execute( + () -> + Entity.getJdbi() + .inTransaction( + handle -> { + timeSeriesDao.insert(recordFQN, entityType, recordJson); + ((CollectionDAO.TestCaseResolutionStatusTimeSeriesDAO) timeSeriesDao) + .upsertIncident( + recordEntity.getStateId().toString(), + recordFQN, + recordEntity.getTestCaseResolutionStatusType().value(), + extractAssigneeName(recordEntity), + recordEntity.getSeverity() != null + ? recordEntity.getSeverity().value() + : null, + recordEntity.getTimestamp(), + recordEntity.getId().toString()); + storeRelationship(recordEntity); + return null; + })); + } + + // The PARENT_OF relationship is written inside persistRecord's transaction. The base + // createNewRecord's post-insert hook must not insert it a second time + @Override + protected void storeRelationshipInternal(TestCaseResolutionStatus recordEntity) { + // Relationship persisted atomically in persistRecord. } private static String extractAssigneeName(TestCaseResolutionStatus recordEntity) { @@ -739,8 +755,6 @@ public void syncFromTask(TestCaseResolutionStatus recordEntity, String recordFQN recordFQN); persistRecord(recordFQN, recordEntity); - - storeRelationship(recordEntity); postCreate(recordEntity); } From 7a42fb1cf51920e8fa448bf1755e23b4e5bd1629 Mon Sep 17 00:00:00 2001 From: TeddyCr Date: Tue, 28 Jul 2026 09:35:04 -0700 Subject: [PATCH 13/13] chore: fix migration --- .../migrations/native/2.1.0/mysql/schemaChanges.sql | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql index 025997c7a94d..9e153396fb77 100644 --- a/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.1.0/mysql/schemaChanges.sql @@ -1,24 +1,21 @@ -- Incident Manager grouped incidents - OpenMetadata 2.1.0 --- MySQL has no `ADD INDEX IF NOT EXISTS`, and environments that ran pre-release builds may --- already carry these indexes, so each ADD INDEX is guarded via information_schema (mirrors --- the approvedById guard in 2.0.0). -- Index the stateId partition used by the incident grouping endpoint (/testCaseIncidentStatus/incidentGroups) -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp) +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_state_id (stateId, timestamp); -- Serve entityFQNHash-driven access on the incident timeline: the /testCaseIncidentStatus list -- filters (testCaseFQN scope, testDefinition semi-join) and the incident grouping CTE scope all -- seek by entityFQNHash; only id-leading and timestamp-leading indexes existed before. -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp) +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_fqn_ts (entityFQNHash, timestamp); -- test_case predates the PRIMARY KEY(id) convention of newer entity tables and had no id index, -- so entity_relationship joins on toId = test_case.id (testDefinition incident filter) and -- id-based lookups fall back to full scans. -ALTER TABLE test_case ADD INDEX idx_test_case_id (id) +ALTER TABLE test_case ADD INDEX idx_test_case_id (id); -- The incident list's assignee filter compares the generated assignee column, which had no -- index and full-scanned the timeline at scale. -ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_assignee (assignee, timestamp) +ALTER TABLE test_case_resolution_status_time_series ADD INDEX idx_test_case_resolution_status_assignee (assignee, timestamp); -- Incident summary table: one row per incident (stateId chain), maintained at write time so -- state-shaped reads (incidentGroups) are O(open incidents) instead of folding full history.