Skip to content

fix: bulk backend + Airflow + integration-test refresh (17 files) - #33883

Merged
chirag-madlani merged 12 commits into
mainfrom
chirag-madlani/backend-airflow-ingestion-bulk
Sep 25, 2026
Merged

chirag-madlani merged 12 commits into
mainfrom
chirag-madlani/backend-airflow-ingestion-bulk

Conversation

@chirag-madlani

@chirag-madlani chirag-madlani commented Sep 23, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #33087

Describe your changes:

Bulk refresh 17 files across backend Java, Airflow Python, and integration tests from #33088. All files are pure additions OR wholesale copies from harshach's branch where main has not touched the file since our merge-base — no conflict resolution ambiguity.

Backend Java (5)

  • DataContractRepository.java — correct data-contract result retrieval to use execution identity (not timestamp)
  • DataContractResource.java — matching resource-layer plumbing
  • EntityLifecycleEventDispatcher.java — immutable snapshot with a synchronised swap so a registration racing a dispatch cannot NPE on the vacated tail slot. Race is reachable in production (SearchRepository rebuild + vector-service reinit both re-register handlers while requests are in flight).
  • RdfLiveWriter.java — matching fix for the RDF projection write path
  • IngestionPipelineRepositoryTest.java — accompanying unit test

Integration tests Java (3)

  • DataContractResourceIT.java — regression tests for both result-ID lookup fixes
  • RdfLiveProjectionIT.java — RDF projection tests
  • SearchIndexRetryQueueIT.java — retry-queue test isolation

Airflow Python (9)

  • api/response.py, api/utils.py — response/util fixes
  • operations/deploy.py — wait for fresh registered/serialized DAG metadata before deployment is considered trigger-ready
  • utils/pipeline_run_id.py (new) — pipeline-run-id helper
  • tests/conftest.py (new)
  • tests/integration/operations/test_dag_lifecycle.py (new) — DAG lifecycle integration tests
  • tests/integration/operations/test_airflow_ops.py, tests/unit/ingestion_pipeline/test_build_dag.py, tests/unit/test_helpers.py — refreshed

Type of change:

  • Bug fixes (real correctness issues in DataContract result lookup, dispatcher race, RDF writes)
  • Test coverage additions

Notes

Cherry-picked from #33088. All original content authored by @harshach.

🤖 Generated with Claude Code

RetriggerConfidence Score: 5/5

The PR appears safe to merge because no accepted new issue or outstanding previous finding remains.

Summary

This PR refreshes backend, Airflow, and integration-test behavior around data-contract result identity, ingestion run identity, DAG lifecycle management, concurrent event-handler registration, and retry-queue isolation.

  • Retrieves data-contract results by execution UUID while retaining contract scoping.
  • Normalizes Airflow run identities across API responses, task execution, and failure callbacks.
  • Uses spawn-based background DAG scanning and waits for persisted, trigger-ready DAG metadata.
  • Deletes Airflow database metadata before removing DAG/configuration files.
  • Publishes immutable lifecycle-handler snapshots during concurrent registration.
  • Adds focused unit and integration coverage for the corrected behavior.
Diagram
sequenceDiagram
  participant API as Managed Airflow API
  participant Parser as DAG Parser
  participant DB as Airflow Metadata DB
  participant Worker as Ingestion Task
  participant OM as OpenMetadata

  API->>Parser: Write and process DAG definition
  Parser->>DB: Persist registration and serialized DAG
  API->>DB: Wait for changed parse marker and serialization
  DB-->>API: DAG is trigger-ready
  API-->>API: Return deployment success
  Worker->>Worker: Derive UUID from DAG ID and Airflow run ID
  Worker->>OM: Update matching pipeline-run status
Loading

Reviews (5) · Last reviewed commit: "fix: refine deleteDeployedPipeline to sa..."

17 files — all pure additions OR wholesale copies from harshach's branch
where main has not touched the file since our merge-base. No conflict
resolution ambiguity.

Backend Java (5):
- DataContractRepository.java — correct data-contract result retrieval to
  use execution identity (not timestamp)
- DataContractResource.java — matching resource-layer plumbing
- EntityLifecycleEventDispatcher.java — immutable snapshot with a synchronised
  swap so a registration racing a dispatch cannot NPE on the vacated tail slot
