Files
milvus/scripts/check_segment_timestamp_usage.sh
0ca60c5b47 feat: add commit_timestamp to SegmentInfo for correct MVCC/TTL/GC on import/CDC segments (#48472)
## What this PR does

Adds `commit_timestamp` (uint64) to `SegmentInfo` and `SegmentLoadInfo`
so that import/CDC segments use their logical commit time — not raw row
timestamps — for all temporal decisions.

**Problem:** When bulk-insert imports rows, the row timestamps generated
during the import process may be slightly older than the actual commit
time. Every time-based check in the system (MVCC snapshot visibility, GC
eligibility, collection-level TTL compaction triggering, delete-buffer
anchoring) sees these outdated timestamps instead of the actual commit
time, producing correctness bugs.

**Solution:**

Two-layer approach:

1. **C++ segcore (load-time overwrite):** During `LoadFieldData`, the
in-memory timestamp column is overwritten to `commit_ts_` when
`commit_ts_ != 0`. This makes existing MVCC/delete logic work correctly
with zero hot-path changes.

2. **Compaction normalization:** During compaction, all compaction paths
(mix/sort/clustering) rewrite row timestamps to `commit_ts` in output
binlogs, then set `CommitTimestamp = 0` on the output segment. After
first compaction, the segment becomes a normal segment with no special
handling needed. `commit_ts` is a temporary state that only exists
between import and first compaction.

**Key design decisions:**

- **TTL field (per-row):** Not affected by commit_ts. TTL field values
represent user-specified expiration intent and are honored as-is.
- **Collection-level TTL:** Uses `max(row_ts, commit_ts)` as the
effective row age to prevent premature expiration.
- **Delete/Upsert before commit_ts:** A delete/upsert with `ts <
commit_ts` does NOT take effect, because the row did not exist at that
time. The original `search_pk(pk, delete_ts)` logic handles this
correctly since `row_ts` is overwritten to `commit_ts`.
- **CommitTimestamp assignment:** Currently TODO in `import_checker.go`,
pending companion PR for 2PC commit flow.

## Changes

- `pkg/proto/data_coord.proto`, `query_coord.proto`, `segcore.proto`:
add `commit_timestamp` field
- `internal/datacoord/segment_info.go`:
`segmentEffectiveTs`/`segmentEffectiveDmlTs`/`effectiveTimestamp`
helpers
- `internal/datacoord/meta.go`: compaction completion mutations set
`CommitTimestamp=0` and normalize position timestamps via
`normalizePositionTimestamp` helper
- `internal/datacoord/compaction_trigger.go`: use `effectiveTimestamp`
for TTL compaction trigger
- `internal/datacoord/handler.go`, `garbage_collector.go`,
`compaction_task_l0.go`: use effective timestamp helpers
- `internal/querycoordv2`: propagate `CommitTimestamp` in
`PackSegmentLoadInfo`
- `internal/querynodev2/delegator`: use `segmentEffectiveTs` for
delete-buffer pin/list anchoring
- `internal/core/src/segcore/ChunkedSegmentSealedImpl`: overwrite
timestamp column at load time when `commit_ts_ != 0`
- `internal/datanode/compactor/timestamp_overwrite.go`: Record/Reader
wrappers for compaction timestamp normalization
-
`internal/datanode/compactor/{mix,merge_sort,sort,clustering}_compactor.go`:
apply timestamp overwrite during compaction

## Tests

- Unit tests: DataCoord helpers, `UpdateCommitTimestamp` operator,
`GenSnapshot` filter, GC eligibility, TTL compaction trigger
- Unit tests: QueryNode `segmentEffectiveTs`, delete-buffer pin at
commit_ts
- Unit tests: `timestamp_overwrite.go` Record/Reader wrappers
- C++ tests: MVCC gate, TTL gate, pre-commit delete not applied, normal
segment unchanged
- Integration tests: MVCC visibility, delete/upsert on import segment,
delete/upsert before commit_ts (should not apply), compaction normalizes
commit_ts to 0

## issue

issue: #48471

design doc:
https://github.com/milvus-io/milvus-design-docs/blob/main/design_docs/20260324-commit-timestamp.md

---------

Signed-off-by: Yihao Dai <yihao.dai@zilliz.com>
Signed-off-by: bigsheeper <yihao.dai@zilliz.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-05-26 10:50:33 +08:00

81 lines
3.3 KiB
Bash
Executable File

#!/bin/bash
# check_segment_timestamp_usage.sh
#
# Static guard: detect direct segment timestamp access in non-test Go files.
# All temporal decisions on segments must use segmentEffectiveTs/segmentEffectiveDmlTs
# to correctly handle import/CDC segments with commit_timestamp.
#
# Allowlisted paths are verified to only operate on Growing/L0 segments or are
# the helper definitions themselves. Each allowlist entry must include a comment
# explaining why the raw access is safe.
#
# Usage: scripts/check_segment_timestamp_usage.sh
# Exit code: 0 = pass, 1 = violations found
set -euo pipefail
PATTERN='(GetStartPosition\(\)\.GetTimestamp\(\)|GetDmlPosition\(\)\.GetTimestamp\(\))'
# Allowlist: paths verified to be safe for raw timestamp access.
# Format: grep -E pattern (file basename or file:context).
ALLOWLIST_PATTERNS=(
# Helper function definitions — segmentEffectiveTs/segmentEffectiveDmlTs
# fallback to raw timestamp when commitTs=0 (by design)
"segmentEffective"
# segment_info.go: helper function bodies (return seg.GetXxxPosition().GetTimestamp())
"segment_info.go"
# Growing segment sealing — import segments are never Growing
"segment_allocation_policy.go"
# Empty Growing segment cleanup — import segments have rows
"segment_manager.go"
# Growing segment release — import segments are never Growing
"segment_checker.go"
# DML pipeline for Growing segments — import segments don't receive DML messages
"flow_graph_dd_node.go"
# Meta update validation guard — compares within same segment, not temporal decision
"meta.go:.*GetDmlPosition"
# GetEarliestStartPositionOfGrowingSegments — filters Growing only
"meta.go:.*GetStartPosition"
# Import task sets positions from actual binlog data (upstream of commit_ts)
"import_task_import.go"
# Growing segment DML position for excluded segments — unflushed only
"services.go"
# L0 deleteCheckPoint — only operates on L0 segments, not import segments
"handler.go:.*deleteCheckPoint"
# Handlers for growing segment info reporting (not temporal decision)
"handlers.go"
# Log statements (not temporal decisions)
"zap\\.Time\\|zap\\.Uint64.*Ts"
# delegator_data.go: segmentEffectiveTs helper fallback + log statements
"delegator_data.go"
)
# Build grep -v pattern from allowlist
ALLOWLIST_REGEX=$(IFS='|'; echo "${ALLOWLIST_PATTERNS[*]}")
VIOLATIONS=$(grep -rn --include='*.go' --exclude='*_test.go' -E "$PATTERN" internal/ \
| grep -v -E "$ALLOWLIST_REGEX" \
|| true)
if [ -n "$VIOLATIONS" ]; then
echo "============================================================"
echo "ERROR: Direct segment timestamp access detected!"
echo ""
echo "For import/CDC segments, raw GetStartPosition().GetTimestamp()"
echo "and GetDmlPosition().GetTimestamp() return stale values."
echo ""
echo "Use segmentEffectiveTs() or segmentEffectiveDmlTs() instead."
echo ""
echo "If this is a false positive (e.g., only operates on Growing"
echo "segments), add to the allowlist in this script with a comment"
echo "explaining why raw access is safe."
echo ""
echo "See: docs/plans/2026-04-02-commit-timestamp-test-design.md"
echo "============================================================"
echo ""
echo "$VIOLATIONS"
exit 1
fi
echo "segment timestamp usage check: PASS"