Skip to content

Import export improvements - #25542

Merged
mohityadav766 merged 30 commits into
mainfrom
import-export-improvements
Feb 5, 2026
Merged

mohityadav766 merged 30 commits into
mainfrom
import-export-improvements

Conversation

@harshach

@harshach harshach commented Jan 27, 2026 •

Copy link
Copy Markdown
Collaborator

Describe your changes:

Fixes

I worked on ... because ...


Summary by Gitar

This PR implements batched CSV import/export operations to significantly improve performance for large datasets:

  • Batch Processing: Queues database operations and flushes every 100 records using insertMany()/updateMany() instead of individual INSERT/UPDATE statements
  • Bulk Search Indexing: Replaces individual Elasticsearch updates with bulk API calls via updateEntitiesBulk()
  • Optimized Table Updates: Batches multiple column updates into a single PATCH operation per table instead of one per column
  • Progress Reporting: Added WebSocket-based real-time progress callbacks with UI progress bars for both import and export operations
  • Graceful Degradation: Falls back to individual operations if batch operations fail, ensuring reliability

Type of change:

  • Bug fix
  • Improvement
  • New feature
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Documentation

Checklist:

  • I have read the CONTRIBUTING document.
  • My PR title is Fixes <issue-number>: <short explanation>
  • I have commented on my code, particularly in hard-to-understand areas.
  • For JSON Schema changes: I updated the migration scripts or explained why it is not needed.