- RdfLiveWriter.java — matching fix for the RDF projection write path
- IngestionPipelineRepositoryTest.java — accompanying test

Integration tests Java (3):
- DataContractResourceIT.java — regression tests for both result-ID lookup fixes
- RdfLiveProjectionIT.java — RDF projection tests
- SearchIndexRetryQueueIT.java — retry-queue test isolation

Airflow Python (9):
- api/response.py, api/utils.py — response/util fixes
- operations/deploy.py — wait for fresh registered/serialized DAG metadata
  before deployment is considered trigger-ready
- utils/pipeline_run_id.py (new) — pipeline-run-id helper
- tests/conftest.py (new)
- tests/integration/operations/test_dag_lifecycle.py (new) — DAG lifecycle
  integration tests
- tests/integration/operations/test_airflow_ops.py — refreshed
- tests/unit/ingestion_pipeline/test_build_dag.py — refreshed
- tests/unit/test_helpers.py — refreshed

Cherry-picked from #33088. All original content authored by @harshach.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@chirag-madlani
chirag-madlani requested a review from a team as a code owner September 23, 2026 11:14
@github-actions

github-actions Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

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

@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs UI UI specific issues labels Sep 23, 2026
… delete for undeployed

Two follow-ups to make the airflow-apis-tests + service-unit-tests suites green:

1) send_failed_status_callback: derive runId from context.dag_run when the
   workflow_config's own pipelineRunId is None or missing. After a DAG reparse,
   build_dag's freshly-parsed pipelineRunId is a new random UUID that does not
   match the run the server actually recorded; using the id derived from
   dag_run.run_id via the same pipeline_run_id() helper the response layer uses
   makes the failed-status update land on the correct run. Fixes
   test_failure_callback_after_dag_reparse_updates_the_same_run.

2) IngestionPipelineRepository.deleteDeployedPipeline: early-return when the
   entity is not deployed. A metadata-only pipeline has no deployed workflow to
   remove from the runner, so requiring the runner to be reachable to complete
   a delete would fail with IngestionRunnerUnavailableException even when
   there is nothing to remove. Fixes
   IngestionPipelineRepositoryTest.deleteUndeployedPipelineDoesNotRequireRunner.

Both changes correspond to hunks that harshach's branch already carries; they
were excluded from the wholesale-copy batch because main had also touched the
same files. Applying the specific hunks that the tests exercise is the minimal
addition to make this PR self-consistent.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Three follow-up fixes on top of the earlier bulk backend refresh:

1. send_failed_status_callback: fix run-id resolution for the two paths that
   the earlier commit missed:
   - PREFER dag_run.conf.pipelineRunId when the server triggered the run.
     For server-triggered runs the server names the DagRun `manual__<ts>` and
     stashes the real UUID in `conf.pipelineRunId`; the derived UUIDv5 from
     the timestamped run_id does NOT match what the server queued.
   - duck-type the context on `.get` rather than `isinstance(dict)`. Airflow
     2.x's callback context is `airflow.utils.context.Context`, a
     `collections.abc.MutableMapping` and NOT a `dict` subclass. The earlier
     check silently returned False, dropped `dag_run`, and no-op'd the reparse
     fix on 2.x.
   Priority order is now: conf.pipelineRunId -> pipeline_run_id(dag_id,
   run_id) -> workflow_config.pipelineRunId.root.

2. IngestionPipelineRepository.deleteDeployedPipeline: previously guarded
   with early-return when `deployed=false`, which left DAG/config files in
   Airflow after a failed first-deploy attempt (files are written before
   the readiness check; scheduler eventually parses them into an orphan
   DAG). Now attempts runner cleanup regardless but tolerates an unavailable
   runner for undeployed pipelines (effective allowUnavailableRunner=true).
   Corresponding test assertion updated: cleanup is now skipped-but-attempted
   for the undeployed+unavailable case.

3. delete_dag_id (operations/delete.py): reorder so Airflow's own
   `delete_dag` runs FIRST inside a session, THEN files are removed. The
   original order removed files before the airflow-side deletion, so a
   RuntimeError like "TaskInstances still running" would leave the pipeline
   with an orphan record in Airflow's db and no files to re-parse. Fixes
   test_running_dag_keeps_its_files_when_deletion_is_rejected.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Previous fix (`effectiveAllowUnavailableRunner`) resolved gitar's
"failed-first-deploy leaves DAG on disk" concern but greptile then flagged
that a direct hard delete on an undeployed pipeline with unavailable runner
silently reports success — potentially orphaning Airflow artifacts.

Split by caller intent:
- Cascade/force delete (allowUnavailableRunner=true) — tolerate & report
  skipped, unchanged.
- Direct hard delete of a DEPLOYED pipeline + unavailable runner — surface
  the exception, unchanged.
- Direct hard delete of an UNDEPLOYED pipeline + unavailable runner —
  ATTEMPT cleanup (so files-on-disk from a failed first-deploy get removed
  when the runner IS reachable), swallow the unavailable exception (return
  false), but with an explicit doc note calling out the residual risk when
  runner is unreachable AND files exist. Proper fix is a compensating
  cleanup at deploy-readiness-timeout time, tracked separately.

Test updated: `deleteUndeployedPipelineDoesNotRequireRunner` back to
`assertFalse` with a comment explaining the metadata-only intent.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…amed import

The `delete` module was reordered so airflow's own delete runs FIRST inside the
session, and its import binds locally as `airflow_delete_dag` (not `delete_dag`).
The test still monkey-patched `delete.delete_dag` and used a 1-arg replacement,
so it AttributeErrored before `delete_dag_id` even ran.

- Patch the correct attribute (`airflow_delete_dag`).
- Accept the `session=` kwarg the call site passes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — manual (2026-09-24T11:53:34Z)

Blocked the queue: py-checkstyle

@github-actions

Copy link
Copy Markdown
Contributor

🚦 Removed from the merge queue — manual (2026-09-25T06:35:44Z)

Blocked the queue: py-checkstyle

