Skip to content

Fixes 24806: refresh the Data Contract DQ DAG deployment on every validation - #31848

Merged
TeddyCr merged 4 commits into
open-metadata:mainfrom
TeddyCr:ISSUE-24806
Sep 3, 2026
Merged

TeddyCr merged 4 commits into
open-metadata:mainfrom
TeddyCr:ISSUE-24806

Conversation

@TeddyCr

@TeddyCr TeddyCr commented Aug 20, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes #24806

A Data Contract's DQ Airflow DAG keeps authenticating with the bot JWT that was current the moment
the contract was first created. Rotating or re-issuing the testsuite-bot token never reaches the
DAG, so every later validation fails with SigningKeyNotFoundException, and there was no server-side
path a contract user could hit to refresh it.

I made POST /v1/dataContracts/{id}/validate always re-deploy the DQ pipeline before triggering it,
so a contract run rewrites the DAG config with a freshly minted token and is self-healing — the
"Expected behavior" the issue asks for.

Type of change:

  • Bug fix

High-level design:

Where the token is pinned. The JWT reaches Airflow exactly once, when the DAG config JSON is
written at deploy time: DagDeployer.store_airflow_pipeline_config
(openmetadata-airflow-apis/.../operations/deploy.py:92) → dump_with_safe_jwt (:50), which
serialises openMetadataServerConnection.securityConfig.jwtToken into
DAG_GENERATED_CONFIGS/<dag_id>.json. The generated DAG re-reads that file on every Airflow parse
(workflows/workflow_factory.py), and workflows/ingestion/test_suite.py copies the connection
straight into workflowConfig. That file is the pin.

Everything upstream of it was already correct. The token is never persisted on the entity —
IngestionPipelineRepository.getFieldsStrippedFromStorageJson() strips
openMetadataServerConnection from the storage JSON — and OpenMetadataConnectionBuilder rebuilds
it from the bot's current DB row on every call, resolving TEST_SUITE → testsuite-bot.

The single gate. DataContractRepository.deployAndTriggerDQValidation guarded the redeploy
behind if (!pipeline.getDeployed()). Once deployed == true, prepareAndDeployIngestionPipeline
was never invoked again for the life of the contract, so the DAG config was written once at creation
and never rewritten.

Why other pipeline types were unaffected. IngestionPipelineRepository.requiresRedeployment
triggers a redeploy on schedule / enabled / sourceConfig / loggerLevel changes. For a metadata
or profiler agent the user edits the pipeline, so the token gets refreshed as a silent side effect.
For a data contract the user edits the DataContract entity, which mutates the TestSuite but never
touches the pipeline's airflowConfig/enabled/sourceConfig/loggerLevel — so
requiresRedeployment returned false every time.

k8s/Argo was never affected. K8sPipelineClient.runPipeline rebuilds the job from the passed
pipeline on every run and re-derives the bot token, so it has no equivalent pinned artifact.

⚠️ Red herring — please don't "simplify" this away. prepareAndRunIngestionPipeline builds a
fresh OpenMetadataConnection on every validate, which looks like the refresh already works. It
does not: AirflowRESTClient.runPipeline posts only {dag_id} (plus an optional conf override),
so that connection never leaves the server. Only deployPipeline posts the full IngestionPipeline
POJO, which is what carries the JWT.

A second non-obvious constraint, now guarded by an inline comment. The two
refreshOpenMetadataServerConnection calls look like duplication and are not. On a first deploy the
follow-up createOrUpdate runs storeEntity → SecretsManager.encryptIngestionPipeline, which at
SecretsManager.java:317 replaces the pipeline's openMetadataServerConnection with the
store=true form and writes it back onto the live object at :330 — a secret reference rather than
the token on an external secrets manager. The rebuild in prepareAndRunIngestionPipeline is what
puts the usable form back before the runner reads it. Folding the two calls into one at the top of
deployAndTriggerDQValidation is tempting and would be wrong.

Deliberate failure semantics. The refresh is best-effort for an already deployed pipeline
(deploy failure logs WARN and still triggers the existing DAG) and strict for a never-deployed
one
(failure propagates). Strict propagation everywhere would be wrong: it would convert a
transient Airflow blip into a new validation failure on installations that work today, whereas
triggering the previously deployed DAG is exactly the pre-fix behaviour. The masked window is
narrower than the catch suggests — refreshOpenMetadataServerConnection runs again outside the
try, so a missing testsuite-bot or a SecretsManagerException is logged and then immediately
rethrown two lines later, marking the result Aborted. Only the deploy HTTP call is genuinely
swallowed.

Cost. Per validation of a contract with quality expectations:

  • one extra POST <airflow>/deploy, which is not free server-side (deploy.py:176-186 runs
    store_airflow_pipeline_config + store_and_validate_dag_file + dag_bag.process_file +
    dag.sync_to_db + scan_dags_job_background());
  • two OpenMetadataConnectionBuilder constructions → 2× bot read, 2× user read, 2× JWT decrypt (a
    remote secret read on an external secrets manager), per the constraint above;
  • no DB write, no change event, no search-index write and no secrets-manager write —
    the && !alreadyDeployed guard keeps the refactor from introducing a createOrUpdate on every
    validation, whose real cost would be storeEntity → encryptIngestionPipeline →
    encryptPasswordFields(store=true), to persist a deployed flag that is already true.

Fan-out — please size this before merge. This is not only user-initiated.
DataContractValidationApp (seeded from json/data/app/DataContractValidationApplication.json,
cron 0 0 * * *) paginates every data contract in the installation in batches of 100 and calls
validateContract on each, plus a second sweep over data-product assets calling
validateContractWithEffective. So the extra deploy is N per day for N contracts, serially — not
per click. I judged this acceptable (it is the same call /ingestionPipelines/deploy/{id} already
makes, and it is what makes the fix self-healing with no user present), but it is worth a look from
someone who knows large-deployment contract counts.

What is NOT fixed. The issue lists three acceptable outcomes; the third — "saving a contract
should regenerate the DAG configuration" — remains unmet. requiresRedeployment still ignores
contract-driven edits, so the refresh happens on /validate only. In practice a rotated token heals
within ≤24h unattended via the nightly app, or immediately on a manual Run Now, but not at the
moment the user saves the contract. Adding a Redeploy button to the contract UI (the other
alternative the issue mentions) is also not included.

Recommended follow-up (not done here). A persistent /deploy failure on an already-deployed
contract is only visible as a WARN in openmetadata.log while validations keep failing against the
stale DAG — the exact symptom of this issue, with the cause hidden. Surfacing it on
DataContractResult.getResult() so the UI shows "DQ DAG could not be refreshed" would fix that, but
deployAndTriggerDQValidation is void and its two callers each construct their own
DataContractResult, so it is an observable behaviour change that deserves its own issue rather than
riding along on a scoped bug fix.

Tests:

Use cases covered

  • An admin rotates the testsuite-bot JWT; the next Data Contract validation re-deploys the DAG so
    it authenticates with the new token instead of the pinned one.
  • A validation still triggers the DAG run after the refresh (the refresh does not swallow the run).
  • The pipeline service is unreachable and the contract's DAG is already deployed → the
    validation still triggers the previously deployed DAG rather than failing.
  • The pipeline service is unreachable and the contract has never been deployed → the validation
    fails loudly instead of triggering a DAG that does not exist.

Unit tests

  • I added unit tests for the new/changed logic.

  • Files added: openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/DataContractPipelineTokenRefreshTest.java (4 tests)

  • Coverage on the changed methods (mvn jacoco:report, from this test class alone):

    Method Line coverage
    refreshDeployedPipelineBeforeRun 100% (10/10)
    refreshOpenMetadataServerConnection 100% (6/6)
    prepareAndRunIngestionPipeline 100% (3/3)
    prepareAndDeployIngestionPipeline 80% (8/10)
    deployAndTriggerDQValidation 60% (9/15)
    Total across changed methods 81.8% (36/44)

    Below the 90% target, and I would rather explain than pad it. The 8 uncovered lines are all
    pre-existing and unreachable from a unit test: 6 are the two guard-clause throws in
    deployAndTriggerDQValidation (no test suite / no pipelines), and 2 are
    setDeployed(true) + createOrUpdate — which need a real JDBI handle. Whole-class coverage of
    DataContractRepository from this class alone is ~4%, which is not a meaningful number: the class
    is 1,856 lines and these tests deliberately exercise only the validate path.

