Skip to content

feat(speedcap): per-user download and upload speed cap - #12

Merged
Free-Guy-IR merged 32 commits into
mainfrom
feat/003-speed-cap
Dec 2, 2026
Merged

Free-Guy-IR merged 32 commits into
mainfrom
feat/003-speed-cap

Conversation

@Free-Guy-IR

Copy link
Copy Markdown
Owner

Draft for CI only, not for merge yet.

  • A new Xray patch adds a per-user token bucket in the dispatcher stats writers, shared by every connection of the user, refuses Vision splice for capped users and bounds a running splice.
  • The node keeps a durable cap store, applies revision and snapshot rules, gates SetUserSpeeds like every other backend call, and hands the store to each core start.
  • Proto: SetUserSpeeds, SpeedEntry, SpeedRejection, SetUserSpeedsResponse with high_water and stale, BaseInfoResponse.supports_speed_cap.

Verification and the production rollout are still pending.

…ed core

A per-email token bucket in the dispatcher stats writers, shared by every
connection of the user, with a one second burst, lazy buckets reaped after
ten idle minutes, a generation counter that live writers re-read, and the
revision and floor rules of SetUserSpeeds. Vision splice is refused for a
capped user and a running splice falls back to the counted copy loop in
256 KiB steps. Caps from XRAY_SPEED_CAP_FILE are loaded before the first
connection. The operation is an AlterInbound operation like session revoke.
The node keeps the per-email cap set in SPEED_CAP_STORE_PATH, written
atomically before the core is told, applies the revision and snapshot
rules, answers rejected, stale and high_water, pushes a diff or the whole
set to the core through AlterInbound, hands the store to every core start
through XRAY_SPEED_CAP_FILE and pushes the whole set again once the core
API answers. gRPC SetUserSpeeds and REST PUT /user/speeds answer
UNIMPLEMENTED or 501 when the primary backend is not xray or its core does
not know the operation. BaseInfoResponse reports supports_speed_cap.
…kend

SetUserSpeeds was in no gate map, so gRPC checked only the API key: a
client holding the key that does not control the node could change caps,
and a node without a backend reached the handler. It now passes the same
current-client and backend gates as every other backend call, like PUT
/user/speeds does in REST. A parity test puts every NodeService RPC in
exactly one gate set; GetOutboundsLatency, ungated before this change,
stays listed as known unclassified so the gap remains visible.
…they can observe

The target starts with whole 4 KiB TLS records so Vision switches to direct
copy, and the tests wait up to 15 s for the core to log the splice before
they cap a user, so a run where Vision did not splice fails instead of
proving nothing.
…in force

A retry of a change the core missed, or a repeated request, carries the
cap the node already enforces at the same revision; reporting it stale made
the panel show it not applied until a healing snapshot. An entry is now
stale exactly when the cap the node enforces for its email after the
request, with no entry or a tombstone meaning none, differs from the
entry's cap. An equal revision with another cap, as after a panel backup
restore, is still stale.
…a directory

Upstream names a single data file *_FILE and keeps each kind of node data
in its own directory under /var/lib/pg-node (SSL_CERT_FILE in certs/,
GENERATED_CONFIG_PATH for generated/), read with GetEnv in Load. The cap
store follows that: SPEED_CAP_FILE, default
/var/lib/pg-node/speedcaps/speed_caps.json, listed in .env.example with
the other optional paths.
…mage

make test_xray_patches runs under GOFLAGS=-race, and the scenario helper
inherited it, so the xray the scenarios started was a race build. Its
checkptr instrumentation stops the upstream Vision outbound at
proxy/vless/outbound/outbound.go:288 (fatal error: checkptr: pointer
arithmetic result points to invalid allocation), which broke both Vision
splice tests in CI. The scenarios now build their xray with GOFLAGS
cleared, CGO_ENABLED=0, -trimpath and the image's ldflags, while the test
process itself keeps -race.
An adversarial mutant that compared only the download cap passed every
store and controller test. This test fails on that mutant and passes on
the store, which compares both directions.
…PI answers

The node pushes the whole cap set once the restarted core's API answers,
so the old test passed even when the cap file never reached the core: the
push covered the first window. The test now polls the restarted core's API
only every 3 s, so the first seconds of traffic meet only what the core
loaded from the file. With the file name kept from the core a 1 s window
carries 13 MB against a 2.2 MB limit; with it the windows stay under.
…ght up with

Open leaves a store dirty until its first push, so the controller retry
tests passed even when a failed push did not mark the store dirty. They now
start after a successful sync, so a store that forgets a failed push leaves
the core without the cap and both tests fail.
…ray chain

The guard replay's self-test requires the chain to end with the zstd and
reality patches and their go.mod checks, and the speed cap patch had been
appended after them. It now goes between listener-mptcp-off and
pinned-ca-servername, where make build_xray's glob order already applies
it; the chain applies with every guard, gives the same tree, and the guard
replay still catches the removal of each of its eight product files.
…node and in the core

A snapshot entry rejected for an empty email or revision 0 still counted as
listed, so the node kept an old record below the new floor while the core
mirror dropped it; the reviewer's randomized differential test hit it at
seed 1 step 82. Both rule sets now skip invalid entries before listing them.
The patch carries the differential test, 400 in-memory seeds of 400 steps
and six file-backed seeds of 150 steps with failed pushes, lost answers and
restarts, run against a copy of this store under testing/speedcapnode, and
a node test fails whenever that copy differs from pkg/speedcap/store.go.
MarkDirty took the store lock that Apply holds through a core push of up to
10 s, so a health-check restart waited behind a hung push (measured 1.95 s
behind a 2 s push). The store now keeps an atomic epoch that MarkDirty
bumps without a lock, and Apply and Sync take the core as caught up only if
the epoch did not move during their push. The post-start sync uses the
caller's context instead of a fresh one. The differential test in the patch
runs against this store.
…l Start

The store had no owner and no expiry, so after a move to a panel that never
sends SetUserSpeeds the caps were loaded on every core start, invisible and
impossible to clear from that panel. Each panel Start now arms a lease of
SPEED_CAP_LEASE_SECONDS (600 by default, read like the stats intervals);
any snapshot disarms it. If it runs out, the node applies an empty snapshot
at its high water: every entry and tombstone goes, the floor rises to the
high water so a delayed diff cannot revive a cap, the same empty set is
mirrored to the core and the node logs it. Core restarts the node starts by
itself never arm or clear the lease.
SpeedEntry gains repeated inbound_tags = 5 on the node proto and in the core
operation. An empty list caps every inbound as before; otherwise only links
whose session inbound tag is listed are capped, still through one bucket per
email, with the tag read from session.Inbound.Tag as upstream routing reads
GetInboundTag. A scope change at a newer revision reaches live writers
through the generation bump without closing a connection, and the Vision
splice is refused only on a covered inbound. Tags are kept canonical on the
node and in the core: empty names dropped, sorted, deduplicated, none on a
tombstone, and length-prefixed so no tag can split into others. The store
file carries them as inbound_tags, and stale compares down, up and the
canonical tags. The differential test draws random scopes and checks the
core's coverage of every probed tag against an oracle; the Dockerfile
guards follow the new signatures.
… refused and the node keeps serving

The owner ordered the sing-box server core removed («کامل بردارش»,
2026-12-01). Once it is gone, a panel that still sends BackendType 2 must
get a clear refusal from the node, and the node must go on serving.

The test drives a fresh in-process node over gRPC the way a panel does:
a Start of type 2 with a sing-box config and a user carrying every
credential must fail with "invalid backend type" (upstream's message for
an unknown type); an AddBackend of type 2 must fail with InvalidArgument
with and without a running primary; a RemoveBackend of type 2 must report
NotFound; and the same node must then start Xray, report started, list
Xray alone and stop advertising sing_box.

RED on 74c660d: the node still builds type 2 as sing-box and fails with
"fork/exec /usr/local/bin/sing-box: no such file or directory".
…and the primary keeps running

The REST counterpart of the gRPC refusal test, on the package's shared
node with its Xray primary: POST /backend of type 2 must answer 400 Bad
Request, DELETE /backend of type 2 must answer 404 Not Found, and the node
must still list Xray alone and serve GET /stats afterwards.

It replaces the REST coverage of the two sing-box tests that go with the
backend. Read from the code and from run-tests.yml, not reproduced: no
remaining extra backend can be attached by the unprivileged CI race run.
WireGuard creates its link through netlink, OpenVPN renders "dev tunN" and
needs an openvpn binary the job does not install, and L2TP's CheckDeps
wants xl2tpd, pppd, /dev/ppp and strongSwan. So the /backend routes are
held on their refusal paths instead.

RED on 74c660d: the node builds type 2 as sing-box, and POST /backend
does not answer within the client's 10 s timeout ("context deadline
exceeded (Client.Timeout exceeded while awaiting headers)").
The owner had the sing-box server core removed («کامل بردارش»,
2026-12-01). It is fork-only: upstream PasarGuard/node has no
backend/singbox. On the production panel its only core (9) drives three
disabled nodes, which the panel track deletes before rollout.

- backend/singbox goes entirely (36 files, 8,675 lines), with its registration in
  buildBackend, "sing_box" in supported_backends, its entry in
  multiInstanceBackends, and config.SingBoxExecutablePath with its
  SINGBOX_EXECUTABLE_PATH variable.
- The four controller tests that exercised sing-box's own API and loopback
  guards and its counter carrying go with it. The Xray counter-carrying
  tests (backend_replacement_counters_test.go) stay as they are.
- The multi-backend unit tests that used SING_BOX as a fake type take
  WIREGUARD, OPEN_VPN or XRAY; every assertion is unchanged.
- The two REST tests that attached a real sing-box extra go, and the
  refusal test of the previous commit holds the /backend routes instead.
- The README fork note and the port warning stop naming sing-box;
  .gitignore drops the sing-box-src build directory.

A Start of type 2 now falls to buildBackend's default and is refused with
upstream's "invalid backend type"; an AddBackend of type 2 is refused as
not shareable. Both RED tests of the previous commits pass.
…ing-box backend

backend/openvpn never depended on sing-box; its comments only compared it
with backend/singbox, which is gone. The sentences and clauses that name
it are deleted and nothing is reworded: no comment gains a word, and the
code is unchanged.
- Dockerfile: the singbox-builder stage and its COPY into the final image
  go; the xray-builder comment loses its pointer to that stage.
- Makefile: build_singbox, test_singbox_http2_guard and the SINGBOX_*
  variables go; scripts/singbox_http2_guard.sh and its test go.
- run-tests.yml: the steps that built the pinned sing-box and ran the live
  sing-box tests go, and the controller race run no longer sets
  SINGBOX_EXECUTABLE_PATH. workflow_gates.lock carries the new fingerprint
  of the test job, regenerated with workflowgate fingerprint; no other job
  changed.
- scripts/test_workflow_policy.sh: the race-step mutations follow the
  one-line controller run, and the sing-box path mutation becomes
  "controller dropped from the race run", the twin of the backend one.
- scripts/toolchain_floor.sh no longer allows a sing-box copy in the final
  stage. Its tests drop the singbox-builder stage from both fixtures and
  move the four cases that used it (GOFLAGS as ARG and as a RUN
  assignment, GOTOOLCHAIN=auto, go env -w GOTOOLCHAIN) and the
  missing-digest case to the builder stage. The final-copy flag case
  copies /app/main with --chmod. Every expected pin count is one lower,
  and every problem count that covered all the golang images too.
- scripts/test_govulncheck_gate.sh: the other-stage fixture applies its
  patch in a builder stage that fetches PasarGuard/node.

Local runs on this tree (macOS, bash 3.2): test_toolchain_floor.sh 299
cases, 0 failed (run in chunks); toolchain_floor.sh 12 pins checked;
test_govulncheck_gate.sh 87 passed; workflow_policy.sh, test_workflow_policy.sh
(57 refusals), test_workflow_steps.sh (238), test_image_tag_policy.sh and
the workflowgate tests pass.
BackendType SING_BOX = 2 is fork-only: upstream main (v0.5.7, 739eab9)
has XRAY and WIREGUARD only. It goes, and "reserved 2;" and
"reserved \"SING_BOX\";" take its place next to the MTProto reservation,
so nothing reuses the number or the name. An older panel that still sends
2 is never misread as another backend: the node decodes it as the bare
enum number 2, and the controller refuses it as an invalid backend type.

Upstream dev (d536e6b) gives 2 to MTPROTO in PasarGuard#120, which no release
carries yet. With 2 reserved, taking that number later needs an explicit
decision to drop the reservation; the PR PasarGuard#61 and PasarGuard#120 waivers record the
collision.

The comment on message Hysteria2 that named sing-box is deleted. The
message and Proxy.hysteria2 = 7 stay on the wire unchanged.

common/service.pb.go is regenerated with protoc 36.2 (v7.36.2) and
protoc-gen-go v1.36.11, the versions in its header;
service_grpc.pb.go does not change. Regenerating the previous proto with
the same tools reproduced the committed files byte for byte.

common/reserved_wire_numbers_test.go expects the reserved names
[MTPROTO SING_BOX] and loses its SING_BOX = 2 check. A new test pins
that 2 has no value, that 2 and the name SING_BOX are reserved, and that
an older panel's Start of type 2 decodes as the bare number. RED on
74c660d: "BackendType 2 has a value again: SING_BOX".
…aivers

