Skip to content

fix(csv): restore FK RELATED_TO edge on recursive/bulk import - #32113

Merged
sonika-shah merged 5 commits into
mainfrom
fix/csv-recursive-fk-related-to-edge
Nov 6, 2026
Merged

sonika-shah merged 5 commits into
mainfrom
fix/csv-recursive-fk-related-to-edge

Conversation

@sonika-shah

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

Copy link
Copy Markdown
Collaborator

Problem

On a recursive CSV import (the whole-tree path the UI uses when importing at service/database/schema level), a table's foreign-key relationship edge (the RELATED_TO / ER graph link between the two tables) was dropped — even though the tableConstraints JSON on the table was preserved.

This was flagged by greptile on #31863 (and its backport #32095). It's a pre-existing issue, not introduced by #31863: before that PR the recursive path dropped both the JSON and the edge; #31863 restored the JSON, leaving the edge drop exposed.

Root cause

The bulk relationship path for tables is asymmetric:

  • clearEntitySpecificRelationshipsForMany deletes both the schema CONTAINS edge and the FK RELATED_TO edge.
  • storeEntitySpecificRelationshipsForMany re-added only CONTAINS.

The single-entity path is fine (storeEntity → addConstraintRelationship), which is why non-recursive imports (they re-PUT each table through the single path) keep the edge — only the recursive/bulk path drops it.

Fix

After the bulk CONTAINS insert, re-add the constraint RELATED_TO edges via addConstraintRelationship, mirroring the single-entity store path. (addConstraintRelationship only acts on constraints with referredColumns, i.e. foreign keys; PK/UNIQUE are no-ops.)

Test

DatabaseServiceResourceIT#test_importExportRecursive_preservesTableConstraints now also asserts the RELATED_TO edge survives a recursive round trip, reading it from the relationship DAO (deterministic — the search-backed ER endpoint is eventually consistent). GREEN with the fix (Tests run: 1, Failures: 0).

Also verified before/after on a live stack (direct entity_relationship query): without the fix the FK edge is dropped by a recursive import; with the fix it survives, while the tableConstraints JSON is preserved in both cases.

Scope

Separate from the CSV constraint/custom-property PRs (#31863 and its backports #32095 / #32096) — this addresses only the ER relationship-edge gap greptile flagged. Backports to 1.13 / 2.0 to follow once this merges.

Greptile Summary

This PR restores table foreign-key RELATED_TO edges during recursive and bulk relationship reconstruction.

  • Resolves referenced table FQNs in one batched lookup and inserts FK edges alongside containment relationships.
  • Extends the recursive CSV round-trip integration test to verify the persisted relationship edge directly through the relationship DAO.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/TableRepository.java Rebuilds FK RELATED_TO relationships in the bulk table relationship-storage path using batched target resolution and insertion.
openmetadata-integration-tests/src/test/java/org/openmetadata/it/tests/DatabaseServiceResourceIT.java Verifies that a recursive CSV round trip preserves both foreign-key constraint metadata and its persisted relationship edge.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Recursive CSV import] --> B[Persist table entities]
  B --> C[Clear table-specific relationships]
  C --> D[Rebuild schema CONTAINS edges]
  C --> E[Resolve FK target table FQNs]
  E --> F[Build RELATED_TO edges]
  D --> G[Bulk insert relationships]
  F --> G
  G --> H[Persisted table relationship graph]
Loading

Reviews (2): Last reviewed commit: "perf(csv): batch FK edge restore; skip u..." | Re-trigger Greptile

Context used:


Summary by Gitar

  • Performance:
    • Batched FK target resolution from the import batch, querying only missing FQNs
    • Folded RELATED_TO edges into the single bulkInsertRelationships call
  • Behavior:
    • Skipped FK edges whose referred table is not yet persisted (cross-chunk)
    • Deduplicated composite foreign keys to one edge per referenced table

This will update automatically on new commits.

The bulk relationship path was asymmetric for tables: clearEntitySpecificRelationshipsForMany
deletes both the schema CONTAINS edge and the foreign-key RELATED_TO (ER) edge, but
storeEntitySpecificRelationshipsForMany only re-added CONTAINS. So on a recursive CSV import
(and bulk create), a table's FK relationship to its referenced table disappeared even though the
tableConstraints JSON was preserved. The single-entity path is unaffected (storeEntity ->
addConstraintRelationship), which is why non-recursive imports kept the edge.

Fix: after the bulk CONTAINS insert, re-add the constraint RELATED_TO edges via
addConstraintRelationship, mirroring the single-entity store path.