How the tests assert. Every assertion is on the payload that reaches the
PipelineServiceClientInterface boundary — recorded into a List<String> by a thenAnswer stub —
so they test what actually leaves the server rather than internal call wiring. There is no
verify() anywhere
in the class. DataContractRepository and IngestionPipelineRepository are
real instances; only the pipeline-service client (a genuine external boundary) is mocked. The bot's
token comes from a stubbed repository read backed by a mutable field, so the headline test rotates
the token mid-test and asserts the second deploy payload carries the new value.

Honest RED status: only one of the four fails without the fix.

  • validateRefreshesTheDeployedDagWithTheCurrentBotToken — fails pre-fix, and is the actual
    regression proof:
    org.opentest4j.AssertionFailedError: expected: <[stale-jwt-token, rotated-jwt-token]> but was: <[]>
    
    <[]> is the bug: two validations of an already-deployed contract with the token rotated in
    between, and not one deploy payload ever reached the pipeline service.
  • The other three pass both before and after. They pin the new best-effort semantics and guard
    the run path; they are not evidence of the bug and I am not presenting them as such.

Backend integration tests

  • Not applicable — no API surface changed (/validate already existed; only its internal
    behaviour changed).
  • Worth flagging for reviewers: deployAndTriggerDQValidation has no pre-existing IT coverage,
    and this specific behaviour cannot be asserted from an IT today — the IT harness wires a real
    AirflowRESTClient against no Airflow with no recording fake, so the deploy payload is not
    observable. That is why the regression test is a unit test. I did run the one existing IT that
    creates a contract with qualityExpectations (and therefore exercises the pipeline create +
    deploy path) as a non-regression check:
    DataContractResourceIT#testDataContractCreatesReverseTestSuiteRelationship → 1/1 pass.

Ingestion integration tests

  • Not applicable — no ingestion changes. The Python side is the symptom location, not the
    defect; no file under ingestion/ or openmetadata-airflow-apis/ was modified.

Playwright (UI) tests

  • Not applicable — no UI changes.

Manual testing performed ✅

  1. Bring up the stack and note the Airflow DAG config dir
    (AIRFLOW__OPENMETADATA_AIRFLOW_APIS__DAG_GENERATED_CONFIGS; dev default
    /opt/airflow/dag_generated_configs).
  2. Create a table, create a test case on it, then create a Data Contract on that table with that test
    case under Quality Expectations. This deploys the DAG once.
  3. Capture the pinned token as TOKEN_A and the file mtime:
    docker exec -it openmetadata_ingestion ls /opt/airflow/dag_generated_configs
    docker exec -it openmetadata_ingestion python -c \
      "import json,sys;print(json.load(open(sys.argv[1]))['openMetadataServerConnection']['securityConfig']['jwtToken'])" \
      /opt/airflow/dag_generated_configs/<dag_id>.json
  4. Rotate the bot JWT. UI: Settings → Bots → testsuite-bot → Revoke Token → Generate New Token.
    By API, note these live under /v1/users (not /v1/bots), take the id in the request
    body
    , and need the bot's User id — not the Bot entity id:
    BOT_USER_ID=$(curl -sH "Authorization: Bearer $ADMIN_JWT" \
      "$OM/api/v1/users/name/testsuite-bot?fields=authenticationMechanism" | jq -r .id)
    curl -sX PUT -H "Authorization: Bearer $ADMIN_JWT" -H 'Content-Type: application/json' \
      "$OM/api/v1/users/revokeToken"   -d "{\"id\":\"$BOT_USER_ID\"}"
    curl -sX PUT -H "Authorization: Bearer $ADMIN_JWT" -H 'Content-Type: application/json' \
      "$OM/api/v1/users/generateToken" -d "{\"id\":\"$BOT_USER_ID\",\"JWTTokenExpiry\":\"7\"}"
    Record the new token as TOKEN_B; assert TOKEN_B != TOKEN_A.
  5. Pre-fix control (on main). Re-run the validation (Run Now, or
    POST /api/v1/dataContracts/{id}/validate). <dag_id>.json still holds TOKEN_A, mtime
    unchanged, and the DAG run fails to authenticate.
  6. Post-fix (this branch). Re-run the validation. <dag_id>.json now holds TOKEN_B and the
    mtime has advanced.
  7. Confirm the run is healthy: the DAG run completes and the contract's latest result leaves
    Running rather than hanging or logging an auth error.
  8. Confirm the no-regression path: stop the Airflow container, trigger /validate on the same
    already-deployed contract, and check for
    Could not refresh DQ pipeline '<fqn>' before validation, running the DAG already deployed: —
    the validation must proceed to the trigger rather than aborting at the deploy step.

Automated gates that were run (real output):

mvn spotless:check -pl openmetadata-service                       BUILD SUCCESS
DataContractPipelineTokenRefreshTest                              Tests run: 4,   Failures: 0, Errors: 0
org.openmetadata.service.jdbi3.*Test                              Tests run: 552, Failures: 0, Errors: 0
AirflowRESTClientTest / K8sPipelineClientTest /
  OpenMetadataConnectionBuilderTest / PipelineTaskKeyTest /
  DataContractFieldSupportTest / IngestionPipelineRepositoryTest  Tests run: 165, Failures: 0, Errors: 0
DataContractResourceIT#testDataContractCreatesReverseTestSuiteRelationship
                                                                  Tests run: 1,   Failures: 0, Errors: 0

Not run: the full openmetadata-service unit suite and the full DataContractResourceIT.

UI screen recording / screenshots:

Not applicable — backend-only change, no UI files touched.

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • My PR is linked to a GitHub issue via Fixes #<issue-number> above.
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: N/A — no schema change, and therefore no migration.
  • For UI changes: N/A — no UI changes.
  • I have added tests (unit / integration / Playwright as applicable) and listed them above.

🤖 Generated with Claude Code

Greptile Summary

This PR refreshes a data contract's DQ pipeline deployment before every validation so Airflow receives the current bot token, while retaining strict first-deploy and best-effort redeploy semantics.

  • Rebuilds the OpenMetadata connection before deployment and again before triggering.
  • Avoids persisting an unchanged deployed flag during routine refreshes.
  • Adds focused tests for token rotation, triggering, and deployment-failure behavior.
  • The best-effort failure path can continue after Airflow has partially replaced the previous deployment.

Confidence Score: 4/5

The PR should not merge until the refresh-failure path stops assuming that a failed Airflow deployment leaves the previous DAG artifacts intact.

Airflow can fail after overwriting the configuration or DAG file, while the new catch suppresses that failure and proceeds to trigger an artifact set that may no longer represent the previous valid deployment.

Files Needing Attention: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java Adds per-validation redeployment and token rebuilding, but suppresses refresh failures even when Airflow may already have partially replaced the prior deployment.
openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/DataContractPipelineTokenRefreshTest.java Adds boundary-focused coverage for rotated tokens and deploy failures, although the failure stub throws before exercising Airflow's partial-write behavior.

Sequence Diagram

sequenceDiagram
  participant V as Contract validation
  participant S as Metadata service
  participant A as Airflow deploy API
  participant F as DAG artifacts
  V->>S: Validate contract
  S->>S: Rebuild current bot connection
  S->>A: Deploy full pipeline
  A->>F: Overwrite config JSON
  A->>F: Overwrite and validate DAG file
  alt Deployment succeeds
    A-->>S: 200 OK
  else Later deployment step fails
    A-->>S: Error
    S->>S: Suppress error for deployed pipeline
  end
  S->>A: Trigger DAG
