Skip to content

[feat](stream) Collect changelog load rows in both storage modes - #69896

Merged
yujun777 merged 10 commits into
apache:masterfrom
yujun777:ivm-changelog-load-rows
Nov 23, 2026
Merged

yujun777 merged 10 commits into
apache:masterfrom
yujun777:ivm-changelog-load-rows

Conversation

@yujun777

@yujun777 yujun777 commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

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

  • Change map: production code +317/-41, tests +1143/-1, and generated test output +148/-0; no documentation or generated protocol source. Production changes have three parts: final published rowset counting and partition replica normalization in SN; optional MS response aggregation and version-based deduplication in cloud; valid periodic stock publication, locking and restored-replica polling. Tests cover those paths and physical counts.
  • Before and after: Counts previously waited for periodic reports. Commits now add physical changelog rows: the regression's append/update/delete sequence reports 3, 5 and 6. Zero deltas preserve unknown counts; positive partial estimates do not imply a complete report. Periodic reports can lower retained counts after TTL cleanup, and restored cloud replicas fetch valid statistics before resuming persisted polling backoff.
  • Configs and defaults: None. No new runtime log statements are added.
  • Impact on existing users: Existing SQL and data visibility are unchanged. Optional protobuf fields preserve compatibility when either side lacks the new statistics. Counts remain estimates: periodic reports and deltas can overlap or lag, and failed publication can miss an immediate delta until the next report.

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 full changelog_p0 directory 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, and test_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

  • Current index counts are independent of each stream's consumption baseline. This PR updates C1; [fix](stream) Estimate stream rows from consumption baselines #69850 snapshots B0/C0 together with the consumed offset and uses stock fallback for nonempty ranges whose deltas are stale.
  • Counts are physical records; UPDATE records are not multiplied by two. Commit statistics are separate from base updatedRows.
  • Tablet identity checks prevent delayed responses from updating replaced data. DROP STATS preserves 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)

  • Behavior changed: Yes (see Details)
  • Does this need documentation: No
  • Pre-submission status: Partially verified: the four cloud row-content failures listed above remain; the new row-count suites pass in ordinary, lazy and subtransaction paths.

AI Disclosure

  • Tool: Codex; gpt-6.1-sol/xhigh for independent reviews
  • Generated: Code, tests, and this description
  • Human review: not stated

@hello-stephen

Copy link
Copy Markdown
Contributor

Thank you for your contribution to Apache Doris.
Don't know what should be done next? See How to process your PR.

Please clearly describe your PR:

  1. What problem was fixed (it's best to include specific error reporting information). How it was fixed.
  2. Which behaviors were modified. What was the previous behavior, what is it now, why was it modified, and what possible impacts might there be.
  3. What features were added. Why was this function added?
  4. Which code was refactored and why was this part of the code refactored?
  5. Which functions were optimized and what is the difference before and after the optimization?

@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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.
  2. Scope and reuse: the four-file change is focused and reuses the existing tablet delta report and statistics serialization.
  3. 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.
  4. 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.
  5. Configuration: no configuration is added.
  6. 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.
  7. Thrift/protobuf IDs: no definition is changed, so no field-ID or required-field compatibility change applies.
  8. 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.
  9. 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.
  10. 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.
  11. Expected results: the added direct-map assertions match their inputs; no regression output artifact is changed.
  12. Observability: existing tablet/transaction identifiers and report logging remain. No separate logging or metrics defect was substantiated.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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()) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5bb280e: TabletMeta now follows Tablet in the import block.

@yujun777
yujun777 force-pushed the ivm-changelog-load-rows branch from 1cb6c79 to 5bb280e Compare October 30, 2026 13:15
@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

1 similar comment
@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

Copy link
Copy Markdown
Contributor Author

/review

@yujun777 yujun777 changed the title [improvement](ivm) Record the rows a load writes to a changelog index [improvement](stream) Record the rows a load writes to a changelog index Oct 30, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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.
  2. Scope and reuse: the changes are focused and reuse the existing tablet delta report, transaction publication, and TableStatsMeta persistence mechanisms.
  3. 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.
  4. 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.
  5. Configuration: no configuration is added.
  6. Compatibility: the new Gson field is optional and lazily initialized, with no thrift/protobuf or wire-shape change.
  7. 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.
  8. 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.
  9. 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.
  10. 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.
  11. 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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.calculateTaskUpdateRows skips 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

Copy link
Copy Markdown
Contributor Author

/review

@yujun777
yujun777 force-pushed the ivm-changelog-load-rows branch from 5bb280e to fecb190 Compare October 30, 2026 14:17
@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

Copy link
Copy Markdown
Contributor Author

/review

@hello-stephen

Copy link
Copy Markdown
Contributor
TPC-H: Total hot run time: 28398 ms
machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
scripts: https://github.com/apache/doris/tree/master/tools/tpch-tools
Tpch sf100 test result on commit fecb190d2b353d80368c0d37610cddbf6ef1569d, data reload: false

------ Round 1 ----------------------------------
============================================
q1	17589	5128	5032	5032
q2	2132	312	260	260
q3	10230	1382	816	816
q4	4682	459	335	335
q5	7438	797	515	515
q6	181	179	153	153
q7	772	814	599	599
q8	9253	1312	1116	1116
q9	5500	4210	4150	4150
q10	6810	1279	1020	1020
q11	433	258	228	228
q12	635	398	286	286
q13	18067	3629	2971	2971
q14	272	270	245	245
q15	q16	709	703	648	648
q17	1359	745	587	587
q18	6954	6172	6110	6110
q19	1099	959	643	643
q20	385	342	232	232
q21	5004	2189	2303	2189
q22	348	305	263	263
Total cold run time: 99852 ms
Total hot run time: 28398 ms

----- Round 2, with runtime_filter_mode=off -----
============================================
q1	5607	5592	5620	5592
q2	709	571	535	535
q3	5191	5372	4954	4954
q4	1996	2173	1562	1562
q5	5255	5167	5572	5167
q6	259	200	157	157
q7	2331	2022	1799	1799
q8	3048	2698	2759	2698
q9	7941	8024	7972	7972
q10	3720	3928	3272	3272
q11	604	441	413	413
q12	720	707	539	539
q13	3525	3917	3309	3309
q14	338	326	284	284
q15	q16	724	736	663	663
q17	8341	7081	6877	6877
q18	13024	12149	12883	12149
q19	910	778	785	778
q20	2180	2143	1928	1928
q21	5750	4783	4786	4783
q22	495	456	406	406
Total cold run time: 72668 ms
Total hot run time: 65837 ms

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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. StatsCalculator then falls back to getRowCountWithDeltaRows, whose new branch returns only post-creation indexUpdatedRows, underestimating the visible changelog until a later tablet report.
  2. Partial TRUNCATE PARTITION replaces changelog tablets but retains the table statistics record. The asynchronous dropStats path invalidates column/partition statistics without clearing indexUpdatedRows, so the branch continues returning rows from the removed partition.
  3. A load whose partition is force-dropped before visibility can still carry old tablet delta rows. DatabaseTransactionMgr removes the missing partition from commit info, but still forwards the transaction delta map; after the old tablet metadata is removed, isChangelogTablet returns false and this code routes those changelog rows into the base updatedRows counter 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 TableStatsMeta JSON 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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@hello-stephen

Copy link
Copy Markdown
Contributor
TPC-DS: Total hot run time: 151672 ms
machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
scripts: https://github.com/apache/doris/tree/master/tools/tpcds-tools
TPC-DS sf100 test result on commit fecb190d2b353d80368c0d37610cddbf6ef1569d, data reload: false

query5	4308	581	462	462
query6	420	201	194	194
query7	4809	447	227	227
query8	323	161	165	161
query9	8806	3216	3220	3216
query10	472	311	260	260
query11	6028	3875	3580	3580
query12	148	91	86	86
query13	1240	440	336	336
query14	6090	3917	3653	3653
query14_1	3392	3414	3405	3405
query15	200	195	180	180
query16	922	419	395	395
query17	841	628	501	501
query18	2420	411	307	307
query19	190	165	130	130
query20	83	85	79	79
query21	204	126	107	107
query22	12982	12999	12873	12873
query23	13431	12848	12335	12335
query23_1	12538	12469	12456	12456
query24	7367	864	463	463
query24_1	476	474	475	474
query25	515	390	338	338
query26	1245	267	142	142
query27	2768	445	273	273
query28	4659	2039	2009	2009
query29	1586	607	439	439
query30	293	213	182	182
query31	1002	929	818	818
query32	133	90	96	90
query33	526	294	233	233
query34	955	865	520	520
query35	723	755	638	638
query36	850	853	737	737
query37	125	96	79	79
query38	1775	1719	1701	1701
query39	832	818	759	759
query39_1	738	722	754	722
query40	214	114	94	94
query41	67	64	63	63
query42	91	85	85	85
query43	363	367	318	318
query44	1377	729	740	729
query45	179	178	171	171
query46	852	988	585	585
query47	2668	2947	2889	2889
query48	306	316	217	217
query49	564	398	291	291
query50	683	286	213	213
query51	10563	10558	10321	10321
query52	81	79	69	69
query53	193	209	150	150
query54	253	193	175	175
query55	68	67	62	62
query56	239	224	197	197
query57	1638	1642	1571	1571
query58	280	266	256	256
query59	2146	2144	1987	1987
query60	293	256	241	241
query61	171	170	167	167
query62	383	346	285	285
query63	192	157	172	157
query64	2866	1048	931	931
query65	3344	3292	3269	3269
query66	1776	435	319	319
query67	20186	20420	20123	20123
query68	3145	1035	617	617
query69	408	286	252	252
query70	883	772	809	772
query71	301	245	229	229
query72	2819	2716	2288	2288
query73	518	531	292	292
query74	4560	4516	4360	4360
query75	2326	2313	1927	1927
query76	2315	1031	628	628
query77	350	374	264	264
query78	9799	9701	9208	9208
query79	1039	879	536	536
query80	719	441	343	343
query81	541	317	271	271
query82	578	133	100	100
query83	269	197	175	175
query84	317	123	100	100
query85	899	419	375	375
query86	353	268	241	241
query87	2003	1947	1814	1814
query88	3839	2886	2868	2868
query89	331	281	238	238
query90	1802	176	178	176
query91	160	154	132	132
query92	101	85	89	85
query93	1016	1025	580	580
query94	466	328	275	275
query95	582	333	305	305
query96	694	498	238	238
query97	2442	2446	2313	2313
query98	172	153	151	151
query99	760	761	641	641
Total cold run time: 234761 ms
Total hot run time: 151672 ms

@hello-stephen

Copy link
Copy Markdown
Contributor
ClickBench: Total hot run time: 24.36 s
machine: 'aliyun_ecs.c7a.8xlarge_32C64G'
scripts: https://github.com/apache/doris/tree/master/tools/clickbench-tools
ClickBench test result on commit fecb190d2b353d80368c0d37610cddbf6ef1569d, data reload: false