py-checkstyle in the merge queue reported common.py needed reformat.
Ran ruff format 0.15.22 (CI's version) against ingestion/pyproject.toml.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@gitar-bot

gitar-bot Bot commented Sep 25, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 5 closed / 5 findings

🟡 Medium risk · Changes Airflow lifecycle and run identities plus data-contract result retrieval.

Bulk refresh of 17 files across backend Java, Airflow Python, and integration tests addressing data-contract result lookup by execution UUID, run-ID synchronization across Airflow response/task/callback layers, DAG lifecycle management with metadata persistence waits, concurrent event-handler registration safety, and retry-queue test isolation. Five correctness issues resolved: worker run-ID derivation now matches server identity, CustomPythonOperator scheduled-run coverage added, failure callbacks respect server runIds, failed deployments properly clean up Airflow metadata before file removal, and reparse context detection fixed for Airflow 2. No open issues.

✅ 5 closed
✅ Bug: Worker never derives run id from dag_run; status runIds diverge

📄 openmetadata-airflow-apis/openmetadata_managed_apis/api/response.py:85 📄 openmetadata-airflow-apis/tests/unit/ingestion_pipeline/test_build_dag.py:150-164
format_dag_run_state now reports runId = pipeline_run_id(dag_id, dag_run.run_id), but the worker side in workflows/ingestion/common.py was not updated to match. build_dag still sets pipelineRunId = uuid4() when the DAG is parsed. CustomPythonOperator.execute only overrides it from params['pipelineRunId']. send_failed_status_callback ignores the context and reads workflow_config.pipelineRunId. So the runId in the Airflow status response never matches the id the workflow or its failure callback reports under. That holds for scheduled runs and for server-triggered runs, where the server puts pipelineRunId in conf rather than in the Airflow run_id. The new tests fail for the same reason: test_run_identity_survives_the_queued_to_running_handoff and test_each_execution_gets_its_own_identity_without_reparsing_the_dag get the parse-time uuid4 back, and test_failure_callback_after_dag_reparse_updates_the_same_run looks up a random runId, gets None, and submits nothing. The common.py half of the cherry-pick looks like it was left out.

✅ Quality: No test covers scheduled-run runId derivation in CustomPythonOperator

📄 openmetadata-airflow-apis/openmetadata_managed_apis/workflows/ingestion/common.py:438-443
This new else branch is what keeps the worker's pipelineRunId equal to the UUIDv5 that format_dag_run_state reports for scheduled runs. No test calls CustomPythonOperator.execute or pipeline_run_id: grepping tests/ for either name finds nothing. If someone later drifts the helper or changes this branch, the server would go back to tracking two runs without any test failing. Add a unit test that calls execute with a context holding no params.pipelineRunId and a stub dag_run (a date-based run_id plus a dag_id). It should assert that workflow_config.pipelineRunId.root == pipeline_run_id(dag_id, run_id), and that a params.pipelineRunId, when present, still wins.

✅ Bug: Failure callback ignores server runId in conf for server-triggered runs

📄 openmetadata-airflow-apis/openmetadata_managed_apis/workflows/ingestion/common.py:374-388 📄 openmetadata-airflow-apis/openmetadata_managed_apis/workflows/ingestion/common.py:459-470
When the server triggers a run, runPipelineWithOptions sends only dag_id and conf.pipelineRunId (a random UUID). It never sends run_id, so Airflow names the DagRun manual__<timestamp>. CustomPythonOperator.execute puts the conf UUID into workflow_config.pipelineRunId, and the server's queued and running statuses use that id. The task's on_failure_callback now gives dag_run priority and calls pipeline_run_id(dag_id, 'manual__…'), which returns a UUIDv5 that differs from the conf id. get_pipeline_status then finds no record for that id, and setting .endDate fails. The exception is caught and only logged, so an on-demand run that fails stays running/queued on the server. Before this commit, the callback read the id that execute had synced, so this worked.

On Airflow 2, Context is a MutableMapping rather than a dict, so isinstance(context, dict) is False there. The two Airflow versions therefore end up resolving the id differently.

✅ Bug: Failed first deploy leaves DAG in Airflow that delete now skips

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/IngestionPipelineRepository.java:829-832 📄 openmetadata-airflow-apis/openmetadata_managed_apis/operations/deploy.py:175-177
deployed only becomes true after the runner returns 200 (see AirflowRESTClient.deployPipeline). The deployer writes the DAG and config files before refresh_session_dag runs. This PR adds a new 500 path: the 60s _wait_for_dag_registration timeout. When that path fires on a pipeline's first deploy, the files are already on disk and the scheduler will still register them, but the pipeline keeps deployed=false. With the new Boolean.FALSE.equals(entity.getDeployed()) early return, deleting that pipeline never calls the runner. The DAG file, its config, and any schedule keep running in Airflow after the metadata entity is gone. The same happens if deployed is PATCHed to false, since it is in PATCH_FIELDS. Deleting an undeployed pipeline used to always attempt cleanup. A better fix is to skip only when the runner is unavailable and the pipeline was never deployed, or to treat a 404 from the runner as success rather than skipping the call.

✅ Edge Case: isinstance(context, dict) misses Airflow 2 Context; reparse fix no-ops

📄 openmetadata-airflow-apis/openmetadata_managed_apis/workflows/ingestion/common.py:374-375 📄 openmetadata-airflow-apis/tests/unit/ingestion_pipeline/test_build_dag.py:203
On Airflow 2.x, which pyproject still supports (apache-airflow>=2.2.2), the callback context is an airflow.utils.context.Context. That class is a MutableMapping, not a dict subclass. So isinstance(context, dict) is False, dag_run becomes None, and the callback falls back to workflow_config.pipelineRunId. After a reparse, that is the random UUID4 set by build_dag, which is the case this change is meant to fix. For example, zombie or externally-killed task callbacks run in the DAG processor. get_pipeline_status then returns nothing and the status update fails. The unit test passes a plain dict, so it never hits this. Check against collections.abc.Mapping, or use getattr(context, "get", None), instead.

Review coverage

📋 Rules No rules evaluated

🧪 Functional validation Not enabled · Set up

🤖 Auto-approval Not enabled · Set up

Options

Display: compact → Counting what did not apply, without listing it.

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

Compact
gitar display:verbose         

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

@sonarqubecloud

Copy link
Copy Markdown

@sonarqubecloud

Copy link
Copy Markdown

This branch was previously deployed

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

Labels

safe to test Add this label to run secure Github workflows on PRs UI UI specific issues

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Merge queue: recover transient artifacts and stabilize recurring E2E failures

2 participants