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/08/04 03:28:00 UTC

(skywalking-banyandb) branch main updated: Vectorized stream query path with native columnar wire frame; enable stream and trace by default (#1241)

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

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


The following commit(s) were added to refs/heads/main by this push:
     new 21d113a59 Vectorized stream query path with native columnar wire frame; enable stream and trace by default (#1241)
21d113a59 is described below

commit 21d113a59f480171d4c55f41dbabbbfc826ea2c3
Author: Gao Hongtao <ha...@gmail.com>
AuthorDate: Tue Aug 4 11:27:55 2026 +0800

    Vectorized stream query path with native columnar wire frame; enable stream and trace by default (#1241)
---
 .gitignore                                         |   2 +
 CHANGES.md                                         |   4 +
 api/data/codec.go                                  |  20 +
 api/data/codec_test.go                             |   5 +-
 api/data/data.go                                   |   9 +-
 api/data/frame_counters.go                         |  90 +++
 api/data/frame_counters_test.go                    | 117 +++
 api/data/{trace_frame.go => stream_frame.go}       |  17 +-
 api/data/stream_frame_test.go                      | 107 +++
 api/data/trace_frame.go                            |   1 +
 banyand/internal/sidx/sidx.go                      |   5 +-
 banyand/measure/block_batch.go                     |   9 +-
 banyand/measure/query_batch.go                     |   3 +-
 .../observability/services/metrics_vec_frame.go    |  74 ++
 .../services/metrics_vec_frame_test.go             | 107 +++
 banyand/observability/services/service.go          |   1 +
 banyand/query/processor.go                         | 215 ++++++
 banyand/query/query.go                             |   1 +
 banyand/query/stream_vec_emit_test.go              |  54 ++
 banyand/queue/sub/sub.go                           |   4 +-
 banyand/stream/benchmark_test.go                   |  12 +-
 banyand/stream/metadata.go                         |   4 +-
 banyand/stream/metadata_test.go                    |  25 +-
 banyand/stream/query_vectorized.go                 | 555 ++++++++++++++
 banyand/stream/query_vectorized_parity_test.go     | 804 +++++++++++++++++++++
 banyand/stream/query_vectorized_test.go            | 437 +++++++++++
 banyand/stream/stream.go                           |  32 +-
 banyand/stream/svc_liaison.go                      |  11 +-
 banyand/stream/svc_standalone.go                   |  14 +-
 banyand/trace/block.go                             |   8 +
 banyand/trace/block_reader.go                      |   7 +-
 banyand/trace/merger_offset_regression_test.go     | 239 ++++++
 banyand/trace/part_iter.go                         |  16 +-
 cmd/soak-driver/catalog/stream.json                | 205 ++++++
 cmd/soak-driver/catalog/trace.json                 | 158 ++++
 cmd/soak-driver/main.go                            | 176 ++++-
 cmd/soak-driver/stream.go                          | 688 ++++++++++++++++++
 cmd/soak-driver/stream_test.go                     | 153 ++++
 cmd/soak-driver/trace.go                           | 678 +++++++++++++++++
 cmd/soak-driver/trace_test.go                      | 367 ++++++++++
 docs/operation/upgrade.md                          |  39 +
 docs/soak/trace-soak-runbook.md                    | 561 ++++++++++++++
 pkg/query/executor/interface.go                    |  39 +
 .../logical/stream/stream_plan_distributed.go      |  71 +-
 .../stream_plan_distributed_vectorized_test.go     | 207 ++++++
 .../logical/stream/stream_plan_indexscan_local.go  |   8 +
 .../stream_plan_indexscan_local_vectorized.go      | 390 ++++++++++
 .../stream_plan_indexscan_local_vectorized_test.go | 133 ++++
 pkg/query/logical/stream/stream_plan_merge.go      |  25 +-
 pkg/query/model/batch.go                           |   6 +-
 pkg/query/vectorized/appendrange.go                |  32 +
 pkg/query/vectorized/{measure => }/frame/decode.go | 106 +--
 pkg/query/vectorized/frame/doc.go                  |  63 ++
 pkg/query/vectorized/{measure => }/frame/encode.go | 121 +---
 pkg/query/vectorized/frame/frame.go                |  95 +++
 pkg/query/vectorized/frame/frame_test.go           | 407 +++++++++++
 pkg/query/vectorized/frame/golden_test.go          | 237 ++++++
 .../vectorized/{measure => }/frame/validate.go     |  41 +-
 pkg/query/vectorized/measure/batchsource.go        |   6 +-
 pkg/query/vectorized/measure/build_batch.go        |   6 +-
 pkg/query/vectorized/measure/frame/decode_test.go  |  17 +
 pkg/query/vectorized/measure/frame/frame.go        | 305 ++++----
 pkg/query/vectorized/schema.go                     |  16 +
 pkg/query/vectorized/stream/columns.go             |  61 ++
 pkg/query/vectorized/stream/config.go              |  84 +++
 .../vectorized/{trace => stream}/config_test.go    |  11 +-
 .../{trace/config_test.go => stream/counters.go}   |  32 +-
 pkg/query/vectorized/stream/distinct.go            |  79 ++
 pkg/query/vectorized/stream/distinct_test.go       |  79 ++
 .../{trace/config_test.go => stream/doc.go}        |  27 +-
 pkg/query/vectorized/stream/egress.go              | 116 +++
 pkg/query/vectorized/stream/egress_null_test.go    |  82 +++
 pkg/query/vectorized/stream/frame/frame.go         | 147 ++++
 pkg/query/vectorized/stream/frame/frame_test.go    | 170 +++++
 pkg/query/vectorized/stream/limit.go               |  92 +++
 pkg/query/vectorized/stream/limit_test.go          | 120 +++
 .../stream/operators_test_helpers_test.go          | 140 ++++
 pkg/query/vectorized/stream/pipeline.go            |  45 ++
 pkg/query/vectorized/stream/schema.go              |  69 ++
 pkg/query/vectorized/stream/schema_test.go         | 111 +++
 pkg/query/vectorized/stream/sorted_merge.go        | 262 +++++++
 pkg/query/vectorized/stream/sorted_merge_test.go   | 220 ++++++
 pkg/query/vectorized/trace/config.go               |  14 +-
 pkg/query/vectorized/trace/config_test.go          |   5 +-
 scripts/soak-vectorized.sh                         | 627 +++++++++++++++-
 ...zed_trace_test.go => vectorized_stream_test.go} |  75 +-
 .../distributed/query/vectorized_test.go           |  20 +
 .../distributed/query/vectorized_trace_test.go     |  22 +
 test/integration/distributed/querybench/README.md  |   3 +
 test/integration/distributed/querybench/config.go  | 220 +++---
 .../distributed/querybench/config_test.go          | 105 +++
 .../distributed/querybench/orchestrate.sh          |  17 +
 .../distributed/querybench/run-docker.sh           |   3 +
 .../distributed/querybench/soak_test.go            | 495 +++++++++++++
 .../distributed/querybench/trace_workload.go       |  25 +-
 .../standalone/query/vectorized_stream_test.go     | 110 +++
 test/soak/Dockerfile.soak-driver                   |  44 ++
 test/soak/docker-compose.soak-distributed.yaml     | 157 ++++
 test/soak/docker-compose.soak.yaml                 |  39 +-
 test/soak/nodes-distributed.yaml                   |  25 +
 100 files changed, 11742 insertions(+), 576 deletions(-)

diff --git a/.gitignore b/.gitignore
index 26afa50b6..20d0916a5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -92,6 +92,8 @@ dist/bench/
 # G5d soak harness runtime artifacts
 dist/soak/
 test/soak/data/
+# Per-node data dirs for the distributed soak topology (SOAK_TOPOLOGY=distributed).
+test/soak/data-distributed/
 
 # Local runtime crash dumps and investigation notes
 crash/
diff --git a/CHANGES.md b/CHANGES.md
index 59c2eec4d..a9b73c55c 100644
--- a/CHANGES.md
+++ b/CHANGES.md
@@ -13,6 +13,10 @@ Release Notes.
 - Refactor the lifecycle cycle-level metrics (`banyandb_lifecycle_cycles_total`, `banyandb_lifecycle_last_run_timestamp_seconds`, `banyandb_lifecycle_last_run_success`) to carry labels `remote_node`, `remote_role`, `remote_tier`, `group`. The label form mirrors the per-message `banyandb_lifecycle_migration_*` family emitted by the queue/pub lifecycle publisher, but the two families describe DIFFERENT things: the cycle-level series describe the SENDER (the lifecycle pod's co-located data  [...]
 - Remove `banyandb_lifecycle_self_identity_resolution_total`. The regression-detection role moves to the now-labeled `banyandb_lifecycle_cycles_total{remote_node!=""}` (an empty `remote_node` series means the registry match failed for every group, the bug the old counter caught), plus the existing receiver-side count of empty `remote_node` on lifecycle `banyandb_queue_sub_total_finished` series. The wire-level `cluster.v1.SendRequest` sender-identity fields are unchanged.
 - Vectorized measure query path is now enabled by default. The columnar pipeline replaces per-row protobuf serialization in `NewMIterator`, cutting allocations and ns/op for scan-heavy measure queries; gRPC wire format (`*measurev1.InternalDataPoint`) is byte-identical. Single-node coverage is complete: scan, GroupBy+Agg via `BatchAggregation`, scalar reduce (`Agg` without `GroupBy`), raw `GroupBy` (without `Agg`), implicit projection coverage for GroupBy/Agg fields, `TopN`/`BottomN`, `o [...]
+- Vectorized **stream** and **trace** query paths are now enabled by default, joining measure. `--stream-vectorized-enabled` and `--trace-vectorized-enabled` now default to `true`. Validated on two axes. A 48h single-node containerized soak per engine covers the compute path (stream 575/575 parity cycles and 84.75M spans; trace parity pass and 84.6M spans; zero memory alerts, no restarts, and TTL reclamation observed releasing memory proportionally to the data it cached). A 6h soak per e [...]
+- Add the vectorized **stream** query path. Timestamp-ordered (asc/desc), index-ordered, criteria-filtered, and multi-group queries dispatch through the columnar pipeline (scan -> batch -> merge -> distinct -> limit) with a native columnar liaison<->data wire frame replacing per-element protobuf. Shapes the vec dispatch does not recognize -- and index-ordered queries whose sort tag is absent from the projection, where the OrderKey column cannot be populated -- fall back to the row path,  [...]
+- Add `banyandb_vec_frame_encoded{engine}` and `banyandb_vec_frame_decoded{engine}` gauges (engine: `measure`/`stream`/`trace`), reporting how many query responses this process has put on the wire as a native columnar frame and how many it has decoded from one. Which wire format a node is actually speaking was otherwise invisible from outside the process, and the 0.11 upgrade-ordering rule depends on exactly that: a data node emits frames only when it is distributed AND its engine flag i [...]
+- [Breaking Change] Enabling a vectorized path by default changes the required rolling-upgrade order: **upgrade "liaison" nodes BEFORE "data" nodes**, the reverse of the general strategy. Each `--*-vectorized-enabled` flag selects the liaison<->data wire format as well as the query engine -- a flag-on distributed data node emits a native columnar frame. A 0.11 liaison decodes both frames and protobuf (dispatching per message on the frame magic byte), but an older liaison has no frame dec [...]
 - Add validation to ensure Measure's ShardingKey contains all Entity tags to guarantee entity locality.
 - Organize access logs under a dedicated "accesslog" subdirectory to improve log organization and separation from other application data.
 - Collect BanyanDB data on e2e test failure for CI debugging.
diff --git a/api/data/codec.go b/api/data/codec.go
index 9e8bf4a19..984bcd550 100644
--- a/api/data/codec.go
+++ b/api/data/codec.go
@@ -166,6 +166,23 @@ func TraceWireModeRaw() bool {
 	return traceWireModeRaw.Load()
 }
 
+// streamWireModeRaw is the per-process wire mode for TopicStreamQuery. Set once
+// at stream-service startup; raw==true selects the native columnar stream frame
+// body, raw==false keeps the proto body. Default false so any process that never
+// sets it keeps the pre-existing proto behavior.
+var streamWireModeRaw atomic.Bool
+
+// SetStreamWireModeRaw publishes the per-process wire mode for TopicStreamQuery.
+func SetStreamWireModeRaw(raw bool) {
+	streamWireModeRaw.Store(raw)
+}
+
+// StreamWireModeRaw reports whether this process emits/decodes native stream
+// frame bodies for TopicStreamQuery.
+func StreamWireModeRaw() bool {
+	return streamWireModeRaw.Load()
+}
+
 // measureQueryResponseCodec dispatches TopicInternalMeasureQuery encode/decode
 // by the per-process wire mode: flag-on → RawFrameCodec, flag-off → ProtoCodec.
 // One static supplier serves both flag-on raw bodies and flag-off proto bodies
@@ -195,6 +212,9 @@ func (c *measureQueryResponseCodec) Unmarshal(body []byte) (any, error) {
 		return c.proto.Unmarshal(body)
 	}
 	if len(body) == 0 || body[0] == RawFrameMagicLeadingByte {
+		if len(body) > 0 {
+			measureFrameDecoded.Add(1)
+		}
 		return c.raw.Unmarshal(body)
 	}
 	return c.proto.Unmarshal(body)
diff --git a/api/data/codec_test.go b/api/data/codec_test.go
index b9de83f1d..ef6a0462a 100644
--- a/api/data/codec_test.go
+++ b/api/data/codec_test.go
@@ -105,9 +105,10 @@ func TestRawFrameCodec_WrongMagic_FailsLoud(t *testing.T) {
 func TestTopicResponseMap_ProtoCodec_RoundTripsByteIdentical(t *testing.T) {
 	var protoTopics int
 	for topic, codec := range TopicResponseMap {
-		if topic == TopicInternalMeasureQuery || topic == TopicTraceQuery {
+		if topic == TopicInternalMeasureQuery || topic == TopicTraceQuery || topic == TopicStreamQuery {
 			// Wire-mode-dispatching codecs; covered separately (measure below,
-			// trace in trace_frame_test.go including flag-off byte-identity).
+			// trace in trace_frame_test.go and stream in stream_frame_test.go,
+			// both including flag-off byte-identity).
 			continue
 		}
 		pc, ok := codec.(*ProtoCodec)
diff --git a/api/data/data.go b/api/data/data.go
index ad9ca6420..0ec54ac2f 100644
--- a/api/data/data.go
+++ b/api/data/data.go
@@ -181,9 +181,12 @@ var (
 	// mode selection, G9f spec G9f.0).
 	// nolint: exhaustruct
 	TopicResponseMap = map[bus.Topic]ResponseCodec{
-		TopicStreamQuery: NewProtoCodec(func() proto.Message {
-			return &streamv1.QueryResponse{}
-		}),
+		TopicStreamQuery: &streamQueryResponseCodec{
+			proto: NewProtoCodec(func() proto.Message {
+				return &streamv1.QueryResponse{}
+			}),
+			raw: NewRawFrameCodec(),
+		},
 		TopicMeasureQuery: NewProtoCodec(func() proto.Message {
 			return &measurev1.QueryResponse{}
 		}),
diff --git a/api/data/frame_counters.go b/api/data/frame_counters.go
new file mode 100644
index 000000000..8db40056d
--- /dev/null
+++ b/api/data/frame_counters.go
@@ -0,0 +1,90 @@
+// 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.
+
+package data
+
+import (
+	"sync/atomic"
+
+	"github.com/apache/skywalking-banyandb/pkg/bus"
+)
+
+// Which wire format a query response actually traveled on is otherwise
+// invisible from outside the process: the mode is a per-process atomic set at
+// startup, and the frame branches are plain code paths that emit no signal. That
+// gap is not academic — a 48h soak reported green while never exercising the frame
+// at all, because it ran a standalone server, where the data node always falls back
+// to protobuf. Nothing in the run could have revealed that.
+//
+// These counters make the frame path assert its own presence. They are incremented
+// at the single choke point per direction (the codec Marshal/Unmarshal raw
+// branches), so a non-zero encode count on a data node and a non-zero decode count
+// on a liaison together prove the columnar frame is carrying real traffic.
+// banyand/observability/services publishes them; a test or soak can also read them
+// in-process through the getters below.
+//
+// They are cumulative and monotonic for the life of the process.
+var (
+	measureFrameEncoded atomic.Int64
+	measureFrameDecoded atomic.Int64
+	streamFrameEncoded  atomic.Int64
+	streamFrameDecoded  atomic.Int64
+	traceFrameEncoded   atomic.Int64
+	traceFrameDecoded   atomic.Int64
+)
+
+// MeasureFrameEncodedCount returns how many measure responses this process has
+// emitted as a native columnar frame rather than protobuf.
+func MeasureFrameEncodedCount() int64 { return measureFrameEncoded.Load() }
+
+// MeasureFrameDecodedCount returns how many measure responses this process has
+// decoded from a native columnar frame rather than protobuf.
+func MeasureFrameDecodedCount() int64 { return measureFrameDecoded.Load() }
+
+// StreamFrameEncodedCount returns how many stream responses this process has
+// emitted as a native columnar frame rather than protobuf.
+func StreamFrameEncodedCount() int64 { return streamFrameEncoded.Load() }
+
+// StreamFrameDecodedCount returns how many stream responses this process has
+// decoded from a native columnar frame rather than protobuf.
+func StreamFrameDecodedCount() int64 { return streamFrameDecoded.Load() }
+
+// TraceFrameEncodedCount returns how many trace responses this process has emitted
+// as a native columnar frame rather than protobuf.
+func TraceFrameEncodedCount() int64 { return traceFrameEncoded.Load() }
+
+// TraceFrameDecodedCount returns how many trace responses this process has decoded
+// from a native columnar frame rather than protobuf.
+func TraceFrameDecodedCount() int64 { return traceFrameDecoded.Load() }
+
+// IncrFrameEncoded records that a native columnar frame body for this topic was
+// put on the wire. It is called from the queue's response-marshal path rather
+// than from a codec: the per-topic ResponseCodec.Marshal methods are only reached
+// by in-process callers, while the real data-node send path hands the already
+// encoded []byte straight to the transport, so counting at the codec would report
+// zero frames on a cluster that is in fact emitting them.
+func IncrFrameEncoded(t bus.Topic) {
+	switch t {
+	case TopicInternalMeasureQuery:
+		measureFrameEncoded.Add(1)
+	case TopicStreamQuery:
+		streamFrameEncoded.Add(1)
+	case TopicTraceQuery:
+		traceFrameEncoded.Add(1)
+	default:
+	}
+}
diff --git a/api/data/frame_counters_test.go b/api/data/frame_counters_test.go
new file mode 100644
index 000000000..fc41e9c6e
--- /dev/null
+++ b/api/data/frame_counters_test.go
@@ -0,0 +1,117 @@
+// 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.
+
+package data
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/require"
+	"google.golang.org/protobuf/proto"
+
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+	tracev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/trace/v1"
+)
+
+// The counters exist to let a soak or an operator assert that the native columnar
+// frame is genuinely carrying traffic. Their whole value is that they are zero when
+// it is not, so both directions are pinned here: a frame body must move them, and a
+// flag-off process must leave them alone.
+//
+// Encode and decode are counted at different layers because the wire path is not
+// symmetric. The liaison decodes through ResponseCodec.Unmarshal, so the decode
+// count lives in the codec; the data node hands its already-encoded frame straight
+// to the transport and never calls ResponseCodec.Marshal, so the encode count lives
+// in the queue's marshalResponse and is exercised via IncrFrameEncoded. Counting
+// encode at the codec looked right and reported a flat zero on a cluster that was
+// demonstrably emitting frames.
+
+func TestStreamFrameCounters_CountRawTrafficOnly(t *testing.T) {
+	c := newStreamCodec()
+	frame := []byte{RawFrameMagicLeadingByte, 0x01, 0x02, 0x03}
+
+	// Flag OFF: a proto response must not be counted as frame traffic. This is the
+	// standalone case, where the data node never emits a frame at all.
+	SetStreamWireModeRaw(false)
+	encBefore, decBefore := StreamFrameEncodedCount(), StreamFrameDecodedCount()
+	body, err := c.Marshal(&streamv1.QueryResponse{})
+	require.NoError(t, err)
+	_, err = c.Unmarshal(body)
+	require.NoError(t, err)
+	require.Equal(t, encBefore, StreamFrameEncodedCount(), "proto encode must not count as a frame")
+	require.Equal(t, decBefore, StreamFrameDecodedCount(), "proto decode must not count as a frame")
+
+	// Flag ON with a frame body: the decode counts, and the send path's
+	// IncrFrameEncoded counts the matching encode.
+	SetStreamWireModeRaw(true)
+	defer SetStreamWireModeRaw(false)
+	encBefore, decBefore = StreamFrameEncodedCount(), StreamFrameDecodedCount()
+	body, err = c.Marshal(frame)
+	require.NoError(t, err)
+	_, err = c.Unmarshal(body)
+	require.NoError(t, err)
+	require.Equal(t, decBefore+1, StreamFrameDecodedCount())
+	IncrFrameEncoded(TopicStreamQuery)
+	require.Equal(t, encBefore+1, StreamFrameEncodedCount())
+
+	// Flag ON but a proto body still travels the proto path (the fallback a traced
+	// query or an unsupported shape takes), so it must not be counted either.
+	encBefore, decBefore = StreamFrameEncodedCount(), StreamFrameDecodedCount()
+	body, err = c.Marshal(&streamv1.QueryResponse{})
+	require.NoError(t, err)
+	_, err = c.Unmarshal(body)
+	require.NoError(t, err)
+	require.Equal(t, encBefore, StreamFrameEncodedCount(), "proto fallback must not count as a frame")
+	require.Equal(t, decBefore, StreamFrameDecodedCount(), "proto fallback must not count as a frame")
+}
+
+func TestTraceFrameCounters_CountRawTrafficOnly(t *testing.T) {
+	c := &traceQueryResponseCodec{
+		proto: NewProtoCodec(func() proto.Message { return &tracev1.InternalQueryResponse{} }),
+		raw:   NewRawFrameCodec(),
+	}
+	frame := []byte{RawFrameMagicLeadingByte, 0x0a, 0x0b}
+
+	SetTraceWireModeRaw(false)
+	encBefore, decBefore := TraceFrameEncodedCount(), TraceFrameDecodedCount()
+	body, err := c.Marshal(&tracev1.InternalQueryResponse{})
+	require.NoError(t, err)
+	_, err = c.Unmarshal(body)
+	require.NoError(t, err)
+	require.Equal(t, encBefore, TraceFrameEncodedCount(), "proto encode must not count as a frame")
+	require.Equal(t, decBefore, TraceFrameDecodedCount(), "proto decode must not count as a frame")
+
+	SetTraceWireModeRaw(true)
+	defer SetTraceWireModeRaw(false)
+	encBefore, decBefore = TraceFrameEncodedCount(), TraceFrameDecodedCount()
+	body, err = c.Marshal(frame)
+	require.NoError(t, err)
+	_, err = c.Unmarshal(body)
+	require.NoError(t, err)
+	require.Equal(t, decBefore+1, TraceFrameDecodedCount())
+	IncrFrameEncoded(TopicTraceQuery)
+	require.Equal(t, encBefore+1, TraceFrameEncodedCount())
+}
+
+// TestIncrFrameEncoded_IgnoresNonFrameTopic guards the default branch: only the
+// three topics that actually carry a columnar frame may move a counter.
+func TestIncrFrameEncoded_IgnoresNonFrameTopic(t *testing.T) {
+	before := MeasureFrameEncodedCount() + StreamFrameEncodedCount() + TraceFrameEncodedCount()
+	IncrFrameEncoded(TopicStreamWrite)
+	after := MeasureFrameEncodedCount() + StreamFrameEncodedCount() + TraceFrameEncodedCount()
+	require.Equal(t, before, after, "a non-frame topic must not be counted as frame traffic")
+}
diff --git a/api/data/trace_frame.go b/api/data/stream_frame.go
similarity index 74%
copy from api/data/trace_frame.go
copy to api/data/stream_frame.go
index 71b716b86..91cd96abd 100644
--- a/api/data/trace_frame.go
+++ b/api/data/stream_frame.go
@@ -17,21 +17,21 @@
 
 package data
 
-// traceQueryResponseCodec dispatches TopicTraceQuery encode/decode by the
-// per-process wire mode, mirroring measureQueryResponseCodec: flag-on passes the
+// streamQueryResponseCodec dispatches TopicStreamQuery encode/decode by the
+// per-process wire mode, mirroring traceQueryResponseCodec: flag-on passes the
 // caller-supplied columnar frame ([]byte) through RawFrameCodec; flag-off (and
 // any proto.Message the caller still emits, e.g. the tracing path) keeps the
 // byte-identical proto body via ProtoCodec.
-type traceQueryResponseCodec struct {
+type streamQueryResponseCodec struct {
 	proto *ProtoCodec
 	raw   *RawFrameCodec
 }
 
 // Marshal encodes the response. In raw wire mode a []byte body (the columnar
-// trace frame) is passed through unchanged; everything else (proto.Message) goes
+// stream frame) is passed through unchanged; everything else (proto.Message) goes
 // through the proto path, covering both flag-off and the proto fallback.
-func (c *traceQueryResponseCodec) Marshal(v any) ([]byte, error) {
-	if TraceWireModeRaw() {
+func (c *streamQueryResponseCodec) Marshal(v any) ([]byte, error) {
+	if StreamWireModeRaw() {
 		if b, ok := v.([]byte); ok {
 			return c.raw.Marshal(b)
 		}
@@ -42,8 +42,9 @@ func (c *traceQueryResponseCodec) Marshal(v any) ([]byte, error) {
 // Unmarshal decodes the response. In raw wire mode a magic-prefixed body is
 // returned as []byte (the columnar frame, decoded downstream by the liaison);
 // otherwise it is proto-unmarshaled.
-func (c *traceQueryResponseCodec) Unmarshal(body []byte) (any, error) {
-	if TraceWireModeRaw() && len(body) > 0 && body[0] == RawFrameMagicLeadingByte {
+func (c *streamQueryResponseCodec) Unmarshal(body []byte) (any, error) {
+	if StreamWireModeRaw() && len(body) > 0 && body[0] == RawFrameMagicLeadingByte {
+		streamFrameDecoded.Add(1)
 		return c.raw.Unmarshal(body)
 	}
 	return c.proto.Unmarshal(body)
diff --git a/api/data/stream_frame_test.go b/api/data/stream_frame_test.go
new file mode 100644
index 000000000..4d7345366
--- /dev/null
+++ b/api/data/stream_frame_test.go
@@ -0,0 +1,107 @@
+// 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.
+
+package data
+
+import (
+	"testing"
+
+	"github.com/stretchr/testify/require"
+	"google.golang.org/protobuf/proto"
+
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+)
+
+func newStreamCodec() *streamQueryResponseCodec {
+	return &streamQueryResponseCodec{
+		proto: NewProtoCodec(func() proto.Message { return &streamv1.QueryResponse{} }),
+		raw:   NewRawFrameCodec(),
+	}
+}
+
+// TestStreamCodec_RawPassthrough verifies that flag-on the codec passes a
+// columnar frame ([]byte) through unchanged on both encode and decode.
+func TestStreamCodec_RawPassthrough(t *testing.T) {
+	SetStreamWireModeRaw(true)
+	defer SetStreamWireModeRaw(false)
+	c := newStreamCodec()
+
+	frame := []byte{RawFrameMagicLeadingByte, 0x01, 0x02, 0x03}
+	body, err := c.Marshal(frame)
+	require.NoError(t, err)
+	require.Equal(t, frame, body, "raw frame must pass through Marshal unchanged")
+
+	got, err := c.Unmarshal(body)
+	require.NoError(t, err)
+	decoded, ok := got.([]byte)
+	require.True(t, ok, "raw-mode Unmarshal of a magic-prefixed body must return []byte")
+	require.Equal(t, frame, decoded, "raw frame must pass through Unmarshal unchanged")
+}
+
+// TestStreamCodec_RawEmptyBody verifies that flag-on, a nil/empty body (a
+// legitimate empty distributed result) falls through to the proto path, yielding
+// an empty *streamv1.QueryResponse rather than being magic-validated.
+func TestStreamCodec_RawEmptyBody(t *testing.T) {
+	SetStreamWireModeRaw(true)
+	defer SetStreamWireModeRaw(false)
+	c := newStreamCodec()
+
+	got, err := c.Unmarshal(nil)
+	require.NoError(t, err)
+	decoded, ok := got.(*streamv1.QueryResponse)
+	require.True(t, ok)
+	require.Empty(t, decoded.GetElements())
+}
+
+// TestStreamCodec_FlagOffIsProto verifies flag-off encodes byte-identically to
+// plain proto.Marshal and round-trips through the proto path.
+func TestStreamCodec_FlagOffIsProto(t *testing.T) {
+	SetStreamWireModeRaw(false)
+	c := newStreamCodec()
+	orig := &streamv1.QueryResponse{
+		Elements: []*streamv1.Element{{ElementId: "element-1", Timestamp: nil}},
+	}
+
+	body, err := c.Marshal(orig)
+	require.NoError(t, err)
+	want, err := proto.Marshal(orig)
+	require.NoError(t, err)
+	require.Equal(t, want, body, "flag-off must encode byte-identically to proto.Marshal")
+
+	got, err := c.Unmarshal(body)
+	require.NoError(t, err)
+	require.True(t, proto.Equal(orig, got.(*streamv1.QueryResponse)))
+}
+
+// TestStreamCodec_FlagOnProtoFallback verifies that flag-on, a proto.Message
+// value (e.g. the tracing path) still goes through the proto path.
+func TestStreamCodec_FlagOnProtoFallback(t *testing.T) {
+	SetStreamWireModeRaw(true)
+	defer SetStreamWireModeRaw(false)
+	c := newStreamCodec()
+	orig := &streamv1.QueryResponse{}
+
+	body, err := c.Marshal(orig)
+	require.NoError(t, err)
+	want, err := proto.Marshal(orig)
+	require.NoError(t, err)
+	require.Equal(t, want, body)
+
+	got, err := c.Unmarshal(body)
+	require.NoError(t, err)
+	require.True(t, proto.Equal(orig, got.(*streamv1.QueryResponse)))
+}
diff --git a/api/data/trace_frame.go b/api/data/trace_frame.go
index 71b716b86..6cff54dbf 100644
--- a/api/data/trace_frame.go
+++ b/api/data/trace_frame.go
@@ -44,6 +44,7 @@ func (c *traceQueryResponseCodec) Marshal(v any) ([]byte, error) {
 // otherwise it is proto-unmarshaled.
 func (c *traceQueryResponseCodec) Unmarshal(body []byte) (any, error) {
 	if TraceWireModeRaw() && len(body) > 0 && body[0] == RawFrameMagicLeadingByte {
+		traceFrameDecoded.Add(1)
 		return c.raw.Unmarshal(body)
 	}
 	return c.proto.Unmarshal(body)
diff --git a/banyand/internal/sidx/sidx.go b/banyand/internal/sidx/sidx.go
index 7f5e118b2..7aa42b037 100644
--- a/banyand/internal/sidx/sidx.go
+++ b/banyand/internal/sidx/sidx.go
@@ -1000,7 +1000,10 @@ func releaseBlockCursor(bc *blockCursor) {
 	bc.p = nil
 	bc.bm = nil
 	bc.userKeys = bc.userKeys[:0]
-	bc.data = bc.data[:0]
+	// Nil the data slice rather than zero-slicing so that sub-slices into
+	// the BytesBlockDecoder backing array (allocated in loadBlockData) become
+	// unreachable and can be reclaimed by GC when the cursor is pooled.
+	bc.data = nil
 	bc.tags = nil
 	bc.seriesID = 0
 	bc.idx = 0
diff --git a/banyand/measure/block_batch.go b/banyand/measure/block_batch.go
index 7922f98ed..afb007cf4 100644
--- a/banyand/measure/block_batch.go
+++ b/banyand/measure/block_batch.go
@@ -126,7 +126,8 @@ func (bc *blockCursor) copyAllToBatch(b *model.MeasureBatch, schema *vectorized.
 			fieldIdx++
 			bc.fillFieldColumnAllRows(col, def, idx, offset, desc)
 		case vectorized.RoleTimestamp, vectorized.RoleVersion,
-			vectorized.RoleSeriesID, vectorized.RoleShardID:
+			vectorized.RoleSeriesID, vectorized.RoleShardID,
+			vectorized.RoleElementID, vectorized.RoleOrderKey:
 			// Metadata handled above.
 		}
 	}
@@ -263,7 +264,8 @@ func (bc *blockCursor) copyToBatch(b *model.MeasureBatch, schema *vectorized.Bat
 			fieldIdx++
 			bc.fillFieldCell(col, def, bc.idx)
 		case vectorized.RoleTimestamp, vectorized.RoleVersion,
-			vectorized.RoleSeriesID, vectorized.RoleShardID:
+			vectorized.RoleSeriesID, vectorized.RoleShardID,
+			vectorized.RoleElementID, vectorized.RoleOrderKey:
 			// Metadata handled via the parallel slices above.
 		}
 	}
@@ -336,7 +338,8 @@ func (bc *blockCursor) replaceInBatch(b *model.MeasureBatch, schema *vectorized.
 			fieldIdx++
 			bc.setFieldCellAt(col, def, bc.idx, lastRow)
 		case vectorized.RoleTimestamp, vectorized.RoleVersion,
-			vectorized.RoleSeriesID, vectorized.RoleShardID:
+			vectorized.RoleSeriesID, vectorized.RoleShardID,
+			vectorized.RoleElementID, vectorized.RoleOrderKey:
 			// Metadata handled above.
 		}
 	}
diff --git a/banyand/measure/query_batch.go b/banyand/measure/query_batch.go
index b45269dc9..9ba8de365 100644
--- a/banyand/measure/query_batch.go
+++ b/banyand/measure/query_batch.go
@@ -334,7 +334,8 @@ func (iqr *indexSortResult) copyToBatch(b *model.MeasureBatch, schema *vectorize
 			fieldIdx++
 			iqr.fillSegFieldCell(col, def, fr)
 		case vectorized.RoleTimestamp, vectorized.RoleVersion,
-			vectorized.RoleSeriesID, vectorized.RoleShardID:
+			vectorized.RoleSeriesID, vectorized.RoleShardID,
+			vectorized.RoleElementID, vectorized.RoleOrderKey:
 			// Metadata handled via the parallel slices above.
 		}
 	}
diff --git a/banyand/observability/services/metrics_vec_frame.go b/banyand/observability/services/metrics_vec_frame.go
new file mode 100644
index 000000000..b8dd26e2d
--- /dev/null
+++ b/banyand/observability/services/metrics_vec_frame.go
@@ -0,0 +1,74 @@
+// 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.
+
+package services
+
+import (
+	"sync"
+
+	"github.com/apache/skywalking-banyandb/api/data"
+	"github.com/apache/skywalking-banyandb/banyand/observability"
+	"github.com/apache/skywalking-banyandb/pkg/meter"
+)
+
+// vecFrameScope holds the query-layer wire-format metrics. They answer a question
+// an operator cannot otherwise ask: is this node actually speaking the native
+// columnar frame, or has it silently fallen back to protobuf?
+//
+// That distinction is load-bearing. The frame is only emitted by a DISTRIBUTED data
+// node with the engine's vectorized path enabled, so a standalone server always
+// reports zero encodes however the flag is set — and a rolling upgrade that brings
+// data nodes up before liaisons produces frames that the older liaisons cannot
+// decode (see docs/operation/upgrade.md). These series make both situations visible
+// instead of leaving them to be inferred from configuration.
+var vecFrameScope = observability.RootScope.SubScope("vec_frame")
+
+var (
+	vecFrameGaugesMu   sync.RWMutex
+	vecFrameEncodedGge meter.Gauge
+	vecFrameDecodedGge meter.Gauge
+)
+
+func init() {
+	MetricsCollector.Register("vec_frame", collectVecFrame)
+}
+
+func (p *metricService) initVecFrameMetrics() {
+	factory := p.With(vecFrameScope)
+	vecFrameGaugesMu.Lock()
+	defer vecFrameGaugesMu.Unlock()
+	// Cumulative counts published as gauges: the values live in api/data as
+	// process-global atomics (that package must stay free of an observability
+	// dependency), so they are sampled here rather than incremented through a
+	// counter handle at the call site.
+	vecFrameEncodedGge = factory.NewGauge("encoded", "engine")
+	vecFrameDecodedGge = factory.NewGauge("decoded", "engine")
+}
+
+func collectVecFrame() {
+	vecFrameGaugesMu.RLock()
+	defer vecFrameGaugesMu.RUnlock()
+	if vecFrameEncodedGge == nil || vecFrameDecodedGge == nil {
+		return
+	}
+	vecFrameEncodedGge.Set(float64(data.MeasureFrameEncodedCount()), "measure")
+	vecFrameDecodedGge.Set(float64(data.MeasureFrameDecodedCount()), "measure")
+	vecFrameEncodedGge.Set(float64(data.StreamFrameEncodedCount()), "stream")
+	vecFrameDecodedGge.Set(float64(data.StreamFrameDecodedCount()), "stream")
+	vecFrameEncodedGge.Set(float64(data.TraceFrameEncodedCount()), "trace")
+	vecFrameDecodedGge.Set(float64(data.TraceFrameDecodedCount()), "trace")
+}
diff --git a/banyand/observability/services/metrics_vec_frame_test.go b/banyand/observability/services/metrics_vec_frame_test.go
new file mode 100644
index 000000000..202bc874b
--- /dev/null
+++ b/banyand/observability/services/metrics_vec_frame_test.go
@@ -0,0 +1,107 @@
+// 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.
+
+package services
+
+import (
+	"testing"
+
+	"github.com/prometheus/client_golang/prometheus"
+	"github.com/stretchr/testify/require"
+
+	"github.com/apache/skywalking-banyandb/api/data"
+)
+
+// gatherVecFrame returns the sample values of one vec_frame metric family keyed by
+// the engine label, reading them the way a scraper would rather than through the
+// gauge handles the code under test holds.
+func gatherVecFrame(t *testing.T, reg *prometheus.Registry, name string) map[string]float64 {
+	t.Helper()
+	families, err := reg.Gather()
+	require.NoError(t, err)
+	out := map[string]float64{}
+	for _, mf := range families {
+		if mf.GetName() != name {
+			continue
+		}
+		for _, m := range mf.GetMetric() {
+			engine := ""
+			for _, lp := range m.GetLabel() {
+				if lp.GetName() == "engine" {
+					engine = lp.GetValue()
+				}
+			}
+			out[engine] = m.GetGauge().GetValue()
+		}
+	}
+	return out
+}
+
+// TestVecFrameMetricsArePublished is the guard on the guard. The frame counters
+// exist so a soak can assert the columnar wire format is genuinely in use, but that
+// assertion is only worth anything if the values actually reach a scrape endpoint —
+// a silent registration failure would look exactly like a cluster emitting no
+// frames, which is the confusion the counters were added to end.
+func TestVecFrameMetricsArePublished(t *testing.T) {
+	svc := newTestPromService(t, true)
+	svc.promReg = prometheus.NewRegistry()
+	svc.initVecFrameMetrics()
+
+	// A labeled gauge has no child series until something Sets it, so the family
+	// is absent from a scrape until the first collection tick. A soak that probes
+	// for these series immediately after startup must allow for that.
+	require.Empty(t, gatherVecFrame(t, svc.promReg, "banyandb_vec_frame_encoded"),
+		"no series should exist before the first collect")
+
+	collectVecFrame()
+	before := gatherVecFrame(t, svc.promReg, "banyandb_vec_frame_encoded")
+	require.Contains(t, before, "stream", "the encoded family must carry a per-engine series")
+	require.Contains(t, before, "measure")
+	require.Contains(t, before, "trace")
+
+	// Move the underlying process-global counter the way the send path does, then
+	// run the collector the metrics loop drives.
+	data.IncrFrameEncoded(data.TopicStreamQuery)
+	collectVecFrame()
+
+	after := gatherVecFrame(t, svc.promReg, "banyandb_vec_frame_encoded")
+	require.Equal(t, before["stream"]+1, after["stream"],
+		"an encoded frame must be visible on the scrape endpoint")
+	require.Equal(t, before["trace"], after["trace"], "a stream frame must not move the trace series")
+	require.Equal(t, before["measure"], after["measure"], "a stream frame must not move the measure series")
+
+	decoded := gatherVecFrame(t, svc.promReg, "banyandb_vec_frame_decoded")
+	require.Contains(t, decoded, "stream", "the decoded family must be published too")
+}
+
+// TestCollectVecFrameBeforeInit asserts the collector is safe before the gauges are
+// built. It is registered from an init() but the gauges are created during Serve,
+// so the metrics loop can reach it first — and a metric service that panics on
+// startup would take the node with it.
+func TestCollectVecFrameBeforeInit(t *testing.T) {
+	vecFrameGaugesMu.Lock()
+	savedEnc, savedDec := vecFrameEncodedGge, vecFrameDecodedGge
+	vecFrameEncodedGge, vecFrameDecodedGge = nil, nil
+	vecFrameGaugesMu.Unlock()
+	defer func() {
+		vecFrameGaugesMu.Lock()
+		vecFrameEncodedGge, vecFrameDecodedGge = savedEnc, savedDec
+		vecFrameGaugesMu.Unlock()
+	}()
+
+	require.NotPanics(t, collectVecFrame)
+}
diff --git a/banyand/observability/services/service.go b/banyand/observability/services/service.go
index f051bfd7d..98fb2ecbf 100644
--- a/banyand/observability/services/service.go
+++ b/banyand/observability/services/service.go
@@ -217,6 +217,7 @@ func (p *metricService) Serve() run.StopNotify {
 		return p.serveWithoutListener()
 	}
 	p.initMetrics()
+	p.initVecFrameMetrics()
 	startupCtx, cancelStartup := context.WithTimeout(context.Background(), 30*time.Second)
 	defer cancelStartup()
 	if containsMode(p.modes, flagNativeMode) {
diff --git a/banyand/query/processor.go b/banyand/query/processor.go
index 0c0cc01fa..ed51c2279 100644
--- a/banyand/query/processor.go
+++ b/banyand/query/processor.go
@@ -50,8 +50,10 @@ import (
 	logical_trace "github.com/apache/skywalking-banyandb/pkg/query/logical/trace"
 	"github.com/apache/skywalking-banyandb/pkg/query/model"
 	"github.com/apache/skywalking-banyandb/pkg/query/tracelabels"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
 	vmeasure "github.com/apache/skywalking-banyandb/pkg/query/vectorized/measure"
 	vecplan "github.com/apache/skywalking-banyandb/pkg/query/vectorized/measure/plan"
+	streamframe "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream/frame"
 )
 
 const (
@@ -70,6 +72,12 @@ type streamQueryProcessor struct {
 	streamService stream.Service
 	*queryService
 	*bus.UnImplementedHealthyListener
+	// distributed is true on a distributed data node, whose query response is
+	// sent over the wire to a remote liaison that decodes the native columnar
+	// frame. It is false in standalone, where the local grpc service consumes the
+	// response directly and expects the proto body — so the frame must not be
+	// emitted there.
+	distributed bool
 }
 
 func (p *streamQueryProcessor) Rev(ctx context.Context, message bus.Message) (resp bus.Message) {
@@ -143,6 +151,22 @@ func (p *streamQueryProcessor) Rev(ctx context.Context, message bus.Message) (re
 			}
 		}()
 	}
+
+	// Vec dispatch: attempt the native columnar path before the row execution.
+	// Gated on the engine flag (VectorizedConfig().Enabled). The plan must expose
+	// StreamVecExecutable (single localIndexScan, no tag filter / multi-group /
+	// skipping filter) — otherwise the assertion fails and we fall through to the
+	// row path below. When tracing is on we MUST return a proto QueryResponse (it
+	// carries common.v1.Trace); the frame emit is gated on tracer == nil.
+	if p.streamService.VectorizedConfig().Enabled {
+		if handled, vecResp := p.tryStreamVecDispatch(ctx, plan, queryCriteria, tracer != nil); handled {
+			resp = vecResp
+			se := plan.(executor.StreamExecutable)
+			se.Close()
+			return
+		}
+	}
+
 	se := plan.(executor.StreamExecutable)
 	defer se.Close()
 	entities, err := se.Execute(ctx)
@@ -163,6 +187,197 @@ func (p *streamQueryProcessor) Rev(ctx context.Context, message bus.Message) (re
 	return
 }
 
+// tryStreamVecDispatch attempts the native columnar (vec) path for a stream
+// query. It returns (false, nil) when the plan is not vec-eligible (the caller
+// then runs the row path). On success it returns (true, resp) where resp is:
+//   - a []byte columnar frame body, when the process is a distributed data node
+//     with the raw wire mode on and tracing off (traced == false);
+//   - a *streamv1.QueryResponse with materialized Elements, for standalone, for a
+//     traced query (the frame has no trace channel), or when the wire mode is off.
+//
+// Any error is surfaced as a *common.Error response (handled=true) rather than
+// falling back to row, matching the measure/trace no-silent-fallback discipline
+// once we have committed to vec.
+func (p *streamQueryProcessor) tryStreamVecDispatch(ctx context.Context, plan logical.Plan,
+	queryCriteria *streamv1.QueryRequest, traced bool,
+) (bool, bus.Message) {
+	now := time.Now().UnixNano()
+
+	// Multi-group query (*limit → *mergePlan): run the vec scan+pipeline per group,
+	// then cross-group merge via the SAME primitives the row mergePlan.Execute uses
+	// (MergeGroupElements) and apply the outer offset:offset+limit slice. The
+	// cross-group merge is element-level (proto Elements), so this always takes the
+	// proto egress — the liaison merges proto/frame bodies interchangeably.
+	if merge, ok := logical_stream.VecMergeExecutable(plan); ok {
+		return p.tryVecMergeDispatch(ctx, merge, queryCriteria, now)
+	}
+
+	vecExec := logical_stream.VecExecutable(plan)
+	if vecExec == nil {
+		return false, bus.Message{}
+	}
+	batches, schema, execErr := vecExec.ExecuteVectorized(ctx)
+	if execErr != nil {
+		p.log.Error().Err(execErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to execute the vectorized query plan")
+		return true, bus.NewMessage(bus.MessageID(now), common.NewError("execute the vectorized query plan for stream %s: %v", queryCriteria.GetName(), execErr))
+	}
+
+	// A criteria query carries a per-element tag filter (VecTagFilter) that must be
+	// applied to materialized Elements (byte-identical to the row tagFilterPlan). The
+	// frame path operates on columnar batches and has no element-level filter stage,
+	// so a filter query forces the proto egress; the liaison merges proto Elements
+	// and frame bodies interchangeably (mixed-mode), so this stays correct.
+	tagFilter, hiddenTags, filterSchema, hasFilter := logical_stream.VecTagFilter(plan)
+
+	// Data-node native wire mode (flag-on, no tracing): emit a columnar frame body
+	// so the send path passes it through and the liaison decodes it. The liaison
+	// applies the global offset/limit slice, so the data node emits the whole
+	// (already per-node-capped) batch set — no slice here.
+	if !hasFilter && streamVecEmitAsFrame(p.distributed, data.StreamWireModeRaw(), traced) {
+		merged, mergeErr := mergeStreamBatches(schema, batches)
+		if mergeErr != nil {
+			p.log.Error().Err(mergeErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to merge the vectorized stream batches")
+			return true, bus.NewMessage(bus.MessageID(now), common.NewError("merge the vectorized stream batches for stream %s: %v", queryCriteria.GetName(), mergeErr))
+		}
+		frameBytes, encErr := streamframe.Encode(merged)
+		if encErr != nil {
+			p.log.Error().Err(encErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to encode the vectorized stream frame")
+			return true, bus.NewMessage(bus.MessageID(now), common.NewError("encode the vectorized stream frame for stream %s: %v", queryCriteria.GetName(), encErr))
+		}
+		return true, bus.NewMessage(bus.MessageID(now), frameBytes)
+	}
+
+	// Standalone (or traced, or wire mode off): materialize Elements in process and
+	// apply the client offset:offset+limit slice the row *limit node would apply.
+	elements, buildErr := stream.BuildElementsFromBatches(batches, vecExec.ProjectionTags())
+	if buildErr != nil {
+		p.log.Error().Err(buildErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to materialize vectorized stream elements")
+		return true, bus.NewMessage(bus.MessageID(now), common.NewError("materialize vectorized stream elements for stream %s: %v", queryCriteria.GetName(), buildErr))
+	}
+	// Criteria query: apply the SAME per-element tagFilter.Match + hidden-tag strip
+	// as the row tagFilterPlan.Execute, BEFORE the outer offset:offset+limit slice
+	// (row order: scan → merge → distinct → filter → limit). The element set handed
+	// to the filter already matches row's, because the merge capped (or deliberately
+	// did not cap) according to the scan's order type — see scanResumesAcrossPulls.
+	if hasFilter {
+		filtered, filterErr := applyStreamTagFilter(elements, tagFilter, hiddenTags, filterSchema)
+		if filterErr != nil {
+			p.log.Error().Err(filterErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to apply the vectorized stream tag filter")
+			return true, bus.NewMessage(bus.MessageID(now), common.NewError("apply the vectorized stream tag filter for stream %s: %v", queryCriteria.GetName(), filterErr))
+		}
+		elements = filtered
+	}
+	if offset, limit, ok := logical_stream.VecOffsetLimit(plan); ok {
+		elements = sliceStreamElements(elements, offset, limit)
+	}
+	return true, bus.NewMessage(bus.MessageID(now), &streamv1.QueryResponse{Elements: elements})
+}
+
+// tryVecMergeDispatch runs the vec path for a multi-group query (*limit →
+// *mergePlan). For EACH group it runs the vec scan → BuildElementsFromBatches →
+// (if the group carries criteria) the SAME per-element tagFilter.Match + hidden-tag
+// strip the row tagFilterPlan.Execute applies. It then cross-group merges via the
+// shared MergeGroupElements (the exact comparableElement/sortableElements +
+// sort.NewItemIter path the row mergePlan.Execute uses) and applies the outer
+// offset:offset+limit slice. Emits proto Elements (element-level merge/filter); the
+// liaison merges proto/frame bodies interchangeably.
+func (p *streamQueryProcessor) tryVecMergeDispatch(ctx context.Context, merge *logical_stream.VecMerge,
+	queryCriteria *streamv1.QueryRequest, now int64,
+) (bool, bus.Message) {
+	perGroup := make([][]*streamv1.Element, 0, len(merge.Groups))
+	for _, group := range merge.Groups {
+		batches, _, execErr := group.Scan.ExecuteVectorized(ctx)
+		if execErr != nil {
+			p.log.Error().Err(execErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to execute the vectorized stream group")
+			return true, bus.NewMessage(bus.MessageID(now), common.NewError("execute the vectorized query plan for stream %s: %v", queryCriteria.GetName(), execErr))
+		}
+		elements, buildErr := stream.BuildElementsFromBatches(batches, group.Scan.ProjectionTags())
+		if buildErr != nil {
+			p.log.Error().Err(buildErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to materialize vectorized stream group elements")
+			return true, bus.NewMessage(bus.MessageID(now), common.NewError("materialize vectorized stream elements for stream %s: %v", queryCriteria.GetName(), buildErr))
+		}
+		if group.HasFilter {
+			filtered, filterErr := applyStreamTagFilter(elements, group.TagFilter, group.HiddenTags, group.FilterSchema)
+			if filterErr != nil {
+				p.log.Error().Err(filterErr).RawJSON("req", logger.Proto(queryCriteria)).Msg("fail to apply the vectorized stream group tag filter")
+				return true, bus.NewMessage(bus.MessageID(now), common.NewError("apply the vectorized stream tag filter for stream %s: %v", queryCriteria.GetName(), filterErr))
+			}
+			elements = filtered
+		}
+		perGroup = append(perGroup, elements)
+	}
+	merged := logical_stream.MergeGroupElements(perGroup, merge.SortByTime, merge.SortTagSpec, merge.Desc)
+	merged = sliceStreamElements(merged, merge.Offset, merge.Limit)
+	return true, bus.NewMessage(bus.MessageID(now), &streamv1.QueryResponse{Elements: merged})
+}
+
+// streamVecEmitAsFrame is the data-node emit gate: emit a native columnar frame
+// ([]byte) only on a distributed data node with the raw wire mode on and tracing
+// OFF. A traced query MUST return a *streamv1.QueryResponse proto (it carries
+// common.v1.Trace, which the frame has no channel for) — so tracing forces the
+// proto egress. Standalone (!distributed) and wire-mode-off also take proto.
+func streamVecEmitAsFrame(distributed, wireModeRaw, traced bool) bool {
+	return distributed && wireModeRaw && !traced
+}
+
+// mergeStreamBatches concatenates the active rows of several columnar batches into
+// a single batch so the frame carries one contiguous columnar block. Selection is
+// respected via the batch schema's active-row semantics at frame encode; here we
+// simply flatten Selection into a fresh dense batch.
+func mergeStreamBatches(schema *vectorized.BatchSchema, batches []*vectorized.RecordBatch) (*vectorized.RecordBatch, error) {
+	total := 0
+	for _, b := range batches {
+		if b != nil {
+			total += b.ActiveLen()
+		}
+	}
+	out := vectorized.NewRecordBatch(schema, total)
+	for _, b := range batches {
+		if b == nil || b.ActiveLen() == 0 {
+			continue
+		}
+		if appendErr := vectorized.AppendActiveRows(out, b); appendErr != nil {
+			return nil, appendErr
+		}
+	}
+	return out, nil
+}
+
+// applyStreamTagFilter keeps only the elements whose tag families satisfy the
+// criteria tag filter, then strips the filter-only (hidden) tags from the kept
+// elements — mirroring the row tagFilterPlan.Execute per-element loop exactly so
+// the vec result is byte-identical.
+func applyStreamTagFilter(elements []*streamv1.Element, tagFilter logical.TagFilter,
+	hiddenTags logical.HiddenTagSet, s logical.Schema,
+) ([]*streamv1.Element, error) {
+	filtered := make([]*streamv1.Element, 0, len(elements))
+	for _, e := range elements {
+		ok, matchErr := tagFilter.Match(logical.TagFamilies(e.TagFamilies), s)
+		if matchErr != nil {
+			return nil, matchErr
+		}
+		if ok {
+			e.TagFamilies = hiddenTags.StripHiddenTags(e.TagFamilies)
+			filtered = append(filtered, e)
+		}
+	}
+	return filtered, nil
+}
+
+// sliceStreamElements applies the client offset:offset+limit window, matching the
+// row *limit.Execute egress slice.
+func sliceStreamElements(elements []*streamv1.Element, offset, limit uint32) []*streamv1.Element {
+	start := int(offset)
+	if start >= len(elements) {
+		return []*streamv1.Element{}
+	}
+	end := start + int(limit)
+	if end > len(elements) {
+		end = len(elements)
+	}
+	return elements[start:end]
+}
+
 type measureQueryProcessor struct {
 	measureService measure.Service
 	*queryService
diff --git a/banyand/query/query.go b/banyand/query/query.go
index acd855ae0..c4e5ca843 100644
--- a/banyand/query/query.go
+++ b/banyand/query/query.go
@@ -73,6 +73,7 @@ func NewService(_ context.Context, streamService stream.Service, measureService
 	svc.sqp = &streamQueryProcessor{
 		streamService: streamService,
 		queryService:  svc,
+		distributed:   distributed,
 	}
 	// topN query processor
 	svc.nqp = &topNQueryProcessor{
diff --git a/banyand/query/stream_vec_emit_test.go b/banyand/query/stream_vec_emit_test.go
new file mode 100644
index 000000000..c449a85ff
--- /dev/null
+++ b/banyand/query/stream_vec_emit_test.go
@@ -0,0 +1,54 @@
+// 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.
+
+package query
+
+import "testing"
+
+// TestStreamVecEmitAsFrame_TraceStaysProto exhaustively pins the data-node emit
+// gate. The load-bearing case: traced=true MUST NOT emit a frame in any
+// combination, because a *streamv1.QueryResponse is the only body that carries
+// common.v1.Trace. Standalone (!distributed) and wire-mode-off also stay proto.
+func TestStreamVecEmitAsFrame_TraceStaysProto(t *testing.T) {
+	cases := []struct {
+		name        string
+		distributed bool
+		wireRaw     bool
+		traced      bool
+		wantFrame   bool
+	}{
+		{name: "distributed+raw+untraced=frame", distributed: true, wireRaw: true, traced: false, wantFrame: true},
+		{name: "distributed+raw+traced=proto", distributed: true, wireRaw: true, traced: true, wantFrame: false},
+		{name: "distributed+off+untraced=proto", distributed: true, wireRaw: false, traced: false, wantFrame: false},
+		{name: "standalone+raw+untraced=proto", distributed: false, wireRaw: true, traced: false, wantFrame: false},
+		{name: "standalone+raw+traced=proto", distributed: false, wireRaw: true, traced: true, wantFrame: false},
+		{name: "standalone+off+untraced=proto", distributed: false, wireRaw: false, traced: false, wantFrame: false},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			got := streamVecEmitAsFrame(tc.distributed, tc.wireRaw, tc.traced)
+			if got != tc.wantFrame {
+				t.Fatalf("streamVecEmitAsFrame(%v,%v,%v)=%v want %v",
+					tc.distributed, tc.wireRaw, tc.traced, got, tc.wantFrame)
+			}
+			// Invariant: a traced query never emits a frame.
+			if tc.traced && got {
+				t.Fatalf("traced query emitted a frame — trace channel would be lost")
+			}
+		})
+	}
+}
diff --git a/banyand/queue/sub/sub.go b/banyand/queue/sub/sub.go
index 6dd17bb4e..e0bd6ba80 100644
--- a/banyand/queue/sub/sub.go
+++ b/banyand/queue/sub/sub.go
@@ -315,11 +315,13 @@ func (s *server) marshalResponse(
 		return body, nil
 	case []byte:
 		rawAllowed := (topic == data.TopicInternalMeasureQuery && data.MeasureWireModeRaw()) ||
-			(topic == data.TopicTraceQuery && data.TraceWireModeRaw())
+			(topic == data.TopicTraceQuery && data.TraceWireModeRaw()) ||
+			(topic == data.TopicStreamQuery && data.StreamWireModeRaw())
 		if !rawAllowed {
 			s.replyWithErrType(stream, writeEntity, nil, fmt.Sprintf("invalid response: unexpected raw body on topic %s", topic), identity, "marshal_error")
 			return nil, fmt.Errorf("invalid raw body")
 		}
+		data.IncrFrameEncoded(topic)
 		return d, nil
 	case *common.Error:
 		s.replyWithErrType(stream, writeEntity, nil, d.Error(), identity, "handler_error")
diff --git a/banyand/stream/benchmark_test.go b/banyand/stream/benchmark_test.go
index 73082260c..d7ae914d0 100644
--- a/banyand/stream/benchmark_test.go
+++ b/banyand/stream/benchmark_test.go
@@ -35,6 +35,7 @@ import (
 	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/storage"
+	"github.com/apache/skywalking-banyandb/banyand/protector"
 	"github.com/apache/skywalking-banyandb/pkg/convert"
 	"github.com/apache/skywalking-banyandb/pkg/index"
 	"github.com/apache/skywalking-banyandb/pkg/index/posting"
@@ -51,6 +52,7 @@ const (
 	version                 = "1.0.0"
 	entityTagValuePrefix    = "entity"
 	filterTagValuePrefix    = "value"
+	testGroupName           = "test"
 )
 
 type parameter struct {
@@ -169,7 +171,7 @@ func generateData(p parameter) ([]*elements, []index.Documents, mockIndex) {
 	return esList, docsList, idx
 }
 
-func openDatabase(b *testing.B, path string) storage.TSDB[*tsTable, option] {
+func openDatabase(b testing.TB, path string) storage.TSDB[*tsTable, option] {
 	ir := storage.IntervalRule{
 		Unit: storage.DAY,
 		Num:  1,
@@ -180,9 +182,13 @@ func openDatabase(b *testing.B, path string) storage.TSDB[*tsTable, option] {
 		TSTableCreator:  newTSTable,
 		SegmentInterval: ir,
 		TTL:             ir,
+		Option: option{
+			mergePolicy: newDefaultMergePolicyForTesting(),
+			protector:   protector.Nop{},
+		},
 	}
 
-	group := "test"
+	group := testGroupName
 	db, err := storage.OpenTSDB(
 		common.SetPosition(context.Background(), func(p common.Position) common.Position {
 			p.Module = "stream"
@@ -195,7 +201,7 @@ func openDatabase(b *testing.B, path string) storage.TSDB[*tsTable, option] {
 	return db
 }
 
-func write(b *testing.B, p parameter, esList []*elements, docsList []index.Documents) storage.TSDB[*tsTable, option] {
+func write(b testing.TB, p parameter, esList []*elements, docsList []index.Documents) storage.TSDB[*tsTable, option] {
 	// Initialize a tstIter object.
 	tmpPath, defFn := test.Space(require.New(b))
 	defer defFn()
diff --git a/banyand/stream/metadata.go b/banyand/stream/metadata.go
index 6d0866faa..b8bb806b4 100644
--- a/banyand/stream/metadata.go
+++ b/banyand/stream/metadata.go
@@ -545,7 +545,7 @@ func (s *supplier) OpenResource(spec resourceSchema.Resource) (resourceSchema.In
 	streamSchema := spec.Schema().(*databasev1.Stream)
 	return openStream(streamSpec{
 		schema: streamSchema,
-	}, s.l, s.pm, s.schemaRepo), nil
+	}, s.l, s.pm, s.schemaRepo, s.option.vectorized), nil
 }
 
 func (s *supplier) ResourceSchema(md *commonv1.Metadata) (resourceSchema.ResourceSchema, error) {
@@ -639,7 +639,7 @@ func (s *queueSupplier) OpenResource(spec resourceSchema.Resource) (resourceSche
 	streamSchema := spec.Schema().(*databasev1.Stream)
 	return openStream(streamSpec{
 		schema: streamSchema,
-	}, s.l, s.pm, s.schemaRepo), nil
+	}, s.l, s.pm, s.schemaRepo, s.option.vectorized), nil
 }
 
 func (s *queueSupplier) ResourceSchema(md *commonv1.Metadata) (resourceSchema.ResourceSchema, error) {
diff --git a/banyand/stream/metadata_test.go b/banyand/stream/metadata_test.go
index ce36a11d6..619636105 100644
--- a/banyand/stream/metadata_test.go
+++ b/banyand/stream/metadata_test.go
@@ -128,7 +128,7 @@ var _ = Describe("Metadata", func() {
 				})
 				Expect(err).ShouldNot(HaveOccurred())
 				Expect(streamSchema).ShouldNot(BeNil())
-				writeData(svcs, size, nil, false)
+				writeData(svcs, size, 0, nil, false)
 				_ = queryAllMeasurements(svcs, size, nil, "")
 
 				l := len(streamSchema.TagFamilies)
@@ -180,7 +180,7 @@ var _ = Describe("Metadata", func() {
 					}
 				})
 				It("get new values for the new added tags", func() {
-					writeData(svcs, size, []string{"test1", "test2", "test3"}, independentFamily)
+					writeData(svcs, size, size, []string{"test1", "test2", "test3"}, independentFamily)
 					dp := queryAllMeasurements(svcs, size*2, []string{"new_tag"}, "")
 					for i := 0; i < size; i++ {
 						Expect(dp[i].TagFamilies[0].Tags[3].Key).Should(Equal("new_tag"))
@@ -211,7 +211,7 @@ var _ = Describe("Metadata", func() {
 					}
 				})
 				It("get new values for the new added tags", func() {
-					writeData(svcs, size, []string{"test1", "test2", "test3"}, independentFamily)
+					writeData(svcs, size, size, []string{"test1", "test2", "test3"}, independentFamily)
 					dp := queryAllMeasurements(svcs, size*2, []string{"new_tag"}, "independent_family")
 
 					for i := 0; i < size; i++ {
@@ -236,7 +236,11 @@ var _ = Describe("Metadata", func() {
 	})
 })
 
-func writeData(svcs *services, expectedSize int, newTag []string, independentFamily bool) {
+// writeData writes expectedSize elements. idOffset shifts the element ids so a
+// second call does not reuse the ids of the first: an element_id identifies an
+// element globally, so reusing one makes the two writes the same element and the
+// query layer is free to collapse them.
+func writeData(svcs *services, expectedSize, idOffset int, newTag []string, independentFamily bool) {
 	bp := svcs.pipeline.NewBatchPublisher(5 * time.Second)
 	defer bp.Close()
 	for i := 0; i < expectedSize; i++ {
@@ -248,7 +252,7 @@ func writeData(svcs *services, expectedSize int, newTag []string, independentFam
 			},
 			Element: &streamv1.ElementValue{
 				Timestamp: timestamppb.New(timestamp.NowMilli()),
-				ElementId: "element" + iStr,
+				ElementId: "element" + strconv.Itoa(idOffset+i),
 				TagFamilies: []*modelv1.TagFamilyForWrite{
 					{
 						Tags: []*modelv1.TagValue{
@@ -396,7 +400,7 @@ var _ = Describe("Schema Change", func() {
 			env := setupSchemaChangeStream(svcs, streamName, groupName, streamSetupOptions{withExtraTag: true})
 			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-2*time.Hour), 5, writeDataOptions{extraTag: extraTagInt})
 			deleteExtraTag(svcs, streamName, groupName)
-			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{})
+			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{elementIDOffset: 5})
 
 			test.EventuallyConsistently(func(innerGm Gomega) {
 				elements := querySchemaChangeData(svcs, streamName, groupName, now.Add(-3*time.Hour), now,
@@ -427,7 +431,7 @@ var _ = Describe("Schema Change", func() {
 			env := setupSchemaChangeStream(svcs, streamName, groupName, streamSetupOptions{})
 			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-2*time.Hour), 5, writeDataOptions{})
 			addExtraTag(svcs, streamName, groupName)
-			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{extraTag: extraTagInt})
+			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{extraTag: extraTagInt, elementIDOffset: 5})
 
 			Eventually(func(innerGm Gomega) {
 				elements := querySchemaChangeData(svcs, streamName, groupName, now.Add(-3*time.Hour), now,
@@ -467,7 +471,8 @@ var _ = Describe("Schema Change", func() {
 			env := setupSchemaChangeStream(svcs, streamName, groupName, streamSetupOptions{withExtraTag: true})
 			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-2*time.Hour), 5, writeDataOptions{extraTag: extraTagInt})
 			changeExtraTagType(svcs, streamName, groupName)
-			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{extraTag: extraTagString, traceIDPrefix: "trace_new_"})
+			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3,
+				writeDataOptions{extraTag: extraTagString, traceIDPrefix: "trace_new_", elementIDOffset: 5})
 
 			Eventually(func(innerGm Gomega) {
 				elements := querySchemaChangeData(svcs, streamName, groupName, now.Add(-3*time.Hour), now,
@@ -567,7 +572,7 @@ var _ = Describe("Schema Change", func() {
 			env := setupSchemaChangeStream(svcs, streamName, groupName, streamSetupOptions{withExtraTag: true})
 			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-2*time.Hour), 5, writeDataOptions{extraTag: extraTagInt})
 			deleteExtraTag(svcs, streamName, groupName)
-			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{})
+			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{elementIDOffset: 5})
 
 			test.EventuallyConsistently(func(innerGm Gomega) {
 				err := queryWithDeletedTagCondition(svcs, streamName, groupName, now)
@@ -585,7 +590,7 @@ var _ = Describe("Schema Change", func() {
 			env := setupSchemaChangeStream(svcs, streamName, groupName, streamSetupOptions{withExtraTag: true})
 			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-2*time.Hour), 5, writeDataOptions{extraTag: extraTagInt})
 			deleteExtraTag(svcs, streamName, groupName)
-			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{})
+			writeSchemaChangeData(svcs, streamName, groupName, now.Add(-1*time.Hour), 3, writeDataOptions{elementIDOffset: 5})
 
 			test.EventuallyConsistently(func(innerGm Gomega) {
 				err := queryWithDeletedTagProjection(svcs, streamName, groupName, now)
diff --git a/banyand/stream/query_vectorized.go b/banyand/stream/query_vectorized.go
new file mode 100644
index 000000000..50c7c9881
--- /dev/null
+++ b/banyand/stream/query_vectorized.go
@@ -0,0 +1,555 @@
+// 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.
+
+package stream
+
+import (
+	"context"
+	"errors"
+	"fmt"
+
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+	"github.com/apache/skywalking-banyandb/banyand/internal/storage"
+	"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/query/vectorized"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
+)
+
+// ErrQueryMemoryBudgetExceeded is returned by the vec scan when a block would be
+// decoded past the per-query QueryMemoryMiB soft budget (after the first-block
+// exception). The scan fails loud rather than silently dropping the block, so the
+// vec path preserves parity with the row path (which errors under memory pressure
+// via the protector) — a partial result would break vec==row equivalence.
+var ErrQueryMemoryBudgetExceeded = errors.New("stream: vectorized query memory budget exceeded")
+
+// streamVecScan is a pull-based columnar scan source for the stream engine. It
+// yields *vectorized.RecordBatch values built directly from blockCursor columns,
+// never constructing a model.StreamResult. Each NextBatch call returns one batch
+// (per block/cursor, per-cursor order preserved); NextBatch returns (nil, nil)
+// when the source is exhausted.
+//
+// Scope note: this source produces correct per-cursor columnar batches only.
+// Global cross-part/cross-shard ordering, dedup, and the in-order top-N cap are
+// M4 operators (SortedMerge/Distinct/Limit) and are deliberately NOT implemented
+// here — see .omc/plans/vectorized-stream-query.md §5.3. The scan therefore emits
+// EVERY matching row (chunked into batchSize batches); it does NOT truncate at
+// MaxElementSize, because a pre-merge storage-order truncation would keep the
+// wrong rows (e.g. the oldest rows for an ORDER BY ts DESC query, since blocks
+// are seriesID-major). The MaxElementSize cap is applied post-merge in the M4
+// pipeline (the correct in-order top-N), matching the row path.
+type streamVecScan struct {
+	sm             *stream
+	schema         *vectorized.BatchSchema
+	tr             *index.RangeOpts
+	ts             *blockScanner
+	tmpBlock       *block
+	mem            *vectorized.MemoryTracker
+	cur            *blockCursor
+	segments       []storage.Segment[*tsTable, option]
+	series         []*pbv1.Series
+	pending        []*blockCursor
+	orderTagFamily string
+	orderTagName   string
+	budgetErr      error
+	qo             queryOptions
+	batchSize      int
+	curOff         int
+	asc            bool
+	indexOrder     bool
+	budgetEngaged  bool
+	closed         bool
+}
+
+// Schema returns the batch schema stamped on every emitted batch.
+func (v *streamVecScan) Schema() *vectorized.BatchSchema { return v.schema }
+
+// NextBatch returns the next columnar batch, or (nil, nil) when exhausted.
+//
+// A single blockCursor can hold more than batchSize rows (stream blocks are
+// capped by uncompressed bytes, not row count), so the cursor is drained across
+// MULTIPLE batches via an advancing offset (v.curOff); the cursor is released
+// only once all its rows are consumed. This prevents silent row loss past
+// batchSize.
+func (v *streamVecScan) NextBatch(ctx context.Context) (*vectorized.RecordBatch, error) {
+	if v.closed {
+		return nil, nil
+	}
+	for {
+		if v.cur == nil {
+			bc, err := v.nextCursor(ctx)
+			if err != nil {
+				return nil, err
+			}
+			if bc == nil {
+				return nil, nil
+			}
+			v.cur = bc
+			v.curOff = 0
+		}
+		batch, err := v.cursorToBatch(v.cur, v.curOff)
+		if err != nil {
+			releaseBlockCursor(v.cur)
+			v.cur = nil
+			return nil, err
+		}
+		v.curOff += batch.Len
+		if v.curOff >= len(v.cur.timestamps) {
+			releaseBlockCursor(v.cur)
+			v.cur = nil
+		}
+		if batch.Len == 0 {
+			continue
+		}
+		return batch, nil
+	}
+}
+
+// nextCursor drains loaded blockCursors, refilling from the block scanner /
+// segment list on demand. It reuses the exact scan helpers the row path uses
+// (searchSeries, getBlockScanner, loadBlockCursor) — it does not duplicate their
+// logic. Returned cursors are positioned at their first row (asc) or last row
+// (desc); callers must releaseBlockCursor.
+func (v *streamVecScan) nextCursor(ctx context.Context) (*blockCursor, error) {
+	for {
+		if len(v.pending) > 0 {
+			bc := v.pending[0]
+			v.pending = v.pending[1:]
+			return bc, nil
+		}
+		// Soft byte budget exceeded: after the already-loaded cursors drain, fail
+		// loud rather than returning a partial result (row-path parity — the row
+		// path errors under memory pressure via the protector).
+		if v.budgetErr != nil {
+			return nil, v.budgetErr
+		}
+		if v.ts != nil {
+			if err := v.fillFromScanner(ctx); err != nil {
+				return nil, err
+			}
+			if len(v.pending) > 0 {
+				continue
+			}
+			// Scanner drained for this segment.
+			if len(v.ts.parts) == 0 {
+				v.ts.close()
+				v.ts = nil
+			}
+			continue
+		}
+		if len(v.segments) == 0 {
+			return nil, nil
+		}
+		var segment storage.Segment[*tsTable, option]
+		if v.asc {
+			segment = v.segments[len(v.segments)-1]
+			v.segments = v.segments[:len(v.segments)-1]
+		} else {
+			segment = v.segments[0]
+			v.segments = v.segments[1:]
+		}
+		qo, err := searchSeries(ctx, v.qo, segment, v.series)
+		if err != nil {
+			return nil, err
+		}
+		ts, err := getBlockScanner(ctx, segment, qo, v.sm.l, v.sm.pm, v.tr)
+		if err != nil {
+			return nil, err
+		}
+		if ts == nil {
+			continue
+		}
+		v.ts = ts
+	}
+}
+
+// fillFromScanner pulls one round of block-scan batches and materializes them
+// into loaded blockCursors appended to v.pending.
+func (v *streamVecScan) fillFromScanner(ctx context.Context) error {
+	batchCh := make(chan *blockScanResultBatch, 1)
+	scanErrCh := make(chan struct{})
+	go func() {
+		defer close(scanErrCh)
+		v.ts.scan(ctx, batchCh)
+		close(batchCh)
+	}()
+	is := v.sm.indexSchema.Load().(indexSchema)
+	var scanErr error
+	for batch := range batchCh {
+		if batch.err != nil {
+			if scanErr == nil {
+				scanErr = batch.err
+			}
+			releaseBlockScanResultBatch(batch)
+			continue
+		}
+		for i := range batch.bss {
+			bs := &batch.bss[i]
+			// Metadata preflight for the QueryMemoryMiB soft budget: predict whether
+			// decoding this block would push cumulative uncompressed bytes over the
+			// budget and, if so, FAIL LOUD before the expensive decode. The first block
+			// always decodes (first-block exception) so a too-small budget never
+			// rejects the whole query. When no budget is set (v.mem == nil) every block
+			// is decoded; the block scanner's protector.Memory quota still bounds it.
+			if v.mem != nil {
+				blockBytes := int64(bs.bm.uncompressedSizeBytes)
+				if v.budgetEngaged {
+					if reserveErr := v.mem.Reserve(blockBytes); reserveErr != nil {
+						if v.budgetErr == nil {
+							v.budgetErr = fmt.Errorf("%w: %w", ErrQueryMemoryBudgetExceeded, reserveErr)
+						}
+						continue
+					}
+				} else {
+					_ = v.mem.Reserve(blockBytes)
+					v.budgetEngaged = true
+				}
+			}
+			bc := generateBlockCursor()
+			bc.init(bs.p, &bs.bm, bs.qo)
+			if loadBlockCursor(bc, v.tmpBlock, bs.qo, is) {
+				if !v.asc {
+					bc.idx = len(bc.timestamps) - 1
+				} else {
+					bc.idx = 0
+				}
+				v.pending = append(v.pending, bc)
+			}
+		}
+		releaseBlockScanResultBatch(batch)
+	}
+	<-scanErrCh
+	return scanErr
+}
+
+// cursorToBatch converts a window [off, off+n) of a loaded blockCursor into a
+// columnar batch, where n is capped at batchSize. It reads the rows into the
+// batch columns using the exact decode copyTo uses (schemaType match →
+// mustDecodeTagValue; else NullTagValue). Reading a window (not always [0,len))
+// lets NextBatch drain a cursor larger than batchSize across several batches
+// without losing rows. Returns an error if an order-key tag value fails to marshal.
+func (v *streamVecScan) cursorToBatch(bc *blockCursor, off int) (*vectorized.RecordBatch, error) {
+	total := len(bc.timestamps)
+	n := total - off
+	if n > v.batchSize {
+		n = v.batchSize
+	}
+	if n <= 0 {
+		return &vectorized.RecordBatch{Schema: v.schema}, nil
+	}
+	end := off + n
+
+	batch := vectorized.NewRecordBatch(v.schema, n)
+	tsCol := batch.Columns[v.schema.TimestampIndex()].(*vectorized.TypedColumn[int64])
+	elemCol := batch.Columns[v.schema.ElementIDIndex()].(*vectorized.TypedColumn[int64])
+	seriesCol := batch.Columns[v.schema.SeriesIDIndex()].(*vectorized.TypedColumn[int64])
+
+	seriesColVal := vstream.SeriesIDToColumn(uint64(bc.bm.seriesID))
+	for row := off; row < end; row++ {
+		tsCol.Append(bc.timestamps[row])
+		elemCol.Append(vstream.ElementIDToColumn(bc.elementIDs[row]))
+		seriesCol.Append(seriesColVal)
+	}
+
+	for _, cf := range bc.tagFamilies {
+		for _, c := range cf.tags {
+			colIdx, ok := v.schema.TagIndex(cf.name, c.name)
+			if !ok {
+				continue
+			}
+			tagCol := batch.Columns[colIdx].(*vectorized.TypedColumn[*modelv1.TagValue])
+			schemaType, hasSchemaType := bc.schemaTagTypes[c.name]
+			for row := off; row < end; row++ {
+				if len(c.values) > row && hasSchemaType && c.valueType == schemaType {
+					tagCol.Append(mustDecodeTagValue(c.valueType, c.values[row]))
+				} else {
+					tagCol.Append(pbv1.NullTagValue)
+				}
+			}
+		}
+	}
+
+	// Any projected tag columns with no matching cursor tag are null-filled so
+	// every column has exactly n rows (mirrors copyTo's NullTagValue fallback).
+	for _, def := range v.schema.Columns {
+		if def.Role != vectorized.RoleTag {
+			continue
+		}
+		colIdx, _ := v.schema.TagIndex(def.TagFamily, def.Name)
+		col := batch.Columns[colIdx].(*vectorized.TypedColumn[*modelv1.TagValue])
+		for col.Len() < n {
+			col.Append(pbv1.NullTagValue)
+		}
+	}
+
+	if v.indexOrder {
+		if okIdx := v.schema.OrderKeyIndex(); okIdx >= 0 {
+			orderCol := batch.Columns[okIdx].(*vectorized.TypedColumn[[]byte])
+			orderColIdx, hasOrderCol := v.schema.TagIndex(v.orderTagFamily, v.orderTagName)
+			var orderTagCol *vectorized.TypedColumn[*modelv1.TagValue]
+			if hasOrderCol {
+				orderTagCol = batch.Columns[orderColIdx].(*vectorized.TypedColumn[*modelv1.TagValue])
+			}
+			for row := 0; row < n; row++ {
+				var keyBytes []byte
+				if orderTagCol != nil {
+					b, mErr := pbv1.MarshalTagValue(orderTagCol.Data()[row])
+					if mErr != nil {
+						return nil, fmt.Errorf("stream vec scan: marshal order key for tag %s.%s: %w",
+							v.orderTagFamily, v.orderTagName, mErr)
+					}
+					keyBytes = b
+				}
+				orderCol.Append(keyBytes)
+			}
+		}
+	}
+
+	batch.Len = n
+	return batch, nil
+}
+
+// Release frees the scan source's resources: the block scanner, the temp block,
+// any pending cursors, and the retained segment references.
+func (v *streamVecScan) Release() {
+	if v.closed {
+		return
+	}
+	v.closed = true
+	if v.cur != nil {
+		releaseBlockCursor(v.cur)
+		v.cur = nil
+	}
+	for _, bc := range v.pending {
+		releaseBlockCursor(bc)
+	}
+	v.pending = nil
+	if v.ts != nil {
+		v.ts.close()
+		v.ts = nil
+	}
+	if v.tmpBlock != nil {
+		releaseBlock(v.tmpBlock)
+		v.tmpBlock = nil
+	}
+	for i := range v.segments {
+		v.segments[i].DecRef()
+	}
+	v.segments = nil
+}
+
+// emptyVecScan is a source that yields nothing — used for bypass/empty-segment
+// cases so callers never special-case a nil source. It still carries a schema so
+// the M4 pipeline can be built over it (SortedMerge requires a schema even when no
+// batch ever arrives).
+type emptyVecScan struct {
+	schema *vectorized.BatchSchema
+}
+
+// Schema returns the empty source's schema (may be nil for degenerate callers).
+func (e emptyVecScan) Schema() *vectorized.BatchSchema { return e.schema }
+
+// NextBatch always returns exhausted.
+func (emptyVecScan) NextBatch(context.Context) (*vectorized.RecordBatch, error) { return nil, nil }
+
+// Release is a no-op.
+func (emptyVecScan) Release() {}
+
+// vecScanSource is the pull contract shared by streamVecScan and emptyVecScan.
+type vecScanSource interface {
+	NextBatch(ctx context.Context) (*vectorized.RecordBatch, error)
+	Schema() *vectorized.BatchSchema
+	Release()
+}
+
+// queryVectorized is the vectorized counterpart of Query. It reuses Query's front
+// half (validate, TSDB, segment selection, series prep, schema tag types, query
+// options) and returns a pull-based columnar scan source.
+//
+// Deliberate deviation from the AC wording ("invoked from query.go"): this is a
+// SEPARATE method rather than a branch inside Query. Query returns
+// model.StreamQueryResult whose Pull() yields *model.StreamResult — a row tuple
+// the vec path is forbidden to build. Routing the vec path through Query would
+// therefore violate the no-row-tuple constraint. queryVectorized is wired into
+// the data-node processor / standalone egress in M6.
+func (s *stream) queryVectorized(_ context.Context, sqo model.StreamQueryOptions) (vecScanSource, error) {
+	if err := validateQueryInput(sqo); err != nil {
+		return nil, err
+	}
+	tsdb, err := s.getTSDB()
+	if err != nil {
+		return nil, err
+	}
+	indexOrderEarly := sqo.Order != nil && sqo.Order.Index != nil
+	var earlyOrderFamily, earlyOrderName string
+	if indexOrderEarly {
+		earlyOrderFamily, earlyOrderName = s.resolveOrderTag(sqo)
+	}
+	emptySchema := vstream.BuildStreamBatchSchema(sqo.TagProjection, earlyOrderFamily, earlyOrderName)
+
+	segments, err := tsdb.SelectSegments(*sqo.TimeRange, true)
+	if err != nil {
+		return nil, err
+	}
+	if len(segments) < 1 {
+		return emptyVecScan{schema: emptySchema}, nil
+	}
+
+	segmentsNeedRelease := true
+	defer func() {
+		if !segmentsNeedRelease {
+			return
+		}
+		for i := range segments {
+			segments[i].DecRef()
+		}
+	}()
+
+	series := prepareSeriesData(sqo)
+	schemaTagTypes := make(map[string]pbv1.ValueType)
+	for _, tf := range s.schema.GetTagFamilies() {
+		for _, tag := range tf.GetTags() {
+			vt := pbv1.TagValueSpecToValueType(tag.GetType())
+			if vt != pbv1.ValueTypeUnknown {
+				schemaTagTypes[tag.GetName()] = vt
+			}
+		}
+	}
+
+	batchSize := s.vectorized.BatchSize
+	if batchSize <= 0 {
+		batchSize = vectorized.DefaultBatchSize
+	}
+
+	indexOrder := sqo.Order != nil && sqo.Order.Index != nil
+	var orderTagFamily, orderTagName string
+	if indexOrder {
+		orderTagFamily, orderTagName = s.resolveOrderTag(sqo)
+	}
+	schema := vstream.BuildStreamBatchSchema(sqo.TagProjection, orderTagFamily, orderTagName)
+
+	// Per-query soft byte budget: cap cumulative uncompressed block bytes decoded
+	// by this scan at QueryMemoryMiB. Enforced as a metadata preflight in
+	// fillFromScanner (first-block exception). This is independent of, and in
+	// addition to, the block scanner's process-wide protector.Memory quota.
+	var mem *vectorized.MemoryTracker
+	if s.vectorized.QueryMemoryMiB > 0 {
+		mem = vectorized.NewMemoryTracker(int64(s.vectorized.QueryMemoryMiB) << 20)
+	}
+
+	qo := prepareQueryOptions(sqo, schemaTagTypes)
+	tr := index.NewIntRangeOpts(qo.minTimestamp, qo.maxTimestamp, true, true)
+
+	asc := true
+	if sqo.Order != nil && sqo.Order.Sort == modelv1.Sort_SORT_DESC {
+		asc = false
+	}
+
+	scan := &streamVecScan{
+		sm:             s,
+		segments:       segments,
+		series:         series,
+		qo:             qo,
+		tr:             &tr,
+		schema:         schema,
+		mem:            mem,
+		batchSize:      batchSize,
+		asc:            asc,
+		indexOrder:     indexOrder,
+		orderTagFamily: orderTagFamily,
+		orderTagName:   orderTagName,
+		tmpBlock:       generateBlock(),
+	}
+	segmentsNeedRelease = false
+	return scan, nil
+}
+
+// resolveOrderTag returns the (family, name) of the single ordered tag for an
+// index-order query. The order index carries exactly one tag name; its family is
+// resolved against the query projection so the order-key column keys on the same
+// passthrough cell used at egress.
+func (s *stream) resolveOrderTag(sqo model.StreamQueryOptions) (family, name string) {
+	if sqo.Order == nil || sqo.Order.Index == nil {
+		return "", ""
+	}
+	tags := sqo.Order.Index.GetTags()
+	if len(tags) != 1 {
+		return "", ""
+	}
+	name = tags[0]
+	for _, proj := range sqo.TagProjection {
+		for _, projName := range proj.Names {
+			if projName == name {
+				return proj.Family, name
+			}
+		}
+	}
+	return "", name
+}
+
+// BuildElementsFromVecBatches drains a columnar scan source and materializes
+// []*streamv1.Element from the batch columns. The Element shape is byte-for-byte
+// identical to BuildElementsFromStreamResult: hex-encoded elementID, timestamppb
+// timestamp, and tag families/tags in projection order (with NullTagValue for a
+// missing projected tag).
+//
+// This is the standalone (§5.6b) in-process egress used by M6's local path. It
+// does NOT apply cross-source dedup/order/limit — those are M4 operators applied
+// upstream; this function preserves whatever order/dedup the batches already
+// carry, matching the row egress' per-result behavior.
+func BuildElementsFromVecBatches(ctx context.Context, source vecScanSource,
+	projectionTags []model.TagProjection,
+) (elements []*streamv1.Element, err error) {
+	if source == nil {
+		return nil, nil
+	}
+	for {
+		select {
+		case <-ctx.Done():
+			return nil, ctx.Err()
+		default:
+		}
+		batch, batchErr := source.NextBatch(ctx)
+		if batchErr != nil {
+			return nil, batchErr
+		}
+		if batch == nil {
+			return elements, nil
+		}
+		if batch.Len == 0 {
+			continue
+		}
+		batchElements, buildErr := vstream.BuildElementsFromBatch(batch, projectionTags)
+		if buildErr != nil {
+			return nil, buildErr
+		}
+		elements = append(elements, batchElements...)
+	}
+}
+
+// BuildElementsFromBatches materializes []*streamv1.Element from an already-drained
+// slice of columnar batches (the M4 pipeline output). It is the egress used by the
+// data-node standalone path — the batches hold the merged/deduped/limited result
+// in memory rather than a live scan source. It delegates to the shared vec egress
+// (vstream) so the columnar→proto conversion is identical to the liaison side.
+func BuildElementsFromBatches(batches []*vectorized.RecordBatch,
+	projectionTags []model.TagProjection,
+) ([]*streamv1.Element, error) {
+	return vstream.BuildElementsFromBatches(batches, projectionTags)
+}
diff --git a/banyand/stream/query_vectorized_parity_test.go b/banyand/stream/query_vectorized_parity_test.go
new file mode 100644
index 000000000..3fa3f45a1
--- /dev/null
+++ b/banyand/stream/query_vectorized_parity_test.go
@@ -0,0 +1,804 @@
+// 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.
+
+package stream
+
+import (
+	"context"
+	"fmt"
+	"math"
+	"strconv"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/require"
+
+	"github.com/apache/skywalking-banyandb/api/common"
+	commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+	"github.com/apache/skywalking-banyandb/banyand/protector"
+	"github.com/apache/skywalking-banyandb/pkg/convert"
+	"github.com/apache/skywalking-banyandb/pkg/index"
+	"github.com/apache/skywalking-banyandb/pkg/logger"
+	pbv1 "github.com/apache/skywalking-banyandb/pkg/pb/v1"
+	logicalstream "github.com/apache/skywalking-banyandb/pkg/query/logical/stream"
+	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
+	"github.com/apache/skywalking-banyandb/pkg/test/flags"
+	"github.com/apache/skywalking-banyandb/pkg/timestamp"
+)
+
+const (
+	indexOrderRuleID      = 1
+	indexOrderSeriesCount = 4
+	indexOrderTSCount     = 12
+)
+
+// parityEntities builds the per-series entity tag-value lists the fixture writer
+// keys on (entity1..entityN), matching the entity index docs writeVecFixture adds.
+func parityEntities(seriesCount int) [][]*modelv1.TagValue {
+	entities := make([][]*modelv1.TagValue, 0, seriesCount)
+	for i := 1; i <= seriesCount; i++ {
+		entities = append(entities, []*modelv1.TagValue{
+			{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: entityTagValuePrefix + strconv.Itoa(i)}}},
+		})
+	}
+	return entities
+}
+
+// fullProjection is the two-tag projection the fixture populates on every element.
+func fullProjection() []model.TagProjection {
+	return []model.TagProjection{{
+		Family: "benchmark-family",
+		Names:  []string{"entity-tag", "filter-tag"},
+	}}
+}
+
+// runVecPipeline drives the vec scan through the FULL M4 pipeline
+// (merge → distinct → limit) exactly as localIndexScan.ExecuteVectorized does at
+// the data-node standalone path, then materializes []*streamv1.Element via the
+// batch egress. limitRows/offset are the M4 pipeline caps; pass limitRows=0 for
+// "no cap" (drain everything). This is the vec oracle used by every parity case.
+func runVecPipeline(ctx context.Context, t *testing.T, s *stream, sqo model.StreamQueryOptions,
+	desc bool, offset, limitRows uint32,
+) []*streamv1.Element {
+	t.Helper()
+	src, err := s.queryVectorized(ctx, sqo)
+	require.NoError(t, err)
+	require.NotNil(t, src)
+	schema := src.Schema()
+	// Mirror ExecuteVectorized: the merge caps at maxElementSize (in-order top-N),
+	// and the trailing Limit applies the client offset/limit slice.
+	mergeCap := 0
+	if sqo.MaxElementSize > 0 && sqo.MaxElementSize < math.MaxInt32 {
+		mergeCap = sqo.MaxElementSize
+	}
+	pipeline, err := vstream.BuildStreamMergePipeline(
+		&testVecSource{src: src, schema: schema}, schema, desc, offset, limitRows, vstream.DefaultConfig().BatchSize, mergeCap)
+	require.NoError(t, err)
+	require.NoError(t, pipeline.Init(ctx))
+	var batches []*vectorized.RecordBatch
+	for {
+		batch, nextErr := pipeline.Next(ctx)
+		require.NoError(t, nextErr)
+		if batch == nil {
+			break
+		}
+		batches = append(batches, batch)
+	}
+	elems, err := BuildElementsFromBatches(batches, sqo.TagProjection)
+	require.NoError(t, err)
+	require.NoError(t, pipeline.Close())
+	return elems
+}
+
+// runRowPath materializes the row oracle's elements: s.Query drains one Pull into
+// a StreamResult, then BuildElementsFromStreamResult converts to elements. The
+// caller controls MaxElementSize via sqo.
+func runRowPath(ctx context.Context, t *testing.T, s *stream, sqo model.StreamQueryOptions) []*streamv1.Element {
+	t.Helper()
+	rowRes, err := s.Query(ctx, sqo)
+	require.NoError(t, err)
+	require.NotNil(t, rowRes)
+	defer rowRes.Release()
+	rowElements, err := logicalstream.BuildElementsFromStreamResult(ctx, rowRes, sqo.TagProjection)
+	require.NoError(t, err)
+	return rowElements
+}
+
+// assertSetParity asserts the two element slices are the SAME set keyed by
+// elementID with identical values (proto.Equal on tags + timestamp), plus the vec
+// output is monotonically ordered by timestamp per asc/desc. This is the tie-break
+// safe discipline the existing parity tests use: equal-timestamp rows have no
+// cross-path-stable order, so only the set (not the per-index order) is compared.
+func assertSetParity(t *testing.T, want, got []*streamv1.Element, desc bool) {
+	t.Helper()
+	require.Equal(t, len(want), len(got), "element-set size mismatch")
+	wantByID := indexByElementID(t, want)
+	gotByID := indexByElementID(t, got)
+	require.Equal(t, len(wantByID), len(gotByID), "unique element-id set size mismatch")
+	for id, wantElem := range wantByID {
+		gotElem, ok := gotByID[id]
+		require.True(t, ok, "vec path missing elementID present in row path: %s", id)
+		assertElementsEqual(t, wantElem, gotElem)
+	}
+	assertMonotonicTS(t, got, desc)
+}
+
+// assertMonotonicTS asserts the elements are monotonically ordered by timestamp
+// (non-decreasing for asc, non-increasing for desc).
+func assertMonotonicTS(t *testing.T, elems []*streamv1.Element, desc bool) {
+	t.Helper()
+	for i := 1; i < len(elems); i++ {
+		prev := elems[i-1].Timestamp.AsTime().UnixNano()
+		cur := elems[i].Timestamp.AsTime().UnixNano()
+		if desc {
+			require.GreaterOrEqual(t, prev, cur, "output not desc-ordered by ts at %d", i)
+		} else {
+			require.LessOrEqual(t, prev, cur, "output not asc-ordered by ts at %d", i)
+		}
+	}
+}
+
+// assertExactParity asserts the two element slices are identical in ORDER and
+// value. Only valid when the fixture has globally unique timestamps (seriesCount=1)
+// so both paths produce the same deterministic total order with no ties.
+func assertExactParity(t *testing.T, want, got []*streamv1.Element) {
+	t.Helper()
+	require.Equal(t, len(want), len(got), "element count mismatch")
+	for i := range want {
+		require.Equal(t, want[i].ElementId, got[i].ElementId, "elementID order mismatch at %d", i)
+		assertElementsEqual(t, want[i], got[i])
+	}
+}
+
+// TestQueryVectorized_Parity_Order runs the row path (oracle) and the full M4 vec
+// pipeline over the SAME fixture for the vec-eligible no-order shapes: default ts
+// order asc and desc. Comparison is set-based + ts-monotonic (tie-break safe)
+// because the multi-series fixture stamps duplicate timestamps.
+func TestQueryVectorized_Parity_Order(t *testing.T) {
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 20,
+		seriesCount:    5,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   1000,
+		scenario:       "vec-parity-order",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := parityEntities(p.seriesCount)
+	projection := fullProjection()
+	ctx := context.Background()
+
+	cases := []struct {
+		order *index.OrderBy
+		name  string
+	}{
+		{name: "no-order-asc", order: &index.OrderBy{Sort: modelv1.Sort_SORT_ASC}},
+		{name: "no-order-desc", order: &index.OrderBy{Sort: modelv1.Sort_SORT_DESC}},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			desc := tc.order.Sort == modelv1.Sort_SORT_DESC
+			sqo := model.StreamQueryOptions{
+				Name:           "benchmark",
+				TimeRange:      &tr,
+				Entities:       entities,
+				TagProjection:  projection,
+				Order:          tc.order,
+				MaxElementSize: math.MaxInt32,
+			}
+
+			rowElements := runRowPath(ctx, t, s, sqo)
+			require.NotEmpty(t, rowElements, "row path produced no elements; fixture is degenerate")
+
+			vecElements := runVecPipeline(ctx, t, s, sqo, desc, 0, uint32(len(rowElements)*4))
+			assertSetParity(t, rowElements, vecElements, desc)
+		})
+	}
+}
+
+// TestQueryVectorized_Parity_IndexOrder runs the row index-sort oracle and the vec
+// OrderKey path over a DEDICATED index-order fixture (buildIndexOrderStream) for
+// order-by-indexed-tag asc + desc. The shared generateData fixture cannot serve as
+// an index-sort oracle (its sortable docs use DocID=timestamp, not the element id
+// the row index-sort resolves against, and set no timestampField for the sort
+// query's date range) — see the writer's doc comment. Comparison is set-based (the
+// order key is the tag term; ties on it are path-specific) with tag-value parity.
+func TestQueryVectorized_Parity_IndexOrder(t *testing.T) {
+	// The index rule the dedicated fixture stamps its sortable docs with. Its single
+	// tag "filter-tag" is the order key resolveOrderTag maps to the projection cell.
+	indexRule := &databasev1.IndexRule{
+		Metadata: &commonv1.Metadata{Name: "filter-idx", Id: indexOrderRuleID},
+		Tags:     []string{"filter-tag"},
+	}
+	s, tr := buildIndexOrderStream(t)
+	entities := parityEntities(indexOrderSeriesCount)
+	projection := fullProjection()
+	ctx := context.Background()
+
+	cases := []struct {
+		name string
+		sort modelv1.Sort
+	}{
+		{name: "index-order-asc", sort: modelv1.Sort_SORT_ASC},
+		{name: "index-order-desc", sort: modelv1.Sort_SORT_DESC},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			desc := tc.sort == modelv1.Sort_SORT_DESC
+			sqo := model.StreamQueryOptions{
+				Name:           "benchmark",
+				TimeRange:      &tr,
+				Entities:       entities,
+				TagProjection:  projection,
+				Order:          &index.OrderBy{Index: indexRule, Sort: tc.sort},
+				MaxElementSize: math.MaxInt32,
+			}
+			rowElements := runRowPath(ctx, t, s, sqo)
+			require.NotEmpty(t, rowElements, "row index-sort produced no elements; fixture is degenerate")
+			vecElements := runVecPipeline(ctx, t, s, sqo, desc, 0, uint32(len(rowElements)*4))
+
+			// Order key is the tag term, not ts — ties on equal tag values order
+			// path-specifically, so assert set parity (values + membership) only.
+			require.Equal(t, len(rowElements), len(vecElements), "element-set size mismatch")
+			rowByID := indexByElementID(t, rowElements)
+			vecByID := indexByElementID(t, vecElements)
+			require.Equal(t, len(rowByID), len(vecByID))
+			for id, wantElem := range rowByID {
+				gotElem, ok := vecByID[id]
+				require.True(t, ok, "vec path missing elementID present in row path: %s", id)
+				assertElementsEqual(t, wantElem, gotElem)
+			}
+		})
+	}
+}
+
+// TestQueryVectorized_Parity_Projection covers projection subsets over the SAME
+// fixture: full projection, a single-tag projection, and a projection of a tag
+// absent from every element (exercising the NullTagValue fill on both paths).
+func TestQueryVectorized_Parity_Projection(t *testing.T) {
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 20,
+		seriesCount:    5,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   1000,
+		scenario:       "vec-parity-projection",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := parityEntities(p.seriesCount)
+	ctx := context.Background()
+
+	cases := []struct {
+		name       string
+		projection []model.TagProjection
+	}{
+		{name: "full", projection: fullProjection()},
+		{name: "single-tag", projection: []model.TagProjection{{Family: "benchmark-family", Names: []string{"filter-tag"}}}},
+		{
+			name: "absent-tag-nulltagvalue",
+			// "missing-tag" is declared in the projection but written by no element,
+			// so both egresses must NullTagValue-fill its column.
+			projection: []model.TagProjection{{Family: "benchmark-family", Names: []string{"entity-tag", "missing-tag"}}},
+		},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			sqo := model.StreamQueryOptions{
+				Name:           "benchmark",
+				TimeRange:      &tr,
+				Entities:       entities,
+				TagProjection:  tc.projection,
+				Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+				MaxElementSize: math.MaxInt32,
+			}
+			rowElements := runRowPath(ctx, t, s, sqo)
+			require.NotEmpty(t, rowElements, "row path produced no elements; fixture is degenerate")
+			vecElements := runVecPipeline(ctx, t, s, sqo, false, 0, uint32(len(rowElements)*4))
+			assertSetParity(t, rowElements, vecElements, false)
+		})
+	}
+}
+
+// TestQueryVectorized_Parity_OffsetLimit covers the offset/limit egress split over
+// a single-series fixture (globally UNIQUE timestamps), enabling exact order+value
+// parity (no ties). The row oracle and vec pipeline both cap the scan at
+// limit+offset and slice [offset:offset+limit], exactly as the *limit plan node
+// does. Cases: limit-only, offset>0+limit, limit>result (all rows), limit<result
+// (top-N).
+func TestQueryVectorized_Parity_OffsetLimit(t *testing.T) {
+	// seriesCount=1 => one element per timestamp => globally unique, totally
+	// ordered timestamps => deterministic total order on BOTH paths => exact parity.
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 30,
+		seriesCount:    1,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   1000,
+		scenario:       "vec-parity-offsetlimit",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := parityEntities(p.seriesCount)
+	projection := fullProjection()
+	ctx := context.Background()
+
+	const total = 30 // timestampCount*seriesCount, all in one batch/segment.
+
+	cases := []struct {
+		name   string
+		offset uint32
+		limit  uint32
+	}{
+		{name: "limit-only", offset: 0, limit: 10},
+		{name: "offset-plus-limit", offset: 5, limit: 10},
+		{name: "limit-larger-than-result", offset: 0, limit: total + 20},
+		{name: "limit-smaller-than-result-topN", offset: 0, limit: 3},
+		{name: "offset-into-tail", offset: total - 2, limit: 10},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			// maxElementSize = limit+offset, mirroring PushDownMaxSize at
+			// stream_analyzer.go:94 (the scan-level cap the *limit node feeds down).
+			maxSize := int(tc.limit) + int(tc.offset)
+			sqo := model.StreamQueryOptions{
+				Name:           "benchmark",
+				TimeRange:      &tr,
+				Entities:       entities,
+				TagProjection:  projection,
+				Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+				MaxElementSize: maxSize,
+			}
+
+			rowAll := runRowPath(ctx, t, s, sqo)
+			// Apply the *limit node's egress slice to the row oracle (query.go/Query
+			// does not itself apply offset/limit — that is the plan node's job).
+			rowSliced := sliceOffsetLimit(rowAll, tc.offset, tc.limit)
+
+			// The vec pipeline applies offset/limit inside NewLimit at egress, so pass
+			// the SAME offset/limit; no post-slice needed.
+			vecElements := runVecPipeline(ctx, t, s, sqo, false, tc.offset, tc.limit)
+
+			// Unique timestamps => exact order+value parity is provable.
+			assertExactParity(t, rowSliced, vecElements)
+			assertMonotonicTS(t, vecElements, false)
+		})
+	}
+}
+
+// sliceOffsetLimit reproduces the *limit plan node's egress slice
+// (allEntities[offset:offset+limit], clamped) so the row oracle can be compared to
+// the vec pipeline's built-in Limit operator.
+func sliceOffsetLimit(elems []*streamv1.Element, offset, limit uint32) []*streamv1.Element {
+	off := int(offset)
+	lim := int(limit)
+	if len(elems) <= off {
+		return []*streamv1.Element{}
+	}
+	end := off + lim
+	if end > len(elems) {
+		end = len(elems)
+	}
+	return elems[off:end]
+}
+
+// TestQueryVectorized_Parity_Boundary covers the degenerate result shapes: empty
+// (query window with no data), single-element, and a >=2-block fixture so
+// cross-block ordering is exercised. Each asserts set parity + ts monotonicity.
+func TestQueryVectorized_Parity_Boundary(t *testing.T) {
+	t.Run("empty-result", func(t *testing.T) {
+		p := parameter{
+			batchCount:     1,
+			timestampCount: 20,
+			seriesCount:    5,
+			tagCardinality: 4,
+			startTimestamp: 1,
+			endTimestamp:   1000,
+			scenario:       "vec-parity-empty",
+		}
+		s, tr := buildVecTestStream(t, p)
+		entities := parityEntities(p.seriesCount)
+		ctx := context.Background()
+
+		// A time range entirely BEFORE the fixture window (which starts at ~now-1h):
+		// SelectSegments still returns the recent segment but the scan yields no rows
+		// in [tr.Start, tr.Start] shifted 100 years back, so both paths are empty.
+		emptyStart := tr.Start.Add(-100 * 365 * 24 * time.Hour)
+		emptyTR := timestamp.NewInclusiveTimeRange(emptyStart, tr.Start.Add(-time.Nanosecond))
+		sqo := model.StreamQueryOptions{
+			Name:           "benchmark",
+			TimeRange:      &emptyTR,
+			Entities:       entities,
+			TagProjection:  fullProjection(),
+			Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+			MaxElementSize: math.MaxInt32,
+		}
+		rowElements := runRowPath(ctx, t, s, sqo)
+		require.Empty(t, rowElements, "expected empty row result for a no-data window")
+		// Pass a real (non-zero) limit so the emptiness comes from the no-data window,
+		// not from Limit(0) emitting nothing by construction (which would make this a
+		// tautology). A large limit lets any wrongly-returned row through and fail.
+		vecElements := runVecPipeline(ctx, t, s, sqo, false, 0, math.MaxUint32)
+		require.Empty(t, vecElements, "expected empty vec result for a no-data window")
+	})
+
+	t.Run("single-element", func(t *testing.T) {
+		// seriesCount=1, timestampCount=1 => exactly one element.
+		p := parameter{
+			batchCount:     1,
+			timestampCount: 1,
+			seriesCount:    1,
+			tagCardinality: 4,
+			startTimestamp: 1,
+			endTimestamp:   1000,
+			scenario:       "vec-parity-single",
+		}
+		s, tr := buildVecTestStream(t, p)
+		entities := parityEntities(p.seriesCount)
+		ctx := context.Background()
+		sqo := model.StreamQueryOptions{
+			Name:           "benchmark",
+			TimeRange:      &tr,
+			Entities:       entities,
+			TagProjection:  fullProjection(),
+			Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+			MaxElementSize: math.MaxInt32,
+		}
+		rowElements := runRowPath(ctx, t, s, sqo)
+		require.Len(t, rowElements, 1, "expected exactly one row element")
+		vecElements := runVecPipeline(ctx, t, s, sqo, false, 0, uint32(len(rowElements)*4))
+		assertExactParity(t, rowElements, vecElements)
+	})
+
+	t.Run("multi-block-cross-block-order", func(t *testing.T) {
+		// A block splits on series-id change (part.go:204), so seriesCount=3 forces
+		// >=3 physical blocks within the single part; the vec SortedMerge must order
+		// across those blocks identically to the row path's cross-block merge. The
+		// element count (3*50=150) stays well under one scan batch round (32 blocks)
+		// so the row oracle's ONE non-empty Pull covers the COMPLETE result — the
+		// documented one-Pull limitation of BuildElementsFromStreamResult. Multiple
+		// series share timestamps (ties), so parity is set-based + ts-monotonic, the
+		// same tie-break-safe discipline the existing parity tests use.
+		p := parameter{
+			batchCount:     1,
+			timestampCount: 50,
+			seriesCount:    3,
+			tagCardinality: 4,
+			startTimestamp: 1,
+			endTimestamp:   1000,
+			scenario:       "vec-parity-multiblock",
+		}
+		s, tr := buildVecTestStream(t, p)
+		entities := parityEntities(p.seriesCount)
+		ctx := context.Background()
+		sqo := model.StreamQueryOptions{
+			Name:           "benchmark",
+			TimeRange:      &tr,
+			Entities:       entities,
+			TagProjection:  fullProjection(),
+			Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+			MaxElementSize: math.MaxInt32,
+		}
+		rowElements := runRowPath(ctx, t, s, sqo)
+		require.NotEmpty(t, rowElements)
+		vecElements := runVecPipeline(ctx, t, s, sqo, false, 0, uint32(len(rowElements)*4))
+		assertSetParity(t, rowElements, vecElements, false)
+
+		// Same fixture, DESC, to exercise the desc cross-block merge direction.
+		sqoDesc := sqo
+		sqoDesc.Order = &index.OrderBy{Sort: modelv1.Sort_SORT_DESC}
+		rowDesc := runRowPath(ctx, t, s, sqoDesc)
+		require.NotEmpty(t, rowDesc)
+		vecDesc := runVecPipeline(ctx, t, s, sqoDesc, true, 0, uint32(len(rowDesc)*4))
+		assertSetParity(t, rowDesc, vecDesc, true)
+	})
+}
+
+// TestQueryVectorized_Parity_Fallback_RowPathCorrect asserts that a shape M6 does
+// NOT vectorize (VecExecutable declines) still returns correct elements via the
+// row path. A tag-filter-wrapped scan (criteria tags needing row-side re-matching)
+// is the canonical non-vectorizable shape: VecExecutable returns nil for it, so
+// the engine runs Query. Here we assert the row path itself is correct on the
+// fixture (the fallback destination), which is the guarantee that matters.
+func TestQueryVectorized_Parity_Fallback_RowPathCorrect(t *testing.T) {
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 20,
+		seriesCount:    5,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   1000,
+		scenario:       "vec-parity-fallback",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := parityEntities(p.seriesCount)
+	ctx := context.Background()
+	sqo := model.StreamQueryOptions{
+		Name:           "benchmark",
+		TimeRange:      &tr,
+		Entities:       entities,
+		TagProjection:  fullProjection(),
+		Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+		MaxElementSize: math.MaxInt32,
+	}
+	rowElements := runRowPath(ctx, t, s, sqo)
+	require.NotEmpty(t, rowElements, "fallback row path produced no elements; fixture is degenerate")
+	// Every element carries the full projection with non-null values (the fixture
+	// writes entity-tag + filter-tag on every element), and ts is asc-ordered.
+	for _, e := range rowElements {
+		require.Len(t, e.TagFamilies, 1)
+		require.Equal(t, "benchmark-family", e.TagFamilies[0].Name)
+		require.Len(t, e.TagFamilies[0].Tags, 2)
+		require.NotEmpty(t, e.ElementId)
+	}
+	assertMonotonicTS(t, rowElements, false)
+
+	// The decline contract itself: VecExecutable returns nil for a plan that is not
+	// the vectorizable *limit→*localIndexScan shape, so the engine runs the row path.
+	require.Nil(t, logicalstream.VecExecutable(nil), "VecExecutable must decline a non-limit plan")
+}
+
+// TestQueryVectorized_Parity_LargeSingleBlock is the C1 regression: a single
+// block with MORE than DefaultBatchSize (1024) rows. Stream blocks are capped by
+// uncompressed BYTES (2 MiB), not row count, so a block can hold >1024 rows; the
+// scan must drain a cursor across multiple batchSize batches. Before the fix the
+// scan emitted only the first batchSize rows of a cursor and silently dropped the
+// rest, so the vec set would be a strict subset of the row set. seriesCount=1 =>
+// one series => one physical block => globally unique, totally ordered timestamps
+// => exact order+value parity is provable.
+func TestQueryVectorized_Parity_LargeSingleBlock(t *testing.T) {
+	const rows = 1500 // > DefaultBatchSize (1024), single series => single block.
+	p := parameter{
+		batchCount:     1,
+		timestampCount: rows,
+		seriesCount:    1,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   10000,
+		scenario:       "vec-parity-large-single-block",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := parityEntities(p.seriesCount)
+	ctx := context.Background()
+	sqo := model.StreamQueryOptions{
+		Name:           "benchmark",
+		TimeRange:      &tr,
+		Entities:       entities,
+		TagProjection:  fullProjection(),
+		Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+		MaxElementSize: math.MaxInt32,
+	}
+	rowElements := runRowPath(ctx, t, s, sqo)
+	require.Len(t, rowElements, rows, "fixture must yield every row in one Pull")
+	vecElements := runVecPipeline(ctx, t, s, sqo, false, 0, uint32(rows*4))
+	// No row loss: the vec path must return the SAME 1500 rows in the same order.
+	assertExactParity(t, rowElements, vecElements)
+}
+
+// TestQueryVectorized_Parity_TopN_Desc is the C2 regression for descending
+// top-N: ORDER BY ts DESC with MaxElementSize < total must return the NEWEST N
+// rows, not the oldest N. Before the fix the scan truncated the first N rows in
+// storage (ascending) order before the merge, so a desc query returned the
+// OLDEST N. seriesCount=1 => unique timestamps => exact parity against the row
+// oracle (which caps AFTER its in-order desc heap merge).
+func TestQueryVectorized_Parity_TopN_Desc(t *testing.T) {
+	const total = 100
+	const topN = 10
+	p := parameter{
+		batchCount:     1,
+		timestampCount: total,
+		seriesCount:    1,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   10000,
+		scenario:       "vec-parity-topn-desc",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := parityEntities(p.seriesCount)
+	ctx := context.Background()
+	sqo := model.StreamQueryOptions{
+		Name:           "benchmark",
+		TimeRange:      &tr,
+		Entities:       entities,
+		TagProjection:  fullProjection(),
+		Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_DESC},
+		MaxElementSize: topN, // per-node cap < total => in-order top-N.
+	}
+	rowElements := runRowPath(ctx, t, s, sqo)
+	require.Len(t, rowElements, topN, "row oracle must cap at MaxElementSize (newest N)")
+	// The vec merge caps at MaxElementSize (topN) in DESC sort order; no client
+	// offset/limit slice (limit=topN, offset=0) so egress keeps all N.
+	vecElements := runVecPipeline(ctx, t, s, sqo, true, 0, uint32(topN))
+	// Newest N kept, in desc order, byte-identical to the row oracle.
+	assertExactParity(t, rowElements, vecElements)
+	assertMonotonicTS(t, vecElements, true)
+}
+
+// TestQueryVectorized_Parity_TopN_MultiSeries_Asc is the C2 cross-series
+// regression: an ASC query over MULTIPLE series with MaxElementSize < total.
+// Blocks are seriesID-major, so a pre-merge storage-order cap would keep rows
+// from the first series(es) only, not the globally-oldest N across all series.
+// The cap must apply AFTER the cross-series merge (in ts order). Multiple series
+// share timestamps (ties), so parity is the set of kept elementIDs + ts
+// monotonicity, the same tie-break-safe discipline the other multi-series cases
+// use.
+func TestQueryVectorized_Parity_TopN_MultiSeries_Asc(t *testing.T) {
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 40,
+		seriesCount:    5,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   10000,
+		scenario:       "vec-parity-topn-multiseries",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := parityEntities(p.seriesCount)
+	ctx := context.Background()
+	const topN = 30 // < 40*5 = 200 total.
+	sqo := model.StreamQueryOptions{
+		Name:           "benchmark",
+		TimeRange:      &tr,
+		Entities:       entities,
+		TagProjection:  fullProjection(),
+		Order:          &index.OrderBy{Sort: modelv1.Sort_SORT_ASC},
+		MaxElementSize: topN,
+	}
+	rowElements := runRowPath(ctx, t, s, sqo)
+	require.Len(t, rowElements, topN, "row oracle must cap at MaxElementSize across series")
+	vecElements := runVecPipeline(ctx, t, s, sqo, false, 0, uint32(topN))
+	require.Len(t, vecElements, topN, "vec must keep exactly the in-order top-N across series")
+	// The kept ts window must match the row oracle's (globally-oldest N): assert the
+	// max kept ts on both paths is identical, so vec did not keep later rows the
+	// oracle excluded. Ties at the boundary ts can pick different elementIDs, so the
+	// boundary ts (not the exact id set) is the cross-path invariant.
+	require.Equal(t, maxTS(rowElements), maxTS(vecElements),
+		"vec kept a different ts window than the row oracle (wrong cross-series top-N)")
+	assertMonotonicTS(t, vecElements, false)
+}
+
+// maxTS returns the largest timestamp (UnixNano) across the elements.
+func maxTS(elems []*streamv1.Element) int64 {
+	var m int64
+	for _, e := range elems {
+		if ts := e.Timestamp.AsTime().UnixNano(); ts > m {
+			m = ts
+		}
+	}
+	return m
+}
+
+// buildIndexOrderStream builds a stream over a DEDICATED index-order fixture whose
+// sortable index docs are shaped for BOTH oracles:
+//   - the ROW index-sort (query_by_idx.go) resolves elements by the sort doc's
+//     DocID == elementID and filters the sort query by the seriesIDField and the
+//     timestampField date range, so each doc sets DocID=elementID and Timestamp=ts.
+//   - the VEC OrderKey path keys on the "filter-tag" tag value (resolveOrderTag),
+//     so the element's filter-tag value equals the sortable field's term.
+//
+// The shared generateData fixture cannot serve as an index-sort oracle: it stamps
+// DocID=timestamp (never matching an element id) and sets no Timestamp on its docs
+// (so the sort query's date range matches nothing). Hence this dedicated writer.
+//
+// Sort values are assigned so index order deliberately DIFFERS from ts order (the
+// per-series value decreases as ts increases), proving the test exercises the
+// order-key path rather than accidentally matching timestamp order.
+func buildIndexOrderStream(t *testing.T) (*stream, timestamp.TimeRange) {
+	require.NoError(t, logger.Init(logger.Logging{Env: "dev", Level: flags.LogLevel}))
+	base := time.Now().Add(-time.Hour).Truncate(time.Hour)
+
+	elems := &elements{}
+	var sortDocs index.Documents
+	var minTS, maxTS int64
+	// Precompute hashed series ids the entity index derives, so the block scanner's
+	// index-resolved series id matches the element rows and the sort field key.
+	sidByK := make(map[int]common.SeriesID, indexOrderSeriesCount)
+	var entityDocs index.Documents
+	for k := 1; k <= indexOrderSeriesCount; k++ {
+		entity := []*modelv1.TagValue{
+			{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: entityTagValuePrefix + strconv.Itoa(k)}}},
+		}
+		series := &pbv1.Series{Subject: "benchmark", EntityValues: entity}
+		require.NoError(t, series.Marshal())
+		sidByK[k] = series.ID
+		entityDocs = append(entityDocs, index.Document{DocID: uint64(series.ID), EntityValues: series.Buffer})
+	}
+
+	for k := 1; k <= indexOrderSeriesCount; k++ {
+		sid := sidByK[k]
+		for j := 1; j <= indexOrderTSCount; j++ {
+			ts := base.UnixNano() + int64(j)*int64(time.Second)
+			if minTS == 0 || ts < minTS {
+				minTS = ts
+			}
+			if ts > maxTS {
+				maxTS = ts
+			}
+			elementIDStr := strconv.Itoa(k) + "-" + strconv.Itoa(j)
+			elementID := convert.HashStr(elementIDStr)
+			// Sort value decreases as ts increases => index order != ts order. Zero-pad
+			// so lexicographic term order equals numeric order.
+			sortRank := indexOrderTSCount - j
+			sortValue := filterTagValuePrefix + fmt.Sprintf("%03d", sortRank)
+
+			elems.seriesIDs = append(elems.seriesIDs, sid)
+			elems.timestamps = append(elems.timestamps, ts)
+			elems.elementIDs = append(elems.elementIDs, elementID)
+			elems.tagFamilies = append(elems.tagFamilies, []tagValues{{
+				tag: "benchmark-family",
+				values: []*tagValue{
+					{tag: "entity-tag", value: []byte(entityTagValuePrefix + strconv.Itoa(k)), valueType: pbv1.ValueTypeStr},
+					{tag: "filter-tag", value: []byte(sortValue), valueType: pbv1.ValueTypeStr},
+				},
+			}})
+
+			sortDocs = append(sortDocs, index.Document{
+				DocID:     elementID,
+				Timestamp: ts,
+				Fields: []index.Field{
+					index.NewBytesField(index.FieldKey{IndexRuleID: indexOrderRuleID, SeriesID: sid}, []byte(sortValue)),
+				},
+			})
+		}
+	}
+
+	db := openDatabase(t, t.TempDir())
+	t.Cleanup(func() { _ = db.Close() })
+	seg, err := db.CreateSegmentIfNotExist(time.Unix(0, elems.timestamps[0]))
+	require.NoError(t, err)
+	seg.IndexDB().Insert(entityDocs)
+	tst, err := seg.CreateTSTableIfNotExist(common.ShardID(0))
+	require.NoError(t, err)
+	tst.mustAddElements(elems)
+	tst.Index().Write(sortDocs)
+	seg.DecRef()
+
+	entity := &databasev1.Entity{TagNames: []string{"entity-tag"}}
+	tagFamily := &databasev1.TagFamilySpec{
+		Name: "benchmark-family",
+		Tags: []*databasev1.TagSpec{
+			{Name: "entity-tag", Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: "filter-tag", Type: databasev1.TagType_TAG_TYPE_STRING},
+		},
+	}
+	schema := &databasev1.Stream{
+		Metadata:    &commonv1.Metadata{Name: "benchmark", Group: "test"},
+		Entity:      entity,
+		TagFamilies: []*databasev1.TagFamilySpec{tagFamily},
+	}
+	s := &stream{
+		schema:     schema,
+		l:          logger.GetLogger("test-vec-idxorder"),
+		pm:         protector.Nop{},
+		vectorized: vstream.DefaultConfig(),
+	}
+	s.vectorized.Enabled = true
+	s.name, s.group = "benchmark", "test"
+	var is indexSchema
+	is.parse(schema)
+	s.indexSchema = atomic.Value{}
+	s.indexSchema.Store(is)
+	s.tsdb.Store(db)
+	return s, timestamp.NewInclusiveTimeRange(time.Unix(0, minTS), time.Unix(0, maxTS))
+}
diff --git a/banyand/stream/query_vectorized_test.go b/banyand/stream/query_vectorized_test.go
new file mode 100644
index 000000000..6963dbc3c
--- /dev/null
+++ b/banyand/stream/query_vectorized_test.go
@@ -0,0 +1,437 @@
+// 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.
+
+package stream
+
+import (
+	"context"
+	"math"
+	"strconv"
+	"sync/atomic"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/require"
+	"google.golang.org/protobuf/proto"
+
+	"github.com/apache/skywalking-banyandb/api/common"
+	commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+	"github.com/apache/skywalking-banyandb/banyand/internal/storage"
+	"github.com/apache/skywalking-banyandb/banyand/protector"
+	"github.com/apache/skywalking-banyandb/pkg/index"
+	"github.com/apache/skywalking-banyandb/pkg/logger"
+	pbv1 "github.com/apache/skywalking-banyandb/pkg/pb/v1"
+	logicalstream "github.com/apache/skywalking-banyandb/pkg/query/logical/stream"
+	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
+	"github.com/apache/skywalking-banyandb/pkg/test/flags"
+	"github.com/apache/skywalking-banyandb/pkg/timestamp"
+)
+
+// buildVecTestStream constructs a stream over a real fixture part written by the
+// benchmark fixture helpers (generateData / write), with the logger, protector,
+// and index schema populated so both the row Query path and the vectorized scan
+// path execute end-to-end.
+func buildVecTestStream(t *testing.T, p parameter) (*stream, timestamp.TimeRange) {
+	require.NoError(t, logger.Init(logger.Logging{Env: "dev", Level: flags.LogLevel}))
+	esList, docsList, _ := generateData(p)
+	// generateData stamps 1970-epoch timestamps, which a live TTL reclaims before
+	// the query runs (SelectSegments returns nothing). Shift every element to a
+	// recent segment and return the covering time range for the query.
+	base := time.Now().Add(-time.Hour).Truncate(time.Hour)
+	var minTS, maxTS int64
+	for _, es := range esList {
+		for i := range es.timestamps {
+			es.timestamps[i] = base.UnixNano() + es.timestamps[i]
+			if minTS == 0 || es.timestamps[i] < minTS {
+				minTS = es.timestamps[i]
+			}
+			if es.timestamps[i] > maxTS {
+				maxTS = es.timestamps[i]
+			}
+		}
+	}
+	tr := timestamp.NewInclusiveTimeRange(time.Unix(0, minTS), time.Unix(0, maxTS))
+	db := writeVecFixture(t, p, esList, docsList)
+
+	entity := &databasev1.Entity{TagNames: []string{"entity-tag"}}
+	tagFamily := &databasev1.TagFamilySpec{
+		Name: "benchmark-family",
+		Tags: []*databasev1.TagSpec{
+			{Name: "entity-tag", Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: "filter-tag", Type: databasev1.TagType_TAG_TYPE_STRING},
+		},
+	}
+	schema := &databasev1.Stream{
+		Metadata:    &commonv1.Metadata{Name: "benchmark", Group: "test"},
+		Entity:      entity,
+		TagFamilies: []*databasev1.TagFamilySpec{tagFamily},
+	}
+	s := &stream{
+		schema:     schema,
+		l:          logger.GetLogger("test-vec-stream"),
+		pm:         protector.Nop{},
+		vectorized: vstream.DefaultConfig(),
+	}
+	s.vectorized.Enabled = true
+	s.name, s.group = "benchmark", "test"
+	var is indexSchema
+	is.parse(schema)
+	s.indexSchema = atomic.Value{}
+	s.indexSchema.Store(is)
+	s.tsdb.Store(db)
+	return s, tr
+}
+
+// writeVecFixture mirrors the benchmark write helper but persists into a
+// t.TempDir() that lives for the whole test, rather than a self-deleting
+// test.Space. The benchmark's write() removes its temp dir on return, which is
+// fine for a bench that never re-reads persisted parts but breaks a query test
+// (and races the background flusher) — hence a dedicated writer here.
+func writeVecFixture(t *testing.T, p parameter, esList []*elements, docsList []index.Documents) storage.TSDB[*tsTable, option] {
+	db := openDatabase(t, t.TempDir())
+	// Close the TSDB before t.TempDir() removal so the background flusher loop
+	// stops writing into a directory that is about to be deleted.
+	t.Cleanup(func() { _ = db.Close() })
+	var docs index.Documents
+	// sidByK maps the placeholder series id generateData stamps (common.SeriesID(k),
+	// k=1..seriesCount) to the real hashed series id the entity index derives from
+	// the marshaled series buffer. generateData writes the placeholder ids, which
+	// the block scanner then fails to match against the index-resolved ids — so the
+	// element rows must be re-stamped with the hashed ids before they are added.
+	sidByK := make(map[common.SeriesID]common.SeriesID, p.seriesCount)
+	for i := 1; i <= p.seriesCount; i++ {
+		entity := []*modelv1.TagValue{
+			{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: entityTagValuePrefix + strconv.Itoa(i)}}},
+		}
+		series := &pbv1.Series{Subject: "benchmark", EntityValues: entity}
+		require.NoError(t, series.Marshal())
+		sidByK[common.SeriesID(i)] = series.ID
+		docs = append(docs, index.Document{DocID: uint64(series.ID), EntityValues: series.Buffer})
+	}
+	for _, es := range esList {
+		for i := range es.seriesIDs {
+			if mapped, ok := sidByK[es.seriesIDs[i]]; ok {
+				es.seriesIDs[i] = mapped
+			}
+		}
+	}
+	seg, err := db.CreateSegmentIfNotExist(time.Unix(0, esList[0].timestamps[0]))
+	require.NoError(t, err)
+	seg.IndexDB().Insert(docs)
+	tst, err := seg.CreateTSTableIfNotExist(common.ShardID(0))
+	require.NoError(t, err)
+	for i := range esList {
+		tst.mustAddElements(esList[i])
+		tst.Index().Write(docsList[i])
+	}
+	seg.DecRef()
+	return db
+}
+
+func indexByElementID(t *testing.T, elements []*streamv1.Element) map[string]*streamv1.Element {
+	out := make(map[string]*streamv1.Element, len(elements))
+	for _, e := range elements {
+		_, exists := out[e.ElementId]
+		require.False(t, exists, "unexpected duplicate elementID within a single path: %s", e.ElementId)
+		out[e.ElementId] = e
+	}
+	return out
+}
+
+func assertElementsEqual(t *testing.T, want, got *streamv1.Element) {
+	require.True(t, proto.Equal(want.Timestamp, got.Timestamp),
+		"timestamp mismatch for %s: want %v got %v", want.ElementId, want.Timestamp, got.Timestamp)
+	require.Equal(t, len(want.TagFamilies), len(got.TagFamilies), "tag family count mismatch for %s", want.ElementId)
+	for i := range want.TagFamilies {
+		wf, gf := want.TagFamilies[i], got.TagFamilies[i]
+		require.Equal(t, wf.Name, gf.Name)
+		require.Equal(t, len(wf.Tags), len(gf.Tags), "tag count mismatch in family %s", wf.Name)
+		for j := range wf.Tags {
+			require.Equal(t, wf.Tags[j].Key, gf.Tags[j].Key)
+			require.True(t, proto.Equal(wf.Tags[j].Value, gf.Tags[j].Value),
+				"tag value mismatch for %s.%s.%s", want.ElementId, wf.Name, wf.Tags[j].Key)
+		}
+	}
+}
+
+// TestQueryVectorized_NoOrder_MatchesRowPath scans a real fixture part with both
+// the row path (Query -> BuildElementsFromStreamResult) and the vec path
+// (queryVectorized -> BuildElementsFromVecBatches) for a no-order query with a
+// two-tag projection, and asserts the produced element SETS are equal (keyed by
+// elementID). Ordering/dedup across sources is M4; comparison is set-based.
+func TestQueryVectorized_NoOrder_MatchesRowPath(t *testing.T) {
+	// A single write batch keeps the fixture to one part / one disjoint block
+	// group, so the row egress (BuildElementsFromStreamResult reads exactly one
+	// non-empty Pull) and the drain-everything vec egress see the identical set.
+	// Cross-part multi-Pull merge is a M4 operator concern, not an M3 scan one.
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 20,
+		seriesCount:    5,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   1000,
+		scenario:       "vec-parity",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := make([][]*modelv1.TagValue, 0, p.seriesCount)
+	for i := 1; i <= p.seriesCount; i++ {
+		entities = append(entities, []*modelv1.TagValue{
+			{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: entityTagValuePrefix + strconv.Itoa(i)}}},
+		})
+	}
+	tagProjection := []model.TagProjection{{
+		Family: "benchmark-family",
+		Names:  []string{"entity-tag", "filter-tag"},
+	}}
+	// No-order query over the full fixture range (no inverted filter) so the
+	// fixture yields a representative, non-degenerate set for the parity check.
+	sqo := model.StreamQueryOptions{
+		Name:           "benchmark",
+		TimeRange:      &tr,
+		Entities:       entities,
+		TagProjection:  tagProjection,
+		MaxElementSize: math.MaxInt32,
+	}
+
+	ctx := context.Background()
+
+	rowRes, err := s.Query(ctx, sqo)
+	require.NoError(t, err)
+	require.NotNil(t, rowRes)
+	defer rowRes.Release()
+	rowElements, err := logicalstream.BuildElementsFromStreamResult(ctx, rowRes, sqo.TagProjection)
+	require.NoError(t, err)
+
+	src, err := s.queryVectorized(ctx, sqo)
+	require.NoError(t, err)
+	require.NotNil(t, src)
+	defer src.Release()
+	vecElements, err := BuildElementsFromVecBatches(ctx, src, sqo.TagProjection)
+	require.NoError(t, err)
+
+	require.NotEmpty(t, rowElements, "row path produced no elements; fixture is degenerate")
+
+	rowByID := indexByElementID(t, rowElements)
+	// The vec path does not dedup across cursors in M3; collapse to first-seen
+	// per elementID so the SET comparison matches the row path's deduped set.
+	vecByID := make(map[string]*streamv1.Element, len(vecElements))
+	for _, e := range vecElements {
+		if _, ok := vecByID[e.ElementId]; !ok {
+			vecByID[e.ElementId] = e
+		}
+	}
+
+	require.Equal(t, len(rowByID), len(vecByID), "element-set size mismatch between row and vec paths")
+	for id, wantElem := range rowByID {
+		gotElem, ok := vecByID[id]
+		require.True(t, ok, "vec path missing elementID present in row path: %s", id)
+		assertElementsEqual(t, wantElem, gotElem)
+	}
+}
+
+// TestQueryVectorized_FullPipeline_MatchesRowPath is the M6 standalone-parity
+// test: it drives the vec scan through the FULL M4 pipeline (merge → distinct →
+// limit) and the batch egress (BuildElementsFromBatches), exactly as the data-node
+// standalone processor path does, then asserts the produced []*streamv1.Element is
+// identical (order + values) to the row path for representative queries.
+func TestQueryVectorized_FullPipeline_MatchesRowPath(t *testing.T) {
+	// A single write batch keeps the fixture to one part so the row egress
+	// (BuildElementsFromStreamResult reads exactly one non-empty Pull) sees the
+	// same complete set the drain-everything vec pipeline does. Cross-part
+	// dedup/merge is covered by the M4 operator unit tests, not this end-to-end
+	// engine parity check.
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 20,
+		seriesCount:    5,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   1000,
+		scenario:       "vec-full-pipeline",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := make([][]*modelv1.TagValue, 0, p.seriesCount)
+	for i := 1; i <= p.seriesCount; i++ {
+		entities = append(entities, []*modelv1.TagValue{
+			{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: entityTagValuePrefix + strconv.Itoa(i)}}},
+		})
+	}
+	tagProjection := []model.TagProjection{{
+		Family: "benchmark-family",
+		Names:  []string{"entity-tag", "filter-tag"},
+	}}
+
+	cases := []struct {
+		name string
+		desc bool
+	}{
+		{name: "ts-order-asc", desc: false},
+		{name: "ts-order-desc", desc: true},
+	}
+	for _, tc := range cases {
+		t.Run(tc.name, func(t *testing.T) {
+			order := &index.OrderBy{Sort: modelv1.Sort_SORT_ASC}
+			if tc.desc {
+				order.Sort = modelv1.Sort_SORT_DESC
+			}
+			sqo := model.StreamQueryOptions{
+				Name:           "benchmark",
+				TimeRange:      &tr,
+				Entities:       entities,
+				TagProjection:  tagProjection,
+				Order:          order,
+				MaxElementSize: math.MaxInt32,
+			}
+
+			ctx := context.Background()
+
+			rowRes, err := s.Query(ctx, sqo)
+			require.NoError(t, err)
+			require.NotNil(t, rowRes)
+			defer rowRes.Release()
+			rowElements, err := logicalstream.BuildElementsFromStreamResult(ctx, rowRes, sqo.TagProjection)
+			require.NoError(t, err)
+			require.NotEmpty(t, rowElements, "row path produced no elements; fixture is degenerate")
+
+			src, err := s.queryVectorized(ctx, sqo)
+			require.NoError(t, err)
+			require.NotNil(t, src)
+			schema := src.Schema()
+			pipeline, err := vstream.BuildStreamMergePipeline(
+				&testVecSource{src: src, schema: schema}, schema, tc.desc, 0, uint32(len(rowElements)*4), vstream.DefaultConfig().BatchSize, 0)
+			require.NoError(t, err)
+			require.NoError(t, pipeline.Init(ctx))
+			var batches []*vectorized.RecordBatch
+			for {
+				batch, nextErr := pipeline.Next(ctx)
+				require.NoError(t, nextErr)
+				if batch == nil {
+					break
+				}
+				batches = append(batches, batch)
+			}
+			vecElements, err := BuildElementsFromBatches(batches, sqo.TagProjection)
+			require.NoError(t, err)
+			require.NoError(t, pipeline.Close())
+
+			// Equal-timestamp rows have no cross-path-stable tie-break (the row
+			// ts-order and the vec SortedMerge tie differently), so parity is
+			// asserted as: (1) identical element SET keyed by elementID with
+			// identical values, and (2) the vec output is monotonically ordered by
+			// timestamp per asc/desc. This is the same set-based discipline the
+			// no-order parity test uses.
+			require.Equal(t, len(rowElements), len(vecElements), "element count mismatch")
+			rowByID := indexByElementID(t, rowElements)
+			vecByID := indexByElementID(t, vecElements)
+			require.Equal(t, len(rowByID), len(vecByID), "element-set size mismatch")
+			for id, wantElem := range rowByID {
+				gotElem, ok := vecByID[id]
+				require.True(t, ok, "vec path missing elementID present in row path: %s", id)
+				assertElementsEqual(t, wantElem, gotElem)
+			}
+			for i := 1; i < len(vecElements); i++ {
+				prev := vecElements[i-1].Timestamp.AsTime().UnixNano()
+				cur := vecElements[i].Timestamp.AsTime().UnixNano()
+				if tc.desc {
+					require.GreaterOrEqual(t, prev, cur, "vec output not desc-ordered by ts at %d", i)
+				} else {
+					require.LessOrEqual(t, prev, cur, "vec output not asc-ordered by ts at %d", i)
+				}
+			}
+		})
+	}
+}
+
+// testVecSource adapts a vecScanSource to a vectorized.PullOperator so the test
+// can drive the M4 pipeline directly, mirroring the production vecSourceOperator.
+type testVecSource struct {
+	src    vecScanSource
+	schema *vectorized.BatchSchema
+}
+
+func (o *testVecSource) Init(context.Context) error            { return nil }
+func (o *testVecSource) OutputSchema() *vectorized.BatchSchema { return o.schema }
+func (o *testVecSource) Close() error                          { o.src.Release(); return nil }
+func (o *testVecSource) NextBatch(ctx context.Context) (*vectorized.RecordBatch, error) {
+	return o.src.NextBatch(ctx)
+}
+
+// TestBuildElementsFromVecBatches_EmptySource verifies the egress helper returns
+// no elements and no error for an exhausted source.
+func TestBuildElementsFromVecBatches_EmptySource(t *testing.T) {
+	elements, err := BuildElementsFromVecBatches(context.Background(), emptyVecScan{},
+		[]model.TagProjection{{Family: "f", Names: []string{"a"}}})
+	require.NoError(t, err)
+	require.Empty(t, elements)
+}
+
+// TestQueryVectorized_MemoryBudget verifies the QueryMemoryMiB soft byte budget
+// FAILS LOUD: a tiny budget processes the first block (first-block exception) but
+// then returns ErrQueryMemoryBudgetExceeded when a later block would exceed the
+// remaining budget, rather than silently truncating. This preserves vec==row
+// parity (the row path errors under memory pressure via the protector). The
+// multi-series fixture yields multiple blocks so the over-budget block is reached.
+func TestQueryVectorized_MemoryBudget(t *testing.T) {
+	p := parameter{
+		batchCount:     1,
+		timestampCount: 20,
+		seriesCount:    5,
+		tagCardinality: 4,
+		startTimestamp: 1,
+		endTimestamp:   1000,
+		scenario:       "vec-budget",
+	}
+	s, tr := buildVecTestStream(t, p)
+	entities := make([][]*modelv1.TagValue, 0, p.seriesCount)
+	for i := 1; i <= p.seriesCount; i++ {
+		entities = append(entities, []*modelv1.TagValue{
+			{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: entityTagValuePrefix + strconv.Itoa(i)}}},
+		})
+	}
+	sqo := model.StreamQueryOptions{
+		Name:           "benchmark",
+		TimeRange:      &tr,
+		Entities:       entities,
+		TagProjection:  []model.TagProjection{{Family: "benchmark-family", Names: []string{"entity-tag"}}},
+		MaxElementSize: math.MaxInt32,
+	}
+	ctx := context.Background()
+
+	// Unbounded scan (default 256 MiB budget): count every row.
+	fullSrc, err := s.queryVectorized(ctx, sqo)
+	require.NoError(t, err)
+	fullElements, err := BuildElementsFromVecBatches(ctx, fullSrc, sqo.TagProjection)
+	require.NoError(t, err)
+	require.Greater(t, len(fullElements), 1, "fixture must yield multiple blocks for the budget test")
+
+	// Budget scan: force a 1-byte budget on the source so the first block decodes
+	// (first-block exception) but the next over-budget block fails the query loud.
+	budgetSrc, err := s.queryVectorized(ctx, sqo)
+	require.NoError(t, err)
+	vs, ok := budgetSrc.(*streamVecScan)
+	require.True(t, ok, "expected *streamVecScan")
+	vs.mem = vectorized.NewMemoryTracker(1)
+	_, err = BuildElementsFromVecBatches(ctx, budgetSrc, sqo.TagProjection)
+	require.Error(t, err, "an over-budget block must fail loud, not silently truncate")
+	require.ErrorIs(t, err, ErrQueryMemoryBudgetExceeded)
+}
diff --git a/banyand/stream/stream.go b/banyand/stream/stream.go
index 7d47871f1..e16c86535 100644
--- a/banyand/stream/stream.go
+++ b/banyand/stream/stream.go
@@ -30,7 +30,9 @@ import (
 	"github.com/apache/skywalking-banyandb/banyand/queue"
 	"github.com/apache/skywalking-banyandb/pkg/logger"
 	"github.com/apache/skywalking-banyandb/pkg/partition"
+	"github.com/apache/skywalking-banyandb/pkg/query/executor"
 	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
 	"github.com/apache/skywalking-banyandb/pkg/run"
 	"github.com/apache/skywalking-banyandb/pkg/schema"
 	"github.com/apache/skywalking-banyandb/pkg/timestamp"
@@ -56,6 +58,7 @@ type option struct {
 	syncInterval                 time.Duration
 	memWaitTimeout               time.Duration
 	failedPartsMaxTotalSizeBytes uint64
+	vectorized                   vstream.VectorizedConfig
 }
 
 // Query allow to retrieve elements in a series of streams.
@@ -70,6 +73,8 @@ type Stream interface {
 	GetSchema() *databasev1.Stream
 	GetIndexRules() []*databasev1.IndexRule
 	Query(ctx context.Context, opts model.StreamQueryOptions) (model.StreamQueryResult, error)
+	QueryVectorized(ctx context.Context, opts model.StreamQueryOptions) (executor.StreamVecScanSource, error)
+	VectorizedConfig() vstream.VectorizedConfig
 }
 
 type indexSchema struct {
@@ -99,6 +104,7 @@ type stream struct {
 	schemaRepo  *schemaRepo
 	name        string
 	group       string
+	vectorized  vstream.VectorizedConfig
 }
 
 func (s *stream) GetSchema() *databasev1.Stream {
@@ -132,14 +138,38 @@ type streamSpec struct {
 }
 
 func openStream(spec streamSpec,
-	l *logger.Logger, pm protector.Memory, schemaRepo *schemaRepo,
+	l *logger.Logger, pm protector.Memory, schemaRepo *schemaRepo, vectorized vstream.VectorizedConfig,
 ) *stream {
 	s := &stream{
 		schema:     spec.schema,
 		l:          l,
 		pm:         pm,
 		schemaRepo: schemaRepo,
+		vectorized: vectorized,
 	}
 	s.parseSpec()
 	return s
 }
+
+// VectorizedConfig returns the per-Stream vectorized query configuration.
+func (s *stream) VectorizedConfig() vstream.VectorizedConfig {
+	return s.vectorized
+}
+
+// QueryVectorized returns a pull-based columnar scan source for the vec path.
+// It is the exported executor-facing wrapper over queryVectorized; the returned
+// vecScanSource already satisfies executor.StreamVecScanSource structurally.
+func (s *stream) QueryVectorized(ctx context.Context, opts model.StreamQueryOptions) (executor.StreamVecScanSource, error) {
+	return s.queryVectorized(ctx, opts)
+}
+
+// bindVectorizedFlags wires VectorizedConfig fields to a run.FlagSet.
+func bindVectorizedFlags(flagS *run.FlagSet, cfg *vstream.VectorizedConfig) {
+	defaults := vstream.DefaultConfig()
+	flagS.BoolVar(&cfg.Enabled, "stream-vectorized-enabled", defaults.Enabled,
+		"enable the vectorized stream query path")
+	flagS.IntVar(&cfg.BatchSize, "stream-vectorized-batch-size", defaults.BatchSize,
+		"row count per vectorized stream batch")
+	flagS.IntVar(&cfg.QueryMemoryMiB, "stream-vectorized-query-memory-mib", defaults.QueryMemoryMiB,
+		"per-query memory budget for the vectorized stream path, in MiB")
+}
diff --git a/banyand/stream/svc_liaison.go b/banyand/stream/svc_liaison.go
index 176b7f6ba..a9fe96fdc 100644
--- a/banyand/stream/svc_liaison.go
+++ b/banyand/stream/svc_liaison.go
@@ -43,6 +43,7 @@ import (
 	"github.com/apache/skywalking-banyandb/pkg/logger"
 	"github.com/apache/skywalking-banyandb/pkg/node"
 	banyandbpath "github.com/apache/skywalking-banyandb/pkg/path"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
 	"github.com/apache/skywalking-banyandb/pkg/run"
 	resourceSchema "github.com/apache/skywalking-banyandb/pkg/schema"
 	"github.com/apache/skywalking-banyandb/pkg/timestamp"
@@ -85,6 +86,11 @@ func (s *liaison) GetRemovalSegmentsTimeRange(group string) *timestamp.TimeRange
 	return s.schemaRepo.GetRemovalSegmentsTimeRange(group)
 }
 
+// VectorizedConfig returns the stream vectorized query configuration.
+func (s *liaison) VectorizedConfig() vstream.VectorizedConfig {
+	return s.option.vectorized
+}
+
 func (s *liaison) CollectDataInfo(_ context.Context, _ string) (*databasev1.DataInfo, error) {
 	return nil, errors.New("collect data info is not supported on liaison node")
 }
@@ -125,6 +131,7 @@ func (s *liaison) FlagSet() *run.FlagSet {
 		"percentage of BanyanDB's allowed disk usage allocated to failed parts storage. "+
 			"Calculated as: totalDisk * stream-max-disk-usage-percent * failed-parts-max-size-percent / 10000. "+
 			"Set to 0 to disable copying failed parts. Valid range: 0-100")
+	bindVectorizedFlags(flagS, &s.option.vectorized)
 	return flagS
 }
 
@@ -141,7 +148,7 @@ func (s *liaison) Validate() error {
 	if s.failedPartsMaxSizePercent < 0 || s.failedPartsMaxSizePercent > 100 {
 		return errors.New("failed-parts-max-size-percent must be between 0 and 100")
 	}
-	return nil
+	return s.option.vectorized.Validate()
 }
 
 func (s *liaison) Name() string {
@@ -154,6 +161,8 @@ func (s *liaison) Role() databasev1.Role {
 
 func (s *liaison) PreRun(ctx context.Context) error {
 	s.l = logger.GetLogger(s.Name())
+	data.SetStreamWireModeRaw(s.option.vectorized.Enabled)
+	s.l.Info().Bool("stream_wire_mode_raw", s.option.vectorized.Enabled).Msg("stream wire mode published (liaison)")
 	s.l.Info().Msg("memory protector is initialized in PreRun")
 	s.lfs = fs.NewLocalFileSystemWithLoggerAndLimit(s.l, s.pm.GetLimit())
 	var err error
diff --git a/banyand/stream/svc_standalone.go b/banyand/stream/svc_standalone.go
index 8a80b99f5..fe8751b3e 100644
--- a/banyand/stream/svc_standalone.go
+++ b/banyand/stream/svc_standalone.go
@@ -42,6 +42,7 @@ import (
 	"github.com/apache/skywalking-banyandb/pkg/fs"
 	"github.com/apache/skywalking-banyandb/pkg/logger"
 	banyandbpath "github.com/apache/skywalking-banyandb/pkg/path"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
 	"github.com/apache/skywalking-banyandb/pkg/run"
 	resourceSchema "github.com/apache/skywalking-banyandb/pkg/schema"
 	"github.com/apache/skywalking-banyandb/pkg/timestamp"
@@ -61,6 +62,7 @@ type Service interface {
 	Query
 	CollectDataInfo(context.Context, string) (*databasev1.DataInfo, error)
 	CollectLiaisonInfo(context.Context, string) (*databasev1.LiaisonInfo, error)
+	VectorizedConfig() vstream.VectorizedConfig
 }
 
 var _ Service = (*standalone)(nil)
@@ -171,6 +173,11 @@ func (s *standalone) GetServiceName() string {
 	return s.Name()
 }
 
+// VectorizedConfig returns the stream vectorized query configuration.
+func (s *standalone) VectorizedConfig() vstream.VectorizedConfig {
+	return s.option.vectorized
+}
+
 func (s *standalone) FlagSet() *run.FlagSet {
 	flagS := run.NewFlagSet("storage")
 	flagS.StringVar(&s.root, "stream-root-path", "/tmp", "the root path of stream")
@@ -197,6 +204,7 @@ func (s *standalone) FlagSet() *run.FlagSet {
 
 	flagS.IntVar(&s.maxFileSnapshotNum, "stream-max-file-snapshot-num", 10, "the maximum number of file snapshots allowed")
 	flagS.DurationVar(&s.minFileSnapshotAge, "stream-min-file-snapshot-age", time.Hour, "minimum age for file snapshots to be eligible for deletion")
+	bindVectorizedFlags(flagS, &s.option.vectorized)
 	return flagS
 }
 
@@ -222,7 +230,7 @@ func (s *standalone) Validate() error {
 		return errors.New("stream-retention-cooldown must be greater than 0")
 	}
 
-	return nil
+	return s.option.vectorized.Validate()
 }
 
 func (s *standalone) Name() string {
@@ -235,6 +243,10 @@ func (s *standalone) Role() databasev1.Role {
 
 func (s *standalone) PreRun(ctx context.Context) error {
 	s.l = logger.GetLogger(s.Name())
+	// Native columnar wire frame for the data↔liaison query hop follows the
+	// vectorized flag (mirrors trace's wire-mode wiring).
+	data.SetStreamWireModeRaw(s.option.vectorized.Enabled)
+	s.l.Info().Bool("stream_wire_mode_raw", s.option.vectorized.Enabled).Msg("stream wire mode published (standalone)")
 	s.l.Info().Msg("memory protector is initialized in PreRun")
 	s.lfs = fs.NewLocalFileSystemWithLoggerAndLimit(s.l, s.pm.GetLimit())
 	var err error
diff --git a/banyand/trace/block.go b/banyand/trace/block.go
index 408e8c382..c022452b0 100644
--- a/banyand/trace/block.go
+++ b/banyand/trace/block.go
@@ -356,6 +356,9 @@ func mustReadSpansFrom(decoder *encoding.BytesBlockDecoder, spans [][]byte, span
 }
 
 func mustSeqReadSpansFrom(decoder *encoding.BytesBlockDecoder, spans [][]byte, spanIDs []string, sm *dataBlock, count int, reader *seqReader) ([][]byte, []string) {
+	if sm == nil || sm.size == 0 {
+		return spans[:0], spanIDs[:0]
+	}
 	if sm.offset != reader.bytesRead {
 		logger.Panicf("offset %d must be equal to bytesRead %d", sm.offset, reader.bytesRead)
 	}
@@ -472,6 +475,11 @@ func (bc *blockCursor) reset() {
 		bc.tags[i].reset()
 	}
 	bc.tags = bc.tags[:0]
+	// Nil the decoder's backing array rather than zero-slicing it so that
+	// the decompressed span bytes (held by decompressBlock inside the decoder)
+	// become unreachable and can be reclaimed by GC when the cursor is pooled.
+	// Reset() only does data=data[:0] which keeps the backing array alive.
+	bc.tagValuesDecoder = encoding.BytesBlockDecoder{}
 }
 
 func (bc *blockCursor) init(p *part, bm *blockMetadata, opts queryOptions) {
diff --git a/banyand/trace/block_reader.go b/banyand/trace/block_reader.go
index 72bc2d8c9..9e875c497 100644
--- a/banyand/trace/block_reader.go
+++ b/banyand/trace/block_reader.go
@@ -234,9 +234,12 @@ func (br *blockReader) peek() *blockPointer {
 	if nextBM, ok := br.pih[0].peekBlockMetadata(); ok {
 		// If the next block in the same part has the same traceID, we can't use fast path
 		if nextBM.traceID == currentTraceID {
-			// Reuse peekBlock to avoid allocation
+			// Reuse peekBlock to avoid allocation. Deep-copy via copyFrom so the
+			// spans/tags *dataBlock pointers are owned by peekBlock; a shallow
+			// struct copy would alias nextBM's pooled dataBlock, which the
+			// following release zeroes (use-after-pool-release).
 			br.peekBlock.reset()
-			br.peekBlock.bm = *nextBM
+			br.peekBlock.bm.copyFrom(nextBM)
 			releaseBlockMetadata(nextBM)
 			return &br.peekBlock
 		}
diff --git a/banyand/trace/merger_offset_regression_test.go b/banyand/trace/merger_offset_regression_test.go
new file mode 100644
index 000000000..26a2d4e92
--- /dev/null
+++ b/banyand/trace/merger_offset_regression_test.go
@@ -0,0 +1,239 @@
+// 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.
+
+package trace
+
+import (
+	"path/filepath"
+	"testing"
+
+	"github.com/stretchr/testify/require"
+
+	"github.com/apache/skywalking-banyandb/pkg/encoding"
+	"github.com/apache/skywalking-banyandb/pkg/fs"
+	pbv1 "github.com/apache/skywalking-banyandb/pkg/pb/v1"
+	"github.com/apache/skywalking-banyandb/pkg/test"
+)
+
+// Test_mustSeqReadSpansFrom_zeroSizeBlock reproduces the trace-merger panic
+// "offset N must be equal to bytesRead M". A block whose spans metadata is
+// {offset:0, size:0} (an empty-spans block written after other blocks) is read
+// through the sequential merge path. The reader has already advanced past byte
+// zero, so the unconditional alignment assertion fires even though the block
+// has no span bytes to read. mustReadRaw already guards this with
+// `bm.spans.size > 0`; mustSeqReadSpansFrom must do the same.
+func Test_mustSeqReadSpansFrom_zeroSizeBlock(t *testing.T) {
+	req := require.New(t)
+	tmpPath, defFn := test.Space(req)
+	defer defFn()
+
+	fileSystem := fs.NewLocalFileSystem()
+	spansPath := filepath.Join(tmpPath, spansFilename)
+
+	// Write a non-empty spans file so the sequential reader can advance past
+	// offset zero, mimicking a real part where earlier blocks carry span bytes.
+	payload := make([]byte, 887)
+	for i := range payload {
+		payload[i] = byte(i)
+	}
+	fs.MustFlush(fileSystem, payload, spansPath, 0o644)
+
+	reader := mustOpenReader(spansPath, fileSystem)
+	defer fs.MustClose(reader)
+
+	sr := &seqReader{}
+	sr.init(reader)
+	defer sr.reset()
+
+	// Advance the reader past offset zero, as a prior block read would.
+	scratch := make([]byte, len(payload))
+	sr.mustReadFull(scratch)
+	require.EqualValues(t, len(payload), sr.bytesRead)
+
+	// A zero-size spans block (empty spans, non-first position): offset stays 0
+	// from reset because mustWriteSpansTo early-returns for empty spans.
+	sm := &dataBlock{offset: 0, size: 0}
+	decoder := &encoding.BytesBlockDecoder{}
+
+	// Before the fix this panics with "offset 0 must be equal to bytesRead 887".
+	require.NotPanics(t, func() {
+		spans, spanIDs := mustSeqReadSpansFrom(decoder, nil, nil, sm, 0, sr)
+		require.Empty(t, spans)
+		require.Empty(t, spanIDs)
+	}, "reading a zero-size spans block must not panic on the alignment assertion")
+}
+
+// Test_mergeBlocks_sameTraceID_twoGenerations exercises the fast/slow path
+// mixing in mergeBlocks across two merge generations with the real fast path
+// enabled (forceSlowMerge=false). A traceID present in two source parts forces
+// the slow merge path (block accumulation) interleaved with fast-path raw
+// copies of unique traceIDs. The merged output is then merged again, and every
+// block must read back with correct span data. This guards the br.peek()
+// deep-copy fix (use-after-pool-release of the spans *dataBlock) and overall
+// offset bookkeeping.
+//
+// Coverage note: this exercises the same-traceID-within-a-granule case. The
+// peekBlockMetadata boundary branch (same traceID straddling a 128KB primary
+// granule edge) cannot be reproduced at unit scale — it needs one traceID to
+// own >2600 blocks (>5GB of spans) — so that path is exercised by the long
+// soak (scripts/soak-vectorized.sh SOAK_ENGINE=trace), where it originally
+// surfaced. Test_mustSeqReadSpansFrom_zeroSizeBlock above is the deterministic
+// guard for the resulting panic.
+func Test_mergeBlocks_sameTraceID_twoGenerations(t *testing.T) {
+	req := require.New(t)
+	tmpPath, defFn := test.Space(req)
+	defer defFn()
+
+	fileSystem := fs.NewLocalFileSystem()
+
+	prevForceSlow := forceSlowMerge
+	forceSlowMerge = false
+	defer func() { forceSlowMerge = prevForceSlow }()
+
+	buildTrace := func(tid, spanID string, ts int64, val string) (string, string, int64, []*tagValue, []byte) {
+		tv := &tagValue{tag: "tag1", valueType: pbv1.ValueTypeStr, value: []byte(val)}
+		return tid, spanID, ts, []*tagValue{tv}, []byte("span-" + spanID)
+	}
+
+	appendTrace := func(ts *traces, tid, spanID string, t int64, val string) {
+		atid, asid, at, atags, aspan := buildTrace(tid, spanID, t, val)
+		ts.traceIDs = append(ts.traceIDs, atid)
+		ts.spanIDs = append(ts.spanIDs, asid)
+		ts.timestamps = append(ts.timestamps, at)
+		ts.tags = append(ts.tags, atags)
+		ts.spans = append(ts.spans, aspan)
+	}
+
+	// Part 0: traceA (unique, fast path), traceM (shared, slow path).
+	p0 := &traces{}
+	appendTrace(p0, "traceA", "a1", 1, "va1")
+	appendTrace(p0, "traceM", "m1", 2, "vm1")
+
+	// Part 1: traceM (shared, slow path), traceZ (unique, fast path).
+	p1 := &traces{}
+	appendTrace(p1, "traceM", "m2", 3, "vm2")
+	appendTrace(p1, "traceZ", "z1", 4, "vz1")
+
+	gen1 := mergeTracesParts(t, fileSystem, tmpPath, 100, []*traces{p0, p1})
+
+	// Second generation: merge the gen-1 output with another fresh part that
+	// also shares traceM, re-driving the slow path on a previously merged part.
+	p2 := &traces{}
+	appendTrace(p2, "traceM", "m3", 5, "vm3")
+	appendTrace(p2, "traceQ", "q1", 6, "vq1")
+	mp2 := generateMemPart()
+	mp2.mustInitFromTraces(p2)
+	mp2.mustFlush(fileSystem, partPath(tmpPath, 150))
+	releaseMemPart(mp2)
+
+	gen2Parts := []*part{
+		gen1,
+		mustOpenFilePart(150, tmpPath, fileSystem),
+	}
+	merged2 := mergePartsDirect(t, fileSystem, tmpPath, 200, gen2Parts)
+
+	// Verify every block in the twice-merged part reads back cleanly.
+	expectedCounts := map[string]int{
+		"traceA": 1,
+		"traceM": 3,
+		"traceQ": 1,
+		"traceZ": 1,
+	}
+	got := readBackBlocks(t, merged2)
+	for tid, want := range expectedCounts {
+		require.Equal(t, want, got[tid], "trace %s span count after two merges", tid)
+	}
+}
+
+// mergeTracesParts flushes the given traces into separate file parts, merges
+// them with mergeBlocks, and returns the opened merged part.
+func mergeTracesParts(t *testing.T, fileSystem fs.FileSystem, tmpPath string, dstID uint64, parts []*traces) *part {
+	t.Helper()
+	src := make([]*part, 0, len(parts))
+	for i, ts := range parts {
+		mp := generateMemPart()
+		mp.mustInitFromTraces(ts)
+		mp.mustFlush(fileSystem, partPath(tmpPath, dstID+uint64(i)+1))
+		releaseMemPart(mp)
+		src = append(src, mustOpenFilePart(dstID+uint64(i)+1, tmpPath, fileSystem))
+	}
+	return mergePartsDirect(t, fileSystem, tmpPath, dstID, src)
+}
+
+// mergePartsDirect runs mergeBlocks over the given source parts and returns the
+// opened merged part.
+func mergePartsDirect(t *testing.T, fileSystem fs.FileSystem, tmpPath string, dstID uint64, src []*part) *part {
+	t.Helper()
+	pii := make([]*partMergeIter, 0, len(src))
+	var traceSize uint64
+	for _, p := range src {
+		iter := generatePartMergeIter()
+		iter.mustInitFromPart(p)
+		pii = append(pii, iter)
+		traceSize += p.partMetadata.TotalCount
+	}
+
+	br := generateBlockReader()
+	br.init(pii)
+	bw := generateBlockWriter()
+	dstPath := partPath(tmpPath, dstID)
+	bw.mustInitForFilePart(fileSystem, dstPath, false, int(traceSize))
+
+	closeCh := make(chan struct{})
+	defer close(closeCh)
+
+	pm, tf, tt, _, err := mergeBlocks(closeCh, bw, br, nil, nil)
+	require.NoError(t, err)
+	require.NotNil(t, pm)
+
+	releaseBlockWriter(bw)
+	releaseBlockReader(br)
+	for _, iter := range pii {
+		releasePartMergeIter(iter)
+	}
+
+	pm.mustWriteMetadata(fileSystem, dstPath)
+	tf.mustWriteTraceIDFilter(fileSystem, dstPath)
+	tt.mustWriteTagType(fileSystem, dstPath)
+	fileSystem.SyncPath(dstPath)
+	return mustOpenFilePart(dstID, tmpPath, fileSystem)
+}
+
+// readBackBlocks loads every block of the part and returns span counts per
+// traceID, asserting span data is decodable.
+func readBackBlocks(t *testing.T, p *part) map[string]int {
+	t.Helper()
+	pmi := generatePartMergeIter()
+	pmi.mustInitFromPart(p)
+	defer releasePartMergeIter(pmi)
+
+	reader := generateBlockReader()
+	reader.init([]*partMergeIter{pmi})
+	defer releaseBlockReader(reader)
+
+	decoder := &encoding.BytesBlockDecoder{}
+	counts := make(map[string]int)
+	for reader.nextBlockMetadata() {
+		bm := reader.block.bm
+		reader.loadBlockData(decoder)
+		require.Equal(t, int(bm.count), len(reader.block.spans),
+			"trace %s: span count mismatch between metadata and data", bm.traceID)
+		counts[bm.traceID] += int(bm.count)
+	}
+	require.NoError(t, reader.error())
+	return counts
+}
diff --git a/banyand/trace/part_iter.go b/banyand/trace/part_iter.go
index 4a316d71a..23b582d8e 100644
--- a/banyand/trace/part_iter.go
+++ b/banyand/trace/part_iter.go
@@ -336,7 +336,21 @@ func (pmi *partMergeIter) loadBlockMetadata() error {
 
 func (pmi *partMergeIter) peekBlockMetadata() (*blockMetadata, bool) {
 	if len(pmi.primaryBuf) == 0 {
-		return nil, false
+		// At a primary-block (granule) boundary the current primaryBuf is
+		// exhausted, but more blocks may exist in the next granule. Look ahead
+		// using the granule index, whose traceID is the first traceID of that
+		// granule. Returning false here would let the fast path treat the
+		// current block as the unique tail of its traceID even when the same
+		// traceID continues in the next granule, producing split blocks and,
+		// after a re-merge, the "offset must equal bytesRead" panic. Only the
+		// traceID is needed by the caller to decide fast vs slow path.
+		if pmi.primaryMetadataIdx >= len(pmi.primaryBlockMetadata) {
+			return nil, false
+		}
+		bm := generateBlockMetadata()
+		bm.reset()
+		bm.traceID = pmi.primaryBlockMetadata[pmi.primaryMetadataIdx].traceID
+		return bm, true
 	}
 	bm := generateBlockMetadata()
 	_, err := bm.unmarshal(pmi.primaryBuf, pmi.tagType)
diff --git a/cmd/soak-driver/catalog/stream.json b/cmd/soak-driver/catalog/stream.json
new file mode 100644
index 000000000..c8609868d
--- /dev/null
+++ b/cmd/soak-driver/catalog/stream.json
@@ -0,0 +1,205 @@
+[
+  {
+    "id": "stream_by_time_svc0",
+    "request": {
+      "groups": [
+        "bench-stream-fixture"
+      ],
+      "name": "sw",
+      "limit": 50,
+      "criteria": {
+        "condition": {
+          "name": "service_id",
+          "op": "BINARY_OP_EQ",
+          "value": {
+            "str": {
+              "value": "svc-0"
+            }
+          }
+        }
+      },
+      "projection": {
+        "tagFamilies": [
+          {
+            "name": "searchable",
+            "tags": [
+              "service_id",
+              "state",
+              "duration"
+            ]
+          }
+        ]
+      }
+    }
+  },
+  {
+    "id": "stream_newest_svc0",
+    "request": {
+      "groups": [
+        "bench-stream-fixture"
+      ],
+      "name": "sw",
+      "limit": 20,
+      "orderBy": {
+        "sort": "SORT_DESC"
+      },
+      "criteria": {
+        "condition": {
+          "name": "service_id",
+          "op": "BINARY_OP_EQ",
+          "value": {
+            "str": {
+              "value": "svc-0"
+            }
+          }
+        }
+      },
+      "projection": {
+        "tagFamilies": [
+          {
+            "name": "searchable",
+            "tags": [
+              "service_id",
+              "state",
+              "duration"
+            ]
+          }
+        ]
+      }
+    }
+  },
+  {
+    "id": "stream_by_duration_svc0",
+    "request": {
+      "groups": [
+        "bench-stream-fixture"
+      ],
+      "name": "sw",
+      "limit": 20,
+      "orderBy": {
+        "indexRuleName": "duration",
+        "sort": "SORT_DESC"
+      },
+      "criteria": {
+        "condition": {
+          "name": "service_id",
+          "op": "BINARY_OP_EQ",
+          "value": {
+            "str": {
+              "value": "svc-0"
+            }
+          }
+        }
+      },
+      "projection": {
+        "tagFamilies": [
+          {
+            "name": "searchable",
+            "tags": [
+              "service_id",
+              "state",
+              "duration"
+            ]
+          }
+        ]
+      }
+    }
+  },
+  {
+    "id": "stream_filter_state_svc0",
+    "request": {
+      "groups": [
+        "bench-stream-fixture"
+      ],
+      "name": "sw",
+      "limit": 30,
+      "criteria": {
+        "le": {
+          "op": "LOGICAL_OP_AND",
+          "left": {
+            "condition": {
+              "name": "service_id",
+              "op": "BINARY_OP_EQ",
+              "value": {
+                "str": {
+                  "value": "svc-0"
+                }
+              }
+            }
+          },
+          "right": {
+            "condition": {
+              "name": "state",
+              "op": "BINARY_OP_EQ",
+              "value": {
+                "int": {
+                  "value": "0"
+                }
+              }
+            }
+          }
+        }
+      },
+      "projection": {
+        "tagFamilies": [
+          {
+            "name": "searchable",
+            "tags": [
+              "service_id",
+              "state",
+              "duration"
+            ]
+          }
+        ]
+      }
+    }
+  },
+  {
+    "id": "stream_all_unfiltered",
+    "request": {
+      "groups": [
+        "bench-stream-fixture"
+      ],
+      "name": "sw",
+      "limit": 50,
+      "projection": {
+        "tagFamilies": [
+          {
+            "name": "searchable",
+            "tags": [
+              "service_id",
+              "state",
+              "duration"
+            ]
+          }
+        ]
+      }
+    }
+  },
+  {
+    "id": "stream_all_by_duration",
+    "request": {
+      "groups": [
+        "bench-stream-fixture"
+      ],
+      "name": "sw",
+      "limit": 20,
+      "orderBy": {
+        "indexRuleName": "duration",
+        "sort": "SORT_DESC"
+      },
+      "projection": {
+        "tagFamilies": [
+          {
+            "name": "searchable",
+            "tags": [
+              "service_id",
+              "state",
+              "duration"
+            ]
+          }
+        ]
+      }
+    }
+  }
+]
diff --git a/cmd/soak-driver/catalog/trace.json b/cmd/soak-driver/catalog/trace.json
new file mode 100644
index 000000000..8dc5b657d
--- /dev/null
+++ b/cmd/soak-driver/catalog/trace.json
@@ -0,0 +1,158 @@
+[
+  {
+    "id": "by_id_single",
+    "request": {
+      "name": "sw",
+      "groups": ["bench-trace-fixture"],
+      "tagProjection": [
+        "trace_id", "state", "service_id", "service_instance_id",
+        "endpoint_id", "duration", "span_id", "timestamp"
+      ],
+      "criteria": {
+        "condition": {
+          "name": "trace_id",
+          "op": "BINARY_OP_EQ",
+          "value": { "str": { "value": "trace-0000000100" } }
+        }
+      },
+      "limit": 1
+    }
+  },
+  {
+    "id": "by_id_batch",
+    "request": {
+      "name": "sw",
+      "groups": ["bench-trace-fixture"],
+      "tagProjection": [
+        "trace_id", "state", "service_id", "service_instance_id",
+        "endpoint_id", "duration", "span_id", "timestamp"
+      ],
+      "criteria": {
+        "condition": {
+          "name": "trace_id",
+          "op": "BINARY_OP_IN",
+          "value": {
+            "strArray": {
+              "value": [
+                "trace-0000000098",
+                "trace-0000000099",
+                "trace-0000000100",
+                "trace-0000000101",
+                "trace-0000000102"
+              ]
+            }
+          }
+        }
+      },
+      "limit": 5
+    }
+  },
+  {
+    "id": "tag_newest",
+    "request": {
+      "name": "sw",
+      "groups": ["bench-trace-fixture"],
+      "tagProjection": [
+        "trace_id", "state", "service_id", "service_instance_id",
+        "endpoint_id", "duration", "span_id", "timestamp"
+      ],
+      "criteria": {
+        "condition": {
+          "name": "service_id",
+          "op": "BINARY_OP_EQ",
+          "value": { "str": { "value": "svc-0" } }
+        }
+      },
+      "orderBy": { "indexRuleName": "timestamp", "sort": "SORT_DESC" },
+      "limit": 50
+    }
+  },
+  {
+    "id": "tag_slowest",
+    "request": {
+      "name": "sw",
+      "groups": ["bench-trace-fixture"],
+      "tagProjection": [
+        "trace_id", "state", "service_id", "service_instance_id",
+        "endpoint_id", "duration", "span_id", "timestamp"
+      ],
+      "criteria": {
+        "le": {
+          "op": "LOGICAL_OP_AND",
+          "left": {
+            "condition": {
+              "name": "service_id",
+              "op": "BINARY_OP_EQ",
+              "value": { "str": { "value": "svc-0" } }
+            }
+          },
+          "right": {
+            "condition": {
+              "name": "state",
+              "op": "BINARY_OP_EQ",
+              "value": { "int": { "value": "0" } }
+            }
+          }
+        }
+      },
+      "orderBy": { "indexRuleName": "duration", "sort": "SORT_DESC" },
+      "limit": 50
+    }
+  },
+  {
+    "id": "tag_complex",
+    "request": {
+      "name": "sw",
+      "groups": ["bench-trace-fixture"],
+      "tagProjection": [
+        "trace_id", "state", "service_id", "service_instance_id",
+        "endpoint_id", "duration", "span_id", "timestamp"
+      ],
+      "criteria": {
+        "le": {
+          "op": "LOGICAL_OP_AND",
+          "left": {
+            "condition": {
+              "name": "state",
+              "op": "BINARY_OP_EQ",
+              "value": { "int": { "value": "0" } }
+            }
+          },
+          "right": {
+            "le": {
+              "op": "LOGICAL_OP_AND",
+              "left": {
+                "condition": {
+                  "name": "service_id",
+                  "op": "BINARY_OP_EQ",
+                  "value": { "str": { "value": "svc-0" } }
+                }
+              },
+              "right": {
+                "le": {
+                  "op": "LOGICAL_OP_AND",
+                  "left": {
+                    "condition": {
+                      "name": "duration",
+                      "op": "BINARY_OP_GE",
+                      "value": { "int": { "value": "1000" } }
+                    }
+                  },
+                  "right": {
+                    "condition": {
+                      "name": "duration",
+                      "op": "BINARY_OP_LE",
+                      "value": { "int": { "value": "2000" } }
+                    }
+                  }
+                }
+              }
+            }
+          }
+        }
+      },
+      "orderBy": { "indexRuleName": "duration", "sort": "SORT_DESC" },
+      "limit": 20
+    }
+  }
+]
diff --git a/cmd/soak-driver/main.go b/cmd/soak-driver/main.go
index 6961ab292..6b3f9a398 100644
--- a/cmd/soak-driver/main.go
+++ b/cmd/soak-driver/main.go
@@ -21,7 +21,6 @@ package main
 
 import (
 	"bufio"
-	"compress/gzip"
 	"context"
 	"encoding/json"
 	"fmt"
@@ -58,6 +57,27 @@ const (
 	soakFieldCount  = "count"
 )
 
+// Engine selects which catalog/fixture the soak-driver targets. The MEASURE
+// path is the default and is unchanged; TRACE dispatches to the trace.go
+// implementation.
+const (
+	engineMeasure = "measure"
+	engineTrace   = "trace"
+	engineStream  = "stream"
+
+	// parityWindow is the lookback applied to time-bounded trace/stream queries;
+	// the fixture spans one second per version, so a wide window covers them all.
+	parityWindow = 7 * 24 * time.Hour
+)
+
+// validateEngine returns an error for an unknown --engine value.
+func validateEngine(engine string) error {
+	if engine != engineMeasure && engine != engineTrace && engine != engineStream {
+		return fmt.Errorf("unknown engine %q: want %q, %q or %q", engine, engineMeasure, engineTrace, engineStream)
+	}
+	return nil
+}
+
 // catalogEntry holds one query template from the JSON catalog. ID is a
 // catalog-unique label used as the baseline key (the proto measure name
 // is the same for every entry, so it cannot key the baseline). Request is
@@ -111,7 +131,7 @@ func main() {
 		Use:   "soak-driver",
 		Short: "G5d soak harness driver — baseline, diff, and pprof capture",
 	}
-	root.AddCommand(newSeedFixtureCmd(), newRecordBaselineCmd(), newReplayAndDiffCmd(), newPprofGrabCmd())
+	root.AddCommand(newSeedFixtureCmd(), newRecordBaselineCmd(), newReplayAndDiffCmd(), newPprofGrabCmd(), newWriteLoadCmd())
 	if execErr := root.Execute(); execErr != nil {
 		_, _ = fmt.Fprintln(os.Stderr, execErr)
 		os.Exit(1)
@@ -175,13 +195,33 @@ func buildQueryRequest(entry catalogEntry, untilMs int64) *measurev1.QueryReques
 
 // newRecordBaselineCmd returns the record-baseline subcommand.
 func newRecordBaselineCmd() *cobra.Command {
-	var addr, catalogPath, outPath string
+	var addr, catalogPath, outPath, engine string
 	var untilMs int64
 
 	cmd := &cobra.Command{
 		Use:   "record-baseline",
-		Short: "Query measures up to --until and write a deterministic baseline JSON",
+		Short: "Query measures (or traces) up to --until and write a deterministic baseline JSON",
 		RunE: func(_ *cobra.Command, _ []string) error {
+			if engineErr := validateEngine(engine); engineErr != nil {
+				return engineErr
+			}
+			if engine == engineTrace {
+				conn, dialErr := dialInsecure(addr)
+				if dialErr != nil {
+					return dialErr
+				}
+				defer conn.Close()
+				return traceRecordBaseline(context.Background(), conn, catalogPath, outPath, untilMs, parityWindow)
+			}
+			if engine == engineStream {
+				conn, dialErr := dialInsecure(addr)
+				if dialErr != nil {
+					return dialErr
+				}
+				defer conn.Close()
+				return streamRecordBaseline(context.Background(), conn, catalogPath, outPath, untilMs, parityWindow)
+			}
+
 			entries, loadErr := loadCatalog(catalogPath)
 			if loadErr != nil {
 				return loadErr
@@ -244,6 +284,7 @@ func newRecordBaselineCmd() *cobra.Command {
 		},
 	}
 	cmd.Flags().StringVar(&addr, "addr", "localhost:17912", "BanyanDB gRPC address")
+	cmd.Flags().StringVar(&engine, "engine", engineMeasure, "engine to query: measure|trace")
 	cmd.Flags().StringVar(&catalogPath, "catalog", "", "Path to query catalog JSON")
 	cmd.Flags().Int64Var(&untilMs, "until", 0, "Upper bound for time range (unix milliseconds)")
 	cmd.Flags().StringVar(&outPath, "out", "baseline.json", "Output path for baseline JSON")
@@ -254,12 +295,32 @@ func newRecordBaselineCmd() *cobra.Command {
 
 // newReplayAndDiffCmd returns the replay-and-diff subcommand.
 func newReplayAndDiffCmd() *cobra.Command {
-	var addr, catalogPath, baselinePath, reportPath string
+	var addr, catalogPath, baselinePath, reportPath, engine string
 
 	cmd := &cobra.Command{
 		Use:   "replay-and-diff",
 		Short: "Re-run catalog queries and compare against baseline; exit non-zero on divergence",
 		RunE: func(_ *cobra.Command, _ []string) error {
+			if engineErr := validateEngine(engine); engineErr != nil {
+				return engineErr
+			}
+			if engine == engineTrace {
+				conn, dialErr := dialInsecure(addr)
+				if dialErr != nil {
+					return dialErr
+				}
+				defer conn.Close()
+				return traceReplayAndDiff(context.Background(), conn, catalogPath, baselinePath, reportPath, parityWindow)
+			}
+			if engine == engineStream {
+				conn, dialErr := dialInsecure(addr)
+				if dialErr != nil {
+					return dialErr
+				}
+				defer conn.Close()
+				return streamReplayAndDiff(context.Background(), conn, catalogPath, baselinePath, reportPath, parityWindow)
+			}
+
 			raw, readErr := os.ReadFile(baselinePath)
 			if readErr != nil {
 				return fmt.Errorf("read baseline %s: %w", baselinePath, readErr)
@@ -377,6 +438,7 @@ func newReplayAndDiffCmd() *cobra.Command {
 		},
 	}
 	cmd.Flags().StringVar(&addr, "addr", "localhost:17912", "BanyanDB gRPC address")
+	cmd.Flags().StringVar(&engine, "engine", engineMeasure, "engine to query: measure|trace")
 	cmd.Flags().StringVar(&catalogPath, "catalog", "", "Path to query catalog JSON")
 	cmd.Flags().StringVar(&baselinePath, "baseline", "baseline.json", "Path to baseline JSON produced by record-baseline")
 	cmd.Flags().StringVar(&reportPath, "report", "diff.json", "Output path for diff report JSON")
@@ -401,7 +463,7 @@ func newPprofGrabCmd() *cobra.Command {
 			goroutinePath := filepath.Join(outDir, fmt.Sprintf("goroutine-%s.txt", ts))
 
 			baseURL := fmt.Sprintf("http://%s/debug/pprof", addr)
-			if fetchErr := fetchGzip(baseURL+"/heap", heapPath); fetchErr != nil {
+			if fetchErr := fetchProfile(baseURL+"/heap", heapPath); fetchErr != nil {
 				return fmt.Errorf("fetch heap profile: %w", fetchErr)
 			}
 
@@ -441,13 +503,37 @@ func newPprofGrabCmd() *cobra.Command {
 // --until to record-baseline so the time-bounded queries hit only this
 // fixture.
 func newSeedFixtureCmd() *cobra.Command {
-	var addr string
-	var rows int
+	var addr, engine string
+	var rows, traces, spans, series, elementsPerSeries int
 
 	cmd := &cobra.Command{
 		Use:   "seed-fixture",
-		Short: "Create a deterministic group/measure and write N rows",
+		Short: "Create a deterministic group/measure (or trace/stream) and write fixture data",
 		RunE: func(_ *cobra.Command, _ []string) error {
+			if engineErr := validateEngine(engine); engineErr != nil {
+				return engineErr
+			}
+			if engine == engineTrace {
+				conn, dialErr := dialInsecure(addr)
+				if dialErr != nil {
+					return dialErr
+				}
+				defer conn.Close()
+				ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+				defer cancel()
+				return traceSeedFixture(ctx, conn, traces, spans)
+			}
+			if engine == engineStream {
+				conn, dialErr := dialInsecure(addr)
+				if dialErr != nil {
+					return dialErr
+				}
+				defer conn.Close()
+				ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
+				defer cancel()
+				return streamSeedFixture(ctx, conn, series, elementsPerSeries)
+			}
+
 			conn, dialErr := dialInsecure(addr)
 			if dialErr != nil {
 				return dialErr
@@ -616,14 +702,67 @@ func newSeedFixtureCmd() *cobra.Command {
 		},
 	}
 	cmd.Flags().StringVar(&addr, "addr", "localhost:17912", "BanyanDB gRPC address")
-	cmd.Flags().IntVar(&rows, "rows", 1000, "number of data points to write")
+	cmd.Flags().StringVar(&engine, "engine", engineMeasure, "engine to seed: measure|trace|stream")
+	cmd.Flags().IntVar(&rows, "rows", 1000, "number of measure data points to write")
+	cmd.Flags().IntVar(&traces, "traces", traceFixtureTraces, "number of traces to write (trace engine)")
+	cmd.Flags().IntVar(&spans, "spans", traceFixtureSpans, "number of spans per trace (trace engine)")
+	cmd.Flags().IntVar(&series, "series", streamFixtureSeries, "number of series to write (stream engine)")
+	cmd.Flags().IntVar(&elementsPerSeries, "elements", streamFixtureElementsPerSeri, "elements per series (stream engine)")
+	return cmd
+}
+
+// newWriteLoadCmd returns the write-load subcommand. It is trace-only:
+// continuous deterministic writes into the rolling load group, outside the
+// parity window, rate-capped at --rps for --duration.
+func newWriteLoadCmd() *cobra.Command {
+	var addr, engine string
+	var traces, spans, rps int
+	var duration time.Duration
+
+	cmd := &cobra.Command{
+		Use:   "write-load",
+		Short: "Continuously write deterministic trace load outside the parity window (trace only)",
+		RunE: func(_ *cobra.Command, _ []string) error {
+			if engineErr := validateEngine(engine); engineErr != nil {
+				return engineErr
+			}
+			if engine != engineTrace && engine != engineStream {
+				return fmt.Errorf("write-load is only supported for engine %q or %q", engineTrace, engineStream)
+			}
+			conn, dialErr := dialInsecure(addr)
+			if dialErr != nil {
+				return dialErr
+			}
+			defer conn.Close()
+
+			ctx, cancel := context.WithTimeout(context.Background(), duration+time.Minute)
+			defer cancel()
+			if engine == engineStream {
+				written, loadErr := streamWriteLoad(ctx, conn, traces, spans, rps, duration)
+				fmt.Printf("[write-load] wrote %d elements over %s\n", written, duration)
+				return loadErr
+			}
+			rowsWritten, loadErr := traceWriteLoad(ctx, conn, traces, spans, rps, duration)
+			fmt.Printf("[write-load] wrote %d spans over %s\n", rowsWritten, duration)
+			if loadErr != nil {
+				return loadErr
+			}
+			return nil
+		},
+	}
+	cmd.Flags().StringVar(&addr, "addr", "localhost:17912", "BanyanDB gRPC address")
+	cmd.Flags().StringVar(&engine, "engine", engineTrace, "engine to write load for: trace")
+	cmd.Flags().IntVar(&traces, "traces", traceFixtureTraces, "number of traces per sweep")
+	cmd.Flags().IntVar(&spans, "spans", traceFixtureSpans, "number of spans per trace")
+	cmd.Flags().IntVar(&rps, "rps", 1000, "rate cap in spans per second")
+	cmd.Flags().DurationVar(&duration, "duration", 30*time.Second, "how long to write load")
 	return cmd
 }
 
-// fetchGzip downloads url and writes the body as a gzip file at dst.
+// fetchProfile downloads url and writes the body as a gzip file at dst.
 // The pprof heap endpoint already returns a gzip-compressed protobuf, so we
 // just pipe the bytes through.
-func fetchGzip(url, dst string) error {
+func fetchProfile(url, dst string) error {
 	body, fetchErr := fetchBytes(url)
 	if fetchErr != nil {
 		return fetchErr
@@ -634,12 +773,15 @@ func fetchGzip(url, dst string) error {
 	}
 	defer f.Close()
 
-	// The pprof heap endpoint returns raw gzip; write it directly.
-	gw := gzip.NewWriter(f)
-	if _, writeErr := gw.Write(body); writeErr != nil {
-		return fmt.Errorf("gzip write: %w", writeErr)
+	// The pprof heap endpoint already returns gzipped protobuf, so write the body
+	// through UNCHANGED. Compressing it again produced a doubly-gzipped file that
+	// `go tool pprof` rejects with "unrecognized profile format" (it gunzips once
+	// and finds gzip, not protobuf) — silently costing every measure/trace/stream
+	// soak its heap evidence until someone gunzipped the artifact by hand.
+	if _, writeErr := f.Write(body); writeErr != nil {
+		return fmt.Errorf("write %s: %w", dst, writeErr)
 	}
-	return gw.Close()
+	return nil
 }
 
 // fetchBytes issues a GET request and returns the response body.
diff --git a/cmd/soak-driver/stream.go b/cmd/soak-driver/stream.go
new file mode 100644
index 000000000..92ce75b16
--- /dev/null
+++ b/cmd/soak-driver/stream.go
@@ -0,0 +1,688 @@
+// 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.
+
+package main
+
+import (
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"sort"
+	"strings"
+	"time"
+
+	"google.golang.org/grpc"
+	"google.golang.org/protobuf/encoding/protojson"
+	"google.golang.org/protobuf/proto"
+	"google.golang.org/protobuf/types/known/timestamppb"
+
+	commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+)
+
+// Stream soak fixture constants. The parity fixture group keeps its data for the
+// run (long TTL); the load group rolls a short TTL so background write-load
+// traffic self-expires. Mirrors the trace soak layout.
+const (
+	streamFixtureGroup = "bench-stream-fixture"
+	streamLoadGroup    = "bench-stream-load"
+	streamName         = "sw"
+
+	streamFixtureSeries          = 8
+	streamFixtureElementsPerSeri = 40
+
+	streamTagFamily     = "searchable"
+	streamTagServiceID  = "service_id"
+	streamTagState      = "state"
+	streamTagDuration   = "duration"
+	streamIndexDuration = "duration"
+
+	// streamIndexDurationID is the explicit IndexRule id. It is the field key the
+	// index-order query resolves against, so it must be non-zero. Each soak group
+	// is dedicated to this fixture, so a fixed id is safe.
+	streamIndexDurationID = 1
+
+	// streamSchemaSettle is how long seed-fixture waits after creating the stream
+	// schema before writing, so the data node's schema watch has applied the
+	// duration index rule + binding. Elements written before the rule lands never
+	// get tree-index entries, which no amount of later waiting repairs.
+	streamSchemaSettle = 5 * time.Second
+
+	// streamVisibleTimeout caps the post-write visibility poll. It covers the
+	// async data flush AND the (slower) local element-index flush that the
+	// index-order query depends on.
+	streamVisibleTimeout = 90 * time.Second
+
+	// streamSvcZeroFraction is the share of series assigned to svc-0; the
+	// catalog's svc-0 filters select exactly this set, so it stays in lock-step
+	// with the generator.
+	streamSvcZeroFraction = 0.5
+)
+
+// streamCatalogEntry holds one query template from the stream JSON catalog.
+type streamCatalogEntry struct {
+	Request *streamv1.QueryRequest
+	ID      string
+}
+
+// streamBaselineRecord is persisted after stream record-baseline runs. Elements
+// holds proto-JSON encoded streamv1.Element messages.
+type streamBaselineRecord struct {
+	QueryName string            `json:"query_name"`
+	Elements  []json.RawMessage `json:"elements"`
+	Groups    []string          `json:"groups"`
+	UntilMs   int64             `json:"until_ms"`
+	Ordered   bool              `json:"ordered"`
+}
+
+// loadStreamCatalog reads the stream JSON catalog ({id, request} entries) and
+// decodes each request via protojson so proto oneofs/enums round-trip.
+func loadStreamCatalog(path string) ([]streamCatalogEntry, error) {
+	raw, readErr := os.ReadFile(path)
+	if readErr != nil {
+		return nil, fmt.Errorf("read stream catalog %s: %w", path, readErr)
+	}
+	var rawEntries []rawCatalogEntry
+	if unmarshalErr := json.Unmarshal(raw, &rawEntries); unmarshalErr != nil {
+		return nil, fmt.Errorf("unmarshal stream catalog array: %w", unmarshalErr)
+	}
+	entries := make([]streamCatalogEntry, 0, len(rawEntries))
+	for idx, rawEntry := range rawEntries {
+		if rawEntry.ID == "" {
+			return nil, fmt.Errorf("stream catalog entry %d: missing id", idx)
+		}
+		req := new(streamv1.QueryRequest)
+		if protoErr := protojson.Unmarshal(rawEntry.Request, req); protoErr != nil {
+			return nil, fmt.Errorf("unmarshal stream catalog entry %q: %w", rawEntry.ID, protoErr)
+		}
+		entries = append(entries, streamCatalogEntry{ID: rawEntry.ID, Request: req})
+	}
+	return entries, nil
+}
+
+// buildStreamQueryRequest injects a [until-window, until] TimeRange into a cloned
+// catalog request. The pinned Limit and OrderBy are preserved verbatim.
+func buildStreamQueryRequest(entry streamCatalogEntry, untilMs int64, window time.Duration) *streamv1.QueryRequest {
+	untilTime := time.UnixMilli(untilMs)
+	beginTime := untilTime.Add(-window)
+	req, _ := proto.Clone(entry.Request).(*streamv1.QueryRequest)
+	req.TimeRange = &modelv1.TimeRange{
+		Begin: timestamppb.New(beginTime),
+		End:   timestamppb.New(untilTime),
+	}
+	return req
+}
+
+// streamCatalogEntryOrdered reports whether the catalog query pins a result order.
+func streamCatalogEntryOrdered(entry streamCatalogEntry) bool {
+	return entry.Request.GetOrderBy().GetIndexRuleName() != ""
+}
+
+// streamStrTagValue wraps a string in a model TagValue.
+func streamStrTagValue(value string) *modelv1.TagValue {
+	return &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: value}}}
+}
+
+// streamIntTagValue wraps an int64 in a model TagValue.
+func streamIntTagValue(value int64) *modelv1.TagValue {
+	return &modelv1.TagValue{Value: &modelv1.TagValue_Int{Int: &modelv1.Int{Value: value}}}
+}
+
+// streamServiceIDForIndex returns the per-series service_id. The first
+// streamSvcZeroFraction of series are svc-0 so the svc-0 catalog filters select
+// an exact, reproducible fraction.
+func streamServiceIDForIndex(seriesIdx, seriesCount int) string {
+	svcZeroCount := int(float64(seriesCount) * streamSvcZeroFraction)
+	if seriesIdx < svcZeroCount {
+		return "svc-0"
+	}
+	return fmt.Sprintf("svc-%d", seriesIdx)
+}
+
+// streamAlreadyExists reports whether err is an idempotent "already exists" error.
+func streamAlreadyExists(err error) bool {
+	return strings.Contains(err.Error(), "already exist")
+}
+
+// streamCreateGroup creates a CATALOG_STREAM group idempotently.
+func streamCreateGroup(ctx context.Context, client databasev1.GroupRegistryServiceClient, name string, ttlDays uint32) error {
+	_, createErr := client.Create(ctx, &databasev1.GroupRegistryServiceCreateRequest{
+		Group: &commonv1.Group{
+			Metadata: &commonv1.Metadata{Name: name},
+			Catalog:  commonv1.Catalog_CATALOG_STREAM,
+			ResourceOpts: &commonv1.ResourceOpts{
+				ShardNum: 2,
+				SegmentInterval: &commonv1.IntervalRule{
+					Unit: commonv1.IntervalRule_UNIT_DAY,
+					Num:  1,
+				},
+				Ttl: &commonv1.IntervalRule{
+					Unit: commonv1.IntervalRule_UNIT_DAY,
+					Num:  ttlDays,
+				},
+			},
+		},
+	})
+	if createErr != nil && !streamAlreadyExists(createErr) {
+		return fmt.Errorf("create stream group %s: %w", name, createErr)
+	}
+	return nil
+}
+
+// streamCreateSchema creates the Stream resource, its duration index rule, and
+// binding for one group, idempotently.
+func streamCreateSchema(
+	ctx context.Context,
+	streamClient databasev1.StreamRegistryServiceClient,
+	indexRuleClient databasev1.IndexRuleRegistryServiceClient,
+	bindingClient databasev1.IndexRuleBindingRegistryServiceClient,
+	group string,
+) error {
+	stream := &databasev1.Stream{
+		Metadata: &commonv1.Metadata{Name: streamName, Group: group},
+		Entity:   &databasev1.Entity{TagNames: []string{streamTagServiceID}},
+		TagFamilies: []*databasev1.TagFamilySpec{{
+			Name: streamTagFamily,
+			Tags: []*databasev1.TagSpec{
+				{Name: streamTagServiceID, Type: databasev1.TagType_TAG_TYPE_STRING},
+				{Name: streamTagState, Type: databasev1.TagType_TAG_TYPE_INT},
+				{Name: streamTagDuration, Type: databasev1.TagType_TAG_TYPE_INT},
+			},
+		}},
+	}
+	if _, createErr := streamClient.Create(ctx, &databasev1.StreamRegistryServiceCreateRequest{Stream: stream}); createErr != nil && !streamAlreadyExists(createErr) {
+		return fmt.Errorf("create stream resource in %s: %w", group, createErr)
+	}
+
+	// Type and Id both matter for an index-ORDER (sortable) stream index:
+	//   - TYPE_INVERTED is the sortable local element index the stream index-order
+	//     path queries via Index().Sort(). No stream index rule uses TYPE_TREE (see
+	//     pkg/test/stream/testdata/index_rules) — a TYPE_TREE rule yields an index
+	//     the sort path never populates, so the ordered query returns 0 rows.
+	//   - Metadata.Id is the numeric IndexRuleID used as the index field key
+	//     (query_by_idx.go builds index.FieldKey{IndexRuleID: rule.Metadata.Id}).
+	//     Leaving it unset means id=0 and the ordered query finds no field.
+	rule := &databasev1.IndexRule{
+		Metadata: &commonv1.Metadata{Id: streamIndexDurationID, Name: streamIndexDuration, Group: group},
+		Tags:     []string{streamTagDuration},
+		Type:     databasev1.IndexRule_TYPE_INVERTED,
+	}
+	if _, createErr := indexRuleClient.Create(ctx, &databasev1.IndexRuleRegistryServiceCreateRequest{IndexRule: rule}); createErr != nil && !streamAlreadyExists(createErr) {
+		return fmt.Errorf("create stream index rule %s in %s: %w", rule.GetMetadata().GetName(), group, createErr)
+	}
+
+	binding := &databasev1.IndexRuleBinding{
+		Metadata: &commonv1.Metadata{Name: "sw-index-rule-binding", Group: group},
+		Rules:    []string{streamIndexDuration},
+		Subject:  &databasev1.Subject{Catalog: commonv1.Catalog_CATALOG_STREAM, Name: streamName},
+		BeginAt:  timestamppb.New(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)),
+		ExpireAt: timestamppb.New(time.Date(2121, 1, 1, 0, 0, 0, 0, time.UTC)),
+	}
+	if _, createErr := bindingClient.Create(ctx, &databasev1.IndexRuleBindingRegistryServiceCreateRequest{IndexRuleBinding: binding}); createErr != nil && !streamAlreadyExists(createErr) {
+		return fmt.Errorf("create stream index rule binding in %s: %w", group, createErr)
+	}
+	return nil
+}
+
+// streamFixtureBaseTime anchors deterministic element timestamps to recent
+// wall-clock time so they fall inside the group's TTL window.
+func streamFixtureBaseTime(totalElements int) time.Time {
+	const marginSec = 60
+	return time.Now().UTC().Truncate(time.Millisecond).Add(-time.Duration(totalElements+marginSec) * time.Second)
+}
+
+// streamSeedFixture creates the two stream groups (long-TTL parity fixture +
+// short-TTL rolling load), the "sw" Stream, the duration index rule and binding,
+// then writes the deterministic fixture into the parity group and prints T1_MS.
+func streamSeedFixture(ctx context.Context, conn *grpc.ClientConn, series, elementsPerSeries int) error {
+	if series <= 0 {
+		series = streamFixtureSeries
+	}
+	if elementsPerSeries <= 0 {
+		elementsPerSeries = streamFixtureElementsPerSeri
+	}
+	groupClient := databasev1.NewGroupRegistryServiceClient(conn)
+	if groupErr := streamCreateGroup(ctx, groupClient, streamFixtureGroup, 30); groupErr != nil {
+		return groupErr
+	}
+	if groupErr := streamCreateGroup(ctx, groupClient, streamLoadGroup, 1); groupErr != nil {
+		return groupErr
+	}
+
+	streamClient := databasev1.NewStreamRegistryServiceClient(conn)
+	indexRuleClient := databasev1.NewIndexRuleRegistryServiceClient(conn)
+	bindingClient := databasev1.NewIndexRuleBindingRegistryServiceClient(conn)
+	for _, group := range []string{streamFixtureGroup, streamLoadGroup} {
+		if schemaErr := streamCreateSchema(ctx, streamClient, indexRuleClient, bindingClient, group); schemaErr != nil {
+			return schemaErr
+		}
+	}
+
+	// The data node applies index rules through its schema watch. Elements written
+	// BEFORE the duration rule + binding land carry no tree-index entries, which is
+	// permanent for those elements — the index-order catalog query would then return
+	// 0 rows forever, no matter how long the baseline waits. Settle before writing.
+	fmt.Printf("[stream seed-fixture] waiting %s for the index rule + binding to reach the data node...\n", streamSchemaSettle)
+	select {
+	case <-time.After(streamSchemaSettle):
+	case <-ctx.Done():
+		return ctx.Err()
+	}
+
+	base := streamFixtureBaseTime(series * elementsPerSeries)
+	highestMs, writeErr := streamWriteFixture(ctx, conn, streamFixtureGroup, series, elementsPerSeries, base, 0)
+	if writeErr != nil {
+		return writeErr
+	}
+	fmt.Printf("[stream seed-fixture] wrote %d series x %d elements to %s/%s\n", series, elementsPerSeries, streamFixtureGroup, streamName)
+
+	// Poll until queryable (stream flush is async ~5s). Query svc-0 series over
+	// the seed window until at least one element is visible.
+	if visErr := streamWaitVisible(ctx, conn, base, highestMs); visErr != nil {
+		return visErr
+	}
+	fmt.Printf("T1_MS=%d\n", highestMs)
+	fmt.Printf("%d\n", highestMs)
+	return nil
+}
+
+// streamElementID returns the deterministic element id for (series, element).
+func streamElementID(serviceID string, elementIdx int) string {
+	return fmt.Sprintf("%s-%06d", serviceID, elementIdx)
+}
+
+// streamWriteFixture writes series*elementsPerSeries deterministic elements into
+// group via the streaming StreamService.Write RPC, checking every response
+// status. Returns the highest element timestamp in ms.
+func streamWriteFixture(ctx context.Context, conn *grpc.ClientConn, group string, series, elementsPerSeries int, base time.Time, versionBase int) (int64, error) {
+	client := streamv1.NewStreamServiceClient(conn)
+	stream, streamErr := client.Write(ctx)
+	if streamErr != nil {
+		return 0, fmt.Errorf("open stream write: %w", streamErr)
+	}
+
+	recvErrCh := make(chan error, 1)
+	go func() {
+		var firstBad string
+		bad := 0
+		for {
+			resp, recvErr := stream.Recv()
+			if errors.Is(recvErr, io.EOF) {
+				if bad > 0 {
+					recvErrCh <- fmt.Errorf("stream write rejected %d elements (first status: %q)", bad, firstBad)
+					return
+				}
+				recvErrCh <- nil
+				return
+			}
+			if recvErr != nil {
+				recvErrCh <- fmt.Errorf("receive stream write response: %w", recvErr)
+				return
+			}
+			if resp.GetStatus() != modelv1.Status_STATUS_SUCCEED.String() {
+				bad++
+				if firstBad == "" {
+					firstBad = resp.GetStatus()
+				}
+			}
+		}
+	}()
+
+	metadata := &commonv1.Metadata{Name: streamName, Group: group}
+	requestMetadata := metadata
+	var highestMs int64
+	globalIdx := 0
+	for seriesIdx := 0; seriesIdx < series; seriesIdx++ {
+		serviceID := streamServiceIDForIndex(seriesIdx, series)
+		for elementIdx := 0; elementIdx < elementsPerSeries; elementIdx++ {
+			version := versionBase + globalIdx + 1
+			ts := base.Add(time.Duration(version) * time.Second)
+			tsMs := ts.UnixMilli()
+			if tsMs > highestMs {
+				highestMs = tsMs
+			}
+			state := int64(0)
+			if globalIdx%20 == 0 {
+				state = 1
+			}
+			duration := int64(1000 + seriesIdx*10 + elementIdx)
+			req := &streamv1.WriteRequest{
+				Metadata: requestMetadata,
+				Element: &streamv1.ElementValue{
+					ElementId: streamElementID(serviceID, version),
+					Timestamp: timestamppb.New(ts),
+					TagFamilies: []*modelv1.TagFamilyForWrite{{
+						Tags: []*modelv1.TagValue{
+							streamStrTagValue(serviceID),
+							streamIntTagValue(state),
+							streamIntTagValue(duration),
+						},
+					}},
+				},
+				MessageId: uint64(time.Now().UnixNano()) + uint64(globalIdx),
+			}
+			if sendErr := stream.Send(req); sendErr != nil {
+				return 0, fmt.Errorf("send stream write: %w", sendErr)
+			}
+			requestMetadata = nil
+			globalIdx++
+		}
+	}
+	if closeErr := stream.CloseSend(); closeErr != nil {
+		return 0, fmt.Errorf("close stream write: %w", closeErr)
+	}
+	if recvErr := <-recvErrCh; recvErr != nil {
+		return 0, recvErr
+	}
+	return highestMs, nil
+}
+
+// streamWaitVisible polls svc-0 until the seeded elements are queryable through
+// BOTH shapes the catalog uses: a plain time-range query (data flushed) and an
+// index-ORDER query keyed on the duration tree index (local element index
+// flushed AND the index rule applied). Gating on the plain query alone is not
+// enough: data becomes visible before the tree index does, so record-baseline
+// would then see 0 rows for the index-order query and abort the run.
+func streamWaitVisible(ctx context.Context, conn *grpc.ClientConn, base time.Time, highestMs int64) error {
+	client := streamv1.NewStreamServiceClient(conn)
+	timeRange := &modelv1.TimeRange{
+		Begin: timestamppb.New(base.Add(-time.Second)),
+		End:   timestamppb.New(time.UnixMilli(highestMs).Add(time.Second)),
+	}
+	plainReq := &streamv1.QueryRequest{
+		Name:       streamName,
+		Groups:     []string{streamFixtureGroup},
+		TimeRange:  timeRange,
+		Projection: streamProjection(),
+		Limit:      100,
+	}
+	orderedReq := &streamv1.QueryRequest{
+		Name:       streamName,
+		Groups:     []string{streamFixtureGroup},
+		TimeRange:  timeRange,
+		Projection: streamProjection(),
+		Limit:      100,
+		OrderBy: &modelv1.QueryOrder{
+			IndexRuleName: streamIndexDuration,
+			Sort:          modelv1.Sort_SORT_DESC,
+		},
+	}
+	count := func(req *streamv1.QueryRequest) int {
+		qctx, qcancel := context.WithTimeout(ctx, 5*time.Second)
+		defer qcancel()
+		resp, qerr := client.Query(qctx, req)
+		if qerr != nil || resp == nil {
+			return 0
+		}
+		return len(resp.GetElements())
+	}
+	var plainSeen, orderedSeen int
+	deadline := time.Now().Add(streamVisibleTimeout)
+	for time.Now().Before(deadline) {
+		plainSeen, orderedSeen = count(plainReq), count(orderedReq)
+		if plainSeen > 0 && orderedSeen > 0 {
+			fmt.Printf("[stream seed-fixture] %d elements visible (plain), %d visible via the %s index order\n",
+				plainSeen, orderedSeen, streamIndexDuration)
+			return nil
+		}
+		time.Sleep(2 * time.Second)
+	}
+	if plainSeen > 0 {
+		return fmt.Errorf("stream seed-fixture: data is visible (%d elements) but the %s index-order query still returns 0 after %s — "+
+			"the element (tree) index did not become queryable; the index rule/binding may not have been applied before the writes landed",
+			plainSeen, streamIndexDuration, streamVisibleTimeout)
+	}
+	return fmt.Errorf("stream seed-fixture: no elements visible after %s — flush/index lag", streamVisibleTimeout)
+}
+
+// streamProjection returns the searchable tag projection every catalog query and
+// the visibility poll share.
+func streamProjection() *modelv1.TagProjection {
+	return &modelv1.TagProjection{
+		TagFamilies: []*modelv1.TagProjection_TagFamily{{
+			Name: streamTagFamily,
+			Tags: []string{streamTagServiceID, streamTagState, streamTagDuration},
+		}},
+	}
+}
+
+// streamRecordBaseline runs the catalog over [T1-window, T1], persists the
+// elements as proto-JSON, and exits non-zero if any catalog query is empty.
+func streamRecordBaseline(ctx context.Context, conn *grpc.ClientConn, catalogPath, outPath string, untilMs int64, window time.Duration) error {
+	entries, loadErr := loadStreamCatalog(catalogPath)
+	if loadErr != nil {
+		return loadErr
+	}
+	client := streamv1.NewStreamServiceClient(conn)
+	records := make([]streamBaselineRecord, 0, len(entries))
+	var emptyQueries []string
+	for _, entry := range entries {
+		req := buildStreamQueryRequest(entry, untilMs, window)
+		queryName := entry.ID
+		queryCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+		resp, queryErr := client.Query(queryCtx, req)
+		cancel()
+		if queryErr != nil {
+			return fmt.Errorf("record-baseline %s: query failed: %w", queryName, queryErr)
+		}
+		rec := streamBaselineRecord{
+			QueryName: queryName,
+			Groups:    entry.Request.GetGroups(),
+			UntilMs:   untilMs,
+			Ordered:   streamCatalogEntryOrdered(entry),
+		}
+		for _, element := range resp.GetElements() {
+			rawElement, marshalErr := protojson.Marshal(element)
+			if marshalErr != nil {
+				return fmt.Errorf("marshal element for %s: %w", queryName, marshalErr)
+			}
+			rec.Elements = append(rec.Elements, json.RawMessage(rawElement))
+		}
+		records = append(records, rec)
+		if len(rec.Elements) == 0 {
+			emptyQueries = append(emptyQueries, queryName)
+		}
+		fmt.Printf("[stream record-baseline] %s: %d elements\n", queryName, len(rec.Elements))
+	}
+
+	out, createErr := os.Create(outPath)
+	if createErr != nil {
+		return fmt.Errorf("create output %s: %w", outPath, createErr)
+	}
+	defer out.Close()
+	enc := json.NewEncoder(out)
+	enc.SetIndent("", "  ")
+	if encErr := enc.Encode(records); encErr != nil {
+		return fmt.Errorf("encode stream baseline: %w", encErr)
+	}
+	fmt.Printf("[stream record-baseline] written to %s\n", outPath)
+	if len(emptyQueries) > 0 {
+		return fmt.Errorf("record-baseline: %d catalog queries returned no elements: %s", len(emptyQueries), strings.Join(emptyQueries, ", "))
+	}
+	return nil
+}
+
+// streamReplayAndDiff re-runs the catalog against the baseline and writes a
+// diffReport (reusing the shared shape so soak-monitor.sh grep matches). Returns
+// a non-zero error on any divergence.
+func streamReplayAndDiff(ctx context.Context, conn *grpc.ClientConn, catalogPath, baselinePath, reportPath string, window time.Duration) error {
+	raw, readErr := os.ReadFile(baselinePath)
+	if readErr != nil {
+		return fmt.Errorf("read stream baseline %s: %w", baselinePath, readErr)
+	}
+	var records []streamBaselineRecord
+	if unmarshalErr := json.Unmarshal(raw, &records); unmarshalErr != nil {
+		return fmt.Errorf("unmarshal stream baseline: %w", unmarshalErr)
+	}
+	entries, loadErr := loadStreamCatalog(catalogPath)
+	if loadErr != nil {
+		return loadErr
+	}
+	client := streamv1.NewStreamServiceClient(conn)
+	report := diffReport{RunAt: time.Now().UTC().Format(time.RFC3339), Pass: true}
+	baselineMap := make(map[string]streamBaselineRecord, len(records))
+	for _, rec := range records {
+		baselineMap[rec.QueryName] = rec
+	}
+
+	for _, entry := range entries {
+		queryName := entry.ID
+		rec, ok := baselineMap[queryName]
+		if !ok {
+			fmt.Printf("[stream replay-and-diff] %s: SKIP (no baseline)\n", queryName)
+			continue
+		}
+		req := buildStreamQueryRequest(entry, rec.UntilMs, window)
+		queryCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+		resp, queryErr := client.Query(queryCtx, req)
+		cancel()
+		if queryErr != nil {
+			report.Divergences = append(report.Divergences, divergence{QueryName: queryName})
+			report.Pass = false
+			fmt.Printf("[stream replay-and-diff] %s: FAIL (%v)\n", queryName, queryErr)
+			continue
+		}
+		report.QueriesRun++
+
+		baselineElements, parseErr := decodeBaselineElements(rec.Elements, queryName)
+		if parseErr != nil {
+			return parseErr
+		}
+		div, matched := compareStreamResults(queryName, baselineElements, resp.GetElements(), rec.Ordered)
+		if !matched {
+			report.Divergences = append(report.Divergences, div)
+			report.Pass = false
+		}
+	}
+
+	outFile, createErr := os.Create(reportPath)
+	if createErr != nil {
+		return fmt.Errorf("create stream report %s: %w", reportPath, createErr)
+	}
+	defer outFile.Close()
+	enc := json.NewEncoder(outFile)
+	enc.SetIndent("", "  ")
+	if encErr := enc.Encode(report); encErr != nil {
+		return fmt.Errorf("encode stream report: %w", encErr)
+	}
+	fmt.Printf("[stream replay-and-diff] %d queries run, %d divergences — %s\n",
+		report.QueriesRun, len(report.Divergences), map[bool]string{true: "PASS", false: "FAIL"}[report.Pass])
+	if !report.Pass {
+		return fmt.Errorf("parity check failed: %d divergences found", len(report.Divergences))
+	}
+	return nil
+}
+
+// decodeBaselineElements decodes the proto-JSON element blobs from a baseline record.
+func decodeBaselineElements(raws []json.RawMessage, queryName string) ([]*streamv1.Element, error) {
+	elements := make([]*streamv1.Element, 0, len(raws))
+	for idx, raw := range raws {
+		element := new(streamv1.Element)
+		if parseErr := protojson.Unmarshal(raw, element); parseErr != nil {
+			return nil, fmt.Errorf("unmarshal baseline element %d for %s: %w", idx, queryName, parseErr)
+		}
+		elements = append(elements, element)
+	}
+	return elements, nil
+}
+
+// compareStreamResults diffs baseline vs replay elements. Unordered queries sort
+// by element_id before comparison; ordered queries preserve position. Returns a
+// divergence and false on the first mismatch.
+func compareStreamResults(queryName string, baseline, replay []*streamv1.Element, ordered bool) (divergence, bool) {
+	div := divergence{QueryName: queryName, BaselineLen: len(baseline), ReplayLen: len(replay)}
+	if len(baseline) != len(replay) {
+		return div, false
+	}
+	baselineNorm := normalizeElements(baseline, ordered)
+	replayNorm := normalizeElements(replay, ordered)
+	matched := true
+	for idx := range baselineNorm {
+		if !proto.Equal(baselineNorm[idx], replayNorm[idx]) {
+			matched = false
+			if len(div.FirstDiffs) < 3 {
+				div.FirstDiffs = append(div.FirstDiffs, pointDiff{
+					Index:    idx,
+					Baseline: baselineNorm[idx].String(),
+					Replay:   replayNorm[idx].String(),
+				})
+			}
+		}
+	}
+	return div, matched
+}
+
+// normalizeElements returns clones; when not ordered, sorts by element_id so set
+// comparison is stable.
+func normalizeElements(elements []*streamv1.Element, ordered bool) []*streamv1.Element {
+	clones := make([]*streamv1.Element, 0, len(elements))
+	for _, element := range elements {
+		clone, _ := proto.Clone(element).(*streamv1.Element)
+		clones = append(clones, clone)
+	}
+	if !ordered {
+		sort.Slice(clones, func(left, right int) bool {
+			return clones[left].GetElementId() < clones[right].GetElementId()
+		})
+	}
+	return clones
+}
+
+// streamWriteLoad runs continuous deterministic writes into the rolling load
+// group, outside the parity window, rate-capped at rps. Returns elements written.
+func streamWriteLoad(ctx context.Context, conn *grpc.ClientConn, series, elementsPerSeries, rps int, duration time.Duration) (int, error) {
+	if series <= 0 {
+		series = streamFixtureSeries
+	}
+	if elementsPerSeries <= 0 {
+		elementsPerSeries = streamFixtureElementsPerSeri
+	}
+	if rps <= 0 {
+		rps = 1000
+	}
+	perSweep := series * elementsPerSeries
+	base := streamFixtureBaseTime(perSweep)
+	deadline := time.Now().Add(duration)
+	total := 0
+	versionBase := 0
+	interval := time.Second / time.Duration(rps)
+	for time.Now().Before(deadline) {
+		select {
+		case <-ctx.Done():
+			return total, ctx.Err()
+		default:
+		}
+		sweepStart := time.Now()
+		if _, writeErr := streamWriteFixture(ctx, conn, streamLoadGroup, series, elementsPerSeries, base, versionBase); writeErr != nil {
+			return total, writeErr
+		}
+		total += perSweep
+		versionBase += perSweep
+		elapsed := time.Since(sweepStart)
+		budget := time.Duration(perSweep) * interval
+		if elapsed < budget {
+			time.Sleep(budget - elapsed)
+		}
+		fmt.Printf("[stream write-load] sweep done: %d elements total\n", total)
+	}
+	return total, nil
+}
diff --git a/cmd/soak-driver/stream_test.go b/cmd/soak-driver/stream_test.go
new file mode 100644
index 000000000..be46b8a7d
--- /dev/null
+++ b/cmd/soak-driver/stream_test.go
@@ -0,0 +1,153 @@
+// 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.
+
+package main
+
+import (
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+)
+
+const streamCatalogTestPath = "catalog/stream.json"
+
+func TestLoadStreamCatalogParsesAllShapes(t *testing.T) {
+	entries, loadErr := loadStreamCatalog(streamCatalogTestPath)
+	require.NoError(t, loadErr)
+	require.Len(t, entries, 4)
+	wantIDs := []string{"stream_by_time_svc0", "stream_newest_svc0", "stream_by_duration_svc0", "stream_filter_state_svc0"}
+	gotIDs := make([]string, 0, len(entries))
+	for _, entry := range entries {
+		gotIDs = append(gotIDs, entry.ID)
+		assert.Equal(t, streamName, entry.Request.GetName(), "entry %s name", entry.ID)
+		assert.Equal(t, []string{streamFixtureGroup}, entry.Request.GetGroups(), "entry %s groups", entry.ID)
+		assert.NotEmpty(t, entry.Request.GetProjection().GetTagFamilies(), "entry %s projection", entry.ID)
+		assert.NotZero(t, entry.Request.GetLimit(), "entry %s must pin a limit", entry.ID)
+	}
+	assert.ElementsMatch(t, wantIDs, gotIDs)
+}
+
+func TestStreamCatalogByDurationIsIndexOrdered(t *testing.T) {
+	entries, loadErr := loadStreamCatalog(streamCatalogTestPath)
+	require.NoError(t, loadErr)
+	var entry streamCatalogEntry
+	for _, e := range entries {
+		if e.ID == "stream_by_duration_svc0" {
+			entry = e
+		}
+	}
+	require.NotEmpty(t, entry.ID)
+	order := entry.Request.GetOrderBy()
+	require.NotNil(t, order)
+	assert.Equal(t, streamIndexDuration, order.GetIndexRuleName())
+	assert.Equal(t, modelv1.Sort_SORT_DESC, order.GetSort())
+	assert.True(t, streamCatalogEntryOrdered(entry), "index-order query must diff position-by-position")
+}
+
+func TestStreamCatalogFilterStateIsAnd(t *testing.T) {
+	entries, loadErr := loadStreamCatalog(streamCatalogTestPath)
+	require.NoError(t, loadErr)
+	var entry streamCatalogEntry
+	for _, e := range entries {
+		if e.ID == "stream_filter_state_svc0" {
+			entry = e
+		}
+	}
+	require.NotEmpty(t, entry.ID)
+	le := entry.Request.GetCriteria().GetLe()
+	require.NotNil(t, le)
+	assert.Equal(t, modelv1.LogicalExpression_LOGICAL_OP_AND, le.GetOp())
+	assert.Equal(t, streamTagServiceID, le.GetLeft().GetCondition().GetName())
+	assert.Equal(t, "svc-0", le.GetLeft().GetCondition().GetValue().GetStr().GetValue())
+	assert.Equal(t, streamTagState, le.GetRight().GetCondition().GetName())
+	assert.Equal(t, int64(0), le.GetRight().GetCondition().GetValue().GetInt().GetValue())
+	assert.False(t, streamCatalogEntryOrdered(entry))
+}
+
+func TestBuildStreamQueryRequestInjectsTimeRangeKeepsLimit(t *testing.T) {
+	entries, loadErr := loadStreamCatalog(streamCatalogTestPath)
+	require.NoError(t, loadErr)
+	entry := entries[0]
+	untilMs := time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC).UnixMilli()
+	window := 7 * 24 * time.Hour
+	req := buildStreamQueryRequest(entry, untilMs, window)
+	require.NotNil(t, req.GetTimeRange())
+	assert.Equal(t, untilMs, req.GetTimeRange().GetEnd().AsTime().UnixMilli())
+	assert.Equal(t, entry.Request.GetLimit(), req.GetLimit(), "pinned limit preserved")
+	assert.Nil(t, entry.Request.GetTimeRange(), "clone semantics: original untouched")
+}
+
+func TestStreamServiceIDExactFraction(t *testing.T) {
+	const series = 8
+	svcZero := 0
+	for idx := 0; idx < series; idx++ {
+		if streamServiceIDForIndex(idx, series) == "svc-0" {
+			svcZero++
+		}
+	}
+	assert.Equal(t, int(float64(series)*streamSvcZeroFraction), svcZero)
+}
+
+func makeElement(id string, duration int64) *streamv1.Element {
+	return &streamv1.Element{
+		ElementId: id,
+		TagFamilies: []*modelv1.TagFamily{{
+			Name: streamTagFamily,
+			Tags: []*modelv1.Tag{{Key: streamTagDuration, Value: streamIntTagValue(duration)}},
+		}},
+	}
+}
+
+func TestCompareStreamResultsUnorderedSetMatch(t *testing.T) {
+	baseline := []*streamv1.Element{makeElement("a", 1), makeElement("b", 2)}
+	replay := []*streamv1.Element{makeElement("b", 2), makeElement("a", 1)}
+	_, matched := compareStreamResults("set", baseline, replay, false)
+	assert.True(t, matched, "unordered comparison sorts by element_id")
+}
+
+func TestCompareStreamResultsOrderedPositionMatters(t *testing.T) {
+	baseline := []*streamv1.Element{makeElement("a", 1), makeElement("b", 2)}
+	replay := []*streamv1.Element{makeElement("b", 2), makeElement("a", 1)}
+	_, matched := compareStreamResults("seq", baseline, replay, true)
+	assert.False(t, matched, "ordered comparison preserves position")
+}
+
+func TestCompareStreamResultsChangedTagNoMatch(t *testing.T) {
+	baseline := []*streamv1.Element{makeElement("a", 1)}
+	replay := []*streamv1.Element{makeElement("a", 999)}
+	div, matched := compareStreamResults("changed", baseline, replay, false)
+	assert.False(t, matched)
+	assert.NotEmpty(t, div.FirstDiffs)
+}
+
+func TestCompareStreamResultsLengthMismatch(t *testing.T) {
+	baseline := []*streamv1.Element{makeElement("a", 1)}
+	replay := []*streamv1.Element{makeElement("a", 1), makeElement("b", 2)}
+	div, matched := compareStreamResults("len", baseline, replay, false)
+	assert.False(t, matched)
+	assert.Equal(t, 1, div.BaselineLen)
+	assert.Equal(t, 2, div.ReplayLen)
+}
+
+func TestValidateEngineStream(t *testing.T) {
+	assert.NoError(t, validateEngine(engineStream))
+}
diff --git a/cmd/soak-driver/trace.go b/cmd/soak-driver/trace.go
new file mode 100644
index 000000000..0a1d60c8c
--- /dev/null
+++ b/cmd/soak-driver/trace.go
@@ -0,0 +1,678 @@
+// 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.
+
+package main
+
+import (
+	"bytes"
+	"context"
+	"encoding/json"
+	"errors"
+	"fmt"
+	"io"
+	"os"
+	"sort"
+	"strings"
+	"time"
+
+	"google.golang.org/grpc"
+	"google.golang.org/protobuf/encoding/protojson"
+	"google.golang.org/protobuf/proto"
+	"google.golang.org/protobuf/types/known/timestamppb"
+
+	commonv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/common/v1"
+	databasev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/database/v1"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	tracev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/trace/v1"
+)
+
+// Trace soak fixture constants. The parity fixture group keeps its data for
+// the duration of the run (long TTL), while the load group rolls a short TTL
+// so background write-load traffic never accumulates unbounded.
+const (
+	traceFixtureGroup = "bench-trace-fixture"
+	traceLoadGroup    = "bench-trace-load"
+	traceName         = "sw"
+
+	traceFixtureTraces = 200
+	traceFixtureSpans  = 5
+	traceSpanBytes     = 1024
+
+	traceTagTraceID    = "trace_id"
+	traceTagState      = "state"
+	traceTagServiceID  = "service_id"
+	traceTagInstanceID = "service_instance_id"
+	traceTagEndpointID = "endpoint_id"
+	traceTagDuration   = "duration"
+	traceTagSpanID     = "span_id"
+	traceTagTimestamp  = "timestamp"
+
+	traceIndexTimestamp = "timestamp"
+	traceIndexDuration  = "duration"
+
+	// traceSvcZeroFraction is the share of generated traces assigned to
+	// service_id "svc-0". The catalog's svc-0 filters select exactly this
+	// fraction, so it must stay in lock-step with the generator.
+	traceSvcZeroFraction = 0.5
+	traceServiceCount    = 8
+	traceInstanceCount   = 4
+	traceEndpointCount   = 6
+)
+
+// traceCatalogEntry holds one query template from the trace JSON catalog.
+type traceCatalogEntry struct {
+	Request *tracev1.QueryRequest
+	ID      string
+}
+
+// traceBaselineRecord is persisted to disk after trace record-baseline runs.
+// Traces holds proto-JSON encoded tracev1.Trace messages.
+type traceBaselineRecord struct {
+	QueryName string            `json:"query_name"`
+	Traces    []json.RawMessage `json:"traces"`
+	Groups    []string          `json:"groups"`
+	UntilMs   int64             `json:"until_ms"`
+	Ordered   bool              `json:"ordered"`
+}
+
+// loadTraceCatalog reads the trace JSON catalog and returns its entries. The
+// on-disk shape reuses rawCatalogEntry ({id, request}); the request bytes are
+// decoded with protojson so proto oneofs (Criteria) and enums (Sort, BinaryOp)
+// round-trip correctly.
+func loadTraceCatalog(path string) ([]traceCatalogEntry, error) {
+	raw, readErr := os.ReadFile(path)
+	if readErr != nil {
+		return nil, fmt.Errorf("read trace catalog %s: %w", path, readErr)
+	}
+	var rawEntries []rawCatalogEntry
+	if unmarshalErr := json.Unmarshal(raw, &rawEntries); unmarshalErr != nil {
+		return nil, fmt.Errorf("unmarshal trace catalog array: %w", unmarshalErr)
+	}
+	entries := make([]traceCatalogEntry, 0, len(rawEntries))
+	for idx, rawEntry := range rawEntries {
+		if rawEntry.ID == "" {
+			return nil, fmt.Errorf("trace catalog entry %d: missing id", idx)
+		}
+		req := new(tracev1.QueryRequest)
+		if protoErr := protojson.Unmarshal(rawEntry.Request, req); protoErr != nil {
+			return nil, fmt.Errorf("unmarshal trace catalog entry %q: %w", rawEntry.ID, protoErr)
+		}
+		entries = append(entries, traceCatalogEntry{ID: rawEntry.ID, Request: req})
+	}
+	return entries, nil
+}
+
+// buildTraceQueryRequest injects a [until-window, until] TimeRange into a
+// cloned catalog request. The catalog's pinned Limit is preserved verbatim —
+// each shape carries the limit the parity check expects.
+func buildTraceQueryRequest(entry traceCatalogEntry, untilMs int64, window time.Duration) *tracev1.QueryRequest {
+	untilTime := time.UnixMilli(untilMs)
+	beginTime := untilTime.Add(-window)
+	req, _ := proto.Clone(entry.Request).(*tracev1.QueryRequest)
+	req.TimeRange = &modelv1.TimeRange{
+		Begin: timestamppb.New(beginTime),
+		End:   timestamppb.New(untilTime),
+	}
+	return req
+}
+
+// traceCatalogEntryOrdered reports whether the catalog query pins a result
+// order via order_by. Ordered queries are diffed position-by-position;
+// unordered queries are sorted before comparison.
+func traceCatalogEntryOrdered(entry traceCatalogEntry) bool {
+	return entry.Request.GetOrderBy().GetIndexRuleName() != ""
+}
+
+// traceStrTagValue wraps a string in a model TagValue.
+func traceStrTagValue(value string) *modelv1.TagValue {
+	return &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: value}}}
+}
+
+// traceIntTagValue wraps an int64 in a model TagValue.
+func traceIntTagValue(value int64) *modelv1.TagValue {
+	return &modelv1.TagValue{Value: &modelv1.TagValue_Int{Int: &modelv1.Int{Value: value}}}
+}
+
+// traceIDForIndex returns the deterministic trace ID for a trace index. The
+// format matches the querybench generator so the catalog's pinned IDs select
+// real fixture traces.
+func traceIDForIndex(traceIdx int) string {
+	return fmt.Sprintf("trace-%010d", traceIdx)
+}
+
+// traceServiceIDForIndex returns the per-TRACE service_id. The first
+// traceSvcZeroFraction of traces are svc-0 so the svc-0 catalog filters select
+// an exact, reproducible fraction; the remainder spread across svc-1..N.
+func traceServiceIDForIndex(traceIdx, traceCount int) string {
+	svcZeroCount := int(float64(traceCount) * traceSvcZeroFraction)
+	if traceIdx < svcZeroCount {
+		return "svc-0"
+	}
+	return fmt.Sprintf("svc-%d", 1+(traceIdx-svcZeroCount)%(traceServiceCount-1))
+}
+
+// traceSpanState returns the per-span state. 95% of spans are state 0 (OK);
+// the remainder are state 1 (error), spread deterministically.
+func traceSpanState(globalSpanIdx int) int64 {
+	if globalSpanIdx%20 == 0 {
+		return 1
+	}
+	return 0
+}
+
+// traceSpanPayload builds a ~spanBytes raw span body prefixed with identity so
+// each span's payload is unique yet reproducible.
+func traceSpanPayload(spanBytes int, traceID string, spanIdx int) []byte {
+	if spanBytes <= 0 {
+		spanBytes = traceSpanBytes
+	}
+	prefix := []byte(fmt.Sprintf("%s:%04d:", traceID, spanIdx))
+	if len(prefix) >= spanBytes {
+		return prefix[:spanBytes]
+	}
+	payload := make([]byte, 0, spanBytes)
+	payload = append(payload, prefix...)
+	payload = append(payload, bytes.Repeat([]byte("x"), spanBytes-len(prefix))...)
+	return payload
+}
+
+// traceSpanTags builds the ordered tag values for one span. The order matches
+// the Trace schema tag spec: trace_id, state, service_id, service_instance_id,
+// endpoint_id, duration, span_id, timestamp.
+func traceSpanTags(base time.Time, version uint64, traceIdx, spanIdx int, traceID, serviceID string) []*modelv1.TagValue {
+	globalSpanIdx := traceIdx*traceFixtureSpans + spanIdx
+	state := traceSpanState(globalSpanIdx)
+	duration := int64(1000 + traceIdx*10 + spanIdx)
+	timestamp := base.Add(time.Duration(version) * time.Second)
+	return []*modelv1.TagValue{
+		traceStrTagValue(traceID),
+		traceIntTagValue(state),
+		traceStrTagValue(serviceID),
+		traceStrTagValue(fmt.Sprintf("%s-inst-%d", serviceID, spanIdx%traceInstanceCount)),
+		traceStrTagValue(fmt.Sprintf("%s-endpoint-%d", serviceID, spanIdx%traceEndpointCount)),
+		traceIntTagValue(duration),
+		traceStrTagValue(fmt.Sprintf("%s-span-%04d", traceID, spanIdx)),
+		{Value: &modelv1.TagValue_Timestamp{Timestamp: timestamppb.New(timestamp)}},
+	}
+}
+
+// traceCreateGroup creates a CATALOG_TRACE group idempotently.
+func traceCreateGroup(ctx context.Context, client databasev1.GroupRegistryServiceClient, name string, ttlDays uint32) error {
+	_, createErr := client.Create(ctx, &databasev1.GroupRegistryServiceCreateRequest{
+		Group: &commonv1.Group{
+			Metadata: &commonv1.Metadata{Name: name},
+			Catalog:  commonv1.Catalog_CATALOG_TRACE,
+			ResourceOpts: &commonv1.ResourceOpts{
+				ShardNum: 1,
+				SegmentInterval: &commonv1.IntervalRule{
+					Unit: commonv1.IntervalRule_UNIT_DAY,
+					Num:  1,
+				},
+				Ttl: &commonv1.IntervalRule{
+					Unit: commonv1.IntervalRule_UNIT_DAY,
+					Num:  ttlDays,
+				},
+			},
+		},
+	})
+	if createErr != nil && !traceAlreadyExists(createErr) {
+		return fmt.Errorf("create trace group %s: %w", name, createErr)
+	}
+	return nil
+}
+
+// traceAlreadyExists reports whether err is an idempotent "already exists" error.
+func traceAlreadyExists(err error) bool {
+	return strings.Contains(err.Error(), "already exist")
+}
+
+// traceSeedFixture creates the two trace groups (parity fixture with a long
+// retain TTL, plus a rolling short-TTL load group), a Trace "sw" clone, the
+// timestamp/duration index rules, and the binding — all idempotently. It then
+// writes the deterministic fixture into the parity group and prints T1_MS, the
+// highest span timestamp (unix ms), to stdout.
+func traceSeedFixture(ctx context.Context, conn *grpc.ClientConn, traces, spans int) error {
+	if traces <= 0 {
+		traces = traceFixtureTraces
+	}
+	if spans <= 0 {
+		spans = traceFixtureSpans
+	}
+	groupClient := databasev1.NewGroupRegistryServiceClient(conn)
+	// Parity fixture group: long TTL so the data stays queryable for the run.
+	if groupErr := traceCreateGroup(ctx, groupClient, traceFixtureGroup, 30); groupErr != nil {
+		return groupErr
+	}
+	// Load group: short TTL so rolling background writes self-expire.
+	if groupErr := traceCreateGroup(ctx, groupClient, traceLoadGroup, 1); groupErr != nil {
+		return groupErr
+	}
+
+	traceClient := databasev1.NewTraceRegistryServiceClient(conn)
+	indexRuleClient := databasev1.NewIndexRuleRegistryServiceClient(conn)
+	bindingClient := databasev1.NewIndexRuleBindingRegistryServiceClient(conn)
+	for _, group := range []string{traceFixtureGroup, traceLoadGroup} {
+		if schemaErr := traceCreateSchema(ctx, traceClient, indexRuleClient, bindingClient, group); schemaErr != nil {
+			return schemaErr
+		}
+	}
+
+	base := traceFixtureBaseTime(traces * spans)
+	highestMs, writeErr := traceWriteFixture(ctx, conn, traceFixtureGroup, traces, spans, base, 0)
+	if writeErr != nil {
+		return writeErr
+	}
+	fmt.Printf("[trace seed-fixture] wrote %d traces x %d spans to %s/%s\n", traces, spans, traceFixtureGroup, traceName)
+	fmt.Printf("T1_MS=%d\n", highestMs)
+	fmt.Printf("%d\n", highestMs)
+	return nil
+}
+
+// traceCreateSchema creates the Trace resource, its index rules, and binding
+// for one group, idempotently.
+func traceCreateSchema(
+	ctx context.Context,
+	traceClient databasev1.TraceRegistryServiceClient,
+	indexRuleClient databasev1.IndexRuleRegistryServiceClient,
+	bindingClient databasev1.IndexRuleBindingRegistryServiceClient,
+	group string,
+) error {
+	trace := &databasev1.Trace{
+		Metadata: &commonv1.Metadata{Name: traceName, Group: group},
+		Tags: []*databasev1.TraceTagSpec{
+			{Name: traceTagTraceID, Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: traceTagState, Type: databasev1.TagType_TAG_TYPE_INT},
+			{Name: traceTagServiceID, Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: traceTagInstanceID, Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: traceTagEndpointID, Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: traceTagDuration, Type: databasev1.TagType_TAG_TYPE_INT},
+			{Name: traceTagSpanID, Type: databasev1.TagType_TAG_TYPE_STRING},
+			{Name: traceTagTimestamp, Type: databasev1.TagType_TAG_TYPE_TIMESTAMP},
+		},
+		TraceIdTagName:   traceTagTraceID,
+		TimestampTagName: traceTagTimestamp,
+		SpanIdTagName:    traceTagSpanID,
+	}
+	if _, createErr := traceClient.Create(ctx, &databasev1.TraceRegistryServiceCreateRequest{Trace: trace}); createErr != nil && !traceAlreadyExists(createErr) {
+		return fmt.Errorf("create trace resource in %s: %w", group, createErr)
+	}
+
+	rules := []*databasev1.IndexRule{
+		{
+			Metadata: &commonv1.Metadata{Name: traceIndexTimestamp, Group: group},
+			Tags:     []string{traceTagServiceID, traceTagInstanceID, traceTagState, traceTagTimestamp},
+			Type:     databasev1.IndexRule_TYPE_TREE,
+		},
+		{
+			Metadata: &commonv1.Metadata{Name: traceIndexDuration, Group: group},
+			Tags:     []string{traceTagServiceID, traceTagInstanceID, traceTagState, traceTagDuration},
+			Type:     databasev1.IndexRule_TYPE_TREE,
+		},
+	}
+	for _, rule := range rules {
+		if _, createErr := indexRuleClient.Create(ctx, &databasev1.IndexRuleRegistryServiceCreateRequest{IndexRule: rule}); createErr != nil && !traceAlreadyExists(createErr) {
+			return fmt.Errorf("create trace index rule %s in %s: %w", rule.GetMetadata().GetName(), group, createErr)
+		}
+	}
+
+	binding := &databasev1.IndexRuleBinding{
+		Metadata: &commonv1.Metadata{Name: "sw-index-rule-binding", Group: group},
+		Rules:    []string{traceIndexDuration, traceIndexTimestamp},
+		Subject:  &databasev1.Subject{Catalog: commonv1.Catalog_CATALOG_TRACE, Name: traceName},
+		BeginAt:  timestamppb.New(time.Date(2021, 1, 1, 0, 0, 0, 0, time.UTC)),
+		ExpireAt: timestamppb.New(time.Date(2121, 1, 1, 0, 0, 0, 0, time.UTC)),
+	}
+	if _, createErr := bindingClient.Create(ctx, &databasev1.IndexRuleBindingRegistryServiceCreateRequest{IndexRuleBinding: binding}); createErr != nil && !traceAlreadyExists(createErr) {
+		return fmt.Errorf("create trace index rule binding in %s: %w", group, createErr)
+	}
+	return nil
+}
+
+// traceFixtureBaseTime anchors the deterministic span timestamps to recent
+// wall-clock time. Span timestamps are base + version*second for version up to
+// totalSpans, so the newest lands ~1 minute in the past and the oldest ~totalSpans
+// seconds before that. They must fall inside the group's TTL retention window
+// (which is relative to now) or BanyanDB silently drops them and queries return
+// empty — a fixed calendar base lands outside retention once wall-clock moves on.
+// Within-run determinism does not depend on the calendar instant: Phase 0 seeds +
+// snapshots and Phase 1 restores that snapshot, so both phases see identical data.
+func traceFixtureBaseTime(totalSpans int) time.Time {
+	const marginSec = 60
+	return time.Now().UTC().Truncate(time.Second).Add(-time.Duration(totalSpans+marginSec) * time.Second)
+}
+
+// traceWriteFixture writes traces*spans deterministic spans into group via the
+// streaming TraceService.Write RPC, checking every per-response status. Version
+// is monotonic across all spans, offset by versionBase so distinct write runs
+// (e.g. write-load) never collide. Returns the highest span timestamp in ms.
+func traceWriteFixture(ctx context.Context, conn *grpc.ClientConn, group string, traces, spans int, base time.Time, versionBase uint64) (int64, error) {
+	client := tracev1.NewTraceServiceClient(conn)
+	stream, streamErr := client.Write(ctx)
+	if streamErr != nil {
+		return 0, fmt.Errorf("open trace write stream: %w", streamErr)
+	}
+
+	recvErrCh := make(chan error, 1)
+	go func() {
+		var firstBad string
+		bad := 0
+		for {
+			resp, recvErr := stream.Recv()
+			if errors.Is(recvErr, io.EOF) {
+				if bad > 0 {
+					recvErrCh <- fmt.Errorf("trace write rejected %d spans (first status: %q)", bad, firstBad)
+					return
+				}
+				recvErrCh <- nil
+				return
+			}
+			if recvErr != nil {
+				recvErrCh <- fmt.Errorf("receive trace write response: %w", recvErr)
+				return
+			}
+			if resp.GetStatus() != modelv1.Status_STATUS_SUCCEED.String() {
+				bad++
+				if firstBad == "" {
+					firstBad = resp.GetStatus()
+				}
+			}
+		}
+	}()
+
+	metadata := &commonv1.Metadata{Name: traceName, Group: group}
+	requestMetadata := metadata
+	var highestMs int64
+	for traceIdx := 0; traceIdx < traces; traceIdx++ {
+		traceID := traceIDForIndex(traceIdx)
+		serviceID := traceServiceIDForIndex(traceIdx, traces)
+		for spanIdx := 0; spanIdx < spans; spanIdx++ {
+			globalSpanIdx := traceIdx*spans + spanIdx
+			version := versionBase + uint64(globalSpanIdx) + 1
+			tags := traceSpanTags(base, version, traceIdx, spanIdx, traceID, serviceID)
+			tsMs := base.Add(time.Duration(version) * time.Second).UnixMilli()
+			if tsMs > highestMs {
+				highestMs = tsMs
+			}
+			req := &tracev1.WriteRequest{
+				Metadata: requestMetadata,
+				Tags:     tags,
+				Span:     traceSpanPayload(traceSpanBytes, traceID, spanIdx),
+				Version:  version,
+			}
+			if sendErr := stream.Send(req); sendErr != nil {
+				return 0, fmt.Errorf("send trace write request: %w", sendErr)
+			}
+			requestMetadata = nil
+		}
+	}
+	if closeErr := stream.CloseSend(); closeErr != nil {
+		return 0, fmt.Errorf("close trace write stream: %w", closeErr)
+	}
+	if recvErr := <-recvErrCh; recvErr != nil {
+		return 0, recvErr
+	}
+	return highestMs, nil
+}
+
+// traceRecordBaseline runs the catalog over [T1-window, T1], persists the
+// resulting traces as proto-JSON, and exits non-zero if any catalog query
+// returns an empty result (an empty baseline is not a usable parity reference).
+func traceRecordBaseline(ctx context.Context, conn *grpc.ClientConn, catalogPath, outPath string, untilMs int64, window time.Duration) error {
+	entries, loadErr := loadTraceCatalog(catalogPath)
+	if loadErr != nil {
+		return loadErr
+	}
+	client := tracev1.NewTraceServiceClient(conn)
+	records := make([]traceBaselineRecord, 0, len(entries))
+	var emptyQueries []string
+	for _, entry := range entries {
+		req := buildTraceQueryRequest(entry, untilMs, window)
+		queryName := entry.ID
+		queryCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+		resp, queryErr := client.Query(queryCtx, req)
+		cancel()
+		if queryErr != nil {
+			return fmt.Errorf("record-baseline %s: query failed: %w", queryName, queryErr)
+		}
+		rec := traceBaselineRecord{
+			QueryName: queryName,
+			Groups:    entry.Request.GetGroups(),
+			UntilMs:   untilMs,
+			Ordered:   traceCatalogEntryOrdered(entry),
+		}
+		for _, trace := range resp.GetTraces() {
+			rawTrace, marshalErr := protojson.Marshal(trace)
+			if marshalErr != nil {
+				return fmt.Errorf("marshal trace for %s: %w", queryName, marshalErr)
+			}
+			rec.Traces = append(rec.Traces, json.RawMessage(rawTrace))
+		}
+		records = append(records, rec)
+		if len(rec.Traces) == 0 {
+			emptyQueries = append(emptyQueries, queryName)
+		}
+		fmt.Printf("[trace record-baseline] %s: %d traces\n", queryName, len(rec.Traces))
+	}
+
+	out, createErr := os.Create(outPath)
+	if createErr != nil {
+		return fmt.Errorf("create output %s: %w", outPath, createErr)
+	}
+	defer out.Close()
+	enc := json.NewEncoder(out)
+	enc.SetIndent("", "  ")
+	if encErr := enc.Encode(records); encErr != nil {
+		return fmt.Errorf("encode trace baseline: %w", encErr)
+	}
+	fmt.Printf("[trace record-baseline] written to %s\n", outPath)
+	if len(emptyQueries) > 0 {
+		return fmt.Errorf("record-baseline: %d catalog queries returned no traces: %s", len(emptyQueries), strings.Join(emptyQueries, ", "))
+	}
+	return nil
+}
+
+// traceReplayAndDiff re-runs the catalog against the recorded baseline and
+// writes a diffReport (reusing the measure-path report shape so soak-monitor.sh
+// grep patterns match). It returns a non-zero error on any divergence.
+func traceReplayAndDiff(ctx context.Context, conn *grpc.ClientConn, catalogPath, baselinePath, reportPath string, window time.Duration) error {
+	raw, readErr := os.ReadFile(baselinePath)
+	if readErr != nil {
+		return fmt.Errorf("read trace baseline %s: %w", baselinePath, readErr)
+	}
+	var records []traceBaselineRecord
+	if unmarshalErr := json.Unmarshal(raw, &records); unmarshalErr != nil {
+		return fmt.Errorf("unmarshal trace baseline: %w", unmarshalErr)
+	}
+	entries, loadErr := loadTraceCatalog(catalogPath)
+	if loadErr != nil {
+		return loadErr
+	}
+	client := tracev1.NewTraceServiceClient(conn)
+	report := diffReport{
+		RunAt: time.Now().UTC().Format(time.RFC3339),
+		Pass:  true,
+	}
+	baselineMap := make(map[string]traceBaselineRecord, len(records))
+	for _, rec := range records {
+		baselineMap[rec.QueryName] = rec
+	}
+
+	for _, entry := range entries {
+		queryName := entry.ID
+		rec, ok := baselineMap[queryName]
+		if !ok {
+			fmt.Printf("[trace replay-and-diff] %s: SKIP (no baseline)\n", queryName)
+			continue
+		}
+		req := buildTraceQueryRequest(entry, rec.UntilMs, window)
+		queryCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
+		resp, queryErr := client.Query(queryCtx, req)
+		cancel()
+		if queryErr != nil {
+			report.Divergences = append(report.Divergences, divergence{QueryName: queryName})
+			report.Pass = false
+			fmt.Printf("[trace replay-and-diff] %s: FAIL (%v)\n", queryName, queryErr)
+			continue
+		}
+		report.QueriesRun++
+
+		baselineTraces, parseErr := decodeBaselineTraces(rec.Traces, queryName)
+		if parseErr != nil {
+			return parseErr
+		}
+		div, matched := compareTraceResults(queryName, baselineTraces, resp.GetTraces(), rec.Ordered)
+		if !matched {
+			report.Divergences = append(report.Divergences, div)
+			report.Pass = false
+		}
+	}
+
+	outFile, createErr := os.Create(reportPath)
+	if createErr != nil {
+		return fmt.Errorf("create trace report %s: %w", reportPath, createErr)
+	}
+	defer outFile.Close()
+	enc := json.NewEncoder(outFile)
+	enc.SetIndent("", "  ")
+	if encErr := enc.Encode(report); encErr != nil {
+		return fmt.Errorf("encode trace report: %w", encErr)
+	}
+	fmt.Printf("[trace replay-and-diff] %d queries run, %d divergences — %s\n",
+		report.QueriesRun, len(report.Divergences), map[bool]string{true: "PASS", false: "FAIL"}[report.Pass])
+	if !report.Pass {
+		return fmt.Errorf("parity check failed: %d divergences found", len(report.Divergences))
+	}
+	return nil
+}
+
+// decodeBaselineTraces decodes the proto-JSON trace blobs from a baseline record.
+func decodeBaselineTraces(raws []json.RawMessage, queryName string) ([]*tracev1.Trace, error) {
+	traces := make([]*tracev1.Trace, 0, len(raws))
+	for idx, raw := range raws {
+		trace := new(tracev1.Trace)
+		if parseErr := protojson.Unmarshal(raw, trace); parseErr != nil {
+			return nil, fmt.Errorf("unmarshal baseline trace %d for %s: %w", idx, queryName, parseErr)
+		}
+		traces = append(traces, trace)
+	}
+	return traces, nil
+}
+
+// compareTraceResults diffs baseline vs replay traces. Spans within each trace
+// are sorted by (span_id, marshaled bytes); unordered queries also sort traces
+// by trace_id, while ordered queries preserve position. It returns a divergence
+// and false on the first mismatch (length or content); the divergence carries up
+// to three first-diff samples for the report.
+func compareTraceResults(queryName string, baseline, replay []*tracev1.Trace, ordered bool) (divergence, bool) {
+	div := divergence{QueryName: queryName, BaselineLen: len(baseline), ReplayLen: len(replay)}
+	if len(baseline) != len(replay) {
+		return div, false
+	}
+	baselineNorm := normalizeTraces(baseline, ordered)
+	replayNorm := normalizeTraces(replay, ordered)
+	matched := true
+	for idx := range baselineNorm {
+		if !proto.Equal(baselineNorm[idx], replayNorm[idx]) {
+			matched = false
+			if len(div.FirstDiffs) < 3 {
+				div.FirstDiffs = append(div.FirstDiffs, pointDiff{
+					Index:    idx,
+					Baseline: baselineNorm[idx].String(),
+					Replay:   replayNorm[idx].String(),
+				})
+			}
+		}
+	}
+	return div, matched
+}
+
+// normalizeTraces returns clones with spans sorted by (span_id, bytes); when
+// not ordered, traces are also sorted by trace_id so set comparison is stable.
+func normalizeTraces(traces []*tracev1.Trace, ordered bool) []*tracev1.Trace {
+	clones := make([]*tracev1.Trace, 0, len(traces))
+	for _, trace := range traces {
+		clone, _ := proto.Clone(trace).(*tracev1.Trace)
+		sort.Slice(clone.Spans, func(left, right int) bool {
+			leftSpan := clone.Spans[left]
+			rightSpan := clone.Spans[right]
+			if leftSpan.GetSpanId() != rightSpan.GetSpanId() {
+				return leftSpan.GetSpanId() < rightSpan.GetSpanId()
+			}
+			leftBytes, leftErr := proto.MarshalOptions{Deterministic: true}.Marshal(leftSpan)
+			rightBytes, rightErr := proto.MarshalOptions{Deterministic: true}.Marshal(rightSpan)
+			if leftErr != nil || rightErr != nil {
+				return left < right
+			}
+			return bytes.Compare(leftBytes, rightBytes) < 0
+		})
+		clones = append(clones, clone)
+	}
+	if !ordered {
+		sort.Slice(clones, func(left, right int) bool {
+			return clones[left].GetTraceId() < clones[right].GetTraceId()
+		})
+	}
+	return clones
+}
+
+// traceWriteLoad runs continuous deterministic writes into the rolling load
+// group, OUTSIDE the parity window (separate group), rate-capped at rps. It
+// returns the number of spans written. Writes proceed in batches of one full
+// fixture sweep, advancing versionBase so spans stay unique.
+func traceWriteLoad(ctx context.Context, conn *grpc.ClientConn, traces, spans, rps int, duration time.Duration) (int, error) {
+	if traces <= 0 {
+		traces = traceFixtureTraces
+	}
+	if spans <= 0 {
+		spans = traceFixtureSpans
+	}
+	if rps <= 0 {
+		rps = 1000
+	}
+	spansPerSweep := traces * spans
+	// Load traffic goes to a SEPARATE group (traceLoadGroup) that the parity
+	// catalog never queries, so group isolation — not timestamp offsetting —
+	// keeps it from polluting parity. Anchor it to recent time so it lands
+	// inside the load group's (short) TTL retention window.
+	base := traceFixtureBaseTime(spansPerSweep)
+	deadline := time.Now().Add(duration)
+	totalSpans := 0
+	var versionBase uint64
+	interval := time.Second / time.Duration(rps)
+	for time.Now().Before(deadline) {
+		select {
+		case <-ctx.Done():
+			return totalSpans, ctx.Err()
+		default:
+		}
+		sweepStart := time.Now()
+		if _, writeErr := traceWriteFixture(ctx, conn, traceLoadGroup, traces, spans, base, versionBase); writeErr != nil {
+			return totalSpans, writeErr
+		}
+		totalSpans += spansPerSweep
+		versionBase += uint64(spansPerSweep)
+		// Rate-cap: a sweep emits spansPerSweep spans, which at rps should
+		// take spansPerSweep*interval. Sleep off any remaining budget.
+		elapsed := time.Since(sweepStart)
+		budget := time.Duration(spansPerSweep) * interval
+		if elapsed < budget {
+			time.Sleep(budget - elapsed)
+		}
+		fmt.Printf("[trace write-load] sweep done: %d spans total\n", totalSpans)
+	}
+	return totalSpans, nil
+}
diff --git a/cmd/soak-driver/trace_test.go b/cmd/soak-driver/trace_test.go
new file mode 100644
index 000000000..e9705a9d2
--- /dev/null
+++ b/cmd/soak-driver/trace_test.go
@@ -0,0 +1,367 @@
+// 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.
+
+package main
+
+import (
+	"encoding/json"
+	"os"
+	"path/filepath"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/assert"
+	"github.com/stretchr/testify/require"
+	"google.golang.org/protobuf/encoding/protojson"
+	"google.golang.org/protobuf/proto"
+
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	tracev1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/trace/v1"
+)
+
+const traceCatalogTestPath = "catalog/trace.json"
+
+func loadTestCatalog(t *testing.T) map[string]traceCatalogEntry {
+	t.Helper()
+	entries, loadErr := loadTraceCatalog(traceCatalogTestPath)
+	require.NoError(t, loadErr)
+	byID := make(map[string]traceCatalogEntry, len(entries))
+	for _, entry := range entries {
+		byID[entry.ID] = entry
+	}
+	return byID
+}
+
+func TestLoadTraceCatalogParsesAllShapes(t *testing.T) {
+	entries, loadErr := loadTraceCatalog(traceCatalogTestPath)
+	require.NoError(t, loadErr)
+	require.Len(t, entries, 5)
+	wantIDs := []string{"by_id_single", "by_id_batch", "tag_newest", "tag_slowest", "tag_complex"}
+	gotIDs := make([]string, 0, len(entries))
+	for _, entry := range entries {
+		gotIDs = append(gotIDs, entry.ID)
+		assert.Equal(t, traceName, entry.Request.GetName(), "entry %s name", entry.ID)
+		assert.Equal(t, []string{traceFixtureGroup}, entry.Request.GetGroups(), "entry %s groups", entry.ID)
+		assert.NotEmpty(t, entry.Request.GetTagProjection(), "entry %s tag projection", entry.ID)
+	}
+	assert.ElementsMatch(t, wantIDs, gotIDs)
+}
+
+func TestTraceCatalogByIDSingleShape(t *testing.T) {
+	entry := loadTestCatalog(t)["by_id_single"]
+	cond := entry.Request.GetCriteria().GetCondition()
+	require.NotNil(t, cond)
+	assert.Equal(t, traceTagTraceID, cond.GetName())
+	assert.Equal(t, modelv1.Condition_BINARY_OP_EQ, cond.GetOp())
+	assert.Equal(t, "trace-0000000100", cond.GetValue().GetStr().GetValue())
+	assert.Equal(t, uint32(1), entry.Request.GetLimit())
+	assert.Nil(t, entry.Request.GetOrderBy())
+	assert.False(t, traceCatalogEntryOrdered(entry))
+}
+
+func TestTraceCatalogByIDBatchShape(t *testing.T) {
+	entry := loadTestCatalog(t)["by_id_batch"]
+	cond := entry.Request.GetCriteria().GetCondition()
+	require.NotNil(t, cond)
+	assert.Equal(t, traceTagTraceID, cond.GetName())
+	assert.Equal(t, modelv1.Condition_BINARY_OP_IN, cond.GetOp())
+	ids := cond.GetValue().GetStrArray().GetValue()
+	require.Len(t, ids, 5)
+	assert.Contains(t, ids, "trace-0000000100")
+	assert.GreaterOrEqual(t, int(entry.Request.GetLimit()), len(ids), "limit must cover the batch")
+	assert.Nil(t, entry.Request.GetOrderBy())
+}
+
+func TestTraceCatalogTagNewestShape(t *testing.T) {
+	entry := loadTestCatalog(t)["tag_newest"]
+	cond := entry.Request.GetCriteria().GetCondition()
+	require.NotNil(t, cond)
+	assert.Equal(t, traceTagServiceID, cond.GetName())
+	assert.Equal(t, modelv1.Condition_BINARY_OP_EQ, cond.GetOp())
+	assert.Equal(t, "svc-0", cond.GetValue().GetStr().GetValue())
+	order := entry.Request.GetOrderBy()
+	require.NotNil(t, order)
+	assert.Equal(t, traceIndexTimestamp, order.GetIndexRuleName())
+	assert.Equal(t, modelv1.Sort_SORT_DESC, order.GetSort())
+	assert.Equal(t, uint32(50), entry.Request.GetLimit())
+	assert.True(t, traceCatalogEntryOrdered(entry))
+}
+
+func TestTraceCatalogTagSlowestShape(t *testing.T) {
+	entry := loadTestCatalog(t)["tag_slowest"]
+	le := entry.Request.GetCriteria().GetLe()
+	require.NotNil(t, le)
+	assert.Equal(t, modelv1.LogicalExpression_LOGICAL_OP_AND, le.GetOp())
+	assert.Equal(t, traceTagServiceID, le.GetLeft().GetCondition().GetName())
+	assert.Equal(t, "svc-0", le.GetLeft().GetCondition().GetValue().GetStr().GetValue())
+	assert.Equal(t, traceTagState, le.GetRight().GetCondition().GetName())
+	assert.Equal(t, int64(0), le.GetRight().GetCondition().GetValue().GetInt().GetValue())
+	order := entry.Request.GetOrderBy()
+	require.NotNil(t, order)
+	assert.Equal(t, traceIndexDuration, order.GetIndexRuleName())
+	assert.Equal(t, modelv1.Sort_SORT_DESC, order.GetSort())
+	assert.Equal(t, uint32(50), entry.Request.GetLimit())
+}
+
+func TestTraceCatalogTagComplexShape(t *testing.T) {
+	entry := loadTestCatalog(t)["tag_complex"]
+	// state == 0 AND service_id == svc-0 AND duration in [lo, hi].
+	criteria := entry.Request.GetCriteria()
+	conditions := collectConditions(criteria)
+	require.GreaterOrEqual(t, len(conditions), 4)
+	names := map[string]int{}
+	for _, cond := range conditions {
+		names[cond.GetName()]++
+	}
+	assert.Equal(t, 1, names[traceTagState])
+	assert.Equal(t, 1, names[traceTagServiceID])
+	assert.Equal(t, 2, names[traceTagDuration], "duration must have a lo and hi bound")
+	var lo, hi int64
+	var sawGE, sawLE bool
+	for _, cond := range conditions {
+		if cond.GetName() != traceTagDuration {
+			continue
+		}
+		switch cond.GetOp() {
+		case modelv1.Condition_BINARY_OP_GE:
+			lo = cond.GetValue().GetInt().GetValue()
+			sawGE = true
+		case modelv1.Condition_BINARY_OP_LE:
+			hi = cond.GetValue().GetInt().GetValue()
+			sawLE = true
+		}
+	}
+	assert.True(t, sawGE && sawLE, "both duration bounds present")
+	assert.Less(t, lo, hi, "duration range must be non-empty")
+	order := entry.Request.GetOrderBy()
+	require.NotNil(t, order)
+	assert.Equal(t, traceIndexDuration, order.GetIndexRuleName())
+	assert.Equal(t, modelv1.Sort_SORT_DESC, order.GetSort())
+	assert.Equal(t, uint32(20), entry.Request.GetLimit())
+}
+
+// collectConditions flattens a criteria tree into its leaf conditions.
+func collectConditions(criteria *modelv1.Criteria) []*modelv1.Condition {
+	if criteria == nil {
+		return nil
+	}
+	if cond := criteria.GetCondition(); cond != nil {
+		return []*modelv1.Condition{cond}
+	}
+	le := criteria.GetLe()
+	if le == nil {
+		return nil
+	}
+	out := collectConditions(le.GetLeft())
+	out = append(out, collectConditions(le.GetRight())...)
+	return out
+}
+
+func TestBuildTraceQueryRequestInjectsTimeRangeKeepsLimit(t *testing.T) {
+	entry := loadTestCatalog(t)["tag_complex"]
+	untilMs := time.Date(2024, 6, 1, 0, 0, 0, 0, time.UTC).UnixMilli()
+	window := 7 * 24 * time.Hour
+	req := buildTraceQueryRequest(entry, untilMs, window)
+	require.NotNil(t, req.GetTimeRange())
+	assert.Equal(t, untilMs, req.GetTimeRange().GetEnd().AsTime().UnixMilli())
+	assert.Equal(t, time.UnixMilli(untilMs).Add(-window).UnixMilli(), req.GetTimeRange().GetBegin().AsTime().UnixMilli())
+	// Catalog's pinned limit must be preserved, not overridden.
+	assert.Equal(t, uint32(20), req.GetLimit())
+	// The original catalog entry must be untouched (clone semantics).
+	assert.Nil(t, entry.Request.GetTimeRange())
+}
+
+func TestTraceFixtureGenerationIsReproducible(t *testing.T) {
+	// A fixed base keeps this in-memory reproducibility check deterministic;
+	// the production base (traceFixtureBaseTime) is now wall-clock-anchored,
+	// which is irrelevant here since no live cluster / TTL is involved.
+	base := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
+	first := generateFixtureTraces(t, 20, 5, base)
+	second := generateFixtureTraces(t, 20, 5, base)
+	require.Len(t, first, len(second))
+	for idx := range first {
+		assert.True(t, proto.Equal(first[idx], second[idx]), "trace %d must be byte-identical across runs", idx)
+	}
+}
+
+// generateFixtureTraces builds the in-memory trace set the seed path would
+// write, without any cluster, so generation determinism can be asserted.
+func generateFixtureTraces(t *testing.T, traces, spans int, base time.Time) []*tracev1.Trace {
+	t.Helper()
+	out := make([]*tracev1.Trace, 0, traces)
+	for traceIdx := 0; traceIdx < traces; traceIdx++ {
+		traceID := traceIDForIndex(traceIdx)
+		serviceID := traceServiceIDForIndex(traceIdx, traces)
+		trace := &tracev1.Trace{TraceId: traceID}
+		for spanIdx := 0; spanIdx < spans; spanIdx++ {
+			globalSpanIdx := traceIdx*spans + spanIdx
+			version := uint64(globalSpanIdx) + 1
+			tags := traceSpanTags(base, version, traceIdx, spanIdx, traceID, serviceID)
+			modelTags := make([]*modelv1.Tag, 0, len(tags))
+			for tagIdx, value := range tags {
+				modelTags = append(modelTags, &modelv1.Tag{Key: traceSchemaTagName(tagIdx), Value: value})
+			}
+			trace.Spans = append(trace.Spans, &tracev1.Span{
+				SpanId: traceID + "-span-" + padSpanIdx(spanIdx),
+				Tags:   modelTags,
+				Span:   traceSpanPayload(traceSpanBytes, traceID, spanIdx),
+			})
+		}
+		out = append(out, trace)
+	}
+	return out
+}
+
+func traceSchemaTagName(idx int) string {
+	names := []string{
+		traceTagTraceID, traceTagState, traceTagServiceID, traceTagInstanceID,
+		traceTagEndpointID, traceTagDuration, traceTagSpanID, traceTagTimestamp,
+	}
+	return names[idx]
+}
+
+func padSpanIdx(spanIdx int) string {
+	return string([]byte{
+		byte('0' + (spanIdx/1000)%10),
+		byte('0' + (spanIdx/100)%10),
+		byte('0' + (spanIdx/10)%10),
+		byte('0' + spanIdx%10),
+	})
+}
+
+func TestTraceServiceIDExactFraction(t *testing.T) {
+	const traces = 200
+	svcZero := 0
+	for traceIdx := 0; traceIdx < traces; traceIdx++ {
+		if traceServiceIDForIndex(traceIdx, traces) == "svc-0" {
+			svcZero++
+		}
+	}
+	assert.Equal(t, int(float64(traces)*traceSvcZeroFraction), svcZero)
+}
+
+func TestCompareTraceResultsEqualMatch(t *testing.T) {
+	baseline := []*tracev1.Trace{makeTrace("trace-a", 2), makeTrace("trace-b", 3)}
+	replay := []*tracev1.Trace{makeTrace("trace-a", 2), makeTrace("trace-b", 3)}
+	_, matched := compareTraceResults("eq", baseline, replay, false)
+	assert.True(t, matched)
+}
+
+func TestCompareTraceResultsReorderedSpansMatch(t *testing.T) {
+	baseline := []*tracev1.Trace{makeTrace("trace-a", 4)}
+	replay := []*tracev1.Trace{makeTrace("trace-a", 4)}
+	// Reverse the replay span order — unordered span comparison must still match.
+	spans := replay[0].Spans
+	for left, right := 0, len(spans)-1; left < right; left, right = left+1, right-1 {
+		spans[left], spans[right] = spans[right], spans[left]
+	}
+	_, matched := compareTraceResults("reorder", baseline, replay, false)
+	assert.True(t, matched)
+}
+
+func TestCompareTraceResultsChangedTagNoMatch(t *testing.T) {
+	baseline := []*tracev1.Trace{makeTrace("trace-a", 2)}
+	replay := []*tracev1.Trace{makeTrace("trace-a", 2)}
+	replay[0].Spans[0].Tags[0].Value = traceStrTagValue("mutated")
+	div, matched := compareTraceResults("changed", baseline, replay, false)
+	assert.False(t, matched)
+	assert.NotEmpty(t, div.FirstDiffs)
+}
+
+func TestCompareTraceResultsOrderedVsUnordered(t *testing.T) {
+	baseline := []*tracev1.Trace{makeTrace("trace-a", 1), makeTrace("trace-b", 1)}
+	replay := []*tracev1.Trace{makeTrace("trace-b", 1), makeTrace("trace-a", 1)}
+	// Unordered: trace order is normalized away, so it matches.
+	_, unorderedMatch := compareTraceResults("set", baseline, replay, false)
+	assert.True(t, unorderedMatch)
+	// Ordered: position matters, so the swapped order diverges.
+	_, orderedMatch := compareTraceResults("seq", baseline, replay, true)
+	assert.False(t, orderedMatch)
+}
+
+func TestCompareTraceResultsLengthMismatch(t *testing.T) {
+	baseline := []*tracev1.Trace{makeTrace("trace-a", 1)}
+	replay := []*tracev1.Trace{makeTrace("trace-a", 1), makeTrace("trace-b", 1)}
+	div, matched := compareTraceResults("len", baseline, replay, false)
+	assert.False(t, matched)
+	assert.Equal(t, 1, div.BaselineLen)
+	assert.Equal(t, 2, div.ReplayLen)
+}
+
+func makeTrace(traceID string, spans int) *tracev1.Trace {
+	trace := &tracev1.Trace{TraceId: traceID}
+	for spanIdx := 0; spanIdx < spans; spanIdx++ {
+		trace.Spans = append(trace.Spans, &tracev1.Span{
+			SpanId: traceID + "-span-" + padSpanIdx(spanIdx),
+			Tags:   []*modelv1.Tag{{Key: traceTagServiceID, Value: traceStrTagValue("svc-0")}},
+			Span:   []byte(traceID),
+		})
+	}
+	return trace
+}
+
+func TestDecodeBaselineTracesRoundTrip(t *testing.T) {
+	original := makeTrace("trace-rt", 3)
+	rawTrace, marshalErr := protojson.Marshal(original)
+	require.NoError(t, marshalErr)
+	decoded, decodeErr := decodeBaselineTraces([]json.RawMessage{json.RawMessage(rawTrace)}, "rt")
+	require.NoError(t, decodeErr)
+	require.Len(t, decoded, 1)
+	assert.True(t, proto.Equal(original, decoded[0]))
+}
+
+func TestTraceReplayAndDiffEmptyBaselineFailsOnDivergence(t *testing.T) {
+	// Mirror record-baseline's empty-result guard: an empty baseline record
+	// is unusable. compareTraceResults against a non-empty replay must diverge.
+	baseline := []*tracev1.Trace(nil)
+	replay := []*tracev1.Trace{makeTrace("trace-a", 1)}
+	_, matched := compareTraceResults("empty", baseline, replay, false)
+	assert.False(t, matched, "empty baseline vs non-empty replay must diverge")
+}
+
+func TestTraceBaselineRecordEmptyDetection(t *testing.T) {
+	// A baseline record with zero traces must be flagged as empty so the
+	// record-baseline path can exit non-zero. This asserts the serialized
+	// shape round-trips and the empty count is observable.
+	dir := t.TempDir()
+	path := filepath.Join(dir, "baseline.json")
+	records := []traceBaselineRecord{
+		{QueryName: "full", Traces: []json.RawMessage{json.RawMessage(`{"traceId":"x"}`)}},
+		{QueryName: "empty", Traces: nil},
+	}
+	data, marshalErr := json.Marshal(records)
+	require.NoError(t, marshalErr)
+	require.NoError(t, os.WriteFile(path, data, 0o600))
+
+	raw, readErr := os.ReadFile(path)
+	require.NoError(t, readErr)
+	var decoded []traceBaselineRecord
+	require.NoError(t, json.Unmarshal(raw, &decoded))
+	empty := 0
+	for _, rec := range decoded {
+		if len(rec.Traces) == 0 {
+			empty++
+		}
+	}
+	assert.Equal(t, 1, empty)
+}
+
+func TestValidateEngine(t *testing.T) {
+	assert.NoError(t, validateEngine(engineMeasure))
+	assert.NoError(t, validateEngine(engineTrace))
+	assert.Error(t, validateEngine("bogus"))
+}
diff --git a/docs/operation/upgrade.md b/docs/operation/upgrade.md
index 8de7e5257..3b3a6e724 100644
--- a/docs/operation/upgrade.md
+++ b/docs/operation/upgrade.md
@@ -33,6 +33,11 @@ Before upgrading the cluster, you should check CHANGELOG.md](https://github.com/
 - Upgrade "data" nodes first, then "liaison" nodes.
 - After upgrading all nodes, the cluster will be running the new version.
 
+> **Exception — upgrading to 0.11 or later.** The vectorized query paths change the
+> liaison<->data wire format, and a data node must never have a vectorized path enabled
+> that the liaison it answers cannot decode. For 0.11 the order is **reversed**: upgrade
+> "liaison" nodes first, then "data" nodes. See [Vectorized query paths enabled by default](#vectorized-query-paths-enabled-by-default-breaking-for-rolling-upgrades).
+
 To ensure this strategy works, you should have a minimum of one node for each role of node in the cluster. For example, if you have a 2-node cluster, you should have at least one "liaison" and one "data" node.
 
 The cluster should also have enough capacity to handle the load when one node is down for upgrade.
@@ -50,6 +55,40 @@ The data ingestion and retrieval will be stopped during the upgrade process. The
 
 If you don't have enough resource to perform a rolling upgrade or you have a large cluster with many nodes, you can use the minimum downtime strategy.
 
+## Upgrading to 0.11
+
+This section describes breaking changes and important behavioral changes when upgrading to BanyanDB 0.11.0.
+
+### Vectorized query paths enabled by default (breaking for rolling upgrades)
+
+The vectorized **stream** and **trace** query paths are now enabled by default, joining **measure** (default-on since 0.10). `--stream-vectorized-enabled`, `--trace-vectorized-enabled` and `--measure-vectorized-enabled` all default to `true`.
+
+**This changes the required rolling-upgrade order. Upgrade "liaison" nodes BEFORE "data" nodes.**
+
+The reason is that each flag selects the liaison<->data wire format as well as the query engine. A flag-on distributed **data** node emits a native columnar frame instead of protobuf. Liaison nodes on 0.11 accept both — they dispatch per message on the frame's leading magic byte and fall back to protobuf — but a liaison still running an older binary has **no frame decoder at all** and will fail to deserialize the response.
+
+The two orders behave differently:
+
+| Upgrade order | Result |
+| --- | --- |
+| Liaison first, then data | **Safe.** New liaisons decode both frames and protobuf; old data nodes keep sending protobuf until upgraded. |
+| Data first, then liaison | **Queries fail** for the duration of the rollout. New data nodes emit frames that old liaisons cannot decode. |
+
+This is the opposite of the general rolling strategy documented above, which applies to all other upgrades.
+
+If you cannot control node ordering, either use the [Minimum Downtime Strategy](#minimum-downtime-strategy-to-upgrade-a-cluster), or start the new data nodes with the vectorized paths explicitly disabled and enable them after every liaison is upgraded:
+
+```shell
+banyand data \
+  --stream-vectorized-enabled=false \
+  --trace-vectorized-enabled=false \
+  --measure-vectorized-enabled=false
+```
+
+Standalone deployments are unaffected: the frame is only emitted on a distributed data node, so a standalone server always uses the protobuf path regardless of the flag.
+
+**Rollback.** Pass `--stream-vectorized-enabled=false` / `--trace-vectorized-enabled=false` / `--measure-vectorized-enabled=false` on the standalone or data-node command line and restart. The row path and the protobuf wire format resume immediately; no data migration is involved, because the flags affect only the query and wire paths, never the on-disk format.
+
 ## Upgrading to 0.10
 
 This section describes breaking changes and important behavioral changes when upgrading to BanyanDB 0.10.0.
diff --git a/docs/soak/trace-soak-runbook.md b/docs/soak/trace-soak-runbook.md
new file mode 100644
index 000000000..549465249
--- /dev/null
+++ b/docs/soak/trace-soak-runbook.md
@@ -0,0 +1,561 @@
+# Trace Vectorized-Query Soak Runbook
+
+This document covers how to run and interpret the two-instrument soak for the
+trace vectorized-query path in SkyWalking BanyanDB. It mirrors the structure
+of `docs/soak/g5d-runbook.md` (the measure soak) but is specific to the trace
+engine additions introduced in `scripts/soak-vectorized.sh SOAK_ENGINE=trace`.
+
+## Overview
+
+The trace soak uses **two instruments** that cover complementary failure modes:
+
+| Instrument | Entry point | What it proves |
+|---|---|---|
+| **1 — Container correctness + survival** | `SOAK_ENGINE=trace ./scripts/soak-vectorized.sh` | Parity (row→vec byte-match), crash/restart survival, goroutine-leak absence, write-load liveness, vec-flag honored |
+| **2 — In-process DQB sustained bench** | `DQB_SOAK=1 DQB_ENGINE=trace ./run-docker.sh` | `vtrace.QueryCount()` liveness, heap `inuse_space` leak gate, budget hard-stop + first-block exception engagement |
+
+Instrument 2 is the **authoritative** gate for memory leak and vec-liveness
+because `vtrace.QueryCount()` is a package-private in-process `atomic.Int64`
+that cannot be read from a separate driver process. Instrument 1 provides the
+crash/restart, OS-level goroutine, and multi-hour parity signals that an
+in-process bench cannot reproduce.
+
+CI gates on **both** instruments independently (two different exit statuses and
+two different JSON artifacts). A pass from one instrument does not subsume the
+other.
+
+### OAP-independence rationale
+
+OAP→BanyanDB trace-module routing is version- and configuration-dependent. The
+soak self-generates all trace writes via `TraceService.Write` (deterministic,
+version-keyed spans, two separate groups) and does not depend on OAP traffic
+for the parity fixture. The OAP/provider/consumer services present in the
+compose stack are background noise only.
+
+## MANDATORY: Both instruments run inside resource-limited containers
+
+**Neither instrument runs on the host directly.** An uncontained invocation is
+a hard error, not a silent fallback.
+
+- **Instrument 1**: BanyanDB runs as a compose service with
+  `deploy.resources.limits` (2 GB / 2 CPU). The `soak-driver` also runs as a
+  compose service (512 MB / 1 CPU) via `docker compose run --rm soak-driver`.
+  The driver reaches BanyanDB over the compose network (`banyandb:17912`,
+  `banyandb:6060`). No driver binary runs on the host.
+- **Instrument 2**: runs only via `run-docker.sh`, which builds the test image
+  and executes the `go test` binary inside a `--cpus/--memory`-limited
+  container. `ValidateSoak()` in `config.go` hard-fails (`DQB_IN_CONTAINER`
+  gate) if `DQB_IN_CONTAINER != 1`. A direct `go test` on the host will be
+  rejected.
+
+The cgroup memory limit is what makes the heap-growth gate and the
+budget-engagement gate (the `--trace-vectorized-query-memory-mib` hard-stop)
+reproducible. Every run records the effective CPU/memory limits and image
+digests in its artifacts.
+
+**Single exception**: pure config/unit tests (catalog parse, query-build,
+compare logic — no cluster, no data) may run on the host via `go test` directly.
+
+## Prerequisites
+
+- Docker daemon running (`docker info` succeeds); Docker Compose v2.
+- Host RAM headroom: at least 8 GB free. The Instrument 1 compose stack peaks
+  at approximately 6.5 GB total across all services.
+- Disk: at least 10 GB free under the repo root for snapshots, profiles, logs.
+- Go toolchain installed (to build the `soak-driver` image and the querybench
+  test binary).
+- The `vectorized-query` branch checked out.
+
+Check headroom:
+
+```bash
+free -h   # look at "available" column
+df -h .   # look at "Avail" column
+```
+
+## Instrument 1 — Container Correctness + Survival Soak
+
+### Environment variables
+
+| Variable | Default | Purpose |
+|---|---|---|
+| `SOAK_ENGINE` | `measure` | Must be `trace` for this runbook |
+| `WARMUP_MIN` | `60` | Minutes to wait before baseline (0 in SMOKE — trace uses self-seeded data, not OAP warmup) |
+| `SOAK_HOURS` | `48` | Phase 1 duration in hours |
+| `PPROF_INTERVAL_MIN` | `30` | Minutes between heap/goroutine pprof captures |
+| `PARITY_INTERVAL_MIN` | `5` | Minutes between `replay-and-diff` runs |
+| `SEED_ROWS` | `1000` | Unused by the trace path (trace uses `--traces`/`--spans` defaults); present in the script for the measure path |
+| `SOAK_TRACE_SPANS_PER_TRACE` | _(driver default: 5)_ | Passed as `--spans` to `seed-fixture` when set; if unset, the driver's compiled-in default is used |
+| `SOAK_TRACE_SERVICES` | _(unset)_ | Documented in the script header but **not currently passed to the driver**; reserved for a future `--services` flag |
+| `SOAK_WRITE_RPS` | `500` | Rate cap in spans/second for the background write-load loop |
+| `SOAK_HEAP_GROWTH_MAX_PCT` | `10` | Advisory threshold recorded in `summary.json`; the authoritative gate is Instrument 2 |
+| `SMOKE` | _(unset)_ | Set to `1` for a ~25-minute condensed run (overrides durations: `WARMUP_MIN=0`, `SOAK_HOURS=0.34`, intervals=1 min) |
+
+### SMOKE invocation
+
+```bash
+cd /path/to/repo
+SOAK_ENGINE=trace SMOKE=1 ./scripts/soak-vectorized.sh
+```
+
+Expected runtime: 25–35 minutes.
+
+### Production 48-hour invocation
+
+```bash
+cd /path/to/repo
+SOAK_ENGINE=trace ./scripts/soak-vectorized.sh
+```
+
+Optional overrides example:
+
+```bash
+SOAK_ENGINE=trace \
+  SOAK_HOURS=48 \
+  PPROF_INTERVAL_MIN=30 \
+  PARITY_INTERVAL_MIN=5 \
+  SOAK_WRITE_RPS=500 \
+  ./scripts/soak-vectorized.sh
+```
+
+### Phase 0 — vec-off, capture golden baseline
+
+1. `BANYANDB_VEC_ENABLED=false docker compose up -d banyandb` — standalone
+   BanyanDB with `--trace-vectorized-enabled=false`, resource-limited (2 GB /
+   2 CPU).
+2. Health-check `http://localhost:17913/api/healthz` (120-attempt cap, 5 s
+   intervals).
+3. `docker compose run --rm soak-driver seed-fixture --engine trace
+   --addr banyandb:17912 [--spans N]` — creates two groups:
+   - `bench-trace-fixture` (retain TTL 30 days, keeps baseline data alive for
+     the full run).
+   - `bench-trace-load` (TTL 1 day, rolling expiry for write-load traffic).
+   Creates the `sw` Trace resource + `timestamp`/`duration` index rules +
+   binding in both groups; writes the deterministic fixture into
+   `bench-trace-fixture`; prints `T1_MS` (highest span timestamp in unix ms).
+4. Wait 8 s for schema-server flush to persist (schema segments must land on
+   disk before snapshot).
+5. `docker compose run --rm soak-driver record-baseline --engine trace
+   --addr banyandb:17912 --catalog /catalog/trace.json --until T1_MS
+   --out /artifacts/baseline.json` — runs all 5 catalog queries over
+   `[T1_MS - 7d, T1_MS]`, persists `[]*Trace` as proto-JSON. **Fails non-zero
+   if any catalog query returns zero traces** (engine-agnostic guard).
+6. Stop BanyanDB → `cp -a data/. data-snapshot/` → `docker compose down -v`.
+
+### Phase 1 — vec-on, soak
+
+1. Restore snapshot → `BANYANDB_VEC_ENABLED=true docker compose up -d banyandb`.
+2. Health-check; then **vec-flag-honored gate**: grep startup logs for
+   `trace-vectorized-enabled=true`. This grep is load-bearing because the
+   parity-clean S=5 fixture produces identical vec-on/vec-off output by design,
+   so parity alone cannot distinguish "vec engaged" from "vec silently disabled".
+3. Initial pprof-grab (heap + goroutine) → `pprof-start/`.
+4. Background loops (fail-tolerant — WARN on a bad tick, never abort):
+   - **parity** (every `PARITY_INTERVAL_MIN`): `replay-and-diff --engine trace`
+     re-runs the catalog vs vec-on live data; writes `diff-<ts>.json`.
+   - **pprof** (every `PPROF_INTERVAL_MIN`): heap + goroutine snapshots.
+   - **write-load** (continuous, rate-capped at `SOAK_WRITE_RPS` spans/s):
+     deterministic writes into `bench-trace-load` using timestamps offset 365
+     days past the fixture base time (never overlaps the parity window); drives
+     flush/merge/compaction/expiry stress; records span count + last-success.
+   - **RSS+disk advisory sampler** (`docker stats` → `rss-trend.csv`).
+   - **log capture** (rotation-bounded `--since 60s` snapshots → `banyand.log`)
+     and memory-alert grep
+     (`budget|MemoryTracker|panic|vectorized` → `memory-alerts.log`).
+5. Wait `SOAK_HOURS` → kill loops → final pprof-grab (`pprof-end/`) → final
+   `replay-and-diff` (sets `FINAL_PASS`) → write `summary.json`.
+
+### Tapered monitor (recommended for unattended runs)
+
+In a separate terminal:
+
+```bash
+./scripts/soak-monitor.sh                    # watches the most recent run
+./scripts/soak-monitor.sh dist/soak/<ts>     # watches a specific run
+```
+
+The monitor greps `diff-*.json` for `"pass": false`, checks that `banyand.log`
+is not stale, and alerts on any `memory-alerts.log` growth. It exits 0 when
+`summary.json` appears with no alerts, 2 if any alert fired.
+
+To abort safely, press Ctrl-C. The `trap` in the script runs
+`docker compose down -v` before exiting.
+
+## Instrument 2 — In-Process DQB Sustained Bench (Authoritative Gate)
+
+Instrument 2 boots an in-process distributed cluster (liaison + data nodes) and
+reads `vtrace.QueryCount()` and `runtime.ReadMemStats` directly — same process —
+to prove liveness and the absence of a cursor-release leak. This topology is the
+only one that can read the package-private atomic counter.
+
+As a side effect, the in-process distributed boot exercises
+`EncodeTraceResultFrame` / `DecodeTraceResultFrame` and the liaison itersort
+merge path for correctness.
+
+### Environment variables
+
+| Variable | Default | Purpose |
+|---|---|---|
+| `DQB_SOAK` | `0` | Set to `1` to activate `TestTraceVecSoak` (otherwise the test skips) |
+| `DQB_ENGINE` | `measure` | Must be `trace` for the soak |
+| `SOAK_HEAP_GROWTH_MAX_PCT` | `10` | Maximum allowable `HeapInuse` growth from post-warmup baseline to end, as a percentage; gate fails if exceeded |
+| `DQB_QUERY_MEMORY_MIB` | `256` | `--trace-vectorized-query-memory-mib` passed to the in-process cluster for the parity phase |
+| `DQB_IN_CONTAINER` | _(must be 1)_ | Hard-fail gate; set automatically by `run-docker.sh` |
+| `DQB_REPORT_DIR` | `.omx/bench-reports/distributed-query` | Directory for `soak-trace-vec-result.json`; set automatically by `run-docker.sh` |
+
+### SMOKE / quick invocation
+
+```bash
+cd /path/to/repo
+DQB_SOAK=1 DQB_ENGINE=trace ./test/integration/distributed/querybench/run-docker.sh \
+  --cpus 4 --memory 8g
+```
+
+### Production invocation (custom budget threshold)
+
+```bash
+DQB_SOAK=1 DQB_ENGINE=trace SOAK_HEAP_GROWTH_MAX_PCT=10 \
+  ./test/integration/distributed/querybench/run-docker.sh \
+  --cpus 4 --memory 8g
+```
+
+`run-docker.sh` builds the querybench image, then runs `orchestrate.sh` inside
+the container. When `DQB_SOAK=1`, `orchestrate.sh` runs only
+`TestTraceVecSoak` (not the full benchmark matrix) and exits.
+
+A direct host `go test` invocation will fail immediately:
+
+```
+invalid soak config: DQB_SOAK=1 requires DQB_IN_CONTAINER=1; invoke via
+test/integration/distributed/querybench/run-docker.sh
+```
+
+### What `TestTraceVecSoak` does
+
+**Phase 1 — parity fixture (200 iterations, liveness + leak gate)**
+
+- Boots in-process cluster vec-on; seeds 1000-trace × 20-span uniform fixture
+  (budget 256 MiB, never truncates → parity clean).
+- Warmup: 3 query iterations to stabilize JIT paths and GC.
+- Snapshots post-warmup `vtrace.QueryCount()` + `runtime.ReadMemStats.HeapInuse`.
+- Runs 200 query iterations, sampling `QueryCount` every 20 iterations to assert
+  monotonicity.
+- Forces GC; snapshots final `QueryCount` + `HeapInuse`.
+
+**Phase 2 — budget-engagement scenario (50 iterations)**
+
+- Boots a second in-process cluster with `QueryMemoryMiB = 2` MiB (the compiled
+  `soakBudgetMiB` constant) + heavy-tail fixture (500-span traces at 1 KiB/span)
+  so the budget hard-stop fires on every query.
+- Runs 50 iterations; asserts each returns a bounded result set and heap stays
+  near-flat (cursor-release path releases skipped cursors without leaking).
+
+### Instrument 2 gates
+
+| Gate | Pass condition |
+|---|---|
+| **QueryCount monotonic** | `vtrace.QueryCount()` is non-decreasing across every 20-iteration sample |
+| **Liveness** | Final `QueryCount` delta from post-warmup baseline ≥ 200 (vec fired every iteration) |
+| **Heap-leak (authoritative)** | `HeapInuse` growth from post-warmup baseline to end ≤ `SOAK_HEAP_GROWTH_MAX_PCT` % (default 10) |
+| **Budget result bound** | Every budget-scenario result has trace count ≤ query limit |
+| **Budget heap** | Budget-scenario `HeapInuse` growth ≤ `SOAK_HEAP_GROWTH_MAX_PCT` % |
+| **Budget liveness** | `QueryCount` delta ≥ 50 over the budget scenario |
+
+## Instrument 1 Gates vs Advisory Signals
+
+### Gates (hard failures)
+
+| Signal | Pass condition |
+|---|---|
+| **Parity (primary)** | `diff-final.json` has `"pass": true` — every catalog query byte-matches baseline via `proto.Equal` per `Trace` (spans sorted by `(span_id, bytes)`, trace order preserved for ordered queries) |
+| **Goroutine drift** | `goroutine_count_end / goroutine_count_start ≤ 1.05` |
+| **No crash/restart** | BanyanDB container uptime continuous; `banyand.log` not stale (`soak-monitor.sh`) |
+| **No memory-alert lines** | `memory-alerts.log` has 0 lines matching `budget\|MemoryTracker\|panic\|vectorized` |
+| **Write-load alive** | `write_load_spans > 0` in `summary.json` |
+| **Vec flag honored** | Startup log grep confirms `--trace-vectorized-enabled=true` was honored |
+
+### Advisory signals (human review only, not gates)
+
+- `rss-trend.csv` — container RSS and data-dir disk usage sampled every 60 s.
+- Container heap `inuse_space` pprof diff (`pprof-start/` vs `pprof-end/`). Use
+  `go tool pprof -inuse_space -base pprof-start/heap-*.pb.gz pprof-end/heap-*.pb.gz`
+  to inspect. The 48 h diff is polluted by write-load/merge/compaction churn
+  unrelated to the cursor-release path; the authoritative leak gate is
+  Instrument 2.
+
+## Trace Catalog
+
+The catalog is `cmd/soak-driver/catalog/trace.json`. All 5 shapes target
+`bench-trace-fixture` / Trace `sw` and carry a pinned `limit`.
+
+| ID | Shape | Filter | Order | Limit |
+|---|---|---|---|---|
+| `by_id_single` | Point lookup | `trace_id = "trace-0000000100"` | none | 1 |
+| `by_id_batch` | Batch lookup | `trace_id IN [98..102]` | none | 5 |
+| `tag_newest` | Tag filter + sort | `service_id = "svc-0"` | `timestamp DESC` | 50 |
+| `tag_slowest` | Tag filter + sort | `service_id = "svc-0" AND state = 0` | `duration DESC` | 50 |
+| `tag_complex` | Multi-condition | `state = 0 AND service_id = "svc-0" AND duration ∈ [1000, 2000]` | `timestamp DESC` | 20 |
+
+All queries project all 8 tags: `trace_id`, `state`, `service_id`,
+`service_instance_id`, `endpoint_id`, `duration`, `span_id`, `timestamp`.
+
+## Two-Group Design
+
+| Group | TTL | Purpose |
+|---|---|---|
+| `bench-trace-fixture` | 30 days | Parity fixture; immutable during Phase 1; baseline never ages out |
+| `bench-trace-load` | 1 day | Rolling write-load target; data self-expires; bounded disk growth |
+
+Write-load writes use timestamps offset 365 days past the fixture base time
+(`2024-01-01T00:00:00Z + 365 days`) so they never land in the parity query
+window `[T1_MS - 7d, T1_MS]`.
+
+## Artifacts
+
+### Instrument 1 artifacts
+
+All artifacts land under `dist/soak/<YYYYMMDDTHHMMSS>/`:
+
+```
+dist/soak/<ts>/
+  run.log                    # tee'd full orchestrator log
+  baseline.json              # array of traceBaselineRecord (proto-JSON Traces)
+  data-snapshot/             # raw BanyanDB /data dir from Phase 0 (vec-off)
+  pprof-start/
+    heap-<unix>.pb.gz        # gzip pprof heap
+    goroutine-<unix>.txt     # goroutine dump (debug=1 text format)
+  pprof-<ts>/                # one directory per PPROF_INTERVAL tick
+  pprof-end/                 # final heap + goroutine before teardown
+  diff-<ts>.json             # one per PARITY_INTERVAL tick
+  diff-final.json            # final canonical parity report (sets FINAL_PASS)
+  banyand.log                # rotation-bounded BanyanDB stdout/stderr
+  memory-alerts.log          # lines matching budget|MemoryTracker|panic|vectorized
+  rss-trend.csv              # advisory: ts_utc, rss_bytes, disk_bytes
+  summary.json               # machine-readable run summary
+```
+
+#### `summary.json` fields (trace engine)
+
+```json
+{
+  "run_ts": "20240101T120000",
+  "engine": "trace",
+  "smoke": "false",
+  "warmup_min": 0,
+  "soak_hours": 48,
+  "t1_ms": 1704067200000,
+  "final_parity_pass": true,
+  "vec_flag_honored": true,
+  "goroutine_count_start": 120,
+  "goroutine_count_end": 122,
+  "memory_alert_lines": 0,
+  "write_load_spans": 8640000,
+  "write_load_alive": true,
+  "write_load_last_ok": "2024-01-03T11:59:00Z",
+  "heap_growth_max_pct_threshold": 10,
+  "banyandb_image_digest": "sha256:...",
+  "banyandb_cpu_nanocpu_limit": "2000000000",
+  "banyandb_memory_bytes_limit": "2147483648",
+  "soak_driver_image_digest": "sha256:...",
+  "artefacts_dir": "/path/to/dist/soak/<ts>"
+}
+```
+
+### Instrument 2 artifact
+
+`soak-trace-vec-result.json` — written to `DQB_REPORT_DIR` (default
+`.omx/bench-reports/distributed-query/`):
+
+```json
+{
+  "engine": "trace",
+  "iterations": 200,
+  "query_count_delta": 200,
+  "query_count_monotonic": true,
+  "liveness_pass": true,
+  "heap_inuse_baseline_bytes": 12345678,
+  "heap_inuse_end_bytes": 12500000,
+  "heap_growth_pct": 1.25,
+  "heap_growth_max_pct": 10,
+  "heap_leak_pass": true,
+  "budget_scenario_result_bound": true,
+  "budget_scenario_heap_pass": true,
+  "budget_scenario_pass": true
+}
+```
+
+## Reading the Artifacts
+
+### Quick all-green check
+
+```bash
+# Instrument 1: final parity + vec flag + write-load + alerts
+jq '{final_parity_pass, vec_flag_honored, write_load_alive, memory_alert_lines,
+     goroutine_count_start, goroutine_count_end}' dist/soak/<ts>/summary.json
+
+# Instrument 1: all intermediate diffs
+jq -r '.pass' dist/soak/<ts>/diff-*.json | sort | uniq -c
+
+# Instrument 2: all gates
+jq '{liveness_pass, heap_leak_pass, budget_scenario_pass, query_count_monotonic,
+     heap_growth_pct, heap_growth_max_pct}' \
+  .omx/bench-reports/distributed-query/soak-trace-vec-result.json
+```
+
+### Goroutine drift
+
+```bash
+# Ratio must be ≤ 1.05
+jq '{goroutine_count_start, goroutine_count_end}' dist/soak/<ts>/summary.json
+```
+
+If the ratio exceeds 1.05, diff the goroutine text files:
+
+```bash
+diff dist/soak/<ts>/pprof-start/goroutine-*.txt \
+     dist/soak/<ts>/pprof-end/goroutine-*.txt | head -80
+```
+
+## Failure Modes
+
+### Parity divergence
+
+**Symptom**: any `diff-<ts>.json` has `"pass": false`; `summary.json`
+`"final_parity_pass"` is `false`.
+
+**Triage**:
+
+```bash
+jq '.divergences' dist/soak/<ts>/diff-<ts>.json
+```
+
+**Parity-FAIL disambiguation**: a divergence after Phase 1 could be caused by
+the vec reader or by a merge/data artifact on the Phase-1 data. To distinguish:
+
+```bash
+# Re-run the failing catalog query with vec-off on Phase-1 data:
+BANYANDB_VEC_ENABLED=false \
+  docker compose -f test/soak/docker-compose.soak.yaml up -d banyandb
+docker compose -f test/soak/docker-compose.soak.yaml run --rm soak-driver \
+  replay-and-diff --engine trace \
+  --addr banyandb:17912 \
+  --catalog /catalog/trace.json \
+  --baseline /artifacts/baseline.json \
+  --report /artifacts/diff-vec-off-debug.json
+```
+
+If `diff-vec-off-debug.json` also diverges, the cause is in the
+data/merge path, not the vec reader. If it passes, the vec reader is at fault.
+
+### Memory-alert lines
+
+**Symptom**: `memory-alerts.log` is non-empty.
+
+**Action**: check `banyand.log` around the alert timestamp. The keywords that
+triggered the alert (`budget`, `MemoryTracker`, `panic`, `vectorized`) indicate
+which subsystem logged the event.
+
+### Goroutine leak
+
+**Symptom**: `goroutine_count_end / goroutine_count_start > 1.05`.
+
+**Action**: identify new goroutine stacks via the text diff above, then file a
+bug against the vectorized trace pipeline with the diff attached.
+
+### Instrument 2 liveness gate FAIL
+
+**Symptom**: `liveness_pass: false` — `query_count_delta < 200`.
+
+**Meaning**: the vec query path was not reached on every iteration. This can
+happen if the `--trace-vectorized-enabled` flag was not honored in-process, or
+if a dispatch branch fell through to the row path. Examine the test's `t.Log`
+output for iteration-level error messages.
+
+### Instrument 2 heap-leak gate FAIL
+
+**Symptom**: `heap_leak_pass: false` — `heap_growth_pct > heap_growth_max_pct`.
+
+**Action**: the cursor-release path is the primary suspect. Enable pprof in the
+test binary and compare heap profiles at warmup vs end; look for retained objects
+in `pkg/query/vectorized/trace`. File a bug with the heap diff attached.
+
+### OOMKill
+
+**Symptom**: a container disappears; `docker compose ps` shows it as `exited`.
+
+**Action**:
+
+```bash
+docker inspect banyandb | jq '.[].State.OOMKilled'
+```
+
+If `true`, BanyanDB exceeded its 2 GB memory limit. Do not increase the limit
+without re-evaluating the host budget. Consider reducing `SOAK_WRITE_RPS` or
+the `--trace-vectorized-query-memory-mib` value to reduce peak RSS.
+
+### Write-load stalled
+
+**Symptom**: `write_load_alive: false` or `write_load_spans: 0` in
+`summary.json`.
+
+**Action**: the write-load background loop logs `WARN` on each failed sweep.
+Check `run.log` for `WARN: parity divergence` or write-load sweep errors.
+A stall means no flush/merge/compaction stress during Phase 1.
+
+## Verification Steps
+
+1. **SMOKE (both instruments)**:
+   ```bash
+   SOAK_ENGINE=trace SMOKE=1 ./scripts/soak-vectorized.sh
+   DQB_SOAK=1 DQB_ENGINE=trace ./test/integration/distributed/querybench/run-docker.sh --cpus 4 --memory 8g
+   ```
+   Both should complete without errors, `summary.json` should have
+   `final_parity_pass: true` and `vec_flag_honored: true`;
+   `soak-trace-vec-result.json` should have all pass fields `true`.
+
+2. **Parity has teeth** (negative control): inject one extra span into the
+   Phase-1 fixture and re-run `replay-and-diff` — `diff-final.json` must show
+   `"pass": false`.
+
+3. **Vec-engaged confirmation** (separate run): run the soak with a deliberately
+   divergent fixture (e.g. extra span on the vec-on side only) and confirm
+   `diff-final.json` FAILs. The parity-clean S=5 fixture cannot distinguish
+   vec-engaged from vec-silently-disabled by result content alone; this
+   divergent-fixture run corroborates the startup-log grep gate.
+
+4. **Measure regression**: `SOAK_ENGINE=measure SMOKE=1 ./scripts/soak-vectorized.sh`
+   must still pass unchanged (measure path is byte-for-byte unmodified).
+
+## Named v1 Gap — Production Distributed-Topology Soak
+
+Instrument 2 boots an in-process distributed cluster (liaison + data nodes) and
+incidentally exercises `EncodeTraceResultFrame` / `DecodeTraceResultFrame` and
+the liaison itersort merge path **for correctness** over in-process gRPC.
+
+What it does **not** cover:
+
+- Real network fan-out between separate OS processes or containers.
+- On-wire `BANYAND_TRACE_NATIVE_WIRE` frame behavior under real TCP.
+- Per-node container RSS and disk usage under production distributed load.
+- Multi-node OOM-kill behavior.
+
+This is the **named v1 gap**: a follow-up production distributed-topology soak
+covering real network fan-out, on-wire frames, and multi-node container RSS.
+The in-process wire/merge path is already covered for correctness; what remains
+is the production transport layer.
+
+## Rollback
+
+To re-run Phase 1 with vec disabled (reproducing baseline behavior):
+
+```bash
+BANYANDB_VEC_ENABLED=false \
+SOAK_DATA_DIR=./test/soak/data \
+docker compose -f test/soak/docker-compose.soak.yaml up -d banyandb
+```
+
+Tear down with:
+
+```bash
+docker compose -f test/soak/docker-compose.soak.yaml down -v
+```
diff --git a/pkg/query/executor/interface.go b/pkg/query/executor/interface.go
index 5aef8b14f..12d789509 100644
--- a/pkg/query/executor/interface.go
+++ b/pkg/query/executor/interface.go
@@ -27,11 +27,33 @@ import (
 	"github.com/apache/skywalking-banyandb/pkg/bus"
 	"github.com/apache/skywalking-banyandb/pkg/iter"
 	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
 )
 
 // StreamExecutionContext allows retrieving data through the stream module.
+//
+// QueryVectorized and VectorizedConfig are the vec-path additions: the former
+// yields a pull-based columnar scan source (the M3 vecScanSource), the latter
+// surfaces the engine-side --stream-vectorized-* configuration so the vec
+// dispatch can decide whether the flag is on.
 type StreamExecutionContext interface {
 	Query(ctx context.Context, opts model.StreamQueryOptions) (model.StreamQueryResult, error)
+	QueryVectorized(ctx context.Context, opts model.StreamQueryOptions) (StreamVecScanSource, error)
+	VectorizedConfig() vstream.VectorizedConfig
+}
+
+// StreamVecScanSource is the pull contract the vec scan source exposes: one
+// columnar batch per NextBatch, (nil, nil) at exhaustion, Release to free
+// resources. It mirrors banyand/stream's vecScanSource without importing it, so
+// the executor package stays free of a data-node dependency cycle.
+type StreamVecScanSource interface {
+	NextBatch(ctx context.Context) (*vectorized.RecordBatch, error)
+	// Schema returns the batch schema the source stamps on every batch it emits.
+	// The M4 SortedMerge validates batch.Schema by pointer identity, so the merge
+	// pipeline MUST be built with this exact schema, not a freshly-built one.
+	Schema() *vectorized.BatchSchema
+	Release()
 }
 
 // StreamExecutable allows querying in the stream schema.
@@ -40,6 +62,23 @@ type StreamExecutable interface {
 	Close()
 }
 
+// StreamVecExecutable is the optional capability a stream plan node exposes when
+// it can be executed through the native columnar (vectorized) path. The data-node
+// processor type-asserts the analyzed plan to this interface; a plan shape that
+// cannot be vectorized (multi-group merge, skipping filter, tag filter, etc.)
+// simply does not implement it, so the assertion fails and the row path runs.
+//
+// ExecuteVectorized returns the fully merged/deduped/limited columnar batches
+// (the M4 pipeline already applied) plus the batch schema, so both the
+// standalone egress and the data-node frame emit consume a single columnar
+// result.
+type StreamVecExecutable interface {
+	ExecuteVectorized(ctx context.Context) ([]*vectorized.RecordBatch, *vectorized.BatchSchema, error)
+	// ProjectionTags returns the projected tag families/names in projection order,
+	// so the egress builds the same tag families/tags the row path would.
+	ProjectionTags() []model.TagProjection
+}
+
 // MeasureExecutionContext allows retrieving data through the measure module.
 type MeasureExecutionContext interface {
 	Query(ctx context.Context, opts model.MeasureQueryOptions) (model.MeasureQueryResult, error)
diff --git a/pkg/query/logical/stream/stream_plan_distributed.go b/pkg/query/logical/stream/stream_plan_distributed.go
index c05d92ea8..da9f44a05 100644
--- a/pkg/query/logical/stream/stream_plan_distributed.go
+++ b/pkg/query/logical/stream/stream_plan_distributed.go
@@ -36,6 +36,10 @@ import (
 	"github.com/apache/skywalking-banyandb/pkg/query"
 	"github.com/apache/skywalking-banyandb/pkg/query/executor"
 	"github.com/apache/skywalking-banyandb/pkg/query/logical"
+	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
+	streamframe "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream/frame"
 )
 
 const defaultQueryTimeout = 5 * time.Second
@@ -168,13 +172,14 @@ func (t *distributedPlan) Execute(ctx context.Context) (ee []*streamv1.Element,
 			if d == nil {
 				continue
 			}
-			resp := d.(*streamv1.QueryResponse)
-			responseCount++
-			if span != nil {
-				span.AddSubTrace(resp.Trace)
+			elements, decodeErr := t.decodeNodeElements(d, span)
+			if decodeErr != nil {
+				allErr = multierr.Append(allErr, decodeErr)
+				continue
 			}
+			responseCount++
 			see = append(see,
-				newSortableElements(resp.Elements, t.sortByTime, t.sortTagSpec))
+				newSortableElements(elements, t.sortByTime, t.sortTagSpec))
 		}
 	}
 	iter := sort.NewItemIter(see, t.desc)
@@ -195,6 +200,62 @@ func (t *distributedPlan) Execute(ctx context.Context) (ee []*streamv1.Element,
 	return result, allErr
 }
 
+// decodeNodeElements converts a single node response into []*streamv1.Element,
+// accepting either the proto *streamv1.QueryResponse (flag-off / tracing / a data
+// node that has not rolled onto the vec path) or the native columnar frame
+// ([]byte, only when the raw wire mode is on). Both feed the SAME
+// sortableElements/comparableElement k-way merge + seen-dedup + distributedLimit
+// downstream, so mixed proto/frame bodies in one broadcast (rolling deploy) merge
+// correctly.
+func (t *distributedPlan) decodeNodeElements(d any, span *query.Span) ([]*streamv1.Element, error) {
+	switch payload := d.(type) {
+	case *streamv1.QueryResponse:
+		if span != nil {
+			span.AddSubTrace(payload.Trace)
+		}
+		return payload.Elements, nil
+	case []byte:
+		if !data.StreamWireModeRaw() {
+			return nil, fmt.Errorf("unexpected raw stream frame body while wire mode is off")
+		}
+		batch, decodeErr := streamframe.Decode(payload)
+		if decodeErr != nil {
+			return nil, fmt.Errorf("decode stream result frame: %w", decodeErr)
+		}
+		elements, buildErr := vstream.BuildElementsFromBatch(batch, projectionFromBatchSchema(batch))
+		if buildErr != nil {
+			return nil, fmt.Errorf("build elements from stream frame: %w", buildErr)
+		}
+		return elements, nil
+	default:
+		return nil, fmt.Errorf("unexpected stream query response type %T", d)
+	}
+}
+
+// projectionFromBatchSchema reconstructs the tag projection (family → names, in
+// column order) from a decoded batch's tag columns, so the frame egress names the
+// same tag families/tags the data node encoded.
+func projectionFromBatchSchema(batch *vectorized.RecordBatch) []model.TagProjection {
+	if batch == nil || batch.Schema == nil {
+		return nil
+	}
+	var projections []model.TagProjection
+	familyIdx := make(map[string]int)
+	for _, def := range batch.Schema.Columns {
+		if def.Role != vectorized.RoleTag {
+			continue
+		}
+		idx, ok := familyIdx[def.TagFamily]
+		if !ok {
+			idx = len(projections)
+			familyIdx[def.TagFamily] = idx
+			projections = append(projections, model.TagProjection{Family: def.TagFamily})
+		}
+		projections[idx].Names = append(projections[idx].Names, def.Name)
+	}
+	return projections
+}
+
 func (t *distributedPlan) String() string {
 	return fmt.Sprintf("distributed:%s", t.queryTemplate.String())
 }
diff --git a/pkg/query/logical/stream/stream_plan_distributed_vectorized_test.go b/pkg/query/logical/stream/stream_plan_distributed_vectorized_test.go
new file mode 100644
index 000000000..914e3c4f4
--- /dev/null
+++ b/pkg/query/logical/stream/stream_plan_distributed_vectorized_test.go
@@ -0,0 +1,207 @@
+// 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.
+
+package stream
+
+import (
+	"encoding/hex"
+	"testing"
+	"time"
+
+	"github.com/stretchr/testify/require"
+	"google.golang.org/protobuf/types/known/timestamppb"
+
+	"github.com/apache/skywalking-banyandb/api/data"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	streamv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/stream/v1"
+	"github.com/apache/skywalking-banyandb/pkg/convert"
+	"github.com/apache/skywalking-banyandb/pkg/iter/sort"
+	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
+	streamframe "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream/frame"
+)
+
+// nodeRow is one element on a simulated data node (time-ordered): (ts, elementID).
+type nodeRow struct {
+	ts        int64
+	elementID uint64
+}
+
+func hexElementID(id uint64) string {
+	return hex.EncodeToString(convert.Uint64ToBytes(id))
+}
+
+// buildNodeBatch builds a columnar batch for a set of rows using the (no-tag,
+// no-order-key) time-order schema, so the frame round-trips through the stream
+// codec exactly as a data node would emit it.
+func buildNodeBatch(schema *vectorized.BatchSchema, rows []nodeRow) *vectorized.RecordBatch {
+	b := vectorized.NewRecordBatch(schema, len(rows))
+	ts := b.Columns[schema.TimestampIndex()].(*vectorized.TypedColumn[int64])
+	eid := b.Columns[schema.ElementIDIndex()].(*vectorized.TypedColumn[int64])
+	sid := b.Columns[schema.SeriesIDIndex()].(*vectorized.TypedColumn[int64])
+	for _, r := range rows {
+		ts.Append(r.ts)
+		eid.Append(vstream.ElementIDToColumn(r.elementID))
+		sid.Append(vstream.SeriesIDToColumn(0))
+	}
+	b.Len = len(rows)
+	return b
+}
+
+// protoResponseForRows builds a *streamv1.QueryResponse mirroring the same rows,
+// so a node can present either a proto body or a frame body for the same data.
+func protoResponseForRows(rows []nodeRow) *streamv1.QueryResponse {
+	elements := make([]*streamv1.Element, 0, len(rows))
+	for _, r := range rows {
+		elements = append(elements, &streamv1.Element{
+			Timestamp: timestamppb.New(time.Unix(0, r.ts)),
+			ElementId: hexElementID(r.elementID),
+		})
+	}
+	return &streamv1.QueryResponse{Elements: elements}
+}
+
+// runLiaisonMerge reproduces distributedPlan.Execute's post-broadcast merge over
+// a set of pre-decoded node responses: decode each (proto or []byte frame) via
+// decodeNodeElements, k-way merge by time, first-seen dedup by ElementId, then the
+// distributedLimit offset:offset+limit slice. It is the exact production merge
+// stack minus the Broadcaster.
+func runLiaisonMerge(t *testing.T, plan *distributedPlan, nodeResponses []any, offset, limit uint32) []*streamv1.Element {
+	t.Helper()
+	var see []sort.Iterator[*comparableElement]
+	for _, d := range nodeResponses {
+		elements, decErr := plan.decodeNodeElements(d, nil)
+		require.NoError(t, decErr)
+		see = append(see, newSortableElements(elements, plan.sortByTime, plan.sortTagSpec))
+	}
+	iter := sort.NewItemIter(see, plan.desc)
+	var merged []*streamv1.Element
+	seen := make(map[string]bool)
+	for iter.Next() {
+		element := iter.Val().Element
+		if !seen[element.ElementId] {
+			seen[element.ElementId] = true
+			merged = append(merged, element)
+		}
+	}
+	start := int(offset)
+	if start > len(merged) {
+		return []*streamv1.Element{}
+	}
+	end := start + int(limit)
+	if end > len(merged) {
+		end = len(merged)
+	}
+	return merged[start:end]
+}
+
+func elementIDSeq(elements []*streamv1.Element) []string {
+	out := make([]string, len(elements))
+	for i, e := range elements {
+		out[i] = e.ElementId
+	}
+	return out
+}
+
+// TestLiaisonMerge_MixedProtoAndFrame_MatchesAllProto is the M6 liaison
+// decode+merge unit test. Three data nodes each present a set of rows; one node's
+// body is a native columnar frame ([]byte), the others are proto responses. The
+// merged/deduped/limited result (with offset>0 and cross-node duplicate
+// ElementIDs) MUST be identical to feeding the equivalent all-proto bodies.
+//
+// This is a UNIT-level test of the liaison merge stack (decodeNodeElements +
+// k-way merge + seen-dedup + distributedLimit). A full multi-data-node broadcast
+// harness is out of scope in-session; see the report notes.
+func TestLiaisonMerge_MixedProtoAndFrame_MatchesAllProto(t *testing.T) {
+	data.SetStreamWireModeRaw(true)
+	defer data.SetStreamWireModeRaw(false)
+
+	// Time-order schema, no tags / no order key — matches a projection-free query.
+	schema := vstream.BuildStreamBatchSchema(nil, "", "")
+
+	// Node A and Node C share elementID 100 (cross-node duplicate); first-seen in
+	// time order must win. Timestamps interleave across nodes to exercise the merge.
+	nodeA := []nodeRow{{ts: 10, elementID: 100}, {ts: 40, elementID: 101}}
+	nodeB := []nodeRow{{ts: 20, elementID: 200}, {ts: 50, elementID: 201}}
+	nodeC := []nodeRow{{ts: 30, elementID: 100}, {ts: 60, elementID: 300}}
+
+	plan := &distributedPlan{sortByTime: true}
+
+	// Encode node B as a native frame; A and C stay proto (mixed rolling deploy).
+	frameB, encErr := streamframe.Encode(buildNodeBatch(schema, nodeB))
+	require.NoError(t, encErr)
+
+	const offset, limit = uint32(1), uint32(3)
+
+	mixed := []any{
+		protoResponseForRows(nodeA),
+		frameB,
+		protoResponseForRows(nodeC),
+	}
+	allProto := []any{
+		protoResponseForRows(nodeA),
+		protoResponseForRows(nodeB),
+		protoResponseForRows(nodeC),
+	}
+
+	mixedResult := runLiaisonMerge(t, plan, mixed, offset, limit)
+	protoResult := runLiaisonMerge(t, plan, allProto, offset, limit)
+
+	require.Equal(t, elementIDSeq(protoResult), elementIDSeq(mixedResult),
+		"mixed proto/frame merge diverged from all-proto merge")
+
+	// Sanity: the merged full order is 100(ts10),200(ts20),[100@ts30 dropped dup],
+	// 101(ts40),201(ts50),300(ts60) → deduped [100,200,101,201,300]; offset 1 limit
+	// 3 → [200,101,201].
+	require.Equal(t, []string{
+		hexElementID(200), hexElementID(101), hexElementID(201),
+	}, elementIDSeq(mixedResult))
+}
+
+// TestLiaisonMerge_FrameDecodeProducesProjectedTags verifies that a frame carrying
+// projected tag columns decodes back into Elements with the same tag families/tags
+// the proto path would carry, so mixed-body merges stay value-identical.
+func TestLiaisonMerge_FrameDecodeProducesProjectedTags(t *testing.T) {
+	data.SetStreamWireModeRaw(true)
+	defer data.SetStreamWireModeRaw(false)
+
+	proj := []model.TagProjection{{Family: "fam", Names: []string{"svc"}}}
+	schema := vstream.BuildStreamBatchSchema(proj, "", "")
+	b := vectorized.NewRecordBatch(schema, 1)
+	b.Columns[schema.TimestampIndex()].(*vectorized.TypedColumn[int64]).Append(10)
+	b.Columns[schema.ElementIDIndex()].(*vectorized.TypedColumn[int64]).Append(vstream.ElementIDToColumn(7))
+	b.Columns[schema.SeriesIDIndex()].(*vectorized.TypedColumn[int64]).Append(vstream.SeriesIDToColumn(0))
+	tagColIdx, ok := schema.TagIndex("fam", "svc")
+	require.True(t, ok)
+	b.Columns[tagColIdx].(*vectorized.TypedColumn[*modelv1.TagValue]).Append(
+		&modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: "svc-A"}}})
+	b.Len = 1
+
+	frame, encErr := streamframe.Encode(b)
+	require.NoError(t, encErr)
+
+	plan := &distributedPlan{sortByTime: true}
+	elements, decErr := plan.decodeNodeElements(frame, nil)
+	require.NoError(t, decErr)
+	require.Len(t, elements, 1)
+	require.Equal(t, hexElementID(7), elements[0].ElementId)
+	require.Len(t, elements[0].TagFamilies, 1)
+	require.Equal(t, "fam", elements[0].TagFamilies[0].Name)
+	require.Equal(t, "svc", elements[0].TagFamilies[0].Tags[0].Key)
+	require.Equal(t, "svc-A", elements[0].TagFamilies[0].Tags[0].Value.GetStr().GetValue())
+}
diff --git a/pkg/query/logical/stream/stream_plan_indexscan_local.go b/pkg/query/logical/stream/stream_plan_indexscan_local.go
index 2baeb9b25..83de1c4b8 100644
--- a/pkg/query/logical/stream/stream_plan_indexscan_local.go
+++ b/pkg/query/logical/stream/stream_plan_indexscan_local.go
@@ -59,6 +59,14 @@ type localIndexScan struct {
 	projectionTags    []model.TagProjection
 	entities          [][]*modelv1.TagValue
 	maxElementSize    int
+	// deferLimitToEgress is set when this scan is wrapped by a tagFilterPlan (a
+	// criteria query). A non-indexed tag filter is applied AFTER the scan at egress,
+	// so a maxElementSize cap inside the vec merge would truncate the ordered set
+	// BEFORE the filter runs and starve it (row-path divergence: the row scan streams
+	// the whole ordered set in chunks and the filter/limit loops pull as many batches
+	// as needed). When set, ExecuteVectorized runs the merge UNCAPPED and the egress
+	// applies filter → then the client offset:offset+limit slice.
+	deferLimitToEgress bool
 }
 
 func (i *localIndexScan) Close() {
diff --git a/pkg/query/logical/stream/stream_plan_indexscan_local_vectorized.go b/pkg/query/logical/stream/stream_plan_indexscan_local_vectorized.go
new file mode 100644
index 000000000..11b5ec3e0
--- /dev/null
+++ b/pkg/query/logical/stream/stream_plan_indexscan_local_vectorized.go
@@ -0,0 +1,390 @@
+// 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.
+
+package stream
+
+import (
+	"context"
+	"math"
+
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	"github.com/apache/skywalking-banyandb/pkg/index"
+	"github.com/apache/skywalking-banyandb/pkg/query/executor"
+	"github.com/apache/skywalking-banyandb/pkg/query/logical"
+	"github.com/apache/skywalking-banyandb/pkg/query/model"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	vstream "github.com/apache/skywalking-banyandb/pkg/query/vectorized/stream"
+)
+
+var _ executor.StreamVecExecutable = (*localIndexScan)(nil)
+
+// VecExecutable returns the vec-eligible StreamVecExecutable at the scan position
+// of the analyzed plan, or nil when the plan cannot be vectorized.
+//
+// Eligibility: the plan top is the *limit node (stream_analyzer.go:86); its Input
+// must resolve to a *localIndexScan — either directly (no criteria) or wrapped in a
+// *tagFilterPlan (criteria query, stream_plan_tag_filter.go). For the tag-filter
+// case the inner scan already projects the criteria + hidden tags and pushes the
+// INDEXED criteria into its sqo (invertedFilter/skippingFilter); the caller then
+// applies the SAME per-element tagFilter.Match + hidden-tag strip that
+// tagFilterPlan.Execute does (via VecTagFilter) so the result is byte-identical to
+// the row path. A multi-group merger or any other shape does not resolve to a
+// *localIndexScan, so we decline and the caller runs the row path.
+func VecExecutable(plan logical.Plan) executor.StreamVecExecutable {
+	l, ok := plan.(*limit)
+	if !ok {
+		return nil
+	}
+	scan := scanFromInput(l.Input)
+	if scan == nil {
+		return nil
+	}
+	// An index-order query sorts by an indexed tag. The vec merge keys on the
+	// OrderKey column, which is populated from the ordered tag's PROJECTED cell
+	// (resolveOrderTag). If the ordered tag is not in the projection, there is no
+	// cell to derive the key from, so the OrderKey column would be empty and the
+	// merge would silently fall back to timestamp order — a wrong result. The row
+	// path sorts via the inverted index regardless of projection, so decline vec
+	// here and let the caller run the row path (correct order).
+	if !scan.orderTagProjected() {
+		return nil
+	}
+	return scan
+}
+
+// scanFromInput resolves the *localIndexScan at the input of the *limit node,
+// unwrapping a *tagFilterPlan (criteria query) whose parent is the scan. Returns
+// nil for any other shape (e.g. a multi-group merger).
+func scanFromInput(input logical.Plan) *localIndexScan {
+	switch in := input.(type) {
+	case *localIndexScan:
+		return in
+	case *tagFilterPlan:
+		if scan, ok := in.parent.(*localIndexScan); ok {
+			// A criteria query applies the tag filter at egress, AFTER the scan, so the
+			// vec merge must reproduce exactly the element set the row scan would hand
+			// its tagFilterPlan. Where the row scan caps depends on the order type —
+			// see scanResumesAcrossPulls.
+			scan.deferLimitToEgress = scanResumesAcrossPulls(scan)
+			return scan
+		}
+	}
+	return nil
+}
+
+// scanResumesAcrossPulls reports whether the row scan backing this plan keeps
+// yielding new elements on successive Pulls, which decides where the vec merge may
+// cap for a criteria (filtered) query.
+//
+// The row path nests three loops: *limit.Execute pulls tagFilterPlan.Execute until
+// it has accumulated limit+offset elements, tagFilterPlan.Execute pulls the scan
+// until a batch yields ≥1 match, and the scan itself caps each batch at
+// maxElementSize. Whether the limit actually gets FILLED therefore depends on the
+// scan resuming:
+//
+//   - index-order (idxResult): the sorted iterator persists across Pulls and each
+//     Pull drains the next maxElementSize entries (query_by_idx.go:262), so row keeps
+//     pulling and DOES fill the limit. The vec merge must stay uncapped, letting the
+//     egress filter the whole ordered set and then apply the limit.
+//   - timestamp order (tsResult): one Pull consumes a whole segment and caps the
+//     result at maxElementSize (query_by_ts.go:136,159); the next Pull only advances
+//     to a further segment. For data inside a single segment the scan is then
+//     exhausted, so row returns only the matches from that first capped batch and
+//     legitimately UNDER-fills the limit (e.g. 30 scanned, 2 rejected ⇒ 28 returned).
+//     The vec merge must cap at maxElementSize to reproduce that same input set.
+//
+// Caveat (documented, not emulated): for timestamp order spanning MULTIPLE segments
+// the row scan does resume per segment, so row could accumulate past the first
+// capped batch where vec stops. Reproducing that needs the scan's segment
+// boundaries, which the vec merge does not see.
+func scanResumesAcrossPulls(scan *localIndexScan) bool {
+	return scan.order != nil && scan.order.Index != nil
+}
+
+// VecTagFilter returns the criteria tag filter, the hidden-tag set, and the schema
+// carried by the *limit plan's *tagFilterPlan input, so the standalone vec egress
+// can apply the SAME per-element tagFilter.Match + hidden-tag strip that the row
+// path's tagFilterPlan.Execute applies. Returns ok=false when the plan is not the
+// *limit → *tagFilterPlan shape (a criteria-less query needs no post-filter).
+func VecTagFilter(plan logical.Plan) (tagFilter logical.TagFilter, hiddenTags logical.HiddenTagSet, schema logical.Schema, ok bool) {
+	l, isLimit := plan.(*limit)
+	if !isLimit {
+		return nil, nil, nil, false
+	}
+	return nodeTagFilter(l.Input)
+}
+
+// nodeTagFilter returns the per-node tag filter, hidden-tag set, and schema when
+// plan is a *tagFilterPlan (a criteria group), else ok=false. It operates on a
+// plan NODE directly (not the *limit wrapper), so both the single-group VecTagFilter
+// (via l.Input) and the multi-group dispatch (via each mergePlan subPlan) share the
+// same extraction — the vec egress then applies the SAME per-element
+// tagFilter.Match + hidden-tag strip that the row tagFilterPlan.Execute applies.
+func nodeTagFilter(plan logical.Plan) (tagFilter logical.TagFilter, hiddenTags logical.HiddenTagSet, schema logical.Schema, ok bool) {
+	tf, isTagFilter := plan.(*tagFilterPlan)
+	if !isTagFilter {
+		return nil, nil, nil, false
+	}
+	return tf.tagFilter, tf.hiddenTags, tf.s, true
+}
+
+// VecMergeGroup is one group's resolved vec scan plus its optional per-element
+// tag filter, for the multi-group dispatch. The processor runs Scan.ExecuteVectorized
+// → BuildElementsFromBatches → (if HasFilter) applyStreamTagFilter, yielding that
+// group's ordered []Element; the caller then cross-group merges via MergeGroupElements.
+type VecMergeGroup struct {
+	Scan         executor.StreamVecExecutable
+	TagFilter    logical.TagFilter
+	HiddenTags   logical.HiddenTagSet
+	FilterSchema logical.Schema
+	HasFilter    bool
+}
+
+// VecMerge is the vec-eligible form of a multi-group query (*limit → *mergePlan).
+// It carries each group's resolved vec node plus the EXACT merge params the row
+// mergePlan.Execute uses (SortByTime, SortTagSpec, Desc), so the dispatch merges
+// across groups via the shared MergeGroupElements and slices with Offset/Limit.
+type VecMerge struct {
+	SortTagSpec logical.TagSpec
+	Groups      []VecMergeGroup
+	Offset      uint32
+	Limit       uint32
+	SortByTime  bool
+	Desc        bool
+}
+
+// VecMergeExecutable returns the vec-eligible multi-group form when the plan is
+// *limit → *mergePlan and EVERY subPlan resolves to a vec-eligible *localIndexScan
+// (via scanFromInput, incl. orderTagProjected). If ANY subPlan is not vec-eligible,
+// it returns ok=false so the whole query runs the row path — vec and row are never
+// mixed across groups. The merge params (sortByTime/sortTagSpec/desc) are taken
+// verbatim from the mergePlan so the cross-group order matches the row path exactly.
+func VecMergeExecutable(plan logical.Plan) (*VecMerge, bool) {
+	l, isLimit := plan.(*limit)
+	if !isLimit {
+		return nil, false
+	}
+	mp, isMerge := l.Input.(*mergePlan)
+	if !isMerge {
+		return nil, false
+	}
+	groups := make([]VecMergeGroup, 0, len(mp.subPlans))
+	for _, sp := range mp.subPlans {
+		scan := scanFromInput(sp)
+		if scan == nil || !scan.orderTagProjected() {
+			return nil, false
+		}
+		filter, hidden, filterSchema, hasFilter := nodeTagFilter(sp)
+		groups = append(groups, VecMergeGroup{
+			Scan:         scan,
+			TagFilter:    filter,
+			HiddenTags:   hidden,
+			FilterSchema: filterSchema,
+			HasFilter:    hasFilter,
+		})
+	}
+	return &VecMerge{
+		Groups:      groups,
+		SortByTime:  mp.sortByTime,
+		SortTagSpec: mp.sortTagSpec,
+		Desc:        mp.desc,
+		Offset:      l.offsetNum,
+		Limit:       l.limitNum,
+	}, true
+}
+
+// orderTagProjected reports whether an index-order query's single ordered tag is
+// present in the scan's tag projection (so the vec OrderKey column can be
+// populated). It is true for non-index-order queries (they key on timestamp, no
+// ordered tag needed) and for the degenerate order shapes vec does not treat as
+// index-order (no Index, or not exactly one ordered tag).
+func (i *localIndexScan) orderTagProjected() bool {
+	if i.order == nil || i.order.Index == nil {
+		return true
+	}
+	tags := i.order.Index.GetTags()
+	if len(tags) != 1 {
+		return true
+	}
+	name := tags[0]
+	for _, proj := range i.projectionTags {
+		for _, projName := range proj.Names {
+			if projName == name {
+				return true
+			}
+		}
+	}
+	return false
+}
+
+// VecOffsetLimit returns the client offset/limit the *limit plan node carries, so
+// the standalone vec egress can apply the same offset:offset+limit slice the row
+// *limit.Execute would apply. Returns ok=false when plan is not the *limit shape.
+func VecOffsetLimit(plan logical.Plan) (offsetNum, limitNum uint32, ok bool) {
+	l, isLimit := plan.(*limit)
+	if !isLimit {
+		return 0, 0, false
+	}
+	return l.offsetNum, l.limitNum, true
+}
+
+// ExecuteVectorized runs the localIndexScan through the native columnar path. It
+// builds the SAME model.StreamQueryOptions the row-path Execute passes to
+// ec.Query, calls ec.QueryVectorized instead, then drives the M4
+// merge → distinct → limit pipeline and drains it into columnar batches.
+//
+// The offset/limit split matches the row path: the localIndexScan's
+// maxElementSize is already limit+offset (PushDownMaxSize at
+// stream_analyzer.go:94), and the enclosing *limit node applies the final
+// offset:offset+limit slice at egress. For a criteria-less query the vec pipeline
+// caps at maxElementSize (offset 0, limit=maxElementSize) exactly like the
+// scan-level cap, and the outer limit node trims — no double offset. For a criteria
+// query (deferLimitToEgress) the merge runs UNCAPPED and the egress applies the tag
+// filter before the outer offset:offset+limit slice, so the filter is never starved
+// by a premature cap (row-path parity — the row scan streams the whole ordered set).
+func (i *localIndexScan) ExecuteVectorized(ctx context.Context) ([]*vectorized.RecordBatch, *vectorized.BatchSchema, error) {
+	select {
+	case <-ctx.Done():
+		return nil, nil, ctx.Err()
+	default:
+	}
+	// Reaching ExecuteVectorized means the dispatch chose the vec path for this
+	// query (VecExecutable returned non-nil). Count it so integration tests can
+	// assert the vec path actually fired rather than silently falling back to row.
+	vstream.IncrQueryCount()
+
+	var orderBy *index.OrderBy
+	if i.order != nil {
+		orderBy = &index.OrderBy{
+			Index: i.order.Index,
+			Sort:  i.order.Sort,
+		}
+	}
+	source, err := i.ec.QueryVectorized(ctx, model.StreamQueryOptions{
+		Name:           i.metadata.GetName(),
+		TimeRange:      &i.timeRange,
+		Entities:       i.entities,
+		InvertedFilter: i.invertedFilter,
+		SkippingFilter: i.skippingFilter,
+		Order:          orderBy,
+		TagProjection:  i.projectionTags,
+		MaxElementSize: i.maxElementSize,
+	})
+	if err != nil {
+		return nil, nil, err
+	}
+	if source == nil {
+		return nil, nil, nil
+	}
+
+	// The M4 SortedMerge validates batch.Schema by pointer identity, so the merge
+	// pipeline MUST use the exact schema the source stamps on its batches — not a
+	// freshly-built one that would be a "foreign" pointer.
+	schema := source.Schema()
+
+	cfg := i.ec.VectorizedConfig()
+	batchSize := cfg.BatchSize
+	if batchSize <= 0 {
+		batchSize = vectorized.DefaultBatchSize
+	}
+	desc := i.order != nil && i.order.Sort == modelv1.Sort_SORT_DESC
+
+	// The per-node request cap (maxElementSize = limit+offset) bounds the total
+	// rows the merge produces; it is applied INSIDE the merge (in-order top-N by
+	// distinct ElementID) so the cap keeps the correct rows in sort order, matching
+	// the row path's cap after its in-order heap merge. The trailing Limit still
+	// applies the SAME limit with offset 0 as a defensive client slice; the final
+	// client offset:offset+limit slice is the enclosing *limit node's job (row path
+	// parity).
+	// A criteria query applies a tag filter at egress AFTER this merge. Capping the
+	// merge at maxElementSize here would keep only the top-N BEFORE the filter runs
+	// and starve it (the row path streams the whole ordered set and filters lazily).
+	// So defer the cap to the egress: run the merge UNCAPPED (mergeCap 0) and make the
+	// trailing pipeline Limit a pass-through (MaxUint32, since a 0 limit emits
+	// NOTHING) — the egress then applies the tag filter and the true
+	// offset:offset+limit slice.
+	limitRows := uint32(0)
+	mergeCap := i.maxElementSize
+	if i.deferLimitToEgress {
+		mergeCap = 0
+		limitRows = math.MaxUint32
+	} else if i.maxElementSize > 0 {
+		limitRows = uint32(i.maxElementSize)
+	}
+
+	pipeline, buildErr := vstream.BuildStreamMergePipeline(
+		&vecSourceOperator{source: source, schema: schema},
+		schema, desc, 0, limitRows, batchSize, mergeCap)
+	if buildErr != nil {
+		source.Release()
+		return nil, nil, buildErr
+	}
+	defer func() {
+		_ = pipeline.Close()
+	}()
+
+	if initErr := pipeline.Init(ctx); initErr != nil {
+		return nil, nil, initErr
+	}
+
+	var batches []*vectorized.RecordBatch
+	for {
+		batch, nextErr := pipeline.Next(ctx)
+		if nextErr != nil {
+			return nil, nil, nextErr
+		}
+		if batch == nil {
+			break
+		}
+		if batch.ActiveLen() == 0 {
+			continue
+		}
+		batches = append(batches, batch)
+	}
+	return batches, schema, nil
+}
+
+// ProjectionTags returns the projected tag families/names for the egress.
+func (i *localIndexScan) ProjectionTags() []model.TagProjection {
+	return i.projectionTags
+}
+
+// vecSourceOperator adapts an executor.StreamVecScanSource (NextBatch/Release)
+// into a vectorized.PullOperator so it can drive the M4 pipeline. Init is a
+// no-op; Close releases the underlying source exactly once.
+type vecSourceOperator struct {
+	source executor.StreamVecScanSource
+	schema *vectorized.BatchSchema
+	closed bool
+}
+
+func (o *vecSourceOperator) Init(context.Context) error { return nil }
+
+func (o *vecSourceOperator) OutputSchema() *vectorized.BatchSchema { return o.schema }
+
+func (o *vecSourceOperator) NextBatch(ctx context.Context) (*vectorized.RecordBatch, error) {
+	return o.source.NextBatch(ctx)
+}
+
+func (o *vecSourceOperator) Close() error {
+	if o.closed {
+		return nil
+	}
+	o.closed = true
+	o.source.Release()
+	return nil
+}
diff --git a/pkg/query/logical/stream/stream_plan_indexscan_local_vectorized_test.go b/pkg/query/logical/stream/stream_plan_indexscan_local_vectorized_test.go
new file mode 100644
index 000000000..f407f0619
--- /dev/null
+++ b/pkg/query/logical/stream/stream_plan_indexscan_local_vectorized_test.go
@@ -0,0 +1,133 @@
+// 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.
+
+package stream
+
+import (
+	"testing"
+
+	"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"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	"github.com/apache/skywalking-banyandb/pkg/query/logical"
+	"github.com/apache/skywalking-banyandb/pkg/query/model"
+)
+
+// newVecEligiblePlan builds a minimal *limit → *localIndexScan plan (the only
+// vec-eligible shape) with the given order and tag projection so VecExecutable's
+// eligibility decision can be exercised in isolation.
+func newVecEligiblePlan(order *logical.OrderBy, projection []model.TagProjection) logical.Plan {
+	scan := &localIndexScan{order: order, projectionTags: projection}
+	return &limit{Parent: &Parent{Input: scan}}
+}
+
+// TestVecExecutable_IndexOrder_TagNotProjected_DeclinesVec is the H2 regression:
+// an index-order query whose sort tag is NOT in the projection cannot populate the
+// vec OrderKey column, so the vec merge would silently fall back to timestamp
+// order (wrong result). VecExecutable must DECLINE (return nil) so the engine runs
+// the row path, which sorts via the inverted index regardless of projection.
+func TestVecExecutable_IndexOrder_TagNotProjected_DeclinesVec(t *testing.T) {
+	order := &logical.OrderBy{
+		Index: &databasev1.IndexRule{
+			Metadata: &commonv1.Metadata{Name: "by-status"},
+			Tags:     []string{"status"},
+		},
+		Sort: modelv1.Sort_SORT_ASC,
+	}
+	// The ordered tag "status" is absent from the projection.
+	projection := []model.TagProjection{{Family: "searchable", Names: []string{"service", "endpoint"}}}
+	plan := newVecEligiblePlan(order, projection)
+
+	require.Nil(t, VecExecutable(plan),
+		"vec must decline an index-order query whose sort tag is not projected")
+}
+
+// TestVecExecutable_IndexOrder_TagProjected_AcceptsVec is the positive control:
+// when the ordered tag IS projected, the OrderKey column can be populated, so vec
+// is eligible and VecExecutable returns the scan.
+func TestVecExecutable_IndexOrder_TagProjected_AcceptsVec(t *testing.T) {
+	order := &logical.OrderBy{
+		Index: &databasev1.IndexRule{
+			Metadata: &commonv1.Metadata{Name: "by-status"},
+			Tags:     []string{"status"},
+		},
+		Sort: modelv1.Sort_SORT_ASC,
+	}
+	projection := []model.TagProjection{{Family: "searchable", Names: []string{"service", "status"}}}
+	plan := newVecEligiblePlan(order, projection)
+
+	require.NotNil(t, VecExecutable(plan),
+		"vec must accept an index-order query whose sort tag is projected")
+}
+
+// TestVecExecutable_TimeOrder_AcceptsVec confirms non-index-order (time-order)
+// queries are unaffected by the H2 projection check: they key on timestamp, need
+// no ordered tag, and remain vec-eligible regardless of projection.
+func TestVecExecutable_TimeOrder_AcceptsVec(t *testing.T) {
+	order := &logical.OrderBy{Sort: modelv1.Sort_SORT_DESC}
+	projection := []model.TagProjection{{Family: "searchable", Names: []string{"service"}}}
+	plan := newVecEligiblePlan(order, projection)
+
+	require.NotNil(t, VecExecutable(plan),
+		"vec must accept a time-order query regardless of projection")
+}
+
+// newVecFilteredPlan builds the criteria shape *limit → *tagFilterPlan →
+// *localIndexScan so scanFromInput's cap decision can be exercised directly.
+func newVecFilteredPlan(order *logical.OrderBy, projection []model.TagProjection) (logical.Plan, *localIndexScan) {
+	scan := &localIndexScan{order: order, projectionTags: projection}
+	filter := &tagFilterPlan{parent: scan, tagFilter: logical.DummyFilter, hiddenTags: logical.HiddenTagSet{}}
+	return &limit{Parent: &Parent{Input: filter}}, scan
+}
+
+// TestScanCap_FilteredTimeOrder_CapsMerge locks the row-parity rule a stream soak
+// exposed. For TIMESTAMP order, one row Pull consumes a segment and caps at
+// maxElementSize, and the following Pull only advances to a further segment — so
+// within a segment the row scan is exhausted and row returns just that first capped
+// batch's matches (30 scanned, 2 rejected ⇒ 28, NOT a filled limit of 30). The vec
+// merge must therefore CAP, feeding the egress filter the same element set.
+func TestScanCap_FilteredTimeOrder_CapsMerge(t *testing.T) {
+	projection := []model.TagProjection{{Family: "searchable", Names: []string{"service", "state"}}}
+	plan, scan := newVecFilteredPlan(nil, projection)
+
+	require.NotNil(t, VecExecutable(plan), "a filtered time-order query is vec-eligible")
+	require.False(t, scan.deferLimitToEgress,
+		"time-order scans do not resume within a segment, so the vec merge must cap at maxElementSize to match row")
+}
+
+// TestScanCap_FilteredIndexOrder_DefersLimit is the other arm: for INDEX order the
+// sorted iterator persists across Pulls (each drains the next maxElementSize
+// entries), so row keeps pulling and DOES fill the limit. Capping the vec merge
+// there would starve the filter and under-return; the merge must stay uncapped and
+// let the egress filter the whole ordered set before the limit slice.
+func TestScanCap_FilteredIndexOrder_DefersLimit(t *testing.T) {
+	order := &logical.OrderBy{
+		Index: &databasev1.IndexRule{
+			Metadata: &commonv1.Metadata{Name: "duration"},
+			Tags:     []string{"duration"},
+		},
+		Sort: modelv1.Sort_SORT_DESC,
+	}
+	projection := []model.TagProjection{{Family: "searchable", Names: []string{"duration", "span_id"}}}
+	plan, scan := newVecFilteredPlan(order, projection)
+
+	require.NotNil(t, VecExecutable(plan), "a filtered index-order query with the sort tag projected is vec-eligible")
+	require.True(t, scan.deferLimitToEgress,
+		"index-order scans resume across Pulls, so the vec merge must stay uncapped to match row filling the limit")
+}
diff --git a/pkg/query/logical/stream/stream_plan_merge.go b/pkg/query/logical/stream/stream_plan_merge.go
index b1eda4d55..b130a447f 100644
--- a/pkg/query/logical/stream/stream_plan_merge.go
+++ b/pkg/query/logical/stream/stream_plan_merge.go
@@ -126,7 +126,7 @@ func (m *mergePlan) Close() {
 // Execute implements executor.StreamExecutable.
 func (m *mergePlan) Execute(ctx context.Context) ([]*streamv1.Element, error) {
 	var allErr error
-	var see []sort.Iterator[*comparableElement]
+	perGroup := make([][]*streamv1.Element, 0, len(m.subPlans))
 
 	for _, sp := range m.subPlans {
 		elements, err := sp.(executor.StreamExecutable).Execute(ctx)
@@ -134,18 +134,29 @@ func (m *mergePlan) Execute(ctx context.Context) ([]*streamv1.Element, error) {
 			allErr = multierr.Append(allErr, err)
 			continue
 		}
-
-		iter := newSortableElements(elements, m.sortByTime, m.sortTagSpec)
-		see = append(see, iter)
+		perGroup = append(perGroup, elements)
 	}
 
-	iter := sort.NewItemIter(see, m.desc)
+	return MergeGroupElements(perGroup, m.sortByTime, m.sortTagSpec, m.desc), allErr
+}
+
+// MergeGroupElements k-way merges the per-group ordered element slices into a
+// single ordered slice, using the SAME comparableElement/sortableElements +
+// sort.NewItemIter primitives the row mergePlan.Execute uses. Both the row path
+// and the vec multi-group dispatch call this so cross-group ordering is
+// byte-identical (DRY). The merge is UNCAPPED — the caller applies the outer
+// offset:offset+limit slice.
+func MergeGroupElements(perGroup [][]*streamv1.Element, sortByTime bool, sortTagSpec logical.TagSpec, desc bool) []*streamv1.Element {
+	see := make([]sort.Iterator[*comparableElement], 0, len(perGroup))
+	for _, elements := range perGroup {
+		see = append(see, newSortableElements(elements, sortByTime, sortTagSpec))
+	}
+	iter := sort.NewItemIter(see, desc)
 	var result []*streamv1.Element
 	for iter.Next() {
 		result = append(result, iter.Val().Element)
 	}
-
-	return result, allErr
+	return result
 }
 
 // Children implements logical.Plan.
diff --git a/pkg/query/model/batch.go b/pkg/query/model/batch.go
index 0e663c082..18c06bace 100644
--- a/pkg/query/model/batch.go
+++ b/pkg/query/model/batch.go
@@ -140,8 +140,10 @@ func AcquireMeasureBatch(schema *vectorized.BatchSchema, capacity int) *MeasureB
 			case vectorized.RoleField:
 				b.Fields = append(b.Fields, vectorized.AcquireColumn(def.Type, capacity))
 			case vectorized.RoleTimestamp, vectorized.RoleVersion,
-				vectorized.RoleSeriesID, vectorized.RoleShardID:
-				// Metadata roles use the parallel slices on the batch.
+				vectorized.RoleSeriesID, vectorized.RoleShardID,
+				vectorized.RoleElementID, vectorized.RoleOrderKey:
+				// Metadata roles use the parallel slices on the batch. ElementID/OrderKey
+				// are stream-only roles that never appear in a measure schema.
 			}
 		}
 	}
diff --git a/pkg/query/vectorized/appendrange.go b/pkg/query/vectorized/appendrange.go
index d02bce608..dc5c600af 100644
--- a/pkg/query/vectorized/appendrange.go
+++ b/pkg/query/vectorized/appendrange.go
@@ -23,6 +23,38 @@ import (
 	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
 )
 
+// AppendActiveRows appends every active row of src (its Selection when present,
+// else all [0,Len) rows) onto dst, column by column, advancing dst.Len. dst and
+// src must share the same schema/column layout. It is the columnar analog of a
+// row-wise copy used to flatten a Selection-narrowed batch into a dense one (frame
+// emit) or to concatenate per-node batches (liaison merge).
+func AppendActiveRows(dst, src *RecordBatch) error {
+	if src == nil || src.ActiveLen() == 0 {
+		return nil
+	}
+	if len(dst.Columns) != len(src.Columns) {
+		return fmt.Errorf("AppendActiveRows: column count mismatch dst=%d src=%d", len(dst.Columns), len(src.Columns))
+	}
+	if src.Selection == nil {
+		for colIdx := range src.Columns {
+			if appendErr := AppendColumnRange(dst.Columns[colIdx], src.Columns[colIdx], 0, src.Len); appendErr != nil {
+				return appendErr
+			}
+		}
+		dst.Len += src.Len
+		return nil
+	}
+	for _, row := range src.Selection {
+		for colIdx := range src.Columns {
+			if appendErr := AppendColumnRange(dst.Columns[colIdx], src.Columns[colIdx], int(row), 1); appendErr != nil {
+				return appendErr
+			}
+		}
+	}
+	dst.Len += len(src.Selection)
+	return nil
+}
+
 // AppendColumnRange copies n rows starting at srcPos from src into dst.
 // Both columns must share the same TypedColumn[T] type. Validity bits are
 // propagated cell-by-cell via dst.MarkNullAt when src.IsNull reports null at
diff --git a/pkg/query/vectorized/measure/frame/decode.go b/pkg/query/vectorized/frame/decode.go
similarity index 67%
rename from pkg/query/vectorized/measure/frame/decode.go
rename to pkg/query/vectorized/frame/decode.go
index 98270271d..ff4a8cff4 100644
--- a/pkg/query/vectorized/measure/frame/decode.go
+++ b/pkg/query/vectorized/frame/decode.go
@@ -28,35 +28,27 @@ import (
 	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
 )
 
-// Decode is the inverse of Encode: it parses a vec columnar raw frame body
-// produced by Encode and returns an in-memory RecordBatch with the same
-// schema, columns and (active) rows. The returned batch's Selection is nil
-// and its Len equals the encoded NumRows — Encode discards inactive rows at
-// encode time, so the decoded batch carries only the rows that were on the
-// wire.
+// Decode is the inverse of Encode: it parses a raw frame body produced by the
+// same codec and returns an in-memory RecordBatch with the same schema, columns
+// and (active) rows. The returned batch's Selection is nil and its Len equals
+// the encoded NumRows.
 //
-// Decode is the load-bearing fail-loud guard for the G9f hard-cutover model
-// on the consumer side: ValidateHeader rejects bad magic / wire version
-// loudly before any column is touched, and the per-column readers reject
-// truncation, unknown role / type bytes, and varint underflows the same way.
-// There is no "lossy fallback" — under flag-on, this is the SOLE decode path
-// for TopicInternalMeasureQuery bodies, so a botched frame must surface as
-// an error, never as a silently-empty result.
+// Decode is the load-bearing fail-loud guard on the consumer side:
+// ValidateHeader rejects bad magic / wire version loudly before any column is
+// touched, and the per-column readers reject truncation, unknown role / type
+// bytes, and varint underflows the same way. There is no lossy fallback.
 //
-// A nil/empty body is rejected here with ErrTruncated. The codec-layer
-// carve-out for empty bodies (api/data/codec.go RawFrameCodec.Unmarshal —
-// nil/empty is a legitimate empty distributed result and is NOT magic-
-// validated) lives one level up; this function is below that carve-out and
-// expects a real frame.
-func Decode(b []byte) (*vectorized.RecordBatch, error) {
-	header, offset, headerErr := ValidateHeader(b)
+// A nil/empty body is rejected here with ErrTruncated; the codec-layer carve-out
+// for legitimately-empty distributed results lives one level up.
+func (c Codec) Decode(b []byte) (*vectorized.RecordBatch, error) {
+	header, offset, headerErr := c.ValidateHeader(b)
 	if headerErr != nil {
 		return nil, headerErr
 	}
 	defs := make([]vectorized.ColumnDef, 0, header.NumCols)
 	cols := make([]vectorized.Column, 0, header.NumCols)
 	for colIdx := range header.NumCols {
-		def, col, consumed, colErr := decodeColumn(b[offset:], header.NumRows)
+		def, col, consumed, colErr := c.decodeColumn(b[offset:], header.NumRows)
 		if colErr != nil {
 			return nil, fmt.Errorf("column %d: %w", colIdx, colErr)
 		}
@@ -74,22 +66,21 @@ func Decode(b []byte) (*vectorized.RecordBatch, error) {
 	}, nil
 }
 
-// decodeColumn parses one column block (header + body) from b. It returns
-// the column definition, the materialized column with nrows rows already
-// appended (validity bits respected), and the number of bytes consumed so
-// the caller can advance its offset.
-func decodeColumn(b []byte, nrows uint64) (vectorized.ColumnDef, vectorized.Column, int, error) {
+// decodeColumn parses one column block (header + body) from b. It returns the
+// column definition, the materialized column with nrows rows already appended
+// (validity bits respected), and the number of bytes consumed.
+func (c Codec) decodeColumn(b []byte, nrows uint64) (vectorized.ColumnDef, vectorized.Column, int, error) {
 	if len(b) < 2 {
 		return vectorized.ColumnDef{}, nil, 0, fmt.Errorf("%w: header needs 2 bytes for role+type, have %d", ErrTruncated, len(b))
 	}
 	roleByte := b[0]
 	typeByte := b[1]
 	offset := 2
-	role, roleErr := unmapColumnRole(frameColRole(roleByte))
+	role, roleErr := c.WireToRole(roleByte)
 	if roleErr != nil {
 		return vectorized.ColumnDef{}, nil, 0, roleErr
 	}
-	ctype, typeErr := unmapColumnType(frameColType(typeByte))
+	ctype, typeErr := c.WireToType(typeByte)
 	if typeErr != nil {
 		return vectorized.ColumnDef{}, nil, 0, typeErr
 	}
@@ -131,7 +122,6 @@ func decodeColumn(b []byte, nrows uint64) (vectorized.ColumnDef, vectorized.Colu
 
 // readValidityBitmap parses ⌈nrows/8⌉ bytes of validity bits. Bit set ⇒ null.
 // Returns one bool per row (true=null) plus the byte count consumed.
-// nrows==0 ⇒ no bytes consumed, empty result.
 func readValidityBitmap(b []byte, nrows uint64) ([]bool, int, error) {
 	if nrows == 0 {
 		return nil, 0, nil
@@ -149,13 +139,12 @@ func readValidityBitmap(b []byte, nrows uint64) ([]bool, int, error) {
 	return nulls, nbytes, nil
 }
 
-// readColumnData materializes one column of nrows rows from b given the
-// validity vector. Fixed-width types read N × 8 bytes regardless of
-// nullness; variable-width types read uvarint(len) + len bytes per row and
-// rely on the validity vector to mark nullness.
+// readColumnData materializes one column of nrows rows from b given the validity
+// vector. Fixed-width types read N × 8 bytes regardless of nullness;
+// variable-width types read uvarint(len) + len bytes per row.
 // nolint:gocyclo // switch-dispatch over ColumnType variants is intentionally exhaustive; splitting per-case helpers would obscure the wire-format mapping
 func readColumnData(b []byte, t vectorized.ColumnType, nrows int, nulls []bool) (vectorized.Column, int, error) {
-	switch t { //nolint:exhaustive // Int64Array/StrArray never appear on the wire; the producer-side encoder rejects them via mapColumnType
+	switch t { //nolint:exhaustive // array column types never appear on the wire; the codec's type mapping rejects them at encode time
 	case vectorized.ColumnTypeInt64:
 		if len(b) < nrows*8 {
 			return nil, 0, fmt.Errorf("%w: int64 column needs %d bytes, have %d", ErrTruncated, nrows*8, len(b))
@@ -227,9 +216,6 @@ func readColumnData(b []byte, t vectorized.ColumnType, nrows int, nulls []bool)
 		}
 		return col, offset, nil
 	case vectorized.ColumnTypeTagValue:
-		// proto-bytes per cell: each cell is uvarint(len) + proto.Marshal(TagValue).
-		// Reconstructed as TypedColumn[*modelv1.TagValue] passthrough so
-		// serializeBatchToProto's pointer-return fast path picks it up.
 		col := vectorized.NewTagValueColumn(nrows)
 		offset := 0
 		for i := range nrows {
@@ -247,7 +233,7 @@ func readColumnData(b []byte, t vectorized.ColumnType, nrows int, nulls []bool)
 				tv := &modelv1.TagValue{}
 				if vlen > 0 {
 					if unmarshalErr := proto.Unmarshal(b[offset:offset+int(vlen)], tv); unmarshalErr != nil {
-						return nil, 0, fmt.Errorf("vectorized.measure.frame: TagValue cell unmarshal row %d: %w", i, unmarshalErr)
+						return nil, 0, fmt.Errorf("vectorized.frame: TagValue cell unmarshal row %d: %w", i, unmarshalErr)
 					}
 				}
 				col.Append(tv)
@@ -273,7 +259,7 @@ func readColumnData(b []byte, t vectorized.ColumnType, nrows int, nulls []bool)
 				fv := &modelv1.FieldValue{}
 				if vlen > 0 {
 					if unmarshalErr := proto.Unmarshal(b[offset:offset+int(vlen)], fv); unmarshalErr != nil {
-						return nil, 0, fmt.Errorf("vectorized.measure.frame: FieldValue cell unmarshal row %d: %w", i, unmarshalErr)
+						return nil, 0, fmt.Errorf("vectorized.frame: FieldValue cell unmarshal row %d: %w", i, unmarshalErr)
 					}
 				}
 				col.Append(fv)
@@ -284,45 +270,3 @@ func readColumnData(b []byte, t vectorized.ColumnType, nrows int, nulls []bool)
 	}
 	return nil, 0, fmt.Errorf("%w: %s", ErrUnsupportedColumnType, t.String())
 }
-
-// unmapColumnRole is the inverse of mapColumnRole: it translates a
-// wire-stable frameColRole byte back to its pkg/query/vectorized.ColumnRole
-// equivalent. Unknown bytes fail loud — the spec forbids dual-wire so an
-// unrecognized role byte is by definition a botched encoder, not a
-// version-skew negotiation.
-func unmapColumnRole(r frameColRole) (vectorized.ColumnRole, error) {
-	switch r {
-	case frameRoleTimestamp:
-		return vectorized.RoleTimestamp, nil
-	case frameRoleVersion:
-		return vectorized.RoleVersion, nil
-	case frameRoleSeriesID:
-		return vectorized.RoleSeriesID, nil
-	case frameRoleShardID:
-		return vectorized.RoleShardID, nil
-	case frameRoleTag:
-		return vectorized.RoleTag, nil
-	case frameRoleField:
-		return vectorized.RoleField, nil
-	}
-	return 0, fmt.Errorf("%w: %d", ErrUnsupportedColumnRole, r)
-}
-
-// unmapColumnType is the inverse of mapColumnType.
-func unmapColumnType(t frameColType) (vectorized.ColumnType, error) {
-	switch t {
-	case frameColInt64:
-		return vectorized.ColumnTypeInt64, nil
-	case frameColFloat64:
-		return vectorized.ColumnTypeFloat64, nil
-	case frameColString:
-		return vectorized.ColumnTypeString, nil
-	case frameColBytes:
-		return vectorized.ColumnTypeBytes, nil
-	case frameColTagValueProto:
-		return vectorized.ColumnTypeTagValue, nil
-	case frameColFieldValueProto:
-		return vectorized.ColumnTypeFieldValue, nil
-	}
-	return 0, fmt.Errorf("%w: %d", ErrUnsupportedColumnType, t)
-}
diff --git a/pkg/query/vectorized/frame/doc.go b/pkg/query/vectorized/frame/doc.go
new file mode 100644
index 000000000..d388c0b62
--- /dev/null
+++ b/pkg/query/vectorized/frame/doc.go
@@ -0,0 +1,63 @@
+// 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.
+
+// Package frame defines the shared, engine-agnostic non-proto columnar binary
+// frame carried as the SendResponse.body for a vec-native query topic. It is a
+// copy-fork of measure's mature frame core (pkg/query/vectorized/measure/frame)
+// lifted into a reusable base so the stream and trace engines do not each fork
+// the fail-loud magic/version/validity-bitmap/uvarint logic. Per-engine
+// bindings supply a Codec whose Magic, WireVersion and role/type wire mappings
+// select their own numbering; the byte layout below is identical across engines.
+//
+// Wire layout:
+//
+//	off  len       field            description
+//	---  --------  ---------------  ---------------------------------------------
+//	  0  4         Magic            codec.Magic; first byte 0x00
+//	                                (data.RawFrameMagicLeadingByte) forces a
+//	                                flag-off proto.Unmarshal of the body to
+//	                                return a non-nil error deterministically.
+//	  4  1         WireVersion      codec.WireVersion.
+//	  5  uvarint   NumRows          number of (active) rows.
+//	  ?  uvarint   NumCols          number of column blocks.
+//	  ?  ...       Columns          NumCols column blocks, in schema order.
+//
+// Each column block (header + body):
+//
+//	off  len       field            description
+//	---  --------  ---------------  ---------------------------------------------
+//	  0  1         Role             codec.RoleToWire(def.Role).
+//	  1  1         Type             codec.TypeToWire(def.Type).
+//	  2  uvarint   NameLen          length of the UTF-8 column name.
+//	  ?  NameLen   Name             column name bytes.
+//	  ?  uvarint   TagFamilyLen     length of the UTF-8 tag family name.
+//	                                Empty for non-RoleTag columns.
+//	  ?  TFL       TagFamily        tag family name bytes.
+//	  ?  ⌈N/8⌉     Validity bitmap  N = NumRows; bit i set ⇒ row i is NULL
+//	                                (1 = null). Empty for N=0.
+//	  ?  ...       Data             type-specific; see appendColumnData.
+//
+// Per-type body encoding (N = NumRows; null-row slots are present but the
+// validity bitmap is the source of truth for nullness):
+//
+//   - Int64:      N × 8 bytes little-endian.
+//   - Float64:    N × 8 bytes IEEE-754 little-endian.
+//   - String:     For each row: uvarint(len) + len UTF-8 bytes.
+//   - Bytes:      Same shape as String, opaque bytes.
+//   - TagValue:   For each row: uvarint(len) + proto.Marshal(*TagValue) bytes.
+//   - FieldValue: For each row: uvarint(len) + proto.Marshal(*FieldValue) bytes.
+package frame
diff --git a/pkg/query/vectorized/measure/frame/encode.go b/pkg/query/vectorized/frame/encode.go
similarity index 57%
rename from pkg/query/vectorized/measure/frame/encode.go
rename to pkg/query/vectorized/frame/encode.go
index c3de1dced..b294ccc97 100644
--- a/pkg/query/vectorized/measure/frame/encode.go
+++ b/pkg/query/vectorized/frame/encode.go
@@ -19,7 +19,6 @@ package frame
 
 import (
 	"encoding/binary"
-	"errors"
 	"fmt"
 	"math"
 
@@ -29,27 +28,18 @@ import (
 	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
 )
 
-// errNilBatch signals that Encode was handed a nil batch or nil schema.
-var errNilBatch = errors.New("vectorized.measure.frame: nil batch or schema")
-
-// Encode serializes a vec columnar RecordBatch into a non-proto raw frame
-// body suitable for clusterv1.SendResponse.Body on TopicInternalMeasureQuery
-// under the G9f throughout-vec design. The returned bytes begin with Magic
-// (0x00-leading), so a flag-off node's proto.Unmarshal of the body
-// deterministically fails loud (G9f spec Principle 3).
-//
-// Only the batch's active rows are encoded: if b.Selection is nil, every row
-// in [0, b.Len) is active; otherwise the rows listed in b.Selection are
-// active in the order they appear. Empty Selection produces a 0-row frame.
+// Encode serializes a vec columnar RecordBatch into a non-proto raw frame body.
+// The returned bytes begin with the codec's Magic (0x00-leading), so a flag-off
+// node's proto.Unmarshal of the body deterministically fails loud.
 //
-// Supported column types are int64, float64, string, and []byte. Any other
-// type yields ErrUnsupportedColumnType so unsupported shapes surface here at
-// encode time, not as silently-wrong wire bytes at the consumer. Likewise an
-// unknown column role yields ErrUnsupportedColumnRole.
+// Only the batch's active rows are encoded: if b.Selection is nil, every row in
+// [0, b.Len) is active; otherwise the rows listed in b.Selection are active in
+// the order they appear. Empty Selection produces a 0-row frame.
 //
-// The decoder lives in G9f.3; this package intentionally ships encode-only
-// per the G9f spec (golden-byte exit, no decode(encode(x)) round-trip here).
-func Encode(b *vectorized.RecordBatch) ([]byte, error) {
+// A column whose vectorized.ColumnType has no wire mapping yields
+// ErrUnsupportedColumnType; an unmapped role yields ErrUnsupportedColumnRole —
+// both surface here at encode time, not as silently-wrong wire bytes.
+func (c Codec) Encode(b *vectorized.RecordBatch) ([]byte, error) {
 	if b == nil || b.Schema == nil {
 		return nil, errNilBatch
 	}
@@ -58,29 +48,23 @@ func Encode(b *vectorized.RecordBatch) ([]byte, error) {
 	ncols := uint64(len(b.Schema.Columns))
 
 	buf := make([]byte, 0, MinHeaderLen)
-	buf = append(buf, Magic[:]...)
-	buf = append(buf, WireVersion)
+	buf = append(buf, c.Magic[:]...)
+	buf = append(buf, c.WireVersion)
 	buf = binary.AppendUvarint(buf, nrows)
 	buf = binary.AppendUvarint(buf, ncols)
 
 	for colIdx, def := range b.Schema.Columns {
-		role, roleErr := mapColumnRole(def.Role)
+		role, roleErr := c.RoleToWire(def.Role)
 		if roleErr != nil {
 			return nil, fmt.Errorf("column %d (%q): %w", colIdx, def.Name, roleErr)
 		}
-		ctype, typeErr := mapColumnType(def.Type)
+		ctype, typeErr := c.TypeToWire(def.Type)
 		if typeErr != nil {
 			return nil, fmt.Errorf("column %d (%q): %w", colIdx, def.Name, typeErr)
 		}
-		buf = append(buf, byte(role), byte(ctype))
+		buf = append(buf, role, ctype)
 		buf = binary.AppendUvarint(buf, uint64(len(def.Name)))
 		buf = append(buf, def.Name...)
-		// TagFamily survives the wire: the row path's BuildBatchSchema
-		// groups RoleTag columns by family for serializeBatchToProto's
-		// TagFamilyGroups output. Dropping it on the wire collapsed
-		// every projected tag family into the empty-name family on the
-		// receive side, producing `tagFamilies[].name == ""` and
-		// breaking the integration fixture's expected YAML.
 		buf = binary.AppendUvarint(buf, uint64(len(def.TagFamily)))
 		buf = append(buf, def.TagFamily...)
 
@@ -96,8 +80,8 @@ func Encode(b *vectorized.RecordBatch) ([]byte, error) {
 }
 
 // activeRowIndices materializes the active-row index list per the
-// RecordBatch.Selection contract: nil ⇒ [0, Len); empty ⇒ no rows;
-// non-empty ⇒ rows listed in Selection (in their order).
+// RecordBatch.Selection contract: nil ⇒ [0, Len); empty ⇒ no rows; non-empty ⇒
+// rows listed in Selection (in their order).
 func activeRowIndices(b *vectorized.RecordBatch) []int {
 	if b.Selection == nil {
 		idx := make([]int, b.Len)
@@ -113,11 +97,9 @@ func activeRowIndices(b *vectorized.RecordBatch) []int {
 	return idx
 }
 
-// appendValidityBitmap appends the per-active-row null bitmap for col. Bit j
-// is set ⇔ col.IsNull(active[j]) is true (1 = null), matching the project's
-// validityBitmap convention. ⌈N/8⌉ bytes, little-endian bit packing: byte k
-// holds rows k*8 … k*8+7, with bit (j%8) within that byte. No bytes are
-// appended when N=0.
+// appendValidityBitmap appends the per-active-row null bitmap for col. Bit j is
+// set ⇔ col.IsNull(active[j]) is true (1 = null). ⌈N/8⌉ bytes, little-endian
+// bit packing. No bytes are appended when N=0.
 func appendValidityBitmap(buf []byte, col vectorized.Column, active []int) []byte {
 	n := len(active)
 	if n == 0 {
@@ -137,14 +119,11 @@ func appendValidityBitmap(buf []byte, col vectorized.Column, active []int) []byt
 
 // appendColumnData appends the type-specific data section for col over the
 // active rows. Fixed-width types (int64, float64) write N × 8 bytes regardless
-// of nullness — the validity bitmap is the source of truth, so null slots
-// carry the underlying source value but the decoder ignores them.
-// Variable-width types (string, []byte) write uvarint(len) + len bytes per row;
-// null rows write len=0 + 0 bytes (the validity bitmap disambiguates "null"
-// from "empty string"/"empty bytes").
+// of nullness. Variable-width types (string, []byte, proto passthroughs) write
+// uvarint(len) + len bytes per row; null rows write len=0 + 0 bytes.
 // nolint:gocyclo // switch-dispatch over ColumnType variants is intentionally exhaustive; splitting per-case helpers would obscure the wire-format mapping
 func appendColumnData(buf []byte, col vectorized.Column, t vectorized.ColumnType, active []int) ([]byte, error) {
-	switch t { //nolint:exhaustive // Int64Array/StrArray are handled via passthrough at the dispatcher; this function never receives them
+	switch t { //nolint:exhaustive // array column types are handled via passthrough at the dispatcher; this function never receives them
 	case vectorized.ColumnTypeInt64:
 		tc, ok := col.(*vectorized.TypedColumn[int64])
 		if !ok {
@@ -204,14 +183,6 @@ func appendColumnData(buf []byte, col vectorized.Column, t vectorized.ColumnType
 		}
 		return buf, nil
 	case vectorized.ColumnTypeTagValue:
-		// proto-bytes per cell. Carries the TagValue oneof intact so
-		// cross-group queries where the same logical tag has divergent
-		// variants across groups (e.g. entity_id is STRING in sw_metric
-		// vs INT in sw_updated) survive the wire — a typed wire column
-		// couldn't represent a column whose cells span multiple oneof
-		// variants. Null cells write len=0 + 0 bytes; the validity
-		// bitmap disambiguates null from "TagValue with default-zero
-		// proto bytes".
 		tc, ok := col.(*vectorized.TypedColumn[*modelv1.TagValue])
 		if !ok {
 			return nil, fmt.Errorf("%w: declared TagValue passthrough but column is %T", ErrUnsupportedColumnType, col)
@@ -222,7 +193,7 @@ func appendColumnData(buf []byte, col vectorized.Column, t vectorized.ColumnType
 			if !col.IsNull(srcRow) && srcRow >= 0 && srcRow < len(data) && data[srcRow] != nil {
 				marshaled, marshalErr := proto.Marshal(data[srcRow])
 				if marshalErr != nil {
-					return nil, fmt.Errorf("vectorized.measure.frame: TagValue cell marshal: %w", marshalErr)
+					return nil, fmt.Errorf("vectorized.frame: TagValue cell marshal: %w", marshalErr)
 				}
 				raw = marshaled
 			}
@@ -231,7 +202,6 @@ func appendColumnData(buf []byte, col vectorized.Column, t vectorized.ColumnType
 		}
 		return buf, nil
 	case vectorized.ColumnTypeFieldValue:
-		// Same proto-bytes shape as ColumnTypeTagValue, FieldValue oneof.
 		tc, ok := col.(*vectorized.TypedColumn[*modelv1.FieldValue])
 		if !ok {
 			return nil, fmt.Errorf("%w: declared FieldValue passthrough but column is %T", ErrUnsupportedColumnType, col)
@@ -242,7 +212,7 @@ func appendColumnData(buf []byte, col vectorized.Column, t vectorized.ColumnType
 			if !col.IsNull(srcRow) && srcRow >= 0 && srcRow < len(data) && data[srcRow] != nil {
 				marshaled, marshalErr := proto.Marshal(data[srcRow])
 				if marshalErr != nil {
-					return nil, fmt.Errorf("vectorized.measure.frame: FieldValue cell marshal: %w", marshalErr)
+					return nil, fmt.Errorf("vectorized.frame: FieldValue cell marshal: %w", marshalErr)
 				}
 				raw = marshaled
 			}
@@ -253,44 +223,3 @@ func appendColumnData(buf []byte, col vectorized.Column, t vectorized.ColumnType
 	}
 	return nil, fmt.Errorf("%w: %s", ErrUnsupportedColumnType, t.String())
 }
-
-// mapColumnType translates a vectorized.ColumnType to its wire-stable
-// frameColType. Unsupported types yield ErrUnsupportedColumnType so callers
-// surface the bad input loudly at encode time.
-func mapColumnType(t vectorized.ColumnType) (frameColType, error) {
-	switch t { //nolint:exhaustive // unsupported types (Int64Array/StrArray) fall through to the ErrUnsupportedColumnType return below
-	case vectorized.ColumnTypeInt64:
-		return frameColInt64, nil
-	case vectorized.ColumnTypeFloat64:
-		return frameColFloat64, nil
-	case vectorized.ColumnTypeString:
-		return frameColString, nil
-	case vectorized.ColumnTypeBytes:
-		return frameColBytes, nil
-	case vectorized.ColumnTypeTagValue:
-		return frameColTagValueProto, nil
-	case vectorized.ColumnTypeFieldValue:
-		return frameColFieldValueProto, nil
-	}
-	return 0, fmt.Errorf("%w: %s", ErrUnsupportedColumnType, t.String())
-}
-
-// mapColumnRole translates a vectorized.ColumnRole to its wire-stable
-// frameColRole. Unsupported roles yield ErrUnsupportedColumnRole.
-func mapColumnRole(r vectorized.ColumnRole) (frameColRole, error) {
-	switch r {
-	case vectorized.RoleTimestamp:
-		return frameRoleTimestamp, nil
-	case vectorized.RoleVersion:
-		return frameRoleVersion, nil
-	case vectorized.RoleSeriesID:
-		return frameRoleSeriesID, nil
-	case vectorized.RoleShardID:
-		return frameRoleShardID, nil
-	case vectorized.RoleTag:
-		return frameRoleTag, nil
-	case vectorized.RoleField:
-		return frameRoleField, nil
-	}
-	return 0, fmt.Errorf("%w: %d", ErrUnsupportedColumnRole, r)
-}
diff --git a/pkg/query/vectorized/frame/frame.go b/pkg/query/vectorized/frame/frame.go
new file mode 100644
index 000000000..c0f3eb575
--- /dev/null
+++ b/pkg/query/vectorized/frame/frame.go
@@ -0,0 +1,95 @@
+// 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.
+
+package frame
+
+import (
+	"errors"
+
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+)
+
+// MagicLen is the length of a frame magic prefix in bytes.
+const MagicLen = 4
+
+// MinHeaderLen is the smallest possible frame header — 4 magic bytes, 1
+// version byte, and the minimal 1-byte uvarint encodings of NumRows=0 and
+// NumCols=0.
+const MinHeaderLen = MagicLen + 1 + 1 + 1
+
+// Header is the parsed frame header (everything up to but not including the
+// first column block).
+type Header struct {
+	NumRows     uint64
+	NumCols     uint64
+	Magic       [4]byte
+	WireVersion uint8
+}
+
+// Sentinel errors. Decode and ValidateHeader wrap these with context so
+// callers can errors.Is against specific failure classes — most importantly,
+// ErrBadMagic at the very first byte is the engineered fail-loud guard the
+// raw-wire hard-cutover model relies on.
+var (
+	// ErrTruncated signals a frame whose length is below the minimum header
+	// length, or whose declared lengths run past the buffer.
+	ErrTruncated = errors.New("vectorized.frame: truncated frame")
+
+	// ErrBadMagic signals a frame whose leading 4 bytes do not match the
+	// codec's Magic. A flag-off (proto) body received on the raw path fails
+	// here loudly, never silently mis-decoded.
+	ErrBadMagic = errors.New("vectorized.frame: bad magic")
+
+	// ErrBadVersion signals a frame whose WireVersion byte does not match the
+	// codec's WireVersion. Hard-cutover means there is no recovery — the
+	// receiver must surface this loudly.
+	ErrBadVersion = errors.New("vectorized.frame: bad wire version")
+
+	// ErrUnsupportedColumnType signals that a column whose
+	// vectorized.ColumnType has no wire mapping crossed the codec. Surfacing
+	// this at encode/decode time prevents silently-wrong wire bytes.
+	ErrUnsupportedColumnType = errors.New("vectorized.frame: unsupported column type")
+
+	// ErrUnsupportedColumnRole signals that a column whose
+	// vectorized.ColumnRole has no wire mapping crossed the codec.
+	ErrUnsupportedColumnRole = errors.New("vectorized.frame: unsupported column role")
+
+	// errNilBatch signals that Encode was handed a nil batch or nil schema.
+	errNilBatch = errors.New("vectorized.frame: nil batch or schema")
+)
+
+// Codec is a parameterized encoder/decoder for the shared vec columnar frame.
+// The byte layout is fixed and engine-agnostic; only the frame signature
+// (Magic), the format version (WireVersion), and the numeric role/type wire
+// mappings are supplied per engine. Two codecs configured with the same Magic,
+// WireVersion, and mapping tables produce byte-identical frames — the property
+// the golden-bytes cross-implementation test verifies against measure's
+// shipped frame package.
+type Codec struct {
+	// RoleToWire maps a vectorized.ColumnRole to its wire byte, or returns
+	// ErrUnsupportedColumnRole for a role the engine does not emit.
+	RoleToWire func(vectorized.ColumnRole) (uint8, error)
+	// WireToRole is the inverse of RoleToWire.
+	WireToRole func(uint8) (vectorized.ColumnRole, error)
+	// TypeToWire maps a vectorized.ColumnType to its wire byte, or returns
+	// ErrUnsupportedColumnType for a type the engine does not emit.
+	TypeToWire func(vectorized.ColumnType) (uint8, error)
+	// WireToType is the inverse of TypeToWire.
+	WireToType  func(uint8) (vectorized.ColumnType, error)
+	Magic       [4]byte
+	WireVersion uint8
+}
diff --git a/pkg/query/vectorized/frame/frame_test.go b/pkg/query/vectorized/frame/frame_test.go
new file mode 100644
index 000000000..0235e47b6
--- /dev/null
+++ b/pkg/query/vectorized/frame/frame_test.go
@@ -0,0 +1,407 @@
+// 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.
+
+package frame
+
+import (
+	"bytes"
+	"encoding/binary"
+	"errors"
+	"math"
+	"testing"
+
+	"google.golang.org/protobuf/proto"
+
+	"github.com/apache/skywalking-banyandb/api/data"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+)
+
+// testCodec mirrors measure's exact numbering so the round-trip and negative
+// tests exercise the full type/role set the shared base supports.
+var testCodec = Codec{
+	Magic:       [4]byte{data.RawFrameMagicLeadingByte, 'V', 'F', 'R'},
+	WireVersion: 3,
+	RoleToWire:  measureRoleToWire,
+	WireToRole:  measureWireToRole,
+	TypeToWire:  measureTypeToWire,
+	WireToType:  measureWireToType,
+}
+
+func measureRoleToWire(r vectorized.ColumnRole) (uint8, error) {
+	switch r {
+	case vectorized.RoleTimestamp:
+		return 1, nil
+	case vectorized.RoleVersion:
+		return 2, nil
+	case vectorized.RoleSeriesID:
+		return 3, nil
+	case vectorized.RoleShardID:
+		return 4, nil
+	case vectorized.RoleTag:
+		return 5, nil
+	case vectorized.RoleField:
+		return 6, nil
+	default:
+		return 0, ErrUnsupportedColumnRole
+	}
+}
+
+func measureWireToRole(b uint8) (vectorized.ColumnRole, error) {
+	switch b {
+	case 1:
+		return vectorized.RoleTimestamp, nil
+	case 2:
+		return vectorized.RoleVersion, nil
+	case 3:
+		return vectorized.RoleSeriesID, nil
+	case 4:
+		return vectorized.RoleShardID, nil
+	case 5:
+		return vectorized.RoleTag, nil
+	case 6:
+		return vectorized.RoleField, nil
+	default:
+		return 0, ErrUnsupportedColumnRole
+	}
+}
+
+func measureTypeToWire(t vectorized.ColumnType) (uint8, error) {
+	switch t { //nolint:exhaustive // test codec deliberately maps only the supported subset
+	case vectorized.ColumnTypeInt64:
+		return 1, nil
+	case vectorized.ColumnTypeFloat64:
+		return 2, nil
+	case vectorized.ColumnTypeString:
+		return 3, nil
+	case vectorized.ColumnTypeBytes:
+		return 4, nil
+	case vectorized.ColumnTypeTagValue:
+		return 5, nil
+	case vectorized.ColumnTypeFieldValue:
+		return 6, nil
+	default:
+		return 0, ErrUnsupportedColumnType
+	}
+}
+
+func measureWireToType(b uint8) (vectorized.ColumnType, error) {
+	switch b {
+	case 1:
+		return vectorized.ColumnTypeInt64, nil
+	case 2:
+		return vectorized.ColumnTypeFloat64, nil
+	case 3:
+		return vectorized.ColumnTypeString, nil
+	case 4:
+		return vectorized.ColumnTypeBytes, nil
+	case 5:
+		return vectorized.ColumnTypeTagValue, nil
+	case 6:
+		return vectorized.ColumnTypeFieldValue, nil
+	default:
+		return 0, ErrUnsupportedColumnType
+	}
+}
+
+func strTagValue(s string) *modelv1.TagValue {
+	return &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: s}}}
+}
+
+func intFieldValue(v int64) *modelv1.FieldValue {
+	return &modelv1.FieldValue{Value: &modelv1.FieldValue_Int{Int: &modelv1.Int{Value: v}}}
+}
+
+// buildRichBatch builds a 3-row batch touching every supported column type with
+// a null cell in each variable-width column and a populated tag family.
+func buildRichBatch(t *testing.T) *vectorized.RecordBatch {
+	t.Helper()
+	schema := vectorized.NewBatchSchema([]vectorized.ColumnDef{
+		{Role: vectorized.RoleTimestamp, Name: "ts", Type: vectorized.ColumnTypeInt64},
+		{Role: vectorized.RoleField, Name: "f", Type: vectorized.ColumnTypeFloat64},
+		{Role: vectorized.RoleTag, Name: "s", TagFamily: "fam", Type: vectorized.ColumnTypeString},
+		{Role: vectorized.RoleTag, Name: "b", TagFamily: "fam", Type: vectorized.ColumnTypeBytes},
+		{Role: vectorized.RoleTag, Name: "tv", TagFamily: "fam", Type: vectorized.ColumnTypeTagValue},
+		{Role: vectorized.RoleField, Name: "fv", Type: vectorized.ColumnTypeFieldValue},
+	})
+	b := vectorized.NewRecordBatch(schema, 3)
+
+	ts := b.Columns[0].(*vectorized.TypedColumn[int64])
+	ts.Append(100)
+	ts.Append(200)
+	ts.Append(300)
+
+	f := b.Columns[1].(*vectorized.TypedColumn[float64])
+	f.Append(1.5)
+	f.Append(2.5)
+	f.Append(3.5)
+
+	s := b.Columns[2].(*vectorized.TypedColumn[string])
+	s.Append("alpha")
+	s.AppendNull()
+	s.Append("gamma")
+
+	bb := b.Columns[3].(*vectorized.TypedColumn[[]byte])
+	bb.Append([]byte{0x01, 0x02})
+	bb.Append([]byte{})
+	bb.AppendNull()
+
+	tv := b.Columns[4].(*vectorized.TypedColumn[*modelv1.TagValue])
+	tv.Append(strTagValue("t0"))
+	tv.Append(strTagValue("t1"))
+	tv.AppendNull()
+
+	fv := b.Columns[5].(*vectorized.TypedColumn[*modelv1.FieldValue])
+	fv.Append(intFieldValue(11))
+	fv.AppendNull()
+	fv.Append(intFieldValue(33))
+
+	b.Len = 3
+	return b
+}
+
+func assertBatchesEqual(t *testing.T, want, got *vectorized.RecordBatch) {
+	t.Helper()
+	if got.Len != want.Len {
+		t.Fatalf("Len mismatch: got %d, want %d", got.Len, want.Len)
+	}
+	if len(got.Columns) != len(want.Columns) {
+		t.Fatalf("column count mismatch: got %d, want %d", len(got.Columns), len(want.Columns))
+	}
+	for ci := range want.Columns {
+		wd := want.Schema.Columns[ci]
+		gd := got.Schema.Columns[ci]
+		if wd.Role != gd.Role || wd.Type != gd.Type || wd.Name != gd.Name || wd.TagFamily != gd.TagFamily {
+			t.Fatalf("column %d def mismatch: got %+v, want %+v", ci, gd, wd)
+		}
+		assertColumnEqual(t, ci, want.Columns[ci], got.Columns[ci])
+	}
+}
+
+// nolint:gocyclo // exhaustive per-type comparison for the test assertion is intentionally flat
+func assertColumnEqual(t *testing.T, ci int, want, got vectorized.Column) {
+	t.Helper()
+	if got.Len() != want.Len() {
+		t.Fatalf("column %d row count mismatch: got %d, want %d", ci, got.Len(), want.Len())
+	}
+	for r := 0; r < want.Len(); r++ {
+		if got.IsNull(r) != want.IsNull(r) {
+			t.Fatalf("column %d row %d null mismatch: got %v, want %v", ci, r, got.IsNull(r), want.IsNull(r))
+		}
+		if want.IsNull(r) {
+			continue
+		}
+		switch wc := want.(type) {
+		case *vectorized.TypedColumn[int64]:
+			if got.(*vectorized.TypedColumn[int64]).Data()[r] != wc.Data()[r] {
+				t.Fatalf("column %d row %d int64 mismatch", ci, r)
+			}
+		case *vectorized.TypedColumn[float64]:
+			if got.(*vectorized.TypedColumn[float64]).Data()[r] != wc.Data()[r] {
+				t.Fatalf("column %d row %d float64 mismatch", ci, r)
+			}
+		case *vectorized.TypedColumn[string]:
+			if got.(*vectorized.TypedColumn[string]).Data()[r] != wc.Data()[r] {
+				t.Fatalf("column %d row %d string mismatch", ci, r)
+			}
+		case *vectorized.TypedColumn[[]byte]:
+			if !bytes.Equal(got.(*vectorized.TypedColumn[[]byte]).Data()[r], wc.Data()[r]) {
+				t.Fatalf("column %d row %d bytes mismatch", ci, r)
+			}
+		case *vectorized.TypedColumn[*modelv1.TagValue]:
+			if !proto.Equal(got.(*vectorized.TypedColumn[*modelv1.TagValue]).Data()[r], wc.Data()[r]) {
+				t.Fatalf("column %d row %d TagValue mismatch", ci, r)
+			}
+		case *vectorized.TypedColumn[*modelv1.FieldValue]:
+			if !proto.Equal(got.(*vectorized.TypedColumn[*modelv1.FieldValue]).Data()[r], wc.Data()[r]) {
+				t.Fatalf("column %d row %d FieldValue mismatch", ci, r)
+			}
+		default:
+			t.Fatalf("column %d unexpected type %T", ci, want)
+		}
+	}
+}
+
+func TestCodec_RoundTrip_AllColumnTypes(t *testing.T) {
+	want := buildRichBatch(t)
+	encoded, err := testCodec.Encode(want)
+	if err != nil {
+		t.Fatalf("Encode: %v", err)
+	}
+	got, decErr := testCodec.Decode(encoded)
+	if decErr != nil {
+		t.Fatalf("Decode: %v", decErr)
+	}
+	assertBatchesEqual(t, want, got)
+}
+
+func TestCodec_RoundTrip_EmptyBatch(t *testing.T) {
+	want := vectorized.NewRecordBatch(vectorized.NewBatchSchema(nil), 0)
+	encoded, err := testCodec.Encode(want)
+	if err != nil {
+		t.Fatalf("Encode: %v", err)
+	}
+	if len(encoded) != MinHeaderLen {
+		t.Fatalf("empty frame length = %d, want %d", len(encoded), MinHeaderLen)
+	}
+	got, decErr := testCodec.Decode(encoded)
+	if decErr != nil {
+		t.Fatalf("Decode: %v", decErr)
+	}
+	if got.Len != 0 || len(got.Columns) != 0 {
+		t.Fatalf("empty batch decoded to Len=%d cols=%d", got.Len, len(got.Columns))
+	}
+}
+
+func TestCodec_RoundTrip_Selection(t *testing.T) {
+	want := buildRichBatch(t)
+	want.Selection = []uint16{2, 0} // reorder + drop row 1
+	encoded, err := testCodec.Encode(want)
+	if err != nil {
+		t.Fatalf("Encode: %v", err)
+	}
+	got, decErr := testCodec.Decode(encoded)
+	if decErr != nil {
+		t.Fatalf("Decode: %v", decErr)
+	}
+	if got.Len != 2 {
+		t.Fatalf("selected Len = %d, want 2", got.Len)
+	}
+	ts := got.Columns[0].(*vectorized.TypedColumn[int64])
+	if ts.Data()[0] != 300 || ts.Data()[1] != 100 {
+		t.Fatalf("selection order wrong: %v", ts.Data())
+	}
+}
+
+func TestCodec_Decode_BadMagic(t *testing.T) {
+	encoded, _ := testCodec.Encode(buildRichBatch(t))
+	encoded[1] = 'X'
+	_, err := testCodec.Decode(encoded)
+	if !errors.Is(err, ErrBadMagic) {
+		t.Fatalf("got %v, want ErrBadMagic", err)
+	}
+}
+
+func TestCodec_Decode_BadVersion(t *testing.T) {
+	encoded, _ := testCodec.Encode(buildRichBatch(t))
+	encoded[MagicLen] = 99
+	_, err := testCodec.Decode(encoded)
+	if !errors.Is(err, ErrBadVersion) {
+		t.Fatalf("got %v, want ErrBadVersion", err)
+	}
+}
+
+func TestCodec_Decode_Truncated(t *testing.T) {
+	encoded, _ := testCodec.Encode(buildRichBatch(t))
+	_, err := testCodec.Decode(encoded[:len(encoded)-3])
+	if !errors.Is(err, ErrTruncated) {
+		t.Fatalf("got %v, want ErrTruncated", err)
+	}
+}
+
+func TestCodec_Decode_TooShortForHeader(t *testing.T) {
+	_, err := testCodec.Decode([]byte{0x00, 'V'})
+	if !errors.Is(err, ErrTruncated) {
+		t.Fatalf("got %v, want ErrTruncated", err)
+	}
+}
+
+// TestCodec_Decode_NumRowsExceedsBody guards the adversarial-header path: a
+// near-2^64 NumRows must be rejected loudly at ValidateHeader, never reaching
+// the column decoder where (NumRows+7)/8 would overflow and make([]bool, NumRows)
+// would OOM-panic. The test passing without a panic is itself the assertion.
+func TestCodec_Decode_NumRowsExceedsBody(t *testing.T) {
+	var b []byte
+	b = append(b, testCodec.Magic[:]...)
+	b = append(b, testCodec.WireVersion)
+	b = binary.AppendUvarint(b, math.MaxUint64) // NumRows far larger than any body
+	b = binary.AppendUvarint(b, 1)              // NumCols=1
+	b = append(b, 0x01, 0x01)                   // partial column bytes; never reached
+	_, err := testCodec.Decode(b)
+	if !errors.Is(err, ErrTruncated) {
+		t.Fatalf("got %v, want ErrTruncated for NumRows exceeding body", err)
+	}
+}
+
+// TestCodec_Decode_NumColsExceedsBody guards the same class for NumCols.
+func TestCodec_Decode_NumColsExceedsBody(t *testing.T) {
+	var b []byte
+	b = append(b, testCodec.Magic[:]...)
+	b = append(b, testCodec.WireVersion)
+	b = binary.AppendUvarint(b, 0)              // NumRows=0
+	b = binary.AppendUvarint(b, math.MaxUint64) // NumCols far larger than any body
+	_, err := testCodec.Decode(b)
+	if !errors.Is(err, ErrTruncated) {
+		t.Fatalf("got %v, want ErrTruncated for NumCols exceeding body", err)
+	}
+}
+
+func TestCodec_Decode_TrailingBytes(t *testing.T) {
+	encoded, _ := testCodec.Encode(buildRichBatch(t))
+	encoded = append(encoded, 0xFF)
+	_, err := testCodec.Decode(encoded)
+	if !errors.Is(err, ErrTruncated) {
+		t.Fatalf("got %v, want ErrTruncated for trailing bytes", err)
+	}
+}
+
+func TestCodec_Decode_UnknownRoleByte(t *testing.T) {
+	schema := vectorized.NewBatchSchema([]vectorized.ColumnDef{
+		{Role: vectorized.RoleTimestamp, Name: "ts", Type: vectorized.ColumnTypeInt64},
+	})
+	b := vectorized.NewRecordBatch(schema, 1)
+	b.Columns[0].(*vectorized.TypedColumn[int64]).Append(1)
+	b.Len = 1
+	encoded, _ := testCodec.Encode(b)
+	// role byte sits right after magic(4)+version(1)+nrows(1)+ncols(1) = offset 7.
+	encoded[7] = 200
+	_, err := testCodec.Decode(encoded)
+	if !errors.Is(err, ErrUnsupportedColumnRole) {
+		t.Fatalf("got %v, want ErrUnsupportedColumnRole", err)
+	}
+}
+
+func TestCodec_Decode_UnknownTypeByte(t *testing.T) {
+	schema := vectorized.NewBatchSchema([]vectorized.ColumnDef{
+		{Role: vectorized.RoleTimestamp, Name: "ts", Type: vectorized.ColumnTypeInt64},
+	})
+	b := vectorized.NewRecordBatch(schema, 1)
+	b.Columns[0].(*vectorized.TypedColumn[int64]).Append(1)
+	b.Len = 1
+	encoded, _ := testCodec.Encode(b)
+	encoded[8] = 200 // type byte
+	_, err := testCodec.Decode(encoded)
+	if !errors.Is(err, ErrUnsupportedColumnType) {
+		t.Fatalf("got %v, want ErrUnsupportedColumnType", err)
+	}
+}
+
+func TestCodec_Encode_NilBatch(t *testing.T) {
+	if _, err := testCodec.Encode(nil); err == nil {
+		t.Fatal("expected error for nil batch")
+	}
+}
+
+func TestCodec_Encode_UnsupportedRole(t *testing.T) {
+	schema := vectorized.NewBatchSchema([]vectorized.ColumnDef{
+		{Role: vectorized.RoleOrderKey, Name: "ok", Type: vectorized.ColumnTypeBytes},
+	})
+	b := vectorized.NewRecordBatch(schema, 0)
+	if _, err := testCodec.Encode(b); !errors.Is(err, ErrUnsupportedColumnRole) {
+		t.Fatalf("got %v, want ErrUnsupportedColumnRole", err)
+	}
+}
diff --git a/pkg/query/vectorized/frame/golden_test.go b/pkg/query/vectorized/frame/golden_test.go
new file mode 100644
index 000000000..48774a9a4
--- /dev/null
+++ b/pkg/query/vectorized/frame/golden_test.go
@@ -0,0 +1,237 @@
+// 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.
+
+package frame_test
+
+import (
+	"bytes"
+	"testing"
+
+	"google.golang.org/protobuf/proto"
+
+	"github.com/apache/skywalking-banyandb/api/data"
+	modelv1 "github.com/apache/skywalking-banyandb/api/proto/banyandb/model/v1"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	sharedframe "github.com/apache/skywalking-banyandb/pkg/query/vectorized/frame"
+	measureframe "github.com/apache/skywalking-banyandb/pkg/query/vectorized/measure/frame"
+)
+
+// measureCodec configures the shared base with measure's exact wire numbering so
+// its output can be compared byte-for-byte against measure's shipped frame
+// package. Any behavioral divergence between the two implementations (validity
+// bitmap packing, uvarint encoding, header layout, per-cell proto marshaling)
+// fails the byte-equality assertion below — stronger than a constant-only check.
+var measureCodec = sharedframe.Codec{
+	Magic:       [4]byte{data.RawFrameMagicLeadingByte, 'V', 'F', 'R'},
+	WireVersion: 3,
+	RoleToWire:  goldenRoleToWire,
+	WireToRole:  goldenWireToRole,
+	TypeToWire:  goldenTypeToWire,
+	WireToType:  goldenWireToType,
+}
+
+func goldenRoleToWire(r vectorized.ColumnRole) (uint8, error) {
+	switch r {
+	case vectorized.RoleTimestamp:
+		return 1, nil
+	case vectorized.RoleVersion:
+		return 2, nil
+	case vectorized.RoleSeriesID:
+		return 3, nil
+	case vectorized.RoleShardID:
+		return 4, nil
+	case vectorized.RoleTag:
+		return 5, nil
+	case vectorized.RoleField:
+		return 6, nil
+	default:
+		return 0, sharedframe.ErrUnsupportedColumnRole
+	}
+}
+
+func goldenWireToRole(b uint8) (vectorized.ColumnRole, error) {
+	switch b {
+	case 1:
+		return vectorized.RoleTimestamp, nil
+	case 2:
+		return vectorized.RoleVersion, nil
+	case 3:
+		return vectorized.RoleSeriesID, nil
+	case 4:
+		return vectorized.RoleShardID, nil
+	case 5:
+		return vectorized.RoleTag, nil
+	case 6:
+		return vectorized.RoleField, nil
+	default:
+		return 0, sharedframe.ErrUnsupportedColumnRole
+	}
+}
+
+func goldenTypeToWire(t vectorized.ColumnType) (uint8, error) {
+	switch t { //nolint:exhaustive // measure's supported subset only
+	case vectorized.ColumnTypeInt64:
+		return 1, nil
+	case vectorized.ColumnTypeFloat64:
+		return 2, nil
+	case vectorized.ColumnTypeString:
+		return 3, nil
+	case vectorized.ColumnTypeBytes:
+		return 4, nil
+	case vectorized.ColumnTypeTagValue:
+		return 5, nil
+	case vectorized.ColumnTypeFieldValue:
+		return 6, nil
+	default:
+		return 0, sharedframe.ErrUnsupportedColumnType
+	}
+}
+
+func goldenWireToType(b uint8) (vectorized.ColumnType, error) {
+	switch b {
+	case 1:
+		return vectorized.ColumnTypeInt64, nil
+	case 2:
+		return vectorized.ColumnTypeFloat64, nil
+	case 3:
+		return vectorized.ColumnTypeString, nil
+	case 4:
+		return vectorized.ColumnTypeBytes, nil
+	case 5:
+		return vectorized.ColumnTypeTagValue, nil
+	case 6:
+		return vectorized.ColumnTypeFieldValue, nil
+	default:
+		return 0, sharedframe.ErrUnsupportedColumnType
+	}
+}
+
+func goldenStrTagValue(s string) *modelv1.TagValue {
+	return &modelv1.TagValue{Value: &modelv1.TagValue_Str{Str: &modelv1.Str{Value: s}}}
+}
+
+// buildGoldenBatch builds a representative measure-shaped batch: int64 + string
+// + bytes + TagValue columns, some null cells, and a populated tag family.
+func buildGoldenBatch() *vectorized.RecordBatch {
+	schema := vectorized.NewBatchSchema([]vectorized.ColumnDef{
+		{Role: vectorized.RoleTimestamp, Name: "ts", Type: vectorized.ColumnTypeInt64},
+		{Role: vectorized.RoleTag, Name: "svc", TagFamily: "meta", Type: vectorized.ColumnTypeString},
+		{Role: vectorized.RoleTag, Name: "raw", TagFamily: "meta", Type: vectorized.ColumnTypeBytes},
+		{Role: vectorized.RoleTag, Name: "tv", TagFamily: "meta", Type: vectorized.ColumnTypeTagValue},
+	})
+	b := vectorized.NewRecordBatch(schema, 3)
+
+	ts := b.Columns[0].(*vectorized.TypedColumn[int64])
+	ts.Append(1000)
+	ts.Append(-2000)
+	ts.Append(3000)
+
+	svc := b.Columns[1].(*vectorized.TypedColumn[string])
+	svc.Append("checkout")
+	svc.AppendNull()
+	svc.Append("")
+
+	raw := b.Columns[2].(*vectorized.TypedColumn[[]byte])
+	raw.Append([]byte{0xDE, 0xAD})
+	raw.Append([]byte{})
+	raw.AppendNull()
+
+	tv := b.Columns[3].(*vectorized.TypedColumn[*modelv1.TagValue])
+	tv.Append(goldenStrTagValue("v0"))
+	tv.AppendNull()
+	tv.Append(goldenStrTagValue("v2"))
+
+	b.Len = 3
+	return b
+}
+
+// TestGoldenBytes_SharedEqualsMeasure is the drift gate: the shared base
+// configured with measure's numbering and measure's shipped Encode must produce
+// byte-identical frames, and each side must decode the other's bytes into equal
+// batches. This proves no behavioral divergence exists — the whole reason a
+// shared base was chosen over a third fork.
+func TestGoldenBytes_SharedEqualsMeasure(t *testing.T) {
+	b := buildGoldenBatch()
+
+	sharedBytes, sharedErr := measureCodec.Encode(b)
+	if sharedErr != nil {
+		t.Fatalf("shared Encode: %v", sharedErr)
+	}
+	measureBytes, measureErr := measureframe.Encode(buildGoldenBatch())
+	if measureErr != nil {
+		t.Fatalf("measure Encode: %v", measureErr)
+	}
+	if !bytes.Equal(sharedBytes, measureBytes) {
+		t.Fatalf("encoded bytes diverge:\n  shared  %#x\n  measure %#x", sharedBytes, measureBytes)
+	}
+
+	// Cross-decode: measure decodes shared bytes.
+	fromMeasure, decMErr := measureframe.Decode(sharedBytes)
+	if decMErr != nil {
+		t.Fatalf("measure.Decode(sharedBytes): %v", decMErr)
+	}
+	// Cross-decode: shared decodes measure bytes.
+	fromShared, decSErr := measureCodec.Decode(measureBytes)
+	if decSErr != nil {
+		t.Fatalf("shared.Decode(measureBytes): %v", decSErr)
+	}
+	assertGoldenBatchEqual(t, buildGoldenBatch(), fromMeasure)
+	assertGoldenBatchEqual(t, buildGoldenBatch(), fromShared)
+}
+
+// nolint:gocyclo // exhaustive per-type comparison for the assertion is intentionally flat
+func assertGoldenBatchEqual(t *testing.T, want, got *vectorized.RecordBatch) {
+	t.Helper()
+	if got.Len != want.Len || len(got.Columns) != len(want.Columns) {
+		t.Fatalf("shape mismatch: got Len=%d cols=%d want Len=%d cols=%d", got.Len, len(got.Columns), want.Len, len(want.Columns))
+	}
+	for ci := range want.Columns {
+		wd, gd := want.Schema.Columns[ci], got.Schema.Columns[ci]
+		if wd.Role != gd.Role || wd.Type != gd.Type || wd.Name != gd.Name || wd.TagFamily != gd.TagFamily {
+			t.Fatalf("column %d def mismatch: got %+v want %+v", ci, gd, wd)
+		}
+		wc, gc := want.Columns[ci], got.Columns[ci]
+		for r := 0; r < want.Len; r++ {
+			if wc.IsNull(r) != gc.IsNull(r) {
+				t.Fatalf("column %d row %d null mismatch", ci, r)
+			}
+			if wc.IsNull(r) {
+				continue
+			}
+			switch w := wc.(type) {
+			case *vectorized.TypedColumn[int64]:
+				if gc.(*vectorized.TypedColumn[int64]).Data()[r] != w.Data()[r] {
+					t.Fatalf("column %d row %d int64 mismatch", ci, r)
+				}
+			case *vectorized.TypedColumn[string]:
+				if gc.(*vectorized.TypedColumn[string]).Data()[r] != w.Data()[r] {
+					t.Fatalf("column %d row %d string mismatch", ci, r)
+				}
+			case *vectorized.TypedColumn[[]byte]:
+				if !bytes.Equal(gc.(*vectorized.TypedColumn[[]byte]).Data()[r], w.Data()[r]) {
+					t.Fatalf("column %d row %d bytes mismatch", ci, r)
+				}
+			case *vectorized.TypedColumn[*modelv1.TagValue]:
+				if !proto.Equal(gc.(*vectorized.TypedColumn[*modelv1.TagValue]).Data()[r], w.Data()[r]) {
+					t.Fatalf("column %d row %d TagValue mismatch", ci, r)
+				}
+			default:
+				t.Fatalf("column %d unexpected type %T", ci, wc)
+			}
+		}
+	}
+}
diff --git a/pkg/query/vectorized/measure/frame/validate.go b/pkg/query/vectorized/frame/validate.go
similarity index 53%
rename from pkg/query/vectorized/measure/frame/validate.go
rename to pkg/query/vectorized/frame/validate.go
index d02e9bb00..621a5c186 100644
--- a/pkg/query/vectorized/measure/frame/validate.go
+++ b/pkg/query/vectorized/frame/validate.go
@@ -22,29 +22,28 @@ import (
 	"fmt"
 )
 
-// ValidateHeader is the fail-loud preflight a decoder calls before parsing
-// any column data. It is the SOLE technical guard for the G9f hard-cutover
-// model (Principle 3): a frame whose magic does not match Magic, or whose
-// wire-version is not WireVersion, is rejected loudly here — never silently
-// mis-decoded.
+// ValidateHeader is the fail-loud preflight a decoder calls before parsing any
+// column data. It is the SOLE technical guard for the raw-wire hard-cutover
+// model: a frame whose magic does not match the codec's Magic, or whose
+// wire-version is not the codec's WireVersion, is rejected loudly here — never
+// silently mis-decoded.
 //
-// It does NOT parse the columnar body; that is the decoder's job (G9f.3).
-// Returns the parsed Header, the number of bytes consumed from b (so the
-// caller can slice b[bytesRead:] to reach the first column block), and a
-// non-nil error wrapping one of ErrTruncated, ErrBadMagic, ErrBadVersion on
-// any failure.
-func ValidateHeader(b []byte) (Header, int, error) {
+// It does NOT parse the columnar body; that is Decode's job. Returns the parsed
+// Header, the number of bytes consumed from b (so the caller can slice
+// b[bytesRead:] to reach the first column block), and a non-nil error wrapping
+// one of ErrTruncated, ErrBadMagic, ErrBadVersion on any failure.
+func (c Codec) ValidateHeader(b []byte) (Header, int, error) {
 	if len(b) < MinHeaderLen {
 		return Header{}, 0, fmt.Errorf("%w: have %d bytes, need at least %d", ErrTruncated, len(b), MinHeaderLen)
 	}
 	var h Header
 	copy(h.Magic[:], b[:MagicLen])
-	if h.Magic != Magic {
-		return Header{}, 0, fmt.Errorf("%w: got %#x, want %#x", ErrBadMagic, h.Magic[:], Magic[:])
+	if h.Magic != c.Magic {
+		return Header{}, 0, fmt.Errorf("%w: got %#x, want %#x", ErrBadMagic, h.Magic[:], c.Magic[:])
 	}
 	h.WireVersion = b[MagicLen]
-	if h.WireVersion != WireVersion {
-		return Header{}, 0, fmt.Errorf("%w: got %d, want %d", ErrBadVersion, h.WireVersion, WireVersion)
+	if h.WireVersion != c.WireVersion {
+		return Header{}, 0, fmt.Errorf("%w: got %d, want %d", ErrBadVersion, h.WireVersion, c.WireVersion)
 	}
 	offset := MagicLen + 1
 	nrows, nrowsLen := binary.Uvarint(b[offset:])
@@ -59,5 +58,17 @@ func ValidateHeader(b []byte) (Header, int, error) {
 	}
 	h.NumCols = ncols
 	offset += ncolsLen
+	// Bound NumRows/NumCols by the body length before any column is parsed. A
+	// frame of length L can encode at most L rows (each row costs at least one
+	// byte across its columns) and at most L-offset columns (each column block is
+	// at least a role+type byte). Without this an adversarial/corrupt header with
+	// a near-2^64 NumRows would (a) overflow the (NumRows+7)/8 validity-byte math
+	// and (b) drive make([]bool, NumRows) into an OOM panic in readValidityBitmap.
+	if h.NumRows > uint64(len(b)) {
+		return Header{}, 0, fmt.Errorf("%w: NumRows=%d exceeds frame length %d", ErrTruncated, h.NumRows, len(b))
+	}
+	if h.NumCols > uint64(len(b)-offset) {
+		return Header{}, 0, fmt.Errorf("%w: NumCols=%d exceeds remaining %d bytes", ErrTruncated, h.NumCols, len(b)-offset)
+	}
 	return h, offset, nil
 }
diff --git a/pkg/query/vectorized/measure/batchsource.go b/pkg/query/vectorized/measure/batchsource.go
index e40cfcb36..8574eb9ae 100644
--- a/pkg/query/vectorized/measure/batchsource.go
+++ b/pkg/query/vectorized/measure/batchsource.go
@@ -191,8 +191,10 @@ func (s *BatchSourceFromBatchResult) copyRowsInto(out *vectorized.RecordBatch,
 			}
 			fieldIdx++
 		case vectorized.RoleTimestamp, vectorized.RoleVersion,
-			vectorized.RoleSeriesID, vectorized.RoleShardID:
-			// Metadata roles handled above via parallel slices.
+			vectorized.RoleSeriesID, vectorized.RoleShardID,
+			vectorized.RoleElementID, vectorized.RoleOrderKey:
+			// Metadata roles handled above via parallel slices. ElementID/OrderKey
+			// are stream-only roles that never appear in a measure schema.
 		}
 	}
 	return nil
diff --git a/pkg/query/vectorized/measure/build_batch.go b/pkg/query/vectorized/measure/build_batch.go
index 426538830..aeefbeb67 100644
--- a/pkg/query/vectorized/measure/build_batch.go
+++ b/pkg/query/vectorized/measure/build_batch.go
@@ -100,9 +100,11 @@ func BuildMeasureBatchFromResult(r *model.MeasureResult, schema *vectorized.Batc
 			}
 			fieldCols = append(fieldCols, col)
 		case vectorized.RoleTimestamp, vectorized.RoleVersion,
-			vectorized.RoleSeriesID, vectorized.RoleShardID:
+			vectorized.RoleSeriesID, vectorized.RoleShardID,
+			vectorized.RoleElementID, vectorized.RoleOrderKey:
 			// Metadata roles are populated via the parallel slices on the
-			// MeasureBatch itself; no per-column entry is needed.
+			// MeasureBatch itself; no per-column entry is needed. ElementID/OrderKey
+			// are stream-only roles that never appear in a measure schema.
 		}
 	}
 
diff --git a/pkg/query/vectorized/measure/frame/decode_test.go b/pkg/query/vectorized/measure/frame/decode_test.go
index 5a79bbbe5..2d601662d 100644
--- a/pkg/query/vectorized/measure/frame/decode_test.go
+++ b/pkg/query/vectorized/measure/frame/decode_test.go
@@ -19,6 +19,7 @@ package frame
 
 import (
 	"bytes"
+	"encoding/binary"
 	"errors"
 	"math"
 	"testing"
@@ -284,6 +285,22 @@ func TestDecode_RoundTrip_MixedColumns(t *testing.T) {
 	}
 }
 
+// TestDecode_NumRowsExceedsBody guards the adversarial-header path: a near-2^64
+// NumRows must be rejected at ValidateHeader before the column decoder, where
+// (NumRows+7)/8 would overflow and make([]bool, NumRows) would OOM-panic. The
+// test completing without a panic is itself the assertion.
+func TestDecode_NumRowsExceedsBody(t *testing.T) {
+	var b []byte
+	b = append(b, Magic[:]...)
+	b = append(b, WireVersion)
+	b = binary.AppendUvarint(b, math.MaxUint64) // NumRows
+	b = binary.AppendUvarint(b, 1)              // NumCols=1
+	b = append(b, 0x01, 0x01)                   // partial column bytes; never reached
+	if _, err := Decode(b); !errors.Is(err, ErrTruncated) {
+		t.Fatalf("got %v, want ErrTruncated for NumRows exceeding body", err)
+	}
+}
+
 // TestDecode_BadMagic_FailsLoud covers the load-bearing fail-loud guard:
 // a body whose first 4 bytes do not match Magic is rejected with ErrBadMagic.
 func TestDecode_BadMagic_FailsLoud(t *testing.T) {
diff --git a/pkg/query/vectorized/measure/frame/frame.go b/pkg/query/vectorized/measure/frame/frame.go
index c3251d278..35d552102 100644
--- a/pkg/query/vectorized/measure/frame/frame.go
+++ b/pkg/query/vectorized/measure/frame/frame.go
@@ -15,14 +15,14 @@
 // specific language governing permissions and limitations
 // under the License.
 
-// Package frame defines the non-proto, vec-native columnar binary frame
+// Package frame binds the shared vec columnar frame codec
+// (pkg/query/vectorized/frame) to the measure engine. It supplies measure's
+// frame signature, wire version and role/type numbering; the byte layout is
+// the shared base's. It is the non-proto, vec-native columnar binary frame
 // carried as the SendResponse.body for TopicInternalMeasureQuery under the
-// G9f throughout-vec design. Encoders live here (G9f.2); the matching
-// decoder lands in G9f.3. The frame format is version-stamped and uses
-// frame-internal type/role enums with explicit numeric values so the wire
-// is stable against pkg/query/vectorized internal enum refactors.
+// G9f throughout-vec design.
 //
-// Wire layout (version 1):
+// Wire layout (version 3):
 //
 //	off  len       field            description
 //	---  --------  ---------------  ---------------------------------------------
@@ -32,156 +32,207 @@
 //	                                a non-nil error deterministically (G9f spec
 //	                                Principle 3, verified against
 //	                                google.golang.org/protobuf@v1.36.11).
-//	  4  1         WireVersion      currently 1.
+//	  4  1         WireVersion      currently 3.
 //	  5  uvarint   NumRows          number of (active) rows.
 //	  ?  uvarint   NumCols          number of column blocks.
 //	  ?  ...       Columns          NumCols column blocks, in schema order.
 //
-// Each column block (header + body):
+// Each column block carries role+type discriminators, the column name, a tag
+// family name (empty for non-RoleTag columns), a validity bitmap and a
+// type-specific data section; the exact byte shapes live in the shared base's
+// encode.go/decode.go.
 //
-//	off  len       field            description
-//	---  --------  ---------------  ---------------------------------------------
-//	  0  1         Role             frameColRole — explicit-value enum mirroring
-//	                                vectorized.ColumnRole.
-//	  1  1         Type             frameColType — explicit-value enum mirroring
-//	                                vectorized.ColumnType.
-//	  2  uvarint   NameLen          length of the UTF-8 column name.
-//	  ?  NameLen   Name             column name bytes.
-//	  ?  uvarint   TagFamilyLen     length of the UTF-8 tag family name (v2).
-//	                                Empty for non-RoleTag columns.
-//	  ?  TFL       TagFamily        tag family name bytes.
-//	  ?  ⌈N/8⌉     Validity bitmap  N = NumRows; bit i set ⇒ row i is NULL
-//	                                (matches the project's validityBitmap: bit=1
-//	                                means null). Empty for N=0.
-//	  ?  ...       Data             type-specific; see encodeColumn for shapes.
+// v1 → v2: each column block carries a uvarint(TagFamilyLen) + TagFamily byte
+// run after the Name so the row path's TagFamilyGroups grouping does not
+// collapse every projected tag family into the empty-name family.
 //
-// Per-type body encoding (N = NumRows; null-row slots are present but the
-// validity bitmap is the source of truth for nullness — decoders MUST treat
-// null-row data bytes as undefined):
-//
-//   - Int64:     N × 8 bytes little-endian.
-//   - Float64:   N × 8 bytes IEEE-754 little-endian.
-//   - String:    For each row in order: uvarint(len) + len UTF-8 bytes.
-//     Null rows have len=0 and 0 bytes; the validity bitmap
-//     disambiguates "null" from "empty string".
-//   - Bytes:     Same shape as String, opaque bytes.
+// v2 → v3: adds two column types — TagValue (5) and FieldValue (6) — that
+// carry proto-marshaled TagValue / FieldValue bytes per cell, so cross-group
+// queries with type-divergent tag/field declarations cross the wire intact.
 package frame
 
 import (
-	"errors"
+	"fmt"
 
 	"github.com/apache/skywalking-banyandb/api/data"
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+	baseframe "github.com/apache/skywalking-banyandb/pkg/query/vectorized/frame"
 )
 
-// Magic is the 4-byte prefix every raw vec columnar frame body MUST begin
-// with. The first byte is data.RawFrameMagicLeadingByte (0x00), which decodes
-// as a varint tag for protobuf field number 0 — protowire.ConsumeTag rejects
-// it with errCodeFieldNumber and proto/decode.go converts the negative tag
-// length into a hard errDecode *before* any unknown-field skip (verified
-// against google.golang.org/protobuf@v1.36.11). That deterministically forces
-// a flag-off node's proto.Unmarshal of a raw frame body into
-// *measurev1.InternalQueryResponse{} to return a non-nil error, collapsing
-// the "garbage-but-parsed silently-empty" failure mode into an unmistakable
-// hard decode error (G9f spec Principle 3, codec contract). The remaining
-// three bytes 'V','F','R' are a distinctive signature so a flag-on decoder
-// can recognize a valid frame from random noise on the same wire.
-var Magic = [4]byte{data.RawFrameMagicLeadingByte, 'V', 'F', 'R'}
-
 // WireVersion is the on-wire frame format version emitted by Encode. The
-// flag-on decoder MUST reject frames carrying any other version with a
-// loud typed error: the G9f hard-cutover model forbids dual-wire, so a
-// version skew on the wire is by definition a botched operator rollout,
-// not a coexistence to negotiate.
-//
-// v1 → v2: each column block now also carries a uvarint(TagFamilyLen) +
-// TagFamily byte run right after the Name. Without it, the row-side
-// serializer's TagFamilyGroups grouping collapsed every projected tag
-// family into the empty-name family on the receive side and produced
-// `tagFamilies[].name == ""` on the wire, diverging from the row path's
-// expected output.
-//
-// v2 → v3: adds two column types — frameColTagValueProto (5) and
-// frameColFieldValueProto (6) — that carry proto-marshaled TagValue /
-// FieldValue bytes per cell. These let cross-group queries with
-// type-divergent tag/field declarations (e.g. entity_id is STRING in
-// sw_metric vs INT in sw_updated) cross the wire intact: a typed wire
-// column can't represent mixed oneof variants, but proto-bytes-per-cell
-// can. The decoder reconstructs them as TypedColumn[*modelv1.TagValue]
-// / [*FieldValue] passthrough columns so serializeBatchToProto handles
-// them via the fast pointer-return path.
+// flag-on decoder MUST reject frames carrying any other version with a loud
+// typed error: the G9f hard-cutover model forbids dual-wire, so a version skew
+// on the wire is by definition a botched operator rollout, not a coexistence
+// to negotiate.
 const WireVersion uint8 = 3
 
+// Magic is the 4-byte prefix every raw measure frame body MUST begin with. The
+// first byte is data.RawFrameMagicLeadingByte (0x00), which decodes as a varint
+// tag for protobuf field number 0 — forcing a flag-off node's proto.Unmarshal
+// of a raw frame body into *measurev1.InternalQueryResponse{} to return a
+// non-nil error (G9f spec Principle 3). The remaining bytes 'V','F','R' are a
+// distinctive signature so a flag-on decoder can recognize a valid frame.
+var Magic = [4]byte{data.RawFrameMagicLeadingByte, 'V', 'F', 'R'}
+
 // MagicLen is the length of Magic in bytes.
-const MagicLen = 4
+const MagicLen = baseframe.MagicLen
 
-// MinHeaderLen is the smallest possible frame header — 4 magic bytes,
-// 1 version byte, and the minimal 1-byte uvarint encodings of NumRows=0
-// and NumCols=0.
-const MinHeaderLen = MagicLen + 1 + 1 + 1
+// MinHeaderLen is the smallest possible frame header — 4 magic bytes, 1
+// version byte, and the minimal 1-byte uvarint encodings of NumRows=0 and
+// NumCols=0.
+const MinHeaderLen = baseframe.MinHeaderLen
 
 // Header is the parsed frame header (everything up to but not including the
 // first column block).
-type Header struct {
-	NumRows     uint64
-	NumCols     uint64
-	Magic       [4]byte
-	WireVersion uint8
-}
+type Header = baseframe.Header
 
-// Sentinel errors. ValidateHeader (and the future decoder) wrap these with
-// context so callers can errors.Is against specific failure classes — most
-// importantly, ErrBadMagic at the very first byte is the engineered fail-loud
-// guard the G9f spec relies on.
+// Sentinel errors re-exported from the shared base so callers keep using
+// errors.Is against frame.ErrX; the identities are shared across the boundary.
 var (
 	// ErrTruncated signals a frame whose length is below the minimum header
 	// length, or whose declared lengths run past the buffer.
-	ErrTruncated = errors.New("vectorized.measure.frame: truncated frame")
-
-	// ErrBadMagic signals a frame whose leading 4 bytes do not match Magic.
-	// In particular a flag-off (proto) body received on the raw path will
-	// fail here loudly, never silently mis-decoded.
-	ErrBadMagic = errors.New("vectorized.measure.frame: bad magic")
-
-	// ErrBadVersion signals a frame whose WireVersion byte does not match
-	// the current WireVersion. Hard-cutover means there is no recovery —
-	// the receiver must surface this loudly.
-	ErrBadVersion = errors.New("vectorized.measure.frame: bad wire version")
-
-	// ErrUnsupportedColumnType signals that the encoder was handed a column
-	// whose pkg/query/vectorized.ColumnType does not have a frame mapping.
-	// Surfacing this at encode time prevents silently-wrong wire bytes.
-	ErrUnsupportedColumnType = errors.New("vectorized.measure.frame: unsupported column type")
-
-	// ErrUnsupportedColumnRole signals that the encoder was handed a column
-	// whose pkg/query/vectorized.ColumnRole does not have a frame mapping.
-	ErrUnsupportedColumnRole = errors.New("vectorized.measure.frame: unsupported column role")
-)
+	ErrTruncated = baseframe.ErrTruncated
 
-// frameColType is the explicit-value, wire-stable column-type discriminator.
-// Numeric values MUST NOT change between WireVersion bumps (or, if they do,
-// the WireVersion MUST bump and decoders MUST refuse the old version).
-type frameColType uint8
+	// ErrBadMagic signals a frame whose leading 4 bytes do not match Magic. A
+	// flag-off (proto) body received on the raw path fails here loudly.
+	ErrBadMagic = baseframe.ErrBadMagic
 
-// Frame column-type values. Add new types at the end; never reorder.
-const (
-	frameColInt64           frameColType = 1
-	frameColFloat64         frameColType = 2
-	frameColString          frameColType = 3
-	frameColBytes           frameColType = 4
-	frameColTagValueProto   frameColType = 5
-	frameColFieldValueProto frameColType = 6
+	// ErrBadVersion signals a frame whose WireVersion byte does not match the
+	// current WireVersion.
+	ErrBadVersion = baseframe.ErrBadVersion
+
+	// ErrUnsupportedColumnType signals that a column whose ColumnType has no
+	// wire mapping crossed the codec.
+	ErrUnsupportedColumnType = baseframe.ErrUnsupportedColumnType
+
+	// ErrUnsupportedColumnRole signals that a column whose ColumnRole has no
+	// wire mapping crossed the codec.
+	ErrUnsupportedColumnRole = baseframe.ErrUnsupportedColumnRole
 )
 
-// frameColRole is the explicit-value, wire-stable column-role discriminator.
-// Same stability contract as frameColType.
-type frameColRole uint8
+// Measure wire-role values. Explicit and stable: add new roles at the end,
+// never reorder.
+const (
+	wireRoleTimestamp uint8 = 1
+	wireRoleVersion   uint8 = 2
+	wireRoleSeriesID  uint8 = 3
+	wireRoleShardID   uint8 = 4
+	wireRoleTag       uint8 = 5
+	wireRoleField     uint8 = 6
+)
 
-// Frame column-role values. Add new roles at the end; never reorder.
+// Measure wire-type values. Explicit and stable. TagValue/FieldValue carry
+// proto-marshaled bytes per cell (v3).
 const (
-	frameRoleTimestamp frameColRole = 1
-	frameRoleVersion   frameColRole = 2
-	frameRoleSeriesID  frameColRole = 3
-	frameRoleShardID   frameColRole = 4
-	frameRoleTag       frameColRole = 5
-	frameRoleField     frameColRole = 6
+	wireTypeInt64      uint8 = 1
+	wireTypeFloat64    uint8 = 2
+	wireTypeString     uint8 = 3
+	wireTypeBytes      uint8 = 4
+	wireTypeTagValue   uint8 = 5
+	wireTypeFieldValue uint8 = 6
 )
+
+// codec is the measure-parameterized shared frame codec. All measure frame I/O
+// flows through this single instance so the wire mapping cannot diverge between
+// Encode and Decode.
+var codec = baseframe.Codec{
+	Magic:       Magic,
+	WireVersion: WireVersion,
+	RoleToWire:  roleToWire,
+	WireToRole:  wireToRole,
+	TypeToWire:  typeToWire,
+	WireToType:  wireToType,
+}
+
+func roleToWire(r vectorized.ColumnRole) (uint8, error) {
+	switch r {
+	case vectorized.RoleTimestamp:
+		return wireRoleTimestamp, nil
+	case vectorized.RoleVersion:
+		return wireRoleVersion, nil
+	case vectorized.RoleSeriesID:
+		return wireRoleSeriesID, nil
+	case vectorized.RoleShardID:
+		return wireRoleShardID, nil
+	case vectorized.RoleTag:
+		return wireRoleTag, nil
+	case vectorized.RoleField:
+		return wireRoleField, nil
+	default:
+		return 0, fmt.Errorf("%w: %d", baseframe.ErrUnsupportedColumnRole, r)
+	}
+}
+
+func wireToRole(b uint8) (vectorized.ColumnRole, error) {
+	switch b {
+	case wireRoleTimestamp:
+		return vectorized.RoleTimestamp, nil
+	case wireRoleVersion:
+		return vectorized.RoleVersion, nil
+	case wireRoleSeriesID:
+		return vectorized.RoleSeriesID, nil
+	case wireRoleShardID:
+		return vectorized.RoleShardID, nil
+	case wireRoleTag:
+		return vectorized.RoleTag, nil
+	case wireRoleField:
+		return vectorized.RoleField, nil
+	default:
+		return 0, fmt.Errorf("%w: %d", baseframe.ErrUnsupportedColumnRole, b)
+	}
+}
+
+func typeToWire(t vectorized.ColumnType) (uint8, error) {
+	switch t { //nolint:exhaustive // measure emits only the scalar/passthrough subset; other types fall through to the error return
+	case vectorized.ColumnTypeInt64:
+		return wireTypeInt64, nil
+	case vectorized.ColumnTypeFloat64:
+		return wireTypeFloat64, nil
+	case vectorized.ColumnTypeString:
+		return wireTypeString, nil
+	case vectorized.ColumnTypeBytes:
+		return wireTypeBytes, nil
+	case vectorized.ColumnTypeTagValue:
+		return wireTypeTagValue, nil
+	case vectorized.ColumnTypeFieldValue:
+		return wireTypeFieldValue, nil
+	default:
+		return 0, fmt.Errorf("%w: %s", baseframe.ErrUnsupportedColumnType, t.String())
+	}
+}
+
+func wireToType(b uint8) (vectorized.ColumnType, error) {
+	switch b {
+	case wireTypeInt64:
+		return vectorized.ColumnTypeInt64, nil
+	case wireTypeFloat64:
+		return vectorized.ColumnTypeFloat64, nil
+	case wireTypeString:
+		return vectorized.ColumnTypeString, nil
+	case wireTypeBytes:
+		return vectorized.ColumnTypeBytes, nil
+	case wireTypeTagValue:
+		return vectorized.ColumnTypeTagValue, nil
+	case wireTypeFieldValue:
+		return vectorized.ColumnTypeFieldValue, nil
+	default:
+		return 0, fmt.Errorf("%w: %d", baseframe.ErrUnsupportedColumnType, b)
+	}
+}
+
+// Encode serializes a measure vec columnar RecordBatch into a raw frame body.
+func Encode(b *vectorized.RecordBatch) ([]byte, error) {
+	return codec.Encode(b)
+}
+
+// Decode parses a measure raw frame body back into a RecordBatch.
+func Decode(b []byte) (*vectorized.RecordBatch, error) {
+	return codec.Decode(b)
+}
+
+// ValidateHeader is the fail-loud preflight a decoder calls before parsing any
+// column data. It rejects a frame whose magic or wire-version does not match
+// this codec, and returns the parsed Header plus the bytes consumed.
+func ValidateHeader(b []byte) (Header, int, error) {
+	return codec.ValidateHeader(b)
+}
diff --git a/pkg/query/vectorized/schema.go b/pkg/query/vectorized/schema.go
index 0ac57fb13..20d04bd4a 100644
--- a/pkg/query/vectorized/schema.go
+++ b/pkg/query/vectorized/schema.go
@@ -28,6 +28,8 @@ const (
 	RoleShardID
 	RoleTag
 	RoleField
+	RoleElementID
+	RoleOrderKey
 )
 
 // ColumnDef describes one column in a BatchSchema.
@@ -67,6 +69,8 @@ type BatchSchema struct {
 	versionIdx      int
 	seriesIDIdx     int
 	shardIDIdx      int
+	elementIDIdx    int
+	orderKeyIdx     int
 }
 
 // NewBatchSchema builds a BatchSchema and precomputes lookup indices.
@@ -77,6 +81,8 @@ func NewBatchSchema(cols []ColumnDef) *BatchSchema {
 		versionIdx:   -1,
 		seriesIDIdx:  -1,
 		shardIDIdx:   -1,
+		elementIDIdx: -1,
+		orderKeyIdx:  -1,
 		tagByPath:    make(map[tagKey]int),
 		fieldByName:  make(map[string]int),
 	}
@@ -103,6 +109,10 @@ func NewBatchSchema(cols []ColumnDef) *BatchSchema {
 		case RoleField:
 			s.fieldByName[c.Name] = i
 			s.FieldColumns = append(s.FieldColumns, i)
+		case RoleElementID:
+			s.elementIDIdx = i
+		case RoleOrderKey:
+			s.orderKeyIdx = i
 		}
 	}
 	return s
@@ -120,6 +130,12 @@ func (s *BatchSchema) SeriesIDIndex() int { return s.seriesIDIdx }
 // ShardIDIndex returns the shard-id column index, or -1 if absent.
 func (s *BatchSchema) ShardIDIndex() int { return s.shardIDIdx }
 
+// ElementIDIndex returns the element-id column index, or -1 if absent.
+func (s *BatchSchema) ElementIDIndex() int { return s.elementIDIdx }
+
+// OrderKeyIndex returns the order-key column index, or -1 if absent.
+func (s *BatchSchema) OrderKeyIndex() int { return s.orderKeyIdx }
+
 // TagIndex returns the column index for a (family, name) tag.
 // Lookup uses a struct key, so it does not allocate.
 func (s *BatchSchema) TagIndex(family, name string) (int, bool) {
diff --git a/pkg/query/vectorized/stream/columns.go b/pkg/query/vectorized/stream/columns.go
new file mode 100644
index 000000000..841ab5f36
--- /dev/null
+++ b/pkg/query/vectorized/stream/columns.go
@@ -0,0 +1,61 @@
+// 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.
+
+package stream
+
+import "github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+
+// Metadata column names for the stream vectorized batch schema.
+const (
+	StreamColumnNameTimestamp = "timestamp"
+	StreamColumnNameElementID = "elementID"
+	StreamColumnNameSeriesID  = "seriesID"
+	StreamColumnNameOrderKey  = "orderKey"
+)
+
+// activeIndices returns the active row indices of a batch: the selection when
+// present, or [0, Len) materialized when the selection is nil.
+func activeIndices(batch *vectorized.RecordBatch) []uint16 {
+	if batch.Selection != nil {
+		return batch.Selection
+	}
+	out := make([]uint16, batch.Len)
+	for rowIdx := range out {
+		out[rowIdx] = uint16(rowIdx)
+	}
+	return out
+}
+
+// streamTimestamps returns the timestamp column of a stream batch.
+func streamTimestamps(batch *vectorized.RecordBatch) *vectorized.TypedColumn[int64] {
+	return batch.Columns[batch.Schema.TimestampIndex()].(*vectorized.TypedColumn[int64])
+}
+
+// streamElementIDs returns the element-id column of a stream batch.
+func streamElementIDs(batch *vectorized.RecordBatch) *vectorized.TypedColumn[int64] {
+	return batch.Columns[batch.Schema.ElementIDIndex()].(*vectorized.TypedColumn[int64])
+}
+
+// streamOrderKeys returns the order-key column of a stream batch, or nil when
+// the batch is not index-ordered (no order-key column present).
+func streamOrderKeys(batch *vectorized.RecordBatch) *vectorized.TypedColumn[[]byte] {
+	idx := batch.Schema.OrderKeyIndex()
+	if idx < 0 {
+		return nil
+	}
+	return batch.Columns[idx].(*vectorized.TypedColumn[[]byte])
+}
diff --git a/pkg/query/vectorized/stream/config.go b/pkg/query/vectorized/stream/config.go
new file mode 100644
index 000000000..70d9ca01f
--- /dev/null
+++ b/pkg/query/vectorized/stream/config.go
@@ -0,0 +1,84 @@
+// 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.
+
+package stream
+
+import (
+	"fmt"
+	"math"
+
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+)
+
+// VectorizedConfig controls the v1 vectorized Stream query path.
+type VectorizedConfig struct {
+	BatchSize int
+	// QueryMemoryMiB is a soft element-loading threshold: it caps the cumulative
+	// uncompressed element bytes fetched from disk per query. Tags, record-batch
+	// overhead, and other per-query allocations are not counted. The first block
+	// always loads regardless of the budget (first-block exception), so a single
+	// oversized block may exceed this value.
+	QueryMemoryMiB int
+	Enabled        bool
+}
+
+// DefaultConfig returns the default stream vectorized configuration — enabled,
+// with the shared default batch size and a 256 MiB per-query memory budget.
+//
+// The query layer dedups by element_id and holds the seen-set for the whole query,
+// because an element_id identifies an element GLOBALLY: two rows carrying one
+// element_id are one element, whatever their timestamps or which parts they were
+// read from. test/cases/stream's "deduplication test" pins that — 50 records over 27
+// distinct ids at 50 different timestamps must come back as 27 rows.
+//
+// The row path uses the same key but allocates its seen-set per merge round
+// (blockCursorHeap.merge / model.MergeStreamResults, one per runTabScanner call), so
+// it only collapses duplicates that land in the same round. That is a weaker
+// guarantee than this path gives, not a different semantic; a fixture that reuses an
+// element_id across two writes is malformed either way.
+//
+// Enabled also selects the liaison<->data wire format: a flag-on distributed data
+// node emits the native columnar frame instead of protobuf. A liaison decodes both
+// (it dispatches on the frame magic byte per message), but an older liaison has no
+// frame decoder at all, so a cluster must upgrade liaison nodes BEFORE data nodes.
+// See docs/operation/upgrade.md.
+//
+// To roll back the vec path entirely, pass --stream-vectorized-enabled=false on the
+// standalone or data-node command line and restart; the row path resumes immediately.
+func DefaultConfig() VectorizedConfig {
+	return VectorizedConfig{
+		Enabled:        true,
+		BatchSize:      vectorized.DefaultBatchSize,
+		QueryMemoryMiB: 256,
+	}
+}
+
+// Validate rejects invalid stream vectorized configurations.
+func (c VectorizedConfig) Validate() error {
+	if c.BatchSize <= 0 {
+		return fmt.Errorf("vectorized.stream: BatchSize must be > 0, got %d", c.BatchSize)
+	}
+	// A batch's Selection is []uint16, so a batch cannot hold more than
+	// math.MaxUint16 rows without overflowing the selection index.
+	if c.BatchSize > math.MaxUint16 {
+		return fmt.Errorf("vectorized.stream: BatchSize must be <= %d, got %d", math.MaxUint16, c.BatchSize)
+	}
+	if c.QueryMemoryMiB <= 0 {
+		return fmt.Errorf("vectorized.stream: QueryMemoryMiB must be > 0, got %d", c.QueryMemoryMiB)
+	}
+	return nil
+}
diff --git a/pkg/query/vectorized/trace/config_test.go b/pkg/query/vectorized/stream/config_test.go
similarity index 72%
copy from pkg/query/vectorized/trace/config_test.go
copy to pkg/query/vectorized/stream/config_test.go
index b523c37a0..7e81ef2b8 100644
--- a/pkg/query/vectorized/trace/config_test.go
+++ b/pkg/query/vectorized/stream/config_test.go
@@ -15,9 +15,10 @@
 // specific language governing permissions and limitations
 // under the License.
 
-package trace
+package stream
 
 import (
+	"math"
 	"testing"
 
 	"github.com/stretchr/testify/require"
@@ -27,7 +28,10 @@ import (
 
 func TestDefaultConfig(t *testing.T) {
 	cfg := DefaultConfig()
-	require.False(t, cfg.Enabled)
+	// Enabled is the default: it selects both the vec query path and the native
+	// columnar liaison<->data wire frame. Flipping it is a wire format change — see
+	// docs/operation/upgrade.md for the upgrade ordering rule.
+	require.True(t, cfg.Enabled)
 	require.Equal(t, vectorized.DefaultBatchSize, cfg.BatchSize)
 	require.Equal(t, 256, cfg.QueryMemoryMiB)
 	require.NoError(t, cfg.Validate())
@@ -37,4 +41,7 @@ func TestVectorizedConfigValidate(t *testing.T) {
 	require.Error(t, VectorizedConfig{BatchSize: 0, QueryMemoryMiB: 256}.Validate())
 	require.Error(t, VectorizedConfig{BatchSize: 1, QueryMemoryMiB: 0}.Validate())
 	require.NoError(t, VectorizedConfig{BatchSize: 1, QueryMemoryMiB: 1}.Validate())
+	// A batch Selection is []uint16, so BatchSize must fit in a uint16.
+	require.NoError(t, VectorizedConfig{BatchSize: math.MaxUint16, QueryMemoryMiB: 1}.Validate())
+	require.Error(t, VectorizedConfig{BatchSize: math.MaxUint16 + 1, QueryMemoryMiB: 1}.Validate())
 }
diff --git a/pkg/query/vectorized/trace/config_test.go b/pkg/query/vectorized/stream/counters.go
similarity index 54%
copy from pkg/query/vectorized/trace/config_test.go
copy to pkg/query/vectorized/stream/counters.go
index b523c37a0..9ff1bead3 100644
--- a/pkg/query/vectorized/trace/config_test.go
+++ b/pkg/query/vectorized/stream/counters.go
@@ -15,26 +15,20 @@
 // specific language governing permissions and limitations
 // under the License.
 
-package trace
+package stream
 
-import (
-	"testing"
+import "sync/atomic"
 
-	"github.com/stretchr/testify/require"
+// Process-wide observability counter. Integration tests snapshot QueryCount()
+// before the test table runs and assert the delta is > 0 to prove the
+// vectorized stream path actually fired (vs silently falling back to the row
+// path for a shape it does not vectorize).
+var queryCount atomic.Int64
 
-	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
-)
+// QueryCount returns the cumulative number of vectorized stream queries executed
+// by this process.
+func QueryCount() int64 { return queryCount.Load() }
 
-func TestDefaultConfig(t *testing.T) {
-	cfg := DefaultConfig()
-	require.False(t, cfg.Enabled)
-	require.Equal(t, vectorized.DefaultBatchSize, cfg.BatchSize)
-	require.Equal(t, 256, cfg.QueryMemoryMiB)
-	require.NoError(t, cfg.Validate())
-}
-
-func TestVectorizedConfigValidate(t *testing.T) {
-	require.Error(t, VectorizedConfig{BatchSize: 0, QueryMemoryMiB: 256}.Validate())
-	require.Error(t, VectorizedConfig{BatchSize: 1, QueryMemoryMiB: 0}.Validate())
-	require.NoError(t, VectorizedConfig{BatchSize: 1, QueryMemoryMiB: 1}.Validate())
-}
+// IncrQueryCount increments the process-wide vectorized stream query counter.
+// Called when the vectorized execution path is taken for a stream query.
+func IncrQueryCount() { queryCount.Add(1) }
diff --git a/pkg/query/vectorized/stream/distinct.go b/pkg/query/vectorized/stream/distinct.go
new file mode 100644
index 000000000..b730ae407
--- /dev/null
+++ b/pkg/query/vectorized/stream/distinct.go
@@ -0,0 +1,79 @@
+// 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.
+
+package stream
+
+import (
+	"context"
+
+	"github.com/apache/skywalking-banyandb/pkg/query/vectorized"
+)
+
+// Distinct deduplicates stream rows by ElementID, keeping the first occurrence
+// in the (already merged) input order. It is stateful across batches via a seen
+// set keyed by the raw uint64 element id, mirroring the row path's first-seen
+// dedup (stream_plan_distributed.go seen map keyed by ElementId). It MUST run
+// downstream of SortedMerge so "first occurrence" reflects the global order.
+type Distinct struct {
+	schema  *vectorized.BatchSchema
+	seen    map[uint64]struct{}
+	elemIdx int
+	closed  bool
+}
+
+// NewDistinct constructs a stream first-seen dedup fusible.
+func NewDistinct(schema *vectorized.BatchSchema) *Distinct {
+	return &Distinct{schema: schema, elemIdx: schema.ElementIDIndex()}
+}
+
+// Init resets the seen set.
... 4251 lines suppressed ...