Repository navigation
perf: cache compiled path regexes and cut request validation allocations - #340
emilien-puget wants to merge 1 commit into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #340 +/- ##
==========================================
+ Coverage 98.74% 98.82% +0.07%
==========================================
Files 94 95 +1
Lines 12310 12451 +141
==========================================
+ Hits 12156 12305 +149
+ Misses 129 125 -4
+ Partials 25 21 -4
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
5371269 to
d2edbce
Compare
daveshanley
left a comment
There was a problem hiding this comment.
Thanks @emilien-puget, this is a seriously good PR. Half the allocations, a 42% geomean drop, and benchmarks that cover the shapes people actually run. That's the kind of thing I love seeing land.
The ExtractParamsForOperation change also fixes a real race that I don't think anyone had spotted. Nice work.
The one thing I'd like changed before merging is the global regex cache, because nothing ever frees it. Details inline. The HEAD and QUERY comments are older bugs that you happened to walk past, so follow-ups are fine for those.
| // | ||
| // ClearRegexCache empties the cache. Call it between document lifecycles in | ||
| // long-running processes to bound memory. | ||
| var regexCache sync.Map // map[string]*regexp.Regexp |
There was a problem hiding this comment.
This is the one I'd like to change before we merge. The cache lives for the life of the process, and nothing ever calls ClearRegexCache. validator.Release() and ValidationOptions.Release() exist so a service can load a spec, validate, throw it away and get its memory back. This cache skips that contract.
Some of our own tools load a lot of specs in one long-running process, so every template from every spec stays here forever. At your measured 4.3 KB an entry, that adds up fast.
GetRegexForPath is also exported. Anyone passing it strings that aren't templates now grows this map without limit, where it used to hold no state at all.
What do you think about defaulting RegexCache to a per-validator sync.Map in NewValidatorFromV3Model instead? Same hit rate, and Release() cleans it up for free.
| func ExtractParamsForOperation(request *http.Request, item *v3.PathItem) []*v3.Parameter { | ||
| params := item.Parameters | ||
| var operationParams []*v3.Parameter | ||
| switch request.Method { |
There was a problem hiding this comment.
Same family as the HEAD comment below, and also older than this PR. There's no case for QUERY or for AdditionalOperations, and the router resolves both. So a 3.2 query operation with its own required params gets matched, and then only the path level params are validated. Fine for a follow-up.
| params = append(params, item.Options.Parameters...) | ||
| operationParams = item.Options.Parameters | ||
| } | ||
| case http.MethodHead: |
There was a problem hiding this comment.
This one predates you, but you're in here so I'll flag it. For a HEAD request on a path with no head operation, ExtractOperation and the router both fall back to get. This function doesn't, so it returns only the path level params.
So HEAD /reports is validated as the GET operation, but GET's required query and header params are never checked. Falling back to item.Get here, the same way ExtractOperation does, closes it. Happy for that to go in here or in a follow-up, your call.
| return item.Parameters | ||
| } | ||
| if len(item.Parameters) == 0 { | ||
| return operationParams |
There was a problem hiding this comment.
This now hands back the operation's own Parameters slice when there are no path level params. Everything in the repo only reads the result, so we're fine internally. It's exported though, so I'd add a line to the doc comment saying the result is read-only. Otherwise someone appends to it and writes straight into the shared model.
| require.Equal(t, []*v3.Parameter{operationOnly}, got) | ||
| }) | ||
|
|
||
| t.Run("both sides merge without writing into the model slice", func(t *testing.T) { |
There was a problem hiding this comment.
Great catch on the backing array. Concurrent GET and POST requests on the same path item could stomp on each other's parameter lists, which is a properly sneaky bug.
The test can't see it though. item.Parameters here has len == cap, so the old append reallocates and passes too. Revert the fix and this test stays green. Build it with spare capacity, something like make([]*v3.Parameter, 1, 4), then check the slot past len is untouched.
| @@ -1,10 +1,10 @@ | |||
| package helpers | |||
There was a problem hiding this comment.
Tiny one: this file is missing the standard copyright header. Worth adding while you're in here.
| // The function ensures that the template is well-formed, with balanced and properly | ||
| // nested braces. If the template is invalid, an error is returned. | ||
| // | ||
| // Compiled regexes are cached by template string. The first call for a template |
There was a problem hiding this comment.
With this in, path segments get cached twice: once here, and again in the user's config.RegexCache in path_parameters.go and paths.comparePaths. WithRegexCache still says it enables regex caching, which is now always on. If the per-validator default from my other comment works out, we're back to one cache and the option means something again.
| // the same values BraceIndices computes. The indices come from the compile | ||
| // cache, so repeated calls for one template do not re-scan it. Callers must | ||
| // treat the returned slice as read-only. An invalid template returns an error. | ||
| func GetBraceIndicesForPath(tpl string) ([]int, error) { |
There was a problem hiding this comment.
The doc says this returns the same values BraceIndices computes, but on a cache miss it runs the whole regex compile. So {id:(abc)} gets indices from BraceIndices and an error from this.
Today that's mostly hidden because GetRegexForPath runs first. In ValidatePathParamsWithPathItem though, when the regex came out of a user supplied RegexCache, this error hits the continue and the segment's params are skipped without a peep. I'd compute the indices separately from the compile, or at least fix the doc.
| before, errBefore := GetRegexForPath("/cache-clear/{id}") | ||
| assert.NoError(t, errBefore) | ||
|
|
||
| ClearRegexCache() |
There was a problem hiding this comment.
These tests share the process-wide cache, and this one clears it while the identity tests next door assert on pointers from that same cache. Works today because nothing here calls t.Parallel(). The day someone adds it, these go flaky. One more nudge toward a cache that isn't global.
| // The schema will be stored and reused from cache if available, otherwise it will be compiled on each call. | ||
| func ValidateRequestSchema(input *ValidateRequestSchemaInput) (bool, []*liberrors.ValidationError) { | ||
| validationOptions := config.NewValidationOptions(input.Options...) | ||
| validationOptions := input.ValidationOptions |
There was a problem hiding this comment.
If someone sets both ValidationOptions and Options, the Options vanish without a word. These input structs are public, so I can see someone passing the validator's options plus config.WithFormatAssertions() for one call and wondering why formats aren't checked. Either document that they're mutually exclusive, or apply Options on top of a copy. Same thing in responses/validate_response.go.
|
thanks for the review @daveshanley , i had other ideas for performances improvments but first i wanted some parity with some previous work done in the main openapi library, i'm taking a look at your comment and might open follow ups |
|
Thanks for the thorough review @daveshanley — all findings are addressed in the pushed commits. The merge blocker — the global regex cache (regex_maker.go): gone, done the way you proposed. The two bugs we walked past — fixed with tests. The smaller findings:
The tests that share the process-wide regex cache are gone with it — the cache tests now seed the per-validator |
…ation allocations Request validation called helpers.GetRegexForPath for every path template on every request and recompiled the same regex each time, and the rest of the request hot path rebuilt per-request state it could reuse. This closes the gap with libopenapi, which caches compiled JSONPath expressions the same way. Changes: - Each validator owns its regex cache: NewValidatorFromV3Model defaults ValidationOptions.RegexCache to a fresh sync.Map, shared with the sub validators through WithExistingOpts, and ValidationOptions.Release empties an owned cache, so compiled regexes die with the validator. GetRegexForPath stays stateless: it compiles and returns. A cache set through config.WithRegexCache keeps the interface contract and stays shared. The default cache is called through its concrete *sync.Map type, so the template key does not box per lookup; custom caches keep the interface path. - The brace indices of path templates are cached on a per-validator map inside the parameter validator, so repeated segment scans allocate once per validator lifetime. - ExtractOperation resolves OpenAPI 3.2 query operations, methods declared under additionalOperations, and falls back to get for HEAD, matching the router. ExtractParamsForOperation delegates to it, so request-level method resolution and parameter extraction cannot drift. Previously a HEAD request on a get-only path skipped GET's required query and header parameters, and 3.2 query operations and custom methods were rejected with a false "no '<METHOD>' method found in the spec" error although the router had resolved them. - ExtractParamsForOperation returns the model slices untouched when one side is empty and merges into an exact-size slice otherwise: appending to item.Parameters can write into the model backing array, and the model stays shared across validators and requests. Its result may alias the model's slices, so the doc comment states it is read-only. - ValidateRequestSchema, ValidateResponseSchema and ValidateResponseHeaders accept pre-built options through an unexported core; internal callers stop building config.NewValidationOptions per request. Exported signatures are unchanged, and the input structs document that ValidationOptions and Options are mutually exclusive. - nonEmptyPathSegments walks the path once with strings.SplitSeq. - ExtractRawQueryValues returns nil for an empty query. - GetRenderedSchema returns the cached ReferenceSchema string instead of copying bytes per call. - compilePathRegexEntry assembles patterns with strings.Builder: bytes.Buffer writes cannot fail, so the unreachable error branch and the fmt call with its interface boxing are gone. Evidence: paired runs, 10 samples per side, benchstat (i7-1265U, Go 1.26), measured back-to-back main vs branch across 12 gateway scenarios including query-heavy, invalid-request, concurrent, format-assertions, strict-server, urlencoded, JSON-response-body and 200-route shapes: - plain GET: 96 -> 35 allocs/op (-64%), 8.0 -> 3.8 us (-52%) - param-heavy GET: 320 -> 94 allocs/op (-71%), 26.0 -> 11.2 us (-57%) - invalid request: 322 -> 96 allocs/op (-70%), 27.0 -> 11.1 us (-59%) - concurrent GET, 12 goroutines: 96 -> 35 allocs/op, 4.2 -> 1.4 us - large route table (200 paths): 113 -> 35 allocs/op (-69%), -68% - format assertions: 97 -> 36 allocs/op; strict server: 98 -> 37 - urlencoded body: 99 -> 87; JSON response body: 57 -> 48 - geomean: -42.6% sec/op, -53.9% B/op, -50.1% allocs/op Memory: an entry holds a few KB (measured 4.3 KB: key string plus compiled regex), so a 1,000-route API costs about 4 MB, and validator.Release drops it with the validator. One candidate was measured and rejected, recorded here: hoisting the per-segment regex out of the parameter loop cost +9% sec/op on the single-parameter shape (three precompute slices, nothing to dedupe). Verification: go test -race -count=1 ./... (21/21 packages), make lint (0 issues), CI green (build, lint, Codecov 100% patch coverage), new tests for the per-validator cache flow, brace indices, the exact-size merge with model-slice safety (verified to fail against the old append), the unbraced-segment skip, the operation resolution fixes, and 12 benchmark scenarios in validator_request_bench_test.go and validator_scenario_bench_test.go.
5ca5bab to
cf51e42
Compare
Goal
Request validation called
helpers.GetRegexForPathfor every path template on every request and recompiled the same regex each time, and the rest of the request hot path rebuilt per-request state it could reuse. This PR caches compiled regexes per validator, then applies the same discipline to the request and response hot path: stop rebuilding per-request state, hoist per-call allocations out of loops, and reuse what the validator already built.It also fixes operation resolution gaps this work surfaced:
ExtractParamsForOperationdisagreed withExtractOperationand the router for HEAD fallback, OpenAPI 3.2queryoperations, andadditionalOperationsmethods.It closes the gap with libopenapi, which caches its compiled JSONPath expressions the same way.
What changed
GetRegexForPathcompiles and returns; the state is gone fromhelpers. Each validator gets its own regex cache by default (NewValidatorFromV3ModelseedsValidationOptions.RegexCachewith a freshsync.Map), shared with the sub-validators throughWithExistingOpts.ValidationOptions.Release()empties an owned cache, so a service can load a spec, validate and get its memory back. A cache set throughconfig.WithRegexCachestays shared.paramValidatorkeeps a per-validator brace-index map with the same lifetime.ExtractOperationresolvesQUERY(OpenAPI 3.2) andadditionalOperationsmethods, and keeps its HEAD fallback toget.ExtractParamsForOperationdelegates to it, so request-level method resolution and parameter extraction can no longer disagree. Before this, a HEAD request on a get-only path skipped GET's required query and header parameters, and 3.2queryand custom methods were rejected with a false "no '' method found in the spec" error.ValidateRequestSchema,ValidateResponseSchemaandValidateResponseHeadersaccept pre-built options through an unexported core; internal callers stop buildingconfig.NewValidationOptionsper request. Exported signatures are unchanged.ExtractParamsForOperationreturns the model slices untouched when one side is empty and merges into an exact-size slice otherwise: appending toitem.Parameterscould write into the model backing array, which is shared across validators and requests. Its result is documented read-only.nonEmptyPathSegmentswalks the path once withstrings.SplitSeq;ExtractRawQueryValuesreturns nil for an empty query;GetRenderedSchemareturns the cachedReferenceSchemastring;compilePathRegexassembles patterns withstrings.Builder.Evidence
Paired runs, 10 samples per side, compared with
benchstat(i7-1265U, Go 1.26). Every commit was measured back-to-back; the table comparesmainagainst the final branch across 12 gateway scenarios. Allocation counts are exact (±0%); time is p<0.001 for the shapes this PR touches (the urlencoded shape shows ~ with allocation improvements of −12%).Reproduce:
Mechanism and memory
Each validator owns its regex cache:
NewValidatorFromV3ModeldefaultsValidationOptions.RegexCacheto a freshsync.Map, the validators built withWithExistingOptsshare it, andRelease()empties an owned cache, so compiled regexes die with the validator instead of living for the process lifetime. A custom cache set throughconfig.WithRegexCachekeeps working and stays shared.GetRegexForPathitself is stateless again. The default cache is a*sync.Mapand the hot paths call it concretely, so the template key does not box per lookup; the per-segment brace indices live in a per-validator map on the parameter validator with the same lifetime.One candidate was measured and rejected, recorded in the commit history: hoisting the per-segment regex out of the parameter loop cost +9% sec/op on the single-parameter shape (three precompute slices, nothing to dedupe), so it was reverted.
Verification
go test -race -count=1 ./...— 21/21 packages PASS (run after every change).make lint(golangci-lint, repo config) — 0 issues.ClearRegexCachesemantics at the options level, cached brace indices, the exact-size merge with model-slice safety, the unbraced-segment skip, and six tests pinning the HEAD/QUERY/additionalOperationsresolution gaps (each flipped by the fix in this PR).validator_request_bench_test.goandvalidator_scenario_bench_test.gocover query-heavy, invalid-request, concurrent, format-assertions, strict-server, urlencoded, JSON-response-body and 200-route shapes.