Loading

Reviews (1): Last reviewed commit: "fix(data-contract): refresh the DQ DAG d..." | Re-trigger Greptile

Greptile also left 1 inline comment on this PR.

Context used:

Fixes open-metadata#24806.

The bot JWT reaches Airflow exactly once: DagDeployer.store_airflow_pipeline_config
serialises openMetadataServerConnection.securityConfig.jwtToken into
DAG_GENERATED_CONFIGS/<dag_id>.json at deploy time, and the generated DAG reads that
file on every parse. Nothing rewrites it afterwards.

deployAndTriggerDQValidation guarded the redeploy behind !pipeline.getDeployed(), so a
data contract deployed once at creation never redeployed again and kept authenticating
with the token it was born with. Rotating testsuite-bot's JWT could not reach the DAG.
Other pipeline types escape this because requiresRedeployment fires when the user edits
the pipeline; editing a DataContract never touches the pipeline's airflowConfig,
enabled, sourceConfig or loggerLevel.

prepareAndRunIngestionPipeline did rebuild a fresh connection, but AirflowRESTClient.
runPipeline posts only {dag_id}, so that connection never left the server.

/validate now always redeploys before triggering, which rewrites the DAG config with a
freshly minted token and makes a rotated token self-healing. Refreshing an already
deployed pipeline is best-effort: a pipeline-service outage logs a warning and still
triggers the previously deployed DAG, so an installation that worked before cannot
start failing. A never-deployed pipeline still propagates the deploy failure. The
masked window is only the deploy HTTP call, because the connection is rebuilt again
outside the catch and a bot or secrets-manager failure is rethrown there.

The !alreadyDeployed guard on the follow-up write does not remove an existing write:
pre-fix that path never reached prepareAndDeployIngestionPipeline at all. It keeps the
refactor from introducing a new one, whose real cost is storeEntity ->
encryptIngestionPipeline -> encryptPasswordFields(store=true), an external
secrets-manager write on AWS SM / Parameter Store, to persist a deployed flag that is
already true.

Boolean.TRUE.equals also makes the check null-safe, where !getDeployed() would have
NPEd on a legacy row with a null flag.

K8sPipelineClient.runPipeline rebuilds the job and its bot token on every run, so the
k8s/Argo runner never had this bug.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
@TeddyCr
TeddyCr requested a review from a team as a code owner August 20, 2026 21:36
Copilot AI lite review requested due to automatic review settings August 20, 2026 21:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

@github-actions

github-actions Bot commented Aug 20, 2026 •

Copy link
Copy Markdown
Contributor

✅ PR checks passed

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

@github-actions github-actions Bot added Ingestion safe to test Add this label to run secure Github workflows on PRs labels Aug 20, 2026
… not cover

Review feedback on open-metadata#31848: the javadoc asserted that a failed refresh always
leaves the previously deployed DAG runnable. DagDeployer.deploy() truncates
<dag_id>.json and <dag_id>.py in place and validates afterwards, so a write that
fails part way through can leave a half-written artifact and that assertion does
not hold.

Behaviour is unchanged. The fallback is still correct for every failure that is
decided before Airflow rewrites the artifacts - transport failures, a payload the
deploy endpoint rejects, and a DagBag reparse failure, which only happens after
both files are fully written with the new token. The partial-write hazard is not
introduced by this PR (pipeline create/update and /ingestionPipelines/deploy/{id}
run the same non-atomic code); this is only the first caller that does not
propagate it, so the javadoc now says so instead of claiming safety it does not
have.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013D3LpP12bP6RBF2tFo5Rmn
Copilot AI review requested due to automatic review settings September 2, 2026 19:02
@github-actions github-actions Bot removed the safe to test Add this label to run secure Github workflows on PRs label Sep 2, 2026
@github-actions github-actions Bot added the safe to test Add this label to run secure Github workflows on PRs label Sep 2, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Changes recommended