Test: DatabaseServiceResourceIT#test_importExportRecursive_preservesTableConstraints now also
asserts the RELATED_TO edge survives a recursive round trip (read from the DAO, not the
eventually-consistent search endpoint). Verified before/after on a live stack: without the fix the
edge is dropped, with the fix it survives.
@sonika-shah
sonika-shah requested a review from a team as a code owner August 26, 2026 13:42
Copilot AI lite review requested due to automatic review settings August 26, 2026 13:42

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

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
Addresses two review points on the initial fix:

- N+1: the per-table addConstraintRelationship() did a getEntityReferenceByName lookup
  and a single addRelationship insert per foreign key. Replaced with buildConstraintRelationships(),
  which resolves all referred tables in one findByNames() query and folds the RELATED_TO edges into
  the caller's existing bulkInsertRelationships() call -- no per-FK query or insert.

- Cross-chunk forward reference (greptile P1): addConstraintRelationship() resolved the referred
  table eagerly and threw EntityNotFoundException when the target was created later in another bulk
  chunk, failing the source table with BAD_REQUEST. The batched resolver skips a referred table that
  is not yet persisted instead of throwing, so a forward reference cannot fail the request. The edge
  is best-effort in the bulk path and is created whenever the target already exists -- always true
  for a recursive re-import of existing tables, the case that regressed. Duplicate edges are harmless
  (bulkInsertTo is INSERT IGNORE / ON CONFLICT DO NOTHING).

Re-verified: recursive-import edge IT still GREEN, and live before/after confirms the FK edge
survives a recursive import.
Copilot AI review requested due to automatic review settings August 26, 2026 14:12

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.

Copilot AI review requested due to automatic review settings September 9, 2026 10:00

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 Sep 9, 2026

Copy link
Copy Markdown
Contributor

✅ Playwright Results — workflow succeeded

Validated commit 4b18ad73f88c73f5dc7d053b227835f9200b6d42 in Playwright run 34337840858, attempt 1.

✅ 4484 passed · ❌ 0 failed · 🟡 4 flaky · ⏭️ 1 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) 54m 20s

⏱️ Max setup 6m 1s · max shard execution 22m 58s · max shard-job elapsed before upload 26m 9s · reporting 17s

🌐 217.57 requests/attempt · 2.31 app boots/UI scenario · 35.27% common-shard skew

Optimization targets still in progress:

  • Common shard skew was 35.27% (convergence target: at most 15%).
  • Browser traffic was 217.57 requests per attempt (convergence target: fewer than 200).
  • Application boot ratio was 2.31 per UI scenario (10919 boots / 4732 scenarios; convergence target: at most 1).
Shard Passed Failed Flaky Skipped Lifecycle failed Lifecycle flaky
✅ Shard advanced-search-01 130 0 0 0 0 0
✅ Shard chromium-01 192 0 0 0 0 0
✅ Shard chromium-02 165 0 0 0 0 0
🟡 Shard chromium-03 184 0 1 0 0 0
✅ Shard chromium-04 156 0 0 0 0 0
✅ Shard chromium-05 197 0 0 0 0 0
✅ Shard chromium-06 150 0 0 0 0 0
✅ Shard chromium-07 190 0 0 0 0 0
✅ Shard chromium-08 192 0 0 0 0 0
🟡 Shard chromium-09 158 0 1 0 0 0
✅ Shard chromium-10 186 0 0 0 0 0
✅ Shard chromium-11 179 0 0 0 0 0
🟡 Shard chromium-12 195 0 1 1 0 0
✅ Shard chromium-13 154 0 0 0 0 0
🟡 Shard chromium-14 169 0 1 0 0 0
✅ Shard chromium-15 224 0 0 0 0 0
✅ Shard chromium-16 180 0 0 0 0 0
✅ Shard chromium-17 169 0 0 0 0 0
✅ Shard chromium-18 212 0 0 0 0 0
✅ Shard chromium-19 138 0 0 0 0 0
✅ Shard chromium-20 189 0 0 0 0 0
✅ Shard chromium-21 185 0 0 0 0 0
✅ Shard chromium-22 170 0 0 0 0 0
✅ Shard data-asset-rules-01 65 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 import-export-01 80 0 0 0 0 0
✅ Shard import-export-02 70 0 0 0 0 0
✅ Shard ingestion-01 39 0 0 0 0 0
✅ Shard ingestion-02 47 0 0 0 0 0
✅ Shard reindex-01 28 0 0 0 0 0
✅ Shard search-01 12 0 0 0 0 0
✅ Shard search-rbac-01 29 0 0 0 0 0
🟡 4 flaky test(s) (passed on retry)
  • Pages/DataContracts.spec.ts › Contract Status badge should be visible on condition if Contract Tab is present/hidden by Persona (shard chromium-03, 1 retry)
  • Pages/TasksUIFlow.spec.ts › Create and resolve description task for Pipeline via UI (shard chromium-09, 1 retry)
  • Features/Workflows/WorkflowOssRestrictions.spec.ts › save-workflow-button fires PUT API and returns to view mode (shard chromium-12, 1 retry)
  • Pages/Domains.spec.ts › Rename domain with assets (tables, topics, dashboards) preserves associations (shard chromium-14, 1 retry)

