Skip to content

fix(jdbi3): chunk IN-list batch queries to stay under DB parameter limit - #28752

Merged
harshach merged 6 commits into
mainfrom
fix/in-list-chunking-bulk-delete
Jun 5, 2026
Merged

harshach merged 6 commits into
mainfrom
fix/in-list-chunking-bulk-delete

Conversation

@sonika-shah

@sonika-shah sonika-shah commented Jun 5, 2026 •

Copy link
Copy Markdown
Collaborator

Fixes #28756

Problem

Deleting a large service fails on PostgreSQL with:

org.postgresql.util.PSQLException: PreparedStatement can have at most 65,535 parameters ...
Given query has 100,002 parameters
[statement: EntityRelationshipDAO.findToBatchAllTypesWithRelationsCondition ...]

The bulk subtree delete/restore path (EntityRepository.bulkHardDeleteSubtree / bulkSoftDeleteSubtree / bulkRestoreSubtree) walks the hierarchy one level at a time and fans every id at a level into a single IN (...) query. JDBI's @BindList emits one bind parameter per element, so a level with ~100k entities (e.g. a service with 100k tables) blows past PostgreSQL's 65,535-parameter ceiling (the protocol's int2-sized numParams field).

The reported findToBatchAllTypes crash was only the first uncaught offender: getExtensionsBatch hits the same limit earlier in populateRelationFields, but that exception is swallowed by the per-entity fallback try/catch, so it silently degrades instead of surfacing. Several other findToBatch* / findFromBatch* and tag batches were vulnerable in other paths (lineage, reindex, profiler-config loads).

Postgres-specific: MySQL caps on max_allowed_packet, and 100k × 36-char UUIDs (~3.6 MB) stays well under its 64 MB default.

Fix

  • Add EntityDAO.queryInChunks(List, Function) and updateInChunks(List, Consumer) helpers that split id lists at MAX_IN_LIST_CHUNK_SIZE (30k) and concatenate results. For inputs at or below the chunk size the list is passed straight through, preserving single-query behavior (and the caller's empty-list handling) exactly.
  • Route every @BindList batch method through the helpers (raw @SqlQuery/@SqlUpdate renamed to *Internal, public signature retained as a default wrapper):
    • EntityRelationshipDAO: all findToBatch* / findFromBatch* overloads
    • EntityExtensionDAO: deleteAllBatch, getExtensionsBatch, getExtensionBatch
    • TagUsageDAO: getTagsInternalBatch, getCertTagsInternalBatch
  • Extract the duplicated deletedCondition(include) clause builder (was repeated ~12×).

Test plan

  • New InListChunkingTest — outcome-based: every chunk stays within MAX_IN_LIST_CHUNK_SIZE, the union of chunks equals the input exactly once (no dropped/duplicated ids), and the aggregated result equals the concatenation of per-chunk results.
  • Existing EntityRepositoryRestoreTest (bulk delete/restore dispatch) — 13/13 still pass.
  • mvn spotless:check -pl openmetadata-service — clean.

🤖 Generated with Claude Code


Additional IN-list paths chunked (same root cause)

An audit of the remaining @BindList paths found three more methods that fan a caller-controlled, catalog-scaled list into one IN (...) and can hit the same ceiling. All now routed through the shared chunking helpers:

  • EntityRelationshipDAO.bulkUpdateFromId — glossary-term reparent updates every nested descendant relationship row in one UPDATE (subtree >65k terms).
  • TagUsageDAO.deleteTagsByTargets — clearing column tags on bulk table update/import passes every column FQN across the batch (wide/nested tables × ~100/batch).
  • EntityTimeSeriesDAO.getLatestExtensionBatch — GET …/ingestionPipelines?fields=pipelineStatuses&limit=… (limit @Max(1000000)) binds one FQN-hash per row.

(One further path — UserDAO.updateLastActivityTimeBulk + its unbounded localActivityCache — is intentionally left for a separate change: it needs repository-level map chunking of the inlined CASE statement plus a cache-bounding decision, not a simple wrapper.)

Bulk subtree delete/restore fans an entire tree level's ids into a single
IN (...) query. JDBI @BindList emits one bind parameter per element, so a
level with ~100k entities (e.g. a service with 100k tables) exceeds
PostgreSQL's 65,535 parameter ceiling ("Given query has 100,002 parameters")
and the operation fails. The reported findToBatchAllTypes crash was only the
first uncaught offender: getExtensionsBatch hits the same limit earlier but is
swallowed by populateRelationFields' per-entity fallback, and ~13 other
findToBatch*/findFromBatch* and tag batches were vulnerable in other paths.

Add EntityDAO.queryInChunks / updateInChunks helpers (chunk at
MAX_IN_LIST_CHUNK_SIZE, pass straight through for small lists so single-query
behavior is preserved) and route every @BindList batch method through them:
findToBatch*/findFromBatch*, entity_extension deleteAllBatch /
getExtensionsBatch / getExtensionBatch, and tag_usage getTagsInternalBatch /
getCertTagsInternalBatch. Also extract the duplicated deletedCondition(include)
clause builder.

Adds InListChunkingTest covering the chunk-size cap, exact input coverage
(no dropped/duplicated ids), and per-chunk result aggregation.
Copilot AI review requested due to automatic review settings June 5, 2026 10:47
@github-actions

github-actions Bot commented Jun 5, 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 backend safe to test Add this label to run secure Github workflows on PRs labels Jun 5, 2026
@sonika-shah sonika-shah added the To release Will cherry-pick this PR into the release branch label Jun 5, 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.

Pull request overview

This PR prevents PostgreSQL “too many prepared statement parameters” failures by chunking large IN (...) batch queries invoked through JDBI @BindList, primarily in bulk delete/restore and other high-fanout relationship/extension/tag fetch paths.

Changes:

  • Added EntityDAO.queryInChunks / EntityDAO.updateInChunks helpers and a shared MAX_IN_LIST_CHUNK_SIZE (30k) to keep each statement under DB parameter ceilings.
  • Refactored multiple CollectionDAO batch DAO methods to wrap @BindList queries/updates with chunking via default methods, and centralized Include → deleted SQL clause generation.
  • Added InListChunkingTest to validate chunk sizing and end-to-end aggregation behavior for representative DAO methods.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/EntityDAO.java Introduces generic chunking helpers for large IN-list queries/updates.
openmetadata-service/src/main/java/org/openmetadata/service/jdbi3/CollectionDAO.java Routes several @BindList batch methods through chunking wrappers and deduplicates deleted-condition logic.
openmetadata-service/src/test/java/org/openmetadata/service/jdbi3/InListChunkingTest.java Adds outcome-based tests ensuring chunk size limits and correct aggregation across chunks.

queryInChunks / updateInChunks split a large id list into chunks, so a
duplicate value landing in two different chunks would be queried (or deleted)
twice — duplicating result rows / issuing a redundant statement, unlike a
single IN (...) which ignores duplicate values. De-duplicate (encounter order
preserved) before chunking, matching the existing findEntitiesByIds pattern.

Adds InListChunkingTest cases covering duplicates split across a chunk
boundary for both the query and update helpers.
Audit of the remaining @BindList paths surfaced three more methods that fan a
caller-controlled, catalog-scaled list into one IN (...) and can hit the same
65,535 parameter ceiling. All routed through the queryInChunks/updateInChunks
helpers:

- EntityRelationshipDAO.bulkUpdateFromId — reparenting a glossary term updates
  every nested descendant's relationship row in one UPDATE; a subtree with
  >65k terms blew the cap. Now chunks toIds via updateInChunks.
- TagUsageDAO.deleteTagsByTargets — clearing column tags on a bulk table
  update/import passes every column FQN across the batch (wide/nested tables x
  ~100 per batch). Now chunks via updateInChunks.
- EntityTimeSeriesDAO.getLatestExtensionBatch — listing ingestion pipelines
  with fields=pipelineStatuses and a large limit (capped at 1,000,000) binds
  one FQN-hash per row. Now chunks via queryInChunks.

Adds InListChunkingTest cases for all three.
Copilot AI review requested due to automatic review settings June 5, 2026 12:59

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.

Pull request overview

Copilot reviewed 4 out of 4 changed files in this pull request and generated no new comments.

Follow-up to the IN-list chunking work — five more @BindList paths fan a catalog-scaled list into one IN (...) and can still hit the 65,535 parameter ceiling. All routed through the existing queryInChunks/updateInChunks helpers.

- EntityRelationshipDAO.bulkRemoveTo / bulkRemoveFrom: the 'remove' siblings of bulkUpdateFromId (already chunked). Reached via the bulkRemove{To,From}Relationship wrappers (their only callers) from DataProductRepository.batchMigrateAssetDomains (all assets of a type under one data product), TeamRepository, DomainRepository.
- UsageDAO.getLatestUsageBatch: GET /v1/tables?fields=usageSummary (and dashboards/pipelines/topics/mlmodels/...) resolves the field over the whole page via setFieldsInBulk; list limit is @max(1000000).
- DataQualityDataTimeSeriesDAO.getLatestRecordBatch: GET /v1/dataQuality/testCases?fields=testCaseResult, same whole-page resolution.
- TestCaseResultTimeSeriesDAO.listResultSummariesForTestSuites: GET /v1/dataQuality/testSuites?fields=summary, binds one id per executable test suite.

Adds InListChunkingTest cases for all five (16 tests pass).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings June 5, 2026 15:04

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.

@sonarqubecloud

sonarqubecloud Bot commented Jun 5, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

🟡 Playwright Results — all passed (14 flaky)

✅ 4268 passed · ❌ 0 failed · 🟡 14 flaky · ⏭️ 88 skipped

Shard Passed Failed Flaky Skipped
🟡 Shard 1 299 0 2 4
🟡 Shard 2 800 0 4 9
🟡 Shard 3 803 0 4 8
🟡 Shard 4 854 0 1 12
✅ Shard 5 721 0 0 47
🟡 Shard 6 791 0 3 8
🟡 14 flaky test(s) (passed on retry)
  • Features/CustomizeDetailPage.spec.ts › Glossary - customization should work (shard 1, 1 retry)
  • Pages/AuditLogs.spec.ts › should apply both User and EntityType filters simultaneously (shard 1, 1 retry)
  • Features/DataQuality/BundleSuiteBulkOperations.spec.ts › Add test case to existing Bundle Suite (shard 2, 1 retry)
  • Features/DataQuality/TestCaseImportExportE2eFlow.spec.ts › Admin: Complete export-import-validate flow (shard 2, 1 retry)
  • Features/DataQuality/TestCaseResultPermissions.spec.ts › User with only VIEW cannot PATCH results (shard 2, 1 retry)
  • Features/Glossary/GlossaryHierarchy.spec.ts › should cancel move operation (shard 2, 1 retry)
  • Features/IncidentManager.spec.ts › Resolving incident & re-run pipeline (shard 3, 1 retry)
  • Features/RTL.spec.ts › Verify Following widget functionality (shard 3, 1 retry)
  • Features/Table.spec.ts › Tags term should be consistent for search (shard 3, 1 retry)
  • Flow/ExploreAggregationCountsMatching.spec.ts › should verify left panel counts and tab search results for normal search (shard 3, 1 retry)
  • Pages/DataContracts.spec.ts › Create Data Contract and validate for Table (shard 4, 1 retry)
  • Pages/Lineage/LineageFilters.spec.ts › Verify lineage schema filter selection (shard 6, 1 retry)
  • Pages/Lineage/LineageRightPanel.spec.ts › Verify custom properties tab IS visible for supported type: searchIndex (shard 6, 1 retry)
  • Pages/Lineage/PlatformLineage.spec.ts › Verify domain platform view (shard 6, 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

@harshach
harshach merged commit 5af1ba5 into main Jun 5, 2026
52 of 58 checks passed
@harshach
harshach deleted the fix/in-list-chunking-bulk-delete branch June 5, 2026 19:45
@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

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

@github-actions

github-actions Bot commented Jun 5, 2026

Copy link
Copy Markdown
Contributor

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

@gitar-bot

gitar-bot Bot commented Jun 5, 2026

Copy link
Copy Markdown
Code Review ✅ Approved

Implements chunking logic for large IN-list queries to prevent PostgreSQL parameter limit violations. The refactor successfully routes vulnerable batch methods through size-constrained helpers while maintaining original query behavior.

Options

Display: compact → Showing less information.

Comment with these commands to change:

Compact
gitar display:verbose         

Was this helpful? React with 👍 / 👎 | Gitar

harshach added a commit that referenced this pull request Jun 5, 2026
…mit (#28752) (#28777)

* fix(jdbi3): chunk IN-list batch queries to stay under DB parameter limit

Bulk subtree delete/restore fans an entire tree level's ids into a single
IN (...) query. JDBI @BindList emits one bind parameter per element, so a
level with ~100k entities (e.g. a service with 100k tables) exceeds
PostgreSQL's 65,535 parameter ceiling ("Given query has 100,002 parameters")
and the operation fails. The reported findToBatchAllTypes crash was only the
first uncaught offender: getExtensionsBatch hits the same limit earlier but is
swallowed by populateRelationFields' per-entity fallback, and ~13 other
findToBatch*/findFromBatch* and tag batches were vulnerable in other paths.

Add EntityDAO.queryInChunks / updateInChunks helpers (chunk at
MAX_IN_LIST_CHUNK_SIZE, pass straight through for small lists so single-query
behavior is preserved) and route every @BindList batch method through them:
findToBatch*/findFromBatch*, entity_extension deleteAllBatch /
getExtensionsBatch / getExtensionBatch, and tag_usage getTagsInternalBatch /
getCertTagsInternalBatch. Also extract the duplicated deletedCondition(include)
clause builder.

Adds InListChunkingTest covering the chunk-size cap, exact input coverage
(no dropped/duplicated ids), and per-chunk result aggregation.

* fix(jdbi3): dedup ids before chunking IN-list batches

queryInChunks / updateInChunks split a large id list into chunks, so a
duplicate value landing in two different chunks would be queried (or deleted)
twice — duplicating result rows / issuing a redundant statement, unlike a
single IN (...) which ignores duplicate values. De-duplicate (encounter order
preserved) before chunking, matching the existing findEntitiesByIds pattern.

Adds InListChunkingTest cases covering duplicates split across a chunk
boundary for both the query and update helpers.

* fix(jdbi3): chunk three more unbounded IN-list paths

Audit of the remaining @BindList paths surfaced three more methods that fan a
caller-controlled, catalog-scaled list into one IN (...) and can hit the same
65,535 parameter ceiling. All routed through the queryInChunks/updateInChunks
helpers:

- EntityRelationshipDAO.bulkUpdateFromId — reparenting a glossary term updates
  every nested descendant's relationship row in one UPDATE; a subtree with
  >65k terms blew the cap. Now chunks toIds via updateInChunks.
- TagUsageDAO.deleteTagsByTargets — clearing column tags on a bulk table
  update/import passes every column FQN across the batch (wide/nested tables x
  ~100 per batch). Now chunks via updateInChunks.
- EntityTimeSeriesDAO.getLatestExtensionBatch — listing ingestion pipelines
  with fields=pipelineStatuses and a large limit (capped at 1,000,000) binds
  one FQN-hash per row. Now chunks via queryInChunks.

Adds InListChunkingTest cases for all three.

* test(jdbi3): cover IN-list chunking pass-through with duplicate ids

The existing tests all feed an over-limit list, leaving queryInChunks /
updateInChunks' else branch (size <= MAX_IN_LIST_CHUNK_SIZE) untested. Add two
cases proving a within-limit list with duplicates issues exactly one
query/statement and is passed through verbatim (no dedup) — the database
collapses the duplicates via IN(...) set semantics. Complements the existing
over-limit dedup tests, which assert against the distinct set.

* fix(jdbi3): chunk five more catalog-scaled IN-list paths

Follow-up to the IN-list chunking work — five more @BindList paths fan a catalog-scaled list into one IN (...) and can still hit the 65,535 parameter ceiling. All routed through the existing queryInChunks/updateInChunks helpers.

- EntityRelationshipDAO.bulkRemoveTo / bulkRemoveFrom: the 'remove' siblings of bulkUpdateFromId (already chunked). Reached via the bulkRemove{To,From}Relationship wrappers (their only callers) from DataProductRepository.batchMigrateAssetDomains (all assets of a type under one data product), TeamRepository, DomainRepository.
- UsageDAO.getLatestUsageBatch: GET /v1/tables?fields=usageSummary (and dashboards/pipelines/topics/mlmodels/...) resolves the field over the whole page via setFieldsInBulk; list limit is @max(1000000).
- DataQualityDataTimeSeriesDAO.getLatestRecordBatch: GET /v1/dataQuality/testCases?fields=testCaseResult, same whole-page resolution.
- TestCaseResultTimeSeriesDAO.listResultSummariesForTestSuites: GET /v1/dataQuality/testSuites?fields=summary, binds one id per executable test suite.

Adds InListChunkingTest cases for all five (16 tests pass).

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

---------

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

[1.13 backport] Dropped the findToBatchAllTypes(List<Integer> relations, Include)
chunking hunk and its findToBatchAllTypesWithRelationsCondition delegate: that
overload originates in temporal lineage (#28426), which is not on the 1.13 branch.
The two queryInChunks dedup / pass-through tests that exercised it were retargeted
to the existing int-relation findToBatchAllTypes overload (same queryInChunks path).
All 16 InListChunkingTest cases pass.

(cherry picked from commit 5af1ba5)

Co-authored-by: sonika-shah <[email protected]>
harshach added a commit that referenced this pull request Jun 6, 2026
Resolve CollectionDAO.java conflict from the CollectionDAO split refactor:

- Port #28752 (chunk IN-list batch queries under the DB parameter ceiling)
  onto the moved DAOs: EntityExtensionDAO/EntityRelationshipDAO now live in
  CoreRelationshipDAOs; TagUsageDAO in ClassificationTagDAOs; UsageDAO in
  AccessControlDAOs; DataQualityDataTimeSeriesDAO/TestCaseResultTimeSeriesDAO
  in TimeSeriesDAOs. EntityDAO.queryInChunks/updateInChunks (auto-merged)
  drive the chunking; F1 dead-code delete and P1 lineage parenthesization
  preserved in EntityExtensionDAO/EntityRelationshipDAO.
- Add IntakeFormDAO from #27600 (ODPS/Custom Forms) to the composite
  CollectionDAO (accessor + interface + IntakeForm import).
- Redirect InListChunkingTest imports to the new declaring interfaces.

Service module compiles (main + test); InListChunkingTest (16) and
CollectionDAOCompositionTest (2) pass.

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

This branch was previously deployed

1 inactive deployment
test — 3270c7e8 Deployed Jun 5, 2026 by harshach via playwright-ci-postgresql (2, 6) #50031
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.

Bulk delete of a large service fails on PostgreSQL: PreparedStatement can have at most 65,535 parameters

3 participants