From fa58fc3ed2543300077334a9d24638dc2282f099 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 00:40:37 -0700 Subject: [PATCH 01/47] Stabilize integration test CI --- .../scripts/classify_playwright_outcome.py | 546 ++++++++++++++++++ .github/scripts/classify_test_outcome.py | 255 ++++++++ .../test_classify_playwright_outcome.py | 291 ++++++++++ .github/scripts/test_classify_test_outcome.py | 180 ++++++ .../integration-tests-mysql-elasticsearch.yml | 352 +++++++++-- ...ion-tests-postgres-elasticsearch-redis.yml | 358 ++++++++++-- .../integration-tests-postgres-opensearch.yml | 352 +++++++++-- .../workflows/java-playwright-external.yml | 56 +- .github/workflows/mysql-nightly-e2e.yml | 35 +- .../playwright-integration-tests-mysql.yml | 18 +- .../playwright-integration-tests-postgres.yml | 18 +- ...ywright-knowledge-graph-postgresql-e2e.yml | 19 +- .github/workflows/playwright-mysql-e2e.yml | 66 ++- ...playwright-ontology-rdf-postgresql-e2e.yml | 19 +- .../workflows/playwright-postgresql-e2e.yml | 413 ++++++++++--- .github/workflows/playwright-sso-tests.yml | 191 +++++- .github/workflows/postgresql-nightly-e2e.yml | 35 +- .github/workflows/py-cli-e2e-tests.yml | 174 +++++- .github/workflows/py-tests-postgres.yml | 200 +++++-- .github/workflows/py-tests.yml | 269 ++++++--- .../tests/integration/lineage/e2e/conftest.py | 16 + .../lineage/e2e/test_view_lineage.py | 6 - ingestion/tests/integration/trino/conftest.py | 58 +- openmetadata-integration-tests/pom.xml | 241 +++++++- .../it/tests/UserMetricsResourceIT.java | 111 +--- .../cache/HardDeleteCacheConsistencyIT.java | 131 +++++ .../test/resources/junit-platform.properties | 3 +- .../apps/bundles/searchIndex/BulkSink.java | 2 + .../searchIndex/ElasticSearchBulkSink.java | 89 ++- .../searchIndex/OpenSearchBulkSink.java | 84 ++- .../service/cache/CacheBundle.java | 63 +- .../service/cache/CacheProvider.java | 17 + .../service/cache/CachedEntityDao.java | 56 +- .../service/cache/CachedLineage.java | 25 + .../service/cache/NotFoundCache.java | 283 ++++++++- .../service/cache/RedisCacheProvider.java | 77 ++- .../drive/ContextFileExtractionService.java | 82 ++- .../service/jdbi3/ContextFileRepository.java | 11 + .../service/jdbi3/EntityRepository.java | 241 ++++++-- .../service/jdbi3/TestCaseRepository.java | 156 ++--- .../service/search/SearchRepository.java | 122 +++- .../service/search/indexes/SearchIndex.java | 2 - .../ElasticSearchBulkSinkBehaviorTest.java | 98 +++- .../OpenSearchBulkSinkBehaviorTest.java | 119 +++- .../service/cache/NotFoundCacheTest.java | 260 +++++++++ .../ContextFileExtractionServiceTest.java | 71 ++- .../jdbi3/EntityRepositoryRestoreTest.java | 26 +- .../service/search/SearchRepositoryTest.java | 97 +++- .../PageObject/Explore/OverviewPageObject.ts | 2 +- .../e2e/Pages/Lineage/LineageFilters.spec.ts | 93 ++- .../Pages/Lineage/LineageRightPanel.spec.ts | 89 ++- .../support/entity/DashboardDataModelClass.ts | 9 +- 52 files changed, 5678 insertions(+), 909 deletions(-) create mode 100644 .github/scripts/classify_playwright_outcome.py create mode 100644 .github/scripts/classify_test_outcome.py create mode 100644 .github/scripts/test_classify_playwright_outcome.py create mode 100644 .github/scripts/test_classify_test_outcome.py create mode 100644 openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/cache/HardDeleteCacheConsistencyIT.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/cache/NotFoundCacheTest.java diff --git a/.github/scripts/classify_playwright_outcome.py b/.github/scripts/classify_playwright_outcome.py new file mode 100644 index 000000000000..cac10e1a8821 --- /dev/null +++ b/.github/scripts/classify_playwright_outcome.py @@ -0,0 +1,546 @@ +"""Build a deterministic Playwright outcome and zero-retry shadow-gate ledger.""" + +import argparse +import glob +import hashlib +import json +import os +import re +import subprocess +from pathlib import Path +from typing import Any + +KNOWN_STATUSES = {"expected", "unexpected", "flaky", "skipped"} +HANG_EXIT_CODES = {124} +ARTIFACT_SHARD_PATTERN = re.compile( + r"(?:playwright|sso)-results-json-(?P[^/]+)$" +) + + +def _expand_globs(patterns: list[str]) -> list[Path]: + return sorted( + { + Path(match) + for pattern in patterns + for match in glob.glob(pattern, recursive=True) + if Path(match).is_file() + }, + key=str, + ) + + +def _file_manifest(files: list[Path]) -> list[dict[str, object]]: + manifest = [] + for file_path in files: + try: + content = file_path.read_bytes() + manifest.append( + { + "path": str(file_path), + "bytes": len(content), + "sha256": hashlib.sha256(content).hexdigest(), + } + ) + except OSError as error: + manifest.append({"path": str(file_path), "error": str(error)}) + return manifest + + +def _infer_shard(file_path: Path) -> str: + for part in reversed(file_path.parts): + match = ARTIFACT_SHARD_PATTERN.match(part) + if match: + return match.group("shard") + return "" + + +def _normalize_file(file_name: object) -> str: + normalized = str(file_name or "").replace("\\", "/") + marker = "playwright/e2e/" + marker_index = normalized.find(marker) + return normalized[marker_index:] if marker_index >= 0 else normalized + + +def _normalize_error(error: object) -> str: + if isinstance(error, dict): + value = error.get("message") or error.get("value") or "" + else: + value = error or "" + normalized = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", str(value)) + normalized = re.sub( + r"[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}", + "", + normalized, + flags=re.IGNORECASE, + ) + normalized = re.sub(r"\b\d+(?:\.\d+)?(?:ms|s|m)\b", "", normalized) + normalized = re.sub(r"(?<=:)(\d+):(\d+)\b", ":", normalized) + normalized = re.sub(r"\b(localhost|127\.0\.0\.1):\d+\b", r"\1:", normalized) + normalized = re.sub(r"(?", normalized) + return re.sub(r"\s+", " ", normalized).strip()[:4000] + + +def _test_record( + test: dict[str, Any], + title: str, + file_name: str, + report_file: Path, + shard: str, +) -> dict[str, object]: + results = test.get("results") + attempts = results if isinstance(results, list) else [] + first_error = "" + for attempt in attempts: + if isinstance(attempt, dict) and attempt.get("error"): + first_error = _normalize_error(attempt["error"]) + break + + project = str(test.get("projectName") or "unknown-project") + stable_id = " :: ".join((project, file_name, title)) + return { + "stableId": stable_id, + "project": project, + "file": file_name, + "title": title, + "status": str(test.get("status") or "unknown"), + "attempts": len(attempts), + "retries": max(0, len(attempts) - 1), + "firstError": first_error, + "errorFingerprint": ( + hashlib.sha256(first_error.encode("utf-8")).hexdigest() + if first_error + else "" + ), + "shard": shard, + "report": str(report_file), + } + + +def _collect_suite_tests( + suite: dict[str, Any], + report_file: Path, + shard: str, + inherited_file: str = "", + inherited_titles: tuple[str, ...] = (), +) -> list[dict[str, object]]: + file_name = _normalize_file(suite.get("file") or inherited_file) + suite_title = str(suite.get("title") or "").strip() + if suite_title.replace("\\", "/") in { + file_name, + file_name.rsplit("/", 1)[-1], + }: + suite_title = "" + title_prefix = inherited_titles + ((suite_title,) if suite_title else ()) + records = [] + + specs = suite.get("specs") + for spec in specs if isinstance(specs, list) else []: + if not isinstance(spec, dict): + continue + spec_file = _normalize_file(spec.get("file") or file_name) + spec_title = str(spec.get("title") or "unnamed test").strip() + title = " › ".join((*title_prefix, spec_title)) + tests = spec.get("tests") + for test in tests if isinstance(tests, list) else []: + if isinstance(test, dict): + records.append(_test_record(test, title, spec_file, report_file, shard)) + + child_suites = suite.get("suites") + for child in child_suites if isinstance(child_suites, list) else []: + if isinstance(child, dict): + records.extend( + _collect_suite_tests( + child, + report_file, + shard, + inherited_file=file_name, + inherited_titles=title_prefix, + ) + ) + return records + + +def _read_reports( + report_files: list[Path], +) -> tuple[list[dict[str, object]], list[str], list[str]]: + records = [] + parse_errors = [] + empty_reports = [] + for report_file in report_files: + try: + report = json.loads(report_file.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as error: + parse_errors.append(f"{report_file}: {error}") + continue + if not isinstance(report, dict): + parse_errors.append(f"{report_file}: the report root is not an object") + continue + + report_records = [] + suites = report.get("suites") + for suite in suites if isinstance(suites, list) else []: + if isinstance(suite, dict): + report_records.extend( + _collect_suite_tests(suite, report_file, _infer_shard(report_file)) + ) + if not report_records: + empty_reports.append(str(report_file)) + records.extend(report_records) + return records, parse_errors, empty_reports + + +def _read_statuses( + status_files: list[Path], +) -> tuple[list[dict[str, object]], list[str]]: + statuses = [] + parse_errors = [] + for status_file in status_files: + try: + status = json.loads(status_file.read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as error: + parse_errors.append(f"{status_file}: {error}") + continue + if not isinstance(status, dict): + parse_errors.append(f"{status_file}: the status root is not an object") + continue + status["_path"] = str(status_file) + status["shard"] = str(status.get("shard") or _infer_shard(status_file)) + statuses.append(status) + return statuses, parse_errors + + +def _expected_shards(explicit: list[str], matrix_json: str) -> tuple[list[str], str]: + shards = {str(shard) for shard in explicit if str(shard)} + if not matrix_json.strip(): + return sorted(shards), "" + try: + matrix = json.loads(matrix_json) + if not isinstance(matrix, dict): + raise ValueError("matrix root is not an object") + shard_indexes = matrix.get("shardIndex", []) + if not isinstance(shard_indexes, list): + raise ValueError("shardIndex is not an array") + shards.update(str(shard) for shard in shard_indexes) + except (ValueError, json.JSONDecodeError) as error: + return sorted(shards), str(error) + return sorted(shards), "" + + +def _parse_exit_code(value: object) -> int | None: + try: + return int(str(value)) if str(value).strip() else None + except ValueError: + return None + + +def _baseline_ids(path: str) -> tuple[set[str], str]: + if not path: + return set(), "" + try: + baseline = json.loads(Path(path).read_text(encoding="utf-8")) + except (OSError, UnicodeError, json.JSONDecodeError) as error: + return set(), str(error) + if isinstance(baseline, list): + return {str(value) for value in baseline}, "" + if not isinstance(baseline, dict): + return set(), "baseline root is not an object or array" + values = baseline.get("stableIds", baseline.get("retryPasses", [])) + if not isinstance(values, list): + return set(), "baseline stableIds/retryPasses is not an array" + return { + str(value.get("stableId") if isinstance(value, dict) else value) + for value in values + }, "" + + +def classify_playwright_outcome( + report_files: list[Path], + status_files: list[Path], + matrix_outcome: str = "", + expected_shards: list[str] | None = None, + require_statuses: bool = False, + retry_baseline_ids: set[str] | None = None, +) -> dict[str, object]: + records, report_parse_errors, empty_reports = _read_reports(report_files) + statuses, status_parse_errors = _read_statuses(status_files) + expected = sorted(set(expected_shards or [])) + baseline_configured = retry_baseline_ids is not None + baseline_ids = retry_baseline_ids or set() + infrastructure_issues = [] + + infrastructure_issues.extend( + f"Invalid Playwright report: {error}" for error in report_parse_errors + ) + infrastructure_issues.extend( + f"Invalid execution status: {error}" for error in status_parse_errors + ) + infrastructure_issues.extend( + f"Playwright report contains zero tests: {path}" for path in empty_reports + ) + unknown_records = [ + record for record in records if record["status"] not in KNOWN_STATUSES + ] + if unknown_records: + infrastructure_issues.append( + f"{len(unknown_records)} test(s) reported an unknown status." + ) + + report_shards = {str(record["shard"]) for record in records if record["shard"]} + status_by_shard = { + str(status["shard"]): status for status in statuses if status.get("shard") + } + failures = [record for record in records if record["status"] == "unexpected"] + retry_passes = [record for record in records if record["status"] == "flaky"] + passed = [record for record in records if record["status"] == "expected"] + skipped = [record for record in records if record["status"] == "skipped"] + failure_count_by_shard: dict[str, int] = {} + for failure in failures: + shard = str(failure["shard"]) + failure_count_by_shard[shard] = failure_count_by_shard.get(shard, 0) + 1 + + if expected: + for shard in expected: + if shard not in report_shards: + infrastructure_issues.append( + f"Shard {shard} did not produce a usable Playwright report." + ) + if require_statuses and shard not in status_by_shard: + infrastructure_issues.append( + f"Shard {shard} did not produce execution status." + ) + for shard in sorted(report_shards - set(expected)): + infrastructure_issues.append( + f"Unexpected shard {shard} produced a Playwright report." + ) + + hung_shards = [] + for status in statuses: + shard = str(status.get("shard") or "unknown") + steps = status.get("steps") + steps = steps if isinstance(steps, dict) else {} + setup_failure = next( + ( + name + for name, outcome in steps.items() + if name != "tests" and outcome in {"failure", "cancelled"} + ), + "", + ) + if setup_failure: + infrastructure_issues.append( + f"Shard {shard} failed during {setup_failure} setup." + ) + + exit_code = _parse_exit_code(status.get("exitCode")) + if exit_code in HANG_EXIT_CODES: + hung_shards.append(shard) + continue + test_outcome = str(steps.get("tests") or "not-run") + if test_outcome != "success" and not ( + test_outcome == "failure" and failure_count_by_shard.get(shard, 0) > 0 + ): + infrastructure_issues.append( + f"Shard {shard} test execution finished with status {test_outcome} " + "without a reported test failure." + ) + + if matrix_outcome == "cancelled": + infrastructure_issues.append("The Playwright matrix was cancelled.") + elif matrix_outcome == "skipped": + infrastructure_issues.append("The Playwright matrix was unexpectedly skipped.") + elif matrix_outcome == "failure" and not failures and not infrastructure_issues: + infrastructure_issues.append( + "The Playwright matrix failed outside a reported test failure." + ) + + if matrix_outcome == "cancelled": + classification = "cancelled" + elif hung_shards: + classification = "hung_test" + elif failures: + classification = "test_failure" + elif infrastructure_issues: + classification = "infrastructure_failure" + elif not records: + classification = "missing_results" + elif retry_passes: + classification = "passed_with_retries" + else: + classification = "passed" + + records.sort(key=lambda record: str(record["stableId"])) + failure_ids = sorted({str(record["stableId"]) for record in failures}) + retry_ids = sorted({str(record["stableId"]) for record in retry_passes}) + skipped_ids = sorted({str(record["stableId"]) for record in skipped}) + new_retry_ids = sorted(set(retry_ids) - baseline_ids) if baseline_configured else [] + unbaselined_retry_ids = retry_ids if not baseline_configured else [] + current_gate_would_fail = classification not in {"passed", "passed_with_retries"} + shadow_gate_would_fail = current_gate_would_fail or bool(retry_ids) + + return { + "schemaVersion": 1, + "classification": classification, + "matrixOutcome": matrix_outcome, + "counts": { + "tests": len(records), + "passed": len(passed), + "failed": len(failures), + "retryPassed": len(retry_passes), + "skipped": len(skipped), + "unknown": len(unknown_records), + }, + "expectedShards": expected, + "observedReportShards": sorted(report_shards), + "observedStatusShards": sorted(status_by_shard), + "hungShards": sorted(set(hung_shards)), + "infrastructureIssues": infrastructure_issues, + "failureStableIds": failure_ids, + "retryPassStableIds": retry_ids, + "newRetryPassStableIds": new_retry_ids, + "unbaselinedRetryPassStableIds": unbaselined_retry_ids, + "skippedStableIds": skipped_ids, + "failures": failures, + "retryPasses": retry_passes, + "skipped": skipped, + "currentGate": {"wouldFail": current_gate_would_fail}, + "retryBaseline": { + "configured": baseline_configured, + "stableIdCount": len(baseline_ids), + }, + "shadowGate": { + "policy": "zero-retry-pass", + "enforcing": False, + "wouldFail": shadow_gate_would_fail, + "shadowOnlyFailure": shadow_gate_would_fail and not current_gate_would_fail, + "retryPassSignatureCount": len(retry_ids), + "newRetryPassSignatureCount": len(new_retry_ids), + }, + "reports": _file_manifest(report_files), + "statuses": _file_manifest(status_files), + "reportParseErrors": report_parse_errors, + "statusParseErrors": status_parse_errors, + } + + +def _source_sha() -> str: + try: + return subprocess.run( + ["git", "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return os.environ.get("GITHUB_SHA", "") + + +def _summary(result: dict[str, object]) -> str: + counts = result["counts"] + context = result["context"] + shadow_gate = result["shadowGate"] + lines = [ + "### Playwright deterministic gate", + "", + f"- Classification: `{result['classification']}`", + f"- Source SHA: `{context['sourceSha']}`", + f"- Profile: `{context['profile']}`", + f"- Tests: {counts['tests']} total, {counts['failed']} failed, " + f"{counts['retryPassed']} passed on retry, {counts['skipped']} skipped", + f"- Current gate would fail: `{str(result['currentGate']['wouldFail']).lower()}`", + f"- Shadow zero-retry gate would fail: `{str(shadow_gate['wouldFail']).lower()}`", + f"- Retry-pass signatures: {shadow_gate['retryPassSignatureCount']}", + "", + ] + if result["retryBaseline"]["configured"]: + lines.insert( + -1, + f"- New retry-pass signatures: {shadow_gate['newRetryPassSignatureCount']}", + ) + else: + lines.insert( + -1, "- Retry baseline: not supplied; signatures are observation-only" + ) + retry_ids = result["retryPassStableIds"] + if retry_ids: + lines.extend(["#### Retry-pass signatures", ""]) + lines.extend(f"- `{stable_id}`" for stable_id in retry_ids[:30]) + if len(retry_ids) > 30: + lines.append(f"- ... and {len(retry_ids) - 30} more") + lines.append("") + return "\n".join(lines) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--report-glob", action="append", default=[]) + parser.add_argument("--status-glob", action="append", default=[]) + parser.add_argument("--matrix-outcome", default="") + parser.add_argument("--expected-shard", action="append", default=[]) + parser.add_argument("--expected-matrix-json", default="") + parser.add_argument("--retry-baseline", default="") + parser.add_argument("--profile", default="") + parser.add_argument("--source-sha", default="") + parser.add_argument("--output", required=True) + parser.add_argument("--summary") + parser.add_argument("--enforce", action="store_true") + args = parser.parse_args() + + report_files = _expand_globs(args.report_glob) + status_files = _expand_globs(args.status_glob) + expected_shards, matrix_error = _expected_shards( + args.expected_shard, args.expected_matrix_json + ) + baseline_ids, baseline_error = _baseline_ids(args.retry_baseline) + result = classify_playwright_outcome( + report_files, + status_files, + matrix_outcome=args.matrix_outcome, + expected_shards=expected_shards, + require_statuses=bool(args.status_glob), + retry_baseline_ids=baseline_ids if args.retry_baseline else None, + ) + if matrix_error: + result["infrastructureIssues"].append( + f"The expected shard matrix was invalid: {matrix_error}" + ) + result["classification"] = "infrastructure_failure" + result["currentGate"]["wouldFail"] = True + result["shadowGate"]["wouldFail"] = True + result["shadowGate"]["shadowOnlyFailure"] = False + if baseline_error: + result["infrastructureIssues"].append( + f"The retry-pass baseline was invalid: {baseline_error}" + ) + result["classification"] = "infrastructure_failure" + result["currentGate"]["wouldFail"] = True + result["shadowGate"]["wouldFail"] = True + result["shadowGate"]["shadowOnlyFailure"] = False + + result["shadowGate"]["enforcing"] = args.enforce + result["context"] = { + "sourceSha": args.source_sha + or os.environ.get("SOURCE_SHA", "") + or _source_sha(), + "profile": args.profile or os.environ.get("TEST_PROFILE", ""), + "runId": os.environ.get("GITHUB_RUN_ID", ""), + "runAttempt": os.environ.get("GITHUB_RUN_ATTEMPT", ""), + "eventName": os.environ.get("GITHUB_EVENT_NAME", ""), + } + + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + summary = _summary(result) + summary_path = args.summary or os.environ.get("GITHUB_STEP_SUMMARY") + if summary_path: + with Path(summary_path).open("a", encoding="utf-8") as summary_file: + summary_file.write(summary) + print(summary, end="") + return int(args.enforce and result["shadowGate"]["wouldFail"]) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/scripts/classify_test_outcome.py b/.github/scripts/classify_test_outcome.py new file mode 100644 index 000000000000..50099b108dbd --- /dev/null +++ b/.github/scripts/classify_test_outcome.py @@ -0,0 +1,255 @@ +"""Classify a CI test process from its exit state, JUnit reports, and diagnostics.""" + +import argparse +import glob +import hashlib +import json +import os +import re +import subprocess +from pathlib import Path +from xml.etree import ElementTree + +HANG_EXIT_CODES = {124} +HANG_PATTERN = re.compile( + r"(?:fork(?:ed)?(?:\s+(?:process|vm))?|test process|command|process)" + r".{0,80}(?:timed out|timeout)|" + r"(?:timed out|timeout).{0,80}" + r"(?:fork(?:ed)?(?:\s+(?:process|vm))?|test process|command|process)", + re.IGNORECASE | re.DOTALL, +) + + +def _local_name(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _junit_counts( + report_files: list[Path], +) -> tuple[dict[str, int], list[dict[str, str]], list[str]]: + totals = {"tests": 0, "failures": 0, "errors": 0, "skipped": 0} + failed_tests = [] + parse_errors = [] + for report_file in report_files: + try: + root = ElementTree.parse(report_file).getroot() + except (ElementTree.ParseError, OSError) as error: + parse_errors.append(f"{report_file}: {error}") + continue + + test_cases = [ + element for element in root.iter() if _local_name(element.tag) == "testcase" + ] + if test_cases: + totals["tests"] += len(test_cases) + for test_case in test_cases: + children_by_name = { + _local_name(child.tag): child for child in test_case + } + child_names = set(children_by_name) + totals["failures"] += int("failure" in child_names) + totals["errors"] += int("error" in child_names) + totals["skipped"] += int("skipped" in child_names) + for failure_type in ("failure", "error"): + failure = children_by_name.get(failure_type) + if failure is None: + continue + class_name = test_case.attrib.get("classname", "") + test_name = test_case.attrib.get("name", "") + failed_tests.append( + { + "id": f"{class_name}#{test_name}", + "className": class_name, + "name": test_name, + "type": failure_type, + "message": failure.attrib.get("message", "")[:1000], + "report": str(report_file), + } + ) + continue + + if _local_name(root.tag) in {"testsuite", "testsuites"}: + for key in totals: + try: + totals[key] += int(root.attrib.get(key, "0")) + except ValueError: + parse_errors.append( + f"{report_file}: invalid {key} count {root.attrib.get(key)!r}" + ) + return totals, failed_tests, parse_errors + + +def _contains_process_timeout(diagnostic_files: list[Path]) -> bool: + for diagnostic_file in diagnostic_files: + try: + with diagnostic_file.open("rb") as file_handle: + content = file_handle.read(2 * 1024 * 1024).decode( + "utf-8", errors="replace" + ) + except OSError: + continue + if HANG_PATTERN.search(content): + return True + return False + + +def _file_manifest(files: list[Path]) -> list[dict[str, object]]: + manifest = [] + for file_path in files: + try: + digest = hashlib.sha256(file_path.read_bytes()).hexdigest() + manifest.append( + { + "path": str(file_path), + "bytes": file_path.stat().st_size, + "sha256": digest, + } + ) + except OSError as error: + manifest.append({"path": str(file_path), "error": str(error)}) + return manifest + + +def classify_outcome( + step_outcome: str, + exit_code: int | None, + report_files: list[Path], + diagnostic_files: list[Path], +) -> dict[str, object]: + tests, failed_tests, parse_errors = _junit_counts(report_files) + reasons = [] + + if step_outcome == "cancelled": + classification = "cancelled" + reasons.append("The test step was cancelled.") + elif exit_code in HANG_EXIT_CODES or _contains_process_timeout(diagnostic_files): + classification = "hung_test" + reasons.append("The test process exceeded its bounded execution time.") + elif tests["failures"] + tests["errors"] > 0: + classification = "test_failure" + reasons.append("JUnit reported a test failure or error.") + elif parse_errors: + classification = "infrastructure_failure" + reasons.append("One or more JUnit reports could not be parsed.") + elif step_outcome == "success" and tests["tests"] == 0: + classification = "missing_results" + reasons.append("The test step succeeded without reporting any tests.") + elif step_outcome in {"failure", "skipped", "unknown", ""} and tests["tests"] == 0: + classification = "setup_failure" + reasons.append("The test process did not produce a test result.") + elif step_outcome != "success" or exit_code not in {None, 0}: + classification = "infrastructure_failure" + reasons.append("Tests did not fail, but the surrounding test process failed.") + else: + classification = "passed" + reasons.append("The test process and every reported test passed.") + + return { + "schemaVersion": 1, + "classification": classification, + "stepOutcome": step_outcome, + "exitCode": exit_code, + "tests": tests, + "failedTests": failed_tests, + "reportCount": len(report_files), + "reports": _file_manifest(report_files), + "reportParseErrors": parse_errors, + "diagnostics": _file_manifest(diagnostic_files), + "reasons": reasons, + } + + +def _expand_globs(patterns: list[str]) -> list[Path]: + return sorted( + { + Path(match) + for pattern in patterns + for match in glob.glob(pattern, recursive=True) + if Path(match).is_file() + }, + key=str, + ) + + +def _parse_exit_code(value: str) -> int | None: + return int(value) if value.strip() else None + + +def _source_sha() -> str: + try: + return subprocess.run( + ["git", "rev-parse", "HEAD"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + except (OSError, subprocess.CalledProcessError): + return os.environ.get("GITHUB_SHA", "") + + +def _summary(result: dict[str, object]) -> str: + tests = result["tests"] + context = result.get("context", {}) + return "\n".join( + [ + "### Test outcome classification", + "", + f"- Classification: `{result['classification']}`", + f"- Source SHA: `{context.get('sourceSha', '')}`", + f"- Profile/lane: `{context.get('profile', '')}` / `{context.get('lane', '')}`", + f"- Step outcome: `{result['stepOutcome']}`", + f"- Exit code: `{result['exitCode']}`", + f"- JUnit: {tests['tests']} tests, {tests['failures']} failures, " + f"{tests['errors']} errors, {tests['skipped']} skipped", + f"- Reports: {result['reportCount']}", + f"- Diagnostics: {len(result['diagnostics'])}", + f"- Reason: {result['reasons'][0]}", + "", + ] + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--step-outcome", required=True) + parser.add_argument("--exit-code", default="") + parser.add_argument("--report-glob", action="append", default=[]) + parser.add_argument("--diagnostic-glob", action="append", default=[]) + parser.add_argument("--output", required=True) + parser.add_argument("--summary") + args = parser.parse_args() + + report_files = _expand_globs(args.report_glob) + diagnostic_files = _expand_globs(args.diagnostic_glob) + result = classify_outcome( + args.step_outcome, + _parse_exit_code(args.exit_code), + report_files, + diagnostic_files, + ) + result["context"] = { + "sourceSha": _source_sha(), + "profile": os.environ.get("TEST_PROFILE", ""), + "lane": os.environ.get("TEST_LANE", ""), + "runId": os.environ.get("GITHUB_RUN_ID", ""), + "runAttempt": os.environ.get("GITHUB_RUN_ATTEMPT", ""), + } + + output_path = Path(args.output) + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text( + json.dumps(result, indent=2, sort_keys=True) + "\n", encoding="utf-8" + ) + + summary = _summary(result) + summary_path = args.summary or os.environ.get("GITHUB_STEP_SUMMARY") + if summary_path: + with Path(summary_path).open("a", encoding="utf-8") as summary_file: + summary_file.write(summary) + print(summary, end="") + + return int(args.step_outcome == "success" and result["classification"] != "passed") + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/.github/scripts/test_classify_playwright_outcome.py b/.github/scripts/test_classify_playwright_outcome.py new file mode 100644 index 000000000000..6d7c3388752e --- /dev/null +++ b/.github/scripts/test_classify_playwright_outcome.py @@ -0,0 +1,291 @@ +import importlib.util +import json +import subprocess +import sys +from pathlib import Path + +SCRIPT_PATH = Path(__file__).with_name("classify_playwright_outcome.py") +SPEC = importlib.util.spec_from_file_location( + "classify_playwright_outcome", SCRIPT_PATH +) +assert SPEC is not None and SPEC.loader is not None +CLASSIFIER = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = CLASSIFIER +SPEC.loader.exec_module(CLASSIFIER) + + +def write_json(path: Path, value: object) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(value), encoding="utf-8") + return path + + +def report( + status: str, results: list[dict[str, object]] | None = None +) -> dict[str, object]: + return { + "suites": [ + { + "title": "suite", + "file": "/workspace/playwright/e2e/example.spec.ts", + "specs": [ + { + "title": "does work", + "tests": [ + { + "projectName": "chromium", + "status": status, + "results": results or [{}], + } + ], + } + ], + } + ] + } + + +def status( + shard: str, tests: str = "success", exit_code: int | None = 0 +) -> dict[str, object]: + return { + "shard": shard, + "exitCode": exit_code, + "steps": { + "checkout": "success", + "setupEnvironment": "success", + "tests": tests, + }, + } + + +def test_passing_report_passes_both_gates(tmp_path: Path) -> None: + report_file = write_json( + tmp_path / "playwright-results-json-1" / "results.json", report("expected") + ) + status_file = write_json( + tmp_path / "playwright-results-json-1" / "ci-status.json", status("1") + ) + + result = CLASSIFIER.classify_playwright_outcome( + [report_file], [status_file], "success", ["1"], True + ) + + assert result["classification"] == "passed" + assert result["currentGate"]["wouldFail"] is False + assert result["shadowGate"]["wouldFail"] is False + assert result["reports"][0]["sha256"] + assert result["statuses"][0]["sha256"] + + +def test_retry_pass_has_stable_signature_and_only_fails_shadow_gate( + tmp_path: Path, +) -> None: + report_file = write_json( + tmp_path / "playwright-results-json-2" / "results.json", + report( + "flaky", + [ + { + "error": { + "message": "\u001b[31mTimed out after 90000ms for entity 123456 " + "and UUID 123e4567-e89b-12d3-a456-426614174000\u001b[0m" + } + }, + {}, + ], + ), + ) + + result = CLASSIFIER.classify_playwright_outcome([report_file], [], "success") + + assert result["classification"] == "passed_with_retries" + assert result["currentGate"]["wouldFail"] is False + assert result["shadowGate"]["wouldFail"] is True + assert result["shadowGate"]["shadowOnlyFailure"] is True + assert result["retryBaseline"]["configured"] is False + assert result["newRetryPassStableIds"] == [] + assert result["unbaselinedRetryPassStableIds"] == result["retryPassStableIds"] + assert result["retryPassStableIds"] == [ + "chromium :: playwright/e2e/example.spec.ts :: suite › does work" + ] + assert result["retryPasses"][0]["attempts"] == 2 + assert "" in result["retryPasses"][0]["firstError"] + assert "" in result["retryPasses"][0]["firstError"] + assert "" in result["retryPasses"][0]["firstError"] + assert "\u001b" not in result["retryPasses"][0]["firstError"] + assert result["retryPasses"][0]["errorFingerprint"] + + +def test_file_root_suite_title_is_not_duplicated(tmp_path: Path) -> None: + report_body = report("expected") + report_body["suites"][0]["title"] = "playwright/e2e/example.spec.ts" + report_file = write_json(tmp_path / "results.json", report_body) + + records, parse_errors, empty_reports = CLASSIFIER._read_reports([report_file]) + + assert parse_errors == [] + assert empty_reports == [] + assert records[0]["stableId"] == ( + "chromium :: playwright/e2e/example.spec.ts :: does work" + ) + + +def test_assertion_failure_is_a_test_failure(tmp_path: Path) -> None: + report_file = write_json( + tmp_path / "results.json", + report("unexpected", [{"error": {"message": "expected true"}}]), + ) + + result = CLASSIFIER.classify_playwright_outcome([report_file], [], "failure") + + assert result["classification"] == "test_failure" + assert result["counts"]["failed"] == 1 + assert result["currentGate"]["wouldFail"] is True + + +def test_setup_failure_without_report_is_infrastructure_failure(tmp_path: Path) -> None: + status_file = write_json( + tmp_path / "playwright-results-json-1" / "ci-status.json", + { + "shard": "1", + "steps": {"setupEnvironment": "failure", "tests": "skipped"}, + }, + ) + + result = CLASSIFIER.classify_playwright_outcome( + [], [status_file], "failure", ["1"], True + ) + + assert result["classification"] == "infrastructure_failure" + assert any("setupEnvironment" in issue for issue in result["infrastructureIssues"]) + + +def test_success_without_report_is_missing_results() -> None: + result = CLASSIFIER.classify_playwright_outcome([], [], "success") + + assert result["classification"] == "missing_results" + assert result["currentGate"]["wouldFail"] is True + + +def test_timeout_exit_code_is_a_hung_test(tmp_path: Path) -> None: + status_file = write_json( + tmp_path / "playwright-results-json-1" / "ci-status.json", + status("1", tests="failure", exit_code=124), + ) + + result = CLASSIFIER.classify_playwright_outcome( + [], [status_file], "failure", ["1"], True + ) + + assert result["classification"] == "hung_test" + assert result["hungShards"] == ["1"] + + +def test_missing_expected_shard_fails_closed(tmp_path: Path) -> None: + report_file = write_json( + tmp_path / "playwright-results-json-1" / "results.json", report("expected") + ) + + result = CLASSIFIER.classify_playwright_outcome( + [report_file], [], "success", ["1", "2"] + ) + + assert result["classification"] == "infrastructure_failure" + assert any("Shard 2" in issue for issue in result["infrastructureIssues"]) + + +def test_baseline_distinguishes_new_retry_passes(tmp_path: Path) -> None: + report_file = write_json( + tmp_path / "results.json", + report("flaky", [{"error": {"message": "first attempt"}}, {}]), + ) + stable_id = "chromium :: playwright/e2e/example.spec.ts :: suite › does work" + + result = CLASSIFIER.classify_playwright_outcome( + [report_file], [], "success", retry_baseline_ids={stable_id} + ) + + assert result["retryPassStableIds"] == [stable_id] + assert result["newRetryPassStableIds"] == [] + assert result["retryBaseline"] == {"configured": True, "stableIdCount": 1} + assert result["unbaselinedRetryPassStableIds"] == [] + + +def test_configured_baseline_reports_a_new_retry_signature(tmp_path: Path) -> None: + report_file = write_json( + tmp_path / "results.json", + report("flaky", [{"error": {"message": "first attempt"}}, {}]), + ) + + result = CLASSIFIER.classify_playwright_outcome( + [report_file], [], "success", retry_baseline_ids={"different stable id"} + ) + + assert result["newRetryPassStableIds"] == result["retryPassStableIds"] + assert result["shadowGate"]["newRetryPassSignatureCount"] == 1 + + +def test_cli_shadow_mode_writes_ledger_but_does_not_fail(tmp_path: Path) -> None: + report_file = write_json( + tmp_path / "results.json", + report("flaky", [{"error": {"message": "first attempt"}}, {}]), + ) + output = tmp_path / "ledger.json" + summary = tmp_path / "summary.md" + + completed = subprocess.run( + [ + sys.executable, + str(SCRIPT_PATH), + "--report-glob", + str(report_file), + "--matrix-outcome", + "success", + "--profile", + "postgresql-pr", + "--source-sha", + "abc123", + "--output", + str(output), + "--summary", + str(summary), + ], + check=False, + capture_output=True, + text=True, + ) + + ledger = json.loads(output.read_text(encoding="utf-8")) + assert completed.returncode == 0 + assert ledger["shadowGate"]["wouldFail"] is True + assert ledger["shadowGate"]["enforcing"] is False + assert ledger["retryBaseline"]["configured"] is False + assert ledger["context"]["sourceSha"] == "abc123" + assert "Shadow zero-retry gate would fail: `true`" in summary.read_text( + encoding="utf-8" + ) + + +def test_cli_enforcement_fails_on_retry_pass(tmp_path: Path) -> None: + report_file = write_json( + tmp_path / "results.json", + report("flaky", [{"error": {"message": "first attempt"}}, {}]), + ) + + completed = subprocess.run( + [ + sys.executable, + str(SCRIPT_PATH), + "--report-glob", + str(report_file), + "--output", + str(tmp_path / "ledger.json"), + "--enforce", + ], + check=False, + capture_output=True, + text=True, + ) + + assert completed.returncode == 1 diff --git a/.github/scripts/test_classify_test_outcome.py b/.github/scripts/test_classify_test_outcome.py new file mode 100644 index 000000000000..2ad5b9feadd4 --- /dev/null +++ b/.github/scripts/test_classify_test_outcome.py @@ -0,0 +1,180 @@ +import importlib.util +import json +import os +import subprocess +import sys +from pathlib import Path + +SCRIPT_PATH = Path(__file__).with_name("classify_test_outcome.py") +SPEC = importlib.util.spec_from_file_location("classify_test_outcome", SCRIPT_PATH) +assert SPEC is not None and SPEC.loader is not None +CLASSIFIER = importlib.util.module_from_spec(SPEC) +sys.modules[SPEC.name] = CLASSIFIER +SPEC.loader.exec_module(CLASSIFIER) + + +def write_report(path: Path, body: str) -> Path: + path.write_text(body, encoding="utf-8") + return path + + +def test_assertion_failure_is_a_test_failure(tmp_path: Path) -> None: + report = write_report( + tmp_path / "TEST-assertion.xml", + '' + '' + '' + "", + ) + diagnostic = write_report(tmp_path / "environment.txt", "runner environment") + + result = CLASSIFIER.classify_outcome("failure", 1, [report], [diagnostic]) + + assert result["classification"] == "test_failure" + assert result["tests"] == {"tests": 1, "failures": 1, "errors": 0, "skipped": 0} + assert result["failedTests"][0]["id"] == "ForcedIT#forced assertion" + assert result["reports"][0]["sha256"] + assert result["diagnostics"][0]["sha256"] + + +def test_setup_failure_has_no_test_result(tmp_path: Path) -> None: + diagnostic = write_report(tmp_path / "setup.log", "container failed health check") + + result = CLASSIFIER.classify_outcome("skipped", None, [], [diagnostic]) + + assert result["classification"] == "setup_failure" + assert result["reportCount"] == 0 + assert len(result["diagnostics"]) == 1 + assert result["diagnostics"][0]["sha256"] + + +def test_hung_process_is_distinct_from_setup_failure(tmp_path: Path) -> None: + try: + subprocess.run( + [sys.executable, "-c", "import time; time.sleep(10)"], + check=False, + timeout=0.01, + ) + except subprocess.TimeoutExpired as error: + diagnostic = write_report(tmp_path / "process-timeout.txt", str(error)) + else: + raise AssertionError("The forced hung process unexpectedly completed") + + result = CLASSIFIER.classify_outcome("failure", 124, [], [diagnostic]) + + assert result["classification"] == "hung_test" + assert result["exitCode"] == 124 + assert result["diagnostics"][0]["sha256"] + + +def test_failsafe_fork_timeout_is_a_hung_test(tmp_path: Path) -> None: + diagnostic = write_report( + tmp_path / "failsafe.dumpstream", "There was a timeout in the fork" + ) + + result = CLASSIFIER.classify_outcome("failure", 1, [], [diagnostic]) + + assert result["classification"] == "hung_test" + assert result["diagnostics"][0]["sha256"] + + +def test_passing_report_is_passed(tmp_path: Path) -> None: + report = write_report( + tmp_path / "TEST-pass.xml", + '' + '' + "", + ) + + result = CLASSIFIER.classify_outcome("success", 0, [report], []) + + assert result["classification"] == "passed" + assert result["tests"]["tests"] == 2 + assert result["tests"]["skipped"] == 1 + + +def test_success_without_reports_fails_closed() -> None: + result = CLASSIFIER.classify_outcome("success", 0, [], []) + + assert result["classification"] == "missing_results" + + +def test_malformed_report_is_infrastructure_failure(tmp_path: Path) -> None: + report = write_report(tmp_path / "TEST-broken.xml", "") + + result = CLASSIFIER.classify_outcome("failure", 1, [report], []) + + assert result["classification"] == "infrastructure_failure" + assert len(result["reportParseErrors"]) == 1 + + +def test_cli_writes_machine_readable_outcome_and_summary(tmp_path: Path) -> None: + report = write_report( + tmp_path / "TEST-pass.xml", + '' + '' + "", + ) + diagnostic = write_report(tmp_path / "environment.txt", "runner environment") + output = tmp_path / "outcome.json" + summary = tmp_path / "summary.md" + environment = os.environ | { + "TEST_PROFILE": "forced-profile", + "TEST_LANE": "parallel", + } + + completed = subprocess.run( + [ + sys.executable, + str(SCRIPT_PATH), + "--step-outcome", + "success", + "--exit-code", + "0", + "--report-glob", + str(report), + "--diagnostic-glob", + str(diagnostic), + "--output", + str(output), + "--summary", + str(summary), + ], + check=False, + capture_output=True, + env=environment, + text=True, + ) + + result = json.loads(output.read_text(encoding="utf-8")) + assert completed.returncode == 0 + assert result["classification"] == "passed" + assert result["context"]["profile"] == "forced-profile" + assert result["context"]["lane"] == "parallel" + assert result["reports"][0]["sha256"] + assert result["diagnostics"][0]["sha256"] + assert "Classification: `passed`" in summary.read_text(encoding="utf-8") + + +def test_cli_fails_closed_when_a_successful_step_has_no_results(tmp_path: Path) -> None: + output = tmp_path / "outcome.json" + + completed = subprocess.run( + [ + sys.executable, + str(SCRIPT_PATH), + "--step-outcome", + "success", + "--exit-code", + "0", + "--output", + str(output), + ], + check=False, + capture_output=True, + text=True, + ) + + result = json.loads(output.read_text(encoding="utf-8")) + assert completed.returncode == 1 + assert result["classification"] == "missing_results" diff --git a/.github/workflows/integration-tests-mysql-elasticsearch.yml b/.github/workflows/integration-tests-mysql-elasticsearch.yml index cb506484d587..a82e86b53eca 100644 --- a/.github/workflows/integration-tests-mysql-elasticsearch.yml +++ b/.github/workflows/integration-tests-mysql-elasticsearch.yml @@ -20,16 +20,24 @@ on: paths: - "openmetadata-service/**" - "openmetadata-integration-tests/**" - - "openmetadata-spec/src/main/resources/json/schema/**" + - "openmetadata-spec/pom.xml" + - "openmetadata-spec/src/**" - "openmetadata-sdk/**" + - "openmetadata-shaded-deps/**" + - "openmetadata-k8s-operator/**" + - "openmetadata-mcp/**" - "common/**" - "pom.xml" + - "Makefile" - "bootstrap/**" + - ".github/scripts/classify_test_outcome.py" + - ".github/workflows/integration-tests-mysql-elasticsearch.yml" pull_request_target: types: [labeled, opened, synchronize, reopened, ready_for_review] permissions: contents: read + pull-requests: read checks: write concurrency: @@ -50,7 +58,7 @@ jobs: outputs: backend: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.backend }} steps: - - uses: dorny/paths-filter@v3 + - uses: dorny/paths-filter@v4 id: filter if: ${{ github.event_name == 'pull_request_target' }} with: @@ -58,29 +66,32 @@ jobs: backend: - 'openmetadata-service/**' - 'openmetadata-integration-tests/**' - - 'openmetadata-spec/src/main/resources/json/schema/**' + - 'openmetadata-spec/pom.xml' + - 'openmetadata-spec/src/**' - 'openmetadata-sdk/**' + - 'openmetadata-shaded-deps/**' + - 'openmetadata-k8s-operator/**' + - 'openmetadata-mcp/**' - 'common/**' - 'pom.xml' + - 'Makefile' - 'bootstrap/**' + - '.github/scripts/classify_test_outcome.py' + - '.github/workflows/integration-tests-mysql-elasticsearch.yml' - integration-tests-mysql-elasticsearch: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.backend == 'true' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + + integration-test-build: + name: Build Integration Test Runtime needs: changes runs-on: ubuntu-latest - timeout-minutes: 90 + timeout-minutes: 60 if: ${{ needs.changes.outputs.backend == 'true' }} steps: - - name: Free Disk Space (Ubuntu) - uses: jlumbroso/free-disk-space@main - with: - tool-cache: true - android: true - dotnet: true - haskell: true - large-packages: true - docker-images: false - swap-storage: true - - name: Wait for the labeler uses: lewagon/wait-on-check-action@v1.7.0 if: ${{ github.event_name == 'pull_request_target' }} @@ -97,15 +108,118 @@ jobs: github-token: '${{ secrets.GITHUB_TOKEN }}' valid-labels: 'safe to test' pull-request-number: '${{ github.event.pull_request.number }}' - disable-reviews: true # To not auto approve changes + disable-reviews: true + + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + + - name: Cache Maven dependencies + uses: actions/cache@v4 + with: + path: ~/.m2 + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Build and Bundle Integration Test Runtime + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SOURCE_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + run: | + project_version="$(mvn --quiet --non-recursive help:evaluate \ + -Dexpression=project.version -DforceStdout -Dstyle.color=never)" + if [[ ! "$project_version" =~ ^[A-Za-z0-9][A-Za-z0-9._+-]*$ ]]; then + echo "Invalid Maven project version: $project_version" + exit 1 + fi + + project_repository="$HOME/.m2/repository/org/open-metadata" + if [[ -d "$project_repository" ]]; then + find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -prune -exec rm -rf -- {} + + fi + + mvn -DskipTests -DskipITs -Dspring-boot.repackage.skip=true \ + clean install -pl :openmetadata-integration-tests -am + + staging="$RUNNER_TEMP/java-it-reactor-repository" + bundle="$RUNNER_TEMP/java-it-build" + mkdir -p "$staging/org/open-metadata" "$bundle" + version_directory_count=0 + while IFS= read -r -d '' version_directory; do + artifact_id="$(basename "$(dirname "$version_directory")")" + mkdir -p "$staging/org/open-metadata/$artifact_id" + cp -a "$version_directory" "$staging/org/open-metadata/$artifact_id/" + version_directory_count=$((version_directory_count + 1)) + done < <(find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -print0) + + if (( version_directory_count == 0 )); then + echo "The Maven build did not install any reactor artifacts." + exit 1 + fi + + find "$staging" -type f -name '*-boot.jar' -delete + tar -C "$staging" -czf "$bundle/reactor-repository.tar.gz" org + ( + cd "$bundle" + sha256sum reactor-repository.tar.gz > reactor-repository.sha256 + ) + printf '%s\n' "$project_version" > "$bundle/project-version.txt" + printf '%s\n' "$SOURCE_SHA" > "$bundle/source-sha.txt" + du -h "$bundle/reactor-repository.tar.gz" | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Upload Integration Test Runtime + uses: actions/upload-artifact@v4 + with: + name: java-it-build-mysql-elasticsearch-${{ github.run_id }} + overwrite: true + path: ${{ runner.temp }}/java-it-build + if-no-files-found: error + retention-days: 1 + compression-level: 0 + + integration-test-lanes: + name: Integration Test Lane (${{ matrix.lane.name }}) + needs: [changes, integration-test-build] + runs-on: ubuntu-latest + timeout-minutes: 90 + if: ${{ needs.changes.outputs.backend == 'true' }} + strategy: + fail-fast: false + matrix: + lane: + - name: parallel + - name: global-state + - name: multi-node + - name: retry-queue + steps: + - name: Free Disk Space (Ubuntu) + uses: jlumbroso/free-disk-space@main + with: + tool-cache: true + android: true + dotnet: true + haskell: true + large-packages: true + docker-images: false + swap-storage: true + # The required build job verifies `safe to test` before this fan-out can run. - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Cache Maven dependencies - id: cache-output uses: actions/cache@v4 with: path: ~/.m2 @@ -113,10 +227,6 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - # Run unconditionally. The previous `if: steps.cache-output.outputs.exit-code == 0` was a - # bug — `actions/cache@v4` exposes `cache-hit` (boolean) and `cache-primary-key`, never - # `exit-code`. The expression always evaluated to false and the steps never ran. Maven - # then ran against whatever JDK the runner happened to ship with, masking the issue. - name: Set up JDK 21 uses: actions/setup-java@v4 with: @@ -127,36 +237,204 @@ jobs: run: | sudo apt-get update sudo apt-get install -y unixodbc-dev python3-venv librdkafka-dev gcc libsasl2-dev build-essential libssl-dev libffi-dev \ - librdkafka-dev unixodbc-dev libevent-dev jq + libevent-dev jq sudo make install_antlr_cli - - name: Build for Integration Tests (MySQL + Elasticsearch) - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: mvn -DskipTests clean install -pl :openmetadata-integration-tests -am + - name: Download Integration Test Runtime + uses: actions/download-artifact@v4 + with: + name: java-it-build-mysql-elasticsearch-${{ github.run_id }} + path: ${{ runner.temp }}/java-it-build - - name: Free build artifacts + - name: Restore Integration Test Runtime run: | - rm -rf openmetadata-service/target/lib openmetadata-service/target/classes - rm -rf openmetadata-spec/target openmetadata-sdk/target common/target - rm -rf openmetadata-shaded-deps/*/target - df -h / + bundle="$RUNNER_TEMP/java-it-build" + ( + cd "$bundle" + sha256sum --check reactor-repository.sha256 + ) + + project_version="$(<"$bundle/project-version.txt")" + source_sha="$(<"$bundle/source-sha.txt")" + if [[ ! "$project_version" =~ ^[A-Za-z0-9][A-Za-z0-9._+-]*$ ]]; then + echo "Invalid Maven project version: $project_version" + exit 1 + fi + if [[ "$(git rev-parse HEAD)" != "$source_sha" ]]; then + echo "The build artifact does not match the checked-out commit." + exit 1 + fi + + project_repository="$HOME/.m2/repository/org/open-metadata" + if [[ -d "$project_repository" ]]; then + find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -prune -exec rm -rf -- {} + + fi + mkdir -p "$HOME/.m2/repository" + tar -C "$HOME/.m2/repository" -xzf "$bundle/reactor-repository.tar.gz" + + test -s "$project_repository/platform/$project_version/platform-$project_version.pom" + test -s "$project_repository/openmetadata-service/$project_version/openmetadata-service-$project_version.jar" - name: Run Integration Tests (MySQL + Elasticsearch) + id: integration-tests env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: mvn verify -pl :openmetadata-integration-tests -Pmysql-elasticsearch + IT_LANE: ${{ matrix.lane.name }} + IT_PARALLELISM: '4' + IT_MAX_POOL_SIZE: '16' + run: | + { + echo "### Java integration configuration" + echo "- Profile: mysql-elasticsearch" + echo "- Lane: ${IT_LANE}" + echo "- Parallel workers: ${IT_PARALLELISM}" + echo "- Compensation-thread ceiling: ${IT_MAX_POOL_SIZE}" + echo "- Runner processors: $(nproc)" + } | tee -a "$GITHUB_STEP_SUMMARY" + + diagnostics="openmetadata-integration-tests/target/ci-diagnostics" + mkdir -p "$diagnostics" + maven_log="$diagnostics/maven.log" + set +e + timeout --signal=TERM --kill-after=60s 65m \ + mvn --no-snapshot-updates verify -pl :openmetadata-integration-tests -Pmysql-elasticsearch \ + -DintegrationTests.lane="${IT_LANE}" \ + -DintegrationTests.parallelStrategy=fixed \ + -DintegrationTests.parallelism="${IT_PARALLELISM}" \ + -DintegrationTests.maxPoolSize="${IT_MAX_POOL_SIZE}" \ + 2>&1 | tee "$maven_log" + pipeline_status=("${PIPESTATUS[@]}") + exit_code="${pipeline_status[0]}" + if (( exit_code == 0 && pipeline_status[1] != 0 )); then + exit_code="${pipeline_status[1]}" + fi + set -e + + max_log_bytes=20971520 + log_bytes="$(stat --format=%s "$maven_log")" + if (( log_bytes > max_log_bytes )); then + tail -c "$max_log_bytes" "$maven_log" > "${maven_log}.tail" + mv "${maven_log}.tail" "$maven_log" + fi + echo "exit_code=${exit_code}" >> "$GITHUB_OUTPUT" + exit "$exit_code" + + - name: Capture Integration Test Diagnostics + if: ${{ always() }} + continue-on-error: true + env: + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + run: | + diagnostics="openmetadata-integration-tests/target/ci-diagnostics" + mkdir -p "$diagnostics" + { + date -u + uname -a + java -version + echo "processors=$(nproc)" + df -h + free -h + docker system df + docker ps -a --no-trunc + } > "$diagnostics/environment.txt" 2>&1 + + capture_container_logs=false + if [ "$TEST_STEP_OUTCOME" != "success" ]; then + capture_container_logs=true + elif ! find openmetadata-integration-tests/target/failsafe-reports \ + -name 'TEST-*.xml' -print -quit 2>/dev/null | grep -q .; then + capture_container_logs=true + fi + + if [ "$capture_container_logs" = "true" ]; then + while IFS= read -r container; do + [[ -n "$container" ]] || continue + name=$(docker inspect --format '{{.Name}}' "$container" | tr -cd '[:alnum:]_.-') + docker logs --timestamps --since 30m --tail 10000 "$container" 2>&1 \ + | tail -c 10485760 > "$diagnostics/docker-${name}.log" || true + done < <(docker ps -aq) + fi + + - name: Classify Integration Test Outcome + if: ${{ always() }} + env: + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + TEST_EXIT_CODE: ${{ steps.integration-tests.outputs.exit_code }} + TEST_PROFILE: mysql-elasticsearch + TEST_LANE: ${{ matrix.lane.name }} + run: | + python3 .github/scripts/classify_test_outcome.py \ + --step-outcome "$TEST_STEP_OUTCOME" \ + --exit-code "$TEST_EXIT_CODE" \ + --report-glob 'openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml' \ + --diagnostic-glob 'openmetadata-integration-tests/target/ci-diagnostics/**/*' \ + --diagnostic-glob 'openmetadata-integration-tests/target/failsafe-reports/*.dump*' \ + --diagnostic-glob 'openmetadata-integration-tests/target/failsafe-reports/*.txt' \ + --output openmetadata-integration-tests/target/ci-diagnostics/outcome.json + + - name: Upload Integration Test Diagnostics + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: java-it-mysql-elasticsearch-${{ matrix.lane.name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + openmetadata-integration-tests/target/ci-diagnostics + openmetadata-integration-tests/target/failsafe-reports/*.dump* + openmetadata-integration-tests/target/failsafe-reports/*.txt + if-no-files-found: warn + retention-days: 7 + + - name: Upload Integration Test Reports + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: java-it-reports-mysql-elasticsearch-${{ matrix.lane.name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml + if-no-files-found: ignore + retention-days: 7 - name: Clean Up + if: ${{ always() }} + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" - name: Publish Test Report if: ${{ always() }} - uses: scacap/action-surefire-report@v1 + continue-on-error: true + uses: ScalableCapital/action-surefire-report@v2 with: github_token: ${{ secrets.GITHUB_TOKEN }} - fail_on_test_failures: true + check_name: Integration Test Report (mysql-elasticsearch, ${{ matrix.lane.name }}) + fail_on_test_failures: false + fail_if_no_tests: false report_paths: 'openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml' + + integration-tests-mysql-elasticsearch: + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'integration-tests-mysql-elasticsearch (ignored label)' || 'integration-tests-mysql-elasticsearch' }} + needs: [changes, integration-test-build, integration-test-lanes] + runs-on: ubuntu-latest + timeout-minutes: 5 + if: ${{ always() && !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} + steps: + - name: Verify Maven Integration Test Lanes + env: + CHANGES_RESULT: ${{ needs.changes.result }} + BACKEND_CHANGED: ${{ needs.changes.outputs.backend }} + BUILD_RESULT: ${{ needs.integration-test-build.result }} + LANES_RESULT: ${{ needs.integration-test-lanes.result }} + run: | + if [[ "$CHANGES_RESULT" == "success" && "$BACKEND_CHANGED" != "true" ]]; then + echo "No backend integration-test paths changed." + exit 0 + fi + + if [[ "$CHANGES_RESULT" != "success" || "$BUILD_RESULT" != "success" || "$LANES_RESULT" != "success" ]]; then + echo "Java integration jobs did not complete successfully: changes=${CHANGES_RESULT}, build=${BUILD_RESULT}, lanes=${LANES_RESULT}" + exit 1 + fi diff --git a/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml b/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml index 3973e12a33d5..a571ea166ea5 100644 --- a/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml +++ b/.github/workflows/integration-tests-postgres-elasticsearch-redis.yml @@ -32,11 +32,18 @@ on: paths: - "openmetadata-service/**" - "openmetadata-integration-tests/**" - - "openmetadata-spec/src/main/resources/json/schema/**" + - "openmetadata-spec/pom.xml" + - "openmetadata-spec/src/**" - "openmetadata-sdk/**" + - "openmetadata-shaded-deps/**" + - "openmetadata-k8s-operator/**" + - "openmetadata-mcp/**" - "common/**" - "pom.xml" + - "Makefile" - "bootstrap/**" + - ".github/scripts/classify_test_outcome.py" + - ".github/workflows/integration-tests-postgres-elasticsearch-redis.yml" # `pull_request_target` is intentional and required so the workflow runs against PRs from # forks (which `pull_request` cannot for security reasons). The `safe to test` label gate # below is what makes this safe — see security note in the file header. @@ -45,6 +52,7 @@ on: permissions: contents: read + pull-requests: read checks: write concurrency: @@ -65,7 +73,7 @@ jobs: outputs: backend: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.backend }} steps: - - uses: dorny/paths-filter@v3 + - uses: dorny/paths-filter@v4 id: filter if: ${{ github.event_name == 'pull_request_target' }} with: @@ -73,29 +81,32 @@ jobs: backend: - 'openmetadata-service/**' - 'openmetadata-integration-tests/**' - - 'openmetadata-spec/src/main/resources/json/schema/**' + - 'openmetadata-spec/pom.xml' + - 'openmetadata-spec/src/**' - 'openmetadata-sdk/**' + - 'openmetadata-shaded-deps/**' + - 'openmetadata-k8s-operator/**' + - 'openmetadata-mcp/**' - 'common/**' - 'pom.xml' + - 'Makefile' - 'bootstrap/**' + - '.github/scripts/classify_test_outcome.py' + - '.github/workflows/integration-tests-postgres-elasticsearch-redis.yml' - integration-tests-postgres-elasticsearch-redis: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.backend == 'true' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + + integration-test-build: + name: Build Integration Test Runtime needs: changes runs-on: ubuntu-latest - timeout-minutes: 90 + timeout-minutes: 60 if: ${{ needs.changes.outputs.backend == 'true' }} steps: - - name: Free Disk Space (Ubuntu) - uses: jlumbroso/free-disk-space@main - with: - tool-cache: true - android: true - dotnet: true - haskell: true - large-packages: true - docker-images: false - swap-storage: true - - name: Wait for the labeler uses: lewagon/wait-on-check-action@v1.7.0 if: ${{ github.event_name == 'pull_request_target' }} @@ -112,21 +123,120 @@ jobs: github-token: '${{ secrets.GITHUB_TOKEN }}' valid-labels: 'safe to test' pull-request-number: '${{ github.event.pull_request.number }}' - disable-reviews: true # To not auto approve changes + disable-reviews: true # SECURITY: this step checks out PR-controlled code while the workflow runs with - # `pull_request_target` privileges (secrets access). The `Verify PR labels` step above - # gates this — the workflow halts before we get here unless a maintainer has applied - # the `safe to test` label. CodeQL flags the pattern; the label gate is the accepted - # mitigation, mirroring how every other integration-tests-*.yml workflow in this repo - # handles fork PRs. + # `pull_request_target` privileges. The label verification above must succeed first. + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + + - name: Cache Maven dependencies + uses: actions/cache@v4 + with: + path: ~/.m2 + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Build and Bundle Integration Test Runtime + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SOURCE_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + run: | + project_version="$(mvn --quiet --non-recursive help:evaluate \ + -Dexpression=project.version -DforceStdout -Dstyle.color=never)" + if [[ ! "$project_version" =~ ^[A-Za-z0-9][A-Za-z0-9._+-]*$ ]]; then + echo "Invalid Maven project version: $project_version" + exit 1 + fi + + project_repository="$HOME/.m2/repository/org/open-metadata" + if [[ -d "$project_repository" ]]; then + find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -prune -exec rm -rf -- {} + + fi + + mvn -DskipTests -DskipITs -Dspring-boot.repackage.skip=true \ + clean install -pl :openmetadata-integration-tests -am + + staging="$RUNNER_TEMP/java-it-reactor-repository" + bundle="$RUNNER_TEMP/java-it-build" + mkdir -p "$staging/org/open-metadata" "$bundle" + version_directory_count=0 + while IFS= read -r -d '' version_directory; do + artifact_id="$(basename "$(dirname "$version_directory")")" + mkdir -p "$staging/org/open-metadata/$artifact_id" + cp -a "$version_directory" "$staging/org/open-metadata/$artifact_id/" + version_directory_count=$((version_directory_count + 1)) + done < <(find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -print0) + + if (( version_directory_count == 0 )); then + echo "The Maven build did not install any reactor artifacts." + exit 1 + fi + + find "$staging" -type f -name '*-boot.jar' -delete + tar -C "$staging" -czf "$bundle/reactor-repository.tar.gz" org + ( + cd "$bundle" + sha256sum reactor-repository.tar.gz > reactor-repository.sha256 + ) + printf '%s\n' "$project_version" > "$bundle/project-version.txt" + printf '%s\n' "$SOURCE_SHA" > "$bundle/source-sha.txt" + du -h "$bundle/reactor-repository.tar.gz" | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Upload Integration Test Runtime + uses: actions/upload-artifact@v4 + with: + name: java-it-build-postgres-elasticsearch-redis-${{ github.run_id }} + overwrite: true + path: ${{ runner.temp }}/java-it-build + if-no-files-found: error + retention-days: 1 + compression-level: 0 + + integration-test-lanes: + name: Integration Test Lane (${{ matrix.lane.name }}) + needs: [changes, integration-test-build] + runs-on: ubuntu-latest + timeout-minutes: 90 + if: ${{ needs.changes.outputs.backend == 'true' }} + strategy: + fail-fast: false + matrix: + lane: + - name: parallel + - name: global-state + - name: multi-node + - name: retry-queue + steps: + - name: Free Disk Space (Ubuntu) + uses: jlumbroso/free-disk-space@main + with: + tool-cache: true + android: true + dotnet: true + haskell: true + large-packages: true + docker-images: false + swap-storage: true + + # The required build job verifies `safe to test` before this fan-out can run. - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Cache Maven dependencies - id: cache-output uses: actions/cache@v4 with: path: ~/.m2 @@ -134,10 +244,6 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - # Run unconditionally. The previous `if: steps.cache-output.outputs.exit-code == 0` was a - # bug — `actions/cache@v4` exposes `cache-hit` (boolean) and `cache-primary-key`, never - # `exit-code`. The expression always evaluated to false and the steps never ran. Maven - # then ran against whatever JDK the runner happened to ship with, masking the issue. - name: Set up JDK 21 uses: actions/setup-java@v4 with: @@ -148,36 +254,204 @@ jobs: run: | sudo apt-get update sudo apt-get install -y unixodbc-dev python3-venv librdkafka-dev gcc libsasl2-dev build-essential libssl-dev libffi-dev \ - librdkafka-dev unixodbc-dev libevent-dev jq + libevent-dev jq sudo make install_antlr_cli - - name: Build for Integration Tests (PostgreSQL + Elasticsearch + Redis) - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: mvn -DskipTests clean install -pl :openmetadata-integration-tests -am + - name: Download Integration Test Runtime + uses: actions/download-artifact@v4 + with: + name: java-it-build-postgres-elasticsearch-redis-${{ github.run_id }} + path: ${{ runner.temp }}/java-it-build - - name: Free build artifacts + - name: Restore Integration Test Runtime run: | - rm -rf openmetadata-service/target/lib openmetadata-service/target/classes - rm -rf openmetadata-spec/target openmetadata-sdk/target common/target - rm -rf openmetadata-shaded-deps/*/target - df -h / + bundle="$RUNNER_TEMP/java-it-build" + ( + cd "$bundle" + sha256sum --check reactor-repository.sha256 + ) + + project_version="$(<"$bundle/project-version.txt")" + source_sha="$(<"$bundle/source-sha.txt")" + if [[ ! "$project_version" =~ ^[A-Za-z0-9][A-Za-z0-9._+-]*$ ]]; then + echo "Invalid Maven project version: $project_version" + exit 1 + fi + if [[ "$(git rev-parse HEAD)" != "$source_sha" ]]; then + echo "The build artifact does not match the checked-out commit." + exit 1 + fi + + project_repository="$HOME/.m2/repository/org/open-metadata" + if [[ -d "$project_repository" ]]; then + find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -prune -exec rm -rf -- {} + + fi + mkdir -p "$HOME/.m2/repository" + tar -C "$HOME/.m2/repository" -xzf "$bundle/reactor-repository.tar.gz" + + test -s "$project_repository/platform/$project_version/platform-$project_version.pom" + test -s "$project_repository/openmetadata-service/$project_version/openmetadata-service-$project_version.jar" - name: Run Integration Tests (PostgreSQL + Elasticsearch + Redis) + id: integration-tests env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: mvn verify -pl :openmetadata-integration-tests -Pcache-tests + IT_LANE: ${{ matrix.lane.name }} + IT_PARALLELISM: '4' + IT_MAX_POOL_SIZE: '16' + run: | + { + echo "### Java integration configuration" + echo "- Profile: cache-tests" + echo "- Lane: ${IT_LANE}" + echo "- Parallel workers: ${IT_PARALLELISM}" + echo "- Compensation-thread ceiling: ${IT_MAX_POOL_SIZE}" + echo "- Runner processors: $(nproc)" + } | tee -a "$GITHUB_STEP_SUMMARY" + + diagnostics="openmetadata-integration-tests/target/ci-diagnostics" + mkdir -p "$diagnostics" + maven_log="$diagnostics/maven.log" + set +e + timeout --signal=TERM --kill-after=60s 65m \ + mvn --no-snapshot-updates verify -pl :openmetadata-integration-tests -Pcache-tests \ + -DintegrationTests.lane="${IT_LANE}" \ + -DintegrationTests.parallelStrategy=fixed \ + -DintegrationTests.parallelism="${IT_PARALLELISM}" \ + -DintegrationTests.maxPoolSize="${IT_MAX_POOL_SIZE}" \ + 2>&1 | tee "$maven_log" + pipeline_status=("${PIPESTATUS[@]}") + exit_code="${pipeline_status[0]}" + if (( exit_code == 0 && pipeline_status[1] != 0 )); then + exit_code="${pipeline_status[1]}" + fi + set -e + + max_log_bytes=20971520 + log_bytes="$(stat --format=%s "$maven_log")" + if (( log_bytes > max_log_bytes )); then + tail -c "$max_log_bytes" "$maven_log" > "${maven_log}.tail" + mv "${maven_log}.tail" "$maven_log" + fi + echo "exit_code=${exit_code}" >> "$GITHUB_OUTPUT" + exit "$exit_code" + + - name: Capture Integration Test Diagnostics + if: ${{ always() }} + continue-on-error: true + env: + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + run: | + diagnostics="openmetadata-integration-tests/target/ci-diagnostics" + mkdir -p "$diagnostics" + { + date -u + uname -a + java -version + echo "processors=$(nproc)" + df -h + free -h + docker system df + docker ps -a --no-trunc + } > "$diagnostics/environment.txt" 2>&1 + + capture_container_logs=false + if [ "$TEST_STEP_OUTCOME" != "success" ]; then + capture_container_logs=true + elif ! find openmetadata-integration-tests/target/failsafe-reports \ + -name 'TEST-*.xml' -print -quit 2>/dev/null | grep -q .; then + capture_container_logs=true + fi + + if [ "$capture_container_logs" = "true" ]; then + while IFS= read -r container; do + [[ -n "$container" ]] || continue + name=$(docker inspect --format '{{.Name}}' "$container" | tr -cd '[:alnum:]_.-') + docker logs --timestamps --since 30m --tail 10000 "$container" 2>&1 \ + | tail -c 10485760 > "$diagnostics/docker-${name}.log" || true + done < <(docker ps -aq) + fi + + - name: Classify Integration Test Outcome + if: ${{ always() }} + env: + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + TEST_EXIT_CODE: ${{ steps.integration-tests.outputs.exit_code }} + TEST_PROFILE: cache-tests + TEST_LANE: ${{ matrix.lane.name }} + run: | + python3 .github/scripts/classify_test_outcome.py \ + --step-outcome "$TEST_STEP_OUTCOME" \ + --exit-code "$TEST_EXIT_CODE" \ + --report-glob 'openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml' \ + --diagnostic-glob 'openmetadata-integration-tests/target/ci-diagnostics/**/*' \ + --diagnostic-glob 'openmetadata-integration-tests/target/failsafe-reports/*.dump*' \ + --diagnostic-glob 'openmetadata-integration-tests/target/failsafe-reports/*.txt' \ + --output openmetadata-integration-tests/target/ci-diagnostics/outcome.json + + - name: Upload Integration Test Diagnostics + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: java-it-postgres-elasticsearch-redis-${{ matrix.lane.name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + openmetadata-integration-tests/target/ci-diagnostics + openmetadata-integration-tests/target/failsafe-reports/*.dump* + openmetadata-integration-tests/target/failsafe-reports/*.txt + if-no-files-found: warn + retention-days: 7 + + - name: Upload Integration Test Reports + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: java-it-reports-postgres-elasticsearch-redis-${{ matrix.lane.name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml + if-no-files-found: ignore + retention-days: 7 - name: Clean Up + if: ${{ always() }} + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" - name: Publish Test Report if: ${{ always() }} - uses: scacap/action-surefire-report@v1 + continue-on-error: true + uses: ScalableCapital/action-surefire-report@v2 with: github_token: ${{ secrets.GITHUB_TOKEN }} - fail_on_test_failures: true + check_name: Integration Test Report (postgres-elasticsearch-redis, ${{ matrix.lane.name }}) + fail_on_test_failures: false + fail_if_no_tests: false report_paths: 'openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml' + + integration-tests-postgres-elasticsearch-redis: + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'integration-tests-postgres-elasticsearch-redis (ignored label)' || 'integration-tests-postgres-elasticsearch-redis' }} + needs: [changes, integration-test-build, integration-test-lanes] + runs-on: ubuntu-latest + timeout-minutes: 5 + if: ${{ always() && !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} + steps: + - name: Verify Maven Integration Test Lanes + env: + CHANGES_RESULT: ${{ needs.changes.result }} + BACKEND_CHANGED: ${{ needs.changes.outputs.backend }} + BUILD_RESULT: ${{ needs.integration-test-build.result }} + LANES_RESULT: ${{ needs.integration-test-lanes.result }} + run: | + if [[ "$CHANGES_RESULT" == "success" && "$BACKEND_CHANGED" != "true" ]]; then + echo "No backend integration-test paths changed." + exit 0 + fi + + if [[ "$CHANGES_RESULT" != "success" || "$BUILD_RESULT" != "success" || "$LANES_RESULT" != "success" ]]; then + echo "Java integration jobs did not complete successfully: changes=${CHANGES_RESULT}, build=${BUILD_RESULT}, lanes=${LANES_RESULT}" + exit 1 + fi diff --git a/.github/workflows/integration-tests-postgres-opensearch.yml b/.github/workflows/integration-tests-postgres-opensearch.yml index 98d632efe96a..8843f968d049 100644 --- a/.github/workflows/integration-tests-postgres-opensearch.yml +++ b/.github/workflows/integration-tests-postgres-opensearch.yml @@ -20,16 +20,24 @@ on: paths: - "openmetadata-service/**" - "openmetadata-integration-tests/**" - - "openmetadata-spec/src/main/resources/json/schema/**" + - "openmetadata-spec/pom.xml" + - "openmetadata-spec/src/**" - "openmetadata-sdk/**" + - "openmetadata-shaded-deps/**" + - "openmetadata-k8s-operator/**" + - "openmetadata-mcp/**" - "common/**" - "pom.xml" + - "Makefile" - "bootstrap/**" + - ".github/scripts/classify_test_outcome.py" + - ".github/workflows/integration-tests-postgres-opensearch.yml" pull_request_target: types: [labeled, opened, synchronize, reopened, ready_for_review] permissions: contents: read + pull-requests: read checks: write concurrency: @@ -50,7 +58,7 @@ jobs: outputs: backend: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.backend }} steps: - - uses: dorny/paths-filter@v3 + - uses: dorny/paths-filter@v4 id: filter if: ${{ github.event_name == 'pull_request_target' }} with: @@ -58,29 +66,32 @@ jobs: backend: - 'openmetadata-service/**' - 'openmetadata-integration-tests/**' - - 'openmetadata-spec/src/main/resources/json/schema/**' + - 'openmetadata-spec/pom.xml' + - 'openmetadata-spec/src/**' - 'openmetadata-sdk/**' + - 'openmetadata-shaded-deps/**' + - 'openmetadata-k8s-operator/**' + - 'openmetadata-mcp/**' - 'common/**' - 'pom.xml' + - 'Makefile' - 'bootstrap/**' + - '.github/scripts/classify_test_outcome.py' + - '.github/workflows/integration-tests-postgres-opensearch.yml' - integration-tests-postgres-opensearch: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.backend == 'true' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + + integration-test-build: + name: Build Integration Test Runtime needs: changes runs-on: ubuntu-latest - timeout-minutes: 90 + timeout-minutes: 60 if: ${{ needs.changes.outputs.backend == 'true' }} steps: - - name: Free Disk Space (Ubuntu) - uses: jlumbroso/free-disk-space@main - with: - tool-cache: true - android: true - dotnet: true - haskell: true - large-packages: true - docker-images: false - swap-storage: true - - name: Wait for the labeler uses: lewagon/wait-on-check-action@v1.7.0 if: ${{ github.event_name == 'pull_request_target' }} @@ -97,15 +108,118 @@ jobs: github-token: '${{ secrets.GITHUB_TOKEN }}' valid-labels: 'safe to test' pull-request-number: '${{ github.event.pull_request.number }}' - disable-reviews: true # To not auto approve changes + disable-reviews: true + + - name: Checkout + uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + + - name: Cache Maven dependencies + uses: actions/cache@v4 + with: + path: ~/.m2 + key: ${{ runner.os }}-maven-${{ hashFiles('**/pom.xml') }} + restore-keys: | + ${{ runner.os }}-maven- + + - name: Set up JDK 21 + uses: actions/setup-java@v4 + with: + java-version: '21' + distribution: 'temurin' + + - name: Build and Bundle Integration Test Runtime + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + SOURCE_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + run: | + project_version="$(mvn --quiet --non-recursive help:evaluate \ + -Dexpression=project.version -DforceStdout -Dstyle.color=never)" + if [[ ! "$project_version" =~ ^[A-Za-z0-9][A-Za-z0-9._+-]*$ ]]; then + echo "Invalid Maven project version: $project_version" + exit 1 + fi + + project_repository="$HOME/.m2/repository/org/open-metadata" + if [[ -d "$project_repository" ]]; then + find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -prune -exec rm -rf -- {} + + fi + + mvn -DskipTests -DskipITs -Dspring-boot.repackage.skip=true \ + clean install -pl :openmetadata-integration-tests -am + + staging="$RUNNER_TEMP/java-it-reactor-repository" + bundle="$RUNNER_TEMP/java-it-build" + mkdir -p "$staging/org/open-metadata" "$bundle" + version_directory_count=0 + while IFS= read -r -d '' version_directory; do + artifact_id="$(basename "$(dirname "$version_directory")")" + mkdir -p "$staging/org/open-metadata/$artifact_id" + cp -a "$version_directory" "$staging/org/open-metadata/$artifact_id/" + version_directory_count=$((version_directory_count + 1)) + done < <(find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -print0) + + if (( version_directory_count == 0 )); then + echo "The Maven build did not install any reactor artifacts." + exit 1 + fi + + find "$staging" -type f -name '*-boot.jar' -delete + tar -C "$staging" -czf "$bundle/reactor-repository.tar.gz" org + ( + cd "$bundle" + sha256sum reactor-repository.tar.gz > reactor-repository.sha256 + ) + printf '%s\n' "$project_version" > "$bundle/project-version.txt" + printf '%s\n' "$SOURCE_SHA" > "$bundle/source-sha.txt" + du -h "$bundle/reactor-repository.tar.gz" | tee -a "$GITHUB_STEP_SUMMARY" + + - name: Upload Integration Test Runtime + uses: actions/upload-artifact@v4 + with: + name: java-it-build-postgres-opensearch-${{ github.run_id }} + overwrite: true + path: ${{ runner.temp }}/java-it-build + if-no-files-found: error + retention-days: 1 + compression-level: 0 + + integration-test-lanes: + name: Integration Test Lane (${{ matrix.lane.name }}) + needs: [changes, integration-test-build] + runs-on: ubuntu-latest + timeout-minutes: 90 + if: ${{ needs.changes.outputs.backend == 'true' }} + strategy: + fail-fast: false + matrix: + lane: + - name: parallel + - name: global-state + - name: multi-node + - name: retry-queue + steps: + - name: Free Disk Space (Ubuntu) + uses: jlumbroso/free-disk-space@main + with: + tool-cache: true + android: true + dotnet: true + haskell: true + large-packages: true + docker-images: false + swap-storage: true + # The required build job verifies `safe to test` before this fan-out can run. - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Cache Maven dependencies - id: cache-output uses: actions/cache@v4 with: path: ~/.m2 @@ -113,10 +227,6 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - # Run unconditionally. The previous `if: steps.cache-output.outputs.exit-code == 0` was a - # bug — `actions/cache@v4` exposes `cache-hit` (boolean) and `cache-primary-key`, never - # `exit-code`. The expression always evaluated to false and the steps never ran. Maven - # then ran against whatever JDK the runner happened to ship with, masking the issue. - name: Set up JDK 21 uses: actions/setup-java@v4 with: @@ -127,36 +237,204 @@ jobs: run: | sudo apt-get update sudo apt-get install -y unixodbc-dev python3-venv librdkafka-dev gcc libsasl2-dev build-essential libssl-dev libffi-dev \ - librdkafka-dev unixodbc-dev libevent-dev jq + libevent-dev jq sudo make install_antlr_cli - - name: Build for Integration Tests (PostgreSQL + OpenSearch) - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: mvn -DskipTests clean install -pl :openmetadata-integration-tests -am + - name: Download Integration Test Runtime + uses: actions/download-artifact@v4 + with: + name: java-it-build-postgres-opensearch-${{ github.run_id }} + path: ${{ runner.temp }}/java-it-build - - name: Free build artifacts + - name: Restore Integration Test Runtime run: | - rm -rf openmetadata-service/target/lib openmetadata-service/target/classes - rm -rf openmetadata-spec/target openmetadata-sdk/target common/target - rm -rf openmetadata-shaded-deps/*/target - df -h / + bundle="$RUNNER_TEMP/java-it-build" + ( + cd "$bundle" + sha256sum --check reactor-repository.sha256 + ) + + project_version="$(<"$bundle/project-version.txt")" + source_sha="$(<"$bundle/source-sha.txt")" + if [[ ! "$project_version" =~ ^[A-Za-z0-9][A-Za-z0-9._+-]*$ ]]; then + echo "Invalid Maven project version: $project_version" + exit 1 + fi + if [[ "$(git rev-parse HEAD)" != "$source_sha" ]]; then + echo "The build artifact does not match the checked-out commit." + exit 1 + fi + + project_repository="$HOME/.m2/repository/org/open-metadata" + if [[ -d "$project_repository" ]]; then + find "$project_repository" -mindepth 2 -maxdepth 2 -type d \ + -name "$project_version" -prune -exec rm -rf -- {} + + fi + mkdir -p "$HOME/.m2/repository" + tar -C "$HOME/.m2/repository" -xzf "$bundle/reactor-repository.tar.gz" + + test -s "$project_repository/platform/$project_version/platform-$project_version.pom" + test -s "$project_repository/openmetadata-service/$project_version/openmetadata-service-$project_version.jar" - name: Run Integration Tests (PostgreSQL + OpenSearch) + id: integration-tests env: GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - run: mvn verify -pl :openmetadata-integration-tests -Ppostgres-opensearch + IT_LANE: ${{ matrix.lane.name }} + IT_PARALLELISM: '4' + IT_MAX_POOL_SIZE: '16' + run: | + { + echo "### Java integration configuration" + echo "- Profile: postgres-opensearch" + echo "- Lane: ${IT_LANE}" + echo "- Parallel workers: ${IT_PARALLELISM}" + echo "- Compensation-thread ceiling: ${IT_MAX_POOL_SIZE}" + echo "- Runner processors: $(nproc)" + } | tee -a "$GITHUB_STEP_SUMMARY" + + diagnostics="openmetadata-integration-tests/target/ci-diagnostics" + mkdir -p "$diagnostics" + maven_log="$diagnostics/maven.log" + set +e + timeout --signal=TERM --kill-after=60s 65m \ + mvn --no-snapshot-updates verify -pl :openmetadata-integration-tests -Ppostgres-opensearch \ + -DintegrationTests.lane="${IT_LANE}" \ + -DintegrationTests.parallelStrategy=fixed \ + -DintegrationTests.parallelism="${IT_PARALLELISM}" \ + -DintegrationTests.maxPoolSize="${IT_MAX_POOL_SIZE}" \ + 2>&1 | tee "$maven_log" + pipeline_status=("${PIPESTATUS[@]}") + exit_code="${pipeline_status[0]}" + if (( exit_code == 0 && pipeline_status[1] != 0 )); then + exit_code="${pipeline_status[1]}" + fi + set -e + + max_log_bytes=20971520 + log_bytes="$(stat --format=%s "$maven_log")" + if (( log_bytes > max_log_bytes )); then + tail -c "$max_log_bytes" "$maven_log" > "${maven_log}.tail" + mv "${maven_log}.tail" "$maven_log" + fi + echo "exit_code=${exit_code}" >> "$GITHUB_OUTPUT" + exit "$exit_code" + + - name: Capture Integration Test Diagnostics + if: ${{ always() }} + continue-on-error: true + env: + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + run: | + diagnostics="openmetadata-integration-tests/target/ci-diagnostics" + mkdir -p "$diagnostics" + { + date -u + uname -a + java -version + echo "processors=$(nproc)" + df -h + free -h + docker system df + docker ps -a --no-trunc + } > "$diagnostics/environment.txt" 2>&1 + + capture_container_logs=false + if [ "$TEST_STEP_OUTCOME" != "success" ]; then + capture_container_logs=true + elif ! find openmetadata-integration-tests/target/failsafe-reports \ + -name 'TEST-*.xml' -print -quit 2>/dev/null | grep -q .; then + capture_container_logs=true + fi + + if [ "$capture_container_logs" = "true" ]; then + while IFS= read -r container; do + [[ -n "$container" ]] || continue + name=$(docker inspect --format '{{.Name}}' "$container" | tr -cd '[:alnum:]_.-') + docker logs --timestamps --since 30m --tail 10000 "$container" 2>&1 \ + | tail -c 10485760 > "$diagnostics/docker-${name}.log" || true + done < <(docker ps -aq) + fi + + - name: Classify Integration Test Outcome + if: ${{ always() }} + env: + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + TEST_EXIT_CODE: ${{ steps.integration-tests.outputs.exit_code }} + TEST_PROFILE: postgres-opensearch + TEST_LANE: ${{ matrix.lane.name }} + run: | + python3 .github/scripts/classify_test_outcome.py \ + --step-outcome "$TEST_STEP_OUTCOME" \ + --exit-code "$TEST_EXIT_CODE" \ + --report-glob 'openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml' \ + --diagnostic-glob 'openmetadata-integration-tests/target/ci-diagnostics/**/*' \ + --diagnostic-glob 'openmetadata-integration-tests/target/failsafe-reports/*.dump*' \ + --diagnostic-glob 'openmetadata-integration-tests/target/failsafe-reports/*.txt' \ + --output openmetadata-integration-tests/target/ci-diagnostics/outcome.json + + - name: Upload Integration Test Diagnostics + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: java-it-postgres-opensearch-${{ matrix.lane.name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: | + openmetadata-integration-tests/target/ci-diagnostics + openmetadata-integration-tests/target/failsafe-reports/*.dump* + openmetadata-integration-tests/target/failsafe-reports/*.txt + if-no-files-found: warn + retention-days: 7 + + - name: Upload Integration Test Reports + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: java-it-reports-postgres-opensearch-${{ matrix.lane.name }}-${{ github.run_id }}-${{ github.run_attempt }} + path: openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml + if-no-files-found: ignore + retention-days: 7 - name: Clean Up + if: ${{ always() }} + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" - name: Publish Test Report if: ${{ always() }} - uses: scacap/action-surefire-report@v1 + continue-on-error: true + uses: ScalableCapital/action-surefire-report@v2 with: github_token: ${{ secrets.GITHUB_TOKEN }} - fail_on_test_failures: true + check_name: Integration Test Report (postgres-opensearch, ${{ matrix.lane.name }}) + fail_on_test_failures: false + fail_if_no_tests: false report_paths: 'openmetadata-integration-tests/target/failsafe-reports/TEST-*.xml' + + integration-tests-postgres-opensearch: + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'integration-tests-postgres-opensearch (ignored label)' || 'integration-tests-postgres-opensearch' }} + needs: [changes, integration-test-build, integration-test-lanes] + runs-on: ubuntu-latest + timeout-minutes: 5 + if: ${{ always() && !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} + steps: + - name: Verify Maven Integration Test Lanes + env: + CHANGES_RESULT: ${{ needs.changes.result }} + BACKEND_CHANGED: ${{ needs.changes.outputs.backend }} + BUILD_RESULT: ${{ needs.integration-test-build.result }} + LANES_RESULT: ${{ needs.integration-test-lanes.result }} + run: | + if [[ "$CHANGES_RESULT" == "success" && "$BACKEND_CHANGED" != "true" ]]; then + echo "No backend integration-test paths changed." + exit 0 + fi + + if [[ "$CHANGES_RESULT" != "success" || "$BUILD_RESULT" != "success" || "$LANES_RESULT" != "success" ]]; then + echo "Java integration jobs did not complete successfully: changes=${CHANGES_RESULT}, build=${BUILD_RESULT}, lanes=${LANES_RESULT}" + exit 1 + fi diff --git a/.github/workflows/java-playwright-external.yml b/.github/workflows/java-playwright-external.yml index 9179e240823f..7657f7bf4b49 100644 --- a/.github/workflows/java-playwright-external.yml +++ b/.github/workflows/java-playwright-external.yml @@ -95,6 +95,31 @@ on: required: false type: string default: '8' + simpleReindexTables: + description: 'Table fixtures for the simple reindex UI scenario' + required: false + type: string + default: '5000' + simpleReindexTopics: + description: 'Topic fixtures for the simple reindex UI scenario' + required: false + type: string + default: '1500' + simpleReindexDashboards: + description: 'Dashboard fixtures for the simple reindex UI scenario' + required: false + type: string + default: '1500' + simpleReindexPipelines: + description: 'Pipeline fixtures for the simple reindex UI scenario' + required: false + type: string + default: '2000' + searchAvailableTables: + description: 'Table fixtures for the search availability UI scenario' + required: false + type: string + default: '5000' permissions: contents: read @@ -202,17 +227,24 @@ jobs: OM_EXTERNAL_USERNAME: ${{ secrets.OM_EXTERNAL_USERNAME }} OM_EXTERNAL_PASSWORD: ${{ secrets.OM_EXTERNAL_PASSWORD }} PW_VIDEO: 'true' + SIMPLE_REINDEX_TABLES: ${{ github.event.inputs.simpleReindexTables || '5000' }} + SIMPLE_REINDEX_TOPICS: ${{ github.event.inputs.simpleReindexTopics || '1500' }} + SIMPLE_REINDEX_DASHBOARDS: ${{ github.event.inputs.simpleReindexDashboards || '1500' }} + SIMPLE_REINDEX_PIPELINES: ${{ github.event.inputs.simpleReindexPipelines || '2000' }} + SEARCH_AVAILABLE_TABLES: ${{ github.event.inputs.searchAvailableTables || '5000' }} + IT_TEST: ${{ github.event.inputs.itTest }} run: | - STRESS_PROPS="-Djpw.simpleReindex.tables=${{ github.event.inputs.simpleReindexTables || '5000' }} \ - -Djpw.simpleReindex.topics=${{ github.event.inputs.simpleReindexTopics || '1500' }} \ - -Djpw.simpleReindex.dashboards=${{ github.event.inputs.simpleReindexDashboards || '1500' }} \ - -Djpw.simpleReindex.pipelines=${{ github.event.inputs.simpleReindexPipelines || '2000' }} \ - -Djpw.searchAvailable.tables=${{ github.event.inputs.searchAvailableTables || '5000' }}" - IT_TEST_PROP="" - if [ -n "${{ github.event.inputs.itTest }}" ]; then - IT_TEST_PROP="-Dit.test=${{ github.event.inputs.itTest }}" + test_args=( + "-Djpw.simpleReindex.tables=${SIMPLE_REINDEX_TABLES}" + "-Djpw.simpleReindex.topics=${SIMPLE_REINDEX_TOPICS}" + "-Djpw.simpleReindex.dashboards=${SIMPLE_REINDEX_DASHBOARDS}" + "-Djpw.simpleReindex.pipelines=${SIMPLE_REINDEX_PIPELINES}" + "-Djpw.searchAvailable.tables=${SEARCH_AVAILABLE_TABLES}" + ) + if [ -n "$IT_TEST" ]; then + test_args+=("-Dit.test=${IT_TEST}") fi - mvn verify -P ui-it -pl :openmetadata-integration-tests $STRESS_PROPS $IT_TEST_PROP \ + mvn verify -P ui-it -pl :openmetadata-integration-tests "${test_args[@]}" \ -Djpw.loader.maxWorkers=${{ github.event.inputs.entityLoaderMaxWorkers || '8' }} \ -Djpw.reindex.timeoutMin=${{ github.event.inputs.reindexTimeoutMin || '60' }} \ -Dui.it.excludedGroups="sso-bootstrap,search-direct" @@ -222,6 +254,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: playwright-traces-external-${{ github.run_id }} + overwrite: true path: openmetadata-integration-tests/target/playwright-traces if-no-files-found: ignore retention-days: 14 @@ -231,6 +264,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: playwright-videos-external-${{ github.run_id }} + overwrite: true path: openmetadata-integration-tests/target/playwright-videos if-no-files-found: ignore retention-days: 14 @@ -240,6 +274,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: failsafe-reports-ui-it-external-${{ github.run_id }} + overwrite: true path: openmetadata-integration-tests/target/failsafe-reports if-no-files-found: ignore retention-days: 14 @@ -371,6 +406,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: failsafe-reports-search-it-external-${{ github.run_id }} + overwrite: true path: openmetadata-integration-tests/target/failsafe-reports if-no-files-found: ignore retention-days: 14 @@ -510,6 +546,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: scale-metrics-${{ matrix.seed }}-${{ github.run_id }} + overwrite: true path: openmetadata-integration-tests/target/benchmark if-no-files-found: ignore retention-days: 30 @@ -519,6 +556,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: failsafe-reports-scale-${{ matrix.seed }}-${{ github.run_id }} + overwrite: true path: openmetadata-integration-tests/target/failsafe-reports if-no-files-found: ignore retention-days: 14 diff --git a/.github/workflows/mysql-nightly-e2e.yml b/.github/workflows/mysql-nightly-e2e.yml index 8770442b39cb..e30b20d94c34 100644 --- a/.github/workflows/mysql-nightly-e2e.yml +++ b/.github/workflows/mysql-nightly-e2e.yml @@ -90,7 +90,7 @@ jobs: - name: Run Playwright tests working-directory: openmetadata-ui/src/main/resources/ui/ run: | - if [ "${{ matrix.shardIndex }}" -eq "1" ]; then + if [ "${{ matrix.shardIndex }}" = "1" ]; then echo "🔹 Running DataAssetRules-only tests on shard 1" # The testMatch pattern ensures only DataAssetRules*.spec.ts files run @@ -99,7 +99,7 @@ jobs: --project=DataAssetRulesEnabled \ --project=DataAssetRulesDisabled - elif [ "${{ matrix.shardIndex }}" -eq "2" ]; then + elif [ "${{ matrix.shardIndex }}" = "2" ]; then echo "🔹 Running search relevance tests on shard 2" npx playwright test \ @@ -124,7 +124,6 @@ jobs: PLAYWRIGHT_SNOWFLAKE_ACCOUNT: ${{ secrets.TEST_SNOWFLAKE_ACCOUNT }} PLAYWRIGHT_SNOWFLAKE_DATABASE: ${{ secrets.TEST_SNOWFLAKE_DATABASE }} PLAYWRIGHT_SNOWFLAKE_WAREHOUSE: ${{ secrets.TEST_SNOWFLAKE_WAREHOUSE }} - PLAYWRIGHT_PROJECT_ID: ${{ steps.cypress-project-id.outputs.CYPRESS_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY: ${{ secrets.TEST_BQ_PRIVATE_KEY }} PLAYWRIGHT_BQ_PROJECT_ID: ${{ secrets.PLAYWRIGHT_BQ_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY_ID: ${{ secrets.TEST_BQ_PRIVATE_KEY_ID }} @@ -173,6 +172,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: blob-report-${{ matrix.shardIndex }} + overwrite: true path: openmetadata-ui/src/main/resources/ui/blob-report retention-days: 1 @@ -181,20 +181,23 @@ jobs: uses: actions/upload-artifact@v4 with: name: playwright-HTML-report-${{ matrix.shardIndex }} + overwrite: true path: openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report retention-days: 1 compression-level: 9 - name: Clean Up + if: always() + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" merge-reports: needs: pw-ci-mysql-branch runs-on: ubuntu-latest - if: ${{ !failure() || !cancelled() }} + if: ${{ always() }} env: # Recommended: pass the GitHub token lets this action correctly # determine the unique run id necessary to re-run the checks @@ -223,6 +226,28 @@ jobs: run: | npx playwright merge-reports --reporter json ./blob-reports > merged_tests_results.json + - name: Evaluate zero-retry gate in shadow mode + if: always() + continue-on-error: true + env: + MATRIX_OUTCOME: ${{ needs.pw-ci-mysql-branch.result }} + run: | + python3 .github/scripts/classify_playwright_outcome.py \ + --report-glob 'openmetadata-ui/src/main/resources/ui/merged_tests_results.json' \ + --matrix-outcome "$MATRIX_OUTCOME" \ + --profile mysql-nightly \ + --output "$RUNNER_TEMP/playwright-shadow-gate/outcome.json" + + - name: Upload Playwright shadow-gate ledger + if: always() + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: playwright-shadow-gate-mysql-nightly-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/playwright-shadow-gate/outcome.json + if-no-files-found: warn + retention-days: 30 + - name: Generate Slack Notification if: ${{ inputs.send_slack_notification }} working-directory: openmetadata-ui/src/main/resources/ui/ diff --git a/.github/workflows/playwright-integration-tests-mysql.yml b/.github/workflows/playwright-integration-tests-mysql.yml index ba6bb131bb4b..ed915aa0a806 100644 --- a/.github/workflows/playwright-integration-tests-mysql.yml +++ b/.github/workflows/playwright-integration-tests-mysql.yml @@ -23,6 +23,7 @@ concurrency: jobs: playwright-mysql: + name: ${{ github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'playwright-mysql (ignored label)' || 'playwright-mysql' }} runs-on: ubuntu-latest if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} strategy: @@ -31,6 +32,12 @@ jobs: browser-type: ["chromium"] environment: test steps: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -60,7 +67,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.event.pull_request.merge_commit_sha }} - name: Cache Maven Dependencies id: cache-output uses: actions/cache@v4 @@ -70,11 +77,9 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - name: Get yarn cache directory path - if: steps.cache-output.outputs.exit-code == 0 id: yarn-cache-dir-path - run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT + run: echo "dir=$(yarn cache dir)" >> "$GITHUB_OUTPUT" - uses: actions/cache@v4 - if: steps.yarn-cache-dir-path.outputs.exit-code == 0 id: yarn-cache with: path: ${{ steps.yarn-cache-dir-path.outputs.dir }} @@ -101,12 +106,15 @@ jobs: make run_e2e_tests - uses: actions/upload-artifact@v4 if: always() + continue-on-error: true with: name: playwright-artifacts path: ingestion/tests/e2e/artifacts/ retention-days: 1 - name: Clean Up + if: always() + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" diff --git a/.github/workflows/playwright-integration-tests-postgres.yml b/.github/workflows/playwright-integration-tests-postgres.yml index c034e44cf280..456823fcdf6a 100644 --- a/.github/workflows/playwright-integration-tests-postgres.yml +++ b/.github/workflows/playwright-integration-tests-postgres.yml @@ -23,6 +23,7 @@ concurrency: jobs: playwright-postgresql: + name: ${{ github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'playwright-postgresql (ignored label)' || 'playwright-postgresql' }} runs-on: ubuntu-latest if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} strategy: @@ -31,6 +32,12 @@ jobs: browser-type: ["chromium"] environment: test steps: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -60,7 +67,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.event.pull_request.merge_commit_sha }} - name: Cache Maven Dependencies id: cache-output uses: actions/cache@v4 @@ -70,11 +77,9 @@ jobs: restore-keys: | ${{ runner.os }}-maven- - name: Get yarn cache directory path - if: steps.cache-output.outputs.exit-code == 0 id: yarn-cache-dir-path - run: echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT + run: echo "dir=$(yarn cache dir)" >> "$GITHUB_OUTPUT" - uses: actions/cache@v4 - if: steps.yarn-cache-dir-path.outputs.exit-code == 0 id: yarn-cache with: path: ${{ steps.yarn-cache-dir-path.outputs.dir }} @@ -101,12 +106,15 @@ jobs: make run_e2e_tests - uses: actions/upload-artifact@v4 if: always() + continue-on-error: true with: name: playwright-artifacts path: ingestion/tests/e2e/artifacts/ retention-days: 1 - name: Clean Up + if: always() + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" diff --git a/.github/workflows/playwright-knowledge-graph-postgresql-e2e.yml b/.github/workflows/playwright-knowledge-graph-postgresql-e2e.yml index 732c8f24996b..a820a8c9ecc8 100644 --- a/.github/workflows/playwright-knowledge-graph-postgresql-e2e.yml +++ b/.github/workflows/playwright-knowledge-graph-postgresql-e2e.yml @@ -58,7 +58,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + ref: ${{ github.sha }} - name: Setup JDK 21 uses: actions/setup-java@v4 @@ -84,6 +84,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: openmetadata-build + overwrite: true path: openmetadata-dist/target/openmetadata-*.tar.gz retention-days: 1 @@ -107,7 +108,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + ref: ${{ github.sha }} - name: Prepare temporary directory for Maven build artifact run: mkdir -p "${{ runner.temp }}/openmetadata-build-artifact" @@ -209,16 +210,22 @@ jobs: PLAYWRIGHT_S3_STORAGE_END_POINT_URL: ${{ secrets.TEST_S3_STORAGE_END_POINT_URL }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - uses: actions/upload-artifact@v4 - if: ${{ !cancelled() }} + - name: Upload Playwright diagnostics + uses: actions/upload-artifact@v4 + if: failure() || cancelled() + continue-on-error: true with: name: playwright-knowledge-graph-report - path: openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report + path: | + openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report + openmetadata-ui/src/main/resources/ui/playwright/output/test-results retention-days: 5 + if-no-files-found: ignore - name: Clean Up if: always() + continue-on-error: true run: | docker compose -f docker/development/docker-compose-postgres.yml -f docker/development/docker-compose-fuseki.yml down --remove-orphans || true docker compose -f docker/development/docker-compose-postgres.yml down --remove-orphans || true - sudo rm -rf ${PWD}/docker/development/docker-volume + sudo rm -rf "${PWD}/docker/development/docker-volume" diff --git a/.github/workflows/playwright-mysql-e2e.yml b/.github/workflows/playwright-mysql-e2e.yml index 146fa42dfb65..c79576697fb3 100644 --- a/.github/workflows/playwright-mysql-e2e.yml +++ b/.github/workflows/playwright-mysql-e2e.yml @@ -40,11 +40,13 @@ concurrency: jobs: playwright-ci-mysql: + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'playwright-ci-mysql (ignored label)' || 'playwright-ci-mysql' }} runs-on: ubuntu-latest if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} environment: test permissions: contents: read + pull-requests: read id-token: write # Required for GitHub OIDC (Flakiness.io reporter) env: # Playwright logs the admin user in many times (performAdminLogin per test, parallel @@ -58,6 +60,12 @@ jobs: shardIndex: [1, 2] shardTotal: [2] steps: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -89,7 +97,20 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + + - name: Detect ingestion-only changes + id: changes + if: ${{ github.event_name == 'pull_request_target' }} + uses: dorny/paths-filter@v4 + with: + predicate-quantifier: 'every' + filters: | + ingestion: + - 'ingestion/**' + non-ingestion: + - '**' + - '!ingestion/**' - name: Cache Maven Dependencies id: cache-output @@ -120,7 +141,7 @@ jobs: - name: Run Playwright tests working-directory: openmetadata-ui/src/main/resources/ui/ run: | - if [[ "${{ contains(github.event.pull_request.changed_files, 'ingestion/') }}" == "true" ]]; then + if [[ "${{ steps.changes.outputs.ingestion }}" == "true" && "${{ steps.changes.outputs.non-ingestion }}" != "true" ]]; then npx playwright test --grep @ingestion --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} else npx playwright test --shard=${{ matrix.shardIndex }}/${{ matrix.shardTotal }} @@ -133,7 +154,6 @@ jobs: PLAYWRIGHT_SNOWFLAKE_DATABASE: ${{ secrets.TEST_SNOWFLAKE_DATABASE }} PLAYWRIGHT_SNOWFLAKE_WAREHOUSE: ${{ secrets.TEST_SNOWFLAKE_WAREHOUSE }} PLAYWRIGHT_SNOWFLAKE_PASSPHRASE: ${{ secrets.TEST_SNOWFLAKE_PASSPHRASE }} - PLAYWRIGHT_PROJECT_ID: ${{ steps.cypress-project-id.outputs.CYPRESS_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY: ${{ secrets.TEST_BQ_PRIVATE_KEY }} PLAYWRIGHT_BQ_PROJECT_ID: ${{ secrets.PLAYWRIGHT_BQ_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY_ID: ${{ secrets.TEST_BQ_PRIVATE_KEY_ID }} @@ -177,15 +197,47 @@ jobs: # determine the unique run id necessary to re-run the checks GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - uses: actions/upload-artifact@v4 - if: ${{ !cancelled() }} + - name: Upload Playwright HTML report + uses: actions/upload-artifact@v4 + if: always() + continue-on-error: true with: name: playwright-report--${{ matrix.shardIndex }} - path: openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report + path: | + openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report + openmetadata-ui/src/main/resources/ui/playwright/output/test-results + retention-days: 5 + if-no-files-found: ignore + + - name: Collect failure diagnostics + if: failure() || cancelled() + continue-on-error: true + run: | + DIAGNOSTICS_DIR="${RUNNER_TEMP}/playwright-ci-diagnostics" + mkdir -p "$DIAGNOSTICS_DIR" + df -h > "$DIAGNOSTICS_DIR/disk-usage.txt" 2>&1 || true + docker system df > "$DIAGNOSTICS_DIR/docker-disk-usage.txt" 2>&1 || true + if [ -f docker/development/docker-compose.yml ]; then + docker compose -f docker/development/docker-compose.yml ps --all \ + > "$DIAGNOSTICS_DIR/docker-compose-ps.txt" 2>&1 || true + docker compose -f docker/development/docker-compose.yml logs --no-color --tail 5000 \ + > "$DIAGNOSTICS_DIR/docker-compose.log" 2>&1 || true + fi + + - name: Upload failure diagnostics + uses: actions/upload-artifact@v4 + if: failure() || cancelled() + continue-on-error: true + with: + name: playwright-ci-diagnostics-mysql-${{ matrix.shardIndex }} + path: ${{ runner.temp }}/playwright-ci-diagnostics retention-days: 5 + if-no-files-found: ignore - name: Clean Up + if: always() + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" diff --git a/.github/workflows/playwright-ontology-rdf-postgresql-e2e.yml b/.github/workflows/playwright-ontology-rdf-postgresql-e2e.yml index fe9c48f3b13a..b404ed7e03c8 100644 --- a/.github/workflows/playwright-ontology-rdf-postgresql-e2e.yml +++ b/.github/workflows/playwright-ontology-rdf-postgresql-e2e.yml @@ -53,7 +53,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + ref: ${{ github.sha }} - name: Setup JDK 21 uses: actions/setup-java@v4 @@ -79,6 +79,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: openmetadata-build + overwrite: true path: openmetadata-dist/target/openmetadata-*.tar.gz retention-days: 1 @@ -102,7 +103,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + ref: ${{ github.sha }} - name: Prepare temporary directory for Maven build artifact run: mkdir -p "${{ runner.temp }}/openmetadata-build-artifact" @@ -160,16 +161,22 @@ jobs: PLAYWRIGHT_IS_OSS: true GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - uses: actions/upload-artifact@v4 - if: ${{ !cancelled() }} + - name: Upload Playwright diagnostics + uses: actions/upload-artifact@v4 + if: failure() || cancelled() + continue-on-error: true with: name: playwright-ontology-rdf-report - path: openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report + path: | + openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report + openmetadata-ui/src/main/resources/ui/playwright/output/test-results retention-days: 5 + if-no-files-found: ignore - name: Clean Up if: always() + continue-on-error: true run: | docker compose -f docker/development/docker-compose-postgres.yml -f docker/development/docker-compose-fuseki.yml down --remove-orphans || true docker compose -f docker/development/docker-compose-postgres.yml down --remove-orphans || true - sudo rm -rf ${PWD}/docker/development/docker-volume + sudo rm -rf "${PWD}/docker/development/docker-volume" diff --git a/.github/workflows/playwright-postgresql-e2e.yml b/.github/workflows/playwright-postgresql-e2e.yml index 49c0a48924cc..6f50026d49ac 100644 --- a/.github/workflows/playwright-postgresql-e2e.yml +++ b/.github/workflows/playwright-postgresql-e2e.yml @@ -30,6 +30,7 @@ on: permissions: contents: read + pull-requests: read concurrency: group: playwright-ci-pr-postgresql-${{ github.event.pull_request.number || github.run_id }} @@ -44,6 +45,7 @@ jobs: steps: - uses: dorny/paths-filter@v4 id: filter + if: ${{ github.event_name == 'pull_request_target' }} with: filters: | e2e: @@ -51,10 +53,13 @@ jobs: - 'openmetadata-ui/**' - 'openmetadata-spec/**' - 'openmetadata-integration-tests/**' + - 'openmetadata-dist/**' - 'ingestion/**' - 'bootstrap/**' - 'conf/**' - 'docker/development/**' + - 'docker/run_local_docker.sh' + - 'docker/run_local_docker_common.sh' - 'openmetadata-clients/**' - 'openmetadata-airflow-apis/**' - 'openmetadata-mcp/**' @@ -66,6 +71,9 @@ jobs: - 'openspec/**' - 'pom.xml' - 'Makefile' + - '.github/actions/setup-openmetadata-test-environment/**' + - '.github/scripts/classify_playwright_outcome.py' + - '.github/workflows/playwright-postgresql-e2e.yml' docker-compose: - 'docker/development/docker-compose.yml' - 'docker/development/docker-compose-postgres.yml' @@ -79,6 +87,12 @@ jobs: needs.check-changes.outputs.e2e == 'true' || needs.check-changes.outputs.docker-compose == 'true') && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') steps: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + - name: Wait for the labeler uses: lewagon/wait-on-check-action@v1.7.0 if: ${{ github.event_name == 'pull_request_target' }} @@ -100,7 +114,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Setup JDK 21 uses: actions/setup-java@v4 @@ -126,6 +140,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: openmetadata-build + overwrite: true path: openmetadata-dist/target/openmetadata-*.tar.gz retention-days: 1 @@ -180,14 +195,18 @@ jobs: SPEC_COUNT=$(echo "$SPEC_FILES" | wc -w) if [ "$SPEC_COUNT" -gt 0 ] && [ "$ALL_COUNT" -eq "$SPEC_COUNT" ]; then - echo "spec_only_mode=true" >> "$GITHUB_OUTPUT" - echo "changed_specs=$SPEC_FILES" >> "$GITHUB_OUTPUT" - echo "matrix=$SPEC_MATRIX" >> "$GITHUB_OUTPUT" + { + echo "spec_only_mode=true" + echo "changed_specs=$SPEC_FILES" + echo "matrix=$SPEC_MATRIX" + } >> "$GITHUB_OUTPUT" echo "Spec-only mode: ${SPEC_COUNT} spec(s) changed" else - echo "spec_only_mode=false" >> "$GITHUB_OUTPUT" - echo "changed_specs=" >> "$GITHUB_OUTPUT" - echo "matrix=$FULL_MATRIX" >> "$GITHUB_OUTPUT" + { + echo "spec_only_mode=false" + echo "changed_specs=" + echo "matrix=$FULL_MATRIX" + } >> "$GITHUB_OUTPUT" echo "Full suite mode (total=${ALL_COUNT}, runnable-specs=${SPEC_COUNT})" fi @@ -210,6 +229,7 @@ jobs: matrix: ${{ fromJSON(needs.detect-changes.outputs.matrix) }} steps: - name: Free Disk Space (Ubuntu) + id: free-disk uses: jlumbroso/free-disk-space@main with: tool-cache: false @@ -221,17 +241,20 @@ jobs: docker-images: false - name: Checkout + id: checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Download Maven build artifact + id: download-build uses: actions/download-artifact@v4 with: name: openmetadata-build path: openmetadata-dist/target - name: Setup Openmetadata Test Environment + id: setup-environment uses: ./.github/actions/setup-openmetadata-test-environment with: python-version: "3.10" @@ -239,14 +262,17 @@ jobs: ingestion_dependency: "all" - name: Setup Node.js + id: setup-node uses: actions/setup-node@v4 with: node-version-file: "openmetadata-ui/src/main/resources/ui/.nvmrc" - name: Install dependencies + id: install-dependencies working-directory: openmetadata-ui/src/main/resources/ui/ run: yarn --ignore-scripts --frozen-lockfile - name: Install Playwright Browsers + id: install-browsers run: npx playwright@1.57.0 install chromium --with-deps - name: Run Playwright tests id: run-tests @@ -286,9 +312,10 @@ jobs: [ -z "$PROJECT_ARGS" ] && PROJECT_ARGS="--project=chromium --project=Basic" + # shellcheck disable=SC2086 npx playwright test $PROJECT_ARGS $CHANGED_SPECS - elif [ "${{ matrix.shardIndex }}" -eq "1" ]; then + elif [ "${{ matrix.shardIndex }}" = "1" ]; then echo "🔹 Running DataAssetRules-only tests on shard 1" # The testMatch pattern ensures only DataAssetRules*.spec.ts files run @@ -298,9 +325,9 @@ jobs: --project=DataAssetRulesDisabled \ --project=Basic \ --project=SearchRBAC \ - --project=DomainIsolation \ + --project=DomainIsolation - elif [ "${{ matrix.shardIndex }}" -eq "2" ]; then + elif [ "${{ matrix.shardIndex }}" = "2" ]; then echo "🔹 Running search relevance tests on shard 2" npx playwright test \ @@ -328,7 +355,6 @@ jobs: PLAYWRIGHT_SNOWFLAKE_DATABASE: ${{ secrets.TEST_SNOWFLAKE_DATABASE }} PLAYWRIGHT_SNOWFLAKE_WAREHOUSE: ${{ secrets.TEST_SNOWFLAKE_WAREHOUSE }} PLAYWRIGHT_SNOWFLAKE_PASSPHRASE: ${{ secrets.TEST_SNOWFLAKE_PASSPHRASE }} - PLAYWRIGHT_PROJECT_ID: ${{ steps.cypress-project-id.outputs.CYPRESS_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY: ${{ secrets.TEST_BQ_PRIVATE_KEY }} PLAYWRIGHT_BQ_PROJECT_ID: ${{ secrets.PLAYWRIGHT_BQ_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY_ID: ${{ secrets.TEST_BQ_PRIVATE_KEY_ID }} @@ -372,87 +398,240 @@ jobs: # determine the unique run id necessary to re-run the checks GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - - uses: actions/upload-artifact@v4 - if: ${{ !cancelled() }} + - name: Record shard execution status + if: always() + env: + FREE_DISK_OUTCOME: ${{ steps.free-disk.outcome }} + CHECKOUT_OUTCOME: ${{ steps.checkout.outcome }} + DOWNLOAD_BUILD_OUTCOME: ${{ steps.download-build.outcome }} + SETUP_ENVIRONMENT_OUTCOME: ${{ steps.setup-environment.outcome }} + SETUP_NODE_OUTCOME: ${{ steps.setup-node.outcome }} + INSTALL_DEPENDENCIES_OUTCOME: ${{ steps.install-dependencies.outcome }} + INSTALL_BROWSERS_OUTCOME: ${{ steps.install-browsers.outcome }} + TEST_OUTCOME: ${{ steps.run-tests.outcome }} + run: | + STATUS_DIR="openmetadata-ui/src/main/resources/ui/playwright/output" + mkdir -p "$STATUS_DIR" + jq -n \ + --arg shard "${{ matrix.shardIndex }}" \ + --arg freeDisk "$FREE_DISK_OUTCOME" \ + --arg checkout "$CHECKOUT_OUTCOME" \ + --arg downloadBuild "$DOWNLOAD_BUILD_OUTCOME" \ + --arg setupEnvironment "$SETUP_ENVIRONMENT_OUTCOME" \ + --arg setupNode "$SETUP_NODE_OUTCOME" \ + --arg installDependencies "$INSTALL_DEPENDENCIES_OUTCOME" \ + --arg installBrowsers "$INSTALL_BROWSERS_OUTCOME" \ + --arg tests "$TEST_OUTCOME" \ + '{ + shard: $shard, + steps: { + freeDisk: $freeDisk, + checkout: $checkout, + downloadBuild: $downloadBuild, + setupEnvironment: $setupEnvironment, + setupNode: $setupNode, + installDependencies: $installDependencies, + installBrowsers: $installBrowsers, + tests: $tests + } + }' > "$STATUS_DIR/ci-status.json" + + - name: Upload Playwright HTML report + uses: actions/upload-artifact@v4 + if: always() + continue-on-error: true with: name: playwright-report-${{ matrix.shardIndex }} + overwrite: true path: openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report retention-days: 5 + if-no-files-found: ignore - name: Upload test results (screenshots, traces) uses: actions/upload-artifact@v4 - if: ${{ !cancelled() }} + if: always() + continue-on-error: true with: name: playwright-test-results-${{ matrix.shardIndex }} + overwrite: true path: openmetadata-ui/src/main/resources/ui/playwright/output/test-results retention-days: 5 + if-no-files-found: ignore - name: Upload results JSON for summary uses: actions/upload-artifact@v4 - if: ${{ !cancelled() }} + if: always() with: name: playwright-results-json-${{ matrix.shardIndex }} - path: openmetadata-ui/src/main/resources/ui/playwright/output/results.json + overwrite: true + path: | + openmetadata-ui/src/main/resources/ui/playwright/output/results.json + openmetadata-ui/src/main/resources/ui/playwright/output/ci-status.json retention-days: 1 if-no-files-found: ignore + - name: Collect failure diagnostics + if: failure() || cancelled() + continue-on-error: true + run: | + DIAGNOSTICS_DIR="${RUNNER_TEMP}/playwright-ci-diagnostics" + mkdir -p "$DIAGNOSTICS_DIR" + df -h > "$DIAGNOSTICS_DIR/disk-usage.txt" 2>&1 || true + docker system df > "$DIAGNOSTICS_DIR/docker-disk-usage.txt" 2>&1 || true + if [ -f docker/development/docker-compose-postgres.yml ]; then + docker compose -f docker/development/docker-compose-postgres.yml ps --all \ + > "$DIAGNOSTICS_DIR/docker-compose-ps.txt" 2>&1 || true + docker compose -f docker/development/docker-compose-postgres.yml logs --no-color --tail 5000 \ + > "$DIAGNOSTICS_DIR/docker-compose.log" 2>&1 || true + fi + + - name: Upload failure diagnostics + uses: actions/upload-artifact@v4 + if: failure() || cancelled() + continue-on-error: true + with: + name: playwright-ci-diagnostics-${{ matrix.shardIndex }} + path: ${{ runner.temp }}/playwright-ci-diagnostics + retention-days: 5 + if-no-files-found: ignore + - name: Clean Up + if: always() + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" playwright-summary: + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'playwright-summary (label ignored)' || 'playwright-summary' }} if: always() - needs: playwright-ci-postgresql + needs: [check-changes, build, detect-changes, playwright-ci-postgresql] runs-on: ubuntu-latest permissions: contents: read pull-requests: write # Posts the consolidated PR comment steps: + - name: Checkout trusted CI classifier + uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.base.sha || github.sha }} + persist-credentials: false + - name: Download all results JSON if: needs.playwright-ci-postgresql.result != 'skipped' uses: actions/download-artifact@v4 + continue-on-error: true with: pattern: playwright-results-json-* path: results + - name: Evaluate zero-retry gate in shadow mode + if: ${{ always() && needs.playwright-ci-postgresql.result != 'skipped' }} + continue-on-error: true + env: + EXPECTED_MATRIX: ${{ needs.detect-changes.outputs.matrix }} + MATRIX_OUTCOME: ${{ needs.playwright-ci-postgresql.result }} + SOURCE_SHA: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} + run: | + python3 .github/scripts/classify_playwright_outcome.py \ + --report-glob 'results/playwright-results-json-*/results.json' \ + --status-glob 'results/playwright-results-json-*/ci-status.json' \ + --matrix-outcome "$MATRIX_OUTCOME" \ + --expected-matrix-json "$EXPECTED_MATRIX" \ + --profile postgresql-pr \ + --source-sha "$SOURCE_SHA" \ + --output "$RUNNER_TEMP/playwright-shadow-gate/outcome.json" + + - name: Upload Playwright shadow-gate ledger + if: ${{ always() && needs.playwright-ci-postgresql.result != 'skipped' }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: playwright-shadow-gate-postgresql-pr-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/playwright-shadow-gate/outcome.json + if-no-files-found: warn + retention-days: 30 + - name: Post consolidated PR comment and gate on results + if: always() uses: actions/github-script@v7 + env: + CHECK_CHANGES_RESULT: ${{ needs.check-changes.result }} + BUILD_RESULT: ${{ needs.build.result }} + DETECT_CHANGES_RESULT: ${{ needs.detect-changes.result }} + PLAYWRIGHT_RESULT: ${{ needs.playwright-ci-postgresql.result }} + E2E_CHANGED: ${{ needs.check-changes.outputs.e2e }} + DOCKER_COMPOSE_CHANGED: ${{ needs.check-changes.outputs.docker-compose }} + EXPECTED_MATRIX: ${{ needs.detect-changes.outputs.matrix }} with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | - const upstreamResult = '${{ needs.playwright-ci-postgresql.result }}'; - if (upstreamResult === 'skipped') { - // Distinguish the two reasons build/playwright can be skipped: - // 1. A non-"safe to test" label was added — build skips intentionally for fork security. - // Tests will run once "safe to test" is applied or code is pushed. - // 2. No relevant paths changed — nothing to test. - const eventAction = context.payload.action; - const labelName = context.payload.label?.name ?? ''; - if (eventAction === 'labeled' && labelName !== 'safe to test') { - console.log(`Playwright E2E tests pending — label "${labelName}" added but only "safe to test" triggers E2E. Tests will run when "safe to test" is applied or code is pushed.`); - } else { - console.log('Playwright E2E tests not required for this PR (no relevant paths changed).'); - } + const fs = require('fs'); + const path = require('path'); + + const checkChangesResult = process.env.CHECK_CHANGES_RESULT; + const buildResult = process.env.BUILD_RESULT; + const detectChangesResult = process.env.DETECT_CHANGES_RESULT; + const upstreamResult = process.env.PLAYWRIGHT_RESULT; + const eventAction = context.payload.action; + const labelName = context.payload.label?.name ?? ''; + const isDraft = context.payload.pull_request?.draft === true; + const isNonTestLabelEvent = eventAction === 'labeled' && labelName !== 'safe to test'; + const testsRequired = context.eventName === 'merge_group' || + context.eventName === 'workflow_dispatch' || + process.env.E2E_CHANGED === 'true' || + process.env.DOCKER_COMPOSE_CHANGED === 'true'; + + if (isDraft) { + console.log('Playwright E2E tests are not required while the PR is a draft.'); return; } - if (upstreamResult === 'cancelled') { - core.setFailed('Playwright E2E tests were cancelled.'); + if (isNonTestLabelEvent) { + console.log(`Playwright E2E tests pending — label "${labelName}" added but only "safe to test" triggers E2E. Tests will run when "safe to test" is applied or code is pushed.`); + return; + } + if (checkChangesResult === 'success' && !testsRequired) { + console.log('Playwright E2E tests not required for this PR (no relevant paths changed).'); return; } - - const fs = require('fs'); - const path = require('path'); const runId = '${{ github.run_id }}'; const repo = context.repo; const prNumber = context.payload.pull_request?.number; - const artifactUrl = `https://github.com/${repo.owner}/${repo.repo}/actions/runs/${runId}`; const commentMarker = ''; + const infrastructureIssues = []; + const addInfrastructureIssue = issue => { + if (!infrastructureIssues.includes(issue)) infrastructureIssues.push(issue); + }; + + if (checkChangesResult !== 'success') { + addInfrastructureIssue(`Change detection finished with status \`${checkChangesResult}\`.`); + } + if (buildResult !== 'success') { + addInfrastructureIssue(`The build job finished with status \`${buildResult}\`.`); + } + if (detectChangesResult !== 'success') { + addInfrastructureIssue(`Shard detection finished with status \`${detectChangesResult}\`.`); + } + if (upstreamResult === 'cancelled') { + addInfrastructureIssue('The Playwright shard matrix was cancelled.'); + } else if (upstreamResult === 'skipped') { + addInfrastructureIssue('The Playwright shard matrix was unexpectedly skipped.'); + } + + let expectedShards = []; + try { + const matrix = JSON.parse(process.env.EXPECTED_MATRIX || '{}'); + expectedShards = (matrix.shardIndex || []).map(String); + if (expectedShards.length === 0) { + addInfrastructureIssue('No expected Playwright shards were declared.'); + } + } catch (error) { + addInfrastructureIssue(`The expected shard matrix was invalid: ${error.message}`); + } - // Collect results from all shards const shardResults = []; const resultsDir = 'results'; if (fs.existsSync(resultsDir)) { @@ -461,7 +640,13 @@ jobs: if (!fs.existsSync(jsonPath)) continue; const shardNum = dir.replace('playwright-results-json-', ''); - const report = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); + let report; + try { + report = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); + } catch (error) { + addInfrastructureIssue(`Shard ${shardNum} uploaded invalid results JSON: ${error.message}`); + continue; + } const allTests = []; function collectTests(suite, filePath) { @@ -488,6 +673,14 @@ jobs: collectTests(suite, ''); } + const knownStatuses = new Set(['expected', 'unexpected', 'flaky', 'skipped']); + const unknownStatuses = allTests.filter(test => !knownStatuses.has(test.status)); + if (allTests.length === 0) { + addInfrastructureIssue(`Shard ${shardNum} reported zero tests.`); + } + if (unknownStatuses.length > 0) { + addInfrastructureIssue(`Shard ${shardNum} reported ${unknownStatuses.length} test(s) with an unknown status.`); + } shardResults.push({ shard: shardNum, genuine: allTests.filter(t => t.status === 'unexpected'), @@ -498,21 +691,69 @@ jobs: } } - if (shardResults.length === 0) { - core.setFailed('No Playwright results found — shards may have been cancelled or failed to upload artifacts.'); - return; + const resultsByShard = new Map(shardResults.map(result => [result.shard, result])); + for (const shard of expectedShards) { + if (!resultsByShard.has(shard)) { + addInfrastructureIssue(`Shard ${shard} did not upload a usable Playwright results artifact.`); + } + } + for (const shard of resultsByShard.keys()) { + if (!expectedShards.includes(shard)) { + addInfrastructureIssue(`Unexpected shard ${shard} uploaded Playwright results.`); + } + } + + const statusByShard = new Map(); + if (fs.existsSync(resultsDir)) { + for (const dir of fs.readdirSync(resultsDir).sort()) { + const statusPath = path.join(resultsDir, dir, 'ci-status.json'); + if (!fs.existsSync(statusPath)) continue; + const shardNum = dir.replace('playwright-results-json-', ''); + try { + const status = JSON.parse(fs.readFileSync(statusPath, 'utf8')); + statusByShard.set(shardNum, status); + } catch (error) { + addInfrastructureIssue(`Shard ${shardNum} uploaded invalid execution status JSON: ${error.message}`); + } + } + } + + for (const shard of expectedShards) { + const status = statusByShard.get(shard); + if (!status) { + addInfrastructureIssue(`Shard ${shard} did not upload its execution status.`); + continue; + } + + const steps = status.steps || {}; + const setupFailure = Object.entries(steps).find( + ([name, outcome]) => name !== 'tests' && ['failure', 'cancelled'].includes(outcome) + ); + if (setupFailure) { + addInfrastructureIssue(`Shard ${shard} failed during \`${setupFailure[0]}\` setup.`); + } + + const shardResult = resultsByShard.get(shard); + const genuineFailures = shardResult?.genuine.length || 0; + if (steps.tests !== 'success' && !(steps.tests === 'failure' && genuineFailures > 0)) { + addInfrastructureIssue(`Shard ${shard} test execution finished with status \`${steps.tests || 'not-run'}\` without a reported test failure.`); + } } - // Aggregate totals const totalPassed = shardResults.reduce((s, r) => s + r.passed.length, 0); const totalFailed = shardResults.reduce((s, r) => s + r.genuine.length, 0); const totalFlaky = shardResults.reduce((s, r) => s + r.flaky.length, 0); const totalSkipped = shardResults.reduce((s, r) => s + r.skipped.length, 0); + if (upstreamResult === 'failure' && totalFailed === 0 && infrastructureIssues.length === 0) { + addInfrastructureIssue('The Playwright shard matrix failed outside a reported test failure.'); + } const lines = [commentMarker]; - if (totalFailed > 0) { - lines.push(`## 🔴 Playwright Results — ${totalFailed} failure(s)${totalFlaky > 0 ? `, ${totalFlaky} flaky` : ''}`); + if (totalFailed > 0 || infrastructureIssues.length > 0) { + const testFailureText = totalFailed > 0 ? `${totalFailed} test failure(s)` : ''; + const infrastructureText = infrastructureIssues.length > 0 ? `${infrastructureIssues.length} pipeline/setup failure(s)` : ''; + lines.push(`## 🔴 Playwright Results — ${[testFailureText, infrastructureText].filter(Boolean).join(', ')}`); } else if (totalFlaky > 0) { lines.push(`## 🟡 Playwright Results — all passed (${totalFlaky} flaky)`); } else { @@ -522,16 +763,26 @@ jobs: lines.push(`✅ ${totalPassed} passed · ❌ ${totalFailed} failed · 🟡 ${totalFlaky} flaky · ⏭️ ${totalSkipped} skipped`); lines.push(''); - // Per-shard summary table + if (infrastructureIssues.length > 0) { + lines.push('### Pipeline and setup failures'); + lines.push(''); + for (const issue of infrastructureIssues) lines.push(`- ${issue}`); + lines.push(''); + } + lines.push('| Shard | Passed | Failed | Flaky | Skipped |'); lines.push('|-------|--------|--------|-------|---------|'); - for (const r of shardResults) { + for (const shard of expectedShards) { + const r = resultsByShard.get(shard); + if (!r) { + lines.push(`| ⛔ Shard ${shard} | — | — | — | — |`); + continue; + } const status = r.genuine.length > 0 ? '🔴' : r.flaky.length > 0 ? '🟡' : '✅'; lines.push(`| ${status} Shard ${r.shard} | ${r.passed.length} | ${r.genuine.length} | ${r.flaky.length} | ${r.skipped.length} |`); } lines.push(''); - // Genuine failures detail const allGenuine = shardResults.flatMap(r => r.genuine.map(t => ({ ...t, shard: r.shard }))); if (allGenuine.length > 0) { lines.push('### Genuine Failures (failed on all attempts)'); @@ -552,7 +803,6 @@ jobs: } } - // Flaky tests const allFlaky = shardResults.flatMap(r => r.flaky.map(t => ({ ...t, shard: r.shard }))); if (allFlaky.length > 0) { lines.push(`
🟡 ${allFlaky.length} flaky test(s) (passed on retry)`); @@ -581,40 +831,47 @@ jobs: const body = lines.join('\n'); - // Post PR comment only for pull_request_target events + try { + await core.summary.addRaw(body).write(); + } catch (error) { + core.warning(`Could not write the Playwright job summary: ${error.message}`); + } + if (prNumber) { - let existingComment = null; - for await (const response of github.paginate.iterator( - github.rest.issues.listComments, { ...repo, issue_number: prNumber, per_page: 100 } - )) { - const found = response.data.find(c => - c.user?.login === 'github-actions[bot]' && c.body?.includes(commentMarker) - ); - if (found) { existingComment = found; break; } - } + try { + let existingComment = null; + for await (const response of github.paginate.iterator( + github.rest.issues.listComments, { ...repo, issue_number: prNumber, per_page: 100 } + )) { + const found = response.data.find(c => + c.user?.login === 'github-actions[bot]' && c.body?.includes(commentMarker) + ); + if (found) { existingComment = found; break; } + } - // Also clean up any old per-shard comments from previous runs - for await (const response of github.paginate.iterator( - github.rest.issues.listComments, { ...repo, issue_number: prNumber, per_page: 100 } - )) { - for (const c of response.data) { - if (c.user?.login === 'github-actions[bot]' && /Playwright Shard \d/.test(c.body || '') && !c.body?.includes(commentMarker)) { - await github.rest.issues.deleteComment({ ...repo, comment_id: c.id }); - console.log(`Deleted old per-shard comment ${c.id}`); + for await (const response of github.paginate.iterator( + github.rest.issues.listComments, { ...repo, issue_number: prNumber, per_page: 100 } + )) { + for (const c of response.data) { + if (c.user?.login === 'github-actions[bot]' && /Playwright Shard \d/.test(c.body || '') && !c.body?.includes(commentMarker)) { + await github.rest.issues.deleteComment({ ...repo, comment_id: c.id }); + console.log(`Deleted old per-shard comment ${c.id}`); + } } } - } - if (existingComment) { - await github.rest.issues.updateComment({ ...repo, comment_id: existingComment.id, body }); - } else { - await github.rest.issues.createComment({ ...repo, issue_number: prNumber, body }); + if (existingComment) { + await github.rest.issues.updateComment({ ...repo, comment_id: existingComment.id, body }); + } else { + await github.rest.issues.createComment({ ...repo, issue_number: prNumber, body }); + } + } catch (error) { + core.warning(`Could not publish the Playwright PR comment: ${error.message}`); } } - // Gate: fail the step (and therefore the job) when genuine test failures exist. - // This is the single source of truth — the same parsed results that drive the - // PR comment also determine whether playwright-summary passes or fails. - if (totalFailed > 0) { - core.setFailed(`${totalFailed} Playwright test(s) failed.`); + if (totalFailed > 0 || infrastructureIssues.length > 0) { + core.setFailed( + `${totalFailed} Playwright test failure(s); ${infrastructureIssues.length} pipeline/setup failure(s).` + ); } diff --git a/.github/workflows/playwright-sso-tests.yml b/.github/workflows/playwright-sso-tests.yml index cadc3c607a9b..7e78a4f0e006 100644 --- a/.github/workflows/playwright-sso-tests.yml +++ b/.github/workflows/playwright-sso-tests.yml @@ -46,6 +46,8 @@ on: - "docker/development/mock-oidc-provider/**" - "docker/development/docker-compose.yml" - "docker/development/.env.sso-test" + - ".github/actions/setup-openmetadata-test-environment/**" + - ".github/scripts/classify_playwright_outcome.py" - ".github/workflows/playwright-sso-tests.yml" workflow_dispatch: inputs: @@ -73,6 +75,7 @@ concurrency: jobs: sso-auth-tests: + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'sso-auth-tests (ignored label)' || 'sso-auth-tests' }} runs-on: ubuntu-latest if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} environment: test @@ -83,6 +86,12 @@ jobs: provider: ${{ github.event_name == 'pull_request_target' && fromJSON('["mock-oidc"]') || github.event.inputs.sso_provider && fromJSON(format('["{0}"]', github.event.inputs.sso_provider)) || fromJSON('["mock-oidc"]') }} steps: + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + - name: Free Disk Space (Ubuntu) uses: jlumbroso/free-disk-space@main with: @@ -115,7 +124,7 @@ jobs: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Cache Maven Dependencies id: cache-output @@ -133,15 +142,21 @@ jobs: docker compose --profile sso-test build mock-oidc-provider docker compose --profile sso-test up -d mock-oidc-provider echo "Waiting for mock OIDC provider to be healthy..." + provider_ready=false for i in $(seq 1 30); do if curl -sf http://localhost:9090/health > /dev/null 2>&1; then echo "Mock OIDC provider is ready" + provider_ready=true break fi echo "Waiting... ($i/30)" sleep 2 done - curl -sf http://localhost:9090/.well-known/openid-configuration || echo "WARNING: Discovery endpoint not ready" + if [ "$provider_ready" != "true" ]; then + echo "Mock OIDC provider did not become healthy within 60 seconds." + exit 1 + fi + curl -fsS http://localhost:9090/.well-known/openid-configuration - name: Setup Openmetadata Test Environment uses: ./.github/actions/setup-openmetadata-test-environment @@ -175,7 +190,8 @@ jobs: run: yarn --ignore-scripts --frozen-lockfile - name: Install Playwright Browsers - run: npx playwright@1.51.1 install chromium webkit --with-deps + working-directory: openmetadata-ui/src/main/resources/ui/ + run: yarn playwright install chromium webkit --with-deps - name: Run Mock OIDC Authentication Tests if: ${{ matrix.provider == 'mock-oidc' }} @@ -193,8 +209,8 @@ jobs: run: npx playwright test --config=playwright.sso.config.ts --workers=1 env: SSO_PROVIDER_TYPE: ${{ matrix.provider }} - SSO_USERNAME: ${{ secrets[format('{0}_SSO_USERNAME', upper(matrix.provider))] }} - SSO_PASSWORD: ${{ secrets[format('{0}_SSO_PASSWORD', upper(matrix.provider))] }} + SSO_USERNAME: ${{ matrix.provider == 'google' && secrets.GOOGLE_SSO_USERNAME || matrix.provider == 'okta' && secrets.OKTA_SSO_USERNAME || matrix.provider == 'azure' && secrets.AZURE_SSO_USERNAME || matrix.provider == 'auth0' && secrets.AUTH0_SSO_USERNAME || matrix.provider == 'saml' && secrets.SAML_SSO_USERNAME || matrix.provider == 'cognito' && secrets.COGNITO_SSO_USERNAME || '' }} + SSO_PASSWORD: ${{ matrix.provider == 'google' && secrets.GOOGLE_SSO_PASSWORD || matrix.provider == 'okta' && secrets.OKTA_SSO_PASSWORD || matrix.provider == 'azure' && secrets.AZURE_SSO_PASSWORD || matrix.provider == 'auth0' && secrets.AUTH0_SSO_PASSWORD || matrix.provider == 'saml' && secrets.SAML_SSO_PASSWORD || matrix.provider == 'cognito' && secrets.COGNITO_SSO_PASSWORD || '' }} PLAYWRIGHT_IS_OSS: true GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} timeout-minutes: 60 @@ -202,48 +218,121 @@ jobs: - name: Upload test results if: always() uses: actions/upload-artifact@v4 + continue-on-error: true with: name: sso-auth-test-results-${{ matrix.provider }} + overwrite: true path: | openmetadata-ui/src/main/resources/ui/playwright/output/sso-playwright-report openmetadata-ui/src/main/resources/ui/playwright/output/sso-test-results retention-days: 5 + if-no-files-found: ignore - name: Upload results JSON for summary uses: actions/upload-artifact@v4 - if: ${{ !cancelled() }} + if: always() with: name: sso-results-json-${{ matrix.provider }} + overwrite: true path: openmetadata-ui/src/main/resources/ui/playwright/output/sso-results.json retention-days: 1 if-no-files-found: ignore + - name: Collect failure diagnostics + if: failure() || cancelled() + continue-on-error: true + run: | + DIAGNOSTICS_DIR="${RUNNER_TEMP}/sso-playwright-ci-diagnostics" + mkdir -p "$DIAGNOSTICS_DIR" + df -h > "$DIAGNOSTICS_DIR/disk-usage.txt" 2>&1 || true + docker system df > "$DIAGNOSTICS_DIR/docker-disk-usage.txt" 2>&1 || true + if [ -f docker/development/docker-compose.yml ]; then + docker compose -f docker/development/docker-compose.yml --profile sso-test ps --all \ + > "$DIAGNOSTICS_DIR/docker-compose-ps.txt" 2>&1 || true + docker compose -f docker/development/docker-compose.yml --profile sso-test logs --no-color --tail 5000 \ + > "$DIAGNOSTICS_DIR/docker-compose.log" 2>&1 || true + fi + + - name: Upload failure diagnostics + uses: actions/upload-artifact@v4 + if: failure() || cancelled() + continue-on-error: true + with: + name: sso-playwright-ci-diagnostics-${{ matrix.provider }} + path: ${{ runner.temp }}/sso-playwright-ci-diagnostics + retention-days: 5 + if-no-files-found: ignore + - name: Clean Up + if: always() + continue-on-error: true run: | cd ./docker/development docker compose --profile sso-test down --remove-orphans 2>/dev/null || true docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" sso-summary: - if: ${{ !cancelled() && github.event_name == 'pull_request_target' && (github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'sso-summary (ignored label)' || 'sso-summary' }} + if: ${{ always() && github.event_name == 'pull_request_target' && (github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} needs: sso-auth-tests runs-on: ubuntu-latest steps: + - name: Checkout trusted CI classifier + uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.base.sha }} + persist-credentials: false + - name: Download results JSON uses: actions/download-artifact@v4 + continue-on-error: true with: pattern: sso-results-json-* path: results + - name: Evaluate zero-retry gate in shadow mode + if: always() + continue-on-error: true + env: + MATRIX_OUTCOME: ${{ needs.sso-auth-tests.result }} + SOURCE_SHA: ${{ github.event.pull_request.merge_commit_sha }} + run: | + python3 .github/scripts/classify_playwright_outcome.py \ + --report-glob 'results/sso-results-json-*/sso-results.json' \ + --matrix-outcome "$MATRIX_OUTCOME" \ + --expected-shard mock-oidc \ + --profile sso-pr \ + --source-sha "$SOURCE_SHA" \ + --output "$RUNNER_TEMP/playwright-shadow-gate/outcome.json" + + - name: Upload SSO Playwright shadow-gate ledger + if: always() + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: playwright-shadow-gate-sso-pr-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/playwright-shadow-gate/outcome.json + if-no-files-found: warn + retention-days: 30 + - name: Post SSO test summary as PR comment + if: always() uses: actions/github-script@v7 + env: + SSO_TEST_RESULT: ${{ needs.sso-auth-tests.result }} with: github-token: ${{ secrets.GITHUB_TOKEN }} script: | const fs = require('fs'); const path = require('path'); + if (context.payload.pull_request?.draft === true) { + console.log('SSO Playwright tests are not required while the PR is a draft.'); + return; + } + + const upstreamResult = process.env.SSO_TEST_RESULT; const runId = '${{ github.run_id }}'; const repo = context.repo; const prNumber = context.payload.pull_request?.number; @@ -251,15 +340,33 @@ jobs: const artifactUrl = `https://github.com/${repo.owner}/${repo.repo}/actions/runs/${runId}`; const commentMarker = ''; + const infrastructureIssues = []; + const addInfrastructureIssue = issue => { + if (!infrastructureIssues.includes(issue)) infrastructureIssues.push(issue); + }; + + if (upstreamResult === 'cancelled') { + addInfrastructureIssue('The SSO Playwright job was cancelled.'); + } else if (upstreamResult === 'skipped') { + addInfrastructureIssue('The SSO Playwright job was unexpectedly skipped.'); + } const allTests = []; const resultsDir = 'results'; + let resultArtifactCount = 0; if (fs.existsSync(resultsDir)) { for (const dir of fs.readdirSync(resultsDir).sort()) { const jsonPath = path.join(resultsDir, dir, 'sso-results.json'); if (!fs.existsSync(jsonPath)) continue; - const report = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); + resultArtifactCount += 1; + let report; + try { + report = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); + } catch (error) { + addInfrastructureIssue(`The SSO results artifact was invalid: ${error.message}`); + continue; + } function collectTests(suite, filePath) { const file = suite.file || filePath || ''; @@ -288,20 +395,31 @@ jobs: } } + if (resultArtifactCount !== 1) { + addInfrastructureIssue(`Expected one SSO results artifact, found ${resultArtifactCount}.`); + } if (allTests.length === 0) { - console.log('No SSO test results found'); - return; + addInfrastructureIssue('The SSO job reported zero tests.'); } const passed = allTests.filter(t => t.status === 'expected'); const failed = allTests.filter(t => t.status === 'unexpected'); const flaky = allTests.filter(t => t.status === 'flaky'); const skipped = allTests.filter(t => t.status === 'skipped'); + const knownTestCount = passed.length + failed.length + flaky.length + skipped.length; + if (knownTestCount !== allTests.length) { + addInfrastructureIssue(`${allTests.length - knownTestCount} SSO test(s) reported an unknown status.`); + } + if (upstreamResult === 'failure' && failed.length === 0) { + addInfrastructureIssue('The SSO job failed during setup or outside a reported test failure.'); + } const lines = [commentMarker]; - if (failed.length > 0) { - lines.push(`## 🔴 SSO Playwright Results — ${failed.length} failure(s)${flaky.length > 0 ? `, ${flaky.length} flaky` : ''}`); + if (failed.length > 0 || infrastructureIssues.length > 0) { + const testFailureText = failed.length > 0 ? `${failed.length} test failure(s)` : ''; + const infrastructureText = infrastructureIssues.length > 0 ? `${infrastructureIssues.length} pipeline/setup failure(s)` : ''; + lines.push(`## 🔴 SSO Playwright Results — ${[testFailureText, infrastructureText].filter(Boolean).join(', ')}`); } else if (flaky.length > 0) { lines.push(`## 🟡 SSO Playwright Results — all passed (${flaky.length} flaky)`); } else { @@ -311,6 +429,13 @@ jobs: lines.push(`✅ ${passed.length} passed · ❌ ${failed.length} failed · 🟡 ${flaky.length} flaky · ⏭️ ${skipped.length} skipped`); lines.push(''); + if (infrastructureIssues.length > 0) { + lines.push('### Pipeline and setup failures'); + lines.push(''); + for (const issue of infrastructureIssues) lines.push(`- ${issue}`); + lines.push(''); + } + if (failed.length > 0) { lines.push('### Failures'); lines.push(''); @@ -340,18 +465,34 @@ jobs: const body = lines.join('\n'); - let existingComment = null; - for await (const response of github.paginate.iterator( - github.rest.issues.listComments, { ...repo, issue_number: prNumber, per_page: 100 } - )) { - const found = response.data.find(c => - c.user?.login === 'github-actions[bot]' && c.body?.includes(commentMarker) - ); - if (found) { existingComment = found; break; } + try { + await core.summary.addRaw(body).write(); + } catch (error) { + core.warning(`Could not write the SSO Playwright job summary: ${error.message}`); } - if (existingComment) { - await github.rest.issues.updateComment({ ...repo, comment_id: existingComment.id, body }); - } else { - await github.rest.issues.createComment({ ...repo, issue_number: prNumber, body }); + try { + let existingComment = null; + for await (const response of github.paginate.iterator( + github.rest.issues.listComments, { ...repo, issue_number: prNumber, per_page: 100 } + )) { + const found = response.data.find(c => + c.user?.login === 'github-actions[bot]' && c.body?.includes(commentMarker) + ); + if (found) { existingComment = found; break; } + } + + if (existingComment) { + await github.rest.issues.updateComment({ ...repo, comment_id: existingComment.id, body }); + } else { + await github.rest.issues.createComment({ ...repo, issue_number: prNumber, body }); + } + } catch (error) { + core.warning(`Could not publish the SSO Playwright PR comment: ${error.message}`); + } + + if (failed.length > 0 || infrastructureIssues.length > 0) { + core.setFailed( + `${failed.length} SSO Playwright test failure(s); ${infrastructureIssues.length} pipeline/setup failure(s).` + ); } diff --git a/.github/workflows/postgresql-nightly-e2e.yml b/.github/workflows/postgresql-nightly-e2e.yml index 62275f4b1624..beeea0f7d3e1 100644 --- a/.github/workflows/postgresql-nightly-e2e.yml +++ b/.github/workflows/postgresql-nightly-e2e.yml @@ -90,7 +90,7 @@ jobs: - name: Run Playwright tests working-directory: openmetadata-ui/src/main/resources/ui/ run: | - if [ "${{ matrix.shardIndex }}" -eq "1" ]; then + if [ "${{ matrix.shardIndex }}" = "1" ]; then echo "🔹 Running DataAssetRules-only tests on shard 1" # The testMatch pattern ensures only DataAssetRules*.spec.ts files run @@ -99,7 +99,7 @@ jobs: --project=DataAssetRulesEnabled \ --project=DataAssetRulesDisabled - elif [ "${{ matrix.shardIndex }}" -eq "2" ]; then + elif [ "${{ matrix.shardIndex }}" = "2" ]; then echo "🔹 Running search relevance tests on shard 2" npx playwright test \ @@ -124,7 +124,6 @@ jobs: PLAYWRIGHT_SNOWFLAKE_ACCOUNT: ${{ secrets.TEST_SNOWFLAKE_ACCOUNT }} PLAYWRIGHT_SNOWFLAKE_DATABASE: ${{ secrets.TEST_SNOWFLAKE_DATABASE }} PLAYWRIGHT_SNOWFLAKE_WAREHOUSE: ${{ secrets.TEST_SNOWFLAKE_WAREHOUSE }} - PLAYWRIGHT_PROJECT_ID: ${{ steps.cypress-project-id.outputs.CYPRESS_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY: ${{ secrets.TEST_BQ_PRIVATE_KEY }} PLAYWRIGHT_BQ_PROJECT_ID: ${{ secrets.PLAYWRIGHT_BQ_PROJECT_ID }} PLAYWRIGHT_BQ_PRIVATE_KEY_ID: ${{ secrets.TEST_BQ_PRIVATE_KEY_ID }} @@ -173,6 +172,7 @@ jobs: uses: actions/upload-artifact@v4 with: name: blob-report-${{ matrix.shardIndex }} + overwrite: true path: openmetadata-ui/src/main/resources/ui/blob-report retention-days: 1 @@ -181,20 +181,23 @@ jobs: uses: actions/upload-artifact@v4 with: name: playwright-HTML-report-${{ matrix.shardIndex }} + overwrite: true path: openmetadata-ui/src/main/resources/ui/playwright/output/playwright-report retention-days: 1 compression-level: 9 - name: Clean Up + if: always() + continue-on-error: true run: | cd ./docker/development docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + sudo rm -rf "${PWD}/docker-volume" merge-reports: needs: pw-ci-postgresql-branch runs-on: ubuntu-latest - if: ${{ !failure() || !cancelled() }} + if: ${{ always() }} env: # Recommended: pass the GitHub token lets this action correctly # determine the unique run id necessary to re-run the checks @@ -223,6 +226,28 @@ jobs: run: | npx playwright merge-reports --reporter json ./blob-reports > merged_tests_results.json + - name: Evaluate zero-retry gate in shadow mode + if: always() + continue-on-error: true + env: + MATRIX_OUTCOME: ${{ needs.pw-ci-postgresql-branch.result }} + run: | + python3 .github/scripts/classify_playwright_outcome.py \ + --report-glob 'openmetadata-ui/src/main/resources/ui/merged_tests_results.json' \ + --matrix-outcome "$MATRIX_OUTCOME" \ + --profile postgresql-nightly \ + --output "$RUNNER_TEMP/playwright-shadow-gate/outcome.json" + + - name: Upload Playwright shadow-gate ledger + if: always() + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: playwright-shadow-gate-postgresql-nightly-${{ github.run_id }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/playwright-shadow-gate/outcome.json + if-no-files-found: warn + retention-days: 30 + - name: Generate Slack Notification if: ${{ inputs.send_slack_notification }} working-directory: openmetadata-ui/src/main/resources/ui/ diff --git a/.github/workflows/py-cli-e2e-tests.yml b/.github/workflows/py-cli-e2e-tests.yml index 09736418cb6a..e4faecfe3df8 100644 --- a/.github/workflows/py-cli-e2e-tests.yml +++ b/.github/workflows/py-cli-e2e-tests.yml @@ -85,28 +85,46 @@ jobs: with: python-version: '3.10' + - name: Reclaim unused disk for Exasol + if: matrix.e2e-test == 'exasol' + continue-on-error: true + run: | + { + echo "Before Exasol disk reclaim" + df -h + docker system df + sudo rm -rf /opt/hostedtoolcache/CodeQL + docker image prune --all --force || true + docker builder prune --all --force || true + echo "After Exasol disk reclaim" + df -h + docker system df + } 2>&1 | tee "${RUNNER_TEMP}/exasol-disk-reclaim.log" + shell: bash + - name: Run Python Unit Tests if: matrix.e2e-test == 'python-unittests' id: python-unittest - continue-on-error: true run: | + set -o pipefail source env/bin/activate cd ingestion - nox --no-venv -s unit-tests + nox --no-venv -s unit-tests 2>&1 | tee unit-test-run.log shell: bash - name: Rename coverage file for Python unit tests if: matrix.e2e-test == 'python-unittests' && steps.python-unittest.outcome == 'success' && env.DEBUG == 'false' + continue-on-error: true run: mv ingestion/.coverage .coverage.python-unittests - name: Run Python Integration Tests if: matrix.e2e-test == 'python-integration' id: python-integration-test - continue-on-error: true run: | + set -o pipefail source env/bin/activate cd ingestion - nox --no-venv -s integration-tests -- --standalone --durations=5 + nox --no-venv -s integration-tests -- --standalone --durations=5 2>&1 | tee integration-test-run.log env: TESTCONTAINERS_RYUK_DISABLED: true shell: bash @@ -114,7 +132,6 @@ jobs: - name: Run CLI E2E Python Tests & record coverage if: matrix.e2e-test != 'python-unittests' && matrix.e2e-test != 'python-integration' id: e2e-test - continue-on-error: true env: E2E_TEST: ${{ matrix.e2e-test }} E2E_BQ_PROJECT_ID_TAXONOMY: ${{ secrets.TEST_BQ_PROJECT_ID_TAXONOMY }} @@ -177,21 +194,28 @@ jobs: E2E_ATHENA_S3STAGINGDIR: ${{ secrets.E2E_ATHENA_S3STAGINGDIR }} E2E_ATHENA_WORKGROUP: ${{ secrets.E2E_ATHENA_WORKGROUP }} run: | + set -o pipefail source env/bin/activate - export SITE_CUSTOMIZE_PATH=$(python -c "import site; import os; from pathlib import Path; print(os.path.relpath(site.getsitepackages()[0], str(Path.cwd())))")/sitecustomize.py - echo "import os" >> $SITE_CUSTOMIZE_PATH - echo "try:" >> $SITE_CUSTOMIZE_PATH - echo " import coverage" >> $SITE_CUSTOMIZE_PATH - echo " os.environ['COVERAGE_PROCESS_START'] = os.path.join(os.environ.get('GITHUB_WORKSPACE', os.getcwd()), 'ingestion', 'pyproject.toml')" >> $SITE_CUSTOMIZE_PATH - echo " coverage.process_startup()" >> $SITE_CUSTOMIZE_PATH - echo "except ImportError:" >> $SITE_CUSTOMIZE_PATH - echo " pass" >> $SITE_CUSTOMIZE_PATH - coverage run --rcfile ingestion/pyproject.toml --branch -m pytest -c ingestion/pyproject.toml --junitxml=ingestion/junit/test-results-$E2E_TEST.xml --ignore=ingestion/tests/unit/source ingestion/tests/cli_e2e/test_cli_$E2E_TEST.py - coverage combine --data-file=.coverage.$E2E_TEST --rcfile=ingestion/pyproject.toml --keep .coverage* - coverage report --rcfile ingestion/pyproject.toml --data-file .coverage.$E2E_TEST || true + site_packages_path="$(python -c "import site; import os; from pathlib import Path; print(os.path.relpath(site.getsitepackages()[0], str(Path.cwd())))")" + SITE_CUSTOMIZE_PATH="${site_packages_path}/sitecustomize.py" + export SITE_CUSTOMIZE_PATH + { + echo "import os" + echo "try:" + echo " import coverage" + echo " os.environ['COVERAGE_PROCESS_START'] = os.path.join(os.environ.get('GITHUB_WORKSPACE', os.getcwd()), 'ingestion', 'pyproject.toml')" + echo " coverage.process_startup()" + echo "except ImportError:" + echo " pass" + } >> "$SITE_CUSTOMIZE_PATH" + coverage run --rcfile ingestion/pyproject.toml --branch -m pytest -c ingestion/pyproject.toml "--junitxml=ingestion/junit/test-results-${E2E_TEST}.xml" --ignore=ingestion/tests/unit/source "ingestion/tests/cli_e2e/test_cli_${E2E_TEST}.py" 2>&1 | tee ingestion/cli-e2e-test-run.log + coverage combine "--data-file=.coverage.${E2E_TEST}" --rcfile=ingestion/pyproject.toml --keep .coverage* || true + coverage report --rcfile ingestion/pyproject.toml "--data-file=.coverage.${E2E_TEST}" || true + shell: bash - name: Upload coverage artifact for Python unit tests if: matrix.e2e-test == 'python-unittests' && steps.python-unittest.outcome == 'success' && env.DEBUG == 'false' + continue-on-error: true uses: actions/upload-artifact@v4 with: name: coverage-${{ matrix.e2e-test }} @@ -200,10 +224,12 @@ jobs: - name: Rename coverage file for Python integration tests if: matrix.e2e-test == 'python-integration' && steps.python-integration-test.outcome == 'success' && env.DEBUG == 'false' + continue-on-error: true run: mv ingestion/.coverage .coverage.python-integration - name: Upload coverage artifact for Python integration tests if: matrix.e2e-test == 'python-integration' && steps.python-integration-test.outcome == 'success' && env.DEBUG == 'false' + continue-on-error: true uses: actions/upload-artifact@v4 with: name: coverage-${{ matrix.e2e-test }} @@ -212,28 +238,105 @@ jobs: - name: Upload coverage artifact for CLI E2E tests if: matrix.e2e-test != 'python-unittests' && matrix.e2e-test != 'python-integration' && steps.e2e-test.outcome == 'success' && env.DEBUG == 'false' + continue-on-error: true uses: actions/upload-artifact@v4 with: name: coverage-${{ matrix.e2e-test }} path: .coverage.${{ matrix.e2e-test }} include-hidden-files: true + - name: Classify Python CLI E2E test outcome + if: ${{ always() }} + env: + CLI_E2E_OUTCOME: ${{ steps.e2e-test.outcome }} + E2E_TEST: ${{ matrix.e2e-test }} + PYTHON_INTEGRATION_OUTCOME: ${{ steps.python-integration-test.outcome }} + PYTHON_UNIT_OUTCOME: ${{ steps.python-unittest.outcome }} + run: | + case "$E2E_TEST" in + python-unittests) + test_outcome="$PYTHON_UNIT_OUTCOME" + test_profile=python-unit-nightly + ;; + python-integration) + test_outcome="$PYTHON_INTEGRATION_OUTCOME" + test_profile=python-integration-nightly + ;; + *) + test_outcome="$CLI_E2E_OUTCOME" + test_profile=python-cli-e2e + ;; + esac + + TEST_PROFILE="$test_profile" TEST_LANE="$E2E_TEST" \ + python3 .github/scripts/classify_test_outcome.py \ + --step-outcome "$test_outcome" \ + --report-glob 'ingestion/junit/test-results-*.xml' \ + --diagnostic-glob 'ingestion/*-test-run.log' \ + --output ingestion/ci-diagnostics/outcome.json + shell: bash + - name: Upload tests artifact - if: (steps.e2e-test.outcome == 'success' || steps.python-unittest.outcome == 'success' || steps.python-integration-test.outcome == 'success') && env.DEBUG == 'false' + if: ${{ always() }} + continue-on-error: true uses: actions/upload-artifact@v4 with: name: tests-${{ matrix.e2e-test }} - path: ingestion/junit/test-results-*.xml + path: | + ingestion/junit/test-results-*.xml + ingestion/ci-diagnostics/outcome.json + ingestion/*-test-run.log + if-no-files-found: warn + retention-days: 14 + compression-level: 1 + + - name: Collect runner and service diagnostics + if: ${{ failure() || cancelled() }} + continue-on-error: true + run: | + diagnostics="${RUNNER_TEMP}/python-ci-diagnostics" + rm -rf "$diagnostics" + mkdir -p "$diagnostics" + df -h > "$diagnostics/disk-usage.txt" 2>&1 || true + free -h > "$diagnostics/memory-usage.txt" 2>&1 || true + docker system df > "$diagnostics/docker-disk-usage.txt" 2>&1 || true + docker ps --all --no-trunc > "$diagnostics/docker-containers.txt" 2>&1 || true + if [ -d docker/development ]; then + (cd docker/development && docker compose ps --all) > "$diagnostics/docker-compose-ps.txt" 2>&1 || true + (cd docker/development && docker compose logs --no-color --tail 2000) > "$diagnostics/docker-compose.log" 2>&1 || true + fi + coredumpctl --no-pager list > "$diagnostics/coredumps.txt" 2>&1 || true + coredumpctl --no-pager info >> "$diagnostics/coredumps.txt" 2>&1 || true + find "$GITHUB_WORKSPACE" /tmp /var/crash -maxdepth 3 -type f \ + \( -name 'core' -o -name 'core.*' -o -name '*.core' -o -name '*.dmp' -o -name '*.crash' \) \ + -printf '%p %s bytes\n' >> "$diagnostics/core-files.txt" 2>/dev/null || true + if [ -f "${RUNNER_TEMP}/exasol-disk-reclaim.log" ]; then + cp "${RUNNER_TEMP}/exasol-disk-reclaim.log" "$diagnostics/" + fi + shell: bash + + - name: Upload runner and service diagnostics + if: ${{ failure() || cancelled() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: py-cli-e2e-diagnostics-${{ matrix.e2e-test }} + path: ${{ runner.temp }}/python-ci-diagnostics/ + if-no-files-found: warn + retention-days: 14 + compression-level: 1 - name: Clean Up - if: matrix.e2e-test != 'python-unittests' + if: ${{ always() && matrix.e2e-test != 'python-unittests' }} + continue-on-error: true run: | cd ./docker/development - docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume + docker compose down --remove-orphans || true + sudo rm -rf "${PWD}/docker-volume" - name: Slack on Failure - if: (steps.e2e-test.outcome == 'failure' || steps.python-unittest.outcome == 'failure' || steps.python-integration-test.outcome == 'failure') && env.DEBUG == 'false' + if: ${{ always() && !cancelled() && env.DEBUG == 'false' && failure() }} + continue-on-error: true uses: slackapi/slack-github-action@v1.23.0 with: payload: | @@ -244,17 +347,30 @@ jobs: SLACK_WEBHOOK_URL: ${{ secrets.E2E_SLACK_WEBHOOK }} SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK - - name: Force failure - if: steps.e2e-test.outcome == 'failure' || steps.python-unittest.outcome == 'failure' || steps.python-integration-test.outcome == 'failure' - run: | - exit 1 + py-cli-e2e-tests-status: + name: py-cli-e2e-tests-status + needs: [check-debug, py-cli-e2e-tests] + if: ${{ always() }} + runs-on: ubuntu-latest + steps: + - name: Verify all expected CLI E2E jobs completed + env: + DEBUG_RESULT: ${{ needs.check-debug.result }} + TEST_RESULT: ${{ needs.py-cli-e2e-tests.result }} + run: | + if [ "$DEBUG_RESULT" != "success" ] || [ "$TEST_RESULT" != "success" ]; then + echo "Expected CLI E2E jobs did not succeed: debug=$DEBUG_RESULT tests=$TEST_RESULT" + exit 1 + fi + shell: bash sonar-cloud-coverage-upload: runs-on: ubuntu-latest needs: - py-cli-e2e-tests - check-debug - if: needs.check-debug.outputs.DEBUG == 'false' + if: ${{ needs.check-debug.outputs.DEBUG == 'false' && needs.py-cli-e2e-tests.result == 'success' }} + continue-on-error: true steps: - name: Checkout @@ -285,11 +401,11 @@ jobs: run: | # Copy coverage artifacts into ingestion/ so paths resolve relative to it for folder in artifacts/coverage-*; do - cp -rT $folder/ ingestion/ ; + [ -d "$folder" ] && cp -rT "$folder/" ingestion/ done mkdir -p ingestion/junit for folder in artifacts/tests-*; do - cp -rT $folder/ ingestion/junit ; + [ -d "$folder" ] && cp -rT "$folder/" ingestion/junit/ done source env/bin/activate cd ingestion diff --git a/.github/workflows/py-tests-postgres.yml b/.github/workflows/py-tests-postgres.yml index 84345cdd4941..2526eb1a1a80 100644 --- a/.github/workflows/py-tests-postgres.yml +++ b/.github/workflows/py-tests-postgres.yml @@ -18,34 +18,68 @@ on: permissions: contents: read + pull-requests: read concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test' }} jobs: - # Detect whether relevant paths changed. When no Python/service/schema files - # are modified the downstream jobs are skipped via their `if` condition. - # A job skipped by `if` reports as "Success", so required checks still pass. + # Authorize pull request code once before the matrix fans out, then detect + # whether relevant paths changed. changes: - name: Detect Changes + name: Authorize & Detect Changes runs-on: ubuntu-latest if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} outputs: - python: ${{ github.event_name == 'workflow_dispatch' && 'true' || steps.filter.outputs.python }} + python: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.python }} steps: - - uses: dorny/paths-filter@v3 + - uses: dorny/paths-filter@v4 id: filter - if: ${{ github.event_name != 'workflow_dispatch' }} + if: ${{ github.event_name == 'pull_request_target' }} with: filters: | python: - 'ingestion/**' - 'openmetadata-service/**' - 'openmetadata-spec/src/main/resources/json/schema/**' + - 'openmetadata-dist/**' + - 'bootstrap/**' + - 'conf/**' + - 'docker/run_local_docker.sh' + - 'docker/run_local_docker_common.sh' + - 'docker/development/docker-compose.yml' + - 'docker/development/docker-compose-postgres.yml' + - '.github/actions/setup-openmetadata-test-environment/**' + - '.github/scripts/classify_test_outcome.py' + - '.github/workflows/py-tests-postgres.yml' - 'pom.xml' - 'Makefile' + - name: Wait for the labeler + uses: lewagon/wait-on-check-action@v1.7.0 + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.python == 'true' }} + with: + ref: ${{ github.event.pull_request.head.sha }} + check-name: Team Label + repo-token: ${{ secrets.GITHUB_TOKEN }} + wait-interval: 30 + + - name: Verify PR labels + uses: jesusvasquez333/verify-pr-label-action@v1.4.0 + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.python == 'true' }} + with: + github-token: "${{ secrets.GITHUB_TOKEN }}" + valid-labels: "safe to test" + pull-request-number: "${{ github.event.pull_request.number }}" + disable-reviews: true + + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.python == 'true' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + py-integration-tests: name: "Integration Tests (${{ matrix.shard.name }}, ${{ matrix.py-version }})" needs: changes @@ -83,28 +117,10 @@ jobs: swap-storage: true docker-images: false - - name: Wait for the labeler - uses: lewagon/wait-on-check-action@v1.7.0 - if: ${{ github.event_name == 'pull_request_target' }} - with: - ref: ${{ github.event.pull_request.head.sha }} - check-name: Team Label - repo-token: ${{ secrets.GITHUB_TOKEN }} - wait-interval: 90 - - - name: Verify PR labels - uses: jesusvasquez333/verify-pr-label-action@v1.4.0 - if: ${{ github.event_name == 'pull_request_target' }} - with: - github-token: "${{ secrets.GITHUB_TOKEN }}" - valid-labels: "safe to test" - pull-request-number: "${{ github.event.pull_request.number }}" - disable-reviews: true # To not auto approve changes - - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Setup Openmetadata Test Environment uses: ./.github/actions/setup-openmetadata-test-environment @@ -113,29 +129,137 @@ jobs: args: "-m no-ui -d postgresql" ingestion_dependency: "mysql,elasticsearch,sample-data" + - name: Reclaim unused disk for the Exasol shard + if: matrix.shard.name == 'shard-2' + continue-on-error: true + run: | + { + echo "Before Exasol shard disk reclaim" + df -h + docker system df + sudo rm -rf /opt/hostedtoolcache/CodeQL + docker image prune --all --force || true + docker builder prune --all --force || true + echo "After Exasol shard disk reclaim" + df -h + docker system df + } 2>&1 | tee "${RUNNER_TEMP}/exasol-disk-reclaim.log" + shell: bash + - name: Run Integration Tests + id: integration-tests run: | + set -o pipefail source env/bin/activate cd ingestion - nox --no-venv -s integration-tests -- --standalone --durations=5 ${{ matrix.shard.nox-args }} + read -r -a shard_args <<< "$NOX_ARGS" + nox --no-venv -s integration-tests -- --standalone --durations=5 "${shard_args[@]}" 2>&1 | tee integration-test-run.log env: + NOX_ARGS: ${{ matrix.shard.nox-args }} TESTCONTAINERS_RYUK_DISABLED: true shell: bash + - name: Classify PostgreSQL Python integration test outcome + if: ${{ always() }} + env: + TEST_LANE: ${{ matrix.shard.name }}-python-${{ matrix.py-version }} + TEST_PROFILE: python-postgresql-integration + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + run: | + python3 .github/scripts/classify_test_outcome.py \ + --step-outcome "$TEST_STEP_OUTCOME" \ + --report-glob 'ingestion/junit/test-results-*.xml' \ + --diagnostic-glob 'ingestion/integration-test-run.log' \ + --output ingestion/ci-diagnostics/outcome.json + + - name: Upload test results + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: py-postgres-integration-test-results-${{ matrix.shard.name }}-${{ matrix.py-version }} + path: | + ingestion/junit/ + ingestion/ci-diagnostics/outcome.json + ingestion/integration-test-run.log + if-no-files-found: warn + retention-days: 14 + compression-level: 1 + + - name: Collect runner and service diagnostics + if: ${{ failure() || cancelled() }} + continue-on-error: true + run: | + diagnostics="${RUNNER_TEMP}/python-ci-diagnostics" + rm -rf "$diagnostics" + mkdir -p "$diagnostics" + df -h > "$diagnostics/disk-usage.txt" 2>&1 || true + free -h > "$diagnostics/memory-usage.txt" 2>&1 || true + docker system df > "$diagnostics/docker-disk-usage.txt" 2>&1 || true + docker ps --all --no-trunc > "$diagnostics/docker-containers.txt" 2>&1 || true + if [ -d docker/development ]; then + (cd docker/development && docker compose ps --all) > "$diagnostics/docker-compose-ps.txt" 2>&1 || true + (cd docker/development && docker compose logs --no-color --tail 2000) > "$diagnostics/docker-compose.log" 2>&1 || true + fi + coredumpctl --no-pager list > "$diagnostics/coredumps.txt" 2>&1 || true + coredumpctl --no-pager info >> "$diagnostics/coredumps.txt" 2>&1 || true + find "$GITHUB_WORKSPACE" /tmp /var/crash -maxdepth 3 -type f \ + \( -name 'core' -o -name 'core.*' -o -name '*.core' -o -name '*.dmp' -o -name '*.crash' \) \ + -printf '%p %s bytes\n' >> "$diagnostics/core-files.txt" 2>/dev/null || true + if [ -f "${RUNNER_TEMP}/exasol-disk-reclaim.log" ]; then + cp "${RUNNER_TEMP}/exasol-disk-reclaim.log" "$diagnostics/" + fi + shell: bash + + - name: Upload runner and service diagnostics + if: ${{ failure() || cancelled() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: py-postgres-integration-diagnostics-${{ matrix.shard.name }}-${{ matrix.py-version }} + path: ${{ runner.temp }}/python-ci-diagnostics/ + if-no-files-found: warn + retention-days: 14 + compression-level: 1 + - name: Clean Up + if: ${{ always() }} + continue-on-error: true run: | cd ./docker/development - docker compose down --remove-orphans - sudo rm -rf ${PWD}/docker-volume - - # Single required-check gate for branch protection. - # Skipped (= "Success") when all test jobs pass or are legitimately skipped. - # Runs and exits 1 only when a test job fails or is cancelled. - # Set "py-tests-postgres / py-tests-status" as the sole required check for this workflow. - py-tests-status: - name: py-tests-status + docker compose down --remove-orphans || true + sudo rm -rf "${PWD}/docker-volume" + + # Set "py-tests-postgres / py-tests-postgres-status" as the sole required check for this workflow. + py-tests-postgres-status: + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'py-tests-postgres-status (ignored label)' || 'py-tests-postgres-status' }} needs: [changes, py-integration-tests] - if: ${{ failure() || cancelled() }} + if: ${{ always() && !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} runs-on: ubuntu-latest steps: - - run: exit 1 + - name: Verify all expected PostgreSQL Python jobs completed + env: + CHANGES_RESULT: ${{ needs.changes.result }} + PYTHON_CHANGED: ${{ needs.changes.outputs.python }} + INTEGRATION_RESULT: ${{ needs.py-integration-tests.result }} + run: | + if [ "$CHANGES_RESULT" != "success" ]; then + echo "Python preflight did not succeed: $CHANGES_RESULT" + exit 1 + fi + + if [ "$PYTHON_CHANGED" = "true" ] && [ "$INTEGRATION_RESULT" != "success" ]; then + echo "Expected PostgreSQL Python jobs did not succeed: integration=$INTEGRATION_RESULT" + exit 1 + fi + + if [ "$PYTHON_CHANGED" = "false" ] && [ "$INTEGRATION_RESULT" != "skipped" ]; then + echo "Unexpected PostgreSQL Python job result for an unchanged tree: integration=$INTEGRATION_RESULT" + exit 1 + fi + + if [ "$PYTHON_CHANGED" != "true" ] && [ "$PYTHON_CHANGED" != "false" ]; then + echo "Python change detection produced an invalid result: $PYTHON_CHANGED" + exit 1 + fi + shell: bash diff --git a/.github/workflows/py-tests.yml b/.github/workflows/py-tests.yml index 44f7140b2be6..9614d581eb36 100644 --- a/.github/workflows/py-tests.yml +++ b/.github/workflows/py-tests.yml @@ -18,6 +18,7 @@ on: permissions: contents: read + pull-requests: read concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} @@ -34,44 +35,40 @@ env: -Dsonar.pullrequest.provider=github jobs: - # Detect whether relevant paths changed. When no Python/service/schema files - # are modified the downstream jobs are skipped via their `if` condition. - # A job skipped by `if` reports as "Success", so required checks still pass. - # This replaces the old py-tests-skip.yml companion workflow. + # Authorize pull request code once before the matrix fans out, then detect + # whether relevant paths changed. changes: - name: Detect Changes + name: Authorize & Detect Changes runs-on: ubuntu-latest if: ${{ !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} outputs: - python: ${{ github.event_name == 'workflow_dispatch' && 'true' || steps.filter.outputs.python }} + python: ${{ github.event_name != 'pull_request_target' && 'true' || steps.filter.outputs.python }} steps: - - uses: dorny/paths-filter@v3 + - uses: dorny/paths-filter@v4 id: filter - if: ${{ github.event_name != 'workflow_dispatch' }} + if: ${{ github.event_name == 'pull_request_target' }} with: filters: | python: - 'ingestion/**' - 'openmetadata-service/**' - 'openmetadata-spec/src/main/resources/json/schema/**' + - 'openmetadata-dist/**' + - 'bootstrap/**' + - 'conf/**' + - 'docker/run_local_docker.sh' + - 'docker/run_local_docker_common.sh' + - 'docker/development/docker-compose.yml' + - 'docker/development/docker-compose-postgres.yml' + - '.github/actions/setup-openmetadata-test-environment/**' + - '.github/scripts/classify_test_outcome.py' + - '.github/workflows/py-tests.yml' - 'pom.xml' - 'Makefile' - py-unit-tests: - name: Unit Tests & Static Checks - needs: changes - if: ${{ needs.changes.outputs.python == 'true' }} - timeout-minutes: 60 - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - py-version: ["3.10", "3.11", "3.12"] - steps: - - name: Wait for the labeler uses: lewagon/wait-on-check-action@v1.7.0 - if: ${{ github.event_name == 'pull_request_target' }} + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.python == 'true' }} with: ref: ${{ github.event.pull_request.head.sha }} check-name: Team Label @@ -80,17 +77,34 @@ jobs: - name: Verify PR labels uses: jesusvasquez333/verify-pr-label-action@v1.4.0 - if: ${{ github.event_name == 'pull_request_target' }} + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.python == 'true' }} with: github-token: "${{ secrets.GITHUB_TOKEN }}" valid-labels: "safe to test" pull-request-number: "${{ github.event.pull_request.number }}" disable-reviews: true + - name: Verify PR merge commit is available + if: ${{ github.event_name == 'pull_request_target' && steps.filter.outputs.python == 'true' && github.event.pull_request.merge_commit_sha == '' }} + run: | + echo "The PR has no merge commit to test. Resolve merge conflicts and rerun the workflow." + exit 1 + + py-unit-tests: + name: Unit Tests & Static Checks + needs: changes + if: ${{ needs.changes.outputs.python == 'true' }} + timeout-minutes: 60 + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + py-version: ["3.10", "3.11", "3.12"] + steps: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Setup Openmetadata Test Environment uses: ./.github/actions/setup-openmetadata-test-environment @@ -105,20 +119,53 @@ jobs: # redundant work and keep the baseline file deterministic. if: matrix.py-version == '3.10' run: | + set -o pipefail source env/bin/activate cd ingestion - nox --no-venv -s static-checks + nox --no-venv -s static-checks 2>&1 | tee static-checks-run.log shell: bash - name: Run Unit Tests + id: unit-tests run: | + set -o pipefail source env/bin/activate cd ingestion - nox --no-venv -s unit-tests + nox --no-venv -s unit-tests 2>&1 | tee unit-test-run.log shell: bash + - name: Classify Python unit test outcome + if: ${{ always() }} + env: + TEST_LANE: python-${{ matrix.py-version }} + TEST_PROFILE: python-unit + TEST_STEP_OUTCOME: ${{ steps.unit-tests.outcome }} + run: | + python3 .github/scripts/classify_test_outcome.py \ + --step-outcome "$TEST_STEP_OUTCOME" \ + --report-glob 'ingestion/junit/test-results-*.xml' \ + --diagnostic-glob 'ingestion/*-test-run.log' \ + --diagnostic-glob 'ingestion/static-checks-run.log' \ + --output ingestion/ci-diagnostics/outcome.json + + - name: Upload test results + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: py-unit-test-results-${{ matrix.py-version }} + path: | + ingestion/junit/ + ingestion/ci-diagnostics/outcome.json + ingestion/*-test-run.log + ingestion/static-checks-run.log + if-no-files-found: warn + retention-days: 14 + compression-level: 1 + - name: Upload coverage artifact if: ${{ matrix.py-version == env.MAIN_PYTHON_VERSION && !cancelled() }} + continue-on-error: true uses: actions/upload-artifact@v4 with: name: coverage-unit @@ -162,28 +209,10 @@ jobs: swap-storage: true docker-images: false - - name: Wait for the labeler - uses: lewagon/wait-on-check-action@v1.7.0 - if: ${{ github.event_name == 'pull_request_target' }} - with: - ref: ${{ github.event.pull_request.head.sha }} - check-name: Team Label - repo-token: ${{ secrets.GITHUB_TOKEN }} - wait-interval: 90 - - - name: Verify PR labels - uses: jesusvasquez333/verify-pr-label-action@v1.4.0 - if: ${{ github.event_name == 'pull_request_target' }} - with: - github-token: "${{ secrets.GITHUB_TOKEN }}" - valid-labels: "safe to test" - pull-request-number: "${{ github.event.pull_request.number }}" - disable-reviews: true # To not auto approve changes - - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} - name: Setup Openmetadata Test Environment uses: ./.github/actions/setup-openmetadata-test-environment @@ -192,61 +221,162 @@ jobs: args: "-m no-ui" ingestion_dependency: "mysql,elasticsearch,sample-data" + - name: Reclaim unused disk for the Exasol shard + if: matrix.shard.name == 'shard-2' + continue-on-error: true + run: | + { + echo "Before Exasol shard disk reclaim" + df -h + docker system df + sudo rm -rf /opt/hostedtoolcache/CodeQL + docker image prune --all --force || true + docker builder prune --all --force || true + echo "After Exasol shard disk reclaim" + df -h + docker system df + } 2>&1 | tee "${RUNNER_TEMP}/exasol-disk-reclaim.log" + shell: bash + - name: Run Integration Tests + id: integration-tests run: | + set -o pipefail source env/bin/activate cd ingestion read -r -a shard_args <<< "$NOX_ARGS" - set +e nox --no-venv -s integration-tests -- --standalone --durations=5 "${shard_args[@]}" 2>&1 | tee integration-test-run.log - status=${PIPESTATUS[0]} - set -e - if [ "$status" -ne 0 ] && { [ "$status" -eq 139 ] || [ "$status" -eq 245 ] || grep -Eq "failed with exit code -11|Segmentation fault|exit code 139" integration-test-run.log; }; then - nox --no-venv -s integration-tests -- --standalone --durations=5 "${shard_args[@]}" - else - exit "$status" - fi env: NOX_ARGS: ${{ matrix.shard.nox-args }} TESTCONTAINERS_RYUK_DISABLED: true shell: bash + - name: Classify Python integration test outcome + if: ${{ always() }} + env: + TEST_LANE: ${{ matrix.shard.name }}-python-${{ matrix.py-version }} + TEST_PROFILE: python-integration + TEST_STEP_OUTCOME: ${{ steps.integration-tests.outcome }} + run: | + python3 .github/scripts/classify_test_outcome.py \ + --step-outcome "$TEST_STEP_OUTCOME" \ + --report-glob 'ingestion/junit/test-results-*.xml' \ + --diagnostic-glob 'ingestion/integration-test-run.log' \ + --output ingestion/ci-diagnostics/outcome.json + - name: Upload coverage artifact if: ${{ matrix.py-version == env.MAIN_PYTHON_VERSION && !cancelled() }} + continue-on-error: true uses: actions/upload-artifact@v4 with: name: coverage-integration-${{ matrix.shard.name }} path: ingestion/.coverage include-hidden-files: true + - name: Upload test results + if: ${{ always() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: py-integration-test-results-${{ matrix.shard.name }}-${{ matrix.py-version }} + path: | + ingestion/junit/ + ingestion/ci-diagnostics/outcome.json + ingestion/integration-test-run.log + if-no-files-found: warn + retention-days: 14 + compression-level: 1 + + - name: Collect runner and service diagnostics + if: ${{ failure() || cancelled() }} + continue-on-error: true + run: | + diagnostics="${RUNNER_TEMP}/python-ci-diagnostics" + rm -rf "$diagnostics" + mkdir -p "$diagnostics" + df -h > "$diagnostics/disk-usage.txt" 2>&1 || true + free -h > "$diagnostics/memory-usage.txt" 2>&1 || true + docker system df > "$diagnostics/docker-disk-usage.txt" 2>&1 || true + docker ps --all --no-trunc > "$diagnostics/docker-containers.txt" 2>&1 || true + if [ -d docker/development ]; then + (cd docker/development && docker compose ps --all) > "$diagnostics/docker-compose-ps.txt" 2>&1 || true + (cd docker/development && docker compose logs --no-color --tail 2000) > "$diagnostics/docker-compose.log" 2>&1 || true + fi + coredumpctl --no-pager list > "$diagnostics/coredumps.txt" 2>&1 || true + coredumpctl --no-pager info >> "$diagnostics/coredumps.txt" 2>&1 || true + find "$GITHUB_WORKSPACE" /tmp /var/crash -maxdepth 3 -type f \ + \( -name 'core' -o -name 'core.*' -o -name '*.core' -o -name '*.dmp' -o -name '*.crash' \) \ + -printf '%p %s bytes\n' >> "$diagnostics/core-files.txt" 2>/dev/null || true + if [ -f "${RUNNER_TEMP}/exasol-disk-reclaim.log" ]; then + cp "${RUNNER_TEMP}/exasol-disk-reclaim.log" "$diagnostics/" + fi + shell: bash + + - name: Upload runner and service diagnostics + if: ${{ failure() || cancelled() }} + continue-on-error: true + uses: actions/upload-artifact@v4 + with: + name: py-integration-diagnostics-${{ matrix.shard.name }}-${{ matrix.py-version }} + path: ${{ runner.temp }}/python-ci-diagnostics/ + if-no-files-found: warn + retention-days: 14 + compression-level: 1 + - name: Clean Up + if: ${{ always() }} + continue-on-error: true run: | cd ./docker/development - docker compose down --remove-orphans + docker compose down --remove-orphans || true sudo rm -rf "${PWD}/docker-volume" - # Single required-check gate for branch protection. - # Skipped (= "Success") when all test jobs pass or are legitimately skipped. - # Runs and exits 1 only when a test job fails or is cancelled. # Set "py-tests / py-tests-status" as the sole required check for this workflow. py-tests-status: - name: py-tests-status + name: ${{ github.event_name == 'pull_request_target' && github.event.action == 'labeled' && github.event.label.name != 'safe to test' && 'py-tests-status (ignored label)' || 'py-tests-status' }} needs: [changes, py-unit-tests, py-integration-tests] - if: ${{ failure() || cancelled() }} + if: ${{ always() && !github.event.pull_request.draft && (github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test') }} runs-on: ubuntu-latest steps: - - run: exit 1 + - name: Verify all expected Python jobs completed + env: + CHANGES_RESULT: ${{ needs.changes.result }} + PYTHON_CHANGED: ${{ needs.changes.outputs.python }} + UNIT_RESULT: ${{ needs.py-unit-tests.result }} + INTEGRATION_RESULT: ${{ needs.py-integration-tests.result }} + run: | + if [ "$CHANGES_RESULT" != "success" ]; then + echo "Python preflight did not succeed: $CHANGES_RESULT" + exit 1 + fi + + if [ "$PYTHON_CHANGED" = "true" ]; then + if [ "$UNIT_RESULT" != "success" ] || [ "$INTEGRATION_RESULT" != "success" ]; then + echo "Expected Python jobs did not succeed: unit=$UNIT_RESULT integration=$INTEGRATION_RESULT" + exit 1 + fi + elif [ "$PYTHON_CHANGED" = "false" ]; then + if [ "$UNIT_RESULT" != "skipped" ] || [ "$INTEGRATION_RESULT" != "skipped" ]; then + echo "Unexpected Python job result for an unchanged tree: unit=$UNIT_RESULT integration=$INTEGRATION_RESULT" + exit 1 + fi + else + echo "Python change detection produced an invalid result: $PYTHON_CHANGED" + exit 1 + fi + shell: bash py-combine-coverage: needs: [changes, py-unit-tests, py-integration-tests] - if: ${{ needs.changes.outputs.python == 'true' && !cancelled() }} + if: ${{ always() && needs.changes.outputs.python == 'true' && needs.py-unit-tests.result == 'success' && needs.py-integration-tests.result == 'success' }} runs-on: ubuntu-latest timeout-minutes: 10 + continue-on-error: true steps: - name: Checkout uses: actions/checkout@v4 with: - ref: ${{ github.event_name == 'merge_group' && github.sha || github.event.pull_request.head.sha }} + ref: ${{ github.event_name == 'pull_request_target' && github.event.pull_request.merge_commit_sha || github.sha }} fetch-depth: 0 filter: blob:none @@ -305,20 +435,3 @@ jobs: with: projectBaseDir: ingestion/ args: ${{ env.SONAR_OPTS }} - - # next two steps are for retrying "Push Results in PR to Sonar" step in case it fails - - name: Wait to retry 'Push Results in PR to Sonar' - if: ${{ github.event_name == 'pull_request_target' && steps.push-to-sonar.outcome != 'success' }} - run: sleep 20s - shell: bash - - - name: Retry 'Push Results in PR to Sonar' - uses: SonarSource/sonarqube-scan-action@v7 - if: ${{ github.event_name == 'pull_request_target' && steps.push-to-sonar.outcome != 'success' }} - continue-on-error: true - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - SONAR_TOKEN: ${{ secrets.INGESTION_SONAR_SECRET }} - with: - projectBaseDir: ingestion/ - args: ${{ env.SONAR_OPTS }} diff --git a/ingestion/tests/integration/lineage/e2e/conftest.py b/ingestion/tests/integration/lineage/e2e/conftest.py index f1287bc4ae56..2e392af323ac 100644 --- a/ingestion/tests/integration/lineage/e2e/conftest.py +++ b/ingestion/tests/integration/lineage/e2e/conftest.py @@ -4,6 +4,7 @@ import oracledb import pytest +from tenacity import retry, retry_if_exception_type, stop_after_delay, wait_fixed from _openmetadata_testutils.ometa import int_admin_ometa from metadata.generated.schema.entity.services.databaseService import DatabaseService @@ -11,6 +12,7 @@ from metadata.workflow.metadata import MetadataWorkflow ORACLE_LINEAGE_SERVICE_NAME = "oracle-local-lineage-test-service" +EXPECTED_ORACLE_VIEWS = {"view_1", "view_2", "view_3", "view_4"} ORACLE_COMMON_CONFIG = { "source": { @@ -119,6 +121,8 @@ def oracle_lineage_ingestion(oracle_lineage_service_name, metadata): metadata_workflow.execute() print("Metadata ingestion workflow completed.") # noqa: T201 + _wait_for_oracle_views_to_be_indexed(metadata, oracle_lineage_service_name) + print("\nRunning lineage ingestion workflow for lineage tests...") # noqa: T201 lineage_workflow_config = OpenMetadataWorkflowConfig.model_validate(ORACLE_LINEAGE_CONFIG) lineage_workflow: IngestionWorkflow = MetadataWorkflow(lineage_workflow_config) @@ -134,6 +138,18 @@ def oracle_lineage_ingestion(oracle_lineage_service_name, metadata): print("Lineage test service cleaned up.") # noqa: T201 +@retry( + retry=retry_if_exception_type(AssertionError), + wait=wait_fixed(1), + stop=stop_after_delay(30), + reraise=True, +) +def _wait_for_oracle_views_to_be_indexed(metadata, service_name: str) -> None: + indexed_views = {view.table_name.lower() for view in metadata.yield_es_view_def(service_name=service_name)} + missing_views = EXPECTED_ORACLE_VIEWS - indexed_views + assert not missing_views, f"Oracle views are not indexed yet: {sorted(missing_views)}" + + def _grant_query_privileges(container): print("\nGranting query privileges to test user...") # noqa: T201 diff --git a/ingestion/tests/integration/lineage/e2e/test_view_lineage.py b/ingestion/tests/integration/lineage/e2e/test_view_lineage.py index 3bfd95f729a5..2952bfd97023 100644 --- a/ingestion/tests/integration/lineage/e2e/test_view_lineage.py +++ b/ingestion/tests/integration/lineage/e2e/test_view_lineage.py @@ -1,10 +1,7 @@ -import pytest - from ingestion.tests.integration.lineage.e2e.helpers import assert_lineage from metadata.generated.schema.entity.data.table import Table -@pytest.mark.flaky(reruns=3) def test_view_1_lineage( oracle_lineage_container, oracle_lineage_ingestion, @@ -20,7 +17,6 @@ def test_view_1_lineage( assert_lineage(lineage, {"BASE_TABLE"}, None, None) -@pytest.mark.flaky(reruns=3) def test_view_2_lineage( oracle_lineage_container, oracle_lineage_ingestion, @@ -36,7 +32,6 @@ def test_view_2_lineage( assert_lineage(lineage, {"view_1"}, None, None) -@pytest.mark.flaky(reruns=3) def test_view_3_lineage( oracle_lineage_container, oracle_lineage_ingestion, @@ -52,7 +47,6 @@ def test_view_3_lineage( assert_lineage(lineage, {"SOURCE_TABLE_1", "SOURCE_TABLE_2"}, None, None) -@pytest.mark.flaky(reruns=3) def test_view_4_lineage( oracle_lineage_container, oracle_lineage_ingestion, diff --git a/ingestion/tests/integration/trino/conftest.py b/ingestion/tests/integration/trino/conftest.py index b458571ae988..14145b970fa9 100644 --- a/ingestion/tests/integration/trino/conftest.py +++ b/ingestion/tests/integration/trino/conftest.py @@ -2,7 +2,6 @@ import random import uuid from pathlib import Path -from time import sleep import docker import pandas as pd @@ -10,7 +9,8 @@ import testcontainers.core.network from sqlalchemy import create_engine, insert, text from sqlalchemy.engine import Engine, make_url -from tenacity import retry, stop_after_delay, wait_fixed +from sqlalchemy.exc import OperationalError +from tenacity import retry, retry_if_exception_type, stop_after_delay, wait_fixed from testcontainers.core.container import DockerContainer from testcontainers.core.generic import DbContainer from testcontainers.minio import MinioContainer @@ -32,6 +32,10 @@ from ..conftest import ingestion_config as base_ingestion_config # noqa: F401, TID252 +class TrinoTableNotReadyError(RuntimeError): + pass + + class TrinoContainer(DbContainer): def __init__( self, @@ -209,17 +213,17 @@ def _execute_with_connect(sql): file_path = Path(os.path.join(data_dir, file)) # noqa: PTH118 if file_path.suffix == ".sql": - create_test_data_from_sql(engine, file_path) + expected_rows = create_test_data_from_sql(engine, file_path) else: - create_test_data_from_parquet(engine, file_path) + expected_rows = create_test_data_from_parquet(engine, file_path) - sleep(1) + wait_for_table_data(engine, file_path.stem, expected_rows) _execute_with_connect("ANALYZE " + f'minio."my_schema"."{file_path.stem}"') _execute_with_connect("CALL system.drop_stats(schema_name => 'my_schema', table_name => 'empty')") return -def create_test_data_from_parquet(engine: Engine, file_path: Path): +def create_test_data_from_parquet(engine: Engine, file_path: Path) -> int: df = pd.read_parquet(file_path) # Convert data types @@ -235,9 +239,10 @@ def create_test_data_from_parquet(engine: Engine, file_path: Path): index=False, method=custom_insert, ) + return len(df.index) -def create_test_data_from_sql(engine: Engine, file_path: Path): +def create_test_data_from_sql(engine: Engine, file_path: Path) -> None: with open(file_path, "r") as f: # noqa: PTH123 sql = f.read() @@ -250,25 +255,34 @@ def create_test_data_from_sql(engine: Engine, file_path: Path): conn.commit() +@retry( + retry=retry_if_exception_type(TrinoTableNotReadyError), + wait=wait_fixed(1), + stop=stop_after_delay(30), + reraise=True, +) +def wait_for_table_data(engine: Engine, table_name: str, expected_rows: int | None) -> None: + try: + with engine.connect() as conn: + row_count = conn.execute(text(f'SELECT COUNT(*) FROM "my_schema"."{table_name}"')).scalar_one() + except OperationalError as exc: + error_message = str(exc) + if "HIVE_CANNOT_OPEN_SPLIT" not in error_message or "File does not exist" not in error_message: + raise + raise TrinoTableNotReadyError(f"Trino data files for [{table_name}] are not readable yet") from exc + + if expected_rows is not None and row_count != expected_rows: + raise TrinoTableNotReadyError( + f"Trino table [{table_name}] contains [{row_count}] rows; expected [{expected_rows}]" + ) + + def custom_insert(self, conn, keys: list[str], data_iter): - """ - Hack pandas.io.sql.SQLTable._execute_insert_multi to retry untill rows are inserted. - This is required becauase using trino with pd.to_sql in our setup us unreliable. - """ - rowcount = 0 - max_tries = 20 - try_num = 0 data = [dict(zip(keys, row)) for row in data_iter] # noqa: B905 - while rowcount != len(data): - if try_num >= max_tries: - raise RuntimeError(f"Failed to insert data after {max_tries} tries") - if try_num > 0: - sleep(min(try_num, 5)) - try_num += 1 + if data: stmt = insert(self.table).values(data) conn.execute(stmt) - rowcount = conn.execute(text("SELECT COUNT(*) FROM " + f'"{self.schema}"."{self.name}"')).scalar() - return rowcount + return len(data) @pytest.fixture(scope="module") diff --git a/openmetadata-integration-tests/pom.xml b/openmetadata-integration-tests/pom.xml index 6b21e22e8eee..b0f2ae01427d 100644 --- a/openmetadata-integration-tests/pom.xml +++ b/openmetadata-integration-tests/pom.xml @@ -15,6 +15,15 @@ ${org.junit.jupiter.version} ${org.junit.platform.version} 3.4.2 + dynamic + 4 + 16 + false + false + 3600 + TagRecognizerFeedbackIT,WorkflowDefinitionResourceIT,AppsResourceIT,SystemResourceIT,VectorEmbeddingIntegrationIT,PatchTableEmbeddingIT,GlossaryOntologyExportIT,UserMetricsResourceIT + SessionMultiNodeIT,SessionRedisMultiNodeIT + SearchIndexRetryQueueIT sso-bootstrap @@ -275,6 +284,14 @@ + + org.apache.maven.plugins + maven-failsafe-plugin + ${maven.failsafe.version} + + true + + org.apache.maven.plugins maven-jar-plugin @@ -310,6 +327,63 @@ + + + integration-lane-parallel + + + integrationTests.lane + parallel + + + + true + false + + + + integration-lane-global-state + + + integrationTests.lane + global-state + + + + false + true + ${integrationTests.globalStateTests} + + + + integration-lane-multi-node + + + integrationTests.lane + multi-node + + + + false + true + ${integrationTests.multiNodeTests} + + + + integration-lane-retry-queue + + + integrationTests.lane + retry-queue + + + + false + true + ${integrationTests.retryQueueTests} + + mysql-elasticsearch @@ -323,23 +397,31 @@ maven-failsafe-plugin ${maven.failsafe.version} - + - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java mysql @@ -362,8 +444,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -371,12 +455,17 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/tests/search/*IT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -388,6 +477,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} scale false @@ -417,24 +509,30 @@ maven-failsafe-plugin ${maven.failsafe.version} - + - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java postgres @@ -457,8 +555,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -466,6 +566,7 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java @@ -473,6 +574,9 @@ **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -484,6 +588,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} false plain @@ -515,22 +622,28 @@ ${maven.failsafe.version} - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java postgres @@ -554,8 +667,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -563,6 +678,7 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java @@ -570,6 +686,9 @@ **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -583,6 +702,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} false plain @@ -610,23 +732,30 @@ maven-failsafe-plugin ${maven.failsafe.version} - + - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java postgres @@ -649,8 +778,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -658,12 +789,17 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/tests/search/*IT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -675,6 +811,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} false plain @@ -703,24 +842,30 @@ maven-failsafe-plugin ${maven.failsafe.version} - + - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java mysql @@ -743,8 +888,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -752,6 +899,7 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java @@ -759,6 +907,9 @@ **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -770,6 +921,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} false plain @@ -799,21 +953,28 @@ ${maven.failsafe.version} - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java mysql @@ -837,8 +998,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -846,12 +1009,17 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/tests/search/*IT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -865,6 +1033,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} false plain @@ -883,20 +1054,22 @@ cache-tests @@ -905,24 +1078,30 @@ maven-failsafe-plugin ${maven.failsafe.version} - + - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java postgres @@ -947,8 +1126,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -956,6 +1137,7 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java @@ -963,6 +1145,9 @@ **/VectorEmbeddingIntegrationIT.java **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -976,6 +1161,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} false plain @@ -1004,23 +1192,30 @@ maven-failsafe-plugin ${maven.failsafe.version} - + - sequential-tests + isolated-tests integration-test + ${integrationTests.skipIsolated} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java true @@ -1045,8 +1240,10 @@ integration-test + ${integrationTests.skipParallel} 1 true + ${integrationTests.forkTimeoutSeconds} -Xmx4096m -XX:+UseG1GC **/*IT.java @@ -1054,12 +1251,17 @@ **/TagRecognizerFeedbackIT.java + **/UserMetricsResourceIT.java **/WorkflowDefinitionResourceIT.java **/AppsResourceIT.java **/SystemResourceIT.java **/tests/search/*IT.java **/VectorEmbeddingIntegrationIT.java + **/PatchTableEmbeddingIT.java **/GlossaryOntologyExportIT.java + **/SessionMultiNodeIT.java + **/SessionRedisMultiNodeIT.java + **/SearchIndexRetryQueueIT.java **/*UIIT.java **/tests/search/scale/** @@ -1073,6 +1275,9 @@ true true + ${integrationTests.parallelStrategy} + ${integrationTests.parallelism} + ${integrationTests.maxPoolSize} false plain diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java index 1fbe3f984ce8..b4d2aa775e29 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/UserMetricsResourceIT.java @@ -34,7 +34,6 @@ import java.util.List; import java.util.Map; import java.util.stream.Collectors; -import org.awaitility.Awaitility; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.parallel.Execution; import org.junit.jupiter.api.parallel.ExecutionMode; @@ -45,7 +44,6 @@ import org.openmetadata.schema.entity.teams.User; import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.sdk.client.OpenMetadataClient; -import org.openmetadata.sdk.models.ListParams; import org.openmetadata.sdk.services.teams.UserService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -208,45 +206,30 @@ private void verifyMetricsStructure(String response) { void testUserMetricsWithRealActivity() throws Exception { OpenMetadataClient adminClient = SdkClients.adminClient(); TestNamespace ns = new TestNamespace("UserMetricsResourceIT"); - - Map initialMetrics = getUserMetrics(); - LOG.info("Initial metrics: {}", initialMetrics); - - String userName = ns.prefix("metricsuser"); - String email = "metricsuser_" + ns.shortPrefix() + "@test.openmetadata.org"; - CreateUser createUser = new CreateUser().withName(userName).withEmail(email).withIsBot(false); - UserService usersApi = adminClient.users(); - User newUser = usersApi.create(createUser); - LOG.info("Created new user: {}", newUser.getName()); + List createdUsers = new ArrayList<>(); + int initialTotalUsers = (Integer) getUserMetrics().get("total_users"); try { - usersApi.getByName(newUser.getName()); - - Awaitility.await("Wait for user metrics to reflect new user") - .atMost(Duration.ofSeconds(30)) - .pollDelay(Duration.ofMillis(500)) - .pollInterval(Duration.ofSeconds(1)) - .ignoreExceptions() - .untilAsserted( - () -> { - assertNotNull(usersApi.getByName(newUser.getName())); - Map m = getUserMetrics(); - int total = (Integer) m.get("total_users"); - assertTrue( - total >= listUserTotal(usersApi), - "Metrics should include every visible user while the created user exists"); - }); + for (int i = 0; i < 3; i++) { + String userName = ns.prefix("metricsuser" + i); + String email = "metricsuser" + i + "_" + ns.shortPrefix() + "@test.openmetadata.org"; + createdUsers.add( + usersApi.create(new CreateUser().withName(userName).withEmail(email).withIsBot(false))); + } + + for (User createdUser : createdUsers) { + User fetchedUser = usersApi.getByName(createdUser.getName()); + assertEquals(createdUser.getId(), fetchedUser.getId(), "Created user should be readable"); + } Map updatedMetrics = getUserMetrics(); LOG.info("Updated metrics after activity: {}", updatedMetrics); int updatedTotalUsers = (Integer) updatedMetrics.get("total_users"); assertTrue( - updatedTotalUsers > 0, - "Metrics should report at least one user while the created user exists"); - User fetchedUser = usersApi.getByName(newUser.getName()); - assertNotNull(fetchedUser, "Created user should exist"); + updatedTotalUsers >= initialTotalUsers + createdUsers.size(), + "Metrics should include every user created and kept alive by this test"); String lastActivity = (String) updatedMetrics.get("last_activity"); assertNotNull(lastActivity, "Last activity should not be null after user activity"); @@ -265,18 +248,14 @@ void testUserMetricsWithRealActivity() throws Exception { int dailyActiveUsers = (Integer) updatedMetrics.get("daily_active_users"); assertTrue(dailyActiveUsers >= 0, "Daily active users should be non-negative"); } finally { - Map deleteParams = new HashMap<>(); - deleteParams.put("hardDelete", "true"); - usersApi.delete(newUser.getId().toString(), deleteParams); + for (User createdUser : createdUsers) { + Map deleteParams = new HashMap<>(); + deleteParams.put("hardDelete", "true"); + usersApi.delete(createdUser.getId().toString(), deleteParams); + } } } - private int listUserTotal(UserService usersApi) { - ListParams params = new ListParams(); - params.setLimit(1); - return usersApi.list(params).getPaging().getTotal(); - } - @Test void testUserMetricsWithBotUser() throws Exception { Map initialMetrics = getUserMetrics(); @@ -289,56 +268,6 @@ void testUserMetricsWithBotUser() throws Exception { "Bot user filtering is implemented in UserMetricsServlet.createNonBotFilter() which adds isBot=false filter"); } - @Test - void testUserMetricsMultipleUsers() throws Exception { - OpenMetadataClient adminClient = SdkClients.adminClient(); - TestNamespace ns = new TestNamespace("UserMetricsResourceIT"); - UserService usersApi = adminClient.users(); - - for (int i = 0; i < 3; i++) { - String userName = ns.prefix("multiuser" + i); - String email = "multiuser" + i + "_" + ns.shortPrefix() + "@test.openmetadata.org"; - CreateUser createUser = new CreateUser().withName(userName).withEmail(email).withIsBot(false); - - User user = usersApi.create(createUser); - try { - usersApi.getByName(user.getName()); - } finally { - Map deleteParams = new HashMap<>(); - deleteParams.put("hardDelete", "true"); - usersApi.delete(user.getId().toString(), deleteParams); - } - } - - Awaitility.await("Wait for metrics to reflect user activity") - .atMost(Duration.ofSeconds(30)) - .pollDelay(Duration.ofMillis(500)) - .pollInterval(Duration.ofSeconds(1)) - .ignoreExceptions() - .until( - () -> { - Map m = getUserMetrics(); - return m.get("last_activity") != null; - }); - - Map metrics = getUserMetrics(); - LOG.info("Metrics after multiple users: {}", metrics); - - String lastActivity = (String) metrics.get("last_activity"); - assertNotNull(lastActivity, "Last activity should not be null"); - - Instant lastActivityTime = Instant.parse(lastActivity); - Instant now = Instant.now(); - long secondsSinceActivity = now.getEpochSecond() - lastActivityTime.getEpochSecond(); - assertTrue( - secondsSinceActivity < MAX_LAST_ACTIVITY_AGE.toSeconds(), - "Last activity should be within last " - + MAX_LAST_ACTIVITY_AGE.toMinutes() - + " minutes, but was " - + secondsSinceActivity - + " seconds ago"); - } - @Test void testDailyActiveUsersMetric() throws Exception { Map metrics = getUserMetrics(); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/cache/HardDeleteCacheConsistencyIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/cache/HardDeleteCacheConsistencyIT.java new file mode 100644 index 000000000000..ad592bcb242e --- /dev/null +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/cache/HardDeleteCacheConsistencyIT.java @@ -0,0 +1,131 @@ +/* + * 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. + */ +package org.openmetadata.it.tests.cache; + +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.junit.jupiter.api.Assumptions; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.openmetadata.it.bootstrap.TestSuiteBootstrap; +import org.openmetadata.it.factories.DatabaseSchemaTestFactory; +import org.openmetadata.it.factories.TableTestFactory; +import org.openmetadata.it.util.SdkClients; +import org.openmetadata.it.util.TestNamespace; +import org.openmetadata.it.util.TestNamespaceExtension; +import org.openmetadata.schema.entity.data.DatabaseSchema; +import org.openmetadata.schema.entity.data.Table; +import org.openmetadata.schema.type.Include; +import org.openmetadata.service.Entity; +import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.util.RequestEntityCache; + +@ExtendWith(TestNamespaceExtension.class) +class HardDeleteCacheConsistencyIT { + private static final String PARALLELISM_PROPERTY = + "junit.jupiter.execution.parallel.config.fixed.parallelism"; + private static final int REPETITIONS = 50; + + @BeforeAll + static void requireRedis() { + Assumptions.assumeTrue( + TestSuiteBootstrap.isRedisEnabled(), + "Hard-delete cache consistency requires cacheProvider=redis"); + } + + @Test + void staleLoaderResultCannotResurrectHardDeletedEntity(TestNamespace namespace) + throws ExecutionException, InterruptedException { + DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(namespace); + Table table = + TableTestFactory.createWithName( + namespace, schema.getFullyQualifiedName(), "hard_delete_cache"); + ImmutablePair idKey = new ImmutablePair<>(Entity.TABLE, table.getId()); + ImmutablePair nameKey = + new ImmutablePair<>(Entity.TABLE, table.getFullyQualifiedName()); + + EntityRepository.CACHE_WITH_ID.invalidate(idKey); + EntityRepository.CACHE_WITH_NAME.invalidate(nameKey); + RequestEntityCache.clear(); + Entity.getEntity(Entity.TABLE, table.getId(), "", Include.NON_DELETED, true); + String staleById = EntityRepository.CACHE_WITH_ID.getIfPresent(idKey); + assertNotNull(staleById); + + RequestEntityCache.clear(); + Entity.getEntityByName( + Entity.TABLE, table.getFullyQualifiedName(), "", Include.NON_DELETED, true); + String staleByName = EntityRepository.CACHE_WITH_NAME.getIfPresent(nameKey); + assertNotNull(staleByName); + + SdkClients.adminClient() + .tables() + .delete(table.getId().toString(), Map.of("hardDelete", "true", "recursive", "true")); + + List> attempts = new ArrayList<>(REPETITIONS * Include.values().length); + for (int repetition = 0; repetition < REPETITIONS; repetition++) { + int currentRepetition = repetition; + for (Include include : Include.values()) { + attempts.add( + () -> { + assertMissing( + table, idKey, nameKey, staleById, staleByName, include, currentRepetition); + return null; + }); + } + } + + int parallelism = Math.max(1, Integer.getInteger(PARALLELISM_PROPERTY, 4)); + try (ExecutorService executor = Executors.newFixedThreadPool(parallelism)) { + for (Future result : executor.invokeAll(attempts)) { + result.get(); + } + } + } + + private static void assertMissing( + Table table, + ImmutablePair idKey, + ImmutablePair nameKey, + String staleById, + String staleByName, + Include include, + int repetition) { + EntityRepository.CACHE_WITH_ID.put(idKey, staleById); + RequestEntityCache.clear(); + assertThrows( + EntityNotFoundException.class, + () -> Entity.getEntity(Entity.TABLE, table.getId(), "", include, true), + () -> "Stale ID cache returned for include=" + include + " repetition=" + repetition); + + EntityRepository.CACHE_WITH_NAME.put(nameKey, staleByName); + RequestEntityCache.clear(); + assertThrows( + EntityNotFoundException.class, + () -> + Entity.getEntityByName(Entity.TABLE, table.getFullyQualifiedName(), "", include, true), + () -> "Stale name cache returned for include=" + include + " repetition=" + repetition); + } +} diff --git a/openmetadata-integration-tests/src/test/resources/junit-platform.properties b/openmetadata-integration-tests/src/test/resources/junit-platform.properties index 5d2b9ca4b760..d7ab0c3a7e5a 100644 --- a/openmetadata-integration-tests/src/test/resources/junit-platform.properties +++ b/openmetadata-integration-tests/src/test/resources/junit-platform.properties @@ -3,7 +3,8 @@ junit.jupiter.execution.parallel.enabled = true junit.jupiter.execution.parallel.mode.default = concurrent junit.jupiter.execution.parallel.mode.classes.default = concurrent -# Use dynamic parallelism based on available processors +# Local runs keep adapting to available processors; CI invocations override this with a fixed, +# reported worker count so failures are reproducible without slowing high-core development hosts. junit.jupiter.execution.parallel.config.strategy = dynamic junit.jupiter.execution.parallel.config.dynamic.factor = 1.0 diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java index 9cce2099e1f8..d795bcabfe02 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java @@ -134,6 +134,8 @@ default StepStats getColumnStats() { /** Key for passing StageStatsTracker through context data to the sink. */ String STATS_TRACKER_CONTEXT_KEY = "stageStatsTracker"; + String SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY = "scriptedPartialUpdates"; + /** * Key for passing a {@code Map} through context data. Producers (the * reindex worker / retry worker / bulk update path) prepare per-entity doc-build context — diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java index 07913003b77c..8a728cf08809 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java @@ -1,5 +1,6 @@ package org.openmetadata.service.apps.bundles.searchIndex; +import static org.openmetadata.service.apps.bundles.searchIndex.BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.ENTITY_TYPE_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.RECREATE_CONTEXT; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.TARGET_INDEX_KEY; @@ -8,15 +9,18 @@ import com.fasterxml.jackson.databind.ObjectMapper; import es.co.elastic.clients.elasticsearch.ElasticsearchAsyncClient; import es.co.elastic.clients.elasticsearch._types.Refresh; +import es.co.elastic.clients.elasticsearch._types.ScriptLanguage; import es.co.elastic.clients.elasticsearch.core.BulkResponse; import es.co.elastic.clients.elasticsearch.core.bulk.BulkOperation; import es.co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem; +import es.co.elastic.clients.json.JsonData; import es.co.elastic.clients.json.jackson.JacksonJsonpMapper; import jakarta.json.stream.JsonGenerator; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; @@ -274,6 +278,8 @@ public void write(List entities, Map contextData) throws Exce contextData.containsKey(RECREATE_CONTEXT) ? (ReindexContext) contextData.get(RECREATE_CONTEXT) : null; + boolean scriptedPartialUpdates = + Boolean.TRUE.equals(contextData.get(SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY)); // Extract StageStatsTracker from context for stats recording StageStatsTracker tracker = extractTracker(contextData); @@ -330,7 +336,13 @@ public void write(List entities, Map contextData) throws Exce .map( entity -> CompletableFuture.runAsync( - () -> addEntity(entity, indexName, tracker, docBuildContexts), + () -> + addEntity( + entity, + indexName, + tracker, + docBuildContexts, + scriptedPartialUpdates), DOC_BUILD_EXECUTOR)) .toList(); CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); @@ -380,13 +392,14 @@ private void addEntity( EntityInterface entity, String indexName, StageStatsTracker tracker, - Map docBuildContexts) { + Map docBuildContexts, + boolean scriptedPartialUpdates) { try { String entityType = Entity.getEntityTypeFromObject(entity); + String docId = entity.getId().toString(); DocBuildContext ctx = docBuildContexts.getOrDefault(entity.getId(), DocBuildContext.empty()); Object searchIndexDoc = Entity.buildSearchIndex(entityType, entity).buildSearchIndexDoc(ctx); String json = JsonUtils.pojoToJson(searchIndexDoc); - String docId = entity.getId().toString(); long rawDocSize = (long) json.getBytes(StandardCharsets.UTF_8).length; long estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; @@ -405,6 +418,20 @@ private void addEntity( estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; } + if (scriptedPartialUpdates) { + SearchRepository.ScriptedPartialUpdate partialUpdate = + searchRepository.buildBulkScriptedPartialUpdate(entity); + if (partialUpdate != null + && addScriptedPartialUpdate( + indexName, docId, entityType, partialUpdate, json, tracker)) { + processSuccess.incrementAndGet(); + if (tracker != null) { + tracker.recordProcess(StatsResult.SUCCESS); + } + return; + } + } + if (estimatedSize > maxPayloadSizeBytes) { LOG.warn( "Document {} of type {} is too large for bulk ({} bytes), sending directly", @@ -467,6 +494,62 @@ private void addEntity( } } + private boolean addScriptedPartialUpdate( + String indexName, + String docId, + String entityType, + SearchRepository.ScriptedPartialUpdate partialUpdate, + String upsertDocument, + StageStatsTracker tracker) { + long estimatedSize = + (long) upsertDocument.getBytes(StandardCharsets.UTF_8).length + + JsonUtils.pojoToJson(partialUpdate.parameters()) + .getBytes(StandardCharsets.UTF_8) + .length + + partialUpdate.script().getBytes(StandardCharsets.UTF_8).length + + BULK_OPERATION_METADATA_OVERHEAD; + if (estimatedSize > maxPayloadSizeBytes) { + return false; + } + + Map params = new HashMap<>(); + partialUpdate + .parameters() + .forEach( + (key, value) -> { + if (value != null) { + params.put(key, JsonData.of(value, JACKSON_JSONP_MAPPER)); + } + }); + BulkOperation operation = + BulkOperation.of( + op -> + op.update( + update -> + update + .index(indexName) + .id(docId) + .retryOnConflict(3) + .action( + action -> + action + .upsert(EsUtils.toJsonData(upsertDocument)) + .script( + script -> + script + .source( + source -> + source.scriptString( + partialUpdate.script())) + .lang(ScriptLanguage.Painless) + .params(params))))); + if (tracker != null) { + tracker.incrementPendingSink(); + } + bulkProcessor.add(operation, docId, entityType, tracker, estimatedSize); + return true; + } + private void recordStaleReferenceWarning( EntityInterface entity, StageStatsTracker tracker, Exception e) { recordStaleReferenceWarning( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java index 6fbd7caf3998..2b0f30e1f619 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java @@ -1,5 +1,6 @@ package org.openmetadata.service.apps.bundles.searchIndex; +import static org.openmetadata.service.apps.bundles.searchIndex.BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.ENTITY_TYPE_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.RECREATE_CONTEXT; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.TARGET_INDEX_KEY; @@ -58,9 +59,12 @@ import org.openmetadata.service.search.vector.OpenSearchVectorService; import org.openmetadata.service.search.vector.VectorDocBuilder; import org.openmetadata.service.search.vector.utils.AvailableEntityTypes; +import os.org.opensearch.client.json.JsonData; import os.org.opensearch.client.json.jackson.JacksonJsonpMapper; import os.org.opensearch.client.opensearch.OpenSearchAsyncClient; +import os.org.opensearch.client.opensearch._types.BuiltinScriptLanguage; import os.org.opensearch.client.opensearch._types.Refresh; +import os.org.opensearch.client.opensearch._types.Script; import os.org.opensearch.client.opensearch.core.BulkResponse; import os.org.opensearch.client.opensearch.core.bulk.BulkOperation; import os.org.opensearch.client.opensearch.core.bulk.BulkResponseItem; @@ -293,6 +297,8 @@ public void write(List entities, Map contextData) throws Exce // Extract StageStatsTracker from context for stats recording StageStatsTracker tracker = extractTracker(contextData); + boolean scriptedPartialUpdates = + Boolean.TRUE.equals(contextData.get(SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY)); // Check if embeddings are enabled for this specific entity type boolean embeddingsEnabled = isVectorEmbeddingEnabledForEntity(entityType); @@ -387,7 +393,8 @@ public void write(List entities, Map contextData) throws Exce tracker, embeddingsEnabled, finalEmbeddingsById, - docBuildContexts), + docBuildContexts, + scriptedPartialUpdates), DOC_BUILD_EXECUTOR)) .toList(); CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); @@ -440,9 +447,11 @@ private void addEntity( StageStatsTracker tracker, boolean embeddingsEnabled, Map existingEmbeddingsById, - Map docBuildContexts) { + Map docBuildContexts, + boolean scriptedPartialUpdates) { try { String entityType = Entity.getEntityTypeFromObject(entity); + String docId = entity.getId().toString(); DocBuildContext ctx = docBuildContexts.getOrDefault(entity.getId(), DocBuildContext.empty()); Object searchIndexDoc = Entity.buildSearchIndex(entityType, entity).buildSearchIndexDoc(ctx); String json = JsonUtils.pojoToJson(searchIndexDoc); @@ -452,7 +461,6 @@ private void addEntity( } String finalJson = json; - String docId = entity.getId().toString(); long rawDocSize = (long) finalJson.getBytes(StandardCharsets.UTF_8).length; long estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; @@ -471,6 +479,20 @@ private void addEntity( estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; } + if (scriptedPartialUpdates) { + SearchRepository.ScriptedPartialUpdate partialUpdate = + searchRepository.buildBulkScriptedPartialUpdate(entity); + if (partialUpdate != null + && addScriptedPartialUpdate( + indexName, docId, entityType, partialUpdate, finalJson, tracker)) { + processSuccess.incrementAndGet(); + if (tracker != null) { + tracker.recordProcess(StatsResult.SUCCESS); + } + return; + } + } + if (estimatedSize > maxPayloadSizeBytes) { LOG.warn( "Document {} of type {} is too large for bulk ({} bytes), sending directly", @@ -533,6 +555,62 @@ private void addEntity( } } + private boolean addScriptedPartialUpdate( + String indexName, + String docId, + String entityType, + SearchRepository.ScriptedPartialUpdate partialUpdate, + String upsertDocument, + StageStatsTracker tracker) { + long estimatedSize = + (long) upsertDocument.getBytes(StandardCharsets.UTF_8).length + + JsonUtils.pojoToJson(partialUpdate.parameters()) + .getBytes(StandardCharsets.UTF_8) + .length + + partialUpdate.script().getBytes(StandardCharsets.UTF_8).length + + BULK_OPERATION_METADATA_OVERHEAD; + if (estimatedSize > maxPayloadSizeBytes) { + return false; + } + + Map params = new HashMap<>(); + partialUpdate + .parameters() + .forEach( + (key, value) -> { + if (value != null) { + params.put(key, JsonData.of(value, JACKSON_JSONP_MAPPER)); + } + }); + BulkOperation operation = + BulkOperation.of( + op -> + op.update( + update -> + update + .index(indexName) + .id(docId) + .retryOnConflict(3) + .upsert(OsUtils.toJsonData(upsertDocument)) + .script( + Script.of( + script -> + script.inline( + inline -> + inline + .lang( + language -> + language.builtin( + BuiltinScriptLanguage.Painless)) + .source(partialUpdate.script()) + .params(params)))))); + if (tracker != null) { + tracker.incrementPendingSink(); + } + bulkProcessor.add(operation, docId, entityType, tracker, estimatedSize); + return true; + } + private void recordStaleReferenceWarning( EntityInterface entity, StageStatsTracker tracker, Exception e) { recordStaleReferenceWarning( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java index d573f2429c76..0e98d9b60176 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheBundle.java @@ -6,6 +6,10 @@ import io.dropwizard.core.setup.Environment; import io.dropwizard.lifecycle.Managed; import io.micrometer.core.instrument.Metrics; +import java.util.HashSet; +import java.util.Map; +import java.util.Set; +import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.openmetadata.service.Entity; import org.openmetadata.service.OpenMetadataApplicationConfig; @@ -72,8 +76,7 @@ public void run(OpenMetadataApplicationConfig configuration, Environment environ } CacheKeys keys = new CacheKeys(cacheConfig.redis.keyspace); - cachedEntityDao = - new CachedEntityDao(Entity.getCollectionDAO(), cacheProvider, keys, cacheConfig); + cachedEntityDao = new CachedEntityDao(cacheProvider, keys, cacheConfig); cachedRelationshipDao = new CachedRelationshipDao(Entity.getCollectionDAO(), cacheProvider, keys, cacheConfig); cachedTagUsageDao = @@ -118,6 +121,13 @@ public void run(OpenMetadataApplicationConfig configuration, Environment environ // the path new cache layers should plug into — implement Invalidatable, call // registerInvalidatable, and the remote-pod invalidation Just Works. for (Invalidatable layer : INVALIDATABLES) { + // NotFoundCache is Redis-backed and therefore already shared by every pod. A + // remote entity invalidation must not delete a hard-delete tombstone that the + // writer just installed after removing the row. Create/restore paths still clear + // the shared marker directly through CacheBundle.invalidateEntity(). + if (layer instanceof NotFoundCache) { + continue; + } try { layer.invalidate(msg.type(), msg.id(), msg.fqn()); } catch (Exception ex) { @@ -231,7 +241,7 @@ public static void registerInvalidatable(Invalidatable layer) { * *

No-op if no layers are registered (cache disabled or none registered yet). */ - public static void invalidateEntity(String type, java.util.UUID id, String fqn) { + public static void invalidateEntity(String type, UUID id, String fqn) { for (Invalidatable layer : INVALIDATABLES) { try { layer.invalidate(type, id, fqn); @@ -241,6 +251,53 @@ public static void invalidateEntity(String type, java.util.UUID id, String fqn) } } + public static Set invalidateEntities(String type, Map entities) { + if (entities == null || entities.isEmpty()) { + return Set.of(); + } + Set hardDeleteWinners = new HashSet<>(); + for (Invalidatable layer : INVALIDATABLES) { + try { + if (layer instanceof NotFoundCache negativeCache) { + hardDeleteWinners.addAll(negativeCache.invalidateAll(type, entities)); + } else if (layer instanceof CachedLineage lineageCache) { + lineageCache.invalidateAll(entities.keySet()); + } else { + entities.forEach((id, fqn) -> layer.invalidate(type, id, fqn)); + } + } catch (Exception e) { + LOG.debug("Invalidatable {} failed for {} created entities", layer, entities.size(), e); + } + } + return hardDeleteWinners; + } + + /** + * Invalidate an entity after an update while preserving a hard-delete tombstone that may have + * committed between the database update and its post-commit cache write-through. + */ + public static boolean invalidateEntityPreservingHardDelete(String type, UUID id, String fqn) { + boolean hardDeleteWon = false; + for (Invalidatable layer : INVALIDATABLES) { + try { + if (layer instanceof NotFoundCache negativeCache) { + hardDeleteWon |= negativeCache.invalidatePreservingHardDelete(type, id, fqn); + } else { + layer.invalidate(type, id, fqn); + } + } catch (Exception e) { + LOG.debug( + "Invalidatable {} failed after update for type={} id={} fqn={}", + layer, + type, + id, + fqn, + e); + } + } + return hardDeleteWon; + } + public static CacheInvalidationPubSub getCacheInvalidationPubSub() { return cacheInvalidationPubSub; } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java index 3813f98b2b8f..9926184510b7 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CacheProvider.java @@ -23,6 +23,23 @@ default boolean deleteIfValue(String key, String expectedValue) { return false; } + /** + * Deletes each key only when its current value matches the corresponding expected value. + * Implementations should pipeline the atomic compare-and-delete operations when possible. + */ + default int deleteIfValues(Map expectedValues) { + if (expectedValues == null || expectedValues.isEmpty()) { + return 0; + } + int deleted = 0; + for (Map.Entry entry : expectedValues.entrySet()) { + if (deleteIfValue(entry.getKey(), entry.getValue())) { + deleted++; + } + } + return deleted; + } + Optional hget(String key, String field); void hset(String key, Map fields, Duration ttl); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedEntityDao.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedEntityDao.java index b49a50eccece..7e1787209909 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedEntityDao.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedEntityDao.java @@ -6,79 +6,31 @@ import java.util.UUID; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.openmetadata.service.Entity; -import org.openmetadata.service.jdbi3.CollectionDAO; -import org.openmetadata.service.jdbi3.EntityDAO; -import org.openmetadata.service.jdbi3.EntityRepository; @Slf4j @RequiredArgsConstructor public class CachedEntityDao { - private final CollectionDAO dao; private final CacheProvider cache; private final CacheKeys keys; private final CacheConfig config; - public String getBase(UUID entityId, String entityType) { - // Reindex worker threads opt out of the cache via EntityCacheBypass so a 580k-entity reindex - // doesn't generate millions of pointless Redis writes (cache hit rate during reindex ≈ 0) - // and isn't held hostage to Redis health (300ms timeouts add up fast at this volume). Go - // straight to DB; skip the write-through. + public Optional getBase(UUID entityId, String entityType) { if (EntityCacheBypass.isSkipped()) { - String entityJson = fetchEntityFromDatabase(entityId, entityType); - return entityJson != null ? entityJson : "{}"; + return Optional.empty(); } String cacheKey = keys.entity(entityType, entityId); - - // Try to get from cache first Optional cached = cache.hget(cacheKey, "base"); CacheMetrics m = CacheMetrics.getInstance(); if (cached.isPresent()) { LOG.debug("Cache hit for entity: {} -> {}", entityType, entityId); if (m != null) m.recordLayerHit(entityType); - return cached.get(); + return cached; } LOG.debug("Cache miss for entity: {} -> {}", entityType, entityId); if (m != null) m.recordLayerMiss(entityType); - - // Fetch from database - String entityJson = fetchEntityFromDatabase(entityId, entityType); - - // Write to cache (write-through caching) - if (entityJson != null && !entityJson.equals("{}")) { - try { - cache.hset( - cacheKey, Map.of("base", entityJson), Duration.ofSeconds(config.entityTtlSeconds)); - if (m != null) m.recordLayerWrite(entityType); - LOG.debug("Cached entity: {} -> {}", entityType, entityId); - } catch (Exception e) { - LOG.warn("Failed to cache entity: {} -> {}", entityType, entityId, e); - } - } - - return entityJson != null ? entityJson : "{}"; - } - - private String fetchEntityFromDatabase(UUID entityId, String entityType) { - try { - // Directly fetch the raw JSON from database - this will have null relationship fields - // just like how it's stored in the database - EntityRepository repository = Entity.getEntityRepository(entityType); - if (repository != null && repository.getDao() != null) { - EntityDAO entityDao = repository.getDao(); - String tableName = entityDao.getTableName(); - String entityJson = entityDao.findById(tableName, entityId, ""); - if (entityJson != null && !entityJson.isEmpty()) { - LOG.debug("Fetched raw entity JSON from database: {} -> {}", entityType, entityId); - return entityJson; - } - } - } catch (Exception e) { - LOG.debug("Failed to fetch entity from database: {} -> {}", entityType, entityId, e); - } - return null; + return Optional.empty(); } /** diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedLineage.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedLineage.java index 2aaca8113dfd..ebc6e225b82b 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedLineage.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/CachedLineage.java @@ -14,8 +14,14 @@ import com.google.common.util.concurrent.Striped; import java.time.Duration; +import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Objects; import java.util.Optional; +import java.util.Set; import java.util.UUID; import java.util.concurrent.locks.Lock; import java.util.function.Supplier; @@ -46,6 +52,7 @@ */ @Slf4j public final class CachedLineage implements Invalidatable { + private static final int INVALIDATION_BATCH_SIZE = 500; private final CacheProvider cache; private final CacheKeys keys; private final int ttlSeconds; @@ -129,6 +136,24 @@ public void invalidate(UUID rootId) { } } + public void invalidateAll(Collection rootIds) { + if (!enabled() || rootIds == null || rootIds.isEmpty()) return; + try { + Set uniqueKeys = new LinkedHashSet<>(rootIds.size()); + rootIds.stream() + .filter(Objects::nonNull) + .map(keys::lineageGraphHash) + .forEach(uniqueKeys::add); + List cacheKeys = new ArrayList<>(uniqueKeys); + for (int offset = 0; offset < cacheKeys.size(); offset += INVALIDATION_BATCH_SIZE) { + int end = Math.min(offset + INVALIDATION_BATCH_SIZE, cacheKeys.size()); + cache.del(cacheKeys.subList(offset, end).toArray(String[]::new)); + } + } catch (Exception e) { + LOG.debug("Lineage batch invalidate failed count={}", rootIds.size(), e); + } + } + /** Convenience for the lineage edge mutation hooks — invalidates both endpoints. */ public void invalidateEdge(UUID fromId, UUID toId) { invalidate(fromId); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/NotFoundCache.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/NotFoundCache.java index 5d557070b000..7fa3b3929672 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/NotFoundCache.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/NotFoundCache.java @@ -13,6 +13,15 @@ package org.openmetadata.service.cache; import java.time.Duration; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; import java.util.UUID; import lombok.extern.slf4j.Slf4j; @@ -23,17 +32,24 @@ * invalidation, a UI flow that creates an entity and immediately reads it would hit the * negative cache and 404 for up to 30s. * - *

Targets: typo'd FQN lookups, references to deleted entities embedded in old links, repeat - * lookups for entities that were never created. Each of these would otherwise hammer the DB - * with a wasted SELECT on every retry. + *

Normal misses are only authoritative for non-deleted reads because a soft-deleted row may + * still match {@code Include.DELETED} or {@code Include.ALL}. Hard-delete markers are distinct and + * authoritative for every include mode, preventing a racing loader from serving an entity that no + * longer exists. * *

Cache-off semantics: {@link #enabled()} returns false when {@code notFoundTtlSeconds <= 0} - * or the provider is unavailable. {@link #isMarkedNotFound} then returns false (treat as - * "we don't know"), forcing the caller down the normal DB path. Same-shape contract as the - * other optional layers. + * or the provider is unavailable. Marker reads then return false (treat as "we don't know"), + * forcing the caller down the normal DB path. Same-shape contract as the other optional layers. */ @Slf4j public final class NotFoundCache implements Invalidatable { + private static final int INVALIDATION_BATCH_SIZE = 500; + private static final int INVALIDATION_CAS_ATTEMPTS = 3; + private static final String LEGACY_NOT_FOUND = "1"; + private static final String NOT_FOUND = "not-found"; + private static final String HARD_DELETED = "hard-deleted"; + private static final String HARD_DELETED_NAME_PREFIX = HARD_DELETED + ":"; + private final CacheProvider cache; private final CacheKeys keys; private final int ttlSeconds; @@ -49,40 +65,265 @@ public boolean enabled() { } public boolean isMarkedNotFoundById(String type, UUID id) { - if (!enabled()) return false; + return markerById(type, id).isPresent(); + } + + public boolean isMarkedNotFoundByName(String type, String fqn) { + return markerByName(type, fqn).isPresent(); + } + + public boolean isMarkedHardDeletedById(String type, UUID id) { + return markerById(type, id).filter(NotFoundCache::isHardDeletedMarker).isPresent(); + } + + public boolean isMarkedHardDeletedByName(String type, String fqn) { + return markerByName(type, fqn).filter(NotFoundCache::isHardDeletedMarker).isPresent(); + } + + public boolean isKnownMissingById(String type, UUID id, boolean includeNormalMisses) { + return isKnownMissing(markerById(type, id), includeNormalMisses); + } + + public boolean isKnownMissingByName(String type, String fqn, boolean includeNormalMisses) { + return isKnownMissing(markerByName(type, fqn), includeNormalMisses); + } + + public void markNotFoundById(String type, UUID id) { + if (!enabled()) return; try { - return cache.get(keys.notFoundById(type, id)).isPresent(); + cache.setIfAbsent(keys.notFoundById(type, id), NOT_FOUND, Duration.ofSeconds(ttlSeconds)); } catch (Exception e) { - LOG.debug("notFound cache read failed (treated as not-cached) type={} id={}", type, id, e); - return false; + LOG.debug("notFound cache write failed type={} id={}", type, id, e); } } - public boolean isMarkedNotFoundByName(String type, String fqn) { - if (!enabled()) return false; + public void markNotFoundByName(String type, String fqn) { + if (!enabled()) return; try { - return cache.get(keys.notFoundByName(type, fqn)).isPresent(); + cache.setIfAbsent(keys.notFoundByName(type, fqn), NOT_FOUND, Duration.ofSeconds(ttlSeconds)); } catch (Exception e) { - LOG.debug("notFound cache read failed (treated as not-cached) type={} fqn={}", type, fqn, e); - return false; + LOG.debug("notFound cache write failed type={} fqn={}", type, fqn, e); } } - public void markNotFoundById(String type, UUID id) { + public void markHardDeletedById(String type, UUID id) { if (!enabled()) return; try { - cache.set(keys.notFoundById(type, id), "1", Duration.ofSeconds(ttlSeconds)); + cache.set(keys.notFoundById(type, id), HARD_DELETED, Duration.ofSeconds(ttlSeconds)); } catch (Exception e) { - LOG.debug("notFound cache write failed type={} id={}", type, id, e); + LOG.debug("hardDelete cache write failed type={} id={}", type, id, e); } } - public void markNotFoundByName(String type, String fqn) { + public void markHardDeletedByName(String type, String fqn, UUID id) { if (!enabled()) return; try { - cache.set(keys.notFoundByName(type, fqn), "1", Duration.ofSeconds(ttlSeconds)); + String marker = id == null ? HARD_DELETED : HARD_DELETED_NAME_PREFIX + id; + cache.set(keys.notFoundByName(type, fqn), marker, Duration.ofSeconds(ttlSeconds)); } catch (Exception e) { - LOG.debug("notFound cache write failed type={} fqn={}", type, fqn, e); + LOG.debug("hardDelete cache write failed type={} fqn={}", type, fqn, e); + } + } + + /** + * Clear ordinary negative entries after a successful update without erasing a hard-delete that + * committed before the updater's post-commit cache phase. Name tombstones from a different + * entity id are stale FQN-reuse markers and may be removed. Every delete is compare-and-delete, + * so a concurrent hard-delete cannot be lost between the marker read and deletion. + */ + public boolean invalidatePreservingHardDelete(String type, UUID id, String fqn) { + if (!enabled()) return false; + try { + String idKey = id == null ? null : keys.notFoundById(type, id); + String nameKey = fqn == null ? null : keys.notFoundByName(type, fqn); + List markerKeys = new ArrayList<>(2); + if (idKey != null) markerKeys.add(idKey); + if (nameKey != null) markerKeys.add(nameKey); + List> markers = cache.mget(markerKeys); + int markerIndex = 0; + Optional idMarker = idKey == null ? Optional.empty() : markers.get(markerIndex++); + Optional nameMarker = nameKey == null ? Optional.empty() : markers.get(markerIndex); + boolean hardDeleteWon = idMarker.filter(NotFoundCache::isHardDeletedMarker).isPresent(); + + if (id != null && idMarker.isPresent()) { + hardDeleteWon |= clearReplaceableMarker(idKey, idMarker.get(), id, false); + } + if (nameKey != null && nameMarker.isPresent()) { + hardDeleteWon |= clearReplaceableMarker(nameKey, nameMarker.get(), id, true); + } + return hardDeleteWon; + } catch (Exception e) { + LOG.debug("notFound update invalidate failed type={} id={} fqn={}", type, id, fqn, e); + return true; + } + } + + public Set invalidateAll(String type, Map entities) { + if (!enabled() || entities == null || entities.isEmpty()) return Set.of(); + Set hardDeleteWinners = new HashSet<>(); + try { + Map> entityIdsByKey = new LinkedHashMap<>(entities.size() * 2); + Set idKeys = new HashSet<>(entities.size()); + entities.forEach( + (id, fqn) -> { + if (id != null) { + String idKey = keys.notFoundById(type, id); + idKeys.add(idKey); + entityIdsByKey.computeIfAbsent(idKey, ignored -> new LinkedHashSet<>()).add(id); + } + if (fqn != null) { + entityIdsByKey + .computeIfAbsent(keys.notFoundByName(type, fqn), ignored -> new LinkedHashSet<>()) + .add(id); + } + }); + List cacheKeys = new ArrayList<>(entityIdsByKey.keySet()); + for (int offset = 0; offset < cacheKeys.size(); offset += INVALIDATION_BATCH_SIZE) { + int end = Math.min(offset + INVALIDATION_BATCH_SIZE, cacheKeys.size()); + List batchKeys = cacheKeys.subList(offset, end); + List> markers = cache.mget(batchKeys); + Map expectedValues = new LinkedHashMap<>(); + for (int index = 0; index < batchKeys.size(); index++) { + String key = batchKeys.get(index); + Optional marker = markers.get(index); + if (marker.isEmpty()) continue; + classifyBatchMarker( + key, marker.get(), idKeys, entityIdsByKey, expectedValues, hardDeleteWinners); + } + deleteReplaceableMarkers(expectedValues, idKeys, entityIdsByKey, hardDeleteWinners); + } + } catch (Exception e) { + LOG.debug("notFound batch invalidate failed type={} count={}", type, entities.size(), e); + entities.keySet().stream().filter(Objects::nonNull).forEach(hardDeleteWinners::add); + } + return hardDeleteWinners; + } + + private boolean clearReplaceableMarker(String key, String marker, UUID id, boolean nameKey) { + String current = marker; + for (int attempt = 0; attempt < INVALIDATION_CAS_ATTEMPTS; attempt++) { + boolean replaceable = + isNormalNotFoundMarker(current) || nameKey && isHardDeleteForDifferentEntity(current, id); + if (!replaceable) { + return isHardDeletedMarker(current); + } + if (cache.deleteIfValue(key, current)) { + return false; + } + Optional replacement = cache.get(key); + if (replacement.isEmpty()) { + return false; + } + current = replacement.get(); + } + throw new IllegalStateException("Negative-cache marker kept changing during invalidation"); + } + + private void deleteReplaceableMarkers( + Map expectedValues, + Set idKeys, + Map> entityIdsByKey, + Set hardDeleteWinners) { + Map pending = expectedValues; + for (int attempt = 0; attempt < INVALIDATION_CAS_ATTEMPTS && !pending.isEmpty(); attempt++) { + if (cache.deleteIfValues(pending) == pending.size()) { + return; + } + List pendingKeys = new ArrayList<>(pending.keySet()); + List> replacements = cache.mget(pendingKeys); + Map retry = new LinkedHashMap<>(); + for (int index = 0; index < pendingKeys.size(); index++) { + if (replacements.get(index).isPresent()) { + classifyBatchMarker( + pendingKeys.get(index), + replacements.get(index).get(), + idKeys, + entityIdsByKey, + retry, + hardDeleteWinners); + } + } + pending = retry; + } + if (!pending.isEmpty()) { + throw new IllegalStateException("Negative-cache markers kept changing during invalidation"); + } + } + + private static void classifyBatchMarker( + String key, + String marker, + Set idKeys, + Map> entityIdsByKey, + Map replaceableMarkers, + Set hardDeleteWinners) { + Set entityIds = entityIdsByKey.get(key); + if (isNormalNotFoundMarker(marker) + || !idKeys.contains(key) && isHardDeleteForDifferentEntities(marker, entityIds)) { + replaceableMarkers.put(key, marker); + } else if (isHardDeletedMarker(marker)) { + addHardDeleteWinners(marker, entityIds, hardDeleteWinners); + } + } + + private static void addHardDeleteWinners( + String marker, Set entityIds, Set hardDeleteWinners) { + if (HARD_DELETED.equals(marker)) { + entityIds.stream().filter(Objects::nonNull).forEach(hardDeleteWinners::add); + return; + } + entityIds.stream() + .filter(Objects::nonNull) + .filter(id -> marker.equals(HARD_DELETED_NAME_PREFIX + id)) + .forEach(hardDeleteWinners::add); + } + + private static boolean isHardDeletedMarker(String marker) { + return HARD_DELETED.equals(marker) || marker.startsWith(HARD_DELETED_NAME_PREFIX); + } + + private static boolean isKnownMissing(Optional marker, boolean includeNormalMisses) { + return marker + .filter( + value -> + isHardDeletedMarker(value) || includeNormalMisses && isNormalNotFoundMarker(value)) + .isPresent(); + } + + private static boolean isNormalNotFoundMarker(String marker) { + return NOT_FOUND.equals(marker) || LEGACY_NOT_FOUND.equals(marker); + } + + private static boolean isHardDeleteForDifferentEntity(String marker, UUID id) { + return marker.startsWith(HARD_DELETED_NAME_PREFIX) + && id != null + && !marker.equals(HARD_DELETED_NAME_PREFIX + id); + } + + private static boolean isHardDeleteForDifferentEntities(String marker, Set entityIds) { + return marker.startsWith(HARD_DELETED_NAME_PREFIX) + && entityIds.stream() + .filter(Objects::nonNull) + .noneMatch(id -> marker.equals(HARD_DELETED_NAME_PREFIX + id)); + } + + private Optional markerById(String type, UUID id) { + if (!enabled()) return Optional.empty(); + try { + return cache.get(keys.notFoundById(type, id)); + } catch (Exception e) { + LOG.debug("notFound cache read failed (treated as not-cached) type={} id={}", type, id, e); + return Optional.empty(); + } + } + + private Optional markerByName(String type, String fqn) { + if (!enabled()) return Optional.empty(); + try { + return cache.get(keys.notFoundByName(type, fqn)); + } catch (Exception e) { + LOG.debug("notFound cache read failed (treated as not-cached) type={} fqn={}", type, fqn, e); + return Optional.empty(); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java b/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java index ae7a020e23dc..aad0053fc1c3 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/cache/RedisCacheProvider.java @@ -21,11 +21,15 @@ import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicInteger; import lombok.extern.slf4j.Slf4j; @Slf4j public class RedisCacheProvider implements CacheProvider { + private static final String DELETE_IF_VALUE_SCRIPT = + "if redis.call('get', KEYS[1]) == ARGV[1] then " + + "return redis.call('del', KEYS[1]) else return 0 end"; // Sliding-window failure detector. A single 300ms timeout used to flip the provider to // unavailable, which combined with a 1s health-check that flipped it back on a single PING // success caused the indexer's setFieldsInBulk path to flap — every cycle it paid one timeout @@ -363,11 +367,7 @@ public boolean deleteIfValue(String key, String expectedValue) { try { Long deleted = syncCommands.eval( - "if redis.call('get', KEYS[1]) == ARGV[1] then " - + "return redis.call('del', KEYS[1]) else return 0 end", - ScriptOutputType.INTEGER, - new String[] {key}, - expectedValue); + DELETE_IF_VALUE_SCRIPT, ScriptOutputType.INTEGER, new String[] {key}, expectedValue); if (m != null && deleted != null && deleted > 0) m.recordEviction(); recordSuccess(); return deleted != null && deleted > 0; @@ -381,6 +381,73 @@ public boolean deleteIfValue(String key, String expectedValue) { } } + @Override + public int deleteIfValues(Map expectedValues) { + if (!available || expectedValues == null || expectedValues.isEmpty()) return 0; + + CacheMetrics m = metrics(); + Timer.Sample sample = startWriteTimer(m); + List> entries = new ArrayList<>(expectedValues.entrySet()); + try { + pipelineLock.lock(); + List> futures = new ArrayList<>(entries.size()); + try { + pipelineConnection.setAutoFlushCommands(false); + try { + for (Map.Entry entry : entries) { + futures.add( + pipelineAsyncCommands.eval( + DELETE_IF_VALUE_SCRIPT, + ScriptOutputType.INTEGER, + new String[] {entry.getKey()}, + entry.getValue())); + } + pipelineConnection.flushCommands(); + } finally { + pipelineConnection.setAutoFlushCommands(true); + } + } finally { + pipelineLock.unlock(); + } + + long timeoutMs = Math.max(1000L, config.redis.commandTimeoutMs * 2L); + boolean allCompleted = + LettuceFutures.awaitAll( + Duration.ofMillis(timeoutMs), futures.toArray(RedisFuture[]::new)); + if (!allCompleted) { + for (RedisFuture future : futures) { + if (!future.isDone()) { + future.cancel(false); + } + } + if (m != null) m.recordError(); + recordFailure(new TimeoutException("deleteIfValues timed out after " + timeoutMs + "ms")); + } + + int deleted = 0; + for (RedisFuture future : futures) { + try { + Long result = future.get(); + if (result != null && result > 0) { + deleted++; + if (m != null) m.recordEviction(); + } + } catch (Exception ignored) { + // A timed-out or failed compare-and-delete is safely treated as not deleted. + } + } + if (allCompleted) recordSuccess(); + return deleted; + } catch (Exception e) { + if (m != null) m.recordError(); + recordFailure(e); + LOG.error("Error deleting {} keys with owner checks", entries.size(), e); + return 0; + } finally { + stopWriteTimer(m, sample); + } + } + @Override public Optional hget(String key, String field) { if (!available) return Optional.empty(); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java index e96c2f813def..21118b144e87 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java @@ -11,6 +11,7 @@ import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.function.Function; import java.util.function.Supplier; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.attachments.Asset; @@ -21,10 +22,12 @@ import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.attachments.AssetService; import org.openmetadata.service.attachments.AssetServiceFactory; +import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.jdbi3.ContextFileRepository; @Slf4j public class ContextFileExtractionService { + private static final int MAX_CONDITIONAL_UPDATE_ATTEMPTS = 3; private final ContextFileRepository repository; private final Supplier assetServiceSupplier; private final Executor executor; @@ -107,7 +110,7 @@ void process(UUID fileId, UUID contentId) { return; } - updateFile( + if (!updateFile( fileId, current -> { if (!contentId.toString().equals(current.getHeadContentId())) { @@ -116,8 +119,10 @@ void process(UUID fileId, UUID contentId) { ContextFile updated = JsonUtils.deepCopy(current, ContextFile.class); updated.setProcessingStatus(ProcessingStatus.Analyzing); return updated; - }); - updateContent( + })) { + return; + } + if (!updateContent( contentId, current -> { // Re-read the file inside the content updater so we don't mark an @@ -133,7 +138,9 @@ void process(UUID fileId, UUID contentId) { updated.setProcessingStatus(ProcessingStatus.Analyzing); updated.setProcessingError(null); return updated; - }); + })) { + return; + } try { ContextFile currentFile = getFile(fileId); @@ -175,7 +182,7 @@ private String describeFailure(Throwable t) { private void applyResult( UUID fileId, UUID contentId, ContextFileTextExtractor.ExtractionResult result) { - updateContent( + if (!updateContent( contentId, current -> { ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); @@ -183,7 +190,9 @@ private void applyResult( updated.setProcessingError(result.processingError()); updated.setExtractedText(result.extractedText()); return updated; - }); + })) { + return; + } updateFile( fileId, @@ -200,7 +209,7 @@ private void applyResult( } private void applyFailure(UUID fileId, UUID contentId, String reason) { - updateContent( + if (!updateContent( contentId, current -> { ContextFileContent updated = JsonUtils.deepCopy(current, ContextFileContent.class); @@ -208,7 +217,9 @@ private void applyFailure(UUID fileId, UUID contentId, String reason) { updated.setProcessingError(reason); updated.setExtractedText(null); return updated; - }); + })) { + return; + } updateFile( fileId, @@ -240,29 +251,44 @@ private ContextFileContent getContent(UUID contentId) { } } - private void updateFile( - UUID fileId, java.util.function.Function updater) { - ContextFile current = getFile(fileId); - if (current == null) { - return; - } - ContextFile updated = updater.apply(current); - if (updated == null) { - return; + private boolean updateFile(UUID fileId, Function updater) { + for (int attempt = 0; attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS; attempt++) { + ContextFile current = getFile(fileId); + if (current == null) { + return false; + } + ContextFile updated = updater.apply(current); + if (updated == null) { + return false; + } + try { + repository.updateIfCurrent(null, current, updated, ADMIN_USER_NAME); + return true; + } catch (PreconditionFailedException e) { + LOG.debug("Context file {} changed during extraction update", fileId); + } } - repository.update(null, current, updated, ADMIN_USER_NAME); + return false; } - private void updateContent( - UUID contentId, java.util.function.Function updater) { - ContextFileContent current = getContent(contentId); - if (current == null) { - return; - } - ContextFileContent updated = updater.apply(current); - if (updated == null) { - return; + private boolean updateContent( + UUID contentId, Function updater) { + for (int attempt = 0; attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS; attempt++) { + ContextFileContent current = getContent(contentId); + if (current == null) { + return false; + } + ContextFileContent updated = updater.apply(current); + if (updated == null) { + return false; + } + try { + repository.getContentRepository().updateIfCurrent(null, current, updated, ADMIN_USER_NAME); + return true; + } catch (PreconditionFailedException e) { + LOG.debug("Context file content {} changed during extraction update", contentId); + } } - repository.getContentRepository().update(null, current, updated, ADMIN_USER_NAME); + return false; } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java index 2b945d304c6c..6582a27742fb 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/ContextFileRepository.java @@ -125,6 +125,17 @@ public void storeEntity(ContextFile file, boolean update) { file.withFolder(folder); } + @Override + protected void storeEntityWithVersion(ContextFile file, boolean update, Double expectedVersion) { + EntityReference folder = file.getFolder(); + file.withFolder(null); + try { + store(file, update, expectedVersion); + } finally { + file.withFolder(folder); + } + } + @Override public void storeRelationships(ContextFile file) { if (file.getFolder() != null) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java index f34fb150cfc7..03c55d3f8e6e 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java @@ -379,6 +379,16 @@ private static long readEpochByName(Pair key) { return epoch == null ? 0L : epoch.get(); } + @VisibleForTesting + static long writeEpochById(String entityType, UUID id) { + return readEpochById(new ImmutablePair<>(entityType, id)); + } + + @VisibleForTesting + static long writeEpochByName(String entityType, String fqn) { + return readEpochByName(cacheNameKey(entityType, fqn)); + } + private static void bumpWriteEpoch(String entityType, UUID id, String fqn) { if (id != null) { try { @@ -1618,15 +1628,24 @@ public final T find(UUID id, Include include) throws EntityNotFoundException { return find(id, include, true); } + private boolean isKnownMissingById(NotFoundCache notFoundCache, UUID id, Include include) { + return notFoundCache != null + && notFoundCache.isKnownMissingById(entityType, id, include == NON_DELETED); + } + + private boolean isKnownMissingByName( + NotFoundCache notFoundCache, String canonicalFqn, Include include) { + return notFoundCache != null + && notFoundCache.isKnownMissingByName(entityType, canonicalFqn, include == NON_DELETED); + } + public final T find(UUID id, Include include, boolean fromCache) throws EntityNotFoundException { var notFoundCache = CacheBundle.getNotFoundCache(); if (!fromCache) { // On the explicit-bypass path the L1 cache is being skipped entirely, so checking the // negative cache before touching the DB is a clear win — short-circuits a known-missing // entity without paying for the DB round-trip. - if (include == NON_DELETED - && notFoundCache != null - && notFoundCache.isMarkedNotFoundById(entityType, id)) { + if (isKnownMissingById(notFoundCache, id, include)) { throw new EntityNotFoundException(entityNotFound(entityType, id)); } CACHE_WITH_ID.invalidate(new ImmutablePair<>(entityType, id)); @@ -1665,18 +1684,15 @@ public final T find(UUID id, Include include, boolean fromCache) throws EntityNo if (cachedJson == null) { // L1 miss. Consult the negative cache so we can short-circuit before invoking the // loader (which would do DB + optional Redis-L2 work). - if (include == NON_DELETED - && notFoundCache != null - && notFoundCache.isMarkedNotFoundById(entityType, id)) { + if (isKnownMissingById(notFoundCache, id, include)) { throw new EntityNotFoundException(entityNotFound(entityType, id)); } try (var ignored = phase("cacheGet")) { cachedJson = CACHE_WITH_ID.get(cacheKey); } - } else if (include == NON_DELETED - && notFoundCache != null + } else if (notFoundCache != null && readEpochById(cacheKey) != 0L - && notFoundCache.isMarkedNotFoundById(entityType, id)) { + && isKnownMissingById(notFoundCache, id, include)) { // Stale L1 from a racing loader after a delete — marker says gone, evict and 404. // Epoch gate skips the Redis GET on keys no writer has touched. CACHE_WITH_ID.invalidate(cacheKey); @@ -2270,9 +2286,7 @@ public final T findByName(String fqn, Include include, boolean fromCache) { // Explicit cache bypass — checking the negative cache before the DB still saves the // DB hit on a known-missing entity. (Same reasoning as find(UUID, …).) String bypassCanonicalFqn = cacheNameKey(entityType, fqn).getRight(); - if (include == NON_DELETED - && notFoundCache != null - && notFoundCache.isMarkedNotFoundByName(entityType, bypassCanonicalFqn)) { + if (isKnownMissingByName(notFoundCache, bypassCanonicalFqn, include)) { throw new EntityNotFoundException(entityNotFound(entityType, fqn)); } CACHE_WITH_NAME.invalidate(cacheNameKey(entityType, fqn)); @@ -2301,18 +2315,15 @@ public final T findByName(String fqn, Include include, boolean fromCache) { String canonicalFqn = cacheKey.getRight(); String cachedJson = CACHE_WITH_NAME.getIfPresent(cacheKey); if (cachedJson == null) { - if (include == NON_DELETED - && notFoundCache != null - && notFoundCache.isMarkedNotFoundByName(entityType, canonicalFqn)) { + if (isKnownMissingByName(notFoundCache, canonicalFqn, include)) { throw new EntityNotFoundException(entityNotFound(entityType, fqn)); } try (var ignored = phase("cacheGet")) { cachedJson = CACHE_WITH_NAME.get(cacheKey); } - } else if (include == NON_DELETED - && notFoundCache != null + } else if (notFoundCache != null && readEpochByName(cacheKey) != 0L - && notFoundCache.isMarkedNotFoundByName(entityType, canonicalFqn)) { + && isKnownMissingByName(notFoundCache, canonicalFqn, include)) { // Stale L1 from a racing loader after a delete — marker says gone, evict and 404. CACHE_WITH_NAME.invalidate(cacheKey); throw new EntityNotFoundException(entityNotFound(entityType, fqn)); @@ -3622,6 +3633,9 @@ public static void onRemoteCacheInvalidate(String entityType, UUID id, String fq if (entityType == null) { return; } + // A remote write races local loaders exactly like a local write. Bump the epoch before + // evicting so a loader that already read stale Redis/DB data cannot repopulate L1 afterward. + bumpWriteEpoch(entityType, id, fqn); if (id != null) { CACHE_WITH_ID.invalidate(new ImmutablePair<>(entityType, id)); } @@ -3842,6 +3856,7 @@ public List createManyEntitiesForImport(List entities, String impersonated // 4. Batch cache writes writeThroughCacheMany(entities, false); + invalidateCreatedEntityCaches(entities); return entities; } @@ -3908,11 +3923,6 @@ protected void postCreate(T entity) { } RdfUpdater.updateEntity(entity); ListCountCache.invalidate(entityType); - // Drop any negative-cache markers (P2.4) for this just-created entity. Without this, a - // create-then-immediately-read flow would 404 for up to notFoundTtlSeconds because a - // prior failed lookup poisoned the negative cache. Iterates the Invalidatable registry - // so future cache layers also get the create signal automatically. - CacheBundle.invalidateEntity(entityType, entity.getId(), entity.getFullyQualifiedName()); } /** @@ -4087,6 +4097,46 @@ protected void postCreate(List entities) { ListCountCache.invalidate(entityType); } + private void invalidateCreatedEntityCaches(T entity) { + if (entity == null || entity.getId() == null) { + return; + } + String fqn = entity.getFullyQualifiedName(); + String canonicalFqn = fqn == null ? null : cacheNameKey(entityType, fqn).getRight(); + if (CacheBundle.invalidateEntityPreservingHardDelete( + entityType, entity.getId(), canonicalFqn)) { + invalidateCreatedEntityAfterHardDelete(entity); + } + } + + private void invalidateCreatedEntityCaches(List entities) { + if (entities == null || entities.isEmpty()) { + return; + } + Map createdEntityKeys = new LinkedHashMap<>(entities.size()); + Map createdEntitiesById = new LinkedHashMap<>(entities.size()); + for (T entity : entities) { + if (entity == null || entity.getId() == null) { + continue; + } + String fqn = entity.getFullyQualifiedName(); + String canonicalFqn = fqn == null ? null : cacheNameKey(entityType, fqn).getRight(); + createdEntityKeys.put(entity.getId(), canonicalFqn); + createdEntitiesById.put(entity.getId(), entity); + } + for (UUID id : CacheBundle.invalidateEntities(entityType, createdEntityKeys)) { + T entity = createdEntitiesById.get(id); + if (entity != null) { + invalidateCreatedEntityAfterHardDelete(entity); + } + } + } + + private void invalidateCreatedEntityAfterHardDelete(T entity) { + RequestEntityCache.invalidate(entityType, entity.getId(), entity.getFullyQualifiedName()); + invalidateCacheForEntity(entityType, entity.getId(), entity.getFullyQualifiedName()); + } + @SuppressWarnings("unused") protected void postUpdate(T original, T updated) { try (var ignored = phase("lifecycleDispatch")) { @@ -4121,6 +4171,21 @@ public final PutResponse update(UriInfo uriInfo, T original, T updated, Strin public final PutResponse update( UriInfo uriInfo, T original, T updated, String updatedBy, String impersonatedBy) { + return updateInternal(uriInfo, original, updated, updatedBy, impersonatedBy, false); + } + + public final PutResponse updateIfCurrent( + UriInfo uriInfo, T original, T updated, String updatedBy) { + return updateInternal(uriInfo, original, updated, updatedBy, null, true); + } + + private PutResponse updateInternal( + UriInfo uriInfo, + T original, + T updated, + String updatedBy, + String impersonatedBy, + boolean requireCurrentVersion) { // Get all the fields in the original entity that can be updated during PUT operation try (var ignored = phase("putHydrateOriginal")) { setFieldsInternal(original, putFields); @@ -4137,9 +4202,16 @@ public final PutResponse update( } // Update the attributes and relationships of an entity - EntityUpdater entityUpdater = getUpdater(original, updated, Operation.PUT, null); + EntityUpdater entityUpdater = + requireCurrentVersion + ? getUpdater(original, updated, Operation.PUT, null, true) + : getUpdater(original, updated, Operation.PUT, null); try (var ignored = phase("putEntityUpdate")) { - entityUpdater.update(); + if (requireCurrentVersion) { + entityUpdater.updateWithOptimisticLocking(); + } else { + entityUpdater.update(); + } } EventType change = entityUpdater.incrementalFieldsChanged() ? EventType.ENTITY_UPDATED : ENTITY_NO_CHANGE; @@ -4877,37 +4949,26 @@ protected final void cleanup(String deletedBy, T entityInterface) { return null; }); - // Re-invalidate after the transaction commits. Any read that slipped in between the - // pre-delete invalidate and the commit could have re-populated the cache from the - // still-visible DB row; clearing again here guarantees the next read goes back to the - // (now empty) DB and observes the deletion. - invalidate(entityInterface); - // Mark the entity as not-found in the negative cache. Without this, a concurrent reader - // racing the deletion can re-populate Guava L1 / Redis between our invalidate() calls - // from the still-visible DB row (the loader fetches it just before the commit lands). - // The marker short-circuits the read path on the L1-miss branch — see find()/findByName() - // where isMarkedNotFound* is consulted after CACHE_WITH_*.getIfPresent() returns null — - // so once the next read misses L1 (because the post-commit invalidate above cleared it), - // the loader is skipped and we throw EntityNotFoundException directly. A stale L1 entry - // that survives the two invalidate passes is NOT caught by this marker (getIfPresent - // returns it before the loader/negative-cache path runs); the second invalidate makes - // that case rare in practice, and it expires within the L1 TTL. Marker TTL - // (notFoundTtlSeconds, default 30 s) outlasts any in-flight request window; - // recreate-with-same-id paths clear the marker via CacheBundle.invalidateEntity() in - // postCreate. - markEntityNotFound(entityInterface); - } - - private void markEntityNotFound(T entity) { + // Install the tombstone before the final post-commit invalidation. This closes both races: + // a read that re-populated from the still-visible row before commit and an older updater whose + // late cache write-through would otherwise resurrect the now-deleted entity. + markEntityHardDeleted(entityInterface); + invalidatePreservingHardDelete(entityInterface); + } + + private void markEntityHardDeleted(T entity) { NotFoundCache notFoundCache = CacheBundle.getNotFoundCache(); if (notFoundCache == null || !notFoundCache.enabled()) { return; } if (entity.getId() != null) { - notFoundCache.markNotFoundById(entityType, entity.getId()); + notFoundCache.markHardDeletedById(entityType, entity.getId()); } if (entity.getFullyQualifiedName() != null) { - notFoundCache.markNotFoundByName(entityType, entity.getFullyQualifiedName()); + notFoundCache.markHardDeletedByName( + entityType, + cacheNameKey(entityType, entity.getFullyQualifiedName()).getRight(), + entity.getId()); } } @@ -4924,6 +4985,14 @@ protected void entitySpecificCleanup(String deletedBy, T entityInterface) { } void invalidate(T entity) { + invalidate(entity, false); + } + + private void invalidatePreservingHardDelete(T entity) { + invalidate(entity, true); + } + + private void invalidate(T entity, boolean preserveHardDelete) { bumpWriteEpoch(entityType, entity.getId(), entity.getFullyQualifiedName()); CACHE_WITH_ID.invalidate(new ImmutablePair<>(entityType, entity.getId())); CACHE_WITH_NAME.invalidate(cacheNameKey(entityType, entity.getFullyQualifiedName())); @@ -4931,7 +5000,12 @@ void invalidate(T entity) { EntityCacheRepair.scheduleRepair( entityType, entity.getId(), entity.getFullyQualifiedName(), null); invalidateCache(entity); - CacheBundle.invalidateEntity(entityType, entity.getId(), entity.getFullyQualifiedName()); + if (preserveHardDelete) { + CacheBundle.invalidateEntityPreservingHardDelete( + entityType, entity.getId(), entity.getFullyQualifiedName()); + } else { + CacheBundle.invalidateEntity(entityType, entity.getId(), entity.getFullyQualifiedName()); + } } @Transaction @@ -5021,6 +5095,7 @@ protected T createNewEntity(T entity) { try (var ignored = phase("createWriteThroughCache")) { writeThroughCache(entity, false); } + invalidateCreatedEntityCaches(entity); return entity; } @@ -5260,6 +5335,7 @@ private List createManyEntities(List entities) { try (var ignored = phase("postCreate")) { postCreate(entities); } + invalidateCreatedEntityCaches(entities); return entities; } @@ -6899,14 +6975,14 @@ private void bulkDeleteEntityRows(List entities) { private void bulkInvalidate(List entities) { for (T entity : entities) { - invalidate(entity); // Mirror cleanup()'s NotFoundCache marker so a concurrent reader that re-populates // L1/Redis between bulkDeleteEntityRows and the next invalidate doesn't keep // returning a stale "found" entity. Without this the next get_by_name/find against // the same id or FQN can still hit the cache and return a deleted entity, which // breaks fixture teardown (DELETE returns 404 because the row is gone but Redis // still hands out the entity to the get_by_name probe). - markEntityNotFound(entity); + markEntityHardDeleted(entity); + invalidatePreservingHardDelete(entity); } } @@ -10299,7 +10375,16 @@ private void invalidateCachesAfterStore() { // so the next GET on this instance can't race an in-flight async repopulate. EntityRepository.this.writeThroughCache(updated, true); RequestEntityCache.invalidate(entityType, id, fqn); - CacheBundle.invalidateEntity(entityType, id, fqn); + boolean hardDeleteWon = CacheBundle.invalidateEntityPreservingHardDelete(entityType, id, fqn); + if (hardDeleteWon) { + if (cachedEntityDao != null) { + cachedEntityDao.invalidateBase(entityType, id); + if (fqn != null) { + cachedEntityDao.invalidateByName(entityType, fqn); + } + } + return; + } EntityCacheRepair.scheduleRepair(entityType, id, fqn, originalFqn); @@ -10643,15 +10728,16 @@ static class EntityLoaderWithName extends CacheLoader, Stri // Race guard — epoch mismatch means a writer ran during the load; throw so Guava skips // caching the now-stale value and find() re-reads via the bypass path. long startEpoch = readEpochByName(fqnPair); - String json = loadInternal(fqnPair); + String json = loadInternal(fqnPair, startEpoch); if (readEpochByName(fqnPair) != startEpoch) { + evictExternalCache(fqnPair, json); throw new LoaderRaceException("Concurrent write during loadByName: " + fqnPair); } return json; } @NonNull - private String loadInternal(@NotNull Pair fqnPair) { + private String loadInternal(@NotNull Pair fqnPair, long startEpoch) { String entityType = fqnPair.getLeft(); String fqn = fqnPair.getRight(); EntityRepository repository = @@ -10659,7 +10745,7 @@ private String loadInternal(@NotNull Pair fqnPair) { EntityDAO dao = repository.getDao(); // Try to load from external cache first (read-through) for cacheable entity types. - if (isCacheableEntityType(entityType)) { + if (isCacheableEntityType(entityType) && readEpochByName(fqnPair) == startEpoch) { var cachedEntityDao = CacheBundle.getCachedEntityDao(); if (cachedEntityDao != null) { Optional cachedJson = cachedEntityDao.getByName(entityType, fqn); @@ -10721,7 +10807,7 @@ private String loadInternal(@NotNull Pair fqnPair) { } // Populate Redis on miss so subsequent reads (incl. cross-instance) can hit cache - if (isCacheableEntityType(entityType)) { + if (isCacheableEntityType(entityType) && readEpochByName(fqnPair) == startEpoch) { var cachedEntityDao = CacheBundle.getCachedEntityDao(); if (cachedEntityDao != null) { try { @@ -10737,6 +10823,24 @@ private String loadInternal(@NotNull Pair fqnPair) { return json; } + + private void evictExternalCache(Pair fqnPair, String json) { + var cachedEntityDao = CacheBundle.getCachedEntityDao(); + if (cachedEntityDao == null) { + return; + } + cachedEntityDao.deleteByName(fqnPair.getLeft(), fqnPair.getRight()); + try { + EntityRepository repository = + Entity.getEntityRepository(fqnPair.getLeft()); + EntityInterface entity = JsonUtils.readValue(json, repository.getEntityClass()); + if (entity.getId() != null) { + cachedEntityDao.deleteBase(fqnPair.getLeft(), entity.getId()); + } + } catch (Exception e) { + LOG.debug("Failed to evict raced cache entry by id for {}", fqnPair, e); + } + } } static class EntityLoaderWithId extends CacheLoader, String> { @@ -10744,15 +10848,19 @@ static class EntityLoaderWithId extends CacheLoader, String> public @NonNull String load(@NotNull Pair idPair) { // See EntityLoaderWithName.load for the race-guard rationale. long startEpoch = readEpochById(idPair); - String json = loadInternal(idPair); + String json = loadInternal(idPair, startEpoch); if (readEpochById(idPair) != startEpoch) { + var cachedEntityDao = CacheBundle.getCachedEntityDao(); + if (cachedEntityDao != null) { + cachedEntityDao.deleteBase(idPair.getLeft(), idPair.getRight()); + } throw new LoaderRaceException("Concurrent write during loadById: " + idPair); } return json; } @NonNull - private String loadInternal(@NotNull Pair idPair) { + private String loadInternal(@NotNull Pair idPair, long startEpoch) { String entityType = idPair.getLeft(); UUID id = idPair.getRight(); EntityRepository repository = @@ -10763,12 +10871,12 @@ private String loadInternal(@NotNull Pair idPair) { if (isCacheableEntityType(entityType)) { var cachedEntityDao = CacheBundle.getCachedEntityDao(); if (cachedEntityDao != null) { - String cachedJson = cachedEntityDao.getBase(id, entityType); - if (cachedJson != null && !cachedJson.isEmpty()) { + Optional cachedJson = cachedEntityDao.getBase(id, entityType); + if (cachedJson.isPresent()) { LOG.debug("CACHE HIT: Loading entity from Redis cache: {} {}", entityType, id); try { Class entityClass = repository.getEntityClass(); - EntityInterface entity = JsonUtils.readValue(cachedJson, entityClass); + EntityInterface entity = JsonUtils.readValue(cachedJson.get(), entityClass); if (entity.getId() == null) { LOG.error( "CACHE ERROR: Cached entity has null ID! Evicting. Type: {}, Expected ID: {}", @@ -10776,7 +10884,7 @@ private String loadInternal(@NotNull Pair idPair) { id); cachedEntityDao.deleteBase(entityType, id); } else { - return cachedJson; + return cachedJson.get(); } } catch (Exception e) { LOG.warn( @@ -10822,6 +10930,13 @@ private String loadInternal(@NotNull Pair idPair) { } } + if (isCacheableEntityType(entityType) && readEpochById(idPair) == startEpoch) { + var cachedEntityDao = CacheBundle.getCachedEntityDao(); + if (cachedEntityDao != null) { + cachedEntityDao.putBase(entityType, id, json); + } + } + return json; } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index 165c86022cad..eab3c2b6afdc 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -31,7 +31,6 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import java.io.IOException; -import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -42,6 +41,7 @@ import java.util.UUID; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import java.util.stream.Collectors; import lombok.SneakyThrows; @@ -1095,133 +1095,96 @@ public void isTestSuiteBasic(String testSuiteFqn) { } } - @Transaction public RestUtil.PutResponse addTestCasesToLogicalTestSuite( TestSuite testSuite, List testCaseIds) { + AtomicReference> addedTestCases = new AtomicReference<>(List.of()); + flushInOneTransaction( + () -> + addedTestCases.set( + addTestCasesToLogicalTestSuiteFlush(testSuite.getId(), testCaseIds))); + + List updatedTestCases = getLogicalSuiteUpdatedTestCase(addedTestCases.get()); + postLogicalSuiteRelationshipUpdate(updatedTestCases); + updateLogicalTestSuite(testSuite.getId()); + return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); + } + + private List addTestCasesToLogicalTestSuiteFlush( + UUID testSuiteId, List testCaseIds) { List originalTestCaseReferences = - findTo(testSuite.getId(), TEST_SUITE, Relationship.CONTAINS, TEST_CASE); - bulkAddToRelationship( - testSuite.getId(), testCaseIds, TEST_SUITE, TEST_CASE, Relationship.CONTAINS); + findTo(testSuiteId, TEST_SUITE, Relationship.CONTAINS, TEST_CASE); + bulkAddToRelationship(testSuiteId, testCaseIds, TEST_SUITE, TEST_CASE, Relationship.CONTAINS); List updatedTestCaseReferences = - findTo(testSuite.getId(), TEST_SUITE, Relationship.CONTAINS, TEST_CASE); + findTo(testSuiteId, TEST_SUITE, Relationship.CONTAINS, TEST_CASE); Set originalIds = originalTestCaseReferences.stream().map(EntityReference::getId).collect(Collectors.toSet()); - List testCaseReferences = - updatedTestCaseReferences.stream() - .filter(ref -> !originalIds.contains(ref.getId())) - .toList(); - - List updatedTestCases = getLogicalSuiteUpdatedTestCase(testCaseReferences); - postLogicalSuiteRelationshipUpdate(updatedTestCases); - updateLogicalTestSuite(testSuite.getId()); - return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); + return updatedTestCaseReferences.stream() + .filter(ref -> !originalIds.contains(ref.getId())) + .toList(); } public RestUtil.PutResponse addAllTestCasesToLogicalTestSuite( TestSuite testSuite, List excludedTestCaseIds) { - // The bulk INSERT IGNORE runs a full scan against test_case and takes gap locks that collide - // with concurrent test-case creation. MySQL raises "Deadlock found when trying to get lock" - // intermittently under IT parallel load. Wrap the retry *outside* the @Transaction boundary - // so each attempt runs in a fresh transaction instead of replaying on a rolled-back handle. - return DeadlockRetry.execute( - () -> addAllTestCasesToLogicalTestSuiteTxn(testSuite, excludedTestCaseIds)); + AtomicReference> addedTestCases = new AtomicReference<>(List.of()); + flushInOneTransaction( + () -> + addedTestCases.set( + addAllTestCasesToLogicalTestSuiteFlush(testSuite.getId(), excludedTestCaseIds))); + + for (List batch : Lists.partition(addedTestCases.get(), 100)) { + List updatedTestCases = getLogicalSuiteUpdatedTestCase(batch); + postLogicalSuiteRelationshipUpdate(updatedTestCases); + } + updateLogicalTestSuite(testSuite.getId()); + return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); } - @Transaction - RestUtil.PutResponse addAllTestCasesToLogicalTestSuiteTxn( - TestSuite testSuite, List excludedTestCaseIds) { + private List addAllTestCasesToLogicalTestSuiteFlush( + UUID testSuiteId, List excludedTestCaseIds) { List originalTestCaseReferences = - findTo(testSuite.getId(), TEST_SUITE, Relationship.CONTAINS, TEST_CASE); + findTo(testSuiteId, TEST_SUITE, Relationship.CONTAINS, TEST_CASE); String tableName = daoCollection.testCaseDAO().getTableName(); if (nullOrEmpty(excludedTestCaseIds)) { - executeWithDeadlockRetry( - () -> - daoCollection - .relationshipDAO() - .bulkInsertAllToRelationship( - testSuite.getId(), - TEST_SUITE, - TEST_CASE, - Relationship.CONTAINS.ordinal(), - tableName)); + daoCollection + .relationshipDAO() + .bulkInsertAllToRelationship( + testSuiteId, TEST_SUITE, TEST_CASE, Relationship.CONTAINS.ordinal(), tableName); } else { - executeWithDeadlockRetry( - () -> - daoCollection - .relationshipDAO() - .bulkInsertAllToRelationshipWithExclusions( - excludedTestCaseIds.stream().map(UUID::toString).toList(), - testSuite.getId(), - TEST_SUITE, - TEST_CASE, - Relationship.CONTAINS.ordinal(), - tableName)); + daoCollection + .relationshipDAO() + .bulkInsertAllToRelationshipWithExclusions( + excludedTestCaseIds.stream().map(UUID::toString).toList(), + testSuiteId, + TEST_SUITE, + TEST_CASE, + Relationship.CONTAINS.ordinal(), + tableName); } List updatedTestCaseReferences = - findTo(testSuite.getId(), TEST_SUITE, Relationship.CONTAINS, TEST_CASE); + findTo(testSuiteId, TEST_SUITE, Relationship.CONTAINS, TEST_CASE); Set originalIds = originalTestCaseReferences.stream().map(EntityReference::getId).collect(Collectors.toSet()); - List newTestCaseReferences = - updatedTestCaseReferences.stream() - .filter(ref -> !originalIds.contains(ref.getId())) - .toList(); - - int batchSize = 100; - for (List batch : Lists.partition(newTestCaseReferences, batchSize)) { - List updatedTestCases = getLogicalSuiteUpdatedTestCase(batch); - postLogicalSuiteRelationshipUpdate(updatedTestCases); - } - updateLogicalTestSuite(testSuite.getId()); - - return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); - } - - private void executeWithDeadlockRetry(Runnable operation) { - int maxAttempts = 3; - for (int attempt = 1; attempt <= maxAttempts; attempt++) { - try { - operation.run(); - return; - } catch (RuntimeException ex) { - if (!isTransientDeadlock(ex) || attempt == maxAttempts) { - throw ex; - } - LOG.debug( - "Retrying logical test suite bulk insert after transient deadlock (attempt {}/{})", - attempt + 1, - maxAttempts); - } - } - } - - private boolean isTransientDeadlock(Throwable throwable) { - for (Throwable current = throwable; current != null; current = current.getCause()) { - if (current instanceof SQLException sqlException) { - int errorCode = sqlException.getErrorCode(); - String sqlState = sqlException.getSQLState(); - if (errorCode == 1213 - || errorCode == 1205 - || "40001".equals(sqlState) - || "40P01".equals(sqlState)) { - return true; - } - } - } - return false; + return updatedTestCaseReferences.stream() + .filter(ref -> !originalIds.contains(ref.getId())) + .toList(); } - @Transaction public RestUtil.DeleteResponse deleteTestCaseFromLogicalTestSuite( UUID testSuiteId, UUID testCaseId) { TestCase testCase = Entity.getEntity(Entity.TEST_CASE, testCaseId, null, null); - deleteRelationship(testSuiteId, TEST_SUITE, testCaseId, TEST_CASE, Relationship.CONTAINS); + flushInOneTransaction( + () -> + deleteRelationship( + testSuiteId, TEST_SUITE, testCaseId, TEST_CASE, Relationship.CONTAINS)); + TestCase updatedTestCase = Entity.getEntity(Entity.TEST_CASE, testCaseId, "*", Include.ALL); ChangeDescription change = new ChangeDescription() + .withPreviousVersion(updatedTestCase.getVersion()) .withFieldsUpdated( List.of( new FieldChange() @@ -1242,6 +1205,7 @@ private List getLogicalSuiteUpdatedTestCase(List test tc -> { ChangeDescription change = new ChangeDescription() + .withPreviousVersion(tc.getVersion()) .withFieldsUpdated( List.of( new FieldChange() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index 7413e4942dde..e20cd17fdd5c 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -118,6 +118,7 @@ import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; import org.openmetadata.schema.service.configuration.elasticsearch.NaturalLanguageSearchConfiguration; import org.openmetadata.schema.settings.SettingsType; +import org.openmetadata.schema.system.StepStats; import org.openmetadata.schema.tests.DataQualityReport; import org.openmetadata.schema.tests.TestSuite; import org.openmetadata.schema.type.AssetCertification; @@ -201,6 +202,8 @@ public void run() { } } + public record ScriptedPartialUpdate(String script, Map parameters) {} + /** * Open a search-write deferral scope on the current thread. While open, the cascade ES mutations * enqueue their work instead of running it inline. Returns {@code true} if this call opened the @@ -343,6 +346,8 @@ public static void deferOrRunSearchWrite( "pipelineStatus", TEST_SUITES); + private static final Set BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS = Set.of(TEST_SUITES); + @Getter private final ElasticSearchConfiguration searchConfiguration; @Getter private final int maxDBConnections; @@ -1502,22 +1507,18 @@ public void updateEntityIndex(EntityInterface entity) { String scriptTxt = DEFAULT_UPDATE_SCRIPT; Map doc = new HashMap<>(); - ChangeDescription incrementalChangeDescription = entity.getIncrementalChangeDescription(); - ChangeDescription changeDescription; - - if (!isNullOrEmptyChangeDescription(incrementalChangeDescription)) { - changeDescription = incrementalChangeDescription; - } else { - changeDescription = entity.getChangeDescription(); - } + ChangeDescription changeDescription = getEffectiveChangeDescription(entity); boolean isNonVersionedUpdate = changeDescription != null && entity.getChangeDescription() != null && Objects.equals( entity.getVersion(), entity.getChangeDescription().getPreviousVersion()); - if (isNonVersionedUpdate && canUseScriptedPartialUpdate(changeDescription)) { - scriptTxt = getScriptWithParams(entity, doc, changeDescription); + ScriptedPartialUpdate partialUpdate = + buildScriptedPartialUpdate(entity, changeDescription, isNonVersionedUpdate); + if (partialUpdate != null) { + scriptTxt = partialUpdate.script(); + doc = partialUpdate.parameters(); } else { if (isNonVersionedUpdate && changeDescription != null) { LOG.debug( @@ -1773,26 +1774,44 @@ public void updateEntitiesIndex(List entities) { bulkSink = createBulkSink(batchSize, maxConcurrentRequests, maxPayloadSizeBytes); Map contextData = new HashMap<>(); contextData.put(ReindexingUtil.ENTITY_TYPE_KEY, entityType); + contextData.put(BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY, true); ReindexingUtil.populateDocBuildContext(contextData, entityType, typeEntities); bulkSink.write(typeEntities, contextData); - bulkSink.flushAndAwait(60); // Wait up to 60 seconds for completion + boolean completed = bulkSink.flushAndAwait(60); // Wait up to 60 seconds for completion + StepStats sinkStats = bulkSink.getStats(); + if (!completed + || (sinkStats != null + && Optional.ofNullable(sinkStats.getFailedRecords()).orElse(0) > 0)) { + throw new IOException( + "Bulk entity update did not complete successfully for type " + entityType); + } } catch (Exception e) { LOG.error("Error during bulk entity update in search index for type {}", entityType, e); - for (EntityInterface entity : typeEntities) { - try { - updateEntityIndex(entity); - } catch (Exception ex) { - LOG.error( - "Error updating entity {} in search index", entity.getFullyQualifiedName(), ex); + boolean bulkSinkQuiescent = true; + if (bulkSink != null) { + bulkSinkQuiescent = closeBulkSinkAndCheckQuiescent(bulkSink); + bulkSink = null; + } + if (bulkSinkQuiescent) { + for (EntityInterface entity : typeEntities) { + try { + updateEntityIndex(entity); + } catch (Exception ex) { + LOG.error( + "Error updating entity {} in search index", entity.getFullyQualifiedName(), ex); + } + } + } else { + for (EntityInterface entity : typeEntities) { + SearchIndexRetryQueue.enqueue( + entity, + "updateEntitiesBulk: bulk sink still active; skipped overlapping fallback", + e); } } } finally { if (bulkSink != null) { - try { - bulkSink.close(); - } catch (Exception e) { - LOG.warn("Error closing bulk sink", e); - } + closeBulkSinkAndCheckQuiescent(bulkSink); } } } @@ -1801,6 +1820,16 @@ public void updateEntitiesIndex(List entities) { propagateEntitiesAfterBulkFlush(dedupedEntities.values()); } + private boolean closeBulkSinkAndCheckQuiescent(BulkSink bulkSink) { + try { + bulkSink.close(); + return bulkSink.getActiveBulkRequestCount() == 0; + } catch (Exception e) { + LOG.warn("Error closing bulk sink", e); + return false; + } + } + private void propagateEntitiesAfterBulkFlush(Iterable entities) { int candidates = 0; int propagated = 0; @@ -3091,6 +3120,55 @@ public String getScriptWithParams( return scriptTxt.toString(); } + public ScriptedPartialUpdate buildBulkScriptedPartialUpdate(EntityInterface entity) { + if (entity == null) { + return null; + } + ChangeDescription changeDescription = getEffectiveChangeDescription(entity); + if (!BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS.equals(getChangedFieldNames(changeDescription))) { + return null; + } + boolean isNonVersionedUpdate = + entity.getChangeDescription() != null + && Objects.equals( + entity.getVersion(), entity.getChangeDescription().getPreviousVersion()); + if (!isNonVersionedUpdate) { + return null; + } + Object testSuites = + Stream.of( + listOrEmpty(changeDescription.getFieldsAdded()), + listOrEmpty(changeDescription.getFieldsUpdated()), + listOrEmpty(changeDescription.getFieldsDeleted())) + .flatMap(List::stream) + .filter(fieldChange -> TEST_SUITES.equals(fieldChange.getName())) + .map(FieldChange::getNewValue) + .filter(Objects::nonNull) + .findFirst() + .orElse(null); + return testSuites == null + ? null + : new ScriptedPartialUpdate( + "ctx._source.testSuites = params.testSuites;", Map.of(TEST_SUITES, testSuites)); + } + + private ScriptedPartialUpdate buildScriptedPartialUpdate( + EntityInterface entity, ChangeDescription changeDescription, boolean isNonVersionedUpdate) { + if (!isNonVersionedUpdate || !canUseScriptedPartialUpdate(changeDescription)) { + return null; + } + Map parameters = new HashMap<>(); + String script = getScriptWithParams(entity, parameters, changeDescription); + return new ScriptedPartialUpdate(script, parameters); + } + + private ChangeDescription getEffectiveChangeDescription(EntityInterface entity) { + ChangeDescription incrementalChangeDescription = entity.getIncrementalChangeDescription(); + return !isNullOrEmptyChangeDescription(incrementalChangeDescription) + ? incrementalChangeDescription + : entity.getChangeDescription(); + } + private boolean canUseScriptedPartialUpdate(ChangeDescription changeDescription) { Set changedFieldNames = getChangedFieldNames(changeDescription); return !changedFieldNames.isEmpty() diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/SearchIndex.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/SearchIndex.java index 3d91e7027532..29f667c778b1 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/SearchIndex.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/SearchIndex.java @@ -43,7 +43,6 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.resources.settings.SettingsCache; -import org.openmetadata.service.search.SearchClient; import org.openmetadata.service.search.SearchIndexUtils; import org.openmetadata.service.util.FullyQualifiedName; import org.slf4j.Logger; @@ -77,7 +76,6 @@ public interface SearchIndex { "certification", "dataProducts"); - SearchClient searchClient = Entity.getSearchRepository().getSearchClient(); Logger LOG = LoggerFactory.getLogger(SearchIndex.class); default Map buildSearchIndexDoc() { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java index f1ce3ed1aa4b..7ad9df56d056 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSinkBehaviorTest.java @@ -9,6 +9,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; @@ -17,6 +18,8 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import es.co.elastic.clients.elasticsearch.core.bulk.BulkOperation; +import es.co.elastic.clients.json.JsonData; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Collections; @@ -27,6 +30,7 @@ import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.openmetadata.schema.EntityInterface; @@ -39,6 +43,7 @@ import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.search.SearchRepository; import org.openmetadata.service.search.elasticsearch.ElasticSearchClient; +import org.openmetadata.service.search.elasticsearch.EsUtils; import org.openmetadata.service.search.indexes.DocBuildContext; import org.openmetadata.service.search.indexes.SearchIndex; import org.openmetadata.service.search.vector.OpenSearchVectorService; @@ -123,11 +128,14 @@ void addEntityRecordsSuccessAndProcessStats() throws Exception { invokePrivate( sink, "addEntity", - new Class[] {EntityInterface.class, String.class, StageStatsTracker.class, Map.class}, + new Class[] { + EntityInterface.class, String.class, StageStatsTracker.class, Map.class, boolean.class + }, entity, "table_index", tracker, - Collections.emptyMap()); + Collections.emptyMap(), + false); verify(processor) .add(any(), eq(entityId.toString()), eq(ENTITY_TYPE), eq(tracker), anyLong()); @@ -138,6 +146,64 @@ void addEntityRecordsSuccessAndProcessStats() throws Exception { } } + @Test + void relationshipPartialUpdateUsesFullDocumentUpsertWithoutRewritingOtherFields() + throws Exception { + EntityInterface entity = mock(EntityInterface.class); + UUID entityId = UUID.randomUUID(); + when(entity.getId()).thenReturn(entityId); + SearchRepository.ScriptedPartialUpdate partialUpdate = + new SearchRepository.ScriptedPartialUpdate( + "ctx._source.testSuites = params.testSuites;", + Map.of("testSuites", List.of(Map.of("id", "suite-id")))); + when(searchRepository.buildBulkScriptedPartialUpdate(entity)).thenReturn(partialUpdate); + + try (MockedConstruction processorConstruction = + mockConstruction(ElasticSearchBulkSink.CustomBulkProcessor.class); + MockedStatic entityMock = mockStatic(Entity.class)) { + ElasticSearchBulkSink sink = new ElasticSearchBulkSink(searchRepository, 10, 2, 1000L); + ElasticSearchBulkSink.CustomBulkProcessor processor = + processorConstruction.constructed().getFirst(); + entityMock.when(Entity::getSearchRepository).thenReturn(searchRepository); + entityMock.when(() -> Entity.getEntityTypeFromObject(entity)).thenReturn(ENTITY_TYPE); + entityMock + .when(() -> Entity.buildSearchIndex(ENTITY_TYPE, entity)) + .thenReturn( + new StubSearchIndex(Map.of("name", "current", "description", "current description"))); + + invokePrivate( + sink, + "addEntity", + new Class[] { + EntityInterface.class, String.class, StageStatsTracker.class, Map.class, boolean.class + }, + entity, + "table_index", + null, + Collections.emptyMap(), + true); + + ArgumentCaptor operationCaptor = ArgumentCaptor.forClass(BulkOperation.class); + verify(processor) + .add( + operationCaptor.capture(), + eq(entityId.toString()), + eq(ENTITY_TYPE), + isNull(), + anyLong()); + BulkOperation operation = operationCaptor.getValue(); + assertTrue(operation.isUpdate()); + assertFalse(Boolean.TRUE.equals(operation.update().action().scriptedUpsert())); + assertEquals( + "current description", + EsUtils.jsonDataToMap((JsonData) operation.update().action().upsert()) + .get("description")); + assertEquals( + "ctx._source.testSuites = params.testSuites;", + operation.update().action().script().source().scriptString()); + } + } + @Test void addEntityRecordsEntityNotFoundWarningsWithoutCallback() throws Exception { EntityInterface entity = mock(EntityInterface.class); @@ -161,11 +227,14 @@ void addEntityRecordsEntityNotFoundWarningsWithoutCallback() throws Exception { invokePrivate( sink, "addEntity", - new Class[] {EntityInterface.class, String.class, StageStatsTracker.class, Map.class}, + new Class[] { + EntityInterface.class, String.class, StageStatsTracker.class, Map.class, boolean.class + }, entity, "table_index", tracker, - Collections.emptyMap()); + Collections.emptyMap(), + false); verify(processorConstruction.constructed().getFirst()).setFailureCallback(failureCallback); verify(tracker).recordProcess(StatsResult.WARNING); @@ -327,11 +396,14 @@ void addEntityLooksUpEntityContextFromMap() throws Exception { invokePrivate( sink, "addEntity", - new Class[] {EntityInterface.class, String.class, StageStatsTracker.class, Map.class}, + new Class[] { + EntityInterface.class, String.class, StageStatsTracker.class, Map.class, boolean.class + }, entity, "table_index", null, - docBuildContexts); + docBuildContexts, + false); assertSame(ctxForEntity, ContextCapturingIndex.observedContext); assertSame(edges, ContextCapturingIndex.observedContext.prefetchedUpstreamLineage()); @@ -357,11 +429,14 @@ void addEntityFallsBackToEmptyContextWhenEntityNotInMap() throws Exception { invokePrivate( sink, "addEntity", - new Class[] {EntityInterface.class, String.class, StageStatsTracker.class, Map.class}, + new Class[] { + EntityInterface.class, String.class, StageStatsTracker.class, Map.class, boolean.class + }, entity, "table_index", null, - Collections.emptyMap()); + Collections.emptyMap(), + false); assertSame(DocBuildContext.empty(), ContextCapturingIndex.observedContext); } @@ -395,11 +470,14 @@ void addEntityNeverTouchesVectorServiceBecauseElasticsearchHasNoEmbeddingPath() invokePrivate( sink, "addEntity", - new Class[] {EntityInterface.class, String.class, StageStatsTracker.class, Map.class}, + new Class[] { + EntityInterface.class, String.class, StageStatsTracker.class, Map.class, boolean.class + }, entity, "table_index", tracker, - Collections.emptyMap()); + Collections.emptyMap(), + false); vectorServiceMock.verify(OpenSearchVectorService::getInstance, never()); verify(tracker).recordProcess(StatsResult.SUCCESS); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java index e5b4de130dbf..ba3bdc7fc90e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSinkBehaviorTest.java @@ -10,6 +10,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; @@ -31,6 +32,7 @@ import java.util.concurrent.atomic.AtomicLong; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; import org.mockito.MockedConstruction; import org.mockito.MockedStatic; import org.openmetadata.schema.EntityInterface; @@ -46,9 +48,13 @@ import org.openmetadata.service.search.indexes.DocBuildContext; import org.openmetadata.service.search.indexes.SearchIndex; import org.openmetadata.service.search.opensearch.OpenSearchClient; +import org.openmetadata.service.search.opensearch.OsUtils; import org.openmetadata.service.search.vector.OpenSearchVectorService; import org.openmetadata.service.search.vector.VectorDocBuilder; import org.openmetadata.service.search.vector.client.EmbeddingClient; +import os.org.opensearch.client.json.JsonData; +import os.org.opensearch.client.opensearch._types.Script; +import os.org.opensearch.client.opensearch.core.bulk.BulkOperation; class OpenSearchBulkSinkBehaviorTest { @@ -138,7 +144,8 @@ void addEntityRecordsSuccessAndProcessStats() throws Exception { StageStatsTracker.class, boolean.class, Map.class, - Map.class + Map.class, + boolean.class }, entity, "table_index", @@ -146,7 +153,8 @@ void addEntityRecordsSuccessAndProcessStats() throws Exception { tracker, false, Collections.emptyMap(), - Collections.emptyMap()); + Collections.emptyMap(), + false); verify(processor) .add(any(), eq(entityId.toString()), eq(ENTITY_TYPE), eq(tracker), anyLong()); @@ -157,6 +165,89 @@ void addEntityRecordsSuccessAndProcessStats() throws Exception { } } + @Test + void relationshipPartialUpdateUsesVectorEnrichedFullUpsertWithoutRewritingOtherFields() + throws Exception { + EntityInterface entity = mock(EntityInterface.class); + UUID entityId = UUID.randomUUID(); + when(entity.getId()).thenReturn(entityId); + SearchRepository.ScriptedPartialUpdate partialUpdate = + new SearchRepository.ScriptedPartialUpdate( + "ctx._source.testSuites = params.testSuites;", + Map.of("testSuites", List.of(Map.of("id", "suite-id")))); + when(searchRepository.buildBulkScriptedPartialUpdate(entity)).thenReturn(partialUpdate); + JsonNode cachedEmbedding = + new ObjectMapper() + .readTree( + "{\"fingerprint\":\"fp\",\"embedding\":[0.1,0.2]," + + "\"textToEmbed\":\"text\",\"textToLLMContext\":\"context\"," + + "\"chunkIndex\":0,\"chunkCount\":1,\"parentId\":\"" + + entityId + + "\"}"); + OpenSearchVectorService vectorService = mock(OpenSearchVectorService.class); + EmbeddingClient embeddingClient = mock(EmbeddingClient.class); + when(vectorService.getEmbeddingClient()).thenReturn(embeddingClient); + when(embeddingClient.getDimension()).thenReturn(2); + + try (MockedConstruction processorConstruction = + mockConstruction(OpenSearchBulkSink.CustomBulkProcessor.class); + MockedStatic entityMock = mockStatic(Entity.class); + MockedStatic vectorServiceMock = + mockStatic(OpenSearchVectorService.class)) { + vectorServiceMock.when(OpenSearchVectorService::getInstance).thenReturn(vectorService); + OpenSearchBulkSink sink = new OpenSearchBulkSink(searchRepository, 10, 2, 2000L); + OpenSearchBulkSink.CustomBulkProcessor processor = + processorConstruction.constructed().getFirst(); + entityMock.when(Entity::getSearchRepository).thenReturn(searchRepository); + entityMock.when(() -> Entity.getEntityTypeFromObject(entity)).thenReturn(ENTITY_TYPE); + entityMock + .when(() -> Entity.buildSearchIndex(ENTITY_TYPE, entity)) + .thenReturn( + new StubSearchIndex(Map.of("name", "current", "description", "current description"))); + + invokePrivate( + sink, + "addEntity", + new Class[] { + EntityInterface.class, + String.class, + ReindexContext.class, + StageStatsTracker.class, + boolean.class, + Map.class, + Map.class, + boolean.class + }, + entity, + "table_index", + null, + null, + true, + Map.of(entityId.toString(), cachedEmbedding), + Collections.emptyMap(), + true); + + ArgumentCaptor operationCaptor = ArgumentCaptor.forClass(BulkOperation.class); + verify(processor) + .add( + operationCaptor.capture(), + eq(entityId.toString()), + eq(ENTITY_TYPE), + isNull(), + anyLong()); + BulkOperation operation = operationCaptor.getValue(); + assertTrue(operation.isUpdate()); + Object operationData = getPrivateField(operation.update(), "data"); + assertFalse(Boolean.TRUE.equals(getPrivateField(operationData, "scriptedUpsert"))); + Map upsert = + OsUtils.jsonDataToMap((JsonData) getPrivateField(operationData, "upsert")); + assertEquals("current description", upsert.get("description")); + assertNotNull(upsert.get("embedding")); + Script script = (Script) getPrivateField(operationData, "script"); + assertEquals("ctx._source.testSuites = params.testSuites;", script.inline().source()); + } + } + @Test void addEntityRecordsEntityNotFoundWarningsWithoutCallback() throws Exception { EntityInterface entity = mock(EntityInterface.class); @@ -187,7 +278,8 @@ void addEntityRecordsEntityNotFoundWarningsWithoutCallback() throws Exception { StageStatsTracker.class, boolean.class, Map.class, - Map.class + Map.class, + boolean.class }, entity, "table_index", @@ -195,7 +287,8 @@ void addEntityRecordsEntityNotFoundWarningsWithoutCallback() throws Exception { tracker, false, Collections.emptyMap(), - Collections.emptyMap()); + Collections.emptyMap(), + false); verify(processorConstruction.constructed().getFirst()).setFailureCallback(failureCallback); verify(tracker).recordProcess(StatsResult.WARNING); @@ -368,7 +461,8 @@ void addEntityLooksUpEntityContextFromMap() throws Exception { StageStatsTracker.class, boolean.class, Map.class, - Map.class + Map.class, + boolean.class }, entity, "table_index", @@ -376,7 +470,8 @@ void addEntityLooksUpEntityContextFromMap() throws Exception { null, false, Collections.emptyMap(), - docBuildContexts); + docBuildContexts, + false); assertSame(ctxForEntity, ContextCapturingIndex.observedContext); assertSame(edges, ContextCapturingIndex.observedContext.prefetchedUpstreamLineage()); @@ -465,7 +560,8 @@ void addEntityFallsBackToEmptyContextWhenEntityNotInMap() throws Exception { StageStatsTracker.class, boolean.class, Map.class, - Map.class + Map.class, + boolean.class }, entity, "table_index", @@ -473,7 +569,8 @@ void addEntityFallsBackToEmptyContextWhenEntityNotInMap() throws Exception { null, false, Collections.emptyMap(), - Collections.emptyMap()); + Collections.emptyMap(), + false); assertSame(DocBuildContext.empty(), ContextCapturingIndex.observedContext); } @@ -796,6 +893,12 @@ private void setAtomicField(Object target, String fieldName, long value) throws } } + private Object getPrivateField(Object target, String fieldName) throws Exception { + Field field = target.getClass().getDeclaredField(fieldName); + field.setAccessible(true); + return field.get(target); + } + private static class StubSearchIndex implements SearchIndex { private final Map doc; diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/cache/NotFoundCacheTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/cache/NotFoundCacheTest.java new file mode 100644 index 000000000000..f4dfa51e6ef6 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/cache/NotFoundCacheTest.java @@ -0,0 +1,260 @@ +/* + * 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. + */ +package org.openmetadata.service.cache; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyMap; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.UUID; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +@ExtendWith(MockitoExtension.class) +class NotFoundCacheTest { + @Mock private CacheProvider provider; + + private final Map values = new HashMap<>(); + private CacheKeys keys; + private NotFoundCache cache; + + @BeforeEach + void setUp() { + CacheConfig config = new CacheConfig(); + config.notFoundTtlSeconds = 30; + keys = new CacheKeys("test"); + cache = new NotFoundCache(provider, keys, config); + + when(provider.available()).thenReturn(true); + when(provider.get(anyString())) + .thenAnswer(invocation -> Optional.ofNullable(values.get(invocation.getArgument(0)))); + lenient() + .when(provider.mget(any())) + .thenAnswer( + invocation -> { + List cacheKeys = invocation.getArgument(0); + if (cacheKeys.stream().anyMatch(Objects::isNull)) { + throw new IllegalArgumentException("Cache keys must not be null"); + } + return cacheKeys.stream().map(key -> Optional.ofNullable(values.get(key))).toList(); + }); + lenient() + .when(provider.setIfAbsent(anyString(), anyString(), any())) + .thenAnswer( + invocation -> + values.putIfAbsent(invocation.getArgument(0), invocation.getArgument(1)) == null); + lenient() + .doAnswer( + invocation -> { + values.put(invocation.getArgument(0), invocation.getArgument(1)); + return null; + }) + .when(provider) + .set(anyString(), anyString(), any()); + lenient() + .doAnswer( + invocation -> { + for (Object argument : invocation.getArguments()) { + if (argument instanceof String[] keys) { + for (String key : keys) values.remove(key); + } else { + values.remove((String) argument); + } + } + return null; + }) + .when(provider) + .del(any(String[].class)); + lenient() + .when(provider.deleteIfValue(anyString(), anyString())) + .thenAnswer( + invocation -> + values.remove( + invocation.getArgument(0, String.class), + invocation.getArgument(1, String.class))); + lenient() + .when(provider.deleteIfValues(anyMap())) + .thenAnswer( + invocation -> { + Map expectedValues = invocation.getArgument(0); + int deleted = 0; + for (Map.Entry entry : expectedValues.entrySet()) { + if (values.remove(entry.getKey(), entry.getValue())) deleted++; + } + return deleted; + }); + } + + @Test + void hardDeleteMarkerIsDistinctAndCannotBeDowngradedByANormalMiss() { + UUID id = UUID.randomUUID(); + String fqn = "service.entity"; + + cache.markNotFoundById("table", id); + cache.markNotFoundByName("table", fqn); + assertTrue(cache.isMarkedNotFoundById("table", id)); + assertFalse(cache.isMarkedHardDeletedById("table", id)); + + cache.markHardDeletedById("table", id); + cache.markHardDeletedByName("table", fqn, id); + cache.markNotFoundById("table", id); + cache.markNotFoundByName("table", fqn); + + assertTrue(cache.isMarkedHardDeletedById("table", id)); + assertTrue(cache.isMarkedHardDeletedByName("table", fqn)); + } + + @Test + void entityInvalidationClearsHardDeleteMarkersForRecreation() { + UUID id = UUID.randomUUID(); + String fqn = "service.entity"; + cache.markHardDeletedById("table", id); + cache.markHardDeletedByName("table", fqn, id); + + cache.invalidate("table", id, fqn); + + assertFalse(cache.isMarkedNotFoundById("table", id)); + assertFalse(cache.isMarkedNotFoundByName("table", fqn)); + } + + @Test + void knownMissingDecisionReadsEachMarkerOnce() { + UUID id = UUID.randomUUID(); + cache.markNotFoundById("table", id); + clearInvocations(provider); + + assertTrue(cache.isKnownMissingById("table", id, true)); + + verify(provider, times(1)).get(anyString()); + } + + @Test + void updateInvalidationCannotEraseAConcurrentHardDelete() { + UUID id = UUID.randomUUID(); + String fqn = "service.entity"; + cache.markHardDeletedById("table", id); + cache.markHardDeletedByName("table", fqn, id); + + assertTrue(cache.invalidatePreservingHardDelete("table", id, fqn)); + + assertTrue(cache.isMarkedHardDeletedById("table", id)); + assertTrue(cache.isMarkedHardDeletedByName("table", fqn)); + } + + @Test + void updateInvalidationClearsNormalMissesAndAReusedNameFromAnotherEntity() { + UUID id = UUID.randomUUID(); + UUID deletedId = UUID.randomUUID(); + String fqn = "service.entity"; + cache.markNotFoundById("table", id); + cache.markHardDeletedByName("table", fqn, deletedId); + + assertFalse(cache.invalidatePreservingHardDelete("table", id, fqn)); + + assertFalse(cache.isMarkedNotFoundById("table", id)); + assertFalse(cache.isMarkedNotFoundByName("table", fqn)); + } + + @Test + void updateInvalidationSupportsEntityWithoutFullyQualifiedName() { + UUID id = UUID.randomUUID(); + cache.markNotFoundById("table", id); + + assertFalse(cache.invalidatePreservingHardDelete("table", id, null)); + + assertFalse(cache.isMarkedNotFoundById("table", id)); + } + + @Test + void batchCreateClearsAReusedNameWithoutErasingTheOldIdTombstone() { + UUID deletedId = UUID.randomUUID(); + UUID createdId = UUID.randomUUID(); + String fqn = "service.entity"; + cache.markHardDeletedById("table", deletedId); + cache.markHardDeletedByName("table", fqn, deletedId); + cache.markNotFoundById("table", createdId); + + cache.invalidateAll("table", Map.of(createdId, fqn)); + + assertTrue(cache.isMarkedHardDeletedById("table", deletedId)); + assertFalse(cache.isMarkedNotFoundById("table", createdId)); + assertFalse(cache.isMarkedNotFoundByName("table", fqn)); + } + + @Test + void hardDeleteThatWinsDuringCompareAndDeleteIsPreserved() { + UUID id = UUID.randomUUID(); + cache.markNotFoundById("table", id); + when(provider.deleteIfValue(anyString(), eq("not-found"))) + .thenAnswer( + invocation -> { + String key = invocation.getArgument(0, String.class); + values.put(key, "hard-deleted"); + return values.remove(key, invocation.getArgument(1, String.class)); + }); + + assertTrue(cache.invalidatePreservingHardDelete("table", id, null)); + + assertTrue(cache.isMarkedHardDeletedById("table", id)); + } + + @Test + void batchCreateCannotEraseAConcurrentHardDelete() { + UUID id = UUID.randomUUID(); + String fqn = "service.entity"; + cache.markNotFoundById("table", id); + cache.markNotFoundByName("table", fqn); + when(provider.deleteIfValues(anyMap())) + .thenAnswer( + invocation -> { + Map expectedValues = invocation.getArgument(0); + expectedValues.keySet().forEach(key -> values.put(key, "hard-deleted")); + return 0; + }); + + assertTrue(cache.invalidateAll("table", Map.of(id, fqn)).contains(id)); + + assertTrue(cache.isMarkedHardDeletedById("table", id)); + assertTrue(cache.isMarkedHardDeletedByName("table", fqn)); + } + + @Test + void legacyNormalMissIsReadAndClearedAfterBatchCreate() { + UUID id = UUID.randomUUID(); + String fqn = "service.entity"; + values.put(keys.notFoundById("table", id), "1"); + values.put(keys.notFoundByName("table", fqn), "1"); + + assertTrue(cache.isKnownMissingById("table", id, true)); + cache.invalidateAll("table", Map.of(id, fqn)); + + assertFalse(cache.isMarkedNotFoundById("table", id)); + assertFalse(cache.isMarkedNotFoundByName("table", fqn)); + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java index 03e4b8f05a47..6edc062e9e36 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java @@ -3,6 +3,7 @@ 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 static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; @@ -19,8 +20,12 @@ import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -36,6 +41,7 @@ import org.openmetadata.schema.entity.data.ProcessingStatus; import org.openmetadata.schema.type.Include; import org.openmetadata.service.attachments.AssetService; +import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.jdbi3.AssetRepository; import org.openmetadata.service.jdbi3.ContextFileContentRepository; import org.openmetadata.service.jdbi3.ContextFileRepository; @@ -85,7 +91,8 @@ void setUp() { lenient().when(repository.getContentRepository()).thenReturn(contentRepository); lenient().when(repository.getAssetRepository()).thenReturn(assetRepository); - when(repository.get(isNull(), eq(fileId), any(), eq(Include.NON_DELETED), eq(false))) + lenient() + .when(repository.get(isNull(), eq(fileId), any(), eq(Include.NON_DELETED), eq(false))) .thenReturn(file); lenient().when(contentRepository.getById(contentId)).thenReturn(content); lenient().when(assetRepository.getById("asset-1")).thenReturn(asset); @@ -103,9 +110,9 @@ void processSuccessMarksAnalyzingThenProcessed() throws Exception { service(Runnable::run, () -> assetService).process(fileId, contentId); verify(repository, times(2)) - .update(isNull(), same(file), updatedFileCaptor.capture(), anyString()); + .updateIfCurrent(isNull(), same(file), updatedFileCaptor.capture(), anyString()); verify(contentRepository, times(2)) - .update(isNull(), same(content), updatedContentCaptor.capture(), anyString()); + .updateIfCurrent(isNull(), same(content), updatedContentCaptor.capture(), anyString()); List fileUpdates = updatedFileCaptor.getAllValues(); assertEquals(ProcessingStatus.Analyzing, fileUpdates.get(0).getProcessingStatus()); @@ -155,11 +162,56 @@ void processSkipsWhenHeadContentNoLongerMatches() { service(Runnable::run, () -> assetService).process(fileId, contentId); - verify(repository, never()).update(any(), any(), any(), anyString()); - verify(contentRepository, never()).update(any(), any(), any(), anyString()); + verify(repository, never()).updateIfCurrent(any(), any(), any(), anyString()); + verify(contentRepository, never()).updateIfCurrent(any(), any(), any(), anyString()); verify(assetService, never()).read(any()); } + @Test + void processDoesNotPublishResultWhenDeleteWinsConditionalWriteRace() throws Exception { + AtomicBoolean deleted = new AtomicBoolean(); + AtomicInteger fileWriteAttempts = new AtomicInteger(); + CountDownLatch finalWriteStarted = new CountDownLatch(1); + CountDownLatch deleteCommitted = new CountDownLatch(1); + + when(repository.get(isNull(), eq(fileId), any(), eq(Include.NON_DELETED), eq(false))) + .thenAnswer(ignored -> deleted.get() ? null : file); + when(assetService.read(asset)) + .thenReturn( + CompletableFuture.completedFuture( + new ByteArrayInputStream("Quarterly results".getBytes()))); + when(textExtractor.extract(any(InputStream.class), same(file))) + .thenReturn(ContextFileTextExtractor.ExtractionResult.processed("Quarterly results", 3)); + when(repository.updateIfCurrent(isNull(), same(file), any(ContextFile.class), anyString())) + .thenAnswer( + invocation -> { + if (fileWriteAttempts.incrementAndGet() == 2) { + finalWriteStarted.countDown(); + if (!deleteCommitted.await(5, TimeUnit.SECONDS)) { + throw new IllegalStateException("Timed out waiting for simulated hard delete"); + } + throw new PreconditionFailedException("Context file was deleted"); + } + return null; + }); + + CompletableFuture processing = + CompletableFuture.runAsync( + () -> service(Runnable::run, () -> assetService).process(fileId, contentId)); + + assertTrue(finalWriteStarted.await(5, TimeUnit.SECONDS)); + deleted.set(true); + deleteCommitted.countDown(); + processing.get(5, TimeUnit.SECONDS); + + assertEquals(2, fileWriteAttempts.get()); + verify(repository, times(2)) + .updateIfCurrent(isNull(), same(file), updatedFileCaptor.capture(), anyString()); + assertEquals( + List.of(ProcessingStatus.Analyzing, ProcessingStatus.Processed), + updatedFileCaptor.getAllValues().stream().map(ContextFile::getProcessingStatus).toList()); + } + @Test void processRethrowsVirtualMachineErrors() throws Exception { when(assetService.read(asset)) @@ -175,9 +227,9 @@ void processRethrowsVirtualMachineErrors() throws Exception { private void verifyFailedWith(String expectedReason) { verify(repository, times(2)) - .update(isNull(), same(file), updatedFileCaptor.capture(), anyString()); + .updateIfCurrent(isNull(), same(file), updatedFileCaptor.capture(), anyString()); verify(contentRepository, times(2)) - .update(isNull(), same(content), updatedContentCaptor.capture(), anyString()); + .updateIfCurrent(isNull(), same(content), updatedContentCaptor.capture(), anyString()); List fileUpdates = updatedFileCaptor.getAllValues(); assertEquals(ProcessingStatus.Analyzing, fileUpdates.get(0).getProcessingStatus()); @@ -193,9 +245,10 @@ private void verifyFailedWith(String expectedReason) { } private void verifyImmediateFailureWith(String expectedReason) { - verify(repository).update(isNull(), same(file), updatedFileCaptor.capture(), anyString()); + verify(repository) + .updateIfCurrent(isNull(), same(file), updatedFileCaptor.capture(), anyString()); verify(contentRepository) - .update(isNull(), same(content), updatedContentCaptor.capture(), anyString()); + .updateIfCurrent(isNull(), same(content), updatedContentCaptor.capture(), anyString()); ContextFile fileUpdate = updatedFileCaptor.getValue(); assertEquals(ProcessingStatus.Failed, fileUpdate.getProcessingStatus()); diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/EntityRepositoryRestoreTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/EntityRepositoryRestoreTest.java index 9c149502e5c5..a4d84d8218a0 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/EntityRepositoryRestoreTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/EntityRepositoryRestoreTest.java @@ -13,6 +13,7 @@ package org.openmetadata.service.jdbi3; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; @@ -31,6 +32,7 @@ import java.util.List; import java.util.Set; import java.util.UUID; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -218,8 +220,7 @@ void bulkRestoreSubtree_emptyOrNullIds_isNoOp() { // bulkRestoreSubtree loads with Include.ALL — guard that neither the DELETED nor ALL // shape is invoked when the input list is empty/null. - verify(pipelineDAO, never()) - .findEntitiesByIds(anyList(), eq(org.openmetadata.schema.type.Include.DELETED)); + verify(pipelineDAO, never()).findEntitiesByIds(anyList(), eq(Include.DELETED)); verify(pipelineDAO, never()).findEntitiesByIds(anyList(), eq(Include.ALL)); assertEquals(0, repo.restoreAdditionalChildrenCalls); } @@ -257,6 +258,27 @@ void invalidate_clearsRegisteredCacheLayers() { } } + @Test + void remoteInvalidationEvictsLocalEntriesAndAdvancesLoaderEpochs() { + UUID id = UUID.randomUUID(); + String fqn = "service.pipeline"; + long idEpoch = EntityRepository.writeEpochById(Entity.PIPELINE, id); + long nameEpoch = EntityRepository.writeEpochByName(Entity.PIPELINE, fqn); + EntityRepository.CACHE_WITH_ID.put(new ImmutablePair<>(Entity.PIPELINE, id), "stale"); + EntityRepository.CACHE_WITH_NAME.put( + EntityRepository.cacheNameKey(Entity.PIPELINE, fqn), "stale"); + + EntityRepository.onRemoteCacheInvalidate(Entity.PIPELINE, id, fqn); + + assertNull( + EntityRepository.CACHE_WITH_ID.getIfPresent(new ImmutablePair<>(Entity.PIPELINE, id))); + assertNull( + EntityRepository.CACHE_WITH_NAME.getIfPresent( + EntityRepository.cacheNameKey(Entity.PIPELINE, fqn))); + assertTrue(EntityRepository.writeEpochById(Entity.PIPELINE, id) > idEpoch); + assertTrue(EntityRepository.writeEpochByName(Entity.PIPELINE, fqn) > nameEpoch); + } + @Test void bulkRestoreSubtree_entitiesPresentButNoneDeleted_stillRunsAdditionalChildrenHook() { // loadForBulk returns entities, but none are in DELETED state. Bulk path must skip diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java index 41f67ad64938..9e8ab3e03d2f 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java @@ -4,6 +4,8 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertInstanceOf; import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.anyList; @@ -15,6 +17,7 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; @@ -34,6 +37,7 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; @@ -41,8 +45,10 @@ import org.mockito.quality.Strictness; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; +import org.openmetadata.schema.tests.TestSuite; import org.openmetadata.schema.type.ChangeDescription; import org.openmetadata.schema.type.EntityReference; +import org.openmetadata.schema.type.FieldChange; import org.openmetadata.service.Entity; import org.openmetadata.service.apps.bundles.searchIndex.BulkSink; import org.openmetadata.service.apps.bundles.searchIndex.ElasticSearchBulkSink; @@ -363,9 +369,44 @@ void testUpdateEntitiesBulkWithSingleType() throws Exception { // Verify correct entityType String entityType = (String) contextCaptor.getValue().get(ReindexingUtil.ENTITY_TYPE_KEY); assertEquals("table", entityType); + assertEquals( + Boolean.TRUE, contextCaptor.getValue().get(BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY)); assertEquals(3, entitiesCaptor.getValue().size()); } + @Test + void buildBulkScriptedPartialUpdateOnlyAcceptsCompleteTestSuiteRelationshipChanges() { + MockEntityWithType testCase = new MockEntityWithType(Entity.TEST_CASE, "testCase"); + TestSuite testSuite = + new TestSuite() + .withId(UUID.randomUUID()) + .withName("logicalSuite") + .withFullyQualifiedName("logicalSuite"); + testCase.setTestSuites(List.of(testSuite)); + testCase.setChangeDescription( + new ChangeDescription() + .withPreviousVersion(testCase.getVersion()) + .withFieldsUpdated( + List.of( + new FieldChange() + .withName(Entity.FIELD_TEST_SUITES) + .withNewValue(testCase.getTestSuites())))); + doCallRealMethod().when(searchRepository).buildBulkScriptedPartialUpdate(any()); + + SearchRepository.ScriptedPartialUpdate partialUpdate = + searchRepository.buildBulkScriptedPartialUpdate(testCase); + + assertNotNull(partialUpdate); + assertTrue(partialUpdate.script().contains("ctx._source.testSuites = params.testSuites;")); + assertNotNull(partialUpdate.parameters().get(Entity.FIELD_TEST_SUITES)); + + testCase.setChangeDescription( + new ChangeDescription() + .withPreviousVersion(0.9) + .withFieldsUpdated(List.of(new FieldChange().withName(Entity.FIELD_TEST_SUITES)))); + assertNull(searchRepository.buildBulkScriptedPartialUpdate(testCase)); + } + @Test void testUpdateEntitiesBulkWithEmptyList() { // Test with empty list - should not call createBulkSink at all @@ -429,12 +470,54 @@ void testUpdateEntitiesBulkFallsBackToIndividualUpdatesWhenBulkWriteFails() thro verify(mockBulkSink).close(); } + @Test + void testUpdateEntitiesBulkClosesTimedOutSinkBeforeIndividualFallback() throws Exception { + SearchRepository realSearchRepository = mock(SearchRepository.class); + BulkSink mockBulkSink = mock(BulkSink.class); + doCallRealMethod().when(realSearchRepository).updateEntitiesIndex(any()); + when(realSearchRepository.createBulkSink(anyInt(), anyInt(), anyLong())) + .thenReturn(mockBulkSink); + when(realSearchRepository.getSearchClient()).thenReturn(elasticSearchClient); + when(realSearchRepository.checkIfIndexingIsSupported(any())).thenReturn(true); + when(mockBulkSink.flushAndAwait(anyInt())).thenReturn(false); + when(mockBulkSink.getActiveBulkRequestCount()).thenReturn(0); + doNothing().when(realSearchRepository).updateEntityIndex(any()); + + EntityInterface entity = new MockEntityWithType("table", "table1"); + realSearchRepository.updateEntitiesIndex(List.of(entity)); + + InOrder inOrder = inOrder(mockBulkSink, realSearchRepository); + inOrder.verify(mockBulkSink).close(); + inOrder.verify(realSearchRepository).updateEntityIndex(entity); + } + + @Test + void testUpdateEntitiesBulkDoesNotOverlapFallbackWithActiveTimedOutSink() throws Exception { + SearchRepository realSearchRepository = mock(SearchRepository.class); + BulkSink mockBulkSink = mock(BulkSink.class); + doCallRealMethod().when(realSearchRepository).updateEntitiesIndex(any()); + when(realSearchRepository.createBulkSink(anyInt(), anyInt(), anyLong())) + .thenReturn(mockBulkSink); + when(realSearchRepository.getSearchClient()).thenReturn(elasticSearchClient); + when(realSearchRepository.checkIfIndexingIsSupported(any())).thenReturn(true); + when(mockBulkSink.flushAndAwait(anyInt())).thenReturn(false); + when(mockBulkSink.getActiveBulkRequestCount()).thenReturn(1); + + EntityInterface entity = new MockEntityWithType("table", "table1"); + realSearchRepository.updateEntitiesIndex(List.of(entity)); + + verify(mockBulkSink).close(); + verify(realSearchRepository, never()).updateEntityIndex(any()); + } + /** Mock entity that allows setting a specific entity type for testing */ static class MockEntityWithType implements EntityInterface { private final UUID id = UUID.randomUUID(); private final String entityType; private final String name; private final String fqn; + private ChangeDescription changeDescription; + private List testSuites; MockEntityWithType(String entityType, String name) { this.entityType = entityType; @@ -489,7 +572,7 @@ public URI getHref() { @Override public ChangeDescription getChangeDescription() { - return null; + return changeDescription; } @Override @@ -518,7 +601,17 @@ public void setName(String name) {} public void setVersion(Double newVersion) {} @Override - public void setChangeDescription(ChangeDescription changeDescription) {} + public void setChangeDescription(ChangeDescription changeDescription) { + this.changeDescription = changeDescription; + } + + public List getTestSuites() { + return testSuites; + } + + public void setTestSuites(List testSuites) { + this.testSuites = testSuites; + } @Override public void setIncrementalChangeDescription(ChangeDescription incrementalChangeDescription) {} diff --git a/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/OverviewPageObject.ts b/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/OverviewPageObject.ts index 3a99f4c4741f..fa717d4c0788 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/OverviewPageObject.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/e2e/PageObject/Explore/OverviewPageObject.ts @@ -810,7 +810,7 @@ export class OverviewPageObject extends RightPanelBase { * Verify owners section is visible */ async shouldShowOwner(ownerName: string): Promise { - await this.page.getByTestId(`${ownerName}`).waitFor({ state: 'visible' }); + await this.container.getByTestId(ownerName).waitFor({ state: 'visible' }); } /** diff --git a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageFilters.spec.ts b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageFilters.spec.ts index fed00352e565..f8a27f97cbac 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageFilters.spec.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageFilters.spec.ts @@ -12,6 +12,7 @@ */ import { APIRequestContext, expect } from '@playwright/test'; import { get } from 'lodash'; +import type { AggregationRequest } from '../../../../src/generated/search/aggregationRequest'; import { ApiEndpointClass } from '../../../support/entity/ApiEndpointClass'; import { ContainerClass } from '../../../support/entity/ContainerClass'; import { DashboardClass } from '../../../support/entity/DashboardClass'; @@ -42,6 +43,7 @@ import { setLineageDepthAndVerify, visitLineageTab, } from '../../../utils/lineage'; +import { waitForSearchIndexed } from '../../../utils/polling'; import { test } from '../../fixtures/pages'; type EntityClassUnion = @@ -80,6 +82,24 @@ const allEntities = { worksheet: WorksheetClass, }; +const searchIndexByEntityType: Record = { + apiEndpoint: 'api_endpoint_search_index', + container: 'container_search_index', + dashboard: 'dashboard_search_index', + dashboardDataModel: 'dashboard_data_model_search_index', + directory: 'directory_search_index', + file: 'file_search_index', + metric: 'metric_search_index', + mlmodel: 'mlmodel_search_index', + pipeline: 'pipeline_search_index', + searchIndex: 'search_entity_search_index', + spreadsheet: 'spreadsheet_search_index', + storedProcedure: 'stored_procedure_search_index', + table: 'table_search_index', + topic: 'topic_search_index', + worksheet: 'worksheet_search_index', +}; + test.describe('Lineage Filters', () => { const lineageEntity = new TableClass(); const entities = Object.values(allEntities).map( @@ -121,6 +141,22 @@ test.describe('Lineage Filters', () => { ); } + await Promise.all( + [lineageEntity, ...entities].map((entity) => { + const entityType = getEntityTypeSearchIndexMapping(entity.type); + const searchIndex = searchIndexByEntityType[entityType]; + if (!searchIndex) { + throw new Error(`Search index is not mapped for ${entity.type}`); + } + + return waitForSearchIndexed( + apiContext, + entity.entityResponseData.fullyQualifiedName, + searchIndex + ); + }) + ); + await afterAction(); }); @@ -410,11 +446,29 @@ test.describe('Lineage Filters', () => { '' ); - const searchResponse = page.waitForResponse( - (response) => - response.url().includes(`/api/v1/search/aggregate`) && - response.request().method() === 'POST' - ); + const searchResponse = page.waitForResponse((response) => { + let requestBody: AggregationRequest; + try { + requestBody = JSON.parse( + response.request().postData() ?? '{}' + ) as AggregationRequest; + } catch { + return false; + } + const normalizedFieldValue = (requestBody.fieldValue ?? '') + .replaceAll('\\', '') + .replace(/^\.\*/, '') + .replace(/\.\*$/, ''); + + return ( + new URL(response.url()).pathname.endsWith( + '/api/v1/search/aggregate' + ) && + response.request().method() === 'POST' && + requestBody.fieldName === 'service.displayName.keyword' && + normalizedFieldValue === serviceName + ); + }); await page .getByTestId('drop-down-menu') @@ -438,8 +492,20 @@ test.describe('Lineage Filters', () => { (_, idx) => idx !== index ); + const lineageResponse = page.waitForResponse((response) => { + const url = new URL(response.url()); + + return ( + url.pathname.endsWith('/api/v1/lineage/getLineageByEntityCount') && + response.request().method() === 'GET' && + url.searchParams.get('fqn') === + lineageEntity.entityResponseData.fullyQualifiedName && + (url.searchParams.get('query_filter') ?? '').includes(serviceName) + ); + }); + await page.getByRole('button', { name: 'Update' }).click(); - await expect(page.getByRole('button', { name: 'Update' })).toBeHidden(); + expect((await lineageResponse).status()).toBe(200); for (const entity of entitiesToShow) { await expect( @@ -461,9 +527,20 @@ test.describe('Lineage Filters', () => { const clearAllBtn = page.getByRole('button', { name: /clear/i }); await expect(clearAllBtn).toBeEnabled(); - await clearAllBtn.click(); + const clearLineageResponse = page.waitForResponse((response) => { + const url = new URL(response.url()); - await waitForAllLoadersToDisappear(page); + return ( + url.pathname.endsWith('/api/v1/lineage/getLineageByEntityCount') && + response.request().method() === 'GET' && + url.searchParams.get('fqn') === + lineageEntity.entityResponseData.fullyQualifiedName && + !(url.searchParams.get('query_filter') ?? '').includes(serviceName) + ); + }); + + await clearAllBtn.click(); + expect((await clearLineageResponse).status()).toBe(200); }); } }); diff --git a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageRightPanel.spec.ts b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageRightPanel.spec.ts index b5ff49c146e0..515913556ba1 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageRightPanel.spec.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/e2e/Pages/Lineage/LineageRightPanel.spec.ts @@ -11,7 +11,6 @@ * limitations under the License. */ import { expect } from '@playwright/test'; -import { get } from 'lodash'; import { PLAYWRIGHT_BASIC_TEST_TAG_OBJ } from '../../../constant/config'; import { SidebarItem } from '../../../constant/sidebar'; import { ApiEndpointClass } from '../../../support/entity/ApiEndpointClass'; @@ -35,8 +34,8 @@ import { getDefaultAdminAPIContext, redirectToHomePage, } from '../../../utils/common'; -import { waitForAllLoadersToDisappear } from '../../../utils/entity'; import { clickLineageNode, visitLineageTab } from '../../../utils/lineage'; +import { waitForSearchIndexed } from '../../../utils/polling'; import { sidebarClick } from '../../../utils/sidebar'; import { test } from '../../fixtures/pages'; @@ -88,13 +87,14 @@ test.describe( await entity.visitEntityPage(page, searchTerm); await visitLineageTab(page); - const nodeFqn = entity.entityResponseData?.['fullyQualifiedName'] ?? ''; + const nodeFqn = + entity.entityResponseData?.['fullyQualifiedName'] || searchTerm; await clickLineageNode(page, nodeFqn); const lineagePanel = page.getByTestId('lineage-entity-panel'); await expect(lineagePanel).toBeVisible(); - await waitForAllLoadersToDisappear(page); + await expect(lineagePanel.getByTestId('overview-tab')).toBeVisible(); const customPropertiesTab = lineagePanel.getByTestId( 'custom-properties-tab' @@ -113,13 +113,41 @@ test.describe( test.describe('Verify custom properties tab is NOT visible for unsupported entity types in platform lineage', () => { const unsupportedServices = [ - { service: new DatabaseServiceClass(), type: 'databaseService' }, - { service: new MessagingServiceClass(), type: 'messagingService' }, - { service: new DashboardServiceClass(), type: 'dashboardService' }, - { service: new PipelineServiceClass(), type: 'pipelineService' }, - { service: new MlmodelServiceClass(), type: 'mlmodelService' }, - { service: new StorageServiceClass(), type: 'storageService' }, - { service: new ApiServiceClass(), type: 'apiService' }, + { + service: new DatabaseServiceClass(), + type: 'databaseService', + searchIndex: 'database_service_search_index', + }, + { + service: new MessagingServiceClass(), + type: 'messagingService', + searchIndex: 'messaging_service_search_index', + }, + { + service: new DashboardServiceClass(), + type: 'dashboardService', + searchIndex: 'dashboard_service_search_index', + }, + { + service: new PipelineServiceClass(), + type: 'pipelineService', + searchIndex: 'pipeline_service_search_index', + }, + { + service: new MlmodelServiceClass(), + type: 'mlmodelService', + searchIndex: 'mlmodel_service_search_index', + }, + { + service: new StorageServiceClass(), + type: 'storageService', + searchIndex: 'storage_service_search_index', + }, + { + service: new ApiServiceClass(), + type: 'apiService', + searchIndex: 'api_service_search_index', + }, ]; test.beforeAll(async ({ browser }) => { @@ -132,6 +160,15 @@ test.describe('Verify custom properties tab is NOT visible for unsupported entit createEntityArray.push(service.create(apiContext)); } await Promise.all(createEntityArray); + await Promise.all( + unsupportedServices.map(({ service, searchIndex }) => + waitForSearchIndexed( + apiContext, + service.entityResponseData.fullyQualifiedName, + searchIndex + ) + ) + ); await afterAction(); }); @@ -144,7 +181,7 @@ test.describe('Verify custom properties tab is NOT visible for unsupported entit test(`Verify custom properties tab is NOT visible for ${type} in platform lineage`, async ({ page, }) => { - const serviceFqn = get(service, 'entityResponseData.fullyQualifiedName'); + const serviceFqn = service.entity.name; await sidebarClick(page, SidebarItem.LINEAGE); @@ -156,21 +193,33 @@ test.describe('Verify custom properties tab is NOT visible for unsupported entit .getByTestId('search-entity-select') .locator('.ant-select-selection-search-input'); - const searchResponse = page.waitForResponse((response) => - response.url().includes('/api/v1/search/query') - ); + const searchResponse = page.waitForResponse((response) => { + const url = new URL(response.url()); + const query = url.searchParams.get('q')?.replaceAll('\\', '') ?? ''; + + return ( + url.pathname.endsWith('/api/v1/search/query') && + response.request().method() === 'GET' && + query.includes(serviceFqn) + ); + }); await searchInput.fill(service.entity.name); const searchResponseResult = await searchResponse; expect(searchResponseResult.status()).toBe(200); const nodeSuggestion = page.getByTestId(`node-suggestion-${serviceFqn}`); - //small timeout to wait for the node suggestion to be visible in dropdown await expect(nodeSuggestion).toBeVisible(); - const lineageResponse = page.waitForResponse((response) => - response.url().includes('/api/v1/lineage/getLineage') - ); + const lineageResponse = page.waitForResponse((response) => { + const url = new URL(response.url()); + + return ( + url.pathname.endsWith('/api/v1/lineage/getLineage') && + response.request().method() === 'GET' && + url.searchParams.get('fqn') === serviceFqn + ); + }); await nodeSuggestion.click(); @@ -185,7 +234,7 @@ test.describe('Verify custom properties tab is NOT visible for unsupported entit const lineagePanel = page.getByTestId('lineage-entity-panel'); await expect(lineagePanel).toBeVisible(); - await waitForAllLoadersToDisappear(page); + await expect(lineagePanel.getByTestId('overview-tab')).toBeVisible(); const customPropertiesTab = lineagePanel.getByTestId( 'custom-properties-tab' diff --git a/openmetadata-ui/src/main/resources/ui/playwright/support/entity/DashboardDataModelClass.ts b/openmetadata-ui/src/main/resources/ui/playwright/support/entity/DashboardDataModelClass.ts index 092cd91ac773..65634e163c45 100644 --- a/openmetadata-ui/src/main/resources/ui/playwright/support/entity/DashboardDataModelClass.ts +++ b/openmetadata-ui/src/main/resources/ui/playwright/support/entity/DashboardDataModelClass.ts @@ -173,8 +173,15 @@ export class DashboardDataModelClass extends EntityClass { this.serviceResponseData = await serviceResponse.json(); this.entityResponseData = await entityResponse.json(); + const dataModelFqn = this.entityResponseData.fullyQualifiedName; + if (!dataModelFqn) { + throw new Error( + 'Dashboard data model response is missing its fully qualified name' + ); + } this.childrenSelectorId = - this.entityResponseData.columns[0].fullyQualifiedName ?? ''; + this.entityResponseData.columns?.[0]?.fullyQualifiedName ?? + `${dataModelFqn}.${this.children[0].name}`; return { service: serviceResponse.body, From 9a1d197eaf0bd5cb8f492eaf03f35fca1d3e1a5a Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 01:22:56 -0700 Subject: [PATCH 02/47] Address integration stability review feedback --- .../playwright-integration-tests-mysql.yml | 3 + .../playwright-integration-tests-postgres.yml | 3 + .../service/jdbi3/TestCaseRepository.java | 117 +++++++++++------- .../service/search/SearchRepository.java | 104 +++++++++++----- .../service/search/SearchRepositoryTest.java | 97 +++++++++++---- 5 files changed, 217 insertions(+), 107 deletions(-) diff --git a/.github/workflows/playwright-integration-tests-mysql.yml b/.github/workflows/playwright-integration-tests-mysql.yml index ed915aa0a806..562b09e80a95 100644 --- a/.github/workflows/playwright-integration-tests-mysql.yml +++ b/.github/workflows/playwright-integration-tests-mysql.yml @@ -17,6 +17,9 @@ on: pull_request_target: types: [labeled, opened, synchronize, reopened, ready_for_review] +permissions: + contents: read + concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test' }} diff --git a/.github/workflows/playwright-integration-tests-postgres.yml b/.github/workflows/playwright-integration-tests-postgres.yml index 456823fcdf6a..57ca9ff6a69a 100644 --- a/.github/workflows/playwright-integration-tests-postgres.yml +++ b/.github/workflows/playwright-integration-tests-postgres.yml @@ -17,6 +17,9 @@ on: pull_request_target: types: [labeled, opened, synchronize, reopened, ready_for_review] +permissions: + contents: read + concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: ${{ github.event_name != 'pull_request_target' || github.event.action != 'labeled' || github.event.label.name == 'safe to test' }} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index eab3c2b6afdc..d3ed753d520a 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.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.csv.CsvUtil.addField; import static org.openmetadata.csv.CsvUtil.addGlossaryTerms; @@ -13,6 +14,7 @@ import static org.openmetadata.service.Entity.FIELD_OWNERS; import static org.openmetadata.service.Entity.FIELD_REVIEWERS; import static org.openmetadata.service.Entity.FIELD_TAGS; +import static org.openmetadata.service.Entity.FIELD_TEST_SUITES; import static org.openmetadata.service.Entity.INGESTION_BOT_NAME; import static org.openmetadata.service.Entity.TABLE; import static org.openmetadata.service.Entity.TEAM; @@ -28,6 +30,7 @@ import static org.openmetadata.service.security.mask.PIIMasker.maskSampleData; import com.google.common.collect.Lists; +import com.google.common.util.concurrent.Striped; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import java.io.IOException; @@ -42,6 +45,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.locks.Lock; import java.util.function.Function; import java.util.stream.Collectors; import lombok.SneakyThrows; @@ -121,6 +125,7 @@ public class TestCaseRepository extends EntityRepository { private static final String PATCH_FIELDS = "owners,entityLink,testSuite,testSuites,testDefinition,computePassedFailedRowCount,useDynamicAssertion,dimensionColumns,topDimensions"; public static final String FAILED_ROWS_SAMPLE_EXTENSION = "testCase.failedRowsSample"; + private static final Striped LOGICAL_SUITE_PUBLICATION_LOCKS = Striped.lock(4096); private final ExecutorService asyncExecutor = Executors.newFixedThreadPool( 1, java.lang.Thread.ofPlatform().name("om-test-case-async").factory()); @@ -1103,8 +1108,7 @@ public RestUtil.PutResponse addTestCasesToLogicalTestSuite( addedTestCases.set( addTestCasesToLogicalTestSuiteFlush(testSuite.getId(), testCaseIds))); - List updatedTestCases = getLogicalSuiteUpdatedTestCase(addedTestCases.get()); - postLogicalSuiteRelationshipUpdate(updatedTestCases); + postLogicalSuiteRelationshipUpdate(addedTestCases.get(), testSuite.getId()); updateLogicalTestSuite(testSuite.getId()); return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); } @@ -1133,8 +1137,7 @@ public RestUtil.PutResponse addAllTestCasesToLogicalTestSuite( addAllTestCasesToLogicalTestSuiteFlush(testSuite.getId(), excludedTestCaseIds))); for (List batch : Lists.partition(addedTestCases.get(), 100)) { - List updatedTestCases = getLogicalSuiteUpdatedTestCase(batch); - postLogicalSuiteRelationshipUpdate(updatedTestCases); + postLogicalSuiteRelationshipUpdate(batch, testSuite.getId()); } updateLogicalTestSuite(testSuite.getId()); return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); @@ -1181,66 +1184,80 @@ public RestUtil.DeleteResponse deleteTestCaseFromLogicalTestSuite( deleteRelationship( testSuiteId, TEST_SUITE, testCaseId, TEST_CASE, Relationship.CONTAINS)); - TestCase updatedTestCase = Entity.getEntity(Entity.TEST_CASE, testCaseId, "*", Include.ALL); - ChangeDescription change = - new ChangeDescription() - .withPreviousVersion(updatedTestCase.getVersion()) - .withFieldsUpdated( - List.of( - new FieldChange() - .withName("testSuites") - .withNewValue(updatedTestCase.getTestSuites()))); - updatedTestCase.setChangeDescription(change); - - postUpdate(testCase, updatedTestCase); + TestCase updatedTestCase = + postLogicalSuiteRelationshipUpdate(List.of(testCase.getEntityReference()), testSuiteId) + .getFirst(); updateLogicalTestSuite(testSuiteId); testCase.setTestSuite(updatedTestCase.getTestSuite()); testCase.setTestSuites(updatedTestCase.getTestSuites()); return new RestUtil.DeleteResponse<>(testCase, ENTITY_DELETED); } - private List getLogicalSuiteUpdatedTestCase(List testCaseReferences) { + private List getLogicalSuiteUpdatedTestCase( + List testCaseReferences, UUID testSuiteId) { List testCases = Entity.getEntities(testCaseReferences, "*", Include.ALL); testCases.forEach( tc -> { - ChangeDescription change = - new ChangeDescription() - .withPreviousVersion(tc.getVersion()) - .withFieldsUpdated( - List.of( - new FieldChange() - .withName("testSuites") - .withNewValue(tc.getTestSuites()))); + TestSuite currentTestSuite = + listOrEmpty(tc.getTestSuites()).stream() + .filter(testSuite -> testSuiteId.equals(testSuite.getId())) + .findFirst() + .orElse(null); + FieldChange relationshipChange = new FieldChange().withName(FIELD_TEST_SUITES); + ChangeDescription change = new ChangeDescription().withPreviousVersion(tc.getVersion()); + if (currentTestSuite == null) { + relationshipChange.setOldValue(List.of(new TestSuite().withId(testSuiteId))); + change.setFieldsDeleted(List.of(relationshipChange)); + } else { + relationshipChange.setNewValue(List.of(currentTestSuite)); + change.setFieldsAdded(List.of(relationshipChange)); + } tc.setChangeDescription(change); }); return testCases; } /** - * Lifecycle hook for the "test case added to a logical test suite" bulk flow. Bypasses - * {@code postUpdateMany}'s {@code writeThroughCacheMany} because adding a CONTAINS row to the - * {@code test_suite ↔ test_case} relationship table does not modify the {@link TestCase} - * entity's stored JSON — {@code testSuites} is stripped from storage JSON (see {@link - * #getFieldsStrippedFromStorageJson}) and is rehydrated from {@code entity_relationship} on - * read. Writing the pre-read snapshot back to cache here races against any concurrent PATCH - * that landed on the same test case during this transaction — exactly the staleness pattern - * that previously caused {@code BaseEntityIT.testBulkFluentAPI} to time out for TestCase when - * {@code test_bulkAddAllTestCasesWithExcludeIds} executed in parallel. Invalidate the - * read-bundle (where {@code testSuites} is fanned out) instead so the next read picks up the - * new relationship without clobbering concurrent writers. + * Publishes logical-suite relationship changes from committed database state. Relationship rows + * do not modify the stored {@link TestCase} JSON, so publication invalidates the hydrated read + * bundle and reloads while holding deterministic per-test-case locks. Concurrent add/delete + * requests therefore publish in lock order, and a late request observes the current relationship + * state instead of replaying its pre-commit snapshot. The resulting change description contains + * an idempotent add/remove delta for search rather than a replacement {@code testSuites} array. */ - private void postLogicalSuiteRelationshipUpdate(List updatedTestCases) { - if (updatedTestCases == null || updatedTestCases.isEmpty()) { - return; + private List postLogicalSuiteRelationshipUpdate( + List testCaseReferences, UUID testSuiteId) { + if (nullOrEmpty(testCaseReferences)) { + return List.of(); + } + + List publicationLocks = new ArrayList<>(); + for (Lock publicationLock : + LOGICAL_SUITE_PUBLICATION_LOCKS.bulkGet( + testCaseReferences.stream().map(EntityReference::getId).toList())) { + if (!publicationLocks.contains(publicationLock)) { + publicationLocks.add(publicationLock); + } } - var cachedReadBundle = CacheBundle.getCachedReadBundle(); - if (cachedReadBundle != null) { - for (TestCase tc : updatedTestCases) { - cachedReadBundle.invalidate(entityType, tc.getId()); + publicationLocks.forEach(Lock::lock); + try { + var cachedReadBundle = CacheBundle.getCachedReadBundle(); + if (cachedReadBundle != null) { + for (EntityReference testCaseReference : testCaseReferences) { + cachedReadBundle.invalidate(entityType, testCaseReference.getId()); + } + } + + List updatedTestCases = + getLogicalSuiteUpdatedTestCase(testCaseReferences, testSuiteId); + EntityLifecycleEventDispatcher.getInstance().onEntitiesUpdated(updatedTestCases, null, null); + updatedTestCases.forEach(RdfUpdater::updateEntity); + return updatedTestCases; + } finally { + for (int index = publicationLocks.size() - 1; index >= 0; index--) { + publicationLocks.get(index).unlock(); } } - EntityLifecycleEventDispatcher.getInstance().onEntitiesUpdated(updatedTestCases, null, null); - updatedTestCases.forEach(RdfUpdater::updateEntity); } @Override @@ -1684,8 +1701,14 @@ private enum Direction { @Override public void postUpdate(TestCase original, TestCase updated) { - hydrateTestSuiteFieldsForSearch(updated); - super.postUpdate(original, updated); + Lock publicationLock = LOGICAL_SUITE_PUBLICATION_LOCKS.get(updated.getId()); + publicationLock.lock(); + try { + hydrateTestSuiteFieldsForSearch(updated); + super.postUpdate(original, updated); + } finally { + publicationLock.unlock(); + } if (EntityStatus.IN_REVIEW.equals(original.getEntityStatus())) { if (EntityStatus.APPROVED.equals(updated.getEntityStatus())) { closeApprovalTask(updated, "Approved the test case"); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index e20cd17fdd5c..6465c37cb931 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -348,6 +348,24 @@ public static void deferOrRunSearchWrite( private static final Set BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS = Set.of(TEST_SUITES); + private static final String TEST_SUITES_ADDED_PARAM = "testSuitesAdded"; + private static final String TEST_SUITE_IDS_DELETED_PARAM = "testSuiteIdsDeleted"; + private static final String TEST_SUITES_DELTA_SCRIPT = + """ + if (params.testSuiteIdsDeleted != null && ctx._source.testSuites != null) { + ctx._source.testSuites.removeIf(suite -> params.testSuiteIdsDeleted.contains(suite.id)); + } + if (params.testSuitesAdded != null) { + if (ctx._source.testSuites == null) { + ctx._source.testSuites = []; + } + for (def addedSuite : params.testSuitesAdded) { + ctx._source.testSuites.removeIf(suite -> suite.id == addedSuite.id); + ctx._source.testSuites.add(addedSuite); + } + } + """; + @Getter private final ElasticSearchConfiguration searchConfiguration; @Getter private final int maxDBConnections; @@ -1753,6 +1771,7 @@ public void updateEntitiesIndex(List entities) { int batchSize = 100; int maxConcurrentRequests = 5; long maxPayloadSizeBytes = SearchClusterMetrics.DEFAULT_BULK_PAYLOAD_SIZE_BYTES; + List bulkUpdatedEntities = new ArrayList<>(); // Process each entity type separately to ensure correct index routing for (Map.Entry> entry : entitiesByType.entrySet()) { @@ -1770,12 +1789,14 @@ public void updateEntitiesIndex(List entities) { } BulkSink bulkSink = null; + boolean bulkWriteAttempted = false; try { bulkSink = createBulkSink(batchSize, maxConcurrentRequests, maxPayloadSizeBytes); Map contextData = new HashMap<>(); contextData.put(ReindexingUtil.ENTITY_TYPE_KEY, entityType); contextData.put(BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY, true); ReindexingUtil.populateDocBuildContext(contextData, entityType, typeEntities); + bulkWriteAttempted = true; bulkSink.write(typeEntities, contextData); boolean completed = bulkSink.flushAndAwait(60); // Wait up to 60 seconds for completion StepStats sinkStats = bulkSink.getStats(); @@ -1785,14 +1806,14 @@ public void updateEntitiesIndex(List entities) { throw new IOException( "Bulk entity update did not complete successfully for type " + entityType); } + bulkUpdatedEntities.addAll(typeEntities); } catch (Exception e) { LOG.error("Error during bulk entity update in search index for type {}", entityType, e); - boolean bulkSinkQuiescent = true; if (bulkSink != null) { - bulkSinkQuiescent = closeBulkSinkAndCheckQuiescent(bulkSink); + closeBulkSink(bulkSink); bulkSink = null; } - if (bulkSinkQuiescent) { + if (!bulkWriteAttempted) { for (EntityInterface entity : typeEntities) { try { updateEntityIndex(entity); @@ -1805,28 +1826,26 @@ public void updateEntitiesIndex(List entities) { for (EntityInterface entity : typeEntities) { SearchIndexRetryQueue.enqueue( entity, - "updateEntitiesBulk: bulk sink still active; skipped overlapping fallback", + "updateEntitiesBulk: outcome unknown after bulk write; skipped stale fallback", e); } } } finally { if (bulkSink != null) { - closeBulkSinkAndCheckQuiescent(bulkSink); + closeBulkSink(bulkSink); } } } // Run fan-out propagation once after all bulk doc updates are flushed. - propagateEntitiesAfterBulkFlush(dedupedEntities.values()); + propagateEntitiesAfterBulkFlush(bulkUpdatedEntities); } - private boolean closeBulkSinkAndCheckQuiescent(BulkSink bulkSink) { + private void closeBulkSink(BulkSink bulkSink) { try { bulkSink.close(); - return bulkSink.getActiveBulkRequestCount() == 0; } catch (Exception e) { LOG.warn("Error closing bulk sink", e); - return false; } } @@ -3029,8 +3048,12 @@ public String getScriptWithParams( ChangeDescription changeDescription) { List fieldsAdded = changeDescription.getFieldsAdded(); StringBuilder scriptTxt = new StringBuilder(); - fieldAddParams.put("updatedAt", entity.getUpdatedAt()); - scriptTxt.append("ctx._source.updatedAt=params.updatedAt;"); + List> testSuitesAdded = new ArrayList<>(); + List testSuiteIdsDeleted = new ArrayList<>(); + if (!BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS.equals(getChangedFieldNames(changeDescription))) { + fieldAddParams.put("updatedAt", entity.getUpdatedAt()); + scriptTxt.append("ctx._source.updatedAt=params.updatedAt;"); + } for (FieldChange fieldChange : fieldsAdded) { if (fieldChange.getName().equalsIgnoreCase(FIELD_FOLLOWERS)) { @SuppressWarnings("unchecked") @@ -3055,6 +3078,9 @@ public String getScriptWithParams( fieldAddParams.put(FIELD_DESCRIPTION, entity.getDescription()); scriptTxt.append("ctx._source.description = params.description;"); } + if (fieldChange.getName().equalsIgnoreCase(TEST_SUITES)) { + testSuitesAdded.addAll(getTestSuiteValues(fieldChange.getNewValue())); + } } for (FieldChange fieldChange : changeDescription.getFieldsDeleted()) { @@ -3070,6 +3096,13 @@ public String getScriptWithParams( if (fieldChange.getName().equalsIgnoreCase(FIELD_DESCRIPTION)) { scriptTxt.append("ctx._source.description = null;"); } + if (fieldChange.getName().equalsIgnoreCase(TEST_SUITES)) { + getTestSuiteValues(fieldChange.getOldValue()).stream() + .map(testSuite -> testSuite.get(ID)) + .filter(Objects::nonNull) + .map(Object::toString) + .forEach(testSuiteIdsDeleted::add); + } } for (FieldChange fieldChange : changeDescription.getFieldsUpdated()) { @@ -3102,11 +3135,6 @@ public String getScriptWithParams( Map doc = JsonUtils.getMap(entity); fieldAddParams.put("newPipelineStatus", doc.get("pipelineStatus")); } - if (fieldChange.getName().equalsIgnoreCase(TEST_SUITES)) { - scriptTxt.append("ctx._source.testSuites = params.testSuites;"); - Map doc = JsonUtils.getMap(entity); - fieldAddParams.put(TEST_SUITES, doc.get(TEST_SUITES)); - } if (fieldChange.getName().equalsIgnoreCase("extension")) { String entityType = entity.getEntityReference().getType(); List> customPropertiesTyped = @@ -3117,6 +3145,11 @@ public String getScriptWithParams( scriptTxt.append("ctx._source.extension = params.extension;"); } } + if (!testSuitesAdded.isEmpty() || !testSuiteIdsDeleted.isEmpty()) { + fieldAddParams.put(TEST_SUITES_ADDED_PARAM, testSuitesAdded); + fieldAddParams.put(TEST_SUITE_IDS_DELETED_PARAM, testSuiteIdsDeleted); + scriptTxt.append(TEST_SUITES_DELTA_SCRIPT); + } return scriptTxt.toString(); } @@ -3125,7 +3158,8 @@ public ScriptedPartialUpdate buildBulkScriptedPartialUpdate(EntityInterface enti return null; } ChangeDescription changeDescription = getEffectiveChangeDescription(entity); - if (!BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS.equals(getChangedFieldNames(changeDescription))) { + if (!BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS.equals(getChangedFieldNames(changeDescription)) + || hasTestSuiteReplacement(changeDescription)) { return null; } boolean isNonVersionedUpdate = @@ -3135,21 +3169,18 @@ public ScriptedPartialUpdate buildBulkScriptedPartialUpdate(EntityInterface enti if (!isNonVersionedUpdate) { return null; } - Object testSuites = - Stream.of( - listOrEmpty(changeDescription.getFieldsAdded()), - listOrEmpty(changeDescription.getFieldsUpdated()), - listOrEmpty(changeDescription.getFieldsDeleted())) - .flatMap(List::stream) - .filter(fieldChange -> TEST_SUITES.equals(fieldChange.getName())) - .map(FieldChange::getNewValue) - .filter(Objects::nonNull) - .findFirst() - .orElse(null); - return testSuites == null - ? null - : new ScriptedPartialUpdate( - "ctx._source.testSuites = params.testSuites;", Map.of(TEST_SUITES, testSuites)); + return buildScriptedPartialUpdate(entity, changeDescription, isNonVersionedUpdate); + } + + private List> getTestSuiteValues(Object value) { + if (value == null) { + return List.of(); + } + List values = value instanceof List list ? list : List.of(value); + return values.stream() + .map(JsonUtils::getMap) + .filter(testSuite -> testSuite.get(ID) != null) + .toList(); } private ScriptedPartialUpdate buildScriptedPartialUpdate( @@ -3172,7 +3203,14 @@ private ChangeDescription getEffectiveChangeDescription(EntityInterface entity) private boolean canUseScriptedPartialUpdate(ChangeDescription changeDescription) { Set changedFieldNames = getChangedFieldNames(changeDescription); return !changedFieldNames.isEmpty() - && changedFieldNames.stream().allMatch(PARTIAL_SCRIPT_SUPPORTED_FIELDS::contains); + && changedFieldNames.stream().allMatch(PARTIAL_SCRIPT_SUPPORTED_FIELDS::contains) + && !hasTestSuiteReplacement(changeDescription); + } + + private boolean hasTestSuiteReplacement(ChangeDescription changeDescription) { + return changeDescription != null + && listOrEmpty(changeDescription.getFieldsUpdated()).stream() + .anyMatch(fieldChange -> TEST_SUITES.equals(fieldChange.getName())); } private Set getChangedFieldNames(ChangeDescription changeDescription) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java index 9e8ab3e03d2f..1195186e5a5e 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryTest.java @@ -17,7 +17,6 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockStatic; @@ -37,7 +36,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; -import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockedStatic; import org.mockito.junit.jupiter.MockitoExtension; @@ -45,6 +43,7 @@ import org.mockito.quality.Strictness; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; +import org.openmetadata.schema.system.StepStats; import org.openmetadata.schema.tests.TestSuite; import org.openmetadata.schema.type.ChangeDescription; import org.openmetadata.schema.type.EntityReference; @@ -377,33 +376,55 @@ void testUpdateEntitiesBulkWithSingleType() throws Exception { @Test void buildBulkScriptedPartialUpdateOnlyAcceptsCompleteTestSuiteRelationshipChanges() { MockEntityWithType testCase = new MockEntityWithType(Entity.TEST_CASE, "testCase"); - TestSuite testSuite = + TestSuite addedTestSuite = new TestSuite() .withId(UUID.randomUUID()) - .withName("logicalSuite") - .withFullyQualifiedName("logicalSuite"); - testCase.setTestSuites(List.of(testSuite)); + .withName("addedLogicalSuite") + .withFullyQualifiedName("addedLogicalSuite"); + TestSuite deletedTestSuite = + new TestSuite() + .withId(UUID.randomUUID()) + .withName("deletedLogicalSuite") + .withFullyQualifiedName("deletedLogicalSuite"); + testCase.setTestSuites(List.of(addedTestSuite)); testCase.setChangeDescription( new ChangeDescription() .withPreviousVersion(testCase.getVersion()) - .withFieldsUpdated( + .withFieldsAdded( List.of( new FieldChange() .withName(Entity.FIELD_TEST_SUITES) - .withNewValue(testCase.getTestSuites())))); + .withNewValue(List.of(addedTestSuite)))) + .withFieldsDeleted( + List.of( + new FieldChange() + .withName(Entity.FIELD_TEST_SUITES) + .withOldValue(List.of(deletedTestSuite))))); doCallRealMethod().when(searchRepository).buildBulkScriptedPartialUpdate(any()); + doCallRealMethod().when(searchRepository).getScriptWithParams(any(), any(), any()); SearchRepository.ScriptedPartialUpdate partialUpdate = searchRepository.buildBulkScriptedPartialUpdate(testCase); assertNotNull(partialUpdate); - assertTrue(partialUpdate.script().contains("ctx._source.testSuites = params.testSuites;")); - assertNotNull(partialUpdate.parameters().get(Entity.FIELD_TEST_SUITES)); + assertFalse(partialUpdate.script().contains("ctx._source.testSuites = params.testSuites")); + assertTrue(partialUpdate.script().contains("testSuiteIdsDeleted.contains(suite.id)")); + assertTrue(partialUpdate.script().contains("ctx._source.testSuites.add(addedSuite)")); + List addedValues = (List) partialUpdate.parameters().get("testSuitesAdded"); + List deletedIds = (List) partialUpdate.parameters().get("testSuiteIdsDeleted"); + assertEquals( + addedTestSuite.getId().toString(), + ((Map) addedValues.getFirst()).get("id").toString()); + assertEquals(List.of(deletedTestSuite.getId().toString()), deletedIds); testCase.setChangeDescription( new ChangeDescription() - .withPreviousVersion(0.9) - .withFieldsUpdated(List.of(new FieldChange().withName(Entity.FIELD_TEST_SUITES)))); + .withPreviousVersion(testCase.getVersion()) + .withFieldsUpdated( + List.of( + new FieldChange() + .withName(Entity.FIELD_TEST_SUITES) + .withNewValue(testCase.getTestSuites())))); assertNull(searchRepository.buildBulkScriptedPartialUpdate(testCase)); } @@ -448,7 +469,7 @@ void testUpdateEntitiesBulkWithNull() { } @Test - void testUpdateEntitiesBulkFallsBackToIndividualUpdatesWhenBulkWriteFails() throws Exception { + void testUpdateEntitiesBulkQueuesRetryWhenBulkWriteOutcomeIsUnknown() throws Exception { SearchRepository realSearchRepository = mock(SearchRepository.class); BulkSink mockBulkSink = mock(BulkSink.class); doCallRealMethod().when(realSearchRepository).updateEntitiesBulk(any()); @@ -457,21 +478,45 @@ void testUpdateEntitiesBulkFallsBackToIndividualUpdatesWhenBulkWriteFails() thro .thenReturn(mockBulkSink); when(realSearchRepository.getSearchClient()).thenReturn(elasticSearchClient); when(realSearchRepository.checkIfIndexingIsSupported(any())).thenReturn(true); - doThrow(new IOException("bulk failure")).when(mockBulkSink).write(any(), any()); - doNothing().when(realSearchRepository).updateEntityIndex(any()); + IOException bulkFailure = new IOException("bulk failure"); + doThrow(bulkFailure).when(mockBulkSink).write(any(), any()); doNothing().when(mockBulkSink).close(); List entities = List.of(new MockEntityWithType("table", "table1")); - realSearchRepository.updateEntitiesBulk(entities); + try (MockedStatic retryQueue = mockStatic(SearchIndexRetryQueue.class)) { + realSearchRepository.updateEntitiesBulk(entities); + + verify(realSearchRepository, never()).updateEntityIndex(any()); + verify(mockBulkSink, never()).flushAndAwait(anyInt()); + verify(mockBulkSink).close(); + retryQueue.verify( + () -> + SearchIndexRetryQueue.enqueue( + entities.getFirst(), + "updateEntitiesBulk: outcome unknown after bulk write; skipped stale fallback", + bulkFailure)); + } + } - verify(realSearchRepository).updateEntityIndex(entities.getFirst()); - verify(mockBulkSink, never()).flushAndAwait(anyInt()); - verify(mockBulkSink).close(); + @Test + void testUpdateEntitiesBulkFallsBackBeforeAnyBulkWriteIsAttempted() { + SearchRepository realSearchRepository = mock(SearchRepository.class); + doCallRealMethod().when(realSearchRepository).updateEntitiesIndex(any()); + when(realSearchRepository.createBulkSink(anyInt(), anyInt(), anyLong())) + .thenThrow(new IllegalStateException("sink creation failed")); + when(realSearchRepository.getSearchClient()).thenReturn(elasticSearchClient); + when(realSearchRepository.checkIfIndexingIsSupported(any())).thenReturn(true); + doNothing().when(realSearchRepository).updateEntityIndex(any()); + + EntityInterface entity = new MockEntityWithType("table", "table1"); + realSearchRepository.updateEntitiesIndex(List.of(entity)); + + verify(realSearchRepository).updateEntityIndex(entity); } @Test - void testUpdateEntitiesBulkClosesTimedOutSinkBeforeIndividualFallback() throws Exception { + void testUpdateEntitiesBulkDoesNotReplayWritesThatCompleteDuringClose() throws Exception { SearchRepository realSearchRepository = mock(SearchRepository.class); BulkSink mockBulkSink = mock(BulkSink.class); doCallRealMethod().when(realSearchRepository).updateEntitiesIndex(any()); @@ -481,18 +526,16 @@ void testUpdateEntitiesBulkClosesTimedOutSinkBeforeIndividualFallback() throws E when(realSearchRepository.checkIfIndexingIsSupported(any())).thenReturn(true); when(mockBulkSink.flushAndAwait(anyInt())).thenReturn(false); when(mockBulkSink.getActiveBulkRequestCount()).thenReturn(0); - doNothing().when(realSearchRepository).updateEntityIndex(any()); EntityInterface entity = new MockEntityWithType("table", "table1"); realSearchRepository.updateEntitiesIndex(List.of(entity)); - InOrder inOrder = inOrder(mockBulkSink, realSearchRepository); - inOrder.verify(mockBulkSink).close(); - inOrder.verify(realSearchRepository).updateEntityIndex(entity); + verify(mockBulkSink).close(); + verify(realSearchRepository, never()).updateEntityIndex(any()); } @Test - void testUpdateEntitiesBulkDoesNotOverlapFallbackWithActiveTimedOutSink() throws Exception { + void testUpdateEntitiesBulkDoesNotReplayPartiallyFailedBulk() throws Exception { SearchRepository realSearchRepository = mock(SearchRepository.class); BulkSink mockBulkSink = mock(BulkSink.class); doCallRealMethod().when(realSearchRepository).updateEntitiesIndex(any()); @@ -500,8 +543,8 @@ void testUpdateEntitiesBulkDoesNotOverlapFallbackWithActiveTimedOutSink() throws .thenReturn(mockBulkSink); when(realSearchRepository.getSearchClient()).thenReturn(elasticSearchClient); when(realSearchRepository.checkIfIndexingIsSupported(any())).thenReturn(true); - when(mockBulkSink.flushAndAwait(anyInt())).thenReturn(false); - when(mockBulkSink.getActiveBulkRequestCount()).thenReturn(1); + when(mockBulkSink.flushAndAwait(anyInt())).thenReturn(true); + when(mockBulkSink.getStats()).thenReturn(new StepStats().withFailedRecords(1)); EntityInterface entity = new MockEntityWithType("table", "table1"); realSearchRepository.updateEntitiesIndex(List.of(entity)); From 6bc78204e49a9da25b477bf669669172069cf93e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 07:34:02 -0700 Subject: [PATCH 03/47] Fix Trino integration test inserts --- ingestion/tests/integration/trino/conftest.py | 29 +++++++++++++++---- 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/ingestion/tests/integration/trino/conftest.py b/ingestion/tests/integration/trino/conftest.py index 14145b970fa9..c8ef456420a3 100644 --- a/ingestion/tests/integration/trino/conftest.py +++ b/ingestion/tests/integration/trino/conftest.py @@ -7,7 +7,7 @@ import pandas as pd import pytest import testcontainers.core.network -from sqlalchemy import create_engine, insert, text +from sqlalchemy import create_engine, text from sqlalchemy.engine import Engine, make_url from sqlalchemy.exc import OperationalError from tenacity import retry, retry_if_exception_type, stop_after_delay, wait_fixed @@ -278,11 +278,28 @@ def wait_for_table_data(engine: Engine, table_name: str, expected_rows: int | No def custom_insert(self, conn, keys: list[str], data_iter): - data = [dict(zip(keys, row)) for row in data_iter] # noqa: B905 - if data: - stmt = insert(self.table).values(data) - conn.execute(stmt) - return len(data) + """Drain Trino DML results before SQLAlchemy can cancel the Hive write.""" + rows = list(data_iter) + if not rows: + return 0 + + identifier_preparer = conn.dialect.identifier_preparer + table_name = identifier_preparer.format_table(self.table) + column_names = ", ".join(identifier_preparer.quote(key) for key in keys) + row_placeholders = f"({', '.join('?' for _ in keys)})" + values_clause = ", ".join(row_placeholders for _ in rows) + statement = f"INSERT INTO {table_name} ({column_names}) VALUES {values_clause}" + parameters = tuple(value for row in rows for value in row) + with conn.connection.driver_connection.cursor() as cursor: + cursor.execute(statement, parameters) + cursor.fetchall() + inserted_rows = cursor.rowcount + + if inserted_rows != len(rows): + raise RuntimeError( + f"Trino inserted [{inserted_rows}] rows into [{self.schema}.{self.name}]; expected [{len(rows)}]" + ) + return inserted_rows @pytest.fixture(scope="module") From 93e43177b6d911fb1219952b0a78e5a3368d617c Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 08:00:59 -0700 Subject: [PATCH 04/47] Preserve bulk search propagation on uncertain writes --- .../service/search/SearchRepository.java | 9 ++-- .../search/SearchRepositoryBehaviorTest.java | 46 +++++++++++++++++++ 2 files changed, 51 insertions(+), 4 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index 6465c37cb931..c1896e866e95 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -1771,7 +1771,7 @@ public void updateEntitiesIndex(List entities) { int batchSize = 100; int maxConcurrentRequests = 5; long maxPayloadSizeBytes = SearchClusterMetrics.DEFAULT_BULK_PAYLOAD_SIZE_BYTES; - List bulkUpdatedEntities = new ArrayList<>(); + List propagationCandidates = new ArrayList<>(); // Process each entity type separately to ensure correct index routing for (Map.Entry> entry : entitiesByType.entrySet()) { @@ -1806,7 +1806,7 @@ public void updateEntitiesIndex(List entities) { throw new IOException( "Bulk entity update did not complete successfully for type " + entityType); } - bulkUpdatedEntities.addAll(typeEntities); + propagationCandidates.addAll(typeEntities); } catch (Exception e) { LOG.error("Error during bulk entity update in search index for type {}", entityType, e); if (bulkSink != null) { @@ -1823,6 +1823,7 @@ public void updateEntitiesIndex(List entities) { } } } else { + propagationCandidates.addAll(typeEntities); for (EntityInterface entity : typeEntities) { SearchIndexRetryQueue.enqueue( entity, @@ -1837,8 +1838,8 @@ public void updateEntitiesIndex(List entities) { } } - // Run fan-out propagation once after all bulk doc updates are flushed. - propagateEntitiesAfterBulkFlush(bulkUpdatedEntities); + // An uncertain bulk outcome still needs its fan-out side effects after the sink is closed. + propagateEntitiesAfterBulkFlush(propagationCandidates); } private void closeBulkSink(BulkSink bulkSink) { diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java index 548e61473dce..9c35b307d68d 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java @@ -14,6 +14,7 @@ import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mockConstruction; import static org.mockito.Mockito.mockStatic; @@ -39,7 +40,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.MockedConstruction; +import org.mockito.MockedStatic; import org.openmetadata.schema.EntityInterface; import org.openmetadata.schema.EntityTimeSeriesInterface; import org.openmetadata.schema.api.entityRelationship.SearchEntityRelationshipRequest; @@ -2924,6 +2927,49 @@ void createBulkSinkUsesSearchTypeSpecificImplementation() { } } + @Test + void bulkTimeoutPropagatesAfterCloseWithoutReplayingTheDocumentWrite() throws Exception { + when(searchClient.getSearchType()) + .thenReturn(ElasticSearchConfiguration.SearchType.ELASTICSEARCH); + EntityInterface service = + mockEntity(Entity.DATABASE_SERVICE, UUID.randomUUID(), "database-service"); + String serviceId = service.getId().toString(); + when(service.getChangeDescription()) + .thenReturn( + changeDescription( + List.of(), + List.of( + new FieldChange() + .withName(Entity.FIELD_DISPLAY_NAME) + .withOldValue("Old Service") + .withNewValue("New Service")), + List.of())); + + try (MockedStatic retryQueue = mockStatic(SearchIndexRetryQueue.class); + MockedConstruction bulkSinks = + mockConstruction( + ElasticSearchBulkSink.class, + (bulkSink, context) -> when(bulkSink.flushAndAwait(60)).thenReturn(false))) { + repository.updateEntitiesIndex(List.of(service)); + + ElasticSearchBulkSink bulkSink = bulkSinks.constructed().getFirst(); + InOrder propagationOrder = inOrder(bulkSink, searchClient); + propagationOrder.verify(bulkSink).close(); + propagationOrder + .verify(searchClient) + .updateChildren(eq(List.of("cluster_database")), any(Pair.class), any(Pair.class)); + verify(searchClient, never()) + .updateEntity(any(String.class), eq(serviceId), any(), any(String.class)); + retryQueue.verify( + () -> + SearchIndexRetryQueue.enqueue( + eq(service), + eq( + "updateEntitiesBulk: outcome unknown after bulk write; skipped stale fallback"), + any(IOException.class))); + } + } + @Test void createReindexHandlerAndDeleteRelationshipHelpersUseExpectedImplementations() { repository.createReindexHandler(); From 4e8fcefd464cfa93d24b9b12780f654853b38086 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 08:13:05 -0700 Subject: [PATCH 05/47] Retry context extraction state updates safely --- .../drive/ContextFileExtractionService.java | 40 ++++++++++++++++--- .../ContextFileExtractionServiceTest.java | 35 ++++++++++++++++ 2 files changed, 70 insertions(+), 5 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java index 21118b144e87..2b49f3df9aef 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java @@ -1,6 +1,8 @@ package org.openmetadata.service.drive; import static org.openmetadata.service.Entity.ADMIN_USER_NAME; +import static org.openmetadata.service.jdbi3.ContextFileContentRepository.CONTEXT_FILE_CONTENT_ENTITY; +import static org.openmetadata.service.jdbi3.ContextFileRepository.CONTEXT_FILE_ENTITY; import java.io.InputStream; import java.util.UUID; @@ -24,10 +26,11 @@ import org.openmetadata.service.attachments.AssetServiceFactory; import org.openmetadata.service.exception.PreconditionFailedException; import org.openmetadata.service.jdbi3.ContextFileRepository; +import org.openmetadata.service.util.RequestEntityCache; @Slf4j public class ContextFileExtractionService { - private static final int MAX_CONDITIONAL_UPDATE_ATTEMPTS = 3; + private static final long CONDITIONAL_UPDATE_RETRY_DELAY_MILLIS = 10; private final ContextFileRepository repository; private final Supplier assetServiceSupplier; private final Executor executor; @@ -105,6 +108,15 @@ public void submit(UUID fileId, UUID contentId) { } void process(UUID fileId, UUID contentId) { + RequestEntityCache.clear(); + try { + processInternal(fileId, contentId); + } finally { + RequestEntityCache.clear(); + } + } + + private void processInternal(UUID fileId, UUID contentId) { ContextFile file = getFile(fileId); if (file == null || !contentId.toString().equals(file.getHeadContentId())) { return; @@ -252,7 +264,7 @@ private ContextFileContent getContent(UUID contentId) { } private boolean updateFile(UUID fileId, Function updater) { - for (int attempt = 0; attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS; attempt++) { + while (true) { ContextFile current = getFile(fileId); if (current == null) { return false; @@ -266,14 +278,17 @@ private boolean updateFile(UUID fileId, Function updat return true; } catch (PreconditionFailedException e) { LOG.debug("Context file {} changed during extraction update", fileId); + RequestEntityCache.invalidate(CONTEXT_FILE_ENTITY, fileId, current.getFullyQualifiedName()); + if (!waitForConditionalUpdateRetry(CONTEXT_FILE_ENTITY, fileId)) { + return false; + } } } - return false; } private boolean updateContent( UUID contentId, Function updater) { - for (int attempt = 0; attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS; attempt++) { + while (true) { ContextFileContent current = getContent(contentId); if (current == null) { return false; @@ -287,8 +302,23 @@ private boolean updateContent( return true; } catch (PreconditionFailedException e) { LOG.debug("Context file content {} changed during extraction update", contentId); + RequestEntityCache.invalidate( + CONTEXT_FILE_CONTENT_ENTITY, contentId, current.getFullyQualifiedName()); + if (!waitForConditionalUpdateRetry(CONTEXT_FILE_CONTENT_ENTITY, contentId)) { + return false; + } } } - return false; + } + + private boolean waitForConditionalUpdateRetry(String entityType, UUID entityId) { + try { + TimeUnit.MILLISECONDS.sleep(CONDITIONAL_UPDATE_RETRY_DELAY_MILLIS); + return true; + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + LOG.warn("Interrupted while retrying {} {} extraction update", entityType, entityId); + return false; + } } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java index 6edc062e9e36..84868d7aa044 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java @@ -212,6 +212,41 @@ void processDoesNotPublishResultWhenDeleteWinsConditionalWriteRace() throws Exce updatedFileCaptor.getAllValues().stream().map(ContextFile::getProcessingStatus).toList()); } + @Test + void processKeepsRetryingTerminalUpdateAfterRepeatedConflicts() throws Exception { + AtomicInteger contentWriteAttempts = new AtomicInteger(); + when(assetService.read(asset)) + .thenReturn( + CompletableFuture.completedFuture( + new ByteArrayInputStream("Quarterly results".getBytes()))); + when(textExtractor.extract(any(InputStream.class), same(file))) + .thenReturn(ContextFileTextExtractor.ExtractionResult.processed("Quarterly results", 3)); + when(contentRepository.updateIfCurrent( + isNull(), same(content), any(ContextFileContent.class), anyString())) + .thenAnswer( + invocation -> { + int attempt = contentWriteAttempts.incrementAndGet(); + if (attempt >= 2 && attempt <= 4) { + throw new PreconditionFailedException("Concurrent content update"); + } + return null; + }); + + service(Runnable::run, () -> assetService).process(fileId, contentId); + + assertEquals(5, contentWriteAttempts.get()); + verify(contentRepository, times(5)) + .updateIfCurrent(isNull(), same(content), updatedContentCaptor.capture(), anyString()); + assertEquals( + ProcessingStatus.Processed, + updatedContentCaptor.getAllValues().getLast().getProcessingStatus()); + verify(repository, times(2)) + .updateIfCurrent(isNull(), same(file), updatedFileCaptor.capture(), anyString()); + assertEquals( + ProcessingStatus.Processed, + updatedFileCaptor.getAllValues().getLast().getProcessingStatus()); + } + @Test void processRethrowsVirtualMachineErrors() throws Exception { when(assetService.read(asset)) From 63c72a72f217462b3d801f5b1904df8bde8e1b9d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 08:31:41 -0700 Subject: [PATCH 06/47] Propagate only confirmed bulk search writes --- .../service/search/SearchRepository.java | 83 ++++++++++++- .../search/SearchRepositoryBehaviorTest.java | 115 +++++++++++++++++- 2 files changed, 191 insertions(+), 7 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index c1896e866e95..6af067f58032 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -83,6 +83,7 @@ import java.util.TreeSet; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -1790,14 +1791,34 @@ public void updateEntitiesIndex(List entities) { BulkSink bulkSink = null; boolean bulkWriteAttempted = false; + boolean bulkWriteReturned = false; + Set failedEntityIds = ConcurrentHashMap.newKeySet(); + Set failedEntityFqns = ConcurrentHashMap.newKeySet(); + AtomicInteger recordedBulkFailures = new AtomicInteger(); try { bulkSink = createBulkSink(batchSize, maxConcurrentRequests, maxPayloadSizeBytes); + bulkSink.setFailureCallback( + (failedEntityType, failedEntityId, failedEntityFqn, errorMessage, stage) -> { + recordedBulkFailures.incrementAndGet(); + if (!nullOrEmpty(failedEntityId)) { + failedEntityIds.add(failedEntityId); + } + if (!nullOrEmpty(failedEntityFqn)) { + failedEntityFqns.add(failedEntityFqn); + } + SearchIndexRetryQueue.enqueue( + failedEntityId, + failedEntityFqn, + failedEntityType, + "updateEntitiesBulk " + stage + ": " + errorMessage); + }); Map contextData = new HashMap<>(); contextData.put(ReindexingUtil.ENTITY_TYPE_KEY, entityType); contextData.put(BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY, true); ReindexingUtil.populateDocBuildContext(contextData, entityType, typeEntities); bulkWriteAttempted = true; bulkSink.write(typeEntities, contextData); + bulkWriteReturned = true; boolean completed = bulkSink.flushAndAwait(60); // Wait up to 60 seconds for completion StepStats sinkStats = bulkSink.getStats(); if (!completed @@ -1809,8 +1830,11 @@ public void updateEntitiesIndex(List entities) { propagationCandidates.addAll(typeEntities); } catch (Exception e) { LOG.error("Error during bulk entity update in search index for type {}", entityType, e); + boolean bulkSinkQuiescent = false; + StepStats finalSinkStats = null; if (bulkSink != null) { - closeBulkSink(bulkSink); + bulkSinkQuiescent = closeBulkSinkAndCheckQuiescent(bulkSink); + finalSinkStats = bulkSink.getStats(); bulkSink = null; } if (!bulkWriteAttempted) { @@ -1823,8 +1847,25 @@ public void updateEntitiesIndex(List entities) { } } } else { - propagationCandidates.addAll(typeEntities); + Set confirmedEntityIds = new HashSet<>(); + if (bulkWriteReturned && bulkSinkQuiescent && finalSinkStats != null) { + addConfirmedPropagationCandidates( + typeEntities, + finalSinkStats, + recordedBulkFailures.get(), + failedEntityIds, + failedEntityFqns, + propagationCandidates, + confirmedEntityIds); + } for (EntityInterface entity : typeEntities) { + String entityId = entity.getId().toString(); + String entityFqn = entity.getFullyQualifiedName(); + if (confirmedEntityIds.contains(entityId) + || failedEntityIds.contains(entityId) + || (entityFqn != null && failedEntityFqns.contains(entityFqn))) { + continue; + } SearchIndexRetryQueue.enqueue( entity, "updateEntitiesBulk: outcome unknown after bulk write; skipped stale fallback", @@ -1833,20 +1874,52 @@ public void updateEntitiesIndex(List entities) { } } finally { if (bulkSink != null) { - closeBulkSink(bulkSink); + closeBulkSinkAndCheckQuiescent(bulkSink); } } } - // An uncertain bulk outcome still needs its fan-out side effects after the sink is closed. propagateEntitiesAfterBulkFlush(propagationCandidates); } - private void closeBulkSink(BulkSink bulkSink) { + private boolean closeBulkSinkAndCheckQuiescent(BulkSink bulkSink) { try { bulkSink.close(); + return bulkSink.getActiveBulkRequestCount() == 0; } catch (Exception e) { LOG.warn("Error closing bulk sink", e); + return false; + } + } + + private void addConfirmedPropagationCandidates( + List entities, + StepStats sinkStats, + int recordedFailures, + Set failedEntityIds, + Set failedEntityFqns, + List propagationCandidates, + Set confirmedEntityIds) { + int failedRecords = Optional.ofNullable(sinkStats.getFailedRecords()).orElse(0); + if (failedRecords == 0) { + propagationCandidates.addAll(entities); + entities.forEach(entity -> confirmedEntityIds.add(entity.getId().toString())); + return; + } + if (recordedFailures < failedRecords) { + LOG.warn( + "Skipping bulk propagation because only {} of {} failed records were identified", + recordedFailures, + failedRecords); + return; + } + for (EntityInterface entity : entities) { + if (!failedEntityIds.contains(entity.getId().toString()) + && (entity.getFullyQualifiedName() == null + || !failedEntityFqns.contains(entity.getFullyQualifiedName()))) { + propagationCandidates.add(entity); + confirmedEntityIds.add(entity.getId().toString()); + } } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java index 9c35b307d68d..d446862a148f 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java @@ -12,6 +12,7 @@ import static org.mockito.ArgumentMatchers.anyBoolean; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.nullable; +import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.inOrder; @@ -35,6 +36,7 @@ import java.util.Optional; import java.util.Set; import java.util.UUID; +import java.util.concurrent.atomic.AtomicReference; import org.apache.commons.lang3.tuple.Pair; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; @@ -66,6 +68,7 @@ import org.openmetadata.schema.service.configuration.elasticsearch.ElasticSearchConfiguration; import org.openmetadata.schema.service.configuration.elasticsearch.NaturalLanguageSearchConfiguration; import org.openmetadata.schema.settings.SettingsType; +import org.openmetadata.schema.system.StepStats; import org.openmetadata.schema.tests.DataQualityReport; import org.openmetadata.schema.tests.TestSuite; import org.openmetadata.schema.type.AssetCertification; @@ -78,7 +81,9 @@ import org.openmetadata.search.IndexMapping; import org.openmetadata.search.IndexMappingLoader; import org.openmetadata.service.Entity; +import org.openmetadata.service.apps.bundles.searchIndex.BulkSink; import org.openmetadata.service.apps.bundles.searchIndex.ElasticSearchBulkSink; +import org.openmetadata.service.apps.bundles.searchIndex.IndexingFailureRecorder; import org.openmetadata.service.apps.bundles.searchIndex.OpenSearchBulkSink; import org.openmetadata.service.events.lifecycle.EntityLifecycleEventDispatcher; import org.openmetadata.service.jdbi3.EntityRepository; @@ -2928,7 +2933,7 @@ void createBulkSinkUsesSearchTypeSpecificImplementation() { } @Test - void bulkTimeoutPropagatesAfterCloseWithoutReplayingTheDocumentWrite() throws Exception { + void bulkTimeoutCompletedDuringClosePropagatesWithoutReplayOrRetry() throws Exception { when(searchClient.getSearchType()) .thenReturn(ElasticSearchConfiguration.SearchType.ELASTICSEARCH); EntityInterface service = @@ -2949,7 +2954,10 @@ void bulkTimeoutPropagatesAfterCloseWithoutReplayingTheDocumentWrite() throws Ex MockedConstruction bulkSinks = mockConstruction( ElasticSearchBulkSink.class, - (bulkSink, context) -> when(bulkSink.flushAndAwait(60)).thenReturn(false))) { + (bulkSink, context) -> { + when(bulkSink.flushAndAwait(60)).thenReturn(false); + when(bulkSink.getStats()).thenReturn(new StepStats().withFailedRecords(0)); + })) { repository.updateEntitiesIndex(List.of(service)); ElasticSearchBulkSink bulkSink = bulkSinks.constructed().getFirst(); @@ -2960,6 +2968,41 @@ void bulkTimeoutPropagatesAfterCloseWithoutReplayingTheDocumentWrite() throws Ex .updateChildren(eq(List.of("cluster_database")), any(Pair.class), any(Pair.class)); verify(searchClient, never()) .updateEntity(any(String.class), eq(serviceId), any(), any(String.class)); + retryQueue.verifyNoInteractions(); + } + } + + @Test + void bulkFailureDoesNotPropagateAnUnconfirmedRoot() throws Exception { + when(searchClient.getSearchType()) + .thenReturn(ElasticSearchConfiguration.SearchType.ELASTICSEARCH); + EntityInterface service = + mockEntity(Entity.DATABASE_SERVICE, UUID.randomUUID(), "database-service"); + when(service.getChangeDescription()) + .thenReturn( + changeDescription( + List.of(), + List.of( + new FieldChange() + .withName(Entity.FIELD_DISPLAY_NAME) + .withOldValue("Old Service") + .withNewValue("New Service")), + List.of())); + + try (MockedStatic retryQueue = mockStatic(SearchIndexRetryQueue.class); + MockedConstruction bulkSinks = + mockConstruction( + ElasticSearchBulkSink.class, + (bulkSink, context) -> { + when(bulkSink.flushAndAwait(60)).thenReturn(true); + when(bulkSink.getStats()).thenReturn(new StepStats().withFailedRecords(1)); + })) { + repository.updateEntitiesIndex(List.of(service)); + + ElasticSearchBulkSink bulkSink = bulkSinks.constructed().getFirst(); + verify(bulkSink).close(); + verify(searchClient, never()) + .updateChildren(any(List.class), any(Pair.class), any(Pair.class)); retryQueue.verify( () -> SearchIndexRetryQueue.enqueue( @@ -2970,6 +3013,74 @@ void bulkTimeoutPropagatesAfterCloseWithoutReplayingTheDocumentWrite() throws Ex } } + @Test + @SuppressWarnings("unchecked") + void partiallyFailedBulkPropagatesOnlyConfirmedRoots() throws Exception { + when(searchClient.getSearchType()) + .thenReturn(ElasticSearchConfiguration.SearchType.ELASTICSEARCH); + EntityInterface failedService = + mockEntity(Entity.DATABASE_SERVICE, UUID.randomUUID(), "failed-service"); + EntityInterface successfulService = + mockEntity(Entity.DATABASE_SERVICE, UUID.randomUUID(), "successful-service"); + ChangeDescription displayNameChange = + changeDescription( + List.of(), + List.of( + new FieldChange() + .withName(Entity.FIELD_DISPLAY_NAME) + .withOldValue("Old Service") + .withNewValue("New Service")), + List.of()); + when(failedService.getChangeDescription()).thenReturn(displayNameChange); + when(successfulService.getChangeDescription()).thenReturn(displayNameChange); + AtomicReference failureCallback = new AtomicReference<>(); + + try (MockedStatic retryQueue = mockStatic(SearchIndexRetryQueue.class); + MockedConstruction bulkSinks = + mockConstruction( + ElasticSearchBulkSink.class, + (bulkSink, context) -> { + doAnswer( + invocation -> { + failureCallback.set(invocation.getArgument(0)); + return null; + }) + .when(bulkSink) + .setFailureCallback(any()); + doAnswer( + invocation -> { + failureCallback + .get() + .onFailure( + Entity.DATABASE_SERVICE, + failedService.getId().toString(), + failedService.getFullyQualifiedName(), + "rejected", + IndexingFailureRecorder.FailureStage.SINK); + return null; + }) + .when(bulkSink) + .write(any(), any()); + when(bulkSink.flushAndAwait(60)).thenReturn(true); + when(bulkSink.getStats()).thenReturn(new StepStats().withFailedRecords(1)); + })) { + repository.updateEntitiesIndex(List.of(failedService, successfulService)); + + ArgumentCaptor> parentMatch = ArgumentCaptor.forClass(Pair.class); + verify(searchClient).updateChildren(any(List.class), parentMatch.capture(), any(Pair.class)); + assertEquals(successfulService.getId().toString(), parentMatch.getValue().getValue()); + verify(bulkSinks.constructed().getFirst()).close(); + retryQueue.verify( + () -> + SearchIndexRetryQueue.enqueue( + failedService.getId().toString(), + failedService.getFullyQualifiedName(), + Entity.DATABASE_SERVICE, + "updateEntitiesBulk SINK: rejected")); + retryQueue.verifyNoMoreInteractions(); + } + } + @Test void createReindexHandlerAndDeleteRelationshipHelpersUseExpectedImplementations() { repository.createReindexHandler(); From ad4bf6997fa0d76db1dd8f2aacfe7a7fb873baf0 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 08:36:57 -0700 Subject: [PATCH 07/47] Yield context extraction retries under contention --- .../drive/ContextFileExtractionService.java | 45 ++++++++++++++++--- .../ContextFileExtractionServiceTest.java | 41 +++++++++++++++++ 2 files changed, 81 insertions(+), 5 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java index 2b49f3df9aef..c94612eab049 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java @@ -30,6 +30,7 @@ @Slf4j public class ContextFileExtractionService { + private static final int MAX_CONDITIONAL_UPDATE_ATTEMPTS = 10; private static final long CONDITIONAL_UPDATE_RETRY_DELAY_MILLIS = 10; private final ContextFileRepository repository; private final Supplier assetServiceSupplier; @@ -103,7 +104,11 @@ public void submit(UUID fileId, UUID contentId) { } catch (RejectedExecutionException e) { LOG.warn( "Skipping text extraction for file {} because the async executor rejected it", fileId, e); - applyFailure(fileId, contentId, "Text extraction queue is full. Please retry later."); + try { + applyFailure(fileId, contentId, "Text extraction queue is full. Please retry later."); + } catch (ConditionalUpdateExhaustedException exhausted) { + LOG.warn("Unable to mark rejected text extraction failed for file {}", fileId); + } } } @@ -111,11 +116,28 @@ void process(UUID fileId, UUID contentId) { RequestEntityCache.clear(); try { processInternal(fileId, contentId); + } catch (ConditionalUpdateExhaustedException e) { + requeueAfterConditionalUpdateContention(fileId, contentId); } finally { RequestEntityCache.clear(); } } + private void requeueAfterConditionalUpdateContention(UUID fileId, UUID contentId) { + try { + executor.execute(() -> process(fileId, contentId)); + LOG.debug("Requeued text extraction for file {} after concurrent updates", fileId); + } catch (RejectedExecutionException e) { + LOG.warn("Unable to requeue text extraction for file {} after concurrent updates", fileId, e); + try { + applyFailure( + fileId, contentId, "Concurrent updates prevented text extraction. Please retry later."); + } catch (ConditionalUpdateExhaustedException exhausted) { + LOG.warn("Unable to mark contended text extraction failed for file {}", fileId); + } + } + } + private void processInternal(UUID fileId, UUID contentId) { ContextFile file = getFile(fileId); if (file == null || !contentId.toString().equals(file.getHeadContentId())) { @@ -180,6 +202,9 @@ private void processInternal(UUID fileId, UUID contentId) { applyResult(fileId, contentId, result); } } catch (Throwable t) { + if (t instanceof ConditionalUpdateExhaustedException exhausted) { + throw exhausted; + } if (t instanceof VirtualMachineError vmError) { throw vmError; } @@ -264,7 +289,7 @@ private ContextFileContent getContent(UUID contentId) { } private boolean updateFile(UUID fileId, Function updater) { - while (true) { + for (int attempt = 1; attempt <= MAX_CONDITIONAL_UPDATE_ATTEMPTS; attempt++) { ContextFile current = getFile(fileId); if (current == null) { return false; @@ -279,16 +304,18 @@ private boolean updateFile(UUID fileId, Function updat } catch (PreconditionFailedException e) { LOG.debug("Context file {} changed during extraction update", fileId); RequestEntityCache.invalidate(CONTEXT_FILE_ENTITY, fileId, current.getFullyQualifiedName()); - if (!waitForConditionalUpdateRetry(CONTEXT_FILE_ENTITY, fileId)) { + if (attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS + && !waitForConditionalUpdateRetry(CONTEXT_FILE_ENTITY, fileId)) { return false; } } } + throw new ConditionalUpdateExhaustedException(CONTEXT_FILE_ENTITY, fileId); } private boolean updateContent( UUID contentId, Function updater) { - while (true) { + for (int attempt = 1; attempt <= MAX_CONDITIONAL_UPDATE_ATTEMPTS; attempt++) { ContextFileContent current = getContent(contentId); if (current == null) { return false; @@ -304,11 +331,13 @@ private boolean updateContent( LOG.debug("Context file content {} changed during extraction update", contentId); RequestEntityCache.invalidate( CONTEXT_FILE_CONTENT_ENTITY, contentId, current.getFullyQualifiedName()); - if (!waitForConditionalUpdateRetry(CONTEXT_FILE_CONTENT_ENTITY, contentId)) { + if (attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS + && !waitForConditionalUpdateRetry(CONTEXT_FILE_CONTENT_ENTITY, contentId)) { return false; } } } + throw new ConditionalUpdateExhaustedException(CONTEXT_FILE_CONTENT_ENTITY, contentId); } private boolean waitForConditionalUpdateRetry(String entityType, UUID entityId) { @@ -321,4 +350,10 @@ private boolean waitForConditionalUpdateRetry(String entityType, UUID entityId) return false; } } + + private static class ConditionalUpdateExhaustedException extends RuntimeException { + private ConditionalUpdateExhaustedException(String entityType, UUID entityId) { + super("Repeated concurrent updates for " + entityType + " " + entityId); + } + } } diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java index 84868d7aa044..6f4ba1d3cb3b 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/drive/ContextFileExtractionServiceTest.java @@ -1,6 +1,7 @@ package org.openmetadata.service.drive; import static org.junit.jupiter.api.Assertions.assertEquals; +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; @@ -26,6 +27,7 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -247,6 +249,45 @@ void processKeepsRetryingTerminalUpdateAfterRepeatedConflicts() throws Exception updatedFileCaptor.getAllValues().getLast().getProcessingStatus()); } + @Test + void processYieldsAndRequeuesAfterSustainedConflicts() throws Exception { + AtomicBoolean conflict = new AtomicBoolean(true); + AtomicInteger fileWriteAttempts = new AtomicInteger(); + AtomicReference requeued = new AtomicReference<>(); + when(repository.updateIfCurrent(isNull(), same(file), any(ContextFile.class), anyString())) + .thenAnswer( + invocation -> { + fileWriteAttempts.incrementAndGet(); + if (conflict.get()) { + throw new PreconditionFailedException("Concurrent file update"); + } + return null; + }); + when(assetService.read(asset)) + .thenReturn( + CompletableFuture.completedFuture( + new ByteArrayInputStream("Quarterly results".getBytes()))); + when(textExtractor.extract(any(InputStream.class), same(file))) + .thenReturn(ContextFileTextExtractor.ExtractionResult.processed("Quarterly results", 3)); + + service(requeued::set, () -> assetService).process(fileId, contentId); + + assertEquals(10, fileWriteAttempts.get()); + Runnable retry = requeued.getAndSet(null); + assertNotNull(retry); + + conflict.set(false); + retry.run(); + + assertNull(requeued.get()); + assertEquals(12, fileWriteAttempts.get()); + verify(contentRepository, times(2)) + .updateIfCurrent(isNull(), same(content), updatedContentCaptor.capture(), anyString()); + assertEquals( + ProcessingStatus.Processed, + updatedContentCaptor.getAllValues().getLast().getProcessingStatus()); + } + @Test void processRethrowsVirtualMachineErrors() throws Exception { when(assetService.read(asset)) From 7f400d2dab9c3403a2b5fd4cb163baf538d43d7e Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 08:44:31 -0700 Subject: [PATCH 08/47] Honor bulk search process failures --- .../org/openmetadata/service/search/SearchRepository.java | 3 ++- .../service/search/SearchRepositoryBehaviorTest.java | 6 +++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index 6af067f58032..b731fccdd7e4 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -1822,6 +1822,7 @@ public void updateEntitiesIndex(List entities) { boolean completed = bulkSink.flushAndAwait(60); // Wait up to 60 seconds for completion StepStats sinkStats = bulkSink.getStats(); if (!completed + || recordedBulkFailures.get() > 0 || (sinkStats != null && Optional.ofNullable(sinkStats.getFailedRecords()).orElse(0) > 0)) { throw new IOException( @@ -1901,7 +1902,7 @@ private void addConfirmedPropagationCandidates( List propagationCandidates, Set confirmedEntityIds) { int failedRecords = Optional.ofNullable(sinkStats.getFailedRecords()).orElse(0); - if (failedRecords == 0) { + if (failedRecords == 0 && recordedFailures == 0) { propagationCandidates.addAll(entities); entities.forEach(entity -> confirmedEntityIds.add(entity.getId().toString())); return; diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java index d446862a148f..1a7ec50b10db 100644 --- a/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java +++ b/openmetadata-service/src/test/java/org/openmetadata/service/search/SearchRepositoryBehaviorTest.java @@ -3056,13 +3056,13 @@ void partiallyFailedBulkPropagatesOnlyConfirmedRoots() throws Exception { failedService.getId().toString(), failedService.getFullyQualifiedName(), "rejected", - IndexingFailureRecorder.FailureStage.SINK); + IndexingFailureRecorder.FailureStage.PROCESS); return null; }) .when(bulkSink) .write(any(), any()); when(bulkSink.flushAndAwait(60)).thenReturn(true); - when(bulkSink.getStats()).thenReturn(new StepStats().withFailedRecords(1)); + when(bulkSink.getStats()).thenReturn(new StepStats().withFailedRecords(0)); })) { repository.updateEntitiesIndex(List.of(failedService, successfulService)); @@ -3076,7 +3076,7 @@ void partiallyFailedBulkPropagatesOnlyConfirmedRoots() throws Exception { failedService.getId().toString(), failedService.getFullyQualifiedName(), Entity.DATABASE_SERVICE, - "updateEntitiesBulk SINK: rejected")); + "updateEntitiesBulk PROCESS: rejected")); retryQueue.verifyNoMoreInteractions(); } } From 751a687f54310904e9b3d42248992225a9720395 Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 09:04:31 -0700 Subject: [PATCH 09/47] Order logical suite publication across nodes --- .../service/jdbi3/TestCaseRepository.java | 49 ++++++- .../service/lock/DatabaseAdvisoryLock.java | 107 +++++++++++++++ .../lock/DatabaseAdvisoryLockTest.java | 122 ++++++++++++++++++ 3 files changed, 274 insertions(+), 4 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/lock/DatabaseAdvisoryLockTest.java diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index d3ed753d520a..78755428e0ac 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -31,9 +31,11 @@ import com.google.common.collect.Lists; import com.google.common.util.concurrent.Striped; +import jakarta.ws.rs.ServiceUnavailableException; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import java.io.IOException; +import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -47,6 +49,7 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.Lock; import java.util.function.Function; +import java.util.function.Supplier; import java.util.stream.Collectors; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; @@ -101,6 +104,7 @@ import org.openmetadata.service.cache.CacheBundle; import org.openmetadata.service.events.lifecycle.EntityLifecycleEventDispatcher; import org.openmetadata.service.exception.EntityNotFoundException; +import org.openmetadata.service.lock.DatabaseAdvisoryLock; import org.openmetadata.service.rdf.RdfUpdater; import org.openmetadata.service.resources.dqtests.TestCaseResource; import org.openmetadata.service.resources.dqtests.TestSuiteMapper; @@ -125,6 +129,8 @@ public class TestCaseRepository extends EntityRepository { private static final String PATCH_FIELDS = "owners,entityLink,testSuite,testSuites,testDefinition,computePassedFailedRowCount,useDynamicAssertion,dimensionColumns,topDimensions"; public static final String FAILED_ROWS_SAMPLE_EXTENSION = "testCase.failedRowsSample"; + private static final String LOGICAL_SUITE_LOCK_PREFIX = "logical-suite:"; + private static final Duration LOGICAL_SUITE_LOCK_TIMEOUT = Duration.ofSeconds(30); private static final Striped LOGICAL_SUITE_PUBLICATION_LOCKS = Striped.lock(4096); private final ExecutorService asyncExecutor = Executors.newFixedThreadPool( @@ -1102,6 +1108,12 @@ public void isTestSuiteBasic(String testSuiteFqn) { public RestUtil.PutResponse addTestCasesToLogicalTestSuite( TestSuite testSuite, List testCaseIds) { + return withLogicalSuitePublicationLock( + testSuite.getId(), () -> addTestCasesToLogicalTestSuiteLocked(testSuite, testCaseIds)); + } + + private RestUtil.PutResponse addTestCasesToLogicalTestSuiteLocked( + TestSuite testSuite, List testCaseIds) { AtomicReference> addedTestCases = new AtomicReference<>(List.of()); flushInOneTransaction( () -> @@ -1130,6 +1142,13 @@ private List addTestCasesToLogicalTestSuiteFlush( public RestUtil.PutResponse addAllTestCasesToLogicalTestSuite( TestSuite testSuite, List excludedTestCaseIds) { + return withLogicalSuitePublicationLock( + testSuite.getId(), + () -> addAllTestCasesToLogicalTestSuiteLocked(testSuite, excludedTestCaseIds)); + } + + private RestUtil.PutResponse addAllTestCasesToLogicalTestSuiteLocked( + TestSuite testSuite, List excludedTestCaseIds) { AtomicReference> addedTestCases = new AtomicReference<>(List.of()); flushInOneTransaction( () -> @@ -1178,6 +1197,12 @@ private List addAllTestCasesToLogicalTestSuiteFlush( public RestUtil.DeleteResponse deleteTestCaseFromLogicalTestSuite( UUID testSuiteId, UUID testCaseId) { + return withLogicalSuitePublicationLock( + testSuiteId, () -> deleteTestCaseFromLogicalTestSuiteLocked(testSuiteId, testCaseId)); + } + + private RestUtil.DeleteResponse deleteTestCaseFromLogicalTestSuiteLocked( + UUID testSuiteId, UUID testCaseId) { TestCase testCase = Entity.getEntity(Entity.TEST_CASE, testCaseId, null, null); flushInOneTransaction( () -> @@ -1193,6 +1218,21 @@ public RestUtil.DeleteResponse deleteTestCaseFromLogicalTestSuite( return new RestUtil.DeleteResponse<>(testCase, ENTITY_DELETED); } + private R withLogicalSuitePublicationLock(UUID testSuiteId, Supplier operation) { + try { + return DatabaseAdvisoryLock.withLock( + Entity.getJdbi(), + LOGICAL_SUITE_LOCK_PREFIX + testSuiteId, + LOGICAL_SUITE_LOCK_TIMEOUT, + operation); + } catch (DatabaseAdvisoryLock.LockUnavailableException exception) { + ServiceUnavailableException unavailable = + new ServiceUnavailableException(exception.getMessage()); + unavailable.initCause(exception); + throw unavailable; + } + } + private List getLogicalSuiteUpdatedTestCase( List testCaseReferences, UUID testSuiteId) { List testCases = Entity.getEntities(testCaseReferences, "*", Include.ALL); @@ -1220,10 +1260,11 @@ private List getLogicalSuiteUpdatedTestCase( /** * Publishes logical-suite relationship changes from committed database state. Relationship rows * do not modify the stored {@link TestCase} JSON, so publication invalidates the hydrated read - * bundle and reloads while holding deterministic per-test-case locks. Concurrent add/delete - * requests therefore publish in lock order, and a late request observes the current relationship - * state instead of replaying its pre-commit snapshot. The resulting change description contains - * an idempotent add/remove delta for search rather than a replacement {@code testSuites} array. + * bundle and reloads while holding deterministic per-test-case locks. Logical-suite mutation + * entry points also hold a database session advisory lock from before the relationship transaction + * through this publication, so requests on different service nodes publish in commit order. The + * resulting change description contains an idempotent add/remove delta for search rather than a + * replacement {@code testSuites} array. */ private List postLogicalSuiteRelationshipUpdate( List testCaseReferences, UUID testSuiteId) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java b/openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java new file mode 100644 index 000000000000..ca724d407062 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java @@ -0,0 +1,107 @@ +/* + * 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. + */ + +package org.openmetadata.service.lock; + +import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; +import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; + +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.locks.LockSupport; +import java.util.function.Supplier; +import lombok.extern.slf4j.Slf4j; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.jdbi.v3.sqlobject.customizer.Bind; +import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlQuery; + +@Slf4j +public final class DatabaseAdvisoryLock { + private static final int MYSQL_LOCK_NAME_LIMIT = 64; + private static final long RETRY_INTERVAL_NANOS = Duration.ofMillis(25).toNanos(); + + private DatabaseAdvisoryLock() {} + + public static T withLock(Jdbi jdbi, String lockKey, Duration timeout, Supplier operation) { + Objects.requireNonNull(jdbi, "jdbi"); + Objects.requireNonNull(lockKey, "lockKey"); + Objects.requireNonNull(timeout, "timeout"); + Objects.requireNonNull(operation, "operation"); + if (lockKey.length() > MYSQL_LOCK_NAME_LIMIT) { + throw new IllegalArgumentException("Database advisory lock key exceeds 64 characters"); + } + if (timeout.isNegative()) { + throw new IllegalArgumentException("Database advisory lock timeout cannot be negative"); + } + + try (Handle handle = jdbi.open()) { + AdvisoryLockDAO lockDAO = handle.attach(AdvisoryLockDAO.class); + acquire(lockDAO, lockKey, timeout); + try { + return operation.get(); + } finally { + release(lockDAO, lockKey); + } + } + } + + private static void acquire(AdvisoryLockDAO lockDAO, String lockKey, Duration timeout) { + long deadline = System.nanoTime() + timeout.toNanos(); + do { + if (lockDAO.tryAcquire(lockKey)) { + return; + } + if (Thread.currentThread().isInterrupted()) { + throw new LockUnavailableException( + "Interrupted while acquiring database advisory lock " + lockKey); + } + long remainingNanos = deadline - System.nanoTime(); + if (remainingNanos > 0) { + LockSupport.parkNanos(Math.min(RETRY_INTERVAL_NANOS, remainingNanos)); + } + } while (System.nanoTime() < deadline); + + throw new LockUnavailableException("Timed out acquiring database advisory lock " + lockKey); + } + + private static void release(AdvisoryLockDAO lockDAO, String lockKey) { + try { + if (!lockDAO.release(lockKey)) { + LOG.warn("Database advisory lock {} was no longer owned during release", lockKey); + } + } catch (RuntimeException exception) { + LOG.warn("Failed to release database advisory lock {}", lockKey, exception); + } + } + + interface AdvisoryLockDAO { + @ConnectionAwareSqlQuery(value = "SELECT GET_LOCK(:lockKey, 0)", connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = "SELECT pg_try_advisory_lock(hashtextextended(:lockKey, 0))", + connectionType = POSTGRES) + boolean tryAcquire(@Bind("lockKey") String lockKey); + + @ConnectionAwareSqlQuery(value = "SELECT RELEASE_LOCK(:lockKey)", connectionType = MYSQL) + @ConnectionAwareSqlQuery( + value = "SELECT pg_advisory_unlock(hashtextextended(:lockKey, 0))", + connectionType = POSTGRES) + boolean release(@Bind("lockKey") String lockKey); + } + + public static final class LockUnavailableException extends RuntimeException { + public LockUnavailableException(String message) { + super(message); + } + } +} diff --git a/openmetadata-service/src/test/java/org/openmetadata/service/lock/DatabaseAdvisoryLockTest.java b/openmetadata-service/src/test/java/org/openmetadata/service/lock/DatabaseAdvisoryLockTest.java new file mode 100644 index 000000000000..255b72378621 --- /dev/null +++ b/openmetadata-service/src/test/java/org/openmetadata/service/lock/DatabaseAdvisoryLockTest.java @@ -0,0 +1,122 @@ +/* + * 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. + */ + +package org.openmetadata.service.lock; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.time.Duration; +import java.util.concurrent.atomic.AtomicBoolean; +import org.jdbi.v3.core.Handle; +import org.jdbi.v3.core.Jdbi; +import org.junit.jupiter.api.Test; + +class DatabaseAdvisoryLockTest { + private static final String LOCK_KEY = "logical-suite:00000000-0000-0000-0000-000000000001"; + + @Test + void executesWhileHoldingAndThenReleasesTheSessionLock() { + Jdbi jdbi = mock(Jdbi.class); + Handle handle = mock(Handle.class); + DatabaseAdvisoryLock.AdvisoryLockDAO lockDAO = mock(DatabaseAdvisoryLock.AdvisoryLockDAO.class); + AtomicBoolean held = new AtomicBoolean(); + when(jdbi.open()).thenReturn(handle); + when(handle.attach(DatabaseAdvisoryLock.AdvisoryLockDAO.class)).thenReturn(lockDAO); + when(lockDAO.tryAcquire(LOCK_KEY)) + .thenAnswer( + ignored -> { + held.set(true); + return true; + }); + when(lockDAO.release(LOCK_KEY)) + .thenAnswer( + ignored -> { + assertTrue(held.get()); + held.set(false); + return true; + }); + + String result = + DatabaseAdvisoryLock.withLock( + jdbi, + LOCK_KEY, + Duration.ZERO, + () -> { + assertTrue(held.get()); + return "published"; + }); + + assertEquals("published", result); + assertFalse(held.get()); + verify(handle).close(); + } + + @Test + void releasesTheSessionLockWhenTheOperationFails() { + Jdbi jdbi = mock(Jdbi.class); + Handle handle = mock(Handle.class); + DatabaseAdvisoryLock.AdvisoryLockDAO lockDAO = mock(DatabaseAdvisoryLock.AdvisoryLockDAO.class); + when(jdbi.open()).thenReturn(handle); + when(handle.attach(DatabaseAdvisoryLock.AdvisoryLockDAO.class)).thenReturn(lockDAO); + when(lockDAO.tryAcquire(LOCK_KEY)).thenReturn(true); + when(lockDAO.release(LOCK_KEY)).thenReturn(true); + + assertThrows( + IllegalArgumentException.class, + () -> + DatabaseAdvisoryLock.withLock( + jdbi, + LOCK_KEY, + Duration.ZERO, + () -> { + throw new IllegalArgumentException("publication failed"); + })); + + verify(lockDAO).release(LOCK_KEY); + verify(handle).close(); + } + + @Test + void timesOutWithoutRunningTheOperation() { + Jdbi jdbi = mock(Jdbi.class); + Handle handle = mock(Handle.class); + DatabaseAdvisoryLock.AdvisoryLockDAO lockDAO = mock(DatabaseAdvisoryLock.AdvisoryLockDAO.class); + AtomicBoolean operationRan = new AtomicBoolean(); + when(jdbi.open()).thenReturn(handle); + when(handle.attach(DatabaseAdvisoryLock.AdvisoryLockDAO.class)).thenReturn(lockDAO); + when(lockDAO.tryAcquire(LOCK_KEY)).thenReturn(false); + + assertThrows( + DatabaseAdvisoryLock.LockUnavailableException.class, + () -> + DatabaseAdvisoryLock.withLock( + jdbi, + LOCK_KEY, + Duration.ZERO, + () -> { + operationRan.set(true); + return null; + })); + + assertFalse(operationRan.get()); + verify(lockDAO, never()).release(LOCK_KEY); + verify(handle).close(); + } +} From ec0acb8610ba259a176ef395028fece3373efe6d Mon Sep 17 00:00:00 2001 From: Sriharsha Chintalapani Date: Thu, 16 Jul 2026 12:09:45 -0700 Subject: [PATCH 10/47] Fence logical suite search publications --- .../it/tests/TestCaseResourceIT.java | 173 +++++++++- .../apps/bundles/searchIndex/BulkSink.java | 2 + .../searchIndex/ElasticSearchBulkSink.java | 67 +++- .../searchIndex/OpenSearchBulkSink.java | 73 ++++- .../EntityLifecycleEventDispatcher.java | 27 +- .../EntityLifecycleEventHandler.java | 16 + .../events/lifecycle/EntityUpdateContext.java | 23 ++ .../handlers/SearchIndexHandler.java | 31 +- .../service/jdbi3/CollectionDAO.java | 23 ++ .../service/jdbi3/TestCaseRepository.java | 302 ++++++++++-------- .../service/jdbi3/TestSuiteRepository.java | 30 ++ .../service/lock/DatabaseAdvisoryLock.java | 107 ------- .../search/SearchIndexRetryWorker.java | 108 ++++++- .../service/search/SearchRepository.java | 283 ++++++++++------ .../search/indexes/DocBuildContext.java | 26 +- .../service/search/indexes/TestCaseIndex.java | 13 + .../search/indexes/TestSuiteIndex.java | 15 + .../workflows/searchIndex/ReindexingUtil.java | 53 ++- .../ElasticSearchBulkSinkBehaviorTest.java | 82 ++++- .../OpenSearchBulkSinkBehaviorTest.java | 81 ++++- .../EntityLifecycleEventDispatcherTest.java | 24 ++ .../handlers/SearchIndexHandlerTest.java | 37 ++- .../service/jdbi3/TestCaseRepositoryTest.java | 30 ++ .../jdbi3/TestSuiteRepositoryTest.java | 42 +++ .../lock/DatabaseAdvisoryLockTest.java | 122 ------- .../search/SearchIndexRetryWorkerTest.java | 103 ++++++ .../search/SearchRepositoryBehaviorTest.java | 72 +++++ .../service/search/SearchRepositoryTest.java | 148 +++++++-- .../search/indexes/DocBuildContextTest.java | 10 + .../search/indexes/TestCaseIndexTest.java | 13 + .../search/indexes/TestSuiteIndexTest.java | 26 ++ .../ReindexingUtilDocBuildContextTest.java | 91 ++++++ .../en/test_case_index_mapping.json | 3 + .../en/test_suite_index_mapping.json | 3 + .../jp/test_case_index_mapping.json | 3 + .../jp/test_suite_index_mapping.json | 3 + .../ru/test_case_index_mapping.json | 3 + .../ru/test_suite_index_mapping.json | 3 + .../zh/test_case_index_mapping.json | 3 + .../zh/test_suite_index_mapping.json | 3 + 40 files changed, 1730 insertions(+), 547 deletions(-) create mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityUpdateContext.java delete mode 100644 openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java create mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/TestSuiteRepositoryTest.java delete mode 100644 openmetadata-service/src/test/java/org/openmetadata/service/lock/DatabaseAdvisoryLockTest.java diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java index 2137209f7494..bea034c04f4b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TestCaseResourceIT.java @@ -21,6 +21,10 @@ import java.util.List; import java.util.Map; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import org.awaitility.Awaitility; @@ -50,6 +54,7 @@ import org.openmetadata.schema.type.Column; import org.openmetadata.schema.type.ColumnDataType; import org.openmetadata.schema.type.EntityHistory; +import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.TagLabel; import org.openmetadata.schema.type.csv.CsvImportResult; import org.openmetadata.schema.utils.JsonUtils; @@ -1085,6 +1090,136 @@ void test_bulkAddTestCasesToLogicalTestSuiteByIds(TestNamespace ns) throws Excep assertTrue(testIdsInSuite.contains(testCase2.getId())); } + @Test + void test_concurrentLogicalSuiteAddsPreserveEverySearchMembership(TestNamespace ns) + throws Exception { + OpenMetadataClient client = SdkClients.adminClient(); + Table table = createTable(ns); + TestCase testCase = + TestCaseBuilder.create(client) + .name(ns.prefix("concurrent_logical_suites")) + .forTable(table) + .testDefinition("tableRowCountToEqual") + .parameter("value", "100") + .create(); + List logicalSuites = + java.util.stream.IntStream.range(0, 6) + .mapToObj( + index -> + client + .testSuites() + .create( + new CreateTestSuite() + .withName(ns.prefix("concurrent_logical_suite_" + index)))) + .toList(); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + List> updates = + logicalSuites.stream() + .map( + suite -> + CompletableFuture.runAsync( + () -> { + try { + start.await(); + addTestCasesToLogicalTestSuite( + client, suite.getId(), List.of(testCase.getId())); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + }, + executor)) + .toList(); + + start.countDown(); + CompletableFuture.allOf(updates.toArray(CompletableFuture[]::new)).join(); + } + + TestCase fetched = client.testCases().get(testCase.getId().toString(), "testSuites"); + List persistedSuiteIds = fetched.getTestSuites().stream().map(TestSuite::getId).toList(); + assertTrue( + persistedSuiteIds.containsAll(logicalSuites.stream().map(TestSuite::getId).toList())); + + try (Rest5Client searchClient = TestSuiteBootstrap.createSearchClient()) { + Awaitility.await("every concurrent logical suite membership is indexed") + .atMost(SEARCH_CONVERGENCE_TIMEOUT) + .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() + .untilAsserted( + () -> { + JsonNode source = queryTestCaseSearchSource(searchClient, testCase.getId()); + logicalSuites.forEach( + suite -> assertSearchDocContainsTestSuite(source, suite.getId())); + assertTrue(source.path("testSuitesRevision").asLong() >= logicalSuites.size()); + }); + } + } + + @Test + void test_concurrentLogicalSuiteTestAddsPreserveEverySearchTest(TestNamespace ns) + throws Exception { + OpenMetadataClient client = SdkClients.adminClient(); + Table table = createTable(ns); + List testCases = + java.util.stream.IntStream.range(0, 6) + .mapToObj( + index -> + TestCaseBuilder.create(client) + .name(ns.prefix("concurrent_logical_suite_test_" + index)) + .forTable(table) + .testDefinition("tableRowCountToEqual") + .parameter("value", "100") + .create()) + .toList(); + TestSuite logicalSuite = + client + .testSuites() + .create(new CreateTestSuite().withName(ns.prefix("concurrent_logical_suite_tests"))); + CountDownLatch start = new CountDownLatch(1); + try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) { + List> updates = + testCases.stream() + .map( + testCase -> + CompletableFuture.runAsync( + () -> { + try { + start.await(); + addTestCasesToLogicalTestSuite( + client, logicalSuite.getId(), List.of(testCase.getId())); + } catch (InterruptedException exception) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(exception); + } + }, + executor)) + .toList(); + + start.countDown(); + CompletableFuture.allOf(updates.toArray(CompletableFuture[]::new)).join(); + } + + TestSuite fetched = client.testSuites().get(logicalSuite.getId().toString(), "tests"); + List persistedTestCaseIds = + fetched.getTests().stream().map(EntityReference::getId).toList(); + assertTrue(persistedTestCaseIds.containsAll(testCases.stream().map(TestCase::getId).toList())); + + try (Rest5Client searchClient = TestSuiteBootstrap.createSearchClient()) { + Awaitility.await("every concurrent logical suite test is indexed") + .atMost(SEARCH_CONVERGENCE_TIMEOUT) + .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() + .untilAsserted( + () -> { + JsonNode source = queryTestSuiteSearchSource(searchClient, logicalSuite.getId()); + testCases.forEach( + testCase -> assertSearchDocContainsTestCase(source, testCase.getId())); + assertTrue(source.path("testsRevision").asLong() >= testCases.size()); + }); + } + } + @Test void test_bulkAddTestCasesToLogicalTestSuiteByIds_nonExistentTestCase(TestNamespace ns) { OpenMetadataClient client = SdkClients.adminClient(); @@ -4702,7 +4837,17 @@ private void addTestCasesToLogicalTestSuite( private JsonNode queryTestCaseSearchSource(Rest5Client searchClient, UUID testCaseId) throws Exception { - refreshTestCaseSearchIndex(searchClient); + return querySearchSource(searchClient, getTestCaseSearchIndexName(), testCaseId); + } + + private JsonNode queryTestSuiteSearchSource(Rest5Client searchClient, UUID testSuiteId) + throws Exception { + return querySearchSource(searchClient, getTestSuiteSearchIndexName(), testSuiteId); + } + + private JsonNode querySearchSource(Rest5Client searchClient, String indexName, UUID entityId) + throws Exception { + refreshSearchIndex(searchClient, indexName); String query = """ @@ -4717,9 +4862,9 @@ private JsonNode queryTestCaseSearchSource(Rest5Client searchClient, UUID testCa } } """ - .formatted(testCaseId); + .formatted(entityId); - Request request = new Request("POST", "/" + getTestCaseSearchIndexName() + "/_search"); + Request request = new Request("POST", "/" + indexName + "/_search"); request.setJsonEntity(query); Response response = searchClient.performRequest(request); @@ -4744,12 +4889,30 @@ private void assertSearchDocContainsTestSuite(JsonNode source, UUID testSuiteId) assertTrue(found, "search document testSuites should contain " + testSuiteId); } + private void assertSearchDocContainsTestCase(JsonNode source, UUID testCaseId) { + assertNotNull(source); + JsonNode tests = source.path("tests"); + assertTrue(tests.isArray(), "tests should be indexed in the search document"); + boolean found = false; + for (JsonNode test : tests) { + if (testCaseId.toString().equals(test.path("id").asText())) { + found = true; + break; + } + } + assertTrue(found, "search document tests should contain " + testCaseId); + } + private String getTestCaseSearchIndexName() { return "openmetadata_test_case_search_index"; } - private void refreshTestCaseSearchIndex(Rest5Client searchClient) throws Exception { - Request request = new Request("POST", "/" + getTestCaseSearchIndexName() + "/_refresh"); + private String getTestSuiteSearchIndexName() { + return "openmetadata_test_suite_search_index"; + } + + private void refreshSearchIndex(Rest5Client searchClient, String indexName) throws Exception { + Request request = new Request("POST", "/" + indexName + "/_refresh"); searchClient.performRequest(request); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java index d795bcabfe02..67e1535c090f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/BulkSink.java @@ -136,6 +136,8 @@ default StepStats getColumnStats() { String SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY = "scriptedPartialUpdates"; + String RELATIONSHIP_REVISIONS_CONTEXT_KEY = "relationshipRevisions"; + /** * Key for passing a {@code Map} through context data. Producers (the * reindex worker / retry worker / bulk update path) prepare per-entity doc-build context — diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java index 8a728cf08809..da6a507f84f2 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/ElasticSearchBulkSink.java @@ -1,11 +1,13 @@ package org.openmetadata.service.apps.bundles.searchIndex; +import static org.openmetadata.service.apps.bundles.searchIndex.BulkSink.RELATIONSHIP_REVISIONS_CONTEXT_KEY; import static org.openmetadata.service.apps.bundles.searchIndex.BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.ENTITY_TYPE_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.RECREATE_CONTEXT; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.TARGET_INDEX_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.isStaleReferenceMessage; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import es.co.elastic.clients.elasticsearch.ElasticsearchAsyncClient; import es.co.elastic.clients.elasticsearch._types.Refresh; @@ -329,6 +331,10 @@ public void write(List entities, Map contextData) throws Exce Map docBuildContexts = (Map) contextData.getOrDefault(DOC_BUILD_CONTEXT_KEY, Collections.emptyMap()); + Map relationshipRevisions = + (Map) + contextData.getOrDefault( + RELATIONSHIP_REVISIONS_CONTEXT_KEY, Collections.emptyMap()); // Add entities to search index in parallel List> futures = @@ -342,7 +348,8 @@ public void write(List entities, Map contextData) throws Exce indexName, tracker, docBuildContexts, - scriptedPartialUpdates), + scriptedPartialUpdates, + relationshipRevisions), DOC_BUILD_EXECUTOR)) .toList(); CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); @@ -394,11 +401,30 @@ private void addEntity( StageStatsTracker tracker, Map docBuildContexts, boolean scriptedPartialUpdates) { + addEntity( + entity, + indexName, + tracker, + docBuildContexts, + scriptedPartialUpdates, + Collections.emptyMap()); + } + + private void addEntity( + EntityInterface entity, + String indexName, + StageStatsTracker tracker, + Map docBuildContexts, + boolean scriptedPartialUpdates, + Map relationshipRevisions) { try { String entityType = Entity.getEntityTypeFromObject(entity); String docId = entity.getId().toString(); DocBuildContext ctx = docBuildContexts.getOrDefault(entity.getId(), DocBuildContext.empty()); - Object searchIndexDoc = Entity.buildSearchIndex(entityType, entity).buildSearchIndexDoc(ctx); + Map searchIndexDoc = + new HashMap<>(Entity.buildSearchIndex(entityType, entity).buildSearchIndexDoc(ctx)); + Long relationshipRevision = relationshipRevisions.get(entity.getId()); + SearchRepository.applyRelationshipRevision(entity, searchIndexDoc, relationshipRevision); String json = JsonUtils.pojoToJson(searchIndexDoc); long rawDocSize = (long) json.getBytes(StandardCharsets.UTF_8).length; long estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; @@ -420,10 +446,13 @@ private void addEntity( if (scriptedPartialUpdates) { SearchRepository.ScriptedPartialUpdate partialUpdate = - searchRepository.buildBulkScriptedPartialUpdate(entity); - if (partialUpdate != null - && addScriptedPartialUpdate( - indexName, docId, entityType, partialUpdate, json, tracker)) { + searchRepository.buildBulkScriptedPartialUpdate(entity, relationshipRevision); + if (relationshipRevision != null && partialUpdate == null) { + throw new IllegalStateException( + "Missing fenced relationship update for " + entityType + " " + docId); + } + if (partialUpdate != null) { + addScriptedPartialUpdate(indexName, docId, entityType, partialUpdate, json, tracker); processSuccess.incrementAndGet(); if (tracker != null) { tracker.recordProcess(StatsResult.SUCCESS); @@ -432,6 +461,19 @@ && addScriptedPartialUpdate( } } + SearchRepository.ScriptedPartialUpdate relationshipDocumentUpdate = + searchRepository.buildRelationshipDocumentUpdate( + entity, JsonUtils.readValue(json, new TypeReference>() {})); + if (relationshipDocumentUpdate != null) { + addScriptedPartialUpdate( + indexName, docId, entityType, relationshipDocumentUpdate, json, tracker); + processSuccess.incrementAndGet(); + if (tracker != null) { + tracker.recordProcess(StatsResult.SUCCESS); + } + return; + } + if (estimatedSize > maxPayloadSizeBytes) { LOG.warn( "Document {} of type {} is too large for bulk ({} bytes), sending directly", @@ -494,24 +536,21 @@ && addScriptedPartialUpdate( } } - private boolean addScriptedPartialUpdate( + private void addScriptedPartialUpdate( String indexName, String docId, String entityType, SearchRepository.ScriptedPartialUpdate partialUpdate, String upsertDocument, StageStatsTracker tracker) { + String effectiveUpsertDocument = partialUpdate.scriptedUpsert() ? "{}" : upsertDocument; long estimatedSize = - (long) upsertDocument.getBytes(StandardCharsets.UTF_8).length + (long) effectiveUpsertDocument.getBytes(StandardCharsets.UTF_8).length + JsonUtils.pojoToJson(partialUpdate.parameters()) .getBytes(StandardCharsets.UTF_8) .length + partialUpdate.script().getBytes(StandardCharsets.UTF_8).length + BULK_OPERATION_METADATA_OVERHEAD; - if (estimatedSize > maxPayloadSizeBytes) { - return false; - } - Map params = new HashMap<>(); partialUpdate .parameters() @@ -533,7 +572,8 @@ private boolean addScriptedPartialUpdate( .action( action -> action - .upsert(EsUtils.toJsonData(upsertDocument)) + .scriptedUpsert(partialUpdate.scriptedUpsert()) + .upsert(EsUtils.toJsonData(effectiveUpsertDocument)) .script( script -> script @@ -547,7 +587,6 @@ private boolean addScriptedPartialUpdate( tracker.incrementPendingSink(); } bulkProcessor.add(operation, docId, entityType, tracker, estimatedSize); - return true; } private void recordStaleReferenceWarning( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java index 6c59427ab83f..30d0b5d30902 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/searchIndex/OpenSearchBulkSink.java @@ -1,11 +1,13 @@ package org.openmetadata.service.apps.bundles.searchIndex; +import static org.openmetadata.service.apps.bundles.searchIndex.BulkSink.RELATIONSHIP_REVISIONS_CONTEXT_KEY; import static org.openmetadata.service.apps.bundles.searchIndex.BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.ENTITY_TYPE_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.RECREATE_CONTEXT; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.TARGET_INDEX_KEY; import static org.openmetadata.service.workflows.searchIndex.ReindexingUtil.isStaleReferenceMessage; +import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; @@ -377,6 +379,10 @@ public void write(List entities, Map contextData) throws Exce Map docBuildContexts = (Map) contextData.getOrDefault(DOC_BUILD_CONTEXT_KEY, Collections.emptyMap()); + Map relationshipRevisions = + (Map) + contextData.getOrDefault( + RELATIONSHIP_REVISIONS_CONTEXT_KEY, Collections.emptyMap()); // Add entities to search index in parallel Map finalEmbeddingsById = existingEmbeddingsById; @@ -394,7 +400,8 @@ public void write(List entities, Map contextData) throws Exce embeddingsEnabled, finalEmbeddingsById, docBuildContexts, - scriptedPartialUpdates), + scriptedPartialUpdates, + relationshipRevisions), DOC_BUILD_EXECUTOR)) .toList(); CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); @@ -449,11 +456,36 @@ private void addEntity( Map existingEmbeddingsById, Map docBuildContexts, boolean scriptedPartialUpdates) { + addEntity( + entity, + indexName, + reindexContext, + tracker, + embeddingsEnabled, + existingEmbeddingsById, + docBuildContexts, + scriptedPartialUpdates, + Collections.emptyMap()); + } + + private void addEntity( + EntityInterface entity, + String indexName, + ReindexContext reindexContext, + StageStatsTracker tracker, + boolean embeddingsEnabled, + Map existingEmbeddingsById, + Map docBuildContexts, + boolean scriptedPartialUpdates, + Map relationshipRevisions) { try { String entityType = Entity.getEntityTypeFromObject(entity); String docId = entity.getId().toString(); DocBuildContext ctx = docBuildContexts.getOrDefault(entity.getId(), DocBuildContext.empty()); - Object searchIndexDoc = Entity.buildSearchIndex(entityType, entity).buildSearchIndexDoc(ctx); + Map searchIndexDoc = + new HashMap<>(Entity.buildSearchIndex(entityType, entity).buildSearchIndexDoc(ctx)); + Long relationshipRevision = relationshipRevisions.get(entity.getId()); + SearchRepository.applyRelationshipRevision(entity, searchIndexDoc, relationshipRevision); String json = JsonUtils.pojoToJson(searchIndexDoc); if (embeddingsEnabled) { @@ -487,10 +519,13 @@ private void addEntity( if (scriptedPartialUpdates) { SearchRepository.ScriptedPartialUpdate partialUpdate = - searchRepository.buildBulkScriptedPartialUpdate(entity); - if (partialUpdate != null - && addScriptedPartialUpdate( - indexName, docId, entityType, partialUpdate, finalJson, tracker)) { + searchRepository.buildBulkScriptedPartialUpdate(entity, relationshipRevision); + if (relationshipRevision != null && partialUpdate == null) { + throw new IllegalStateException( + "Missing fenced relationship update for " + entityType + " " + docId); + } + if (partialUpdate != null) { + addScriptedPartialUpdate(indexName, docId, entityType, partialUpdate, finalJson, tracker); processSuccess.incrementAndGet(); if (tracker != null) { tracker.recordProcess(StatsResult.SUCCESS); @@ -499,6 +534,19 @@ && addScriptedPartialUpdate( } } + SearchRepository.ScriptedPartialUpdate relationshipDocumentUpdate = + searchRepository.buildRelationshipDocumentUpdate( + entity, JsonUtils.readValue(finalJson, new TypeReference>() {})); + if (relationshipDocumentUpdate != null) { + addScriptedPartialUpdate( + indexName, docId, entityType, relationshipDocumentUpdate, finalJson, tracker); + processSuccess.incrementAndGet(); + if (tracker != null) { + tracker.recordProcess(StatsResult.SUCCESS); + } + return; + } + if (estimatedSize > maxPayloadSizeBytes) { LOG.warn( "Document {} of type {} is too large for bulk ({} bytes), sending directly", @@ -561,24 +609,21 @@ && addScriptedPartialUpdate( } } - private boolean addScriptedPartialUpdate( + private void addScriptedPartialUpdate( String indexName, String docId, String entityType, SearchRepository.ScriptedPartialUpdate partialUpdate, String upsertDocument, StageStatsTracker tracker) { + String effectiveUpsertDocument = partialUpdate.scriptedUpsert() ? "{}" : upsertDocument; long estimatedSize = - (long) upsertDocument.getBytes(StandardCharsets.UTF_8).length + (long) effectiveUpsertDocument.getBytes(StandardCharsets.UTF_8).length + JsonUtils.pojoToJson(partialUpdate.parameters()) .getBytes(StandardCharsets.UTF_8) .length + partialUpdate.script().getBytes(StandardCharsets.UTF_8).length + BULK_OPERATION_METADATA_OVERHEAD; - if (estimatedSize > maxPayloadSizeBytes) { - return false; - } - Map params = new HashMap<>(); partialUpdate .parameters() @@ -597,7 +642,8 @@ private boolean addScriptedPartialUpdate( .index(indexName) .id(docId) .retryOnConflict(3) - .upsert(OsUtils.toJsonData(upsertDocument)) + .scriptedUpsert(partialUpdate.scriptedUpsert()) + .upsert(OsUtils.toJsonData(effectiveUpsertDocument)) .script( Script.of( script -> @@ -614,7 +660,6 @@ private boolean addScriptedPartialUpdate( tracker.incrementPendingSink(); } bulkProcessor.add(operation, docId, entityType, tracker, estimatedSize); - return true; } private void recordStaleReferenceWarning( diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventDispatcher.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventDispatcher.java index a1f55b457017..9c38234d1252 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventDispatcher.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventDispatcher.java @@ -208,6 +208,14 @@ public void onEntitiesUpdated( List entities, ChangeDescription changeDescription, SubjectContext subjectContext) { + onEntitiesUpdated(entities, changeDescription, subjectContext, EntityUpdateContext.empty()); + } + + public void onEntitiesUpdated( + List entities, + ChangeDescription changeDescription, + SubjectContext subjectContext, + EntityUpdateContext updateContext) { if (entities == null || entities.isEmpty()) { return; } @@ -217,7 +225,13 @@ public void onEntitiesUpdated( "Dispatching bulk entity updated event for {} ({} entities)", entityType, entities.size()); Map> snapshots = buildSnapshots(entities, OP_UPDATED); for (EntityLifecycleEventHandler handler : getApplicableHandlers(entityType)) { - dispatchBulkUpdate(handler, entities, snapshots, changeDescription, subjectContext); + dispatchBulkUpdate( + handler, + entities, + snapshots, + changeDescription, + subjectContext, + updateContext == null ? EntityUpdateContext.empty() : updateContext); } } @@ -232,7 +246,8 @@ private void dispatchBulkUpdate( List entities, Map> snapshots, ChangeDescription changeDescription, - SubjectContext subjectContext) { + SubjectContext subjectContext, + EntityUpdateContext updateContext) { if (handler.isAsync()) { for (EntityInterface entity : entities) { ChangeDescription change = @@ -243,12 +258,16 @@ private void dispatchBulkUpdate( entity, snapshots.get(entity.getId()), OP_UPDATED, - e -> handler.onEntityUpdated(e, change, subjectContext), + e -> + handler.onEntityUpdated( + e, change, subjectContext, updateContext.forEntity(entity.getId())), handler); } } else { runInline( - () -> handler.onEntitiesUpdated(entities, changeDescription, subjectContext), handler); + () -> + handler.onEntitiesUpdated(entities, changeDescription, subjectContext, updateContext), + handler); } } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventHandler.java index 8ef51c8bd14a..f655c6e073fd 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityLifecycleEventHandler.java @@ -43,6 +43,14 @@ default void onEntityUpdated( // Default empty implementation } + default void onEntityUpdated( + EntityInterface entity, + ChangeDescription changeDescription, + SubjectContext subjectContext, + EntityUpdateContext updateContext) { + onEntityUpdated(entity, changeDescription, subjectContext); + } + /** * Called after multiple entities are updated. Default implementation delegates to * the single-entity onEntityUpdated for backward compatibility. @@ -62,6 +70,14 @@ default void onEntitiesUpdated( } } + default void onEntitiesUpdated( + List entities, + ChangeDescription changeDescription, + SubjectContext subjectContext, + EntityUpdateContext updateContext) { + onEntitiesUpdated(entities, changeDescription, subjectContext); + } + /** * Called after an entity is successfully updated. */ diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityUpdateContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityUpdateContext.java new file mode 100644 index 000000000000..7fb65da9c699 --- /dev/null +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/EntityUpdateContext.java @@ -0,0 +1,23 @@ +package org.openmetadata.service.events.lifecycle; + +import java.util.Map; +import java.util.UUID; + +/** Additional ordering metadata for an entity update that is not part of the public entity schema. */ +public record EntityUpdateContext(Map relationshipRevisions) { + private static final EntityUpdateContext EMPTY = new EntityUpdateContext(Map.of()); + + public EntityUpdateContext { + relationshipRevisions = + relationshipRevisions == null ? Map.of() : Map.copyOf(relationshipRevisions); + } + + public static EntityUpdateContext empty() { + return EMPTY; + } + + public EntityUpdateContext forEntity(UUID entityId) { + Long revision = relationshipRevisions.get(entityId); + return revision == null ? EMPTY : new EntityUpdateContext(Map.of(entityId, revision)); + } +} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/SearchIndexHandler.java b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/SearchIndexHandler.java index 10f777751f77..7c6119398215 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/SearchIndexHandler.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/events/lifecycle/handlers/SearchIndexHandler.java @@ -21,6 +21,7 @@ import org.openmetadata.schema.type.ChangeDescription; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.service.events.lifecycle.EntityLifecycleEventHandler; +import org.openmetadata.service.events.lifecycle.EntityUpdateContext; import org.openmetadata.service.search.SearchIndexRetryQueue; import org.openmetadata.service.search.SearchRepository; import org.openmetadata.service.security.policyevaluator.SubjectContext; @@ -186,25 +187,41 @@ public void onEntitiesUpdated( List entities, ChangeDescription changeDescription, SubjectContext subjectContext) { + onEntitiesUpdated(entities, changeDescription, subjectContext, EntityUpdateContext.empty()); + } + + @Override + public void onEntitiesUpdated( + List entities, + ChangeDescription changeDescription, + SubjectContext subjectContext, + EntityUpdateContext updateContext) { if (entities == null || entities.isEmpty()) { LOG.warn("Received null entities in onEntitiesUpdated"); return; } LOG.debug("Search index handler: Updating search indexes for {} entities", entities.size()); + EntityUpdateContext effectiveContext = + updateContext == null ? EntityUpdateContext.empty() : updateContext; try { - searchRepository.updateEntitiesIndex(entities); + searchRepository.updateEntitiesIndex(entities, effectiveContext.relationshipRevisions()); LOG.debug("Successfully updated search indexes for {} entities", entities.size()); } catch (Exception e) { LOG.error("Failed to bulk update search indexes for {} entities", entities.size(), e); for (EntityInterface entity : entities) { - onEntityUpdated( - entity, - entity.getChangeDescription() != null - ? entity.getChangeDescription() - : changeDescription, - subjectContext); + Long relationshipRevision = effectiveContext.relationshipRevisions().get(entity.getId()); + if (relationshipRevision == null) { + onEntityUpdated( + entity, + entity.getChangeDescription() != null + ? entity.getChangeDescription() + : changeDescription, + subjectContext); + } else { + searchRepository.updateEntityIndex(entity, relationshipRevision); + } } } } 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 f552bbd9eac7..35569ff78ea4 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 @@ -1586,6 +1586,29 @@ void insertMany( @Bind("jsonSchema") String jsonSchema, @Bind("json") List json); + @Transaction + @ConnectionAwareSqlBatch( + value = + "INSERT INTO entity_extension(id, extension, jsonSchema, json) " + + "VALUES (:id, :extension, :jsonSchema, JSON_OBJECT('revision', 1)) " + + "ON DUPLICATE KEY UPDATE jsonSchema = VALUES(jsonSchema), " + + "json = JSON_SET(entity_extension.json, '$.revision', " + + "COALESCE(CAST(JSON_UNQUOTE(JSON_EXTRACT(entity_extension.json, '$.revision')) AS UNSIGNED), 0) + 1)", + connectionType = MYSQL) + @ConnectionAwareSqlBatch( + value = + "INSERT INTO entity_extension(id, extension, jsonSchema, json) " + + "VALUES (:id, :extension, :jsonSchema, jsonb_build_object('revision', 1)) " + + "ON CONFLICT (id, extension) DO UPDATE SET jsonSchema = EXCLUDED.jsonSchema, " + + "json = jsonb_build_object('revision', " + + "COALESCE((entity_extension.json ->> 'revision')::bigint, 0) + 1)", + connectionType = POSTGRES) + @BatchChunkSize(100) + void incrementRevisions( + @BindUUID("id") List ids, + @Bind("extension") String extension, + @Bind("jsonSchema") String jsonSchema); + @ConnectionAwareSqlUpdate( value = "UPDATE entity_extension SET json = :json where (json -> '$.id') = :id", connectionType = MYSQL) diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java index 78755428e0ac..ce42ac565658 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestCaseRepository.java @@ -30,12 +30,9 @@ import static org.openmetadata.service.security.mask.PIIMasker.maskSampleData; import com.google.common.collect.Lists; -import com.google.common.util.concurrent.Striped; -import jakarta.ws.rs.ServiceUnavailableException; import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.UriInfo; import java.io.IOException; -import java.time.Duration; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -47,9 +44,7 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.locks.Lock; import java.util.function.Function; -import java.util.function.Supplier; import java.util.stream.Collectors; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; @@ -103,8 +98,8 @@ import org.openmetadata.service.Entity; import org.openmetadata.service.cache.CacheBundle; import org.openmetadata.service.events.lifecycle.EntityLifecycleEventDispatcher; +import org.openmetadata.service.events.lifecycle.EntityUpdateContext; import org.openmetadata.service.exception.EntityNotFoundException; -import org.openmetadata.service.lock.DatabaseAdvisoryLock; import org.openmetadata.service.rdf.RdfUpdater; import org.openmetadata.service.resources.dqtests.TestCaseResource; import org.openmetadata.service.resources.dqtests.TestSuiteMapper; @@ -129,9 +124,10 @@ public class TestCaseRepository extends EntityRepository { private static final String PATCH_FIELDS = "owners,entityLink,testSuite,testSuites,testDefinition,computePassedFailedRowCount,useDynamicAssertion,dimensionColumns,topDimensions"; public static final String FAILED_ROWS_SAMPLE_EXTENSION = "testCase.failedRowsSample"; - private static final String LOGICAL_SUITE_LOCK_PREFIX = "logical-suite:"; - private static final Duration LOGICAL_SUITE_LOCK_TIMEOUT = Duration.ofSeconds(30); - private static final Striped LOGICAL_SUITE_PUBLICATION_LOCKS = Striped.lock(4096); + public static final String TEST_SUITES_REVISION_EXTENSION = + "internal.testCase.testSuitesRevision"; + public static final String TEST_SUITES_REVISION_FIELD = "testSuitesRevision"; + private static final String TEST_SUITES_REVISION_SCHEMA = "testSuitesRevision"; private final ExecutorService asyncExecutor = Executors.newFixedThreadPool( 1, java.lang.Thread.ofPlatform().name("om-test-case-async").factory()); @@ -995,11 +991,29 @@ private void updateTestSuite(TestCase testCase) { } } - private void updateLogicalTestSuite(UUID testSuiteId) { - var testSuiteRepository = (TestSuiteRepository) Entity.getEntityRepository(Entity.TEST_SUITE); - TestSuite testSuite = Entity.getEntity(Entity.TEST_SUITE, testSuiteId, "*", ALL); - var original = TestSuiteRepository.copyTestSuite(testSuite); - testSuiteRepository.postUpdate(original, testSuite); + private void updateLogicalTestSuite(LogicalSuiteRelationshipChange relationshipChange) { + if (relationshipChange.isEmpty()) { + return; + } + var cachedReadBundle = CacheBundle.getCachedReadBundle(); + if (cachedReadBundle != null) { + cachedReadBundle.invalidate(TEST_SUITE, relationshipChange.testSuiteId()); + } + TestSuite testSuite = Entity.getEntity(TEST_SUITE, relationshipChange.testSuiteId(), "*", ALL); + FieldChange testsChange = + new FieldChange().withName("tests").withNewValue(listOrEmpty(testSuite.getTests())); + testSuite.setChangeDescription( + new ChangeDescription() + .withPreviousVersion(testSuite.getVersion()) + .withFieldsUpdated(List.of(testsChange))); + EntityLifecycleEventDispatcher.getInstance() + .onEntitiesUpdated( + List.of(testSuite), + null, + null, + new EntityUpdateContext( + Map.of(testSuite.getId(), relationshipChange.relationshipRevision()))); + RdfUpdater.updateEntity(testSuite); } @Transaction @@ -1108,24 +1122,19 @@ public void isTestSuiteBasic(String testSuiteFqn) { public RestUtil.PutResponse addTestCasesToLogicalTestSuite( TestSuite testSuite, List testCaseIds) { - return withLogicalSuitePublicationLock( - testSuite.getId(), () -> addTestCasesToLogicalTestSuiteLocked(testSuite, testCaseIds)); - } - - private RestUtil.PutResponse addTestCasesToLogicalTestSuiteLocked( - TestSuite testSuite, List testCaseIds) { - AtomicReference> addedTestCases = new AtomicReference<>(List.of()); + AtomicReference relationshipChange = + new AtomicReference<>(LogicalSuiteRelationshipChange.empty()); flushInOneTransaction( () -> - addedTestCases.set( + relationshipChange.set( addTestCasesToLogicalTestSuiteFlush(testSuite.getId(), testCaseIds))); - postLogicalSuiteRelationshipUpdate(addedTestCases.get(), testSuite.getId()); - updateLogicalTestSuite(testSuite.getId()); + postLogicalSuiteRelationshipUpdate(relationshipChange.get()); + updateLogicalTestSuite(relationshipChange.get()); return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); } - private List addTestCasesToLogicalTestSuiteFlush( + private LogicalSuiteRelationshipChange addTestCasesToLogicalTestSuiteFlush( UUID testSuiteId, List testCaseIds) { List originalTestCaseReferences = findTo(testSuiteId, TEST_SUITE, Relationship.CONTAINS, TEST_CASE); @@ -1135,34 +1144,36 @@ private List addTestCasesToLogicalTestSuiteFlush( findTo(testSuiteId, TEST_SUITE, Relationship.CONTAINS, TEST_CASE); Set originalIds = originalTestCaseReferences.stream().map(EntityReference::getId).collect(Collectors.toSet()); - return updatedTestCaseReferences.stream() - .filter(ref -> !originalIds.contains(ref.getId())) - .toList(); + List addedTestCases = + updatedTestCaseReferences.stream() + .filter(ref -> !originalIds.contains(ref.getId())) + .toList(); + return prepareLogicalSuiteRelationshipChange(testSuiteId, addedTestCases); } public RestUtil.PutResponse addAllTestCasesToLogicalTestSuite( TestSuite testSuite, List excludedTestCaseIds) { - return withLogicalSuitePublicationLock( - testSuite.getId(), - () -> addAllTestCasesToLogicalTestSuiteLocked(testSuite, excludedTestCaseIds)); - } - - private RestUtil.PutResponse addAllTestCasesToLogicalTestSuiteLocked( - TestSuite testSuite, List excludedTestCaseIds) { - AtomicReference> addedTestCases = new AtomicReference<>(List.of()); + AtomicReference relationshipChange = + new AtomicReference<>(LogicalSuiteRelationshipChange.empty()); flushInOneTransaction( () -> - addedTestCases.set( + relationshipChange.set( addAllTestCasesToLogicalTestSuiteFlush(testSuite.getId(), excludedTestCaseIds))); - for (List batch : Lists.partition(addedTestCases.get(), 100)) { - postLogicalSuiteRelationshipUpdate(batch, testSuite.getId()); + for (List batch : + Lists.partition(relationshipChange.get().testCaseReferences(), 100)) { + Map batchRevisions = new HashMap<>(); + for (EntityReference testCase : batch) { + batchRevisions.put( + testCase.getId(), relationshipChange.get().testCaseRevisions().get(testCase.getId())); + } + postLogicalSuiteRelationshipUpdate(List.copyOf(batch), batchRevisions); } - updateLogicalTestSuite(testSuite.getId()); + updateLogicalTestSuite(relationshipChange.get()); return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); } - private List addAllTestCasesToLogicalTestSuiteFlush( + private LogicalSuiteRelationshipChange addAllTestCasesToLogicalTestSuiteFlush( UUID testSuiteId, List excludedTestCaseIds) { List originalTestCaseReferences = findTo(testSuiteId, TEST_SUITE, Relationship.CONTAINS, TEST_CASE); @@ -1190,114 +1201,157 @@ private List addAllTestCasesToLogicalTestSuiteFlush( Set originalIds = originalTestCaseReferences.stream().map(EntityReference::getId).collect(Collectors.toSet()); - return updatedTestCaseReferences.stream() - .filter(ref -> !originalIds.contains(ref.getId())) - .toList(); + List addedTestCases = + updatedTestCaseReferences.stream() + .filter(ref -> !originalIds.contains(ref.getId())) + .toList(); + return prepareLogicalSuiteRelationshipChange(testSuiteId, addedTestCases); } public RestUtil.DeleteResponse deleteTestCaseFromLogicalTestSuite( UUID testSuiteId, UUID testCaseId) { - return withLogicalSuitePublicationLock( - testSuiteId, () -> deleteTestCaseFromLogicalTestSuiteLocked(testSuiteId, testCaseId)); - } - - private RestUtil.DeleteResponse deleteTestCaseFromLogicalTestSuiteLocked( - UUID testSuiteId, UUID testCaseId) { TestCase testCase = Entity.getEntity(Entity.TEST_CASE, testCaseId, null, null); + AtomicReference relationshipChange = + new AtomicReference<>(LogicalSuiteRelationshipChange.empty()); flushInOneTransaction( - () -> - deleteRelationship( - testSuiteId, TEST_SUITE, testCaseId, TEST_CASE, Relationship.CONTAINS)); + () -> { + deleteRelationship(testSuiteId, TEST_SUITE, testCaseId, TEST_CASE, Relationship.CONTAINS); + relationshipChange.set( + prepareLogicalSuiteRelationshipChange( + testSuiteId, List.of(testCase.getEntityReference()))); + }); TestCase updatedTestCase = - postLogicalSuiteRelationshipUpdate(List.of(testCase.getEntityReference()), testSuiteId) - .getFirst(); - updateLogicalTestSuite(testSuiteId); + postLogicalSuiteRelationshipUpdate(relationshipChange.get()).getFirst(); + updateLogicalTestSuite(relationshipChange.get()); testCase.setTestSuite(updatedTestCase.getTestSuite()); testCase.setTestSuites(updatedTestCase.getTestSuites()); return new RestUtil.DeleteResponse<>(testCase, ENTITY_DELETED); } - private R withLogicalSuitePublicationLock(UUID testSuiteId, Supplier operation) { - try { - return DatabaseAdvisoryLock.withLock( - Entity.getJdbi(), - LOGICAL_SUITE_LOCK_PREFIX + testSuiteId, - LOGICAL_SUITE_LOCK_TIMEOUT, - operation); - } catch (DatabaseAdvisoryLock.LockUnavailableException exception) { - ServiceUnavailableException unavailable = - new ServiceUnavailableException(exception.getMessage()); - unavailable.initCause(exception); - throw unavailable; - } - } - - private List getLogicalSuiteUpdatedTestCase( - List testCaseReferences, UUID testSuiteId) { + private List getLogicalSuiteUpdatedTestCase(List testCaseReferences) { List testCases = Entity.getEntities(testCaseReferences, "*", Include.ALL); testCases.forEach( tc -> { - TestSuite currentTestSuite = - listOrEmpty(tc.getTestSuites()).stream() - .filter(testSuite -> testSuiteId.equals(testSuite.getId())) - .findFirst() - .orElse(null); - FieldChange relationshipChange = new FieldChange().withName(FIELD_TEST_SUITES); - ChangeDescription change = new ChangeDescription().withPreviousVersion(tc.getVersion()); - if (currentTestSuite == null) { - relationshipChange.setOldValue(List.of(new TestSuite().withId(testSuiteId))); - change.setFieldsDeleted(List.of(relationshipChange)); - } else { - relationshipChange.setNewValue(List.of(currentTestSuite)); - change.setFieldsAdded(List.of(relationshipChange)); - } - tc.setChangeDescription(change); + FieldChange relationshipChange = + new FieldChange() + .withName(FIELD_TEST_SUITES) + .withNewValue(listOrEmpty(tc.getTestSuites())); + tc.setChangeDescription( + new ChangeDescription() + .withPreviousVersion(tc.getVersion()) + .withFieldsUpdated(List.of(relationshipChange))); }); return testCases; } + private LogicalSuiteRelationshipChange prepareLogicalSuiteRelationshipChange( + UUID testSuiteId, List testCaseReferences) { + if (nullOrEmpty(testCaseReferences)) { + return LogicalSuiteRelationshipChange.empty(); + } + + List testCaseIds = + testCaseReferences.stream().map(EntityReference::getId).distinct().sorted().toList(); + daoCollection + .entityExtensionDAO() + .incrementRevisions( + testCaseIds, TEST_SUITES_REVISION_EXTENSION, TEST_SUITES_REVISION_SCHEMA); + daoCollection + .entityExtensionDAO() + .incrementRevisions( + List.of(testSuiteId), + TestSuiteRepository.TESTS_REVISION_EXTENSION, + TestSuiteRepository.getTestsRevisionSchema()); + Map testCaseRevisions = getTestSuiteRelationshipRevisions(testCaseIds); + if (testCaseRevisions.size() != testCaseIds.size()) { + throw new IllegalStateException("Failed to persist every test suite relationship revision"); + } + Long relationshipRevision = + TestSuiteRepository.getTestsRelationshipRevisions(List.of(testSuiteId)).get(testSuiteId); + if (relationshipRevision == null) { + throw new IllegalStateException("Failed to persist the test suite tests revision"); + } + + return new LogicalSuiteRelationshipChange( + testSuiteId, testCaseReferences, testCaseRevisions, relationshipRevision); + } + + public static Map getTestSuiteRelationshipRevisions(List testCaseIds) { + if (nullOrEmpty(testCaseIds)) { + return Map.of(); + } + CollectionDAO collectionDAO = Entity.getCollectionDAO(); + if (collectionDAO == null || collectionDAO.entityExtensionDAO() == null) { + return Map.of(); + } + Map revisions = new HashMap<>(); + for (CollectionDAO.ExtensionRecordWithId record : + collectionDAO + .entityExtensionDAO() + .getExtensionBatch( + testCaseIds.stream().map(UUID::toString).toList(), + TEST_SUITES_REVISION_EXTENSION)) { + TestSuiteRelationshipRevision revision = + JsonUtils.readValue(record.extensionJson(), TestSuiteRelationshipRevision.class); + revisions.put(record.id(), revision.revision()); + } + return revisions; + } + /** * Publishes logical-suite relationship changes from committed database state. Relationship rows * do not modify the stored {@link TestCase} JSON, so publication invalidates the hydrated read - * bundle and reloads while holding deterministic per-test-case locks. Logical-suite mutation - * entry points also hold a database session advisory lock from before the relationship transaction - * through this publication, so requests on different service nodes publish in commit order. The - * resulting change description contains an idempotent add/remove delta for search rather than a - * replacement {@code testSuites} array. + * bundle and reloads the replacement snapshot after the transaction that advances durable + * revisions for every affected test case and the logical suite. Higher revisions therefore reload + * after every lower revision's relationship commit. Search applies snapshots whose revision is not + * older than the indexed one, while ordinary TestCase and logical TestSuite writes preserve these + * revision-owned fields, so publications may run concurrently across service nodes without + * allowing a late request to overwrite newer relationship state. */ private List postLogicalSuiteRelationshipUpdate( - List testCaseReferences, UUID testSuiteId) { - if (nullOrEmpty(testCaseReferences)) { + LogicalSuiteRelationshipChange relationshipChange) { + return postLogicalSuiteRelationshipUpdate( + relationshipChange.testCaseReferences(), relationshipChange.testCaseRevisions()); + } + + private List postLogicalSuiteRelationshipUpdate( + List testCaseReferences, Map testCaseRevisions) { + if (testCaseReferences.isEmpty()) { return List.of(); } - List publicationLocks = new ArrayList<>(); - for (Lock publicationLock : - LOGICAL_SUITE_PUBLICATION_LOCKS.bulkGet( - testCaseReferences.stream().map(EntityReference::getId).toList())) { - if (!publicationLocks.contains(publicationLock)) { - publicationLocks.add(publicationLock); - } + var cachedReadBundle = CacheBundle.getCachedReadBundle(); + if (cachedReadBundle != null) { + testCaseReferences.forEach( + reference -> cachedReadBundle.invalidate(entityType, reference.getId())); } - publicationLocks.forEach(Lock::lock); - try { - var cachedReadBundle = CacheBundle.getCachedReadBundle(); - if (cachedReadBundle != null) { - for (EntityReference testCaseReference : testCaseReferences) { - cachedReadBundle.invalidate(entityType, testCaseReference.getId()); - } - } + List updatedTestCases = getLogicalSuiteUpdatedTestCase(testCaseReferences); + EntityLifecycleEventDispatcher.getInstance() + .onEntitiesUpdated( + updatedTestCases, null, null, new EntityUpdateContext(testCaseRevisions)); + updatedTestCases.forEach(RdfUpdater::updateEntity); + return updatedTestCases; + } - List updatedTestCases = - getLogicalSuiteUpdatedTestCase(testCaseReferences, testSuiteId); - EntityLifecycleEventDispatcher.getInstance().onEntitiesUpdated(updatedTestCases, null, null); - updatedTestCases.forEach(RdfUpdater::updateEntity); - return updatedTestCases; - } finally { - for (int index = publicationLocks.size() - 1; index >= 0; index--) { - publicationLocks.get(index).unlock(); - } + private record TestSuiteRelationshipRevision(long revision) {} + + private record LogicalSuiteRelationshipChange( + UUID testSuiteId, + List testCaseReferences, + Map testCaseRevisions, + long relationshipRevision) { + private LogicalSuiteRelationshipChange { + testCaseReferences = List.copyOf(testCaseReferences); + testCaseRevisions = Map.copyOf(testCaseRevisions); + } + + private boolean isEmpty() { + return testSuiteId == null; + } + + private static LogicalSuiteRelationshipChange empty() { + return new LogicalSuiteRelationshipChange(null, List.of(), Map.of(), 0L); } } @@ -1742,14 +1796,8 @@ private enum Direction { @Override public void postUpdate(TestCase original, TestCase updated) { - Lock publicationLock = LOGICAL_SUITE_PUBLICATION_LOCKS.get(updated.getId()); - publicationLock.lock(); - try { - hydrateTestSuiteFieldsForSearch(updated); - super.postUpdate(original, updated); - } finally { - publicationLock.unlock(); - } + hydrateTestSuiteFieldsForSearch(updated); + super.postUpdate(original, updated); if (EntityStatus.IN_REVIEW.equals(original.getEntityStatus())) { if (EntityStatus.APPROVED.equals(updated.getEntityStatus())) { closeApprovalTask(updated, "Approved the test case"); diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestSuiteRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestSuiteRepository.java index 2cffaa75e3a9..0ae4dadbc704 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestSuiteRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TestSuiteRepository.java @@ -93,6 +93,9 @@ @Slf4j public class TestSuiteRepository extends EntityRepository { public static final String SUMMARY_FIELD = "summary"; + public static final String TESTS_REVISION_EXTENSION = "internal.testSuite.testsRevision"; + public static final String TESTS_REVISION_FIELD = "testsRevision"; + private static final String TESTS_REVISION_SCHEMA = "testsRevision"; private static final String UPDATE_FIELDS = "tests"; private static final String PATCH_FIELDS = "tests"; private static final int MAX_CONCURRENT_REPORT_QUERIES = 10; @@ -152,6 +155,33 @@ public TestSuiteRepository() { fieldFetchers.put("pipelines", this::fetchAndSetIngestionPipelines); } + public static Map getTestsRelationshipRevisions(List testSuiteIds) { + if (nullOrEmpty(testSuiteIds)) { + return Map.of(); + } + CollectionDAO collectionDAO = Entity.getCollectionDAO(); + if (collectionDAO == null || collectionDAO.entityExtensionDAO() == null) { + return Map.of(); + } + Map revisions = new HashMap<>(); + for (CollectionDAO.ExtensionRecordWithId record : + collectionDAO + .entityExtensionDAO() + .getExtensionBatch( + testSuiteIds.stream().map(UUID::toString).toList(), TESTS_REVISION_EXTENSION)) { + TestsRelationshipRevision revision = + JsonUtils.readValue(record.extensionJson(), TestsRelationshipRevision.class); + revisions.put(record.id(), revision.revision()); + } + return revisions; + } + + static String getTestsRevisionSchema() { + return TESTS_REVISION_SCHEMA; + } + + private record TestsRelationshipRevision(long revision) {} + @Override public ResultList listFromSearchWithOffset( UriInfo uriInfo, diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java b/openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java deleted file mode 100644 index ca724d407062..000000000000 --- a/openmetadata-service/src/main/java/org/openmetadata/service/lock/DatabaseAdvisoryLock.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * 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. - */ - -package org.openmetadata.service.lock; - -import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; -import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; - -import java.time.Duration; -import java.util.Objects; -import java.util.concurrent.locks.LockSupport; -import java.util.function.Supplier; -import lombok.extern.slf4j.Slf4j; -import org.jdbi.v3.core.Handle; -import org.jdbi.v3.core.Jdbi; -import org.jdbi.v3.sqlobject.customizer.Bind; -import org.openmetadata.service.jdbi3.locator.ConnectionAwareSqlQuery; - -@Slf4j -public final class DatabaseAdvisoryLock { - private static final int MYSQL_LOCK_NAME_LIMIT = 64; - private static final long RETRY_INTERVAL_NANOS = Duration.ofMillis(25).toNanos(); - - private DatabaseAdvisoryLock() {} - - public static T withLock(Jdbi jdbi, String lockKey, Duration timeout, Supplier operation) { - Objects.requireNonNull(jdbi, "jdbi"); - Objects.requireNonNull(lockKey, "lockKey"); - Objects.requireNonNull(timeout, "timeout"); - Objects.requireNonNull(operation, "operation"); - if (lockKey.length() > MYSQL_LOCK_NAME_LIMIT) { - throw new IllegalArgumentException("Database advisory lock key exceeds 64 characters"); - } - if (timeout.isNegative()) { - throw new IllegalArgumentException("Database advisory lock timeout cannot be negative"); - } - - try (Handle handle = jdbi.open()) { - AdvisoryLockDAO lockDAO = handle.attach(AdvisoryLockDAO.class); - acquire(lockDAO, lockKey, timeout); - try { - return operation.get(); - } finally { - release(lockDAO, lockKey); - } - } - } - - private static void acquire(AdvisoryLockDAO lockDAO, String lockKey, Duration timeout) { - long deadline = System.nanoTime() + timeout.toNanos(); - do { - if (lockDAO.tryAcquire(lockKey)) { - return; - } - if (Thread.currentThread().isInterrupted()) { - throw new LockUnavailableException( - "Interrupted while acquiring database advisory lock " + lockKey); - } - long remainingNanos = deadline - System.nanoTime(); - if (remainingNanos > 0) { - LockSupport.parkNanos(Math.min(RETRY_INTERVAL_NANOS, remainingNanos)); - } - } while (System.nanoTime() < deadline); - - throw new LockUnavailableException("Timed out acquiring database advisory lock " + lockKey); - } - - private static void release(AdvisoryLockDAO lockDAO, String lockKey) { - try { - if (!lockDAO.release(lockKey)) { - LOG.warn("Database advisory lock {} was no longer owned during release", lockKey); - } - } catch (RuntimeException exception) { - LOG.warn("Failed to release database advisory lock {}", lockKey, exception); - } - } - - interface AdvisoryLockDAO { - @ConnectionAwareSqlQuery(value = "SELECT GET_LOCK(:lockKey, 0)", connectionType = MYSQL) - @ConnectionAwareSqlQuery( - value = "SELECT pg_try_advisory_lock(hashtextextended(:lockKey, 0))", - connectionType = POSTGRES) - boolean tryAcquire(@Bind("lockKey") String lockKey); - - @ConnectionAwareSqlQuery(value = "SELECT RELEASE_LOCK(:lockKey)", connectionType = MYSQL) - @ConnectionAwareSqlQuery( - value = "SELECT pg_advisory_unlock(hashtextextended(:lockKey, 0))", - connectionType = POSTGRES) - boolean release(@Bind("lockKey") String lockKey); - } - - public static final class LockUnavailableException extends RuntimeException { - public LockUnavailableException(String message) { - super(message); - } - } -} diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java index cb36ddcbd4b3..1d87b24fde0f 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryWorker.java @@ -24,6 +24,7 @@ import java.util.concurrent.atomic.AtomicReference; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.tests.TestSuite; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.Relationship; @@ -31,10 +32,13 @@ import org.openmetadata.search.IndexMapping; import org.openmetadata.service.Entity; import org.openmetadata.service.apps.bundles.searchIndex.BulkSink; +import org.openmetadata.service.cache.CacheBundle; import org.openmetadata.service.exception.EntityNotFoundException; import org.openmetadata.service.jdbi3.CollectionDAO; import org.openmetadata.service.jdbi3.CollectionDAO.SearchIndexRetryQueueDAO.SearchIndexRetryRecord; import org.openmetadata.service.jdbi3.EntityRepository; +import org.openmetadata.service.jdbi3.TestCaseRepository; +import org.openmetadata.service.jdbi3.TestSuiteRepository; import org.openmetadata.service.workflows.searchIndex.ReindexingUtil; import os.org.opensearch.client.opensearch._types.OpenSearchException; @@ -381,6 +385,7 @@ private void reindexEntityCascade(EntityReference root) throws Exception { ArrayDeque queue = new ArrayDeque<>(); Set visited = new HashSet<>(); List entitiesToIndex = new ArrayList<>(); + Map relationshipRevisions = new HashMap<>(); queue.add(root); int processed = 0; @@ -399,24 +404,33 @@ private void reindexEntityCascade(EntityReference root) throws Exception { continue; } - EntityInterface entity; + StableEntitySnapshot snapshot; try { - String fields = String.join(",", ReindexingUtil.getSearchIndexFields(current.getType())); - entity = Entity.getEntity(current, fields, Include.ALL); + snapshot = loadStableEntitySnapshot(current); + } catch (EntityNotFoundException ex) { + continue; } catch (Exception ex) { + if (isRelationshipRevisionEntityType(current.getType())) { + throw ex; + } continue; } + EntityInterface entity = snapshot.entity(); if (entity == null) { continue; } entitiesToIndex.add(entity); + if (snapshot.relationshipRevision() != null) { + relationshipRevisions.put(entity.getId(), snapshot.relationshipRevision()); + } processed++; if (entitiesToIndex.size() >= CASCADE_BATCH_SIZE) { - upsertEntitiesInBulk(entitiesToIndex); + upsertEntitiesInBulk(entitiesToIndex, relationshipRevisions); entitiesToIndex.clear(); + relationshipRevisions.clear(); } addChildrenByRelation( @@ -443,12 +457,51 @@ private void reindexEntityCascade(EntityReference root) throws Exception { } if (!entitiesToIndex.isEmpty()) { - upsertEntitiesInBulk(entitiesToIndex); + upsertEntitiesInBulk(entitiesToIndex, relationshipRevisions); } } - private void upsertEntitiesInBulk(List entitiesToIndex) throws Exception { - if (entitiesToIndex.size() == 1) { + private StableEntitySnapshot loadStableEntitySnapshot(EntityReference reference) { + String fields = String.join(",", ReindexingUtil.getSearchIndexFields(reference.getType())); + if (!isRelationshipRevisionEntityType(reference.getType())) { + return new StableEntitySnapshot(Entity.getEntity(reference, fields, Include.ALL), null); + } + + for (int attempt = 0; attempt < 3; attempt++) { + long revisionBefore = getRelationshipRevision(reference); + var cachedReadBundle = CacheBundle.getCachedReadBundle(); + if (cachedReadBundle != null) { + cachedReadBundle.invalidate(reference.getType(), reference.getId()); + } + EntityInterface entity = Entity.getEntity(reference, fields, Include.ALL); + if (entity instanceof TestSuite testSuite && !Boolean.FALSE.equals(testSuite.getBasic())) { + return new StableEntitySnapshot(entity, null); + } + long revisionAfter = getRelationshipRevision(reference); + if (revisionBefore == revisionAfter) { + return new StableEntitySnapshot(entity, revisionAfter); + } + } + throw new IllegalStateException( + "Relationships kept changing while preparing search retry for " + reference.getId()); + } + + private boolean isRelationshipRevisionEntityType(String entityType) { + return Entity.TEST_CASE.equals(entityType) || Entity.TEST_SUITE.equals(entityType); + } + + private long getRelationshipRevision(EntityReference reference) { + Map revisions = + Entity.TEST_CASE.equals(reference.getType()) + ? TestCaseRepository.getTestSuiteRelationshipRevisions(List.of(reference.getId())) + : TestSuiteRepository.getTestsRelationshipRevisions(List.of(reference.getId())); + return revisions.getOrDefault(reference.getId(), 0L); + } + + private void upsertEntitiesInBulk( + List entitiesToIndex, Map relationshipRevisions) + throws Exception { + if (entitiesToIndex.size() == 1 && relationshipRevisions.isEmpty()) { upsertEntityDirect(entitiesToIndex.getFirst()); return; } @@ -486,10 +539,37 @@ private void upsertEntitiesInBulk(List entitiesToIndex) throws for (Map.Entry> entry : entitiesByType.entrySet()) { Map context = new HashMap<>(); context.put(ReindexingUtil.ENTITY_TYPE_KEY, entry.getKey()); + Map typeRelationshipRevisions = + relationshipRevisionsFor(entry.getValue(), relationshipRevisions); + if (!typeRelationshipRevisions.isEmpty()) { + context.put(BulkSink.RELATIONSHIP_REVISIONS_CONTEXT_KEY, typeRelationshipRevisions); + } ReindexingUtil.populateDocBuildContext(context, entry.getKey(), entry.getValue()); bulkSink.write(entry.getValue(), context); } + if (!relationshipRevisions.isEmpty()) { + for (Map.Entry> entry : entitiesByType.entrySet()) { + List relationshipEntities = + entry.getValue().stream() + .filter(entity -> relationshipRevisions.containsKey(entity.getId())) + .toList(); + if (relationshipEntities.isEmpty()) { + continue; + } + Map typeRelationshipRevisions = + relationshipRevisionsFor(relationshipEntities, relationshipRevisions); + Map relationshipContext = new HashMap<>(); + relationshipContext.put(ReindexingUtil.ENTITY_TYPE_KEY, entry.getKey()); + relationshipContext.put(BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY, true); + relationshipContext.put( + BulkSink.RELATIONSHIP_REVISIONS_CONTEXT_KEY, typeRelationshipRevisions); + ReindexingUtil.populateDocBuildContext( + relationshipContext, entry.getKey(), relationshipEntities); + bulkSink.write(relationshipEntities, relationshipContext); + } + } + boolean flushComplete = bulkSink.flushAndAwait(60); if (!flushComplete) { throw new RuntimeException("Retry bulk flush timed out"); @@ -512,6 +592,18 @@ private void upsertEntitiesInBulk(List entitiesToIndex) throws } } + private Map relationshipRevisionsFor( + List entities, Map relationshipRevisions) { + Map revisions = new HashMap<>(); + for (EntityInterface entity : entities) { + Long revision = relationshipRevisions.get(entity.getId()); + if (revision != null) { + revisions.put(entity.getId(), revision); + } + } + return revisions; + } + private void upsertEntityDirect(EntityInterface entity) throws Exception { if (entity == null || entity.getEntityReference() == null || entity.getId() == null) { return; @@ -565,6 +657,8 @@ private void removeStaleEntityById(String entityId) { } } + private record StableEntitySnapshot(EntityInterface entity, Long relationshipRevision) {} + // --------------------------------------------------------------------------- // Resilience: client availability, backoff, and error classification // --------------------------------------------------------------------------- diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java index f6e3fc492f18..dd7b63a00042 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchRepository.java @@ -203,7 +203,78 @@ public void run() { } } - public record ScriptedPartialUpdate(String script, Map parameters) {} + public record ScriptedPartialUpdate( + String script, Map parameters, boolean scriptedUpsert) { + public ScriptedPartialUpdate(String script, Map parameters) { + this(script, parameters, false); + } + } + + private record RelationshipRevisionSpec( + String relationshipField, + String revisionField, + String replacementScript, + String documentUpdateScript) {} + + private static RelationshipRevisionSpec relationshipRevisionSpec( + String relationshipField, String revisionField) { + String replacementScript = + """ + if (ctx._source.%2$s == null || params.%2$s >= ctx._source.%2$s) { + ctx._source.%1$s = params.%1$s; + ctx._source.%2$s = params.%2$s; + } + """ + .formatted(relationshipField, revisionField); + String documentUpdateScript = + """ + def preserveRelationship = ctx._source.containsKey('%1$s') || ctx._source.containsKey('%2$s'); + for (k in params.keySet()) { + if (k != 'fieldsToRemove' && (!preserveRelationship || (k != '%1$s' && k != '%2$s'))) { + ctx._source.put(k, params.get(k)); + } + } + if (params.containsKey('fieldsToRemove')) { + for (field in params.fieldsToRemove) { + if (!preserveRelationship || (field != '%1$s' && field != '%2$s')) { + ctx._source.remove(field); + } + } + } + """ + .formatted(relationshipField, revisionField); + return new RelationshipRevisionSpec( + relationshipField, revisionField, replacementScript, documentUpdateScript); + } + + private static RelationshipRevisionSpec relationshipRevisionSpec(EntityInterface entity) { + if (entity == null || entity.getEntityReference() == null) { + return null; + } + String entityType = entity.getEntityReference().getType(); + if (Entity.TEST_CASE.equals(entityType)) { + return TEST_CASE_RELATIONSHIP_REVISION; + } + if (Entity.TEST_SUITE.equals(entityType) + && entity instanceof TestSuite testSuite + && Boolean.FALSE.equals(testSuite.getBasic())) { + return TEST_SUITE_RELATIONSHIP_REVISION; + } + return null; + } + + public static void applyRelationshipRevision( + EntityInterface entity, Map document, Long relationshipRevision) { + if (relationshipRevision == null) { + return; + } + RelationshipRevisionSpec revisionSpec = relationshipRevisionSpec(entity); + if (revisionSpec == null) { + throw new IllegalArgumentException( + "Relationship revisions can only update test cases and logical test suites"); + } + document.put(revisionSpec.revisionField(), relationshipRevision); + } /** * Open a search-write deferral scope on the current thread. While open, the cascade ES mutations @@ -344,28 +415,15 @@ public static void deferOrRunSearchWrite( "extension", "queryUsedIn", "votes", - "pipelineStatus", - TEST_SUITES); + "pipelineStatus"); - private static final Set BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS = Set.of(TEST_SUITES); - - private static final String TEST_SUITES_ADDED_PARAM = "testSuitesAdded"; - private static final String TEST_SUITE_IDS_DELETED_PARAM = "testSuiteIdsDeleted"; - private static final String TEST_SUITES_DELTA_SCRIPT = - """ - if (params.testSuiteIdsDeleted != null && ctx._source.testSuites != null) { - ctx._source.testSuites.removeIf(suite -> params.testSuiteIdsDeleted.contains(suite.id)); - } - if (params.testSuitesAdded != null) { - if (ctx._source.testSuites == null) { - ctx._source.testSuites = []; - } - for (def addedSuite : params.testSuitesAdded) { - ctx._source.testSuites.removeIf(suite -> suite.id == addedSuite.id); - ctx._source.testSuites.add(addedSuite); - } - } - """; + private static final String TESTS = "tests"; + private static final String TEST_SUITES_REVISION = "testSuitesRevision"; + private static final String TESTS_REVISION = "testsRevision"; + private static final RelationshipRevisionSpec TEST_CASE_RELATIONSHIP_REVISION = + relationshipRevisionSpec(TEST_SUITES, TEST_SUITES_REVISION); + private static final RelationshipRevisionSpec TEST_SUITE_RELATIONSHIP_REVISION = + relationshipRevisionSpec(TESTS, TESTS_REVISION); @Getter private final ElasticSearchConfiguration searchConfiguration; @Getter private final int maxDBConnections; @@ -1506,11 +1564,11 @@ public void updateTimeSeriesEntity(EntityTimeSeriesInterface entityTimeSeries) { * entity to the durable retry outbox. Returns {@code false} (run inline) for every non-flush * caller — the post-commit search-index handler, reindex apps, lineage jobs. */ - private boolean deferEntityIndex(EntityInterface entity) { + private boolean deferEntityIndex(EntityInterface entity, Long relationshipRevision) { EntityReference ref = entity.getEntityReference(); return deferSearchWrite( new DeferredSearchWrite( - () -> updateEntityIndex(entity), + () -> updateEntityIndex(entity, relationshipRevision), "updateEntityIndex", entity.getId() != null ? entity.getId().toString() : null, entity.getFullyQualifiedName(), @@ -1522,11 +1580,15 @@ private boolean deferEntityIndex(EntityInterface entity) { * This method is used by SearchIndexHandler. */ public void updateEntityIndex(EntityInterface entity) { + updateEntityIndex(entity, null); + } + + public void updateEntityIndex(EntityInterface entity, Long relationshipRevision) { if (entity == null) { LOG.warn("Entity is null, cannot update index."); return; } - if (deferEntityIndex(entity)) { + if (deferEntityIndex(entity, relationshipRevision)) { return; } @@ -1554,29 +1616,50 @@ public void updateEntityIndex(EntityInterface entity) { ChangeDescription changeDescription = getEffectiveChangeDescription(entity); - boolean isNonVersionedUpdate = - changeDescription != null - && entity.getChangeDescription() != null - && Objects.equals( - entity.getVersion(), entity.getChangeDescription().getPreviousVersion()); - ScriptedPartialUpdate partialUpdate = - buildScriptedPartialUpdate(entity, changeDescription, isNonVersionedUpdate); - if (partialUpdate != null) { - scriptTxt = partialUpdate.script(); - doc = partialUpdate.parameters(); - } else { - if (isNonVersionedUpdate && changeDescription != null) { - LOG.debug( - "Falling back to full document indexing for non-versioned update. entityType={}, entityId={}, changedFields={}", - entityType, - entityId, - getChangedFieldNames(changeDescription)); + if (relationshipRevision != null) { + RelationshipRevisionSpec revisionSpec = relationshipRevisionSpec(entity); + if (revisionSpec == null) { + throw new IllegalArgumentException( + "Relationship revisions can only update test cases and logical test suites"); } - SearchIndex elasticSearchIndex = searchIndexFactory.buildIndex(entityType, entity); - doc = elasticSearchIndex.buildSearchIndexDoc(); + SearchIndex searchIndex = searchIndexFactory.buildIndex(entityType, entity); + doc = new HashMap<>(searchIndex.buildSearchIndexDoc()); doc = SearchIndexUtils.stripDocMapIfOversized( doc, SearchClusterMetrics.DEFAULT_BULK_PAYLOAD_SIZE_BYTES, entityId, entityType); + applyRelationshipRevision(entity, doc, relationshipRevision); + scriptTxt = revisionSpec.replacementScript(); + } else { + boolean isNonVersionedUpdate = + changeDescription != null + && entity.getChangeDescription() != null + && Objects.equals( + entity.getVersion(), entity.getChangeDescription().getPreviousVersion()); + ScriptedPartialUpdate partialUpdate = + buildScriptedPartialUpdate(entity, changeDescription, isNonVersionedUpdate); + if (partialUpdate != null) { + scriptTxt = partialUpdate.script(); + doc = partialUpdate.parameters(); + } else { + if (isNonVersionedUpdate && changeDescription != null) { + LOG.debug( + "Falling back to full document indexing for non-versioned update. entityType={}, entityId={}, changedFields={}", + entityType, + entityId, + getChangedFieldNames(changeDescription)); + } + SearchIndex searchIndex = searchIndexFactory.buildIndex(entityType, entity); + doc = searchIndex.buildSearchIndexDoc(); + doc = + SearchIndexUtils.stripDocMapIfOversized( + doc, SearchClusterMetrics.DEFAULT_BULK_PAYLOAD_SIZE_BYTES, entityId, entityType); + ScriptedPartialUpdate relationshipDocumentUpdate = + buildRelationshipDocumentUpdate(entity, doc); + if (relationshipDocumentUpdate != null) { + scriptTxt = relationshipDocumentUpdate.script(); + doc = relationshipDocumentUpdate.parameters(); + } + } } searchClient.updateEntity(getWriteIndexName(indexMapping), entityId, doc, scriptTxt); @@ -1759,10 +1842,25 @@ public void updateEntitiesByReference(List references) { * @param entities List of entities to update in the search index */ public void updateEntitiesIndex(List entities) { + updateEntitiesIndexInternal(entities, Map.of()); + } + + public void updateEntitiesIndex( + List entities, Map relationshipRevisions) { + updateEntitiesIndexInternal(entities, relationshipRevisions); + } + + private void updateEntitiesIndexInternal( + List entities, Map suppliedRelationshipRevisions) { if (entities == null || entities.isEmpty()) { return; } + Map relationshipRevisions = + suppliedRelationshipRevisions == null + ? Map.of() + : Map.copyOf(suppliedRelationshipRevisions); + // Keep only the latest state per (entityType, entityId) within the same bulk call. // This avoids repeated writes/propagation for duplicates in a single request. Map dedupedEntities = new LinkedHashMap<>(); @@ -1841,6 +1939,9 @@ public void updateEntitiesIndex(List entities) { Map contextData = new HashMap<>(); contextData.put(ReindexingUtil.ENTITY_TYPE_KEY, entityType); contextData.put(BulkSink.SCRIPTED_PARTIAL_UPDATES_CONTEXT_KEY, true); + if (!relationshipRevisions.isEmpty()) { + contextData.put(BulkSink.RELATIONSHIP_REVISIONS_CONTEXT_KEY, relationshipRevisions); + } ReindexingUtil.populateDocBuildContext(contextData, entityType, typeEntities); bulkWriteAttempted = true; bulkSink.write(typeEntities, contextData); @@ -1867,7 +1968,12 @@ public void updateEntitiesIndex(List entities) { if (!bulkWriteAttempted) { for (EntityInterface entity : typeEntities) { try { - updateEntityIndex(entity); + Long relationshipRevision = relationshipRevisions.get(entity.getId()); + if (relationshipRevision == null) { + updateEntityIndex(entity); + } else { + updateEntityIndex(entity, relationshipRevision); + } } catch (Exception ex) { LOG.error( "Error updating entity {} in search index", entity.getFullyQualifiedName(), ex); @@ -3149,12 +3255,8 @@ public String getScriptWithParams( ChangeDescription changeDescription) { List fieldsAdded = changeDescription.getFieldsAdded(); StringBuilder scriptTxt = new StringBuilder(); - List> testSuitesAdded = new ArrayList<>(); - List testSuiteIdsDeleted = new ArrayList<>(); - if (!BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS.equals(getChangedFieldNames(changeDescription))) { - fieldAddParams.put("updatedAt", entity.getUpdatedAt()); - scriptTxt.append("ctx._source.updatedAt=params.updatedAt;"); - } + fieldAddParams.put("updatedAt", entity.getUpdatedAt()); + scriptTxt.append("ctx._source.updatedAt=params.updatedAt;"); for (FieldChange fieldChange : fieldsAdded) { if (fieldChange.getName().equalsIgnoreCase(FIELD_FOLLOWERS)) { @SuppressWarnings("unchecked") @@ -3179,9 +3281,6 @@ public String getScriptWithParams( fieldAddParams.put(FIELD_DESCRIPTION, entity.getDescription()); scriptTxt.append("ctx._source.description = params.description;"); } - if (fieldChange.getName().equalsIgnoreCase(TEST_SUITES)) { - testSuitesAdded.addAll(getTestSuiteValues(fieldChange.getNewValue())); - } } for (FieldChange fieldChange : changeDescription.getFieldsDeleted()) { @@ -3197,13 +3296,6 @@ public String getScriptWithParams( if (fieldChange.getName().equalsIgnoreCase(FIELD_DESCRIPTION)) { scriptTxt.append("ctx._source.description = null;"); } - if (fieldChange.getName().equalsIgnoreCase(TEST_SUITES)) { - getTestSuiteValues(fieldChange.getOldValue()).stream() - .map(testSuite -> testSuite.get(ID)) - .filter(Objects::nonNull) - .map(Object::toString) - .forEach(testSuiteIdsDeleted::add); - } } for (FieldChange fieldChange : changeDescription.getFieldsUpdated()) { @@ -3246,42 +3338,49 @@ public String getScriptWithParams( scriptTxt.append("ctx._source.extension = params.extension;"); } } - if (!testSuitesAdded.isEmpty() || !testSuiteIdsDeleted.isEmpty()) { - fieldAddParams.put(TEST_SUITES_ADDED_PARAM, testSuitesAdded); - fieldAddParams.put(TEST_SUITE_IDS_DELETED_PARAM, testSuiteIdsDeleted); - scriptTxt.append(TEST_SUITES_DELTA_SCRIPT); - } return scriptTxt.toString(); } public ScriptedPartialUpdate buildBulkScriptedPartialUpdate(EntityInterface entity) { - if (entity == null) { - return null; - } - ChangeDescription changeDescription = getEffectiveChangeDescription(entity); - if (!BULK_PARTIAL_SCRIPT_SUPPORTED_FIELDS.equals(getChangedFieldNames(changeDescription)) - || hasTestSuiteReplacement(changeDescription)) { - return null; - } - boolean isNonVersionedUpdate = - entity.getChangeDescription() != null - && Objects.equals( - entity.getVersion(), entity.getChangeDescription().getPreviousVersion()); - if (!isNonVersionedUpdate) { + return buildBulkScriptedPartialUpdate(entity, null); + } + + public ScriptedPartialUpdate buildRelationshipDocumentUpdate( + EntityInterface entity, Map document) { + RelationshipRevisionSpec revisionSpec = relationshipRevisionSpec(entity); + if (revisionSpec == null || document == null) { return null; } - return buildScriptedPartialUpdate(entity, changeDescription, isNonVersionedUpdate); + return new ScriptedPartialUpdate( + revisionSpec.documentUpdateScript(), new HashMap<>(document), true); } - private List> getTestSuiteValues(Object value) { - if (value == null) { - return List.of(); + public ScriptedPartialUpdate buildBulkScriptedPartialUpdate( + EntityInterface entity, Long relationshipRevision) { + RelationshipRevisionSpec revisionSpec = relationshipRevisionSpec(entity); + if (revisionSpec == null || relationshipRevision == null) { + return null; } - List values = value instanceof List list ? list : List.of(value); - return values.stream() - .map(JsonUtils::getMap) - .filter(testSuite -> testSuite.get(ID) != null) - .toList(); + ChangeDescription changeDescription = getEffectiveChangeDescription(entity); + if (changeDescription != null) { + if (!Set.of(revisionSpec.relationshipField()).equals(getChangedFieldNames(changeDescription)) + || !hasRelationshipReplacement(changeDescription, revisionSpec.relationshipField())) { + return null; + } + boolean isNonVersionedUpdate = + entity.getChangeDescription() != null + && Objects.equals( + entity.getVersion(), entity.getChangeDescription().getPreviousVersion()); + if (!isNonVersionedUpdate) { + return null; + } + } + Map parameters = new HashMap<>(); + Object relationships = JsonUtils.getMap(entity).get(revisionSpec.relationshipField()); + parameters.put( + revisionSpec.relationshipField(), relationships == null ? List.of() : relationships); + parameters.put(revisionSpec.revisionField(), relationshipRevision); + return new ScriptedPartialUpdate(revisionSpec.replacementScript(), parameters); } private ScriptedPartialUpdate buildScriptedPartialUpdate( @@ -3305,13 +3404,15 @@ private boolean canUseScriptedPartialUpdate(ChangeDescription changeDescription) Set changedFieldNames = getChangedFieldNames(changeDescription); return !changedFieldNames.isEmpty() && changedFieldNames.stream().allMatch(PARTIAL_SCRIPT_SUPPORTED_FIELDS::contains) - && !hasTestSuiteReplacement(changeDescription); + && !hasRelationshipReplacement(changeDescription, TEST_SUITES) + && !hasRelationshipReplacement(changeDescription, TESTS); } - private boolean hasTestSuiteReplacement(ChangeDescription changeDescription) { + private boolean hasRelationshipReplacement( + ChangeDescription changeDescription, String relationshipField) { return changeDescription != null && listOrEmpty(changeDescription.getFieldsUpdated()).stream() - .anyMatch(fieldChange -> TEST_SUITES.equals(fieldChange.getName())); + .anyMatch(fieldChange -> relationshipField.equals(fieldChange.getName())); } private Set getChangedFieldNames(ChangeDescription changeDescription) { diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java index ea06b20762c7..8b1f41fab793 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/indexes/DocBuildContext.java @@ -30,31 +30,49 @@ *

  • {@link ServiceStylePrefetch#prefetched(Optional)} with a value — prefetched style to apply. * * + *

    {@code relationshipRevision} is {@code null} when it was not prefetched and a non-null + * monotonic revision (including zero for no relationship changes yet) when the caller loaded it in + * bulk. + * * The context is passed by value down the doc-build call chain; nothing is stored in thread-local * state, so callers and mixins see the dependency in their method signatures. */ public record DocBuildContext( - List prefetchedUpstreamLineage, ServiceStylePrefetch serviceStylePrefetch) { + List prefetchedUpstreamLineage, + ServiceStylePrefetch serviceStylePrefetch, + Long relationshipRevision) { private static final DocBuildContext EMPTY = - new DocBuildContext(null, ServiceStylePrefetch.notPrefetched()); + new DocBuildContext(null, ServiceStylePrefetch.notPrefetched(), null); public DocBuildContext { serviceStylePrefetch = serviceStylePrefetch == null ? ServiceStylePrefetch.notPrefetched() : serviceStylePrefetch; } + public DocBuildContext( + List prefetchedUpstreamLineage, ServiceStylePrefetch serviceStylePrefetch) { + this(prefetchedUpstreamLineage, serviceStylePrefetch, null); + } + public static DocBuildContext empty() { return EMPTY; } public static DocBuildContext withUpstreamLineage(List upstreamLineage) { - return new DocBuildContext(upstreamLineage, ServiceStylePrefetch.notPrefetched()); + return new DocBuildContext(upstreamLineage, ServiceStylePrefetch.notPrefetched(), null); } public static DocBuildContext of( List upstreamLineage, ServiceStylePrefetch serviceStylePrefetch) { - return new DocBuildContext(upstreamLineage, serviceStylePrefetch); + return new DocBuildContext(upstreamLineage, serviceStylePrefetch, null); + } + + public static DocBuildContext of( + List upstreamLineage, + ServiceStylePrefetch serviceStylePrefetch, + Long relationshipRevision) { + return new DocBuildContext(upstreamLineage, serviceStylePrefetch, relationshipRevision); } public record ServiceStylePrefetch(boolean prefetched, Optional