mirror of
https://github.com/daeuniverse/honk.git
synced 2026-12-06 16:01:20 +00:00
feat(score): preserve active incumbents and validate carrier pressure (#279)
* feat(score): verify fresh evidence and bound TCP recovery * fix(core): distinguish DNS timeouts from dial admission waits * fix(score): date business usability from response progress * fix(score): preserve recovered incumbents with comparable evidence * fix(score): retain qualified active business paths * feat(score): request bounded validation on carrier pressure * perf(outbound): avoid reboxing observed TLS carriers * feat(score): expose accepted carrier pressure causes * feat(ci): publish debug tags to one rolling release * fix(ci): reject incomplete Debug artifacts before publication
This commit is contained in:
1 parent
b48f7d9cbc
commit
318edf5826
60 files changed
+3838
-427
No files matched your search
@@ -18,9 +18,18 @@ Its `public-vless-loopback` job uses the repository-pinned compiler and checksum
|
||||
|
||||
The independent weekly `fuzz` job uses the nightly channel from `crates/honk-ebpf/rust-toolchain.toml` and `CARGO_FUZZ_VERSION` from `pins.env`. It runs `document`, `share_link`, and `lexer` sequentially with two workers, 480 seconds per target, a 10-second input timeout and a 2048 MiB RSS limit. The job has a 40-minute timeout and uploads `fuzz-inputs` on success or failure. It keeps `contents: read` and opens no issues.
|
||||
|
||||
`.github/workflows/release.yml` on `v*`: `cargo test --workspace --no-fail-fast` (`cmake` + `libclang-dev` required for boring-sys), then `honk-core --features ebpf` for `x86_64`/`aarch64` × `gnu`/`musl`. Native gnu uses `cargo build`; the other three use **zig cc/c++ `ci/zigcc` / `ci/zigcxx` wrappers**. Cross CMake injects ASM `--target` flags rejected by GCC and, in Rust-triple spelling, zig; wrappers strip/re-anchor on `$ZIGCC_TARGET`. Musl sets `link-self-contained=no` for zig CRT. Each target ships default mimalloc and `-stock` without `mimalloc` (lower RSS high-water on small gateways). The host compiler comes from the root `rust-toolchain.toml`; build eBPF once on the host with `crates/honk-ebpf/rust-toolchain.toml` and pinned prebuilt `bpf-linker`; **verify `.BTF`** before packaging. Publish GitHub Release tarballs; `alpha`/`beta`/`rc` tags are prereleases.
|
||||
`.github/workflows/release.yml` on `v*` and `debug.*`: `cargo test --workspace --no-fail-fast` (`cmake` + `libclang-dev` required for boring-sys), then `honk-core --features ebpf` for `x86_64`/`aarch64` × `gnu`/`musl`. Native gnu uses `cargo build`; the other three use **zig cc/c++ `ci/zigcc` / `ci/zigcxx` wrappers**. Cross CMake injects ASM `--target` flags rejected by GCC and, in Rust-triple spelling, zig; wrappers strip/re-anchor on `$ZIGCC_TARGET`. Musl sets `link-self-contained=no` for zig CRT. Each target ships default mimalloc and `-stock` without `mimalloc` (lower RSS high-water on small gateways). The host compiler comes from the root `rust-toolchain.toml`; build eBPF once on the host with `crates/honk-ebpf/rust-toolchain.toml` and pinned prebuilt `bpf-linker`; **verify `.BTF`** before packaging. Publish GitHub Release tarballs; formal `alpha`/`beta`/`rc` tags and all Debug builds are prereleases.
|
||||
|
||||
Before upload, every x86_64 matrix entry extracts its packaged tarball into a clean temporary directory and runs the nested `honk-core --version`. This covers the loader and early startup for gnu/musl and both allocators, not configuration or datapath behavior. aarch64 artifacts are not executed. Manual release runs keep the same build checks; publication remains restricted to `v*` tag refs.
|
||||
Before upload, every x86_64 matrix entry extracts its packaged tarball into a clean temporary directory and runs the nested `honk-core --version`. This covers the loader and early startup for gnu/musl and both allocators, not configuration or datapath behavior. aarch64 artifacts are not executed. Manual release runs keep the same build checks; publication remains restricted to `v*` and `debug.*` tag refs, never branches or the rolling `debug` tag itself.
|
||||
|
||||
### Rolling Debug release
|
||||
|
||||
- Push a source tag such as `debug.2026.9.19.score.1`; the trigger accepts `debug.*` without prescribing a date or component format. It runs the same tests and eight release-profile builds as formal tags.
|
||||
- Before moving `debug` or updating the release, `.github/ci/check-debug-artifacts.sh` requires all eight expected tarballs to be regular, nonempty files. Missing or empty inputs fail without changing the current publication. The release test job runs `.github/ci/test-debug-artifacts.sh` against the same check.
|
||||
- Successful publication force-updates only `refs/tags/debug` to the source commit and creates or updates the release titled `Debug` at `/releases/tag/debug`. Original source tags remain intact. The release is always a prerelease with `make_latest: false`; notes identify the source tag, commit and workflow run.
|
||||
- Fixed `honk-core-debug-<target>[-stock].tar.gz` names let the existing release action replace attachments rather than accumulate per-tag assets. The release itself is not deleted or recreated. Tag, notes and asset updates are not transactional: a failure after publication starts may leave them inconsistent. Retrying only the release job requires all build artifacts to remain available; if any have expired (one-day retention) or been deleted, use **Re-run all jobs** to rebuild the complete set.
|
||||
- All Debug workflows share a concurrency group with `cancel-in-progress: false`, so a new push does not interrupt a running publication. GitHub may replace pending runs and does not guarantee queue order. After a complete successful publication, Debug represents that publisher, not necessarily the newest source tag; a subsequent failed publication can leave the partial state described above.
|
||||
- The rolling tag must permit force updates by the workflow token, and the Debug release must remain mutable. `contents: write` stays confined to the publication job. Updating `debug` cannot retrigger `debug.*`; formal `v*` publication remains independent.
|
||||
|
||||
### Release process (standing convention)
|
||||
|
||||
|
||||
Executable
+9
@@ -0,0 +1,9 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
for artifact in dist/honk-core-debug-{x86_64,aarch64}-unknown-linux-{gnu,musl}{,-stock}.tar.gz; do
|
||||
if [[ ! -f "$artifact" || ! -s "$artifact" ]]; then
|
||||
printf '::error::Missing or empty Debug artifact: %s. Re-run all jobs to rebuild the complete set.\n' "$artifact" >&2
|
||||
exit 1
|
||||
fi
|
||||
done
|
||||
Executable
+41
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
ci_dir=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)
|
||||
work=$(mktemp -d)
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
cd "$work"
|
||||
mkdir dist
|
||||
|
||||
for target in x86_64-unknown-linux-gnu x86_64-unknown-linux-musl aarch64-unknown-linux-gnu aarch64-unknown-linux-musl; do
|
||||
for suffix in '' -stock; do
|
||||
printf 'artifact\n' > "dist/honk-core-debug-$target$suffix.tar.gz"
|
||||
done
|
||||
done
|
||||
bash "$ci_dir/check-debug-artifacts.sh"
|
||||
|
||||
expect_rejection() {
|
||||
local status=0
|
||||
bash "$ci_dir/check-debug-artifacts.sh" > failure.log 2>&1 || status=$?
|
||||
if [[ "$status" != 1 ]]; then
|
||||
cat failure.log >&2
|
||||
printf 'Expected incomplete Debug artifacts to be rejected, got exit %s\n' "$status" >&2
|
||||
exit 1
|
||||
fi
|
||||
}
|
||||
|
||||
artifact=dist/honk-core-debug-aarch64-unknown-linux-musl-stock.tar.gz
|
||||
mv "$artifact" saved.tar.gz
|
||||
expect_rejection
|
||||
mv saved.tar.gz "$artifact"
|
||||
bash "$ci_dir/check-debug-artifacts.sh"
|
||||
|
||||
: > "$artifact"
|
||||
expect_rejection
|
||||
rm "$artifact"
|
||||
mkdir "$artifact"
|
||||
expect_rejection
|
||||
rm -r dist
|
||||
expect_rejection
|
||||
|
||||
printf 'Debug artifact preflight regression passed\n'
|
||||
@@ -2,15 +2,15 @@ name: Release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags: ["v*"]
|
||||
tags: ["v*", "debug.*"]
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.event_name == 'pull_request' && format('ci-{0}-pr-{1}', github.workflow, github.event.pull_request.number) || format('ci-{0}-{1}', github.workflow, github.run_id) }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
group: ${{ startsWith(github.ref, 'refs/tags/debug.') && 'release-debug' || format('ci-{0}-{1}', github.workflow, github.run_id) }}
|
||||
cancel-in-progress: false
|
||||
|
||||
env:
|
||||
CARGO_TERM_COLOR: always
|
||||
@@ -22,6 +22,8 @@ jobs:
|
||||
timeout-minutes: 25
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
- name: Test Debug artifact preflight
|
||||
run: bash .github/ci/test-debug-artifacts.sh
|
||||
- name: Read Rust toolchain
|
||||
id: toolchain
|
||||
run: echo "stable=$(grep -oP '^channel\s*=\s*\"\K[^\"]+' rust-toolchain.toml)" >> "$GITHUB_OUTPUT"
|
||||
@@ -74,6 +76,8 @@ jobs:
|
||||
name: build ${{ matrix.target }}${{ matrix.suffix }}
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 40
|
||||
env:
|
||||
ARTIFACT_NAME: honk-core-${{ startsWith(github.ref, 'refs/tags/debug.') && 'debug' || github.ref_name }}-${{ matrix.target }}${{ matrix.suffix }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
@@ -213,7 +217,7 @@ jobs:
|
||||
- name: Package artifact
|
||||
run: |
|
||||
set -euo pipefail
|
||||
name="honk-core-${{ github.ref_name }}-${{ matrix.target }}${{ matrix.suffix }}"
|
||||
name="$ARTIFACT_NAME"
|
||||
mkdir -p "dist/$name"
|
||||
cp "target/${{ matrix.target }}/release/honk-core" "dist/$name/"
|
||||
cp LICENSE README.md "dist/$name/"
|
||||
@@ -221,8 +225,6 @@ jobs:
|
||||
|
||||
- name: Start the packaged x86_64 artifact
|
||||
if: startsWith(matrix.target, 'x86_64-')
|
||||
env:
|
||||
ARTIFACT_NAME: honk-core-${{ github.ref_name }}-${{ matrix.target }}${{ matrix.suffix }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
smoke_dir=$(mktemp -d "$RUNNER_TEMP/release-smoke.XXXXXX")
|
||||
@@ -234,7 +236,7 @@ jobs:
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
|
||||
with:
|
||||
name: honk-core-${{ matrix.target }}${{ matrix.suffix }}
|
||||
path: honk-core-${{ github.ref_name }}-${{ matrix.target }}${{ matrix.suffix }}.tar.gz
|
||||
path: ${{ env.ARTIFACT_NAME }}.tar.gz
|
||||
retention-days: 1
|
||||
|
||||
release:
|
||||
@@ -244,7 +246,7 @@ jobs:
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: write
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
if: startsWith(github.ref, 'refs/tags/v') || startsWith(github.ref, 'refs/tags/debug.')
|
||||
steps:
|
||||
- name: Download all artifacts
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
|
||||
@@ -253,8 +255,44 @@ jobs:
|
||||
merge-multiple: true
|
||||
|
||||
- name: Create release
|
||||
if: startsWith(github.ref, 'refs/tags/v')
|
||||
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3
|
||||
with:
|
||||
files: dist/*.tar.gz
|
||||
prerelease: ${{ contains(github.ref_name, 'alpha') || contains(github.ref_name, 'beta') || contains(github.ref_name, 'rc') }}
|
||||
generate_release_notes: true
|
||||
|
||||
- name: Checkout Debug source
|
||||
if: startsWith(github.ref, 'refs/tags/debug.')
|
||||
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with:
|
||||
ref: ${{ github.sha }}
|
||||
path: debug-source
|
||||
|
||||
- name: Check complete Debug artifacts
|
||||
if: startsWith(github.ref, 'refs/tags/debug.')
|
||||
run: bash debug-source/.github/ci/check-debug-artifacts.sh
|
||||
|
||||
- name: Move rolling Debug tag
|
||||
if: startsWith(github.ref, 'refs/tags/debug.')
|
||||
working-directory: debug-source
|
||||
run: git push --force origin "$GITHUB_SHA:refs/tags/debug"
|
||||
|
||||
- name: Update Debug release
|
||||
if: startsWith(github.ref, 'refs/tags/debug.')
|
||||
uses: softprops/action-gh-release@efb35369e0ad2afab669f228072c1b0d510eae64 # v3
|
||||
with:
|
||||
tag_name: debug
|
||||
name: Debug
|
||||
target_commitish: ${{ github.sha }}
|
||||
prerelease: true
|
||||
make_latest: "false"
|
||||
files: dist/*.tar.gz
|
||||
overwrite_files: true
|
||||
fail_on_unmatched_files: true
|
||||
body: |
|
||||
Rolling debug build; replaced by subsequent successful debug-tag runs.
|
||||
|
||||
Source tag: `${{ github.ref_name }}`
|
||||
Commit: `${{ github.sha }}`
|
||||
Build: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}
|
||||
@@ -85,6 +85,11 @@ Score keeps business reliability separate from event-timed performance and confi
|
||||
|
||||
Score verification is a scoped empirical claim, not a statistical error guarantee or automatic optimality certificate. The same evaluator identifies availability/response gaps, schedules bounded real-flow validation and publishes readonly validity; missing transfer waits for actual offered load. Keep practical equivalence, provisional forwarding, observed usability and supported comparison separate. Claims must expire with their weakest supporting evidence; API reads cannot spend validation budgets or mutate counters.
|
||||
|
||||
Score ordinary incumbent protection is separate from verification. Keep first-choice utility and existing trial budgets; an ineligible or unresolved-failure incumbent may escape without waiting. Recovery uses genuine targeted Traffic RX after setup/TX or a successful bidirectional terminal's actual RX, strictly newer than each applicable cell failure. Live publication is event-driven and capped at once per second per reporter; no timer guarantees delivery of throttled progress. Existing outcome counts, streaks/backoff and terminal verification remain independent. Fresh business RX can retain already earned four-completion qualification for 60 seconds from RX time; below-threshold expired/invalidated leases cannot be revived by RX alone. Failure/reload invalidation and started-cell incarnation fences remain authoritative; neutral cancellation does not retract factual RX. Hold maturity and reliability blending still use actual decayed counts without overlapping sums. Healthy promotion compares qualified common metric pairs against a fixed incumbent; expiry alone is not a performance advantage. `ordinarySwitch` excludes first choice/trials/Peek and is distinct from `switchFlap`. Do not add per-packet logs or exported target identities.
|
||||
|
||||
Score carrier pressure is advisory node-to-proxy evidence, never business outcome, target performance or ordinary UDP loss. Runtime-owner weak binding and active-authority/publication-time fences own admission. Physical TCP uses length-checked borrowed `TCP_INFO` with event-driven one-second gating; QUIC reuses its existing monitor after confirmation/publication and resets peer/counter baselines. Shared carriers publish sustained episodes, not one event per logical flow. Health-filter family is not socket identity; hints reopen node-scoped questions only for carrier-backed networks, excluding native Shadowsocks UDP and unobserved raw SOCKS/direct paths. Preserve validation budgets, backoff, utility, qualification, pool liveness, Vision Direct and terminal/health semantics. `carrierPressure` and `carrierValidation` are readonly diagnostic counters, not loss rates.
|
||||
`carrierRttPressure` and `carrierLossPressure` count the reason at fresh-hint admission; a combined episode increments both but only one `carrierPressure`. Duplicate/stale hints add no cause counts. These are overlapping diagnostics, not transport identities, packet loss rates or additional business failures.
|
||||
|
||||
## Build and test commands
|
||||
|
||||
### Rust workspace
|
||||
|
||||
@@ -42,6 +42,14 @@ Vision currently implements downstream unpadding and Direct handling only. Uplin
|
||||
|
||||
**Upgrade warning:** `vless_mode` is removed and every VLESS node ID is re-derived. Migrate static links and cached/provider content before upgrading, especially offline. Name-based Selector choices and recent persisted delay samples can survive; do not delete them. See the [migration guide](doc/en/reference/nodes.md#migration-from-vless_mode).
|
||||
|
||||
## Debug builds
|
||||
|
||||
Maintainers can push a `debug.*` tag, for example `debug.2026.9.19.score.1`, to run the existing release tests and build matrix. Successful runs update the same [Debug prerelease](https://github.com/daeuniverse/honk/releases/tag/debug), not a new release per source tag or the Latest release. These are release-profile binaries, not Cargo debug-profile builds.
|
||||
|
||||
The rolling `debug` tag and `honk-core-debug-<target>[-stock].tar.gz` assets are replaced. The original source tags remain, and the release notes record the source tag, commit and workflow run. Debug runs are serialized; pending intermediate runs may be superseded.
|
||||
|
||||
Before changing the rolling tag or release, publication checks that all eight expected archives are present and nonempty. If workflow artifacts have expired or been deleted, use **Re-run all jobs**, not only the release job. Publication itself is not transactional: failures after it starts can leave the tag, release notes and assets inconsistent until recovery.
|
||||
|
||||
## Before Using This Repository
|
||||
|
||||
### Important: Review Status
|
||||
|
||||
@@ -42,6 +42,14 @@ Vision 始终禁止 TCP 多路复用,但允许仅 UDP 的 Xray mux。默认允
|
||||
|
||||
**升级注意:**`vless_mode` 已删除,所有 VLESS 节点 ID 都会重新派生。升级前请迁移静态链接与缓存/provider 内容,尤其是离线升级。按名称保存的 Selector 选择及近期持久化延迟样本可继续使用,不要删除它们。见[迁移说明](doc/zh/reference/nodes.md#从-vless_mode-迁移)。
|
||||
|
||||
## Debug 构建
|
||||
|
||||
维护者推送 `debug.*` tag(例如 `debug.2026.9.19.score.1`)即可运行现有 release 测试与构建矩阵。成功后更新同一个 [Debug 预发布](https://github.com/daeuniverse/honk/releases/tag/debug),不会为每个源 tag 新建 release,也不会取代 Latest。这些仍是 release profile 二进制,并非 Cargo debug profile 构建。
|
||||
|
||||
滚动 `debug` tag 与 `honk-core-debug-<target>[-stock].tar.gz` 附件会被替换。原始源 tag 保留,release 说明记录源 tag、commit 和 workflow run。Debug 运行串行执行;尚在等待的中间运行可能被后续运行取代。
|
||||
|
||||
修改滚动 tag 或 release 前,发布步骤会检查八个预期归档是否齐全且非空。若 workflow artifact 已过期或被删除,应选择 **Re-run all jobs**,而不是只重跑 release job。发布过程本身不是原子的:开始更新后的失败可能使 tag、release 说明和附件暂时不一致,需恢复后才能重新一致。
|
||||
|
||||
## 使用本仓库前
|
||||
|
||||
### 重要:Review 状态
|
||||
|
||||
@@ -877,11 +877,18 @@ async fn get_outbound_stats(State(s): State<Arc<ClashState>>) -> Json<serde_json
|
||||
"reliabilityWinner": counters.reliability_winner,
|
||||
"performanceWinner": counters.performance_winner,
|
||||
"incumbentHeld": counters.incumbent_held,
|
||||
"insufficientEvidenceHeld": counters.insufficient_evidence_held,
|
||||
"incumbentIneligible": counters.incumbent_ineligible,
|
||||
"freshFailureBypass": counters.fresh_failure_bypass,
|
||||
"deadFiltered": counters.dead_filtered,
|
||||
"ordinarySwitch": counters.ordinary_switch,
|
||||
"switchFlap": counters.switch_flap,
|
||||
"failStreakExcluded": counters.fail_streak_excluded,
|
||||
"exploreBackedOff": counters.explore_backed_off,
|
||||
"carrierPressure": counters.carrier_pressure,
|
||||
"carrierRttPressure": counters.carrier_rtt_pressure,
|
||||
"carrierLossPressure": counters.carrier_loss_pressure,
|
||||
"carrierValidation": counters.carrier_validation,
|
||||
})
|
||||
};
|
||||
serde_json::json!({
|
||||
|
||||
@@ -127,6 +127,9 @@ impl ControlPlane {
|
||||
None,
|
||||
)
|
||||
.map_err(|e| anyhow::anyhow!("invalid node set: {}", e))?;
|
||||
group_manager
|
||||
.read()
|
||||
.bind_transport_quality(&runtime_registry);
|
||||
runtime_registry.activate_background_dial_admission();
|
||||
let runtime_registry = runtime_registry.into_shared();
|
||||
info!(
|
||||
|
||||
@@ -460,11 +460,15 @@ impl ControlPlaneHandle {
|
||||
{
|
||||
scope.start();
|
||||
tracing::debug!("Pooled TCP to {} acquired for {}", addr, target);
|
||||
return entry
|
||||
.tcp
|
||||
.dial_with_tcp(node, target, target_domain, tcp, connect_timeout)
|
||||
.await
|
||||
.map(|stream| (stream, true));
|
||||
let dial =
|
||||
entry
|
||||
.tcp
|
||||
.dial_with_tcp(node, target, target_domain, tcp, connect_timeout);
|
||||
let stream = match generation.get(&node.id) {
|
||||
Some(runtime) => runtime.transport_quality().scope(dial).await,
|
||||
None => dial.await,
|
||||
}?;
|
||||
return Ok((stream, true));
|
||||
}
|
||||
|
||||
// Pool miss (or pools disabled) — fresh connect through the
|
||||
|
||||
@@ -340,6 +340,8 @@ impl ControlPlane {
|
||||
Some(self.alive_set.clone()),
|
||||
self.group_manager.read().score_state(),
|
||||
);
|
||||
let runtimes = self.runtime_registry.read().clone();
|
||||
new_gm.bind_transport_quality(&runtimes);
|
||||
// Migrate runtime choices before wiring callbacks: migration must
|
||||
// not fire persistence or connection interruption.
|
||||
new_gm.migrate_selector_choices_from(&self.group_manager.read());
|
||||
|
||||
@@ -332,6 +332,7 @@ impl ControlPlane {
|
||||
return Ok(false);
|
||||
}
|
||||
};
|
||||
new_group_manager.bind_transport_quality(&new_runtime_registry);
|
||||
let reuse_dns_router = dns_routing_state_reusable(¤t_config, &new_config)
|
||||
&& current_dns_router.geo_fingerprint() == dns_geo_fingerprint;
|
||||
let dns_router = if reuse_dns_router {
|
||||
|
||||
@@ -878,6 +878,8 @@ impl ControlPlane {
|
||||
}
|
||||
}
|
||||
_ = heartbeat.tick() => {
|
||||
let manager = self.group_manager.read().clone();
|
||||
manager.observe_transport_quality();
|
||||
trace!(
|
||||
"control plane heartbeat (iteration {}, active_connections={})",
|
||||
loop_count,
|
||||
|
||||
@@ -187,3 +187,165 @@ async fn accepted_udp_progress_changes_selection_before_endpoint_finishes() {
|
||||
control.finish(ScoreOutcome::Cancelled);
|
||||
assert!(pool.shutdown().await);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delivered_udp_reply_restores_incumbent_protection_before_endpoint_finishes() {
|
||||
let server = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let target = server.local_addr().unwrap();
|
||||
let client = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let client_addr = client.local_addr().unwrap();
|
||||
let outbound = Arc::new(UdpSocket::bind("127.0.0.1:0").await.unwrap());
|
||||
let outbound_addr = outbound.local_addr().unwrap();
|
||||
let nodes = [
|
||||
Node {
|
||||
name: "live".into(),
|
||||
id: TEST_NODE_ID,
|
||||
..Default::default()
|
||||
},
|
||||
Node {
|
||||
name: "challenger".into(),
|
||||
id: OTHER_NODE_ID,
|
||||
..Default::default()
|
||||
},
|
||||
];
|
||||
let manager = GroupManager::new(
|
||||
&[Group {
|
||||
name: "score".into(),
|
||||
policy: GroupPolicy::Score,
|
||||
nodes: nodes.iter().map(|node| node.id).collect(),
|
||||
..Default::default()
|
||||
}],
|
||||
&nodes,
|
||||
);
|
||||
let context = ScoreSelectionContext {
|
||||
network: SelectionNetwork::Udp,
|
||||
probe_domain: honk_outbound::alive::ProbeDomain::DataUdp,
|
||||
target_family: Some(honk_outbound::alive::IpVersion::V4),
|
||||
health_family: honk_outbound::alive::IpVersion::V4,
|
||||
target: Some(target.into()),
|
||||
};
|
||||
for (index, node) in nodes.iter().enumerate() {
|
||||
let feedback = manager.feedback_for_node(node.id, context.clone()).unwrap();
|
||||
// One failure stays below the mature switching margin. Response-free
|
||||
// histories and fixed probes isolate recovery from scheduler latency.
|
||||
for _ in 0..512 {
|
||||
let reporter = feedback.start();
|
||||
reporter.setup_succeeded();
|
||||
reporter.tx(1);
|
||||
reporter.rx(1);
|
||||
reporter.finish(ScoreOutcome::Success);
|
||||
}
|
||||
let probe = feedback.with_source(honk_outbound::group::ScoreSource::HealthProbe);
|
||||
for _ in 0..8 {
|
||||
let reporter = probe.start();
|
||||
reporter.probe_latency(Duration::from_millis(100 + index as u64));
|
||||
reporter.finish(ScoreOutcome::Success);
|
||||
}
|
||||
}
|
||||
let aggregate = ScoreSelectionContext::aggregate(
|
||||
SelectionNetwork::Udp,
|
||||
honk_outbound::alive::ProbeDomain::DataUdp,
|
||||
honk_outbound::alive::IpVersion::V4,
|
||||
);
|
||||
assert_eq!(
|
||||
manager
|
||||
.selection_plan_for_target("score", &aggregate)
|
||||
.entries[0]
|
||||
.node
|
||||
.id,
|
||||
TEST_NODE_ID,
|
||||
);
|
||||
let feedback = manager.feedback_for_node(TEST_NODE_ID, context).unwrap();
|
||||
let reporter = feedback.start();
|
||||
reporter.setup_succeeded();
|
||||
let endpoint = Arc::new(UdpEndpoint::new_scored(
|
||||
transport(outbound, target),
|
||||
target,
|
||||
false,
|
||||
TEST_NODE_ID,
|
||||
honk_outbound::alive::IpVersion::V4,
|
||||
Some(reporter),
|
||||
));
|
||||
let pool = Arc::new(UdpEndpointPool::new());
|
||||
let stats = Arc::new(StatsManager::new());
|
||||
let permit = Arc::new(Semaphore::new(1)).try_acquire_owned().unwrap();
|
||||
let mut lease = match pool.reserve_or_enqueue(client_addr, target, b"q", permit, &stats) {
|
||||
EndpointReservation::Initializing(lease) => lease,
|
||||
_ => panic!("live flow must reserve a fresh endpoint"),
|
||||
};
|
||||
let mut driver = pool.spawn_driver(
|
||||
client_addr,
|
||||
target,
|
||||
lease.generation(),
|
||||
lease.decision_token(),
|
||||
Arc::clone(&endpoint),
|
||||
lease.take_queue_receiver().unwrap(),
|
||||
test_reply_socket().await,
|
||||
Arc::new(honk_outbound::alive::AliveDialerSet::new()),
|
||||
Arc::clone(&stats),
|
||||
"live".into(),
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(1), driver.wait_ready())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert!(lease.commit_ready(Arc::clone(&endpoint)));
|
||||
driver.start(lease.take_first().unwrap()).unwrap();
|
||||
drop(lease);
|
||||
tokio::time::timeout(Duration::from_secs(1), driver.wait_first_ack())
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let mut buf = [0; 8];
|
||||
let (len, peer) = tokio::time::timeout(Duration::from_secs(1), server.recv_from(&mut buf))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(peer, outbound_addr);
|
||||
assert_eq!(&buf[..len], b"q");
|
||||
|
||||
let failed = feedback.start();
|
||||
failed.setup_succeeded();
|
||||
failed.finish(ScoreOutcome::Timeout);
|
||||
// Peek uses the same aggregate history without committing the bypass.
|
||||
assert_eq!(
|
||||
manager.get_score_selection_for_network("score", SelectionNetwork::Udp),
|
||||
Some("challenger".into()),
|
||||
);
|
||||
let before = manager.score_reason_snapshot()[0].udp;
|
||||
assert_eq!(before.ordinary_switch, 0);
|
||||
|
||||
server.send_to(b"r", outbound_addr).await.unwrap();
|
||||
let (len, _) = tokio::time::timeout(Duration::from_secs(1), client.recv_from(&mut buf))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&buf[..len], b"r");
|
||||
assert_eq!(endpoint.upload.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(endpoint.download.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(pool.driver_count(), 1);
|
||||
assert!(!endpoint.dead.load(Ordering::Acquire));
|
||||
assert_eq!(
|
||||
manager
|
||||
.selection_plan_for_target("score", &aggregate)
|
||||
.entries[0]
|
||||
.node
|
||||
.id,
|
||||
TEST_NODE_ID,
|
||||
"accepted RX must restore protection before terminal settlement",
|
||||
);
|
||||
let recovered = manager.score_reason_snapshot()[0].udp;
|
||||
assert_eq!(recovered.incumbent_held, before.incumbent_held + 1);
|
||||
assert_eq!(recovered.fresh_failure_bypass, 0);
|
||||
assert_eq!(recovered.incumbent_ineligible, 0);
|
||||
assert_eq!(recovered.ordinary_switch, 0);
|
||||
|
||||
endpoint.finish_score(ScoreOutcome::Success);
|
||||
endpoint.finish_score(ScoreOutcome::Io(io::ErrorKind::ConnectionReset));
|
||||
assert_eq!(
|
||||
manager.get_score_selection_for_network("score", SelectionNetwork::Udp),
|
||||
Some("live".into()),
|
||||
"a duplicate terminal failure must not replace the settled success",
|
||||
);
|
||||
assert!(pool.shutdown().await);
|
||||
}
|
||||
@@ -1965,4 +1965,30 @@ mod tests {
|
||||
pool.check_invariants();
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observed_plain_trojan_ready_pool_rejects_closed_carrier() {
|
||||
tokio::time::timeout(Duration::from_secs(3), async {
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = listener.local_addr().unwrap();
|
||||
let mut node = ready_identity_trojan_node(address, "localhost", "observed");
|
||||
node.tls_mut().unwrap().enabled = false;
|
||||
node.id = node.derive_id();
|
||||
let target: SocketAddr = "192.0.2.1:80".parse().unwrap();
|
||||
let mut stream = honk_outbound::proxy::trojan::TrojanHandler::new()
|
||||
.dial(&node, target, None, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap();
|
||||
let (peer, _) = listener.accept().await.unwrap();
|
||||
drop(peer);
|
||||
let mut byte = [0u8; 1];
|
||||
assert!(!matches!(stream.stream.read(&mut byte).await, Ok(n) if n > 0));
|
||||
let pool = ConnectionPool::new();
|
||||
let key = ConnectionPool::ready_key(1, node.id, target, None);
|
||||
pool.deposit_ready(1, &key, stream).await;
|
||||
assert!(pool.acquire_ready(&key).await.is_none());
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -727,11 +727,18 @@ async fn score_stats_are_authenticated_deterministic_and_private() {
|
||||
"reliabilityWinner": 0,
|
||||
"performanceWinner": 0,
|
||||
"incumbentHeld": 0,
|
||||
"insufficientEvidenceHeld": 0,
|
||||
"incumbentIneligible": 0,
|
||||
"freshFailureBypass": 0,
|
||||
"deadFiltered": 0,
|
||||
"ordinarySwitch": 0,
|
||||
"switchFlap": 0,
|
||||
"failStreakExcluded": 0,
|
||||
"exploreBackedOff": 0,
|
||||
"carrierPressure": 0,
|
||||
"carrierRttPressure": 0,
|
||||
"carrierLossPressure": 0,
|
||||
"carrierValidation": 0,
|
||||
},
|
||||
"udp": {
|
||||
"coldExplore": 0,
|
||||
@@ -739,11 +746,18 @@ async fn score_stats_are_authenticated_deterministic_and_private() {
|
||||
"reliabilityWinner": 0,
|
||||
"performanceWinner": 0,
|
||||
"incumbentHeld": 0,
|
||||
"insufficientEvidenceHeld": 0,
|
||||
"incumbentIneligible": 0,
|
||||
"freshFailureBypass": 0,
|
||||
"deadFiltered": 0,
|
||||
"ordinarySwitch": 0,
|
||||
"switchFlap": 0,
|
||||
"failStreakExcluded": 0,
|
||||
"exploreBackedOff": 0,
|
||||
"carrierPressure": 0,
|
||||
"carrierRttPressure": 0,
|
||||
"carrierLossPressure": 0,
|
||||
"carrierValidation": 0,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -754,11 +768,18 @@ async fn score_stats_are_authenticated_deterministic_and_private() {
|
||||
"reliabilityWinner": 0,
|
||||
"performanceWinner": 0,
|
||||
"incumbentHeld": 0,
|
||||
"insufficientEvidenceHeld": 0,
|
||||
"incumbentIneligible": 0,
|
||||
"freshFailureBypass": 0,
|
||||
"deadFiltered": 0,
|
||||
"ordinarySwitch": 0,
|
||||
"switchFlap": 0,
|
||||
"failStreakExcluded": 0,
|
||||
"exploreBackedOff": 0,
|
||||
"carrierPressure": 0,
|
||||
"carrierRttPressure": 0,
|
||||
"carrierLossPressure": 0,
|
||||
"carrierValidation": 0,
|
||||
},
|
||||
"udp": {
|
||||
"coldExplore": 0,
|
||||
@@ -766,11 +787,18 @@ async fn score_stats_are_authenticated_deterministic_and_private() {
|
||||
"reliabilityWinner": 0,
|
||||
"performanceWinner": 0,
|
||||
"incumbentHeld": 0,
|
||||
"insufficientEvidenceHeld": 0,
|
||||
"incumbentIneligible": 0,
|
||||
"freshFailureBypass": 0,
|
||||
"deadFiltered": 0,
|
||||
"ordinarySwitch": 0,
|
||||
"switchFlap": 0,
|
||||
"failStreakExcluded": 0,
|
||||
"exploreBackedOff": 0,
|
||||
"carrierPressure": 0,
|
||||
"carrierRttPressure": 0,
|
||||
"carrierLossPressure": 0,
|
||||
"carrierValidation": 0,
|
||||
},
|
||||
},
|
||||
],
|
||||
|
||||
@@ -40,6 +40,151 @@ fn business_success(
|
||||
reporter.finish(ScoreOutcome::Success);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn score_stats_count_only_committed_switches_and_distinguish_ineligible_incumbents() {
|
||||
let nodes = [make_node("private-a"), make_node("private-b")];
|
||||
let app = spawn_app_with_config(
|
||||
Config {
|
||||
nodes: nodes.to_vec(),
|
||||
groups: vec![
|
||||
Group {
|
||||
name: "auto".into(),
|
||||
policy: GroupPolicy::Score,
|
||||
nodes: nodes.iter().map(|node| node.id).collect(),
|
||||
..Default::default()
|
||||
},
|
||||
Group {
|
||||
name: "empty".into(),
|
||||
policy: GroupPolicy::Score,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..Default::default()
|
||||
},
|
||||
"",
|
||||
"",
|
||||
)
|
||||
.await;
|
||||
let manager = app.state.group_manager.read().clone();
|
||||
let zero = serde_json::json!({
|
||||
"coldExplore": 0,
|
||||
"periodicExplore": 0,
|
||||
"reliabilityWinner": 0,
|
||||
"performanceWinner": 0,
|
||||
"incumbentHeld": 0,
|
||||
"insufficientEvidenceHeld": 0,
|
||||
"incumbentIneligible": 0,
|
||||
"freshFailureBypass": 0,
|
||||
"deadFiltered": 0,
|
||||
"ordinarySwitch": 0,
|
||||
"switchFlap": 0,
|
||||
"failStreakExcluded": 0,
|
||||
"exploreBackedOff": 0,
|
||||
"carrierPressure": 0,
|
||||
"carrierRttPressure": 0,
|
||||
"carrierLossPressure": 0,
|
||||
"carrierValidation": 0,
|
||||
});
|
||||
let initial = get_json(&app, "/stats").await;
|
||||
let groups = initial["score"]["groups"].as_array().unwrap();
|
||||
assert_eq!(groups.len(), 2);
|
||||
assert_eq!(groups[0]["name"], "auto");
|
||||
assert_eq!(groups[1]["name"], "empty");
|
||||
for group in groups {
|
||||
for network in ["tcp", "udp"] {
|
||||
assert_eq!(group[network], zero);
|
||||
}
|
||||
}
|
||||
|
||||
for (network, label) in [
|
||||
(SelectionNetwork::Tcp, "tcp"),
|
||||
(SelectionNetwork::Udp, "udp"),
|
||||
] {
|
||||
let context = ScoreSelectionContext {
|
||||
target: Some(ScoreTarget::domain("private-switch.example", 6543)),
|
||||
target_family: Some(IpVersion::V4),
|
||||
..context(network)
|
||||
};
|
||||
for node in &nodes {
|
||||
let trial = manager.selection_plan_for_target("auto", &context);
|
||||
assert_eq!(trial.entries[0].node.id, node.id);
|
||||
assert_eq!(
|
||||
get_json(&app, "/stats").await["score"]["groups"][0][label]["ordinarySwitch"],
|
||||
0
|
||||
);
|
||||
}
|
||||
for node in &nodes {
|
||||
for _ in 0..16 {
|
||||
business_success(&manager, node, &context, true);
|
||||
}
|
||||
}
|
||||
|
||||
let first = manager.selection_plan_for_target("auto", &context);
|
||||
let incumbent = first.entries[0].node.id;
|
||||
let first_stats = get_json(&app, "/stats").await;
|
||||
assert_eq!(
|
||||
first_stats["score"]["groups"][0][label]["ordinarySwitch"],
|
||||
0
|
||||
);
|
||||
let stay = manager.selection_plan_for_target("auto", &context);
|
||||
assert_eq!(stay.entries[0].node.id, incumbent);
|
||||
let before = get_json(&app, "/stats").await;
|
||||
let before_counts = &before["score"]["groups"][0][label];
|
||||
assert_eq!(before_counts["ordinarySwitch"], 0);
|
||||
assert_eq!(before_counts["incumbentIneligible"], 0);
|
||||
|
||||
for _ in 0..3 {
|
||||
manager
|
||||
.feedback_for_node(incumbent, context.clone())
|
||||
.unwrap()
|
||||
.start()
|
||||
.setup_failed(ScoreOutcome::Timeout);
|
||||
}
|
||||
let switched = manager.selection_plan_for_target("auto", &context);
|
||||
let challenger = nodes.iter().find(|node| node.id != incumbent).unwrap();
|
||||
assert_eq!(switched.entries[0].node.id, challenger.id);
|
||||
let after = get_json(&app, "/stats").await;
|
||||
let after_counts = &after["score"]["groups"][0][label];
|
||||
assert_eq!(after_counts["ordinarySwitch"], 1);
|
||||
assert_eq!(after_counts["incumbentIneligible"], 1);
|
||||
assert_eq!(after_counts["freshFailureBypass"], 0);
|
||||
for reason in [
|
||||
"coldExplore",
|
||||
"periodicExplore",
|
||||
"reliabilityWinner",
|
||||
"performanceWinner",
|
||||
"incumbentHeld",
|
||||
"insufficientEvidenceHeld",
|
||||
"freshFailureBypass",
|
||||
] {
|
||||
assert_eq!(
|
||||
after_counts[reason], before_counts[reason],
|
||||
"{label}: {reason}"
|
||||
);
|
||||
}
|
||||
for path in ["/proxies", "/proxies/auto", "/stats"] {
|
||||
get_json(&app, path).await;
|
||||
}
|
||||
assert_eq!(get_json(&app, "/stats").await["score"], after["score"]);
|
||||
}
|
||||
|
||||
let final_stats = get_json(&app, "/stats").await;
|
||||
for network in ["tcp", "udp"] {
|
||||
assert_eq!(
|
||||
final_stats["score"]["groups"][0][network]["ordinarySwitch"],
|
||||
1
|
||||
);
|
||||
assert_eq!(final_stats["score"]["groups"][1][network], zero);
|
||||
}
|
||||
let encoded = final_stats["score"].to_string();
|
||||
assert!(!encoded.contains("private-switch.example"));
|
||||
assert!(!encoded.contains("6543"));
|
||||
for node in &nodes {
|
||||
assert!(!encoded.contains(&node.name));
|
||||
assert!(!encoded.contains(&node.id.to_string()));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn score_verification_is_private_readonly_and_uses_canonical_candidates() {
|
||||
let (a, b, dead, unchosen) = (
|
||||
|
||||
@@ -258,6 +258,7 @@ pub struct GroupManager {
|
||||
interrupt_callback: RwLock<Option<InterruptCallback>>,
|
||||
score_state: Arc<ScorePolicyState>,
|
||||
score_authority: Arc<score::ScoreAuthority>,
|
||||
transport_quality: RwLock<Vec<score::TransportQualitySource>>,
|
||||
}
|
||||
|
||||
impl GroupManager {
|
||||
@@ -331,6 +332,7 @@ impl GroupManager {
|
||||
interrupt_callback: RwLock::new(None),
|
||||
score_state,
|
||||
score_authority: Arc::new(score::ScoreAuthority),
|
||||
transport_quality: RwLock::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod evidence;
|
||||
mod feedback;
|
||||
mod pressure;
|
||||
mod ranking;
|
||||
mod selection;
|
||||
#[cfg(test)]
|
||||
@@ -8,6 +9,7 @@ mod verification;
|
||||
|
||||
use evidence::{MetricSnapshot, Performance, PerformanceSnapshot};
|
||||
pub use feedback::{ScoreFeedback, ScoreReporter};
|
||||
pub(in crate::group) use pressure::TransportQualitySource;
|
||||
pub use verification::{
|
||||
ScoreComparison, ScoreEvidenceBasis, ScoreEvidenceGaps, ScoreValidationAction,
|
||||
ScoreVerificationCounters, ScoreVerificationSnapshot, ScoreVerificationState,
|
||||
@@ -37,7 +39,6 @@ const MIN_TRAINED_EVIDENCE: f64 = 0.5;
|
||||
const SCORE_SWITCH_FULL_EVIDENCE: f64 = 8.0;
|
||||
const SCORE_SWITCH_FLAP_WINDOW: u64 = 8;
|
||||
const SELECTION_HISTORY_CAPACITY: usize = 4096;
|
||||
const SCORE_FAILURE_FORGIVENESS_THRESHOLD: f64 = 0.01;
|
||||
const SCORE_EXPLORATION_MIN_PERIOD: u64 = 16;
|
||||
const SCORE_EXPLORATION_MAX_PERIOD: u64 = 64;
|
||||
const SCORE_EXPLORE_BACKOFF_BASE: Duration = Duration::from_secs(5 * 60);
|
||||
@@ -54,6 +55,9 @@ const MAX_THROUGHPUT_DURATION: Duration = Duration::from_secs(10);
|
||||
const REVALIDATION_INTERVAL: Duration = Duration::from_secs(30);
|
||||
const PERFORMANCE_VALIDATION_SAMPLES: f64 = 4.0;
|
||||
const PERFORMANCE_SWITCH_MARGIN: f64 = 0.1;
|
||||
const LIVE_RX_INTERVAL: Duration = Duration::from_secs(1);
|
||||
const LIVE_QUALIFICATION_TTL: Duration = Duration::from_secs(60);
|
||||
const CARRIER_PRESSURE_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
/// Separates business outcomes from configured health and preparation.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
@@ -189,10 +193,13 @@ struct Stats {
|
||||
useful_business: WeightedMean,
|
||||
business_invalidated_through: Option<Instant>,
|
||||
failed_at: Option<Instant>,
|
||||
last_business_rx_at: Option<Instant>,
|
||||
qualified_until: Option<Instant>,
|
||||
warm_setup_ms: WeightedMean,
|
||||
probes: [evidence::ProbeMetric; 6],
|
||||
last_attempt: Option<Instant>,
|
||||
degraded_at: Option<Instant>,
|
||||
carrier_pressure: [Option<crate::transport_quality::TransportPressure>; 2],
|
||||
fail_streak: u32,
|
||||
explore_not_before: Option<Instant>,
|
||||
updated_at: Option<Instant>,
|
||||
@@ -273,16 +280,11 @@ enum SelectionReason {
|
||||
ReliabilityWinner,
|
||||
PerformanceWinner,
|
||||
IncumbentHeld,
|
||||
InsufficientEvidenceHeld,
|
||||
IncumbentIneligible,
|
||||
FreshFailureBypass,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
enum HoldDecision {
|
||||
Held,
|
||||
FreshFailureBypass,
|
||||
UseBest,
|
||||
}
|
||||
|
||||
impl SelectionReason {
|
||||
fn is_exploration(self) -> bool {
|
||||
matches!(self, Self::ColdExplore | Self::PeriodicExplore)
|
||||
@@ -317,11 +319,18 @@ pub struct ScoreReasonCounters {
|
||||
pub reliability_winner: u64,
|
||||
pub performance_winner: u64,
|
||||
pub incumbent_held: u64,
|
||||
pub insufficient_evidence_held: u64,
|
||||
pub incumbent_ineligible: u64,
|
||||
pub fresh_failure_bypass: u64,
|
||||
pub dead_filtered: u64,
|
||||
pub ordinary_switch: u64,
|
||||
pub switch_flap: u64,
|
||||
pub fail_streak_excluded: u64,
|
||||
pub explore_backed_off: u64,
|
||||
pub carrier_pressure: u64,
|
||||
pub carrier_rtt_pressure: u64,
|
||||
pub carrier_loss_pressure: u64,
|
||||
pub carrier_validation: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
@@ -351,6 +360,7 @@ struct StateInner {
|
||||
selection_reasons: HashMap<SelectionReasonKey, ScoreReasonCounters>,
|
||||
verification_counters: HashMap<SelectionReasonKey, ScoreVerificationCounters>,
|
||||
active_authority: Option<Arc<ScoreAuthority>>,
|
||||
published_at: Option<Instant>,
|
||||
tick: u64,
|
||||
exact_evictions: u64,
|
||||
aggregate_evictions: u64,
|
||||
@@ -374,6 +384,7 @@ impl Default for StateInner {
|
||||
),
|
||||
selection_reasons: HashMap::new(),
|
||||
verification_counters: HashMap::new(),
|
||||
published_at: None,
|
||||
active_authority: None,
|
||||
tick: 0,
|
||||
exact_evictions: 0,
|
||||
@@ -439,6 +450,7 @@ impl ScorePolicyState {
|
||||
let mut inner = self.inner.lock();
|
||||
let now = Instant::now();
|
||||
inner.active_authority = Some(authority);
|
||||
inner.published_at = Some(now);
|
||||
inner.valid = membership.into_iter().collect();
|
||||
inner.valid_groups = groups.into_iter().collect();
|
||||
let StateInner {
|
||||
@@ -511,6 +523,7 @@ impl ScorePolicyState {
|
||||
// In-flight traffic keeps its cells, but a new generation must remeasure health.
|
||||
for (_, stats) in inner.aggregate.iter_mut() {
|
||||
stats.probes = Default::default();
|
||||
stats.carrier_pressure = Default::default();
|
||||
stats.invalidate_business(now);
|
||||
}
|
||||
for (_, stats) in inner.exact.iter_mut() {
|
||||
@@ -552,6 +565,8 @@ impl ScorePolicyState {
|
||||
SelectionReason::ReliabilityWinner => &mut counts.reliability_winner,
|
||||
SelectionReason::PerformanceWinner => &mut counts.performance_winner,
|
||||
SelectionReason::IncumbentHeld => &mut counts.incumbent_held,
|
||||
SelectionReason::InsufficientEvidenceHeld => &mut counts.insufficient_evidence_held,
|
||||
SelectionReason::IncumbentIneligible => &mut counts.incumbent_ineligible,
|
||||
SelectionReason::FreshFailureBypass => &mut counts.fresh_failure_bypass,
|
||||
};
|
||||
*counter = counter.saturating_add(1);
|
||||
@@ -593,16 +608,16 @@ impl ScorePolicyState {
|
||||
history.previous = Some(history.current);
|
||||
history.current = node_id;
|
||||
history.switched_at = history.selections;
|
||||
let counters = inner
|
||||
.selection_reasons
|
||||
.entry(SelectionReasonKey::new(
|
||||
&history_key.group,
|
||||
history_key.network,
|
||||
))
|
||||
.or_default();
|
||||
counters.ordinary_switch = counters.ordinary_switch.saturating_add(1);
|
||||
if switch_flap {
|
||||
let counter = &mut inner
|
||||
.selection_reasons
|
||||
.entry(SelectionReasonKey::new(
|
||||
&history_key.group,
|
||||
history_key.network,
|
||||
))
|
||||
.or_default()
|
||||
.switch_flap;
|
||||
*counter = counter.saturating_add(1);
|
||||
counters.switch_flap = counters.switch_flap.saturating_add(1);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -751,10 +766,10 @@ impl ScorePolicyState {
|
||||
struct ScoreSnapshot {
|
||||
attempts: f64,
|
||||
completed: f64,
|
||||
hysteresis_completed: f64,
|
||||
reliability: f64,
|
||||
reliability_upper: f64,
|
||||
useful_completed: f64,
|
||||
qualification_retained: bool,
|
||||
performance: PerformanceSnapshot,
|
||||
target_performance: PerformanceSnapshot,
|
||||
probe: MetricSnapshot,
|
||||
@@ -763,13 +778,20 @@ struct ScoreSnapshot {
|
||||
observed_reliability: f64,
|
||||
last_attempt: Option<Instant>,
|
||||
degraded_at: Option<Instant>,
|
||||
failures: f64,
|
||||
carrier_pressure_at: Option<Instant>,
|
||||
unresolved_failure: bool,
|
||||
explore_backed_off: bool,
|
||||
fail_streak: u32,
|
||||
selected_at: u64,
|
||||
verification: verification::VerificationEvidence,
|
||||
}
|
||||
|
||||
impl ScoreSnapshot {
|
||||
fn qualified(&self) -> bool {
|
||||
self.useful_completed >= PERFORMANCE_VALIDATION_SAMPLES || self.qualification_retained
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct PerformanceBaseline {
|
||||
performance: PerformanceSnapshot,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
use super::ranking::explore_backoff;
|
||||
use super::{
|
||||
AggregateKey, ExactKey, FlowSample, MAX_THROUGHPUT_DURATION, MIN_THROUGHPUT_BYTES,
|
||||
MIN_THROUGHPUT_DURATION, PERFORMANCE_MAX_AGE, PERFORMANCE_VALIDATION_SAMPLES,
|
||||
RELIABILITY_CONFIDENCE_Z, SCORE_EVIDENCE_HALF_LIFE, ScoreAttribution, ScoreAuthority,
|
||||
ScoreOutcome, ScorePolicyState, ScoreSelectionContext, ScoreSource, StartedCells, Stats,
|
||||
WeightedMean,
|
||||
AggregateKey, ExactKey, FlowSample, LIVE_QUALIFICATION_TTL, MAX_THROUGHPUT_DURATION,
|
||||
MIN_THROUGHPUT_BYTES, MIN_THROUGHPUT_DURATION, PERFORMANCE_MAX_AGE,
|
||||
PERFORMANCE_VALIDATION_SAMPLES, RELIABILITY_CONFIDENCE_Z, SCORE_EVIDENCE_HALF_LIFE,
|
||||
ScoreAttribution, ScoreAuthority, ScoreOutcome, ScorePolicyState, ScoreSelectionContext,
|
||||
ScoreSource, StartedCells, Stats, WeightedMean,
|
||||
};
|
||||
use lru::LruCache;
|
||||
use std::sync::Arc;
|
||||
@@ -95,6 +95,9 @@ impl WeightedMean {
|
||||
pub(super) enum Observation {
|
||||
Setup(Duration),
|
||||
Response(Duration),
|
||||
BusinessProgress {
|
||||
rx_at: Instant,
|
||||
},
|
||||
Probe {
|
||||
latency: Duration,
|
||||
scope: u64,
|
||||
@@ -207,12 +210,56 @@ impl Stats {
|
||||
.record(*rx as f64 / elapsed.as_secs_f64(), now);
|
||||
}
|
||||
}
|
||||
(ScoreSource::Traffic, Observation::BusinessProgress { rx_at })
|
||||
if self
|
||||
.business_invalidated_through
|
||||
.is_none_or(|fence| *rx_at > fence) =>
|
||||
{
|
||||
self.last_business_rx_at = Some(
|
||||
self.last_business_rx_at
|
||||
.map_or(*rx_at, |seen| seen.max(*rx_at)),
|
||||
);
|
||||
self.retain_qualification(*rx_at, now);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn retain_qualification(&mut self, rx_at: Instant, now: Instant) {
|
||||
let factor = self
|
||||
.updated_at
|
||||
.map_or(1.0, |at| evidence_decay(now.saturating_duration_since(at)));
|
||||
let qualified = self.useful_completed() * factor >= PERFORMANCE_VALIDATION_SAMPLES;
|
||||
let rx_at = if qualified {
|
||||
self.last_business_rx_at.unwrap_or(rx_at)
|
||||
} else {
|
||||
rx_at
|
||||
};
|
||||
if now.saturating_duration_since(rx_at) >= LIVE_QUALIFICATION_TTL
|
||||
|| self
|
||||
.business_invalidated_through
|
||||
.is_some_and(|fence| rx_at <= fence)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if qualified || self.qualified_until.is_some_and(|until| rx_at < until) {
|
||||
let until = rx_at + LIVE_QUALIFICATION_TTL;
|
||||
// A delayed terminal can bridge the lease to newer observed RX, but not across a silent gap.
|
||||
let latest = self
|
||||
.last_business_rx_at
|
||||
.filter(|at| *at < until)
|
||||
.unwrap_or(rx_at);
|
||||
let until = latest + LIVE_QUALIFICATION_TTL;
|
||||
self.qualified_until = Some(
|
||||
self.qualified_until
|
||||
.map_or(until, |previous| previous.max(until)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn invalidate_business(&mut self, now: Instant) {
|
||||
self.useful_business = WeightedMean::default();
|
||||
self.qualified_until = None;
|
||||
self.business_invalidated_through = Some(
|
||||
self.business_invalidated_through
|
||||
.map_or(now, |at| at.max(now)),
|
||||
@@ -253,6 +300,11 @@ impl Stats {
|
||||
if count_usefulness {
|
||||
if sample.outcome == ScoreOutcome::Success && sample.tx > 0 && sample.rx > 0 {
|
||||
self.useful_success += 1.0;
|
||||
if let Some(at) = sample.last_rx_at {
|
||||
self.last_business_rx_at =
|
||||
Some(self.last_business_rx_at.map_or(at, |seen| seen.max(at)));
|
||||
self.retain_qualification(at, now);
|
||||
}
|
||||
if let Some(at) = sample.last_rx_at
|
||||
&& now.saturating_duration_since(at) < PERFORMANCE_MAX_AGE
|
||||
&& self
|
||||
@@ -486,6 +538,9 @@ impl ScorePolicyState {
|
||||
observation: Observation,
|
||||
now: Instant,
|
||||
) {
|
||||
if matches!(observation, Observation::BusinessProgress { .. }) && context.target.is_none() {
|
||||
return;
|
||||
}
|
||||
Self::update_started(inner, context, attributions, cells, |stats, _| {
|
||||
stats.observe(&observation, source, now)
|
||||
});
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
use super::evidence::Observation;
|
||||
use super::{
|
||||
FlowSample, MAX_THROUGHPUT_DURATION, MIN_THROUGHPUT_BYTES, MIN_THROUGHPUT_DURATION,
|
||||
ScoreAttribution, ScoreAuthority, ScoreOutcome, ScorePolicyState, ScoreSelectionContext,
|
||||
ScoreSource, StartedCells,
|
||||
FlowSample, LIVE_RX_INTERVAL, MAX_THROUGHPUT_DURATION, MIN_THROUGHPUT_BYTES,
|
||||
MIN_THROUGHPUT_DURATION, ScoreAttribution, ScoreAuthority, ScoreOutcome, ScorePolicyState,
|
||||
ScoreSelectionContext, ScoreSource, StartedCells,
|
||||
};
|
||||
use parking_lot::Mutex;
|
||||
use std::hash::{Hash, Hasher};
|
||||
@@ -124,6 +124,7 @@ impl ScoreFeedback {
|
||||
tx: 0,
|
||||
rx: 0,
|
||||
last_rx_at: None,
|
||||
published_rx_at: None,
|
||||
window_tx: 0,
|
||||
window_rx: 0,
|
||||
}),
|
||||
@@ -140,6 +141,7 @@ struct ReporterProgress {
|
||||
tx: u64,
|
||||
rx: u64,
|
||||
last_rx_at: Option<Instant>,
|
||||
published_rx_at: Option<Instant>,
|
||||
window_start: Instant,
|
||||
window_tx: u64,
|
||||
window_rx: u64,
|
||||
@@ -249,6 +251,17 @@ impl ScoreReporter {
|
||||
}
|
||||
if rx > 0 {
|
||||
progress.last_rx_at = Some(progress.last_rx_at.map_or(now, |at| at.max(now)));
|
||||
if progress.setup.is_some()
|
||||
&& progress.tx > 0
|
||||
&& self.shared.feedback.context.target.is_some()
|
||||
&& progress
|
||||
.published_rx_at
|
||||
.is_none_or(|at| now.saturating_duration_since(at) >= LIVE_RX_INTERVAL)
|
||||
{
|
||||
// Bound scorer-lock traffic independently of packet rate; no timer turns silence into progress.
|
||||
progress.published_rx_at = Some(now);
|
||||
self.observe(Observation::BusinessProgress { rx_at: now }, now);
|
||||
}
|
||||
}
|
||||
if now.saturating_duration_since(progress.window_start) > MAX_THROUGHPUT_DURATION {
|
||||
progress.window_start = now;
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
use std::sync::Weak;
|
||||
|
||||
use crate::runtime::OutboundRuntimeRegistry;
|
||||
use crate::transport_quality::{TransportPressure, TransportQuality};
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(in crate::group) struct TransportQualitySource {
|
||||
node_id: Uuid,
|
||||
groups: Vec<String>,
|
||||
udp_carried: bool,
|
||||
quality: Weak<TransportQuality>,
|
||||
}
|
||||
|
||||
impl GroupManager {
|
||||
/// Bind concrete runtime owners before publishing this manager's authority.
|
||||
pub fn bind_transport_quality(&self, runtimes: &OutboundRuntimeRegistry) {
|
||||
let sources = runtimes
|
||||
.values()
|
||||
.filter_map(|runtime| {
|
||||
let groups: Vec<_> = self
|
||||
.groups
|
||||
.values()
|
||||
.filter(|group| group.policy == honk_config::group::GroupPolicy::Score)
|
||||
.filter(|group| self.group_reaches_node(&group.name, runtime.node.id))
|
||||
.map(|group| group.name.clone())
|
||||
.collect();
|
||||
if groups.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let quality = runtime.transport_quality();
|
||||
quality.enable();
|
||||
Some(TransportQualitySource {
|
||||
node_id: runtime.node.id,
|
||||
groups,
|
||||
udp_carried: runtime.udp_capable
|
||||
&& matches!(
|
||||
runtime.node.protocol(),
|
||||
honk_config::types::NodeProtocol::Trojan
|
||||
| honk_config::types::NodeProtocol::VLess
|
||||
| honk_config::types::NodeProtocol::AnyTLS
|
||||
| honk_config::types::NodeProtocol::Hysteria2
|
||||
| honk_config::types::NodeProtocol::Tuic
|
||||
| honk_config::types::NodeProtocol::Juicity
|
||||
),
|
||||
quality: Arc::downgrade(&quality),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
*self.transport_quality.write() = sources;
|
||||
}
|
||||
|
||||
/// Consume advisory carrier episodes without crediting or failing a flow.
|
||||
pub fn observe_transport_quality(&self) {
|
||||
let now = Instant::now();
|
||||
for source in self.transport_quality.read().iter() {
|
||||
let Some(quality) = source.quality.upgrade() else {
|
||||
continue;
|
||||
};
|
||||
let observations = quality.snapshot();
|
||||
self.score_state.observe_carrier_pressure(
|
||||
&self.score_authority,
|
||||
source.node_id,
|
||||
&source.groups,
|
||||
source.udp_carried,
|
||||
observations,
|
||||
now,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ScorePolicyState {
|
||||
pub(super) fn observe_carrier_pressure(
|
||||
&self,
|
||||
authority: &Arc<ScoreAuthority>,
|
||||
node_id: Uuid,
|
||||
groups: &[String],
|
||||
udp_carried: bool,
|
||||
observations: [Option<TransportPressure>; 2],
|
||||
now: Instant,
|
||||
) {
|
||||
if !observations.iter().flatten().any(|pressure| {
|
||||
pressure.observed_at <= now
|
||||
&& now.duration_since(pressure.observed_at) < CARRIER_PRESSURE_TTL
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
let mut inner = self.inner.lock();
|
||||
if !inner
|
||||
.active_authority
|
||||
.as_ref()
|
||||
.is_some_and(|active| Arc::ptr_eq(active, authority))
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(published_at) = inner.published_at else {
|
||||
return;
|
||||
};
|
||||
for group in groups {
|
||||
if !inner.valid.contains(&(group.clone(), node_id)) {
|
||||
continue;
|
||||
}
|
||||
for network in [SelectionNetwork::Tcp, SelectionNetwork::Udp] {
|
||||
if network == SelectionNetwork::Udp && !udp_carried {
|
||||
continue;
|
||||
}
|
||||
let key = AggregateKey {
|
||||
group: group.clone(),
|
||||
network,
|
||||
family: None,
|
||||
node_id,
|
||||
};
|
||||
let Some(stats) = inner.aggregate.peek_mut(&key) else {
|
||||
continue;
|
||||
};
|
||||
let mut accepted = 0_u64;
|
||||
let mut rtt_episodes = 0_u64;
|
||||
let mut loss_episodes = 0_u64;
|
||||
for (family, observation) in observations.iter().enumerate() {
|
||||
let Some(observation) = observation else {
|
||||
continue;
|
||||
};
|
||||
let at = observation.observed_at;
|
||||
if at <= published_at
|
||||
|| at > now
|
||||
|| now.duration_since(at) >= CARRIER_PRESSURE_TTL
|
||||
|| stats.carrier_pressure[family]
|
||||
.is_some_and(|previous| previous.observed_at >= at)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
stats.carrier_pressure[family] = Some(*observation);
|
||||
accepted += 1;
|
||||
match observation.reason {
|
||||
crate::transport_quality::PressureReason::Rtt => rtt_episodes += 1,
|
||||
crate::transport_quality::PressureReason::Loss => loss_episodes += 1,
|
||||
crate::transport_quality::PressureReason::Both => {
|
||||
rtt_episodes += 1;
|
||||
loss_episodes += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
if accepted != 0 {
|
||||
let counts = inner
|
||||
.selection_reasons
|
||||
.entry(SelectionReasonKey::new(group, network))
|
||||
.or_default();
|
||||
counts.carrier_pressure = counts.carrier_pressure.saturating_add(accepted);
|
||||
counts.carrier_rtt_pressure =
|
||||
counts.carrier_rtt_pressure.saturating_add(rtt_episodes);
|
||||
counts.carrier_loss_pressure =
|
||||
counts.carrier_loss_pressure.saturating_add(loss_episodes);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,9 @@
|
||||
use super::evidence::evidence_decay;
|
||||
use super::{
|
||||
AggregateKey, ExactKey, HoldDecision, MIN_TRAINED_EVIDENCE, MetricSnapshot,
|
||||
PERFORMANCE_SWITCH_MARGIN, PERFORMANCE_VALIDATION_SAMPLES, PerformanceBaseline,
|
||||
PerformanceSnapshot, RELIABILITY_CLOSE, REVALIDATION_INTERVAL, RankedSelection,
|
||||
SCORE_EXPLORATION_MAX_PERIOD, SCORE_EXPLORATION_MIN_PERIOD, SCORE_EXPLORE_BACKOFF_BASE,
|
||||
SCORE_EXPLORE_BACKOFF_MAX, SCORE_FAIL_STREAK_EXCLUDE, SCORE_FAILURE_FORGIVENESS_THRESHOLD,
|
||||
AggregateKey, ExactKey, MIN_TRAINED_EVIDENCE, MetricSnapshot, PERFORMANCE_SWITCH_MARGIN,
|
||||
PerformanceBaseline, PerformanceSnapshot, RELIABILITY_CLOSE, REVALIDATION_INTERVAL,
|
||||
RankedSelection, SCORE_EXPLORATION_MAX_PERIOD, SCORE_EXPLORATION_MIN_PERIOD,
|
||||
SCORE_EXPLORE_BACKOFF_BASE, SCORE_EXPLORE_BACKOFF_MAX, SCORE_FAIL_STREAK_EXCLUDE,
|
||||
SCORE_SWITCH_FULL_EVIDENCE, ScoreAuthority, ScorePolicyState, ScoreSelectionContext,
|
||||
ScoreSnapshot, SelectionCadence, SelectionCadenceKey, SelectionHistoryKey, SelectionReason,
|
||||
SelectionReasonKey, StateInner, Stats,
|
||||
@@ -163,6 +162,21 @@ impl ScorePolicyState {
|
||||
index,
|
||||
reason: SelectionReason::PeriodicExplore,
|
||||
};
|
||||
if snapshots[ordinary.index]
|
||||
.carrier_pressure_at
|
||||
.is_some_and(|at| {
|
||||
inner
|
||||
.selection_counts
|
||||
.get(&cadence_key)
|
||||
.is_some_and(|cadence| at > cadence.revalidated_at)
|
||||
})
|
||||
{
|
||||
let counts = inner
|
||||
.selection_reasons
|
||||
.entry(SelectionReasonKey::new(group, context.network))
|
||||
.or_default();
|
||||
counts.carrier_validation = counts.carrier_validation.saturating_add(1);
|
||||
}
|
||||
}
|
||||
if selection.reason.is_exploration()
|
||||
&& let Some(cadence) = inner.selection_counts.get_mut(&cadence_key)
|
||||
@@ -231,26 +245,58 @@ pub(super) fn ordinary_selection(
|
||||
let Some(index) = incumbent.filter(|&index| index != best.index) else {
|
||||
return best;
|
||||
};
|
||||
if !normal_eligible(&snapshots[index], performance) {
|
||||
return if snapshots[index].failures >= SCORE_FAILURE_FORGIVENESS_THRESHOLD {
|
||||
RankedSelection {
|
||||
index: best.index,
|
||||
reason: SelectionReason::FreshFailureBypass,
|
||||
}
|
||||
} else {
|
||||
best
|
||||
let current = &snapshots[index];
|
||||
if !normal_eligible(current, performance) {
|
||||
return RankedSelection {
|
||||
index: best.index,
|
||||
reason: SelectionReason::IncumbentIneligible,
|
||||
};
|
||||
}
|
||||
match hold_decision(&snapshots[index], &snapshots[best.index], performance) {
|
||||
HoldDecision::Held => RankedSelection {
|
||||
index,
|
||||
reason: SelectionReason::IncumbentHeld,
|
||||
},
|
||||
HoldDecision::FreshFailureBypass => RankedSelection {
|
||||
if current.unresolved_failure {
|
||||
return RankedSelection {
|
||||
index: best.index,
|
||||
reason: SelectionReason::FreshFailureBypass,
|
||||
},
|
||||
HoldDecision::UseBest => best,
|
||||
};
|
||||
}
|
||||
if current.completed < MIN_TRAINED_EVIDENCE {
|
||||
return best;
|
||||
}
|
||||
let margin = switch_margin(current.completed);
|
||||
let mut promoted = None;
|
||||
let mut best_has_comparison = false;
|
||||
// Compare every challenger with the same incumbent, not a pairwise tournament.
|
||||
for (candidate_index, candidate) in snapshots.iter().enumerate() {
|
||||
if candidate_index == index
|
||||
|| !normal_eligible(candidate, performance)
|
||||
|| candidate.completed < MIN_TRAINED_EVIDENCE
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let (gain, comparable) = promotion_gain(current, candidate);
|
||||
if candidate_index == best.index {
|
||||
best_has_comparison = comparable;
|
||||
}
|
||||
if gain >= margin
|
||||
&& gain > 0.0
|
||||
&& promoted.is_none_or(|(_, previous_gain)| gain > previous_gain)
|
||||
{
|
||||
promoted = Some((candidate_index, gain));
|
||||
}
|
||||
}
|
||||
if let Some((index, _)) = promoted {
|
||||
RankedSelection {
|
||||
index,
|
||||
reason: SelectionReason::PerformanceWinner,
|
||||
}
|
||||
} else {
|
||||
RankedSelection {
|
||||
index,
|
||||
reason: if best_has_comparison {
|
||||
SelectionReason::IncumbentHeld
|
||||
} else {
|
||||
SelectionReason::InsufficientEvidenceHeld
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -316,7 +362,7 @@ pub(super) fn normal_eligible(score: &ScoreSnapshot, baseline: PerformanceBaseli
|
||||
return false;
|
||||
}
|
||||
if baseline.any_qualified {
|
||||
score.useful_completed >= PERFORMANCE_VALIDATION_SAMPLES
|
||||
score.qualified()
|
||||
&& score.reliability_upper + RELIABILITY_CLOSE >= baseline.best_reliability
|
||||
&& score.observed_reliability + RELIABILITY_CLOSE >= baseline.best_observed_reliability
|
||||
} else {
|
||||
@@ -330,24 +376,67 @@ pub(super) fn switch_margin(completed: f64) -> f64 {
|
||||
0.05 * PERFORMANCE_SWITCH_MARGIN * (completed / SCORE_SWITCH_FULL_EVIDENCE).clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
pub(super) fn hold_decision(
|
||||
incumbent: &ScoreSnapshot,
|
||||
best: &ScoreSnapshot,
|
||||
performance: PerformanceBaseline,
|
||||
) -> HoldDecision {
|
||||
let trained =
|
||||
incumbent.completed >= MIN_TRAINED_EVIDENCE && best.completed >= MIN_TRAINED_EVIDENCE;
|
||||
if !normal_eligible(incumbent, performance)
|
||||
|| !trained
|
||||
|| utility(best, performance) - utility(incumbent, performance)
|
||||
>= switch_margin(incumbent.hysteresis_completed)
|
||||
{
|
||||
HoldDecision::UseBest
|
||||
} else if incumbent.failures < SCORE_FAILURE_FORGIVENESS_THRESHOLD {
|
||||
HoldDecision::Held
|
||||
} else {
|
||||
HoldDecision::FreshFailureBypass
|
||||
fn qualified_pair(left: MetricSnapshot, right: MetricSnapshot) -> Option<(f64, f64)> {
|
||||
if left.confidence < 1.0 || right.confidence < 1.0 {
|
||||
return None;
|
||||
}
|
||||
Some((left.value?, right.value?))
|
||||
}
|
||||
|
||||
fn performance_pair(
|
||||
incumbent: &ScoreSnapshot,
|
||||
candidate: &ScoreSnapshot,
|
||||
metric: fn(&PerformanceSnapshot) -> MetricSnapshot,
|
||||
) -> Option<(f64, f64)> {
|
||||
qualified_pair(
|
||||
metric(&incumbent.target_performance),
|
||||
metric(&candidate.target_performance),
|
||||
)
|
||||
.or_else(|| {
|
||||
qualified_pair(
|
||||
metric(&incumbent.performance),
|
||||
metric(&candidate.performance),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn promotion_gain(incumbent: &ScoreSnapshot, candidate: &ScoreSnapshot) -> (f64, bool) {
|
||||
let latency = performance_pair(incumbent, candidate, |metrics| metrics.response)
|
||||
.or_else(|| {
|
||||
(incumbent.probe_scope == candidate.probe_scope)
|
||||
.then(|| qualified_pair(incumbent.probe, candidate.probe))
|
||||
.flatten()
|
||||
})
|
||||
.or_else(|| performance_pair(incumbent, candidate, |metrics| metrics.setup))
|
||||
.or_else(|| qualified_pair(incumbent.warm_setup, candidate.warm_setup));
|
||||
let mut comparable = latency.is_some();
|
||||
let latency_gain = latency.map_or(0.0, |(left, right)| {
|
||||
let best = left.min(right).max(1.0);
|
||||
(best / right.max(1.0)).min(1.0) - (best / left.max(1.0)).min(1.0)
|
||||
});
|
||||
let mut incumbent_rate = 0.0_f64;
|
||||
let mut candidate_rate = 0.0_f64;
|
||||
for pair in [
|
||||
performance_pair(incumbent, candidate, |metrics| metrics.upload),
|
||||
performance_pair(incumbent, candidate, |metrics| metrics.download),
|
||||
]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
comparable = true;
|
||||
let best = pair.0.max(pair.1).max(1.0);
|
||||
incumbent_rate = incumbent_rate.max((pair.0 / best).clamp(0.0, 1.0));
|
||||
candidate_rate = candidate_rate.max((pair.1 / best).clamp(0.0, 1.0));
|
||||
}
|
||||
let reliability_gain = if incumbent.qualified() && candidate.qualified() {
|
||||
candidate.observed_reliability - incumbent.observed_reliability
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
(
|
||||
reliability_gain + 0.03 * latency_gain + 0.02 * (candidate_rate - incumbent_rate),
|
||||
comparable,
|
||||
)
|
||||
}
|
||||
|
||||
fn mark_selected(
|
||||
@@ -424,14 +513,10 @@ pub(super) fn score_snapshot(
|
||||
);
|
||||
score.completed = score.completed.max(family.completed);
|
||||
score.useful_completed = score.useful_completed.max(family.useful_completed);
|
||||
score.qualification_retained |= family.qualification_retained;
|
||||
score.attempts = score.attempts.max(family.attempts);
|
||||
score.hysteresis_completed = if family.completed > 0.0 {
|
||||
family.completed
|
||||
} else {
|
||||
score.hysteresis_completed
|
||||
};
|
||||
score.performance = prefer_specific(score.performance, family.performance);
|
||||
score.failures = score.failures.max(family.failures);
|
||||
score.unresolved_failure |= family.unresolved_failure;
|
||||
score.fail_streak = score.fail_streak.max(family.fail_streak);
|
||||
score.explore_backed_off |= family.explore_backed_off;
|
||||
score.selected_at = score.selected_at.max(family.selected_at);
|
||||
@@ -443,6 +528,17 @@ pub(super) fn score_snapshot(
|
||||
let probe = &stats.probes[super::evidence::probe_slot(context)];
|
||||
score.probe = probe.latency.snapshot(now);
|
||||
score.probe_scope = probe.scope;
|
||||
// The filter family is not the socket selected by a dual-stack dial.
|
||||
// A carrier hint asks a node-wide question; it is not target performance.
|
||||
score.carrier_pressure_at = stats
|
||||
.carrier_pressure
|
||||
.iter()
|
||||
.flatten()
|
||||
.filter(|pressure| {
|
||||
now.saturating_duration_since(pressure.observed_at) < super::CARRIER_PRESSURE_TTL
|
||||
})
|
||||
.map(|pressure| pressure.observed_at)
|
||||
.max();
|
||||
}
|
||||
if let (Some(family), Some(target)) = (context.target_family, context.target.as_ref())
|
||||
&& let Some(stats) = inner.exact.peek(&ExactKey {
|
||||
@@ -465,13 +561,9 @@ pub(super) fn score_snapshot(
|
||||
);
|
||||
score.completed = score.completed.max(exact.completed);
|
||||
score.useful_completed = score.useful_completed.max(exact.useful_completed);
|
||||
score.hysteresis_completed = if exact.completed > 0.0 {
|
||||
exact.completed
|
||||
} else {
|
||||
score.hysteresis_completed
|
||||
};
|
||||
score.qualification_retained |= exact.qualification_retained;
|
||||
score.target_performance = exact.performance;
|
||||
score.failures = score.failures.max(exact.failures);
|
||||
score.unresolved_failure |= exact.unresolved_failure;
|
||||
score.fail_streak = score.fail_streak.max(exact.fail_streak);
|
||||
score.explore_backed_off |= exact.explore_backed_off;
|
||||
score.selected_at = score.selected_at.max(exact.selected_at);
|
||||
@@ -482,6 +574,7 @@ pub(super) fn score_snapshot(
|
||||
.map(|stats| super::verification::VerificationEvidence::new(stats, now))
|
||||
.unwrap_or_default();
|
||||
}
|
||||
score.degraded_at = score.degraded_at.max(score.carrier_pressure_at);
|
||||
score
|
||||
}
|
||||
|
||||
@@ -495,8 +588,8 @@ pub(super) fn snapshot(stats: &Stats, now: Instant) -> ScoreSnapshot {
|
||||
ScoreSnapshot {
|
||||
attempts: stats.attempts * factor,
|
||||
completed: stats.completed() * factor,
|
||||
hysteresis_completed: stats.completed() * factor,
|
||||
useful_completed: stats.useful_completed() * factor,
|
||||
qualification_retained: stats.qualified_until.is_some_and(|until| now < until),
|
||||
reliability,
|
||||
reliability_upper,
|
||||
observed_reliability: if observations > 0.0 {
|
||||
@@ -506,7 +599,11 @@ pub(super) fn snapshot(stats: &Stats, now: Instant) -> ScoreSnapshot {
|
||||
},
|
||||
performance: stats.performance.snapshot(now),
|
||||
warm_setup: stats.warm_setup_ms.snapshot(now),
|
||||
failures: (stats.setup_failure + stats.useful_failure) * factor,
|
||||
unresolved_failure: stats.failed_at.is_some_and(|failure| {
|
||||
stats
|
||||
.last_business_rx_at
|
||||
.is_none_or(|success| success <= failure)
|
||||
}),
|
||||
explore_backed_off: stats.explore_not_before.is_some_and(|until| until > now),
|
||||
degraded_at: stats
|
||||
.degraded_at
|
||||
@@ -550,17 +647,17 @@ pub(super) fn performance_baseline(snapshots: &[ScoreSnapshot]) -> PerformanceBa
|
||||
let any_qualified = snapshots
|
||||
.iter()
|
||||
.filter(healthy)
|
||||
.any(|score| score.useful_completed >= PERFORMANCE_VALIDATION_SAMPLES);
|
||||
.any(|score| score.qualified());
|
||||
let best_reliability = snapshots
|
||||
.iter()
|
||||
.filter(healthy)
|
||||
.filter(|score| !any_qualified || score.useful_completed >= PERFORMANCE_VALIDATION_SAMPLES)
|
||||
.filter(|score| !any_qualified || score.qualified())
|
||||
.map(|score| score.reliability)
|
||||
.fold(0.0, f64::max);
|
||||
let best_observed_reliability = snapshots
|
||||
.iter()
|
||||
.filter(healthy)
|
||||
.filter(|score| !any_qualified || score.useful_completed >= PERFORMANCE_VALIDATION_SAMPLES)
|
||||
.filter(|score| !any_qualified || score.qualified())
|
||||
.map(|score| score.observed_reliability)
|
||||
.fold(0.0, f64::max);
|
||||
let mut baseline = PerformanceBaseline {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
use super::evidence::evidence_decay;
|
||||
use super::ranking::{exploration_period, exploration_target, score_snapshot};
|
||||
use super::*;
|
||||
use honk_config::group::{Group, GroupPolicy};
|
||||
@@ -8,6 +7,8 @@ mod cadence;
|
||||
mod evidence;
|
||||
mod live;
|
||||
mod performance;
|
||||
mod pressure;
|
||||
mod progress;
|
||||
mod reasons;
|
||||
mod selection;
|
||||
mod verification;
|
||||
@@ -120,15 +121,22 @@ fn train_at(
|
||||
download: u64,
|
||||
now: Instant,
|
||||
) {
|
||||
for _ in 0..samples {
|
||||
let reporter = manager
|
||||
.feedback_for_group_node("score", leaf.id, target.clone())
|
||||
.unwrap()
|
||||
.start_at(now);
|
||||
let feedback = manager
|
||||
.feedback_for_group_node("score", leaf.id, target.clone())
|
||||
.unwrap();
|
||||
let reporters: Vec<_> = (0..samples).map(|_| feedback.start_at(now)).collect();
|
||||
for reporter in &reporters {
|
||||
reporter.setup_succeeded_at(now);
|
||||
}
|
||||
for reporter in &reporters {
|
||||
reporter.first_response_at(now + response);
|
||||
reporter.transfer_at(1, download.max(1), now + Duration::from_secs(1));
|
||||
reporter.finish_at(ScoreOutcome::Success, true, now + Duration::from_secs(1));
|
||||
}
|
||||
let finished = now + Duration::from_secs(1).max(response);
|
||||
for reporter in &reporters {
|
||||
reporter.transfer_at(1, download.max(1), finished);
|
||||
}
|
||||
for reporter in reporters {
|
||||
reporter.finish_at(ScoreOutcome::Success, true, finished);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -21,7 +21,6 @@ fn overlapping_layers_count_each_terminal_completion_once() {
|
||||
);
|
||||
assert!((score.completed - 3.0).abs() < 0.001);
|
||||
assert!((score.useful_completed - 3.0).abs() < 0.001);
|
||||
assert!((score.hysteresis_completed - 3.0).abs() < 0.001);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -470,8 +469,8 @@ fn cancelled_cold_trials_keep_alternative_coverage() {
|
||||
for leaf in &nodes[1..] {
|
||||
let score = score_snapshot(&state.inner.lock(), "score", &target, leaf.id, now);
|
||||
assert_eq!(
|
||||
(score.attempts, score.completed, score.failures),
|
||||
(0.0, 0.0, 0.0)
|
||||
(score.attempts, score.completed, score.unresolved_failure),
|
||||
(0.0, 0.0, false)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,180 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recovered_historical_failure_holds_five_percent_latency_jitter() {
|
||||
let nodes = [node("incumbent"), node("challenger")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = context("business.example", IpVersion::V4);
|
||||
let now = Instant::now();
|
||||
let past = now - Duration::from_secs(3600);
|
||||
let failure = manager
|
||||
.feedback_for_group_node("score", nodes[0].id, target.clone())
|
||||
.unwrap()
|
||||
.start_at(past);
|
||||
failure.setup_succeeded_at(past);
|
||||
failure.finish_at(ScoreOutcome::Io(io::ErrorKind::ConnectionReset), true, past);
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
200,
|
||||
Duration::from_millis(100 + index as u64 * 10),
|
||||
1,
|
||||
now + Duration::from_secs(index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(4)),
|
||||
0
|
||||
);
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[1],
|
||||
&target,
|
||||
200,
|
||||
Duration::from_millis(95),
|
||||
1,
|
||||
now + Duration::from_secs(5),
|
||||
);
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(7)),
|
||||
0
|
||||
);
|
||||
let reasons = manager
|
||||
.score_state()
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(reasons.incumbent_held, 1);
|
||||
assert_eq!(reasons.fresh_failure_bypass, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_newer_business_rx_restores_incumbent_protection() {
|
||||
for recovery in [
|
||||
"none",
|
||||
"old-rx",
|
||||
"same-time-rx",
|
||||
"setup-only",
|
||||
"probe",
|
||||
"warmup",
|
||||
"neutral",
|
||||
"other-target",
|
||||
"business-rx",
|
||||
"new-rx-before-old-finish",
|
||||
] {
|
||||
let nodes = [node("incumbent"), node("challenger")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = context("business.example", IpVersion::V4);
|
||||
let now = Instant::now();
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
1000,
|
||||
Duration::from_millis(100 + index as u64 * 10),
|
||||
1,
|
||||
now + Duration::from_secs(index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(4)),
|
||||
0
|
||||
);
|
||||
let feedback = manager
|
||||
.feedback_for_group_node("score", nodes[0].id, target.clone())
|
||||
.unwrap();
|
||||
let failed_at = now + Duration::from_secs(6);
|
||||
let late = matches!(
|
||||
recovery,
|
||||
"old-rx" | "same-time-rx" | "new-rx-before-old-finish"
|
||||
)
|
||||
.then(|| {
|
||||
let at = if recovery == "same-time-rx" {
|
||||
failed_at
|
||||
} else {
|
||||
failed_at - Duration::from_secs(1)
|
||||
};
|
||||
let reporter = feedback.start_at(at);
|
||||
reporter.setup_succeeded_at(at);
|
||||
reporter.transfer_at(1, 1, at);
|
||||
reporter
|
||||
});
|
||||
let failure = feedback.start_at(failed_at);
|
||||
failure.setup_succeeded_at(failed_at);
|
||||
failure.finish_at(ScoreOutcome::Timeout, true, failed_at);
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[1],
|
||||
&target,
|
||||
1000,
|
||||
Duration::from_millis(95),
|
||||
1,
|
||||
now + Duration::from_secs(7),
|
||||
);
|
||||
let at = now + Duration::from_secs(9);
|
||||
match recovery {
|
||||
"business-rx" | "new-rx-before-old-finish" | "other-target" => {
|
||||
let recovered_target = if recovery == "other-target" {
|
||||
context("other.example", IpVersion::V4)
|
||||
} else {
|
||||
target.clone()
|
||||
};
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[0],
|
||||
&recovered_target,
|
||||
20,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
at,
|
||||
);
|
||||
}
|
||||
"setup-only" | "neutral" | "probe" | "warmup" => {
|
||||
let source = match recovery {
|
||||
"probe" => ScoreSource::HealthProbe,
|
||||
"warmup" => ScoreSource::Warmup,
|
||||
_ => ScoreSource::Traffic,
|
||||
};
|
||||
let reporter = feedback.clone().with_source(source).start_at(at);
|
||||
reporter.setup_succeeded_at(at);
|
||||
if recovery != "setup-only" {
|
||||
reporter.transfer_at(1, 1, at);
|
||||
}
|
||||
let outcome = if recovery == "neutral" {
|
||||
ScoreOutcome::Cancelled
|
||||
} else {
|
||||
ScoreOutcome::Success
|
||||
};
|
||||
reporter.finish_at(outcome, recovery != "setup-only", at);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let selected_at = now + Duration::from_secs(11);
|
||||
if let Some(late) = late {
|
||||
late.finish_at(ScoreOutcome::Success, true, selected_at);
|
||||
}
|
||||
let recovered = matches!(
|
||||
recovery,
|
||||
"business-rx" | "new-rx-before-old-finish" | "neutral"
|
||||
);
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, selected_at),
|
||||
usize::from(!recovered),
|
||||
"{recovery}"
|
||||
);
|
||||
let reasons = manager
|
||||
.score_state()
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(
|
||||
reasons.fresh_failure_bypass,
|
||||
u64::from(!recovered),
|
||||
"{recovery}"
|
||||
);
|
||||
assert_eq!(reasons.incumbent_ineligible, 0, "{recovery}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_manager_authority_stays_revoked_after_same_name_recreation() {
|
||||
let survivor = node("survivor");
|
||||
@@ -98,147 +274,6 @@ fn captured_feedback_requires_current_authority_at_start() {
|
||||
assert_eq!(state.inner.lock().tick, before_tick);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn single_failure_layer_freshness_is_unchanged() {
|
||||
// Given: one aggregate failure cell with exactly one half-life of age.
|
||||
let node = node("leaf");
|
||||
let context = context("example.com", IpVersion::V4);
|
||||
let start = Instant::now();
|
||||
let mut inner = StateInner::default();
|
||||
inner.aggregate.put(
|
||||
AggregateKey {
|
||||
group: "score".into(),
|
||||
network: SelectionNetwork::Tcp,
|
||||
family: None,
|
||||
node_id: node.id,
|
||||
},
|
||||
Stats {
|
||||
setup_failure: 2.0,
|
||||
updated_at: Some(start),
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
|
||||
// When: the scorer snapshots the single layer after one half-life.
|
||||
let score = score_snapshot(
|
||||
&inner,
|
||||
"score",
|
||||
&context,
|
||||
node.id,
|
||||
start + SCORE_EVIDENCE_HALF_LIFE,
|
||||
);
|
||||
|
||||
// Then: existing decay remains unchanged and no absent layer contributes.
|
||||
println!("single failure layer envelope={:.12}", score.failures);
|
||||
assert_close(score.failures, 1.0);
|
||||
}
|
||||
|
||||
fn layered_failure_value(ages: [Option<Duration>; 3]) -> f64 {
|
||||
let node = node("leaf");
|
||||
let context = context("example.com", IpVersion::V4);
|
||||
let start = Instant::now();
|
||||
let now = start + Duration::from_secs(60);
|
||||
let mut inner = StateInner::default();
|
||||
for (index, age) in ages.into_iter().enumerate() {
|
||||
let Some(age) = age else {
|
||||
continue;
|
||||
};
|
||||
let stats = Stats {
|
||||
setup_failure: 1.0,
|
||||
updated_at: Some(now - age),
|
||||
..Default::default()
|
||||
};
|
||||
match index {
|
||||
0 | 1 => {
|
||||
inner.aggregate.put(
|
||||
AggregateKey {
|
||||
group: "score".into(),
|
||||
network: SelectionNetwork::Tcp,
|
||||
family: (index == 1).then_some(IpVersion::V4),
|
||||
node_id: node.id,
|
||||
},
|
||||
stats,
|
||||
);
|
||||
}
|
||||
2 => {
|
||||
inner.exact.put(
|
||||
ExactKey {
|
||||
group: "score".into(),
|
||||
network: SelectionNetwork::Tcp,
|
||||
family: IpVersion::V4,
|
||||
target: context.target.clone().unwrap(),
|
||||
node_id: node.id,
|
||||
},
|
||||
stats,
|
||||
);
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
score_snapshot(&inner, "score", &context, node.id, now).failures
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layered_failure_freshness_uses_one_envelope() {
|
||||
// Given: the same 30-second-old failure appears in overlapping layers.
|
||||
let age = Some(Duration::from_secs(30));
|
||||
|
||||
// When: one, two, and three layers are independently snapshotted.
|
||||
let global_only = layered_failure_value([age, None, None]);
|
||||
let global_family = layered_failure_value([age, age, None]);
|
||||
let global_family_exact = layered_failure_value([age, age, age]);
|
||||
println!(
|
||||
"layered failure envelope: global_only={global_only:.12} global_family={global_family:.12} global_family_exact={global_family_exact:.12}"
|
||||
);
|
||||
|
||||
// Then: replication does not increase the effective failure envelope.
|
||||
assert_close(global_family, global_only);
|
||||
assert_close(global_family_exact, global_only);
|
||||
let aged = layered_failure_value([
|
||||
Some(Duration::from_secs(SCORE_EVIDENCE_HALF_LIFE.as_secs() * 8)),
|
||||
Some(Duration::from_secs(SCORE_EVIDENCE_HALF_LIFE.as_secs() * 8)),
|
||||
Some(Duration::from_secs(SCORE_EVIDENCE_HALF_LIFE.as_secs() * 8)),
|
||||
]);
|
||||
let incumbent =
|
||||
super::super::ranking::snapshot(&trained_stats(8.0, 100.0, Instant::now()), Instant::now());
|
||||
let challenger = ScoreSnapshot {
|
||||
failures: 0.0,
|
||||
..incumbent
|
||||
};
|
||||
let retained = super::super::ranking::hold_decision(
|
||||
&ScoreSnapshot {
|
||||
failures: aged,
|
||||
..incumbent
|
||||
},
|
||||
&challenger,
|
||||
super::super::ranking::performance_baseline(&[incumbent, challenger]),
|
||||
) == HoldDecision::Held;
|
||||
println!("aged layered envelope={aged:.12} retained_incumbent={retained}");
|
||||
assert!(aged < SCORE_FAILURE_FORGIVENESS_THRESHOLD);
|
||||
assert!(retained);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn specific_failure_freshness_is_not_hidden() {
|
||||
// Given: global, family, and exact evidence are respectively 30, 20, and 10 seconds old.
|
||||
let global = evidence_decay(Duration::from_secs(30));
|
||||
let family = evidence_decay(Duration::from_secs(20));
|
||||
let exact = evidence_decay(Duration::from_secs(10));
|
||||
|
||||
// When: all three overlapping layers are snapshotted together.
|
||||
let effective = layered_failure_value([
|
||||
Some(Duration::from_secs(30)),
|
||||
Some(Duration::from_secs(20)),
|
||||
Some(Duration::from_secs(10)),
|
||||
]);
|
||||
println!(
|
||||
"specific failure envelope: global_30s={global:.12} family_20s={family:.12} exact_10s={exact:.12} effective={effective:.12}"
|
||||
);
|
||||
|
||||
// Then: the freshest specific layer is the effective envelope.
|
||||
assert_close(effective, exact);
|
||||
}
|
||||
|
||||
pub(super) fn inner_update_response(state: &ScorePolicyState, key: AggregateKey, latency_ms: f64) {
|
||||
let mut inner = state.inner.lock();
|
||||
let stats = inner.aggregate.get_mut(&key).unwrap();
|
||||
|
||||
@@ -409,8 +409,8 @@ fn setup_quality_survives_neutral_completion_without_a_response() {
|
||||
);
|
||||
assert_eq!(score.target_performance.setup.value, Some(60.0));
|
||||
assert_eq!(
|
||||
(score.attempts, score.completed, score.failures),
|
||||
(0.0, 0.0, 0.0)
|
||||
(score.attempts, score.completed, score.unresolved_failure),
|
||||
(0.0, 0.0, false)
|
||||
);
|
||||
assert_eq!(
|
||||
state.peek_rank("score", &target, &nodes.iter().collect::<Vec<_>>()),
|
||||
@@ -454,8 +454,8 @@ fn concurrent_failed_probe_cannot_retire_successful_probe_evidence() {
|
||||
let score = score_snapshot(&state.inner.lock(), "score", &target, nodes[1].id, now);
|
||||
assert_eq!(score.probe.value, Some(5.0));
|
||||
assert_eq!(
|
||||
(score.attempts, score.completed, score.failures),
|
||||
(0.0, 0.0, 0.0)
|
||||
(score.attempts, score.completed, score.unresolved_failure),
|
||||
(0.0, 0.0, false)
|
||||
);
|
||||
assert_eq!(
|
||||
state.peek_rank("score", &target, &nodes.iter().collect::<Vec<_>>()),
|
||||
|
||||
@@ -1,5 +1,257 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn one_exact_success_cannot_weaken_mature_incumbent_protection() {
|
||||
let nodes = [node("incumbent"), node("challenger")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let previous = context("previous.example", IpVersion::V4);
|
||||
let target = context("new.example", IpVersion::V4);
|
||||
let now = Instant::now();
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&previous,
|
||||
200,
|
||||
Duration::from_millis(100 + index as u64 * 10),
|
||||
1,
|
||||
now + Duration::from_secs(index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(4)),
|
||||
0
|
||||
);
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[0],
|
||||
&target,
|
||||
1,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
now + Duration::from_secs(5),
|
||||
);
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[1],
|
||||
&previous,
|
||||
200,
|
||||
Duration::from_millis(95),
|
||||
1,
|
||||
now + Duration::from_secs(7),
|
||||
);
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(9)),
|
||||
0
|
||||
);
|
||||
let state = manager.score_state();
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.incumbent_held,
|
||||
1
|
||||
);
|
||||
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(if index == 0 { 600 } else { 60 }),
|
||||
1,
|
||||
now + Duration::from_secs(10 + index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(14)),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.ordinary_switch,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expired_incumbent_holds_unmatched_refresh_but_shared_probe_can_promote() {
|
||||
let nodes = [node("a-100ms"), node("b-110ms"), node("c-120ms")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = context("business.example", IpVersion::V4);
|
||||
let now = Instant::now();
|
||||
let start = now - Duration::from_secs(124);
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(100 + index as u64 * 10),
|
||||
1,
|
||||
start + Duration::from_secs(index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, start + Duration::from_secs(6)),
|
||||
0
|
||||
);
|
||||
for (index, leaf) in nodes.iter().enumerate().skip(1) {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(100 + index as u64 * 10),
|
||||
1,
|
||||
start + Duration::from_secs(80 + index as u64 * 2),
|
||||
);
|
||||
}
|
||||
let state = manager.score_state();
|
||||
let refs = nodes.iter().collect::<Vec<_>>();
|
||||
assert_eq!(state.peek_rank("score", &target, &refs), 0);
|
||||
let _ = rank_at(&manager, &nodes, &target, now);
|
||||
assert_eq!(rank_at(&manager, &nodes, &target, now), 0);
|
||||
let reasons = state.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(reasons.insufficient_evidence_held, 2);
|
||||
assert_eq!(reasons.ordinary_switch, 0);
|
||||
assert_eq!(reasons.periodic_explore, 0);
|
||||
|
||||
let probe = context("configured.example", IpVersion::V4);
|
||||
for (leaf, latency) in nodes[..2].iter().zip([600, 60]) {
|
||||
probe_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&probe,
|
||||
ScoreSource::HealthProbe,
|
||||
Duration::from_millis(latency),
|
||||
now,
|
||||
);
|
||||
}
|
||||
assert_eq!(rank_at(&manager, &nodes, &target, now), 1);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.ordinary_switch,
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_global_best_cannot_mask_comparable_third_challenger() {
|
||||
let nodes = [
|
||||
node("incumbent"),
|
||||
node("unmatched-fast"),
|
||||
node("shared-probe-fast"),
|
||||
];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = context("business.example", IpVersion::V4);
|
||||
let now = Instant::now();
|
||||
let start = now - Duration::from_secs(124);
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(100 + index as u64 * 10),
|
||||
1,
|
||||
start + Duration::from_secs(index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, start + Duration::from_secs(6)),
|
||||
0
|
||||
);
|
||||
for (index, latency) in [(1, 10), (2, 100)] {
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[index],
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(latency),
|
||||
1,
|
||||
start + Duration::from_secs(80 + index as u64 * 2),
|
||||
);
|
||||
}
|
||||
let probe = context("configured.example", IpVersion::V4);
|
||||
for (index, latency) in [(0, 600), (2, 60)] {
|
||||
probe_at(
|
||||
&manager,
|
||||
&nodes[index],
|
||||
&probe,
|
||||
ScoreSource::HealthProbe,
|
||||
Duration::from_millis(latency),
|
||||
now,
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
manager
|
||||
.score_state()
|
||||
.peek_rank("score", &target, &nodes.iter().collect::<Vec<_>>()),
|
||||
2
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opposite_direction_strengths_do_not_create_a_pairwise_rate_gain() {
|
||||
let nodes = [node("upload"), node("download"), node("extreme-upload")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = context("business.example", IpVersion::V4);
|
||||
let now = Instant::now();
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
now + Duration::from_secs(index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(6)),
|
||||
0
|
||||
);
|
||||
for (index, (tx, rx)) in [
|
||||
(1_000_000, 100_000),
|
||||
(100_000, 1_000_000),
|
||||
(10_000_000, 65_536),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let at = now + Duration::from_secs(7 + index as u64 * 2);
|
||||
let feedback = manager
|
||||
.feedback_for_group_node("score", nodes[index].id, target.clone())
|
||||
.unwrap();
|
||||
let reporters: Vec<_> = (0..4).map(|_| feedback.start_at(at)).collect();
|
||||
for reporter in &reporters {
|
||||
reporter.setup_succeeded_at(at);
|
||||
}
|
||||
for reporter in &reporters {
|
||||
reporter.first_response_at(at + Duration::from_millis(100));
|
||||
}
|
||||
for reporter in &reporters {
|
||||
reporter.transfer_at(tx, rx, at + Duration::from_secs(1));
|
||||
}
|
||||
for reporter in reporters {
|
||||
reporter.finish_at(ScoreOutcome::Success, true, at + Duration::from_secs(1));
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(13)),
|
||||
0
|
||||
);
|
||||
let reasons = manager
|
||||
.score_state()
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(reasons.incumbent_held, 1);
|
||||
assert_eq!(reasons.ordinary_switch, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn less_sampled_faster_leaf_wins_normal_selection() {
|
||||
let nodes = [node("historical"), node("faster")];
|
||||
|
||||
@@ -0,0 +1,331 @@
|
||||
use super::*;
|
||||
use crate::transport_quality::{PressureReason, TransportPressure};
|
||||
|
||||
fn pressure_at(manager: &GroupManager, node_id: Uuid, family: IpVersion, at: Instant) {
|
||||
let mut observations = [None; 2];
|
||||
observations[family as usize] = Some(TransportPressure {
|
||||
observed_at: at,
|
||||
reason: PressureReason::Both,
|
||||
});
|
||||
manager.score_state.observe_carrier_pressure(
|
||||
&manager.score_authority,
|
||||
node_id,
|
||||
&["score".into()],
|
||||
true,
|
||||
observations,
|
||||
at,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carrier_pressure_reopens_only_budgeted_comparison_without_penalizing_business() {
|
||||
for network in [SelectionNetwork::Tcp, SelectionNetwork::Udp] {
|
||||
let nodes = [node("incumbent"), node("alternative")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let mut target = context("business.example", IpVersion::V4);
|
||||
target.network = network;
|
||||
target.probe_domain = if network == SelectionNetwork::Tcp {
|
||||
ProbeDomain::Tcp
|
||||
} else {
|
||||
ProbeDomain::DataUdp
|
||||
};
|
||||
let start = Instant::now();
|
||||
for leaf in &nodes {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
start,
|
||||
);
|
||||
}
|
||||
let ready = start + Duration::from_secs(2);
|
||||
for _ in 0..16 {
|
||||
assert_eq!(rank_at(&manager, &nodes, &target, ready), 0);
|
||||
}
|
||||
let state = manager.score_state();
|
||||
let at = ready + Duration::from_secs(1);
|
||||
let before = score_snapshot(&state.inner.lock(), "score", &target, nodes[0].id, at);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", network)
|
||||
.periodic_explore,
|
||||
0
|
||||
);
|
||||
pressure_at(&manager, nodes[0].id, IpVersion::V4, at);
|
||||
pressure_at(&manager, nodes[0].id, IpVersion::V4, at);
|
||||
let after = score_snapshot(&state.inner.lock(), "score", &target, nodes[0].id, at);
|
||||
assert_close(after.completed, before.completed);
|
||||
assert_close(after.useful_completed, before.useful_completed);
|
||||
assert_close(after.reliability, before.reliability);
|
||||
assert_eq!(after.fail_streak, before.fail_streak);
|
||||
assert_eq!(after.explore_backed_off, before.explore_backed_off);
|
||||
assert_eq!(after.qualified(), before.qualified());
|
||||
let refs = nodes.iter().collect::<Vec<_>>();
|
||||
let counters = state.selection_reason_counts("score", network);
|
||||
for _ in 0..10 {
|
||||
assert_eq!(state.peek_rank("score", &target, &refs), 0);
|
||||
}
|
||||
assert_eq!(state.selection_reason_counts("score", network), counters);
|
||||
assert_eq!(counters.carrier_pressure, 1);
|
||||
assert_eq!(counters.carrier_rtt_pressure, 1);
|
||||
assert_eq!(counters.carrier_loss_pressure, 1);
|
||||
assert_eq!(rank_at(&manager, &nodes, &target, at), 1);
|
||||
let validated = state.selection_reason_counts("score", network);
|
||||
assert_eq!(validated.periodic_explore, 1);
|
||||
assert_eq!(validated.carrier_validation, 1);
|
||||
assert_eq!(validated.ordinary_switch, 0);
|
||||
for _ in 0..15 {
|
||||
pressure_at(&manager, nodes[0].id, IpVersion::V4, at);
|
||||
assert_eq!(rank_at(&manager, &nodes, &target, at), 0);
|
||||
}
|
||||
let bounded = state.selection_reason_counts("score", network);
|
||||
assert_eq!(bounded.periodic_explore, 1);
|
||||
assert_eq!(bounded.carrier_pressure, 1);
|
||||
assert_eq!(bounded.carrier_rtt_pressure, 1);
|
||||
assert_eq!(bounded.carrier_loss_pressure, 1);
|
||||
assert_eq!(bounded.ordinary_switch, 0);
|
||||
// A successful measurement, not the hint, earns ordinary promotion.
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[1],
|
||||
&target,
|
||||
4,
|
||||
Duration::from_millis(10),
|
||||
1,
|
||||
at,
|
||||
);
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, at + Duration::from_secs(1)),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", network)
|
||||
.ordinary_switch,
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn carrier_pressure_is_owner_scoped_expiring_and_cannot_create_flow_evidence() {
|
||||
let nodes = [node("one"), node("two")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let start = Instant::now();
|
||||
pressure_at(&manager, nodes[0].id, IpVersion::V4, start);
|
||||
assert_eq!(manager.score_cache_snapshot().aggregate_cells, 0);
|
||||
let target = context("family.example", IpVersion::V6);
|
||||
for leaf in &nodes {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
start,
|
||||
);
|
||||
}
|
||||
let at = start + Duration::from_secs(2);
|
||||
manager.score_state.observe_carrier_pressure(
|
||||
&manager.score_authority,
|
||||
nodes[0].id,
|
||||
&["score".into()],
|
||||
true,
|
||||
[
|
||||
Some(TransportPressure {
|
||||
observed_at: at,
|
||||
reason: PressureReason::Rtt,
|
||||
}),
|
||||
None,
|
||||
],
|
||||
at,
|
||||
);
|
||||
let state = manager.score_state();
|
||||
let score = |context: &ScoreSelectionContext, now| {
|
||||
score_snapshot(&state.inner.lock(), "score", context, nodes[0].id, now)
|
||||
};
|
||||
assert_eq!(score(&target, at).carrier_pressure_at, Some(at));
|
||||
let mut other_carrier_family = target.clone();
|
||||
other_carrier_family.health_family = IpVersion::V6;
|
||||
assert_eq!(
|
||||
score(&other_carrier_family, at).carrier_pressure_at,
|
||||
Some(at)
|
||||
);
|
||||
let expired = at + CARRIER_PRESSURE_TTL;
|
||||
assert!(score(&target, expired).carrier_pressure_at.is_none());
|
||||
let reasons = state.selection_reason_counts("score", target.network);
|
||||
assert_eq!(reasons.carrier_rtt_pressure, 1);
|
||||
assert_eq!(reasons.carrier_loss_pressure, 0);
|
||||
let late = [
|
||||
Some(TransportPressure {
|
||||
observed_at: at,
|
||||
reason: PressureReason::Loss,
|
||||
}),
|
||||
None,
|
||||
];
|
||||
state.observe_carrier_pressure(
|
||||
&manager.score_authority,
|
||||
nodes[0].id,
|
||||
&["score".into()],
|
||||
true,
|
||||
late,
|
||||
at,
|
||||
);
|
||||
assert_eq!(
|
||||
state.selection_reason_counts("score", target.network),
|
||||
reasons
|
||||
);
|
||||
state.observe_carrier_pressure(
|
||||
&manager.score_authority,
|
||||
nodes[0].id,
|
||||
&["score".into()],
|
||||
true,
|
||||
late,
|
||||
expired,
|
||||
);
|
||||
assert_eq!(
|
||||
state.selection_reason_counts("score", target.network),
|
||||
reasons
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaced_runtime_and_retired_manager_cannot_publish_carrier_pressure() {
|
||||
let leaf = Node::from_share_link("socks5://127.0.0.1:1080#old").unwrap();
|
||||
let groups = [group("score", std::slice::from_ref(&leaf))];
|
||||
let old_runtimes =
|
||||
crate::runtime::OutboundRuntimeRegistry::build(std::slice::from_ref(&leaf)).unwrap();
|
||||
let old = GroupManager::new(&groups, std::slice::from_ref(&leaf));
|
||||
old.bind_transport_quality(&old_runtimes);
|
||||
let target = context("reload.example", IpVersion::V4);
|
||||
train_at(
|
||||
&old,
|
||||
&leaf,
|
||||
&target,
|
||||
20,
|
||||
Duration::from_millis(1),
|
||||
1,
|
||||
Instant::now() - Duration::from_secs(2),
|
||||
);
|
||||
let mut renamed = leaf.clone();
|
||||
renamed.name = "replacement".into();
|
||||
let (new_runtimes, reused) = crate::runtime::OutboundRuntimeRegistry::build_reusing(
|
||||
std::slice::from_ref(&renamed),
|
||||
64,
|
||||
Some(&old_runtimes),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(reused.is_empty());
|
||||
let replacement =
|
||||
GroupManager::with_alive_set_and_score_state(&groups, &[renamed], None, old.score_state());
|
||||
replacement.bind_transport_quality(&new_runtimes);
|
||||
replacement.publish_score_membership();
|
||||
let old_quality = old_runtimes.get(&leaf.id).unwrap().transport_quality();
|
||||
old_quality.report(false, PressureReason::Loss, Instant::now());
|
||||
old.observe_transport_quality();
|
||||
replacement.observe_transport_quality();
|
||||
assert_eq!(
|
||||
replacement
|
||||
.score_state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.carrier_pressure,
|
||||
0
|
||||
);
|
||||
new_runtimes
|
||||
.get(&leaf.id)
|
||||
.unwrap()
|
||||
.transport_quality()
|
||||
.report(false, PressureReason::Loss, Instant::now());
|
||||
replacement.observe_transport_quality();
|
||||
assert_eq!(
|
||||
replacement
|
||||
.score_state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.carrier_pressure,
|
||||
1
|
||||
);
|
||||
let successor = GroupManager::with_alive_set_and_score_state(
|
||||
&groups,
|
||||
std::slice::from_ref(&leaf),
|
||||
None,
|
||||
old.score_state(),
|
||||
);
|
||||
successor.bind_transport_quality(&new_runtimes);
|
||||
successor.publish_score_membership();
|
||||
successor.observe_transport_quality();
|
||||
assert_eq!(
|
||||
successor
|
||||
.score_state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.carrier_pressure,
|
||||
1
|
||||
);
|
||||
assert!(
|
||||
score_snapshot(
|
||||
&successor.score_state.inner.lock(),
|
||||
"score",
|
||||
&target,
|
||||
leaf.id,
|
||||
Instant::now()
|
||||
)
|
||||
.carrier_pressure_at
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shadowsocks_tcp_pressure_does_not_spend_native_udp_validation() {
|
||||
let leaf = Node::from_share_link("ss://YWVzLTEyOC1nY206cGFzcw@127.0.0.1:8388#carrier").unwrap();
|
||||
let nodes = std::slice::from_ref(&leaf);
|
||||
let manager = GroupManager::new(&[group("score", nodes)], nodes);
|
||||
let runtimes = crate::runtime::OutboundRuntimeRegistry::build(nodes).unwrap();
|
||||
manager.bind_transport_quality(&runtimes);
|
||||
let tcp = context("same-node.example", IpVersion::V4);
|
||||
let mut udp = tcp.clone();
|
||||
udp.network = SelectionNetwork::Udp;
|
||||
udp.probe_domain = ProbeDomain::DataUdp;
|
||||
for target in [&tcp, &udp] {
|
||||
train_at(
|
||||
&manager,
|
||||
&leaf,
|
||||
target,
|
||||
20,
|
||||
Duration::from_millis(10),
|
||||
1,
|
||||
Instant::now() - Duration::from_secs(2),
|
||||
);
|
||||
}
|
||||
runtimes.get(&leaf.id).unwrap().transport_quality().report(
|
||||
false,
|
||||
PressureReason::Loss,
|
||||
Instant::now(),
|
||||
);
|
||||
manager.observe_transport_quality();
|
||||
let state = manager.score_state();
|
||||
let inner = state.inner.lock();
|
||||
assert!(
|
||||
score_snapshot(&inner, "score", &tcp, leaf.id, Instant::now())
|
||||
.carrier_pressure_at
|
||||
.is_some()
|
||||
);
|
||||
assert!(
|
||||
score_snapshot(&inner, "score", &udp, leaf.id, Instant::now())
|
||||
.carrier_pressure_at
|
||||
.is_none()
|
||||
);
|
||||
drop(inner);
|
||||
let tcp_counts = state.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(tcp_counts.carrier_pressure, 1);
|
||||
assert_eq!(tcp_counts.carrier_rtt_pressure, 0);
|
||||
assert_eq!(tcp_counts.carrier_loss_pressure, 1);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", SelectionNetwork::Udp)
|
||||
.carrier_pressure,
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,604 @@
|
||||
use super::super::ranking::{normal_eligible, ordinary_selection, performance_baseline};
|
||||
use super::*;
|
||||
|
||||
fn udp_context() -> ScoreSelectionContext {
|
||||
let mut target = context("active-udp.example", IpVersion::V4);
|
||||
target.network = SelectionNetwork::Udp;
|
||||
target.probe_domain = ProbeDomain::DataUdp;
|
||||
target
|
||||
}
|
||||
|
||||
fn snapshots(
|
||||
manager: &GroupManager,
|
||||
nodes: &[Node],
|
||||
target: &ScoreSelectionContext,
|
||||
at: Instant,
|
||||
) -> Vec<ScoreSnapshot> {
|
||||
let state = manager.score_state();
|
||||
let inner = state.inner.lock();
|
||||
nodes
|
||||
.iter()
|
||||
.map(|node| score_snapshot(&inner, "score", target, node.id, at))
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_udp_keeps_earned_qualification_without_inventing_completions() {
|
||||
let nodes = [node("incumbent"), node("challenger"), node("cold")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = udp_context();
|
||||
let now = Instant::now();
|
||||
for (index, samples) in [4, 5, 3].into_iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[index],
|
||||
&target,
|
||||
samples,
|
||||
Duration::from_millis(100 + index as u64 * 5),
|
||||
1,
|
||||
now,
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(1)),
|
||||
0
|
||||
);
|
||||
let active: Vec<_> = nodes
|
||||
.iter()
|
||||
.map(|leaf| {
|
||||
let reporter = manager
|
||||
.feedback_for_group_node("score", leaf.id, target.clone())
|
||||
.unwrap()
|
||||
.start_at(now + Duration::from_secs(1));
|
||||
reporter.setup_succeeded_at(now + Duration::from_secs(1));
|
||||
reporter
|
||||
})
|
||||
.collect();
|
||||
for second in (2..=662).step_by(30) {
|
||||
let at = now + Duration::from_secs(second);
|
||||
for reporter in &active {
|
||||
reporter.transfer_at(1, 1, at);
|
||||
}
|
||||
let scores = snapshots(&manager, &nodes, &target, at);
|
||||
let baseline = performance_baseline(&scores);
|
||||
assert!(scores[0].useful_completed < 4.0);
|
||||
if second == 2 {
|
||||
assert!(scores[1].useful_completed >= 4.0);
|
||||
}
|
||||
assert!(baseline.any_qualified);
|
||||
assert!(normal_eligible(&scores[0], baseline));
|
||||
assert!(normal_eligible(&scores[1], baseline));
|
||||
assert!(!normal_eligible(&scores[2], baseline));
|
||||
for (score, samples) in scores.iter().zip([4.0, 5.0, 3.0]) {
|
||||
let expected = samples * (-((second - 1) as f64) / 1800.0).exp2();
|
||||
assert_close(score.completed, expected);
|
||||
assert_close(score.useful_completed, expected);
|
||||
assert_eq!(score.fail_streak, 0);
|
||||
assert!(!score.unresolved_failure);
|
||||
}
|
||||
if second == 2 {
|
||||
assert_eq!(rank_at(&manager, &nodes, &target, at), 0);
|
||||
}
|
||||
let ordinary = ordinary_selection(
|
||||
&scores,
|
||||
&nodes.iter().collect::<Vec<_>>(),
|
||||
Some(0),
|
||||
baseline,
|
||||
);
|
||||
assert_eq!(ordinary.index, 0);
|
||||
}
|
||||
let state = manager.score_state();
|
||||
let verification = state
|
||||
.verification_snapshot_at(
|
||||
"score",
|
||||
&target,
|
||||
&nodes.iter().collect::<Vec<_>>(),
|
||||
now + Duration::from_secs(662),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(verification.state, ScoreVerificationState::Provisional);
|
||||
assert_eq!(verification.evidence_age_ms, None);
|
||||
let reasons = state.selection_reason_counts("score", SelectionNetwork::Udp);
|
||||
assert_eq!(reasons.incumbent_ineligible, 0);
|
||||
assert_eq!(reasons.ordinary_switch, 0);
|
||||
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[1],
|
||||
&target,
|
||||
5,
|
||||
Duration::from_millis(105),
|
||||
1,
|
||||
now + Duration::from_secs(720),
|
||||
);
|
||||
let expiry = now + Duration::from_secs(722);
|
||||
let before = snapshots(&manager, &nodes, &target, expiry - Duration::from_nanos(1));
|
||||
assert!(normal_eligible(&before[0], performance_baseline(&before)));
|
||||
let expired = snapshots(&manager, &nodes, &target, expiry);
|
||||
assert!(!normal_eligible(
|
||||
&expired[0],
|
||||
performance_baseline(&expired)
|
||||
));
|
||||
let ordinary = ordinary_selection(
|
||||
&expired,
|
||||
&nodes.iter().collect::<Vec<_>>(),
|
||||
Some(0),
|
||||
performance_baseline(&expired),
|
||||
);
|
||||
assert_eq!(ordinary.index, 1);
|
||||
assert_eq!(ordinary.reason, SelectionReason::IncumbentIneligible);
|
||||
active[0].transfer_at(1, 1, expiry + Duration::from_secs(1));
|
||||
let late = snapshots(&manager, &nodes, &target, expiry + Duration::from_secs(1));
|
||||
assert!(!normal_eligible(&late[0], performance_baseline(&late)));
|
||||
|
||||
let settled_at = expiry + Duration::from_secs(2);
|
||||
let before = snapshots(&manager, &nodes, &target, settled_at);
|
||||
let clone = active[0].clone();
|
||||
active[0].finish_at(ScoreOutcome::Success, true, settled_at);
|
||||
clone.finish_at(ScoreOutcome::Timeout, true, settled_at);
|
||||
clone.transfer_at(1, 1, settled_at + Duration::from_secs(1));
|
||||
let settled = snapshots(&manager, &nodes, &target, settled_at);
|
||||
assert_close(settled[0].completed, before[0].completed + 1.0);
|
||||
assert_close(
|
||||
settled[0].useful_completed,
|
||||
before[0].useful_completed + 1.0,
|
||||
);
|
||||
assert!(normal_eligible(&settled[0], performance_baseline(&settled)));
|
||||
assert!(!settled[0].unresolved_failure);
|
||||
for reporter in &active[1..] {
|
||||
reporter.finish_at(ScoreOutcome::Cancelled, true, settled_at);
|
||||
}
|
||||
let terminal_expiry = expiry + Duration::from_secs(61);
|
||||
let before = snapshots(
|
||||
&manager,
|
||||
&nodes,
|
||||
&target,
|
||||
terminal_expiry - Duration::from_nanos(1),
|
||||
);
|
||||
assert!(before[0].useful_completed < 4.0);
|
||||
assert!(normal_eligible(&before[0], performance_baseline(&before)));
|
||||
let expired = snapshots(&manager, &nodes, &target, terminal_expiry);
|
||||
assert!(!normal_eligible(
|
||||
&expired[0],
|
||||
performance_baseline(&expired)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn publishable_business_rx_restores_hold_but_never_settles_the_flow() {
|
||||
let nodes = [node("incumbent"), node("challenger")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = udp_context();
|
||||
let now = Instant::now();
|
||||
for (index, leaf) in nodes.iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
1000,
|
||||
Duration::from_millis(100 + index as u64 * 10),
|
||||
1,
|
||||
now + Duration::from_secs(index as u64 * 2),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(4)),
|
||||
0
|
||||
);
|
||||
let feedback = manager
|
||||
.feedback_for_group_node("score", nodes[0].id, target.clone())
|
||||
.unwrap();
|
||||
let failed_at = now + Duration::from_secs(6);
|
||||
let failure = feedback.start_at(failed_at);
|
||||
failure.setup_succeeded_at(failed_at);
|
||||
failure.finish_at(ScoreOutcome::Timeout, true, failed_at);
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[1],
|
||||
&target,
|
||||
1000,
|
||||
Duration::from_millis(95),
|
||||
1,
|
||||
now + Duration::from_secs(7),
|
||||
);
|
||||
let at = now + Duration::from_secs(9);
|
||||
for source in [ScoreSource::HealthProbe, ScoreSource::Warmup] {
|
||||
let reporter = feedback.clone().with_source(source).start_at(at);
|
||||
reporter.setup_succeeded_at(at);
|
||||
reporter.transfer_at(1, 1, at);
|
||||
reporter.finish_at(ScoreOutcome::Success, true, at);
|
||||
}
|
||||
let mut untargeted = target.clone();
|
||||
untargeted.target = None;
|
||||
let unscoped = feedback
|
||||
.clone()
|
||||
.with_context(untargeted.clone())
|
||||
.start_at(at);
|
||||
unscoped.setup_succeeded_at(at);
|
||||
unscoped.transfer_at(1, 1, at);
|
||||
unscoped.finish_at(ScoreOutcome::Cancelled, true, at);
|
||||
let setup_only = feedback.start_at(at);
|
||||
setup_only.setup_succeeded_at(at);
|
||||
setup_only.finish_at(ScoreOutcome::Cancelled, false, at);
|
||||
let rx_only = feedback.start_at(at);
|
||||
rx_only.setup_succeeded_at(at);
|
||||
rx_only.transfer_at(0, 1, at);
|
||||
rx_only.finish_at(ScoreOutcome::Cancelled, true, at);
|
||||
let active = feedback.start_at(at);
|
||||
active.transfer_at(0, 1, at);
|
||||
active.setup_succeeded_at(at);
|
||||
active.transfer_at(1, 0, at);
|
||||
active.transfer_at(0, 0, at);
|
||||
let before = snapshots(&manager, &nodes, &target, at);
|
||||
assert!(before[0].unresolved_failure);
|
||||
untargeted.target_family = None;
|
||||
assert!(snapshots(&manager, &nodes, &untargeted, at)[0].unresolved_failure);
|
||||
let baseline = performance_baseline(&before);
|
||||
assert!(normal_eligible(&before[0], baseline));
|
||||
let bypass = ordinary_selection(
|
||||
&before,
|
||||
&nodes.iter().collect::<Vec<_>>(),
|
||||
Some(0),
|
||||
baseline,
|
||||
);
|
||||
assert_eq!(bypass.index, 1);
|
||||
assert_eq!(bypass.reason, SelectionReason::FreshFailureBypass);
|
||||
|
||||
active.transfer_at(0, 1, at);
|
||||
let recovered = snapshots(&manager, &nodes, &target, at);
|
||||
assert!(!recovered[0].unresolved_failure);
|
||||
assert_close(recovered[0].attempts, before[0].attempts);
|
||||
assert_close(recovered[0].completed, before[0].completed);
|
||||
assert_close(recovered[0].useful_completed, before[0].useful_completed);
|
||||
assert_close(recovered[0].reliability, before[0].reliability);
|
||||
assert_close(recovered[0].reliability_upper, before[0].reliability_upper);
|
||||
assert_close(
|
||||
recovered[0].observed_reliability,
|
||||
before[0].observed_reliability,
|
||||
);
|
||||
assert_eq!(recovered[0].fail_streak, 1);
|
||||
assert!(recovered[0].explore_backed_off);
|
||||
assert!(recovered[0].verification.business.value.is_none());
|
||||
assert_eq!(rank_at(&manager, &nodes, &target, at), 0);
|
||||
let reasons = manager
|
||||
.score_state()
|
||||
.selection_reason_counts("score", SelectionNetwork::Udp);
|
||||
assert_eq!(reasons.incumbent_held, 1);
|
||||
assert_eq!(reasons.fresh_failure_bypass, 0);
|
||||
|
||||
let next_failure = feedback.start_at(at + Duration::from_millis(100));
|
||||
next_failure.setup_succeeded_at(at + Duration::from_millis(100));
|
||||
next_failure.finish_at(ScoreOutcome::Timeout, true, at + Duration::from_millis(100));
|
||||
active.transfer_at(0, 1, at + Duration::from_millis(200));
|
||||
let throttled = snapshots(&manager, &nodes, &target, at + Duration::from_millis(200));
|
||||
assert!(throttled[0].unresolved_failure);
|
||||
// No timer flushes throttled RX: only the next publishable RX or terminal can recover.
|
||||
let published_at = at + Duration::from_secs(1);
|
||||
let before = snapshots(&manager, &nodes, &target, published_at);
|
||||
active.transfer_at(0, 1, published_at);
|
||||
let published = snapshots(&manager, &nodes, &target, published_at);
|
||||
assert!(!published[0].unresolved_failure);
|
||||
assert_eq!(published[0].fail_streak, 2);
|
||||
assert!(published[0].explore_backed_off);
|
||||
assert_close(published[0].completed, before[0].completed);
|
||||
assert_close(published[0].useful_completed, before[0].useful_completed);
|
||||
let clone = active.clone();
|
||||
active.finish_at(ScoreOutcome::Cancelled, true, published_at);
|
||||
clone.finish_at(ScoreOutcome::Success, true, published_at);
|
||||
let cancelled = snapshots(&manager, &nodes, &target, published_at);
|
||||
assert!(!cancelled[0].unresolved_failure);
|
||||
assert_close(cancelled[0].completed, published[0].completed);
|
||||
assert_close(cancelled[0].useful_completed, published[0].useful_completed);
|
||||
assert_close(
|
||||
cancelled[0].attempts,
|
||||
published[0].attempts - (-1.0_f64 / 1800.0).exp2(),
|
||||
);
|
||||
assert!(cancelled[0].verification.business.value.is_none());
|
||||
|
||||
let last_failure_at = published_at + Duration::from_secs(1);
|
||||
let last_failure = feedback.start_at(last_failure_at);
|
||||
last_failure.setup_succeeded_at(last_failure_at);
|
||||
last_failure.finish_at(ScoreOutcome::Timeout, true, last_failure_at);
|
||||
let failed = snapshots(&manager, &nodes, &target, last_failure_at);
|
||||
clone.transfer_at(1, 1, last_failure_at + Duration::from_secs(1));
|
||||
clone.finish_at(
|
||||
ScoreOutcome::Timeout,
|
||||
true,
|
||||
last_failure_at + Duration::from_secs(1),
|
||||
);
|
||||
last_failure.finish_at(ScoreOutcome::Success, true, last_failure_at);
|
||||
let ignored = snapshots(&manager, &nodes, &target, last_failure_at);
|
||||
assert!(ignored[0].unresolved_failure);
|
||||
assert_eq!(ignored[0].fail_streak, 3);
|
||||
assert_close(ignored[0].completed, failed[0].completed);
|
||||
assert_close(ignored[0].useful_completed, failed[0].useful_completed);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_rx_recovers_after_verification_age_without_refreshing_verification() {
|
||||
let nodes = [node("incumbent"), node("challenger")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = udp_context();
|
||||
let now = Instant::now();
|
||||
// Two failures must stay below the mature margin to isolate recovery from risk-based promotion.
|
||||
for leaf in &nodes {
|
||||
train_at(
|
||||
&manager,
|
||||
leaf,
|
||||
&target,
|
||||
512,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
now,
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
rank_at(&manager, &nodes, &target, now + Duration::from_secs(2)),
|
||||
0
|
||||
);
|
||||
let feedback = manager
|
||||
.feedback_for_group_node("score", nodes[0].id, target.clone())
|
||||
.unwrap();
|
||||
let at = now + Duration::from_secs(3);
|
||||
let active = feedback.start_at(at);
|
||||
active.setup_succeeded_at(at);
|
||||
let failure = feedback.start_at(at);
|
||||
failure.setup_succeeded_at(at);
|
||||
failure.finish_at(ScoreOutcome::Timeout, true, at);
|
||||
active.transfer_at(1, 1, at + Duration::from_millis(100));
|
||||
assert!(
|
||||
!snapshots(&manager, &nodes, &target, at + Duration::from_millis(100))[0]
|
||||
.unresolved_failure
|
||||
);
|
||||
let next_failure = feedback.start_at(at + Duration::from_millis(200));
|
||||
next_failure.setup_succeeded_at(at + Duration::from_millis(200));
|
||||
next_failure.finish_at(ScoreOutcome::Timeout, true, at + Duration::from_millis(200));
|
||||
active.transfer_at(0, 1, at + Duration::from_millis(300));
|
||||
let finished_at = now + Duration::from_secs(124);
|
||||
let before = snapshots(&manager, &nodes, &target, finished_at);
|
||||
assert!(before[0].unresolved_failure);
|
||||
active.finish_at(ScoreOutcome::Success, true, finished_at);
|
||||
let after = snapshots(&manager, &nodes, &target, finished_at);
|
||||
assert!(!after[0].unresolved_failure);
|
||||
assert_close(after[0].useful_completed, before[0].useful_completed + 1.0);
|
||||
let baseline = performance_baseline(&after);
|
||||
assert!(normal_eligible(&after[0], baseline));
|
||||
let ordinary = ordinary_selection(&after, &nodes.iter().collect::<Vec<_>>(), Some(0), baseline);
|
||||
assert_eq!(ordinary.index, 0);
|
||||
assert_eq!(ordinary.reason, SelectionReason::InsufficientEvidenceHeld);
|
||||
assert_eq!(
|
||||
manager
|
||||
.score_state()
|
||||
.verification_snapshot_at(
|
||||
"score",
|
||||
&target,
|
||||
&nodes.iter().collect::<Vec<_>>(),
|
||||
finished_at,
|
||||
)
|
||||
.unwrap()
|
||||
.state,
|
||||
ScoreVerificationState::Provisional
|
||||
);
|
||||
assert!(after[0].verification.business.value.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reload_and_eviction_fence_progress_without_disabling_surviving_reporters() {
|
||||
let nodes = [node("survivor"), node("challenger")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = udp_context();
|
||||
let before = Instant::now() - Duration::from_secs(10);
|
||||
for (index, samples) in [4, 5].into_iter().enumerate() {
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[index],
|
||||
&target,
|
||||
samples,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
before,
|
||||
);
|
||||
}
|
||||
let feedback = manager
|
||||
.feedback_for_group_node("score", nodes[0].id, target.clone())
|
||||
.unwrap();
|
||||
let active = feedback.start_at(before + Duration::from_secs(2));
|
||||
active.setup_succeeded_at(before + Duration::from_secs(2));
|
||||
active.transfer_at(1, 1, before + Duration::from_secs(2));
|
||||
let qualified = snapshots(&manager, &nodes, &target, before + Duration::from_secs(2));
|
||||
assert!(normal_eligible(
|
||||
&qualified[0],
|
||||
performance_baseline(&qualified)
|
||||
));
|
||||
let state = manager.score_state();
|
||||
let replacement = GroupManager::with_alive_set_and_score_state(
|
||||
&[group("score", &nodes)],
|
||||
&nodes,
|
||||
None,
|
||||
Arc::clone(&state),
|
||||
);
|
||||
replacement.publish_score_membership();
|
||||
let after = Instant::now() + Duration::from_secs(1);
|
||||
active.transfer_at(0, 1, before + Duration::from_secs(3));
|
||||
let stale = snapshots(&replacement, &nodes, &target, after);
|
||||
assert!(!normal_eligible(&stale[0], performance_baseline(&stale)));
|
||||
active.transfer_at(0, 1, after);
|
||||
let surviving = snapshots(&replacement, &nodes, &target, after);
|
||||
assert!(!normal_eligible(
|
||||
&surviving[0],
|
||||
performance_baseline(&surviving)
|
||||
));
|
||||
assert_close(surviving[0].useful_completed, stale[0].useful_completed);
|
||||
assert!(surviving[0].verification.business.value.is_none());
|
||||
|
||||
let new_feedback = replacement
|
||||
.feedback_for_group_node("score", nodes[0].id, target.clone())
|
||||
.unwrap();
|
||||
let failure = new_feedback.start_at(after + Duration::from_secs(1));
|
||||
failure.setup_succeeded_at(after + Duration::from_secs(1));
|
||||
failure.finish_at(ScoreOutcome::Timeout, true, after + Duration::from_secs(1));
|
||||
active.transfer_at(0, 1, after + Duration::from_secs(2));
|
||||
assert!(
|
||||
!snapshots(
|
||||
&replacement,
|
||||
&nodes,
|
||||
&target,
|
||||
after + Duration::from_secs(2)
|
||||
)[0]
|
||||
.unresolved_failure
|
||||
);
|
||||
|
||||
{
|
||||
let mut inner = state.inner.lock();
|
||||
inner.exact.resize(NonZeroUsize::new(1).unwrap());
|
||||
inner.aggregate.resize(NonZeroUsize::new(2).unwrap());
|
||||
}
|
||||
let evicting = replacement
|
||||
.feedback_for_group_node("score", nodes[1].id, target.clone())
|
||||
.unwrap()
|
||||
.start_at(after + Duration::from_secs(3));
|
||||
let recreated = new_feedback.start_at(after + Duration::from_secs(3));
|
||||
recreated.setup_succeeded_at(after + Duration::from_secs(3));
|
||||
recreated.finish_at(ScoreOutcome::Timeout, true, after + Duration::from_secs(3));
|
||||
let before_late = snapshots(
|
||||
&replacement,
|
||||
&nodes[..1],
|
||||
&target,
|
||||
after + Duration::from_secs(4),
|
||||
);
|
||||
assert!(before_late[0].unresolved_failure);
|
||||
active.transfer_at(0, 1, after + Duration::from_secs(4));
|
||||
active.finish_at(ScoreOutcome::Success, true, after + Duration::from_secs(4));
|
||||
let ignored = snapshots(
|
||||
&replacement,
|
||||
&nodes[..1],
|
||||
&target,
|
||||
after + Duration::from_secs(4),
|
||||
);
|
||||
assert!(ignored[0].unresolved_failure);
|
||||
assert_close(ignored[0].completed, before_late[0].completed);
|
||||
assert_close(ignored[0].useful_completed, before_late[0].useful_completed);
|
||||
assert_eq!(ignored[0].fail_streak, before_late[0].fail_streak);
|
||||
let fresh = new_feedback.start_at(after + Duration::from_secs(5));
|
||||
fresh.setup_succeeded_at(after + Duration::from_secs(5));
|
||||
fresh.transfer_at(1, 1, after + Duration::from_secs(5));
|
||||
assert!(
|
||||
!snapshots(
|
||||
&replacement,
|
||||
&nodes[..1],
|
||||
&target,
|
||||
after + Duration::from_secs(5)
|
||||
)[0]
|
||||
.unresolved_failure
|
||||
);
|
||||
fresh.finish_at(
|
||||
ScoreOutcome::Cancelled,
|
||||
true,
|
||||
after + Duration::from_secs(5),
|
||||
);
|
||||
evicting.finish_at(
|
||||
ScoreOutcome::Cancelled,
|
||||
true,
|
||||
after + Duration::from_secs(5),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn delayed_terminal_bridges_qualification_to_already_observed_newer_rx() {
|
||||
let nodes = [node("delayed"), node("qualified")];
|
||||
let manager = GroupManager::new(&[group("score", &nodes)], &nodes);
|
||||
let target = udp_context();
|
||||
let now = Instant::now();
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[0],
|
||||
&target,
|
||||
4,
|
||||
Duration::from_millis(100),
|
||||
1,
|
||||
now,
|
||||
);
|
||||
let feedback = manager
|
||||
.feedback_for_group_node("score", nodes[0].id, target.clone())
|
||||
.unwrap();
|
||||
let active = feedback.start_at(now + Duration::from_secs(1));
|
||||
active.setup_succeeded_at(now + Duration::from_secs(1));
|
||||
for second in (1..=1801).step_by(30) {
|
||||
active.transfer_at(1, 1, now + Duration::from_secs(second));
|
||||
}
|
||||
let state = manager.score_state();
|
||||
let started = now + Duration::from_secs(1802);
|
||||
let cells = state.start_at(&target, feedback.attributions(), started);
|
||||
train_at(
|
||||
&manager,
|
||||
&nodes[1],
|
||||
&target,
|
||||
5,
|
||||
Duration::from_millis(105),
|
||||
1,
|
||||
now + Duration::from_secs(1869),
|
||||
);
|
||||
active.transfer_at(0, 1, now + Duration::from_secs(1871));
|
||||
let terminal_at = now + Duration::from_secs(1881);
|
||||
let before = snapshots(&manager, &nodes, &target, terminal_at);
|
||||
assert!(!normal_eligible(&before[0], performance_baseline(&before)));
|
||||
|
||||
// RX at +50 was delivered late; RX at +70 alone could not bridge the +60 expiry.
|
||||
let sample = FlowSample {
|
||||
outcome: ScoreOutcome::Success,
|
||||
setup: Some(Duration::ZERO),
|
||||
source: ScoreSource::Traffic,
|
||||
tx: 1,
|
||||
rx: 1,
|
||||
last_rx_at: Some(now + Duration::from_secs(1851)),
|
||||
elapsed: terminal_at.duration_since(started),
|
||||
count_usefulness: true,
|
||||
};
|
||||
state.finish_at(
|
||||
&target,
|
||||
feedback.attributions(),
|
||||
&cells,
|
||||
&sample,
|
||||
terminal_at,
|
||||
);
|
||||
let bridged_at = now + Duration::from_secs(1921);
|
||||
let bridged = snapshots(&manager, &nodes, &target, bridged_at);
|
||||
assert!(bridged[0].useful_completed < 4.0);
|
||||
assert!(normal_eligible(&bridged[0], performance_baseline(&bridged)));
|
||||
let ordinary = ordinary_selection(
|
||||
&bridged,
|
||||
&nodes.iter().collect::<Vec<_>>(),
|
||||
Some(0),
|
||||
performance_baseline(&bridged),
|
||||
);
|
||||
assert_eq!(ordinary.index, 0);
|
||||
let expires_at = now + Duration::from_secs(1931);
|
||||
let before_expiry = snapshots(
|
||||
&manager,
|
||||
&nodes,
|
||||
&target,
|
||||
expires_at - Duration::from_nanos(1),
|
||||
);
|
||||
assert!(normal_eligible(
|
||||
&before_expiry[0],
|
||||
performance_baseline(&before_expiry)
|
||||
));
|
||||
let expired = snapshots(&manager, &nodes, &target, expires_at);
|
||||
assert!(!normal_eligible(
|
||||
&expired[0],
|
||||
performance_baseline(&expired)
|
||||
));
|
||||
active.transfer_at(0, 1, expires_at + Duration::from_secs(1));
|
||||
let gap = snapshots(
|
||||
&manager,
|
||||
&nodes,
|
||||
&target,
|
||||
expires_at + Duration::from_secs(1),
|
||||
);
|
||||
assert!(!normal_eligible(&gap[0], performance_baseline(&gap)));
|
||||
active.finish_at(
|
||||
ScoreOutcome::Cancelled,
|
||||
true,
|
||||
expires_at + Duration::from_secs(1),
|
||||
);
|
||||
}
|
||||
@@ -112,7 +112,7 @@ fn switch_flap_ignores_cross_target_interleaving() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn applied_score_selection_records_switch_flap() {
|
||||
fn ordinary_switch_counts_commits_but_not_first_choice_stay_peek_or_trial() {
|
||||
let nodes = [node("first"), node("second")];
|
||||
let node_refs = [&nodes[0], &nodes[1]];
|
||||
let state = ScorePolicyState::default();
|
||||
@@ -136,20 +136,92 @@ fn applied_score_selection_records_switch_flap() {
|
||||
.put(keys[1].clone(), trained_stats(8.0, 200.0, now));
|
||||
}
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, now), 0);
|
||||
|
||||
inner_update_response(&state, keys[0].clone(), 200.0);
|
||||
inner_update_response(&state, keys[1].clone(), 50.0);
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, now), 1);
|
||||
|
||||
inner_update_response(&state, keys[0].clone(), 50.0);
|
||||
inner_update_response(&state, keys[1].clone(), 200.0);
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, now), 0);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.switch_flap,
|
||||
.ordinary_switch,
|
||||
0
|
||||
);
|
||||
|
||||
inner_update_response(&state, keys[0].clone(), 200.0);
|
||||
inner_update_response(&state, keys[1].clone(), 50.0);
|
||||
let before_peek = state.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(state.peek_rank("score", &context, &node_refs), 1);
|
||||
assert_eq!(
|
||||
state.selection_reason_counts("score", SelectionNetwork::Tcp),
|
||||
before_peek
|
||||
);
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, now), 1);
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, now), 1);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.ordinary_switch,
|
||||
1
|
||||
);
|
||||
|
||||
let expired = now + PERFORMANCE_MAX_AGE + Duration::from_secs(1);
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, expired), 0);
|
||||
let trial = state.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(trial.periodic_explore, 1);
|
||||
assert_eq!(trial.ordinary_switch, 1);
|
||||
state
|
||||
.inner
|
||||
.lock()
|
||||
.selection_reasons
|
||||
.get_mut(&SelectionReasonKey::new("score", SelectionNetwork::Tcp))
|
||||
.unwrap()
|
||||
.insufficient_evidence_held = u64::MAX;
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, expired), 1);
|
||||
assert_eq!(
|
||||
state
|
||||
.selection_reason_counts("score", SelectionNetwork::Tcp)
|
||||
.insufficient_evidence_held,
|
||||
u64::MAX
|
||||
);
|
||||
{
|
||||
let mut inner = state.inner.lock();
|
||||
inner
|
||||
.aggregate
|
||||
.put(keys[0].clone(), trained_stats(8.0, 50.0, expired));
|
||||
inner
|
||||
.aggregate
|
||||
.put(keys[1].clone(), trained_stats(8.0, 200.0, expired));
|
||||
}
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, expired), 0);
|
||||
let switched = state.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(switched.ordinary_switch, 2);
|
||||
assert_eq!(switched.switch_flap, 1);
|
||||
|
||||
{
|
||||
let mut inner = state.inner.lock();
|
||||
inner.aggregate.get_mut(&keys[0]).unwrap().fail_streak = SCORE_FAIL_STREAK_EXCLUDE;
|
||||
let counts = inner
|
||||
.selection_reasons
|
||||
.get_mut(&SelectionReasonKey::new("score", SelectionNetwork::Tcp))
|
||||
.unwrap();
|
||||
counts.ordinary_switch = u64::MAX;
|
||||
}
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, expired), 1);
|
||||
let saturated = state.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(saturated.ordinary_switch, u64::MAX);
|
||||
assert_eq!(saturated.incumbent_ineligible, 1);
|
||||
assert_eq!(saturated.fresh_failure_bypass, 0);
|
||||
{
|
||||
let mut inner = state.inner.lock();
|
||||
inner.aggregate.get_mut(&keys[0]).unwrap().fail_streak = 0;
|
||||
inner.aggregate.get_mut(&keys[1]).unwrap().fail_streak = SCORE_FAIL_STREAK_EXCLUDE;
|
||||
inner
|
||||
.selection_reasons
|
||||
.get_mut(&SelectionReasonKey::new("score", SelectionNetwork::Tcp))
|
||||
.unwrap()
|
||||
.incumbent_ineligible = u64::MAX;
|
||||
}
|
||||
assert_eq!(state.rank_at("score", &context, &node_refs, expired), 0);
|
||||
let saturated = state.selection_reason_counts("score", SelectionNetwork::Tcp);
|
||||
assert_eq!(saturated.incumbent_ineligible, u64::MAX);
|
||||
assert_eq!(saturated.ordinary_switch, u64::MAX);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -272,6 +344,7 @@ fn selection_reason_precedence_is_stable() {
|
||||
Stats {
|
||||
attempts: 257.0,
|
||||
useful_failure: 1.0,
|
||||
failed_at: Some(now),
|
||||
selected_at: 1,
|
||||
..trained_stats(256.0, 100.0, now)
|
||||
},
|
||||
@@ -400,6 +473,7 @@ fn selection_reason_precedence_is_stable() {
|
||||
"bypass",
|
||||
ScoreReasonCounters {
|
||||
fresh_failure_bypass: 1,
|
||||
ordinary_switch: 1,
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
@@ -480,7 +554,10 @@ fn selection_reason_counting_respects_apply_and_filter_boundaries() {
|
||||
+ counts.reliability_winner
|
||||
+ counts.performance_winner
|
||||
+ counts.incumbent_held
|
||||
+ counts.fresh_failure_bypass,
|
||||
+ counts.fresh_failure_bypass
|
||||
+ counts.incumbent_ineligible
|
||||
+ counts.insufficient_evidence_held
|
||||
+ counts.ordinary_switch,
|
||||
0
|
||||
);
|
||||
}
|
||||
@@ -562,10 +639,17 @@ fn selection_reason_counting_respects_apply_and_filter_boundaries() {
|
||||
performance_winner: u64::MAX,
|
||||
incumbent_held: u64::MAX,
|
||||
fresh_failure_bypass: u64::MAX,
|
||||
incumbent_ineligible: u64::MAX,
|
||||
insufficient_evidence_held: u64::MAX,
|
||||
ordinary_switch: u64::MAX,
|
||||
dead_filtered: u64::MAX,
|
||||
switch_flap: u64::MAX,
|
||||
fail_streak_excluded: u64::MAX,
|
||||
explore_backed_off: u64::MAX,
|
||||
carrier_pressure: u64::MAX,
|
||||
carrier_rtt_pressure: u64::MAX,
|
||||
carrier_loss_pressure: u64::MAX,
|
||||
carrier_validation: u64::MAX,
|
||||
};
|
||||
stale_state.inner.lock().selection_reasons.insert(
|
||||
SelectionReasonKey::new("stale", SelectionNetwork::Tcp),
|
||||
@@ -724,10 +808,6 @@ fn score_reason_snapshot_is_sorted_fixed_and_private() {
|
||||
assert_eq!(snapshot[0].tcp, ScoreReasonCounters::default());
|
||||
assert_eq!(snapshot[1].udp, ScoreReasonCounters::default());
|
||||
|
||||
let debug = format!("{snapshot:?}");
|
||||
assert!(!debug.contains("private-node-alpha"));
|
||||
assert!(!debug.contains("private-node-beta"));
|
||||
assert!(!debug.contains("private-target.internal"));
|
||||
let ScoreReasonCounters {
|
||||
cold_explore: _,
|
||||
periodic_explore: _,
|
||||
@@ -735,10 +815,17 @@ fn score_reason_snapshot_is_sorted_fixed_and_private() {
|
||||
performance_winner: _,
|
||||
incumbent_held: _,
|
||||
fresh_failure_bypass: _,
|
||||
incumbent_ineligible: _,
|
||||
insufficient_evidence_held: _,
|
||||
ordinary_switch: _,
|
||||
dead_filtered: _,
|
||||
switch_flap: _,
|
||||
fail_streak_excluded: _,
|
||||
explore_backed_off: _,
|
||||
carrier_pressure: _,
|
||||
carrier_rtt_pressure: _,
|
||||
carrier_loss_pressure: _,
|
||||
carrier_validation: _,
|
||||
} = snapshot[0].tcp;
|
||||
|
||||
let _ = manager.selection_plan_for_target(
|
||||
@@ -748,26 +835,6 @@ fn score_reason_snapshot_is_sorted_fixed_and_private() {
|
||||
let later = manager.score_reason_snapshot();
|
||||
assert_eq!(snapshot[1].tcp.cold_explore, 1);
|
||||
assert_eq!(later[1].tcp.cold_explore, 2);
|
||||
|
||||
let saturated = ScoreReasonCounters {
|
||||
cold_explore: u64::MAX,
|
||||
periodic_explore: u64::MAX,
|
||||
reliability_winner: u64::MAX,
|
||||
performance_winner: u64::MAX,
|
||||
incumbent_held: u64::MAX,
|
||||
fresh_failure_bypass: u64::MAX,
|
||||
dead_filtered: u64::MAX,
|
||||
switch_flap: u64::MAX,
|
||||
fail_streak_excluded: u64::MAX,
|
||||
explore_backed_off: u64::MAX,
|
||||
};
|
||||
state.inner.lock().selection_reasons.insert(
|
||||
SelectionReasonKey::new("z-score", SelectionNetwork::Udp),
|
||||
saturated,
|
||||
);
|
||||
let saturated_snapshot = manager.score_reason_snapshot();
|
||||
assert_eq!(saturated_snapshot[1].udp, saturated);
|
||||
println!("owned score snapshot={snapshot:?} later={later:?} saturated={saturated_snapshot:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -49,7 +49,7 @@ fn idle_terminal_does_not_refresh_old_business_evidence() {
|
||||
let score = score_snapshot(&state.inner.lock(), "score", &target, nodes[0].id, expired);
|
||||
assert_eq!(score.completed, 5.0);
|
||||
assert_eq!(score.useful_completed, 5.0);
|
||||
assert_eq!(score.failures, 0.0);
|
||||
assert_eq!(score.fail_streak, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -19,6 +19,7 @@ pub mod runtime;
|
||||
pub(crate) mod session;
|
||||
mod shared_error;
|
||||
pub mod tls;
|
||||
pub mod transport_quality;
|
||||
pub mod urltest;
|
||||
pub mod util;
|
||||
|
||||
|
||||
@@ -1301,6 +1301,7 @@ async fn connect_transport(
|
||||
let password = node.anytls().unwrap().password.as_deref().unwrap_or("");
|
||||
let auth = authentication_payload(password, padding);
|
||||
let tcp = crate::util::connect_outbound(addr, connect_timeout).await?;
|
||||
let tcp = crate::transport_quality::tcp::ObservedTcp::new(tcp);
|
||||
debug!("AnyTLS: TCP connected to {}", addr);
|
||||
|
||||
let connector = match tls_connector {
|
||||
@@ -1314,11 +1315,12 @@ async fn connect_transport(
|
||||
.sni
|
||||
.clone()
|
||||
.unwrap_or_else(|| node.host().to_string());
|
||||
let tls = tokio::time::timeout(connect_timeout, connector.connect(&server_name, tcp))
|
||||
let mut tls = tokio::time::timeout(connect_timeout, connector.connect(&server_name, tcp))
|
||||
.await
|
||||
.map_err(|_| {
|
||||
anyhow::anyhow!("AnyTLS TLS handshake timed out after {connect_timeout:?}")
|
||||
})??;
|
||||
tls.get_mut().activate();
|
||||
debug!("AnyTLS: TLS handshake completed with {}", addr);
|
||||
let (read, write) = tokio::io::split(crate::tls::BatchRead::new(tls));
|
||||
|
||||
@@ -1359,15 +1361,18 @@ impl AnyTlsHandler {
|
||||
.as_ref()
|
||||
.map(|runtime| runtime.anytls_tls_connector())
|
||||
.transpose()?;
|
||||
dial_session(
|
||||
let dial = dial_session(
|
||||
&node,
|
||||
&label,
|
||||
Duration::from_secs(10),
|
||||
tls_connector,
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
)
|
||||
.await
|
||||
);
|
||||
match runtime {
|
||||
Some(runtime) => runtime.transport_quality().scope(dial).await,
|
||||
None => dial.await,
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1649,15 +1654,17 @@ impl WarmableOutbound for AnyTlsHandler {
|
||||
let inbound_payload_budget = pool.inbound_payload_budget();
|
||||
Self::warm_pool_with(runtime, move || async move {
|
||||
let tls_connector = dial_runtime.anytls_tls_connector()?;
|
||||
dial_session(
|
||||
&node,
|
||||
&addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
)
|
||||
.await
|
||||
dial_runtime
|
||||
.transport_quality()
|
||||
.scope(dial_session(
|
||||
&node,
|
||||
&addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
))
|
||||
.await
|
||||
})
|
||||
.await
|
||||
}
|
||||
@@ -1707,15 +1714,17 @@ impl TcpOutbound for AnyTlsHandler {
|
||||
let inbound_payload_budget = Arc::clone(&inbound_payload_budget);
|
||||
async move {
|
||||
let tls_connector = runtime.anytls_tls_connector()?;
|
||||
dial_session(
|
||||
&node,
|
||||
&addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
)
|
||||
.await
|
||||
runtime
|
||||
.transport_quality()
|
||||
.scope(dial_session(
|
||||
&node,
|
||||
&addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
))
|
||||
.await
|
||||
}
|
||||
},
|
||||
move |session, permit| {
|
||||
@@ -1779,15 +1788,17 @@ impl PacketOutbound for AnyTlsHandler {
|
||||
let inbound_payload_budget = Arc::clone(&inbound_payload_budget);
|
||||
async move {
|
||||
let tls_connector = runtime.anytls_tls_connector()?;
|
||||
dial_session(
|
||||
&node,
|
||||
&addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
)
|
||||
.await
|
||||
runtime
|
||||
.transport_quality()
|
||||
.scope(dial_session(
|
||||
&node,
|
||||
&addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
))
|
||||
.await
|
||||
}
|
||||
},
|
||||
move |session, permit| {
|
||||
@@ -1825,15 +1836,17 @@ impl PacketOutbound for AnyTlsHandler {
|
||||
let tls_connector = dial_runtime.anytls_tls_connector()?;
|
||||
let padding_state = Arc::clone(&padding_state);
|
||||
let inbound_payload_budget = Arc::clone(&inbound_payload_budget);
|
||||
dial_session(
|
||||
dial_node.as_ref(),
|
||||
&dial_addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
)
|
||||
.await
|
||||
dial_runtime
|
||||
.transport_quality()
|
||||
.scope(dial_session(
|
||||
dial_node.as_ref(),
|
||||
&dial_addr,
|
||||
connect_timeout,
|
||||
Some(tls_connector),
|
||||
padding_state,
|
||||
inbound_payload_budget,
|
||||
))
|
||||
.await
|
||||
},
|
||||
)
|
||||
.await
|
||||
|
||||
@@ -63,6 +63,7 @@ use tracing::debug;
|
||||
|
||||
use crate::quic::defrag::Defragmenter;
|
||||
use crate::quic::{QuicClient, QuicConnState, now_secs};
|
||||
use crate::transport_quality::TransportQuality;
|
||||
|
||||
use super::{
|
||||
PacketOutbound, PacketTransport, ProbeableOutbound, ProxyStream, QuicSendToken, TcpOutbound,
|
||||
@@ -415,8 +416,8 @@ impl crate::runtime::QuicRuntimeClient for Hy2Client {
|
||||
self
|
||||
}
|
||||
|
||||
async fn enable_metrics(&self) {
|
||||
self.quic.enable_metrics().await;
|
||||
async fn enable_metrics(&self, quality: Arc<TransportQuality>) {
|
||||
self.quic.enable_metrics(quality).await;
|
||||
}
|
||||
|
||||
async fn force_close(&self) {
|
||||
|
||||
@@ -13,6 +13,7 @@ use honk_config::node::Node;
|
||||
use tracing::debug;
|
||||
|
||||
use crate::quic::{QuicClient, QuicConnState, now_secs, recv_read_exact as read_exact};
|
||||
use crate::transport_quality::TransportQuality;
|
||||
|
||||
use super::addr::SocksAddr as JuiceAddr;
|
||||
use super::{
|
||||
@@ -123,8 +124,8 @@ impl crate::runtime::QuicRuntimeClient for JuicityClient {
|
||||
self
|
||||
}
|
||||
|
||||
async fn enable_metrics(&self) {
|
||||
self.quic.enable_metrics().await;
|
||||
async fn enable_metrics(&self, quality: Arc<TransportQuality>) {
|
||||
self.quic.enable_metrics(quality).await;
|
||||
}
|
||||
|
||||
async fn force_close(&self) {
|
||||
|
||||
@@ -175,6 +175,9 @@ impl ProxyStream {
|
||||
if let Some(tcp) = any.downcast_ref::<tokio::net::TcpStream>() {
|
||||
return Some(tcp.as_raw_fd());
|
||||
}
|
||||
if let Some(tcp) = any.downcast_ref::<crate::transport_quality::tcp::ObservedTcp>() {
|
||||
return Some(tcp.as_raw_fd());
|
||||
}
|
||||
if let Some(tls) = any.downcast_ref::<tokio_boring::SslStream<tokio::net::TcpStream>>() {
|
||||
return Some(tls.get_ref().as_raw_fd());
|
||||
}
|
||||
|
||||
@@ -236,11 +236,12 @@ impl ProxyRegistry {
|
||||
.find(protocol)
|
||||
.ok_or_else(|| anyhow::anyhow!("No handler for protocol {:?}", protocol))?;
|
||||
let stream = generation
|
||||
.scope_dials(
|
||||
entry
|
||||
.tcp
|
||||
.dial_runtime(runtime, target, target_domain, connect_timeout),
|
||||
)
|
||||
.scope_dials(runtime.transport_quality().scope(entry.tcp.dial_runtime(
|
||||
runtime,
|
||||
target,
|
||||
target_domain,
|
||||
connect_timeout,
|
||||
)))
|
||||
.await?;
|
||||
if generation.is_shutdown() {
|
||||
anyhow::bail!("outbound runtime generation shut down during dial");
|
||||
@@ -366,12 +367,16 @@ impl ProxyRegistry {
|
||||
) -> anyhow::Result<Arc<dyn PacketTransport>> {
|
||||
let (runtime, packet) = self.packet_runtime(&generation, node_id, target.port())?;
|
||||
let transport = generation
|
||||
.scope_dials(packet.dial_udp_transport_runtime(
|
||||
runtime,
|
||||
target,
|
||||
target_domain,
|
||||
connect_timeout,
|
||||
))
|
||||
.scope_dials(
|
||||
runtime
|
||||
.transport_quality()
|
||||
.scope(packet.dial_udp_transport_runtime(
|
||||
runtime,
|
||||
target,
|
||||
target_domain,
|
||||
connect_timeout,
|
||||
)),
|
||||
)
|
||||
.await?;
|
||||
if generation.is_shutdown() {
|
||||
anyhow::bail!("outbound runtime generation shut down during UDP dial");
|
||||
@@ -392,11 +397,13 @@ impl ProxyRegistry {
|
||||
) -> anyhow::Result<PreparedUdpTransport> {
|
||||
let (runtime, packet) = self.packet_runtime(&generation, node_id, target.port())?;
|
||||
let prepared = generation
|
||||
.scope_dials(packet.dial_udp_transport_speculative_runtime(
|
||||
runtime,
|
||||
target,
|
||||
target_domain,
|
||||
connect_timeout,
|
||||
.scope_dials(runtime.transport_quality().scope(
|
||||
packet.dial_udp_transport_speculative_runtime(
|
||||
runtime,
|
||||
target,
|
||||
target_domain,
|
||||
connect_timeout,
|
||||
),
|
||||
))
|
||||
.await?;
|
||||
if generation.is_shutdown() {
|
||||
|
||||
@@ -9,6 +9,7 @@ use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use crate::transport_quality::tcp::TcpPressure;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, ReadBuf};
|
||||
use tokio::net::TcpStream;
|
||||
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
|
||||
@@ -39,6 +40,8 @@ type PrologueFuture = Pin<
|
||||
/// prologue (which `dial` completes before returning this type).
|
||||
pub(crate) struct SsStream {
|
||||
write_half: OwnedWriteHalf,
|
||||
pressure: TcpPressure,
|
||||
peer_authenticated: bool,
|
||||
/// Read half, parked inside the pending 2022 prologue future until the
|
||||
/// response header has been consumed.
|
||||
read_half: Option<OwnedReadHalf>,
|
||||
@@ -70,9 +73,12 @@ impl SsStream {
|
||||
recv_cipher: AeadCipher,
|
||||
recv_nonce: Vec<u8>,
|
||||
) -> Self {
|
||||
let pressure = TcpPressure::new(&inner);
|
||||
let (read_half, write_half) = inner.into_split();
|
||||
Self {
|
||||
write_half,
|
||||
pressure,
|
||||
peer_authenticated: true,
|
||||
read_half: Some(read_half),
|
||||
send_cipher,
|
||||
send_nonce,
|
||||
@@ -97,10 +103,13 @@ impl SsStream {
|
||||
send_nonce: Vec<u8>,
|
||||
prologue: Ss2022Prologue,
|
||||
) -> Self {
|
||||
let pressure = TcpPressure::new(&inner);
|
||||
let (read_half, write_half) = inner.into_split();
|
||||
let recv_prologue: PrologueFuture = Box::pin(prologue.run(read_half));
|
||||
Self {
|
||||
write_half,
|
||||
pressure,
|
||||
peer_authenticated: false,
|
||||
read_half: None,
|
||||
send_cipher,
|
||||
send_nonce,
|
||||
@@ -125,10 +134,13 @@ impl SsStream {
|
||||
send_nonce: Vec<u8>,
|
||||
prologue: LegacyPrologue,
|
||||
) -> Self {
|
||||
let pressure = TcpPressure::new(&inner);
|
||||
let (read_half, write_half) = inner.into_split();
|
||||
let recv_prologue: PrologueFuture = Box::pin(prologue.run(read_half));
|
||||
Self {
|
||||
write_half,
|
||||
pressure,
|
||||
peer_authenticated: false,
|
||||
read_half: None,
|
||||
send_cipher,
|
||||
send_nonce,
|
||||
@@ -185,6 +197,10 @@ impl AsyncRead for SsStream {
|
||||
this.recv_nonce = nonce;
|
||||
this.recv_prologue = None;
|
||||
this.prefill_plaintext(&first_payload);
|
||||
if !first_payload.is_empty() {
|
||||
this.peer_authenticated = true;
|
||||
this.pressure.observe(this.write_half.as_ref());
|
||||
}
|
||||
}
|
||||
Poll::Ready(Err(e)) => return Poll::Ready(Err(e)),
|
||||
Poll::Pending => return Poll::Pending,
|
||||
@@ -228,6 +244,8 @@ impl AsyncRead for SsStream {
|
||||
this.carry = rest;
|
||||
}
|
||||
if out_len > 0 {
|
||||
this.peer_authenticated = true;
|
||||
this.pressure.observe(this.write_half.as_ref());
|
||||
out.advance(out_len);
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
@@ -291,6 +309,10 @@ impl AsyncRead for SsStream {
|
||||
tag_len,
|
||||
)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e.to_string()))?;
|
||||
if out_len > 0 {
|
||||
this.peer_authenticated = true;
|
||||
this.pressure.observe(this.write_half.as_ref());
|
||||
}
|
||||
this.plain_start = 0;
|
||||
this.plain_end = out_len;
|
||||
this.carry = rest;
|
||||
@@ -387,6 +409,9 @@ impl SsStream {
|
||||
Poll::Pending => return Poll::Pending,
|
||||
};
|
||||
self.send_off += n;
|
||||
if self.peer_authenticated {
|
||||
self.pressure.observe(self.write_half.as_ref());
|
||||
}
|
||||
}
|
||||
self.send_buf.clear();
|
||||
self.send_off = 0;
|
||||
|
||||
@@ -23,6 +23,7 @@ use tokio::io::{AsyncRead, AsyncWrite, AsyncWriteExt, ReadBuf};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::AsyncReadWrite;
|
||||
use crate::transport_quality::tcp::ObservedTcp;
|
||||
|
||||
/// Connect if needed, then apply TLS and `node.transport` wrapping.
|
||||
pub(crate) async fn wrap_transport(
|
||||
@@ -61,8 +62,8 @@ pub(crate) async fn maybe_tls_wrap(
|
||||
connect_timeout: std::time::Duration,
|
||||
) -> anyhow::Result<Box<dyn AsyncReadWrite>> {
|
||||
match maybe_tls_wrap_concrete(node, tcp, connect_timeout).await? {
|
||||
MaybeTls::Tls(stream) => Ok(Box::new(crate::tls::BatchRead::new(*stream))),
|
||||
MaybeTls::Plain(stream) => Ok(Box::new(stream)),
|
||||
MaybeTls::Tls(stream) => Ok(Box::new(crate::tls::BatchRead::new(stream))),
|
||||
MaybeTls::Plain(stream) => Ok(stream),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,8 +71,8 @@ pub(crate) async fn maybe_tls_wrap(
|
||||
/// Vision direct-copy switch must reach the raw TCP socket under the TLS
|
||||
/// stream once the server abandons the outer TLS session.
|
||||
pub(crate) enum MaybeTls {
|
||||
Tls(Box<crate::tls::TlsStream<TcpStream>>),
|
||||
Plain(TcpStream),
|
||||
Tls(crate::tls::TlsStream<ObservedTcp>),
|
||||
Plain(Box<ObservedTcp>),
|
||||
}
|
||||
|
||||
pub(crate) async fn maybe_tls_wrap_concrete(
|
||||
@@ -98,8 +99,9 @@ pub(crate) async fn maybe_tls_wrap_concrete(
|
||||
let setup = async {
|
||||
let tcp = initial_tcp.await?;
|
||||
let peer = tcp.peer_addr()?;
|
||||
let tcp = ObservedTcp::new(tcp);
|
||||
let chrome = crate::tls::chrome_mode();
|
||||
let tls_stream =
|
||||
let mut tls_stream =
|
||||
match crate::reality::reality_connect_with_key_shares(tcp, &reality, chrome, true)
|
||||
.await
|
||||
{
|
||||
@@ -123,6 +125,7 @@ pub(crate) async fn maybe_tls_wrap_concrete(
|
||||
connect_timeout.min(remaining),
|
||||
)
|
||||
.await?;
|
||||
let tcp = ObservedTcp::new(tcp);
|
||||
crate::reality::reality_connect_with_key_shares(
|
||||
tcp, &reality, chrome, false,
|
||||
)
|
||||
@@ -132,7 +135,8 @@ pub(crate) async fn maybe_tls_wrap_concrete(
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
Ok(MaybeTls::Tls(Box::new(tls_stream)))
|
||||
tls_stream.get_mut().activate();
|
||||
Ok(MaybeTls::Tls(tls_stream))
|
||||
};
|
||||
return tokio::time::timeout_at(deadline, setup)
|
||||
.await
|
||||
@@ -140,14 +144,16 @@ pub(crate) async fn maybe_tls_wrap_concrete(
|
||||
std::io::Error::new(std::io::ErrorKind::TimedOut, "REALITY setup timeout")
|
||||
})?;
|
||||
}
|
||||
let tcp = initial_tcp.await?;
|
||||
let mut tcp = ObservedTcp::new(initial_tcp.await?);
|
||||
if tls.enabled {
|
||||
let connector = crate::tls::build_connector(node)?;
|
||||
let server_name = tls.sni.clone().unwrap_or_else(|| node.host().to_string());
|
||||
let tls_stream = connector.connect(&server_name, tcp).await?;
|
||||
return Ok(MaybeTls::Tls(Box::new(tls_stream)));
|
||||
let mut tls_stream = connector.connect(&server_name, tcp).await?;
|
||||
tls_stream.get_mut().activate();
|
||||
return Ok(MaybeTls::Tls(tls_stream));
|
||||
}
|
||||
Ok(MaybeTls::Plain(tcp))
|
||||
tcp.activate();
|
||||
Ok(MaybeTls::Plain(Box::new(tcp)))
|
||||
}
|
||||
|
||||
/// Upgrade an already-connected (optionally TLS-wrapped) stream to
|
||||
|
||||
@@ -15,6 +15,7 @@ use tracing::debug;
|
||||
|
||||
use crate::quic::defrag::Defragmenter;
|
||||
use crate::quic::{QuicClient, QuicConnState, now_secs, recv_read_exact as read_exact};
|
||||
use crate::transport_quality::TransportQuality;
|
||||
|
||||
use super::addr::{self, SocksAddr};
|
||||
use super::{
|
||||
@@ -405,8 +406,8 @@ impl crate::runtime::QuicRuntimeClient for TuicClient {
|
||||
self
|
||||
}
|
||||
|
||||
async fn enable_metrics(&self) {
|
||||
self.quic.enable_metrics().await;
|
||||
async fn enable_metrics(&self, quality: Arc<TransportQuality>) {
|
||||
self.quic.enable_metrics(quality).await;
|
||||
}
|
||||
|
||||
async fn force_close(&self) {
|
||||
|
||||
@@ -135,15 +135,17 @@ impl VLessHandler {
|
||||
connect_timeout: std::time::Duration,
|
||||
) -> anyhow::Result<Box<dyn AsyncReadWrite>> {
|
||||
let permit = runtime.acquire_vless_carrier()?;
|
||||
self.dial_carrier(
|
||||
&runtime.node,
|
||||
uuid,
|
||||
header,
|
||||
None,
|
||||
connect_timeout,
|
||||
Some(permit),
|
||||
)
|
||||
.await
|
||||
runtime
|
||||
.transport_quality()
|
||||
.scope(self.dial_carrier(
|
||||
&runtime.node,
|
||||
uuid,
|
||||
header,
|
||||
None,
|
||||
connect_timeout,
|
||||
Some(permit),
|
||||
))
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn dial_retained_base(
|
||||
|
||||
@@ -4,9 +4,9 @@ use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
|
||||
use crate::transport_quality::tcp::ObservedTcp;
|
||||
use bytes::{Buf, BytesMut};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::super::encryption::EncryptedStream;
|
||||
use crate::proxy::AsyncReadWrite;
|
||||
@@ -26,7 +26,7 @@ pub(super) trait DirectRead {
|
||||
}
|
||||
}
|
||||
|
||||
impl DirectRead for TcpStream {
|
||||
impl DirectRead for ObservedTcp {
|
||||
fn poll_direct_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
@@ -36,7 +36,7 @@ impl DirectRead for TcpStream {
|
||||
}
|
||||
}
|
||||
|
||||
impl DirectRead for tokio_boring::SslStream<TcpStream> {
|
||||
impl DirectRead for tokio_boring::SslStream<ObservedTcp> {
|
||||
fn poll_direct_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
|
||||
@@ -15,6 +15,8 @@ use quinn::{ClientConfig, Connection, Endpoint, RecvStream, TransportConfig, Var
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::warn;
|
||||
|
||||
use crate::transport_quality::TransportQuality;
|
||||
|
||||
pub mod boring;
|
||||
mod client;
|
||||
mod endpoint;
|
||||
@@ -422,7 +424,7 @@ struct State<C> {
|
||||
conn: Option<(Connection, Arc<C>)>,
|
||||
connections: Vec<TrackedConnection<C>>,
|
||||
next_connection_id: u64,
|
||||
metrics_enabled: bool,
|
||||
quality: Option<Arc<TransportQuality>>,
|
||||
|
||||
/// Set by [`QuicClient::force_close`]: future dials fail instead of
|
||||
/// re-dialing into a closed client.
|
||||
|
||||
@@ -8,6 +8,8 @@ use anyhow::{Context as _, anyhow};
|
||||
use quinn::{ClientConfig, Connection, Endpoint, VarInt};
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::transport_quality::TransportQuality;
|
||||
|
||||
use super::endpoint::{clamp_quic_payload_size, client_endpoint_with_mtu};
|
||||
use super::metrics::{QuicClientConnectionMonitor, spawn_quic_client_connection_monitor};
|
||||
use super::{
|
||||
@@ -105,7 +107,7 @@ impl<C: Send + Sync + 'static> QuicClient<C> {
|
||||
conn: None,
|
||||
connections: Vec::new(),
|
||||
next_connection_id: 1,
|
||||
metrics_enabled: false,
|
||||
quality: None,
|
||||
closed: false,
|
||||
})),
|
||||
}
|
||||
@@ -140,14 +142,14 @@ impl<C: Send + Sync + 'static> QuicClient<C> {
|
||||
self.endpoint_factory = Some(Arc::new(factory));
|
||||
self
|
||||
}
|
||||
pub(crate) async fn enable_metrics(&self)
|
||||
pub(crate) async fn enable_metrics(&self, quality: Arc<TransportQuality>)
|
||||
where
|
||||
C: QuicConnState,
|
||||
{
|
||||
let mut state = self.state.lock().await;
|
||||
state.metrics_enabled = true;
|
||||
state.quality = Some(Arc::clone(&quality));
|
||||
for tracked in &state.connections {
|
||||
tracked.monitor.enable_metrics();
|
||||
tracked.monitor.enable_metrics(Arc::clone(&quality));
|
||||
if let Some(ctx) = tracked.state.upgrade() {
|
||||
ctx.enable_telemetry();
|
||||
}
|
||||
@@ -209,7 +211,7 @@ impl<C: Send + Sync + 'static> QuicClient<C> {
|
||||
{
|
||||
let conn = conn.clone();
|
||||
let ctx = Arc::clone(ctx);
|
||||
let metrics_enabled = state.metrics_enabled;
|
||||
let metrics_enabled = state.quality.is_some();
|
||||
drop(state);
|
||||
// The QUIC connection is already admitted and reusable; time the
|
||||
// logical stream before its protocol open can block or cancel.
|
||||
@@ -297,7 +299,7 @@ impl<C: Send + Sync + 'static> QuicClient<C> {
|
||||
}
|
||||
};
|
||||
let ctx = Arc::new(ctx);
|
||||
if state.metrics_enabled {
|
||||
if state.quality.is_some() {
|
||||
on_publish(ctx.as_ref(), &conn);
|
||||
}
|
||||
close_guard.disarm();
|
||||
@@ -309,7 +311,7 @@ impl<C: Send + Sync + 'static> QuicClient<C> {
|
||||
Arc::clone(&self.flow_control_profiles),
|
||||
ipv6,
|
||||
owner.clone(),
|
||||
state.metrics_enabled,
|
||||
state.quality.clone(),
|
||||
));
|
||||
state.connections.push(TrackedConnection {
|
||||
id,
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, LazyLock, Weak};
|
||||
use std::time::Instant;
|
||||
|
||||
use parking_lot::Mutex as SyncMutex;
|
||||
use quinn::Connection;
|
||||
|
||||
use crate::transport_quality::{CarrierSample, CarrierSampler, TransportQuality};
|
||||
|
||||
use super::flow_control::{
|
||||
AdaptiveFlowSampler, apply_flow_control_profile, seed_flow_control_profile,
|
||||
};
|
||||
@@ -350,17 +354,86 @@ pub fn monitor_quic_connection(conn: &Connection) -> QuicConnectionMonitor {
|
||||
}
|
||||
}
|
||||
|
||||
struct QuicCarrierPressure {
|
||||
quality: Arc<TransportQuality>,
|
||||
remote: SocketAddr,
|
||||
sampler: CarrierSampler,
|
||||
}
|
||||
|
||||
impl QuicCarrierPressure {
|
||||
fn new(quality: Arc<TransportQuality>, mut remote: SocketAddr) -> Self {
|
||||
remote.set_ip(remote.ip().to_canonical());
|
||||
Self {
|
||||
sampler: CarrierSampler::new(Arc::clone(&quality), remote.is_ipv6()),
|
||||
quality,
|
||||
remote,
|
||||
}
|
||||
}
|
||||
|
||||
fn observe(&mut self, stats: &quinn::ConnectionStats, mut remote: SocketAddr, at: Instant) {
|
||||
remote.set_ip(remote.ip().to_canonical());
|
||||
if remote != self.remote {
|
||||
self.remote = remote;
|
||||
self.sampler = CarrierSampler::new(Arc::clone(&self.quality), remote.is_ipv6());
|
||||
}
|
||||
// Confirmation and runtime admission each start a fresh carrier baseline.
|
||||
if !self.quality.is_enabled() || stats.frame_rx.handshake_done == 0 {
|
||||
self.sampler.reset();
|
||||
return;
|
||||
}
|
||||
let Some(transmitted) = stats
|
||||
.path
|
||||
.sent_packets
|
||||
.checked_sub(stats.path.sent_plpmtud_probes)
|
||||
else {
|
||||
self.sampler.reset();
|
||||
return;
|
||||
};
|
||||
self.sampler.observe(CarrierSample {
|
||||
at,
|
||||
rtt: Some(stats.path.rtt),
|
||||
acknowledged: Some(stats.path.acked_ack_eliciting_packets),
|
||||
transmitted: Some(transmitted),
|
||||
// Quinn already excludes PLPMTUD losses; do not subtract them twice.
|
||||
lost: Some(stats.path.lost_packets),
|
||||
lost_bytes: Some(stats.path.lost_bytes),
|
||||
// These are ACKed stream bytes, not all offered UDP payload bytes.
|
||||
tx_bytes: Some(stats.flow_control.sent_bytes),
|
||||
rx_bytes: Some(stats.flow_control.received_bytes),
|
||||
tx_datagrams: Some(stats.frame_tx.datagram),
|
||||
rx_datagrams: Some(stats.frame_rx.datagram),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct QuicClientConnectionMonitor {
|
||||
conn: Connection,
|
||||
metrics_enabled: Arc<AtomicBool>,
|
||||
tracker: Arc<SyncMutex<QuicMetricTracker>>,
|
||||
pressure: Arc<SyncMutex<Option<QuicCarrierPressure>>>,
|
||||
task: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl QuicClientConnectionMonitor {
|
||||
pub(super) fn enable_metrics(&self) {
|
||||
pub(super) fn enable_metrics(&self, quality: Arc<TransportQuality>) {
|
||||
self.metrics_enabled.store(true, Ordering::Release);
|
||||
self.tracker.lock().sample(self.conn.stats());
|
||||
let at = Instant::now();
|
||||
let stats = {
|
||||
let mut tracker = self.tracker.lock();
|
||||
let stats = self.conn.stats();
|
||||
tracker.sample(stats);
|
||||
stats
|
||||
};
|
||||
let mut pressure = self.pressure.lock();
|
||||
if pressure
|
||||
.as_ref()
|
||||
.is_none_or(|current| !Arc::ptr_eq(¤t.quality, &quality))
|
||||
{
|
||||
let remote = self.conn.remote_address();
|
||||
let mut sampler = QuicCarrierPressure::new(quality, remote);
|
||||
sampler.observe(&stats, remote, at);
|
||||
*pressure = Some(sampler);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -376,7 +449,7 @@ pub(super) fn spawn_quic_client_connection_monitor<C: Send + Sync + 'static>(
|
||||
profiles: Arc<AdaptiveFlowProfiles>,
|
||||
ipv6: bool,
|
||||
owner: Weak<C>,
|
||||
metrics_enabled: bool,
|
||||
quality: Option<Arc<TransportQuality>>,
|
||||
) -> QuicClientConnectionMonitor {
|
||||
let family = usize::from(ipv6);
|
||||
let initial_stats = conn.stats();
|
||||
@@ -387,6 +460,13 @@ pub(super) fn spawn_quic_client_connection_monitor<C: Send + Sync + 'static>(
|
||||
apply_flow_control_profile(&conn, &initial_stats, profile);
|
||||
}
|
||||
let mut sampler = AdaptiveFlowSampler::new(&initial_stats, path_now_millis());
|
||||
let metrics_enabled = quality.is_some();
|
||||
let pressure = Arc::new(SyncMutex::new(quality.map(|quality| {
|
||||
let remote = conn.remote_address();
|
||||
let mut sampler = QuicCarrierPressure::new(quality, remote);
|
||||
sampler.observe(&initial_stats, remote, Instant::now());
|
||||
sampler
|
||||
})));
|
||||
let tracker = Arc::new(SyncMutex::new(QuicMetricTracker::default()));
|
||||
if metrics_enabled {
|
||||
tracker.lock().sample(initial_stats);
|
||||
@@ -395,6 +475,7 @@ pub(super) fn spawn_quic_client_connection_monitor<C: Send + Sync + 'static>(
|
||||
let task_conn = conn.clone();
|
||||
let task_tracker = Arc::clone(&tracker);
|
||||
let task_enabled = Arc::clone(&enabled);
|
||||
let task_pressure = Arc::clone(&pressure);
|
||||
let task = tokio::spawn(async move {
|
||||
let mut ticker = tokio::time::interval_at(
|
||||
tokio::time::Instant::now() + QUIC_SAMPLE_INTERVAL,
|
||||
@@ -408,6 +489,7 @@ pub(super) fn spawn_quic_client_connection_monitor<C: Send + Sync + 'static>(
|
||||
if owner.upgrade().is_none() {
|
||||
break;
|
||||
}
|
||||
let at = Instant::now();
|
||||
let stats = task_conn.stats();
|
||||
{
|
||||
let mut profiles = profiles.lock();
|
||||
@@ -418,6 +500,11 @@ pub(super) fn spawn_quic_client_connection_monitor<C: Send + Sync + 'static>(
|
||||
if task_enabled.load(Ordering::Acquire) {
|
||||
task_tracker.lock().sample(stats);
|
||||
}
|
||||
if task_conn.close_reason().is_none()
|
||||
&& let Some(pressure) = task_pressure.lock().as_mut()
|
||||
{
|
||||
pressure.observe(&stats, task_conn.remote_address(), at);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -432,6 +519,275 @@ pub(super) fn spawn_quic_client_connection_monitor<C: Send + Sync + 'static>(
|
||||
conn,
|
||||
metrics_enabled: enabled,
|
||||
tracker,
|
||||
pressure,
|
||||
task,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
use crate::transport_quality::PressureReason;
|
||||
|
||||
fn loss_stats(tick: u64) -> quinn::ConnectionStats {
|
||||
let mut stats = quinn::ConnectionStats::default();
|
||||
stats.frame_rx.handshake_done = 1;
|
||||
stats.path.rtt = Duration::from_millis(20);
|
||||
stats.path.acked_ack_eliciting_packets = 32 * tick;
|
||||
stats.path.sent_packets = 64 * tick;
|
||||
stats.path.sent_plpmtud_probes = 32 * tick;
|
||||
stats.path.lost_plpmtud_probes = 32 * tick;
|
||||
stats.path.lost_packets = 3 * tick;
|
||||
stats.path.lost_bytes = 3600 * tick;
|
||||
stats.frame_tx.datagram = 32 * tick;
|
||||
stats
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_datagram_pressure_excludes_probe_sends_not_probe_losses() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=2 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
pressure.observe(&loss_stats(3), remote, now + Duration::from_secs(3));
|
||||
let event = quality.snapshot()[0].unwrap();
|
||||
assert_eq!(event.reason, PressureReason::Loss);
|
||||
assert_eq!(event.observed_at, now + Duration::from_secs(3));
|
||||
assert!(quality.snapshot()[1].is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn heartbeat_ack_and_probe_only_traffic_cannot_publish_pressure() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=12 {
|
||||
let mut stats = loss_stats(tick);
|
||||
// Even one tiny heartbeat each second is below the TUIC idle fence.
|
||||
stats.frame_tx.datagram = tick;
|
||||
stats.flow_control.sent_bytes = 64 * tick;
|
||||
stats.udp_tx.bytes = 65536 * tick;
|
||||
stats.frame_tx.ping = tick;
|
||||
stats.frame_rx.acks = 64 * tick;
|
||||
stats.path.rtt = Duration::from_millis(if tick < 5 { 20 } else { 80 });
|
||||
pressure.observe(&stats, remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot().iter().all(Option::is_none));
|
||||
for tick in 13..=24 {
|
||||
let mut stats = loss_stats(tick);
|
||||
stats.frame_tx.datagram = 12;
|
||||
stats.flow_control.sent_bytes = 64 * 12;
|
||||
stats.path.sent_packets = stats.path.sent_plpmtud_probes;
|
||||
stats.path.lost_packets = 0;
|
||||
stats.path.lost_bytes = 0;
|
||||
pressure.observe(&stats, remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot().iter().all(Option::is_none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn receive_only_datagrams_do_not_turn_ack_losses_into_send_pressure() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=8 {
|
||||
let mut stats = loss_stats(tick);
|
||||
stats.frame_tx.datagram = 0;
|
||||
stats.frame_rx.datagram = 32 * tick;
|
||||
pressure.observe(&stats, remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot().iter().all(Option::is_none));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn activation_and_handshake_confirmation_discard_old_history() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=4 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
quality.enable();
|
||||
for tick in 5..=9 {
|
||||
let mut stats = loss_stats(tick);
|
||||
stats.frame_rx.handshake_done = 0;
|
||||
pressure.observe(&stats, remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
for tick in 10..=12 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
pressure.observe(&loss_stats(13), remote, now + Duration::from_secs(13));
|
||||
assert_eq!(
|
||||
quality.snapshot()[0].unwrap().observed_at,
|
||||
now + Duration::from_secs(13)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_activation_reseeds_a_confirmed_carrier() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=2 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
quality.enable();
|
||||
for tick in 3..=5 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
pressure.observe(&loss_stats(6), remote, now + Duration::from_secs(6));
|
||||
assert_eq!(
|
||||
quality.snapshot()[0].unwrap().observed_at,
|
||||
now + Duration::from_secs(6)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_probe_send_counters_restart_the_observation_window() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=2 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
let mut invalid = loss_stats(3);
|
||||
invalid.path.sent_packets = invalid.path.sent_plpmtud_probes - 1;
|
||||
pressure.observe(&invalid, remote, now + Duration::from_secs(3));
|
||||
for tick in 4..=6 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
pressure.observe(&loss_stats(7), remote, now + Duration::from_secs(7));
|
||||
assert_eq!(
|
||||
quality.snapshot()[0].unwrap().observed_at,
|
||||
now + Duration::from_secs(7)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_ipv4_retains_current_pressure_streak() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let mapped = "[::ffff:127.0.0.1]:443".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=2 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
pressure.observe(&loss_stats(3), mapped, now + Duration::from_secs(3));
|
||||
assert_eq!(
|
||||
quality.snapshot()[0].unwrap().observed_at,
|
||||
now + Duration::from_secs(3)
|
||||
);
|
||||
assert!(quality.snapshot()[1].is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_tuple_changes_reseed_and_switch_family() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let remote = "127.0.0.1:443".parse().unwrap();
|
||||
let next_port = "127.0.0.1:444".parse().unwrap();
|
||||
let ipv6 = "[::1]:444".parse().unwrap();
|
||||
let mut pressure = QuicCarrierPressure::new(Arc::clone(&quality), remote);
|
||||
let now = Instant::now();
|
||||
for tick in 0..=2 {
|
||||
pressure.observe(&loss_stats(tick), remote, now + Duration::from_secs(tick));
|
||||
}
|
||||
for tick in 3..=5 {
|
||||
pressure.observe(
|
||||
&loss_stats(tick),
|
||||
next_port,
|
||||
now + Duration::from_secs(tick),
|
||||
);
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
pressure.observe(&loss_stats(6), next_port, now + Duration::from_secs(6));
|
||||
let first = quality.snapshot()[0].unwrap().observed_at;
|
||||
assert_eq!(first, now + Duration::from_secs(6));
|
||||
for tick in 7..=9 {
|
||||
pressure.observe(&loss_stats(tick), ipv6, now + Duration::from_secs(tick));
|
||||
assert!(quality.snapshot()[1].is_none());
|
||||
}
|
||||
pressure.observe(&loss_stats(10), ipv6, now + Duration::from_secs(10));
|
||||
assert_eq!(
|
||||
quality.snapshot()[1].unwrap().observed_at,
|
||||
now + Duration::from_secs(10)
|
||||
);
|
||||
assert_eq!(quality.snapshot()[0].unwrap().observed_at, first);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn repeated_monitor_activation_preserves_current_pressure_streak() {
|
||||
use crate::quic::{self, testutil};
|
||||
|
||||
let (server_endpoint, remote) = testutil::server_endpoint(&[b"h3"], true).unwrap();
|
||||
let accepted = tokio::spawn({
|
||||
let endpoint = server_endpoint.clone();
|
||||
async move { endpoint.accept().await.unwrap().await.unwrap() }
|
||||
});
|
||||
let mut node = honk_config::node::Node {
|
||||
outbound: honk_config::node::OutboundConfig::Hysteria2(Default::default()),
|
||||
..Default::default()
|
||||
};
|
||||
node.tls_mut().unwrap().skip_cert_verify = true;
|
||||
let config = quic::client_config(&node, &[b"h3"], quic::QuicClientOptions::default())
|
||||
.await
|
||||
.unwrap();
|
||||
let endpoint = quic::client_endpoint(false).unwrap();
|
||||
let conn = endpoint
|
||||
.connect_with(config, remote, "localhost")
|
||||
.unwrap()
|
||||
.await
|
||||
.unwrap();
|
||||
let server = accepted.await.unwrap();
|
||||
let owner = Arc::new(());
|
||||
let monitor = spawn_quic_client_connection_monitor(
|
||||
conn,
|
||||
Arc::new(AdaptiveFlowProfiles::default()),
|
||||
false,
|
||||
Arc::downgrade(&owner),
|
||||
None,
|
||||
);
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
monitor.enable_metrics(Arc::clone(&quality));
|
||||
let now = Instant::now() + Duration::from_secs(20);
|
||||
for tick in 0..=3 {
|
||||
monitor.enable_metrics(Arc::clone(&quality));
|
||||
monitor.pressure.lock().as_mut().unwrap().observe(
|
||||
&loss_stats(tick),
|
||||
remote,
|
||||
now + Duration::from_secs(tick),
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
quality.snapshot()[0].unwrap().observed_at,
|
||||
now + Duration::from_secs(3)
|
||||
);
|
||||
drop(monitor);
|
||||
server.close(quinn::VarInt::from_u32(0), b"test complete");
|
||||
endpoint.close(quinn::VarInt::from_u32(0), b"test complete");
|
||||
server_endpoint.close(quinn::VarInt::from_u32(0), b"test complete");
|
||||
}
|
||||
}
|
||||
@@ -52,7 +52,12 @@ pub enum GenerationRuntime {
|
||||
}
|
||||
|
||||
impl GenerationRuntime {
|
||||
pub(crate) fn build(self, node: &Node, metrics_enabled: bool) -> ProtocolRuntime {
|
||||
pub(crate) fn build(
|
||||
self,
|
||||
node: &Node,
|
||||
metrics_enabled: bool,
|
||||
quality: Arc<crate::transport_quality::TransportQuality>,
|
||||
) -> ProtocolRuntime {
|
||||
match self {
|
||||
Self::None => ProtocolRuntime::None,
|
||||
Self::AnyTls => ProtocolRuntime::AnyTls(AnyTlsRuntime::new()),
|
||||
@@ -65,7 +70,7 @@ impl GenerationRuntime {
|
||||
let _ = node;
|
||||
ProtocolRuntime::None
|
||||
}
|
||||
Self::Quic => ProtocolRuntime::Quic(QuicRuntime::new(metrics_enabled)),
|
||||
Self::Quic => ProtocolRuntime::Quic(QuicRuntime::new(metrics_enabled, quality)),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -92,8 +97,8 @@ pub enum ProtocolRuntime {
|
||||
#[async_trait::async_trait]
|
||||
pub trait QuicRuntimeClient: Send + Sync + 'static {
|
||||
fn into_erased(self: Arc<Self>) -> Arc<dyn std::any::Any + Send + Sync>;
|
||||
/// Start aggregate telemetry for a persistent QUIC client.
|
||||
async fn enable_metrics(&self) {}
|
||||
/// Activate persistent-carrier telemetry without reporting business outcomes.
|
||||
async fn enable_metrics(&self, _quality: Arc<crate::transport_quality::TransportQuality>) {}
|
||||
/// Close the cached connection and endpoint, awaiting any in-flight
|
||||
/// dial so its late-arriving connection is closed too.
|
||||
async fn force_close(&self);
|
||||
@@ -111,6 +116,7 @@ pub trait QuicRuntimeClient: Send + Sync + 'static {
|
||||
pub struct QuicRuntime {
|
||||
state: tokio::sync::Mutex<QuicRuntimeState>,
|
||||
flow_control_profiles: Arc<crate::quic::AdaptiveFlowProfiles>,
|
||||
transport_quality: Arc<crate::transport_quality::TransportQuality>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -126,13 +132,17 @@ impl std::fmt::Debug for QuicRuntime {
|
||||
}
|
||||
}
|
||||
impl QuicRuntime {
|
||||
pub(crate) fn new(metrics_enabled: bool) -> Self {
|
||||
pub(crate) fn new(
|
||||
metrics_enabled: bool,
|
||||
transport_quality: Arc<crate::transport_quality::TransportQuality>,
|
||||
) -> Self {
|
||||
Self {
|
||||
flow_control_profiles: Arc::new(crate::quic::AdaptiveFlowProfiles::default()),
|
||||
state: tokio::sync::Mutex::new(QuicRuntimeState {
|
||||
metrics_enabled,
|
||||
..Default::default()
|
||||
}),
|
||||
transport_quality,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -158,7 +168,9 @@ impl QuicRuntime {
|
||||
}
|
||||
let client = build().await?;
|
||||
if state.metrics_enabled {
|
||||
client.enable_metrics().await;
|
||||
client
|
||||
.enable_metrics(Arc::clone(&self.transport_quality))
|
||||
.await;
|
||||
}
|
||||
state.client = Some(Arc::clone(&client) as Arc<dyn QuicRuntimeClient>);
|
||||
Ok(client)
|
||||
@@ -183,12 +195,16 @@ impl QuicRuntime {
|
||||
.downcast::<T>()
|
||||
.map_err(|_| anyhow::anyhow!("QUIC client slot type mismatch"))?;
|
||||
if state.metrics_enabled {
|
||||
client.enable_metrics().await;
|
||||
client
|
||||
.enable_metrics(Arc::clone(&self.transport_quality))
|
||||
.await;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if state.metrics_enabled {
|
||||
client.enable_metrics().await;
|
||||
client
|
||||
.enable_metrics(Arc::clone(&self.transport_quality))
|
||||
.await;
|
||||
}
|
||||
state.client = Some(client as Arc<dyn QuicRuntimeClient>);
|
||||
Ok(())
|
||||
@@ -357,6 +373,7 @@ pub struct NodeRuntime {
|
||||
pub node: Arc<Node>,
|
||||
pub udp_capable: bool,
|
||||
pub runtime: ProtocolRuntime,
|
||||
transport_quality: Arc<crate::transport_quality::TransportQuality>,
|
||||
/// One-shot runtime outside any generation (see [`Self::ephemeral`]).
|
||||
/// Session protocols skip their standby janitor for these: there is no
|
||||
/// long-lived owner to keep warm state for, only [`Self::close`] to
|
||||
@@ -438,16 +455,18 @@ impl NodeRuntime {
|
||||
node: &Node,
|
||||
#[cfg(any(feature = "rprx", test))] vless_carriers: Arc<tokio::sync::Semaphore>,
|
||||
) -> Arc<Self> {
|
||||
let transport_quality = Arc::new(crate::transport_quality::TransportQuality::default());
|
||||
Arc::new(Self {
|
||||
node: Arc::new(node.clone()),
|
||||
udp_capable: (crate::descriptor::descriptor(node.protocol()).supports_udp)(node),
|
||||
runtime: crate::descriptor::descriptor(node.protocol())
|
||||
.generation_runtime
|
||||
.build(node, false),
|
||||
.build(node, false, Arc::clone(&transport_quality)),
|
||||
ephemeral: true,
|
||||
warm_retention: Arc::new(tokio::sync::Mutex::new(0)),
|
||||
#[cfg(any(feature = "rprx", test))]
|
||||
vless_carriers,
|
||||
transport_quality,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -493,6 +512,11 @@ impl NodeRuntime {
|
||||
self.ephemeral
|
||||
}
|
||||
|
||||
/// Advisory evidence belongs to this runtime, not merely its reusable node ID.
|
||||
pub fn transport_quality(&self) -> Arc<crate::transport_quality::TransportQuality> {
|
||||
Arc::clone(&self.transport_quality)
|
||||
}
|
||||
|
||||
pub(crate) async fn retain_warm(self: &Arc<Self>, reason: WarmRetention) -> WarmAttempt {
|
||||
let mut retention = Arc::clone(&self.warm_retention).lock_owned().await;
|
||||
let bit = reason.bit();
|
||||
@@ -991,19 +1015,24 @@ impl OutboundRuntimeRegistry {
|
||||
reused.insert(node.id);
|
||||
runtime
|
||||
}
|
||||
None => Arc::new(NodeRuntime {
|
||||
node: Arc::new(node.clone()),
|
||||
udp_capable: (crate::descriptor::descriptor(node.protocol()).supports_udp)(
|
||||
node,
|
||||
),
|
||||
runtime: crate::descriptor::descriptor(node.protocol())
|
||||
.generation_runtime
|
||||
.build(node, true),
|
||||
ephemeral: false,
|
||||
warm_retention: Arc::new(tokio::sync::Mutex::new(0)),
|
||||
#[cfg(any(feature = "rprx", test))]
|
||||
vless_carriers: Arc::clone(&vless_carrier_semaphore),
|
||||
}),
|
||||
None => {
|
||||
let transport_quality =
|
||||
Arc::new(crate::transport_quality::TransportQuality::default());
|
||||
Arc::new(NodeRuntime {
|
||||
node: Arc::new(node.clone()),
|
||||
udp_capable: (crate::descriptor::descriptor(node.protocol()).supports_udp)(
|
||||
node,
|
||||
),
|
||||
runtime: crate::descriptor::descriptor(node.protocol())
|
||||
.generation_runtime
|
||||
.build(node, true, Arc::clone(&transport_quality)),
|
||||
transport_quality,
|
||||
ephemeral: false,
|
||||
warm_retention: Arc::new(tokio::sync::Mutex::new(0)),
|
||||
#[cfg(any(feature = "rprx", test))]
|
||||
vless_carriers: Arc::clone(&vless_carrier_semaphore),
|
||||
})
|
||||
}
|
||||
};
|
||||
map.insert(node.id, runtime);
|
||||
}
|
||||
|
||||
@@ -493,7 +493,7 @@ fn build_reusing_ignores_parse_timestamps() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn speculative_quic_publish_keeps_a_concurrent_incumbent() {
|
||||
let runtime = QuicRuntime::new(true);
|
||||
let runtime = QuicRuntime::new(true, Arc::default());
|
||||
let incumbent: Arc<FakeQuicClient> = runtime
|
||||
.client(|| async { Ok(Arc::new(FakeQuicClient::default())) })
|
||||
.await
|
||||
@@ -514,7 +514,7 @@ async fn speculative_quic_publish_keeps_a_concurrent_incumbent() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_quic_publish_before_slot_lock_changes_nothing() {
|
||||
let runtime = Arc::new(QuicRuntime::new(true));
|
||||
let runtime = Arc::new(QuicRuntime::new(true, Arc::default()));
|
||||
let state_guard = runtime.state.lock().await;
|
||||
let detached = Arc::new(FakeQuicClient::default());
|
||||
let detached_weak = Arc::downgrade(&detached);
|
||||
@@ -586,7 +586,7 @@ async fn cancelled_last_quic_release_still_clears_the_client_slot() {
|
||||
|
||||
#[tokio::test]
|
||||
async fn quic_runtime_close_covers_client_and_rejects_new_builds() {
|
||||
let runtime = QuicRuntime::new(true);
|
||||
let runtime = QuicRuntime::new(true, Arc::default());
|
||||
let client: Arc<FakeQuicClient> = runtime
|
||||
.client(|| async { Ok(Arc::new(FakeQuicClient::default())) })
|
||||
.await
|
||||
|
||||
@@ -0,0 +1,251 @@
|
||||
//! Advisory pressure on one node-to-proxy carrier, never business-flow outcomes.
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use parking_lot::Mutex;
|
||||
|
||||
pub(crate) mod tcp;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum PressureReason {
|
||||
Rtt,
|
||||
Loss,
|
||||
Both,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct TransportPressure {
|
||||
pub observed_at: Instant,
|
||||
pub reason: PressureReason,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TransportQuality {
|
||||
enabled: AtomicBool,
|
||||
pressure: Mutex<[Option<TransportPressure>; 2]>,
|
||||
}
|
||||
|
||||
tokio::task_local! {
|
||||
static CURRENT_QUALITY: Arc<TransportQuality>;
|
||||
}
|
||||
|
||||
impl TransportQuality {
|
||||
/// Enable collection only when a Score authority binds this runtime.
|
||||
pub fn enable(&self) {
|
||||
self.enabled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub(crate) fn is_enabled(&self) -> bool {
|
||||
self.enabled.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> [Option<TransportPressure>; 2] {
|
||||
*self.pressure.lock()
|
||||
}
|
||||
|
||||
/// Bind physical construction, not a logical stream's later I/O polls.
|
||||
/// Spawned factories must enter this scope using their captured runtime.
|
||||
pub async fn scope<F: Future>(self: Arc<Self>, future: F) -> F::Output {
|
||||
CURRENT_QUALITY.scope(self, future).await
|
||||
}
|
||||
|
||||
pub(crate) fn current() -> Option<Arc<Self>> {
|
||||
CURRENT_QUALITY.try_with(Arc::clone).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn report(&self, ipv6: bool, reason: PressureReason, now: Instant) {
|
||||
if !self.is_enabled() {
|
||||
return;
|
||||
}
|
||||
let mut slots = self.pressure.lock();
|
||||
let slot = &mut slots[usize::from(ipv6)];
|
||||
if slot.is_some_and(|previous| {
|
||||
now.saturating_duration_since(previous.observed_at) < Duration::from_secs(30)
|
||||
}) {
|
||||
return;
|
||||
}
|
||||
*slot = Some(TransportPressure {
|
||||
observed_at: now,
|
||||
reason,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct CarrierSample {
|
||||
pub at: Instant,
|
||||
pub rtt: Option<Duration>,
|
||||
pub acknowledged: Option<u64>,
|
||||
pub transmitted: Option<u64>,
|
||||
pub lost: Option<u64>,
|
||||
pub lost_bytes: Option<u64>,
|
||||
pub tx_bytes: Option<u64>,
|
||||
pub rx_bytes: Option<u64>,
|
||||
pub tx_datagrams: Option<u64>,
|
||||
pub rx_datagrams: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct Episode {
|
||||
suspect: u8,
|
||||
normal: u8,
|
||||
latched: bool,
|
||||
}
|
||||
|
||||
impl Episode {
|
||||
fn observe(&mut self, pressure: Option<bool>) -> bool {
|
||||
match pressure {
|
||||
None => {
|
||||
self.suspect = 0;
|
||||
self.normal = 0;
|
||||
}
|
||||
Some(false) => {
|
||||
self.suspect = 0;
|
||||
self.normal = (self.normal + 1).min(2);
|
||||
if self.normal == 2 {
|
||||
self.latched = false;
|
||||
}
|
||||
}
|
||||
Some(true) => {
|
||||
self.normal = 0;
|
||||
self.suspect = (self.suspect + 1).min(3);
|
||||
if self.suspect == 3 && !self.latched {
|
||||
self.latched = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct CarrierSampler {
|
||||
quality: Arc<TransportQuality>,
|
||||
ipv6: bool,
|
||||
previous: Option<CarrierSample>,
|
||||
baseline: Duration,
|
||||
trained: u8,
|
||||
rtt: Episode,
|
||||
loss: Episode,
|
||||
}
|
||||
|
||||
impl CarrierSampler {
|
||||
pub(crate) fn new(quality: Arc<TransportQuality>, ipv6: bool) -> Self {
|
||||
Self {
|
||||
quality,
|
||||
ipv6,
|
||||
previous: None,
|
||||
baseline: Duration::ZERO,
|
||||
trained: 0,
|
||||
rtt: Episode::default(),
|
||||
loss: Episode::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn reset(&mut self) {
|
||||
self.previous = None;
|
||||
self.baseline = Duration::ZERO;
|
||||
self.trained = 0;
|
||||
self.rtt = Episode::default();
|
||||
self.loss = Episode::default();
|
||||
}
|
||||
|
||||
pub(crate) fn observe(&mut self, sample: CarrierSample) {
|
||||
if !self.quality.is_enabled() {
|
||||
self.reset();
|
||||
return;
|
||||
}
|
||||
let Some(previous) = self.previous else {
|
||||
self.previous = Some(sample);
|
||||
return;
|
||||
};
|
||||
let elapsed = sample.at.saturating_duration_since(previous.at);
|
||||
if elapsed < Duration::from_secs(1) {
|
||||
return;
|
||||
}
|
||||
let counters = [
|
||||
(sample.acknowledged, previous.acknowledged),
|
||||
(sample.transmitted, previous.transmitted),
|
||||
(sample.lost, previous.lost),
|
||||
(sample.lost_bytes, previous.lost_bytes),
|
||||
(sample.tx_bytes, previous.tx_bytes),
|
||||
(sample.rx_bytes, previous.rx_bytes),
|
||||
(sample.tx_datagrams, previous.tx_datagrams),
|
||||
(sample.rx_datagrams, previous.rx_datagrams),
|
||||
];
|
||||
if elapsed > Duration::from_secs(10)
|
||||
|| counters
|
||||
.iter()
|
||||
.any(|(new, old)| new.zip(*old).is_some_and(|(new, old)| new < old))
|
||||
{
|
||||
self.reset();
|
||||
self.previous = Some(sample);
|
||||
return;
|
||||
}
|
||||
self.previous = Some(sample);
|
||||
let delta = |new: Option<u64>, old: Option<u64>| {
|
||||
new.zip(old).and_then(|(new, old)| new.checked_sub(old))
|
||||
};
|
||||
let tx = delta(sample.tx_bytes, previous.tx_bytes);
|
||||
let rx = delta(sample.rx_bytes, previous.rx_bytes);
|
||||
let tx_datagrams = delta(sample.tx_datagrams, previous.tx_datagrams);
|
||||
let rx_datagrams = delta(sample.rx_datagrams, previous.rx_datagrams);
|
||||
let enough = |tx: Option<u64>, rx: Option<u64>, minimum| {
|
||||
tx.is_some_and(|n| n >= minimum)
|
||||
|| rx.is_some_and(|n| n >= minimum)
|
||||
|| tx
|
||||
.zip(rx)
|
||||
.is_some_and(|(tx, rx)| tx.saturating_add(rx) >= minimum)
|
||||
};
|
||||
let active = enough(tx, rx, 4096) || enough(tx_datagrams, rx_datagrams, 32);
|
||||
let acknowledged = delta(sample.acknowledged, previous.acknowledged)
|
||||
.is_some_and(|acknowledged| acknowledged > 0);
|
||||
if !active || !acknowledged {
|
||||
self.rtt.observe(None);
|
||||
self.loss.observe(None);
|
||||
return;
|
||||
}
|
||||
|
||||
let rtt_pressure = sample.rtt.filter(|rtt| !rtt.is_zero()).and_then(|rtt| {
|
||||
if self.trained < 4 {
|
||||
self.baseline = self
|
||||
.baseline
|
||||
.saturating_mul(u32::from(self.trained))
|
||||
.saturating_add(rtt)
|
||||
/ u32::from(self.trained + 1);
|
||||
self.trained += 1;
|
||||
return None;
|
||||
}
|
||||
let pressure = rtt >= self.baseline.saturating_add(self.baseline / 2)
|
||||
&& rtt >= self.baseline.saturating_add(Duration::from_millis(20));
|
||||
if !pressure && !self.rtt.latched {
|
||||
self.baseline = self.baseline.saturating_mul(3).saturating_add(rtt) / 4;
|
||||
}
|
||||
Some(pressure)
|
||||
});
|
||||
let sent_payload =
|
||||
tx.is_some_and(|tx| tx >= 4096) || tx_datagrams.is_some_and(|tx| tx >= 32);
|
||||
let loss_pressure = delta(sample.transmitted, previous.transmitted)
|
||||
.zip(delta(sample.lost, previous.lost))
|
||||
.zip(delta(sample.lost_bytes, previous.lost_bytes))
|
||||
.filter(|((sent, _), _)| sent_payload && *sent >= 32)
|
||||
.map(|((sent, lost), bytes)| {
|
||||
lost >= 3 && bytes > 0 && u128::from(lost) * 100 >= u128::from(sent) * 5
|
||||
});
|
||||
let rtt = self.rtt.observe(rtt_pressure);
|
||||
let loss = self.loss.observe(loss_pressure);
|
||||
let reason = match (rtt, loss) {
|
||||
(true, true) => PressureReason::Both,
|
||||
(true, false) => PressureReason::Rtt,
|
||||
(false, true) => PressureReason::Loss,
|
||||
(false, false) => return,
|
||||
};
|
||||
self.quality.report(self.ipv6, reason, sample.at);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,224 @@
|
||||
use std::io;
|
||||
use std::pin::Pin;
|
||||
use std::task::{Context, Poll};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
use super::{CarrierSample, CarrierSampler, TransportQuality};
|
||||
|
||||
/// Lives with the physical I/O owner, never with a logical mux stream.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct TcpPressure {
|
||||
sampler: Option<CarrierSampler>,
|
||||
last_sample: Option<Instant>,
|
||||
}
|
||||
|
||||
impl TcpPressure {
|
||||
pub(crate) fn new(socket: &TcpStream) -> Self {
|
||||
let sampler = TransportQuality::current().and_then(|quality| {
|
||||
let peer = socket.peer_addr().ok()?;
|
||||
Some(CarrierSampler::new(
|
||||
quality,
|
||||
peer.ip().to_canonical().is_ipv6(),
|
||||
))
|
||||
});
|
||||
Self {
|
||||
sampler,
|
||||
last_sample: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn observe(&mut self, socket: &TcpStream) {
|
||||
let Some(sampler) = self.sampler.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if !sampler.quality.is_enabled() {
|
||||
sampler.reset();
|
||||
return;
|
||||
}
|
||||
let now = Instant::now();
|
||||
if self
|
||||
.last_sample
|
||||
.is_some_and(|last| now.saturating_duration_since(last) < Duration::from_secs(1))
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.last_sample = Some(now);
|
||||
sampler.observe(read_sample(socket, now));
|
||||
}
|
||||
}
|
||||
|
||||
/// The observer is dormant through TLS/REALITY authentication and has no I/O
|
||||
/// authority: it neither owns another descriptor nor changes a poll result.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct ObservedTcp {
|
||||
inner: TcpStream,
|
||||
pressure: TcpPressure,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl std::os::fd::AsRawFd for ObservedTcp {
|
||||
fn as_raw_fd(&self) -> std::os::fd::RawFd {
|
||||
std::os::fd::AsRawFd::as_raw_fd(&self.inner)
|
||||
}
|
||||
}
|
||||
|
||||
impl ObservedTcp {
|
||||
pub(crate) fn new(inner: TcpStream) -> Self {
|
||||
let pressure = TcpPressure::new(&inner);
|
||||
Self {
|
||||
inner,
|
||||
pressure,
|
||||
active: false,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn activate(&mut self) {
|
||||
self.active = true;
|
||||
self.pressure.observe(&self.inner);
|
||||
}
|
||||
|
||||
fn observe(&mut self) {
|
||||
if self.active {
|
||||
self.pressure.observe(&self.inner);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for ObservedTcp {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
let this = self.get_mut();
|
||||
let before = buf.filled().len();
|
||||
let result = Pin::new(&mut this.inner).poll_read(cx, buf);
|
||||
if matches!(&result, Poll::Ready(Ok(()))) && buf.filled().len() > before {
|
||||
this.observe();
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for ObservedTcp {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let this = self.get_mut();
|
||||
let result = Pin::new(&mut this.inner).poll_write(cx, buf);
|
||||
if matches!(&result, Poll::Ready(Ok(n)) if *n > 0) {
|
||||
this.observe();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn poll_write_vectored(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
bufs: &[io::IoSlice<'_>],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
let this = self.get_mut();
|
||||
let result = Pin::new(&mut this.inner).poll_write_vectored(cx, bufs);
|
||||
if matches!(&result, Poll::Ready(Ok(n)) if *n > 0) {
|
||||
this.observe();
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
self.inner.is_write_vectored()
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().inner).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.get_mut().inner).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
fn unknown_sample(at: Instant) -> CarrierSample {
|
||||
CarrierSample {
|
||||
at,
|
||||
rtt: None,
|
||||
acknowledged: None,
|
||||
transmitted: None,
|
||||
lost: None,
|
||||
lost_bytes: None,
|
||||
tx_bytes: None,
|
||||
rx_bytes: None,
|
||||
tx_datagrams: None,
|
||||
rx_datagrams: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
fn read_sample(_socket: &TcpStream, at: Instant) -> CarrierSample {
|
||||
unknown_sample(at)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn read_sample(socket: &TcpStream, at: Instant) -> CarrierSample {
|
||||
use std::os::fd::{AsFd, AsRawFd};
|
||||
|
||||
// SAFETY: tcp_info is a C integer-only struct with a valid zero value. The
|
||||
// borrowed fd cannot outlive this synchronous call or race owner teardown.
|
||||
let mut info: libc::tcp_info = unsafe { std::mem::zeroed() };
|
||||
let mut length = std::mem::size_of_val(&info) as libc::socklen_t;
|
||||
let fd = socket.as_fd();
|
||||
// SAFETY: both writable pointers cover their declared sizes, getsockopt
|
||||
// respects the supplied capacity, and no pointer or fd escapes this call.
|
||||
let result = unsafe {
|
||||
libc::getsockopt(
|
||||
fd.as_raw_fd(),
|
||||
libc::IPPROTO_TCP,
|
||||
libc::TCP_INFO,
|
||||
(&mut info as *mut libc::tcp_info).cast(),
|
||||
&mut length,
|
||||
)
|
||||
};
|
||||
if result != 0 {
|
||||
return unknown_sample(at);
|
||||
}
|
||||
sample_from_info(&info, length as usize, at)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn sample_from_info(info: &libc::tcp_info, length: usize, at: Instant) -> CarrierSample {
|
||||
macro_rules! field {
|
||||
($field:ident) => {
|
||||
(length
|
||||
>= std::mem::offset_of!(libc::tcp_info, $field)
|
||||
+ std::mem::size_of_val(&info.$field))
|
||||
.then_some(u64::from(info.$field))
|
||||
};
|
||||
}
|
||||
// Linux TCP_ESTABLISHED is 1; libc does not export the state enum.
|
||||
// Closed sockets must not turn the final kernel snapshot into new evidence.
|
||||
if field!(tcpi_state) != Some(1) {
|
||||
return unknown_sample(at);
|
||||
}
|
||||
CarrierSample {
|
||||
at,
|
||||
rtt: field!(tcpi_rtt)
|
||||
.filter(|rtt| *rtt > 0)
|
||||
.map(Duration::from_micros),
|
||||
acknowledged: field!(tcpi_bytes_acked),
|
||||
transmitted: field!(tcpi_data_segs_out),
|
||||
lost: field!(tcpi_total_retrans),
|
||||
lost_bytes: field!(tcpi_bytes_retrans),
|
||||
tx_bytes: field!(tcpi_bytes_sent),
|
||||
rx_bytes: field!(tcpi_bytes_received),
|
||||
tx_datagrams: None,
|
||||
rx_datagrams: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, target_os = "linux"))]
|
||||
mod tests;
|
||||
@@ -0,0 +1,87 @@
|
||||
use super::*;
|
||||
use std::sync::Arc;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
#[test]
|
||||
fn truncated_kernel_fields_remain_unknown_instead_of_zero_measurements() {
|
||||
// SAFETY: the Linux TCP_INFO ABI consists entirely of integer fields.
|
||||
let mut info: libc::tcp_info = unsafe { std::mem::zeroed() };
|
||||
info.tcpi_state = 1;
|
||||
info.tcpi_rtt = 40_000;
|
||||
info.tcpi_bytes_acked = 16384;
|
||||
info.tcpi_data_segs_out = 64;
|
||||
info.tcpi_total_retrans = 4;
|
||||
info.tcpi_bytes_retrans = 4096;
|
||||
info.tcpi_bytes_sent = 65536;
|
||||
info.tcpi_bytes_received = 8192;
|
||||
let now = Instant::now();
|
||||
let short = sample_from_info(
|
||||
&info,
|
||||
std::mem::offset_of!(libc::tcp_info, tcpi_bytes_acked) + 7,
|
||||
now,
|
||||
);
|
||||
assert_eq!(short.rtt, Some(Duration::from_millis(40)));
|
||||
assert_eq!(short.lost, Some(4));
|
||||
assert!(short.acknowledged.is_none());
|
||||
assert!(short.transmitted.is_none());
|
||||
assert!(short.tx_bytes.is_none());
|
||||
assert!(short.lost_bytes.is_none());
|
||||
let tail = sample_from_info(
|
||||
&info,
|
||||
std::mem::offset_of!(libc::tcp_info, tcpi_bytes_retrans) + 7,
|
||||
now,
|
||||
);
|
||||
assert_eq!(tail.tx_bytes, Some(65536));
|
||||
assert!(tail.lost_bytes.is_none());
|
||||
info.tcpi_state = 7;
|
||||
let closed = sample_from_info(&info, std::mem::size_of_val(&info), now);
|
||||
assert!(closed.acknowledged.is_none());
|
||||
assert!(closed.rtt.is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn observed_tcp_loopback_preserves_cancelled_reads_payload_and_half_close() {
|
||||
tokio::time::timeout(Duration::from_secs(5), async {
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let socket = TcpStream::connect(listener.local_addr().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let (mut peer, _) = listener.accept().await.unwrap();
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let mut observed = quality
|
||||
.clone()
|
||||
.scope(async { ObservedTcp::new(socket) })
|
||||
.await;
|
||||
observed.activate();
|
||||
let mut output = [0u8; 8192];
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(10), observed.read_exact(&mut output))
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
tokio::time::sleep(Duration::from_millis(1001)).await;
|
||||
peer.write_all(&[42; 8192]).await.unwrap();
|
||||
observed.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(output, [42; 8192]);
|
||||
observed.write_all(&[17; 8192]).await.unwrap();
|
||||
observed.flush().await.unwrap();
|
||||
peer.read_exact(&mut output).await.unwrap();
|
||||
assert_eq!(output, [17; 8192]);
|
||||
let sample = read_sample(&observed.inner, Instant::now());
|
||||
assert!(sample.rtt.is_some_and(|rtt| !rtt.is_zero()));
|
||||
assert!(sample.rx_bytes.is_none_or(|bytes| bytes >= 8192));
|
||||
assert!(sample.tx_bytes.is_none_or(|bytes| bytes >= 8192));
|
||||
assert!(quality.snapshot().iter().all(Option::is_none));
|
||||
observed.shutdown().await.unwrap();
|
||||
assert_eq!(peer.read(&mut output).await.unwrap(), 0);
|
||||
peer.write_all(b"after-half-close").await.unwrap();
|
||||
peer.shutdown().await.unwrap();
|
||||
let mut remaining = Vec::new();
|
||||
observed.read_to_end(&mut remaining).await.unwrap();
|
||||
assert_eq!(remaining, b"after-half-close");
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
use super::*;
|
||||
|
||||
fn fixture() -> (Arc<TransportQuality>, CarrierSampler, CarrierSample) {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
quality.enable();
|
||||
let sampler = CarrierSampler::new(Arc::clone(&quality), false);
|
||||
let sample = CarrierSample {
|
||||
at: Instant::now(),
|
||||
rtt: Some(Duration::from_millis(40)),
|
||||
acknowledged: Some(0),
|
||||
transmitted: Some(0),
|
||||
lost: Some(0),
|
||||
lost_bytes: Some(0),
|
||||
tx_bytes: Some(0),
|
||||
rx_bytes: Some(0),
|
||||
tx_datagrams: Some(0),
|
||||
rx_datagrams: Some(0),
|
||||
};
|
||||
(quality, sampler, sample)
|
||||
}
|
||||
|
||||
fn step(sample: &mut CarrierSample, rtt_ms: u64, lost: u64) -> CarrierSample {
|
||||
sample.at += Duration::from_secs(1);
|
||||
sample.rtt = Some(Duration::from_millis(rtt_ms));
|
||||
sample.acknowledged = sample.acknowledged.map(|n| n + 8192);
|
||||
sample.transmitted = sample.transmitted.map(|n| n + 64);
|
||||
sample.lost = sample.lost.map(|n| n + lost);
|
||||
sample.lost_bytes = sample.lost_bytes.map(|n| n + lost * 512);
|
||||
sample.tx_bytes = sample.tx_bytes.map(|n| n + 8192);
|
||||
sample.rx_bytes = sample.rx_bytes.map(|n| n + 4096);
|
||||
*sample
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trained_rtt_requires_sustain_and_rearms_without_refreshing_a_continuing_episode() {
|
||||
let (quality, mut sampler, mut sample) = fixture();
|
||||
sampler.observe(sample);
|
||||
for _ in 0..4 {
|
||||
sampler.observe(step(&mut sample, 40, 0));
|
||||
}
|
||||
for _ in 0..2 {
|
||||
sampler.observe(step(&mut sample, 80, 0));
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
}
|
||||
sampler.observe(step(&mut sample, 80, 0));
|
||||
let first = quality.snapshot()[0].unwrap();
|
||||
assert_eq!(first.reason, PressureReason::Rtt);
|
||||
assert_eq!(first.observed_at, sample.at);
|
||||
for _ in 0..65 {
|
||||
sampler.observe(step(&mut sample, 80, 0));
|
||||
}
|
||||
assert_eq!(
|
||||
quality.snapshot()[0].unwrap().observed_at,
|
||||
first.observed_at
|
||||
);
|
||||
sampler.observe(step(&mut sample, 40, 0));
|
||||
sampler.observe(step(&mut sample, 80, 0));
|
||||
assert_eq!(
|
||||
quality.snapshot()[0].unwrap().observed_at,
|
||||
first.observed_at
|
||||
);
|
||||
for _ in 0..2 {
|
||||
sampler.observe(step(&mut sample, 40, 0));
|
||||
}
|
||||
for _ in 0..3 {
|
||||
sampler.observe(step(&mut sample, 80, 0));
|
||||
}
|
||||
assert_eq!(quality.snapshot()[0].unwrap().observed_at, sample.at);
|
||||
assert!(quality.snapshot()[1].is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn outgoing_loss_is_independent_of_rtt_but_requires_payload_and_packet_volume() {
|
||||
let (quality, mut sampler, mut sample) = fixture();
|
||||
sample.rtt = None;
|
||||
sampler.observe(sample);
|
||||
for _ in 0..3 {
|
||||
let mut next = step(&mut sample, 40, 4);
|
||||
next.rtt = None;
|
||||
sampler.observe(next);
|
||||
}
|
||||
assert_eq!(quality.snapshot()[0].unwrap().reason, PressureReason::Loss);
|
||||
|
||||
for mode in 0..4 {
|
||||
let (quality, mut sampler, mut sample) = fixture();
|
||||
sampler.observe(sample);
|
||||
for _ in 0..8 {
|
||||
let before = sample;
|
||||
step(&mut sample, 40, 4);
|
||||
match mode {
|
||||
0 => sample.tx_bytes = before.tx_bytes, // RX-only ACKs are not send loss.
|
||||
1 => sample.transmitted = before.transmitted.map(|n| n + 31),
|
||||
2 => sample.lost_bytes = None,
|
||||
_ => sample.lost = before.lost.map(|n| n + 3), // Below five percent.
|
||||
}
|
||||
sampler.observe(sample);
|
||||
}
|
||||
assert!(quality.snapshot()[0].is_none(), "mode {mode}");
|
||||
}
|
||||
|
||||
let (quality, mut sampler, mut sample) = fixture();
|
||||
sample.tx_bytes = None;
|
||||
sample.rx_bytes = None;
|
||||
sampler.observe(sample);
|
||||
for _ in 0..3 {
|
||||
step(&mut sample, 40, 4);
|
||||
sample.tx_datagrams = sample.tx_datagrams.map(|n| n + 32);
|
||||
sampler.observe(sample);
|
||||
}
|
||||
assert_eq!(quality.snapshot()[0].unwrap().reason, PressureReason::Loss);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_idle_resets_and_out_of_order_samples_do_not_invent_episodes() {
|
||||
for interruption in 0..6 {
|
||||
let (quality, mut sampler, mut sample) = fixture();
|
||||
sampler.observe(sample);
|
||||
for _ in 0..4 {
|
||||
sampler.observe(step(&mut sample, 40, 0));
|
||||
}
|
||||
for _ in 0..2 {
|
||||
sampler.observe(step(&mut sample, 80, 4));
|
||||
}
|
||||
match interruption {
|
||||
0 => {
|
||||
// Idle counters cannot preserve a sustain streak.
|
||||
sample.at += Duration::from_secs(1);
|
||||
sampler.observe(sample);
|
||||
}
|
||||
1 => {
|
||||
// An unknown RTT/loss window is not recovery or suspicion.
|
||||
step(&mut sample, 80, 4);
|
||||
let mut unknown = sample;
|
||||
unknown.rtt = None;
|
||||
unknown.lost_bytes = None;
|
||||
sampler.observe(unknown);
|
||||
}
|
||||
2 => {
|
||||
// Counter reset seeds, rather than interpreting lifetime loss.
|
||||
let at = sample.at + Duration::from_secs(1);
|
||||
sample = fixture().2;
|
||||
sample.at = at;
|
||||
sampler.observe(sample);
|
||||
}
|
||||
3 => {
|
||||
sample.at += Duration::from_secs(11);
|
||||
sampler.observe(sample);
|
||||
}
|
||||
4 => {
|
||||
// Tiny payload cannot be accumulated across windows.
|
||||
sample.at += Duration::from_secs(1);
|
||||
sample.tx_bytes = sample.tx_bytes.map(|n| n + 8);
|
||||
sample.rx_bytes = sample.rx_bytes.map(|n| n + 8);
|
||||
sample.acknowledged = sample.acknowledged.map(|n| n + 8);
|
||||
sampler.observe(sample);
|
||||
}
|
||||
_ => {
|
||||
// Missing ACK progress is not fresh RTT evidence.
|
||||
let acknowledged = sample.acknowledged;
|
||||
step(&mut sample, 80, 4);
|
||||
sample.acknowledged = acknowledged;
|
||||
sampler.observe(sample);
|
||||
}
|
||||
}
|
||||
sampler.observe(step(&mut sample, 80, 4));
|
||||
assert!(
|
||||
quality.snapshot()[0].is_none(),
|
||||
"interruption {interruption}"
|
||||
);
|
||||
}
|
||||
|
||||
let (quality, mut sampler, mut sample) = fixture();
|
||||
sampler.observe(sample);
|
||||
for _ in 0..4 {
|
||||
sampler.observe(step(&mut sample, 40, 0));
|
||||
}
|
||||
for _ in 0..2 {
|
||||
sampler.observe(step(&mut sample, 80, 0));
|
||||
}
|
||||
let mut stale = sample;
|
||||
stale.at -= Duration::from_secs(2);
|
||||
stale.tx_bytes = Some(0);
|
||||
sampler.observe(stale);
|
||||
sampler.observe(step(&mut sample, 80, 0));
|
||||
assert_eq!(quality.snapshot()[0].unwrap().observed_at, sample.at);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_coalesces_carriers_and_disabled_history_cannot_publish() {
|
||||
let quality = Arc::new(TransportQuality::default());
|
||||
let mut sampler = CarrierSampler::new(Arc::clone(&quality), false);
|
||||
let mut sample = fixture().2;
|
||||
sampler.observe(sample);
|
||||
for _ in 0..8 {
|
||||
sampler.observe(step(&mut sample, 80, 8));
|
||||
}
|
||||
quality.enable();
|
||||
sampler.observe(step(&mut sample, 80, 8));
|
||||
assert!(quality.snapshot()[0].is_none());
|
||||
for _ in 0..3 {
|
||||
sampler.observe(step(&mut sample, 80, 8));
|
||||
}
|
||||
let at = quality.snapshot()[0].unwrap().observed_at;
|
||||
quality.report(false, PressureReason::Rtt, at + Duration::from_secs(29));
|
||||
quality.report(false, PressureReason::Both, at - Duration::from_secs(1));
|
||||
assert_eq!(quality.snapshot()[0].unwrap().observed_at, at);
|
||||
quality.report(true, PressureReason::Rtt, at);
|
||||
assert_eq!(quality.snapshot()[1].unwrap().observed_at, at);
|
||||
quality.report(false, PressureReason::Both, at + Duration::from_secs(30));
|
||||
assert_eq!(quality.snapshot()[0].unwrap().reason, PressureReason::Both);
|
||||
}
|
||||
+15
-3
@@ -43,12 +43,18 @@ Score first runs the same liveness filter as every other policy. The filter's he
|
||||
|
||||
The exact key is `(group, TCP/UDP, target IPv4/IPv6, normalized target, NodeId)`. Domains are ASCII-lowercased with one trailing dot removed and retain their port; IP targets retain the socket address. A second bounded `(group, TCP/UDP, target family or no family, NodeId)` aggregate supplies the prior for cold targets and receives targetless warm-up samples. Global aggregate, family aggregate, and exact-target evidence blend hierarchically until the more specific layer has enough evidence. Recursive selection carries the same target context and attributes the leaf outcome to every Score group traversed.
|
||||
|
||||
Business attempt and outcome evidence decays with a 30-minute half-life. Setup failures carry extra weight in the Beta confidence bounds. Qualified candidates need four effective useful completions, compatible reliability bounds and comparable observed failure risk; sparse candidates receive bounded trials. Once qualified, utility uses observed reliability rather than rewarding the most-sampled node's lower bound. Normal ranking, metric baselines, incumbent eligibility and winner reasons use the same eligible set. Overlapping global/family/exact completion evidence is never added as independent samples.
|
||||
Business attempt and outcome evidence decays with a 30-minute half-life. Setup failures carry extra weight in the Beta confidence bounds. Initial evidence qualification requires four effective useful completions; ordinary candidates must also meet the existing reliability bounds, observed-failure band and streak gate. Fresh targeted business RX can retain earned qualification for 60 seconds from its event time, renewing an unexpired lease without adding completions. An expired or invalidated lease cannot be restored by RX alone while effective completions remain below four. Failure and reload invalidate the lease. Sparse candidates still receive bounded trials. Ordinary ranking, metric baselines and reliability comparison share this qualification rule; overlapping global/family/exact completion evidence is never added as independent samples, and reliability blending and hold maturity still use actual decayed counts.
|
||||
|
||||
Performance has its own event timestamps and bounded four-observation inertia. Each metric loses confidence after 60 seconds and expires at 120 seconds regardless of historical completion count. Configured probe RTT supplies a baseline; fresh comparable target response and directional goodput can override it. Probe RTT, setup and response latency are normalized within their own measurement scope, not pooled as interchangeable milliseconds. HTTP identity includes the normalized request URI and method; probe domain and health family remain distinct.
|
||||
|
||||
Ordinary first choice still uses group-relative utility. If that winner is already the incumbent, it stays. An ineligible incumbent can be replaced immediately; an eligible incumbent with an unresolved business failure also bypasses holding. Recovery uses actual business RX strictly newer than each applicable cell's last failure: either accepted live progress from a targeted Traffic reporter with setup and TX, or a successful bidirectional terminal outcome. Live progress also respects the failure/reload invalidation fence and captured cell incarnation. Setup-only work, TX-only activity, probes, warm-up and cancellation alone cannot manufacture recovery; cancellation does not retract already accepted RX. Historical failure counts, streaks and backoff still change only through the existing terminal settlement rules.
|
||||
|
||||
For a trained, eligible, recovered incumbent, every eligible trained challenger is compared against that same incumbent. Performance pairs require full confidence on both sides: exact response, existing family-preferred aggregate response, same-cohort probe, paired setup, then paired warm setup. Each throughput direction uses a shared exact or aggregate pair; both candidates retain the existing best-direction utility over that shared set. Observed reliability contributes only when both candidates meet the shared evidence-qualification rule. A gain must clear the existing margin, capped at `0.005`; its support is the maximum of separately decayed global/family/exact completion counts, never their sum. Sparse exact evidence cannot reduce mature protection. Missing or expired performance alone is not a gain; holding does not certify availability and existing bounded trials remain possible. There is no fixed residency timer or guarantee that every performance dimension improves.
|
||||
|
||||
`ScoreFeedback::start()` creates a cloneable `ScoreReporter` only when associated work starts. Setup and first response publish once at their observation time. Accepted TCP writes and successfully delivered UDP progress feed nonoverlapping, event-driven 1–10 second windows; a measured direction needs at least 64 KiB, with bidirectional flow progress and a response. Windows do not add Beta successes. Final settlement contributes at most one outcome and never adds already-published bytes again; dropping the last unfinished handle cancels. Rejection, cancellation and shutdown remove the attempt without a failure, while factual observations remain. Idle or application-limited traffic is not proof of congestion; no sampler task, payload replay or connection migration is added.
|
||||
|
||||
Business-RX publication is separate from throughput windows: the first eligible positive RX publishes immediately, then at most once per second per reporter. Only another positive RX call can publish live progress; no timer or TX-only callback flushes a suppressed receive. A post-failure receive inside the throttle interval can therefore wait for the next publishable RX or terminal settlement, not necessarily one wall-clock second. Live publications neither add Beta outcomes nor refresh terminal verification evidence.
|
||||
|
||||
Admission-scoped TCP dialing starts its reporter at the first admitted physical attempt or immediately before a logical open on a reused session or QUIC connection, not while waiting for cold physical admission. The callback is one-shot; completed paths without either boundary retain the completion fallback.
|
||||
|
||||
An unstarted scope's timeout is a local capacity refusal only while a physical-admission acquisition is still pending. DNS resolution before admission remains an ordinary timeout, allowing the existing eligible retry path. Classification inspects the scope before cancelling its future; cancellation removes only that acquisition's pending registration.
|
||||
@@ -61,6 +67,12 @@ Traffic reporters cover transparent TCP/UDP, supported DNS exchanges and UI down
|
||||
|
||||
Startup exploration has one finite group/network/target-family allowance: all candidates up to four, otherwise `ceil(sqrt(n)) + 1`. Later time/count/degradation opportunities share one reservation and are spent only on unresolved availability/response questions. A promising contender with real progress receives a focused run of at most eight trial selections; cancellation or no progress rotates opportunities rather than pinning the run. This lets sparse large-group candidates finish qualification before historical evidence decays. Fresh settled or near-equivalent cohorts stop forced sampling; expiry, contradiction or membership/probe changes create new gaps. The coarse bound remains 30 seconds or `clamp(2n,16,64)` selections, with degradation requiring at least 16 selections since the prior trial. Real failures retain 5-minute-to-6-hour backoff; only business success reduces the streak. Trials never acquire committed-incumbent protection, and three-failure exclusion does not permanently prevent backoff-expired recovery.
|
||||
|
||||
Carrier-pressure hints are separate from business results and performance scores. Score-bound runtimes observe sustained TCP RTT/retransmission or QUIC RTT/loss pressure on the honk-to-proxy carrier; the existing five-second heartbeat admits fresh episodes. A hint reopens comparison freshness only within the existing validation cadence, eligibility and backoff. It never changes utility, qualification, failure counts, Alive state or existing flows. Actual business observations must justify promotion.
|
||||
|
||||
Sampling uses active 1–10 second intervals with fresh ACK progress and at least 4 KiB payload-byte progress or 32 QUIC DATAGRAM frames. RTT trains on four active samples, then requires three consecutive intervals at least 1.5 times the baseline and 20 ms higher. Send-loss pressure requires meaningful outgoing payload, at least 32 transmissions, three retransmissions/lost packets, positive retransmitted/lost bytes and a 5% count ratio for three intervals. This is a pressure heuristic, not an application-loss estimate or a coherent packet cohort. Unknown/idle intervals prove neither pressure nor recovery. Two qualified normal intervals rearm an episode; each runtime/carrier family publishes at most once per 30 seconds. Hints expire after 60 seconds without being refreshed by reads.
|
||||
|
||||
The health-filter family is not necessarily the actual socket family chosen by address racing. Producers keep actual-family slots, while Score uses the latest fresh event as a node-owner comparison question, not a target/family performance penalty. Only carrier-backed networks receive it; Shadowsocks TCP pressure does not affect native Shadowsocks UDP. Warm configured probes can contribute carrier activity without becoming business evidence. Ordinary UDP loss, raw SOCKS/direct splice, reverse-path loss and proxy-to-target loss remain unknown. Reload fences prior episodes and replaced owners. No carrier or target identities are exported.
|
||||
|
||||
Score state is demand-driven, memory-only, process-local, and non-configurable. Exact cells use a 4,096-entry LRU and aggregate cells use a separate 4,096-entry LRU. Exact-target evidence is transport-quality evidence, not a semantic-unlock capability result; existing routing or geosite rules can select a dedicated service-specific Score group when that coarse cohort is desired. A successful in-process reload shares the same state `Arc`, publishes the new valid `(group, member)` set, and prunes removed cells; late feedback for deleted membership is ignored. Process restart clears everything. Score cells and scorer-only target data are never logged, persisted, or returned by Clash APIs; the existing `/connections` destination metadata remains unchanged.
|
||||
|
||||
Neutral cells remain in the bounded LRUs rather than being eagerly deleted while another reporter may still own their incarnation. Reload clears configured-probe baselines and rejects old-generation probe observations; admitted business flows may continue reporting for surviving membership and matching cell incarnations. Eviction never permits an old reporter to recreate a cell.
|
||||
@@ -73,9 +85,9 @@ The same evaluator identifies missing availability, response and transfer eviden
|
||||
|
||||
Claims expire when their weakest supporting evidence crosses the full-confidence boundary (at most 60 seconds here), sooner if effective completion evidence or a supporting failure exclusion expires. Failed business outcomes and committed reload revoke recent usability without erasing long-term reliability. API reads derive current validity without advancing clocks, trials or counters. Authorized Apply records confirmations, expiry/contradiction transitions, validation selections and accumulated time to confirmation in existing bounded history; a confirmation may concern a probe comparison while business usability remains provisional. See [API semantics](../reference/api.md#score-verification).
|
||||
|
||||
Recent usability is dated by the latest positive business RX, never by TX-only progress or terminal cleanup. Late completions retain their once-only lifetime outcome but cannot contribute expired RX or RX at or before the latest failure/reload fence. Unexpired out-of-order completions preserve the newest observation clock, and an admitted surviving flow may contribute genuinely new RX after that fence.
|
||||
Verification's recent usability remains terminal-based and is dated by the latest positive business RX, never by TX-only progress or terminal cleanup. A retained ordinary qualification lease or live recovery does not upgrade `scoreVerification`: it can remain provisional while an active incumbent is retained. Late completions retain their once-only lifetime outcome but cannot contribute expired RX or RX at or before the latest failure/reload fence to recent verification evidence. Unexpired out-of-order completions preserve the newest observation clock, and an admitted surviving flow may contribute genuinely new RX after that fence.
|
||||
|
||||
An authorized applied multi-candidate rank increments exactly one final reason in precedence order: `coldExplore`, `periodicExplore`, `incumbentHeld`, `freshFailureBypass`, `reliabilityWinner`, then `performanceWinner`. `deadFiltered` independently counts unique leaf candidates removed by liveness filtering. `switchFlap` independently counts a committed winner switching back to its prior winner within eight selections of the same `(group, network, family, target)` scope, so unrelated targets interleaving their own winners never count; targetless selections share one bucket, and history is bounded by a 4,096-entry LRU. Cold and periodic exploration do not mutate this regret window. `failStreakExcluded` sums, per authorized rank, the candidates dropped by the three-consecutive-fresh-failure gate, and `exploreBackedOff` sums the candidates currently in exploration backoff. Peek, proxy/stat reads, singleton bypasses, and last-resort selection are neutral. The authenticated `/stats.score.groups[]` snapshot exposes only those per-group TCP/UDP counters; it contains no cells, nodes, targets, cadence, or manager authority. `/stats.score.cache` exposes each 4,096-entry evidence LRU's current cell count and cumulative eviction total, still without any group, node, or target identity.
|
||||
An authorized applied multi-candidate rank increments one final reason: `coldExplore`, `periodicExplore`, `incumbentIneligible`, `freshFailureBypass`, `insufficientEvidenceHeld`, `incumbentHeld`, `reliabilityWinner` or `performanceWinner`. `insufficientEvidenceHeld` means no challenger earned promotion and the ordinary utility winner lacked a fully qualified shared performance comparison; it does not claim that reliability history is absent. `ordinarySwitch` separately counts committed normal A→B identity changes within the same `(group, network, family, target)` history; first choices and trials do not count. `switchFlap` is its subset returning to the prior winner within eight ordinary selections. `deadFiltered`, `failStreakExcluded` and `exploreBackedOff` count affected candidates, not failed flows. History remains a 4,096-entry LRU; unknown/evicted history cannot prove a switch. Peek, proxy/stat reads, singleton bypass and last-resort selection remain neutral for these counters. Authenticated `/stats.score` exports only fixed group/network counters and the two evidence-cache occupancy/eviction totals, without scorer-private node/target/cell identities.
|
||||
|
||||
Clash represents a Score group as `type: "url_test"`, reports the current aggregate TCP winner in `now`, and rejects `PUT /proxies/{name}`.
|
||||
|
||||
|
||||
@@ -290,6 +290,8 @@ Cold and pooled-bare Trojan streams use that same complete transport stack.
|
||||
TLS batching returns bytes already read before surfacing a later I/O error on
|
||||
the next non-empty read; it never converts that error into EOF.
|
||||
|
||||
`transport_quality` owns advisory per-runtime carrier pressure. Common TCP/TLS/REALITY and AnyTLS use a physical-I/O adapter; Shadowsocks borrows its existing socket half. Linux `TCP_INFO` is read at most once per active second, checking each field against the returned ABI length; missing fields/errors remain unknown and never alter I/O. Vision Direct and ready-pool descriptor probing retain the socket path. Hy2/TUIC/Juicity reuse their existing one-second physical QUIC monitor, excluding pre-confirmation/pre-publication history and reseeding on peer changes. Logical mux children do not each report the same carrier event. No extra descriptor or per-TCP sampling task is retained; quiescent TCP has no new event-driven observation. See [Score pressure semantics](./groups.md#score-scoring-and-lifecycle).
|
||||
|
||||
The gRPC transport is a hand-written minimal gRPC-over-HTTP/2 client that interoperates with official sing-box Trojan+gRPC. The
|
||||
opening HEADERS frame does not set `END_STREAM`, and TLS requests use
|
||||
`:scheme: https`. DATA carries gRPC length prefixes and the protobuf
|
||||
|
||||
+10
-4
@@ -187,8 +187,10 @@ A non-empty `external_ui_download_detour` forces the initial request and redirec
|
||||
H = { count, sumNanos, buckets } // buckets has 64 fixed log2 slots
|
||||
R = {
|
||||
coldExplore, periodicExplore, reliabilityWinner, performanceWinner,
|
||||
incumbentHeld, freshFailureBypass, deadFiltered, switchFlap,
|
||||
failStreakExcluded, exploreBackedOff
|
||||
incumbentHeld, insufficientEvidenceHeld, incumbentIneligible,
|
||||
freshFailureBypass, deadFiltered, ordinarySwitch, switchFlap,
|
||||
failStreakExcluded, exploreBackedOff, carrierPressure, carrierRttPressure,
|
||||
carrierLossPressure, carrierValidation
|
||||
} // every R value is a u64 count
|
||||
```
|
||||
|
||||
@@ -241,7 +243,11 @@ events.
|
||||
|
||||
`score.groups` is an additive part of the authenticated `/stats` response. It is an empty array when no group currently uses `policy: score`; otherwise it contains every current Score group, including groups with no resolved leaves, sorted lexicographically by `name`. Each group always has both `tcp` and `udp` objects, and each object always has every `R` field above. Missing network activity is represented by zeroes, never omitted fields.
|
||||
|
||||
Each value is a saturating `u64` count, not a latency, throughput or health measurement. One authorized multi-candidate Score Apply records one final reason: `coldExplore` for the finite startup allowance; `periodicExplore` for shared time/count/degradation revalidation; `incumbentHeld` for a retained committed winner; `freshFailureBypass` when fresh failure defeats eligibility or holding; `reliabilityWinner` when no alternative qualifies for normal comparison; otherwise `performanceWinner`. A performance reason does not prove improvement or a switch. `deadFiltered` counts unique health-filtered leaves. `switchFlap` counts return to the prior committed winner within eight target-scoped selections, excluding trials. `failStreakExcluded` and `exploreBackedOff` count affected candidates per rank. Peek, API reads, singleton bypass and last resort do not increment these counters.
|
||||
Each value is a saturating `u64` count, not a latency, throughput or health measurement. One authorized multi-candidate Score Apply records one final reason: `coldExplore` or `periodicExplore` for validation; `incumbentIneligible` for leaving an incumbent outside ordinary eligibility; `freshFailureBypass` for an eligible incumbent's unresolved business failure; `insufficientEvidenceHeld` when no challenger earns promotion and the ordinary utility winner lacks a qualified shared performance comparison; `incumbentHeld` when comparison does not clear the hold margin; otherwise `reliabilityWinner` or `performanceWinner` retain their alternative-eligibility classification. `performanceWinner` does not prove improvement or a switch, and `insufficientEvidenceHeld` does not mean reliability history is absent. `ordinarySwitch` counts actual committed normal A→B choices; `switchFlap` counts returns to the prior winner within eight same-target ordinary choices. First choices, trials and missing prior history cannot add switches. `deadFiltered`, `failStreakExcluded` and `exploreBackedOff` count affected candidates per rank. Peek, API reads, singleton bypass and last resort do not increment these counters; ranks in nested groups are not a one-to-one count of dispatched connections.
|
||||
|
||||
`carrierPressure` counts fresh carrier-family episodes admitted into an existing group/network aggregate cell, not packets or failed connections; duplicate heartbeat reads do not increment it. `carrierValidation` counts periodic validation selections while the ordinary winner has a carrier hint newer than the previous validation. It is an overlapping diagnostic count, not another exclusive reason or proof that the hint alone caused the selection. Hints do not alter business reliability, qualification or health. These fields are readonly on API reads; carrier observations arrive from the control heartbeat independently of selection calls.
|
||||
|
||||
`carrierRttPressure` and `carrierLossPressure` retain the accepted episode's reason. An episode indicating both increments both reason counters but increments `carrierPressure` only once. These overlapping counts do not identify a specific carrier/transport, measure an application loss rate, or add failures; duplicate or stale hints increment none of them. TCP loss pressure means retransmission pressure, not confirmed application packet loss.
|
||||
|
||||
Counters begin at zero on process start and accumulate in process memory only. They survive a successful reload while the group name remains configured, including zero-leaf and temporary Score-to-non-Score-to-Score transitions; non-Score groups are hidden from this response. A committed deletion prunes that name's counters, and a recreated name starts at zero. Generation-fenced superseded managers cannot mutate counters after replacement, including after same-name recreation. The snapshot is copied before JSON serialization, so reading it cannot mutate selection state.
|
||||
|
||||
@@ -254,7 +260,7 @@ Score group objects in `/proxies` and `/proxies/{name}` add `scoreVerification`.
|
||||
| Field | Meaning |
|
||||
| --- | --- |
|
||||
| `selected` | Existing public member tag for this readonly evaluation, or null with no ordinary eligible candidate. TCP `now` uses this same evaluated choice when present. |
|
||||
| `state` | `provisional` or `observedUsable`; the latter requires recent business evidence, not successful HEAD probes alone. |
|
||||
| `state` | `provisional` or `observedUsable`; the latter requires recent successful-terminal business evidence, not probes or live RX alone. Ordinary qualification retention and recovery do not relax this certification. |
|
||||
| `comparison` / `basis` | `unconfirmed`, `equivalent` or `supported`, with `none`, `configuredProbe`, `targetResponse`, `aggregateResponse`, `upload` or `download` as the limited evidence basis. No probability or guaranteed optimum is implied. |
|
||||
| `missing` | Boolean availability/response/transfer gaps across the relevant candidate coverage; selected usability can be observed while an alternative still needs validation. |
|
||||
| `nextAction` | `nextBusinessFlow` reserves future real work only when the shared budget permits; `awaitTransfer` waits for real offered load, never active bulk testing; `backoff` retains failure isolation; `none` means no actionable missing work. |
|
||||
|
||||
@@ -75,17 +75,21 @@ Score chooses one authoritative leaf after ordinary health filtering. Proxy-heal
|
||||
|
||||
The finite startup allowance covers every candidate up to four, otherwise `ceil(sqrt(n)) + 1`. Subsequent validation opportunities exist after 30 seconds, `clamp(2n,16,64)` selections, or observed degradation after at least 16 selections since the last trial, but are spent only on unresolved evidence gaps. A progressing promising contender gets at most eight focused trial selections; no-progress/cancelled work rotates fairly. Triggers share a `(group, TCP/UDP, target family or none)` budget; Peek and new targets cannot mint opportunities, and fresh equivalent cohorts stop forced sampling. Exploration does not acquire ordinary incumbent protection. Real failures retain exponential backoff and three-failure normal exclusion, while backoff-expired recovery trials remain possible.
|
||||
|
||||
Business reliability retains its 30-minute half-life. Performance confidence ages independently and expires after 120 seconds regardless of sample count. Setup and first response publish immediately; accepted transfer progress uses nonoverlapping 1–10 second windows with at least 64 KiB in the measured direction, bidirectional flow progress and a response. Windows never multiply terminal successes or failures. Goodput is workload-dependent, not link capacity; silence is not congestion. Mature switching protection is `0.005` after eight effective completions, with fresh failure bypass. These experimental constants are not configurable; see [the lifecycle design](../design/groups.md#score-scoring-and-lifecycle).
|
||||
Business reliability retains its 30-minute half-life. Performance confidence ages independently and expires after 120 seconds regardless of sample count. Setup and first response publish immediately; accepted transfer progress uses nonoverlapping 1–10 second windows with at least 64 KiB in the measured direction, bidirectional flow progress and a response. Windows never multiply terminal successes or failures. Goodput is workload-dependent, not link capacity; silence is not congestion. Mature switching protection is `0.005` after eight effective completions, using the maximum separately decayed support across applicable layers. Ineligible incumbents and unresolved business failures bypass holding; recovered historical failure mass alone does not. Healthy incumbent promotion requires qualified common performance or supported observed-reliability gain rather than missing-data bonuses. These experimental constants are not configurable; see [the lifecycle design](../design/groups.md#score-scoring-and-lifecycle).
|
||||
|
||||
Targeted Traffic RX after setup and TX can restore ordinary incumbent protection before the flow ends, without clearing failure streaks or adding terminal successes. The first eligible RX publishes immediately; subsequent publication is event-driven and capped at once per second per reporter, so a suppressed receive needs another publishable RX or terminal settlement. Four effective useful completions plus fresh business RX can earn a 60-second qualification lease; RX within that lease can renew it without inflating evidence counts. Failure/reload invalidates the lease, and below-threshold candidates cannot regain an expired lease from RX alone. These ordinary-selection rules do not relax the terminal-evidence requirements of `scoreVerification`.
|
||||
|
||||
Business scores remain scoped by group, transport, target family, normalized target and node identity. Global/family/exact reliability is blended without adding overlapping completions. Target performance overrides its baseline only while fresh and comparable. Probe RTT has separate protocol/family and normalized HTTP URI/method identity; warm-up supplies setup quality only. Nested paths attribute a real outcome once to every traversed Score group.
|
||||
|
||||
Transparent TCP/UDP, supported DNS exchanges and UI downloads report actual business attempts. Configured HTTP/UDP/QUIC probes provide fresh quality without adding business successes or clearing traffic streaks. Manual Clash delay measurements retain their Alive/API history but do not feed a configured Score baseline or turn arbitrary target failure into real-dial demotion. Actual preparation remains warm-up evidence. Independent Score QUIC handshakes preserve existing DataUdp health recovery without invented byte volume.
|
||||
|
||||
Sustained measured carrier pressure may reopen bounded comparison without adding business failures or directly changing the winner. This is honk-to-proxy advisory evidence, not end-to-end UDP loss or a first-request guarantee; unsupported paths remain unknown. See [carrier-pressure scope](../design/groups.md#score-scoring-and-lifecycle).
|
||||
|
||||
Score state is memory-only and process-local, with one 4,096-entry LRU for exact node-target cells and another 4,096-entry LRU for aggregate cells. Exact-target evidence measures observed transport quality, not whether a service is semantically unlocked; use existing routing or geosite rules to select a dedicated service-specific Score group when that coarse cohort is needed. A successful in-process reload shares the same state and removes cells for deleted groups or members; process restart clears it. Score cells and scorer-only domain/IP keys are never logged, persisted, or returned by Clash APIs. Established connection metadata is unaffected.
|
||||
|
||||
After a retryable TCP setup failure, a Score-owned request may try one different permitted leaf even if ordinary ranking still prefers the failed node. Both attempts share a deadline and existing dial admission. Selector boundaries and actual primary final-edge provenance remain authoritative; no new direct/final route or application payload replay is introduced. A committed reload invalidates probe baselines while retaining valid in-flight business evidence; neutral cells stay within the existing bounded LRUs.
|
||||
|
||||
Each authorized applied multi-candidate rank records exactly one reason in this order: initial exploration (`coldExplore`), periodic exploration (`periodicExplore`), held incumbent (`incumbentHeld`), fresh-failure bypass (`freshFailureBypass`), reliability winner (`reliabilityWinner`), or performance winner (`performanceWinner`). Separately, `deadFiltered` counts unique leaf candidates removed by liveness filtering. `switchFlap` counts a committed winner returning to its previous winner within eight selections; exploration is excluded from that window. `failStreakExcluded` sums, per rank, the candidates dropped by the three-consecutive-fresh-failure gate; `exploreBackedOff` sums the candidates currently in exploration backoff. Peek and display/API reads are neutral. Authenticated `/stats.score.groups[]` exports only these aggregate TCP/UDP counters and group names; it exports no cells, nodes, targets, cadence, or manager-authority data. `/stats.score.cache` exports the current cell count and cumulative eviction total of each 4,096-entry evidence LRU, without any group, node, or target identity.
|
||||
Each authorized applied multi-candidate rank records one exclusive reason: `coldExplore`, `periodicExplore`, `incumbentIneligible`, `freshFailureBypass`, `insufficientEvidenceHeld`, `incumbentHeld`, `reliabilityWinner` or `performanceWinner`. `ordinarySwitch` counts committed same-scope A→B changes, excluding first choices and trials; `switchFlap` counts the subset returning to the previous winner within eight ordinary choices. Candidate filtering/backoff counters remain separate. Peek and display/API reads are neutral. Authenticated `/stats.score.groups[]` exposes only fixed group/network counters; `/stats.score.cache` describes the two bounded evidence LRUs. See [API reason semantics](./api.md#score-selection-reason-fields); no scorer-private node or target identities are exported.
|
||||
|
||||
For Clash compatibility, Score remains automatic but is represented as `type: "url_test"`; `now` is the current aggregate TCP winner, and `PUT /proxies/{name}` is rejected.
|
||||
|
||||
|
||||
+15
-3
@@ -43,12 +43,18 @@ Score 首先运行与其他策略相同的存活性过滤。过滤所用的 heal
|
||||
|
||||
精确键为 `(group, TCP/UDP, target IPv4/IPv6, normalized target, NodeId)`。domain 会转为 ASCII 小写、去掉一个末尾点并保留端口;IP 目标保留 socket address。第二个有界的 `(group, TCP/UDP, optional target family, NodeId)` 聚合层为冷目标提供先验,并接收无目标预热样本。精确目标、target-family 和全局聚合层按衰减后的有效证据分层混合:精确证据增多时逐渐覆盖聚合证据,老化后又逐渐让出权重。递归选择携带同一 target context,并把叶节点结果归因到路径上的每个 Score 组。
|
||||
|
||||
业务 attempt 与终态证据使用 30 分钟半衰期,setup 失败在 Beta 置信界中承担更强惩罚。正常性能候选需要四个有效 useful 完成、相容的可靠性置信界和接近的实际失败风险;稀疏候选通过有界试用获得验证。合格后的 utility 使用实际可靠性,不再奖励样本最多者的下置信界。普通排名、性能基准、现任资格和胜出原因共用候选资格,重叠的全局、地址族和精确目标完成证据不作为独立样本相加。
|
||||
业务 attempt 与终态证据使用 30 分钟半衰期,setup 失败在 Beta 置信界中承担更强惩罚。首次取得证据资格仍需要四个有效 useful 完成;普通候选还必须满足既有可靠性置信界、实际失败风险带和连败门槛。新鲜的定向业务 RX 可将已取得的资格保留到其事件时间之后 60 秒,在租约尚未过期时续期,但不增加完成数。有效完成数不足四时,已过期或失效的租约不能仅靠 RX 重新取得;失败和 reload 会撤销租约。稀疏候选仍通过有界试用验证。普通排名、性能基准和可靠性比较共用该资格规则;全局、地址族和精确目标的重叠完成数不相加,可靠性混合与保持支撑仍使用实际衰减计数。
|
||||
|
||||
性能使用独立事件时间和四次观测封顶的惯性;各指标在 60 秒后降低置信度、120 秒时过期,不受历史完成数影响。配置探测 RTT 提供基线,新鲜且可比的目标响应和分方向 goodput 可以覆盖基线。探测 RTT、setup 与首响应分别在自己的测量范围内归一,不把不同含义的毫秒值混池。HTTP 探测身份包含规范化 URI 与方法,探测 domain 和健康地址族也分别隔离。
|
||||
|
||||
普通首次选择仍使用组内相对 utility;该赢家已经是现任时保持不变。不再合格的现任可立即替换;仍合格但业务失败尚未恢复的现任也可绕过保持。恢复依据是严格晚于每个适用 cell 最后失败的实际业务 RX:可以来自已完成 setup 且已有 TX 的定向 Traffic reporter 的已接受活跃进展,也可以来自双向成功终态。活跃进展还受失败/reload 失效边界与已捕获 cell incarnation 约束。仅 setup、单向 TX、探测、预热和取消本身不能制造恢复;取消也不会撤回已经发生的有效 RX。历史失败数、连败与退避仍只按既有终态规则结算。
|
||||
|
||||
对于已训练、合格且已恢复的现任,所有合格且已训练的挑战者都与同一个现任比较。性能证据必须双方均有完整置信:依次选择精确响应、既有地址族优先聚合响应、同 cohort 探测、同类 setup、同类预热 setup。吞吐各方向分别选择双方共同的精确或聚合证据,双方在共同方向集合上保留既有的最佳方向 utility。实际可靠性差仅在双方均满足共用证据资格规则时参与。优势必须超过既有保持门槛,上限仍为 `0.005`;支撑量取全局/地址族/精确完成数分别衰减后的最大值,不能相加。稀疏精确证据不再削弱成熟保护。性能缺失或过期本身不构成优势;保持现任不等于确认可用,既有有界试用仍可进行。不新增固定驻留时间,也不保证每个性能维度同时改善。
|
||||
|
||||
实际工作开始时才创建可 clone 的 `ScoreReporter`。setup 与首响应按事件时间各发布一次;TCP 已接受的写入和 UDP 已成功发送、交付的进展进入互不重叠的 1–10 秒事件驱动窗口。被测方向至少传输 64 KiB,且 flow 已有双向进展及响应;窗口不增加 Beta 成功次数。终态最多结算一次,不重复加入已发布字节,最后一个未完成 handle 被释放时取消。拒绝、取消与关闭撤销 attempt 而不制造失败,已实际发生的观测保留。空闲或应用限速不是拥塞证据;不新增采样任务、负载重放或连接迁移。
|
||||
|
||||
业务 RX 上报独立于吞吐窗口:首次符合条件的正向 RX 立即发布,随后每个 reporter 每秒至多一次。只有后续非零 RX 回调能再次发布活跃进展;没有定时器,单向 TX 也不会补发被限频的接收事件。因此,失败后落在限频间隔内的 RX 可能需要等待下一次可发布的 RX 或终态,不保证一个自然秒内恢复。活跃发布不增加 Beta 终态,也不刷新终态验证证据。
|
||||
|
||||
带拨号准入作用域的 TCP 拨号,在首个物理尝试获准后,或复用 session/QUIC 连接上的逻辑 open 开始前启动 reporter;等待冷物理拨号准入时不启动。回调只执行一次;未经过这两个边界便已完成的路径保留完成时的兜底回调。
|
||||
|
||||
尚未开始工作的作用域,只有仍在等待物理拨号准入时,超时才属于本地容量拒绝。准入前的 DNS 解析超时仍是普通超时,保留既有的合格候选重试路径。分类先检查作用域,再取消 future;取消只移除该次申请的待准入登记。
|
||||
@@ -61,6 +67,12 @@ Traffic reporter 覆盖透明 TCP/UDP、受支持的 DNS exchange 和 UI 下载
|
||||
|
||||
冷启动只有一份组/网络/目标地址族预算:四个及以下覆盖全部,否则为 `ceil(sqrt(n)) + 1`。后续时间/次数/退化机会共享一次预留,仅用于尚未解决的可用性或响应问题。有真实进展的有希望候选得到最多八次试用选择的集中验证;取消或无进展会轮转,不能永久占住验证。这让低流量大组有机会在历史衰减前完成资格确认。新鲜且已经解决或近似等价的候选停止强制采样,过期、矛盾或成员/探测变化再产生缺口。粗粒度边界仍为 30 秒或 `clamp(2n,16,64)` 次选择,退化加速至少要求距前次试用经过 16 次选择。真实失败保留 5 分钟至 6 小时退避,只有业务成功降低连败;试用不获得现任保持保护,三连败排除也不能永久封死退避到期后的恢复验证。
|
||||
|
||||
Carrier 压力提示独立于业务结果和性能评分。与 Score 绑定的 runtime 在 honk→代理服务器的物理连接上观测持续 TCP RTT/重传或 QUIC RTT/丢包压力,已有五秒心跳接收新鲜事件。提示只在既有验证频率、资格与退避约束内重新打开比较新鲜度问题,不改变 utility、资格、失败计数、Alive 或已有连接。晋升仍需真实业务观测支持。
|
||||
|
||||
采样使用 1–10 秒活跃区间,要求有新 ACK 进展,以及至少 4 KiB payload 字节进展或 32 个 QUIC DATAGRAM frame。RTT 先以四个活跃样本训练基线,再要求连续三个区间同时达到基线的 1.5 倍且增加至少 20 ms。发送侧重传/丢包压力要求足够出站 payload、至少 32 次发送、三个重传/丢失包、非零重传/丢失字节及 5% 计数比,连续满足三个区间。这只是压力启发式,不是应用丢包率,计数未必对应同一批包。未知/空闲区间不能证明压力或恢复;两个合格正常区间才能重新解锁事件。每个 runtime/carrier 地址族至多每 30 秒发布一次,提示在 60 秒后过期,读取不续期。
|
||||
|
||||
健康过滤地址族不一定是地址竞速最终使用的 socket 地址族。生产者保留实际地址族槽,Score 则把最新新鲜事件视为节点所有者需要重新比较的提示,而非目标/地址族性能惩罚。只有被测 carrier 承载的网络接收提示,Shadowsocks TCP 压力不影响原生 Shadowsocks UDP。热连接上的配置探测可能贡献 carrier 活动,但不能成为业务证据。普通 UDP 丢包、裸 SOCKS/direct splice、反向丢包及代理到目标的丢包仍未知。reload 隔离旧事件和被替换所有者,不导出 carrier 或目标身份。
|
||||
|
||||
共享状态由 mutex 保护且仅存于当前进程内存:精确 cell 使用 4,096-entry LRU,聚合 cell 使用另一个 4,096-entry LRU。精确目标证据衡量 transport 质量,并不是语义解锁能力的结果;需要这种粗粒度 cohort 时,可用已有 routing 或 geosite 规则选择专用服务 Score 组。已提交的进程内 reload 会复用同一共享状态、发布新的合法 `(group, member)` 集合并裁剪已删除 cell;已删除成员的迟到反馈会被忽略。进程重启会清空一切。Score 不提供调节项;评分 cell 与仅由 scorer 持有的目标数据不会进入日志、持久化存储或任何 API 输出,已有的 `/connections` 目标元数据保持不变。
|
||||
|
||||
中性 cell 保留在有界 LRU 中,不在其他 reporter 仍持有 incarnation 时提前删除。reload 清空配置探测基线并拒绝旧代探测观测;已准入业务 flow 对存续成员和匹配 incarnation 仍可报告。淘汰后的旧 reporter 不能重建 cell。
|
||||
@@ -73,9 +85,9 @@ Traffic reporter 覆盖透明 TCP/UDP、受支持的 DNS exchange 和 UI 下载
|
||||
|
||||
结论在最弱支持证据跌破完整置信门槛时失效(此处最多 60 秒);有效完成数或作为依据的失败排除更早失效时相应提前。业务失败与提交 reload 撤销近期可用性确认,但不清空长期可靠性。API 读取即时重算有效性,不推进采样或计数;已授权 Apply 利用既有有界历史累计确认、过期/矛盾、验证选择和确认耗时。一次确认可以仅指探测比较,业务仍处于临时状态;详见 [API 语义](../reference/api.md#score-验证信息)。
|
||||
|
||||
近期可用性以最近一次非零业务 RX 的观测时间计时,单向 TX 和终态清理都不能刷新它。迟到的完成仍保留一次性的长期终态,但已过期的 RX,以及不晚于最近失败/reload 失效边界的 RX,都不能补回近期证据。尚未过期但乱序到达的完成保留最新观测时钟;已准入且继续存活的 flow 可以用边界之后真正新增的 RX 重新提供证据。
|
||||
验证所用的近期可用性仍依赖终态,并以最近一次非零业务 RX 的观测时间计时,单向 TX 和终态清理都不能刷新它。普通资格续租或活跃恢复不会提升 `scoreVerification`:即使正在保留一个活跃现任,它仍可能是 provisional。迟到的完成保留一次性的长期终态,但已过期的 RX,以及不晚于最近失败/reload 边界的 RX,不能补回近期验证证据。尚未过期但乱序到达的完成保留最新观测时钟;已准入且继续存活的 flow 可以用边界之后真正新增的 RX 重新提供证据。
|
||||
|
||||
一次已授权的多候选 Apply 按优先级恰好增加一个最终原因:`coldExplore`、`periodicExplore`、`incumbentHeld`、`freshFailureBypass`、`reliabilityWinner`,然后是 `performanceWinner`。`deadFiltered` 独立计数被活性过滤移除的唯一叶候选。`switchFlap` 独立计数同一 `(group, network, family, target)` 作用域内已提交胜者在八次选择内切回前一胜者——无关目标交错各自的胜者永远不计入;无目标选择共享一个桶,历史由 4,096 项 LRU 封顶。冷探索与周期探索不修改这段后悔窗口。`failStreakExcluded` 按每次已授权 rank 累计被三连败新鲜失败门排除的候选数,`exploreBackedOff` 累计当前处于探索退避的候选数。Peek、proxy/stat 读取、单例旁路和最后尝试选择均保持中性。经鉴权的 `/stats.score.groups[]` 快照只公开这些按组的 TCP/UDP 计数,不包含 cell、节点、目标、cadence 或 manager authority。`/stats.score.cache` 公开两个 4,096 项证据 LRU 各自的当前 cell 数与累计淘汰数,同样不含任何组、节点或目标身份。
|
||||
一次已授权的多候选 rank 只增加一个最终原因:`coldExplore`、`periodicExplore`、`incumbentIneligible`、`freshFailureBypass`、`insufficientEvidenceHeld`、`incumbentHeld`、`reliabilityWinner` 或 `performanceWinner`。`insufficientEvidenceHeld` 表示没有挑战者获得晋升,且普通 utility 赢家缺少双方均完整合格的性能比较,并不表示没有可靠性历史。`ordinarySwitch` 独立统计同一 `(group, network, family, target)` 历史中的普通已提交 A→B 变更,不含首次选择和试用;`switchFlap` 是其中在八次普通选择内返回前一赢家的子集。`deadFiltered`、`failStreakExcluded`、`exploreBackedOff` 累计受影响候选,不是失败连接数。历史仍是 4,096 项 LRU,缺失/淘汰的历史不能证明发生了切换。Peek、proxy/stat 读取、单例旁路和最后尝试选择不增加这些计数。经鉴权的 `/stats.score` 只导出固定组/网络计数和两个证据缓存的占用/淘汰数,不导出 scorer 私有节点/目标/cell 身份。
|
||||
|
||||
### URLTest 排名与滞后
|
||||
|
||||
|
||||
@@ -258,6 +258,8 @@ Trojan 冷连接和 pool 中取出的裸连接使用同一套完整 transport。
|
||||
TLS 批量读取先返回已经读到的字节,再在下一次非空读取中报告后续的 I/O
|
||||
错误,不会把该错误转换成 EOF。
|
||||
|
||||
`transport_quality` 管理按 runtime 所有者归属的 carrier 压力提示。共享 TCP/TLS/REALITY 与 AnyTLS 在物理 I/O 层观测,Shadowsocks 借用已有 socket half。Linux `TCP_INFO` 每个活跃秒最多读取一次,各字段按内核返回 ABI 长度独立检查;缺失或读取失败保持未知,不能改变 I/O。Vision Direct 与 ready pool 的 FD 存活性检查保留 socket 路径。Hy2/TUIC/Juicity 复用已有每秒物理 QUIC 采样,隔离握手确认/发布前历史,peer 改变时重建基线;逻辑 mux 子流不会重复报告同一事件。不额外持有 FD,也不创建逐 TCP 定时任务;静止 TCP 不产生新的事件驱动观测。详见 [Score 压力语义](./groups.md#score-评分与生命周期)。
|
||||
|
||||
gRPC transport 是手写的最小 gRPC-over-HTTP/2 client。opening HEADERS
|
||||
frame 不设置 `END_STREAM`,TLS 请求使用 `:scheme: https`。DATA 携带 gRPC
|
||||
长度前缀,以及 gun 风格服务端预期的 protobuf 单 bytes 字段 envelope。
|
||||
|
||||
+10
-4
@@ -182,8 +182,10 @@ WebSocket upgrade 也可以改用 `?token=<percent-encoded-secret>`。honk 会
|
||||
H = { count, sumNanos, buckets } // buckets has 64 fixed log2 slots
|
||||
R = {
|
||||
coldExplore, periodicExplore, reliabilityWinner, performanceWinner,
|
||||
incumbentHeld, freshFailureBypass, deadFiltered, switchFlap,
|
||||
failStreakExcluded, exploreBackedOff
|
||||
incumbentHeld, insufficientEvidenceHeld, incumbentIneligible,
|
||||
freshFailureBypass, deadFiltered, ordinarySwitch, switchFlap,
|
||||
failStreakExcluded, exploreBackedOff, carrierPressure, carrierRttPressure,
|
||||
carrierLossPressure, carrierValidation
|
||||
} // R 的每个值均为 u64 计数
|
||||
```
|
||||
|
||||
@@ -207,7 +209,11 @@ R = {
|
||||
|
||||
`score.groups` 是经鉴权 `/stats` 响应中的附加部分。当前没有任何组使用 `policy: score` 时它为 `[]`;否则它包含每个当前 Score 组(包括没有解析出叶节点的组),按 `name` 的字典序排列。每组始终都有 `tcp` 和 `udp` 对象,且每个对象始终包含全部 `R` 字段;没有网络活动时以零表示,绝不省略字段。
|
||||
|
||||
每个值是饱和 `u64` 计数,不是延迟、吞吐或健康测量。一次已授权的多候选 Score Apply 记录一个最终原因:`coldExplore` 表示有限冷启动预算;`periodicExplore` 表示共享时间/计数/退化验证;`incumbentHeld` 表示保持已提交胜者;`freshFailureBypass` 表示新鲜失败使资格或保持失效;没有其他普通合格候选时为 `reliabilityWinner`,其余为 `performanceWinner`。性能原因不证明提速或发生切换。`deadFiltered` 计数唯一健康过滤叶节点;`switchFlap` 计数同目标八次选择内返回前一已提交胜者,不包含试用;`failStreakExcluded` 和 `exploreBackedOff` 按 rank 计数受影响候选。Peek、API 读取、单例与最后尝试旁路不增加这些计数。
|
||||
每个值是饱和 `u64` 计数,不是延迟、吞吐或健康测量。一次已授权的多候选 Score Apply 记录一个最终原因:`coldExplore` 或 `periodicExplore` 表示验证;`incumbentIneligible` 表示现任已不满足普通资格;`freshFailureBypass` 表示合格现任的业务失败尚未恢复;`insufficientEvidenceHeld` 表示没有挑战者获得晋升且普通 utility 赢家缺少双方合格的性能比较;`incumbentHeld` 表示比较优势未跨过保持门槛;其余 `reliabilityWinner`、`performanceWinner` 保留按替代候选资格分类的含义。`performanceWinner` 不证明提速或发生切换,`insufficientEvidenceHeld` 不表示可靠性历史缺失。`ordinarySwitch` 统计实际普通已提交 A→B 选择;`switchFlap` 统计其中同目标八次普通选择内返回前一赢家的情况。首次选择、试用及缺少之前历史时不能增加切换计数。`deadFiltered`、`failStreakExcluded` 和 `exploreBackedOff` 按 rank 累计受影响候选。Peek、API 读取、单例与最后尝试旁路不增加这些计数;嵌套组 rank 与实际出站连接并非一一对应。
|
||||
|
||||
`carrierPressure` 统计被已有组/网络聚合 cell 接收的新鲜 carrier 地址族事件,不是包数或失败连接数;重复心跳读取不增加它。`carrierValidation` 统计普通赢家具有晚于上次验证的 carrier 提示时发生的周期验证选择;它是可重叠的诊断计数,不是新的互斥原因,也不证明只有该提示导致选择。提示不改变业务可靠性、资格或健康。字段在 API 读取时只读;carrier 观测由控制心跳接入,与选路调用独立。
|
||||
|
||||
`carrierRttPressure` 与 `carrierLossPressure` 保留被接收事件的原因。两种条件同时满足时,两个原因计数均增加,但 `carrierPressure` 只增加一次。这些可重叠计数不标识具体 carrier/传输协议,不是应用丢包率,也不增加失败;重复或过期提示均不增加它们。TCP 的 loss pressure 表示重传压力,不代表已确认应用包丢失。
|
||||
|
||||
计数在进程启动时从零开始,只在进程内存中累积。只要组名仍在已提交配置中,成功 reload 会保留它们,包括零叶节点以及临时 Score→非 Score→Score 转换;非 Score 组不会显示在此响应中。已提交的删除会清除该名称的计数,之后重新创建同名组从零开始。受 generation fence 约束的已淘汰 manager 在被替换后不能再修改计数,即使同名组随后被重新创建。快照在 JSON 序列化前复制,读取不会改变选路状态。
|
||||
|
||||
@@ -220,7 +226,7 @@ R = {
|
||||
| 字段 | 含义 |
|
||||
| --- | --- |
|
||||
| `selected` | 本次只读判定对应的既有公开成员 tag;没有普通合格候选时为 null。存在时 TCP `now` 使用同一次判定的选择。 |
|
||||
| `state` | `provisional` 或 `observedUsable`;后者需要近期业务证据,不能仅由 HEAD 成功获得。 |
|
||||
| `state` | `provisional` 或 `observedUsable`;后者需要近期成功终态的业务证据,不能仅由探测或活跃 RX 获得。普通资格续租和恢复不会放宽这一认证。 |
|
||||
| `comparison` / `basis` | `unconfirmed`、`equivalent` 或 `supported`,依据为 `none`、`configuredProbe`、`targetResponse`、`aggregateResponse`、`upload` 或 `download`。不代表误判概率或保证最优。 |
|
||||
| `missing` | 相关候选覆盖范围内的 availability/response/transfer 布尔缺口;当前路径已观测可用时,备选仍可能需要验证。 |
|
||||
| `nextAction` | `nextBusinessFlow` 仅在共享预算允许时使用未来真实流量;`awaitTransfer` 等待真实负载,不主动大流量测速;`backoff` 保留失败隔离;`none` 表示没有可执行的缺失工作。 |
|
||||
|
||||
@@ -75,17 +75,21 @@ Score 经普通健康过滤后选择一个权威叶节点;代理健康地址
|
||||
|
||||
冷启动预算为四个及以下覆盖全部,否则 `ceil(sqrt(n)) + 1`。后续机会在距前次试用 30 秒、累计 `clamp(2n,16,64)` 次选择,或出现退化且已过至少 16 次选择后产生,但只用于未解决的证据缺口。有希望且持续进展的候选最多获得八次集中试用;取消或无进展则公平轮转。触发条件共享组/网络/目标地址族预算,Peek 和新目标不能产生新预算,新鲜等价候选停止强制采样。试用不获得普通现任保护,真实失败保留指数退避和三连败普通排除,退避到期仍允许恢复试用。
|
||||
|
||||
业务可靠性仍使用 30 分钟半衰期;性能置信度独立老化,120 秒后过期,不受样本数量影响。setup 与首响应即时发布,已接受的传输进展使用互不重叠的 1–10 秒窗口,被测方向至少 64 KiB 且 flow 已有双向进展和响应。窗口不增加终态成功或失败次数。goodput 受业务需求影响,不等于链路容量,静默不是拥塞。现任保持在八次有效完成后达到 `0.005`,新鲜失败可绕过。常量是不可配置的实验边界,详见[生命周期设计](../design/groups.md#score-评分与生命周期)。
|
||||
业务可靠性仍使用 30 分钟半衰期;性能置信度独立老化,120 秒后过期,不受样本数量影响。setup 与首响应即时发布,已接受的传输进展使用互不重叠的 1–10 秒窗口,被测方向至少 64 KiB 且 flow 已有双向进展和响应。窗口不增加终态成功或失败次数。goodput 受业务需求影响,不等于链路容量,静默不是拥塞。现任保持在八次有效完成后达到 `0.005`,支撑量取适用层分别衰减后的最大值。不合格现任和未恢复的业务失败可绕过保持;已恢复的历史失败量不再单独取消保护。健康现任的替换需要双方合格的共同性能依据或有充分支撑的实际可靠性优势,不能只靠对手缺失数据获益。常量仍不可配置,详见[生命周期设计](../design/groups.md#score-评分与生命周期)。
|
||||
|
||||
已完成 setup 且已有 TX 的定向 Traffic RX,可在 flow 结束前恢复普通现任保护,但不清除连败、不增加终态成功。首次合格 RX 立即发布,后续按事件驱动且每个 reporter 每秒至多一次;被限频的接收需要等待下一次可发布 RX 或终态。四个有效 useful 完成与新鲜业务 RX 可取得 60 秒资格租约,租约内 RX 可续期而不扩大证据计数。失败/reload 使租约失效;低于完成数门槛的候选不能仅凭 RX 恢复已过期租约。普通选路的这些规则不会放宽 `scoreVerification` 的终态证据要求。
|
||||
|
||||
业务评分仍按组、transport、目标地址族、规范化目标和节点身份隔离;全局/地址族/精确目标可靠性分层混合,但不把重叠完成数相加。目标性能仅在新鲜可比时覆盖基线。探测 RTT 单独保留 protocol/family 与规范化 HTTP URI/方法身份;预热只提供 setup 质量。一次真实结果向经过的每个 Score 组归因一次。
|
||||
|
||||
透明 TCP/UDP、受支持的 DNS exchange 和 UI 下载反馈真实业务 attempt。配置 HTTP/UDP/QUIC 探测提供近期质量,不增加业务成功或清除真实连败。手动 Clash delay 保留 Alive/API 历史,但不建立配置 Score 基线,也不把任意目标失败变成真实拨号降级;实际准备仍记预热质量。独立 Score QUIC 握手保留既有 DataUdp 健康恢复,不虚构字节流量。
|
||||
|
||||
持续且实际测得的 carrier 压力可以重新打开预算内比较,但不增加业务失败,也不直接改变赢家。这是 honk→代理服务器的提示证据,不是端到端 UDP 丢包率或首请求保证;不支持观测的路径仍未知。详见[提示范围](../design/groups.md#score-评分与生命周期)。
|
||||
|
||||
全部评分状态仅存于当前进程内存。精确 node-target cell 使用硬上限为 4,096 的 LRU,聚合 cell 使用另一个 4,096 项 LRU。精确目标证据衡量的是实际 transport 质量,不表示服务在语义上已解锁;需要这种粗粒度 cohort 时,应使用已有 routing 或 geosite 规则选择专用的服务 Score 组。成功的进程内 reload 复用同一共享状态并移除已删除组或成员的 cell;进程重启会清空状态。评分 cell 与仅由 scorer 持有的 domain/IP 键不会进入日志、持久化存储或任何 API 输出。Clash 仍将 Score 表示为 `type: "url_test"`,在 `now` 中显示当前聚合 TCP 胜者,并拒绝对该组执行 `PUT /proxies/{name}`。
|
||||
|
||||
可重试的 TCP 建立失败后,Score 所属请求至多顺序尝试一个不同的合格叶节点,不要求普通评分先改选。两次尝试共享 deadline 和既有拨号准入;Selector 边界与首选实际经过的 final 边保持权威,不新增 direct/final 兜底或重放应用负载。提交 reload 时清空探测基线,但保留有效在途业务证据;中性 cell 仍受既有 LRU 容量约束。
|
||||
|
||||
每次已授权的多候选 Apply 按固定优先级只记录一个原因:初始探索(`coldExplore`)、周期探索(`periodicExplore`)、保持现任(`incumbentHeld`)、新鲜失败绕过(`freshFailureBypass`)、可靠性胜出(`reliabilityWinner`)或性能胜出(`performanceWinner`)。`deadFiltered` 独立记录活性过滤移除的唯一叶候选。`switchFlap` 记录已提交胜者在八次选择内返回前一胜者;探索不进入该窗口。`failStreakExcluded` 按每次 rank 累计被三连败新鲜失败门排除的候选数,`exploreBackedOff` 累计当前处于探索退避的候选数。Peek 与展示/API 读取保持中性。经鉴权的 `/stats.score.groups[]` 只导出这些按组汇总的 TCP/UDP 计数和组名,不导出 cell、节点、目标、cadence 或 manager authority。`/stats.score.cache` 导出两个 4,096 项证据 LRU 的当前 cell 数与累计淘汰数,不含任何组、节点或目标身份。
|
||||
每次已授权的多候选 rank 只记录一个互斥原因:`coldExplore`、`periodicExplore`、`incumbentIneligible`、`freshFailureBypass`、`insufficientEvidenceHeld`、`incumbentHeld`、`reliabilityWinner` 或 `performanceWinner`。`ordinarySwitch` 记录同作用域普通已提交 A→B 变更,不含首次选择和试用;`switchFlap` 是其中八次普通选择内返回前一赢家的子集。候选过滤/退避计数保持独立。Peek 与展示/API 读取保持中性。经鉴权的 `/stats.score.groups[]` 只导出固定组/网络计数,`/stats.score.cache` 描述两个有界证据 LRU。详见 [API 原因语义](./api.md#score-选路原因字段),不导出 scorer 私有节点或目标身份。
|
||||
|
||||
采样在共享预算内解决明确的可用性/响应缺口,有进展的候选最多连续获得八次集中试用;新鲜等价候选停止强制采样,缺少传输证据则等待真实负载。新增 `scoreVerification` 区分临时转发、已观测可用性、限定比较、证据范围/有效期及下一步,详见 [API 验证](./api.md#score-验证信息)。这些是可撤销的经验结论,不是最优候选识别或未来网络行为的保证。
|
||||
|
||||
|
||||
Reference in new issue
Block a user