With the singbox-builder stage gone nothing pins sing-box or sing-quic,
so the drift check watches node and xray only.

- scripts/upstream_drift.sh: the sing-box and sing-quic sections leave
  the components (the default is now "node xray"), together with
  gomod_version and module_rev, which only the sing-quic pin read.
- .github/upstream-waivers.txt loses 43 rows: the 40 whose id is a
  SagerNet/sing-box commit, the 2 whose id is a SagerNet/sing-quic commit
  (each checked with git cat-file against a commit-only fetch of both
  repositories on 2026-12-02), and GHSA-r5hm-mp3j-285g, the sing-box SOCKS
  advisory. 114 rows remain.
- The 17 MTProto rows for upstream PR PasarGuard#61 and PasarGuard#120 no longer say the
  fork has SING_BOX = 2; they say BackendType 2 stays reserved by number
  and by name. Their category, branch: scope, "not merged", "dev-only"
  and until: tokens are untouched.
- The synthetic suites drop the sing-box fixture repository and the
  singbox-builder stage, and the two cases that only exercised the
  sing-box component (an xray patch naming a sing-box commit, a sing-box
  commit off its oldstable line). The CRLF case and the
  pin-in-another-stage case now hide or declare in the builder stage, and
  the bypass case that needed a trailer naming no xray commit passes a
  literal 40-hex id instead of a sing-box commit.
- docs/upstream-parity.md: the current-state sections (intro, other
  branches, third-party upstreams, pins, how a port is recognised, not
  covered, the drift check, running it locally) describe node and xray
  only, and a "Retired in feature 004" paragraph records the two
  components. The dated state sections are history and stay as written.

Local runs (macOS): upstream_drift_bypass_test.sh 21 of 21 passed; in
upstream_drift_test.sh the changed and neighbouring cases (clean,
xray-patch-applied, xray-patch-not-applied, xray-patch-other-stage,
xray-patch-shell-comment, xray-build-crlf-hides-the-builder-stage,
xray-dev-only-needs-no-waiver, xray-pin-declared-in-another-stage) pass.
The whole suite runs in CI (make test-drift).
NodeVersion goes 0.6.27 to 0.6.28, one patch step from the last value the
fork used (v0.8.27, 73fa6bd; no branch or tag on GitHub carries 0.6.28),
because BaseInfoResponse.supported_backends loses "sing_box" and a panel
reads that list to decide what a node can run. It is the same step the
MTProto removal took (641d19c). TestNodeVersionIsPinned and the three
upstream-waiver rows that cite the constant follow.
…ays out of the fork

The 17 waiver rows for upstream PR PasarGuard#61 and PasarGuard#120 explained their refusal only
by the wire collision on BackendType 2 and asked to revisit the backend if
upstream merged it. The owner ordered the Telegram proxy removed from the fork
on 2026-11-10 and confirmed on 2026-12-02 that it stays out, so the rows now
say so and the backend itself is never ported.

PasarGuard#120 stays pending under the release-only rule for the one generic piece it
carries, the retry-later sync error (backend/errors.go RetryLaterError,
HTTP 503 in controller/rest/sync_errors.go, gRPC Unavailable in
controller/rpc/sync_errors.go), which is ported or refused on its own once a
release contains it; its until: date moves from 2026-11-30 to 2026-12-31.
bfc492f cut the sentences about the removed sing-box backend out of the
openvpn comments, but it reflowed what was left and so wrote comment text of
its own ("This", "xray's"). The fork writes no comments, so the 19 comment
blocks that held a reworded line are removed whole instead: 122 comment lines
and one blank line left behind by the cut go, no line is added, and every other
removed line is a comment, so the code is unchanged (go vet and go build pass
for linux).
…rd#124 hold

docs/upstream-parity.md still said PR PasarGuard#61 was rejected only for its numbers
and asked to revisit it if upstream merged it. It now gives the owner's
decision that the Telegram proxy stays out of the fork, as the waiver rows
already do since 1f448d7, and points at PasarGuard#120's generic retry-later sync error,
which is ported or refused on its own once a release contains it.

Upstream PasarGuard#124 (9ccd263) is still in no release tag: the compare API shows it
ahead of v0.5.7, the newest tag, on 2026-12-02. Its pending hold had expired on
2026-11-30 and now runs until 2026-12-31 under the release-only rule.
…node is silent

The lease armed by a panel Start ended on time alone, so a 003 panel that
became unreachable right after a Start lost every stored cap when the lease
ran out (final review N7-1: 8303 Mbit/s against a cap of 8 on the real core).

The lease is now checked every SPEED_CAP_LEASE_SECONDS and ends only when the
controlling panel was heard within the last half lease at this check and at
the previous one, the Start counting as heard. A silent panel keeps the caps,
a panel back from a silence gets a whole lease for its snapshot, and a panel
that keeps calling without a snapshot still loses them one lease after its
Start. A check of an older lease never replaces the timer of a newer Start and
never re-arms a stopped one, and no store call runs under the controller lock.

ExpireLease ends the lease only after the empty set was saved: a failed save
clears nothing, keeps the lease armed, is retried at the next check and is
logged as such (N7-3). The store copy in the xray speed cap patch is
regenerated from d2758a02 with the patches applied in alphabetical order;
the index line of app/dispatcher/default.go now names the pre-image of that
chain, the hunks are unchanged.

Tests: a silent panel keeps the caps on the fake core and on the real patched
core, a snapshot read before a newer diff lands after a silence, a panel back
from a silence keeps the caps for a whole lease, a failed save is retried, a
core restart through Xray.Restart leaves the lease as it found it (N7-5), and
the non-Xray primary test uses wireguard instead of the sing-box type that
feature 004 removes (M1).
Brings the sing-box server core removal (004, a145ce3) into the per-user
speed cap branch (003, 3c1b5b4) so both ship in one node image.

The merge had no conflicts. common/service.pb.go, which both branches
changed, and common/service_grpc.pb.go are byte for byte what protoc 36.2
with protoc-gen-go v1.36.11 and protoc-gen-go-grpc 1.6.2 write for the
merged common/service.proto: BackendType keeps 2 and "SING_BOX" reserved,
and the service keeps SetUserSpeeds. The patches directory is the one 003
had. On the merged tree, with go1.27.4, GOOS=linux go build ./... and
go vet ./... for darwin and linux pass, and go test -run '^$' ./...
builds and starts every test binary. NodeVersion is 004's 0.6.28 here and
moves in the next commit.
NodeVersion goes 0.6.28 to 0.6.29, one patch step from the highest 0.6
value on any branch or tag of the fork on GitHub (0.6.28, on
feat/004-remove-singbox and ci-004-remove-singbox), for the node that
ships the per-user speed cap and the sing-box removal together.
TestNodeVersionIsPinned failed against the 0.6.28 constant and passes
after the bump. The three upstream-waiver rows that cite the constant
follow.
…peeds does

Final review V1: the first rev-8 lease counted the panel Start as heard, so a
single request in the second half of the first lease cleared the stored caps
of a panel that was otherwise silent (fake core: floor 105 and no entries;
real core: 3788 Mbit/s against a cap of 8), and a SetUserSpeeds that the
backend gate refused before the store counted as heard without ending the
lease.

The first lease check no longer counts the Start, so the lease ends only after
the panel was heard before two checks a lease apart, which one request can
never satisfy; a panel that never sends SetUserSpeeds now loses old caps two
leases after its Start instead of one. Any SetUserSpeeds from the panel that
holds the node ends the lease in the request tracking of both transports,
before the backend gate, through the new Store.EndLease; the store copy in the
xray speed cap patch is regenerated. The lease-end push is registered with the
user-sync registry, so a Start waiting behind a hung push cancels it after the
drain grace (L1), and the lease log says what was observed (L2).
Brings the speed cap lease fix V1 (f820feb, on 3c1b5b4) into the
branch that already carries 004, so the node image has both.

The merge had no conflicts and its 11 files are exactly f820feb's;
common/ is unchanged from 7bb0dfe. With go1.27.4, GOOS=linux go build
./..., go vet ./... for darwin and linux, and go test -run '^$' ./...
pass. The Dockerfile's Xray d2758a02 patch chain and make build_xray's
alphabetical chain both apply, give the same tree, and differ from the
pre-V1 tree only in testing/speedcapnode/store.go. Under -race, with an
Xray built by make build_xray from this tree, the controller speed cap
and lease tests (19), the controller/rpc and controller/rest lease and
gate tests, pkg/speedcap, and the BackendType 2 refusal tests pass.
NodeVersion stays 0.6.29.
@Free-Guy-IR
Free-Guy-IR merged commit 81cf5b0 into main Dec 2, 2026
15 checks passed
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.

1 participant