Backtestshugorun-20260930-140149#15027
metrics: --templateMetrics duration columns have inconsistent formatting
Our patch was judged better than the merged fix.
In this judgment, Patch A = our agent, Patch B = the merged fix.
Both patches fix the root cause the same way: `WriteMetrics` stops printing `time.Duration.String()` and calls a `formatDuration` helper that always prints two decimals with a fixed-width unit suffix. Correctness. Both align the decimal points. - Patch A uses `%.2f%-2s`, which gives a 2-rune unit (`"s "`, `"ms"`, `"µs"`, `"ns"`). Go's fmt measures width in runes, so the right-aligned `%15s`/`%12s` columns put every decimal point 5 runes from the end. - Patch B uses a 3-rune suffix (`" s"`, `" ms"`, `" µs"`, `" ns"`), which also aligns. - Neither patch breaks the aligned-column behaviour the issue asks for. - Patch A's output keeps the existing value-plus-unit token shape (`1.50s`, `12.00µs`). The existing partials integration test regex still strips those tokens unchanged. - Patch B inserts a space between value and unit. The old regex would then strip only the unit and leave the number, so B has to change `tpl/partials/partials_integration_test.go`. The change is correct and B made it, but it shows B's format is a bigger departure from the old output. Tests. Patch A is stronger. - It unit-tests `formatDuration` across all units, including 0 and values over 60s. - It also adds an end-to-end `TestWriteMetricsDurationAlignment`. That test fills a `Store` with durations of different magnitudes, runs `WriteMetrics`, and checks that the rune indices of the decimal points match on every row. - That test checks the exact property the issue reports, and it would fail against the old `Duration.String()` output. - Patch B tests only the formatter's string output with four cases and never checks column alignment in the table. Scope and craft. Both are small and focused. - Patch A documents its helper. - Patch B adds a stray blank line and needs a regex change in an unrelated test file. Overall, Patch A is equally correct, verifies the alignment property directly, and needs no changes to existing tests.
The judge saw only the two patches, labelled A and B in random order, with issue links and version numbers removed. The reasoning above is shown verbatim.
Solve
30m 59s13 turns
Wall-clock time in the container
Full test suite
No new failures
3,728 passed · 99 skipped · 3,829 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
81vs 41 merged
Changed lines, ours vs merged
The issue
View on GitHubThe --templateMetrics output table prints duration values (sum/avg/max) using time.Duration.String(), which varies both units and decimal places depending on the magnitude. This makes the table hard to scan when rows have durations of different magnitudes.
Proposed fix: Use a fixed-decimal formatter (two decimal places, unit suffix padded to consistent width) so decimal points align across all rows in the table.
The two patches
metrics/metrics.goindex 08d9322ab..9d703c20c 100644@@ -180,9 +180,9 @@ func (s *Store) WriteMetrics(w io.Writer) { sort.Sort(bySum(results)) for _, v := range results { if s.calculateHints {- fmt.Fprintf(w, " %15s %12s %12s %9d %7.f %6d %5d %s\n", v.sum, v.avg, v.max, v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key)+ fmt.Fprintf(w, " %15s %12s %12s %9d %7.f %6d %5d %s\n", formatDuration(v.sum), formatDuration(v.avg), formatDuration(v.max), v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key) } else {- fmt.Fprintf(w, " %15s %12s %12s %5d %s\n", v.sum, v.avg, v.max, v.count, v.key)+ fmt.Fprintf(w, " %15s %12s %12s %5d %s\n", formatDuration(v.sum), formatDuration(v.avg), formatDuration(v.max), v.count, v.key) } } }@@ -248,6 +248,24 @@ func howSimilar(a, b any) int { return 0 } +// formatDuration formats d with two decimals and a fixed-width unit+// so that durations align on the decimal point in tabular output.+func formatDuration(d time.Duration) string {+ var value float64+ var unit string+ switch {+ case d < time.Microsecond:+ value, unit = float64(d), "ns"+ case d < time.Millisecond:+ value, unit = float64(d)/float64(time.Microsecond), "µs"+ case d < time.Second:+ value, unit = float64(d)/float64(time.Millisecond), "ms"+ default:+ value, unit = float64(d)/float64(time.Second), "s"+ }+ return fmt.Sprintf("%.2f%-2s", value, unit)+}+ // howSimilar is a naive diff implementation that returns // a number between 0-100 indicating how similar a and b are. // 100 is when all words in a also exists in b.metrics/metrics_test.goindex 83dc1433f..486d4683c 100644@@ -14,9 +14,11 @@ package metrics import (+ "bytes" "html/template" "strings" "testing"+ "time" "github.com/gohugoio/hugo/resources/page" @@ -66,3 +68,60 @@ func BenchmarkHowSimilar(b *testing.B) { howSimilar(s1, s2) } }++func TestFormatDuration(t *testing.T) {+ c := qt.New(t)++ for _, test := range []struct {+ d time.Duration+ expect string+ }{+ {0, "0.00ns"},+ {500 * time.Nanosecond, "500.00ns"},+ {12 * time.Microsecond, "12.00µs"},+ {1234567 * time.Nanosecond, "1.23ms"},+ {123456789 * time.Nanosecond, "123.46ms"},+ {1500 * time.Millisecond, "1.50s "},+ {90 * time.Second, "90.00s "},+ } {+ c.Assert(formatDuration(test.d), qt.Equals, test.expect, qt.Commentf("%d", test.d))+ }+}++func TestWriteMetricsDurationAlignment(t *testing.T) {+ c := qt.New(t)++ s := NewProvider(false).(*Store)+ s.metrics["a"] = []time.Duration{1500 * time.Millisecond, 500 * time.Millisecond}+ s.metrics["b"] = []time.Duration{123456789 * time.Nanosecond}+ s.metrics["c"] = []time.Duration{12 * time.Microsecond}+ s.metrics["d"] = []time.Duration{500 * time.Nanosecond}++ var buf bytes.Buffer+ s.WriteMetrics(&buf)++ lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")+ c.Assert(len(lines), qt.Equals, 3+len(s.metrics))++ // Rune indices of the decimal points in each of the three duration columns.+ decimalPositions := func(line string) []int {+ var positions []int+ for i, r := range []rune(line) {+ if r == '.' {+ positions = append(positions, i)+ }+ }+ return positions+ }++ var expect []int+ for _, line := range lines[3:] {+ positions := decimalPositions(line)+ c.Assert(positions, qt.HasLen, 3, qt.Commentf("line: %q", line))+ if expect == nil {+ expect = positions+ continue+ }+ c.Assert(positions, qt.DeepEquals, expect, qt.Commentf("line: %q\n%s", line, buf.String()))+ }+}
metrics/metrics.goindex 08d9322ab..aca7c4c9b 100644@@ -178,15 +178,29 @@ func (s *Store) WriteMetrics(w io.Writer) { } sort.Sort(bySum(results))+ for _, v := range results { if s.calculateHints {- fmt.Fprintf(w, " %15s %12s %12s %9d %7.f %6d %5d %s\n", v.sum, v.avg, v.max, v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key)+ fmt.Fprintf(w, " %15s %12s %12s %9d %7.f %6d %5d %s\n", formatDuration(v.sum), formatDuration(v.avg), formatDuration(v.max), v.cacheFactor, float64(v.cacheCount)/float64(v.count)*100, v.cacheCount, v.count, v.key) } else {- fmt.Fprintf(w, " %15s %12s %12s %5d %s\n", v.sum, v.avg, v.max, v.count, v.key)+ fmt.Fprintf(w, " %15s %12s %12s %5d %s\n", formatDuration(v.sum), formatDuration(v.avg), formatDuration(v.max), v.count, v.key) } } } +func formatDuration(d time.Duration) string {+ switch {+ case d >= time.Second:+ return fmt.Sprintf("%.2f s", float64(d)/float64(time.Second)) // additional spacing between value and unit+ case d >= time.Millisecond:+ return fmt.Sprintf("%.2f ms", float64(d)/float64(time.Millisecond))+ case d >= time.Microsecond:+ return fmt.Sprintf("%.2f µs", float64(d)/float64(time.Microsecond))+ default:+ return fmt.Sprintf("%.2f ns", float64(d)/float64(time.Nanosecond))+ }+}+ // A result represents the calculated results for a given metric. type result struct { key stringmetrics/metrics_test.goindex 83dc1433f..1e5221ec1 100644@@ -17,6 +17,7 @@ import ( "html/template" "strings" "testing"+ "time" "github.com/gohugoio/hugo/resources/page" @@ -66,3 +67,21 @@ func BenchmarkHowSimilar(b *testing.B) { howSimilar(s1, s2) } }++func TestFormatDuration(t *testing.T) {+ c := qt.New(t)+ tests := []struct {+ duration time.Duration+ want string+ }{+ {4*time.Second + 342*time.Millisecond, "4.34 s"}, // additional spacing between value and unit+ {170*time.Millisecond + 289*time.Microsecond, "170.29 ms"},+ {16*time.Microsecond + 90*time.Nanosecond, "16.09 µs"},+ {147 * time.Nanosecond, "147.00 ns"},+ }++ for _, tt := range tests {+ got := formatDuration(tt.duration)+ c.Assert(got, qt.Equals, tt.want)+ }+}tpl/partials/partials_integration_test.goindex dc49cbdc5..58b4248c0 100644@@ -170,8 +170,8 @@ D1 got := buf.String() - // Get rid of all the durations, they are never the same.- durationRe := regexp.MustCompile(`\b[\.\d]*(ms|ns|µs|s)\b`)+ // Get rid of all the durations, including the space and unit, they are never the same.+ durationRe := regexp.MustCompile(`\b[\.\d]*\s*(ms|ns|µs|s)\b`) normalize := func(s string) string { s = durationRe.ReplaceAllString(s, "")
What the agent reported
I fixed the misaligned duration columns in --templateMetrics, but ./bt-test ./metrics/ couldn't run here. There's no Go module cache and proxy.golang.org can't be reached, so the run ended with FAIL github.com/gohugoio/hugo/metrics [setup failed] before compiling anything. My test evidence comes from a separate stdlib-only module in /tmp instead (described below).
What was wrong: WriteMetrics in metrics/metrics.go printed sum, average and maximum using Go's default duration formatting. That gives 2s, 1.5s, 123.456789ms or 12µs depending on size, so the number of decimals and the unit width changed from row to row and the decimal points didn't line up.
What I changed:
metrics/metrics.go: added a small helper,formatDuration. It picks ns, µs, ms or s by magnitude and prints two decimals with the unit padded to two characters, so seconds get a trailing space. Examples:500.00ns,12.00µs,123.46ms,1.50s. Both table-row print calls use it now; column widths and headers are unchanged.metrics/metrics_test.go: added two tests.TestFormatDurationchecks seven values across all four units.TestWriteMetricsDurationAlignmentwrites a table with 2s, 123ms, 12µs and 500ns rows. It asserts that every row has three decimal points and that they sit in the same character columns.
Test evidence:
- Stand-in check: I copied
metrics.goand the two new tests into a throwaway module with stand-ins for the three Hugo imports and for quicktest, then deleted it. - With the new code, both tests pass.
- With the old code (
formatDurationreturning the default string), both fail. For example, the table row reads2s 1s 1.5sand has only one decimal point instead of three. - Other checks:
gofmtreports nothing. - Not run: the existing tests (
TestSimilarPercentage*), because they need the real dependencies. They don't touch the code I changed. - Before merging, run
./bt-test ./metrics/in an environment with module access.
Blast radius: only the data rows of the --templateMetrics table change. Nothing else calls this formatting.
Requirements:
- Replace the default duration formatting for sum/avg/max: done in both table variants (with and without cache hints); covered by the alignment test.
- Two decimal places: done; covered by
TestFormatDuration. - Unit suffix padded to a consistent width: done;
sbecomess, andµcounts as one character for padding. Covered by both tests. - Decimal points align across rows of different magnitudes: done; covered by the alignment test (passes with the change, fails without it in the stand-in module).
The reviewer found no blocking problems. One cosmetic quirk: the unit is chosen before rounding, so 999,999ns prints as 1000.00µs rather than 1.00ms. Alignment still holds.
The changes are uncommitted, with no scratch files left in the repo. AGENTS.md and CLAUDE.md were already deleted before I started, and I didn't touch them.