feat(mtr): 新增几何均值和抖动列及 Fields 编辑页

增加 Drop 和可重复的空格列,统一文本输出与回放间距;向 JSON report、回放及 MCP 输出新增统计字段,并覆盖零 RTT、迁移合并和终端交互。
This commit is contained in:
tsosunchia committed 2026-09-08 18:28:38 +08:00
1 parent 751e9e3618
commit 795d7de7aa
28 files changed
+760 -120

No files matched your search

+2 -1
View File
@@ -124,7 +124,8 @@
- `--mtr-record FILE` 独占创建新文件,保留完整 UTF-8 JSON 行;写入失败停止探测。首个会话错误及阶段不被后续录制 start/finish 错误覆盖。
- `--mtr-replay FILE` 为纯离线独立入口,拒绝 target/探测参数/stdin;TTY 默认停在末尾,非 TTY/report 输出最终表,JSON 使用独立 `mtr_replay` 文档。
- 回放 `j/J` 定位、Space 播放、`p` 暂停、`r` 回到开头;残缺文件恢复有效前缀但非零退出。显示副本过滤 Unicode Cc/Cf,文件与 JSON 原值保留。
- `--mtr-columns` 只控制 MTR/回放文本列,不改变 RAW/JSON;`o/O` 会话内编辑,`d/D` 历史视图、`g/G` 切换三种图表。默认统计列不变,新增可选 Received/Rcv。
- `--mtr-columns` 只控制 MTR/回放文本列,不改变 RAW/JSON 的列选择;`o/O` 会话内编辑,`d/D` 历史视图、`g/G` 切换三种图表。默认统计列不变,可选 Received/Rcv、Dropped/Drop、Gmean/Jttr/Javg/Jmax/Jint;`space` 和编辑态空格增加实际间距。
- 扩展统计在共享 `MTRHopStat` 计算,JSON report/回放和 MCP 输出对应字段;旧录制按事件顺序重算。Jint 使用 mtr 累积尺度,公式与零值规则见 `docs/mtr-columns.md`。
- 契约与验收入口:[MTR JSON](docs/mtr-json.md)、[录制/回放](docs/mtr-session.md)、[CLI 说明](skills/nexttrace/references/cli-fallback.md)。
### Doctor、fwmark 与 TOS
+8 -5
View File
@@ -711,11 +711,13 @@ nexttrace -w --mtr-columns received,snt,last 1.1.1.1
ntr --mtr-columns received 1.1.1.1
```
`--mtr-columns` accepts any nonempty selection of `loss,snt,received,last,avg,best,wrst,stdev`, in the supplied order. Names ignore case and surrounding spaces; unknown names, duplicates and empty entries are errors. `received` is displayed as `Rcv`. The default remains `Loss%, Snt, Last, Avg, Best, Wrst, StDev`.
`--mtr-columns` accepts any nonempty selection of `loss,snt,received,last,avg,best,wrst,stdev,dropped,gmean,jitter,javg,jmax,jint,space`, in the supplied order. Names ignore case and surrounding spaces; unknown names, duplicate metrics and empty entries are errors. `space` adds one display space and may repeat; at least one metric is required. `received` is displayed as `Rcv`. The default remains `Loss%, Snt, Last, Avg, Best, Wrst, StDev`.
The option applies to TUI, non-TTY tables and report/wide output, including offline replay text output. It does not enable MTR: full/tiny require `-t`, `-r` or `-w`; ntr uses its default MTR mode. RAW, JSON, traditional traceroute and other standalone modes reject it before initialization. Custom TUI columns keep complete numbers and at least 8 Host cells; a narrow terminal shows a notice until widened or fewer columns are selected.
Press `o/O` to edit the current column codes: `L=Loss S=Snt R=Received N=Last A=Avg B=Best W=Wrst V=StDev`. Codes ignore case; spaces separate codes. Enter validates and applies, Esc cancels, Backspace deletes and Ctrl-U clears. Invalid or duplicate codes and an empty draft keep the editor open. Bracketed paste converts newlines to spaces without submitting. The draft is limited to 256 ASCII characters.
Press `o/O` to edit the current column codes: `L=Loss D=Drop R=Received S=Snt N=Last B=Best A=Avg W=Wrst V=StDev G=Gmean J=Jttr M=Javg X=Jmax I=Jint`. Codes ignore case; each space adds one display space. Leading, trailing and repeated spaces are preserved. Enter validates and applies, Esc cancels, Backspace deletes and Ctrl-U clears. Invalid or duplicate metric codes, an empty draft and a spaces-only draft keep the editor open. Bracketed paste converts newlines to spaces without submitting. The draft is limited to 256 ASCII characters.
The `Fields:` page lists every code on a separate line. See [MTR column metrics](docs/mtr-columns.md) for formulas, spacing examples and JSON fields.
While editing, other shortcuts are inactive and Ctrl-C still exits. Editing does not pause probes, reset counters or change the paused state. Applying a selection from history view returns to the statistics table; cancellation preserves the view. History columns stay fixed. Changes last only for this session; editing and resizing work while paused.
@@ -1099,9 +1101,10 @@ Arguments:
-w --wide MTR wide report mode (implies --mtr
--report); alone equals --mtr --report
--wide
--mtr-columns MTR text columns in order: loss,snt,
received,last,avg,best,wrst,stdev;
does not enable MTR
--mtr-columns MTR text columns in order: loss, snt,
received, last, avg, best, wrst, stdev,
dropped, gmean, jitter, javg, jmax, jint,
space (does not enable MTR)
--show-ips MTR only: display both PTR hostnames and
numeric IPs (PTR first, IP in parentheses)
-y --ipinfo Set initial MTR TUI host info mode (0-4).
+8 -5
View File
@@ -702,11 +702,13 @@ nexttrace -w --mtr-columns received,snt,last 1.1.1.1
ntr --mtr-columns received 1.1.1.1
```
`--mtr-columns` 支持 `loss,snt,received,last,avg,best,wrst,stdev` 的任意非空子集及顺序,忽略大小写与列名两端空格;未知列、重复列、空项报错。`received` 显示为 `Rcv`。默认仍为 `Loss%、Snt、Last、Avg、Best、Wrst、StDev`。
`--mtr-columns` 支持 `loss,snt,received,last,avg,best,wrst,stdev,dropped,gmean,jitter,javg,jmax,jint,space` 的任意非空子集及顺序,忽略大小写与列名两端空格;未知列、重复指标列、空项报错。`space` 增加一格显示间距,可重复,但至少需要一个指标列。`received` 显示为 `Rcv`。默认仍为 `Loss%、Snt、Last、Avg、Best、Wrst、StDev`。
参数适用于 TUI、非 TTY 表格和 report/wide,也支持离线回放的文字输出;不自动开启 MTR:full/tiny 需配合 `-t/-r/-w`,ntr 使用默认 MTR 模式。RAW、JSON、传统 traceroute 和其他独立模式会在初始化前拒绝该参数。自定义 TUI 保留完整数字及至少 8 格 Host;空间不足时显示提示,加宽终端或减少列后恢复。
按 `o/O` 编辑当前字段码:`L=Loss S=Snt R=Received N=Last A=Avg B=Best W=Wrst V=StDev`。输入不区分大小写,空格用于分隔。Enter 校验并应用,Esc 取消,Backspace 删除末尾字符,Ctrl-U 清空。空串、未知码和重复码保留编辑状态并显示错误。括号粘贴中的换行转为空格,不自动提交;草稿最多 256 个 ASCII 字符。
按 `o/O` 编辑当前字段码:`L=Loss D=Drop R=Received S=Snt N=Last B=Best A=Avg W=Wrst V=StDev G=Gmean J=Jttr M=Javg X=Jmax I=Jint`。输入不区分大小写;每个空格增加一格实际显示间距,保留首尾及连续空格。Enter 校验并应用,Esc 取消,Backspace 删除末尾字符,Ctrl-U 清空。空串、纯空格、未知码和重复指标码保留编辑状态并显示错误。括号粘贴中的换行转为空格,不自动提交;草稿最多 256 个 ASCII 字符。
`Fields:` 页面逐行列出字段说明。计算口径、空格示例及 JSON 字段见 [MTR 列指标](docs/mtr-columns.md)。
编辑期间其他快捷键不生效,Ctrl-C 仍退出;探测、计数及暂停状态保持不变。从历史视图应用列后返回统计表,取消则保留历史视图。历史图表的固定列不变,列选择仅在当前会话有效;暂停期间仍可编辑和调整窗口大小。
@@ -1074,9 +1076,10 @@ Arguments:
-w --wide MTR wide report mode (implies --mtr
--report); alone equals --mtr --report
--wide
--mtr-columns MTR text columns in order: loss,snt,
received,last,avg,best,wrst,stdev;
does not enable MTR
--mtr-columns MTR text columns in order: loss, snt,
received, last, avg, best, wrst, stdev,
dropped, gmean, jitter, javg, jmax, jint,
space (does not enable MTR)
--show-ips MTR only: display both PTR hostnames and
numeric IPs (PTR first, IP in parentheses)
-y --ipinfo Set initial MTR TUI host info mode (0-4).
+1 -1
View File
@@ -568,7 +568,7 @@ func registerMTRFlags(parser *argparse.Parser) mtrCLIFlags {
}
return mtrCLIFlags{
mtrMode: mtrMode,
columns: parser.String("", "mtr-columns", &argparse.Options{Help: "MTR text columns in order: loss,snt,received,last,avg,best,wrst,stdev (does not enable MTR)"}),
columns: parser.String("", "mtr-columns", &argparse.Options{Help: "MTR text columns in order: loss, snt, received, last, avg, best, wrst, stdev, dropped, gmean, jitter, javg, jmax, jint, space (does not enable MTR)"}),
reportMode: parser.Flag("r", "report", &argparse.Options{Help: "MTR report mode (non-interactive, implies --mtr); can trigger MTR without --mtr"}),
wideMode: parser.Flag("w", "wide", &argparse.Options{Help: "MTR wide report mode (implies --mtr --report); alone equals --mtr --report --wide"}),
showIPs: parser.Flag("", "show-ips", &argparse.Options{Help: "MTR only: display both PTR hostnames and numeric IPs (PTR first, IP in parentheses)"}),
+21 -4
View File
@@ -40,7 +40,7 @@ func TestMTRColumnEditorApplyCancelAndIsolation(t *testing.T) {
}
feedMTRKeys(u, &k, "\x15rL\x7f n\r")
c, e := u.columnSnapshot()
if e.Active || printer.MTRColumnCodes(c) != "RN" || u.IsHistoryMode() || !u.IsPaused() {
if e.Active || printer.MTRColumnCodes(c) != "R N" || u.IsHistoryMode() || !u.IsPaused() {
t.Fatalf("%v %+v", c, e)
}
// Invalid/duplicate/empty drafts stay open, cancellation preserves applied columns and view.
@@ -54,14 +54,14 @@ func TestMTRColumnEditorApplyCancelAndIsolation(t *testing.T) {
feedMTRKeys(u, &k, "\x1b")
k.expireEscape(u, time.Now().Add(mtrEscapeDelay))
c, e = u.columnSnapshot()
if e.Active || printer.MTRColumnCodes(c) != "RN" || !u.IsHistoryMode() {
if e.Active || printer.MTRColumnCodes(c) != "R N" || !u.IsHistoryMode() {
t.Fatal("cancel changed state")
}
}
// Returned selection is isolated from callers.
c[0] = printer.MTRColumnLoss
c, _ = u.columnSnapshot()
if printer.MTRColumnCodes(c) != "RN" {
if printer.MTRColumnCodes(c) != "R N" {
t.Fatal("snapshot aliases state")
}
}
@@ -89,7 +89,7 @@ func TestMTRColumnEditorEscapePasteAndLimit(t *testing.T) {
}
feedMTRKeys(u, &k, "\r")
c, e := u.columnSnapshot()
if e.Active || printer.MTRColumnCodes(c) != "RNL" {
if e.Active || printer.MTRColumnCodes(c) != "R N L" {
t.Fatal(c, e)
}
feedMTRKeys(u, &k, "o\x15"+strings.Repeat("a", 300))
@@ -205,3 +205,20 @@ func TestMTRRedrawInitialPausedResizeAndCleanup(t *testing.T) {
t.Fatal("wrote after cleanup")
}
}
func TestMTRColumnEditorNewCodesKeepReplayShortcutsIsolated(t *testing.T) {
u := newMTRUI(nil, 0)
u.replay = &mtrReplayControls{commands: make(chan mtrReplayCommand, 1), duration: time.Hour}
u.paused.Store(true)
var k mtrKeyInput
feedMTRKeys(u, &k, "o\x15 DGJMXI \r")
columns, editor := u.columnSnapshot()
if editor.Active || printer.MTRColumnCodes(columns) != " DGJMXI " || u.replayEditor.Active || !u.IsPaused() {
t.Fatalf("%v %+v", columns, editor)
}
feedMTRKeys(u, &k, "o")
_, editor = u.columnSnapshot()
if editor.Draft != " DGJMXI " {
t.Fatal(editor)
}
}
+1 -1
View File
@@ -56,7 +56,7 @@ func TestMTRColumnsModeContract(t *testing.T) {
func TestMTRColumnsCLIRejectsBeforeInitialization(t *testing.T) {
cases := [][]string{
{"-r", "--mtr-columns", "loss,LOSS"}, {"-r", "--mtr-columns", ""},
{"-r", "--mtr-columns", "received,"}, {"-r", "--mtr-columns", "jitter"},
{"-r", "--mtr-columns", "received,"}, {"-r", "--mtr-columns", "unknown"},
{"-r", "--raw", "--mtr-columns", "loss"}, {"-r", "--json", "--mtr-columns", "loss"},
}
if runtime.GOOS == "windows" {
+68
View File
@@ -0,0 +1,68 @@
# MTR column metrics
Full, tiny and ntr support the same columns in live text output, reports and
offline replay. The default remains `LSNABWV` (Loss%, Snt, Last, Avg, Best, Wrst,
StDev). Column selection does not enable MTR or apply to RAW/JSON.
| Code | CLI name | Heading | JSON statistic | Definition |
| --- | --- | --- | --- | --- |
| D | dropped | Drop | dropped | Completed probes without a reply: snt minus received |
| G | gmean | Gmean | gmean_ms | Geometric mean of successful RTTs |
| J | jitter | Jttr | jitter_ms | Absolute difference of successive successful RTTs |
| M | javg | Javg | jitter_avg_ms | Mean jitter, including the first zero sample |
| X | jmax | Jmax | jitter_max_ms | Maximum jitter |
| I | jint | Jint | jitter_interarrival_ms | mtr-scale accumulator: I = 15/16 I + J |
| space | space | extra space | — | One additional display space |
RTT and jitter units are milliseconds. These definitions follow
[mtr's statistics](https://github.com/traviscross/mtr/blob/v0.94/ui/net.c), while
retaining NextTrace floating-point precision rather than mtr's integer microsecond
rounding. Jint deliberately uses mtr's accumulator scale, approximately 16 times
the divided RFC interarrival estimate. It is not measured packet-arrival spacing.
Statistics retain NextTrace's existing responder-per-row accounting. Successful
samples are consumed in aggregator/event order, independently for each TTL and
responder. Timeouts neither become zero RTTs nor break the successful RTT chain.
The first successful sample has zero jitter. A successful zero RTT participates
normally and makes the geometric mean zero. Rows without successful replies have
zero RTT-derived statistics in JSON; waiting text rows keep metric cells blank.
For successful RTTs 10, 20 and 40 ms, Gmean is 20, Jttr 20, Javg 10, Jmax 20 and
Jint 29.375 ms. A timeout between these replies changes Drop, not those metrics.
The mean is evaluated in log space, without retaining the full sample history.
Reset clears these statistics. Metadata updates do not add samples. The retained
`MigrateStats` API joins the destination successful sequence followed by the
source sequence, including their boundary jitter. Its count cap preserves derived
statistics by rescaling cumulative means; it does not reconstruct a truncated
sample prefix. Live destination handling clears old rows rather than migrating
them.
## Selection and spacing
```sh
nexttrace -w --mtr-columns loss,snt,space,dropped,gmean,jitter,javg,jmax,jint example.com
nexttrace --mtr-replay session.jsonl --mtr-columns loss,space,space,jitter,jint
```
CSV names ignore case and surrounding whitespace. Use explicit `space` entries
for spacing; an empty CSV entry remains invalid. Spaces may repeat, including at
the beginning and end, but at least one metric is required. Metrics cannot repeat.
In the `o/O` Fields editor, literal spaces insert the same extra spacing. The page
lists each code with its description. Enter applies, Esc cancels, Backspace deletes,
Ctrl-U clears, and Ctrl-C exits. Bracketed paste maps newlines and tabs to spaces
without submitting. Editing does not pause or resume probing. The selection
survives reopening the editor but is not persisted as a user preference.
## Structured output and recordings
All six numeric fields are included in CLI JSON reports, replay JSON and
`nexttrace_mtr_report` service/MCP statistics, even when zero. JSON schema version
remains 1; consumers must tolerate additive fields. MCP output schema describes
the fields and units. RAW, NDJSON and WebSocket probe events remain unchanged;
they do not gain aggregate snapshots.
Existing recordings retain raw RTTs and can be replayed with the new metrics.
Recording schema and event order are unchanged. See [session compatibility](mtr-session.md#extended-column-statistics)
for replaying a recording with new column names in an older binary.
+5 -1
View File
@@ -87,7 +87,11 @@ Example validation failure:
Statistics are shared with text wide reports, without reaggregation or row
collapsing. Each [MTRHopStat](../trace/mtr_stats.go) has `ttl`, optional `host`
and `ip`, `loss_percent`, `snt`, `last_ms`, `avg_ms`, `best_ms`, `wrst_ms`,
`stdev_ms`, `received`, and optional `geo`, `mpls`, `response`. Multiple responders
`stdev_ms`, `received`, `dropped`, `gmean_ms`, `jitter_ms`, `jitter_avg_ms`,
`jitter_max_ms`, `jitter_interarrival_ms`, and optional `geo`, `mpls`, `response`.
The additional statistics are always present, including zero values, within
schema version 1. See [column metrics](mtr-columns.md) for definitions and the
mtr-scale interarrival accumulator (not the divided RFC estimate). Multiple responders
and unknown rows retain the aggregator's existing identity and ordering rules.
`snt` counts completed events already entered into the aggregator. Interruptions
do not synthesize timeout events for in-flight probes. RTT units are milliseconds.
+12
View File
@@ -195,3 +195,15 @@ go to stderr. A completed probe session is not itself a reachability verdict.
Recordings contain target, source and responder addresses and available
metadata. Redact those fields before attaching files to a public issue when
they identify private infrastructure.
## Extended column statistics
Replay recomputes dropped packets, geometric mean and jitter from the recorded
successful RTTs in event sequence order, not completion-timestamp order. Existing
recordings need no conversion. See [column metrics](mtr-columns.md).
The recording schema stays unchanged. A new recording may name additional
columns (including `space`) in `display.columns`. Older binaries need an explicit
supported `--mtr-columns` selection for text replay of such a recording; JSON
replay does not parse display columns. Interactive column edits remain local to
the display and do not rewrite the recording's initial column selection.
+3 -1
View File
@@ -51,7 +51,9 @@ func TestServiceJSONContractsGolden(t *testing.T) {
Wrst: 1.75,
StDev: 0.25,
Received: 2,
MPLS: []string{"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"},
Dropped: 1, GMean: 1.479019945774904,
Jitter: 0.5, JitterAvg: 0.25, JitterMax: 0.5, JitterInterarrival: 0.5,
MPLS: []string{"[MPLS: Lbl 16000, TC 0, S 1, TTL 63]"},
Response: &trace.MTRProbeResponse{
Kind: trace.MTRResponseTransit,
Description: "ICMP Time Exceeded",
+6
View File
@@ -36,6 +36,12 @@
"protocol": "icmp",
"stats": [
{
"dropped": 1,
"gmean_ms": 1.479019945774904,
"jitter_ms": 0.5,
"jitter_avg_ms": 0.25,
"jitter_max_ms": 0.5,
"jitter_interarrival_ms": 0.5,
"ttl": 1,
"host": "edge.example",
"ip": "192.0.2.1",
+47 -9
View File
@@ -20,35 +20,55 @@ const (
MTRColumnBest
MTRColumnWrst
MTRColumnStDev
MTRColumnDropped
MTRColumnGMean
MTRColumnJitter
MTRColumnJitterAvg
MTRColumnJitterMax
MTRColumnJitterInterarrival
MTRColumnSpace
)
var mtrColumnDefinitions = [...]struct {
name, title string
code byte
description string
}{
{"loss", "Loss%", 'L'}, {"snt", "Snt", 'S'}, {"received", "Rcv", 'R'},
{"last", "Last", 'N'}, {"avg", "Avg", 'A'}, {"best", "Best", 'B'},
{"wrst", "Wrst", 'W'}, {"stdev", "StDev", 'V'},
{"loss", "Loss%", 'L', "Loss Ratio"},
{"snt", "Snt", 'S', "Sent Packets"},
{"received", "Rcv", 'R', "Received Packets"},
{"last", "Last", 'N', "Newest RTT(ms)"},
{"avg", "Avg", 'A', "Average RTT(ms)"},
{"best", "Best", 'B', "Min/Best RTT(ms)"},
{"wrst", "Wrst", 'W', "Max/Worst RTT(ms)"},
{"stdev", "StDev", 'V', "Standard Deviation"},
{"dropped", "Drop", 'D', "Dropped Packets"},
{"gmean", "Gmean", 'G', "Geometric Mean"},
{"jitter", "Jttr", 'J', "Current Jitter"},
{"javg", "Javg", 'M', "Jitter Mean/Avg."},
{"jmax", "Jmax", 'X', "Worst Jitter"},
{"jint", "Jint", 'I', "Interarrival Jitter"},
{"space", "", ' ', "Space between fields"},
}
func DefaultMTRColumns() []MTRColumn {
return []MTRColumn{MTRColumnLoss, MTRColumnSnt, MTRColumnLast, MTRColumnAvg, MTRColumnBest, MTRColumnWrst, MTRColumnStDev}
}
// ParseMTRColumns accepts comma-separated CLI names, or space-separated TUI codes.
// ParseMTRColumns accepts comma-separated CLI names or TUI codes; spaces add display spacing.
func ParseMTRColumns(input string, codes bool) ([]MTRColumn, error) {
tokens := strings.Split(strings.ToLower(input), ",")
if codes {
tokens = nil
for _, c := range strings.ToUpper(input) {
if c != ' ' {
tokens = append(tokens, string(c))
}
tokens = append(tokens, string(c))
}
}
var columns []MTRColumn
for _, token := range tokens {
token = strings.TrimSpace(token)
if !codes {
token = strings.TrimSpace(token)
}
if token == "" {
return nil, fmt.Errorf("empty MTR column entry")
}
@@ -79,11 +99,17 @@ func ValidateMTRColumns(columns []MTRColumn) error {
if int(c) >= len(mtrColumnDefinitions) {
return fmt.Errorf("unknown MTR column %d", c)
}
if c == MTRColumnSpace {
continue
}
if seen[c] {
return fmt.Errorf("duplicate MTR column %s", mtrColumnDefinitions[c].name)
}
seen[c] = true
}
if len(seen) == 0 {
return fmt.Errorf("select at least one MTR column")
}
return nil
}
@@ -120,6 +146,18 @@ func mtrColumnValue(c MTRColumn, s trace.MTRHopStat) string {
return formatMs(s.Wrst)
case MTRColumnStDev:
return formatMs(s.StDev)
case MTRColumnDropped:
return fmt.Sprint(s.Dropped)
case MTRColumnGMean:
return formatMs(s.GMean)
case MTRColumnJitter:
return formatMs(s.Jitter)
case MTRColumnJitterAvg:
return formatMs(s.JitterAvg)
case MTRColumnJitterMax:
return formatMs(s.JitterMax)
case MTRColumnJitterInterarrival:
return formatMs(s.JitterInterarrival)
default:
return ""
}
@@ -144,7 +182,7 @@ func mtrSelectedMetrics(columns []MTRColumn, widths []int, stat *trace.MTRHopSta
value = mtrColumnValue(c, *stat)
}
cells[i] = padLeft(value, widths[i])
if colorize && stat != nil && (c == MTRColumnLoss || c == MTRColumnSnt || c == MTRColumnReceived) {
if colorize && stat != nil && (c == MTRColumnLoss || c == MTRColumnSnt || c == MTRColumnReceived || c == MTRColumnDropped) {
cells[i], _ = mtrColorPacketsByLoss(cells[i], "", stat.Loss, isWaitingHopStat(*stat))
}
}
+77 -25
View File
@@ -16,32 +16,64 @@ type MTRColumnEditor struct {
Draft, Error string
}
func renderMTRColumnEditor(b *strings.Builder, editor MTRColumnEditor, width int) {
var line string
for _, word := range strings.Fields("L=Loss S=Snt R=Received N=Last A=Avg B=Best W=Wrst V=StDev") {
if line != "" && len(line)+1+len(word) > width {
tuiLine(b, "%s", line)
line = ""
}
if line != "" {
line += " "
}
line += word
func renderMTRColumnEditor(b *strings.Builder, header MTRTUIHeader, width, height int) {
editor := header.ColumnEditor
prefix := "Fields: "
if width < len(prefix)+2 {
prefix = ""
}
tuiLine(b, "%s", truncateByDisplayWidth(line, width))
for _, help := range []string{"Enter: apply Esc: cancel", "Backspace: delete", "Ctrl-U: clear"} {
tuiLine(b, "%s", truncateByDisplayWidth(help, width))
}
prefix := "Columns: "
available := max(1, width-len(prefix)-1)
draft := editor.Draft
if len(draft) > available {
draft = draft[len(draft)-available:]
}
tuiLine(b, "%s", truncateByDisplayWidth(prefix+draft+"_", width))
fields := prefix + draft + "_"
// Leave the last terminal row unused: CRLF there would scroll the page.
remaining := max(0, height-1)
line := func(text string) {
if remaining > 0 {
tuiLine(b, "%s", truncateByDisplayWidth(text, width))
remaining--
}
}
if height >= 9 {
line(buildMTRTUITitleLine(header, width))
if width < 40 {
line(buildMTRTUIRouteText(header))
} else {
line(buildMTRTUIRouteLine(header, width, mtrTUIClock(header)))
}
}
line(fields)
if editor.Error != "" {
tuiLine(b, "%s", truncateByDisplayWidth(editor.Error, width))
line(editor.Error)
}
// Keep editing controls visible even when the field list does not fit.
controls := []string{"Enter: apply Esc: cancel", "Backspace: delete", "Ctrl-U: clear Ctrl-C: quit"}
if width >= 72 {
controls = []string{"Enter: apply Esc: cancel Backspace: delete Ctrl-U: clear Ctrl-C: quit"}
}
order := []MTRColumn{MTRColumnSpace, MTRColumnLoss, MTRColumnDropped, MTRColumnReceived,
MTRColumnSnt, MTRColumnLast, MTRColumnBest, MTRColumnAvg, MTRColumnWrst,
MTRColumnStDev, MTRColumnGMean, MTRColumnJitter, MTRColumnJitterAvg,
MTRColumnJitterMax, MTRColumnJitterInterarrival}
if remaining >= len(order)+len(controls)+2 {
line("")
}
count := min(len(order), max(0, remaining-len(controls)-1))
for _, column := range order[:count] {
def := mtrColumnDefinitions[column]
code := string(def.code)
if column == MTRColumnSpace {
code = "<sp>"
}
line(" " + code + ": " + def.description)
}
if count < len(order) && remaining > len(controls) {
line("Enlarge terminal for help")
}
for _, help := range controls {
line(help)
}
}
@@ -89,9 +121,7 @@ func MTRTablePrinterWithColumns(stats []trace.MTRHopStat, iteration, mode, nameM
}
fmt.Print("\033[H\033[2J")
headers := []any{"Hop"}
for _, c := range columns {
headers = append(headers, mtrColumnDefinitions[c].title)
}
headers = append(headers, mtrTableColumnCells(columns, nil)...)
headers = append(headers, "Host")
tbl := table.New(headers...).WithWriter(os.Stdout)
tbl.WithHeaderFormatter(color.New(color.FgGreen, color.Underline).SprintfFunc()).WithFirstColumnFormatter(color.New(color.FgYellow).SprintfFunc())
@@ -103,9 +133,7 @@ func MTRTablePrinterWithColumns(stats []trace.MTRHopStat, iteration, mode, nameM
}
prevTTL = s.TTL
row := []any{hop}
for _, c := range columns {
row = append(row, mtrColumnValue(c, s))
}
row = append(row, mtrTableColumnCells(columns, &s)...)
row = append(row, appendMTRResponseMarker(formatMTRHostWithMPLS(s, mode, nameMode, lang, showIPs), s))
tbl.AddRow(row...)
}
@@ -145,3 +173,27 @@ func renderMTRSelectedHeader(b *strings.Builder, header MTRTUIHeader, width int)
tuiLine(b, "%s", truncateByDisplayWidth("O:cols Q:quit "+mtrTUIStatusText(header.Status), width))
}
}
// table applies two spaces of padding per cell. Attach explicit spacers to real
// cells so each requested space adds exactly one character, not another column.
func mtrTableColumnCells(columns []MTRColumn, stat *trace.MTRHopStat) []any {
var cells []any
spaces := ""
for _, c := range columns {
if c == MTRColumnSpace {
spaces += " "
continue
}
value := mtrColumnDefinitions[c].title
if stat != nil {
value = mtrColumnValue(c, *stat)
}
cells = append(cells, spaces+value)
spaces = ""
}
if spaces != "" && len(cells) > 0 {
last := len(cells) - 1
cells[last] = cells[last].(string) + spaces
}
return cells
}
+119 -7
View File
@@ -15,8 +15,8 @@ func TestMTRColumnContract(t *testing.T) {
for _, tt := range []struct{ names, codes string }{
{"loss,snt,last,avg,best,wrst,stdev", "LSNABWV"},
{"received", "r"}, {" LAST ", "n"},
{"loss,snt,received,last,avg,best,wrst,stdev", "L S R N A B W V"},
{"stdev,wrst,best,avg,last,received,snt,loss", "vwb anrsl"},
{"loss,snt,received,last,avg,best,wrst,stdev", "LSRNABWV"},
{"stdev,wrst,best,avg,last,received,snt,loss", "vwbanrsl"},
{"avg,received,loss,stdev,snt", "ARLVS"},
} {
a, err := ParseMTRColumns(tt.names, false)
@@ -35,12 +35,12 @@ func TestMTRColumnContract(t *testing.T) {
t.Fatalf("roundtrip: %v", err)
}
}
for _, s := range []string{"", " ", ",", "loss,", ",snt", "loss,,snt", "loss,LOSS", "rcv", "jitter"} {
for _, s := range []string{"", " ", ",", "loss,", ",snt", "loss,,snt", "loss,LOSS", "rcv", "unknown"} {
if _, err := ParseMTRColumns(s, false); err == nil {
t.Errorf("accepted %q", s)
}
}
for _, s := range []string{"", " ", "LL", "l L", "X", "L,S", "L\nS", "L\tS", "L"} {
for _, s := range []string{"", " ", "LL", "l L", "Z", "L,S", "L\nS", "L\tS", "L"} {
if _, err := ParseMTRColumns(s, true); err == nil {
t.Errorf("accepted %q", s)
}
@@ -124,7 +124,7 @@ func TestMTRCustomFrameAndEditorStayWithinTerminal(t *testing.T) {
}
}
if editing {
for _, code := range []string{"L=Loss", "S=Snt", "R=Received", "N=Last", "A=Avg", "B=Best", "W=Wrst", "V=StDev"} {
for _, code := range []string{"L: Loss", "S: Sent", "R: Received", "N: Newest", "A: Average", "B: Min/Best", "W: Max/Worst", "V: Standard", "G: Geometric", "J: Current", "M: Jitter", "X: Worst", "I: Interarrival"} {
if !strings.Contains(out, code) {
t.Fatalf("missing %s in %d: %s", code, width, out)
}
@@ -143,8 +143,8 @@ func TestMTRColumnsDistinguishesEmptyAndUnknownEntries(t *testing.T) {
t.Fatalf("input %q: %v", input, err)
}
}
_, err := ParseMTRColumns("jitter", false)
if err == nil || err.Error() != `unknown MTR column "jitter"` {
_, err := ParseMTRColumns("unknown", false)
if err == nil || err.Error() != `unknown MTR column "unknown"` {
t.Fatalf("unknown column: %v", err)
}
}
@@ -188,3 +188,115 @@ func TestMTRDefaultControlsMeasureVisibleColorWidth(t *testing.T) {
t.Fatalf("colored controls: %q", line)
}
}
func TestMTRExpandedColumnsAndSpaces(t *testing.T) {
for _, tt := range []struct{ names, codes string }{
{"dropped,gmean,jitter,javg,jmax,jint", "DGJMXI"},
{"loss,space,avg", "L A"},
{"space,loss,space,space,avg,space", " L A "},
} {
columns, err := ParseMTRColumns(tt.names, false)
if err != nil || MTRColumnCodes(columns) != tt.codes {
t.Fatalf("%v %v", columns, err)
}
roundtrip, err := ParseMTRColumns(tt.codes, true)
if err != nil || !slices.Equal(columns, roundtrip) {
t.Fatalf("roundtrip %v %v", roundtrip, err)
}
}
for _, input := range []string{"space", "space,space", "jitter,JITTER", "loss, ,avg"} {
if _, err := ParseMTRColumns(input, false); err == nil {
t.Fatalf("accepted %q", input)
}
}
stat := trace.MTRHopStat{TTL: 1, IP: "192.0.2.1", Dropped: 2, GMean: 20, Jitter: 20, JitterAvg: 10, JitterMax: 20, JitterInterarrival: 29.375}
columns, _ := ParseMTRColumns("dropped,gmean,jitter,javg,jmax,jint", false)
widths := mtrColumnWidths(columns, []trace.MTRHopStat{stat})
if got := strings.Fields(mtrSelectedMetrics(columns, widths, &stat, false)); !slices.Equal(got, []string{"2", "20.00", "20.00", "10.00", "20.00", "29.38"}) {
t.Fatal(got)
}
stat = trace.MTRHopStat{TTL: 1, Snt: 2, Dropped: 2, Loss: 100}
if strings.TrimSpace(mtrSelectedMetrics(columns, widths, &stat, false)) != "" {
t.Fatal("waiting row has metrics")
}
}
func TestMTRSpaceWidthAcrossTextOutputs(t *testing.T) {
old := color.NoColor
color.NoColor = true
t.Cleanup(func() { color.NoColor = old })
stat := trace.MTRHopStat{TTL: 1, IP: "192.0.2.1", Loss: 1, Avg: 2}
for _, tt := range []struct {
codes string
extra int
}{{"LA", 0}, {"L A", 1}, {"L A", 2}, {" LA ", 2}} {
columns, _ := ParseMTRColumns(tt.codes, true)
base, _ := ParseMTRColumns("LA", true)
renderers := []func([]MTRColumn) string{
func(c []MTRColumn) string {
return mtrSelectedMetrics(c, mtrColumnWidths(c, []trace.MTRHopStat{stat}), &stat, false)
},
func(c []MTRColumn) string {
return captureStdout(t, func() { MTRTablePrinterWithColumns([]trace.MTRHopStat{stat}, 1, 0, 0, "en", false, c) })
},
func(c []MTRColumn) string {
return captureStdout(t, func() {
MTRReportPrint([]trace.MTRHopStat{stat}, MTRReportOptions{Columns: c, SrcHost: "source", Wide: true})
})
},
func(c []MTRColumn) string {
var b strings.Builder
err := WriteMTRReplayReport(&b, []trace.MTRHopStat{stat}, MTRReportOptions{Columns: c, SrcHost: "source", Wide: true})
if err != nil {
t.Fatal(err)
}
return b.String()
},
}
for i, render := range renderers {
got, want := strings.Split(strings.TrimSuffix(render(columns), "\n"), "\n"), strings.Split(strings.TrimSuffix(render(base), "\n"), "\n")
if len(got) != len(want) {
t.Fatal(got, want)
}
for row := range got {
if strings.Contains(got[row], "Loss%") || strings.Contains(got[row], "1.0%") {
if len(got[row])-len(want[row]) != tt.extra {
t.Fatalf("renderer %d codes %q: %q versus %q", i, tt.codes, got[row], want[row])
}
}
}
}
}
}
func TestMTRFieldsPageDimensions(t *testing.T) {
old := color.NoColor
color.NoColor = true
t.Cleanup(func() { color.NoColor = old })
for _, size := range [][2]int{{80, 24}, {24, 24}, {80, 10}, {24, 8}, {24, 4}} {
for _, replay := range []bool{false, true} {
h := MTRTUIHeader{Target: "192.0.2.1", SrcHost: "source", ColumnEditor: MTRColumnEditor{Active: true, Draft: "LS DGJMXI", Error: "duplicate MTR column loss"}}
if replay {
h.Replay = &MTRReplayStatus{Complete: true}
}
var b strings.Builder
mtrTUIRenderWithSize(&b, h, nil, size[0], size[1])
out := strings.TrimPrefix(b.String(), "\x1b[H\x1b[2J")
if strings.Count(out, "\r\n") >= size[1] || !strings.Contains(out, "Fields: LS DGJMXI_") {
t.Fatal(size, out)
}
for _, line := range strings.Split(out, "\r\n") {
if displayWidth(line) > size[0] {
t.Fatalf("overflow %v: %q", size, line)
}
}
if size[1] >= 24 {
for _, label := range []string{"D: Dropped Packets", "G: Geometric Mean", "J: Current Jitter", "M: Jitter Mean/Avg.", "X: Worst Jitter", "I: Interarrival Jitter"} {
if !strings.Contains(out, label) {
t.Fatalf("missing %s: %s", label, out)
}
}
}
}
}
}
+10 -4
View File
@@ -369,11 +369,19 @@ var getTermWidth = func() int {
// MTRTUIRender 将 MTR TUI 帧渲染到 w。
// 每帧重新获取终端宽度并计算自适应布局。
func MTRTUIRender(w io.Writer, header MTRTUIHeader, stats []trace.MTRHopStat) {
mtrTUIRenderWithWidth(w, header, stats, getTermWidth())
_, height, err := term.GetSize(int(os.Stdout.Fd()))
if err != nil || height <= 0 {
height = 24
}
mtrTUIRenderWithSize(w, header, stats, getTermWidth(), height)
}
// mtrTUIRenderWithWidth 是带可控宽度的内部渲染入口(测试用)。
func mtrTUIRenderWithWidth(w io.Writer, header MTRTUIHeader, stats []trace.MTRHopStat, termWidth int) {
mtrTUIRenderWithSize(w, header, stats, termWidth, 24)
}
func mtrTUIRenderWithSize(w io.Writer, header MTRTUIHeader, stats []trace.MTRHopStat, termWidth, termHeight int) {
lo := buildMTRTUILayout(stats, termWidth)
var b strings.Builder
@@ -385,9 +393,7 @@ func mtrTUIRenderWithWidth(w io.Writer, header MTRTUIHeader, stats []trace.MTRHo
return
}
if header.ColumnEditor.Active {
tuiLine(&b, "%s", buildMTRTUITitleLine(header, lo.termWidth))
tuiLine(&b, "%s", mtrTUIStatusText(header.Status))
renderMTRColumnEditor(&b, header.ColumnEditor, lo.termWidth)
renderMTRColumnEditor(&b, header, lo.termWidth, termHeight)
_, _ = fmt.Fprint(w, b.String())
return
}
+27 -9
View File
@@ -29,11 +29,11 @@ def main(binary):
master, slave = pty.openpty()
original = termios.tcgetattr(slave)
def resize(width):
def resize(width, height=32):
if windows:
process.setwinsize(32, width)
process.setwinsize(height, width)
else:
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 32, width, 0, 0))
fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", height, width, 0, 0))
def read(seconds=0.3):
end = time.monotonic() + seconds
@@ -71,8 +71,12 @@ def main(binary):
assert rows, text
return rows[-1].split()
command = [
os.path.abspath(binary), "-t", "--mtr-columns", "loss,snt,received,avg",
help_result = subprocess.run([binary, "--help"], capture_output=True, text=True,
check=True, timeout=10)
# ntr defaults to MTR and does not register --mtr.
mode = ["--mtr"] if re.search(r"^\s+-t\s+--mtr\s", help_result.stdout, re.M) else []
command = [os.path.abspath(binary)] + mode + [
"--mtr-columns", "loss,snt,received,avg",
"-d", "disable-geoip", "-n", "-s", "127.0.0.1", "-m", "1",
"-i", "100", "--timeout", "100", "--no-color", "127.0.0.1",
]
@@ -88,9 +92,9 @@ def main(binary):
send("p")
paused = expect("Paused") + read(0.6) # Drain any in-flight probes.
send("o")
expect("Columns: LSRA_", "\x1b[?2004h")
expect("Fields: LSRA_", "\x1b[?2004h")
send("\x15\x1b[200~r\nl s n a b w v\x1b[201~")
expect("Columns: r l s n a b w v_")
expect("Fields: r l s n a b w v_")
send("\r")
applied = expect("Rcv", "Last", "Paused", "\x1b[?2004l")
old, new = counters(paused), counters(applied)
@@ -99,7 +103,7 @@ def main(binary):
resize(24)
expect("Select fewer columns")
send("o")
expect("Columns: RLSNABWV_", "R=Received", "N=Last")
expect("Fields: R L S N A B W V_", "R: Received", "N: Newest")
send("\x15l\x1b")
expect("Select fewer columns") # Bare Esc needs no subsequent read.
resize(120)
@@ -109,6 +113,19 @@ def main(binary):
send("o\x15ar\r")
applied = expect("Avg", "Rcv", "Paused")
assert "History" not in applied.split("\x1b[H\x1b[2J")[-1], applied
resize(160, 24)
send("o")
expect("Fields:", "G: Geometric Mean", "I: Interarrival Jitter")
send("\x15 DRSGJMXI \r")
expect("Drop", "Gmean", "Jttr", "Javg", "Jmax", "Jint", "Paused")
send("o")
expect("Fields: DRSGJMXI _")
resize(80, 10)
expect("Fields: DRSGJMXI _", "Enlarge terminal", "Enter: apply")
send("\x15GG\r")
expect("duplicate MTR column gmean")
send("\x1b")
expect("Drop", "Jint", "Paused")
send("q")
expect("\x1b[?1049l", "\x1b[?25h")
if windows:
@@ -126,7 +143,8 @@ def main(binary):
"checks": ["loopback probes", "pause", "prefill", "paste newline",
"apply", "unchanged paused counters", "narrow notice",
"narrow editor", "bare Esc", "resize while paused",
"history apply", "terminal restore"],
"history apply", "expanded metrics", "space roundtrip",
"short editor", "duplicate metric", "terminal restore"],
}, indent=2))
finally:
if windows:
+1 -1
View File
@@ -220,7 +220,7 @@ def main(binary):
offline.send("d")
offline.expect("History")
offline.send("o")
offline.expect("Columns:")
offline.expect("Fields:")
offline.send("\x15la\r")
offline.expect("Loss%", "Avg", "Paused")
offline.send(" ")
+8 -1
View File
@@ -72,7 +72,7 @@ func (s *recordingMCPService) MTRReport(_ context.Context, input service.MTRRepo
Target: "example.com",
ResolvedIP: "93.184.216.34",
Protocol: "icmp",
Stats: []trace.MTRHopStat{{TTL: 1, Geo: &ipgeo.IPGeoData{Router: map[string][]string{}}}},
Stats: []trace.MTRHopStat{{TTL: 1, Snt: 3, Received: 2, Dropped: 1, GMean: 1.5, Jitter: 0.5, JitterAvg: 0.25, JitterMax: 0.5, JitterInterarrival: 0.5, Geo: &ipgeo.IPGeoData{Router: map[string][]string{}}}},
PathEnd: &service.TraceStopReason{Hop: 4, Reason: trace.StopReasonDestination},
}, nil
}
@@ -190,6 +190,13 @@ func TestMCPHandlerRegistersAllToolsWithSchemas(t *testing.T) {
assertSchemaProperties(t, byName["nexttrace_traceroute"].OutputSchema, []string{"stop_reason"})
assertSchemaProperties(t, byName["nexttrace_mtr_report"].OutputSchema, []string{"path_end"})
assertSchemaProperties(t, byName["nexttrace_mtr_raw"].OutputSchema, []string{"path_end"})
reportSchema := schemaMap(t, byName["nexttrace_mtr_report"].OutputSchema)
statsSchema := reportSchema["properties"].(map[string]any)["stats"].(map[string]any)
itemSchema := statsSchema["items"].(map[string]any)
if ref, ok := itemSchema["$ref"].(string); ok {
itemSchema = reportSchema["$defs"].(map[string]any)[strings.TrimPrefix(ref, "#/$defs/")].(map[string]any)
}
assertSchemaProperties(t, itemSchema, []string{"dropped", "gmean_ms", "jitter_ms", "jitter_avg_ms", "jitter_max_ms", "jitter_interarrival_ms"})
}
func TestMCPHandlerCallsEveryToolWithStructuredContent(t *testing.T) {
+8 -2
View File
@@ -35,6 +35,7 @@
{
"avg_ms": 0,
"best_ms": 0,
"dropped": 1,
"geo": {
"asnumber": "",
"city": "",
@@ -55,10 +56,15 @@
"source": "",
"whois": ""
},
"gmean_ms": 1.5,
"jitter_avg_ms": 0.25,
"jitter_interarrival_ms": 0.5,
"jitter_max_ms": 0.5,
"jitter_ms": 0.5,
"last_ms": 0,
"loss_percent": 0,
"received": 0,
"snt": 0,
"received": 2,
"snt": 3,
"stdev_ms": 0,
"ttl": 1,
"wrst_ms": 0
@@ -90,3 +90,16 @@ Globalping CLI mode is single-location oriented. For Agent multi-location work,
nexttrace --deploy --mcp
nexttrace --deploy --mcp --listen 0.0.0.0:1080 --deploy-token "$TOKEN"
```
### MTR column metrics
Use `--mtr-columns loss,snt,space,dropped,gmean,jitter,javg,jmax,jint` in MTR text
mode or offline replay. `space` inserts one extra display space; it may repeat.
`o/O` opens the `Fields:` editor, where literal spaces have the same meaning.
Codes `D/G/J/M/X/I` select Drop/Gmean/Jttr/Javg/Jmax/Jint. The default columns stay
unchanged. `--mtr-columns` remains unavailable with RAW or JSON.
Jitter compares successive successful RTTs per responder row, across timeouts.
The first jitter is zero and participates in Javg. Jint is the mtr-scale
accumulator (`I = 15/16 I + jitter`), not the divided RFC estimate. Gmean includes
successful zero RTTs, which make it zero. Drop is `snt - received`.
+6
View File
@@ -71,6 +71,12 @@ Final answer shape: use [output-templates.md](output-templates.md#nexttrace_trac
### `nexttrace_mtr_report`
Runs bounded MTR and returns aggregated `stats[]` plus optional `path_end`.
Each row includes `dropped`, `gmean_ms`, `jitter_ms`, `jitter_avg_ms`,
`jitter_max_ms`, and `jitter_interarrival_ms`, including zero values. Jitter
compares successful RTTs within each responder row. The first zero jitter counts
in its mean. Interarrival jitter is the mtr-scale accumulator
`I = 15/16 I + jitter`, not the divided RFC estimate. No input parameter is needed
to obtain these fields.
Adds:
@@ -103,6 +103,11 @@ English template:
## `nexttrace_mtr_report`
When jitter or additional columns are requested, include the relevant
`dropped`, `gmean_ms`, `jitter_ms`, `jitter_avg_ms`, `jitter_max_ms`, and
`jitter_interarrival_ms` values from `stats[]`. Label the last as mtr-scale Jint;
do not present it as the divided RFC estimate. Keep the default table concise.
中文模板:
```markdown
+2 -1
View File
@@ -61,7 +61,8 @@ func TestMTRSessionReplayMatchesScheduler(t *testing.T) {
result.MPLS = []string{"label 20", "label 10"}
result.Response = &MTRProbeResponse{Kind: kind, Description: kind}
}
rt.processProbeSuccess(ttl, result, time.Now().Add(-time.Second))
// Completion timestamps may move backwards; application order is authoritative.
rt.processProbeSuccess(ttl, result, time.Now().Add(-time.Duration(len(events)+1)*time.Second))
if err := context.Cause(rt.ctx); err != nil {
t.Fatal(err)
}
+42 -29
View File
@@ -11,20 +11,26 @@ import (
// MTRHopStat 表示 MTR 输出中一行统计数据。
type MTRHopStat struct {
TTL int `json:"ttl"`
Host string `json:"host,omitempty"`
IP string `json:"ip,omitempty"`
Loss float64 `json:"loss_percent"`
Snt int `json:"snt"`
Last float64 `json:"last_ms"`
Avg float64 `json:"avg_ms"`
Best float64 `json:"best_ms"`
Wrst float64 `json:"wrst_ms"`
StDev float64 `json:"stdev_ms"`
Geo *ipgeo.IPGeoData `json:"geo,omitempty"`
MPLS []string `json:"mpls,omitempty"`
Received int `json:"received"`
Response *MTRProbeResponse `json:"response,omitempty"`
Dropped int `json:"dropped" jsonschema:"Completed probes without a reply on this responder row"`
GMean float64 `json:"gmean_ms" jsonschema:"Geometric mean of successful RTTs in milliseconds"`
Jitter float64 `json:"jitter_ms" jsonschema:"Absolute difference between successive successful RTTs in milliseconds"`
JitterAvg float64 `json:"jitter_avg_ms" jsonschema:"Mean jitter including the first zero sample in milliseconds"`
JitterMax float64 `json:"jitter_max_ms" jsonschema:"Maximum jitter in milliseconds"`
JitterInterarrival float64 `json:"jitter_interarrival_ms" jsonschema:"mtr-scale interarrival accumulator in milliseconds: I = 15/16 I + jitter, not the divided RFC estimate"`
TTL int `json:"ttl"`
Host string `json:"host,omitempty"`
IP string `json:"ip,omitempty"`
Loss float64 `json:"loss_percent"`
Snt int `json:"snt"`
Last float64 `json:"last_ms"`
Avg float64 `json:"avg_ms"`
Best float64 `json:"best_ms"`
Wrst float64 `json:"wrst_ms"`
StDev float64 `json:"stdev_ms"`
Geo *ipgeo.IPGeoData `json:"geo,omitempty"`
MPLS []string `json:"mpls,omitempty"`
Received int `json:"received"`
Response *MTRProbeResponse `json:"response,omitempty"`
}
// MTRSnapshot 是某一时刻的完整快照。
@@ -52,21 +58,28 @@ type mtrHopIdentity struct {
}
type mtrHopAccum struct {
identity mtrHopIdentity
host string
ip string
sent int
received int
sum float64
sumSq float64 // Σ(rtt²),用于在线方差
last float64
best float64
worst float64
geo *ipgeo.IPGeoData
order uint64
mplsSet map[string]struct{}
seenUpdate uint64
geoUpdate uint64
identity mtrHopIdentity
host string
ip string
sent int
received int
sum float64
sumSq float64 // Σ(rtt²),用于在线方差
logSum float64
hasZeroRTT bool
first float64
jitter float64
jitterSum float64
jitterMax float64
jitterInterarrival float64
last float64
best float64
worst float64
geo *ipgeo.IPGeoData
order uint64
mplsSet map[string]struct{}
seenUpdate uint64
geoUpdate uint64
}
// mtrTTLBucket keeps rows in first-observation order. index points into rows,
+23 -13
View File
@@ -113,6 +113,7 @@ func (agg *MTRAggregator) includeAttemptLocked(bucket *mtrTTLBucket, attempt Hop
}
rttMs := float64(attempt.RTT) / float64(time.Millisecond)
updateMTRVariability(acc, rttMs)
acc.sum += rttMs
acc.sumSq += rttMs * rttMs
acc.received++
@@ -153,6 +154,7 @@ func parseMTRAddr(value string) (netip.Addr, bool) {
}
func mergeMTRHopAccum(dst, src *mtrHopAccum) {
mergeMTRVariability(dst, src)
dst.sent += src.sent
dst.received += src.received
if src.received > 0 {
@@ -243,6 +245,8 @@ func capMTRHopAccum(acc *mtrHopAccum, maxPerHop int) {
sumSqNew = (sumNew * sumNew) / nNew
}
acc.logSum *= ratio
acc.jitterSum *= ratio
acc.sum = sumNew
acc.sumSq = sumSqNew
acc.received = acc.sent
@@ -284,19 +288,25 @@ func buildMTRHopStat(acc *mtrHopAccum, ttl int) MTRHopStat {
}
return MTRHopStat{
TTL: ttl,
Host: acc.host,
IP: acc.ip,
Loss: lossPct,
Snt: acc.sent,
Last: acc.last,
Avg: avg,
Best: best,
Wrst: acc.worst,
StDev: stdev,
Geo: acc.geo,
MPLS: mpls,
Received: acc.received,
Dropped: lossCount,
GMean: mtrGeometricMean(acc),
Jitter: acc.jitter,
JitterAvg: mtrJitterMean(acc),
JitterMax: acc.jitterMax,
JitterInterarrival: acc.jitterInterarrival,
TTL: ttl,
Host: acc.host,
IP: acc.ip,
Loss: lossPct,
Snt: acc.sent,
Last: acc.last,
Avg: avg,
Best: best,
Wrst: acc.worst,
StDev: stdev,
Geo: acc.geo,
MPLS: mpls,
Received: acc.received,
}
}
+65
View File
@@ -0,0 +1,65 @@
package trace
import "math"
// Keep successful samples in aggregator order, independently for each responder.
// Timeouts never enter this calculation. The first jitter is zero and counts in
// the mean, as in mtr. Interarrival jitter uses mtr's unscaled accumulator;
// retain floating-point precision instead of mtr's integer microsecond rounding.
func updateMTRVariability(acc *mtrHopAccum, rtt float64) {
if rtt <= 0 {
acc.hasZeroRTT = true
} else {
acc.logSum += math.Log(rtt)
}
if acc.received == 0 {
acc.first = rtt
return
}
acc.jitter = math.Abs(rtt - acc.last)
acc.jitterSum += acc.jitter
acc.jitterMax = max(acc.jitterMax, acc.jitter)
acc.jitterInterarrival = acc.jitterInterarrival*15/16 + acc.jitter
}
// MigrateStats appends the source summary after the destination summary, matching
// its existing last-RTT policy. Join the successful sequences at their boundary.
// A capped summary retains derived statistics, not an actual truncated prefix.
func mergeMTRVariability(dst, src *mtrHopAccum) {
if src.received == 0 {
return
}
dst.logSum += src.logSum
dst.hasZeroRTT = dst.hasZeroRTT || src.hasZeroRTT
if dst.received == 0 {
dst.first = src.first
dst.jitter = src.jitter
dst.jitterSum = src.jitterSum
dst.jitterMax = src.jitterMax
dst.jitterInterarrival = src.jitterInterarrival
return
}
boundary := math.Abs(src.first - dst.last)
dst.jitter = src.jitter
if src.received == 1 {
dst.jitter = boundary
}
dst.jitterSum += src.jitterSum + boundary
dst.jitterMax = max(dst.jitterMax, src.jitterMax, boundary)
decay := math.Pow(15.0/16, float64(src.received-1))
dst.jitterInterarrival = (dst.jitterInterarrival*15/16+boundary)*decay + src.jitterInterarrival
}
func mtrGeometricMean(acc *mtrHopAccum) float64 {
if acc.received == 0 || acc.hasZeroRTT {
return 0
}
return math.Exp(acc.logSum / float64(acc.received))
}
func mtrJitterMean(acc *mtrHopAccum) float64 {
if acc.received == 0 {
return 0
}
return acc.jitterSum / float64(acc.received)
}
+142
View File
@@ -0,0 +1,142 @@
package trace
import (
"math"
"net"
"reflect"
"testing"
"time"
)
func variabilityProbe(agg *MTRAggregator, ttl int, ip string, ms float64) {
hop := Hop{TTL: ttl}
if ip != "" {
hop.Success = true
hop.Address = &net.IPAddr{IP: net.ParseIP(ip)}
hop.RTT = time.Duration(ms * float64(time.Millisecond))
}
agg.Update(mtrGoldenResult(ttl, hop), 1)
}
func variabilityValues(s MTRHopStat) []float64 {
return []float64{s.GMean, s.Jitter, s.JitterAvg, s.JitterMax, s.JitterInterarrival}
}
func requireVariability(t *testing.T, got MTRHopStat, want []float64) {
t.Helper()
for i, value := range variabilityValues(got) {
if math.IsNaN(value) || math.IsInf(value, 0) || math.Abs(value-want[i]) > 1e-9*math.Max(1, math.Abs(want[i])) {
t.Fatalf("metric %d: got %v want %v", i, value, want[i])
}
}
}
func TestMTRVariabilitySuccessfulSequence(t *testing.T) {
for _, tt := range []struct {
name string
samples, want []float64
}{
{"first", []float64{10}, []float64{10, 0, 0, 0, 0}},
{"constant", []float64{7, 7, 7}, []float64{7, 0, 0, 0, 0}},
{"increasing", []float64{10, 20, 40}, []float64{20, 20, 10, 20, 29.375}},
{"zero", []float64{0, 10, 5}, []float64{0, 5, 5, 10, 14.375}},
{"submicrosecond", []float64{0.000001, 0.000004}, []float64{0.000002, 0.000003, 0.0000015, 0.000003, 0.000003}},
} {
t.Run(tt.name, func(t *testing.T) {
agg := NewMTRAggregator()
variabilityProbe(agg, 1, "", 0)
for _, ms := range tt.samples {
variabilityProbe(agg, 1, "192.0.2.1", ms)
}
variabilityProbe(agg, 1, "", 0)
stat := agg.Snapshot()[0]
requireVariability(t, stat, tt.want)
if stat.Dropped != 2 || stat.Snt != len(tt.samples)+2 || stat.Received != len(tt.samples) {
t.Fatal(stat)
}
})
}
agg := NewMTRAggregator()
variabilityProbe(agg, 1, "", 0)
requireVariability(t, agg.Snapshot()[0], []float64{0, 0, 0, 0, 0})
if agg.Snapshot()[0].Dropped != 1 {
t.Fatal(agg.Snapshot())
}
}
func TestMTRVariabilityResponderIsolation(t *testing.T) {
agg := NewMTRAggregator()
variabilityProbe(agg, 1, "192.0.2.1", 10)
variabilityProbe(agg, 1, "192.0.2.2", 100)
variabilityProbe(agg, 1, "", 0)
variabilityProbe(agg, 1, "192.0.2.1", 14)
stats := agg.Snapshot()
requireVariability(t, stats[0], []float64{math.Sqrt(140), 4, 2, 4, 4})
requireVariability(t, stats[1], []float64{100, 0, 0, 0, 0})
if len(stats) != 3 || stats[2].Dropped != 1 {
t.Fatal(stats)
}
before := agg.Snapshot()
clone := agg.Clone()
variabilityProbe(clone, 1, "192.0.2.1", 20)
if !reflect.DeepEqual(agg.Snapshot(), before) {
t.Fatal("clone contaminated original")
}
agg.ClearHop(1)
variabilityProbe(agg, 1, "192.0.2.1", 30)
requireVariability(t, agg.Snapshot()[0], []float64{30, 0, 0, 0, 0})
agg.Reset()
variabilityProbe(agg, 1, "192.0.2.1", 40)
requireVariability(t, agg.Snapshot()[0], []float64{40, 0, 0, 0, 0})
}
func TestMTRVariabilityMergeMatchesConcatenation(t *testing.T) {
for _, samples := range [][]float64{{10, 20, 40, 15, 30}, {0, 10, 4, 0}, {10, 10, 10}} {
full := NewMTRAggregator()
for _, ms := range samples {
variabilityProbe(full, 1, "192.0.2.1", ms)
}
for split := 0; split <= len(samples); split++ {
joined := NewMTRAggregator()
// Include empty-success summaries on either side as well as real sequences.
variabilityProbe(joined, 1, "", 0)
for i, ms := range samples {
ttl := 1
if i >= split {
ttl = 2
}
variabilityProbe(joined, ttl, "192.0.2.1", ms)
}
joined.MigrateStats(2, 1, 0)
stats := joined.Snapshot()
for _, stat := range stats {
if stat.Received > 0 {
requireVariability(t, stat, variabilityValues(full.Snapshot()[0]))
}
}
}
}
}
func TestMTRVariabilityCapPreservesDerivedStatistics(t *testing.T) {
agg := NewMTRAggregator()
for _, ms := range []float64{10, 20, 40, 80} {
variabilityProbe(agg, 2, "192.0.2.1", ms)
}
before := agg.Snapshot()[0]
agg.MigrateStats(2, 1, 1)
capped := agg.Snapshot()[0]
requireVariability(t, capped, variabilityValues(before))
if capped.Snt != 1 || capped.Received != 1 || capped.Dropped != 0 {
t.Fatal(capped)
}
variabilityProbe(agg, 1, "192.0.2.1", 40)
requireVariability(t, agg.Snapshot()[0], []float64{math.Sqrt(before.GMean * 40), 40, (before.JitterAvg + 40) / 2, 40, before.JitterInterarrival*15/16 + 40})
variabilityProbe(agg, 2, "192.0.2.1", 20)
agg.MigrateStats(2, 1, 0)
for _, v := range variabilityValues(agg.Snapshot()[0]) {
if math.IsNaN(v) || math.IsInf(v, 0) {
t.Fatal(v)
}
}
}
+30
View File
@@ -2,6 +2,12 @@
"iteration": 3,
"stats": [
{
"dropped": 1,
"gmean_ms": 10.000000000000002,
"jitter_ms": 0,
"jitter_avg_ms": 0,
"jitter_max_ms": 0,
"jitter_interarrival_ms": 0,
"ttl": 1,
"host": "edge.example",
"ip": "192.0.2.1",
@@ -19,6 +25,12 @@
"received": 1
},
{
"dropped": 0,
"gmean_ms": 19.999999999999996,
"jitter_ms": 0,
"jitter_avg_ms": 0,
"jitter_max_ms": 0,
"jitter_interarrival_ms": 0,
"ttl": 2,
"host": "core-a.example",
"ip": "198.51.100.1",
@@ -32,6 +44,12 @@
"received": 1
},
{
"dropped": 0,
"gmean_ms": 30.000000000000004,
"jitter_ms": 0,
"jitter_avg_ms": 0,
"jitter_max_ms": 0,
"jitter_interarrival_ms": 0,
"ttl": 2,
"host": "core-b.example",
"ip": "198.51.100.2",
@@ -45,6 +63,12 @@
"received": 1
},
{
"dropped": 1,
"gmean_ms": 0,
"jitter_ms": 0,
"jitter_avg_ms": 0,
"jitter_max_ms": 0,
"jitter_interarrival_ms": 0,
"ttl": 2,
"loss_percent": 100,
"snt": 1,
@@ -56,6 +80,12 @@
"received": 0
},
{
"dropped": 0,
"gmean_ms": 40,
"jitter_ms": 0,
"jitter_avg_ms": 0,
"jitter_max_ms": 0,
"jitter_interarrival_ms": 0,
"ttl": 3,
"ip": "2001:db8::3",
"loss_percent": 0,