query1	0.00	0.00	0.01
query2	0.09	0.06	0.05
query3	0.26	0.08	0.08
query4	1.61	0.13	0.12
query5	0.24	0.25	0.25
query6	1.17	0.69	0.71
query7	0.04	0.01	0.01
query8	0.06	0.04	0.04
query9	0.41	0.34	0.36
query10	0.63	0.57	0.59
query11	0.19	0.15	0.14
query12	0.20	0.16	0.15
query13	0.50	0.52	0.50
query14	1.03	1.03	1.03
query15	0.63	0.61	0.62
query16	0.33	0.35	0.37
query17	1.22	1.15	1.11
query18	0.21	0.19	0.19
query19	2.13	2.01	2.05
query20	0.02	0.01	0.01
query21	15.42	0.20	0.13
query22	4.83	0.05	0.05
query23	16.27	0.34	0.13
query24	3.09	0.61	0.30
query25	0.12	0.05	0.07
query26	0.90	0.22	0.15
query27	0.04	0.04	0.05
query28	2.86	0.75	0.37
query29	12.52	4.14	3.27
query30	0.28	0.16	0.11
query31	2.77	0.55	0.34
query32	3.22	0.59	0.52
query33	3.18	3.11	3.18
query34	15.31	3.99	3.42
query35	3.34	3.34	3.34
query36	0.58	0.45	0.43
query37	0.10	0.07	0.06
query38	0.05	0.04	0.03
query39	0.03	0.03	0.03
query40	0.18	0.15	0.14
query41	0.08	0.04	0.03
query42	0.04	0.03	0.03
query43	0.04	0.04	0.03
Total cold run time: 96.22 s
Total hot run time: 24.36 s

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@hello-stephen

Copy link
Copy Markdown
Contributor

FE UT Coverage Report

Increment line coverage 65.00% (13/20) 🎉
Increment coverage report
Complete coverage report

yujun777 added a commit to yujun777/doris that referenced this pull request Nov 4, 2026
### 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
@yujun777

yujun777 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

yujun777 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. 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.
  2. Scope and reuse: the production change is focused and reuses existing reporting and partition index state.
  3. 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.
  4. 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.
  5. Configuration: none added.
  6. Compatibility: existing storage fields remain usable, but reused report semantics are incompatible with older FE readers; see the new P2.
  7. Thrift/protobuf IDs: no definitions changed, so cross-branch field-ID comparison is not applicable.
  8. 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.
  9. Conditions: attachment-null, missing-tablet and removed-partition branches have concrete cases and nearby rationale; partition-specific replica allocation is used for changelog rows.
  10. 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.
  11. Test results: no result artifacts changed. This was static inspection only: no builds, tests, benchmarks or runtime validation were executed.
  12. Observability: existing publish and delta-report logs provide transaction/tablet/count context; no additional critical gap was found.
  13. 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.
  14. 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.
  15. 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.
  16. 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.
  17. 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()});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@yujun777
yujun777 dismissed stale reviews from englefly and luwei16 via 6128e4b November 23, 2026 04:08
@yujun777
yujun777 force-pushed the ivm-changelog-load-rows branch from a266e6a to 6128e4b Compare November 23, 2026 04:08
@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.
@yujun777

Copy link
Copy Markdown
Contributor Author

run buildall

@yujun777

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 RowCountReport and MaterializedIndex centralize 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).

@yujun777

Copy link
Copy Markdown
Contributor Author

run vault_p0

@deardeng deardeng left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@englefly englefly left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@yujun777
yujun777 merged commit a0662fe into apache:master Nov 23, 2026
37 of 38 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

PR approved by anyone and no changes requested.

@github-actions github-actions Bot added the approved Indicates a PR has been approved by one committer. label Nov 23, 2026
@github-actions

Copy link
Copy Markdown
Contributor

PR approved by at least one committer and no changes requested.

yujun777 added a commit to yujun777/doris that referenced this pull request Nov 23, 2026
### 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
yujun777 added a commit to yujun777/doris that referenced this pull request Nov 24, 2026
### 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
yujun777 added a commit to yujun777/doris that referenced this pull request Nov 24, 2026
### 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
yujun777 added a commit that referenced this pull request Nov 24, 2026
…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.
TsukiokaKogane added a commit to TsukiokaKogane/doris that referenced this pull request Nov 24, 2026
### 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.
yujun777 added a commit that referenced this pull request Nov 26, 2026
…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.
yujun777 added a commit that referenced this pull request Nov 27, 2026
#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

approved Indicates a PR has been approved by one committer. incremental-computation reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants