Backtestshugorun-20261002-200313#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 replace `time.Duration.String()` with a two-decimal formatter whose unit suffix has a fixed width. Since fmt pads by rune count, both make decimal points line up in right-aligned columns, so both fix the core issue.
Correctness: Patch A handles the rounding edge case. It moves to the next unit when the rounded value reaches 1000, so 999.996µs prints as 1.00ms rather than 1000.00µs, and it handles negative values. Patch B switches on the raw threshold, so it can print values like "1000.00 µs". Alignment still holds in that case, but the output is less tidy. Patch B's space between value and unit broke the existing duration-stripping regex in the partials integration test, and it correctly updated that test. Patch A's format ("1.23s ", "2.00ms") still matches the old regex, so no change was needed. Neither approach is wrong, but A's output stays compatible with existing consumers. One caveat: A relies on `strconv` and `math` already being imported in metrics.go, which I believe they are. A also detects the unit by round-tripping through ParseFloat, which is slightly clunky.
Tests: Patch A tests `formatDuration` thoroughly, including unit boundaries, rounding rollover and negatives. It also adds an end-to-end `WriteMetrics` test that checks decimal-point positions match across rows in both the hints and non-hints modes, which tests the issue's actual requirement. Patch B only unit-tests four representative values and never checks table alignment.
Scope and craft: both are focused. Patch B's code is simpler, but Patch A's edge-case handling and much stronger verification of the alignment property make it the better fix overall.
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
39m 26s
Wall-clock time in the container
Full test suite
No new failures
3,730 passed · 99 skipped · 3,831 total
Contamination audit
Clean
No sign the agent saw the real fix
Patch size
95vs 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..ea7819ff7 100644@@ -180,13 +180,38 @@ 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) } } } +// formatDuration formats d with two decimal places and a unit suffix+// padded to a fixed width, so that decimal points align when the+// values are right-aligned in a table column.+func formatDuration(d time.Duration) string {+ units := []struct {+ suffix string+ div time.Duration+ }{+ {"ns", time.Nanosecond},+ {"µs", time.Microsecond},+ {"ms", time.Millisecond},+ {"s ", time.Second},+ }+ var s string+ for _, u := range units {+ s = strconv.FormatFloat(float64(d)/float64(u.div), 'f', 2, 64) + u.suffix+ // Use the next unit if the rounded value reaches 1000,+ // e.g. 999.996µs is printed as 1.00ms, not 1000.00µs.+ if v, _ := strconv.ParseFloat(s[:len(s)-len(u.suffix)], 64); math.Abs(v) < 1000 {+ break+ }+ }+ return s+}+ // A result represents the calculated results for a given metric. type result struct { key stringmetrics/metrics_test.goindex 83dc1433f..37087d25e 100644@@ -14,9 +14,11 @@ package metrics import (+ "bytes" "html/template" "strings" "testing"+ "time" "github.com/gohugoio/hugo/resources/page" @@ -58,6 +60,70 @@ func TestSimilarPercentageNonString(t *testing.T) { c.Assert(howSimilar(testStruct{Name: "A"}, testStruct{Name: "A"}), qt.Equals, 100) } +func TestFormatDuration(t *testing.T) {+ c := qt.New(t)++ c.Assert(formatDuration(0), qt.Equals, "0.00ns")+ c.Assert(formatDuration(500*time.Nanosecond), qt.Equals, "500.00ns")+ c.Assert(formatDuration(1500*time.Nanosecond), qt.Equals, "1.50µs")+ c.Assert(formatDuration(123456*time.Nanosecond), qt.Equals, "123.46µs")+ c.Assert(formatDuration(2*time.Millisecond), qt.Equals, "2.00ms")+ c.Assert(formatDuration(1234567890*time.Nanosecond), qt.Equals, "1.23s ")+ c.Assert(formatDuration(90*time.Second), qt.Equals, "90.00s ")++ // Values that round up to 1000 of a unit use the next unit.+ c.Assert(formatDuration(999996*time.Nanosecond), qt.Equals, "1.00ms")+ c.Assert(formatDuration(999996*time.Microsecond), qt.Equals, "1.00s ")+ c.Assert(formatDuration(999994*time.Nanosecond), qt.Equals, "999.99µs")+ c.Assert(formatDuration(-1500*time.Nanosecond), qt.Equals, "-1.50µs")+}++func TestWriteMetricsAlignedDurations(t *testing.T) {+ for _, calculateHints := range []bool{false, true} {+ t.Run("", func(t *testing.T) {+ c := qt.New(t)++ s := NewProvider(calculateHints).(*Store)+ s.metrics["a.html"] = []time.Duration{1234567890 * time.Nanosecond, 2 * time.Second}+ s.metrics["b.html"] = []time.Duration{123456 * time.Nanosecond}+ s.metrics["c.html"] = []time.Duration{2 * time.Millisecond, 500 * time.Nanosecond}+ s.metrics["d.html"] = []time.Duration{42 * time.Nanosecond}++ var buf bytes.Buffer+ s.WriteMetrics(&buf)++ lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")[3:]+ c.Assert(lines, qt.HasLen, 4)++ // Each of the three duration columns must have its decimal point+ // at the same (rune) position in every row.+ var dotPositions [][]int+ for _, line := range lines {+ var positions []int+ for i, r := range []rune(line) {+ if r == '.' {+ positions = append(positions, i)+ }+ }+ c.Assert(len(positions) >= 3, qt.IsTrue, qt.Commentf("line: %q", line))+ dotPositions = append(dotPositions, positions[:3])+ }+ for _, positions := range dotPositions[1:] {+ c.Assert(positions, qt.DeepEquals, dotPositions[0], qt.Commentf("output:\n%s", buf.String()))+ }++ out := buf.String()+ c.Assert(out, qt.Contains, "3.23s ")+ c.Assert(out, qt.Contains, "1.62s ")+ c.Assert(out, qt.Contains, "2.00s ")+ c.Assert(out, qt.Contains, "123.46µs")+ c.Assert(out, qt.Contains, "2.00ms")+ c.Assert(out, qt.Contains, "1.00ms")+ c.Assert(out, qt.Contains, "42.00ns")+ })+ }+}+ func BenchmarkHowSimilar(b *testing.B) { s1 := "Hugo is cool and " + strings.Repeat("fun ", 10) + "!" s2 := "Hugo is cool and " + strings.Repeat("cool ", 10) + "!"
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, "")