📦 Download artifacts

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

@github-actions

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.

Copilot AI lite review requested due to automatic review settings November 5, 2026 09:08

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 insufficient remaining quota.

Referred tables already in the batch (the common recursive-import case) are
resolved from memory, so only out-of-batch targets hit findByNames. Also walks
constraints once and dedupes composite-FK targets per table.
Copilot AI lite review requested due to automatic review settings November 6, 2026 06:53

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 insufficient remaining quota.

@gitar-bot

gitar-bot Bot commented Nov 6, 2026

Copy link
Copy Markdown
Code Review ✅ Approved

🔴 High risk · Batched FK edge restoration changes persisted relationship data; skipping targets absent from the batch and database may leave ER links missing.

Restores the foreign-key RELATED_TO edge dropped during recursive and bulk CSV imports by batching FK target resolution from the import batch and folding edges into the existing bulk relationship insert. Skips cross-chunk targets not yet persisted and deduplicates composite foreign keys to one edge per referenced table. No issues found.

Verification

Rules No rules evaluated

Functional validation Not enabled

Set up

Auto-approval Not enabled

Set up

For more verification details, comment gitar display:verbose.

Options

Display: compact → Showing compact verification results.

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 merged commit 38bbe83 into main Nov 6, 2026
66 of 69 checks passed
@sonika-shah
sonika-shah deleted the fix/csv-recursive-fk-related-to-edge branch November 6, 2026 10:36
sonika-shah added a commit that referenced this pull request Nov 6, 2026
…on recursive CSV import (#37244)

* Fixes #31857, #31858: preserve table constraints and column custom properties 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.

(cherry picked from commit 0a603cd)

* fix(csv): restore FK RELATED_TO edge on recursive/bulk import

The bulk relationship path was asymmetric for tables: clearEntitySpecificRelationshipsForMany
deletes both the schema CONTAINS edge and the foreign-key RELATED_TO (ER) edge, but
storeEntitySpecificRelationshipsForMany only re-added CONTAINS. So on a recursive CSV import
(and bulk create), a table's FK relationship to its referenced table disappeared even though the
tableConstraints JSON was preserved. The single-entity path is unaffected (storeEntity ->
addConstraintRelationship), which is why non-recursive imports kept the edge.

Fix: after the bulk CONTAINS insert, re-add the constraint RELATED_TO edges via
addConstraintRelationship, mirroring the single-entity store path.

Test: DatabaseServiceResourceIT#test_importExportRecursive_preservesTableConstraints now also
asserts the RELATED_TO edge survives a recursive round trip (read from the DAO, not the
eventually-consistent search endpoint). Verified before/after on a live stack: without the fix the
edge is dropped, with the fix it survives.

(cherry picked from commit 25880b2)

* perf(csv): batch FK edge restore; skip unresolved cross-chunk targets

Addresses two review points on the initial fix:

- N+1: the per-table addConstraintRelationship() did a getEntityReferenceByName lookup
  and a single addRelationship insert per foreign key. Replaced with buildConstraintRelationships(),
  which resolves all referred tables in one findByNames() query and folds the RELATED_TO edges into
  the caller's existing bulkInsertRelationships() call -- no per-FK query or insert.

- Cross-chunk forward reference (greptile P1): addConstraintRelationship() resolved the referred
  table eagerly and threw EntityNotFoundException when the target was created later in another bulk
  chunk, failing the source table with BAD_REQUEST. The batched resolver skips a referred table that
  is not yet persisted instead of throwing, so a forward reference cannot fail the request. The edge
  is best-effort in the bulk path and is created whenever the target already exists -- always true
  for a recursive re-import of existing tables, the case that regressed. Duplicate edges are harmless
  (bulkInsertTo is INSERT IGNORE / ON CONFLICT DO NOTHING).

Re-verified: recursive-import edge IT still GREEN, and live before/after confirms the FK edge
survives a recursive import.

(cherry picked from commit 4482fac)

* perf(csv): resolve FK targets from the import batch before querying

Referred tables already in the batch (the common recursive-import case) are
resolved from memory, so only out-of-batch targets hit findByNames. Also walks
constraints once and dedupes composite-FK targets per table.

(cherry picked from commit 23bf8e2)
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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants