Repository navigation
feat(flink): report read lag and pending work from the Source V2 split enumerator - #20735
skywalker0618 wants to merge 7 commits into
Conversation
cshuo
left a comment
There was a problem hiding this comment.
A high-level design question, is it possible to track lag and backlog in the Source V2 reader or enumerator without changing the core incremental read path, particularly IncrementalInputSplits and HoodieSourceSplit?
…t enumerator The continuous split enumerator now tracks discovered splits until the readers finish them and reports, per table: - readLagSeconds: seconds since the oldest pending commit completed - pendingCommits, split into undiscoveredCommits and inFlightCommits - pendingSplits, pendingRecords and pendingBytes A commit is pending until every split reading it is finished. After each discovery, the enumerator reads the commit metadata of the new commits to find which commits wrote each split's file group and the expected records and bytes. Splits restored from the enumerator state are re-resolved asynchronously on start. The incremental read path, the splits and the state serializers are unchanged. Part of apache#20531.
7a5f842 to
08f8800
Compare
Thanks for the suggestion! It was originally done that way because the information was already available during split generation. On second thought, it's indeed better not to touch the core components. In the revised commit, the enumerator reads the commit metadata of each new commit a second time to compute the lag info, so IncrementalInputSplits, HoodieSourceSplit and the serializers are unchanged. On restart, the enumerator refetches the lag info for the restored splits asynchronously. |
| } | ||
| HoodieContinuousSplitBatch batch = splitDiscover.discoverSplits(issuedOffset); | ||
| String nextOffset = StringUtils.isNullOrEmpty(batch.getOffset()) ? issuedOffset : batch.getOffset(); | ||
| return new DiscoveryResult(batch, resolveLagInfo(batch.getSplits()), getUndiscoveredCommits(nextOffset, false)); |
There was a problem hiding this comment.
Could we publish the discovered splits first and resolve their lag info asynchronously? Once readers drain the previous batch, they have to wait for a second round of commit metadata reads before they can start the next one.
There was a problem hiding this comment.
Great suggestion, moved the lag info to async
There was a problem hiding this comment.
Thanks for moving the write-stat lookup after split publication. Could we also refresh undiscoveredCommits asynchronously after publishing the batch? When the reader skips clustering or insert-overwrite operations, the backlog query checks replace-commit metadata before applying the offset filter. Readers can therefore wait for metadata from already-consumed commits before receiving splits that are ready to assign.
There was a problem hiding this comment.
Good catch! Updated:
- HoodieContinuousSplitEnumerator now refreshes undiscoveredCommits asynchronously via callAsync after splits are published and position is updated.
- DefaultHoodieSplitDiscover.getUndiscoveredCommits now filters completed instants by offset (and read.end-commit) before calling IncrementalQueryAnalyzer.filterInstantsAsPerUserConfigs, so skipClustering / skipInsertOverwrite won't read metadata for already-consumed replace commits.
| long records = 0L; | ||
| long bytes = 0L; | ||
| if (isExactMatch(split)) { | ||
| for (String commit : new TreeSet<>(rangeCommits)) { |
There was a problem hiding this comment.
Each split in a batch builds a TreeSet from the same commit range and scans every commit, even if only one commit touched its file group. Could we sort the range once and index the writes by file group?
There was a problem hiding this comment.
Thanks for indexing writes by file ID. Before publishing the batch, lagMetrics.addSplits() still walks the full commit range once per split on the coordinator thread. Could we group splits that share a range and increment each commit’s counter once by the number of splits in that group?
There was a problem hiding this comment.
Done. FlinkStreamReadLagMetrics (addSplits, updateSplits, finishSplits) now groups splits sharing the same readCommits reference via IdentityHashMap and increments/decrements each commit counter once by the group count. Also deduplicated shared ranges in DefaultHoodieSplitDiscover (getRangeLagInfo, getRangeCommits, getExactMatchCommits).
| private final FlinkStreamReadLagMetrics lagMetrics; | ||
|
|
||
| // Splits restored from the state, whose lag info is resolved once the enumerator starts | ||
| private final List<HoodieSourceSplit> restoredSplits; |
There was a problem hiding this comment.
restoredSplits keeps every restored split reachable for the lifetime of the job, even after readers finish them. Could we release the list once the async lag lookup completes?
danny0405
left a comment
There was a problem hiding this comment.
Two additional metric correctness issues and one small simplification suggestion. The split-delivery latency, repeated range sorting, and restored-split retention concerns are already covered by the existing inline comments.
| return 0L; | ||
| } | ||
| try { | ||
| return Duration.between(HoodieInstantTimeGenerator.parseDateFromInstantTime(oldest).toInstant(), clock.instant()).getSeconds(); |
There was a problem hiding this comment.
[P2] Could we parse the completion time using the table's configured timeline timezone? HoodieInstantTimeGenerator.parseDateFromInstantTime uses ZoneId.systemDefault(), so for a UTC table with the JobManager in Asia/Shanghai a freshly completed commit appears roughly eight hours old; other timezone combinations can produce negative lag. Clock.systemUTC() does not change how the completion timestamp is parsed. Please add a test with a UTC table and a different JVM timezone, using an independently constructed expected instant—the current tests construct the clock with the same parser and therefore mask the mismatch.
There was a problem hiding this comment.
Done, added UTs too.
| scanContext.isSkipInsertOverwrite()); | ||
| return timeline.getInstantsAsStream() | ||
| .map(HoodieInstant::getCompletionTime) | ||
| .filter(completionTime -> completionTime != null && completionTime.compareTo(offset) > 0) |
There was a problem hiding this comment.
[P2] Could we also apply the configured read.end-commit bound here, with the same semantics as discovery? IncrementalInputSplits.inputSplits passes READ_END_COMMIT to the query analyzer, but this calculation counts every completion after the issued offset. If the reader has consumed through its configured end and the table receives later commits, those commits remain permanently 'undiscovered': pendingCommits stays nonzero and readLagSeconds keeps growing even though all eligible data has been consumed. A test with an end bound and a later completed commit would cover this.
There was a problem hiding this comment.
Sure, changed.
| } | ||
|
|
||
| private static Map<String, HoodieSourceSplitLagInfo> getSplitLagInfo(Collection<HoodieSourceSplit> splits) { | ||
| return splits.stream().collect(Collectors.toMap(HoodieSourceSplit::splitId, HoodieSourceSplitLagInfo::of, (first, second) -> first)); |
There was a problem hiding this comment.
Minor simplification: this fallback map construction duplicates the default implementation of HoodieContinuousSplitDiscover.getLagInfo, including its duplicate-key policy. Could we extract a shared collection-to-fallback-info helper, for example on HoodieSourceSplitLagInfo, and use it in both places?
- Publish the discovered splits before resolving their lag info from the commit metadata, which now runs as a separate async call - Index the commit writes by file group once instead of sorting each split's range - Release the restored splits once their lag info lookup is scheduled - Parse completion times in the table's timeline timezone - Bound the undiscovered commits by read.end-commit - Share the fallback lag info helper
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #20735 +/- ##
============================================
+ Coverage 80.89% 80.91% +0.01%
- Complexity 36206 36293 +87
============================================
Files 2591 2594 +3
Lines 147957 148152 +195
Branches 18316 18345 +29
============================================
+ Hits 119697 119876 +179
Misses 19971 19971
- Partials 8289 8305 +16
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
|
Hi @cshuo @danny0405 I made modifications according to the review comments, do you mind taking another look? Thanks! |
|
@skywalker0618 I left two follow-up comments in the threads above. Could you take a look? |
…s in lag metrics - Refresh undiscoveredCommits asynchronously after discovered splits are published so backlog queries do not delay split assignment - Filter completed instants by offset and read.end-commit before applying user skip configs in DefaultHoodieSplitDiscover.getUndiscoveredCommits so replace-commit metadata is not read for already-consumed commits - Group splits sharing a commit range reference in FlinkStreamReadLagMetrics (addSplits, updateSplits, finishSplits) and deduplicate shared ranges in DefaultHoodieSplitDiscover so each shared commit range is walked once per batch
Oops, sorry I missed previous comments. Fixed them, thanks! |
…urce-v2-read-lag-metrics # Conflicts: # hudi-flink-datasource/hudi-flink/src/test/java/org/apache/hudi/source/split/TestDefaultHoodieSplitDiscover.java
| } | ||
|
|
||
| if (enumeratorContext.metricGroup() != null) { | ||
| this.lagMetrics = new FlinkStreamReadLagMetrics(enumeratorContext.metricGroup(), tableName, splitDiscover.getTimelineZone()); |
There was a problem hiding this comment.
A streaming source can start before the table exists. When that happens, HoodieContinuousSplitEnumerator passes the JVM default time zone to FlinkStreamReadLagMetrics, which stores it in its final timelineZone field. If the table is later created with a UTC timeline, readLagSeconds still uses that original zone. Could we resolve completion times using the table’s time zone when discovery reads them? That would also avoid adding getTimelineZone() to the interface.
There was a problem hiding this comment.
Sure, changed
| Map<Collection<String>, Integer> commitRangeCounts = new IdentityHashMap<>(); | ||
| Map<String, Integer> completionTimeCounts = new HashMap<>(); | ||
| lagInfos.forEach((splitId, lagInfo) -> { | ||
| if (pendingSplits.putIfAbsent(splitId, lagInfo) == null) { |
There was a problem hiding this comment.
putIfAbsent assumes a split ID stays unique across JobManager restarts. I reproduced a checkpointed split and a newly discovered split for the same file group both receiving 0:file after the split-number generator restarted. The gauge reported one pending split, then zero when the first finished, while the second was still outstanding. Could we make discovery and completion distinguish both splits across restore, and cover that sequence with a checkpoint round-trip test?
There was a problem hiding this comment.
Great point, I changed to use a stable identifier composed of <split ID, partition path, commit ID> so it can identify the restart case where split ID changes for a file.
| @Override | ||
| void onSplitsAddedBack(List<HoodieSourceSplit> splits) { | ||
| if (lagMetrics != null) { | ||
| lagMetrics.addSplits(HoodieSourceSplitLagInfo.ofSplits(splits)); |
There was a problem hiding this comment.
If a reader finishes a split after the last checkpoint and then fails, Flink can return that split for replay after its metrics entry has been removed. ofSplits recreates the entry with an unknown completion time and zero records and bytes. Those values persist for the entire replay, so a stalled reader can report zero lag. Could we resolve lag info for newly reinserted splits here, as we do for restored splits?
There was a problem hiding this comment.
Great point, changed! Reinserted splits now are re-added into metrics.
| if (throwable != null) { | ||
| log.warn("Failed to get the undiscovered commits after {}", offset, throwable); | ||
| } else if (undiscoveredCommits != null) { | ||
| lagMetrics.setUndiscoveredCommits(undiscoveredCommits); |
There was a problem hiding this comment.
Two callAsync refreshes can finish in reverse order. If discovery advances from A to B while the refresh for A is still running, its late callback can overwrite B’s result and make consumed commits appear in undiscoveredCommits again. Could we tag each refresh with a generation and apply only the latest one? A test that completes the callbacks in reverse order would cover this, including paused polls that share an offset.
There was a problem hiding this comment.
Great point, changed.
| if (split.getInstantRange().isPresent() && split.getInstantRange().get() instanceof InstantRange.ExactMatchRange) { | ||
| return ((InstantRange.ExactMatchRange) split.getInstantRange().get()).getInstants(); | ||
| } | ||
| return Collections.singletonList(split.getLatestCommit()); |
There was a problem hiding this comment.
A copy-on-write CDC split carries its commit instants in HoodieCdcSourceSplit.getChanges() and has an empty instant range. I reproduced a split containing changes from two commits being credited only to the newer one here. This understates inFlightCommits and makes readLagSeconds miss the older pending commit. Could we use the distinct change instants for CDC splits?
| .filter(instant -> instantTimes.contains(instant.requestedTime())) | ||
| .forEach(instant -> commits.put(instant.requestedTime(), Pair.of(instant, activeTimeline))); | ||
| instantTimes.stream().filter(instantTime -> !commits.containsKey(instantTime)).min(String::compareTo).ifPresent(oldest -> { | ||
| HoodieTimeline archivedTimeline = client.getArchivedTimeline(oldest, false).getCommitsTimeline().filterCompletedInstants(); |
There was a problem hiding this comment.
On an initial read.start-commit=earliest snapshot, a single old file can take this path just to resolve its completion time. The V2 archived timeline eagerly loads commit metadata from oldest onward, so the JobManager can load years of metadata for that one file. Could snapshot splits use the completion-time query view and reserve archived write-stat reads for incremental splits that need them?
There was a problem hiding this comment.
Great point, changed
| scanContext.isSkipInsertOverwrite()); | ||
| return timeline.getInstantsAsStream() | ||
| .map(HoodieInstant::getCompletionTime) | ||
| .sorted() |
There was a problem hiding this comment.
setUndiscoveredCommits uses only the number of completion times and the earliest one. Could we return those two values from a single pass? That removes the list allocation and the O(n log n) sort on every backlog refresh.
…etrics - Resolve commit completion times to Instant using the table's timeline timezone inside DefaultHoodieSplitDiscover, removing getTimelineZone() and FlinkStreamReadLagMetrics.timelineZone - Key lag tracking and SplitRequestEvent completions by a stable split key (splitId, partitionPath, latestCommit) so restored and newly discovered splits stay distinct across JobManager restarts without changing checkpoint serializers - Re-resolve lag info asynchronously in HoodieContinuousSplitEnumerator.onSplitsAddedBack for newly reinserted splits after reader rollback - Tag refreshUndiscoveredCommits async callbacks with a generation counter and ignore stale completions - Extract distinct change instants for HoodieCdcSourceSplit in HoodieSourceSplitLagInfo - Use CompletionTimeQueryView for non-exact-match splits (snapshot/CDC) and reserve archived timeline loads for missing exact-match incremental commits - Return undiscovered commit count and earliest completion time in a single pass via HoodieContinuousSplitDiscover.UndiscoveredCommits
| (undiscoveredCommits, throwable) -> { | ||
| if (throwable != null) { | ||
| log.warn("Failed to get the undiscovered commits after {}", offset, throwable); | ||
| } else if (undiscoveredCommits != null && generation == undiscoveredCommitsGeneration) { |
There was a problem hiding this comment.
The generation check prevents a late result from overwriting a newer one, but it can also discard every successful refresh. I held discovery paused at one offset and completed each refresh immediately after the next poll started. Eight refreshes returned a positive count and undiscoveredCommits stayed at 0. Could we coalesce outstanding refreshes for the same offset, or accept the newest completed generation for the current offset? The existing reverse-order test would still need to pass.
| LocalDateTime dateTime = LocalDateTime.parse( | ||
| HoodieInstantTimeGenerator.fixInstantTimeCompatibility(completionTime), | ||
| HoodieInstantTimeGenerator.MILLIS_INSTANT_TIME_FORMATTER); | ||
| return dateTime.atZone(timelineZone).toInstant(); |
There was a problem hiding this comment.
Legacy active instants use the commit file’s modification time. Both InstantGeneratorV1 and the legacy-filename path in InstantGeneratorV2 format that time in the reader JVM’s zone. On a UTC table with the JobManager in Asia/Shanghai, I reproduced a 12:00Z modification time parsing as 20:00Z here, which gives readLagSeconds = -28800 at completion. Could we preserve the timestamp’s origin when converting it, including when selecting the oldest undiscovered instant? A legacy and a modern filename in the same test would cover both paths.
| List<String> readCommits = new ArrayList<>(); | ||
| long records = 0L; | ||
| long bytes = 0L; | ||
| if (isExactMatch(split)) { |
There was a problem hiding this comment.
The CDC change-instant fix gives the right commit count, but the record and byte accumulators still run only for exact-match splits. On a COW table I discovered four incremental BASE_FILE_INSERT CDC splits. The commit recorded 8 inserts and 1,738,429 bytes, while the resolved splits contributed 0 to both pendingRecords and pendingBytes. Could we use the file-group write stats for this case? The existing CDC test checks the commit list and completion time, so asserting the estimates for a pure insert would catch this.
| Map<Instant, Integer> completionTimeCounts = new HashMap<>(); | ||
| lagInfos.forEach((splitKey, lagInfo) -> { | ||
| if (pendingSplits.putIfAbsent(splitKey, lagInfo) == null) { | ||
| addedKeys.add(splitKey); |
There was a problem hiding this comment.
Small performance point: addedKeys collects every new split on the coordinator thread, but only onSplitsAddedBack consumes the returned keys. Ordinary discovery and checkpoint restore discard the set. Could we collect those keys only for the add-back path? That saves a temporary hash entry per split in the largest batches, before they are published to the assigner.
Track unfinished splits and their oldest known completion time. Resolve file-group writes only for multi-commit ranges and initialize restored metrics from the split provider at startup.
|
@skywalker0618, the copy-on-write example in #20531 explains why I narrowed this PR to The record and byte estimates add a different question and more metadata accounting. For example, two commits can update the same row, so summing their write stats can count that row twice. With this change, a single-commit split needs only a timestamp. We still consult write metadata for multi-commit ranges so an older commit stops contributing to lag as soon as its own file groups finish. Restore also uses the splits already in the provider when the enumerator starts. This leaves the commit-count gauges for a follow-up to #20531, especially |
@danny0405 Sounds great, thanks for fixing those! The PR is much cleaner now. After you merge this PR I can work on pendingCommits, I think it's worthwhile to show how many commits are not finished yet. How do you think? |
can you retry your CI to make it pass |
@danny0405 Ok it passes now! |
Describe the issue this Pull Request addresses
Part of #20531. A Source V2 streaming reader can discover a copy-on-write commit in minutes and spend hours emitting its records. Operators need to see how old the oldest unfinished work is and how many discovered splits still have records to emit.
Summary and Changelog
The continuous split enumerator registers two gauges under the table metric group for append-only and copy-on-write reads.
readLagSecondspendingSplitsDiscovery, restore and splits returned by a reader use the same tracking path. On startup the enumerator reads the splits that the source restored into the split provider. A stable tracking key distinguishes splits when a split number is reused after recovery.
Impact
Operators can observe reader backlog with the existing source and checkpoint formats. A single-commit split needs only its commit completion time. For a multi-commit exact-match split, the enumerator uses write metadata to identify which commits wrote its file group. This lets the lag drop as soon as the last split for an older commit finishes. Timestamp lookups run asynchronously so split publication can proceed.
Risk Level
low
A pending split counts immediately. Its contribution to read lag becomes visible when its timestamp lookup succeeds, so lag can temporarily read zero while splits are pending. After recovery, the enumerator can count reader-owned splits only if a reader returns them.
Verification on Flink 2.2 covered 83 tests across the metrics, source, enumerator, reader, discovery and split-request suites, including out-of-order callbacks, checkpoint recovery and multi-commit file groups. Checkstyle passed.
Documentation Update
The Flink monitoring documentation should describe both gauges and when lag becomes visible after recovery. The website update is pending.
Contributor's checklist