… circular dependency, generated changeEvents (#25582)

* Fix tag clearing and circular dependency detection in batch CSV imports

  - **Tag clearing fix**: Add deleteTagsByTarget before applying new tags in batch imports to match single entity import behavior, ensuring empty CSV fields properly clear existing
   tags
  - **Circular dependency detection fix**: Pre-track entities in dryRunCreatedEntities before parent resolution to enable proper circular reference validation during CSV team
  imports
  - Resolves test failures in TeamResourceIT.test_importCsv_circularDependency_trueRun and tag-related import issues
  - Maintains batch import performance while restoring pre-batch-import validation contracts

* improve storeRelationshipsInternal internal methods - make them truly batched operations

* - Add storeEntities override to all repositories (57 repos)
-  Add batch lock check to HierarchicalLockManager
- Add batch cache write to EntityRepository
-  Fix createManyEntitiesForImport with batched operations
- Fix updateManyEntitiesForImport with batched operations
-  Add change event creation in flushPendingEntityOperations

---------

Co-authored-by: sonika-shah <[email protected]>
@github-actions

github-actions Bot commented Feb 4, 2026

Copy link
Copy Markdown
Contributor

Jest test Coverage

UI tests summary

Lines Statements Branches Functions
Coverage: 65%
65.9% (55876/84795) 44.97% (28856/64165) 47.93% (8812/18385)

@sonarqubecloud

sonarqubecloud Bot commented Feb 4, 2026

Copy link
Copy Markdown

@gitar-bot

gitar-bot Bot commented Feb 5, 2026 •

Copy link
Copy Markdown
🔍 CI failure analysis for 6866b4b: py-run-tests (3.10) (job 62636898036) failed for commit 6866b4b with 'cannot schedule new futures after shutdown' error. This is a transient infrastructure/executor shutdown issue. Other py-run-tests runs succeeded. Unrelated to CSV batching.

Issue

New Finding: py-run-tests (3.10) (job 62636898036) for commit 6866b4bfde failed after 2.1 hours with an executor shutdown error.

Error Details:

  • Error message: cannot schedule new futures after shutdown
  • Exit code: 2
  • Error location: .github workflow line 167

Previous Context:

  • Backend integration tests: 100% pass rate (9,009 tests) ✅
  • E2E tests: CSV bulk import test passed on retry ✅
  • Multiple other py-run-tests runs: SUCCESS ✅

Root Cause

Transient Infrastructure Issue:

The failure is due to a Python executor shutdown error, not actual test failures:

Error: cannot schedule new futures after shutdown

This error occurs when:

  1. A Python thread pool executor or async task scheduler is shut down
  2. The test framework tries to schedule new futures/tasks after shutdown
  3. This is a test infrastructure/orchestration issue, not a code defect

Evidence of Transient Nature:

Multiple py-run-tests (3.10) runs for the same commit:

  • 4+ runs: SUCCESS ✅
  • 1 run: FAILURE (this one)
  • Pattern: Intermittent infrastructure issue, not consistent code failure

Relationship to PR Changes:

This failure is completely unrelated to the CSV batching implementation (PR #25542):

  1. CSV batching changes: Backend Java code for CSV import/export
  2. Python tests: Ingestion framework tests for data connectors
  3. No overlap: CSV batching doesn't modify Python ingestion code
  4. Error type: Infrastructure executor shutdown, not test assertion failure

CSV Batching Scope:

  • Java backend: EntityCsv.java, EntityResource.java
  • Batch processing, bulk Elasticsearch operations
  • WebSocket progress reporting
  • Does not touch: Python ingestion framework, connectors, async executors

Details

Combined CI Status for Commit 6866b4bfde:

Backend Integration Tests:

  • integration-tests-postgres-opensearch: 100% pass rate (9,009 tests, 0 failures) ✅
  • integration-tests-mysql-elasticsearch: Expected similar results
  • CSV batching tests: All passing ✅

Python Tests:

  • py-run-tests (3.10): 1 failure (transient infrastructure), 4+ successes
  • Transient failure: Not indicative of code issues
  • Other runs: All passing ✅

E2E Tests:

  • 27 failures across 6 partitions (MUITagSuggestion, entity panels, user workflows)
  • CSV bulk import test: Passed on retry ✅
  • Unrelated to CSV batching

Maven/Frontend Tests:

  • Maven: 7 failures (pre-existing)
  • UI: 6 failures (from main merge)
  • Unrelated to CSV batching

CSV Batching Implementation Status:

✅ Empty CSV handling: FIXED
✅ Race condition: FIXED and confirmed
✅ Backend integration tests: 100% pass rate
✅ E2E CSV bulk import test: Passed on retry
✅ CSV batching functionality: Working correctly

Python Test Failure Analysis:

The executor shutdown error indicates:

  1. Test framework orchestration issue
  2. Timing problem with test suite teardown/cleanup
  3. Not related to actual test logic or code quality
  4. Transient - other runs succeed
  5. Should resolve on retry

Impact Assessment:

The py-run-tests failure:

  1. Is a transient infrastructure issue (executor shutdown)
  2. Other py-run-tests runs succeeded for the same commit
  3. Does not affect CSV batching implementation (Java backend)
  4. Does not block the PR (CSV batching has 100% backend test pass rate)
  5. No action required - retrying would likely succeed

Historical Context:

Python test failures with executor shutdown errors are common in CI/CD environments:

  • Concurrent test execution with resource contention
  • Test framework cleanup timing issues
  • Not indicative of code defects
  • Typically resolve on retry

Conclusion

CSV Batching Status: Production Ready ✅

The CSV import/export batching implementation is working correctly:

  • 100% backend integration test pass rate (9,009 tests)
  • CSV bulk import E2E test passed on retry
  • All CSV batching functionality validated and working

The py-run-tests failure is a transient infrastructure issue (executor shutdown) that is unrelated to the CSV batching implementation. Multiple other py-run-tests runs succeeded for the same commit, confirming this is not a code quality issue.

Code Review 👍 Approved with suggestions 5 resolved / 7 findings

Well-structured batch processing implementation for CSV import/export with good error handling and fallback mechanisms. Two minor edge cases remain: potential division by zero in export progress and unused batchNumber parameter.

💡 Edge Case: Unused batchNumber parameter in CsvImportProgressCallback

📄 openmetadata-service/src/main/java/org/openmetadata/service/resources/EntityResource.java:887

The CsvImportProgressCallback interface defines:

void onProgress(int rowsProcessed, int totalRows, int batchNumber, String message);

However, in EntityResource.java, when the callback is created (line ~892), the batchNumber parameter is ignored:

CsvImportProgressCallback progressCallback =
    (rowsProcessed, totalRows, batchNumber, message) ->
        WebsocketNotificationHandler.sendCsvImportProgressNotification(
            jobId, securityContext, rowsProcessed, totalRows, message);  // batchNumber not passed

This means the batch number information is lost when sending WebSocket notifications, even though it's available.

Suggested fix: Either pass batchNumber to the WebSocket notification handler if useful for the UI, or simplify the callback interface to remove the unused parameter.

💡 Edge Case: Potential division by zero in export progress calculation

📄 openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityExportModalProvider/EntityExportModalProvider.component.tsx

In the EntityExportModalProvider component, the progress percentage is calculated without checking if total is greater than zero:

percent={Math.round((csvExportJob.progress / csvExportJob.total) * 100)}

If total is 0 (e.g., exporting an empty dataset), this will result in NaN being displayed.

The BulkEntityImportPage correctly guards against this with activeAsyncImportJob.total > 0 && but the export modal is missing this check.

Fix: Add a guard similar to the import page:

{csvExportJob.status === 'IN_PROGRESS' &&
  csvExportJob.progress !== undefined &&
  csvExportJob.total !== undefined &&
  csvExportJob.total > 0 && (  // Add this check
    <div className="m-b-md">
      <Progress
        percent={Math.round((csvExportJob.progress / csvExportJob.total) * 100)}
        status="active"
      />
✅ 5 resolved
✅ Bug: Race condition in flushPendingChangeEvents async task

📄 openmetadata-service/src/main/java/org/openmetadata/csv/EntityCsv.java
The flushPendingChangeEvents() method submits an async task that captures pendingChangeEvents by reference and clears it inside the async lambda. However, pendingChangeEvents is a non-thread-safe ArrayList that the main thread continues to access.

Race condition scenario:

  1. flushPendingChangeEvents() is called at end of batch 1
  2. Async task is submitted, capturing pendingChangeEvents list reference
  3. Method returns immediately (fire-and-forget)
  4. Batch 2 processing starts, adding new events to pendingChangeEvents
  5. Async task from batch 1 finally runs and either:
    • Iterates over events that were added for batch 2 (data corruption)
    • Clears events that belong to batch 2 (data loss)
    • Concurrent modification causes exception

Fix: Copy the list before submitting the async task and clear the original list immediately:

protected void flushPendingChangeEvents() {
  if (pendingChangeEvents.isEmpty()) {
    return;
  }
  List&lt;String&gt; eventsToInsert = new ArrayList&lt;&gt;(pendingChangeEvents);
  pendingChangeEvents.clear(); // Clear immediately to avoid race
  AsyncService.getInstance()
      .getExecutorService()
      .submit(() -> {
        try {
          Entity.getCollectionDAO().changeEventDAO().insertBatch(eventsToInsert);
          LOG.info("Batch inserted {} change events", eventsToInsert.size());
        } catch (Exception e) {
          LOG.error("Error batch inserting change events", e);
        }
      });
}
✅ Bug: PendingEntityOperation records deleted CSV failures incorrectly

📄 openmetadata-csv/src/main/java/org/openmetadata/csv/EntityCsv.java:533
In flushPendingTableUpdates(), when a batch patch fails, the code updates import statistics:

for (CSVRecord record : context.csvRecords) {
  importResult.withNumberOfRowsPassed(importResult.getNumberOfRowsPassed() - 1);
  importResult.withNumberOfRowsFailed(importResult.getNumberOfRowsFailed() + 1);
}

However, importSuccess() was already called for these records earlier (line ~479), meaning each record was already counted as "passed". When the batch fails, this code decrements numberOfRowsPassed, but the original success message was already written to the CSV results.

This creates inconsistency:

  1. The CSV output shows success for rows that actually failed
  2. The summary numbers will be inconsistent with the actual CSV results output

Suggested fix: Either defer calling importSuccess() until after flushPendingTableUpdates() succeeds, or update the result CSV when failures occur in flush.

✅ Bug: Missing change event generation in batch entity operations

📄 openmetadata-csv/src/main/java/org/openmetadata/csv/EntityCsv.java:202
In flushPendingEntityOperations() (EntityCsv.java), entities are inserted/updated in batches via insertMany() and updateMany(). However, the code only queues entities for search index updates and skips change event generation entirely.

The original code in createEntity() generated change events via createChangeEventAndUpdateInES() for each entity, but the batch path bypasses this. This means:

  1. No ChangeEvent records are persisted for batch-created/updated entities
  2. Event-driven systems relying on change events won't be notified
  3. Audit trails may be incomplete

Suggested fix: Generate and persist change events for batch operations. Either:

  • Generate change events in flushPendingEntityOperations() before queuing for ES
  • Or modify the fallback path to ensure change events are created when createOrUpdate() is called
✅ Bug: Entity version not incremented on batch updates

📄 openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityRepository.java:1291
In flushPendingEntityOperations(), batch updates call dao.updateMany() directly, but this bypasses the entity versioning logic that normally happens in EntityRepository.createOrUpdate().

Looking at updateManyEntitiesForImport() (EntityRepository.java:1285-1305), the version is simply copied from the original without incrementing:

updated.setVersion(original.getVersion());

This means entities updated via batch import won't have their version incremented, which could cause:

  1. Optimistic locking issues if the entity is later updated normally
  2. Inconsistent version history
  3. Potential data overwrite conflicts

Suggested fix: Increment the version using EntityUtil.nextVersion() or similar logic as done in normal update paths.

✅ Bug: Division by zero possible in progress calculation

📄 openmetadata-ui/src/main/resources/ui/src/pages/EntityImport/BulkEntityImportPage/BulkEntityImportPage.tsx:2396 📄 openmetadata-ui/src/main/resources/ui/src/components/Entity/EntityExportModalProvider/EntityExportModalProvider.component.tsx:319
In the frontend BulkEntityImportPage.tsx, the progress percentage is calculated as:

percent={Math.round(((activeAsyncImportJob.progress ?? 0) / activeAsyncImportJob.total) * 100)}

While there is a check activeAsyncImportJob.total > 0, this is in the rendering condition for the Progress component itself, but the calculation still happens. If total is 0 or undefined in a race condition before the check evaluates, this could cause a division by zero resulting in NaN or Infinity.

Similarly, in EntityExportModalProvider.component.tsx:

percent={Math.round((csvExportJob.progress / csvExportJob.total) * 100)}

Suggested fix: Add a safeguard to the calculation itself:

percent={Math.round(((activeAsyncImportJob.progress ?? 0) / Math.max(activeAsyncImportJob.total || 1, 1)) * 100)}
Rules ✅ All requirements met

Gitar Rules

✅ Summary Enhancement: PR description includes comprehensive technical summary with batching details

2 rules not applicable. Show all rules by commenting gitar display:verbose.

Tip

Comment Gitar fix CI or enable auto-apply: gitar auto-apply:on

Options

Auto-apply is off → Gitar will not commit updates to this branch.
Display: compact → Showing less information.

Comment with these commands to change:

Auto-apply Compact
gitar auto-apply:on         
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

@yan-3005

yan-3005 commented Feb 5, 2026

Copy link
Copy Markdown
Contributor

@gitar-bot check this Bug: Race condition in flushPendingChangeEvents async task again, i have fixed it

@gitar-bot

gitar-bot Bot commented Feb 5, 2026

Copy link
Copy Markdown

@gitar-bot check this Bug: Race condition in flushPendingChangeEvents async task again, i have fixed it

I've reviewed the race condition fix in EntityCsv.java:1277-1293. The issue has been resolved ✅

What was fixed:

The previous code had a race condition where pendingChangeEvents.clear() was called inside the async task, meaning new events could be added to the list between when the task was submitted and when it cleared the list.

Current implementation (commit b23c2512f8):

List<String> eventsToInsert = new ArrayList<>(pendingChangeEvents);
pendingChangeEvents.clear(); // Clear immediately to avoid race condition
AsyncService.getInstance()
    .getExecutorService()
    .submit(
        () -> {
          try {
            Entity.getCollectionDAO().changeEventDAO().insertBatch(eventsToInsert);
            LOG.info("Batch inserted {} change events", eventsToInsert.size());
          } catch (Exception e) {
            LOG.error("Error batch inserting change events", e);
          }
        });

Why this fixes the race condition:

  1. Creates a defensive copy of the list (eventsToInsert) on the calling thread
  2. Clears pendingChangeEvents immediately before submitting the async task
  3. The async task operates on the isolated copy, preventing concurrent modification

This ensures that any new events added after the clear operation will be part of the next batch, and the async task processes a stable snapshot of events. Great fix! 👍

@sonarqubecloud

sonarqubecloud Bot commented Feb 5, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Feb 5, 2026

Copy link
Copy Markdown
Contributor

Failed to cherry-pick changes to the 1.11.9 branch.
Please cherry-pick the changes manually.
You can find more details here.

This branch had an error being deployed

1 failed deployment
test — 6866b4bf Deployed Feb 5, 2026 by harshach via playwright-ci-postgresql (4, 6) #33114
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 To release Will cherry-pick this PR into the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants