You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@seatunnel.apache.org by "DanielLeens (via GitHub)" <gi...@apache.org> on 2026/09/05 01:42:01 UTC
[I] [Feature][Connector-V2][JDBC] Bound sampling cost and live split memory for large-table reads [seatunnel]
DanielLeens opened a new issue, #12097:
URL: https://github.com/apache/seatunnel/issues/12097
### Search before asking
I reviewed #10288 (database-side sampled balanced sharding) and #10596 (allow disabling sampling). This is a related, broader design discussion: reducing sampling scans alone does not bound the memory used by chunk generation, split assignment, reader queues, and checkpoint state. Please link or consolidate this issue if the community prefers one tracking issue.
### Description
Could contributors help design a minimally invasive, reusable JDBC split-planning improvement that addresses both expensive sampling scans and unbounded in-memory split metadata for very large tables?
We need to control database work, sample memory, and the number of simultaneously resident splits together, while preserving data coverage, reasonable work per split, and recovery semantics. No particular algorithm is prescribed here; alternative designs and database execution-plan evidence would be very welcome.
#### Current upstream behavior
The following findings were checked against `dev` commit [`ce4cde54c8abc7a6a9e3831110dbab029512ef7b`](https://github.com/apache/seatunnel/commit/ce4cde54c8abc7a6a9e3831110dbab029512ef7b). They are source-level observations, not the result of a new large-scale benchmark or an attached heap dump.
1. **The default sampling path consumes the entire query result before retaining every Nth row.** `JdbcDialect.sampleDataFromColumn()` executes `SELECT split_column FROM table` (or from the configured subquery), iterates the complete ResultSet, retains every `samplingRate`-th value in an `ArrayList`, converts it to an array, and sorts it. Thus increasing the inverse sampling rate reduces retained samples but not the rows traversed and returned through JDBC. A covering index may change the physical access path, but it does not make this a bounded sample query. [Default implementation](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/JdbcDialect.java#L385), [Oracle override](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connect
ors/seatunnel/jdbc/internal/dialect/oracle/OracleDialect.java#L333).
2. **Chunk and split collections are eagerly materialized.** `DynamicChunkSplitter.createDynamicSplits()` obtains the complete `List<ChunkRange>` and builds a second `List<JdbcSourceSplit>`. Both sampled and iterative uneven splitting accumulate chunk ranges. This leaves memory proportional to the number of generated boundaries/splits even if the sampling query becomes cheaper. [Conversion](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/DynamicChunkSplitter.java#L81), [sampled and iterative splitting](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/DynamicChunkSplitter.java#L632).
3. **Assignment moves the backlog to readers rather than bounding it.** `JdbcSourceSplitEnumerator.run()` generates all splits for a table, groups them into pending lists, and assigns each reader its complete list. `handleSplitRequest()` currently throws unsupported-operation. `JdbcSourceReader.addSplits()` appends all received splits to an uncapped deque, and `snapshotState()` copies that deque. The enumerator state also contains its pending split lists. [Enumerator](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/JdbcSourceSplitEnumerator.java#L73), [Reader](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/JdbcSourceReader.java#L38), [state](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e38
31110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/state/JdbcSourceState.java#L32).
4. **Disabling sampling is already supported, but does not solve the full resource problem.** With `split.allow-sampling=false`, the uneven-data path uses iterative chunk-boundary queries and still builds the full chunk list. With sampling enabled, this path is chosen when the distribution heuristic considers the key uneven and the estimated split count exceeds `split.sample-sharding.threshold`. [Strategy selection](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/source/DynamicChunkSplitter.java#L455).
#### Illustrative scale
For a table with 100 billion rows, an **explicitly configured** `split.size=100000`, and inverse sampling rate 1000:
- The estimated split count is 1 million; the actual count depends on key distribution and boundary deduplication.
- The current full-result sampling path can retain approximately 100 million sample values and then sort them.
- A plan with approximately 1 million distinct boundaries produces correspondingly large chunk/split lists, assignment payloads, reader queues, and recoverable pending state.
These are arithmetic scaling examples, not measured object sizes or a claim that every such job necessarily OOMs. Actual memory depends on types, heap sizing, serialization, and consumption speed. The inspected upstream default `split.size` is **8096**, not 100000. [Defaults](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/config/JdbcSourceOptions.java#L49).
#### Desired outcomes
- **Bound planning memory across the job:** sample values, chunk metadata, enumerator backlog, assignment/serialization batches, reader prefetch, and checkpoint state. Per-table limits alone are insufficient for multi-table jobs. A task may process many small splits over its lifetime without keeping all of them resident simultaneously.
- **Reduce and measure planning-side database work:** distinguish sampling, min/max, exact counts, statistics collection, and repeated boundary queries. A small result or `fetchSize` does not by itself prove low physical scan cost. The inspected Oracle row-count path can also execute `ANALYZE ... COMPUTE STATISTICS` unless `skip_analyze` is set, or use exact counting for query-based reads; these costs should be accounted for separately. [Oracle row-count path](https://github.com/apache/seatunnel/blob/ce4cde54c8abc7a6a9e3831110dbab029512ef7b/seatunnel-connectors-v2/connector-jdbc/src/main/java/org/apache/seatunnel/connectors/seatunnel/jdbc/internal/dialect/oracle/OracleDialect.java#L224).
- **Preserve manageable split sizes and skew handling:** simply lowering total split count may create very large or skewed splits. The current JDBC reader processes a whole split while holding the checkpoint lock, so larger splits also affect checkpoint latency and recovery work. A total-count cap and a live-buffer cap have different tradeoffs.
- **Preserve correctness and recovery:** cover the intended query/filter scope without gaps or unintended overlap; handle NULLs, duplicate/hot keys, sparse ranges, empty/insufficient samples, and stale estimates. If planning becomes incremental, define ownership of planned, assigned, returned, and completed splits, checkpoint compatibility, and rescaling behavior. Restoring must not silently change already established boundaries through fresh sampling.
- **Keep common logic shared and adaptations narrow:** editing the interface default alone will not cover dialects that override sampling. Database-native sampling/index behavior must be validated for supported database versions and query shapes, including databases without suitable indexes or native sampling.
- **Keep the change reviewable:** prefer reuse of existing connector APIs and a minimal coherent implementation over an unrelated engine redesign; do not claim an end-to-end fix while one unbounded stage remains.
#### Questions for contributors
1. What is the smallest practical design that bounds live split state end to end: lazy split generation with bounded reader requests, a compact resumable range plan, a bounded total split count with an explicit split-size policy, or another approach?
2. How should bounded samples be used to plan many reasonably balanced splits without building a full boundary list or falling back to a database query for every row-count chunk? Are coarse sampled ranges plus incremental refinement viable, and how should their database cost be limited?
3. Which database-native block sampling, existing histogram/statistics, or indexed probing approaches have measured low scan cost? What should the explicit fallback be when those capabilities are unavailable? Reservoir sampling over the full ResultSet bounds memory but does not remove its scan/network cost; SQL-side random filters or `NTILE` should also be evaluated by actual plans rather than assumed efficient.
4. Can the existing `sendSplitRequest()` / `handleSplitRequest()` interfaces support bounded JDBC prefetch with safe checkpoint/assignment ordering? How should synchronous requests, cancellation, and existing saved state be handled?
#### Suggested validation
- Compare baseline and candidate plans on dense, sparse, and highly skewed indexed keys, plus unsupported/no-index cases and filtered queries; report scanned rows/blocks, returned rows/bytes, SQL count, planning latency, and heap usage.
- Use a synthetic million-split workload with slow or paused readers. Assert that generation stops at the configured budget and that no upstream list, downstream queue, in-flight payload, or completion-tracking collection grows with total processed split count.
- Exercise multiple tables under a shared budget, wide metadata, empty samples, NULL/duplicate keys, stale statistics, timeout, and cancellation.
- Inject failures around planning advancement, assignment, split return, and checkpoint completion. Verify restored coverage and existing delivery guarantees, including compatibility with old state and changes in reader parallelism.
- Check both sampling-enabled and sampling-disabled paths. Improvements to one must not hide unbounded behavior in the other.
### Usage Scenario
Large JDBC batch reads with billions to hundreds of billions of rows, uneven keys, multiple tables, and source databases where extra planning scans are expensive. The goal is a root-cause improvement that benefits JDBC users across dialects, rather than a driver-specific workaround. CDC snapshot splitting is related, but has a separate lifecycle and should be evaluated explicitly rather than assumed fixed by a JDBC change.
### Related issues
- #10288: database-side sampled balanced sharding. This issue adds end-to-end live split memory and recovery constraints to that discussion.
- #10596: disabling sampling. The current `split.allow-sampling` option is acknowledged; this is not another request for the switch.
### Are you willing to submit a PR?
- [ ] Yes I am willing to submit a PR!
Opening this for community design input and contributor proposals before choosing an implementation. Execution plans, production-scale measurements, and small proof-of-concept comparisons would be especially helpful.
### Code of Conduct
- [x] I agree to follow this project's [Code of Conduct](https://www.apache.org/foundation/policies/conduct).
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Improve][Connector-V2][JDBC] Excessive scanning and split-memory growth when reading large tables [seatunnel]
Posted by "CryoThrust (via GitHub)" <gi...@apache.org>.
CryoThrust commented on issue #12097:
URL: https://github.com/apache/seatunnel/issues/12097#issuecomment-5551288601
The proposed direction is promising, but I would separate the work into two independently verifiable phases so the optimization does not change read semantics and split planning at the same time.\n\n1. First establish a bounded-dispatch contract: keep the existing `ChunkRange` generation algorithm, but introduce a reader/enumerator handoff that limits in-flight/pending split metadata and preserves deterministic split IDs across checkpoint/restart. This gives a measurable memory bound without changing predicates.\n2. Then add database-side sampling or boundary probing per dialect behind an explicit capability, with a conservative fallback that never silently downloads the full split-key column for a large table.\n\nFor the boundary algorithm, the acceptance contract should explicitly cover: nullable keys (a dedicated NULL split or documented exclusion), duplicate probe boundaries (guaranteed progress), inclusive/exclusive predicates with no overlap/gap, planning snapshot consistenc
y, empty ranges, and restart identity. I would also report plan metrics such as rows/bytes scanned during planning, generated split count, peak pending metadata, and fallback reason.\n\nA small first PR could therefore add deterministic split-plan/property tests and a bounded pending-state abstraction, before any dialect-specific SQL. That keeps the performance claim measurable and makes it easier to review correctness independently from database-specific sampling syntax.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Improve][Connector-V2][JDBC] Excessive scanning and split-memory growth when reading large tables [seatunnel]
Posted by "DanielLeens (via GitHub)" <gi...@apache.org>.
DanielLeens commented on issue #12097:
URL: https://github.com/apache/seatunnel/issues/12097#issuecomment-5551704114
Thanks @programmerloverun. I rechecked current dev and the open PR set. The report still identifies three distinct costs: the JDBC sampling path drains the complete result set, the enumerator materializes and assigns all generated splits, and each reader appends its assignment to an unbounded deque. There is no open PR covering this combined path.
GitHub did not accept an assignee update for this account, so this comment records the accepted coordination claim rather than asserting that issue metadata changed.
Please keep the investigation and implementation order explicit. The first slice must show how a bounded handoff can work without changing split predicates, stable split IDs, checkpoint restore, or read completeness. The current enumerator does not implement split requests, so a cap that merely withholds assignments would strand remaining work. Add deterministic tests for split progression, null and duplicate boundaries, empty ranges, restore, and skew before adding dialect-specific sampling SQL. Any database-side sampling or probing must be an explicit dialect capability with a fallback that never silently returns to a full client-side scan. Attach the measured planning scan volume, generated and pending split counts, peak retained metadata, and comparable before/after results to the focused PR.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Improve][Connector-V2][JDBC] Excessive scanning and split-memory growth when reading large tables [seatunnel]
Posted by "CryoThrust (via GitHub)" <gi...@apache.org>.
CryoThrust commented on issue #12097:
URL: https://github.com/apache/seatunnel/issues/12097#issuecomment-5551076901
A few correctness/recovery constraints seem important before implementation, especially if the design combines arithmetic ranges with boundary probing:
- The split predicate must define `NULL` handling and inclusive/exclusive boundaries explicitly. Adjacent splits should be disjoint while covering every row, including nullable split keys and duplicate boundary values.
- `MIN/MAX` and probe results need a consistency contract. If planning runs outside a transaction or the source changes during enumeration, document whether snapshot isolation is required, or how the reader prevents gaps/duplicates caused by moving boundaries.
- A split cap should be a cap on planned work, not an implicit row-count guarantee. For highly skewed keys, expose when a bounded split plan may produce uneven reader load and keep checkpoint/retry identity stable for each generated range.
- For database-side sampling, specify the fallback when sampling is unsupported or returns too few distinct keys. The fallback must not silently revert to a full client-side column scan for very large tables.
- Please include acceptance tests for nullable keys, duplicate boundary values, empty ranges, skewed distributions, concurrent inserts/deletes during planning, and enumerator restart from a checkpoint.
These constraints would make the optimization measurable without changing the source's read-completeness or recoverability semantics.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Improve][Connector-V2][JDBC] Excessive scanning and split-memory growth when reading large tables [seatunnel]
Posted by "programmerloverun (via GitHub)" <gi...@apache.org>.
programmerloverun commented on issue #12097:
URL: https://github.com/apache/seatunnel/issues/12097#issuecomment-5550874421
<img width="940" height="481" alt="Image" src="https://github.com/user-attachments/assets/50ee2a07-d897-4e1d-8ca6-43cc12fbc8e8" />
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Improve][Connector-V2][JDBC] Excessive scanning and split-memory growth when reading large tables [seatunnel]
Posted by "programmerloverun (via GitHub)" <gi...@apache.org>.
programmerloverun commented on issue #12097:
URL: https://github.com/apache/seatunnel/issues/12097#issuecomment-5550850478
Hi, I would like to take this issue.
I will investigate the excessive scanning and split memory growth problem for JDBC Source V2 when reading large tables, and work on the improvement.
Please assign this issue to me, thanks.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
Re: [I] [Improve][Connector-V2][JDBC] Excessive scanning and split-memory growth when reading large tables [seatunnel]
Posted by "programmerloverun (via GitHub)" <gi...@apache.org>.
programmerloverun commented on issue #12097:
URL: https://github.com/apache/seatunnel/issues/12097#issuecomment-5550865886
@DanielLeens @davidzollo Here is my proposed solution. I would like to go over it with you and check whether there are any missing parts or unreasonable aspects.
## 1. Background
The SeaTunnel JDBC Source, before starting parallel reads, first plans splits based on a split key: depending on the data distribution, it chooses uniform splitting, iterative non-uniform splitting, or sampling-based splitting.
The current implementation has two key paths:
1. **Sampling-based planning**: `sampleDataFromColumn()` queries the split column; the client iterates over the `ResultSet`, keeps samples at `inverse-sampling.rate`, then sorts them to determine boundaries. The default path essentially scans the entire split-column result set and keeps one row out of every N.
2. **Split materialization and dispatch**: all splits are generated at once — the Enumerator splits the entire table and hands everything to the Reader in one go; the Reader buffers them in an unbounded queue.
On small and medium tables this strategy is usually acceptable; but in batch sync scenarios with **tens to hundreds of billions of rows, skewed keys, multiple tables, and expensive planning scans against the source database**, planning cost and JVM memory scale linearly (or even super-linearly) with data size. The community already has a sampling switch ([#10596](https://github.com/apache/seatunnel/issues/10596) / [#10604](https://github.com/apache/seatunnel/pull/10604)) and a database-side sampling proposal ([#10288](https://github.com/apache/seatunnel/issues/10288)), but neither covers the combined problem of "sampling scan + full materialization of split metadata".
## 2. Goal
In ultra-large-table, skewed-key, multi-table JDBC Source scenarios, eliminate slow planning, memory bloat, and OOM risk caused by **full-scale sampling scans + fully materialized/buffered split metadata**, without sacrificing the correctness and recoverability of parallel reads.
## 3. Design
### 3.1 Reference Approaches
1. **Apache Spark JDBC: arithmetic range splitting, with the number of splits bound to parallelism**
Suppose a table has a numeric column `id`, roughly ranging from 1 to 1000, and you want to read this table with 4-way parallelism.
You tell Spark four things:
- Which column to split by: `id`
- Minimum value: 1
- Maximum value: 1000
- Number of partitions: 4 (usually roughly equal to your desired parallelism)
This generates 4 ranges (illustrative):
| Split | Approximate condition | Reader |
| --- | --- | --- |
| 0 | `id < 251` (edge cases like very small values / `null` omitted) | Task 0 |
| 1 | `id >= 251 AND id < 501` | Task 1 |
| 2 | `id >= 501 AND id < 751` | Task 2 |
| 3 | `id >= 751` | Task 3 |
Each Task connects to the database on its own and queries only its own range. This is **arithmetic range splitting**: divide using the lower and upper bounds to obtain equal-width ranges.
"**Number of splits bound to parallelism**" means: if you ask for 4 splits, you get roughly 4 splits — not 1 million splits just because the table has 10 billion rows.
2. **Alibaba DataX: database-side SAMPLE + number of splits close to Channel**
> Channel: the number of concurrent channels in DataX, which can be understood as "how many read tasks run at the same time". For example, `channel = 4` means roughly 4-way parallel reads.
>
> Database-side SAMPLE: sampling is done inside the database, instead of pulling the entire column back to DataX and keeping one row out of every N.
> Oracle example: `SELECT id FROM t SAMPLE(1)` → the database returns only about 1% of the rows (the exact syntax varies by database).
Suppose the table is very large, with 100 million rows.
Instead of pulling 100 million `id`s, we only get back id samples at roughly **1%** of the original volume.
Sort the samples and pick boundaries at a partition count close to the channel number — e.g. split into 4 ranges, yielding boundaries `a < b < c`.
We then get four ranges: `(-∞, a) [a, b) [b, c) [c, +∞)`
Each Channel/Task performs the full `SELECT` over its own range in parallel: the number of splits is bounded, and so is the planning traffic.
3. **Apache Flink CDC: uniform step + index probing, avoiding full-column client-side sampling**
Two strategies are used:
**Strategy 1: the key distribution looks uniform — split directly with an arithmetic step**
First query `MIN(id)` and `MAX(id)`, then estimate the row count and compute a distribution factor. If the distribution looks fairly uniform, split by step:
```java
Suppose id ranges from 1 to 1000, and a chunk is roughly 250 rows.
Split into:
[1, 251), [251, 501), [501, 751), [751, +∞)
```
**Strategy 2: the key distribution is non-uniform — repeatedly "probe" the database for the upper bound of the next chunk**
When the value range is huge but the actual row count is small, or the data is crowded into one segment, equal-width splitting leads to:
- many empty chunks, or
- a few extremely heavy chunks.
In this case, switch tactics: starting from the current lower bound, let the database tell you **what the upper bound is after roughly `chunkSize` rows further down**.
```java
current lower bound = 1, chunkSize = 1000
Ask the DB: with id >= 1, roughly 1000 rows further down, what is the largest id?
DB answers: 3520
→ chunk [1, 3520)
Ask again: with id >= 3520, roughly 1000 rows further down, what is the largest id?
DB answers: 3605
→ chunk [3520, 3605)
……until MAX is covered
```
### 3.2 What We Do
1. Following Spark/DataX, use a **split cap** to solve split explosion.
2. Following Flink, use **uniform arithmetic splitting + boundary probing for non-uniform distributions** to replace full-column client-side sampling. SAMPLE and batched dispatch are not the main path in this phase. We only enhance the JDBC Source's generic splitting capability, keeping read-completeness and recoverability semantics while controlling memory and planning cost.
<img width="2092" height="1212" alt="Image" src="https://github.com/user-attachments/assets/58d29f22-48c9-4c28-ad0f-6a08d0fa3e0a" />
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: commits-unsubscribe@seatunnel.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org