Skip to content

Backport #31863 to 2.0: preserve table constraints and column custom properties on recursive CSV import - #32095

Closed
sonika-shah wants to merge 3 commits into
2.0from
backport/csv-recursive-31857-31858-2.0
Closed

sonika-shah wants to merge 3 commits into
2.0from
backport/csv-recursive-31857-31858-2.0

Conversation

@sonika-shah

@sonika-shah sonika-shah commented Aug 26, 2026 •

Copy link
Copy Markdown
Collaborator

Backport of #31863 to the 2.0 release branch.

Fixes #31857 and #31858 for 2.0.

What

Recursive CSV import (?recursive=true, the path the UI Manage → Import uses at schema/database/service level) silently dropped two things on tables:

Fix

  • EntityCsv.createTableEntity now fetches the existing table with tableConstraints,tablePartition so a createOrUpdate on import carries them through instead of nulling them.
  • EntityRepository.removeExtensions (bulk-import path) now deletes only the entity's own customFieldSchema rows via a new batched, jsonSchema-scoped DAO delete (CollectionDAO.deleteByJsonSchemaBatch) instead of deleteAllBatch, which also removed columnExtension rows. One statement per chunk — no N+1.

Validation

  • openmetadata-service and openmetadata-integration-tests compile clean.
  • EntityCsvTest: 65/0.
  • Recursive round-trip ITs in DatabaseServiceResourceIT (PK+UNIQUE+FK constraints; table+column custom properties together) included.

Cherry-pick applied cleanly with no conflicts.

Greptile Summary

The backport preserves table constraints, table partition metadata, and column custom-property extension rows during recursive CSV imports.

  • Expands existing-table retrieval to carry non-CSV table fields through updates.
  • Narrows batched extension deletion to the entity’s custom-field schema.
  • Adds recursive round-trip integration coverage for constraints and custom properties.

Confidence Score: 4/5

The PR is not yet safe to merge because recursive updates can still remove foreign-key RELATED_TO edges while retaining only the constraint JSON.

Batch update cleanup deletes table-to-table RELATED_TO relationships, while the subsequent bulk relationship-storage path restores containment only and never invokes the constraint relationship writer.

Files Needing Attention: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java and openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DatabaseServiceResourceIT.java

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java Existing table retrieval now includes constraints and partition data, but the downstream batch path still fails to restore foreign-key relationship edges.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java Adds a chunked, jsonSchema-scoped extension deletion operation.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java Uses schema-scoped deletion so table custom-property replacement does not remove column extensions.
openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DatabaseServiceResourceIT.java Adds recursive round-trip coverage, but the constraint test does not verify the persisted foreign-key relationship edge.
openmetadata-service/src/test/java/org/openmetadata/csv/EntityCsvTest.java Updates the dependency-resolution expectation for the expanded table field selection.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Recursive CSV import] --> B[Load existing table]
  B --> C[Carry constraints and partition data]
  C --> D[Batch entity update]
  D --> E[Clear existing relationships]
  E --> F[Store entity and containment]
  F --> G[Persist preserved table JSON]
  E -. RELATED_TO removed .-> H[Foreign-key edge absent]
Loading

Reviews (2): Last reviewed commit: "Merge branch '2.0' into backport/csv-rec..." | Re-trigger Greptile

Context used:

