You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@skywalking.apache.org by ha...@apache.org on 2026/09/15 09:10:01 UTC

(skywalking-banyandb) 09/15: fix(trace): enforce time ranges for non-timestamp sorted queries (#1333)

This is an automated email from the ASF dual-hosted git repository.

hanahmily pushed a commit to branch release-0.11.1
in repository https://gitbox.apache.org/repos/asf/skywalking-banyandb.git

commit e075769c682f8d761026a66231c46a5d77bda50c
Author: Gao Hongtao <ha...@gmail.com>
AuthorDate: Fri Sep 11 10:40:55 2026 +0800

    fix(trace): enforce time ranges for non-timestamp sorted queries (#1333)
    
    Filter partially covered SIDX parts before trace deduplication and bypass timestamp checks for fully covered parts. Preserve user filters and projections, handle timestamp entities and conservative merge bounds, and add regression coverage and part-scan benchmarks.
    
    Fixes apache/skywalking#14058
    
    (cherry picked from commit 17da658000a624847a1fa87eeece13ed72438d9c)
---
 TRACE_QUERY_TIME_RANGE_DESIGN.md                   | 400 +++++++++++++++++++++
 banyand/internal/sidx/interfaces.go                |  27 +-
 banyand/internal/sidx/merge.go                     |  28 +-
 banyand/internal/sidx/query.go                     |  58 ++-
 banyand/internal/sidx/sidx.go                      |  30 +-
 banyand/internal/sidx/timestamp_test.go            | 140 ++++++++
 banyand/trace/query.go                             | 233 +++++++++++-
 banyand/trace/query_test.go                        |  94 +++++
 banyand/trace/query_time_benchmark_test.go         | 355 ++++++++++++++++++
 banyand/trace/streaming_pipeline.go                |   2 +-
 pkg/query/logical/trace/index_filter_test.go       |  45 +++
 pkg/query/logical/trace/trace_analyzer.go          |   1 +
 pkg/query/logical/trace/trace_plan_tag_filter.go   |   6 +-
 .../cases/trace/data/want/time_range_trace_001.yml |  30 ++
 test/cases/trace/trace.go                          |  13 +
 15 files changed, 1412 insertions(+), 50 deletions(-)

diff --git a/TRACE_QUERY_TIME_RANGE_DESIGN.md b/TRACE_QUERY_TIME_RANGE_DESIGN.md
new file mode 100644
index 000000000..56522d18b
--- /dev/null
+++ b/TRACE_QUERY_TIME_RANGE_DESIGN.md
@@ -0,0 +1,400 @@
+# Exact time filtering for ordered trace queries
+
+Status: core fix implemented and validated locally, including the part-coverage
+fast path and real-matcher benchmarks.
+
+Upstream issue: [apache/skywalking#14058](https://github.com/apache/skywalking/issues/14058).
+
+Investigated revision: `d8ce8281`. Context: HAPI session
+`ff9632fa-3b97-45cd-8ab2-183b82e776b9` (PR CI Fail).
+
+## Confirmed bug
+
+An ordered trace search can return traces with no span inside its requested time
+window when the ordering key is duration rather than the schema timestamp.
+
+The existing `TestIssue14058LatencyOrderIgnoresTimeRange` reproduces this with an
+empty 15-minute interval inside a populated daily segment:
+
+| Experiment | Timestamp order | Duration order |
+| --- | ---: | ---: |
+| Current code | 0 traces | 8 traces (incorrect) |
+| Add only SIDX MinTimestamp/MaxTimestamp | 0 traces | 8 traces (still incorrect) |
+| Experimental stored-tag matcher plus internal timestamp projection | 0 traces | 0 traces (test passes) |
+
+All three investigation experiments were run locally before implementation. Build overlays supplied the missing generated
+mocks and replaced the missing UI bundle embed with an existing HTML asset; no
+production source or existing reproduction file was edited. The second experiment
+also overlaid the proposed two timestamp bounds. Logs are
+`/tmp/repro-14058-design.log` and `/tmp/repro-14058-bounds-only.log`.
+
+The passing prototype was also overlay-only; its log is
+`/tmp/repro-14058-exact-prototype.log`. It validates the ordinary duration-index
+approach against this reproduction, not the full design: composite entities,
+internal exclusive bounds, and the regression matrix below are not implemented or
+validated by that prototype. Overlays are under `/tmp/trace-time-range-design/`.
+
+## Root cause
+
+1. `pkg/query/logical/trace/trace_plan_tag_filter.go:75-78` translates the time
+   window to key bounds only for timestamp ordering. This distinction is correct:
+   duration keys must not be compared with epoch timestamps.
+2. `banyand/trace/query.go:301-310` forwards key restrictions and existing filters,
+   but adds neither exact time filtering nor timestamp part bounds.
+3. `banyand/internal/sidx/query.go:208` and `part_wrapper.go:206-222` use timestamp
+   bounds only for whole-part overlap tests. They do not enforce a row predicate.
+4. The write paths currently use entire segment bounds for SIDX part metadata
+   (`write_standalone.go:439-442`, `write_liaison.go:226-229`). Part pruning alone
+   therefore does not even repair the supplied empty-window reproduction.
+
+The missing invariant is **time eligibility independent of sort-key eligibility**.
+
+## Contract and scope
+
+For ordered searches, a candidate row must satisfy:
+
+```text
+existing series/key restrictions AND existing row predicate AND timestamp in TimeRange
+```
+
+The same row must satisfy the row predicate and time condition. Two different
+spans, one satisfying time and another satisfying the predicate, are not enough.
+Time qualification must happen before the row supplies a trace's representative
+sort key, before deduplication, and before pagination.
+
+Preserve public inclusive begin/end semantics. The public API validates
+millisecond precision, while storage and ordering use nanoseconds; never convert
+storage bounds with UnixMilli. Internal TimeRange inclusivity flags must also be
+respected, including empty ranges and overflow-safe handling of exclusive bounds.
+
+Preserve the existing distinction between **selecting a trace through a qualifying
+span** and **clipping the spans returned for that trace**. Timestamp ordering today
+selects IDs and then reconstructs their traces. This fix must not silently truncate
+out-of-window sibling spans. Explicit trace-ID queries bypass SIDX; retain that
+lookup behavior and document it with tests rather than accidentally changing it.
+
+## Recommended implementation
+
+### 1. Centralize restriction construction at the trace-to-SIDX boundary
+
+Extract a small request-building helper used by `prepareSIDXStreaming`, shared by
+legacy and vectorized execution. It receives the selected index, schema timestamp
+name, TimeRange, existing key bounds/filter, projection, and resolved series.
+
+Keep key and timestamp ranges separate. Set `MinTimestamp`/`MaxTimestamp` for
+part classification. Trusted conservative part bounds can prove either exclusion
+or complete coverage; overlap alone cannot prove that individual rows qualify.
+Legacy parts without trustworthy timestamp bounds remain eligible for exact
+filtering.
+
+Determine where the timestamp resides from the actual selected index's tag list,
+not from an index name such as `timestamp` or `duration`:
+
+| Timestamp representation | Exact restriction |
+| --- | --- |
+| Last index tag: the ordering key | Intersect existing key bounds with the time interval. |
+| Index prefix: a series entity | Filter resolved series by its timestamp entity value. |
+| Ordinary stored SIDX tag | Apply the time matcher only to partially covered or unknown-range parts. |
+
+An empty key intersection or empty post-filter series set must return an empty
+result, not an invalid SIDX request or the fallback series ID `1`.
+
+### 2. Classify each part before loading timestamp columns
+
+For query interval Q and trusted part timestamp envelope P:
+
+| Relationship | Action |
+| --- | --- |
+| Q and P are disjoint | Skip the part. |
+| Q completely contains P | Scan without the implicit row time predicate. |
+| Q intersects but does not completely contain P | Apply exact row time filtering. |
+| P is missing, incomplete, or not trustworthy | Apply exact row time filtering; never infer coverage. |
+
+For inclusive bounds, full coverage means `queryMin <= partMin` and
+`partMax <= queryMax`. Respect exclusive query endpoints in internal callers.
+The reverse containment (part contains query) does NOT allow bypassing the filter.
+
+Make this decision per part, not once for the whole request. One query may fully
+cover interior parts and only partially cover boundary parts. Use the part
+metadata available at block-cursor construction before loading tag data
+(`banyand/internal/sidx/query.go:582-590`, `sidx.go:542-559`). Classify against
+immutable part metadata during block-cursor construction, not per row. Caching
+request variants across a part's blocks is a potential follow-up if profiling
+demonstrates a benefit.
+
+Keep the implicit time predicate and its extra projection dependency separate
+from the original user predicate/projection in the internal SIDX request. Prepare
+immutable base and time-filtered variants. Covered parts use the base variant;
+partial/unknown parts use the time-filtered variant. Do not mutate the shared
+request or projection maps from concurrent block workers. Apply this consistently
+to synchronous and streaming SIDX cursor loading where the new filter is used.
+
+On the covered path, do not add or decode the timestamp column solely for the
+implicit time check. Still load it if the user projection or another predicate
+requires it. Retain every user predicate, including explicit timestamp criteria:
+coverage eliminates only the implicit TimeRange predicate. Preserve existing
+empty-projection semantics rather than assuming an empty tag map means no I/O.
+
+Segment-wide bounds written today are conservative: a full-segment query can use
+the bypass, but a narrow query must filter rows. Tighter actual-row part bounds
+could expand the fast path later without being required for this fix.
+
+Metadata correctness is a prerequisite for both skipping and bypassing. In
+particular, merging a known-range part with an unknown-range part must preserve
+an unknown envelope unless a trusted encompassing segment envelope is available.
+Audit `sidx/merge.go:124-143`, which currently aggregates non-nil bounds, and test
+mixed legacy/new metadata rather than assuming a non-nil aggregate covers all rows.
+
+### 3. Add a small timestamp matcher for partially covered parts
+
+Implement a trace-owned `model.TagFilterMatcher` decorator. Look up the schema's
+timestamp tag by name, check its typed value against TimeRange, then delegate to
+the original matcher if present. Retain the original decoder when wrapping one;
+otherwise use the trace decoder. No user criteria is a supported case.
+
+Compose as `time AND (original predicate)`, preserving all original OR grouping.
+Use exact TimeRange membership; null or wrong-type values must not accidentally
+match. Missing timestamps that are actually represented as keys/entities must
+take their corresponding route above, not be mistaken for null stored tags.
+
+For the time-filtered variant, clone the SIDX projection, deduplicate its names,
+and append the timestamp tag.
+Do not modify the caller's projection, logical result schema, or payload projection.
+SIDX loads tags and constructs matcher inputs from projection names, so merely
+adding a matcher is insufficient when the timestamp was not requested.
+
+The existing `sidx.blockCursorBuilder.processWithFilter` calls the matcher before
+`appendElement` marks a payload seen (`sidx.go:370-397,473-480`). Reuse this point.
+Post-response filtering is too late: an invalid row may already have suppressed
+another qualifying row of the same trace or supplied the wrong ordering key.
+
+Keep this matcher allocation-light and immutable: precompute the timestamp name
+and bounds once, with no per-row schema lookup or mutation of shared requests.
+Do not introduce new matcher errors without addressing SIDX's existing behavior
+of logging a matcher error and dropping that block rather than propagating it.
+
+### 4. Resolve composite-index entities correctly
+
+`processIndexRules` removes every index-rule tag from stored SIDX tags
+(`write_standalone.go:315-330`), not just the ordering key. A timestamp in the index
+prefix therefore needs series filtering, not a stored-tag matcher.
+
+There is an existing layout hazard: `pkg/query/logical/trace/schema.go:27-32`
+derives entities from the first rule, rather than necessarily the selected rule.
+Do not blindly index `seriesToEntity` using another rule's positions. Derive the
+query's entity layout from the selected rule before building entity constraints
+and resolving series, and use that same layout for timestamp extraction. Keep
+layout identity explicit in the internal handoff if necessary. Test a selected
+rule that is not first. Missing or inconsistent layout metadata must produce a
+clear planning/request error rather than an unfiltered fallback.
+
+For the ordinary duration index this requires no write-path or storage-format
+change: the timestamp is already stored as a tag. Composite timestamp entities
+are recoverable through their series metadata; no reindex is inherently required.
+
+## Adjacent correctness finding: descending deduplication
+
+Source inspection found a separate ordering hazard. SIDX's block builder scans
+ascending physical keys and deduplicates trace payloads before descending cursor
+traversal is selected (`sidx.go:379-397,504-519`, `query.go:585-590`). Multiple
+qualifying rows of the same trace in one block can therefore retain the minimum
+duration even for DESC.
+
+This is not the cause of the time leak, and the time fix must not be represented
+as repairing it automatically. Add an independent regression. For complete
+ordering correctness, retain the direction-correct qualifying representative per
+payload, while preserving ascending cursor storage and aligned data/tag arrays;
+alternatively defer deduplication to the ordered merge, with measured memory and
+batching costs. Treat this as a separate, independently testable change rather
+than expanding the timestamp matcher into a deduplication rewrite.
+
+## Regression plan
+
+Use a deterministic fixture that forces mixed timestamps into the same block and
+part. Wait for data visibility explicitly; do not depend on sleeps or accidental
+flush boundaries. Distinct traces with durations unrelated to timestamps should
+provide the basic membership oracle.
+
+1. Original empty interval within a populated segment; timestamp and duration
+   ordering both return zero.
+2. Before/begin/inside/end/after timestamps in one part. Public millisecond
+   endpoints, plus internal nanosecond/exclusive-boundary unit tests.
+3. Default timestamp order, explicitly named timestamp index, and differently
+   named duration indexes; ASC and DESC; duration key restrictions still applied.
+4. No criteria, AND/OR criteria, and an existing timestamp criterion. An outside
+   row must never satisfy a user OR branch without satisfying the global window.
+5. Projection excludes timestamp, includes it, or is empty. Assert no mutation or
+   unrequested response fields; repeated requests must behave identically.
+6. Same trace with an outside high-ranked row and an inside lower-ranked row.
+   Outside rows cannot suppress inside rows or supply their ordering keys.
+7. Several invalid rows before valid ones, small LIMIT, nonzero OFFSET, multiple
+   batches/parts/shards. Assert exact IDs and keys, not just counts.
+8. Timestamp as a composite entity; selected rule not first; no surviving series.
+9. Parts lacking timestamp metadata; memory, flushed/reopened, and merged parts.
+10. Legacy/vectorized execution and standalone/distributed ingestion/query parity.
+11. Complete-trace sibling spans and explicit trace-ID lookup compatibility.
+12. Independent same-trace/multiple-inside-duration test for the DESC dedup hazard.
+13. Full part coverage bypasses the implicit matcher, while partial coverage and
+    unknown bounds invoke it. Test a single request mixing covered, partial, and
+    disjoint parts; all rows/results must match an always-filtered reference.
+14. Covered parts retain user predicates and requested timestamp values. Instrument
+    matcher calls and column loading to prove no extra implicit timestamp work
+    occurs on the bypass path; verify shared projections remain unchanged.
+15. Known/unknown metadata merged together cannot incorrectly prove disjointness
+    or full coverage. Include exclusive-boundary containment cases.
+
+Use request-builder unit tests for restriction/projection behavior, SIDX-level
+tests for same-block witness handling, and integration tests for API results.
+Assert the same unpaginated membership across sort modes; assert each mode's
+ordering separately. Cover error/cancellation cleanup if builder signatures change.
+
+## Required benchmark: part scans with and without timestamp filtering
+
+`BenchmarkSIDXPartScanTimestampFilter` is implemented in
+`banyand/trace/query_time_benchmark_test.go`, where it can invoke the actual
+trace-owned timestamp matcher through public SIDX APIs without an import cycle.
+It benchmarks part/block loading and filtering, not only the timestamp comparison.
+This benchmark is part of implementation acceptance, not an optional follow-up.
+
+### Apples-to-apples full-coverage comparison
+
+Use the same immutable duration-keyed part, query bounds, key range, batch size,
+ordering, and response projection for each variant. Choose a query that fully
+covers the part so all variants must return identical IDs, keys, and row counts:
+
+| Variant | Implicit timestamp predicate | Extra timestamp column work |
+| --- | --- | --- |
+| `NoTimeFilter` | Disabled in the benchmark baseline | None unless already requested |
+| `ForcedTimeFilter` | Applied to every row despite full coverage | Load/decode timestamp for filtering |
+| `AutoCoverageBypass` | Production part-coverage decision bypasses it | Same as the baseline |
+
+Keep forced filtering and filter disabling confined to the benchmark harness;
+do not introduce a public configuration switch. The forced variant must exercise
+the real matcher/projection path, not a synthetic equivalent predicate.
+
+Run two projection cases: timestamp omitted, and timestamp already required by
+the base request. The first measures the combined column-loading, decoding, and
+predicate cost; the second holds the required columns constant and measures the
+incremental filter-path cost. Also cover no existing predicate versus a fixed
+existing tag predicate, verifying that bypass preserves the latter.
+
+### Partial-coverage and mixed-part workloads
+
+Add partial-overlap cases with deterministic 0%, 10%, 50%, and 100% matching rows.
+The 0% and 100% cases can use conservative part envelopes wider than the actual
+row timestamps. Compare production automatic filtering against forced filtering;
+both must produce identical results. Do not present an unfiltered partial scan
+as a correct competing implementation: its output cardinality and semantics differ.
+
+Include a multi-part case with fully covered interior parts, partially covered
+boundary parts, and disjoint parts. Compare selective filtering against always
+filtering all overlapping parts. Add unknown-bound parts to exercise the safe
+fallback. Hold candidate parts and the dataset fixed across paired variants.
+
+### Fixture, measurement, and reporting
+
+- Use fixed-seed timestamps independent of duration keys and unique trace IDs for
+  the primary benchmark, avoiding deduplication/selectivity confounders. Exercise
+  ASC and DESC, small and large multi-block parts (for example 10K and 100K rows),
+  and both in-memory and flushed/reopened parts.
+- Construct, flush, and publish parts before timing. Keep the snapshot stable;
+  exclude ingestion, fixture generation, and background merges from measured work.
+- Drain each scan completely and release results/resources within each iteration.
+  Do not use LIMIT or stop after the first result for the full-scan comparison.
+- Validate result equivalence and fast-path matcher/column-loading counters in
+  untimed checks. Avoid a per-row atomic instrumentation cost in timed scans.
+- Report `ns/op`, `B/op`, `allocs/op`, and input rows/second. Record output counts
+  separately so selective workloads cannot appear faster merely by returning fewer
+  rows. If reporting bytes read/decoded, distinguish logical column bytes from
+  physical disk I/O; do not label warmed filesystem-cache runs as cold-storage tests.
+- Run repeated samples on the same machine with fixed Go version and GOMAXPROCS.
+  Use statistical comparisons, not a brittle single-run timing assertion in CI.
+
+Suggested command after implementation and normal test-artifact setup:
+
+```sh
+GOMAXPROCS=2 go test ./banyand/trace -run '^$' \
+  -bench '^BenchmarkSIDXPartScanTimestampFilter$' -benchmem -count=10
+```
+
+Include the benchmark results in the implementation report. The coverage-bypass
+case should remain close to the no-filter baseline, and its savings relative to
+forced filtering must be measured rather than assumed. If metadata checks or
+request/projection handling cause a material regression, investigate before
+acceptance. Initial measurements and the implemented workload coverage are below.
+
+## Delivery and validation
+
+Implement and validate the exact-filter fix before optimizing timestamp metadata.
+Add focused tests in `banyand/trace`, `pkg/query/logical/trace`, and
+`banyand/internal/sidx`; replace/promote the ad-hoc integration reproduction with
+maintained fixtures without weakening its assertion. Exercise the existing
+standalone and distributed trace suites, then focused race tests and repository
+format/lint checks. Compare narrow-window duration-query allocations and latency
+with and without a user predicate; timestamp-key queries should retain their
+key-range fast path without an unnecessary tag decode.
+
+No public API, on-disk encoding, or configuration switch is proposed. Add a
+release note explaining corrected non-timestamp ordered search results. A
+bounds-only patch, response-side filtering, or time values substituted into
+duration key bounds does not satisfy acceptance.
+
+## Implementation and validation record
+
+The implementation adds a separate implicit time-filter request variant, exact
+timestamp-tag matching, timestamp-key intersection, selected-index timestamp-entity
+filtering, and conservative propagation of unknown timestamp envelopes through
+merge. Empty half-open intervals are handled explicitly. User predicates and
+response projections remain separate from the extra timestamp dependency.
+
+Maintained integration cases now live in `test/cases/trace/trace.go`, shared by
+standalone/distributed and legacy/vectorized suites. The empty-gap regression
+fails against baseline production code and passes with the fix. A narrow-window
+case selects the qualifying trace while retaining its out-of-window sibling spans.
+The original user reproduction file and `sortedMIterator` remain untouched.
+
+Validation completed:
+
+- Full SIDX and logical trace package tests, including race runs.
+- Focused trace query, vectorized, timestamp-matcher/entity, and streaming tests,
+  including a race run.
+- Existing standalone and distributed trace integration suites.
+- New shared integration regressions in both standalone and distributed modes.
+- Original `TestIssue14058LatencyOrderIgnoresTimeRange` reproduction.
+- Pinned golangci-lint v1.64.8 for SIDX, trace, logical trace, and shared trace cases;
+  gofumpt and `git diff --check`.
+- The mixed known/unknown merge regression independently fails against the original
+  merge implementation and passes with conservative merged bounds.
+
+Green integration runs used `/tmp/trace-time-range-design/overlay.json` only for
+missing generated build artifacts/UI embedding, never to replace the query fix.
+Generated mock artifacts were also materialized locally for lint's parser.
+
+### Recorded benchmark samples
+
+Command: `GOMAXPROCS=2 go test ./banyand/trace -run '^$'
+-bench '^BenchmarkSIDXPartScanTimestampFilter$' -benchmem -benchtime=100ms -count=3`.
+Linux/amd64, AMD EPYC 7B13, Go 1.25.13. These are warm in-process scans, not
+cold-storage measurements. Medians from three short samples, no existing user
+predicate, timestamp omitted from the response projection:
+
+| Fixture | Variant | ms/op | B/op | allocs/op |
+| --- | --- | ---: | ---: | ---: |
+| Memory, 10K rows, ASC | No time filter | 7.975 | 7,998,063 | 40,829 |
+| Memory, 10K rows, ASC | Forced exact filter | 14.114 | 13,358,037 | 130,876 |
+| Memory, 10K rows, ASC | Coverage bypass | 8.226 | 8,409,034 | 40,848 |
+| Flushed/reopened, 100K rows, ASC | No time filter | 88.688 | 72,964,864 | 407,153 |
+| Flushed/reopened, 100K rows, ASC | Forced exact filter | 133.400 | 124,216,872 | 1,307,356 |
+| Flushed/reopened, 100K rows, ASC | Coverage bypass | 86.651 | 73,258,720 | 407,182 |
+
+The measured bypass is close to the unfiltered baseline, with substantially less
+work than forced filtering. Treat these samples as an initial comparison, not a
+statistical performance guarantee. Full output:
+`/tmp/trace-time-range-final-benchmark.log`.
+
+The benchmark also covers projected timestamps, an existing service predicate,
+10K flushed/reopened DESC scans, and partial-overlap selectivity of 0%, 10%, 50%,
+and 100%, comparing forced and automatic exact filtering with identical IDs/keys.
+Mixed-part performance workloads remain an extension; unknown-envelope correctness
+is covered by tests. The independent descending same-trace deduplication issue
+described above is not changed by this patch.
diff --git a/banyand/internal/sidx/interfaces.go b/banyand/internal/sidx/interfaces.go
index bafeb9415..790ab1a5b 100644
--- a/banyand/internal/sidx/interfaces.go
+++ b/banyand/internal/sidx/interfaces.go
@@ -110,8 +110,15 @@ type WriteRequest struct {
 
 // QueryRequest specifies parameters for a query operation, following StreamQueryOptions pattern.
 type QueryRequest struct {
-	Filter         index.Filter
-	TagFilter      model.TagFilterMatcher
+	Filter    index.Filter
+	TagFilter model.TagFilterMatcher
+	// TimeTagFilter combines exact timestamp eligibility AND TagFilter. It replaces
+	// TagFilter only for partial or unknown timestamp-envelope parts.
+	TimeTagFilter model.TagFilterMatcher
+	// TimeTagName is an internal filter-only column dependency; it is never added
+	// to response projections.
+	TimeTagName    string
+	FilterTagNames []string
 	Order          *index.OrderBy
 	MinKey         *int64
 	MaxKey         *int64
@@ -121,6 +128,10 @@ type QueryRequest struct {
 	SeriesIDs      []common.SeriesID
 	TagProjection  []model.TagProjection
 	MaxBatchSize   int
+	// TimeIncludeStart and TimeIncludeEnd are used only when proving full-part
+	// coverage; exact TimeTagFilter membership remains authoritative.
+	TimeIncludeStart bool
+	TimeIncludeEnd   bool
 }
 
 // ScanProgressFunc is a callback for reporting scan progress.
@@ -369,6 +380,12 @@ func (sqr ScanQueryRequest) Validate() error {
 func (qr *QueryRequest) Reset() {
 	qr.SeriesIDs = nil
 	qr.Filter = nil
+	qr.TagFilter = nil
+	qr.TimeTagFilter = nil
+	qr.TimeTagName = ""
+	qr.TimeIncludeStart = false
+	qr.TimeIncludeEnd = false
+	qr.FilterTagNames = nil
 	qr.Order = nil
 	qr.TagProjection = nil
 	qr.MaxBatchSize = 0
@@ -388,6 +405,12 @@ func (qr *QueryRequest) CopyFrom(other *QueryRequest) {
 	}
 
 	qr.Filter = other.Filter
+	qr.TagFilter = other.TagFilter
+	qr.TimeTagFilter = other.TimeTagFilter
+	qr.TimeTagName = other.TimeTagName
+	qr.TimeIncludeStart = other.TimeIncludeStart
+	qr.TimeIncludeEnd = other.TimeIncludeEnd
+	qr.FilterTagNames = append(qr.FilterTagNames[:0], other.FilterTagNames...)
 	qr.Order = other.Order
 
 	if other.TagProjection != nil {
diff --git a/banyand/internal/sidx/merge.go b/banyand/internal/sidx/merge.go
index 4d1438aa4..c3b866788 100644
--- a/banyand/internal/sidx/merge.go
+++ b/banyand/internal/sidx/merge.go
@@ -120,25 +120,25 @@ func (s *sidx) mergeParts(fileSystem fs.FileSystem, closeCh <-chan struct{}, par
 	if err != nil {
 		return nil, err
 	}
-	// Aggregate optional timestamp range from merged parts
+	// A merged envelope is trustworthy only when every input supplies both bounds.
+	// Aggregating known inputs while silently ignoring a legacy unknown part could make
+	// the resulting metadata prove a disjoint or fully-covered range incorrectly.
 	var minVal, maxVal int64
-	var hasMinTS, hasMaxTS bool
+	hasTimestampEnvelope := len(parts) > 0
 	for i := range parts {
-		p := parts[i].p.partMetadata
-		if p.MinTimestamp != nil {
-			if !hasMinTS || *p.MinTimestamp < minVal {
-				minVal = *p.MinTimestamp
-				hasMinTS = true
-			}
+		partMetadata := parts[i].p.partMetadata
+		if partMetadata == nil || partMetadata.MinTimestamp == nil || partMetadata.MaxTimestamp == nil {
+			hasTimestampEnvelope = false
+			break
 		}
-		if p.MaxTimestamp != nil {
-			if !hasMaxTS || *p.MaxTimestamp > maxVal {
-				maxVal = *p.MaxTimestamp
-				hasMaxTS = true
-			}
+		if i == 0 || *partMetadata.MinTimestamp < minVal {
+			minVal = *partMetadata.MinTimestamp
+		}
+		if i == 0 || *partMetadata.MaxTimestamp > maxVal {
+			maxVal = *partMetadata.MaxTimestamp
 		}
 	}
-	if hasMinTS && hasMaxTS {
+	if hasTimestampEnvelope {
 		pm.MinTimestamp = &minVal
 		pm.MaxTimestamp = &maxVal
 	}
diff --git a/banyand/internal/sidx/query.go b/banyand/internal/sidx/query.go
index 3519d662e..69867edb9 100644
--- a/banyand/internal/sidx/query.go
+++ b/banyand/internal/sidx/query.go
@@ -537,6 +537,54 @@ func determineTagsToLoad(req QueryRequest) map[string]struct{} {
 	return tagsToLoad
 }
 
+// requestForPart returns immutable request and tag-loading variants for a part. Timestamp
+// envelopes can only prove that every row is in range; any partial or unknown envelope
+// must keep the exact row predicate.
+func requestForPart(req QueryRequest, tagsToLoad map[string]struct{}, p *part) (QueryRequest, map[string]struct{}) {
+	if !partNeedsTimeFilter(req, p) {
+		return req, tagsToLoad
+	}
+
+	effectiveReq := req
+	effectiveReq.TagFilter = req.TimeTagFilter
+	effectiveReq.FilterTagNames = append([]string(nil), req.FilterTagNames...)
+	if req.TimeTagName != "" {
+		effectiveReq.FilterTagNames = append(effectiveReq.FilterTagNames, req.TimeTagName)
+	}
+	// An empty set deliberately means "load all tags". Preserve that behavior instead
+	// of turning an empty user projection into a timestamp-only projection.
+	if len(tagsToLoad) == 0 || req.TimeTagName == "" {
+		return effectiveReq, tagsToLoad
+	}
+	effectiveTagsToLoad := make(map[string]struct{}, len(tagsToLoad)+1)
+	for tagName := range tagsToLoad {
+		effectiveTagsToLoad[tagName] = struct{}{}
+	}
+	effectiveTagsToLoad[req.TimeTagName] = struct{}{}
+	return effectiveReq, effectiveTagsToLoad
+}
+
+func partNeedsTimeFilter(req QueryRequest, p *part) bool {
+	if req.TimeTagFilter == nil {
+		return false
+	}
+	if req.MinTimestamp == nil || req.MaxTimestamp == nil || p == nil || p.partMetadata == nil {
+		return true
+	}
+	partMin := p.partMetadata.MinTimestamp
+	partMax := p.partMetadata.MaxTimestamp
+	if partMin == nil || partMax == nil {
+		return true
+	}
+	if *req.MinTimestamp > *partMin || *partMax > *req.MaxTimestamp {
+		return true
+	}
+	if *req.MinTimestamp == *partMin && !req.TimeIncludeStart {
+		return true
+	}
+	return *req.MaxTimestamp == *partMax && !req.TimeIncludeEnd
+}
+
 func (s *sidx) buildCursorsForBatch(
 	ctx context.Context,
 	batch *blockScanResultBatch,
@@ -579,10 +627,11 @@ func (s *sidx) buildCursorsForBatch(
 						return
 					}
 
+					effectiveReq, effectiveTagsToLoad := requestForPart(req, tagsToLoad, bsResult.p)
 					bc := generateBlockCursor()
-					bc.init(bsResult.p, &bsResult.bm, req)
+					bc.init(bsResult.p, &bsResult.bm, effectiveReq)
 
-					if s.loadBlockCursor(bc, tmpBlock, bsResult, tagsToLoad, req, s.pm, metrics) {
+					if s.loadBlockCursor(bc, tmpBlock, bsResult, effectiveTagsToLoad, effectiveReq, s.pm, metrics) {
 						if asc {
 							bc.idx = 0
 						} else {
@@ -658,9 +707,10 @@ func (s *sidx) buildCursorsForBatchSync(
 			}
 			return nil, ctxErr
 		}
+		effectiveReq, effectiveTagsToLoad := requestForPart(req, tagsToLoad, bsResult.p)
 		bc := generateBlockCursor()
-		bc.init(bsResult.p, &bsResult.bm, req)
-		if s.loadBlockCursor(bc, tmpBlock, bsResult, tagsToLoad, req, s.pm, metrics) {
+		bc.init(bsResult.p, &bsResult.bm, effectiveReq)
+		if s.loadBlockCursor(bc, tmpBlock, bsResult, effectiveTagsToLoad, effectiveReq, s.pm, metrics) {
 			if asc {
 				bc.idx = 0
 			} else {
diff --git a/banyand/internal/sidx/sidx.go b/banyand/internal/sidx/sidx.go
index 4b2340100..5b179fdd0 100644
--- a/banyand/internal/sidx/sidx.go
+++ b/banyand/internal/sidx/sidx.go
@@ -374,7 +374,7 @@ func (b *blockCursorBuilder) processWithFilter(req QueryRequest, log *logger.Log
 
 	tags := make([]*modelv1.Tag, 0, len(b.block.tags))
 	decoder := req.TagFilter.GetDecoder()
-	orderedTagNames := b.orderedTagNamesForFilter(req.TagProjection)
+	orderedTagNames := b.orderedTagNamesForFilter(req.TagProjection, req.FilterTagNames)
 
 	for i := 0; i < len(b.block.userKeys); i++ {
 		dataBytes := b.block.data[i]
@@ -441,24 +441,34 @@ func (b *blockCursorBuilder) collectTagsForFilter(
 	return buf
 }
 
-func (b *blockCursorBuilder) orderedTagNamesForFilter(projections []model.TagProjection) []string {
+func (b *blockCursorBuilder) orderedTagNamesForFilter(projections []model.TagProjection, filterTagNames ...[]string) []string {
+	var extraTagNames []string
+	if len(filterTagNames) > 0 {
+		extraTagNames = filterTagNames[0]
+	}
 	// Preserve projection order for reproducible matcher inputs and diagnostics.
 	// Logical matchers resolve values by tag key rather than relying on this order.
 	if len(projections) > 0 {
 		seenTagNames := make(map[string]struct{}, len(b.block.tags))
 		tagNames := make([]string, 0, len(b.block.tags))
+		appendTagName := func(tagName string) {
+			if _, exists := seenTagNames[tagName]; exists {
+				return
+			}
+			if _, exists := b.block.tags[tagName]; !exists {
+				return
+			}
+			tagNames = append(tagNames, tagName)
+			seenTagNames[tagName] = struct{}{}
+		}
 		for _, proj := range projections {
 			for _, tagName := range proj.Names {
-				if _, exists := seenTagNames[tagName]; exists {
-					continue
-				}
-				if _, exists := b.block.tags[tagName]; !exists {
-					continue
-				}
-				tagNames = append(tagNames, tagName)
-				seenTagNames[tagName] = struct{}{}
+				appendTagName(tagName)
 			}
 		}
+		for _, tagName := range extraTagNames {
+			appendTagName(tagName)
+		}
 		return tagNames
 	}
 
diff --git a/banyand/internal/sidx/timestamp_test.go b/banyand/internal/sidx/timestamp_test.go
index b9b8b1731..c154f6745 100644
--- a/banyand/internal/sidx/timestamp_test.go
+++ b/banyand/internal/sidx/timestamp_test.go
@@ -27,9 +27,11 @@ import (
 	"github.com/stretchr/testify/require"
 
 	"github.com/apache/skywalking-banyandb/api/common"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
 	"github.com/apache/skywalking-banyandb/banyand/observability"
 	"github.com/apache/skywalking-banyandb/banyand/protector"
 	"github.com/apache/skywalking-banyandb/pkg/fs"
+	pbv1 "github.com/apache/skywalking-banyandb/pkg/pb/v1"
 )
 
 // writeTestDataWithTimeRange writes test data with optional min/max timestamps (back-compat: nil means no timestamps).
@@ -396,3 +398,141 @@ func TestMerge_TimestampPropagation(t *testing.T) {
 		assert.Equal(t, int64(300), *m.MaxTimestamp)
 	})
 }
+
+func TestRequestForPartUsesTimestampFilterOnlyWhenNeeded(t *testing.T) {
+	minTimestamp := int64(100)
+	maxTimestamp := int64(200)
+	timeFilter := &mockTagFilterMatcher{}
+	req := QueryRequest{
+		MinTimestamp:  &minTimestamp,
+		MaxTimestamp:  &maxTimestamp,
+		TagFilter:     nil,
+		TimeTagFilter: timeFilter,
+		TimeTagName:   "timestamp",
+	}
+	baseTags := map[string]struct{}{"service": {}}
+
+	coveredMin, coveredMax := int64(120), int64(180)
+	coveredPart := &part{partMetadata: &partMetadata{MinTimestamp: &coveredMin, MaxTimestamp: &coveredMax}}
+	coveredRequest, coveredTags := requestForPart(req, baseTags, coveredPart)
+	assert.Nil(t, coveredRequest.TagFilter)
+	assert.Equal(t, baseTags, coveredTags)
+
+	partialMin, partialMax := int64(80), int64(180)
+	partialPart := &part{partMetadata: &partMetadata{MinTimestamp: &partialMin, MaxTimestamp: &partialMax}}
+	partialRequest, partialTags := requestForPart(req, baseTags, partialPart)
+	assert.Same(t, timeFilter, partialRequest.TagFilter)
+	assert.Contains(t, partialTags, "timestamp")
+	assert.NotContains(t, baseTags, "timestamp")
+
+	unknownPart := &part{partMetadata: &partMetadata{}}
+	unknownRequest, _ := requestForPart(req, baseTags, unknownPart)
+	assert.Same(t, timeFilter, unknownRequest.TagFilter)
+}
+
+func TestTimestampFilterPartVariantsPreserveBaseFilterAndNilProjection(t *testing.T) {
+	sidx := createTestSIDX(t)
+	defer func() {
+		assert.NoError(t, sidx.Close())
+	}()
+
+	partMin, partMax := int64(0), int64(20)
+	requests := []WriteRequest{createTestWriteRequest(1, 1, "trace", Tag{Name: "other", Value: []byte("present"), ValueType: pbv1.ValueTypeStr})}
+	writeTestDataWithTimeRange(t, sidx, requests, 1, 1, &partMin, &partMax)
+	waitForIntroducerLoop()
+
+	queryMin, queryMax := int64(0), int64(20)
+	baseFilter := &mockTagFilterMatcher{decoder: testTagValueDecoder, matchFunc: func(_ []*modelv1.Tag) (bool, error) { return false, nil }}
+	coveredResponses, queryErr := sidx.QuerySync(context.Background(), QueryRequest{
+		SeriesIDs:        []common.SeriesID{1},
+		TagFilter:        baseFilter,
+		TimeTagFilter:    &mockTagFilterMatcher{},
+		TimeTagName:      "timestamp",
+		MinTimestamp:     &queryMin,
+		MaxTimestamp:     &queryMax,
+		TimeIncludeStart: true,
+		TimeIncludeEnd:   true,
+	})
+	require.NoError(t, queryErr)
+	require.Empty(t, coveredResponses, "coverage bypass must retain the original predicate")
+
+	// Widening the conservative envelope makes the same row partial. A nil projection
+	// retains its historic all-tags behavior so the time matcher can still inspect
+	// non-projected delegate inputs.
+	partialMin := int64(-1)
+	memPart, convertErr := sidx.ConvertToMemPart(requests, 2, &partialMin, &partMax)
+	require.NoError(t, convertErr)
+	sidx.IntroduceMemPart(2, memPart)
+	waitForIntroducerLoop()
+	seenOtherTag := false
+	partialResponses, queryErr := sidx.QuerySync(context.Background(), QueryRequest{
+		SeriesIDs: []common.SeriesID{1},
+		TimeTagFilter: &mockTagFilterMatcher{decoder: testTagValueDecoder, matchFunc: func(tags []*modelv1.Tag) (bool, error) {
+			for _, tag := range tags {
+				if tag.GetKey() == "other" {
+					seenOtherTag = true
+				}
+			}
+			return true, nil
+		}},
+		TimeTagName:      "timestamp",
+		MinTimestamp:     &queryMin,
+		MaxTimestamp:     &queryMax,
+		TimeIncludeStart: true,
+		TimeIncludeEnd:   true,
+	})
+	require.NoError(t, queryErr)
+	require.NotEmpty(t, partialResponses)
+	require.True(t, seenOtherTag)
+}
+
+func TestMergeUnknownTimestampEnvelopeCannotSkipOrBypassFiltering(t *testing.T) {
+	instance := createTestSIDX(t)
+	t.Cleanup(func() {
+		assert.NoError(t, instance.Close())
+	})
+	knownMin, knownMax := int64(100), int64(200)
+	writeTestDataWithTimeRange(t, instance, []WriteRequest{createTestWriteRequest(1, 1, "known")}, 1, 1, &knownMin, &knownMax)
+	writeTestDataWithTimeRange(t, instance, []WriteRequest{createTestWriteRequest(1, 2, "unknown")}, 1, 2, nil, nil)
+	partIDs := map[uint64]struct{}{1: {}, 2: {}}
+	flushIntroduction, flushErr := instance.Flush(partIDs)
+	require.NoError(t, flushErr)
+	require.NotNil(t, flushIntroduction)
+	instance.IntroduceFlushed(flushIntroduction)
+	flushIntroduction.Release()
+	mergeIntroduction, mergeErr := instance.Merge(nil, partIDs, 10, nil)
+	require.NoError(t, mergeErr)
+	require.NotNil(t, mergeIntroduction)
+	instance.IntroduceMerged(mergeIntroduction)()
+
+	queryMin, queryMax := int64(300), int64(400)
+	request := QueryRequest{
+		SeriesIDs:    []common.SeriesID{1},
+		MinTimestamp: &queryMin,
+		MaxTimestamp: &queryMax,
+	}
+	responses, queryErr := instance.QuerySync(context.Background(), request)
+	require.NoError(t, queryErr)
+	var values []string
+	for _, response := range responses {
+		for _, value := range response.Data {
+			values = append(values, string(value))
+		}
+	}
+	require.ElementsMatch(t, []string{"known", "unknown"}, values, "unknown merged bounds cannot prove disjointness")
+
+	request.MinTimestamp, request.MaxTimestamp = &knownMin, &knownMax
+	request.TimeIncludeStart, request.TimeIncludeEnd = true, true
+	filterCalls := 0
+	request.TimeTagFilter = &mockTagFilterMatcher{
+		decoder: testTagValueDecoder,
+		matchFunc: func(_ []*modelv1.Tag) (bool, error) {
+			filterCalls++
+			return false, nil
+		},
+	}
+	responses, queryErr = instance.QuerySync(context.Background(), request)
+	require.NoError(t, queryErr)
+	require.Empty(t, responses)
+	require.Equal(t, 2, filterCalls, "known input bounds cannot prove coverage of the unknown input")
+}
diff --git a/banyand/trace/query.go b/banyand/trace/query.go
index 01020fbeb..e2bf39b10 100644
--- a/banyand/trace/query.go
+++ b/banyand/trace/query.go
@@ -21,6 +21,7 @@ import (
 	"context"
 	"fmt"
 	"maps"
+	"math"
 	"sort"
 	"time"
 
@@ -28,6 +29,7 @@ import (
 	"google.golang.org/protobuf/types/known/timestamppb"
 
 	"github.com/apache/skywalking-banyandb/api/common"
+	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
 	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
 	"github.com/apache/skywalking-banyandb/banyand/internal/sidx"
 	"github.com/apache/skywalking-banyandb/banyand/internal/storage"
@@ -38,6 +40,7 @@ import (
 	"github.com/apache/skywalking-banyandb/pkg/pool"
 	"github.com/apache/skywalking-banyandb/pkg/query/model"
 	vtrace "github.com/apache/skywalking-banyandb/pkg/query/vectorized/trace"
+	"github.com/apache/skywalking-banyandb/pkg/timestamp"
 )
 
 var traceQueryResultTracker = pool.RegisterTracker("trace.queryResult")
@@ -49,6 +52,57 @@ const (
 
 var nilResult = model.TraceQueryResult(nil)
 
+type timestampTagFilterMatcher struct {
+	delegate  model.TagFilterMatcher
+	decoder   model.TagValueDecoder
+	timeRange timestamp.TimeRange
+	tagName   string
+	empty     bool
+}
+
+func newTimestampTagFilterMatcher(timeRange timestamp.TimeRange, tagName string, delegate model.TagFilterMatcher) model.TagFilterMatcher {
+	matcher := &timestampTagFilterMatcher{
+		timeRange: timeRange,
+		tagName:   tagName,
+		delegate:  delegate,
+		decoder:   mustDecodeTagValueAndArray,
+		empty:     traceTimeRangeEmpty(timeRange),
+	}
+	if delegate != nil && delegate.GetDecoder() != nil {
+		matcher.decoder = delegate.GetDecoder()
+	}
+	return matcher
+}
+
+func (ttfm *timestampTagFilterMatcher) Match(tags []*modelv1.Tag) (bool, error) {
+	if ttfm.empty {
+		return false, nil
+	}
+	for _, tag := range tags {
+		if tag.GetKey() != ttfm.tagName {
+			continue
+		}
+		timestampValue := tag.GetValue().GetTimestamp()
+		if timestampValue == nil || !ttfm.timeRange.Contains(timestampValue.AsTime().UnixNano()) {
+			return false, nil
+		}
+		if ttfm.delegate == nil {
+			return true, nil
+		}
+		return ttfm.delegate.Match(tags)
+	}
+	return false, nil
+}
+
+func (ttfm *timestampTagFilterMatcher) GetDecoder() model.TagValueDecoder {
+	return ttfm.decoder
+}
+
+func traceTimeRangeEmpty(timeRange timestamp.TimeRange) bool {
+	return timeRange.Start.After(timeRange.End) ||
+		timeRange.Start.Equal(timeRange.End) && (!timeRange.IncludeStart || !timeRange.IncludeEnd)
+}
+
 type queryOptions struct {
 	seriesToEntity map[common.SeriesID][]*modelv1.TagValue
 	schemaTagTypes map[string]pbv1.ValueType
@@ -128,7 +182,12 @@ func (t *trace) Query(ctx context.Context, tqo model.TraceQueryOptions) (model.T
 
 	tables := collectTables(segments)
 
-	sidxInstances, sidxQueryRequest, useSIDXStreaming := t.prepareSIDXStreaming(storageTQO, qo, tables)
+	sidxInstances, sidxQueryRequest, useSIDXStreaming, prepareErr := t.prepareSIDXStreaming(storageTQO, qo, tables)
+	if prepareErr != nil {
+		// Assign the outer error so the deferred result cleanup releases segments.
+		err = prepareErr
+		return nil, err
+	}
 	if len(qo.traceIDs) == 0 && !useSIDXStreaming {
 		result.Release()
 		return nilResult, nil
@@ -270,9 +329,12 @@ func (t *trace) prepareSIDXStreaming(
 	tqo model.TraceQueryOptions,
 	qo queryOptions,
 	tables []*tsTable,
-) ([]sidx.SIDX, sidx.QueryRequest, bool) {
+) ([]sidx.SIDX, sidx.QueryRequest, bool, error) {
 	if len(tqo.TraceIDs) > 0 || tqo.Order == nil {
-		return nil, sidx.QueryRequest{}, false
+		return nil, sidx.QueryRequest{}, false, nil
+	}
+	if traceTimeRangeEmpty(*tqo.TimeRange) {
+		return nil, sidx.QueryRequest{}, false, nil
 	}
 
 	sidxName := "default"
@@ -287,32 +349,167 @@ func (t *trace) prepareSIDXStreaming(
 		}
 	}
 	if len(sidxInstances) == 0 {
-		return nil, sidx.QueryRequest{}, false
+		return nil, sidx.QueryRequest{}, false, nil
 	}
 
-	seriesIDs := make([]common.SeriesID, 0, len(qo.seriesToEntity))
-	for seriesID := range qo.seriesToEntity {
-		seriesIDs = append(seriesIDs, seriesID)
+	selectedRule := t.selectedIndexRule(sidxName)
+	if selectedRule == nil && sidxName != "default" {
+		return nil, sidx.QueryRequest{}, false, fmt.Errorf("selected trace index %q has no schema rule", sidxName)
 	}
-	if len(seriesIDs) == 0 {
-		seriesIDs = []common.SeriesID{1}
+	timestampRepresentation := t.selectedIndexTimestampRepresentation(sidxName)
+	seriesIDs := make([]common.SeriesID, 0, len(qo.seriesToEntity))
+	if timestampRepresentation == timestampEntity {
+		var filterErr error
+		seriesIDs, filterErr = filterTimestampEntitySeries(qo.seriesToEntity, selectedRule, t.schema.GetTimestampTagName(), *tqo.TimeRange)
+		if filterErr != nil {
+			return nil, sidx.QueryRequest{}, false, filterErr
+		}
+		if len(seriesIDs) == 0 {
+			return nil, sidx.QueryRequest{}, false, nil
+		}
+	} else {
+		for seriesID := range qo.seriesToEntity {
+			seriesIDs = append(seriesIDs, seriesID)
+		}
+		if len(seriesIDs) == 0 {
+			seriesIDs = []common.SeriesID{1}
+		}
 	}
 
+	minTimestamp := tqo.TimeRange.Start.UnixNano()
+	maxTimestamp := tqo.TimeRange.End.UnixNano()
+	minKey, maxKey := tqo.MinVal, tqo.MaxVal
+	if timestampRepresentation == timestampOrderingKey {
+		if !tqo.TimeRange.IncludeStart {
+			if minTimestamp == math.MaxInt64 {
+				return nil, sidx.QueryRequest{}, false, nil
+			}
+			minTimestamp++
+		}
+		if !tqo.TimeRange.IncludeEnd {
+			if maxTimestamp == math.MinInt64 {
+				return nil, sidx.QueryRequest{}, false, nil
+			}
+			maxTimestamp--
+		}
+		if minTimestamp > maxTimestamp {
+			return nil, sidx.QueryRequest{}, false, nil
+		}
+		if minKey < minTimestamp {
+			minKey = minTimestamp
+		}
+		if maxKey > maxTimestamp {
+			maxKey = maxTimestamp
+		}
+		if minKey > maxKey {
+			return nil, sidx.QueryRequest{}, false, nil
+		}
+	}
 	req := sidx.QueryRequest{
-		Filter:         tqo.SkippingFilter,
-		TagFilter:      tqo.TagFilter,
-		Order:          tqo.Order,
-		MaxBatchSize:   tqo.MaxTraceSize,
-		MinKey:         &tqo.MinVal,
-		MaxKey:         &tqo.MaxVal,
-		SeriesIDs:      seriesIDs,
-		SchemaTagTypes: qo.schemaTagTypes,
+		Filter:           tqo.SkippingFilter,
+		TagFilter:        tqo.TagFilter,
+		Order:            tqo.Order,
+		MaxBatchSize:     tqo.MaxTraceSize,
+		MinKey:           &minKey,
+		MaxKey:           &maxKey,
+		MinTimestamp:     &minTimestamp,
+		MaxTimestamp:     &maxTimestamp,
+		TimeIncludeStart: tqo.TimeRange.IncludeStart,
+		TimeIncludeEnd:   tqo.TimeRange.IncludeEnd,
+		SeriesIDs:        seriesIDs,
+		SchemaTagTypes:   qo.schemaTagTypes,
+	}
+	if timestampRepresentation == timestampStoredTag {
+		req.TimeTagName = t.schema.GetTimestampTagName()
+		req.TimeTagFilter = newTimestampTagFilterMatcher(*tqo.TimeRange, req.TimeTagName, tqo.TagFilter)
 	}
 	if tqo.TagProjection != nil {
 		req.TagProjection = []model.TagProjection{*tqo.TagProjection}
 	}
 
-	return sidxInstances, req, true
+	return sidxInstances, req, true, nil
+}
+
+// selectedIndexRule returns the configured rule for an SIDX name.
+func (t *trace) selectedIndexRule(sidxName string) *databasev1.IndexRule {
+	for _, indexRule := range t.GetIndexRules() {
+		if indexRule.GetMetadata().GetName() == sidxName {
+			return indexRule
+		}
+	}
+	return nil
+}
+
+// filterTimestampEntitySeries applies the time range to timestamp values carried
+// by the selected index's series prefix. The logical planner derives the same
+// selected-rule layout before resolving these series.
+func filterTimestampEntitySeries(seriesToEntity map[common.SeriesID][]*modelv1.TagValue,
+	indexRule *databasev1.IndexRule, timestampTagName string, timeRange timestamp.TimeRange,
+) ([]common.SeriesID, error) {
+	if indexRule == nil {
+		return nil, fmt.Errorf("timestamp entity index rule is missing")
+	}
+	if traceTimeRangeEmpty(timeRange) {
+		return nil, nil
+	}
+	timestampPosition := -1
+	for index, tagName := range indexRule.GetTags()[:len(indexRule.GetTags())-1] {
+		if tagName == "" {
+			return nil, fmt.Errorf("timestamp entity index has an empty tag name")
+		}
+		if tagName == timestampTagName {
+			timestampPosition = index
+			break
+		}
+	}
+	if timestampPosition < 0 {
+		return nil, fmt.Errorf("timestamp entity is absent from the selected index prefix")
+	}
+	seriesIDs := make([]common.SeriesID, 0, len(seriesToEntity))
+	for seriesID, entityValues := range seriesToEntity {
+		if len(entityValues) != len(indexRule.GetTags())-1 {
+			return nil, fmt.Errorf("series %d has %d entities, selected index requires %d", seriesID, len(entityValues), len(indexRule.GetTags())-1)
+		}
+		timestampValue := entityValues[timestampPosition].GetTimestamp()
+		if timestampValue != nil && timeRange.Contains(timestampValue.AsTime().UnixNano()) {
+			seriesIDs = append(seriesIDs, seriesID)
+		}
+	}
+	return seriesIDs, nil
+}
+
+type timestampIndexRepresentation uint8
+
+const (
+	timestampOrderingKey timestampIndexRepresentation = iota
+	timestampStoredTag
+	timestampEntity
+)
+
+// selectedIndexTimestampRepresentation identifies where the selected SIDX keeps
+// timestamp. Every index-rule tag is removed from stored tags; only its final tag
+// is the ordering key.
+func (t *trace) selectedIndexTimestampRepresentation(sidxName string) timestampIndexRepresentation {
+	timestampTagName := t.schema.GetTimestampTagName()
+	for _, indexRule := range t.GetIndexRules() {
+		if indexRule.GetMetadata().GetName() != sidxName {
+			continue
+		}
+		tags := indexRule.GetTags()
+		for idx, tagName := range tags {
+			if tagName != timestampTagName {
+				continue
+			}
+			if idx == len(tags)-1 {
+				return timestampOrderingKey
+			}
+			return timestampEntity
+		}
+		return timestampStoredTag
+	}
+	// A default index is timestamp ordered by the logical planner. Unknown named
+	// indexes must not infer a stored timestamp tag and silently filter all rows.
+	return timestampOrderingKey
 }
 
 type queryResult struct {
diff --git a/banyand/trace/query_test.go b/banyand/trace/query_test.go
index 24c127973..db4f439e5 100644
--- a/banyand/trace/query_test.go
+++ b/banyand/trace/query_test.go
@@ -26,8 +26,10 @@ import (
 	"github.com/google/go-cmp/cmp"
 	"github.com/stretchr/testify/require"
 	"google.golang.org/protobuf/testing/protocmp"
+	"google.golang.org/protobuf/types/known/timestamppb"
 
 	"github.com/apache/skywalking-banyandb/api/common"
+	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
 	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
 	"github.com/apache/skywalking-banyandb/banyand/protector"
 	"github.com/apache/skywalking-banyandb/pkg/fs"
@@ -490,3 +492,95 @@ func allPartsFlushed(tst *tsTable) func() bool {
 		return true
 	}
 }
+
+func TestTimestampTagFilterMatcherHonorsRangeBeforeDelegate(t *testing.T) {
+	instant := time.Unix(0, 100)
+	matcher := newTimestampTagFilterMatcher(timestamp.NewTimeRange(instant, instant, true, true), "timestamp", nil)
+	matched, matchErr := matcher.Match([]*modelv1.Tag{{
+		Key: "timestamp",
+		Value: &modelv1.TagValue{Value: &modelv1.TagValue_Timestamp{
+			Timestamp: timestamppb.New(instant),
+		}},
+	}})
+	require.NoError(t, matchErr)
+	require.True(t, matched)
+
+	exclusiveMatcher := newTimestampTagFilterMatcher(timestamp.NewTimeRange(instant, instant, true, false), "timestamp", nil)
+	matched, matchErr = exclusiveMatcher.Match([]*modelv1.Tag{{
+		Key: "timestamp",
+		Value: &modelv1.TagValue{Value: &modelv1.TagValue_Timestamp{
+			Timestamp: timestamppb.New(instant),
+		}},
+	}})
+	require.NoError(t, matchErr)
+	require.False(t, matched)
+}
+
+func TestTimestampTagFilterMatcherDelegatesOnlyForEligibleRows(t *testing.T) {
+	start := time.Unix(0, 100)
+	delegateCalls := 0
+	delegate := &traceTestTagMatcher{match: func(_ []*modelv1.Tag) (bool, error) {
+		delegateCalls++
+		return true, nil
+	}}
+	matcher := newTimestampTagFilterMatcher(timestamp.NewInclusiveTimeRange(start, start.Add(time.Nanosecond)), "timestamp", delegate)
+	for _, testCase := range []struct {
+		name    string
+		nanos   int64
+		matched bool
+	}{
+		{name: "before", nanos: 99, matched: false},
+		{name: "start", nanos: 100, matched: true},
+		{name: "end", nanos: 101, matched: true},
+		{name: "after", nanos: 102, matched: false},
+	} {
+		t.Run(testCase.name, func(t *testing.T) {
+			matched, matchErr := matcher.Match([]*modelv1.Tag{{
+				Key: "timestamp",
+				Value: &modelv1.TagValue{Value: &modelv1.TagValue_Timestamp{
+					Timestamp: timestamppb.New(time.Unix(0, testCase.nanos)),
+				}},
+			}})
+			require.NoError(t, matchErr)
+			require.Equal(t, testCase.matched, matched)
+		})
+	}
+	require.Equal(t, 2, delegateCalls)
+}
+
+func TestFilterTimestampEntitySeries(t *testing.T) {
+	indexRule := &databasev1.IndexRule{Tags: []string{"service", "timestamp", "duration"}}
+	series := map[common.SeriesID][]*modelv1.TagValue{
+		1: {strTagValue("a"), timestampTagValue(0, 100)},
+		2: {strTagValue("a"), timestampTagValue(0, 200)},
+	}
+	seriesIDs, filterErr := filterTimestampEntitySeries(series, indexRule, "timestamp", timestamp.NewInclusiveTimeRange(time.Unix(0, 100), time.Unix(0, 100)))
+	require.NoError(t, filterErr)
+	require.Equal(t, []common.SeriesID{1}, seriesIDs)
+
+	seriesIDs, filterErr = filterTimestampEntitySeries(series, indexRule, "timestamp", timestamp.NewInclusiveTimeRange(time.Unix(0, 300), time.Unix(0, 300)))
+	require.NoError(t, filterErr)
+	require.Empty(t, seriesIDs)
+
+	emptyRange := timestamp.NewTimeRange(time.Unix(0, 100), time.Unix(0, 100), true, false)
+	seriesIDs, filterErr = filterTimestampEntitySeries(series, indexRule, "timestamp", emptyRange)
+	require.NoError(t, filterErr)
+	require.Empty(t, seriesIDs)
+
+	inconsistentSeries := map[common.SeriesID][]*modelv1.TagValue{1: {strTagValue("a")}}
+	inconsistentRange := timestamp.NewInclusiveTimeRange(time.Unix(0, 0), time.Unix(0, 1))
+	_, filterErr = filterTimestampEntitySeries(inconsistentSeries, indexRule, "timestamp", inconsistentRange)
+	require.Error(t, filterErr)
+}
+
+type traceTestTagMatcher struct {
+	match func([]*modelv1.Tag) (bool, error)
+}
+
+func (tttm *traceTestTagMatcher) Match(tags []*modelv1.Tag) (bool, error) {
+	return tttm.match(tags)
+}
+
+func (tttm *traceTestTagMatcher) GetDecoder() model.TagValueDecoder {
+	return mustDecodeTagValueAndArray
+}
diff --git a/banyand/trace/query_time_benchmark_test.go b/banyand/trace/query_time_benchmark_test.go
new file mode 100644
index 000000000..8a7df55ad
--- /dev/null
+++ b/banyand/trace/query_time_benchmark_test.go
@@ -0,0 +1,355 @@
+// Licensed to Apache Software Foundation (ASF) under one or more contributor
+// license agreements. See the NOTICE file distributed with this work for
+// additional information regarding copyright ownership. The ASF licenses this
+// file to you under the Apache License, Version 2.0 (the "License"); you may
+// not use this file except in compliance with the License. You may obtain a
+// copy of the License at
+//
+//	http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+// License for the specific language governing permissions and limitations
+// under the License.
+
+package trace
+
+import (
+	"context"
+	"fmt"
+	"math/bits"
+	"runtime"
+	"testing"
+	"time"
+
+	"github.com/apache/skywalking-banyandb/api/common"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	"github.com/apache/skywalking-banyandb/banyand/internal/sidx"
+	"github.com/apache/skywalking-banyandb/banyand/protector"
+	"github.com/apache/skywalking-banyandb/pkg/convert"
+	"github.com/apache/skywalking-banyandb/pkg/fs"
+	"github.com/apache/skywalking-banyandb/pkg/index"
+	pbv1 "github.com/apache/skywalking-banyandb/pkg/pb/v1"
+	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	"github.com/apache/skywalking-banyandb/pkg/timestamp"
+)
+
+const (
+	benchmarkTimestampTag = "start_time"
+	benchmarkServiceTag   = "service"
+	benchmarkServiceValue = "benchmark"
+)
+
+// BenchmarkSIDXPartScanTimestampFilter measures the real SIDX part scan path.
+// Forced cases clear only the request's timestamp selection hints. This is
+// deliberately benchmark-local: the production TimeTagFilter still carries the
+// exact range and must scan the same part. Auto cases retain the hints, allowing
+// the production coverage-bypass decision to omit that matcher.
+func BenchmarkSIDXPartScanTimestampFilter(b *testing.B) {
+	previousMaxProcs := runtime.GOMAXPROCS(2)
+	b.Cleanup(func() {
+		runtime.GOMAXPROCS(previousMaxProcs)
+	})
+
+	fixtures := []struct {
+		name   string
+		rows   int
+		reopen bool
+		order  modelv1.Sort
+	}{
+		{name: "Memory/10K/ASC", rows: 10_000, order: modelv1.Sort_SORT_ASC},
+		{name: "FlushedReopened/10K/DESC", rows: 10_000, reopen: true, order: modelv1.Sort_SORT_DESC},
+		{name: "FlushedReopened/100K/ASC", rows: 100_000, reopen: true, order: modelv1.Sort_SORT_ASC},
+	}
+	for _, fixtureConfig := range fixtures {
+		b.Run(fixtureConfig.name, func(b *testing.B) {
+			fixture := newTimestampScanBenchmarkFixture(b, fixtureConfig.rows, fixtureConfig.reopen, false)
+			fixture.runFullCoverage(b, fixtureConfig.order)
+			partialFixture := newTimestampScanBenchmarkFixture(b, fixtureConfig.rows, fixtureConfig.reopen, true)
+			partialFixture.runPartialOverlap(b, fixtureConfig.order)
+		})
+	}
+}
+
+type timestampScanBenchmarkFixture struct {
+	instance sidx.SIDX
+	rows     int
+	minTime  int64
+	maxTime  int64
+}
+
+func newTimestampScanBenchmarkFixture(b *testing.B, rows int, reopen, conservativeEnvelope bool) *timestampScanBenchmarkFixture {
+	b.Helper()
+
+	root := b.TempDir()
+	fileSystem := fs.NewLocalFileSystem()
+	options, optionsErr := sidx.NewOptions(root, protector.Nop{})
+	if optionsErr != nil {
+		b.Fatalf("create SIDX options: %v", optionsErr)
+	}
+	instance, instanceErr := sidx.NewSIDX(fileSystem, options)
+	if instanceErr != nil {
+		b.Fatalf("create SIDX: %v", instanceErr)
+	}
+
+	const baseTimestamp = int64(1_700_000_000_000_000_000)
+	minTime := baseTimestamp
+	maxTime := baseTimestamp + int64(rows) - 1
+	requests := make([]sidx.WriteRequest, 0, rows)
+	for row := 0; row < rows; row++ {
+		// The key deliberately has no timestamp semantics. Reversing its bits
+		// gives a deterministic ordering independent of the timestamp column.
+		key := int64(bits.Reverse64(uint64(row)))
+		rowTimestamp := minTime + int64(row)
+		requests = append(requests, sidx.WriteRequest{
+			SeriesID: common.SeriesID(1),
+			Key:      key,
+			Data:     []byte(fmt.Sprintf("trace-%06d", row)),
+			Tags: []sidx.Tag{
+				{Name: benchmarkTimestampTag, Value: convert.Int64ToBytes(rowTimestamp), ValueType: pbv1.ValueTypeTimestamp},
+				{Name: benchmarkServiceTag, Value: []byte(benchmarkServiceValue), ValueType: pbv1.ValueTypeStr},
+			},
+		})
+	}
+	partMinTime, partMaxTime := minTime, maxTime
+	if conservativeEnvelope {
+		partMinTime -= int64(rows) * 2
+		partMaxTime += int64(rows) * 2
+	}
+	memPart, convertErr := instance.ConvertToMemPart(requests, 1, &partMinTime, &partMaxTime)
+	if convertErr != nil {
+		b.Fatalf("convert benchmark part: %v", convertErr)
+	}
+	instance.IntroduceMemPart(1, memPart)
+	snapshot := instance.CurrentSnapshot()
+	if snapshot == nil {
+		b.Fatal("published benchmark part is not visible")
+	}
+	snapshot.DecRef()
+
+	if reopen {
+		flushIntroduction, flushErr := instance.Flush(map[uint64]struct{}{1: {}})
+		if flushErr != nil {
+			b.Fatalf("flush benchmark part: %v", flushErr)
+		}
+		if flushIntroduction == nil {
+			b.Fatal("flush benchmark part: missing introduction")
+		}
+		instance.IntroduceFlushed(flushIntroduction)
+		flushIntroduction.Release()
+		if closeErr := instance.Close(); closeErr != nil {
+			b.Fatalf("close flushed SIDX: %v", closeErr)
+		}
+
+		options.AvailablePartIDs = []uint64{1}
+		instance, instanceErr = sidx.NewSIDX(fileSystem, options)
+		if instanceErr != nil {
+			b.Fatalf("reopen flushed SIDX: %v", instanceErr)
+		}
+	}
+	b.Cleanup(func() {
+		if closeErr := instance.Close(); closeErr != nil {
+			b.Errorf("close benchmark SIDX: %v", closeErr)
+		}
+	})
+
+	return &timestampScanBenchmarkFixture{instance: instance, rows: rows, minTime: minTime, maxTime: maxTime}
+}
+
+func (f *timestampScanBenchmarkFixture) runFullCoverage(b *testing.B, order modelv1.Sort) {
+	b.Helper()
+
+	for _, hasExistingPredicate := range []bool{false, true} {
+		predicateName := "NoExistingPredicate"
+		if hasExistingPredicate {
+			predicateName = "ExistingServicePredicate"
+		}
+		for _, projectTimestamp := range []bool{false, true} {
+			projectionName := "TimestampOmitted"
+			if projectTimestamp {
+				projectionName = "TimestampProjected"
+			}
+			baseRequest := f.request(order, f.minTime, f.maxTime, hasExistingPredicate, projectTimestamp)
+			matcher := newTimestampTagFilterMatcher(
+				timestamp.NewTimeRange(time.Unix(0, f.minTime), time.Unix(0, f.maxTime), true, true),
+				benchmarkTimestampTag,
+				baseRequest.TagFilter,
+			)
+			variants := []struct {
+				name    string
+				request sidx.QueryRequest
+			}{
+				{name: "NoTimeFilter", request: baseRequest},
+				{name: "ForcedTimeFilter", request: f.forcedRequest(baseRequest, matcher)},
+				{name: "AutoCoverageBypass", request: f.autoRequest(baseRequest, matcher)},
+			}
+			baseline := f.mustQueryRows(b, variants[0].request)
+			if len(baseline) != f.rows {
+				b.Fatalf("full-coverage baseline returned %d rows, want %d", len(baseline), f.rows)
+			}
+			for _, variant := range variants {
+				rows := f.mustQueryRows(b, variant.request)
+				assertBenchmarkRowsEqual(b, baseline, rows)
+				f.runRequest(b, predicateName+"/"+projectionName+"/"+variant.name, variant.request, len(rows))
+			}
+		}
+	}
+}
+
+func (f *timestampScanBenchmarkFixture) runPartialOverlap(b *testing.B, order modelv1.Sort) {
+	b.Helper()
+
+	for _, matchPercent := range []int{0, 10, 50, 100} {
+		minTime, maxTime := f.partialRange(matchPercent)
+		baseRequest := f.request(order, minTime, maxTime, false, false)
+		matcher := newTimestampTagFilterMatcher(
+			timestamp.NewTimeRange(time.Unix(0, minTime), time.Unix(0, maxTime), true, true),
+			benchmarkTimestampTag,
+			nil,
+		)
+		forcedRequest := f.forcedRequest(baseRequest, matcher)
+		autoRequest := f.autoRequest(baseRequest, matcher)
+		forcedRows := f.mustQueryRows(b, forcedRequest)
+		autoRows := f.mustQueryRows(b, autoRequest)
+		assertBenchmarkRowsEqual(b, forcedRows, autoRows)
+		wantRows := f.rows * matchPercent / 100
+		if len(forcedRows) != wantRows {
+			b.Fatalf("partial %d%% returned %d rows, want %d", matchPercent, len(forcedRows), wantRows)
+		}
+		f.runRequest(b, fmt.Sprintf("Partial/%dPercent/ForcedTimeFilter", matchPercent), forcedRequest, len(forcedRows))
+		f.runRequest(b, fmt.Sprintf("Partial/%dPercent/AutoSelectiveFilter", matchPercent), autoRequest, len(autoRows))
+	}
+}
+
+func (f *timestampScanBenchmarkFixture) partialRange(matchPercent int) (int64, int64) {
+	if matchPercent == 0 {
+		// This intentionally overlaps the conservative envelope used by the
+		// benchmark part selection fixture, while containing no row timestamp.
+		return f.minTime - int64(f.rows), f.minTime - 1
+	}
+	matchingRows := f.rows * matchPercent / 100
+	return f.minTime, f.minTime + int64(matchingRows) - 1
+}
+
+func (f *timestampScanBenchmarkFixture) request(order modelv1.Sort, minTime, maxTime int64, existingPredicate, projectTimestamp bool) sidx.QueryRequest {
+	request := sidx.QueryRequest{
+		SeriesIDs:        []common.SeriesID{1},
+		Order:            &index.OrderBy{Sort: order},
+		MinTimestamp:     &minTime,
+		MaxTimestamp:     &maxTime,
+		TimeIncludeStart: true,
+		TimeIncludeEnd:   true,
+		MaxBatchSize:     1024,
+	}
+	if existingPredicate {
+		request.TagFilter = benchmarkServiceMatcher{}
+		request.FilterTagNames = []string{benchmarkServiceTag}
+	}
+	// Keep this harmless non-timestamp column projected in every full-scan case.
+	// Without it an empty projection instructs SIDX to load all tags, including
+	// the timestamp column that TimestampOmitted is intended to avoid.
+	projectedTags := []string{benchmarkServiceTag}
+	if projectTimestamp {
+		projectedTags = append(projectedTags, benchmarkTimestampTag)
+	}
+	if len(projectedTags) > 0 {
+		request.TagProjection = []model.TagProjection{{Names: projectedTags}}
+	}
+	return request
+}
+
+func (f *timestampScanBenchmarkFixture) forcedRequest(request sidx.QueryRequest, matcher model.TagFilterMatcher) sidx.QueryRequest {
+	// Clear only selection hints in this benchmark request. The production time
+	// matcher retains the exact range, while partNeedsTimeFilter safely selects
+	// the row predicate for this same immutable part.
+	request.MinTimestamp = nil
+	request.MaxTimestamp = nil
+	request.TimeTagFilter = matcher
+	request.TimeTagName = benchmarkTimestampTag
+	return request
+}
+
+func (f *timestampScanBenchmarkFixture) autoRequest(request sidx.QueryRequest, matcher model.TagFilterMatcher) sidx.QueryRequest {
+	request.TimeTagFilter = matcher
+	request.TimeTagName = benchmarkTimestampTag
+	return request
+}
+
+func (f *timestampScanBenchmarkFixture) mustQueryRows(b *testing.B, request sidx.QueryRequest) map[string]int64 {
+	b.Helper()
+
+	responses, queryErr := f.instance.QuerySync(context.Background(), request)
+	if queryErr != nil {
+		b.Fatalf("query benchmark part: %v", queryErr)
+	}
+	rows := make(map[string]int64, f.rows)
+	for _, response := range responses {
+		if response == nil {
+			continue
+		}
+		if response.Error != nil {
+			b.Fatalf("query response error: %v", response.Error)
+		}
+		for rowIndex, data := range response.Data {
+			rows[string(data)] = response.Keys[rowIndex]
+		}
+	}
+	return rows
+}
+
+func (f *timestampScanBenchmarkFixture) runRequest(b *testing.B, name string, request sidx.QueryRequest, outputRows int) {
+	b.Helper()
+	b.Run(name, func(b *testing.B) {
+		b.ReportAllocs()
+		b.ResetTimer()
+		for iteration := 0; iteration < b.N; iteration++ {
+			responses, queryErr := f.instance.QuerySync(context.Background(), request)
+			if queryErr != nil {
+				b.Fatalf("query benchmark part: %v", queryErr)
+			}
+			rows := 0
+			for _, response := range responses {
+				if response != nil {
+					rows += response.Len()
+				}
+			}
+			if rows != outputRows {
+				b.Fatalf("query returned %d rows, want %d", rows, outputRows)
+			}
+		}
+		b.StopTimer()
+		if elapsed := b.Elapsed(); elapsed > 0 {
+			b.ReportMetric(float64(f.rows*b.N)/elapsed.Seconds(), "input_rows/s")
+		}
+		b.ReportMetric(float64(outputRows), "output_rows/op")
+	})
+}
+
+func assertBenchmarkRowsEqual(b *testing.B, want, got map[string]int64) {
+	b.Helper()
+	if len(got) != len(want) {
+		b.Fatalf("row count mismatch: got %d, want %d", len(got), len(want))
+	}
+	for traceID, wantKey := range want {
+		gotKey, ok := got[traceID]
+		if !ok || gotKey != wantKey {
+			b.Fatalf("row mismatch for %q: got key %d present %t, want key %d", traceID, gotKey, ok, wantKey)
+		}
+	}
+}
+
+type benchmarkServiceMatcher struct{}
+
+func (benchmarkServiceMatcher) Match(tags []*modelv1.Tag) (bool, error) {
+	for _, tag := range tags {
+		if tag.GetKey() == benchmarkServiceTag && tag.GetValue().GetStr().GetValue() == benchmarkServiceValue {
+			return true, nil
+		}
+	}
+	return false, nil
+}
+
+func (benchmarkServiceMatcher) GetDecoder() model.TagValueDecoder {
+	return mustDecodeTagValueAndArray
+}
diff --git a/banyand/trace/streaming_pipeline.go b/banyand/trace/streaming_pipeline.go
index 81098197e..766bd2787 100644
--- a/banyand/trace/streaming_pipeline.go
+++ b/banyand/trace/streaming_pipeline.go
@@ -304,8 +304,8 @@ type sidxStreamRunner struct {
 	errEvents      chan sidxStreamError
 	heap           *sidxStreamHeap
 	seenTraceIDs   map[string]struct{}
-	req            sidx.QueryRequest
 	batch          traceBatch
+	req            sidx.QueryRequest
 	errWg          sync.WaitGroup
 	nextSeq        int
 	total          atomic.Int64
diff --git a/pkg/query/logical/trace/index_filter_test.go b/pkg/query/logical/trace/index_filter_test.go
index 2f6843b2c..acccda4a6 100644
--- a/pkg/query/logical/trace/index_filter_test.go
+++ b/pkg/query/logical/trace/index_filter_test.go
@@ -21,6 +21,7 @@ import (
 	"testing"
 
 	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
 
 	commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
 	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
@@ -433,3 +434,47 @@ func TestBuildFilterDeduplicatesCollectedTagNames(t *testing.T) {
 	assert.NoError(t, err)
 	assert.Equal(t, []string{"service_id"}, collectedTagNamesOR, "service_id should appear only once")
 }
+
+func TestTraceAnalyzerUsesSelectedIndexRuleEntityLayout(t *testing.T) {
+	trace := &databasev1.Trace{
+		Metadata:         &commonv1.Metadata{Name: "trace", Group: "default"},
+		TraceIdTagName:   "trace_id",
+		SpanIdTagName:    "span_id",
+		TimestampTagName: "timestamp",
+		Tags: []*databasev1.TraceTagSpec{
+			{Name: "trace_id", Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: "span_id", Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: "service", Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: "region", Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: "duration", Type: databasev1.TagType_TAG_TYPE_INT},
+		},
+	}
+	firstRule := &databasev1.IndexRule{Metadata: &commonv1.Metadata{Name: "first_rule"}, Tags: []string{"service", "duration"}}
+	compositeRule := &databasev1.IndexRule{Metadata: &commonv1.Metadata{Name: "custom_composite"}, Tags: []string{"service", "region", "duration"}}
+	singleRule := &databasev1.IndexRule{Metadata: &commonv1.Metadata{Name: "custom_single"}, Tags: []string{"duration"}}
+	schema, schemaErr := BuildSchema(trace, []*databasev1.IndexRule{firstRule, compositeRule, singleRule})
+	assert.NoError(t, schemaErr)
+
+	for _, testCase := range []struct {
+		name          string
+		indexRuleName string
+		wantEntityLen int
+	}{
+		{name: "non_first_composite", indexRuleName: "custom_composite", wantEntityLen: 2},
+		{name: "non_first_single", indexRuleName: "custom_single", wantEntityLen: 0},
+	} {
+		t.Run(testCase.name, func(t *testing.T) {
+			plan, analyzeErr := (&unresolvedTraceTagFilter{
+				traceIDTagName: "trace_id",
+				spanIDTagName:  "span_id",
+				orderByTag:     "duration",
+				indexRuleName:  testCase.indexRuleName,
+			}).Analyze(schema)
+			require.NoError(t, analyzeErr)
+			scan, ok := plan.(*localScan)
+			require.True(t, ok)
+			require.Len(t, scan.entities, 1)
+			assert.Len(t, scan.entities[0], testCase.wantEntityLen)
+		})
+	}
+}
diff --git a/pkg/query/logical/trace/trace_analyzer.go b/pkg/query/logical/trace/trace_analyzer.go
index 74c97690a..d84312e1b 100644
--- a/pkg/query/logical/trace/trace_analyzer.go
+++ b/pkg/query/logical/trace/trace_analyzer.go
@@ -245,6 +245,7 @@ func parseTraceTags(criteria *tracev1.QueryRequest, metadata *commonv1.Metadata,
 		traceIDTagName:   traceIDTagName,
 		spanIDTagName:    spanIDTagName,
 		orderByTag:       orderByTag,
+		indexRuleName:    criteria.GetOrderBy().GetIndexRuleName(),
 		timestampTagName: timestampTagName,
 		groupIndex:       groupIndex,
 	}
diff --git a/pkg/query/logical/trace/trace_plan_tag_filter.go b/pkg/query/logical/trace/trace_plan_tag_filter.go
index 25b06f3fb..f04031340 100644
--- a/pkg/query/logical/trace/trace_plan_tag_filter.go
+++ b/pkg/query/logical/trace/trace_plan_tag_filter.go
@@ -46,6 +46,7 @@ type unresolvedTraceTagFilter struct {
 	traceIDTagName   string
 	spanIDTagName    string
 	orderByTag       string
+	indexRuleName    string
 	timestampTagName string
 	projectionTags   [][]*logical.Tag
 	groupIndex       int
@@ -54,6 +55,9 @@ type unresolvedTraceTagFilter struct {
 func (uis *unresolvedTraceTagFilter) Analyze(s logical.Schema) (logical.Plan, error) {
 	ctx := newTraceAnalyzerContext(s)
 	entityList := s.EntityList()
+	if ok, selectedRule := s.IndexRuleDefined(uis.indexRuleName); ok && len(selectedRule.GetTags()) > 0 {
+		entityList = selectedRule.GetTags()[:len(selectedRule.GetTags())-1]
+	}
 	entityDict := make(map[string]int)
 	entity := make([]*modelv1.TagValue, len(entityList))
 	for idx, e := range entityList {
@@ -137,7 +141,7 @@ func (uis *unresolvedTraceTagFilter) Analyze(s logical.Schema) (logical.Plan, er
 	var tagFilter logical.TagFilter
 	if uis.criteria != nil {
 		var orderByTags []string
-		if ok, indexRule := s.IndexRuleDefined(uis.orderByTag); ok {
+		if ok, indexRule := s.IndexRuleDefined(uis.indexRuleName); ok {
 			orderByTags = indexRule.Tags
 		}
 		skippedTagNames := make([]string, 0, len(orderByTags)+2)
diff --git a/test/cases/trace/data/want/time_range_trace_001.yml b/test/cases/trace/data/want/time_range_trace_001.yml
new file mode 100644
index 000000000..2e84191da
--- /dev/null
+++ b/test/cases/trace/data/want/time_range_trace_001.yml
@@ -0,0 +1,30 @@
+# Licensed to Apache Software Foundation (ASF) under one or more contributor
+# license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright
+# ownership. Apache Software Foundation (ASF) licenses this file to you under
+# the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#     http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+traces:
+  - spans:
+      - span: trace_001_span_1
+        spanId: span_001_1
+      - span: trace_001_span_2
+        spanId: span_001_2
+      - span: trace_001_span_3
+        spanId: span_001_3
+      - span: trace_001_span_4
+        spanId: span_001_4
+      - span: trace_001_span_5
+        spanId: span_001_5
+    traceId: trace_001
diff --git a/test/cases/trace/trace.go b/test/cases/trace/trace.go
index 75c79ee68..7823f0f8e 100644
--- a/test/cases/trace/trace.go
+++ b/test/cases/trace/trace.go
@@ -49,6 +49,19 @@ var traceEntries = []any{
 	g.Entry("query by empty span ids", helpers.Args{Input: "in_empty_span_ids", Duration: 1 * time.Hour, WantEmpty: true}),
 	g.Entry("order by timestamp", helpers.Args{Input: "order_timestamp_desc", Duration: 1 * time.Hour}),
 	g.Entry("order by duration", helpers.Args{Input: "order_duration_desc", Duration: 1 * time.Hour}),
+	// The seed occupies the first seconds of each minute. This gap stays within
+	// the populated segment even when BaseTime is the last minute of the day.
+	g.Entry("timestamp order excludes same-segment time gap",
+		helpers.Args{Input: "order_timestamp_desc", Offset: 20 * time.Second, Duration: 10 * time.Second, WantEmpty: true}),
+	g.Entry("duration order excludes same-segment time gap",
+		helpers.Args{Input: "order_duration_desc", Offset: 20 * time.Second, Duration: 10 * time.Second, WantEmpty: true}),
+	g.Entry("duration order filters time before pagination",
+		helpers.Args{
+			Input:  "gen_feat_order_duration_asc_limit2_offset1_proj_explicit_1",
+			Offset: 20 * time.Second, Duration: 10 * time.Second, WantEmpty: true,
+		}),
+	g.Entry("duration order selects a qualifying span and preserves its complete trace",
+		helpers.Args{Input: "order_duration_desc", Want: "time_range_trace_001", Offset: 750 * time.Millisecond, Duration: 500 * time.Millisecond}),
 	g.Entry("duration range 10-1000 order by timestamp",
 		helpers.Args{Input: "duration_range_order_timestamp", Duration: 1 * time.Hour}),
 	g.Entry("duration range with bound parameters",