JackieTien97 commented on code in PR #179:
URL: https://github.com/apache/iotdb-client-go/pull/179#discussion_r4609795803


##########
subscription/consumer/provider.go:
##########
@@ -0,0 +1,498 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package consumer
+
+import (
+       "github.com/apache/iotdb-client-go/subscription"
+       "github.com/apache/iotdb-client-go/subscription/payload"
+       "github.com/apache/iotdb-client-go/subscription/internal/protocol"
+       "github.com/apache/iotdb-client-go/subscription/internal/rpcsession"
+       "github.com/apache/iotdb-client-go/subscription/internal/wire"
+
+       "context"
+       "errors"
+       "strconv"
+       "strings"
+       "sync/atomic"
+
+       "github.com/apache/thrift/lib/go/thrift"
+
+       "github.com/apache/iotdb-client-go/v2/client"
+       "github.com/apache/iotdb-client-go/v2/common"
+       "github.com/apache/iotdb-client-go/v2/rpc"
+)
+
+const (
+       subscriptionFrameReserve = 1024
+       // Oversized-entry status is returned by servers that enforce 
subscription
+       // materialization limits. Keep the compatibility value local to the 
consumer.
+       subscriptionOversizedEntryStatus int32 = 1920

Review Comment:
   **Status 1920 is classified as an oversized entry 
(`ErrorKindPayloadExceed`), but in IoTDB 1920 is 
`SUBSCRIPTION_CONNECTION_REPLACED`.** It was added in apache/iotdb#19130, and 
the DataNode returns it for requests sent on a connection that a reconnection 
from the same consumer instance has replaced.
   
   Java treats it as a retryable connection failure. 
`AbstractSubscriptionProvider` converts 1920 into 
`SubscriptionConnectionException` and marks the provider unavailable, as 
asserted by 
`SubscriptionProviderStatusTest#testReplacedConnectionStatusIsRetryable` and 
`SubscriptionProviderConnectionTimeoutTest#testReplacedConnectionIsRetryableForPollAndCommit`.
 `AbstractSubscriptionConsumer#pollInternal` then catches the exception, 
schedules `syncIfUnavailable`, and returns an empty list.
   
   Here, `verifySubscriptionProviderStatus` (L468) reports 
`Kind=ErrorKindPayloadExceed`, and `Poll` returns the error to the caller. I 
reproduced this with an in-process fake Thrift server that answers POLL with 
1920: `Poll` returned `subscription: server status 1920: ...`, and `errors.As` 
yielded `Kind=6` (`ErrorKindPayloadExceed`). The connection abort at L245 and 
the follow-up recovery do match Java.
   
   The oversized-entry condition reaches the client in the poll body as a 
critical `ErrorPayload` whose message contains `SUBSCRIPTION_OVERSIZED_ENTRY`. 
`newSubscriptionPollError` already handles that case, so it is unrelated to 
this status code.
   
   Suggestion: add `SubscriptionConnectionReplaced int32 = 1920` next to the 
other subscription codes in `client/protocol.go`, classify it as 
`ErrorKindConnection`, and treat it on the poll path as a retryable provider 
failure, as Java does. The `status.Code != subscriptionOversizedEntryStatus` 
check in `commitNode` (pull_progress.go L336) already makes 1920 retryable for 
commits, which looks intended; only the name and classification need to change.



##########
subscription/config.go:
##########
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package subscription
+
+import "time"
+
+// Dialect selects one data model for an instance. A shared subscription 
interface
+// does not imply that tree and table connections or record decoding are 
identical.
+type Dialect string
+
+const (
+       // TreeDialect selects tree-model connections and record interpretation.
+       TreeDialect Dialect = "tree"
+       // TableDialect selects table-model connections and record 
interpretation.
+       TableDialect Dialect = "table"
+)
+
+// ConnectionConfig describes the RPC connections owned by a subscription 
client.
+// Password and EncryptedPassword are mutually exclusive. NodeURLs contains
+// host:port addresses and supports a single node as well as a cluster seed 
list.
+type ConnectionConfig struct {

Review Comment:
   **TLS gap compared with Java.** The Java subscription session and consumer 
builders support `useSSL`, `trustStore`, `trustStorePwd`, `keyStore`, 
`keyStorePwd` and `sslProtocol`, so Java consumers can connect to SSL-enabled 
clusters. `ConnectionConfig` has no TLS option, and `doc.go` states that none 
is exposed, even though the Session client in this repo already supports 
`client.Config.TLSConfig`.
   
   Please either add a TLS option that reuses the existing transport support, 
or list this next to the TsFile limitation in the documented differences, so 
users of SSL-enabled clusters know the Go consumer cannot connect.



##########
test/e2e/config_test.go:
##########
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package e2e
+
+import (
+       "os"
+       "strings"
+       "testing"
+       "time"
+
+       "github.com/apache/iotdb-client-go/subscription"
+       subsession "github.com/apache/iotdb-client-go/subscription/session"
+       "github.com/apache/iotdb-client-go/v2/client"
+)
+
+const (
+       e2eDefaultNodeURLs  = "iotdb:6668,iotdb:6667,iotdb:6669"
+       e2eDefaultTableHost = "iotdb"
+       e2eDefaultTablePort = "6667"
+       e2eDefaultUsername  = "root"
+       e2eDefaultPassword  = "root"
+)
+
+var (
+       e2eNodeURLs = e2eDefaultValue("IOTDB_E2E_NODE_URLS", "", 
e2eDefaultNodeURLs)
+       e2eUsername = e2eDefaultValue("IOTDB_E2E_USERNAME", "IOTDB_USERNAME", 
e2eDefaultUsername)
+       e2ePassword = e2eValueOrFallback("IOTDB_E2E_PASSWORD", 
"IOTDB_PASSWORD", e2eDefaultPassword)
+)
+
+// Subscription cases are discovered by the normal go test run but require an
+// explicit environment opt-in. Endpoint and credential defaults come from the
+// shared E2E configuration.
+const (
+       subscriptionE2EDefaultEnabled = false

Review Comment:
   **Most of the subscription client is not exercised in CI.** Because the E2E 
tests are opt-in, the Apache e2e job reports all 24 `TestSubscription*` cases 
as `--- SKIP`.
   
   Unit-test coverage of the module, measured with `go test -cover ./...` under 
`subscription/`, is 11.4% overall: `consumer` 0.1%, `internal/protocol` 34.6%, 
`processor` 77.2%. The poll, commit, seek, recovery and push logic in 
`consumer` therefore has almost no automated verification in this repo's CI.
   
   Could you add unit tests against an in-process fake Thrift server 
(`rpc.NewIClientRPCServiceProcessor` with `thrift.NewTSimpleServer4`)? A fake 
of about 150 lines was enough to reproduce the 1920 and Push cases above, so 
covering the main error, redirect-ACK and recovery branches should be cheap.



##########
test/e2e/subscription_tree_test.go:
##########
@@ -0,0 +1,1019 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package e2e
+
+import (
+       "context"
+       "errors"
+       "fmt"
+       "reflect"
+       "strings"
+       "sync/atomic"
+       "testing"
+       "time"
+
+       "github.com/apache/iotdb-client-go/subscription"
+       subconsumer "github.com/apache/iotdb-client-go/subscription/consumer"
+       subpayload "github.com/apache/iotdb-client-go/subscription/payload"
+       subsession "github.com/apache/iotdb-client-go/subscription/session"
+       "github.com/apache/iotdb-client-go/v2/client"
+)
+
+func subscriptionE2EContext(t *testing.T) context.Context {
+       t.Helper()
+       ctx, cancel := context.WithTimeout(context.Background(), 
subscriptionE2ETestTimeout)
+       t.Cleanup(cancel)
+       return ctx
+}
+
+var subscriptionE2ESequence atomic.Uint64
+
+func subscriptionE2EName(prefix string) string {
+       return fmt.Sprintf("%s_%d_%d", prefix, time.Now().UnixNano(), 
subscriptionE2ESequence.Add(1))
+}
+
+func subscriptionE2EManager(t *testing.T, connection 
subscription.ConnectionConfig, dialect subscription.Dialect) 
subsession.SubscriptionSession {
+       t.Helper()
+       config := subsession.DefaultSubscriptionSessionConfig()
+       config.Connection, config.Dialect = connection, dialect
+       manager, err := subsession.NewSubscriptionSession(config)
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(func() {
+               if err := manager.Close(); err != nil {
+                       t.Errorf("close subscription manager: %v", err)
+               }
+       })
+       ctx, cancel := context.WithTimeout(context.Background(), 
subscriptionE2EOpenTimeout)
+       defer cancel()
+       if err := manager.Open(ctx); err != nil {
+               t.Fatal(err)
+       }
+       return manager
+}
+
+func subscriptionE2ETopic(t *testing.T, ctx context.Context, manager 
subsession.SubscriptionSession, name string, attributes map[string]string) {
+       t.Helper()
+       if err := manager.CreateTopic(ctx, name, 
subsession.CreateTopicOptions{Attributes: attributes}); err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(func() {
+               cleanupCtx, cancel := context.WithTimeout(context.Background(), 
subscriptionE2ECleanupTimeout)
+               defer cancel()
+               for {
+                       err := manager.DropTopic(cleanupCtx, name, 
subsession.DropOptions{IfExists: true})
+                       if err == nil {
+                               return
+                       }
+                       select {
+                       case <-cleanupCtx.Done():
+                               t.Errorf("drop topic %s: %v", name, err)
+                               return
+                       case <-time.After(100 * time.Millisecond):
+                       }
+               }
+       })
+}
+
+func subscriptionE2EPull(t *testing.T, ctx context.Context, connection 
subscription.ConnectionConfig, dialect subscription.Dialect, topic string, 
autoCommit bool) subconsumer.SubscriptionPullConsumer {
+       t.Helper()
+       config := subconsumer.DefaultSubscriptionPullConsumerConfig()
+       config.Consumer.Connection, config.Consumer.Dialect = connection, 
dialect
+       config.Consumer.HeartbeatInterval = subscriptionE2EHeartbeatInterval
+       config.Consumer.EndpointsSyncInterval = 
subscriptionE2EEndpointsSyncInterval
+       config.AutoCommit, config.AutoCommitInterval = &autoCommit, 
subscriptionE2EAutoCommitInterval
+       consumer, err := subconsumer.NewSubscriptionPullConsumer(config)
+       if err != nil {
+               t.Fatal(err)
+       }
+       // Keep subscriptions until Close can finish any pending automatic ACKs.
+       t.Cleanup(func() {
+               if err := consumer.Close(); err != nil {
+                       t.Errorf("close pull consumer: %v", err)
+               }
+       })
+       if err := consumer.Open(ctx); err != nil {
+               t.Fatal(err)
+       }
+       if err := consumer.Subscribe(ctx, topic); err != nil {
+               t.Fatal(err)
+       }
+       return consumer
+}
+
+func subscriptionTreeWriter(t *testing.T, connection 
subscription.ConnectionConfig) (*client.Session, string) {
+       t.Helper()
+       session, err := client.NewClusterSession(&client.ClusterConfig{
+               NodeUrls: connection.NodeURLs,
+               UserName: connection.Username,
+               Password: connection.Password,
+       })
+       if err != nil {
+               t.Fatal(err)
+       }
+       if err := session.Open(false, subscriptionE2EWriterTimeoutMs); err != 
nil {
+               _ = session.Close()
+               t.Fatal(err)
+       }
+       database := "root." + subscriptionE2EName("sub_tree")
+       t.Cleanup(func() {
+               // The existing Session API has no per-statement context 
argument.
+               if err := session.ExecuteNonQueryStatement("DELETE DATABASE " + 
database); err != nil {
+                       t.Errorf("delete tree database: %v", err)
+               }
+               if err := session.Close(); err != nil {
+                       t.Errorf("close tree writer: %v", err)
+               }
+       })
+       subscriptionTreeSQL(t, &session, "CREATE DATABASE "+database)
+       for _, series := range []string{".d1.s1", ".d1.s2", ".d2.s1"} {
+               subscriptionTreeSQL(t, &session, "CREATE TIMESERIES 
"+database+series+" WITH DATATYPE=INT64, ENCODING=RLE")
+       }
+       return &session, database
+}
+
+func subscriptionTreeSQL(t *testing.T, writer *client.Session, sql string) {
+       t.Helper()
+       if err := writer.ExecuteNonQueryStatement(sql); err != nil {
+               t.Fatalf("tree statement failed: %v", err)
+       }
+}
+
+type subscriptionTreeRow struct {
+       target    string
+       column    string
+       timestamp int64
+       value     int64
+}
+
+func subscriptionTreeInsert(t *testing.T, writer *client.Session, database, 
device, column string, timestamp, value int64) subscriptionTreeRow {
+       t.Helper()
+       target := database + "." + device
+       subscriptionTreeSQL(t, writer, fmt.Sprintf("INSERT INTO %s(time,%s) 
VALUES (%d,%d)", target, column, timestamp, value))
+       return subscriptionTreeRow{target: target, column: column, timestamp: 
timestamp, value: value}
+}
+
+func subscriptionTreeRows(ctx context.Context, message 
subpayload.SubscriptionMessage) ([]subscriptionTreeRow, error) {
+       batches, err := message.Records()
+       if err != nil {
+               return nil, err
+       }
+       var records []subscriptionTreeRow
+       for _, batch := range batches {
+               if batch.Dialect() != subscription.TreeDialect {
+                       return nil, fmt.Errorf("unexpected batch dialect %s", 
batch.Dialect())
+               }
+               columns := batch.Columns()
+               for row, err := range batch.Rows() {
+                       if err != nil {
+                               return nil, err
+                       }
+                       if err := ctx.Err(); err != nil {
+                               return nil, err
+                       }
+                       if row.Timestamp == nil || len(row.Values) != 
len(columns) {
+                               return nil, errors.New("tree row lost timestamp 
or column mapping")
+                       }
+                       for index, value := range row.Values {
+                               if value == nil {
+                                       continue
+                               }
+                               integer, ok := value.(int64)
+                               if !ok {
+                                       return nil, fmt.Errorf("unexpected tree 
value %T", value)
+                               }
+                               records = append(records, 
subscriptionTreeRow{target: batch.Target(), column: columns[index].Name, 
timestamp: *row.Timestamp, value: integer})
+                       }
+               }
+       }
+       return records, nil
+}
+
+func subscriptionTreeCollect(t *testing.T, ctx context.Context, consumer 
subconsumer.SubscriptionPullConsumer, expected int, manual, snapshot bool) 
map[subscriptionTreeRow]int {
+       t.Helper()
+       seen := make(map[subscriptionTreeRow]int)
+       empty := 0
+       for round := 0; round < subscriptionE2EMaxPollRounds; round++ {
+               messages, err := consumer.Poll(ctx, subscriptionE2EPollTimeout)
+               if err != nil {
+                       t.Fatal(err)
+               }
+               rows, err := subscriptionTreeReadAndCommit(ctx, consumer, 
messages, manual)
+               if err != nil {
+                       t.Fatal(err)
+               }
+               for _, row := range rows {
+                       seen[row]++
+               }
+               if len(messages) == 0 {
+                       empty++
+               } else {
+                       empty = 0
+               }
+               if snapshot {
+                       if consumer.AllConsumed() {
+                               return seen
+                       }
+               } else if len(seen) >= expected && empty >= 
subscriptionE2EQuietPollRounds {
+                       return seen
+               }
+       }
+       t.Fatalf("did not reach completion/quiet tail; rows=%v snapshot=%t", 
seen, snapshot)
+       return nil
+}
+
+func subscriptionTreeReadAndCommit(ctx context.Context, consumer 
subconsumer.SubscriptionPullConsumer, messages 
[]subpayload.SubscriptionMessage, manual bool) ([]subscriptionTreeRow, error) {
+       defer func() {
+               for _, message := range messages {
+                       message.Release()
+               }
+       }()
+       var records []subscriptionTreeRow
+       for _, message := range messages {
+               rows, err := subscriptionTreeRows(ctx, message)
+               if err != nil {
+                       return nil, err
+               }
+               if manual {
+                       if err := consumer.Commit(ctx, message); err != nil {
+                               return nil, err
+                       }
+               }
+               records = append(records, rows...)
+       }
+       return records, nil
+}
+
+func subscriptionTreeRequireRows(t *testing.T, actual 
map[subscriptionTreeRow]int, rows ...subscriptionTreeRow) {
+       t.Helper()
+       expected := make(map[subscriptionTreeRow]int)
+       for _, row := range rows {
+               expected[row]++
+       }
+       if !reflect.DeepEqual(actual, expected) {
+               t.Fatalf("tree rows differ: actual=%v expected=%v", actual, 
expected)
+       }
+}
+
+// Reference: local/IoTDBSubscriptionTopicIT.testBasicCreateTopic* and
+// testBasicDropTopic* under Java's subscription/it directory. SHOW assertions
+// follow an actual subscription rather than inspecting consumer configuration.
+func TestSubscriptionTreeTopicManagement(t *testing.T) {
+       connection := subscriptionE2EConnection(t)
+       ctx := subscriptionE2EContext(t)
+       writer, database := subscriptionTreeWriter(t, connection)
+       subscriptionTreeInsert(t, writer, database, "d1", "s1", 0, 0)
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       manager := subscriptionE2EManager(t, connection, 
subscription.TreeDialect)
+       topic := subscriptionE2EName("tree_management")
+       path := database + ".d1.s1"
+       subscriptionE2ETopic(t, ctx, manager, topic, 
map[string]string{"format": "SubscriptionRecordHandler", "path": path})
+       if err := manager.CreateTopic(ctx, topic, 
subsession.CreateTopicOptions{IfNotExists: true, Attributes: 
map[string]string{"path": database + ".d2.**"}}); err != nil {
+               t.Fatal(err)
+       }
+       metadata, found, err := manager.Topic(ctx, topic)
+       if err != nil || !found || !strings.Contains(metadata.Attributes, 
"path="+path) {
+               t.Fatalf("conditional creation changed existing topic: %+v 
found=%t error=%v", metadata, found, err)
+       }
+       topics, err := manager.Topics(ctx)
+       if err != nil {
+               t.Fatal(err)
+       }
+       listed := false
+       for _, record := range topics {
+               if record.Name == topic {
+                       listed = true
+               }
+       }
+       if !listed {
+               t.Fatalf("created topic missing from SHOW TOPICS: %+v", topics)
+       }
+       if err := manager.AlterTopic(ctx, topic, 
map[string]string{"start-time": "10"}); err != nil {
+               t.Fatal(err)
+       }
+       metadata, found, err = manager.Topic(ctx, topic)
+       if err != nil || !found || !strings.Contains(metadata.Attributes, 
"start-time=10") {
+               t.Fatalf("altered topic not visible: %+v found=%t error=%v", 
metadata, found, err)
+       }
+       consumer := subscriptionE2EPull(t, ctx, connection, 
subscription.TreeDialect, topic, false)
+       subscriptions, err := manager.Subscriptions(ctx, topic)
+       if err != nil {
+               t.Fatal(err)
+       }
+       visible := false
+       for _, record := range subscriptions {
+               if record.Topic == topic && record.GroupID == 
consumer.Info().GroupID {
+                       visible = true
+               }
+       }
+       if !visible {
+               t.Fatalf("subscribed group missing from SHOW SUBSCRIPTIONS: 
%+v", subscriptions)
+       }
+       if err := consumer.Unsubscribe(ctx, topic); err != nil {
+               t.Fatal(err)
+       }
+       if err := consumer.Close(); err != nil {
+               t.Fatal(err)
+       }
+       for repeat := 0; repeat < 2; repeat++ {
+               if err := manager.DropTopic(ctx, topic, 
subsession.DropOptions{IfExists: true}); err != nil {
+                       t.Fatal(err)
+               }
+       }
+       if _, found, err := manager.Topic(ctx, topic); err != nil || found {
+               t.Fatalf("dropped topic still visible: found=%t error=%v", 
found, err)
+       }
+}
+
+// Reference: dual/treemodel/IoTDBSubscriptionTopicIT.testTabletTopicWithPath
+// and testTabletTopicWithTime, combined with explicit excluded-data 
assertions.
+func TestSubscriptionTreePullFiltersPathAndTime(t *testing.T) {
+       connection := subscriptionE2EConnection(t)
+       ctx := subscriptionE2EContext(t)
+       writer, database := subscriptionTreeWriter(t, connection)
+       want := []subscriptionTreeRow{
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 25, 
125),
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 50, 
150),
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 75, 
175),
+       }
+       for _, timestamp := range []int64{0, 24, 76, 100} {
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 
timestamp, -timestamp-1)
+       }
+       subscriptionTreeInsert(t, writer, database, "d1", "s2", 50, -2)
+       subscriptionTreeInsert(t, writer, database, "d2", "s1", 50, -3)
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       manager := subscriptionE2EManager(t, connection, 
subscription.TreeDialect)
+       topic := subscriptionE2EName("tree_filter")
+       subscriptionE2ETopic(t, ctx, manager, topic, map[string]string{
+               "format": "SubscriptionRecordHandler", "mode": "initial", 
"path": database + ".d1.s1", "start-time": "25", "end-time": "75", "strict": 
"true",
+       })
+       consumer := subscriptionE2EPull(t, ctx, connection, 
subscription.TreeDialect, topic, false)
+       subscriptionTreeRequireRows(t, subscriptionTreeCollect(t, ctx, 
consumer, len(want), true, false), want...)
+}
+
+// Reference: 
dual/treemodel/IoTDBSubscriptionTopicIT.testTabletTopicWithSnapshotMode.
+// The automatic-commit variant also covers released record buffers while ACKs
+// and termination are still pending.
+func TestSubscriptionTreeSnapshotCompletesWithAutomaticCommit(t *testing.T) {
+       connection := subscriptionE2EConnection(t)
+       ctx := subscriptionE2EContext(t)
+       writer, database := subscriptionTreeWriter(t, connection)
+       want := []subscriptionTreeRow{
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 10, 
110),
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 20, 
120),
+       }
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       manager := subscriptionE2EManager(t, connection, 
subscription.TreeDialect)
+       topic := subscriptionE2EName("tree_snapshot")
+       subscriptionE2ETopic(t, ctx, manager, topic, 
map[string]string{"format": "SubscriptionRecordHandler", "mode": "snapshot", 
"path": database + ".d1.s1"})
+       consumer := subscriptionE2EPull(t, ctx, connection, 
subscription.TreeDialect, topic, true)
+       // Post-subscribe rows must not extend the historical snapshot.
+       subscriptionTreeInsert(t, writer, database, "d1", "s1", 30, -30)
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       subscriptionTreeRequireRows(t, subscriptionTreeCollect(t, ctx, 
consumer, len(want), false, true), want...)
+       if !consumer.AllConsumed() {
+               t.Fatal("snapshot did not terminate")
+       }
+}
+
+// Reference: 
consensus/local/IoTDBConsensusSubscriptionBasicIT.testRealtimeOnlyAfterSubscribe
+// and 
IoTDBConsensusSubscriptionSeekIT.testSeekAfterCheckpointReplaysExactTail.
+func TestSubscriptionTreeIncrementalSeekAfterReplaysExactTail(t *testing.T) {
+       connection := subscriptionE2EConnection(t)
+       ctx := subscriptionE2EContext(t)
+       writer, database := subscriptionTreeWriter(t, connection)
+       subscriptionTreeInsert(t, writer, database, "d1", "s1", 0, -1)
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       manager := subscriptionE2EManager(t, connection, 
subscription.TreeDialect)
+       topic := subscriptionE2EName("tree_seek")
+       subscriptionE2ETopic(t, ctx, manager, topic, 
map[string]string{"format": "SubscriptionRecordHandler", "mode": "incremental", 
"order-mode": "per-writer", "path": database + ".d1.s1"})
+       consumer := subscriptionE2EPull(t, ctx, connection, 
subscription.TreeDialect, topic, false)
+       var prefix []subscriptionTreeRow
+       for timestamp := int64(1); timestamp <= 3; timestamp++ {
+               prefix = append(prefix, subscriptionTreeInsert(t, writer, 
database, "d1", "s1", timestamp, timestamp*10))
+       }
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       subscriptionTreeRequireRows(t, subscriptionTreeCollect(t, ctx, 
consumer, len(prefix), true, false), prefix...)
+       checkpoint, err := consumer.CommittedPositions(topic)
+       if err != nil || len(checkpoint) == 0 {
+               t.Fatalf("no confirmed writer checkpoint: %+v error=%v", 
checkpoint, err)
+       }
+       var tail []subscriptionTreeRow
+       for timestamp := int64(4); timestamp <= 6; timestamp++ {
+               tail = append(tail, subscriptionTreeInsert(t, writer, database, 
"d1", "s1", timestamp, timestamp*10))
+       }
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       subscriptionTreeRequireRows(t, subscriptionTreeCollect(t, ctx, 
consumer, len(tail), true, false), tail...)
+       if err := consumer.SeekAfter(ctx, topic, checkpoint); err != nil {
+               t.Fatal(err)
+       }
+       subscriptionTreeRequireRows(t, subscriptionTreeCollect(t, ctx, 
consumer, len(tail), true, false), tail...)
+}
+
+type subscriptionTreePushResult struct {
+       rows    []subscriptionTreeRow
+       context subpayload.CommitContext
+       failed  bool
+       err     error
+}
+
+// This supplements Java's local/IoTDBSubscriptionBasicIT record Push scenarios
+// with a callback failure and actual confirmed-progress evidence after retry.
+func TestSubscriptionTreePushAfterConsumeRedeliversOneFailure(t *testing.T) {
+       connection := subscriptionE2EConnection(t)
+       ctx := subscriptionE2EContext(t)
+       writer, database := subscriptionTreeWriter(t, connection)
+       subscriptionTreeInsert(t, writer, database, "d1", "s1", 0, -1)
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       manager := subscriptionE2EManager(t, connection, 
subscription.TreeDialect)
+       topic := subscriptionE2EName("tree_push")
+       subscriptionE2ETopic(t, ctx, manager, topic, map[string]string{
+               "format": "SubscriptionRecordHandler", "mode": "incremental", 
"order-mode": "per-writer", "path": database + ".d1.s1", 
"recycle-uncommitted-event-interval-ms": "1000",
+       })
+       var failedOnce atomic.Bool
+       results := make(chan subscriptionTreePushResult, 8)
+       config := subconsumer.DefaultSubscriptionPushConsumerConfig()
+       config.Consumer.Connection = connection
+       config.Consumer.HeartbeatInterval = subscriptionE2EHeartbeatInterval
+       config.PollTimeout, config.PollInterval = subscriptionE2EPollTimeout, 
subscriptionE2EPushPollInterval
+       config.AckStrategy = subconsumer.AckAfterConsume
+       config.Handler = func(callbackCtx context.Context, message 
subpayload.SubscriptionMessage) error {
+               rows, err := subscriptionTreeRows(callbackCtx, message)
+               failed := err == nil && failedOnce.CompareAndSwap(false, true)
+               result := subscriptionTreePushResult{rows: rows, context: 
message.CommitContext(), failed: failed, err: err}
+               select {
+               case results <- result:
+               case <-callbackCtx.Done():
+                       return callbackCtx.Err()
+               }
+               if err != nil {
+                       return err
+               }
+               if failed {
+                       return errors.New("intentional one-time processing 
failure")
+               }
+               return nil
+       }
+       consumer, err := subconsumer.NewSubscriptionPushConsumer(config)
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(func() {
+               if err := consumer.Close(); err != nil {
+                       t.Errorf("close push consumer: %v", err)
+               }
+               cleanupCtx, cancel := context.WithTimeout(context.Background(), 
subscriptionE2ECleanupTimeout)
+               defer cancel()
+               for {
+                       select {
+                       case err, open := <-consumer.Errors():
+                               if !open {
+                                       return
+                               }
+                               t.Errorf("terminal push error: %v", err)
+                       case <-cleanupCtx.Done():
+                               t.Error("push callbacks did not stop")
+                               return
+                       }
+               }
+       })
+       if err := consumer.Open(ctx); err != nil {
+               t.Fatal(err)
+       }
+       if err := consumer.Subscribe(ctx, topic); err != nil {
+               t.Fatal(err)
+       }
+       want := subscriptionTreeInsert(t, writer, database, "d1", "s1", 1, 101)
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       attempts := 0
+       var confirmed subpayload.CommitContext
+       for attempts < 2 {
+               select {
+               case result := <-results:
+                       if result.err != nil {
+                               t.Fatal(result.err)
+                       }
+                       if !reflect.DeepEqual(result.rows, 
[]subscriptionTreeRow{want}) || result.failed != (attempts == 0) {
+                               t.Fatalf("unexpected callback attempt %d: %+v", 
attempts, result)
+                       }
+                       confirmed = result.context
+                       attempts++
+               case err, open := <-consumer.Errors():
+                       t.Fatalf("push stopped after ordinary failure: open=%t 
error=%v", open, err)
+               case <-ctx.Done():
+                       t.Fatal(ctx.Err())
+               }
+       }
+       if confirmed.Writer == nil {
+               t.Fatal("incremental delivery did not expose writer progress")
+       }
+       ticker := time.NewTicker(subscriptionTreeE2EProgressPollInterval)
+       defer ticker.Stop()
+       for {
+               progress, err := consumer.CommittedPositions(topic)
+               if err != nil {
+                       t.Fatal(err)
+               }
+               position, found := 
progress[confirmed.Writer.ID.RegionID][confirmed.Writer.ID]
+               if found && (position.PhysicalTime > 
confirmed.Writer.Progress.PhysicalTime ||
+                       (position.PhysicalTime == 
confirmed.Writer.Progress.PhysicalTime && position.LocalSeq >= 
confirmed.Writer.Progress.LocalSeq)) {
+                       return
+               }
+               select {
+               case err, open := <-consumer.Errors():
+                       t.Fatalf("push terminated before successful ACK: 
open=%t error=%v", open, err)
+               case extra := <-results:
+                       t.Fatalf("message redelivered after successful 
processing: %+v", extra)
+               case <-ctx.Done():
+                       t.Fatal(ctx.Err())
+               case <-ticker.C:
+               }
+       }
+}
+
+// This Go-specific rejection contract replaces the Java TsFile read-success
+// scenarios: topic management is supported, file decoding is not.
+func TestSubscriptionTreeTsFilePollIsExplicitlyUnsupported(t *testing.T) {
+       connection := subscriptionE2EConnection(t)
+       ctx := subscriptionE2EContext(t)
+       writer, database := subscriptionTreeWriter(t, connection)
+       subscriptionTreeInsert(t, writer, database, "d1", "s1", 1, 101)
+       subscriptionTreeSQL(t, writer, "FLUSH")
+       manager := subscriptionE2EManager(t, connection, 
subscription.TreeDialect)
+       topic := subscriptionE2EName("tree_tsfile")
+       subscriptionE2ETopic(t, ctx, manager, topic, 
map[string]string{"format": "SubscriptionTsFileHandler", "mode": "initial", 
"path": database + ".d1.s1"})
+       consumer := subscriptionE2EPull(t, ctx, connection, 
subscription.TreeDialect, topic, false)
+       for round := 0; round < subscriptionE2EMaxPollRounds; round++ {
+               messages, err := consumer.Poll(ctx, subscriptionE2EPollTimeout)
+               if len(messages) != 0 {
+                       for _, message := range messages {
+                               message.Release()
+                       }
+                       t.Fatal("unsupported TsFile poll delivered records")
+               }
+               if errors.Is(err, subscription.ErrUnsupportedTsFile) {
+                       cleanupCtx, cancel := 
context.WithTimeout(context.Background(), subscriptionE2ECleanupTimeout)
+                       defer cancel()
+                       if unsubscribeErr := consumer.Unsubscribe(cleanupCtx, 
topic); unsubscribeErr != nil {
+                               t.Fatalf("unsubscribe after unsupported TsFile: 
%v", unsubscribeErr)
+                       }
+                       return
+               }
+               if err != nil {
+                       t.Fatal(err)
+               }
+       }
+       t.Fatal("no TsFile payload reached the decoding boundary")
+}
+
+func subscriptionTreePullWithIdentity(
+       t *testing.T,
+       ctx context.Context,
+       connection subscription.ConnectionConfig,
+       consumerID, groupID string,
+       autoCommit bool,
+       topics ...string,
+) subconsumer.SubscriptionPullConsumer {
+       t.Helper()
+       config := subconsumer.DefaultSubscriptionPullConsumerConfig()
+       config.Consumer.Connection = connection
+       config.Consumer.Dialect = subscription.TreeDialect
+       config.Consumer.ConsumerID = consumerID
+       config.Consumer.GroupID = groupID
+       config.Consumer.HeartbeatInterval = subscriptionE2EHeartbeatInterval
+       config.Consumer.EndpointsSyncInterval = 
subscriptionE2EEndpointsSyncInterval
+       config.AutoCommit, config.AutoCommitInterval = &autoCommit, 
subscriptionE2EAutoCommitInterval
+       consumer, err := subconsumer.NewSubscriptionPullConsumer(config)
+       if err != nil {
+               t.Fatal(err)
+       }
+       t.Cleanup(func() {
+               if err := consumer.Close(); err != nil {
+                       t.Errorf("close pull consumer: %v", err)
+               }
+       })
+       if err := consumer.Open(ctx); err != nil {
+               t.Fatal(err)
+       }
+       if err := consumer.Subscribe(ctx, topics...); err != nil {
+               t.Fatal(err)
+       }
+       return consumer
+}
+
+// Java reference: 
IoTDBConsensusSubscriptionConsumerGroupIT.testDifferentConsumerGroupsReceiveIndependentFullData.
+func TestSubscriptionTreeConsumerGroupsReceiveIndependentData(t *testing.T) {
+       connection := subscriptionE2EConnection(t)
+       ctx := subscriptionE2EContext(t)
+       writer, database := subscriptionTreeWriter(t, connection)
+       want := []subscriptionTreeRow{
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 1, 101),
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 2, 102),
+               subscriptionTreeInsert(t, writer, database, "d1", "s1", 3, 103),
+       }
+       subscriptionTreeSQL(t, writer, "FLUSH")
+
+       manager := subscriptionE2EManager(t, connection, 
subscription.TreeDialect)
+       topic := subscriptionE2EName("tree_groups")
+       subscriptionE2ETopic(t, ctx, manager, topic, map[string]string{
+               "format": "SubscriptionRecordHandler", "mode": "snapshot", 
"path": database + ".d1.s1",
+       })
+
+       first := subscriptionTreePullWithIdentity(t, ctx, connection, 
subscriptionE2EName("tree_group_consumer"), 
subscriptionE2EName("tree_group_a"), true, topic)
+       second := subscriptionTreePullWithIdentity(t, ctx, connection, 
subscriptionE2EName("tree_group_consumer"), 
subscriptionE2EName("tree_group_b"), true, topic)
+       subscriptionTreeRequireRows(t, subscriptionTreeCollect(t, ctx, first, 
len(want), false, true), want...)
+       subscriptionTreeRequireRows(t, subscriptionTreeCollect(t, ctx, second, 
len(want), false, true), want...)
+}
+
+func TestSubscriptionTreeConsumerReadsMultipleTopics(t *testing.T) {

Review Comment:
   **Flaky against the current server, with an apparently server-side root 
cause.** On the first full run, this test and 
`TestSubscriptionTableSnapshotStrictManualCommitCompletion` both hit the 20 s 
timeout: all rows had arrived, but `AllConsumed()` never became true.
   
   In repeat loops:
   - This multi-topic case, alternating Go and Java runs: Go passed 1/6, an 
equivalent Java program 6/6.
   - The table strict manual-commit case: Go passed 4/8, Java 5/8.
   
   Every failing run I inspected, Go and Java alike, has the same server-side 
signature:
   - Rows were delivered and ACKed, and the terminate events were committed.
   - The ConfigNode logged `Detected completion of pipe ...`.
   - No `PipeHandleMetaChangeProcedure` was submitted until another pipe 
completed about 21 s later.
   
   As a result the topic is never marked completed, no TERMINATION is returned, 
and `AllConsumed()` stays false. This needs a server-side follow-up. It may be 
related to the heartbeat-round gating of `canSubmitHandleMetaChangeProcedure` 
in `PipeHeartbeatParser`.
   
   I could not explain why the Go client hits this much more often than Java in 
the multi-topic case. A proxy capture shows the same `pipeSubscribe` sequence 
from both clients: one POLL returning two TABLETS, four continuation polls, and 
one COMMIT carrying both contexts. Until the server side is fixed, the 
completion tests will stay flaky wherever `IOTDB_SUBSCRIPTION_E2E=1` is set.



##########
subscription/consumer/push_consumer.go:
##########
@@ -0,0 +1,455 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package consumer
+
+import (
+       "github.com/apache/iotdb-client-go/subscription"
+       "github.com/apache/iotdb-client-go/subscription/payload"
+       "github.com/apache/iotdb-client-go/subscription/internal/protocol"
+       "github.com/apache/iotdb-client-go/subscription/internal/record"
+       "github.com/apache/iotdb-client-go/subscription/internal/identifier"
+
+       "context"
+       "errors"
+       "fmt"
+       "sync"
+       "time"
+)
+
+// NewSubscriptionPushConsumer copies and validates config without connecting.
+// Handler is required. Open starts sequential background delivery with the
+// configured acknowledgment strategy; its context limits opening only.
+// Close cancels delivery and closes connections without waiting for an active
+// Handler. Its message remains valid until that Handler returns.
+func NewSubscriptionPushConsumer(config SubscriptionPushConsumerConfig) 
(SubscriptionPushConsumer, error) {
+       resolved, err := normalizeSubscriptionPushConsumerConfig(config)
+       if err != nil {
+               return nil, err
+       }
+       autoCommit := false
+       consumer, err := 
newSubscriptionPullConsumer(SubscriptionPullConsumerConfig{
+               Consumer: resolved.Consumer,
+               AutoCommit: &autoCommit,
+               AutoCommitInterval: 
DefaultSubscriptionPullConsumerConfig().AutoCommitInterval,
+       })
+       if err != nil {
+               return nil, err
+       }
+       return &subscriptionPushConsumer{
+               config: resolved,
+               consumer: consumer,
+               operations: make(chan struct{}, 1),
+               generations: make(map[string]uint64),
+               errors: make(chan error, 1),
+       }, nil
+}
+
+type subscriptionPushConsumer struct {
+       config SubscriptionPushConsumerConfig
+       consumer *subscriptionPullConsumer
+       operations chan struct{}
+       mu sync.Mutex
+       generations map[string]uint64
+       started bool
+       closed bool
+       terminal error
+       deliveryCancel context.CancelFunc
+       callbackTopic string
+       callbackCancel context.CancelFunc
+       errors chan error
+       errorsClosed sync.Once
+}
+
+type subscriptionPushDelivery struct {
+       message payload.SubscriptionMessage
+       generation uint64
+}
+
+func (c *subscriptionPushConsumer) Open(ctx context.Context) error {
+       if ctx == nil {
+               return errors.New("subscription: context must not be nil")
+       }
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+       c.mu.Lock()
+       err := c.deliveryStateLocked()
+       c.mu.Unlock()
+       if err != nil {
+               return err
+       }
+       if err := c.consumer.Open(ctx); err != nil {
+               return err
+       }
+       c.mu.Lock()
+       if err := c.deliveryStateLocked(); err != nil {
+               c.mu.Unlock()
+               return err
+       }
+       if c.started {
+               c.mu.Unlock()
+               return nil
+       }
+       c.consumer.mu.RLock()
+       lifeCtx := c.consumer.lifeCtx
+       c.consumer.mu.RUnlock()
+       deliveryCtx, cancel := context.WithCancel(lifeCtx)
+       c.deliveryCancel = cancel
+       c.started = true
+       c.mu.Unlock()
+       go c.runDelivery(deliveryCtx)
+       return nil
+}
+
+func (c *subscriptionPushConsumer) Close() error {
+       c.mu.Lock()
+       if c.closed {
+               c.mu.Unlock()
+               return nil
+       }
+       c.closed = true
+       if c.deliveryCancel != nil {
+               c.deliveryCancel()
+       }
+       started := c.started
+       c.mu.Unlock()
+       // The loop is not a core worker: a Handler may close its own consumer.
+       // It retains ownership of its messages until the Handler has returned.
+       err := c.consumer.Close()
+       if !started {
+               c.closeErrors()
+       }
+       return err
+}
+
+func (c *subscriptionPushConsumer) Errors() <-chan error {
+       return c.errors
+}
+
+func (c *subscriptionPushConsumer) Info() SubscriptionConsumerInfo {
+       return c.consumer.Info()
+}
+
+func (c *subscriptionPushConsumer) LatestWatermark() (int64, bool) {
+       return c.consumer.LatestWatermark()
+}
+
+func (c *subscriptionPushConsumer) AllConsumed() bool {
+       return c.consumer.AllConsumed()
+}
+
+func (c *subscriptionPushConsumer) Subscribe(ctx context.Context, topics 
...string) error {
+       return c.consumer.Subscribe(ctx, topics...)
+}
+
+func (c *subscriptionPushConsumer) Unsubscribe(ctx context.Context, topics 
...string) error {
+       return c.consumer.Unsubscribe(ctx, topics...)
+}
+
+func (c *subscriptionPushConsumer) Positions(topic string) 
(payload.TopicProgress, error) {
+       return c.consumer.Positions(topic)
+}
+
+func (c *subscriptionPushConsumer) CommittedPositions(topic string) 
(payload.TopicProgress, error) {
+       return c.consumer.CommittedPositions(topic)
+}
+
+func (c *subscriptionPushConsumer) SeekToBeginning(ctx context.Context, topic 
string) error {
+       return c.seek(ctx, topic, protocol.SeekBeginning, nil)
+}
+
+func (c *subscriptionPushConsumer) SeekToEnd(ctx context.Context, topic 
string) error {
+       return c.seek(ctx, topic, protocol.SeekEnd, nil)
+}
+
+func (c *subscriptionPushConsumer) Seek(ctx context.Context, topic string, 
progress payload.TopicProgress) error {
+       return c.seek(ctx, topic, protocol.SeekProgress, progress)
+}
+
+func (c *subscriptionPushConsumer) SeekAfter(ctx context.Context, topic 
string, progress payload.TopicProgress) error {
+       return c.seek(ctx, topic, protocol.SeekAfterProgress, progress)
+}
+
+func (c *subscriptionPushConsumer) seek(ctx context.Context, topic string, 
kind int16, progress payload.TopicProgress) error {
+       name, err := identifier.Parse(topic)
+       if err != nil {
+               return err
+       }
+       if err := c.acquireOperations(ctx); err != nil {
+               return err
+       }
+       defer c.releaseOperations()
+       if err := c.consumer.checkOpen(); err != nil {
+               return err
+       }
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+       c.mu.Lock()
+       if c.closed {
+               c.mu.Unlock()
+               return subscription.ErrClosed
+       }
+       // Even a failed multi-provider seek can change server state. Never 
confirm
+       // or start another callback for an older delivery of the affected 
topic.
+       c.generations[name]++
+       var cancelCallback context.CancelFunc
+       if c.callbackTopic == name {
+               cancelCallback = c.callbackCancel
+       }
+       c.mu.Unlock()
+       // Keep a callback's context usable for a seek invoked from that 
callback.
+       // Cancel the obsolete delivery after the request completes instead.
+       if cancelCallback != nil {
+               defer cancelCallback()
+       }
+       return c.consumer.seekProgress(ctx, topic, kind, progress)
+}
+
+func (c *subscriptionPushConsumer) acquireOperations(ctx context.Context) 
error {
+       if ctx == nil {
+               return errors.New("subscription: context must not be nil")
+       }
+       if err := ctx.Err(); err != nil {
+               return err
+       }
+       select {
+       case c.operations <- struct{}{}:
+               return nil
+       case <-ctx.Done():
+               return ctx.Err()
+       }
+}
+
+func (c *subscriptionPushConsumer) releaseOperations() {
+       <-c.operations
+}
+
+func (c *subscriptionPushConsumer) deliveryStateLocked() error {
+       if c.closed {
+               return subscription.ErrClosed
+       }
+       return c.terminal
+}
+
+func (c *subscriptionPushConsumer) pollDeliveries(ctx context.Context) 
([]subscriptionPushDelivery, error) {
+       if err := c.acquireOperations(ctx); err != nil {
+               return nil, err
+       }
+       defer c.releaseOperations()
+       c.mu.Lock()
+       err := c.deliveryStateLocked()
+       c.mu.Unlock()
+       if err != nil {
+               return nil, err
+       }
+       messages, err := c.consumer.Poll(ctx, c.config.PollTimeout)
+       if err != nil {
+               return nil, err
+       }
+       c.mu.Lock()
+       defer c.mu.Unlock()
+       if err := c.deliveryStateLocked(); err != nil {
+               for _, message := range messages {
+                       message.Release()
+               }
+               return nil, err
+       }
+       deliveries := make([]subscriptionPushDelivery, 0, len(messages))
+       for _, message := range messages {
+               deliveries = append(deliveries, subscriptionPushDelivery{
+                       message: message,
+                       generation: 
c.generations[record.ReadCommitContext(message).Topic],
+               })
+       }
+       return deliveries, nil
+}
+
+func (c *subscriptionPushConsumer) runDelivery(ctx context.Context) {
+       var terminal error
+       defer func() { c.finishDelivery(terminal) }()
+       for {
+               if err := ctx.Err(); err != nil {
+                       terminal = c.terminalDeliveryError(err)
+                       return
+               }
+               deliveries, err := c.pollDeliveries(ctx)
+               if err == nil {
+                       err = c.deliver(ctx, deliveries)
+               }
+               if err != nil {
+                       terminal = c.terminalDeliveryError(err)
+                       if terminal != nil || ctx.Err() != nil {
+                               return
+                       }
+               }
+               // Wait after the entire round, including callbacks and 
acknowledgment.
+               // A slow round therefore never overlaps the next round.
+               timer := time.NewTimer(c.config.PollInterval)
+               select {
+               case <-ctx.Done():
+                       timer.Stop()
+                       terminal = c.terminalDeliveryError(ctx.Err())
+                       return
+               case <-timer.C:
+               }
+       }
+}
+
+func (c *subscriptionPushConsumer) deliver(ctx context.Context, deliveries 
[]subscriptionPushDelivery) error {
+       defer func() {
+               for _, delivery := range deliveries {
+                       delivery.message.Release()
+               }
+       }()
+       if c.config.AckStrategy == AckBeforeConsume {
+               if err := c.commitDeliveries(ctx, deliveries, false); err != 
nil {
+                       return err
+               }
+       }
+       var succeeded, failed []subscriptionPushDelivery
+       for _, delivery := range deliveries {
+               if err := ctx.Err(); err != nil {
+                       return err
+               }
+               callbackCtx, finish, current := c.beginCallback(ctx, delivery)
+               if !current {
+                       continue
+               }
+               err := c.invokeHandler(callbackCtx, delivery.message)
+               finish()
+               delivery.message.Release()
+               if err == nil {
+                       succeeded = append(succeeded, delivery)
+               } else {
+                       failed = append(failed, delivery)
+               }
+       }
+       if c.config.AckStrategy == AckBeforeConsume {
+               return nil
+       }
+       // Java confirms successful callbacks before nacking failures. An ACK 
error
+       // leaves the failed group unconfirmed for server-side recovery.
+       if err := c.commitDeliveries(ctx, succeeded, false); err != nil {
+               return err
+       }
+       return c.commitDeliveries(ctx, failed, true)
+}
+
+func (c *subscriptionPushConsumer) beginCallback(ctx context.Context, delivery 
subscriptionPushDelivery) (context.Context, func(), bool) {
+       topic := record.ReadCommitContext(delivery.message).Topic
+       c.mu.Lock()
+       defer c.mu.Unlock()
+       if c.deliveryStateLocked() != nil || ctx.Err() != nil || 
c.generations[topic] != delivery.generation {
+               return nil, nil, false
+       }
+       callbackCtx, cancel := context.WithCancel(ctx)
+       c.callbackTopic = topic
+       c.callbackCancel = cancel
+       return callbackCtx, func() {
+               cancel()
+               c.mu.Lock()
+               c.callbackTopic = ""
+               c.callbackCancel = nil
+               c.mu.Unlock()
+       }, true
+}
+
+func (c *subscriptionPushConsumer) invokeHandler(ctx context.Context, message 
payload.SubscriptionMessage) (err error) {
+       defer func() {
+               if failure := recover(); failure != nil {
+                       err = fmt.Errorf("subscription: push handler panicked: 
%v", failure)
+               }
+       }()
+       return c.config.Handler(ctx, message)
+}
+
+func (c *subscriptionPushConsumer) commitDeliveries(ctx context.Context, 
deliveries []subscriptionPushDelivery, nack bool) error {
+       if len(deliveries) == 0 {
+               return nil
+       }
+       if err := c.acquireOperations(ctx); err != nil {
+               return err
+       }
+       defer c.releaseOperations()
+       c.mu.Lock()
+       if err := c.deliveryStateLocked(); err != nil {
+               c.mu.Unlock()
+               return err
+       }
+       messages := make([]payload.SubscriptionMessage, 0, len(deliveries))
+       for _, delivery := range deliveries {
+               if 
c.generations[record.ReadCommitContext(delivery.message).Topic] == 
delivery.generation {
+                       messages = append(messages, delivery.message)
+               }
+       }
+       c.mu.Unlock()
+       if len(messages) == 0 {
+               return nil
+       }
+       commitCtx, cancel := context.WithTimeout(ctx, 
c.config.Consumer.Connection.ConnectTimeout)
+       defer cancel()
+       operationCtx, finish, err := c.consumer.linkContext(commitCtx)
+       if err != nil {
+               return err
+       }
+       defer finish()
+       contexts, err := c.consumer.messageCommitContexts(messages)
+       if err != nil {
+               return err
+       }
+       return c.consumer.commitContexts(operationCtx, contexts, nack)
+}
+
+func (c *subscriptionPushConsumer) terminalDeliveryError(failure error) error {
+       c.mu.Lock()
+       closed := c.closed
+       c.mu.Unlock()
+       if closed {
+               return nil
+       }
+       if err := c.consumer.checkOpen(); err != nil {
+               return err
+       }
+       if flowFatalPollError(failure) || flowCriticalPollError(failure) {

Review Comment:
   **Behavioral difference from Java: a single critical poll error permanently 
stops Push delivery.**
   
   `terminalDeliveryError` treats every critical error as terminal. That covers 
server statuses 1900/1901/1909/1912 and anything else that falls into the 
default branch of `verifySubscriptionProviderStatus`. It also covers critical 
`ErrorPayload`s from the server, such as the WAL replay error and 
`SUBSCRIPTION_OVERSIZED_ENTRY`. `runDelivery` then exits, and the only way to 
resume is to read `Errors()` and recreate the consumer.
   
   In Java, `AbstractSubscriptionPushConsumer.AutoPollWorker#run` catches every 
exception and polls again on the next `autoPollIntervalMs` tick. Only close or 
fencing cancels the worker.
   
   Repro: a fake server answers the first POLL with 1909 and every later POLL 
normally. The Go delivery loop stops after that first poll, and the server sees 
no further POLL for the next 2+ seconds. Java's worker would keep polling on 
its 100 ms schedule.
   
   The README documents the current behavior, so this may be intentional. If it 
is, please list it explicitly as a difference from Java and explain how to 
recreate the consumer. Otherwise, consider making only fencing and TsFile 
terminal, and retrying critical errors on the next round.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to