Stage-Enum Runners
When a Kubernetes operator evaluates multiple expression-driven constructs, such as assertions and variable bindings, through the same lookup, substitution, compilation, invocation, and evaluation sequence, extract a shared runner that reports failures via a small stage enum. This eliminates duplication without collapsing caller-specific status semantics, tracing, or result typing.
Keep caller semantics out of the shared runner
Passing mode flags, status structs, or caller-specific reason codes into a shared evaluation function recreates branching inside the helper and couples unrelated behaviors. Return the failing stage as a small enum instead, and let each call site own its reasons, messages, spans, and result checks.
Recognizing Pipeline Duplication Across Call Sites¶
In an expression-driven controller, bindings typically resolve before assertions so fetched values become real Common Expression Language (CEL) variables rather than text substituted into later expressions. Because both bindings and assertions query external state and evaluate a CEL expression, the assertion and binding evaluation functions can each open-code roughly 70 lines of identical five-stage plumbing:
- Accessor lookup
- Argument substitution against run parameters and bound variables
- CEL expression compilation
- Accessor invocation
- CEL expression evaluation
Lowering a local cyclomatic-complexity gate, such as tuning gocyclo from an unreachable ceiling of 30 down to 10 to
match CI complexity checks, often surfaces smaller shared steps first. Extracting a shared argument-substitution helper
(reused across assertions, bindings, and sub-state parameter resolution) and a shared response-shaping helper across HTTP
accessors cuts complexity incrementally (reducing an assertion runner from 11 to 9 and a recursive precondition walker
from 17 to 8) before consolidating the full pipeline.
Designing the Shared Runner and Stage Enum¶
Extract the shared five-stage skeleton into a single runner that runs stages sequentially, halts at the first failure, and returns a small stage enum alongside the error or evaluated value. Keep the runner unaware of CRD status types, closed-enum external reasons, and expected return types.
Keep false-pass defenses inside the shared stages so every caller inherits them:
- Fail on unresolved argument placeholders rather than substituting empty strings, which would query the wrong path and still return a plausible response.
- Treat empty service selectors as matching nothing rather than resolving to an unrelated service.
- Reject empty credential values as missing rather than authenticating blank and reporting a downstream 401 as the target's fault.
Keeping Caller-Specific Concerns at the Call Site¶
Returning a stage enum cleanly divides pipeline mechanics from caller policy.
| Responsibility | Shared runner | Assertion caller | Binding caller |
|---|---|---|---|
| Five-stage execution | Runs lookup, substitution, compilation, invocation, and evaluation; stops at first failure | Invokes runner and maps stage enum | Invokes runner and maps stage enum |
| Status reasons | Returns stage enum and raw error | Maps stages to closed-enum assertion reasons and messages | Maps stages to binding-specific reasons and messages |
| Control flow | Stateless per call | Independent; failed asserts do not skip siblings | Sequential; a failed binding aborts later bindings and marks asserts as skipped due to unmet preconditions |
| Typed result handling | Returns raw evaluated CEL value | Enforces boolean result at evaluation time | Extracts string value for later variables |
| Tracing spans | No caller-specific span lifecycle | Owns assert span status and attributes | Adds resolved bindings to the enclosing definition span |
Separating result typing is necessary in CEL: because accessors return varying shapes, the value is exposed as a dynamic type, so compilation cannot statically reject a non-boolean assertion expression. Compilation stays shared, while boolean validation stays at the assertion call site.
Preserving Tracing Span Semantics Around the Runner¶
When an evaluation run is traced via OpenTelemetry, span status must stay distinct from assertion verdicts. The trace uses a root span named for the state definition rather than the generated run object, child spans per walked definition (nesting sub-states recursively), child spans per assert, and grandchild spans per accessor call.
At the assertion call site, passing and failing assertion verdicts both represent completed evaluations and report a successful span status. Only genuine execution failures (such as accessor errors, expression compilation failures, missing parameters, failed bindings, or missing targets) report an error span status. Skipped asserts whose preconditions were not met still emit a span marked as a warning rather than disappearing silently, while definition spans reflect held versus not-held. Call sites and walkers also stamp run parameters and resolved bindings onto run and definition spans, since parameters used only inside a CEL expression never pass through an accessor's argument map.
Guard trace IDs against no-op providers
When telemetry is disabled, OpenTelemetry's no-op provider returns an all-zero trace ID. Guard .status assignment
by checking that the trace ID is valid so placeholder values are never stored, test both states with
go test -shuffle=on, and keep telemetry initialization non-blocking so exporter errors never block a verdict.
Structuring Controller Files for Direct Stage Testing¶
Pairing runner extraction with splitting oversized controller files by concern makes stage-mapping helpers directly reachable in unit tests. For example, breaking a 600-line controller under a 250-code-line cap divides it into reconcile loop, precondition walk, assert evaluation, CEL compilation, and status files.
Testing pure and stub-testable helpers with a hand-written accessor stub and an in-memory OpenTelemetry exporter raises
controller coverage (for example, from 8.8% to 14.0%) without spinning up an envtest control plane for every
transition. Reserve envtest for end-to-end reconciliation and status-ownership checks.
Verifying Behavioral Invariance During Extraction¶
Treat runner extraction as a pure refactor verified at each step:
- Confirm closed-enum reason codes, error-message strings, and
.statuspayloads remain unchanged across both callers. - Run
go testand inspectgocyclonumbers after each individual extraction rather than testing only after a batch of edits. - Keep unit tests on subtle boundaries, including dynamic-type evaluation checks, unresolved placeholder failures, and valid versus invalid trace IDs.
- Enforce declared coverage floors in configuration so refactors cannot silently drop test coverage under a passing suite.