Skip to content

Stop copying and eagerly decoding every tampered packet - #12

Merged
reflog merged 1 commit into
mainfrom
reflog/reduce-per-packet-allocations
Sep 1, 2026
Merged

reflog merged 1 commit into
mainfrom
reflog/reduce-per-packet-allocations

Conversation

@reflog

@reflog reflog commented Sep 1, 2026 •

Copy link
Copy Markdown
Contributor

Why

geneva-server applies a strategy to every packet of a proxy's traffic, so the per-packet cost of Apply is multiplied by the packet rate — at 1 Gbps with MTU-sized frames, ~83k packets/s per direction.

Profiling the sidecar under a tamper-every-data-packet strategy put ~30% of its CPU in the garbage collector and the scheduler feeding it, and the allocations were mostly from this package: 13 KB and 27 allocations per tampered packet.

Two of them are avoidable without touching any API.

What changed

actions/serialize.go — serializePacket re-decoded the bytes it had just serialized with gopacket.Default, which takes a second copy of the whole packet and eagerly decodes every layer. The buffer is allocated in that function and never reused, so the packet can alias it (NoCopy), and callers of a tampered packet generally serialize it straight back out rather than inspecting layers, so Lazy costs them nothing.

actions/tamper_action.go — tamperIPv4 allocated a fresh Contents buffer per packet where the TCP path directly beside it already appends into the existing one.

Measured

Through geneva-server's engine benchmark, per 1460-byte packet:

case before after
tamper 3268 ns, 13312 B, 27 allocs 2120 ns, 10888 B, 23 allocs
duplicate 2322 ns 1522 ns
pass-through 1017 ns 700 ns

A 31–35% reduction in per-packet cost. End to end on a 1-vCPU box this sits inside run-to-run noise, but CPU-per-byte is the quantity that decides whether a small VPS can carry a strategy at line rate, and that is what it improves.

The remaining allocations are the serialize buffers themselves, which would need a pooled or caller-provided buffer to remove — an API change, deliberately not in here.

Testing

Full suite green (go test ./...), including the tamper and fragment tests that assert byte-level output and checksums. The aliasing change is safe by construction: the buffer being aliased is allocated inside the same function and has no other reference.

Companion to getlantern/geneva-server (steering + hot-path work); that repo will bump this dependency once merged.

Summary by CodeRabbit

  • Performance
    • Improved packet processing efficiency through lazy decoding and reduced memory copying.
    • Reused existing packet buffers where possible to reduce allocations.
  • Bug Fixes
    • Preserved existing packet serialization and tampering behavior while improving resource usage.

The geneva-server sidecar applies a strategy to every packet of a proxy's
traffic, so the per-packet cost of Apply is multiplied by the packet rate: at
1 Gbps with MTU-sized frames a box sees ~83k packets/s per direction. A CPU
profile of a tamper-every-data-packet strategy spent ~30% of its time in the
garbage collector and the scheduler feeding it, and the allocations were mostly
from here: 13 KB and 27 allocations per tampered packet.

Two of those are avoidable without touching any API.

serializePacket re-decoded the freshly serialized bytes with gopacket.Default,
which takes a second copy of the whole packet and eagerly decodes every layer.
The buffer was allocated in that function and is not reused, so the packet can
alias it, and callers of a tampered packet generally serialize it straight back
out rather than inspecting layers — Lazy costs them nothing.

tamperIPv4 allocated a fresh Contents buffer per packet where the TCP path
beside it already appends into the existing one.

Measured through geneva-server's engine benchmark, per 1460-byte packet:

  tamper     3268 ns -> 2120 ns   13312 B -> 10888 B   27 -> 23 allocs
  duplicate  2322 ns -> 1522 ns
  passthrough 1017 ns ->  700 ns

The remaining allocations are the serialize buffers themselves, which would
need a pooled or caller-provided buffer to remove — an API change, not this.
@coderabbitai

coderabbitai Bot commented Sep 1, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Team

Run ID: 8eb05b9f-b990-47f4-84aa-481f31bf3d06

📥 Commits

Reviewing files that changed from the base of the PR and between 394a10a and 9eefee4.

📒 Files selected for processing (2)
  • actions/serialize.go
  • actions/tamper_action.go

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

The changes reduce copying during packet serialization and IPv4 tampering. Serialized packets use lazy, zero-copy decoding. IPv4 tampering reuses the existing header buffer.

Changes

Packet buffer optimization

Layer / File(s) Summary
Serialization and IPv4 header buffer reuse
actions/serialize.go, actions/tamper_action.go
serializeTamperedPacket enables lazy decoding and buffer aliasing. tamperIPv4 reuses ip.Contents while preserving the serialized header bytes.

Estimated code review effort: 1 (Trivial) | ~2 minutes

Merge Risk: ⚪ Minimal · up to 9eefe

This localized change reduces per-packet CPU and allocation costs without changing the public API; no actionable merge-blocking risk remains after normal checks and review.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main changes: it reduces packet copying and eager decoding during tampered packet handling.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch reflog/reduce-per-packet-allocations

Comment @coderabbitai help to get the list of available commands.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR reduces per-packet CPU and allocation overhead in the actions hot path by avoiding unnecessary buffer copies and eager packet decoding when rebuilding tampered packets.

Changes:

  • Rebuild tampered packets using gopacket.DecodeOptions{Lazy: true, NoCopy: true} to avoid a second full-packet copy and eager layer decoding.
  • Reuse the existing IPv4 header Contents buffer via append(ip.Contents[:0], ...) instead of allocating/copying a new buffer per packet.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
actions/tamper_action.go Reuses the IPv4 header backing buffer to reduce allocations during IPv4 tampering.
actions/serialize.go Switches rebuilt tampered packets to lazy decode + no-copy to eliminate redundant copy/decoding work.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@reflog
reflog merged commit c04e0fa into main Sep 1, 2026
7 checks passed
reflog added a commit to getlantern/geneva-server that referenced this pull request Sep 1, 2026
getlantern/geneva#12 is merged, so pick it up: serializePacket no longer copies
and eagerly decodes every tampered packet, and tamperIPv4 reuses its header
buffer.

Engine benchmark per 1460-byte packet, against this branch before the bump:

  tamper       3268 ns -> 1922 ns
  duplicate    2322 ns -> 1575 ns
  passthrough  1017 ns ->  533 ns
reflog added a commit to getlantern/geneva-server that referenced this pull request Sep 2, 2026
…ink costs (#3)

* Steer only what the strategy can act on

The sidecar's cost is the NFQUEUE round trip, not the manipulation. Measured on
a 1-vCPU staging box running vless+REALITY, a bulk TLS transfer fell from
105 MB/s to 25 MB/s with the sidecar running and *no strategy loaded*, while a
strategy that duplicated every data packet cost only ~4 MB/s beyond that. An
eval box waiting for its first candidate, and a prod box rolled back with
PUT "", were both paying full price for manipulating nothing.

A Geneva strategy returns any packet its triggers do not match byte for byte, so
a packet that cannot match does not need to be in userspace to be handled
correctly. Steering is therefore derived from the strategy:

  - No trees at all: no table, no rules, and the NIC left alone. An
    unconfigured sidecar now has no effect on the box, which is what "eval boots
    in pass-through" was always supposed to mean.
  - Triggers on TCP flags: nftables matches those flag combinations, per
    direction, and bulk data never leaves the kernel. This is the common case —
    real strategies act on the handshake.
  - Anything nftables cannot express (payload, IP fields, TCP options): queue
    everything, exactly as before.

internal/steering owns the derivation and the reconcile. The kernel and the NIC
are now reprogrammed on every strategy change rather than only at boot, so PUT
goes through the controller instead of straight to the engine: a strategy change
can put a box on or take it off the data path. Ordering inside the reconcile is
load-bearing and commented — offloads down before any queue opens, rules
programmed before the engine swaps, offloads restored only once the rules are
gone.

Two related fixes fall out. Stopping the sidecar now restores the offloads it
disabled (it never did, so a box that had run one stayed de-offloaded until
rebuild), and re-enabling them needs sg/tx before tso/gso or the kernel rejects
those two. And `--mode=prod --strategy-file=<empty file>` used to satisfy the
"prod requires a strategy" check and boot in pass-through; with scoping that
would silently leave a prod box off the data path, so the check now runs against
the resolved DNA.

The scoping is only safe if the kernel never filters a packet the strategy would
have touched. TestScopeNeverNarrowerThanStrategy pins exactly that: for every
strategy shape and every packet the selector rejects, the engine must return
Unchanged. Gas semantics are preserved for free, since gas is consumed only by
matching packets and the filtered ones never matched.

Measured with the new bench/ harness (docker, 2 GB per condition):

  no-sidecar                  7086 MB/s        0 CPU-s/GB          0 pkts
  eval/no-strategy            6426 MB/s        0 CPU-s/GB          0 pkts
  eval/handshake-only          935 MB/s        0 CPU-s/GB          0 pkts
  eval/tamper-every-packet      81 MB/s     14.9 CPU-s/GB       1.48M pkts
  prod/rolled-back-to-empty   6977 MB/s        0 CPU-s/GB          0 pkts

Zero packets reach userspace for a handshake-only strategy against bulk
traffic, and zero for no strategy. What remains in the handshake row is the NIC
offload teardown, which costs ~7x on a veth pair but measured ~1% on the real
VM; tamper-every-packet is unchanged because it genuinely must see every packet.

The censor-reachability signal is the one thing scoping takes away: an
outbound-only strategy no longer brings inbound packets to the classifier that
estimates whether a box's IP is burned. --observe-inbound restores it at the
cost of a round trip per inbound packet, off by default, and never at the
expense of the no-strategy case. Reading those counts from nftables counters
instead would give both; that is the obvious next step and is not in here.

* bench: stop tracking the strategy mount target

run.sh rewrites bench/strategy.dna for every condition, so tracking it left the
tree dirty after each benchmark run. The runner creates it instead.

* Own the netlink hot path instead of paying for a generic one

A tamper-every-data-packet strategy ran at 74 MB/s and burned 14.9 CPU-seconds
per GB in the benchmark harness. Profiling said the Geneva engine was under 10%
of that: 41% was syscalls and ~30% was the garbage collector and the scheduler
feeding it.

The cause was the generic Go netlink stack. mdlayher/netlink's Receive
allocates a fresh page-sized buffer per call, does a MSG_PEEK recvmsg to size
the message, then a second recvmsg to read it, then allocates again to parse
it — two syscalls and several allocations for every packet before any work
happens. go-nfqueue then marshals each verdict through the same generic path.

So the setup still goes through mdlayher/netlink, where it is readable and runs
once, and the per-packet path is ours:

  - One recvmsg into a reusable buffer, returning however many packets the
    kernel has queued rather than exactly one.
  - Parsing in place: a payload is a subslice of the read buffer, whose lifetime
    is exactly the window in which the verdict is issued.
  - Accept verdicts batched into one message per read. A batch verdict covers
    every id up to the one it names and ids increase monotonically, so a run of
    accepts collapses — and the batch is flushed before any individual verdict
    for a later id, or it would swallow a packet meant to be dropped.
  - Verdict messages marshalled into a reusable buffer.
  - A rewritten packet replaces the queued one instead of being dropped and
    reinjected through the raw socket, which also skips a second trip through
    netfilter and a routing lookup. Only the extra packets of a fan-out
    strategy still need the raw socket.
  - engine.Process takes a caller-owned Scratch, so the decode copy and the
    output slice are reused per queue goroutine rather than allocated per
    packet, and the decode is Lazy+NoCopy.

Measured with bench/run.sh, 2 GB per condition, tamper-every-data-packet:

              throughput      CPU/GB     CPU/packet
  before        74 MB/s     14.9 s       17.7 us
  after        163 MB/s      4.3 s        5.8 us

2.2x the throughput for 3.5x less CPU per byte, which is the number that
decides whether a 1-vCPU VPS can carry a strategy at line rate. Zero-packet
conditions are unchanged, since no packet reaches userspace in them at all.

This also fixes two things the old path got wrong. A packet the kernel copied
only part of was manipulated and reinjected as if whole; it is now detected via
NFQA_CAP_LEN and accepted unmodified, counted in verdicts.truncated. And a
socket-buffer overrun was invisible; ENOBUFS is now counted in
verdicts.overruns, where a nonzero value means packets bypassed the strategy.

Two bugs found while doing it, both by running against a real kernel rather
than only the unit tests: the kernel does not pad the last attribute or the
last message in a buffer, so stepping by the aligned length walks off the end
(it panicked immediately), and the offload restore tried to re-enable features
the driver reports as fixed, which now come from reading ethtool -k first.
Shutdown also hung until the container was killed, because the readers kept
draining the socket that Close needed an ack from; the readers are now
interrupted and waited for, and Close no longer sends an unbind it cannot hear
the answer to.

--pprof-addr serves profiles on a mux of its own, off unless the flag is set.

* Document what --observe-inbound actually costs

The flag's cost was described as "roughly half the packets on a busy proxy",
which was a guess and wrong about the mechanism. Measured on a 1-vCPU staging
box (route d711a4df, vless+REALITY), holding the strategy fixed and toggling
only the flag:

  download-heavy, handshake-only strategy   105.1 -> 105.0 MB/s   free
  download-heavy, tamper every data packet   36.6 ->  33.3 MB/s   -9%
  upload-heavy, handshake-only strategy      79.3 ->  47.4 MB/s   -40%

The cost is one round trip per inbound packet, so it tracks the inbound packet
rate rather than the byte rate, and which way the box's bulk traffic runs
decides everything. A download's inbound direction is nothing but stretch-ACKs
— 18.9k inbound packets across 900 MB, one per ~33 outbound data packets — so
observing it is free. An upload's inbound direction is the bulk stream, and then
every packet pays.

Same default (off), but an operator can now decide by direction instead of by a
number that was wrong in both directions.

* Refuse --observe-inbound in prod mode

Observing inbound costs a userspace round trip per inbound packet, whether or
not the strategy can act on one. Measured on a 1-vCPU box: free where clients
download, since a download's inbound direction is only stretch-ACKs, but -40%
where they upload. A prod box does not get to choose which its users do, so the
flag is a bet on traffic shape that nobody is in a position to make.

What it buys is the censor-reachability signal, an inference from a SYN-to-data
ratio — and an eval box, which carries no client traffic, produces that same
signal for nothing. The box that can afford the cost is the box that does not
have to pay it.

So prod refuses the flag at startup instead of warning about it, and the
controller will not apply the observation floor outside eval mode either: the
CLI is not the only thing that can build one, and the hot-swap path writes
geneva.env on a live box.

A prod box that genuinely needs inbound packets in userspace still has a precise
way to ask — give the strategy an inbound tree, and steering follows the
strategy. The e2e now does exactly that instead of passing the flag, which
surfaced something worth writing down: the signal is only as complete as the
strategy's inbound triggers. An `A*` tree never matches a client SYN, and the
burn estimate is a SYN-to-data ratio, so e2e/strategy.txt carries both trees.

* Address Copilot review: set the netlink family, document the verdict counters

Two review findings, handled differently because only one was a defect.

The netlink family was left at zero. The kernel does not read that field for
the messages it is sent with here — the queue bind and the verdicts — which is
why v0.0.1 worked with it unset, and why the e2e and a 1.3M-packet staging run
never noticed. But an implicit AF_UNSPEC in an IPv4-only sidecar reads as an
oversight rather than a decision, so it is now AF_INET explicitly, with a
comment saying the kernel ignores it so nobody mistakes it for the switch that
would enable IPv6.

The review also asked for Stats.Modified to be incremented on the fallback path
where an overwrite verdict is refused and the replacement goes out through the
raw socket instead. Not done: that packet is already counted in Reinjected and
its original in Dropped, and counting it a second time would make
Accepted + Dropped + Modified stop reconciling with PacketsIn — which is the
property that makes a bypassed or lost packet visible.

The underlying complaint is fair, though: the counters are per mechanism, so
"how many packets did the strategy change" is Modified plus the fan-out share of
Reinjected, and neither answers it alone. That was nowhere in the code, and now
it is, on Stats and at the fallback itself.

* Address CodeRabbit review: a shutdown hang, a stale table, and honest benchmarks

Four real findings, one of them a bug I would have shipped.

Run did not cancel the surviving pump when its peer failed. interrupt makes that
pump's read return a deadline error, which pump treats as the ordinary
idle-queue case and retries — against a deadline still in the past. So one pump
failing meant the other busy-spun and wg.Wait never returned: a hang on
shutdown, not a slow exit. Run now derives a cancellable context and cancels it
before interrupting the queues.

Start with an idle strategy recorded the empty scope without programming it, so
a table left behind by an unclean exit survived into a process that then opens
its queues. A leftover table with no reader is harmless — the rules carry
bypass — but with a reader attached it is live steering, which would put a box
with no strategy back on the data path: precisely what this branch promises
cannot happen. Now programmed, with a root-gated test that installs a stale
table and asserts Start removes it. Verified the test fails without the fix.

Start also left the NIC de-offloaded if rule programming failed after the
offloads came down, since the caller only registers teardown once Start
succeeds.

And two in the harness, both of which already cost me a wrong measurement
today. bulk reported a throughput number for a transfer that failed or came up
short, so a broken condition could be recorded as a result; it now exits
non-zero. run.sh collapsed any telemetry failure to zero, which reads exactly
like the ideal result — a stopped sidecar showing 0 CPU and 0 packets — so it
now aborts while a sidecar is expected, and only the deliberate no-sidecar
baseline may report zero. Units are GiB and MiB/s throughout, since that is what
the byte counts are.

* Bump geneva for the per-packet allocation fixes

getlantern/geneva#12 is merged, so pick it up: serializePacket no longer copies
and eagerly decodes every tampered packet, and tamperIPv4 reuses its header
buffer.

Engine benchmark per 1460-byte packet, against this branch before the bump:

  tamper       3268 ns -> 1922 ns
  duplicate    2322 ns -> 1575 ns
  passthrough  1017 ns ->  533 ns

* Count the censor signal in the kernel instead of steering for it

Steering follows the strategy, so an outbound-only strategy delivers no inbound
packet to userspace — and the censor-reachability signal is about inbound
packets. Scoping was buying throughput by going blind, with --observe-inbound as
the only way back and a measured -40% on upload-heavy traffic as its price.

The classification moves into nftables instead. A table that exists for steering
now also carries named counters and a chain that sorts arriving packets into
them (RST, SYN, FIN, data, ack_only, in that precedence, each rule returning so
every packet lands in exactly one bucket), read once per export interval through
`nft -j list counters`. No packet is queued for the signal, it works the same in
prod and eval, and it does not care whether the strategy has an inbound tree.
The e2e now asserts exactly that: inbound SYNs and data counted while the
ruleset carries no inbound queue rule at all.

censor.Source is the seam — the kernel counters and the userspace classifier
both satisfy it, and only one is active on a box. --censor-counters=false picks
the old path, where the signal is again only as complete as what the strategy
steers.

Two of the userspace classifier's buckets have no kernel equivalent and report
zero: `undecodable`, since nothing decodes these packets, and `fragment`, which
would need a rule with no port match because a non-initial fragment carries no
TCP header. And "carries a payload" is `meta length > 80`, because nftables
cannot subtract one header field from another; a pure ACK with 32 bytes of
options is 72 bytes, so the threshold is safe for anything proxy traffic
produces.

The kernel's counters are objects inside the sidecar's table, so a strategy
change rebuilds them from zero. KernelSource accumulates deltas and treats a
decrease as a restart, so the exported series stays monotonic and a rollout does
not read as a counter going backwards. A failed read keeps the last known counts
rather than reporting zeroes, which would read as the censor having stopped.

The counters never keep a table alive on their own: a box with no strategy still
has nothing of ours in the kernel, and reports no censor signal. That gap is
deliberate — see the README — and a box that should be reporting a burn rate is
a box that should have a strategy.

Also drops what --observe-inbound was standing in for: with the counters, it no
longer has anything to do with the censor signal, and what it still buys is
packets rather than counts, which only the eval canary pool consumes.

* Apply the cleanup review: dedup helpers, unblock the censor read, trim the verdict marshal

Reuse: netlink framing constants now alias x/sys/unix instead of shadowing
kernel ABI; one missing-table predicate serves both nft call paths; the
packet builder and TableExists live in internal/testutil instead of three
near-identical test copies; e2e and bench source scripts/harness-lib.sh for
the step/cleanup/wait-healthy scaffolding; one slog adapter serves both the
runtime and the steering controller.

Efficiency: KernelSource no longer holds its mutex across the nft exec, so
/healthz and the metric callback read last-known totals instead of stalling
behind a subprocess; CensorCounts answers an idle box without forking nft;
marshalVerdict clears only the bytes not otherwise written instead of the
whole buffer; classify compares with bytes.Equal.

Altitude: PUT /strategy now requires Providers.Apply and fails loudly
instead of silently swapping the engine without reprogramming the kernel;
the censor counter names derive from censor.KernelEvents so the kernel and
metric views cannot drift; steering.Config embeds the base nftables.Config
instead of copying it field by field.

Simplification: dead Controller.DNA/Scope, the unused censorRules port
parameter, the unread counter Table field, and the bench script's no-op
gb_moved are gone; handle() uses the accept helper on its fail-open paths;
eventFor's per-refresh linear scan became a package-level map.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Address Copilot review: parenthesize flag sets, classify apply errors, honest decode bench

Multi-flag sets are now rendered in parentheses: nft parses bare pipes with
its own operator precedence, so `tcp flags & syn|ack == syn|ack` installed
cleanly as a completely different match — verified against a real nft, which
lists it back as `tcp flags & (syn | ack) | ack`. A wildcard multi-flag
trigger like SA* would have silently mis-scoped; regression test added.

PUT /strategy now tells a client error from an infrastructure one: parse and
validate failures wrap the new engine.ErrInvalidStrategy and stay 400, while
a failure to program the kernel for a valid strategy is a 500 — a 400 there
would send the caller off fixing a DNA that is fine.

BenchmarkDecode uses the same Lazy/NoCopy decode options Process uses, so it
measures the hot path's decode rather than gopacket's eager default.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
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.

2 participants