From 1513c3266a6adddfc893099e2a3d2ead2b170ba6 Mon Sep 17 00:00:00 2001 From: Jeremy Schoemaker Date: Mon, 21 Sep 2026 03:18:13 -0500 Subject: [PATCH] fix(tree): grow skippedNodes stack when routes are added after pooling --- routes_test.go | 23 +++++++++++++++++++++++ tree.go | 9 +++++++++ 2 files changed, 32 insertions(+) diff --git a/routes_test.go b/routes_test.go index dbfaad5c..4a9bfb89 100644 --- a/routes_test.go +++ b/routes_test.go @@ -941,3 +941,26 @@ func TestIssue4818_MethodNotAllowedManyTrees(t *testing.T) { t.Fatalf("expected 405, got %d", w.Code) } } + +// TestRouterSkippedNodesGrowsAfterLateRouteRegistration ensures that a Context +// recycled from the pool can still walk a tree that became deeper after the +// Context was allocated. The skippedNodes stack is sized from engine.maxSections +// at allocation time, so routes registered after the first request used to make +// the tree walk reslice the stack beyond its capacity and panic. +func TestRouterSkippedNodesGrowsAfterLateRouteRegistration(t *testing.T) { + router := New() + router.GET("/a", func(c *Context) { c.String(http.StatusOK, "a") }) + + // Seed the pool with a Context sized for the shallow tree. + w := PerformRequest(router, http.MethodGet, "/a") + assert.Equal(t, http.StatusOK, w.Code) + + // Deepen the tree after a Context has already been pooled. + router.GET("/x/:p", func(c *Context) { c.String(http.StatusOK, "p") }) + router.GET("/x/y/:q", func(c *Context) { c.String(http.StatusOK, "q") }) + router.GET("/x/y/z/w", func(c *Context) { c.String(http.StatusOK, "w") }) + + w = PerformRequest(router, http.MethodGet, "/x/y/z/w") + assert.Equal(t, http.StatusOK, w.Code) + assert.Equal(t, "w", w.Body.String()) +} diff --git a/tree.go b/tree.go index 6efe2e0e..49ed6cab 100644 --- a/tree.go +++ b/tree.go @@ -440,6 +440,15 @@ walk: // Outer loop for walking the tree // strings.HasPrefix(n.children[len(n.children)-1].path, ":") == n.wildChild if n.wildChild { index := len(*skippedNodes) + // Preallocate capacity if necessary: the stack is + // sized from engine.maxSections when the Context was + // allocated, which can be stale for a pooled Context + // if routes were registered later. + if cap(*skippedNodes) < index+1 { + newSkippedNodes := make([]skippedNode, len(*skippedNodes), index+1) + copy(newSkippedNodes, *skippedNodes) + *skippedNodes = newSkippedNodes + } *skippedNodes = (*skippedNodes)[:index+1] (*skippedNodes)[index] = skippedNode{ path: prefix + path,