Repository navigation
[feat](stream) Collect changelog load rows in both storage modes - #69896
Conversation
|
Thank you for your contribution to Apache Doris. Please clearly describe your PR:
|
|
run buildall |
|
/review |
There was a problem hiding this comment.
Reviewed the complete four-file diff at 1cb6c79. Two P2 findings need correction: normal grouped changelog loads never report their attached changelog rowsets, and the new Java import violates the mandatory FE Checkstyle gate. Both are posted inline. There were no existing inline findings to carry forward and no additional user-provided focus points.
The review converged in 2 rounds: all three independent reviewers returned NO_NEW_VALUABLE_FINDINGS in the latest round, every changed file and assigned mechanism was covered, and all candidates and initial risks were verified, deduplicated or dismissed with source evidence.
Critical checkpoint conclusions:
- Goal and proof: separate base/changelog load counters are the intended behavior. The FE accumulator works for directly supplied values, but the BE loop sees base transaction rowsets while the changelog resides in attach_changelog; therefore ordinary loads do not populate the new counter. The added test bypasses this producer and does not prove the complete behavior.
- Scope and reuse: the four-file change is focused and reuses the existing tablet delta report and statistics serialization.
- Concurrency and locking: the publish parent owns the report map and joins its workers; existing changelog-first tablet locks are unchanged. All accesses and lazy initialization of the new map take the TableStatsMeta monitor. No added IO, journal waits, or lock-order cycle was found. A repair must read the final attachment count after workers finish because MoW publication can append changelog rows.
- Lifecycle and initialization: TabletTxnInfo retains attachment ownership through publication and recovery. The new map belongs to the statistics record, survives ordinary analyze updates, and is discarded with that record. No new static initialization or reference cycle is introduced.
- Configuration: no configuration is added.
- Compatibility: the optional Gson field is initialized lazily when absent, following existing concurrent-map serialization patterns. The existing report field is reused; no new protocol shape or toolchain/library dependency is introduced. Older producers do not supply changelog history.
- Thrift/protobuf IDs: no definition is changed, so no field-ID or required-field compatibility change applies.
- Parallel paths: normal, retry, asynchronous and cloud reporting paths were traced. Existing replica averaging/missing-report approximations remain. Cloud/legacy events still report base table scalars and do not populate the new index counter; this is a feature limitation, with no separate current consumer failure established.
- Conditional logic: comments explain why changelog rows differ from base rows, but the BE condition tests the wrong transaction representation (first inline finding). Zero additions intentionally leave the map unchanged. Missing-tablet/checkpoint concerns were checked against actual index rebuild and replay registration, without another reachable regression.
- Test coverage: the new deterministic JUnit case covers additive map behavior, zero additions and base isolation. It adds no publish/report integration, routing, replay or serialization coverage. Existing attachment recovery tests were inspected. No builds, tests, Checkstyle execution, benchmarks or runtime validation were performed under the static-only contract.
- Expected results: the added direct-map assertions match their inputs; no regression output artifact is changed.
- Observability: existing tablet/transaction identifiers and report logging remain. No separate logging or metrics defect was substantiated.
- Persistence and failover: transaction delta maps already persist with VISIBLE state and use the same statistics application on replay; image/CREATE/TRUNCATE paths register changelog tablet metadata. The new map participates in statistics JSON/image persistence. No additional replay divergence was verified.
- Writes and atomicity: the patch changes statistics reporting and estimates, without changing rowset visibility, version selection, delete bitmap publication or committed data writes. No new data-loss or memory-safety issue was identified by source inspection.
- FE/BE passing: the existing callback and aggregation chain accepts tablet-keyed counts, but the attached changelog count is missing at its producer (first finding). No other new variable needs propagation.
- Performance: the new FE classification adds one inverted-index lookup per reported tablet on changelog tables and bounded synchronized map work. No additional current-head performance regression was substantiated.
- Other issues: the import-order finding is supported by error-severity CustomImportOrder, the Maven validate binding and the FE Checkstyle workflow. A suspected stream-wrapper null dereference was dismissed because the sole current consumer cannot reach that fallback with the wrapper's empty local partition map.
Coverage limits: this is a static review. The lifetime accumulator alone is not an exact retained-row or per-stream unconsumed-row count after TTL, statistics recreation or upgrade. The stream-estimation consumer described in dependent PR #69850 is outside this diff, so no end-to-end stream-plan improvement or failure is claimed here. There are no unresolved candidates or unread assigned source paths.
Review converged after 2 round(s).
| auto tablet_id = rowset_meta_ptr->tablet_id(); | ||
| if (_publish_version_req.base_tablet_ids.contains(tablet_id)) { | ||
| if (_publish_version_req.base_tablet_ids.contains(tablet_id) | ||
| || tablet->is_changelog_tablet()) { |
There was a problem hiding this comment.
[P2] Report the attached changelog rowset for grouped loads
Normal changelog loads commit only the base rowset into TxnManager: GroupRowsetBuilder::commit_txn stores the companion in txn_info_it->second->attach_changelog.rowset, and ChangelogRowsetBuilder::commit_txn only marks it committed. get_txn_related_tablets therefore exposes the base tablet to this loop, so the new is_changelog_tablet() branch never inserts the companion tablet ID or its rows. Those loads leave the new FE changelog counter at zero. Report the attached rowset under its own tablet ID after publish workers finish (MoW publication can append changelog segments), and cover the emitted report map in a publish-path test; the added direct-accumulator test cannot detect this omission.
There was a problem hiding this comment.
Fixed in 5bb280e. You are right that the changelog rowset is attached to the base tablet's transaction info rather than committed as a tablet of its own, so the is_changelog_tablet() branch never saw it; it is gone now. The publish path collects the attached rowset of each base tablet and reports it under its own tablet id after token->wait(), so a rowset that a merge-on-write publication extends with changelog segments is counted with its final row count.
| import org.apache.doris.catalog.ScalarType; | ||
| import org.apache.doris.catalog.Table; | ||
| import org.apache.doris.catalog.TableIf; | ||
| import org.apache.doris.catalog.TabletMeta; |
There was a problem hiding this comment.
[P2] Place TabletMeta after Tablet to pass FE Checkstyle
The new import precedes Tablet, but fe/check/checkstyle/checkstyle.xml enables alphabetical CustomImportOrder at error severity. fe/pom.xml binds the failing check to validate, and the FE Checkstyle workflow also runs it, with no applicable suppression. Move TabletMeta below Tablet so the required validation gate accepts this change.
There was a problem hiding this comment.
Fixed in 5bb280e: TabletMeta now follows Tablet in the import block.
1cb6c79 to
5bb280e
Compare
|
run buildall |
1 similar comment
|
run buildall |
|
/review |
There was a problem hiding this comment.
Reviewed the complete four-file diff at exact PR head 5bb280e against base 374d87d. The intended goal is to carry the rows written to the attached changelog index into FE statistics so changelog scans can use a useful row estimate. The accumulator and its direct unit test cover the storage side, but two end-to-end paths still lose that information.
Critical checkpoint conclusions:
- Goal and proof: the FE accumulator correctly keeps changelog rows separate from base rows for a direct tablet-record event, but a partial BE publish retry drops already-published tablets from the final report, and cloud commits never populate the accumulator. The added unit test does not exercise either producer path.
- Scope and reuse: the changes are focused and reuse the existing tablet delta report, transaction publication, and TableStatsMeta persistence mechanisms.
- Concurrency and locking: BE publication tasks run concurrently and are joined by token->wait() before the rowset count is read; existing changelog-first tablet lock order is unchanged. TableStatsMeta additions and reads are synchronized. The retry lifecycle still loses a successful tablet's report.
- Lifecycle: TxnManager removes a successful tablet's txn entry during publish. The worker clears its delta map before retrying, so a later successful retry cannot rediscover that tablet's attached changelog rowset.
- Configuration: no configuration is added.
- Compatibility: the new Gson field is optional and lazily initialized, with no thrift/protobuf or wire-shape change.
- Parallel paths: local BE tablet-record reporting is updated, but the cloud commit path still reports only table-level base-index rows. Asynchronous tablet-stat refresh may eventually fill the gap, but the immediate post-load estimate remains zero.
- Conditional logic and data correctness: changelog rows are intentionally excluded from base-table updatedRows and partition base-index accounting. The two findings are statistics undercounting issues; rowset visibility and delete-bitmap publication are otherwise unchanged.
- Persistence and failover: the existing transaction delta map is persisted with visible transaction state and replayed through AnalysisManager; the new per-index map participates in TableStatsMeta JSON persistence. No separate replay or locking defect was verified.
- Testing and observability: the direct JUnit test covers additive accumulation, zero additions, and base-index isolation. No publish-path, retry, cloud, replay, or serialization integration test was added. Under the static-only contract, no build, test, Checkstyle, benchmark, or runtime validation was run. Existing identifiers and report logging remain sufficient for these paths.
- Performance: the new local classification adds one inverted-index lookup per reported tablet and bounded synchronized map work; no additional current-head performance regression was substantiated.
Existing inline threads 4422920699 and 4422920705 were verified as fixed on this head and are not reposted. There is no additional user-provided focus.
The review reached the round limit after the required final sweep. All changed files and main producer/consumer paths were statically covered and the two candidates below were independently verified, but the latest delegated sweeps were interrupted by the temporary model-capacity error, so the contract's all-subagent NO_NEW_VALUABLE_FINDINGS convergence condition was not evidenced.
Review did not converge after 3 rounds. This automated review cannot pass the review check.
The final static sweep covered all four changed files and verified both findings, but the required latest-round delegated NO_NEW_VALUABLE_FINDINGS evidence was unavailable because both round-2 child sweeps hit the temporary model-capacity error. No unresolved code candidate remains; convergence is false solely because the delegated convergence evidence could not be obtained before the three-round cap.
| // derive them from the rows it loaded into the base tablets -- an update writes change | ||
| // rows without adding a base row, and a delete adds none to the base but at least one | ||
| // to the changelog -- and it keeps the count to estimate how many rows a read of the | ||
| // changelog returns. |
There was a problem hiding this comment.
[P2] Preserve attached changelog rows across publish retries
If one tablet publishes successfully and a sibling tablet fails, this vector is local to the failed execute attempt. TxnManager::publish_txn removes the successful tablet's txn info, PublishVersionWorkerPool clears table_id_to_tablet_id_to_num_delta_rows before retrying, and PublishVersionDaemon discards reports from tasks with any error tablet. The final successful retry therefore contains only the previously failed tablet, so the already-published tablet's changelog rows are never added to TableStatsMeta. Preserve successful tablets' changelog counts across retries or report them from the final aggregation so a partial publish cannot permanently undercount the changelog index.
There was a problem hiding this comment.
The retry path here has the same guarantee as the base index delta rows, and I kept it that way rather than diverging:
- Within one
execute()the retry loop is inside the function and the collected changelog rowsets are declared before it, so a retry of the same attempt keeps the rowset of a tablet that already published (the rowset object stays valid, and its row count is the final one). - Across attempts the report is discarded as a whole:
PublishVersionDaemon.calculateTaskUpdateRowsskips a task that reports any error tablet, for the base delta rows as well as for these. So a tablet that published in a failed attempt contributes its delta with the next report, which is the periodic tablet report and includes the changelog index. That is the existing behaviour of the base index counter, and changing it means aggregating per-tablet reports across attempts on the frontend, which I would rather do for both counters in one change than only for the changelog one.
There was a problem hiding this comment.
Updated in 9fb10c4. The FE now applies changelog deltas directly to the partition's MaterializedIndex row-count estimate; the TableStatsMeta lifetime accumulator is gone. A later tablet-stat report refreshes the physical count, rather than repairing a cumulative counter. My earlier reply conflated those two mechanisms.
Cross-attempt publish reporting can still omit a tablet that succeeded in an earlier failed attempt, just as for base deltas. This remains a documented limitation; preserving deltas across attempts should cover both paths in a follow-up.
| @@ -1525,6 +1535,7 @@ public void replayUpdateRowsRecord(UpdateRowsEvent event) { | |||
| + "rows for all replica {}, tablets count {}", | |||
| olapTable.getName(), tableUpdateRows, replicaNum, rowsForAllReplica, tabletRows.size()); | |||
There was a problem hiding this comment.
[P2] Feed cloud changelog writes into the per-index counter
The new counter is updated only for local tabletRecords. Cloud commits call updateUpdatedRows(updatedRows, ...) with a table-level value from meta-service calc_table_stats, and that helper sums only base_tablet_ids, so attached changelog rowsets are never added. Immediately after a cloud load, before the asynchronous tablet-stat refresh reports the changelog index, getRowCountWithDeltaRows therefore returns zero for a changelog scan even though rows are visible. Extend the cloud commit/statistics path to report changelog rows per index (or carry them in the existing response) before relying on this accumulator.
There was a problem hiding this comment.
Agreed, and it is recorded as a known limitation in the description: a cloud commit reports rows per table from the meta-service calc_table_stats, which sums only base_tablet_ids, so there is no per-index value to route. Until that path carries the changelog rows, a cloud stream read keeps falling back to the row count of the table, which is the behaviour before this PR — safe, just loose. Feeding the cloud counter needs the meta-service side to sum the attached changelog rowsets as well; I would keep it in a follow-up rather than growing this one into the cloud txn path.
There was a problem hiding this comment.
The cloud limitation remains explicit in the updated description. Cloud commits do not provide per-index changelog deltas, so this PR only updates shared-nothing publish reporting. Cloud changelog counts still come from asynchronous tablet statistics.
In 9fb10c4 the lifetime accumulator and its zero-valued fallback were removed; local deltas now update the partition index read by P/Q. My earlier description of the cloud fallback as safe was too strong: stale changelog/base counts do not guarantee an upper bound. Extending the cloud commit response remains a separate change.
|
run buildall |
|
/review |
5bb280e to
fecb190
Compare
|
run buildall |
|
/review |
TPC-H: Total hot run time: 28398 ms |
There was a problem hiding this comment.
Reviewed the complete four-file diff at exact PR head fecb190 against base 374d87d.
The PR's goal is to carry rows written to attached changelog rowsets into the FE per-index statistics accumulator. The grouped-load producer fix is present, and the direct accumulator test is correct, but three lifecycle paths still make the new count incorrect:
TableStatsMeta(OlapTable)creates a zero changelog baseline. After DROP STATS (or another record recreation), existing changelog rowsets are still readable while the physical changelog index count is unknown.StatsCalculatorthen falls back togetRowCountWithDeltaRows, whose new branch returns only post-creationindexUpdatedRows, underestimating the visible changelog until a later tablet report.- Partial TRUNCATE PARTITION replaces changelog tablets but retains the table statistics record. The asynchronous
dropStatspath invalidates column/partition statistics without clearingindexUpdatedRows, so the branch continues returning rows from the removed partition. - A load whose partition is force-dropped before visibility can still carry old tablet delta rows.
DatabaseTransactionMgrremoves the missing partition from commit info, but still forwards the transaction delta map; after the old tablet metadata is removed,isChangelogTabletreturns false and this code routes those changelog rows into the baseupdatedRowscounter permanently.
Critical checkpoint conclusions:
- Goal and proof: the normal attached-rowset path now reports the final row count after
token->wait(), and FE routes direct tablet records by index. The new unit test covers additive accumulation and base-index isolation, but it does not cover record recreation, partition replacement, missing metadata, or the publish/report integration. - Scope and reuse: the four-file change is focused and reuses the existing tablet delta map and
TableStatsMetaJSON persistence. The three findings above are in the new counter's lifecycle and consumer boundary. - Concurrency and locking: BE publication workers are joined before the attached rowset metadata is read; existing changelog-first tablet lock order is unchanged. The FE counter methods synchronize on
TableStatsMeta, and no new deadlock or blocking I/O was found. Existing publish-retry aggregation remains a known P2 thread and is not duplicated here. - Lifecycle and initialization: the new accumulator has no partial-truncate reset and no pre-existing-row baseline, and the missing-metadata branch silently chooses the wrong index. No static initialization or ownership cycle was introduced.
- Configuration, Thrift/protobuf, ABI, and protocol compatibility: no configuration, generated definition, field ID, wire shape, or toolchain change is present.
- Parallel paths: local tablet-record reporting is updated. Cloud table-level reporting still omits changelog rows, and publish retries can lose successful siblings; both are already reported by existing inline P2 comments 4424460818 and 4424460813 and are not reposted. The grouped-load omission and import-order comments are fixed on this head.
- Error handling and data correctness: rowset visibility, version selection, delete bitmaps, and committed data writes are unchanged. The new failures affect statistics/cardinality accounting; unknown tablet metadata must not be silently treated as a base tablet.
- Persistence/failover: the optional Gson field participates in normal serialization, but stale or zero lifecycle state is what causes the findings above. Transaction delta maps are still applied through the existing visible/replay path.
- Testing and observability: only the added deterministic JUnit behavior is represented in the diff; no publish-path, replay, truncate, serialization, or cloud integration test was added. Under the static-only contract, I did not run builds, tests, Checkstyle, benchmarks, or runtime validation. Existing transaction/tablet identifiers and logging are sufficient for the reviewed paths.
- Performance: the new classification performs one inverted-index lookup per reported tablet and bounded synchronized map work; no separate current-head performance regression was substantiated.
- User focus: no additional user-provided focus points were supplied.
The review converged after 2 rounds. All three assigned round-2 rechecks returned NO_NEW_VALUABLE_FINDINGS; all changed files and assigned mechanisms were covered, and every candidate was verified, deduplicated, or dismissed. The review remains static-only, so runtime ordering of asynchronous reports is a stated coverage limit. Existing P2 threads 4424460813 and 4424460818 remain applicable to this head but are not duplicated. No existing P0/P1 inline finding applies, so existing_blocking_comment_ids is empty.
Review converged after 2 round(s).
| public synchronized long getRowCountWithDeltaRows(OlapTable table, long indexId) { | ||
| if (isChangelogIndex(table, indexId)) { | ||
| // The changelog index has no collected row count: the rows a load wrote to it are the | ||
| // only count this record keeps, and they are added rather than taken as a lower bound |
There was a problem hiding this comment.
[P2] Preserve the existing changelog baseline when recreating table statistics. After DROP STATS (or another removal/recreation of TableStatsMeta), new TableStatsMeta(OlapTable) initializes no changelog row count. While the changelog tablet's FE row count is still unknown, StatsCalculator falls back to this branch, which returns only indexUpdatedRows from loads after the record was created. Existing changelog rowsets therefore remain visible but are estimated as zero/partial until a separate tablet report supplies a count. Preserve an existing changelog baseline or keep the fallback unknown instead of converting a missing baseline to zero.
There was a problem hiding this comment.
Fixed in 9fb10c4 by removing the TableStatsMeta changelog accumulator and its row-count fallback. Published deltas now update the partition's changelog MaterializedIndex directly, preserving its existing row-count estimate independently of DROP STATS or statistics-record recreation. An unavailable index count starts from the reported load delta as a best-effort estimate; it is not claimed to contain unknown historical rows.
The new AnalysisManagerTest case verifies that removing/recreating TableStatsMeta leaves the public changelog row-count lookup unchanged.
| return; | ||
| } | ||
| indexUpdatedRows().merge(indexId, rows, Long::sum); | ||
| } |
There was a problem hiding this comment.
[P2] Reset changelog deltas when a partition is truncated. Partial TRUNCATE PARTITION replaces the partition and its changelog tablets but keeps the table's TableStatsMeta; the subsequent dropStats invalidates column/partition statistics without clearing indexUpdatedRows. A later changelog row-count fallback therefore returns rows from the deleted partition as if they were still present. Clear or partition-scope this accumulator as part of the truncate/replay lifecycle so the estimate cannot retain removed rows.
There was a problem hiding this comment.
Fixed in 9fb10c4. Changelog load deltas now update each partition's own MaterializedIndex, rather than an index-wide lifetime accumulator in TableStatsMeta. Partial TRUNCATE replaces the affected partition/index and therefore discards its old estimate while retaining the other partitions' counts.
The new test replaces one partition, verifies that the old rows disappear from the public row-count lookups, and checks that late reports for the old partition do not repopulate the replacement.
| for (Entry<Long, Long> entry : tabletRows.entrySet()) { | ||
| if (changelogIndexId > 0 && isChangelogTablet(entry.getKey(), changelogIndexId)) { | ||
| // The change rows of the load, which are neither the rows loaded into the | ||
| // base index nor a lower bound of the table's rows: see TableStatsMeta. |
There was a problem hiding this comment.
[P2] Do not route unknown tablet IDs into the base counter. When a load's partition is force-dropped before its transaction becomes visible, DatabaseTransactionMgr removes the missing partition from the commit info but still forwards the transaction's tablet delta map. The old changelog tablet metadata has already been removed, so isChangelogTablet returns false and this branch adds its rows to updatedRows. That permanently inflates the base estimate and leaves the changelog counter missing. Carry the index identity with the event or discard/handle missing tablet metadata explicitly instead of treating it as a base tablet.
There was a problem hiding this comment.
Fixed in 9fb10c4. For changelog tables, tablet metadata and the owning partition are resolved before classifying any reported tablet. Missing metadata or a removed partition causes that entry to be skipped, rather than falling through into base updatedRows.
AnalysisManagerTest covers both deleted tablet metadata and a replaced partition whose old tablet metadata is still present, and verifies that neither case inflates the base counter.
TPC-DS: Total hot run time: 151672 ms |
ClickBench: Total hot run time: 24.36 s |
There was a problem hiding this comment.
Static review of PR 69896 at head fecb190 converged after three bounded rounds. Four new P2 findings are inline: the synthetic changelog wrapper returns a zero row estimate before the new TableStatsMeta fallback; user-injected base stats bypass the changelog accumulator; TTL compaction leaves the persisted accumulator stale; and per-partition replica allocations are divided by the table default. Existing review context was independently revalidated: stale/unknown tablet routing (r4425241009), partial-truncate reset (r4425241002), recreated-statistics baseline (r4425240994), and the cloud limitation (r4424460818) still apply and were not reposted; the retry concern (r4424460813) is shared pre-existing base-delta behavior; the checkstyle import issue (r4422920705) is fixed. No additional user focus was supplied. BE publication, FE routing/locking, lifecycle, serialization, and test coverage were inspected; no new issue was found beyond the inline set. This was a static-only review: builds and tests were not executed. All anchors were verified against the authoritative diff, and all final reviewers returned NO_NEW_VALUABLE_FINDINGS.
Review converged after 3 round(s).
| if (isChangelogIndex(table, indexId)) { | ||
| // The changelog index has no collected row count: the rows a load wrote to it are the | ||
| // only count this record keeps, and they are added rather than taken as a lower bound | ||
| // of the table's rows. |
There was a problem hiding this comment.
[P2] Route changelog scans through the new row-count fallback. StatsCalculator calls TableStatsMeta.getRowCountWithDeltaRows only when getRowCountForIndex(..., true) returns -1, but OlapChangelogTableWrapper inherits OlapTable.getRowCountForIndex without overriding it and its inherited idToPartition is empty, so that method returns 0. Every real changelog scan therefore bypasses this branch and is planned as an empty table despite indexUpdatedRows. Delegate the lookup to the origin table or override the wrapper so the accumulated changelog count is reachable.
There was a problem hiding this comment.
The wrapper lookup issue belongs to the consumer change in #69850, which adds row-count delegation and stream-specific estimates. It is not fixed by this PR alone.
In 9fb10c4 this PR no longer introduces a TableStatsMeta fallback: published deltas update the partition changelog MaterializedIndex directly, so the existing partition-index lookup used by P/Q reads the updated estimate. The new test exercises both public partition and whole-index row-count lookups. The wrapper work remains scoped to #69850.
| * while this call runs are not part of the snapshot, whichever state reads them accumulates them in | ||
| * {@link #updatedRows} and reports them as delta rows. | ||
| */ | ||
| public synchronized long getRowCountWithDeltaRows(OlapTable table, long indexId) { |
There was a problem hiding this comment.
[P2] Keep the changelog accumulator reachable with injected stats. When userInjected is true, StatsCalculator returns getRowCount(selectedIndexId) without the fallback. ALTER STATS normally injects only the base index, so a changelog scan receives UNKNOWN and ignores the rows accumulated by this new field. Apply the changelog branch before the userInjected shortcut or otherwise supply a changelog-index value.
There was a problem hiding this comment.
The StatsCalculator shortcut for injected statistics is a consumer-side issue to address with explicit wrapper-estimate priority in #69850; this PR does not change that shortcut.
In 9fb10c4 the separate TableStatsMeta accumulator was removed. Changelog deltas now update the partition MaterializedIndex row count, which the P/Q metadata lookup reads independently of injected base statistics. This supplies the source count, while wrapper estimate selection remains in the consumer PR.
| */ | ||
| public synchronized void addIndexUpdatedRows(long indexId, long rows) { | ||
| if (rows <= 0) { | ||
| return; |
There was a problem hiding this comment.
[P2] Account for changelog TTL expiration in this accumulator. Each load is merged permanently into indexUpdatedRows, but BE changelog TTL compaction removes expired rowsets and no FE path subtracts or invalidates those rows. During the interval when the changelog index row count is still unknown, getRowCountWithDeltaRows reports expired rows as readable, overestimating the scan. Invalidate this fallback on TTL-driven removal or tie it to a current reported baseline.
There was a problem hiding this comment.
Fixed in 9fb10c4 by removing the lifetime accumulator. Loads now adjust the partition's changelog MaterializedIndex estimate, and the existing periodic tablet-stat path replaces that estimate with the retained row count, including TTL removal. The estimate can still be stale until a fresh report arrives; it no longer permanently accumulates expired rows in a separate persisted map.
The new test replaces the estimate with a lower reported retained count and verifies that the next load is added to that refreshed baseline.
| @@ -1525,6 +1535,7 @@ public void replayUpdateRowsRecord(UpdateRowsEvent event) { | |||
| + "rows for all replica {}, tablets count {}", | |||
| olapTable.getName(), tableUpdateRows, replicaNum, rowsForAllReplica, tabletRows.size()); | |||
There was a problem hiding this comment.
[P2] Use the partition's replica allocation for changelog deltas. This code divides every changelog tablet's aggregate by the table default replica count, but MODIFY PARTITION allows a changelog partition to use a different allocation. With default 3 replicas and a one-replica partition, nine emitted rows are recorded as 3, so update/delete-only loads permanently undercount the changelog estimate. Divide per tablet/partition (or carry the producer cardinality) instead.
There was a problem hiding this comment.
Fixed in 9fb10c4. Each changelog tablet's aggregate delta is divided by its owning partition's replica allocation before updating that partition's index estimate. It is no longer divided by the table default.
The new test uses a table default of three replicas with one- and three-replica partitions: reported totals of 9 and 18 add 9 and 6 rows respectively, while changelog rows remain excluded from the base counter.
FE UT Coverage ReportIncrement line coverage |
### What problem does this PR solve? Issue Number: None Related PR: apache#69850, apache#69896 Problem Summary: Stream P/Q snapshots read partition index row counts, but changelog load deltas were stored in a separate lifetime counter in table statistics. That counter was not read by the partition lookup, lost its baseline after DROP STATS, and retained removed rows after TTL or partial TRUNCATE. Apply published changelog deltas directly to the partition index row-count estimate. Periodic tablet statistics replace the estimate, and partition replacement naturally discards it. Normalize each changelog tablet's rows using its partition replica allocation and ignore late reports for removed tablets or partitions so changelog rows cannot enter the base counter. Remove the unused lifetime counter and cover the partition lookup and statistics/partition lifecycle in AnalysisManagerTest. Cloud commits and partial publish retries remain subject to the existing asynchronous statistics limitations. A report that already includes the load may temporarily cause an overestimate until the next report. ### Release note Shared-nothing loads update partition changelog row-count estimates before periodic tablet statistics arrive. ### Check List (For Author) - Test: Unit Test - AnalysisManagerTest: 28 passed - TableStatsMetaTest: 15 passed - FE Checkstyle validation passed - Behavior changed: Yes, publish deltas update partition changelog estimates - Does this need documentation: No
|
run buildall |
|
/review |
There was a problem hiding this comment.
Reviewed exact head 9fb10c4c0e147d4b9b079b4e57961ab39d03bdaf. One new P2 finding is inline: unconditional companion rows change the semantics of a base-only report consumed by older FEs during supported BE-before-FE upgrades. No existing P0/P1 finding remains to carry forward.
The reviewed flow is grouped load -> attached changelog rowset -> publish workers/MoW append -> token wait -> tablet delta report -> transaction visibility/replay -> partition MaterializedIndex -> public row-count lookup.
Critical checkpoint conclusions:
- Goal and evidence: the same-head shared-nothing path supplies final changelog counts to partition estimates. The added FE test's assertions cover both public getters; full transport/P/Q integration is not tested here.
- Scope and reuse: the production change is focused and reuses existing reporting and partition index state.
- Concurrency and locking: master visibility and follower/checkpoint transaction replay hold table write locks, excluding TabletStatMgr's read-locked count replacement. The coordinator reads rowset counts after worker completion. No new lock order or heavy locked operation was found.
- Lifecycle/static initialization: shared ownership retains attached rowsets through reporting; DROP STATS preserves index counts and partition replacement discards the affected baseline. Checkpoint loading/replay rebuilds tablet metadata. No new static initializer, cycle or leak was found.
- Configuration: none added.
- Compatibility: existing storage fields remain usable, but reused report semantics are incompatible with older FE readers; see the new P2.
- Thrift/protobuf IDs: no definitions changed, so cross-branch field-ID comparison is not applicable.
- Parallel paths: cloud commits and async/cross-attempt publication still depend on later tablet statistics for omitted changelog deltas. Existing threads already cover cloud and retries; they are not reposted. Wrapper delegation and injected-stat priority remain consumer work discussed in #69850.
- Conditions: attachment-null, missing-tablet and removed-partition branches have concrete cases and nearby rationale; partition-specific replica allocation is used for changelog rows.
- Test coverage: inspected positive and negative FE assertions cover mixed one-/three-replica partitions, missing metadata, DROP STATS, baseline replacement and partial TRUNCATE with late reports. BE emitted-map/MoW integration, mixed-version and end-to-end consumer tests remain absent.
- Test results: no result artifacts changed. This was static inspection only: no builds, tests, benchmarks or runtime validation were executed.
- Observability: existing publish and delta-report logs provide transaction/tablet/count context; no additional critical gap was found.
- Transaction/persistence/failover: visible transaction state carries the delta map and replays through the same path; MaterializedIndex.rowCount already persists. No new journal record is required. Counts remain approximate across independent statistics samples and failover.
- Data writes/atomicity/crashes: rowset visibility, versions and delete-bitmap transitions are unchanged; the new state is an estimate. Known failed-attempt omissions and stale/double-counted baselines do not establish an exact count or upper bound.
- FE/BE propagation: same-head transport reaches the correct index and keeps changelog rows out of base/partition update counters; mixed-version propagation is the inline defect.
- Performance/memory: additional work is linear in reported tablets with one metadata lookup and a shared pointer per companion; no material new retention or performance defect was found.
- Further sweep: all three changed files, upstream/downstream paths, candidate dispositions and risk items were rechecked. No other verified new finding or unresolved static candidate remains.
Existing review context: attached-rowset reporting and import ordering are fixed. The revised partition-index design addresses the reported replica-allocation, missing-tablet, DROP STATS, TRUNCATE and lifetime-TTL accumulator issues. Retry/cloud omissions remain acknowledged limitations; wrapper/injected-stat concerns remain consumer follow-ups. All existing findings are P2, so existing_blocking_comment_ids is empty. There was no additional user-provided focus.
Static review converged in 2 rounds. All assigned reviewers completed the final pass without additional valuable findings. Coverage limits are the unexecuted integration/upgrade behavior and absent tests described above; all changed paths and static risk questions were covered.
Review converged after 2 round(s).
| } | ||
| for (const RowsetSharedPtr& changelog_rowset : attached_changelog_rowsets) { | ||
| const RowsetMetaSharedPtr& rowset_meta = changelog_rowset->rowset_meta(); | ||
| tablet_id_to_num_delta_rows.insert({rowset_meta->tablet_id(), rowset_meta->num_rows()}); |
There was a problem hiding this comment.
[P2] Negotiate changelog deltas before extending the base-only report
The supported rolling-upgrade order upgrades BE before FE. During that window, a pre-PR FE's AnalysisManager.replayUpdateRowsRecord sums every entry in this existing map into base updatedRows, without classifying the new changelog tablet IDs. An insert producing 10 base rows and 10 changelog rows on each of three replicas therefore records 60 / 3 = 20 base delta rows instead of 10, inflating the base statistics counter and any row-preserving estimate that uses its delta. The new FE classifier cannot protect the old master, and PublishVersionTask.toThrift() sends no capability indicating that the receiver understands companion rows. Gate this reporting on a negotiated capability, or carry changelog deltas in a separate optional field that old FEs ignore, and cover the old-reader/new-writer case.
There was a problem hiding this comment.
Changelog has not been officially released yet, and there are no changelog tablets in production. Therefore, the rolling-upgrade compatibility scenario described here does not arise. Compatibility between unreleased changelog implementations is outside the scope of this PR.
a266e6a to
6128e4b
Compare
|
run buildall |
|
/review |
There was a problem hiding this comment.
Static review of PR 69896 at exact head 6128e4b converged after two bounded rounds. Two new P2 findings are inline: retained-count reports can replace a changelog estimate with a stale baseline while suppressing the delivered version range, and an incomplete lazy commit omits ChangelogStatsPB with no later completion/retry response to restore it. Existing inline P2 threads were re-read and not duplicated; no existing P0/P1 finding remains to carry forward. The BE publish path, FE row-count/stat managers, cloud commit paths, protobuf field compatibility, tests, and regression additions were statically inspected. No builds or tests were executed under the static-only review contract. No additional user focus was supplied.
Review converged after 2 round(s).
| private transient long changelogRowCountReportVersion = -1; | ||
|
|
||
| public MaterializedIndex() { | ||
| this.state = IndexState.NORMAL; |
There was a problem hiding this comment.
[P2] Preserve pending changelog deltas when applying retained row reports. setReportedRowCount replaces the accumulated estimate but only removes ranges at or below version; it does not reapply pending ranges newer than that baseline. The local and cloud stat managers pass the current partition version even when the replica/RPC row count was fetched before a newer commit. A v4 commit can add 10 rows and record range v4, then a stale report with the pre-v4 count can set the index back to 0 and tag it as v4; the v4 response is suppressed by version <= changelogRowCountReportVersion/contains, so the 10 rows disappear until a later full report. Carry the report's actual snapshot version (or reject stale reports) and preserve/reapply deltas newer than the retained baseline.
There was a problem hiding this comment.
Fixed the stale-report overwrite in 6f1c4ce. Shared-nothing uses the BE report's version, and cloud reads the partition version in the same KV transaction as the tablet row count. FE keeps the applied deltas until a complete report covers them. That report can still lower the retained count after TTL cleanup.
The new FE unit test reproduced the overwrite before the fix (expected 10 rows, got 0) and passed afterward. All 107 focused FE tests and 7 Cloud ASAN tests passed.
|
|
||
| // Use the transaction's final rowset counters, not the tablet's retained-row statistics. A | ||
| // changelog tablet is logical in cloud mode, so its rows must not be divided by replicas. | ||
| static void fill_changelog_stats(const std::unordered_map<int64_t, TabletIndexPB>& tablet_indexes, |
There was a problem hiding this comment.
[P2] Preserve changelog stats across incomplete lazy commits. When the lazy visibility task fails, this guard omits changelog_stats; FE also skips the incomplete response. A later commit retry can wait for that task to succeed, but the next loop sees TXN_STATUS_VISIBLE and returns only txn_info through the existing early-return branch, so no response carries this transaction's changelog delta. The BE sends only the original response to reportCommitTxnResult, leaving the index undercounted until periodic tablet stats. Retain or regenerate the rowset metadata for the successful retry and test incomplete-then-successful retry so the delta is applied exactly once.
### Background Visible loads add changelog rows to the FE estimate before periodic tablet statistics arrive. Complete reports calibrate the retained row count, including decreases after TTL cleanup. ### What problem does this PR solve? Issue Number: None Related PR: apache#69896 (review follow-up) PR Type: Bugfix Problem Summary: A count collected before a load can overwrite that load's delta when its report is applied afterward. Require a complete report that covers the applied deltas before replacing the estimate. ### Details - **Frequency:** A periodic stats refresh overlaps a visible changelog load. - **Root cause:** FE paired earlier row counts with the partition version at aggregation time. - **Why existing tests missed it:** The reports used in tests already covered the applied deltas. - **Fix:** Keep the reported count and its coverage version together. Reject stale or partial replacements while a versioned estimate is available. - **Other paths and branches:** Shared-nothing uses the BE report version. Cloud reads the version with the row count for requested changelog tablets. - **Behavior change:** A sufficiently recent complete report still calibrates retained counts and retires covered deltas. ### Testing - Reproduced the defect with the stale-report test. It expected 10 rows and received 0 before the fix. - Passed 107 focused FE tests and seven Cloud ASAN tests covering legacy and versioned statistics reads. - Passed FE Checkstyle, C++ formatting, and Cloud clang-tidy. ### Release note Stale tablet statistics no longer erase changelog rows already counted from visible loads. ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: No - Pre-submission status: Ready for the targeted review fix.
|
run buildall |
|
/review |
There was a problem hiding this comment.
Static review of head 6f1c4ced0336e74d2b2441a61ea5eb5ba6bff9cf: no new actionable inline finding beyond existing threads and the PR's explicitly declared estimate limits. All 22 changed paths were reviewed. No committed-data loss or query-visibility regression was established.
The reviewed flow is SN grouped writer → final attached rowset after publish workers → tablet delta map → visibility callback → partition index; cloud final rowsets → immediate/lazy/subtransaction response → FE callback → version-deduplicated partition index. Periodic reports supply retained stock, including TTL reductions.
Critical checkpoint conclusions:
- Goal and evidence: immediate physical changelog counts are supplied in both storage modes, separately from base counters. Added unit and regression sources cover the main paths. Concurrent report/delta overlaps remain approximate as expressly documented in the PR; no stronger exact-accounting requirement was established.
- Scope and reuse: changes remain focused on estimate production/calibration; shared
RowCountReportandMaterializedIndexcentralize snapshot and deduplication handling. - Concurrency: table write locks serialize FE estimate mutations; replica rows/version are an immutable volatile pair. Existing SN visibility/replay locks are reentrant and table ordering is preserved. RPC waits precede aggregation locks. No new lock inversion found; individually paired reports do not make an entire index snapshot atomic; this remains part of the declared estimate overlap.
- Lifecycle and memory: attached rowset shared ownership lasts through worker completion; MoW historical segments are counted afterwards. Restore clears estimate/dedup state and delayed responses validate current tablet identity. No new thread, reference cycle or static-initialization dependency identified.
- Configuration: no production settings added; existing cloud polling modes now revalidate restored reports before backoff.
- Compatibility: added protobuf fields are optional/repeated. Missing versions cannot replace an already versioned changelog estimate. The old-FE/base-map expansion concern is already thread 4462665542, including the author's unreleased-feature scope response; it is not duplicated.
- Protocol IDs: complete touched definitions compared on HEAD, target master and branch-4.2/4.1/4.0/3.1. New tags TabletStatsPB.20, CommitTxnResponse.11 and GetTabletStatsRequest.4 are unused there; ChangelogStatsPB is new. No reused ID, enum change or new required field found. No new BE libc/linker/header ABI surface was introduced; binary validation was not performed.
- Parallel paths: SN publish and periodic aggregation, cloud immediate/lazy/subtransaction commits, both cloud request builders and response push paths were traced. Both FE aggregators can combine tablet snapshots at different versions; this was traced and dispositioned as acknowledged approximation rather than a new actionable defect. Untouched SN buckets create empty companion rowsets and advance normally.
- Conditions and errors: unknown/zero counts, incomplete responses, replacement identity, report freshness and bounded-range conditions have concrete explanations. Existing RPC status propagation is retained; no independent newly ignored failure found.
- Test coverage: inspected BE final-MoW publish/retry tests, MS ordinary/lazy/subtransaction/conflict/versioned-read tests, FE normalization/dedup/partial-report/lifecycle/polling/cap tests and both regression suites. The lazy conversion-before-version-bump and staggered-tablet/delayed-callback interleavings are not tested; their temporary count overlaps are part of the stated estimate limits. No build, test, benchmark or runtime validation was run under this static-only contract.
- Golden results: physical append/update/delete counts 3/5/6 are consistent with the source scenarios; stream expansion differs intentionally. Rollback preserves four rows, the next commit adds one, and consumption leaves retained stock unchanged. SHOW DATA projection uses the runner's sorting path. Generation provenance cannot be proved statically; no claim that outputs were regenerated here.
- Observability: existing transaction/table logs and statistics metrics remain available; no heavy new INFO logging or separate actionable observability regression found.
- Persistence and failover: SN changes replay through existing visible-transaction records. Cloud additive estimates and dedup state remain local and periodic reports revalidate recovered replicas; no new authoritative persisted transaction state is added. These are estimates rather than an exactly-once durable accounting system.
- Data writes and atomicity: authoritative publication/delete-bitmap transitions are unchanged. FE estimate mutation is serialized with replacement; incomplete lazy responses do not apply additive counts. Lazy tablet counters can precede the final partition-version bump; this can temporarily inflate an estimate, but does not expose those rows to data queries.
- Cross-process variables: successful cloud responses carry partition/index/version/tablet identity; both stats request constructors request coverage and the existing protobuf push preserves it. No new expression/planner transport path is involved.
- Performance: deduplication is capped at 1,024 ranges, consecutive versions coalesce, non-changelog commits avoid the extra aggregation, and changelog IDs no longer drive unnecessary base-partition scans. Added work is proportional to affected tablets. Broader aggregation locks contain no new RPC or journal wait.
- Further review: all 22 changed paths, existing threads and initial risk items were checked, including negative/retry paths and fixture cleanup. All candidates have explicit evidence-based dispositions; no new actionable inline is retained.
Existing-thread disposition: incomplete-lazy retry omission 4661836999 and cross-attempt SN omission 4424460813 still apply as already-reported P2 limitations. The earlier stale-report overwrite is addressed for truthful coherent snapshots by actual coverage versions and rejection below applied deltas; the remaining producer/aggregation overlap cases are described below as acknowledged limits. Attachment reporting, partition replica allocation, missing/replaced metadata, truncate/DROP STATS lifetime accumulation and import ordering are addressed. Wrapper/injected-stat consumer questions remain known context scoped to companion PR #69850. No existing P0/P1 finding was independently confirmed.
User focus: no additional focus was supplied. Coverage limits are static inspection and unverified runtime/output-generation evidence; the author's reported cloud row-content test failures were not independently reproduced. The delivery helper states the final convergence result separately.
Estimate-limit adjudication: the live PR description explicitly states that periodic reports and deltas may overlap or lag. Two reachable cases were investigated: (1) lazy conversion commits tablet counters before its final partition-version bump, so a baseline may already contain a subsequently delivered delta; (2) tablet snapshots on opposite sides of a commit may be summed at their minimum version, then overlap the delayed aggregate callback. Both can temporarily double-count rows. They require no new data visibility behavior, and a subsequent coherent complete report replaces the estimate; cloud mode 2 bypasses polling backoff for reports below the applied delta's required version. Without evidence of persistent error, an authoritative data effect, or an exact-accounting promise beyond the stated approximation, these are disclosed limitations rather than new inline defects. They are distinct from the already-reported incomplete-lazy and cross-attempt omissions, which were independently confirmed and are not duplicated.
Review converged after 3 round(s).
|
run vault_p0 |
|
PR approved by anyone and no changes requested. |
|
PR approved by at least one committer and no changes requested. |
### Background Stream planning estimates retained changelog rows using periodic tablet statistics and visible write notifications. Periodic statistics reflect row removal from TTL cleanup, while write notifications keep the estimate responsive between reports. Tablets are sampled independently, so a complete set of samples can lag the latest write. ### What problem does this PR solve? Issue Number: None Related PR: apache#69896 (introduced the report-version guard) PR Type: Bugfix Problem Summary: Continuous writes can keep every complete report one version behind, preventing FE from removing expired rows from its estimate. FE now uses each complete report with nondecreasing coverage to reset the estimate. In a five-round test with 100 retained rows and a 10-row write ahead of every report, the original estimate grows from 110 to 150. With the fix, it returns to 100 after each report. ### Details - **Change map:** FE catalog (89 additions, 69 deletions) updates report aggregation and limits immediate estimates. FE unit tests (131 additions, 44 deletions) exercise both storage modes, capacity, retries, and Cloud polling. - **Frequency:** Always in the deterministic case where each complete report lags a counted write. TTL cleanup makes the stale estimate diverge from retained rows. - **Root cause:** The tablet statistics managers and MaterializedIndex required periodic coverage to reach the latest applied write. A complete but lagging report could never correct the estimate during continuous writes. - **Why existing tests missed it:** The FE unit tests covered an eventual up-to-date report. The immediate-count and Cloud subtransaction suites pause periodic publication to check write estimates. Neither exercised repeated lagging reports. - **Fix:** Replace the estimate with the complete report sum and begin a new window with a 128-write-version budget per changelog index. Tablet counts can include writes newer than their reported version, so replaying prior deltas can double count. Preserve a version boundary to suppress already observed writes after a reset. Advance Cloud's refresh watermark even when the estimate is at capacity. - **Other paths and branches:** Covers shared-nothing publish and Cloud commit notifications. The guard from apache#69896 is absent from the checked upstream 3.1, 4.0, 4.1, and 4.2 branches. - **Behavior change:** The estimate can temporarily omit recently written rows when a report lags or the budget is exhausted. A first notification that arrives after a sample already included its rows can briefly inflate the estimate. A later complete report recalibrates it. ### Testing - On the prior PR head, the overlap assertion returned 17 instead of 12. The lagging-report assertion returned 110 instead of 100. The capacity assertion returned 138 instead of 128. - All 118 tests passed with the updated FE classes across MaterializedIndexTest, TabletStatMgrTest, StreamRowCountEstimatorTest, AnalysisManagerTest, and CloudGlobalTransactionMgrTest. The mode-2 polling test checks that a skipped write triggers a fresh tablet stats request. - FE core Checkstyle passed. Producer timing scenarios were reproduced as FE inputs. Live-cluster regression was not run. ### Release note Periodic statistics can correct the estimated changelog row count during continuous writes. ### Check List (For Author) - Behavior changed: Yes (see Details) - Does this need documentation: No - Pre-submission status: Ready
### Background Stream scans derive column statistics from the source table for the estimated number of rows in the scan. ### What problem does this PR solve? Issue Number: None Related PR: apache#69850, apache#69896, apache#69817 PR Type: Bugfix Problem Summary: Floating-point rounding can inflate fractional NULL counts during validation. Source min/max can exclude values visible at a stream offset. Stream estimates also resolve partition names with partition analysis off. ### Details - **Root cause:** The scan NDV cap can round up at the validity boundary. Source bounds come from a different data population. The partition analysis switch was checked after partition names had been resolved. - **Fix:** Round the capped NDV down when necessary, use unbounded ranges for offset-scoped statistics, and check the switch before resolving partition names. - **Why existing tests missed it:** Earlier cases used integer NULL counts, predicates inside the source bounds, and result-only assertions for the disabled partition statistics path. ### Testing - FE build and Checkstyle passed. - The SQL regression test_stream_column_statistics passed. - Before-and-after checks reproduced 1 versus 0.01 rows for IS NULL and 0 versus 10 rows for equality outside the source range. - Focused FE suites exercise stream statistics, filter estimation, row-count estimates, wrapper behavior, and plan provenance. ### Release note Improve optimizer cardinality estimates for stream and historical predicates. ### Check List (For Author) - Behavior changed: Yes (optimizer estimates) - Does this need documentation: No - Pre-submission status: Partially verified: cloud integration was not run
### Background Offset-scoped stream statistics carry NULL counts and NDV even when no value bounds are available at the scan offset. ### What problem does this PR solve? Issue Number: None Related PR: apache#69850, apache#69896, apache#69817 PR Type: Bugfix Problem Summary: Multiplication and division can produce NaN or false finite endpoints from unbounded column statistics. IN predicates can then estimate zero rows even when the query matches data. ### Details - **Root cause:** Arithmetic endpoint operations treat infinity sentinels as observed values. Infinity divided by infinity produces NaN, and a finite numerator divided by an infinite denominator produces a zero endpoint. - **Fix:** Propagate unbounded ranges through multiplication and division when an operand has unavailable bounds. Preserve the derived NDV and NULL count for selectivity estimation. - **Why existing tests missed it:** Existing predicate coverage uses direct slots or finite arithmetic endpoints. ### Testing - FE build with Checkstyle and focused FE unit tests passed. - SQL regression test_stream_column_statistics passed. - A stream snapshot returned the same two rows before and after the change. The filter estimate for (a / b) IN (1, 2) changed from 0 to 20 rows on the same 100-row scan estimate. ### Release note Improve cardinality estimation for arithmetic filters over stream scans. ### Check List (For Author) - Behavior changed: Yes (optimizer estimates) - Does this need documentation: No - Pre-submission status: Partially verified: cloud integration was not run
…70564) ### Background Incremental streams and historical snapshots are lowered into OLAP scans, filters, projections and unions. The optimizer needs column NDV and NULL counts for join estimates and runtime-filter selectivity, in addition to each scan's row estimate. ### What problem does this PR solve? Issue Number: None Related PR: #69850 (stream row-count estimates), #69896 (changelog row-count collection), #69817 (IS NULL estimation) PR Type: Enhancement Problem Summary: Stream and historical scans currently reuse distributions for a different population, or look up statistics under the stream identity. This change maps business columns to their source OLAP statistics and derives a new distribution for each scan, preserving the source NULL fraction and capping NDV at its estimated non-NULL rows. Most of the diff tests population conversion and propagation; the production change also copies partition HLLs before merging to avoid mutating cached statistics. ### Details - **Change map:** 459 changed production lines, 706 changed test lines and 41 generated expectation lines. The scan calculator shares row count setup, partition lookups and virtual column estimation, with separate methods for ordinary and stream column distributions. A source-table/index adapter resolves cache lookups for named streams and their historical snapshots. The changelog wrapper records whether normalization produced the scan from a named stream. Tests cover conversion, mapping, cache isolation and propagation, followed by a SQL plan/result regression. - **Before and after:** A source column with count=1000, NULLs=900 and NDV=100, read by a scan estimated at 100 rows, now has count=100, NULLs=90 and NDV=10. Low NDVs are retained instead of proportionally scaled. Source count and NULL count always come from the same table or merged-partition population, even when the source statistics predate current table growth. BEFORE/AFTER columns use the original business column, while internal columns stay unknown. The average width is retained and the total size and original statistic are rebuilt. Source ranges and hot values are omitted because they describe a different population. The NDV cap accounts for floating-point rounding so fractional NULL counts survive validity checks. Join-reorder validation consumes the same adjusted statistics. - **Configs and defaults:** No new configuration. Stream scans only resolve partition names when `enable_partition_analyze` is enabled. Manually injected source statistics take priority, and a missing selected partition falls back to the full table-level population. - **Impact on existing users:** Ordinary OLAP, direct base-table incremental reads, stream resets, and IVM post-snapshot reads use the ordinary distribution rules. Named stream snapshots are estimated at their consumption offset. Stream and historical scan estimates can change join/RF cost decisions. Stream and historical scans use the upstream row-count estimator as the output population. Explicit estimates already cover the selected partitions, including fallback for missing partition counts. Predicate estimates for a stream scan use its scoped population. Statistics derivation records unknown key statistics after early NDV validation. The source NULL fraction remains an approximation. Without offset-specific min/max statistics, an equality predicate uses the scoped NDV even for values outside the source range.
### Background The migration fixture commits two writes before publishing either version. The second publish adds a changelog segment for the earlier row image, and the test checks the final row count and the result of retrying that publish. ### What problem does this PR solve? Issue Number: None Related PR: apache#69585 (explicit changelog mappings), apache#69896 (published row counts) PR Type: Test Problem Summary: The test constructed its publish requests without the column mapping supplied to the writer. The first transaction failed before the row-count checks. Send the prepared source index ID, historical-value flag and column UIDs in the original and retried requests. ### Details - Failure: The first publish returned INVALID_ARGUMENT for a missing changelog mapping on tablet 13005 in transaction 23005. - Cause: The test omitted the publish snapshot and left the newly inserted BEFORE and delete-sign columns with implicit IDs. - Stability evidence: Assign each new column an explicit, free UID before tablet creation. Inserting BEFORE preserves the existing system column IDs. Exercise the original segment, row-count and retry assertions with the prepared mapping. ### Testing - Reproduced the missing-mapping error on the parent with the single row-count test. - Ran run-be-ut.sh under ASAN on macOS arm64. All four TestEngineStorageMigrationTask cases and the two BetaRowsetTest merge cases passed. The build used the local compiler-only workaround for the unrelated Darwin TLS test. - clang-format 16, changed-file clang-tidy and git diff --check passed. ### Release note None ### Check List (For Author) - Behavior changed: No - Does this need documentation: No - Pre-submission status: Ready for review. Linux CI has not rerun. ### AI Disclosure - Tool: Codex - Generated: Test fixture changes, verification and commit description. - Human review: Pending.
…0892) ### Background Stream planning estimates retained changelog rows using periodic tablet statistics and visible write notifications. Periodic statistics reflect row removal from TTL cleanup, while write notifications keep the estimate responsive between reports. Tablets are sampled independently, so a complete set of samples can lag the latest write. ### What problem does this PR solve? Issue Number: None Related PR: #69896 (introduced the report-version guard) PR Type: Bugfix Problem Summary: Continuous writes can keep every complete report one version behind, preventing FE from removing expired rows from its estimate. FE now uses each complete report with nondecreasing coverage to reset the estimate. In a five-round test with 100 retained rows and a 10-row write ahead of every report, the original estimate grows from 110 to 150. With the fix, it returns to 100 after each report. ### Details - **Change map:** FE catalog (89 additions, 69 deletions) updates report aggregation and limits immediate estimates. FE unit tests (131 additions, 44 deletions) exercise both storage modes, capacity, retries, and Cloud polling. - **Frequency:** Always in the deterministic case where each complete report lags a counted write. TTL cleanup makes the stale estimate diverge from retained rows. - **Root cause:** The tablet statistics managers and MaterializedIndex required periodic coverage to reach the latest applied write. A complete but lagging report could never correct the estimate during continuous writes. - **Why existing tests missed it:** The FE unit tests covered an eventual up-to-date report. The immediate-count and Cloud subtransaction suites pause periodic publication to check write estimates. Neither exercised repeated lagging reports. - **Fix:** Replace the estimate with the complete report sum and begin a new window with a 128-write-version budget per changelog index. Tablet counts can include writes newer than their reported version, so replaying prior deltas can double count. Preserve a version boundary to suppress already observed writes after a reset. Advance Cloud's refresh watermark even when the estimate is at capacity. - **Other paths and branches:** Covers shared-nothing publish and Cloud commit notifications. The guard from #69896 is absent from the checked upstream 3.1, 4.0, 4.1, and 4.2 branches. - **Behavior change:** The estimate can temporarily omit recently written rows when a report lags or the budget is exhausted. A first notification that arrives after a sample already included its rows can briefly inflate the estimate. A later complete report recalibrates it.
#70895) ### Background Cloud FE fetches statistics for batches of tablets. For changelog tablets it also requests the published partition version associated with the row count. The response already supports omitting that version, and FE treats absent coverage as unknown. ### What problem does this PR solve? Issue Number: None Related PR: #69896 (introduced the optional row-count version read) PR Type: Bugfix Problem Summary: A read or parse error on an optional partition version aborts the tablet statistics batch. For example, a request with a malformed changelog tablet version followed by an ordinary tablet with 100 rows returns a non-OK status, and FE discards the response. With this change the batch returns both statistics entries, omits the affected tablet's version, and reports the ordinary tablet's 100 rows. ### Details - **Frequency:** Always when the optional lookup hits a read or parse error after the tablet stats were read successfully. - **Root cause:** GetTabletStats treated an optional coverage lookup like a tablet stats read error and returned an RPC-level failure before processing the rest of the batch. - **Why existing tests missed it:** The legacy and versioned GetTabletStats tests cover successful statistics reads, including valid coverage. The changelog SQL suites test the resulting row estimates without injecting a malformed optional version document into a mixed batch. - **Fix:** Keep the tablet stats, log the coverage error, and omit the optional field for the affected tablet. Missing partition versions still map to version 1 and errors when reading the stats themselves still fail the RPC. - **Other paths and branches:** The change covers both legacy and versioned Cloud metadata reads. The optional lookup is absent from the checked upstream 3.1, 4.0, 4.1, and 4.2 release branches. - **Behavior change:** An optional version-read error no longer discards independently readable tablet statistics in the same batch.
Background
Changelog indexes retain physical change records for table streams. Their row-count estimates come from periodic tablet statistics, independently of base-table load statistics. Updates and deletes can produce changelog records whose counts differ from the base-table load rows.
What problem does this PR solve?
Issue Number: None
Related PR: #69850 (persists consumption baselines with offsets and estimates stream ranges)
PR Type: Enhancement
Problem Summary:
Changelog row counts can remain stale or unknown between tablet reports, and cloud commit responses previously carried no partition/index-level changelog delta. Successful visible commits now supplement these estimates in both storage modes, while valid periodic reports calibrate retained stock. Most of the diff tests publication, retries, incomplete reports and recovery; no new configuration is required after upgrading.
Details
Testing
122 focused FE tests passed locally across runs, covering index counts, publication, retries and restored-cloud polling. The recovery scheduling test failed before the fix and passed afterwards.
The version-range cap follow-up passed 75 focused FE tests and the FE build with Checkstyle. Its new limit test reproduced continued accumulation before the fix. Coverage includes partial and complete reports, retries, resuming below the cap and consecutive version coalescing.
One ASAN BE test passed with real concurrent MoW publication and retry; five ASAN MS RPC tests passed for ordinary, lazy and subtransaction commits, including failures and base/changelog separation.
Shared-nothing
changelog_p0: 27 suites passed before the final logging cleanup and cloud test additions; the immediate-count suite passed again after its cloud-compatible FORCE cleanup change.Local ASAN cloud cluster (1 FE, 1 BE, MS, Recycler and FDB): immediate-count and subtransaction suites passed with periodic publication paused; forcing lazy commits passed both suites against the same golden files, with existing MS logs confirming
commit_txn_eventually. The fullchangelog_p0directory passed 24/28 suites. Four existing suites failed on row contents:test_changelog_before_column_name,test_cloud_changelog_publish_conflict,test_changelog_multi_segment, andtest_changelog_basic; all four failed again in an isolated batch, and their expected results were not changed.With periodic reports paused, the extended immediate-count suite passed in SN and cloud: two successive loads and stream consumptions grow retained changelog counts from 2 to 3 to 4; consumption leaves current counts unchanged, and each consumed interval becomes empty. The new golden sections were generated by the runner.
Notes for Reviewers
updatedRows.DROP STATSpreserves the estimate; data replacement resets it. Complete periodic reports retire covered deduplication versions. Each Cloud changelog index tracks at most 1,024 ranges. Immediate updates pause while full and resume when an advancing complete report frees a range.Release note
Successful loads supplement changelog row-count estimates before the next periodic tablet report in both storage modes. Periodic statistics continue to calibrate retained counts.
Check List (For Author)
AI Disclosure