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..a9d7c1a4e68f --- /dev/null +++ b/.github/scripts/classify_test_outcome.py @@ -0,0 +1,257 @@ +"""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"(?:\bfork(?:ed)?(?:\s+(?:process|vm))?\b|\btest process\b|\bcommand\b|\bprocess\b)" + r".{0,80}\b(?:timed out|timeout)\b|" + r"\b(?:timed out|timeout)\b.{0,80}" + r"(?:\bfork(?:ed)?(?:\s+(?:process|vm))?\b|\btest process\b|\bcommand\b|\bprocess\b)", + 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 ( + step_outcome != "success" and _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/configure_docker_storage.sh b/.github/scripts/configure_docker_storage.sh new file mode 100644 index 000000000000..73cc04a49426 --- /dev/null +++ b/.github/scripts/configure_docker_storage.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash + +set -euo pipefail + +readonly docker_root="/mnt/docker" +readonly minimum_free_kb=$((32 * 1024 * 1024)) + +if [[ ! -d /mnt ]]; then + echo "::error::The runner does not provide /mnt" + exit 1 +fi + +if [[ "$(stat -c '%d' /)" == "$(stat -c '%d' /mnt)" ]]; then + available_kb="$(df --output=avail -k / | tail -n 1)" + if ((available_kb < minimum_free_kb)); then + echo "::error::The runner root has ${available_kb} KiB free; ${minimum_free_kb} KiB is required" + df -h / /mnt + exit 1 + fi + + echo "The runner uses one filesystem with ${available_kb} KiB free; keeping the existing Docker root" + docker info --format 'Docker root: {{.DockerRootDir}}' + df -h / /mnt + exit 0 +fi + +daemon_config="$(mktemp)" +trap 'rm -f "$daemon_config"' EXIT + +if sudo test -s /etc/docker/daemon.json; then + sudo jq --arg root "$docker_root" '. + {"data-root": $root}' \ + /etc/docker/daemon.json | tee "$daemon_config" > /dev/null +else + jq -n --arg root "$docker_root" '{"data-root": $root}' > "$daemon_config" +fi + +sudo systemctl stop docker +sudo rm -rf "$docker_root" +sudo mkdir -p "$docker_root" +sudo install -m 0644 "$daemon_config" /etc/docker/daemon.json +sudo systemctl start docker + +actual_root="$(docker info --format '{{.DockerRootDir}}')" +if [[ "$actual_root" != "$docker_root" ]]; then + echo "::error::Docker data root is $actual_root; expected $docker_root" + exit 1 +fi + +docker info --format 'Docker root: {{.DockerRootDir}}' +df -h / /mnt 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..48a824ecadc7 --- /dev/null +++ b/.github/scripts/test_classify_test_outcome.py @@ -0,0 +1,198 @@ +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_timeout_configuration_does_not_mark_successful_run_as_hung( + tmp_path: Path, +) -> None: + report = write_report( + tmp_path / "TEST-pass.xml", + '' + '', + ) + diagnostic = write_report( + tmp_path / "maven.log", + "Redis cache provider initialized (commandTimeoutMs=1000)", + ) + + result = CLASSIFIER.classify_outcome("success", 0, [report], [diagnostic]) + + assert result["classification"] == "passed" + + +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 4c05a5881159..d35632d5e269 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 @@ -512,6 +548,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 @@ -521,6 +558,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..562b09e80a95 100644 --- a/.github/workflows/playwright-integration-tests-mysql.yml +++ b/.github/workflows/playwright-integration-tests-mysql.yml @@ -17,12 +17,16 @@ 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' }} 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 +35,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 +70,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 +80,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 +109,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..57ca9ff6a69a 100644 --- a/.github/workflows/playwright-integration-tests-postgres.yml +++ b/.github/workflows/playwright-integration-tests-postgres.yml @@ -17,12 +17,16 @@ 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' }} 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 +35,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 +70,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 +80,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 +109,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 4839fbab7ccd..3fad8aa3656c 100644 --- a/.github/workflows/py-tests-postgres.yml +++ b/.github/workflows/py-tests-postgres.yml @@ -18,34 +18,69 @@ 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/configure_docker_storage.sh' + - '.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 @@ -75,7 +110,7 @@ jobs: --ignore=tests/integration/sql_server steps: - name: Free Disk Space (Ubuntu) - uses: jlumbroso/free-disk-space@main + uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be with: tool-cache: false android: true @@ -85,28 +120,14 @@ 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: Use runner data disk for Docker + if: matrix.shard.name == 'shard-2' + run: bash .github/scripts/configure_docker_storage.sh - name: Setup Openmetadata Test Environment uses: ./.github/actions/setup-openmetadata-test-environment @@ -115,29 +136,138 @@ 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 info > "$diagnostics/docker-info.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 + 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-postgres / py-tests-status" as the sole required check for this workflow. + # Keep the existing required context until the repository ruleset is migrated atomically. 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-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 5de3c2673b00..29bab3b33530 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,41 @@ 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/configure_docker_storage.sh' + - '.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 +78,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 +120,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 @@ -154,7 +202,7 @@ jobs: --ignore=tests/integration/sql_server steps: - name: Free Disk Space (Ubuntu) - uses: jlumbroso/free-disk-space@main + uses: jlumbroso/free-disk-space@54081f138730dfa15788a46383842cd2f914a1be with: tool-cache: false android: true @@ -164,28 +212,14 @@ 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: Use runner data disk for Docker + if: matrix.shard.name == 'shard-2' + run: bash .github/scripts/configure_docker_storage.sh - name: Setup Openmetadata Test Environment uses: ./.github/actions/setup-openmetadata-test-environment @@ -194,61 +228,163 @@ 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 info > "$diagnostics/docker-info.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 @@ -307,20 +443,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/.github/workflows/ui-checkstyle.yml b/.github/workflows/ui-checkstyle.yml index a2cfc2fc93b2..5abd08e7e17d 100644 --- a/.github/workflows/ui-checkstyle.yml +++ b/.github/workflows/ui-checkstyle.yml @@ -299,6 +299,7 @@ jobs: uses: peter-evans/find-comment@v3 id: fc if: ${{ github.event_name == 'pull_request_target' }} + continue-on-error: true with: issue-number: ${{ github.event.pull_request.number }} comment-author: github-actions[bot] @@ -306,7 +307,8 @@ jobs: - name: Post or update summary comment uses: actions/github-script@v7 - if: ${{ github.event_name == 'pull_request_target' }} + if: ${{ github.event_name == 'pull_request_target' && steps.fc.outcome == 'success' }} + continue-on-error: true with: script: | const checks = [ diff --git a/Makefile b/Makefile index b7c7289bba17..089aba1c724f 100644 --- a/Makefile +++ b/Makefile @@ -60,10 +60,37 @@ generate: ## Generate the pydantic models from the JSON Schemas to the ingestio $(MAKE) install .PHONY: install_antlr_cli +ANTLR_VERSION := 4.9.2 +ANTLR_COMPLETE_JAR_URL := https://repo1.maven.org/maven2/org/antlr/antlr4/$(ANTLR_VERSION)/antlr4-$(ANTLR_VERSION)-complete.jar +ANTLR_COMPLETE_JAR_SHA256 := bb117b1476691dc2915a318efd36f8957c0ad93447fb1dac01107eb15fe137cd +ANTLR_INSTALL_DIR ?= /usr/local/bin + install_antlr_cli: ## Install antlr CLI locally - echo '#!/usr/bin/java -jar' > /usr/local/bin/antlr4 - curl https://www.antlr.org/download/antlr-4.9.2-complete.jar >> /usr/local/bin/antlr4 - chmod 755 /usr/local/bin/antlr4 + @set -eu; \ + jar_file=$$(mktemp); \ + cli_file=$$(mktemp "$(ANTLR_INSTALL_DIR)/.antlr4.XXXXXX"); \ + trap 'rm -f "$$jar_file" "$$cli_file"' EXIT; \ + attempt=1; \ + while :; do \ + if curl --fail --location --silent --show-error \ + --retry 3 --retry-all-errors --retry-delay 2 --retry-max-time 120 \ + --connect-timeout 15 --max-time 60 \ + --output "$$jar_file" "$(ANTLR_COMPLETE_JAR_URL)" \ + && printf '%s %s\n' "$(ANTLR_COMPLETE_JAR_SHA256)" "$$jar_file" | shasum -a 256 --check \ + && jar tf "$$jar_file" > /dev/null; then \ + break; \ + fi; \ + if [ "$$attempt" -ge 3 ]; then \ + echo "Failed to download a valid ANTLR $(ANTLR_VERSION) CLI after $$attempt attempts" >&2; \ + exit 1; \ + fi; \ + attempt=$$((attempt + 1)); \ + sleep 2; \ + done; \ + printf '%s\n' '#!/usr/bin/java -jar' > "$$cli_file"; \ + cat "$$jar_file" >> "$$cli_file"; \ + chmod 755 "$$cli_file"; \ + mv "$$cli_file" "$(ANTLR_INSTALL_DIR)/antlr4" ## SNYK SNYK_ARGS := --severity-threshold=high diff --git a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql index b052504fd32d..005991ada0d5 100644 --- a/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/mysql/schemaChanges.sql @@ -366,11 +366,31 @@ CREATE TABLE IF NOT EXISTS search_index_retry_queue ( entityType VARCHAR(128) NOT NULL, retryCount INT NOT NULL DEFAULT 0, claimedAt TIMESTAMP NULL DEFAULT NULL, + claimToken VARCHAR(36) DEFAULT NULL, PRIMARY KEY (entityId, entityFqn), KEY idx_search_index_retry_queue_status (status), KEY idx_search_index_retry_queue_claimed_at (claimedAt) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; +-- Migration statements are deduplicated by checksum. Use a block-specific prepared statement +-- name so earlier PREPARE/EXECUTE helpers in this file cannot suppress this ALTER. +SET @search_index_retry_claim_token_ddl = ( + SELECT IF( + EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 'search_index_retry_queue' + AND column_name = 'claimToken' + ), + 'SELECT 1', + 'ALTER TABLE search_index_retry_queue ADD COLUMN claimToken VARCHAR(36) DEFAULT NULL' + ) +); +PREPARE search_index_retry_claim_token_stmt FROM @search_index_retry_claim_token_ddl; +EXECUTE search_index_retry_claim_token_stmt; +DEALLOCATE PREPARE search_index_retry_claim_token_stmt; + -- ContextMemory entity - reusable Context Center memory. CREATE TABLE IF NOT EXISTS context_memory ( id VARCHAR(36) GENERATED ALWAYS AS (json ->> '$.id') STORED NOT NULL, diff --git a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql index 1a975f20b3a4..278bf314cd43 100644 --- a/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql +++ b/bootstrap/sql/migrations/native/2.0.0/postgres/schemaChanges.sql @@ -317,8 +317,10 @@ CREATE TABLE IF NOT EXISTS search_index_retry_queue ( entityType VARCHAR(128) NOT NULL, retryCount INTEGER NOT NULL DEFAULT 0, claimedAt TIMESTAMP NULL, + claimToken VARCHAR(36) NULL, PRIMARY KEY (entityId, entityFqn) ); +ALTER TABLE search_index_retry_queue ADD COLUMN IF NOT EXISTS claimToken VARCHAR(36) NULL; CREATE INDEX IF NOT EXISTS idx_search_index_retry_queue_status ON search_index_retry_queue (status); CREATE INDEX IF NOT EXISTS idx_search_index_retry_queue_claimed_at diff --git a/ingestion/src/metadata/ingestion/source/database/exasol/queries.py b/ingestion/src/metadata/ingestion/source/database/exasol/queries.py index 6bc382e5cb7a..876810a22b03 100644 --- a/ingestion/src/metadata/ingestion/source/database/exasol/queries.py +++ b/ingestion/src/metadata/ingestion/source/database/exasol/queries.py @@ -15,7 +15,9 @@ WHERE s.sql_text NOT LIKE '/* {{"app": "OpenMetadata", %%}} */%%' AND s.success = TRUE AND s.sql_text NOT LIKE '/* {{"app": "dbt", %%}} */%%' - AND s.start_time between TO_TIMESTAMP('{start_time}') and TO_TIMESTAMP('{end_time}') + AND s.start_time between + CONVERT_TZ(TO_TIMESTAMP('{start_time}'), 'UTC', DBTIMEZONE) + AND CONVERT_TZ(TO_TIMESTAMP('{end_time}'), 'UTC', DBTIMEZONE) {filters} LIMIT {result_limit} """ diff --git a/ingestion/tests/integration/conftest.py b/ingestion/tests/integration/conftest.py index ccfa7882e0e8..9ab64a0b6a84 100644 --- a/ingestion/tests/integration/conftest.py +++ b/ingestion/tests/integration/conftest.py @@ -38,10 +38,11 @@ def _package_of(item) -> str | None: def _prune_docker_images() -> None: import docker from docker.errors import DockerException + from requests.exceptions import RequestException try: reclaimed = docker.from_env().images.prune(filters={"dangling": False}).get("SpaceReclaimed", 0) - except DockerException: + except (DockerException, RequestException): logging.exception("Failed to prune docker images") return logging.info( diff --git a/ingestion/tests/integration/data_quality/test_data_diff.py b/ingestion/tests/integration/data_quality/test_data_diff.py index fddac1e50fa6..fadc59084b79 100644 --- a/ingestion/tests/integration/data_quality/test_data_diff.py +++ b/ingestion/tests/integration/data_quality/test_data_diff.py @@ -1,13 +1,12 @@ -from datetime import datetime # noqa: I001 +import random +from datetime import datetime import pytest from dirty_equals import IsApprox, IsPositiveInt from pydantic import BaseModel -from sqlalchemy import VARBINARY +from sqlalchemy import VARBINARY, MetaData, create_engine, text from sqlalchemy import Column as SQAColumn -from sqlalchemy import MetaData from sqlalchemy import Table as SQATable -from sqlalchemy import create_engine, text from sqlalchemy.dialects import postgresql from sqlalchemy.engine import Connection, make_url from sqlalchemy.sql import sqltypes @@ -36,6 +35,7 @@ class TestParameters(BaseModel): table2_fqn: str expected: TestCaseResult table_profile_config: TableProfilerConfig = None + deterministic_sample_salt: str | None = None def __init__(self, *args, **kwargs): if args: @@ -105,13 +105,11 @@ def __init__(self, *args, **kwargs): ], ), "POSTGRES_SERVICE.dvdrental.public.customer", - TestCaseResult.model_construct( + TestCaseResult( timestamp=int(datetime.now().timestamp() * 1000), testCaseStatus=TestCaseStatus.Success, failedRows=0, - # we use approximations around the 99.5 confidence interval since the - # sampling in data diff uses hash based partitioning - passedRows=IsApprox(10, delta=15) & IsPositiveInt, + passedRows=11, ), TableProfilerConfig( profileSampleConfig=ProfileSampleConfig( @@ -122,6 +120,7 @@ def __init__(self, *args, **kwargs): }, ), ), + "abcde", ), ( TestCaseDefinition( @@ -366,6 +365,7 @@ def test_happy_paths( prepare_data, ingest_postgres_metadata, ingest_mysql_service, + monkeypatch: pytest.MonkeyPatch, patched_metadata, parameters: TestParameters, sink_config, @@ -408,6 +408,9 @@ def test_happy_paths( ) if parameters.table_profile_config: metadata.create_or_update_table_profiler_config(table1.fullyQualifiedName.root, parameters.table_profile_config) + if parameters.deterministic_sample_salt: + sample_salt = parameters.deterministic_sample_salt + monkeypatch.setattr(random, "choices", lambda *_args, **_kwargs: list(sample_salt)) workflow_config = { "source": { "type": "postgres", 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/sources/database/exasol/base.py b/ingestion/tests/integration/sources/database/exasol/base.py index 58843ff56b28..2338acaf445d 100644 --- a/ingestion/tests/integration/sources/database/exasol/base.py +++ b/ingestion/tests/integration/sources/database/exasol/base.py @@ -20,6 +20,9 @@ DB_PORT = 8563 CONTAINER_SUFFIX = "exasolquery" CONTAINER_NAME = f"db_container_{CONTAINER_SUFFIX}" +DOCKER_IMAGE = f"exasol/docker-db:{DB_VERSION}" +DOCKER_PULL_ATTEMPTS = 3 +DOCKER_PULL_RETRY_SECONDS = 10 SCHEMA_NAME = "OPENMETADATA_QUERY_TEST" TABLE_NAME = "DATATYPES" SIMILAR_TABLE_NAME = f"{TABLE_NAME}_EXTRA" @@ -101,12 +104,31 @@ def _prepare_exasol_objects(engine: Engine) -> None: connection.execute(text(statement)) +def _ensure_exasol_image() -> None: + image_inspect = subprocess.run( + ["docker", "image", "inspect", DOCKER_IMAGE], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + if image_inspect.returncode == 0: + return + + for attempt in range(1, DOCKER_PULL_ATTEMPTS + 1): + pull_result = subprocess.run(["docker", "pull", DOCKER_IMAGE], check=False) + if pull_result.returncode == 0: + return + if attempt == DOCKER_PULL_ATTEMPTS: + pull_result.check_returncode() + sleep(DOCKER_PULL_RETRY_SECONDS) + + class ExasolTestBase: engine: ClassVar[Engine] @classmethod def setup_class(cls): - subprocess.run(["docker", "pull", f"exasol/docker-db:{DB_VERSION}"], check=True) + _ensure_exasol_image() subprocess.run( [ "itde", diff --git a/ingestion/tests/integration/sources/database/exasol/test_usage.py b/ingestion/tests/integration/sources/database/exasol/test_usage.py index b184abb506bb..3d7447e63264 100644 --- a/ingestion/tests/integration/sources/database/exasol/test_usage.py +++ b/ingestion/tests/integration/sources/database/exasol/test_usage.py @@ -156,15 +156,22 @@ def test_usage_workflow_publishes_stage_data(self, metadata, tmp_path): ) ) + target_query_filter = f""" + UPPER(s.sql_text) LIKE '%FROM {SCHEMA_NAME}.{TABLE_NAME}%' + OR UPPER(s.sql_text) LIKE '%FROM {SCHEMA_NAME}.{VIEW_NAME}%' + """ wait_for_system_table( self.engine, EXASOL_SQL_STATEMENT.format( start_time="2000-01-01 00:00:00", end_time="2999-01-01 00:00:00", - filters="", + filters=f""" + AND s.command_name = 'SELECT' + AND ({target_query_filter}) + """, result_limit=10, ), - expected_count=3, + expected_count=2, timeout_seconds=120, ) @@ -178,6 +185,7 @@ def test_usage_workflow_publishes_stage_data(self, metadata, tmp_path): "type": DatabaseUsageConfigType.DatabaseUsage.value, "queryLogDuration": 1, "resultLimit": 10000, + "filterCondition": target_query_filter, } }, }, @@ -208,7 +216,7 @@ def test_usage_workflow_publishes_stage_data(self, metadata, tmp_path): usage_counts = {table: value.count for (table, _), value in table_usage.items()} assert any(TABLE_NAME.lower() in table.lower() for table in usage_counts) - assert sum(usage_counts.values()) >= 3 + assert sum(usage_counts.values()) >= 2 recorded_queries = [ query for queries in table_queries.values() for query in queries if query.query and query.query.root diff --git a/ingestion/tests/integration/trino/conftest.py b/ingestion/tests/integration/trino/conftest.py index 3107813d042c..111f0bcd58e9 100644 --- a/ingestion/tests/integration/trino/conftest.py +++ b/ingestion/tests/integration/trino/conftest.py @@ -2,15 +2,15 @@ import random import uuid from pathlib import Path -from time import sleep import docker 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 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 @@ -31,6 +31,14 @@ from ..conftest import ingestion_config as base_ingestion_config # noqa: F401, TID252 +HIVE_METASTORE_IMAGE = ( + "bitsondatadev/hive-metastore@sha256:b44a186b6dcffafc6a72327aaa5912a5824feecb50718aaf661727ff6aef011b" +) + + +class TrinoTableNotReadyError(RuntimeError): + pass + class TrinoContainer(DbContainer): def __init__( @@ -167,7 +175,7 @@ def mysql_container(docker_network): @pytest.fixture(scope="package") def hive_metastore_container(mysql_container, minio_container, docker_network): with ( - HiveMetaStoreContainer("bitsondatadev/hive-metastore:latest") + HiveMetaStoreContainer(HIVE_METASTORE_IMAGE) .with_network(docker_network) .with_network_aliases("metastore") .with_env("METASTORE_DB_HOSTNAME", "mariadb") @@ -213,17 +221,50 @@ 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')") + engine.dispose() return -def create_test_data_from_parquet(engine: Engine, file_path: Path): +@pytest.fixture(scope="package") +def reset_trino_table_statistics(trino_container, create_test_data): + engine = create_engine(make_url(trino_container.get_connection_url()).set(database="minio")) + + def reset(table_name: str) -> None: + with engine.connect() as conn: + conn.execute(text(f"CALL system.drop_stats(schema_name => 'my_schema', table_name => '{table_name}')")) + conn.commit() + + with engine.connect() as conn: + conn.execute( + text(f"CALL system.flush_metadata_cache(schema_name => 'my_schema', table_name => '{table_name}')") + ) + conn.commit() + + with engine.connect() as conn: + rows = conn.execute(text(f'SHOW STATS FOR "my_schema"."{table_name}"')) + table_statistics = [row._asdict() for row in rows if row._asdict().get("column_name") is None] + + if len(table_statistics) != 1: + raise AssertionError( + f"Expected one table statistics row for [my_schema.{table_name}], got [{len(table_statistics)}]" + ) + if table_statistics[0].get("row_count") is not None: + raise AssertionError( + f"Expected missing row-count statistics for [my_schema.{table_name}], " + f"got [{table_statistics[0].get('row_count')}]" + ) + + yield reset + engine.dispose() + + +def create_test_data_from_parquet(engine: Engine, file_path: Path) -> int: df = pd.read_parquet(file_path) # Convert data types @@ -239,9 +280,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() @@ -254,25 +296,51 @@ 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 - stmt = insert(self.table).values(data) - conn.execute(stmt) - rowcount = conn.execute(text("SELECT COUNT(*) FROM " + f'"{self.schema}"."{self.name}"')).scalar() - return rowcount + """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") diff --git a/ingestion/tests/integration/trino/hive/Dockerfile b/ingestion/tests/integration/trino/hive/Dockerfile index 576c37d40a35..eec58520002e 100644 --- a/ingestion/tests/integration/trino/hive/Dockerfile +++ b/ingestion/tests/integration/trino/hive/Dockerfile @@ -1,4 +1,4 @@ -ARG BASE_IMAGE=bitsondatadev/hive-metastore:latest +ARG BASE_IMAGE=bitsondatadev/hive-metastore@sha256:b44a186b6dcffafc6a72327aaa5912a5824feecb50718aaf661727ff6aef011b FROM ${BASE_IMAGE} COPY conf/metastore-site.xml /opt/apache-hive-metastore-3.0.0-bin/conf/metastore-site.xml COPY entrypoint.sh /entrypoint.sh @@ -6,4 +6,4 @@ ENV JDBC_CONNECTION_URL="" ENV MINIO_ENDPOINT="" USER root RUN chmod +x /entrypoint.sh -USER hive \ No newline at end of file +USER hive diff --git a/ingestion/tests/integration/trino/test_profiler.py b/ingestion/tests/integration/trino/test_profiler.py index 131cc3b99177..28a93fe3416b 100644 --- a/ingestion/tests/integration/trino/test_profiler.py +++ b/ingestion/tests/integration/trino/test_profiler.py @@ -37,11 +37,15 @@ def run_profiler( ingestion_config, profiler_config, create_test_data, + reset_trino_table_statistics, request, ): search_cache.clear() profiler_config = deepcopy(profiler_config) merge(request.param, profiler_config) + source_config = DatabaseServiceProfilerPipeline.model_validate(profiler_config["source"]["sourceConfig"]["config"]) + if source_config.useStatistics: + reset_trino_table_statistics("empty") run_workflow(MetadataWorkflow, ingestion_config) run_workflow(ProfilerWorkflow, profiler_config) return profiler_config @@ -167,6 +171,8 @@ def test_profiler(run_profiler, metadata, db_service, parameters: ProfilerTestPa table: Table = metadata.get_latest_table_profile( parameters.table_fqn.format(database_service=db_service.fullyQualifiedName.root) ) + if parameters.expected_table_profile.rowCount is None: + assert table.profile.rowCount is None, "expected row count to remain absent when statistics are unavailable" assert_equal_pydantic_objects( parameters.expected_table_profile, # we dont want to validate the timestamp because it will be different for each run @@ -180,26 +186,3 @@ def test_profiler(run_profiler, metadata, db_service, parameters: ProfilerTestPa profile, column.profile.model_copy(update={"timestamp": profile.timestamp}), ) - - -@pytest.mark.parametrize( - "parameters", - [ - ProfilerTestParameters( - "{database_service}.minio.my_schema.empty", - TableProfile(timestamp=Timestamp(0), rowCount=None), - [], - lambda x: x.useStatistics == True, # noqa: E712 - ), - ], - ids=lambda x: x.table_fqn.split(".")[-1], -) -def test_no_statistics(run_profiler, metadata, db_service, parameters: ProfilerTestParameters): - if not parameters.config_predicate( - DatabaseServiceProfilerPipeline.model_validate(run_profiler["source"]["sourceConfig"]["config"]) - ): - pytest.skip("Skipping test becuase its not supported for this profiler configuation") - table: Table = metadata.get_latest_table_profile( - parameters.table_fqn.format(database_service=db_service.fullyQualifiedName.root) - ) - assert table.profile.rowCount is None, "expected empty row count for a table with no collected statistics" diff --git a/ingestion/tests/integration/trino/test_table_metric_computer_trino.py b/ingestion/tests/integration/trino/test_table_metric_computer_trino.py index d14d582ac044..d228e5dfd55f 100644 --- a/ingestion/tests/integration/trino/test_table_metric_computer_trino.py +++ b/ingestion/tests/integration/trino/test_table_metric_computer_trino.py @@ -41,12 +41,6 @@ class TitanicModel(Base): name = Column(String(256)) -class EmptyModel(Base): - __tablename__ = "empty" - __table_args__ = {"schema": "my_schema"} # noqa: RUF012 - id = Column(Integer, primary_key=True) - - @pytest.fixture(scope="module") def trino_engine(trino_container, create_test_data): engine = create_engine(make_url(trino_container.get_connection_url()).set(database="minio")) @@ -106,18 +100,3 @@ def test_show_stats_returns_column_metadata(self, trino_session): assert "passengerid" in result.columnNames assert "name" in result.columnNames fallback.assert_not_called() - - def test_empty_table_with_dropped_stats_falls_back(self, trino_session): - """empty table had stats dropped — SHOW STATS returns NULL row_count. - Should fall back to COUNT(*).""" - computer = _build_computer(trino_session, EmptyModel) - fallback_result = Mock(rowCount=0, columnCount=None, sizeInBytes=None, columnNames=None, createDateTime=None) - with patch.object( - BaseTableMetricComputer, - "compute", - return_value=fallback_result, - ) as fallback: - result = computer.compute() - assert result is not None - assert result.rowCount == 0 - fallback.assert_called_once() diff --git a/ingestion/tests/unit/metadata/pii/test_tag_processor_integration.py b/ingestion/tests/unit/metadata/pii/test_tag_processor_integration.py index b26a491eab3e..7f46e9bd93c4 100644 --- a/ingestion/tests/unit/metadata/pii/test_tag_processor_integration.py +++ b/ingestion/tests/unit/metadata/pii/test_tag_processor_integration.py @@ -534,21 +534,21 @@ def test_skip_already_tagged_columns( ], ) - # Create TagProcessor + score_tags_for_column = Mock() processor = TagProcessor( config=workflow_config, metadata=metadata, classification_manager=classification_manager, + score_tags_for_column=score_tags_for_column, max_tags_per_column=10, ) - # Process column tag_labels = processor.create_column_tag_labels(column=column_with_tag, sample_data=sample_email_password_data) - # Should return empty list (tag already applied) assert len(tag_labels) == 0, ( f"Should not re-suggest existing tags, got {len(tag_labels)}: {[l.tagFQN for l in tag_labels]}" # noqa: E741 ) + score_tags_for_column.assert_not_called() def test_idempotent_mutually_exclusive_tags( self, diff --git a/ingestion/tests/unit/topology/database/test_exasol.py b/ingestion/tests/unit/topology/database/test_exasol.py index e61cff5ea0af..7c7825acdbff 100644 --- a/ingestion/tests/unit/topology/database/test_exasol.py +++ b/ingestion/tests/unit/topology/database/test_exasol.py @@ -92,5 +92,5 @@ def test_get_sql_statement(self): assert "EXA_STATISTICS.EXA_DBA_AUDIT_SQL" in sql assert '"aborted"' not in sql assert "LIMIT 250" in sql - assert "TO_TIMESTAMP('2025-01-01 00:00:00')" in sql - assert "TO_TIMESTAMP('2025-01-02 00:00:00')" in sql + assert "CONVERT_TZ(TO_TIMESTAMP('2025-01-01 00:00:00'), 'UTC', DBTIMEZONE)" in sql + assert "CONVERT_TZ(TO_TIMESTAMP('2025-01-02 00:00:00'), 'UTC', DBTIMEZONE)" in sql 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/drive/DriveFileUploadIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/drive/DriveFileUploadIT.java index cf61fbc5f264..f9c8dd319a8b 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/drive/DriveFileUploadIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/drive/DriveFileUploadIT.java @@ -46,6 +46,7 @@ import org.apache.pdfbox.pdmodel.font.PDType1Font; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; +import org.awaitility.core.ConditionTimeoutException; import org.glassfish.jersey.client.ClientProperties; import org.glassfish.jersey.media.multipart.FormDataMultiPart; import org.glassfish.jersey.media.multipart.MultiPartFeature; @@ -87,6 +88,8 @@ class DriveFileUploadIT { private static final Duration EXTRACTION_TIMEOUT = Duration.ofSeconds(60); private static final Duration SEARCH_VISIBLE_TIMEOUT = Duration.ofSeconds(60); private static final Duration POLL_INTERVAL = Duration.ofMillis(500); + private static final int SEARCH_RESULT_SIZE = 100; + private static final int DIAGNOSTIC_BODY_LIMIT = 4000; private static String serverBaseUrl; private static Client multipartClient; private static WebTarget uploadTarget; @@ -263,21 +266,56 @@ private Folder createFolder(TestNamespace ns, String name) throws Exception { private void assertSearchContainsFile(String query, UUID fileId) { RestClient rest = RestClient.admin(); String encodedQuery = URLEncoder.encode(query, StandardCharsets.UTF_8); + String searchPath = + "v1/search/query?q=" + + encodedQuery + + "&index=context_file_search_index&from=0&size=" + + SEARCH_RESULT_SIZE; - await() - .pollInterval(POLL_INTERVAL) - .atMost(SEARCH_VISIBLE_TIMEOUT) - .untilAsserted( - () -> { - try (Response searchResponse = - rest.rawGet( - "v1/search/query?q=" - + encodedQuery - + "&index=context_file_search_index&from=0&size=10")) { - assertEquals(200, searchResponse.getStatus()); - assertTrue(searchResponse.readEntity(String.class).contains(fileId.toString())); - } - }); + try { + await() + .pollInterval(POLL_INTERVAL) + .atMost(SEARCH_VISIBLE_TIMEOUT) + .untilAsserted( + () -> { + try (Response searchResponse = rest.rawGet(searchPath)) { + String responseBody = searchResponse.readEntity(String.class); + assertEquals(200, searchResponse.getStatus(), responseBody); + assertTrue(responseBody.contains(fileId.toString())); + } + }); + } catch (ConditionTimeoutException e) { + throw new AssertionError(searchFailureDiagnostics(rest, searchPath, query, fileId), e); + } + } + + private String searchFailureDiagnostics( + RestClient rest, String searchPath, String query, UUID fileId) { + String searchResponse = readDiagnosticResponse(rest, searchPath); + String indexedDocument = + readDiagnosticResponse( + rest, "v1/search/get/context_file_search_index/doc/" + fileId.toString()); + return "Context file " + + fileId + + " was not searchable for query " + + query + + ". Search response: " + + searchResponse + + ". Indexed document: " + + indexedDocument; + } + + private String readDiagnosticResponse(RestClient rest, String path) { + try (Response response = rest.rawGet(path)) { + String body = response.readEntity(String.class); + String truncatedBody = + body.length() <= DIAGNOSTIC_BODY_LIMIT + ? body + : body.substring(0, DIAGNOSTIC_BODY_LIMIT) + "...[truncated]"; + return "status=" + response.getStatus() + ", body=" + truncatedBody; + } catch (Exception e) { + return "request failed: " + e.getMessage(); + } } private ContextFile awaitProcessed(UUID fileId, String expectedText) { @@ -440,7 +478,12 @@ void testUploadedTextFileIsSearchableByExtractedText(TestNamespace ns) throws Ex .getBytes(StandardCharsets.UTF_8); ContextFile file; - try (Response response = uploadFile("search-fixture.txt", content, "Search Fixture", null)) { + try (Response response = + uploadFile( + uniqueUploadedFileName(ns, "search-fixture.txt"), + content, + ns.shortPrefix("Search Fixture"), + null)) { String body = response.readEntity(String.class); assertEquals(CREATED.getStatusCode(), response.getStatus(), "Upload failed: " + body); file = JsonUtils.readValue(body, ContextFile.class); @@ -458,7 +501,11 @@ void testUploadedPdfIsSearchableByExtractedText(TestNamespace ns) throws Excepti ContextFile file; try (Response response = - uploadFile("search-fixture.pdf", content, ns.shortPrefix("PDF Search"), null)) { + uploadFile( + uniqueUploadedFileName(ns, "search-fixture.pdf"), + content, + ns.shortPrefix("PDF Search"), + null)) { String body = response.readEntity(String.class); assertEquals(CREATED.getStatusCode(), response.getStatus(), "Upload failed: " + body); file = JsonUtils.readValue(body, ContextFile.class); @@ -476,7 +523,11 @@ void testUploadedSpreadsheetIsSearchableByExtractedText(TestNamespace ns) throws ContextFile file; try (Response response = - uploadFile("search-fixture.xlsx", content, ns.shortPrefix("Spreadsheet Search"), null)) { + uploadFile( + uniqueUploadedFileName(ns, "search-fixture.xlsx"), + content, + ns.shortPrefix("Spreadsheet Search"), + null)) { String body = response.readEntity(String.class); assertEquals(CREATED.getStatusCode(), response.getStatus(), "Upload failed: " + body); file = JsonUtils.readValue(body, ContextFile.class); @@ -501,7 +552,11 @@ void testUploadedImageIsSearchableByOcrExtractedText(TestNamespace ns) throws Ex ContextFile file; try (Response response = - uploadFile("search-fixture.png", content, ns.shortPrefix("Image Search"), null)) { + uploadFile( + uniqueUploadedFileName(ns, "search-fixture.png"), + content, + ns.shortPrefix("Image Search"), + null)) { String body = response.readEntity(String.class); assertEquals(CREATED.getStatusCode(), response.getStatus(), "Upload failed: " + body); file = JsonUtils.readValue(body, ContextFile.class); diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/RelevancyFixtures.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/RelevancyFixtures.java index 402c8ae43130..8706d6aff3c5 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/RelevancyFixtures.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/search/RelevancyFixtures.java @@ -56,9 +56,14 @@ public static void reportUsage(final Table table, final int count) { .execute(HttpMethod.POST, "/v1/usage/table/" + table.getId(), usage, EntityUsage.class); } - /** A short token with no shared substring across calls — safe to use as a search query marker. */ + /** An alphabetic token that remains whole under the search word-delimiter analyzer. */ public static String uniqueToken(final String prefix) { - return prefix + UUID.randomUUID().toString().replace("-", "").substring(0, 12); + final String hexSuffix = UUID.randomUUID().toString().replace("-", "").substring(0, 12); + final StringBuilder token = new StringBuilder(prefix); + hexSuffix + .chars() + .forEach(character -> token.append((char) ('g' + Character.digit(character, 16)))); + return token.toString(); } public static TagLabel tierLabel(final String tierFqn) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java index 717d5b7630ad..42b231fd45e6 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/SearchIndexRetryQueueIT.java @@ -129,6 +129,36 @@ void testUpsertOverwritesOnConflict(TestNamespace ns) { retryQueueDAO.deleteByEntity(entityId, entityFqn); } + @Test + void testPlainUpsertPreservesExistingPropagationContext(TestNamespace ns) { + String entityId = UUID.randomUUID().toString(); + String entityFqn = ns.prefix("rq") + ".entity"; + String propagationContext = + "\n" + SearchIndexRetryQueueDAO.PROPAGATION_CONTEXT_TOKEN + "eyJwcmV2aW91c1ZlcnNpb24iOjF9"; + + retryQueueDAO.upsert( + entityId, + entityFqn, + "propagation failure" + propagationContext, + SearchIndexRetryQueue.STATUS_COMPLETED, + "table"); + retryQueueDAO.upsert( + entityId, + entityFqn, + "new indexing failure", + SearchIndexRetryQueue.STATUS_COMPLETED, + "table"); + + SearchIndexRetryRecord record = + retryQueueDAO.findByStatus(SearchIndexRetryQueue.STATUS_COMPLETED, 1000).stream() + .filter(r -> r.getEntityId().equals(entityId)) + .findFirst() + .orElseThrow(); + assertEquals("new indexing failure" + propagationContext, record.getFailureReason()); + + retryQueueDAO.deleteByEntity(entityId, entityFqn); + } + @Test void testFindByStatuses(TestNamespace ns) { String id1 = UUID.randomUUID().toString(); @@ -210,8 +240,10 @@ void testClaimRecordSetsClaimedAt(TestNamespace ns) { retryQueueDAO.upsert( entityId, entityFqn, "failure", SearchIndexRetryQueue.STATUS_PENDING, "table"); + String claimToken = UUID.randomUUID().toString(); int claimed = - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING); + retryQueueDAO.claimRecord( + entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING, claimToken); assertEquals(1, claimed); List inProgress = @@ -220,6 +252,7 @@ void testClaimRecordSetsClaimedAt(TestNamespace ns) { inProgress.stream().filter(r -> r.getEntityId().equals(entityId)).findFirst().orElseThrow(); assertEquals(SearchIndexRetryQueue.STATUS_IN_PROGRESS, record.getStatus()); assertNotNull(record.getClaimedAt()); + assertEquals(claimToken, record.getClaimToken()); retryQueueDAO.deleteByEntity(entityId, entityFqn); } @@ -233,11 +266,19 @@ void testClaimRecordFailsIfStatusChanged(TestNamespace ns) { entityId, entityFqn, "failure", SearchIndexRetryQueue.STATUS_COMPLETED, ""); int first = - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_COMPLETED); + retryQueueDAO.claimRecord( + entityId, + entityFqn, + SearchIndexRetryQueue.STATUS_COMPLETED, + UUID.randomUUID().toString()); assertEquals(1, first); int second = - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_COMPLETED); + retryQueueDAO.claimRecord( + entityId, + entityFqn, + SearchIndexRetryQueue.STATUS_COMPLETED, + UUID.randomUUID().toString()); assertEquals(0, second); retryQueueDAO.deleteByEntity(entityId, entityFqn); @@ -331,7 +372,8 @@ void testRecoverStaleInProgress(TestNamespace ns) { retryQueueDAO.upsert( entityId, entityFqn, "failure", SearchIndexRetryQueue.STATUS_PENDING, "table"); - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING); + retryQueueDAO.claimRecord( + entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING, UUID.randomUUID().toString()); List inProgress = retryQueueDAO.findByStatus(SearchIndexRetryQueue.STATUS_IN_PROGRESS, 1000); @@ -350,6 +392,7 @@ void testRecoverStaleInProgress(TestNamespace ns) { pending.stream().filter(r -> r.getEntityId().equals(entityId)).findFirst().orElseThrow(); assertEquals(SearchIndexRetryQueue.STATUS_PENDING, record.getStatus()); assertNull(record.getClaimedAt()); + assertNull(record.getClaimToken()); retryQueueDAO.deleteByEntity(entityId, entityFqn); } @@ -360,7 +403,8 @@ void testRecoverStaleDoesNotAffectRecentClaims(TestNamespace ns) { String entityFqn = ns.prefix("rq") + ".entity"; retryQueueDAO.upsert(entityId, entityFqn, "failure", SearchIndexRetryQueue.STATUS_PENDING, ""); - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING); + retryQueueDAO.claimRecord( + entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING, UUID.randomUUID().toString()); List inProgress = retryQueueDAO.findByStatus(SearchIndexRetryQueue.STATUS_IN_PROGRESS, 1000); @@ -389,10 +433,12 @@ void testUpdateFailureAndRetryCountIncrementsCountAndRetainsAttemptTime(TestName retryQueueDAO.upsert( entityId, entityFqn, "initial", SearchIndexRetryQueue.STATUS_PENDING, "table"); - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING); + String claimToken = UUID.randomUUID().toString(); + retryQueueDAO.claimRecord( + entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING, claimToken); retryQueueDAO.updateFailureAndRetryCount( - entityId, entityFqn, "retry 1 failed", SearchIndexRetryQueue.STATUS_PENDING); + entityId, entityFqn, "retry 1 failed", SearchIndexRetryQueue.STATUS_PENDING, claimToken); List records = retryQueueDAO.findByStatus(SearchIndexRetryQueue.STATUS_PENDING, 1000); @@ -401,6 +447,7 @@ void testUpdateFailureAndRetryCountIncrementsCountAndRetainsAttemptTime(TestName assertEquals(1, record.getRetryCount()); assertEquals("retry 1 failed", record.getFailureReason()); assertNotNull(record.getClaimedAt()); + assertNull(record.getClaimToken()); retryQueueDAO.deleteByEntity(entityId, entityFqn); } @@ -412,20 +459,33 @@ void testClaimPendingHonorsRetryBackoff(TestNamespace ns) { retryQueueDAO.upsert( entityId, entityFqn, "initial", SearchIndexRetryQueue.STATUS_PENDING, "table"); - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING); + String initialClaimToken = UUID.randomUUID().toString(); + retryQueueDAO.claimRecord( + entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING, initialClaimToken); retryQueueDAO.updateFailureAndRetryCount( - entityId, entityFqn, "retry 1 failed", SearchIndexRetryQueue.STATUS_PENDING_RETRY_1); + entityId, + entityFqn, + "retry 1 failed", + SearchIndexRetryQueue.STATUS_PENDING_RETRY_1, + initialClaimToken); List delayedFirstRetry = retryQueueDAO.claimPending(1000, 3600, 7200); assertTrue( delayedFirstRetry.stream().noneMatch(record -> record.getEntityId().equals(entityId))); List eligibleFirstRetry = retryQueueDAO.claimPending(1000, 0, 0); - assertTrue( - eligibleFirstRetry.stream().anyMatch(record -> record.getEntityId().equals(entityId))); + SearchIndexRetryRecord firstRetryClaim = + eligibleFirstRetry.stream() + .filter(record -> record.getEntityId().equals(entityId)) + .findFirst() + .orElseThrow(); retryQueueDAO.updateFailureAndRetryCount( - entityId, entityFqn, "retry 2 failed", SearchIndexRetryQueue.STATUS_PENDING_RETRY_2); + entityId, + entityFqn, + "retry 2 failed", + SearchIndexRetryQueue.STATUS_PENDING_RETRY_2, + firstRetryClaim.getClaimToken()); List delayedSecondRetry = retryQueueDAO.claimPending(1000, 0, 7200); assertTrue( @@ -458,9 +518,10 @@ void testRetryCountProgressionToFailed(TestNamespace ns) { SearchIndexRetryQueue.STATUS_FAILED }; for (int i = 0; i < 3; i++) { - retryQueueDAO.claimRecord(entityId, entityFqn, statusProgression[i]); + String claimToken = UUID.randomUUID().toString(); + retryQueueDAO.claimRecord(entityId, entityFqn, statusProgression[i], claimToken); retryQueueDAO.updateFailureAndRetryCount( - entityId, entityFqn, "attempt " + (i + 1) + " failed", nextStatuses[i]); + entityId, entityFqn, "attempt " + (i + 1) + " failed", nextStatuses[i], claimToken); } List failed = @@ -716,7 +777,8 @@ void testWorkerStaleRecoveryIntegration(TestNamespace ns) throws Exception { retryQueueDAO.upsert( entityId, entityFqn, "stale test", SearchIndexRetryQueue.STATUS_PENDING, ""); - retryQueueDAO.claimRecord(entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING); + retryQueueDAO.claimRecord( + entityId, entityFqn, SearchIndexRetryQueue.STATUS_PENDING, UUID.randomUUID().toString()); List inProgress = retryQueueDAO.findByStatus(SearchIndexRetryQueue.STATUS_IN_PROGRESS, 1000); @@ -735,6 +797,7 @@ void testWorkerStaleRecoveryIntegration(TestNamespace ns) throws Exception { SearchIndexRetryRecord record = pending.stream().filter(r -> r.getEntityId().equals(entityId)).findFirst().orElseThrow(); assertNull(record.getClaimedAt()); + assertNull(record.getClaimToken()); retryQueueDAO.deleteByEntity(entityId, entityFqn); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TagResourceIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TagResourceIT.java index 0fde73ffa58b..3a0959ac2f31 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TagResourceIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/TagResourceIT.java @@ -15,11 +15,13 @@ import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; import java.util.Set; import java.util.UUID; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream; import java.util.stream.StreamSupport; +import org.apache.commons.lang3.RandomStringUtils; import org.awaitility.Awaitility; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; @@ -670,7 +672,8 @@ void test_searchTagByClassificationDisplayName(TestNamespace ns) { OpenMetadataClient client = SdkClients.adminClient(); ObjectMapper mapper = new ObjectMapper(); String uniqueSuffix = java.util.UUID.randomUUID().toString().substring(0, 8); - String displayName = "PW Classification " + ns.uniqueShortId(); + String searchToken = ("xqz" + RandomStringUtils.randomAlphabetic(16)).toLowerCase(Locale.ROOT); + String displayName = "PW Classification " + searchToken; Classification classification = client @@ -694,7 +697,7 @@ void test_searchTagByClassificationDisplayName(TestNamespace ns) { .untilAsserted( () -> { String response = - client.search().query(displayName).index("tag_search_index").size(25).execute(); + client.search().query(searchToken).index("tag_search_index").size(25).execute(); JsonNode root = mapper.readTree(response); JsonNode hits = root.path("hits").path("hits"); boolean found = 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..75d440902331 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; @@ -1035,6 +1040,11 @@ void test_bulkAddTestCasesToLogicalTestSuiteByIds(TestNamespace ns) throws Excep .parameter("columnCount", "2") .create(); + testCase1.setDescription("Edited before logical suite assignment"); + patchEntity(testCase1.getId().toString(), testCase1); + testCase2.setDescription("Also edited before logical suite assignment"); + patchEntity(testCase2.getId().toString(), testCase2); + CreateTestSuite suiteReq = new CreateTestSuite(); suiteReq.setName(ns.prefix("logical_bulk_ids")); TestSuite logicalSuite = client.testSuites().create(suiteReq); @@ -1083,6 +1093,152 @@ void test_bulkAddTestCasesToLogicalTestSuiteByIds(TestNamespace ns) throws Excep updatedSuite.getTests().stream().map(ref -> ref.getId()).toList(); assertTrue(testIdsInSuite.contains(testCase1.getId())); assertTrue(testIdsInSuite.contains(testCase2.getId())); + + try (Rest5Client searchClient = TestSuiteBootstrap.createSearchClient()) { + Awaitility.await("edited test cases added to logical suite are indexed") + .atMost(SEARCH_CONVERGENCE_TIMEOUT) + .pollInterval(Duration.ofSeconds(2)) + .ignoreExceptions() + .untilAsserted( + () -> { + assertSearchDocContainsTestSuite( + queryTestCaseSearchSource(searchClient, testCase1.getId()), + logicalSuite.getId()); + assertSearchDocContainsTestSuite( + queryTestCaseSearchSource(searchClient, testCase2.getId()), + logicalSuite.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 @@ -4702,7 +4858,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 +4883,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 +4910,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-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/search/EntityRankingSeeders.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntityRankingSeeders.java index 9b2252330401..44a838af913f 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntityRankingSeeders.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntityRankingSeeders.java @@ -625,7 +625,7 @@ public String seed( .withFields( List.of( new SearchIndexField() - .withName(RankingSupport.uniqueTerm(ns)) + .withName(EntitySeeder.tokenFreeValue(ns)) .withDataType(SearchIndexDataType.TEXT))); List tags = EntitySeeder.tierTags(tier1); if (tags != null) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntitySeeder.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntitySeeder.java index 3cf527db42d9..fbfd7060a88f 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntitySeeder.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/EntitySeeder.java @@ -62,7 +62,7 @@ String seed( /** Unique entity name; the token is the leading clean sub-token only for {@code NAME}. */ static String nameFor(TestNamespace ns, String token, Placement placement) { - String lead = placement == Placement.NAME ? token : RankingSupport.uniqueTerm(ns); + String lead = placement == Placement.NAME ? token : tokenFreeValue(ns); return ns.prefix(lead + "-" + ns.uniqueShortId()); } @@ -70,19 +70,24 @@ static String displayNameFor(TestNamespace ns, String token, Placement placement return switch (placement) { case DISPLAY_NAME_EXACT -> token; case DISPLAY_NAME_PHRASE -> token + " reporting warehouse"; - default -> "gd " + RankingSupport.uniqueTerm(ns); + default -> tokenFreeValue(ns); }; } static String descriptionFor(TestNamespace ns, String token, Placement placement) { return placement == Placement.DESCRIPTION ? "this asset mentions " + token + " once in prose" - : "generic description body " + RankingSupport.uniqueTerm(ns); + : tokenFreeValue(ns); } /** The token to write into the distinctive nested field, or a generic value for other placements. */ static String distinctiveFor(TestNamespace ns, String token, Placement placement) { - return placement == Placement.DISTINCTIVE ? token : "generic_" + RankingSupport.uniqueTerm(ns); + return placement == Placement.DISTINCTIVE ? token : tokenFreeValue(ns); + } + + /** Hex-only value whose alphabet cannot overlap {@link RankingSupport#uniqueTerm(TestNamespace)}. */ + static String tokenFreeValue(TestNamespace ns) { + return "aa" + ns.uniqueShortId(); } static List tierTags(boolean tier1) { diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/RankingSupport.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/RankingSupport.java index c5413dfa5965..87bd31595569 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/RankingSupport.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/RankingSupport.java @@ -33,8 +33,8 @@ private RankingSupport() {} private static final Duration INDEX_WAIT = Duration.ofSeconds(30); private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); - /** A hit's name + fqn + score — enough to assert relative ranking. */ - record Hit(String name, String fqn, double score) { + /** A hit's identifying and ranking fields. */ + record Hit(String name, String fqn, double score, String tier) { boolean matches(String token) { return contains(name, token) || contains(fqn, token); } @@ -82,7 +82,8 @@ private static SearchResult parse(String body) throws Exception { new Hit( text(source, "name"), text(source, "fullyQualifiedName"), - hit.path("_score").asDouble(0.0))); + hit.path("_score").asDouble(0.0), + text(source.path("tier"), "tagFQN"))); } return new SearchResult(hits); } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchEntityRankingIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchEntityRankingIT.java index ae6cabeca1d3..f311843588cc 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchEntityRankingIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchEntityRankingIT.java @@ -138,7 +138,7 @@ private void evaluateCase( + " vs " + rankLow + " -> " - + result.names()); + + result.hits()); } } diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java index b036ba832d64..db4a66ed00ba 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/search/SearchRelevancyPreviewIT.java @@ -196,13 +196,15 @@ void highlightFieldsAppearInResults(final TestNamespace ns) { @Test void matchTypeExactRequiresTheFullKeyword(final TestNamespace ns) { - final String exactName = RelevancyFixtures.uniqueToken("ex"); + final String namePrefix = RelevancyFixtures.uniqueToken("ex"); + final String exactName = namePrefix + "a"; + final String nearMatchName = namePrefix + "b"; final DatabaseSchema schema = DatabaseSchemaTestFactory.createSimple(ns); final Table exactTable = RelevancyFixtures.createTable(schema, exactName, "plaindescription", null); - final Table prefixedTable = - RelevancyFixtures.createTable(schema, exactName + "extra", "plaindescription", null); - awaitIndexed(exactName, 2); + final Table nearMatchTable = + RelevancyFixtures.createTable(schema, nearMatchName, "plaindescription", null); + awaitIndexed(namePrefix, 2); final SearchSettings base = currentSettings(); @@ -211,7 +213,7 @@ void matchTypeExactRequiresTheFullKeyword(final TestNamespace ns) { exact, TABLE_INDEX, NAME_FIELD, 5.0, FieldBoost.MatchType.EXACT); exact = SearchSettingsTestHelper.withRankingDisabled(exact, TABLE_INDEX); assertThat(SearchSettingsTestHelper.previewIds(server, exactName, TABLE_INDEX, exact, 10)) - .as("matchType=exact must match only the whole-keyword name, not the prefixed sibling") + .as("matchType=exact must match only the whole-keyword name, not the one-edit sibling") .containsExactly(exactTable.getId().toString()); SearchSettings standard = SearchSettingsTestHelper.copyOf(base); @@ -223,8 +225,8 @@ void matchTypeExactRequiresTheFullKeyword(final TestNamespace ns) { // an exact size (mirrors maxResultHitsClampsTheReturnedHits), which such a foreign hit // inflates. assertThat(SearchSettingsTestHelper.previewIds(server, exactName, TABLE_INDEX, standard, 10)) - .as("matchType=standard must match both the exact and the prefixed name") - .contains(exactTable.getId().toString(), prefixedTable.getId().toString()); + .as("matchType=standard must match both the exact and one-edit names") + .contains(exactTable.getId().toString(), nearMatchTable.getId().toString()); } @Test diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/observability/TestSuiteDetailsPageReindexUIIT.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/observability/TestSuiteDetailsPageReindexUIIT.java index b201ccea6b17..fc4d9aa0c1fc 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/observability/TestSuiteDetailsPageReindexUIIT.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/scenarios/observability/TestSuiteDetailsPageReindexUIIT.java @@ -75,19 +75,21 @@ void addTestCaseModalSurvivesReindex(final UiSession ui, final TestNamespace ns) reindex.awaitIndexed("testCase", java.util.List.of(tc1, tc2)); final String suiteName = "ts_bd_" + UUID.randomUUID().toString().substring(0, 8); - BundleTestSuitePage.openCreateForm(ui) - .fillNameDescriptionAndAttach(suiteName, "bundle suite e2e", tc1.getName()); + final BundleTestSuitePage suitePage = + BundleTestSuitePage.openCreateForm(ui) + .fillNameDescriptionAndAttach(suiteName, "bundle suite e2e", tc1.getName()); - runDetailModalFlow(ui, suiteName); + runDetailModalFlow(suitePage, suiteName); // Reindex the seeded testCases — verify the modal still functions after rebuild. reindex.recreateAndAwait("testCase", java.util.List.of(tc1, tc2)); - runDetailModalFlow(ui, suiteName); + runDetailModalFlow(suitePage, suiteName); } - private static void runDetailModalFlow(final UiSession ui, final String suiteName) { - BundleTestSuitePage.openCreateForm(ui) + private static void runDetailModalFlow( + final BundleTestSuitePage suitePage, final String suiteName) { + suitePage .openDetail(suiteName) .openAddTestCaseModal() .assertModalFilterDropdownsVisible() diff --git a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java index 1fd249ddbe64..6751baf5e32a 100644 --- a/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java +++ b/openmetadata-integration-tests/src/test/java/org/openmetadata/playwright/ui/pages/BundleTestSuitePage.java @@ -72,11 +72,10 @@ public BundleTestSuitePage fillNameDescriptionAndAttach( /** Navigate to {@code /test-suites/}. */ public BundleTestSuitePage openDetail(final String suiteName) { - final Page newPage = page.context().newPage(); final String url = session.uiUrl("/test-suites/" + URLEncoder.encode(suiteName, StandardCharsets.UTF_8)); - newPage.waitForResponse(r -> r.url().contains(API_LIST), () -> newPage.navigate(url)); - return new BundleTestSuitePage(newPage, session); + page.waitForResponse(r -> r.url().contains(API_LIST), () -> page.navigate(url)); + return this; } /** Click the Add Test Case button on the detail page; wait for modal list response. */ 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/changeEvent/AbstractEventConsumer.java b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java index 33c8a5a0ca81..39978464c333 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/apps/bundles/changeEvent/AbstractEventConsumer.java @@ -42,6 +42,7 @@ import org.openmetadata.schema.utils.ResultList; import org.openmetadata.service.Entity; import org.openmetadata.service.events.errors.EventPublisherException; +import org.openmetadata.service.jdbi3.CollectionDAO.ChangeEventDAO.ChangeEventRecord; import org.openmetadata.service.notifications.recipients.RecipientResolver; import org.openmetadata.service.notifications.recipients.context.Recipient; import org.openmetadata.service.util.DIContainer; @@ -58,15 +59,18 @@ public abstract class AbstractEventConsumer implements Alert, Consumer, Job { public static final String DESTINATION_MAP_KEY = "SubscriptionMapKey"; public static final String ALERT_OFFSET_KEY = "alertOffsetKey"; + public static final String ALERT_PENDING_GAP_SINCE_KEY = "alertPendingGapSinceKey"; public static final String ALERT_INFO_KEY = "alertInfoKey"; public static final String OFFSET_EXTENSION = "eventSubscription.Offset"; public static final String METRICS_EXTENSION = "eventSubscription.metrics"; public static final String FAILED_EVENT_EXTENSION = "eventSubscription.failedEvent"; + static final long GAP_RESOLVE_TIMEOUT_MS = 30_000; protected final DIContainer dependencies; private long offset = -1; - // Highest change_event.offset actually read in the last poll. Used to advance the cursor by true - // offset instead of row count, since change_event.offset is a non-contiguous AUTO_INCREMENT. + // Highest change_event.offset that is safe to commit after the last poll. private long lastReadOffset = -1; + private long pendingGapSince; + private boolean gapStateChanged; private long startingOffset = -1; private AlertMetrics alertMetrics; @@ -113,6 +117,9 @@ private void init(JobExecutionContext context) { EventSubscriptionOffset eventSubscriptionOffset = loadInitialOffset(context); this.offset = eventSubscriptionOffset.getCurrentOffset(); this.startingOffset = eventSubscriptionOffset.getStartingOffset(); + this.lastReadOffset = this.offset; + this.pendingGapSince = loadPendingGapSince(); + this.gapStateChanged = false; this.alertMetrics = loadInitialMetrics(); this.destinationMap = loadDestinationsMap(context); @@ -197,6 +204,24 @@ private EventSubscriptionOffset loadInitialOffset(JobExecutionContext context) { return getStartingOffset(eventSubscription.getId()); } + private long loadPendingGapSince() { + Object value = jobDetail.getJobDataMap().get(ALERT_PENDING_GAP_SINCE_KEY); + if (value instanceof Number number) { + return number.longValue(); + } + if (value instanceof String stringValue && !stringValue.isBlank()) { + try { + return Long.parseLong(stringValue); + } catch (NumberFormatException e) { + LOG.warn( + "Invalid pending gap timestamp '{}' for event subscription {}", + stringValue, + eventSubscription.getId()); + } + } + return 0L; + } + private Map> loadDestinationsMap(JobExecutionContext context) { Map> dMap = new HashMap<>(); if (eventSubscription.getDestinations() == null) { @@ -341,6 +366,8 @@ public void commit(JobExecutionContext jobExecutionContext) { .getJobDataMap() .put(ALERT_OFFSET_KEY, JsonUtils.pojoToJson(eventSubscriptionOffset)); + persistPendingGapState(jobExecutionContext); + jobExecutionContext .getJobDetail() .getJobDataMap() @@ -384,11 +411,25 @@ private void batchRecordSuccessfulEvents(UUID subscriptionId, long timestamp) { public ResultList pollEvents(long offset, long batchSize) { var records = Entity.getCollectionDAO().changeEventDAO().listWithOffset((int) batchSize, offset); + CursorPlan cursorPlan = + planCursor(offset, pendingGapSince, records, System.currentTimeMillis()); + gapStateChanged = cursorPlan.pendingGapSince() != pendingGapSince; + pendingGapSince = cursorPlan.pendingGapSince(); + lastReadOffset = cursorPlan.offset(); + + if (cursorPlan.skippedGap()) { + LOG.warn( + "Event subscription {} skipping unfilled change_event gap [{} .. {}] after {}ms", + eventSubscription.getId(), + offset + 1, + cursorPlan.offset(), + GAP_RESOLVE_TIMEOUT_MS); + } + List changeEvents = new ArrayList<>(); List errorEvents = new ArrayList<>(); - long maxOffset = offset; - for (var eventRecord : records) { - maxOffset = Math.max(maxOffset, eventRecord.offset()); + for (int index = 0; index < cursorPlan.recordCount(); index++) { + var eventRecord = records.get(index); try { ChangeEvent event = JsonUtils.readValue(eventRecord.json(), ChangeEvent.class); if (event == null) { @@ -409,13 +450,44 @@ public ResultList pollEvents(long offset, long batchSize) { ex); } } - // Track the true maximum offset read so the cursor advances past exactly these rows. Advancing - // by row count re-read the tail whenever the AUTO_INCREMENT offset column had gaps (rolled-back - // txns / retention deletes), redelivering those change events. - this.lastReadOffset = maxOffset; - return new ResultList<>(changeEvents, errorEvents, null, null, records.size()); + return new ResultList<>(changeEvents, errorEvents, null, null, cursorPlan.recordCount()); + } + + /** + * Advances only across a contiguous prefix of committed offsets. AUTO_INCREMENT values become + * visible at commit, so a concurrent transaction can temporarily hide a lower offset while a + * higher offset is already readable. Waiting at that gap prevents permanent event loss. A gap + * that remains unfilled is eventually treated as a rolled-back insert so consumers cannot stall + * forever. + */ + static CursorPlan planCursor( + long currentOffset, long pendingGapSince, List records, long now) { + if (records.isEmpty()) { + return new CursorPlan(currentOffset, 0L, 0, false); + } + + int contiguousCount = 0; + long expectedOffset = currentOffset + 1; + while (contiguousCount < records.size() + && records.get(contiguousCount).offset() == expectedOffset) { + contiguousCount++; + expectedOffset++; + } + + if (contiguousCount > 0) { + return new CursorPlan(currentOffset + contiguousCount, 0L, contiguousCount, false); + } + if (pendingGapSince == 0L) { + return new CursorPlan(currentOffset, now, 0, false); + } + if (now - pendingGapSince >= GAP_RESOLVE_TIMEOUT_MS) { + return new CursorPlan(records.getFirst().offset() - 1, 0L, 0, true); + } + return new CursorPlan(currentOffset, pendingGapSince, 0, false); } + record CursorPlan(long offset, long pendingGapSince, int recordCount, boolean skippedGap) {} + @Override public void execute(JobExecutionContext jobExecutionContext) { this.init(jobExecutionContext); @@ -442,14 +514,22 @@ public void execute(JobExecutionContext jobExecutionContext) { e); } finally { - if (!eventsWithReceivers.isEmpty()) { - // Advance to the true max offset read (set by pollEvents), not by row count. + if (lastReadOffset > offset) { offset = lastReadOffset; commit(jobExecutionContext); + } else if (gapStateChanged) { + persistPendingGapState(jobExecutionContext); } } } + private void persistPendingGapState(JobExecutionContext jobExecutionContext) { + jobExecutionContext + .getJobDetail() + .getJobDataMap() + .put(ALERT_PENDING_GAP_SINCE_KEY, Long.toString(pendingGapSince)); + } + public EventSubscription getEventSubscription() { return eventSubscription; } 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..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 @@ -134,6 +134,10 @@ 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"; + + 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 3f76e49e1817..b28e373143f0 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,18 +1,23 @@ 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; 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; @@ -284,6 +289,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); @@ -355,6 +362,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 = @@ -370,7 +381,9 @@ public void write(List entities, Map contextData) throws Exce tracker, embeddingsEnabled, finalEmbeddingsById, - docBuildContexts), + docBuildContexts, + scriptedPartialUpdates, + relationshipRevisions), DOC_BUILD_EXECUTOR)) .toList(); CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); @@ -423,18 +436,23 @@ private void addEntity( StageStatsTracker tracker, boolean embeddingsEnabled, Map existingEmbeddingsById, - Map docBuildContexts) { + 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) { json = enrichWithEmbedding(entity, json, existingEmbeddingsById, tracker); } - String docId = entity.getId().toString(); long rawDocSize = (long) json.getBytes(StandardCharsets.UTF_8).length; long estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; @@ -453,6 +471,36 @@ private void addEntity( estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; } + if (scriptedPartialUpdates) { + SearchRepository.ScriptedPartialUpdate partialUpdate = + 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); + } + return; + } + } + + 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", @@ -515,6 +563,137 @@ private void addEntity( } } + private void addScriptedPartialUpdate( + String indexName, + String docId, + String entityType, + SearchRepository.ScriptedPartialUpdate partialUpdate, + String upsertDocument, + StageStatsTracker tracker) { + String effectiveUpsertDocument = partialUpdate.scriptedUpsert() ? "{}" : upsertDocument; + Map scriptParameters = partialUpdate.parametersForIndexing(); + long estimatedSize = + (long) effectiveUpsertDocument.getBytes(StandardCharsets.UTF_8).length + + JsonUtils.pojoToJson(scriptParameters).getBytes(StandardCharsets.UTF_8).length + + partialUpdate.script().getBytes(StandardCharsets.UTF_8).length + + BULK_OPERATION_METADATA_OVERHEAD; + Map params = new HashMap<>(); + scriptParameters.forEach( + (key, value) -> { + if (value != null) { + params.put(key, JsonData.of(value, JACKSON_JSONP_MAPPER)); + } + }); + if (estimatedSize > maxPayloadSizeBytes) { + LOG.warn( + "Scripted update {} of type {} is too large for bulk ({} bytes), sending directly", + docId, + entityType, + estimatedSize); + totalSubmitted.incrementAndGet(); + if (tracker != null) { + tracker.incrementPendingSink(); + } + updateScriptedDocumentDirectly( + indexName, + docId, + entityType, + partialUpdate, + effectiveUpsertDocument, + params, + tracker, + estimatedSize); + return; + } + BulkOperation operation = + BulkOperation.of( + op -> + op.update( + update -> + update + .index(indexName) + .id(docId) + .retryOnConflict(3) + .action( + action -> + action + .scriptedUpsert(partialUpdate.scriptedUpsert()) + .upsert(EsUtils.toJsonData(effectiveUpsertDocument)) + .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); + } + + private void updateScriptedDocumentDirectly( + String indexName, + String docId, + String entityType, + SearchRepository.ScriptedPartialUpdate partialUpdate, + String upsertDocument, + Map params, + StageStatsTracker tracker, + long estimatedSize) { + try { + Map upsert = + JsonUtils.readValue(upsertDocument, new TypeReference>() {}); + searchClient + .getNewClient() + .update( + update -> + update + .index(indexName) + .id(docId) + .refresh(Refresh.False) + .retryOnConflict(3) + .scriptedUpsert(partialUpdate.scriptedUpsert()) + .upsert(upsert) + .script( + script -> + script + .source(source -> source.scriptString(partialUpdate.script())) + .lang(ScriptLanguage.Painless) + .params(params)), + Map.class); + totalSuccess.incrementAndGet(); + updateStats(); + if (tracker != null) { + tracker.recordSink(StatsResult.SUCCESS); + } + } catch (Exception e) { + LOG.error( + "Direct scripted update failed for document {} of type {}: {}", + docId, + entityType, + e.getMessage(), + e); + totalFailed.incrementAndGet(); + updateStats(); + if (tracker != null) { + tracker.recordSink(StatsResult.FAILED); + } + if (failureCallback != null) { + failureCallback.onFailure( + entityType, + docId, + null, + String.format( + "Scripted update too large for bulk (%d bytes); direct update failed: %s", + estimatedSize, e.getMessage()), + IndexingFailureRecorder.FailureStage.SINK); + } + } + } + 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 a55c0284e9e1..8b78e3925ea9 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,10 +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; @@ -58,9 +61,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 +299,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); @@ -371,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; @@ -387,7 +399,9 @@ public void write(List entities, Map contextData) throws Exce tracker, embeddingsEnabled, finalEmbeddingsById, - docBuildContexts), + docBuildContexts, + scriptedPartialUpdates, + relationshipRevisions), DOC_BUILD_EXECUTOR)) .toList(); CompletableFuture.allOf(futures.toArray(CompletableFuture[]::new)).join(); @@ -440,11 +454,38 @@ private void addEntity( StageStatsTracker tracker, boolean embeddingsEnabled, Map existingEmbeddingsById, - Map docBuildContexts) { + 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) { @@ -458,7 +499,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; @@ -477,6 +517,36 @@ private void addEntity( estimatedSize = rawDocSize + BULK_OPERATION_METADATA_OVERHEAD; } + if (scriptedPartialUpdates) { + SearchRepository.ScriptedPartialUpdate partialUpdate = + 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); + } + return; + } + } + + 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", @@ -539,6 +609,141 @@ private void addEntity( } } + private void addScriptedPartialUpdate( + String indexName, + String docId, + String entityType, + SearchRepository.ScriptedPartialUpdate partialUpdate, + String upsertDocument, + StageStatsTracker tracker) { + String effectiveUpsertDocument = partialUpdate.scriptedUpsert() ? "{}" : upsertDocument; + Map scriptParameters = partialUpdate.parametersForIndexing(); + long estimatedSize = + (long) effectiveUpsertDocument.getBytes(StandardCharsets.UTF_8).length + + JsonUtils.pojoToJson(scriptParameters).getBytes(StandardCharsets.UTF_8).length + + partialUpdate.script().getBytes(StandardCharsets.UTF_8).length + + BULK_OPERATION_METADATA_OVERHEAD; + Map params = new HashMap<>(); + scriptParameters.forEach( + (key, value) -> { + if (value != null) { + params.put(key, JsonData.of(value, JACKSON_JSONP_MAPPER)); + } + }); + if (estimatedSize > maxPayloadSizeBytes) { + LOG.warn( + "Scripted update {} of type {} is too large for bulk ({} bytes), sending directly", + docId, + entityType, + estimatedSize); + totalSubmitted.incrementAndGet(); + if (tracker != null) { + tracker.incrementPendingSink(); + } + updateScriptedDocumentDirectly( + indexName, + docId, + entityType, + partialUpdate, + effectiveUpsertDocument, + params, + tracker, + estimatedSize); + return; + } + BulkOperation operation = + BulkOperation.of( + op -> + op.update( + update -> + update + .index(indexName) + .id(docId) + .retryOnConflict(3) + .scriptedUpsert(partialUpdate.scriptedUpsert()) + .upsert(OsUtils.toJsonData(effectiveUpsertDocument)) + .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); + } + + private void updateScriptedDocumentDirectly( + String indexName, + String docId, + String entityType, + SearchRepository.ScriptedPartialUpdate partialUpdate, + String upsertDocument, + Map params, + StageStatsTracker tracker, + long estimatedSize) { + try { + Map upsert = + JsonUtils.readValue(upsertDocument, new TypeReference>() {}); + searchClient + .getNewClient() + .update( + update -> + update + .index(indexName) + .id(docId) + .refresh(Refresh.False) + .retryOnConflict(3) + .scriptedUpsert(partialUpdate.scriptedUpsert()) + .upsert(upsert) + .script( + script -> + script.inline( + inline -> + inline + .lang( + language -> + language.builtin(BuiltinScriptLanguage.Painless)) + .source(partialUpdate.script()) + .params(params))), + Map.class); + totalSuccess.incrementAndGet(); + updateStats(); + if (tracker != null) { + tracker.recordSink(StatsResult.SUCCESS); + } + } catch (Exception e) { + LOG.error( + "Direct scripted update failed for document {} of type {}: {}", + docId, + entityType, + e.getMessage(), + e); + totalFailed.incrementAndGet(); + updateStats(); + if (tracker != null) { + tracker.recordSink(StatsResult.FAILED); + } + if (failureCallback != null) { + failureCallback.onFailure( + entityType, + docId, + null, + String.format( + "Scripted update too large for bulk (%d bytes); direct update failed: %s", + estimatedSize, e.getMessage()), + IndexingFailureRecorder.FailureStage.SINK); + } + } + } + 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..bca5e6340a45 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 @@ -72,8 +72,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 = 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/drive/ContextFileExtractionService.java b/openmetadata-service/src/main/java/org/openmetadata/service/drive/ContextFileExtractionService.java index e96c2f813def..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 @@ -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; @@ -11,6 +13,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 +24,14 @@ 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; +import org.openmetadata.service.util.RequestEntityCache; @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; private final Executor executor; @@ -97,17 +104,47 @@ 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); + } } } 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())) { return; } - updateFile( + if (!updateFile( fileId, current -> { if (!contentId.toString().equals(current.getHeadContentId())) { @@ -116,8 +153,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 +172,9 @@ void process(UUID fileId, UUID contentId) { updated.setProcessingStatus(ProcessingStatus.Analyzing); updated.setProcessingError(null); return updated; - }); + })) { + return; + } try { ContextFile currentFile = getFile(fileId); @@ -161,6 +202,9 @@ void process(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; } @@ -175,7 +219,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 +227,9 @@ private void applyResult( updated.setProcessingError(result.processingError()); updated.setExtractedText(result.extractedText()); return updated; - }); + })) { + return; + } updateFile( fileId, @@ -200,7 +246,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 +254,9 @@ private void applyFailure(UUID fileId, UUID contentId, String reason) { updated.setProcessingError(reason); updated.setExtractedText(null); return updated; - }); + })) { + return; + } updateFile( fileId, @@ -240,29 +288,72 @@ private ContextFileContent getContent(UUID contentId) { } } - private void updateFile( - UUID fileId, java.util.function.Function updater) { - ContextFile current = getFile(fileId); - if (current == null) { - return; + private boolean updateFile(UUID fileId, Function updater) { + for (int attempt = 1; 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); + RequestEntityCache.invalidate(CONTEXT_FILE_ENTITY, fileId, current.getFullyQualifiedName()); + if (attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS + && !waitForConditionalUpdateRetry(CONTEXT_FILE_ENTITY, fileId)) { + return false; + } + } } - ContextFile updated = updater.apply(current); - if (updated == null) { - return; + throw new ConditionalUpdateExhaustedException(CONTEXT_FILE_ENTITY, fileId); + } + + private boolean updateContent( + UUID contentId, Function updater) { + for (int attempt = 1; 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); + RequestEntityCache.invalidate( + CONTEXT_FILE_CONTENT_ENTITY, contentId, current.getFullyQualifiedName()); + if (attempt < MAX_CONDITIONAL_UPDATE_ATTEMPTS + && !waitForConditionalUpdateRetry(CONTEXT_FILE_CONTENT_ENTITY, contentId)) { + return false; + } + } } - repository.update(null, current, updated, ADMIN_USER_NAME); + throw new ConditionalUpdateExhaustedException(CONTEXT_FILE_CONTENT_ENTITY, contentId); } - private void updateContent( - UUID contentId, java.util.function.Function updater) { - ContextFileContent current = getContent(contentId); - if (current == null) { - return; + 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; } - ContextFileContent updated = updater.apply(current); - if (updated == null) { - return; + } + + private static class ConditionalUpdateExhaustedException extends RuntimeException { + private ConditionalUpdateExhaustedException(String entityType, UUID entityId) { + super("Repeated concurrent updates for " + entityType + " " + entityId); } - repository.getContentRepository().update(null, current, updated, ADMIN_USER_NAME); } } 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..ec843b90be97 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 @@ -28,6 +28,7 @@ import static org.openmetadata.service.jdbi3.locator.ConnectionType.MYSQL; import static org.openmetadata.service.jdbi3.locator.ConnectionType.POSTGRES; +import com.fasterxml.jackson.annotation.JsonIgnore; import java.sql.ResultSet; import java.sql.SQLException; import java.util.AbstractMap; @@ -1586,6 +1587,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) @@ -13438,6 +13462,8 @@ public SearchIndexFailureRecord map(ResultSet rs, StatementContext ctx) throws S /** DAO for incremental search retry queue records. */ interface SearchIndexRetryQueueDAO { + String PROPAGATION_CONTEXT_TOKEN = "__OPENMETADATA_SEARCH_PROPAGATION_V1__:"; + @lombok.Getter @lombok.AllArgsConstructor class SearchIndexRetryRecord { @@ -13448,20 +13474,65 @@ class SearchIndexRetryRecord { private final String entityType; private final int retryCount; private final java.sql.Timestamp claimedAt; + @JsonIgnore private final String claimToken; + + public SearchIndexRetryRecord( + String entityId, + String entityFqn, + String failureReason, + String status, + String entityType, + int retryCount, + java.sql.Timestamp claimedAt) { + this(entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt, null); + } } @ConnectionAwareSqlUpdate( value = "INSERT INTO search_index_retry_queue (entityId, entityFqn, failureReason, status, entityType) " + "VALUES (:entityId, :entityFqn, :failureReason, :status, :entityType) " - + "ON DUPLICATE KEY UPDATE failureReason = VALUES(failureReason), status = VALUES(status), entityType = VALUES(entityType)", + + "ON DUPLICATE KEY UPDATE failureReason = CASE " + + "WHEN LOCATE('" + + PROPAGATION_CONTEXT_TOKEN + + "', " + + "COALESCE(VALUES(failureReason), '')) > 0 " + + "OR LOCATE('" + + PROPAGATION_CONTEXT_TOKEN + + "', " + + "COALESCE(failureReason, '')) = 0 THEN VALUES(failureReason) " + + "ELSE CONCAT(COALESCE(VALUES(failureReason), ''), CHAR(10), " + + "SUBSTRING(failureReason, LOCATE('" + + PROPAGATION_CONTEXT_TOKEN + + "', " + + "failureReason))) END, " + + "status = VALUES(status), entityType = VALUES(entityType), retryCount = 0, " + + "claimedAt = NULL, claimToken = NULL", connectionType = MYSQL) @ConnectionAwareSqlUpdate( value = "INSERT INTO search_index_retry_queue (entityId, entityFqn, failureReason, status, entityType) " + "VALUES (:entityId, :entityFqn, :failureReason, :status, :entityType) " + "ON CONFLICT (entityId, entityFqn) DO UPDATE SET " - + "failureReason = EXCLUDED.failureReason, status = EXCLUDED.status, entityType = EXCLUDED.entityType", + + "failureReason = CASE " + + "WHEN POSITION('" + + PROPAGATION_CONTEXT_TOKEN + + "' IN " + + "COALESCE(EXCLUDED.failureReason, '')) > 0 " + + "OR POSITION('" + + PROPAGATION_CONTEXT_TOKEN + + "' IN " + + "COALESCE(search_index_retry_queue.failureReason, '')) = 0 " + + "THEN EXCLUDED.failureReason " + + "ELSE COALESCE(EXCLUDED.failureReason, '') || CHR(10) || " + + "SUBSTRING(search_index_retry_queue.failureReason FROM " + + "POSITION('" + + PROPAGATION_CONTEXT_TOKEN + + "' IN " + + "search_index_retry_queue.failureReason)) END, " + + "status = EXCLUDED.status, " + + "entityType = EXCLUDED.entityType, retryCount = 0, claimedAt = NULL, " + + "claimToken = NULL", connectionType = POSTGRES) void upsert( @Bind("entityId") String entityId, @@ -13471,14 +13542,14 @@ void upsert( @Bind("entityType") String entityType); @SqlQuery( - "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt " + "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt, claimToken " + "FROM search_index_retry_queue WHERE status = :status LIMIT :limit") @RegisterRowMapper(SearchIndexRetryRecordMapper.class) List findByStatus( @Bind("status") String status, @Bind("limit") int limit); @SqlQuery( - "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt " + "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt, claimToken " + "FROM search_index_retry_queue WHERE status IN () LIMIT :limit") @RegisterRowMapper(SearchIndexRetryRecordMapper.class) List findByStatuses( @@ -13486,7 +13557,7 @@ List findByStatuses( @ConnectionAwareSqlQuery( value = - "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt " + "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt, claimToken " + "FROM search_index_retry_queue WHERE status = 'PENDING' " + "OR (status = 'PENDING_RETRY_1' AND (claimedAt IS NULL OR " + "claimedAt <= DATE_SUB(NOW(), INTERVAL :firstRetryBackoffSeconds SECOND))) " @@ -13496,7 +13567,7 @@ List findByStatuses( connectionType = MYSQL) @ConnectionAwareSqlQuery( value = - "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt " + "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt, claimToken " + "FROM search_index_retry_queue WHERE status = 'PENDING' " + "OR (status = 'PENDING_RETRY_1' AND (claimedAt IS NULL OR " + "claimedAt <= NOW() - (:firstRetryBackoffSeconds * INTERVAL '1 second'))) " @@ -13540,6 +13611,14 @@ int updateStatus( "DELETE FROM search_index_retry_queue WHERE entityId = :entityId AND entityFqn = :entityFqn") int deleteByEntity(@Bind("entityId") String entityId, @Bind("entityFqn") String entityFqn); + @SqlUpdate( + "DELETE FROM search_index_retry_queue WHERE entityId = :entityId AND entityFqn = :entityFqn " + + "AND status = 'IN_PROGRESS' AND claimToken = :claimToken") + int deleteClaimed( + @Bind("entityId") String entityId, + @Bind("entityFqn") String entityFqn, + @Bind("claimToken") String claimToken); + @SqlUpdate("DELETE FROM search_index_retry_queue WHERE status IN ()") int deleteByStatuses(@BindList("statuses") List statuses); @@ -13547,27 +13626,31 @@ int updateStatus( int countByStatus(@Bind("status") String status); @SqlUpdate( - "UPDATE search_index_retry_queue SET status = 'IN_PROGRESS', claimedAt = NOW() " + "UPDATE search_index_retry_queue SET status = 'IN_PROGRESS', claimedAt = NOW(), " + + "claimToken = :claimToken " + "WHERE entityId = :entityId AND entityFqn = :entityFqn AND status = :currentStatus") int claimRecord( @Bind("entityId") String entityId, @Bind("entityFqn") String entityFqn, - @Bind("currentStatus") String currentStatus); + @Bind("currentStatus") String currentStatus, + @Bind("claimToken") String claimToken); @SqlUpdate( - "UPDATE search_index_retry_queue SET status = 'PENDING', claimedAt = NULL " + "UPDATE search_index_retry_queue SET status = 'PENDING', claimedAt = NULL, claimToken = NULL " + "WHERE status = 'IN_PROGRESS' AND claimedAt < :cutoff") int recoverStaleInProgress(@Bind("cutoff") java.sql.Timestamp cutoff); @SqlUpdate( "UPDATE search_index_retry_queue SET status = :status, failureReason = :failureReason, " - + "retryCount = retryCount + 1, claimedAt = NOW() " - + "WHERE entityId = :entityId AND entityFqn = :entityFqn") + + "retryCount = retryCount + 1, claimedAt = NOW(), claimToken = NULL " + + "WHERE entityId = :entityId AND entityFqn = :entityFqn " + + "AND status = 'IN_PROGRESS' AND claimToken = :claimToken") int updateFailureAndRetryCount( @Bind("entityId") String entityId, @Bind("entityFqn") String entityFqn, @Bind("failureReason") String failureReason, - @Bind("status") String status); + @Bind("status") String status, + @Bind("claimToken") String claimToken); default List claimPending(int batchSize) { return claimPending(batchSize, 0, 0); @@ -13587,17 +13670,31 @@ default List claimPending( if (claimed.size() >= batchSize) { break; } + String claimToken = UUID.randomUUID().toString(); int updated = - claimRecord(candidate.getEntityId(), candidate.getEntityFqn(), candidate.getStatus()); + claimRecord( + candidate.getEntityId(), + candidate.getEntityFqn(), + candidate.getStatus(), + claimToken); if (updated == 1) { - claimed.add(candidate); + claimed.add( + new SearchIndexRetryRecord( + candidate.getEntityId(), + candidate.getEntityFqn(), + candidate.getFailureReason(), + "IN_PROGRESS", + candidate.getEntityType(), + candidate.getRetryCount(), + new java.sql.Timestamp(System.currentTimeMillis()), + claimToken)); } } return claimed; } @SqlQuery( - "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt " + "SELECT entityId, entityFqn, failureReason, status, entityType, retryCount, claimedAt, claimToken " + "FROM search_index_retry_queue ORDER BY retryCount DESC, claimedAt DESC " + "LIMIT :limit OFFSET :offset") @RegisterRowMapper(SearchIndexRetryRecordMapper.class) @@ -13616,7 +13713,8 @@ public SearchIndexRetryRecord map(ResultSet rs, StatementContext ctx) throws SQL rs.getString("status"), rs.getString("entityType"), rs.getInt("retryCount"), - rs.getTimestamp("claimedAt")); + rs.getTimestamp("claimedAt"), + rs.getString("claimToken")); } } } 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..2294a01a37ca 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 { @@ -3622,6 +3632,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)); } @@ -3908,10 +3921,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()); } @@ -4121,6 +4130,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 +4161,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; @@ -4882,19 +4913,6 @@ protected final void cleanup(String deletedBy, T entityInterface) { // 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); } @@ -4907,7 +4925,8 @@ private void markEntityNotFound(T entity) { notFoundCache.markNotFoundById(entityType, entity.getId()); } if (entity.getFullyQualifiedName() != null) { - notFoundCache.markNotFoundByName(entityType, entity.getFullyQualifiedName()); + notFoundCache.markNotFoundByName( + entityType, cacheNameKey(entityType, entity.getFullyQualifiedName()).getRight()); } } @@ -10643,15 +10662,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 +10679,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 +10741,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 +10757,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 +10782,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 +10805,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 +10818,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 +10864,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/LineageRepository.java b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java index 75387b56320e..f70d73060a07 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/LineageRepository.java @@ -1254,13 +1254,7 @@ public boolean deleteLineageByFQN( if (!nullOrEmpty(relationshipObject)) { // Finally, delete lineage relationship boolean result = - dao.relationshipDAO() - .delete( - from.getId(), - from.getType(), - to.getId(), - to.getType(), - Relationship.UPSTREAM.ordinal()) + deleteLineageRelationshipWithRetry(from.getId(), from.getType(), to.getId(), to.getType()) > 0; LineageDetails lineageDetails = JsonUtils.readValue(relationshipObject.getJson(), LineageDetails.class); @@ -1337,13 +1331,7 @@ public boolean deleteLineage( if (!nullOrEmpty(relationshipObject)) { // Finally, delete lineage relationship boolean result = - dao.relationshipDAO() - .delete( - from.getId(), - from.getType(), - to.getId(), - to.getType(), - Relationship.UPSTREAM.ordinal()) + deleteLineageRelationshipWithRetry(from.getId(), from.getType(), to.getId(), to.getType()) > 0; LineageDetails lineageDetails = JsonUtils.readValue(relationshipObject.getJson(), LineageDetails.class); @@ -1479,13 +1467,8 @@ private void processExtendedLineageCleanup(EntityReference fromRef, EntityRefere LineageDetails lineageDetails = JsonUtils.readValue(relation.getJson(), LineageDetails.class); if (lineageDetails.getAssetEdges() - 1 < 1) { - dao.relationshipDAO() - .delete( - fromRef.getId(), - fromRef.getType(), - toRef.getId(), - toRef.getType(), - Relationship.UPSTREAM.ordinal()); + deleteLineageRelationshipWithRetry( + fromRef.getId(), fromRef.getType(), toRef.getId(), toRef.getType()); deleteLineageFromSearch(fromRef, toRef, lineageDetails); } else { lineageDetails.withAssetEdges(lineageDetails.getAssetEdges() - 1); @@ -1513,6 +1496,14 @@ private void processExtendedLineageCleanup(EntityReference fromRef, EntityRefere } } + private int deleteLineageRelationshipWithRetry( + UUID fromId, String fromEntity, UUID toId, String toEntity) { + return DeadlockRetry.execute( + () -> + dao.relationshipDAO() + .delete(fromId, fromEntity, toId, toEntity, Relationship.UPSTREAM.ordinal())); + } + private void processDeletedRelations( List relations, String deletedBy) { for (CollectionDAO.EntityRelationshipObject obj : relations) { 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..95c82cf55352 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; @@ -31,7 +33,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 +43,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; @@ -96,6 +98,7 @@ 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.rdf.RdfUpdater; import org.openmetadata.service.resources.dqtests.TestCaseResource; @@ -121,6 +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"; + 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()); @@ -984,11 +991,31 @@ 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())); + ChangeDescription changeDescription = + new ChangeDescription() + .withPreviousVersion(testSuite.getVersion()) + .withFieldsUpdated(List.of(testsChange)); + testSuite.setChangeDescription(changeDescription); + testSuite.setIncrementalChangeDescription(changeDescription); + EntityLifecycleEventDispatcher.getInstance() + .onEntitiesUpdated( + List.of(testSuite), + null, + null, + new EntityUpdateContext( + Map.of(testSuite.getId(), relationshipChange.relationshipRevision()))); + RdfUpdater.updateEntity(testSuite); } @Transaction @@ -1095,142 +1122,110 @@ public void isTestSuiteBasic(String testSuiteFqn) { } } - @Transaction public RestUtil.PutResponse addTestCasesToLogicalTestSuite( TestSuite testSuite, List testCaseIds) { + AtomicReference relationshipChange = + new AtomicReference<>(LogicalSuiteRelationshipChange.empty()); + flushInOneTransaction( + () -> + relationshipChange.set( + addTestCasesToLogicalTestSuiteFlush(testSuite.getId(), testCaseIds))); + + postLogicalSuiteRelationshipUpdate(relationshipChange.get()); + updateLogicalTestSuite(relationshipChange.get()); + return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); + } + + private LogicalSuiteRelationshipChange 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 = + List addedTestCases = 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 prepareLogicalSuiteRelationshipChange(testSuiteId, addedTestCases); } 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 relationshipChange = + new AtomicReference<>(LogicalSuiteRelationshipChange.empty()); + flushInOneTransaction( + () -> + relationshipChange.set( + addAllTestCasesToLogicalTestSuiteFlush(testSuite.getId(), excludedTestCaseIds))); + + 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(relationshipChange.get()); + return new RestUtil.PutResponse<>(Response.Status.OK, testSuite, LOGICAL_TEST_CASE_ADDED); } - @Transaction - RestUtil.PutResponse addAllTestCasesToLogicalTestSuiteTxn( - TestSuite testSuite, List excludedTestCaseIds) { + private LogicalSuiteRelationshipChange 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 = + List addedTestCases = 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 prepareLogicalSuiteRelationshipChange(testSuiteId, addedTestCases); } - @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); - TestCase updatedTestCase = Entity.getEntity(Entity.TEST_CASE, testCaseId, "*", Include.ALL); - ChangeDescription change = - new ChangeDescription() - .withFieldsUpdated( - List.of( - new FieldChange() - .withName("testSuites") - .withNewValue(updatedTestCase.getTestSuites()))); - updatedTestCase.setChangeDescription(change); - - postUpdate(testCase, updatedTestCase); - updateLogicalTestSuite(testSuiteId); + AtomicReference relationshipChange = + new AtomicReference<>(LogicalSuiteRelationshipChange.empty()); + flushInOneTransaction( + () -> { + deleteRelationship(testSuiteId, TEST_SUITE, testCaseId, TEST_CASE, Relationship.CONTAINS); + relationshipChange.set( + prepareLogicalSuiteRelationshipChange( + testSuiteId, List.of(testCase.getEntityReference()))); + }); + + TestCase updatedTestCase = + postLogicalSuiteRelationshipUpdate(relationshipChange.get()).getFirst(); + updateLogicalTestSuite(relationshipChange.get()); testCase.setTestSuite(updatedTestCase.getTestSuite()); testCase.setTestSuites(updatedTestCase.getTestSuites()); return new RestUtil.DeleteResponse<>(testCase, ENTITY_DELETED); @@ -1240,43 +1235,128 @@ private List getLogicalSuiteUpdatedTestCase(List test List testCases = Entity.getEntities(testCaseReferences, "*", Include.ALL); testCases.forEach( tc -> { - ChangeDescription change = + FieldChange relationshipChange = + new FieldChange() + .withName(FIELD_TEST_SUITES) + .withNewValue(listOrEmpty(tc.getTestSuites())); + ChangeDescription changeDescription = new ChangeDescription() - .withFieldsUpdated( - List.of( - new FieldChange() - .withName("testSuites") - .withNewValue(tc.getTestSuites()))); - tc.setChangeDescription(change); + .withPreviousVersion(tc.getVersion()) + .withFieldsUpdated(List.of(relationshipChange)); + tc.setChangeDescription(changeDescription); + tc.setIncrementalChangeDescription(changeDescription); }); 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; + } + /** - * 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 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 void postLogicalSuiteRelationshipUpdate(List updatedTestCases) { - if (updatedTestCases == null || updatedTestCases.isEmpty()) { - return; + private List postLogicalSuiteRelationshipUpdate( + LogicalSuiteRelationshipChange relationshipChange) { + return postLogicalSuiteRelationshipUpdate( + relationshipChange.testCaseReferences(), relationshipChange.testCaseRevisions()); + } + + private List postLogicalSuiteRelationshipUpdate( + List testCaseReferences, Map testCaseRevisions) { + if (testCaseReferences.isEmpty()) { + return List.of(); } + var cachedReadBundle = CacheBundle.getCachedReadBundle(); if (cachedReadBundle != null) { - for (TestCase tc : updatedTestCases) { - cachedReadBundle.invalidate(entityType, tc.getId()); - } + testCaseReferences.forEach( + reference -> cachedReadBundle.invalidate(entityType, reference.getId())); } - EntityLifecycleEventDispatcher.getInstance().onEntitiesUpdated(updatedTestCases, null, null); + List updatedTestCases = getLogicalSuiteUpdatedTestCase(testCaseReferences); + EntityLifecycleEventDispatcher.getInstance() + .onEntitiesUpdated( + updatedTestCases, null, null, new EntityUpdateContext(testCaseRevisions)); updatedTestCases.forEach(RdfUpdater::updateEntity); + return updatedTestCases; + } + + 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); + } } @Override 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/resources/apps/AppResource.java b/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java index abf1b8c11020..17789e630151 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/resources/apps/AppResource.java @@ -88,6 +88,7 @@ import org.openmetadata.service.limits.Limits; import org.openmetadata.service.resources.Collection; import org.openmetadata.service.resources.EntityResource; +import org.openmetadata.service.search.SearchIndexRetryQueue; import org.openmetadata.service.search.SearchRepository; import org.openmetadata.service.secrets.SecretsManager; import org.openmetadata.service.secrets.SecretsManagerFactory; @@ -482,7 +483,19 @@ public Response listRetryQueue( } CollectionDAO.SearchIndexRetryQueueDAO retryQueueDAO = Entity.getCollectionDAO().searchIndexRetryQueueDAO(); - var records = retryQueueDAO.listAll(limitParam, offset); + var records = + retryQueueDAO.listAll(limitParam, offset).stream() + .map( + record -> + new CollectionDAO.SearchIndexRetryQueueDAO.SearchIndexRetryRecord( + record.getEntityId(), + record.getEntityFqn(), + SearchIndexRetryQueue.visibleFailureReason(record.getFailureReason()), + record.getStatus(), + record.getEntityType(), + record.getRetryCount(), + record.getClaimedAt())) + .toList(); int total = retryQueueDAO.countAll(); return Response.ok(new ResultList<>(records, offset, total)).build(); } diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java index eccb11ef8e5f..8669f090feea 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchIndexRetryQueue.java @@ -1,9 +1,13 @@ package org.openmetadata.service.search; import io.micrometer.core.instrument.Metrics; +import java.nio.charset.StandardCharsets; +import java.util.Base64; import java.util.UUID; import lombok.extern.slf4j.Slf4j; import org.openmetadata.schema.EntityInterface; +import org.openmetadata.schema.type.ChangeDescription; +import org.openmetadata.schema.utils.JsonUtils; import org.openmetadata.service.Entity; import org.openmetadata.service.jdbi3.CollectionDAO; @@ -19,6 +23,11 @@ public final class SearchIndexRetryQueue { private static final int MAX_REASON_LENGTH = 8192; + // The retry table is already deployed without a payload column. Keep the durable context in its + // TEXT failureReason while hiding this suffix from the queue API. + private static final String PROPAGATION_CONTEXT_MARKER = + "\n" + CollectionDAO.SearchIndexRetryQueueDAO.PROPAGATION_CONTEXT_TOKEN; + private SearchIndexRetryQueue() {} public static void enqueue(EntityInterface entity, String operation, Throwable failure) { @@ -34,6 +43,30 @@ public static void enqueue(EntityInterface entity, String operation, Throwable f failureReason(operation, failure)); } + public static void enqueueWithPropagation( + EntityInterface entity, + ChangeDescription propagationChangeDescription, + String failureReason) { + if (entity == null) { + return; + } + String entityType = + entity.getEntityReference() != null ? entity.getEntityReference().getType() : ""; + enqueue( + entity.getId() != null ? entity.getId().toString() : null, + entity.getFullyQualifiedName(), + entityType, + withPropagationContext(failureReason, propagationChangeDescription)); + } + + public static void enqueueWithPropagation( + EntityInterface entity, + ChangeDescription propagationChangeDescription, + String operation, + Throwable failure) { + enqueueWithPropagation(entity, propagationChangeDescription, failureReason(operation, failure)); + } + public static void enqueue(String entityId, String entityFqn, String failureReason) { enqueue(entityId, entityFqn, "", failureReason); } @@ -85,6 +118,62 @@ public static String failureReason(String operation, Throwable failure) { return truncate(safeOperation + ": " + message); } + static String withPropagationContext( + String failureReason, ChangeDescription propagationChangeDescription) { + if (propagationChangeDescription == null) { + return truncate(failureReason); + } + String encodedContext = + Base64.getUrlEncoder() + .withoutPadding() + .encodeToString( + JsonUtils.pojoToJson(propagationChangeDescription) + .getBytes(StandardCharsets.UTF_8)); + String visibleReason = truncate(failureReason); + return (visibleReason == null ? "" : visibleReason) + + PROPAGATION_CONTEXT_MARKER + + encodedContext; + } + + static ChangeDescription getPropagationContext(String failureReason) { + if (failureReason == null) { + return null; + } + int markerIndex = failureReason.lastIndexOf(PROPAGATION_CONTEXT_MARKER); + if (markerIndex < 0) { + return null; + } + String encodedContext = + failureReason.substring(markerIndex + PROPAGATION_CONTEXT_MARKER.length()); + try { + String json = + new String(Base64.getUrlDecoder().decode(encodedContext), StandardCharsets.UTF_8); + return JsonUtils.readValue(json, ChangeDescription.class); + } catch (Exception e) { + throw new IllegalArgumentException("Invalid search propagation retry context", e); + } + } + + public static String visibleFailureReason(String failureReason) { + if (failureReason == null) { + return null; + } + int markerIndex = failureReason.lastIndexOf(PROPAGATION_CONTEXT_MARKER); + return markerIndex < 0 ? failureReason : failureReason.substring(0, markerIndex); + } + + static String preservePropagationContext(String existingReason, String newReason) { + if (existingReason == null) { + return truncate(newReason); + } + int markerIndex = existingReason.lastIndexOf(PROPAGATION_CONTEXT_MARKER); + if (markerIndex < 0) { + return truncate(newReason); + } + String visibleReason = truncate(newReason); + return (visibleReason == null ? "" : visibleReason) + existingReason.substring(markerIndex); + } + public static String normalize(String value) { if (value == null) { return ""; @@ -112,6 +201,10 @@ private static String truncate(String value) { if (value == null) { return null; } + int markerIndex = value.lastIndexOf(PROPAGATION_CONTEXT_MARKER); + if (markerIndex >= 0) { + return truncate(value.substring(0, markerIndex)) + value.substring(markerIndex); + } if (value.length() <= MAX_REASON_LENGTH) { return value; } 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..a55edda3dd2c 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,8 @@ 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.ChangeDescription; import org.openmetadata.schema.type.EntityReference; import org.openmetadata.schema.type.Include; import org.openmetadata.schema.type.Relationship; @@ -31,10 +33,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; @@ -175,21 +180,16 @@ private void processRecord(SearchIndexRetryRecord record) { try { EntityReference root = resolveEntityReference(record); if (root != null) { - reindexEntityCascade(root); - collectionDAO - .searchIndexRetryQueueDAO() - .deleteByEntity(record.getEntityId(), record.getEntityFqn()); - Metrics.counter("search.retry.processed", "result", "success").increment(); + EntityInterface rootEntity = reindexEntityCascade(root); + propagateAfterRetry(rootEntity, record.getFailureReason()); + completeClaim(record); return; } String entityId = normalize(record.getEntityId()); if (!entityId.isEmpty()) { - removeStaleEntityById(entityId); - collectionDAO - .searchIndexRetryQueueDAO() - .deleteByEntity(record.getEntityId(), record.getEntityFqn()); - Metrics.counter("search.retry.processed", "result", "success").increment(); + removeStaleEntityById(entityId, record.getEntityType()); + completeClaim(record); return; } @@ -206,7 +206,9 @@ private void handleProcessingError(SearchIndexRetryRecord record, Exception e) { String reason = SearchIndexRetryQueue.failureReason("retryFailed", e); if (isRetryable(e)) { String nextStatus = retryableNextStatus(record.getRetryCount()); - recordRetryFailure(record, reason, nextStatus); + if (!recordRetryFailure(record, reason, nextStatus)) { + return; + } if (STATUS_FAILED.equals(nextStatus)) { Metrics.counter("search.retry.processed", "result", "exhausted").increment(); LOG.warn( @@ -225,7 +227,9 @@ private void handleProcessingError(SearchIndexRetryRecord record, Exception e) { e.getMessage()); } } else { - recordRetryFailure(record, reason, STATUS_FAILED); + if (!recordRetryFailure(record, reason, STATUS_FAILED)) { + return; + } Metrics.counter("search.retry.processed", "result", "non_retryable").increment(); LOG.warn( "Non-retryable error for entityId={} entityFqn={}, marking as FAILED: {}", @@ -235,11 +239,45 @@ private void handleProcessingError(SearchIndexRetryRecord record, Exception e) { } } - private void recordRetryFailure(SearchIndexRetryRecord record, String reason, String status) { - collectionDAO - .searchIndexRetryQueueDAO() - .updateFailureAndRetryCount(record.getEntityId(), record.getEntityFqn(), reason, status); + boolean recordRetryFailure(SearchIndexRetryRecord record, String reason, String status) { + String retainedReason = + SearchIndexRetryQueue.preservePropagationContext(record.getFailureReason(), reason); + int updated = + collectionDAO + .searchIndexRetryQueueDAO() + .updateFailureAndRetryCount( + record.getEntityId(), + record.getEntityFqn(), + retainedReason, + status, + record.getClaimToken()); + if (updated == 0) { + recordSuperseded(record); + return false; + } Metrics.counter("search.retry.processed", "result", "failure").increment(); + return true; + } + + boolean completeClaim(SearchIndexRetryRecord record) { + int deleted = + collectionDAO + .searchIndexRetryQueueDAO() + .deleteClaimed(record.getEntityId(), record.getEntityFqn(), record.getClaimToken()); + if (deleted == 0) { + recordSuperseded(record); + return false; + } + Metrics.counter("search.retry.processed", "result", "success").increment(); + return true; + } + + private void recordSuperseded(SearchIndexRetryRecord record) { + Metrics.counter("search.retry.processed", "result", "superseded").increment(); + LOG.debug( + "Search retry claim was superseded for entityId={} entityFqn={}", + record.getEntityId(), + record.getEntityFqn()); } // --------------------------------------------------------------------------- @@ -377,12 +415,14 @@ private List candidateEntityTypes() { // Reindexing // --------------------------------------------------------------------------- - private void reindexEntityCascade(EntityReference root) throws Exception { + EntityInterface 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; + EntityInterface rootEntity = null; while (!queue.isEmpty() && processed < MAX_CASCADE_REINDEX) { EntityReference current = queue.poll(); @@ -399,24 +439,35 @@ 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); - } catch (Exception ex) { + snapshot = loadStableEntitySnapshot(current); + } catch (EntityNotFoundException ex) { + removeStaleEntityById(current.getId().toString(), current.getType()); continue; + } catch (Exception ex) { + throw ex; } + EntityInterface entity = snapshot.entity(); if (entity == null) { - continue; + throw new IllegalStateException( + "Loaded an empty entity while processing search retry for " + current.getId()); + } + if (root.getId().equals(current.getId()) && root.getType().equals(current.getType())) { + rootEntity = entity; } 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 +494,60 @@ private void reindexEntityCascade(EntityReference root) throws Exception { } if (!entitiesToIndex.isEmpty()) { - upsertEntitiesInBulk(entitiesToIndex); + upsertEntitiesInBulk(entitiesToIndex, relationshipRevisions); + } + return rootEntity; + } + + void propagateAfterRetry(EntityInterface rootEntity, String failureReason) throws IOException { + ChangeDescription propagationChangeDescription = + SearchIndexRetryQueue.getPropagationContext(failureReason); + if (rootEntity != null && propagationChangeDescription != null) { + searchRepository.propagateEntityAfterRetry(rootEntity, propagationChangeDescription); } } - 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 +585,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 +638,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; @@ -529,7 +667,7 @@ private void upsertEntityDirect(EntityInterface entity) throws Exception { searchRepository .getSearchClient() .createEntity( - indexMapping.getIndexName(searchRepository.getClusterAlias()), + searchRepository.getWriteIndexName(indexMapping), entity.getId().toString(), JsonUtils.pojoToJson(doc)); } @@ -549,22 +687,37 @@ private void addChildrenByRelation( } } - private void removeStaleEntityById(String entityId) { - for (String entityType : searchRepository.getSearchEntities()) { + void removeStaleEntityById(String entityId, String entityTypeHint) throws Exception { + String normalizedEntityType = normalize(entityTypeHint); + Set entityTypes = + normalizedEntityType.isEmpty() + || searchRepository.getIndexMapping(normalizedEntityType) == null + ? searchRepository.getSearchEntities() + : Set.of(normalizedEntityType); + for (String entityType : entityTypes) { IndexMapping indexMapping = searchRepository.getIndexMapping(entityType); if (indexMapping == null) { continue; } - try { - searchRepository - .getSearchClient() - .deleteEntity(indexMapping.getIndexName(searchRepository.getClusterAlias()), entityId); - } catch (Exception ignored) { - // Ignore not-found / index mismatch and continue best-effort cleanup. + String canonicalIndex = indexMapping.getIndexName(searchRepository.getClusterAlias()); + for (String targetIndex : searchRepository.getWriteFanoutTargets(canonicalIndex)) { + try { + searchRepository.getSearchClient().deleteEntity(targetIndex, entityId); + } catch (ElasticsearchException e) { + if (e.status() != 404) { + throw e; + } + } catch (OpenSearchException e) { + if (e.status() != 404) { + throw e; + } + } } } } + 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 3a289e60c172..97af2b9c306b 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; @@ -118,6 +119,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; @@ -146,6 +148,7 @@ import org.openmetadata.service.search.elasticsearch.ElasticSearchClient; import org.openmetadata.service.search.elasticsearch.EsUtils; import org.openmetadata.service.search.indexes.ColumnSearchIndex; +import org.openmetadata.service.search.indexes.DocBuildContext; import org.openmetadata.service.search.indexes.PipelineExecutionIndex; import org.openmetadata.service.search.indexes.SearchIndex; import org.openmetadata.service.search.lineage.LineageDomainFilter; @@ -204,6 +207,116 @@ public void run() { } } + public record ScriptedPartialUpdate( + String script, Map parameters, boolean scriptedUpsert) { + public ScriptedPartialUpdate(String script, Map parameters) { + this(script, parameters, false); + } + + /** + * Converts null document fields into explicit removals for the relationship-preserving + * scripted-upsert contract. Omitting a null parameter leaves the old value untouched in the + * existing search document. + */ + public Map parametersForIndexing() { + if (!scriptedUpsert || parameters.values().stream().noneMatch(Objects::isNull)) { + return parameters; + } + + Map normalizedParameters = new LinkedHashMap<>(); + Set fieldsToRemove = new TreeSet<>(); + Object configuredRemovals = parameters.get("fieldsToRemove"); + if (configuredRemovals instanceof Iterable removals) { + for (Object field : removals) { + if (field != null) { + fieldsToRemove.add(field.toString()); + } + } + } + parameters.forEach( + (field, value) -> { + if ("fieldsToRemove".equals(field)) { + return; + } + if (value == null) { + fieldsToRemove.add(field); + } else { + normalizedParameters.put(field, value); + } + }); + if (!fieldsToRemove.isEmpty()) { + normalizedParameters.put("fieldsToRemove", List.copyOf(fieldsToRemove)); + } + return normalizedParameters; + } + } + + 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 * enqueue their work instead of running it inline. Returns {@code true} if this call opened the @@ -343,8 +456,15 @@ public static void deferOrRunSearchWrite( "extension", "queryUsedIn", "votes", - "pipelineStatus", - TEST_SUITES); + "pipelineStatus"); + + 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; @@ -1093,6 +1213,7 @@ public void createEntityIndex(EntityInterface entity) { SearchIndexRetryQueue.enqueue( entityId, entity.getFullyQualifiedName(), + entityType, SearchIndexRetryQueue.failureReason("createEntityIndex", ie)); LOG.error( "Issue creating new search document for entity [{}] and entityType [{}]", @@ -1349,6 +1470,7 @@ public void createEntitiesIndex(List entities) throws IOExcepti SearchIndexRetryQueue.enqueue( entity.getId() != null ? entity.getId().toString() : null, entity.getFullyQualifiedName(), + entityType, "createEntitiesIndex: Search client unavailable"); } return; @@ -1515,11 +1637,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(), @@ -1531,11 +1653,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; } @@ -1561,35 +1687,55 @@ 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); - } 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( + DocBuildContext.withRelationshipRevision(relationshipRevision))); 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.parametersForIndexing(); + } + } } searchClient.updateEntity(getWriteIndexName(indexMapping), entityId, doc, scriptTxt); @@ -1612,12 +1758,7 @@ public void updateEntityIndex(EntityInterface entity) { if (requiresPropagation(changeDescription, entityType, entity)) { // Time propagation operations startTime = System.currentTimeMillis(); - propagateInheritedFieldsToChildren( - entityType, entityId, changeDescription, indexMapping, entity); - propagateGlossaryTags(entityType, entity.getFullyQualifiedName(), changeDescription); - propagateCertificationTags(entityType, entity, changeDescription); - propagateServiceStyle(entityType, entity, changeDescription); - propagateToRelatedEntities(entityType, changeDescription, indexMapping, entity); + propagateEntitySearchChanges(entity, entityType, changeDescription, indexMapping); propagateTime = System.currentTimeMillis() - startTime; LOG.info( @@ -1648,10 +1789,7 @@ public void updateEntityIndex(EntityInterface entity) { Metrics.counter("search.index.propagation.skipped", tags).increment(); } } catch (Exception ie) { - SearchIndexRetryQueue.enqueue( - entityId, - entity.getFullyQualifiedName(), - SearchIndexRetryQueue.failureReason("updateEntityIndex", ie)); + enqueueEntityRetry(entity, "updateEntityIndex", ie); LOG.error( "Issue updating the search document for entity [{}] and entityType [{}]", entityId, @@ -1772,10 +1910,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<>(); @@ -1811,53 +1964,181 @@ public void updateEntitiesIndex(List entities) { int batchSize = 100; int maxConcurrentRequests = 5; long maxPayloadSizeBytes = SearchClusterMetrics.DEFAULT_BULK_PAYLOAD_SIZE_BYTES; + List propagationCandidates = new ArrayList<>(); // Process each entity type separately to ensure correct index routing for (Map.Entry> entry : entitiesByType.entrySet()) { String entityType = entry.getKey(); List typeEntities = entry.getValue(); + Map typeEntitiesById = + typeEntities.stream() + .collect( + Collectors.toUnmodifiableMap( + entity -> entity.getId().toString(), Function.identity())); + Map typeEntitiesByFqn = + typeEntities.stream() + .filter(entity -> !nullOrEmpty(entity.getFullyQualifiedName())) + .collect( + Collectors.toUnmodifiableMap( + EntityInterface::getFullyQualifiedName, + Function.identity(), + (first, ignored) -> first)); if (!getSearchClient().isClientAvailable()) { for (EntityInterface entity : typeEntities) { - SearchIndexRetryQueue.enqueue( - entity.getId() != null ? entity.getId().toString() : null, - entity.getFullyQualifiedName(), - "updateEntitiesBulk: Search client unavailable"); + enqueueEntityRetry(entity, "updateEntitiesBulk: Search client unavailable"); } continue; } 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); + } + EntityInterface failedEntity = + !nullOrEmpty(failedEntityId) ? typeEntitiesById.get(failedEntityId) : null; + if (failedEntity == null && !nullOrEmpty(failedEntityFqn)) { + failedEntity = typeEntitiesByFqn.get(failedEntityFqn); + } + String failureReason = "updateEntitiesBulk " + stage + ": " + errorMessage; + if (failedEntity != null) { + enqueueEntityRetry(failedEntity, failureReason); + } else { + SearchIndexRetryQueue.enqueue( + failedEntityId, failedEntityFqn, failedEntityType, failureReason); + } + }); 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); - bulkSink.flushAndAwait(60); // Wait up to 60 seconds for completion + bulkWriteReturned = true; + 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( + "Bulk entity update did not complete successfully for type " + entityType); + } + propagationCandidates.addAll(typeEntities); } 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 = false; + StepStats finalSinkStats = null; + if (bulkSink != null) { + bulkSinkQuiescent = closeBulkSinkAndCheckQuiescent(bulkSink); + finalSinkStats = bulkSink.getStats(); + bulkSink = null; + } + if (!bulkWriteAttempted) { + for (EntityInterface entity : typeEntities) { + try { + 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); + } + } + } else { + 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; + } + enqueueEntityRetry( + entity, + "updateEntitiesBulk: outcome unknown after bulk write; skipped stale fallback", + e); } } } finally { if (bulkSink != null) { - try { - bulkSink.close(); - } catch (Exception e) { - LOG.warn("Error closing bulk sink", e); - } + closeBulkSinkAndCheckQuiescent(bulkSink); } } } - // Run fan-out propagation once after all bulk doc updates are flushed. - propagateEntitiesAfterBulkFlush(dedupedEntities.values()); + propagateEntitiesAfterBulkFlush(propagationCandidates); + } + + 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 && recordedFailures == 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()); + } + } } private void propagateEntitiesAfterBulkFlush(Iterable entities) { @@ -1887,12 +2168,7 @@ private void propagateEntitiesAfterBulkFlush(Iterable entities) candidates++; try { IndexMapping indexMapping = entityIndexMap.get(entityType); - propagateInheritedFieldsToChildren( - entityType, entity.getId().toString(), changeDescription, indexMapping, entity); - propagateGlossaryTags(entityType, entity.getFullyQualifiedName(), changeDescription); - propagateCertificationTags(entityType, entity, changeDescription); - propagateServiceStyle(entityType, entity, changeDescription); - propagateToRelatedEntities(entityType, changeDescription, indexMapping, entity); + propagateEntitySearchChanges(entity, entityType, changeDescription, indexMapping); propagated++; } catch (Exception e) { LOG.error( @@ -1912,6 +2188,64 @@ private void propagateEntitiesAfterBulkFlush(Iterable entities) } } + void propagateEntityAfterRetry( + EntityInterface entity, ChangeDescription propagationChangeDescription) throws IOException { + if (entity == null || entity.getId() == null || entity.getEntityReference() == null) { + return; + } + String entityType = entity.getEntityReference().getType(); + if (!checkIfIndexingIsSupported(entityType) + || !requiresPropagation(propagationChangeDescription, entityType, entity)) { + return; + } + propagateEntitySearchChanges( + entity, entityType, propagationChangeDescription, entityIndexMap.get(entityType)); + } + + private void propagateEntitySearchChanges( + EntityInterface entity, + String entityType, + ChangeDescription changeDescription, + IndexMapping indexMapping) + throws IOException { + propagateInheritedFieldsToChildren( + entityType, entity.getId().toString(), changeDescription, indexMapping, entity); + propagateGlossaryTags(entityType, entity.getFullyQualifiedName(), changeDescription); + propagateCertificationTags(entityType, entity, changeDescription); + propagateServiceStyle(entityType, entity, changeDescription); + propagateToRelatedEntities(entityType, changeDescription, indexMapping, entity); + } + + private void enqueueEntityRetry(EntityInterface entity, String failureReason) { + if (entity == null) { + return; + } + ChangeDescription changeDescription = getEffectiveChangeDescription(entity); + if (!isNullOrEmptyChangeDescription(changeDescription)) { + SearchIndexRetryQueue.enqueueWithPropagation(entity, changeDescription, failureReason); + return; + } + String entityType = + entity.getEntityReference() != null ? entity.getEntityReference().getType() : ""; + SearchIndexRetryQueue.enqueue( + entity.getId() != null ? entity.getId().toString() : null, + entity.getFullyQualifiedName(), + entityType, + failureReason); + } + + private void enqueueEntityRetry(EntityInterface entity, String operation, Throwable failure) { + if (entity == null) { + return; + } + ChangeDescription changeDescription = getEffectiveChangeDescription(entity); + if (!isNullOrEmptyChangeDescription(changeDescription)) { + SearchIndexRetryQueue.enqueueWithPropagation(entity, changeDescription, operation, failure); + return; + } + SearchIndexRetryQueue.enqueue(entity, operation, failure); + } + public void updateEntitiesBulk(List entities) { updateEntitiesIndex(entities); } @@ -3132,11 +3466,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 = @@ -3150,10 +3479,78 @@ public String getScriptWithParams( return scriptTxt.toString(); } + public ScriptedPartialUpdate buildBulkScriptedPartialUpdate(EntityInterface entity) { + return buildBulkScriptedPartialUpdate(entity, null); + } + + public ScriptedPartialUpdate buildRelationshipDocumentUpdate( + EntityInterface entity, Map document) { + RelationshipRevisionSpec revisionSpec = relationshipRevisionSpec(entity); + if (revisionSpec == null || document == null) { + return null; + } + return new ScriptedPartialUpdate( + revisionSpec.documentUpdateScript(), new HashMap<>(document), true); + } + + public ScriptedPartialUpdate buildBulkScriptedPartialUpdate( + EntityInterface entity, Long relationshipRevision) { + RelationshipRevisionSpec revisionSpec = relationshipRevisionSpec(entity); + if (revisionSpec == null || relationshipRevision == null) { + return null; + } + 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( + 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() - && changedFieldNames.stream().allMatch(PARTIAL_SCRIPT_SUPPORTED_FIELDS::contains); + && changedFieldNames.stream().allMatch(PARTIAL_SCRIPT_SUPPORTED_FIELDS::contains) + && !hasRelationshipReplacement(changeDescription, TEST_SUITES) + && !hasRelationshipReplacement(changeDescription, TESTS); + } + + private boolean hasRelationshipReplacement( + ChangeDescription changeDescription, String relationshipField) { + return changeDescription != null + && listOrEmpty(changeDescription.getFieldsUpdated()).stream() + .anyMatch(fieldChange -> relationshipField.equals(fieldChange.getName())); } private Set getChangedFieldNames(ChangeDescription changeDescription) { @@ -3675,7 +4072,8 @@ public Set getSearchEntities() { private boolean shouldSkipStreamingIndexing( String entityType, String entityId, String entityFqn, String operation) { if (!getSearchClient().isClientAvailable()) { - SearchIndexRetryQueue.enqueue(entityId, entityFqn, operation + ": Search client unavailable"); + SearchIndexRetryQueue.enqueue( + entityId, entityFqn, entityType, operation + ": Search client unavailable"); return true; } return false; diff --git a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchUtils.java b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchUtils.java index 7241011bbd2e..6e367e1319d5 100644 --- a/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchUtils.java +++ b/openmetadata-service/src/main/java/org/openmetadata/service/search/SearchUtils.java @@ -683,6 +683,8 @@ public static boolean isDataAssetIndex(String indexName) { Entity.SPREADSHEET, "file_search_index", Entity.FILE, + "context_file_search_index", + Entity.CONTEXT_FILE, "metric_search_index", Entity.METRIC -> true; default -> false; @@ -774,6 +776,7 @@ public static String mapEntityTypesToIndexNames(String indexName) { case "file_search_index", Entity.FILE -> Entity.FILE; case "worksheet_search_index", Entity.WORKSHEET -> Entity.WORKSHEET; case "spreadsheet_search_index", Entity.SPREADSHEET -> Entity.SPREADSHEET; + case "context_file_search_index", Entity.CONTEXT_FILE -> Entity.CONTEXT_FILE; case "column_search_index", Entity.TABLE_COLUMN -> Entity.TABLE_COLUMN; case "dataAsset" -> "dataAsset"; default -> "dataAsset"; 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..da764c2675ec 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,53 @@ *
  • {@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 withRelationshipRevision(long relationshipRevision) { + return new DocBuildContext(null, ServiceStylePrefetch.notPrefetched(), relationshipRevision); } 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