The new “redeploy on every validation” path is currently unconditional across pipeline clients (not Airflow-specific) and the best-effort failure log drops stack traces, creating avoidable operational churn and diagnosability gaps.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Review details
  • Files reviewed: 2/2 changed files
  • Comments generated: 1
  • Review effort level: Lite

Comment on lines +1193 to +1197
private void refreshDeployedPipelineBeforeRun(IngestionPipeline pipeline, TestSuite testSuite) {
boolean alreadyDeployed = Boolean.TRUE.equals(pipeline.getDeployed());
try {
prepareAndDeployIngestionPipeline(pipeline, testSuite);
} catch (RuntimeException e) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Both valid, both fixed in 53ecd19. Thanks — the churn is worse than you describe.

Gating. You're right that the pinning is Airflow's alone: AirflowRESTClient.runPipeline posts only {dag_id}, so the token can only reach an already-deployed DAG via another deploy. K8sPipelineClient.runPipeline inlines a freshly built config into ENV_CONFIG (buildEnvVars → buildCommonIngestionEnvVars(..., includeConfig=true) → buildWorkflowConfigWithOverrides(pipeline, ...)), and Collate's ArgoServiceClient.runPipeline rebuilds the whole Workflow spec through WorkflowConfigBuilder, which reads ingestionPipeline.getOpenMetadataServerConnection() per call. Both already carry the current token.

And the wasted work is specifically wasted: a data contract's DQ pipeline is created with a bare new AirflowConfig() (DataContractRepository:987), so scheduleInterval is null. That means k8s wrote an om-config-/om-secret- pair that only the CronJob path ever reads (buildEnvVarsForCronJob via configMapKeyRef) — so on an unscheduled pipeline nothing consumes them at all — and Argo took its unscheduled branch, which calls cleanCronWorkflow(), i.e. issued a CronWorkflow delete per validation. With DataContractValidationApp sweeping every contract nightly that was N of each per day.

I went with a capability on PipelineServiceClientInterface rather than a className check:

default boolean pinsCredentialsAtDeployTime() { return false; }

overridden to true in AirflowRESTClient only. It states why a runner needs the refresh instead of naming a vendor, and the false default is the correct answer for every other implementation — including out-of-tree ones, which keep compiling untouched. One trap worth noting: MeteredPipelineServiceClient is a decorator, so it has to delegate the method; without that it would have answered false for Airflow and silently disabled the whole fix. Non-pinning runners now keep the exact pre-refresh behaviour — deploy only when nothing is deployed yet.

Log. Fixed, e is now passed as the trailing arg so the stack trace is emitted alongside the message.

Tests. validateDoesNotRedeployARunnerThatRebuildsTheTokenOnEveryRun fails without the gate:

org.opentest4j.AssertionFailedError: expected: <[]> but was: <[stale-jwt-token, rotated-jwt-token]>

plus one pinning the first deploy still happening on a non-pinning runner. The four existing tests needed when(client.pinsCredentialsAtDeployTime()).thenReturn(true) — Mockito's default of false would otherwise have disabled the behaviour under test, which is the same trap as the decorator. 159/159 green across DataContractPipelineTokenRefreshTest, AirflowRESTClientTest, K8sPipelineClientTest, IngestionPipelineRepositoryTest, PipelineTaskKeyTest, OpenMetadataConnectionBuilderTest.

Out of scope but worth an issue: the scheduled paths do pin the token — Argo's CronWorkflow spec and k8s's om-config-/om-secret- objects are written at deploy time and only rewritten on redeploy. Same bug class as #24806 reached through a different trigger. Not touched here, since contract validation goes through runPipeline.

@TeddyCr TeddyCr added this to Shipping Sep 2, 2026
@TeddyCr TeddyCr moved this to In Review / QA 👀 in Shipping Sep 2, 2026
@TeddyCr TeddyCr removed this from Shipping Sep 2, 2026
@github-actions github-actions Bot added safe to test Add this label to run secure Github workflows on PRs and removed safe to test Add this label to run secure Github workflows on PRs labels Sep 2, 2026

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🔵 Needs a closer look

It changes validation-time operational behavior by introducing per-validation redeploy calls (with best-effort failure semantics) and should get a final human review focused on runtime/scale impact and external-dependency failure modes.

Review details
  • Files reviewed: 5/5 changed files
  • Comments generated: 0 new
  • Review effort level: Lite

@gitar-bot

gitar-bot Bot commented Sep 2, 2026

Copy link
Copy Markdown
Code Review ✅ Approved 2 resolved / 2 findings

Fixes token pinning in Data Contract DQ DAG deployments by redeploying the pipeline before every validation so Airflow receives the current bot token, with best-effort semantics for already-deployed contracts. Addresses the redeploy multiplying load in the nightly sweep and the deploy-failure WARN omitting exceptions as known trade-offs. Comprehensive unit tests added covering token rotation, triggering, and deployment-failure behavior with 81.8% line coverage on changed methods.

✅ 2 resolved
✅ Performance: Redeploy on every validate multiplies load in nightly sweep

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java:1172-1173 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java:1184-1197
deployAndTriggerDQValidation now unconditionally calls prepareAndDeployIngestionPipeline (a full POST /deploy that runs store_airflow_pipeline_config, DAG file validation, dag_bag.process_file, sync_to_db and a background scan) before every trigger. Since DataContractValidationApp paginates and validates every data contract nightly (plus a data-product sweep), this turns into N serial Airflow deploys per night for N contracts — previously zero once deployed. On large installations this can materially lengthen the sweep and load the pipeline service. Consider gating the redeploy (e.g. only for user-initiated /validate, or throttling deploys per contract) or confirming the deployment cost scales acceptably for high contract counts.

✅ Quality: Deploy-failure WARN omits exception, hiding root cause

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/DataContractRepository.java:1192-1195
The catch block logs only e.getMessage() as a string argument, so no stack trace is emitted. A persistent /deploy failure on an already-deployed contract is the exact silent-failure symptom this issue is about, and losing the exception makes diagnosing it (e.g. distinguishing a transient network blip from a SecretsManager/auth error) harder. Pass the exception as the final SLF4J argument so the stack trace is logged.

Options

Display: compact → Showing less information.

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

Compact
gitar display:verbose         

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

@sonarqubecloud

sonarqubecloud Bot commented Sep 2, 2026

Copy link
Copy Markdown

@TeddyCr
TeddyCr enabled auto-merge September 2, 2026 22:00
@TeddyCr
TeddyCr added this pull request to the merge queue Sep 2, 2026
Merged via the queue into open-metadata:main with commit 285932f Sep 3, 2026
135 of 139 checks passed
@TeddyCr
TeddyCr deleted the ISSUE-24806 branch September 3, 2026 10:15
shrabantipaul-collate pushed a commit to PRADDZY/OpenMetadata that referenced this pull request Sep 3, 2026
…idation (open-metadata#31848)

* fix(data-contract): refresh the DQ DAG deployment on every validation

Fixes open-metadata#24806.

The bot JWT reaches Airflow exactly once: DagDeployer.store_airflow_pipeline_config
serialises openMetadataServerConnection.securityConfig.jwtToken into
DAG_GENERATED_CONFIGS/<dag_id>.json at deploy time, and the generated DAG reads that
file on every parse. Nothing rewrites it afterwards.

deployAndTriggerDQValidation guarded the redeploy behind !pipeline.getDeployed(), so a
data contract deployed once at creation never redeployed again and kept authenticating
with the token it was born with. Rotating testsuite-bot's JWT could not reach the DAG.
Other pipeline types escape this because requiresRedeployment fires when the user edits
the pipeline; editing a DataContract never touches the pipeline's airflowConfig,
enabled, sourceConfig or loggerLevel.

prepareAndRunIngestionPipeline did rebuild a fresh connection, but AirflowRESTClient.
runPipeline posts only {dag_id}, so that connection never left the server.

/validate now always redeploys before triggering, which rewrites the DAG config with a
freshly minted token and makes a rotated token self-healing. Refreshing an already
deployed pipeline is best-effort: a pipeline-service outage logs a warning and still
triggers the previously deployed DAG, so an installation that worked before cannot
start failing. A never-deployed pipeline still propagates the deploy failure. The
masked window is only the deploy HTTP call, because the connection is rebuilt again
outside the catch and a bot or secrets-manager failure is rethrown there.

The !alreadyDeployed guard on the follow-up write does not remove an existing write:
pre-fix that path never reached prepareAndDeployIngestionPipeline at all. It keeps the
refactor from introducing a new one, whose real cost is storeEntity ->
encryptIngestionPipeline -> encryptPasswordFields(store=true), an external
secrets-manager write on AWS SM / Parameter Store, to persist a deployed flag that is
already true.

Boolean.TRUE.equals also makes the check null-safe, where !getDeployed() would have
NPEd on a legacy row with a null flag.

K8sPipelineClient.runPipeline rebuilds the job and its bot token on every run, so the
k8s/Argo runner never had this bug.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

* docs(data-contract): state what the best-effort refresh fallback does not cover

Review feedback on open-metadata#31848: the javadoc asserted that a failed refresh always
leaves the previously deployed DAG runnable. DagDeployer.deploy() truncates
<dag_id>.json and <dag_id>.py in place and validates afterwards, so a write that
fails part way through can leave a half-written artifact and that assertion does
not hold.

Behaviour is unchanged. The fallback is still correct for every failure that is
decided before Airflow rewrites the artifacts - transport failures, a payload the
deploy endpoint rejects, and a DagBag reparse failure, which only happens after
both files are fully written with the new token. The partial-write hazard is not
introduced by this PR (pipeline create/update and /ingestionPipelines/deploy/{id}
run the same non-atomic code); this is only the first caller that does not
propagate it, so the javadoc now says so instead of claiming safety it does not
have.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013D3LpP12bP6RBF2tFo5Rmn

* fix(data-contract): only refresh runners that pin credentials at deploy time

Review feedback on open-metadata#31848: the refresh fired for every PipelineServiceClient
implementation, but the pinned-JWT problem is Airflow's alone. AirflowRESTClient.
runPipeline posts only the dag_id, so the token can only reach an already
deployed DAG through another deploy. K8sPipelineClient.runPipeline inlines a
freshly built workflow config into ENV_CONFIG and Collate's ArgoServiceClient
rebuilds the whole Workflow spec via WorkflowConfigBuilder, so both already carry
the current token on every run.

Re-deploying those was therefore pure churn for a problem they do not have, and
not free: a data contract's DQ pipeline is created with a bare AirflowConfig and
so has no scheduleInterval, which means k8s wrote a ConfigMap and a Secret that
only the CronJob path ever reads, and Argo took its unscheduled branch and issued
a CronWorkflow delete. DataContractValidationApp sweeps every contract nightly,
so that was N of each per day.

Expressed as a capability on PipelineServiceClientInterface rather than a check
on the configured className, so it says why a runner needs the refresh instead of
naming a vendor. The default is false, which is the correct answer for every
implementation except Airflow - including out-of-tree ones, which keep compiling
untouched. MeteredPipelineServiceClient delegates it; without that the decorator
would silently answer false for Airflow and disable the fix.

Non-pinning runners keep the pre-refresh behaviour of deploying only when nothing
is deployed yet. Also log the exception, not just its message, so a persistent
refresh failure is diagnosable.

Tests: two added. validateDoesNotRedeployARunnerThatRebuildsTheTokenOnEveryRun
fails without the gate with expected <[]> but was <[stale-jwt-token,
rotated-jwt-token]>. The existing four needed the mock stubbed to true, since a
Mockito default of false would have disabled the fix under test.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_013D3LpP12bP6RBF2tFo5Rmn

---------

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>

This branch was previously deployed

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

Labels

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Dag configs - jwtToken - cannot get updated in Data Contract Dags

3 participants