…operties on recursive CSV import (#31863)

* Fixes #31857: preserve table constraints on recursive CSV import

createTableEntity fetched the existing table without tableConstraints/
tablePartition, so the subsequent createOrUpdate persisted them as null and
the recursive CSV import silently dropped every table's PK/UNIQUE/FK. Load
those fields so they carry through unchanged.

Adds DatabaseServiceResourceIT.test_importExportRecursive_preservesTableConstraints.

* test: cover FOREIGN_KEY (ER) in recursive CSV constraint round trip

Adds a referenced table and a FOREIGN_KEY constraint (with referredColumns)
so the recursive round trip also asserts the referenced-table linkage
survives, not just PRIMARY_KEY/UNIQUE.

* Fixes #31858: preserve column custom properties on recursive CSV import

createTableEntity fetched the table with "extension" but not "columns";
TableRepository.setFields only hydrates column.extension when both fields are
requested, so the recursive table-row createOrUpdate persisted columns with
null extension and dropped column custom properties before the column rows
patched back. Add "columns" to the fetch so column extension is hydrated and
carried through.

Adds DatabaseServiceResourceIT.test_importExportRecursive_preservesColumnCustomProperties.
Verified: 3 recursive round-trip ITs pass (constraints+FK, column custom
properties, and the pre-existing column tags/glossary test) — Tests run: 3,
Failures: 0, Errors: 0.

* test: update EntityCsvTest mock stub for new createTableEntity fetch fields

createTableEntity now fetches tableConstraints,tablePartition,columns; the
unit test stubbed getEntityWithDependencyResolution on the exact old field
string, so the stub stopped matching and returned null -> NPE. Update the stub
to the new field string. EntityCsvTest: Tests run: 65, Failures: 0.

* Fixes #31858: preserve column custom properties via targeted removeExtensions

The complete fix. The bulk import update path (updateManyEntitiesForImport)
called removeExtensions(originals), which did a blanket
entityExtensionDAO.deleteAllBatch(id) -- deleting EVERY entity_extension row
for a table (including its columnExtension rows) whenever the entity carried
table-level extension -- then re-stored only the table-level extension. So a
recursive CSV import of a table that had BOTH table-level and column-level
custom properties silently dropped the column custom properties.

Make removeExtensions targeted, mirroring the single-entity removeExtension()
(delete only the entity's own custom-property rows), so columnExtension rows
are no longer collateral-deleted.

Also revert the earlier createTableEntity 'columns' fetch addition (it only
masked the column-only case; the real defect was the blanket delete above) --
the fetch keeps tableConstraints,tablePartition for #31857.

Strengthen DatabaseServiceResourceIT.test_importExportRecursive_preservesColumnCustomProperties
to define + set a table-level custom property alongside column-level ones, so
the regression (which only manifests when both are present) can't false-green.

Verified live on a 2.0 stack: recursive export->import at table/schema/database/
service now preserves table + column custom properties AND table constraints;
EntityCsvTest 65/0; the 3 recursive ITs pass.

* perf(csv-import): batch removeExtensions custom-property delete (avoid N+1)

The prior fix looped removeExtension(entity) per entity, which fires one DELETE
per custom-property field -- an N+1 for bulk imports of many entities.

Restore a single batched delete but scope it to the entity's own custom-property
rows via a new jsonSchema-filtered DAO batch:
  DELETE FROM entity_extension WHERE id IN (<ids>) AND jsonSchema = 'customFieldSchema'
run one statement per chunk (updateInChunks). This keeps columnExtension (and
version) rows untouched -- so column custom properties still survive a bulk
import that updates table-level extension -- without the per-field N+1.

Verified: EntityCsvTest 65/0; DatabaseServiceResourceIT recursive tests 0 fail
(incl. table+column custom properties); ColumnCustomPropertiesIT 30/0.
@sonika-shah
sonika-shah requested a review from a team as a code owner August 26, 2026 10:50
@github-actions

Copy link
Copy Markdown
Contributor

❌ PR checklist incomplete

This PR cannot be merged until the following are addressed on its linked issue:

  • No GitHub issue is linked. Link an issue in the Development section of the PR (or add Fixes #12345 to the description). For a same-org cross-repo issue, add Fixes open-metadata/<repo>#123 to the description.

The fields live on the linked issue in the Shipping project (open the issue → right sidebar → Projects). After you set them, re-run this check (or push a commit) — issue/project changes do not re-trigger it automatically.

Maintainers can bypass this check by adding the skip-pr-checks label.

@github-actions github-actions Bot added backend safe to test Add this label to run secure Github workflows on PRs labels Aug 26, 2026
// table-level extension would silently wipe its column-level custom properties.
if (!entityIds.isEmpty()) {
daoCollection.entityExtensionDAO().deleteAllBatch(entityIds);
daoCollection.entityExtensionDAO().deleteByJsonSchemaBatch(entityIds, "customFieldSchema");

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Quality: Magic string "customFieldSchema" repeated instead of a constant

The jsonSchema value "customFieldSchema" is hardcoded in removeExtensions and again in storeCustomProperty/insertMany, while the sibling value already lives in a named constant (TableRepository.COLUMN_EXTENSION_JSON_SCHEMA = "columnExtension"). Introducing a shared constant (e.g. CUSTOM_FIELD_SCHEMA) and using it at both the write and the new delete site prevents these two values from silently drifting apart, which would reintroduce the exact wipe bug this PR fixes. Functionally correct as written; this is a maintainability note.

Was this helpful? React with 👍 / 👎

@github-actions

Copy link
Copy Markdown
Contributor

The Java checkstyle failed.

Please run mvn spotless:apply in the root of your repository and commit the changes to this PR.
You can also use pre-commit to automate the Java code formatting.

You can install the pre-commit hooks with make install_test precommit_install.

@github-actions

github-actions Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

✅ Playwright Results — workflow succeeded

Validated commit ca0cb998416384e2d976853460e95de3376bb5bb in Playwright run 33474177969, attempt 1.

✅ 555 passed · ❌ 0 failed · 🟡 0 flaky · ⏭️ 0 skipped · 🧰 0 lifecycle flaky

Performance

Blocking targets: ✅ met · Optimization targets: 🟡 in progress

Shard-job maxima below are not the full workflow wall time; the linked run includes build, fixture, planning, and reporting.

🕒 Full workflow signal wall (to summary) 1h 6m 35s

⏱️ Max setup 3m 29s · max shard execution 18m 5s · max shard-job elapsed before upload 21m 36s · reporting 3s

🌐 207.91 requests/attempt · 2.82 app boots/UI scenario · 11.24% common-shard skew

Optimization targets still in progress:

  • Browser traffic was 207.91 requests per attempt (convergence target: fewer than 200).
  • Application boot ratio was 2.82 per UI scenario (1626 boots / 576 scenarios; convergence target: at most 1).
Shard Passed Failed Flaky Skipped Lifecycle failed Lifecycle flaky
✅ Shard chromium-01 143 0 0 0 0 0
✅ Shard chromium-02 133 0 0 0 0 0
✅ Shard chromium-03 123 0 0 0 0 0
✅ Shard data-asset-rules-01 63 0 0 0 0 0
✅ Shard domain-isolation-01 16 0 0 0 0 0
✅ Shard global-state-01 34 0 0 0 0 0
✅ Shard ingestion-01 1 0 0 0 0 0
✅ Shard reindex-01 2 0 0 0 0 0
✅ Shard search-01 11 0 0 0 0 0
✅ Shard search-rbac-01 29 0 0 0 0 0

📦 Download artifacts

How to debug locally
# Download playwright-test-results-<shard> artifact and unzip
npx playwright show-trace path/to/trace.zip    # view trace

Khairajani added a commit that referenced this pull request Aug 26, 2026
`TestCaseResolutionStatusResource` imports `CommonUtil.listOrEmpty` and
`CommonUtil.nullOrEmpty` but no longer uses either, so `mvn spotless:check` fails and
the `java-checkstyle` job is red for every PR targeting this branch -- #32095 and
#32093 fail identically. The usages went away in #32017 while the imports stayed.

Import-only change, produced by `mvn spotless:apply`; no logic touched. Needed here
only so this backport can be validated.

`main` needs no equivalent fix: both symbols are imported and used five times each in
that file there. On `1.13` the imports do not exist. This is 2.0-only.
@sonika-shah
sonika-shah enabled auto-merge (squash) August 26, 2026 13:25
@github-actions

Copy link
Copy Markdown
Contributor

The Java checkstyle failed.

Please run mvn spotless:apply in the root of your repository and commit the changes to this PR.
You can also use pre-commit to automate the Java code formatting.

You can install the pre-commit hooks with make install_test precommit_install.

@gitar-bot

gitar-bot Bot commented Sep 1, 2026 •

Copy link
Copy Markdown
Code Review 👍 Approved with suggestions 0 closed / 1 findings

Backport of recursive CSV import fix preserves table constraints and column custom properties by fetching existing table metadata on import and narrowing extension deletion to entity-level custom fields only. Consider introducing a shared constant for the "customFieldSchema" jsonSchema value (currently hardcoded at lines 5803 and 5808 in EntityRepository.java) to prevent future drift from the existing COLUMN_EXTENSION_JSON_SCHEMA constant pattern.

💡 Quality: Magic string "customFieldSchema" repeated instead of a constant

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:5803 📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:5808

The jsonSchema value "customFieldSchema" is hardcoded in removeExtensions and again in storeCustomProperty/insertMany, while the sibling value already lives in a named constant (TableRepository.COLUMN_EXTENSION_JSON_SCHEMA = "columnExtension"). Introducing a shared constant (e.g. CUSTOM_FIELD_SCHEMA) and using it at both the write and the new delete site prevents these two values from silently drifting apart, which would reintroduce the exact wipe bug this PR fixes. Functionally correct as written; this is a maintainability note.

🤖 Prompt for agents
Code Review: Backport of recursive CSV import fix preserves table constraints and column custom properties by fetching existing table metadata on import and narrowing extension deletion to entity-level custom fields only. Consider introducing a shared constant for the "customFieldSchema" jsonSchema value (currently hardcoded at lines 5803 and 5808 in EntityRepository.java) to prevent future drift from the existing COLUMN_EXTENSION_JSON_SCHEMA constant pattern.

1. 💡 Quality: Magic string "customFieldSchema" repeated instead of a constant
   Files: openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:5803, openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:5808

   The jsonSchema value "customFieldSchema" is hardcoded in removeExtensions and again in storeCustomProperty/insertMany, while the sibling value already lives in a named constant (TableRepository.COLUMN_EXTENSION_JSON_SCHEMA = "columnExtension"). Introducing a shared constant (e.g. CUSTOM_FIELD_SCHEMA) and using it at both the write and the new delete site prevents these two values from silently drifting apart, which would reintroduce the exact wipe bug this PR fixes. Functionally correct as written; this is a maintainability note.

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

@sonika-shah
sonika-shah disabled auto-merge September 1, 2026 06:37
Khairajani added a commit that referenced this pull request Sep 1, 2026
…#32005) + scale the deploy-pipelines deadline (#31976) (#32101)

* fix(airflow-apis): stop re-parsing the whole DAG folder on every pipeline deploy (#32005)

* fix(airflow-apis): stop re-parsing the whole DAG folder on every deploy

`get_dagbag` built a DagBag over the entire DAG folder and called `collect_dags`,
so each deploy parsed every DAG in the deployment. That makes a single deploy cost
O(total DAGs) and a bulk deploy O(total DAGs^2).

On Airflow 2.x the folder was never actually walked: `read_dags_from_db=True` made
both `collect_dags` and `collect_dags_from_db` early return, and DAGs came from the
serialized-DAG table. The Airflow 3.x support gate dropped that kwarg, which turned
an O(1) DB read into an O(N) filesystem walk.

The deploy path does not need a populated bag. `refresh_session_dag` calls
`process_file` on the DAG file it has just written and then asks for that single
`dag_id`, and `process_file` bags the DAG itself. Build the bag with
`collect_dags=False` instead. The kwarg exists on DagBag in both Airflow 2.x and
3.x, so the version branching goes away with it.

The folder walk was also masking `process_file`: `collect_dags` stamps
`file_last_changed` for every file it walks, including the one just written, so the
following `process_file` hit its `only_if_updated` early return and returned no
dags. The DAG was bagged by the folder walk as a side effect rather than by the call
that intends to bag it. The pre-fix test run confirms this - `found_dags` did not
contain the deployed dag.

Drop the `dagbag size` log line, which would now always report 0. The adjacent
`processed dags` line carries the same signal and starts reporting the real dag.

The per-deploy `DagFileProcessorManager` fork in `scan_dags_job_background` is left
alone deliberately. On Airflow 3 `DAG.sync_to_db` delegates to `bulk_write_to_db`,
which writes DagModel and asset rows but does not call `SerializedDagModel.write_dag`,
so that scan is what serializes a newly deployed DAG. Removing or skipping it would
leave deployed pipelines unrunnable.

Tests: `tests/unit/ingestion_pipeline/test_get_dagbag.py` - the bag comes back empty
over a populated folder, `collect_dags` is never called, and `process_file` still
bags the deployed DAG and only that DAG. All three fail before this change.

* fix(airflow-apis): keep the pre-3.0 DagBag path unchanged

`collect_dags` was only added to `DagBag.__init__` in Airflow 2.5 (absent in 2.4.0,
present in 2.5.3), and the plugin declares `apache-airflow>=2.2.2`, so passing it
unconditionally raised `TypeError` on 2.2 through 2.4 and failed every deploy there.

Scope the change to Airflow >= 3.0, which is where the regression is. Below 3.0 the
bag is still built with `read_dags_from_db=True`, which early returns out of
`collect_dags`, so that path never walked the DAG folder and needs no change.

Gate the new tests on Airflow 3 for the same reason.

* fix(airflow-apis): unblock airflow-apis-tests on Airflow 3.3

`TestAirflowOps.setUpClass` passed `include_examples=False` to `DagBag`. Airflow 3.3
dropped that keyword -- DAG discovery is bundle based there, so example DAGs are no
longer a constructor flag -- and Python raises `TypeError` for an unknown keyword.
The call is in class setup, so all three tests in the class error before running.

This is unrelated to the DagBag change in this branch: the test builds its own DagBag
and never calls `get_dagbag`. It broke when the Airflow pin moved from 3.2.2 to 3.3.0
in #31338, and has failed on every branch that reached this job since. Fixed here only
because the job has to be green for this branch to be validated; happy to split it out.

Detect the keyword instead of assuming it, matching the `sync_to_db` and `bag_dag`
compatibility checks already in this setup, so the test keeps working on Airflow 2.x
and on 3.x.

Not changed: the workflow's `paths` filter still only watches
`openmetadata-airflow-apis/**`, so a pin bump in `ingestion/setup.py` cannot trigger
the suite it affects -- which is why this went unnoticed. Widening it would run a
24 minute docker-stack job on a file that changed 26 times in the last 90 days
against this module's 5, so that tradeoff is left to maintainers.

* fix(ops): scale the deploy-pipelines chunk deadline with the chunk size (#31976)

* fix(ops): scale the deploy-pipelines chunk deadline with the chunk size

deploy-pipelines POSTs chunks of pipeline IDs to the bulk deploy endpoint,
which registers each pipeline sequentially, but bounded the request with a
fixed 2 minute deadline. At the default chunk size of 20 that budgets 6
seconds per pipeline, which a freshly restarted pipeline service does not
meet, so the client abandoned requests whose work was still progressing.

A client deadline does not cancel the server, so the abandoned chunk kept
deploying while the command marked all 20 pipelines FAILED and exited 1. A
Kubernetes restartPolicy of OnFailure then replayed the whole run on top of
work still in flight, adding load to an operation that was already
succeeding. On a catalog of 92 pipelines this reported failure while 90 were
deployed.

Budget the deadline per pipeline and multiply by the chunk size, so it no
longer silently becomes too short as a catalog grows, and expose the chunk
size and the per-pipeline budget as options. The command previously accepted
none, so neither value was reachable from a deployment configuration.

Extract the deadline calculation and the failure check as static functions so
the scaling and the exit code are unit testable without a database.

Reporting is left unchanged: an abandoned chunk is still recorded as failed.
The persisted deployed flag cannot correct it, because the deploy path only
ever sets it to true and never resets it, so it records whether a pipeline was
ever deployed rather than what this run did. Reading it to clear a timeout
would turn a genuine failure into a silent success on any redeploy. A per-run
answer needs the deploy response itself, which is a separate change.

* fix(ops): reject a non-positive deploy-pipelines chunk size

Exposing --chunk-size made a value that was previously hardcoded to 20
reachable from outside, and chunkList advances its loop with i += chunkSize.
A chunk size of 0 never advances, appending empty chunks until the heap is
exhausted, and a negative size makes subList throw, which the surrounding
handler turns into every pipeline being reported as FAILED.

Validate both options before the deploy runs and report each offending value,
rather than clamping, so a mistyped flag is not silently replaced by a
different deadline. Guard chunkList as well, so a non-positive size fails
loudly instead of spinning if another caller ever skips validation.

A non-positive --seconds-per-pipeline was already safe, since the deadline
floors at the previous fixed 2 minutes, but it is rejected too rather than
silently falling back to the deadline this option exists to move away from.

Drops the deployChunkTimeout(0, 30) assertion, which implied a chunk size of
0 was supported when it now fails validation.

* test(ops): cover picocli binding for the deploy-pipelines options

Parsing the command with picocli asserts the new options bind to the values
passed on the command line and that the declared defaults still match the
20 and 30 the description documents. Neither was covered: the existing tests
call the helpers directly, so a mistyped option name or a default drifting
from its description would not have failed anything.

Reads the defaults from the command spec rather than the parse result, since
matchedOptionValue only reports options actually present on the command line.

Needs no database, so it stays a unit test.

* style: drop unused static imports flagged by spotless on 2.0

`TestCaseResolutionStatusResource` imports `CommonUtil.listOrEmpty` and
`CommonUtil.nullOrEmpty` but no longer uses either, so `mvn spotless:check` fails and
the `java-checkstyle` job is red for every PR targeting this branch -- #32095 and
#32093 fail identically. The usages went away in #32017 while the imports stayed.

Import-only change, produced by `mvn spotless:apply`; no logic touched. Needed here
only so this backport can be validated.

`main` needs no equivalent fix: both symbols are imported and used five times each in
that file there. On `1.13` the imports do not exist. This is 2.0-only.
@github-actions

github-actions Bot commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

This PR has had no activity for 30 days and will be closed in 7 days if no further activity occurs.
Feel free to reopen it if you'd like to continue working on it.

@github-actions github-actions Bot added the Stale label Oct 4, 2026
@github-actions

Copy link
Copy Markdown
Contributor

Closing due to inactivity. Reopen anytime to continue.

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

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant