Skip to content

perf: precompile namespace filter rules - #1074

Open
liusf1993 wants to merge 1 commit into
alibaba:developfrom
liusf1993:perf/precompile-namespace-filter
Open

liusf1993 wants to merge 1 commit into
alibaba:developfrom
liusf1993:perf/precompile-namespace-filter

Conversation

@liusf1993

Copy link
Copy Markdown

Summary

Namespace filtering currently calls regexp.MatchString with the same generated rule strings for every namespace. This recompiles the regular expressions on the hot path, including when a large number of oplog records belong to namespaces outside the configured filter.

  • Compile the whitelist and blacklist rules once when constructing a NamespaceFilter and reuse the compiled expressions.
  • Preserve the existing rule construction, match/prefix semantics, whitelist/blacklist precedence, empty and malformed pattern behavior, and command/time-series exceptions. No configuration or public API changes.
  • Add table-driven compatibility tests and a benchmark covering 1, 4 and 23 rules for both match and miss paths.

Benchmark

Go 1.27.3, darwin/arm64, Apple M4. Same benchmark on the develop baseline and this change; medians of three runs per case:

go test ./collector/filter -run '^$' -bench '^BenchmarkNamespaceFilterNs$' -benchmem -benchtime=200ms -count=3
23 rules Before (ns/op) After (ns/op) Allocations/op
Whitelist match 37,653 247.10 325 → 1
Whitelist miss (different database) 35,848 25.79 325 → 1
Blacklist match 37,871 246.80 325 → 1
Blacklist miss (different database) 38,622 24.86 325 → 1

Compiled-rule initialization is outside the timed loop. The figures measure individual FilterNs calls with synthetic namespaces, not end-to-end replication throughput.

Validation

  • New TestNamespaceFilterRuleMatching passes on both the original and optimized implementation.
  • Main and tools module builds pass (go build ./...); all tracked Go files are gofmt-clean.
  • MongoDB-free CI tests pass: collector/configure, collector/filter, collector/transform, collector/spool.
  • TLS regressions and relevant collector configuration tests pass.
  • go test -race ./collector/filter -count=1 passes.
  • Upstream ACK/barrier race regressions and filtered transaction/checkpoint regressions pass together (three repeats, shuffled).
  • The MongoDB-backed integration suite was not run.

Namespace filtering invokes regexp.MatchString with the same rule strings
for each namespace, recompiling unchanged expressions on the hot path.

Compile whitelist and blacklist rules once per filter and reuse them.
Preserve empty and malformed-pattern behavior, rule precedence and
special namespace handling. Add compatibility tests and benchmarks.

Co-Authored-By: OpenAI Codex <noreply@openai.com>
AI-Model: gpt-6.2-sol
AI-Contributed/Feature: 25/25
AI-Contributed/UT: 81/81
@CLAassistant

CLAassistant commented Nov 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@zhongli-james zhongli-james self-assigned this Nov 30, 2026
@zhongli-james
zhongli-james self-requested a review November 30, 2026 01:47
@zhongli-james

Copy link
Copy Markdown
Collaborator

Reviewed 51047bd on top of origin/develop feee8a5, go1.27.4 darwin/arm64 (Apple M4), against the local mshake-* MongoDB 7.0 cluster. No blocking issues — this looks mergeable. I tried to break the equivalence claim rather than take it on faith; what I ran is below.

Equivalence

The entire semantic surface of the change is filterNsByRules. FilterNs is byte-identical between the two revisions, and every entry point funnels into filterNsByRules: NamespaceFilter.Filter(log) via filter.filter(log) (collector/filter/oplog_filter.go:419), and the applyOps branch via a direct FilterNs(innerNs) per inner op (collector/filter/oplog_filter.go:391).

I re-implemented the develop version of filterNsByRules verbatim (string rules, regexp.MatchString, discarded errors) and diffed it against the compiled version over 25 white rule-sets × 25 black rule-sets × 33 namespaces = 20,625 combinations, zero divergence. The corpus covers nil and empty slices, {""}, invalid patterns (source.[, [) alone and mixed with valid ones in both orders, trailing/leading/double dots, |, (), *, ^$, pre-escaped \., unicode and $; namespaces cover .$cmd, system.views, system.buckets.*, system.profile, admin.$cmd and literal metacharacters.

That probe only exercises the unexported rule layer, which leaves the system.buckets.* logical-name rewrite covered by argument rather than by measurement. So I also transcribed the develop FilterNs wrapper verbatim, paired it with the baseline rule layer and whiteDBRuleMap, and compared the full exported entry point over 32 × 32 rule-set pairs × 45 namespaces = 46,080 combinations, again zero divergence. This corpus adds multi-rule sets and near-miss prefixes (p.q / p.qr / p.qs / p.q.r, gogo.test1X, source.system.buckets.events7).

The white/black error asymmetry is preserved correctly: invalid whitelist filters everything, invalid blacklist filters nothing, and invalidWhiteRule is exactly what stops the first case from degrading into "no whitelist configured".

Test sensitivity

TestNamespaceFilterRuleMatching passes on the develop baseline as well, which is the right shape for a behavior-preserving refactor. To confirm it isn't vacuous I deleted filter.invalidWhiteRule || from collector/filter/doc_filter.go:122 and re-ran: invalid_white_rejects fails with expected: true, actual: false. The one genuinely new piece of logic is guarded by an assertion that bites.

Concurrency

Production shares a single *NamespaceFilter across batcher workers. I ran one shared instance under -race with 32 goroutines × 500 iterations × 7 namespaces, asserting against results computed single-threaded first: clean, no race report. The PR adds no shared mutable state and no lazy initialization.

Minor, non-blocking: the new table never uses more than one rule

All 22 cases pass a single-element (or empty) slice, so the alternation grouping that convertToRule exists to build is untested — not just by this table, but anywhere in the package. Concretely: change collector/filter/oplog_filter.go:262 from fmt.Sprintf("^(%s)$|^(%s).*$", …) to fmt.Sprintf("^%s$|^%s.*$", …) and go test ./collector/filter -count=1 still reports ok. That mutant is a genuine regression — alternation binds loosest, so the pattern degenerates to (^gogo\.test1) OR (gogo\.test2$) OR …, and NewNamespaceFilter([]string{"gogo.test1","gogo.test2"}, nil).FilterNs("gogo.test1X") returns false where it must return true.

convertToRule is untouched by this PR, so this is a pre-existing hole rather than something you introduced. But since the table is explicitly about rule construction and prefix semantics, a few multi-rule rows would close it cheaply:

{name: "multi rule exact match", white: []string{"gogo.test1", "gogo.test2"}, namespace: "gogo.test2"},
{name: "multi rule prefix boundary", white: []string{"gogo.test1", "gogo.test2"}, namespace: "gogo.test1X", filtered: true},
{name: "multi rule prefix match", white: []string{"gogo.test1", "gogo.test2"}, namespace: "gogo.test2.archive"},
{name: "multi rule black boundary", black: []string{"gogo.test1", "gogo.test2"}, namespace: "gogo.test2X"},

I ran these four rows on your branch: all pass, and the prefix boundary one goes red under the mutant above.

Verified locally

  • go build ./... — main module and tools/ module, both clean
  • gofmt -l on all three changed files — clean
  • go vet ./collector/filter — 42 pre-existing unkeyed-field warnings, all in untouched test files (filter_test.go, lazy_test.go, orphan_filter_test.go); zero in the three changed files
  • go test ./collector/filter ./collector/configure ./collector/transform ./collector/spool -count=1 — ok
  • go test -race ./collector/filter -count=1 — ok
  • go test -p 1 ./collector/... -count=1 -timeout 25m against the local MongoDB 7.0 cluster — all 9 packages ok, including collector (316s, where the batcher / barrier-ACK / filtered-transaction regressions live) and collector/reader
  • Your benchmark, re-run on both branches sequentially: the 325 → 1 allocs/op claim reproduces exactly (all 36 runs on the PR side report 1 alloc/op). 23-rule medians on my box: white match 21952 → 151.0 ns/op, white miss 21425 → 14.23 ns/op. Absolute latencies differ from your figures on both sides of the comparison; same direction and order of magnitude.
  • All construction sites build the filter once, not per record (collector/syncer.go:186, collector/docsyncer/doc_syncer.go:324 and :599, collector/coordinator/full.go:102, collector/reader/event_reader.go:151, collector/coordinator/timeseries_change_stream.go:37, cmd/collector/sanitize.go:463), so "compile once" is a real win on the oplog path rather than a per-record reconstruction.

@zhongli-james

Copy link
Copy Markdown
Collaborator

Thank you for your contribution—excellent work!

This branch has not been deployed

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants