Repository navigation
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #694 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 316 316
Lines 40280 40608 +328
==========================================
+ Hits 40280 40608 +328
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:
|
|
Not sure if you are accepting external PRs or what the procedure is, but I'm using your lib in an arazzo tool I'm building and want to see if I can get these fixes for issues I ran into merged upstream. This should bring it closer in line with the full arazzo spec. I see there is already a PR for handling 1/0 properly so I can rebase and modify if that gets pushed. Thanks for the work you do on this library, love it. |
b492e05 to
46f2680
Compare
46f2680 to
6e7c78c
Compare
daveshanley
left a comment
There was a problem hiding this comment.
Thanks for this Shaun, and thanks for the kind words. Compound criteria have been a gap for a while, so this is very welcome. The parser is clean, the precedence is right, and the null rules are spot on.
A few things need sorting before it can go in. There are two tokenizer regressions (operators in JSON pointers, and UTF-8), a performance hit, and the output change, which I'd like to split out. Details inline.
Also, the description still talks about the 0/1 change and its tests. That fix (#690) already landed on main, so worth a tidy up.
| } | ||
|
|
||
| // isOptionalRuntimeValueError must only be called with a non-nil error. | ||
| func isOptionalRuntimeValueError(err error) bool { |
There was a problem hiding this comment.
Matching on error message text is going to bite us. Someone rewords an error in expression and the runtime quietly changes behaviour here.
It also misses a few cases that are just as "missing" as the ones listed:
{"items": []} $response.body#/items/0/id -> array index 0 out of bounds
{"data": null} $response.body#/data/id -> cannot traverse into scalar node
no headers sent $request.header.X -> no request headers available
The last one is inconsistent. If the step sent any other header, the same expression comes back as null. The engine leaves that map nil when a step sends no headers, so this happens for real.
I'd add a sentinel error in expression (like ErrLocalSymbolNotFound), wrap it with %w everywhere a value isn't there, and check it here with errors.Is.
And because || always evaluates both sides, $statusCode == 200 || $response.body#/items/0/id == 'x' errors on an empty list, even though the left side is true. I'd short-circuit.
There was a problem hiding this comment.
yes text error matching is dumb, I should have caught that. One option Claude suggested was determining optional runtime value status off of the existing ExpressionType rather than introduce a new sentinel error var. I implemented this. Thoughts?
There was a problem hiding this comment.
Good call, I prefer this to a sentinel. Every evaluation error for these types depends on the data in the request or response, so treating them all as null is safe. And there's no message text to drift.
One gap: the payload and message types are missing. $response.payload#/x still errors when it's absent, while $response.body#/x comes back null. I'd add RequestPayload, ResponsePayload and the Message* types to the switch.
There was a problem hiding this comment.
got it, added payload and message types, now handled as null.
aace49d to
fbf0505
Compare
e1414f6 to
0d6ed02
Compare
daveshanley
left a comment
There was a problem hiding this comment.
Nice work Shaun, this is a big step up. All five threads are sorted, and the engine path went from 2.5x slower than main to roughly twice as fast:
$statusCode == 200 73ns -> 37ns 2 -> 0 allocs
$response.body#/status == 'ok' 121ns -> 72ns 5 -> 2 allocs
Short-circuiting works, the cached tree holds up across different contexts, and missing outputs fail fast again.
One blocker left, which is the uncached path. Details inline, plus a couple of small things.
|
|
||
| // compileSimpleCondition returns the compiled tree for condition, caching both | ||
| // successful compiles and syntax errors when caches is non-nil. | ||
| func compileSimpleCondition(condition string, caches *criterionCaches) (*compiledCondition, error) { |
There was a problem hiding this comment.
This is the last blocker. EvaluateCriterion is public and has no cache, so every call compiles the condition from scratch. Against main (alternating runs, n=12):
$statusCode == 200 64ns -> 210ns (+226%) 2 -> 7 allocs
$response.body#/status == 'ok' 145ns -> 307ns (+112%) 5 -> 10 allocs
The profile puts all seven allocs on compiling. The token slice grows three times, then there are three nodes and the compiledCondition.
Size the token slice up front and allocate the nodes from a single slice. That should cut most of them. Measure it against main's numbers and we're there.
There was a problem hiding this comment.
I've implemented a separate evaluation path for cases of non-compound criteria (single operand or 'operand op operand') which I think would be the majority of cases. This follows similar logic to main and keeps the allocs very low. Also implemented a pre-allocated token slice and slab of condition nodes that further improves both the compound and non-compound cases.
Benchmark (added) shows parity or improvement across the board.
| benchmark | main ns/op | branch ns/op | Δ time | main B/op | branch B/op | main allocs | branch allocs |
|---|---|---|---|---|---|---|---|
status_code ($statusCode == 200) |
84.3 | 82.7 | −2% | 72 | 0 | 2 | 0 |
response_body ($response.body#/status == 'ok') |
192.2 | 196.2 | +2% | 128 | 48 | 5 | 3 |
compound (&& with grouped ||) |
n/a | 728.7 | n/a | n/a | 2760 | n/a | 6 |
There was a problem hiding this comment.
I was surprised by "0" allocs here in the first case, but it seems it is because a lookup table is used for integers from 0-255. It would require an allocation for $statusCode == 500.
| func newOperandNode(raw string) *conditionNode { | ||
| op := strings.TrimSpace(raw) | ||
| if strings.HasPrefix(op, "$") { | ||
| return &conditionNode{kind: condOperand, raw: op, isExpr: true} |
There was a problem hiding this comment.
With short-circuiting, a typo in a branch that doesn't run is never caught:
$statusCode == 200 || $respnse.body#/x == 1 -> true, no error
Parse the runtime expression here, once, and keep the parsed expression.Expression on the node. Typos then fail at compile time in every branch, and value() skips the parse lookup on every evaluation.
Unknown steps still need the context, so those stay runtime errors.
There was a problem hiding this comment.
added parsing of full expressions and cacheing of parsed expressions and errors.
| return &conditionNode{kind: condOperand, raw: op, isExpr: true} | ||
| } | ||
| // Literals never touch the expression context, so they convert once here. | ||
| literal, _ := evaluateSimpleOperand(op, nil, nil) |
There was a problem hiding this comment.
evaluateSimpleOperand only ever gets literals with no context now. Its $ and empty-string branches are only reachable from coverage_test.go, and the error gets thrown away here.
A small simpleLiteral(op string) any helper would be cleaner, and the tests for the dead branches can go.
The Arazzo Criterion Object operators table lists && (and), || (or) and () (logical grouping) alongside the comparison operators, but simple conditions were split on the first comparison operator found, so only a single `left <op> right` comparison could be expressed. Grammar Simple conditions are tokenized and parsed by a small recursive-descent parser. || binds looser than &&, which binds looser than the comparison operators (==, !=, <, <=, >, >=). Comparisons do not chain, and a parenthesised group is a boolean operand, so `($flag) == true` coerces the group before comparing. Malformed conditions (unterminated strings, unbalanced parentheses, misplaced or trailing operators) are errors. Tokenizing runtime expressions JSON pointers, header names and parameter names may contain operator characters, so a runtime expression is one operand that runs to the next whitespace, matching expression.SplitSimpleCondition on main: `$response.body#/a>b == 1` compares the value at /a>b. A trailing ')' that the expression does not balance itself closes an open group, so `($response.body#/flag)` works and `#/f(x)` stays intact. Consequences: - `$statusCode==200` without spaces is a single operand, as on main. - Inside a group, a pointer token ending in an unbalanced ')' cannot be written; that ')' always closes the group. Whitespace is matched as ASCII only. The tokenizer works on bytes, and unicode.IsSpace(rune(b)) misread the UTF-8 continuation bytes 0x85 and 0xA0 (as in "Å" and "à") as whitespace, splitting those operands. Compile once, cache per engine Each condition is compiled once into an evaluation tree and cached in a new criterionCaches.simple map, keyed by the trimmed condition. Syntax errors are cached too, as the regex and JSONPath caches already do, and Engine.ClearCaches() resets the map with the rest. Literal operands are converted at compile time. Runtime expressions keep their raw text and are evaluated against the current context through the engine's expression cache, so a cached tree never holds runtime values. EvaluateCriterion without an engine compiles on every call. Because conditions compile before evaluating, a syntax error is now reported ahead of a runtime error from an earlier operand. https://spec.openapis.org/arazzo/v1.0.1.html#operators Co-Authored-By: Claude Opus 5.5 <[email protected]>
71186bc to
f59c6f1
Compare
EvaluateCriterion has no cache, so every call compiled the condition from scratch. After the && / || / grouping change that cost 7 allocs for a single comparison, up from 2 on main. - Evaluate a lone operand or single comparison without compiling when there is no cache, keeping the nodes on the stack. - Split out non-recursive operandValue/operandTruth so those nodes do not escape to the heap. - Tokenize into a stack scratch buffer and allocate parser nodes from a single slab sized to the token count. - Add BenchmarkEvaluateCriterionPublic and a differential test checking the fast path against the compiled path. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
&& and || stop evaluating once the left side decides the result, so a typo such as $statusCod in a branch that never runs was never parsed and went unreported until that branch was reached. Parse every runtime expression operand when the condition is compiled and keep the parsed expression on the node. Malformed expressions now fail in every branch, the error is cached with the condition, and evaluation no longer looks the expression up again. Compiling goes through the engine's expression parser, and runs after the tree is built so structural errors still take precedence. Failures that need the context, such as an unknown step, remain runtime errors. Uncached compound conditions compile slightly slower because every operand is now parsed, including ones in skipped branches. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Simple conditions only convert literal operands this way now: runtime expressions are parsed when the condition is compiled. The helper's expression and empty-string branches were reachable only from tests, and its error was always discarded. simpleLiteral takes an already-trimmed literal and returns the value directly. Trimming and the runtime expression check stay in initOperandNode. Quote stripping now requires two characters, so a lone quote can no longer slice out of range. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
6197f14 to
7d84af5
Compare
A missing $response.body#/x reads as null in a simple condition, but a missing $request.payload, $response.payload or any $message.* source still returned an error, although they are resolved the same way. Add the payload and message expression types to isOptionalRuntimeValue so every request, response and message source reads as null when absent. Step outputs and a nil context still error. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
7d84af5 to
c36ff9e
Compare
Summary
Brings
simpleCriterion Object evaluation in line with the Arazzo 1.0.1 operators table, and aims for performance parity withmain.Changes
&&,||and(). Simple conditions only supported a singleleft <op> rightcomparison. They are now parsed with a small recursive-descent parser:||binds looser than&&, which binds looser than comparisons. This makes conditions like this one possible:Malformed conditions (unterminated strings, unbalanced parentheses, misplaced operators) are errors.
Runtime expressions end at whitespace, as with
SplitSimpleConditiononmain, because JSON pointers and header names can contain operator characters ($response.body#/a>b == 1). A trailing)the expression doesn't balance itself closes an open group, so($response.body#/flag)works. Whitespace matching is now ASCII-only, which fixes operands containing characters likeÅandàbeing split.Missing and null values. A value legitimately absent from a request or response (header, query/path parameter, body pointer segment, or the body itself, $request.payload, $response.payload and every $message.* source) evaluates to
nullinstead of failing the condition, so$statusCode == 204 || $response.body#/flagpasses on an empty 204.nullis falsy, equals onlynull, and makes<,<=,>,>=false. Previously it compared as the string"<nil>", so$response.body#/count > 0passed on a 204. Unknown steps, workflows, inputs, outputs and components are still errors.Compile once per engine. Each condition is compiled to a tree and cached in
criterionCaches(reset byEngine.ClearCaches()). Literals are converted at compile time. Runtime expressions are evaluated against the current context on every call, so cached trees hold no runtime values. Lone operand criterion or single comparison (non-compound) skip compilation.BenchmarkSimpleCriterionvsmain:maintrue$statusCode == 200$method == 'POST'$statusCode == 200 && ($method == 'POST' || $method == 'PUT')BenchmarkEvaluateCriterionPublic(uncachedEvaluateCriterion) vsmain:$statusCode == 200$response.body#/status == 'ok'&&with grouped||)Behaviour notes
$statusCode==200without spaces is one operand, as onmain.)characters close open groups, one per open group. Any that are left over stay in the pointer.Out of scope
!(logical not),[]and.as operators, and thenullliteral.Tests
New tests in
arazzo/criterion_test.gocover operator precedence and grouping, missing and null values, syntax errors, operator characters and parentheses in JSON pointers, non-ASCII operands, and the compiled-condition cache.go test ./...passes.Benchmarks
BenchmarkSimpleCriterionandBenchmarkEvaluateCriterionPublicadded.🤖 Generated with Claude Code