Skip to content

[Bug]: Concurrent conntrack event delivery retains destroyed flows in CN monitoring map #32851

Done

Description

@LeftHandCold

Summary

The CN's conntrack monitor can indefinitely retain an already-destroyed flow in activeConns when concurrent conntrack workers deliver its DESTROY event before its NEW event. All kernel events can be received successfully, with the kernel table empty, while the reported connection count and retained *conntrack.Flow objects remain nonzero.

This is a pre-existing defect discovered while reviewing #32845, not a regression introduced by that PR. It reproduces on both its clean base and head; cmd/mo-service/debug_connections.go is byte-identical between them. The socket upgrade removes unnecessary Background receive watchers, but does not fix this independent event-order/retention problem.

Versions and environment

  • Branch: main / PR fix(conntrack): avoid socket watchers for background receives #32845.
  • Base: e1160015bb5895c1677d5fc1496c4bee440592b3.
  • Head: 4c4a2fcb756bbe582e497ed5684b8ec6bfc8d36e.
  • Linux amd64, Go 1.27.1, GOWORK=off, GOMAXPROCS=4; test host has 20 logical CPUs.
  • conntrack v0.5.1 and netlink v1.7.2 on both revisions; socket v0.5.1 on base and v0.7.0 on head.
  • Kernel experiments run only inside disposable network namespaces. The flows are synthetic UDP conntrack entries created/deleted through the kernel API, not customer traffic or production data.

Observed results

Each event-accounting run creates and deletes 2,048 distinct flows with eight producers. Producers wait for complete event consumption after each batch of 32 flows, avoiding a large uncontrolled receive burst. The application event channel has the same 65,536 capacity as MO. Assertions check exactly one NEW and one DESTROY for every tuple, matching IDs, no receive errors, and an empty final kernel dump.

Revision/mode Workers NEW / DESTROY received Final kernel flows Stale entries with MO's map update rule
Head, normal, three runs 16 2,048 / 2,048 each 0 each 24, 25, 13
Head, normal, production worker count on this host 20 2,048 / 2,048 each 0 each 23, 22, 18
Head, normal, control, three runs 1 2,048 / 2,048 each 0 each 0, 0, 0
Base, race 16 2,048 / 2,048 0 405
Head, race, corresponding comparison 16 2,048 / 2,048 0 39

The counts depend on scheduling and are not a comparative performance or leak-rate estimate. The failure also occurs without race instrumentation.

Verification against the actual MO consumer

To rule out an error in the small map oracle, I captured all 4,096 events from a separate non-race head run that ended with 21 stale entries. I replayed their original order through the unmodified logConnTrack implementation copied byte-for-byte from the tested commit, and observed its actual conntrack: stats log field through the supported log reporter hook.

After a consumer acknowledgement established that every input event had been processed:

Original captured order, head: connections=21, 21, 21
Original captured order, base: connections=21, 21, 21
Same events, NEW-before-DESTROY control, head: connections=0, 0, 0
Same events, NEW-before-DESTROY control, base: connections=0, 0, 0

These were three subsequent reporting ticks per case. Only the existing report-interval test seam was set to 50 ms to avoid waiting five seconds per observation. The consumer source and event-processing logic were unchanged. This was an extracted-source test, not a claim of a complete running CN or customer-data reproduction.

Root cause and reachability

  1. startConnectionTracking starts multiple conntrack decoders using uint8(max(runtime.NumCPU(), 16)). This is 20 workers on the test host.
  2. Each upstream conntrack v0.5.1 eventWorker independently receives a message, unmarshals it, then sends the event to the shared channel. There is no ordering barrier covering receipt through publication across workers. Delivery to the consumer can therefore reverse two events for the same flow.
  3. logConnTrack assumes lifecycle order:
Actual kernel lifecycle:     NEW(id) -> DESTROY(id)
Observed delivery:          DESTROY(id) -> NEW(id)
Consumer:                   delete(absent id) -> activeConns[id] = flow
Final kernel state:         absent
Final consumer state:       retained flow
  1. The map has no reconciliation, expiry or terminal-event memory. The periodic tick logs its size and iterates it; it does not remove stale entries. The production consumer is started with context.Background(), so ordinary completed flows do not trigger a terminal cleanup of the map.

Impact and limits

  • Confirmed: false active-connection statistics and retention of completed-flow objects in a long-lived monitor.
  • With continued qualifying connection churn, additional stale objects can accumulate and each periodic scan processes them. The experiments establish retention and the missing cleanup path; they do not measure a production memory growth rate or reproduce an OOM.
  • This is independent of database table/index consistency. No SQL data corruption or transaction failure was demonstrated.
  • This is also independent of the negative WaitGroup counter panic in [Bug]: 4.2 AP CN crashes with negative WaitGroup counter in the conntrack/socket receive watcher during Family concurrency #31954; the two should not be assigned the same root cause.
  • An initial unbounded burst caused ENOBUFS on both base and head. Those runs are excluded from the ordering proof above. The bounded runs received every expected event and had no receive error.

Reproduction

The standalone test below is a compact version of the kernel experiment. It was separately run on the exact head: 16 workers failed with 21 retained entries; the one-worker control passed with zero. It fails an intentional correctness assertion when the kernel table is empty but the event-derived map is not.

From the repository root at the tested revision, using Go 1.27.1:

challenge_dir="$(mktemp -d)"
# Save the Go test below as "$challenge_dir/conntrack_order_test.go".
GOWORK=off go test -mod=readonly -c \
  -o "$challenge_dir/order.test" "$challenge_dir/conntrack_order_test.go"
challenge_host_netns="$(readlink /proc/self/ns/net)"

# Reproducer: each invocation owns a new, disposable network namespace.
sudo unshare --net env CHALLENGE_HOST_NETNS="$challenge_host_netns" \
  CHALLENGE_WORKERS=16 GOMAXPROCS=4 \
  "$challenge_dir/order.test" -test.v -test.count=3 -test.timeout=30s \
  -test.run '^TestConntrackOrder$'

# Control, with the same input and oracle.
sudo unshare --net env CHALLENGE_HOST_NETNS="$challenge_host_netns" \
  CHALLENGE_WORKERS=1 GOMAXPROCS=4 \
  "$challenge_dir/order.test" -test.v -test.count=3 -test.timeout=30s \
  -test.run '^TestConntrackOrder$'

Expected behavior / correction direction

After observing the final lifecycle event for every generated flow and draining the stream, the monitor should agree with the empty kernel table and release completed-flow objects.

Preserve lifecycle order through the receive/decode/publication path. A single ordered receiver is the smallest candidate supported by the control experiment, but its throughput and burst behavior need validation before adopting it. An alternative concurrent design must explicitly preserve per-flow order. Kernel event-loss recovery/reconciliation remains a separate concern; increasing channel capacity alone does not fix the demonstrated no-loss reordering case.

Acceptance should include ordered and reversed delivery fixtures, actual multi-producer kernel events, a same-process churn/reclamation check, and normal/race modes. Do not treat removing socket watchers as acceptance of this map-retention issue.

Related / duplicate check

Standalone kernel reproducer: conntrack_order_test.go
package challenge

import (
	"net/netip"
	"os"
	"strconv"
	"sync"
	"testing"
	"time"

	"github.com/ti-mo/conntrack"
	"github.com/ti-mo/netfilter"
)

// Run only in a disposable network namespace; never changes host conntrack.
func TestConntrackOrder(t *testing.T) {
	host := os.Getenv("CHALLENGE_HOST_NETNS")
	here, e := os.Readlink("/proc/self/ns/net")
	if e != nil || host == "" || here == host {
		t.Fatal("isolated network namespace required")
	}
	workers := 16
	if s := os.Getenv("CHALLENGE_WORKERS"); s != "" {
		workers, e = strconv.Atoi(s)
		if e != nil || workers < 1 || workers > 64 {
			t.Fatal("invalid workers")
		}
	}
	listener, e := conntrack.Dial(nil)
	if e != nil {
		t.Fatal(e)
	}
	events := make(chan conntrack.Event, 65536)
	errs, e := listener.Listen(events, uint8(workers), []netfilter.NetlinkGroup{netfilter.GroupCTNew, netfilter.GroupCTDestroy})
	if e != nil {
		listener.Close()
		t.Fatal(e)
	}
	defer listener.Close()
	const producers, batches, perBatch = 8, 64, 4
	gates := make([]chan struct{}, batches)
	for i := range gates {
		gates[i] = make(chan struct{})
	}
	stop := make(chan struct{})
	var wg sync.WaitGroup
	defer func() { close(stop); wg.Wait() }()
	failures := make(chan error, producers)
	for p := 0; p < producers; p++ {
		c, err := conntrack.Dial(nil)
		if err != nil {
			t.Fatal(err)
		}
		wg.Add(1)
		go func(p int) {
			defer wg.Done()
			defer c.Close()
			for batch := 0; batch < batches; batch++ {
				for i := 0; i < perBatch; i++ {
					select {
					case <-stop:
						return
					default:
					}
					f := conntrack.NewFlow(17, 0, netip.MustParseAddr("192.0.2.1"), netip.MustParseAddr("198.51.100.1"), uint16(1024+p*batches*perBatch+batch*perBatch+i), 9000, 120, 0)
					if e := c.Create(f); e != nil {
						failures <- e
						return
					}
					if e := c.Delete(f); e != nil {
						failures <- e
						return
					}
				}
				select {
				case <-gates[batch]:
				case <-stop:
					return
				}
			}
		}(p)
	}
	active := map[uint32]bool{}
	news := map[uint16]uint32{}
	deletes := map[uint16]uint32{}
	timeout := time.NewTimer(15 * time.Second)
	defer timeout.Stop()
	for batch := 0; batch < batches; batch++ {
		for i := 0; i < producers*perBatch*2; i++ {
			select {
			case e := <-failures:
				t.Fatal(e)
			case e := <-errs:
				t.Fatal(e)
			case <-timeout.C:
				t.Fatal("missing events")
			case ev := <-events:
				if ev.Flow == nil {
					t.Fatal("nil flow")
				}
				port, id := ev.Flow.TupleOrig.Proto.SourcePort, ev.Flow.ID
				switch ev.Type {
				case conntrack.EventNew:
					if _, ok := news[port]; ok {
						t.Fatal("duplicate NEW")
					}
					news[port] = id
					active[id] = true
				case conntrack.EventDestroy:
					if _, ok := deletes[port]; ok {
						t.Fatal("duplicate DESTROY")
					}
					deletes[port] = id
					delete(active, id)
				default:
					t.Fatal("unexpected event")
				}
			}
		}
		close(gates[batch])
	}
	wg.Wait()
	if len(news) != 2048 || len(deletes) != 2048 {
		t.Fatal("wrong event counts")
	}
	for port, id := range news {
		if deletes[port] != id {
			t.Fatal("NEW/DESTROY ID mismatch")
		}
	}
	c, e := conntrack.Dial(nil)
	if e != nil {
		t.Fatal(e)
	}
	defer c.Close()
	flows, e := c.Dump(nil)
	if e != nil {
		t.Fatal(e)
	}
	t.Logf("workers=%d NEW=%d DESTROY=%d kernel_flows=%d active_map=%d", workers, len(news), len(deletes), len(flows), len(active))
	if len(flows) != 0 {
		t.Fatal("kernel table not empty")
	}
	if len(active) != 0 {
		t.Fatalf("stale active map entries: %d", len(active))
	}
}

Activity

  1. self-assigned this
    on Nov 17, 2026
  2. added
    severity/s0
    and removed on Nov 17, 2026
  3. XuPeng-SH commented on Nov 17, 2026

    @XuPeng-SH
    Contributor

    转 QA 验证,不代表验收通过,保持 issue 开放。

    关联 #32854 已合 main:44e9c75b0f4db6499cfc4779fc1c2559c9f042eb(head 37f9908132100777d5307cb39497d280f4c2c01f)。通过既有 Listen API 使用一个 ordered receiver,防止多个 worker 在 receive/decode/publication 间颠倒同一 flow 的 NEW/DESTROY。没有修改 channel 容量、map consumer、依赖、关闭所有权或增加过期/补偿机制。

    已报告证据:

    • 作者在 Linux amd64 / Go 1.27.1、base 43addc1 上记录 startup assertion red/green、100 race repetitions,完整 cmd/mo-service normal/race 各 169 通过、零 skip。
    • 隔离 network namespace、每次 16,384 flow、8 producers 的 32/64-flow bounded batches:原 20 workers 三轮均有约 2,487–2,990 个残留,单 worker 六轮均为 0;每轮核对完整 NEW/DESTROY、ID、无 receive error 和空 kernel table。
    • 作者报告同进程 20 轮 race、327,680 生命周期,kernel/map 每轮归零;socket 0.7.0 依赖图兼容控制三轮也为 0。
    • 评审 31a0362 复用 frozen-head build/UT/SCA/coverage/compose 成功状态,没有本地重跑 Go/native/kernel;作者 runtime/race/capacity 的原始 local_validation artifacts 未提供给评审。因此以上运行结果保持作者归属,不冒称本轮或评审独立实测。最终队列因 fork 编辑权限出队,PR metadata 已确认合并,但不推断最终 CI 全绿。

    边界:约 90k–115k events/sec 只是合成 bounded workload 观察,不是生产吞吐保证。256/2048-flow 大突发在新旧配置均撞到既有 kernel receive-buffer 限制,不计为通过;fatal receive error 会终止 worker,本修复没有 event-loss recovery/reconciliation,不能声称修复所有 conntrack 统计不准。该 no-loss ordering 问题与 #31954 负 WaitGroup panic 独立,也不证明 OOM 或 SQL 数据一致性问题已解决。

    请 QA 在最终 main 复核实际多 producer kernel events 的无丢失计数、flow ID、kernel 与 consumer map 归零、同进程持续 churn/对象释放、正常/race、startup/Listen failure cleanup,并检查有界吞吐和突发错误的明确报告。测试仅使用授权的隔离环境,不改宿主/客户 conntrack;将事件丢失/恢复需求单独记录,勿混为本 issue 的已验证无丢失重排反例。

    已读完整 issue/PR 评论、评审和变更,没有适用于当前修复的已验证反例或明确未完开发 follow-up。按持续交接流程改派唯一 @Ariznawlll。

  4. XuPeng-SH commented on Nov 17, 2026

    @XuPeng-SH
    Contributor

    QA 补充交接:接收异常后的监控恢复

    关联后续 #32865 已于 2026-11-17 16:27:48 UTC 合入 main,SHA 59bf4b8f1ad93d80115c5a0f816d83dd1dfadab8(head 97fca13a482f75966e70ed2e6ba6a1bd05da8ce9)。本 issue 已由 @Ariznawlll 接手,保留现负责人,仅补充原 #32854 交接后的修复范围,不代表验收通过。

    这次保留单 worker 的事件顺序,fatal receive error(含 ENOBUFS)后使旧统计 generation 失效、关闭旧 listener,并限频重建独立队列/map。它恢复后续观测,不补回丢失事件,不保证完整 kernel-table 快照;统计明确 since_listener_start / complete=false。cleanup 失败则停止重试,初始权限/配置失败仍非致命且不后台重试。

    作者报告 Linux 全 cmd/mo-service normal/race 各 186 tests/subtests、8 专项各 100 race repetitions 通过;独立 netns 中实际 MO consumer/supervisor 的 3 轮真实 ENOBUFS 后恢复,随后 32 TCP+32 UDP 的统计 0→64→0。审查独立复跑 exact-file normal/race、8 lifecycle 测试各 100 race repetitions 和 3 socket-boundary race 测试,未复跑作者真实 kernel ENOBUFS;完整 package 证据引用 exact-head CI。merge queue 报 CI Required 成功。本次巡检未本地测试。

    QA 建议将有序无丢事件的原问题与“丢事件后恢复观测”分开验证:重复 receive failure、旧 generation 隔离、有限重试、cleanup 失败和后续真实流生命周期。生产长时稳定性、实际吞吐/内存、原 #31954 panic 根因、SQL/数据一致性均不因这些测试被宣称通过。

  5. Ariznawlll commented on Nov 20, 2026

    @Ariznawlll
    Collaborator

    QA 阶段性进展(2026-11-20,真实内核场景尚未执行)

    固定 main b543648d99395492918ce0a5a3c08a7de952042d,CI 已核对 #32854 44e9c75b0f4db6499cfc4779fc1c2559c9f042eb 和 #32865 59bf4b8f1ad93d80115c5a0f816d83dd1dfadab8 均为祖先。

    Linux run https://github.com/matrixorigin/motr/actions/runs/44718381718 已实际完成:

    • MatrixOne/native SDK、普通及 race command test 编译成功;先前 runner 磁盘不足已通过释放 hosted SDK/镜像空间及独立 Go cache 解决。
    • TestStartConnectionTrackingClosesOnListenFailure、TestConntrack*、recovery、cleanup 等选定测试普通模式三轮及 race 一轮步骤成功。

    真实内核 flow 尚未跑起来,不能记为产品通过或产品失败。 最新失败日志是 stat .../matrixone/motr/.github/qa/issue_32851_kernel_test.go: no such file or directory,发生在编译/执行内核 fixture 前。该文件存在于 QA 分支,但 PR merge checkout 中路径缺失,正在核对 checkout 内容并加显式存在性断言,避免再把缺失 fixture 误报成内核失败。

    回归:https://github.com/matrixorigin/motr/pull/370,保持 OPEN。尚未取得本 QA 的 NEW=1024、DESTROY=1024、flow ID 一致、kernel table=0、active map=0 的真实证据;同进程 churn、正常/race 内核轮次及真实 ENOBUFS 后恢复也仍待测。模拟 ENOBUFS 单测不能替代真实内核异常恢复。生产长时吞吐/内存、#31954 panic 和 SQL 一致性不在本修复已验证范围。

  6. Ariznawlll commented on Nov 22, 2026

    @Ariznawlll
    Collaborator

    阶段性测试证据

    Linux 隔离网络命名空间的 MOTR CI run 45052061906 已完成,使用 main b543648d99395492918ce0a5a3c08a7de952042d。经 Git 对比,该版本与本次本地最新 main cc2c82dc4a6cb2cbcc046ef9caebde50c6004b15 的 debug_connections.go 和相关测试文件内容一致;这仍不是在新提交上执行的证据。

    • 实际 MO listenConntrack / logConnTrack 在真实内核事件下验证:创建 64 条流后统计 64,全部删除后统计 0、内核表 0;普通模式三轮和 race 模式一轮通过。
    • 原理级 8 producer 并发场景,单 worker 在普通模式三轮和 race 模式五轮均收到 1024 对 NEW/DESTROY,内核表和事件 map 残留均为 0。
    • 16 worker 负对照同样收到全部 1024 对事件、内核表为空,但事件 map 残留 1,证明用例能检出乱序残留;这是故意的旧行为对照,不是修复版本失败。
    • 生产生命周期/恢复定向测试普通 24 次和 race 8 次通过。真实 ENOBUFS / 高负载吞吐不属于上述通过结论。

    MOTR PR #370 已进一步固定到最新 main 并扩至原始 2048 对事件;新的 Linux CI 仍在执行,尚不能将旧版 1024 对结果当成该轮通过。Issue 保持开放,待最新版本和吞吐边界完成验收。

    最新 main 补充复测

    MOTR CI run 45056755633 已实际使用 cc2c82dc4a6cb2cbcc046ef9caebde50c6004b15 并通过:

    • 单 worker / 8 producer,按原始规模每轮接收 2048 对 NEW/DESTROY,普通 3 轮、race 5 轮均为内核 0 / map 0。
    • 实际 MO 监听和消费者处理 256 条真实内核流:普通 3 轮、race 1 轮均由 256 降为 0,内核表为 0。
    • 16 worker 负对照收到全部 2048 对后内核为 0、map 残留 6,复现旧乱序症状;此失败是预期对照。
    • 生命周期与恢复测试普通 24 次、race 8 次通过。

    以上完整覆盖受控原始事件规模和实际消费者,但尚未提供长期高连接 churn、生产量级 burst/吞吐或真实 ENOBUFS 恢复验收,因此保留 Issue,不把该轮功能通过扩展为性能/长期稳定性结论。

  7. Ariznawlll commented on Nov 24, 2026

    @Ariznawlll
    Collaborator

    结论

    按原始“无丢失事件被多 worker 乱序交付,导致 DESTROY 后 flow 残留在 active map”问题验收通过,关闭本 Issue。单 ordered receiver 在真实多生产者内核事件和实际 MO consumer 下均保持 NEW/DESTROY 顺序,最终 kernel table 与 active map 同时归零;16-worker 负对照仍能复现残留,证明断言可以检出原故障。

    测试版本与修复

    原始多生产者内核场景

    测试仅在一次性 Linux network namespace 中创建合成 UDP conntrack 流,不修改宿主或客户流量:

    • 8 producers、单 worker,每轮完整接收 2048 NEW + 2048 DESTROY,普通 3/3、race 5/5 均为 kernel_flows=0 active_map=0。
    • 实际 MO listenConntrack / logConnTrack 处理 256 条真实内核流:普通 3/3、race 1/1 均由 active 256 降为 0,内核表也为 0。
    • 16-worker 负对照在完整收到 2048 对事件、内核表为 0 后仍残留 8 条;另有确定性注入残留 1 条的对照。二者证明测试不是永远通过的假 oracle。
    • 生命周期、接收异常恢复和 cleanup 定向测试普通 24 次、race 8 次通过,覆盖 NEW/DESTROY 清零、模拟 ENOBUFS、旧 generation 失效、有限重试及关闭所有权。

    回归去向与边界

    专项 fixture 和 workflow 保存在 MOTR #370,最新 run 已上传 kernel.log、kernel-race.log、production-consumer*.log、负对照及生命周期日志,可从上述 CI 追溯。

    本关闭结论不扩大为长期生产 churn、生产级 burst/吞吐或真实内核 ENOBUFS 的独立 QA 验收;模拟 ENOBUFS 单测没有冒称真实内核异常测试。事件丢失后的恢复只保证后续观测重建,不补回丢失事件,也不保证完整 kernel-table 快照。#31954 的负 WaitGroup panic、生产 OOM 和 SQL 数据一致性均不属于本单关闭范围。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

kind/bugseverity/s0

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions