refactor: split Context.Run, Subcontext.Run and NewSubcontext (maat #1) #245
All Vouch review confidence checks passed
Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)).
Review depth and reviewer attention state are adequate.
Model 1 · Change Risk (XGBoost)
Score: 0.52 · 650 lines diff across 8 files
Model 2 · Review Depth (DistilBERT)
Depth Score: 0.17 · 1 substantive comment(s)
Model 3 · Review Timing & Attention
Session adequacy: 100% · Reviewer familiarity: 35%
Bedrock Claude 3 · Risk Narration
(disconnected)
Groq Risk Narration
AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
Model 1 · Change Risk Attribution
SHAP Weights
Diff Size
diff_size
0.388
Shallow Review Depth
shallow_review_depth
0.289
Real PR Conversation Timeline
1 comments
"Review active on #245"
general
weight: 0.35
eliottness
Split
Context.Run,Subcontext.RunandContext.NewSubcontextinto small helpers. This is item #1 of themaatassessment (DD-29), tracked as DD-31.These three functions had the most
maathits in the root package: 2 criticalMAAT-FUNC-006hits (12 and 13 return points), a cyclomatic complexity up to 17, and a maintainability index below 44. EachRunnow keeps only the guards, the run timer and its two defers. The rest moves to helpers, so each defer stays in the function that owns its resource. The order in which defers run does not change.There is no change of public API and no change of behavior. Only
context.go,subcontext.goand the newrun_paths_test.gochange.Commits
Read them in order.
go test ./...passes after each commit.1.
test: cover Run guard paths and pinner hand-off. Addsrun_paths_test.go. All tests pass onmainbefore the refactor.2.
refactor: split Context.Run into helpers.3.
refactor: split Subcontext.Run into helpers. Same names and shape as commit 2, to compare side by side.4.
refactor: split Context.NewSubcontext into helpers.5.
refactor: move NewSubcontext closed guard into initSubcontextLocked. Added after review round 1 (see the last section). It only moves one guard and adds doc comments.New helpers (same names on
ContextandSubcontext):emptyRunError,checkRunnable,encodeAndEval,encodeRunData,startEvalLocked,evalLocked,keepOrUnpin. ForNewSubcontext:initSubcontextLocked,newSubcontextTimer,addSubcontextLocked.Review guide: lock and defer order
RuncallsencodeAndEval, which callsevalLocked. A callee returns before its caller, and Go runs defers in LIFO order in one function. So the order is the same as onmain.| Runs |
Context.Rundefer (final line) | In |Subcontext.Rundefer (final line) | In ||---|---|---|---|---|
| 1st |
ObjectDestroy(context.go:329) |evalLocked|ObjectDestroy(subcontext.go:188) |evalLocked|| 2nd |
resultPinner.Unpin(context.go:326) |evalLocked|resultPinner.Unpin(subcontext.go:185) |evalLocked|| 3rd |
evalsInFlight.Done(context.go:280) |encodeAndEval|parent.evalsInFlight.Done(subcontext.go:132) |encodeAndEval|| 4th |
mu.Unlock(context.go:275) |encodeAndEval|s.mu.Unlock(subcontext.go:127) |encodeAndEval|| 5th | pinner closure (
context.go:263) callskeepOrUnpin(context.go:342) |encodeAndEval| pinner closure (subcontext.go:115) callskeepOrUnpin(subcontext.go:200) |encodeAndEval|| 6th |
runTimer.Stop(context.go:219) |Run|runTimer.Stop(subcontext.go:70) |Run|| 7th |
TimerStats(context.go:216) |Run|TimerStats(subcontext.go:67) |Run|In
NewSubcontext, the handle-release defer (context.go:115) andmu.Unlock(context.go:122) stay inNewSubcontext. The new helpers have no defer.success = trueis still set before theSubcontextis allocated and registered.These four points stay true:
1.
evalsInFlight.Addis under the lock:Context.startEvalLockedis only called betweencontext.mu.Lock()and its deferred unlock.Subcontext.startEvalLockedcallsAddbetweens.parent.mu.Lock()ands.parent.mu.Unlock().2. The lock order is
s.mu, thenparent.mu. OnlySubcontext.startEvalLockedtakesparent.mu, while the caller holdss.mu.3.
ObjectDestroyand the result unpin run inevalLocked, so before the eval lock is released.4.
wafOwnsData = trueis the last statement beforeContextEval/SubcontextEval. The pinner closure reads the value whenencodeAndEvalreturns, after the unlock, as onmain.The pinner defer must stay a closure.
defer x.keepOrUnpin(pinner, wafOwnsData)would readwafOwnsDatatoo early and unpin data that the WAF still reads. The existing tests do not catch this.TestContextRunKeepsPinnerUntilClose,TestSubcontextRunKeepsPinnerUntilCloseand mutations M1/M2 do.The pinner is still allocated (
new(runtime.Pinner)inencodeAndEval) afternewRunTimersucceeded, as onmain. Norecoveris added.wafEncodeTimer.Stop()is still a plain call before the error check.keepOrUnpinbody diffThe two
keepOrUnpincopies (comments removed,context.ands.replaced byR.) are identical. This command prints nothing:Result: empty output, exit code 0.
New tests (
run_paths_test.go)Fixture: the Arachni test rule (
ua0-600-12x,match_regex^Arachni) on the addressmy.input. The input{"my.input": "Arachni"}matches it, so the first evaluation on a freshContextcreates one event. The tests that check!HasEventstherefore fail if the WAF evaluates the input when it should not. (The WAF reports a rule only once per context, so a second run of the same input has no event.)| Test | What it checks |
|---|---|
|
TestContextRunKeepsPinnerUntilClose,TestSubcontextRunKeepsPinnerUntilClose| Each successful run hands its input pinner to the runner.Closereleases them. ||
TestSubcontextRunParentClosedBeforeEval| A run rejected because the parent is closed leaves no outstanding evaluation (Closereturns within 5 s). TheclosedHintrestore runs once only, beforeClose. ||
TestRunChecksUnderEvalLock| The closed andctx.Errchecks made under the eval lock, forContextandSubcontext. A context wrapper (errGateCtx) proves thatRunpassed the earlier checks before the test changes the state. No sleep. ||
TestRunGuardOrder| Order of the guards: nil, empty, closed, exhausted timer,ctx.Err. ||
TestRunUnknownTimerKeyKeepsNoPinner| A run with an unknownTimerKeyfails and keeps no input pinner. |Evidence (not run by CI)
maatmaat analyze ./... --output json --detail full, onmain(2727c22) and on this PR head. Exit code 1 in both cases, because the score is below the threshold of 95.| Score | Before | After |
|---|---|---|
| Overall | 90 | 91 |
| Root module | 79 | 82 |
|
context.go| 55 | 100 ||
subcontext.go| 62 | 100 ||
run_paths_test.go| - | 100 |Hits removed: 28 (2 critical, 11 error, 15 warning). Hits added: 0. Total hits: 198 before, 170 after.
| File | Function | Hits | Rules (severity, value) |
|---|---|---|---|
|
context.go|NewSubcontext| 8 | CC-001 (warning, 13), CC-002 (warning, 13), FUNC-002 (warning, 13), FUNC-003 (warning, 36), FUNC-006 (warning, 7), HALSTEAD-001 (warning, 1099.1), MI-001 (error, 43.0), SLOC-001 (warning, 36) ||
context.go|Run| 10 | CC-001 (warning, 15), CC-002 (warning, 13), FUNC-002 (warning, 15), FUNC-003 (error, 51), FUNC-006 (critical, 12), HALSTEAD-001 (warning, 1533.7), HALSTEAD-002 (warning, 21690.6), IMPL-002 (error, 11.2), MI-001 (error, 38.4), SLOC-001 (error, 51) ||
subcontext.go|Run| 10 | CC-001 (error, 17), CC-002 (warning, 15), FUNC-002 (error, 17), FUNC-003 (error, 55), FUNC-006 (critical, 13), HALSTEAD-001 (warning, 1718.2), HALSTEAD-002 (warning, 30008.5), IMPL-002 (error, 11.2), MI-001 (error, 37.1), SLOC-001 (error, 55) |Hits that stay in these files, not on the three functions:
MAAT-ARCH-005onContextandSubcontext,MAAT-MI-001onContext.CloseandSubcontext.close.Compiler diagnostics
go version:go1.27.4 darwin/arm64E1,
go build -gcflags=-m . 2>&1 | grep -E '^\./(context|subcontext)\.go' | grep -E 'wafOwnsData|moved to heap': exactly 4 lines, as expected.E2,
go build -gcflags='-d=defer' . 2>&1 | grep -E '^\./(context|subcontext)\.go': 21 lines, all 21 end withopen-coded defer.Mutation checks (M1-M7)
Each mutation was applied alone to a throwaway copy outside the repo. In the M3-M6 rows, the no-kept-pinner assertion fails too. M3-M6 also fail on commit 1 (the tests on
maincode, with the same mutation on the original lines).| # | Mutation | Run on | Test that fails | Result |
|---|---|---|---|---|
| M1 |
defer func() { context.keepOrUnpin(...) }()becomesdefer context.keepOrUnpin(pinner, wafOwnsData)| PR head |TestContextRunKeepsPinnerUntilClose| fails || M2 | the same in
Subcontext.encodeAndEval| PR head |TestSubcontextRunKeepsPinnerUntilClose| fails || M3 | delete the locked
closedHintcheck ofContext| commit 1 and PR head |TestRunChecksUnderEvalLock/Context/closed| fails (both) || M4 | delete the locked
ctx.Errcheck ofContext| commit 1 and PR head |TestRunChecksUnderEvalLock/Context/cancel| fails (both). The error assertion still passes,!HasEventsand no-kept-pinner fail. || M5 | delete the locked
s.closedHintcheck | commit 1 and PR head |TestRunChecksUnderEvalLock/Subcontext/closed| fails (both) || M6 | delete the locked
ctx.Errcheck ofSubcontext| commit 1 and PR head |TestRunChecksUnderEvalLock/Subcontext/cancel| fails (both). Same as M4. || M7 | swap the timer guard and the
ctx.Errguard incheckRunnable(Context, then Subcontext) | PR head |TestRunGuardOrder/.../timer_comes_before_ctx.Err| fails (both) |Only the target case fails in M3-M7. The other cases of the same test pass.
Race and vet
| Command | Result |
|---|---|
|
go test -count=1 ./...| pass ||
go vet ./...| pass ||
go test -race -count=3 ./...| pass ||
go test -race -count=20 -run 'Race\|Concurrent\|Close\|SubContext\|Subcontext\|Canceled\|Sibling\|GoroutineLeaks\|Pinner\|UnderEvalLock\|GuardOrder' .(42 tests, 81 s) | pass |Benchmarks
Machine: Apple M5 Pro, AC power.
go test -cforbefore(mainat2727c22) andafter(this PR head). 10 rounds, the order of before/after alternates between rounds,-test.benchmem. Set:BenchmarkWAF|BenchmarkRunOnly|BenchmarkSubcontextRunOnly|BenchmarkSibling|BenchmarkContextRun|BenchmarkSubcontextRun. Control:WAF/ContextLifecycle.Verdict per row: every row passes, the control is stable.
WAF/DataComplexity/Heavy(+1.57 %, p=0.035). Three rows had a median delta of +2 % or more with p >= 0.05 (inconclusive by the rule):WAF/DataComplexity/Minimal(+2.7 %),WAF/DataComplexity/Realistic(+2.7 %) andContextRun(+2.9 %). The controlWAF/ContextLifecyclemoved +2.0 % with p=0.315, so it is stable.-rerun1.txt):Heavy+1.4 % (p=0.989),Minimal+0.9 %,Realistic+0.1 %. None significant, all below +2 %. ControlContextLifecyclep=0.445, stable.-rerun2.txt):ContextRun-1.5 % (p=0.239). Control p=0.862, stable.<details><summary>benchstat, main run (10 rounds): full output</summary>
</details>
<details><summary>benchstat, rerun 1 (20 rounds): <code>WAF/DataComplexity</code> + control</summary>
</details>
<details><summary>benchstat, rerun 2 (20 rounds): <code>ContextRun</code> + control</summary>
</details>
Review round 1: changes and evidence (commit 5)
Review round 1 found that
NewSubcontexthad a cyclomatic complexity of 8 and 6 returns, and asked for three doc comments. Commit 5 (bbb6fe2) does this and nothing else:ddwaf_contextguard moves fromNewSubcontextto the start ofinitSubcontextLocked. It still runs undercontext.mu, beforeddwaf_subcontext_init. The lock and both defers stay inNewSubcontext. No new helper.newSubcontextTimerstates that the caller MUST holdcontext.mu. BothkeepOrUnpinstate that they takepinnersMuthemselves, so the caller MUST NOT hold it. The line numbers of the defer table above are updated (keepOrUnpinmoves by 1 line).gocyclo context.go subcontext.go: the highest value is 6 (NewSubcontext, and the unchangedSubcontext.close).initSubcontextLockedis 5.NewSubcontexthas 5 returns. No function that the PR adds or changes is above 6.| Check on commit 5 | Result |
|---|---|
|
go test -count=1 ./...,go vet ./...| pass ||
go test -race -count=3 ./...| pass || targeted
go test -race -count=20 -run '...' .(plan v2 §6, 76 s) | pass || E1 | same 4 lines as above (
wafOwnsData does not escape×2,moved to heap: result×2) || E2 | 21 lines, all
open-coded defer(raw output in the Compiler diagnostics section) ||
keepOrUnpinbody diff | empty ||
go doc -all .againstmain| identical ||
maat| overall 90 → 91, root 79 → 82,context.go100,subcontext.go100,run_paths_test.go100. 28 hits removed (2 critical, 11 error, 15 warning), 0 added. Same as before commit 5. |Mutations M1–M7 are not run again. Commit 5 does not touch
Run,startEvalLockedorkeepOrUnpincode.Benchmarks for commit 5
Rows that call
NewSubcontextorSubcontext.Run(WAF/Subcontext,SubcontextRun,SubcontextRunOnly,SiblingSubcontext) plus the controlWAF/ContextLifecycle.beforeis381405eandafteris769f868(the commit IDs before the commits were signed; the signed IDs areb1c5366andbbb6fe2, with the same trees). Same protocol as above (alternating order,-test.benchmem). The machine was loaded by other jobs (load average 11–16), so all absolute times are higher than in the first measurement. allocs/op is equal on every row in the three attempts. B/op shows no significant increase on any row. One row has a significant B/op decrease:SiblingSubcontextSerializedin attempt 2 (−0.08 %, p=0.006).1. Attempt 1 (10 rounds): rejected for measurement quality. This is a deviation, not a trigger of control rule 5. The control
WAF/ContextLifecyclehad p=0.052, which is not below 0.05, so rule 5 did not apply. I rejected the attempt because the spread is too large to read (WAF/ContextLifecycle±27 % before, ±337 % after). I did not use it for any verdict. Output kept below for transparency. The final verdict does not depend on it.2. Attempt 2 (10 rounds, new files): rows to rerun. The control is stable (p=0.912). Two rows have a median delta ≥ +2 % with p ≥ 0.05 (inconclusive by rule 3):
WAF/Subcontext(+2.3 %) andSiblingSubcontextSerialized(+4.6 %). Other rows are below +2 % or negative.3. Rerun (20 rounds, new files, with the control): all pass.
WAF/Subcontext−3.2 % (p=0.512),SiblingSubcontextSerialized−1.2 % (p=0.433), controlWAF/ContextLifecycle+0.8 % (p=0.868, stable).Verdict per row: every row passes, the control is stable.
<details><summary>Attempt 1 (rejected, 10 rounds)</summary>
</details>
<details><summary>Attempt 2 (10 rounds)</summary>
</details>
<details><summary>Rerun (20 rounds): <code>WAF/Subcontext</code>, <code>SiblingSubcontextSerialized</code> + control</summary>
</details>
Out of scope
Context.Close,Subcontext.close,ARCH-005(field types of the structs), a shared pinner type, and the other files of the DD-29 sub-issues.