fix(effectors): fixes from the stack re-review #632
All Vouch review confidence checks passed
Residual risk 0.28 = Change Risk (0.52) × (1 − Review Confidence (0.47)).
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.02 · 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.344
Real PR Conversation Timeline
1 comments
"Review active on #632"
general
weight: 0.35
gusfcarvalho
What
One commit per fix (#11 and #12 add tests only), plus one self-review commit (a shared test helper, and the UI LLD line).
1. IPv6 zone in an effector base URL (#595):
NormalizeBaseURLrejects a host with a zone (https://[fe80::1%25en0]).url.Parseunescapes%25, so the canonical form it wrote back could not be parsed again.2. Trailing input in a parameter schema (#596):
params.Parsereads toio.EOFafter the value.dec.More()is false before a stray top-level}or], so{"type":"object"}}used to be accepted.3.
defaulton the root object (#597):params.Parserejects it ("set it on each property").Defaults()and the agent'sMergeonly read property defaults, so a root default was validated and then dropped.action-parameters.mdnow says so.4. Domain events for HTTP step transitions (#603/#618):
createStepTransitionServicebuilds the evidence integration withWithDomainEvents(config.EffectorDomainEvents()), and the fallback evidence service getsWithDomainEvents()too. Evidence written when a step moves over HTTP now writes a subject-changed outbox row, as the worker's does.5. Preview error count (#607):
POST /api/rules/previewreturnserror-count(every evaluation error) anderrors-truncated(some aren't listed). Before, errors past the first 100 were dropped silently. Swagger regenerated.6. Lock order in
ReconcileSubject(#610): before touching any effect row, it takes a transaction advisory lock on the key of every effect it can touch, in hash order. Two subjects of one action can't deadlock over two shared effects. Prune deletes withFOR UPDATE SKIP LOCKED, so it never waits while holding rows.7. Stale pending subjects (#612): a trigger change, or an action target change (
Change.TargetChanged), drops the subjects that haven't entered yet (Machine.DropPending). A pending effect left with no subjects turns inactive silently. A tick can't enter a subject that was evaluated against the old condition, and the backfill adds back the ones that still match.8. Text stored from outside CCF (#615): a shared
effectors.StorableTextreplaces invalid UTF-8 with U+FFFD, drops NUL and cuts on a rune boundary. It is used for agent response bodies, rejection reasons (including the JSONerrorfield, which was not bounded before) and rule errors. It replaces the twotruncateUTF8copies.9. Duplicate backfill jobs (#617):
rules.BackfillArgscarries the outbox event id, and the job is unique by args, so the after-commit enqueue and the dispatcher's enqueue of the same outbox row give one job.10. Unbounded durations (#620):
ParseDurationcaps each part and the total at 3650d (MaxDuration). Before,3650d2562047hoverflowed.11. Fail-closed source read (#621), tests only: the
canReadSourceerror branch (PDP error, or no PDP) answers 403.12. Action update route (#622), tests only:
TestChangesNeedSourceReadcoversPUT /rules/{id}/actions/{actionId}.13.
DeleteAgentracing rule saves (#625):-
DeleteAgentlocks the agent rowFOR UPDATEinside its transaction and lists the rules using it there. Without?confirm=delete-rulesit still answers 409 with those rules, and the transaction rolls back.- Rule and rule action saves that set an agent share-lock that row first. If the agent is gone or inactive they fail with 422 on
effector.agent(the unknown-agent message).- Saves now lock agent → rule row → actions, the order
DeleteAgentuses.touchRulemoved first in the action routes, and the rule delete updates the rule before its actions.14. Snoozed expiry retried forever (#627):
expiryDuplicatecounts a job scheduled up to 1s after the requested expiry as scheduled for it (expiryTolerance).15. Resume without a generation (#628):
ResumeActiononly schedules the tick atlast_repeat_at + repeat(or now).-
Settleresumes a finished effect that has repeats left when that repeat is due. It deliversrepeated(stateactive), orfinishedat the new max.- Until then the effect stays
finished, so an effect's state changes only together with a delivered generation.- Nothing is delivered at the moment of the change.
- Docs (
user-interface.md,triggers.md,wire-interface.md,lld/poc-followups.md) and theUpdateActionswagger description updated.16. Comprehension variable named
subject(#630): a map key records whether its operand starts from a macro's iteration variable. A guard onsubjectdoesn't cover a lookup on a variable that shadows it, in the same expression or from the condition, and the reverse holds too. Example:subject.components.map(subject, subject.labels["owner"])with"owner" in subject.labelsinwhennow warns. It fails at runtime.Round 2
Second stack review (2026-12-03). One commit per item, each with a test that fails without its fix (M3 is test-only; the docs item has no test), plus one self-review commit (
0daeee7, a shared test helper).7f43634: an agent answering verification with a NUL made the job error unstorable (River keeps errors in jsonb, 22P05), and River's completer then retried the whole completion batch forever, unrelated jobs included. Verify and the deliverer put agent text throughStorableText, and every effector and rules worker is registered throughstorableErrors, which makes a returned error's text storable (2 KiB) and unwraps to the original (snooze and cancel still work).ae29d4d: two outbox rows for the same tick or delivery in oneInsertManyTxfailed the statement (SQLSTATE 21000) and stalled the outbox.dispatchBatchfolds engine job rows by River's unique key; folded rows are marked processed.73f5112: free text (status message, link rel/title, version, descriptions) is made storable; a NUL anywhere else in an action, inrefsor inheld_digestis a 400 with the field path (MalformedError). No more 500 and lost writes.overridable_action_config_flags(#619),99876b4: test only.Clear(#611),508bdec: Prune's deleted-rules pass deletes withFOR UPDATE SKIP LOCKED(a rule or action with effects left keeps its row for a later run), andDeleteAgentEffectorlocks the agent's effects in id order, the orderClearuses.7b00004: rule and action saves lock the rule row in their transaction (after the agents, before the actions) and decide from the rule and action as they are then. A trigger change, new action or target change that waited for an enable now applies (DropPending, backfill); a save that waited for the rule's delete answers 404 and writes nothing (before: 201 with a live action on the deleted rule, or 500). Rule update, delete and enable do the same.7ef09b5:lockAgentsonly requires the agent row to exist, asResolveAgentand the docs do. A deleted agent keeps its 422 ("no agent with ID").Registervs agent delete (#613, #625),2a200f0:Registertakes the agent rowFOR SHAREfirst, so it serialises withDeleteAgent. A registration that finds the agent deleted answers 401 and stores nothing (before: 40P01 and a 500, or rows re-created for a deleted agent).PruneInstances(#618),cbfafeb: the prune locks the stale instances with the staleness condition in the same statement (FOR UPDATE SKIP LOCKED), then deletes their actions and the instances.DeleteAgentEffectordeletes instances before actions. One lock order acrossRegister,PruneInstancesand the agent delete: agent, instance, actions. A registration during the prune survives.Settle),c882edc:isFinaltreatspendinglikeinactive, the state the agent was given for that generation.c97abf0: the triggers.md state diagram edge for raised repeats is the delivered repeat, plus thefinished → finishedcase; triggers.md,lld/poc-followups.mdand theUpdateActiondescription say "asrepeated(active again), orfinishedif it reaches the new max". Swagger regenerated.Round 2 choices
FOR NO KEY UPDATE, the lock the oldtouchRuleUPDATE already took, so evaluations (FOR SHARE) serialise with saves as before. A rule enable that changes nothing still opens a transaction to read the rule under that lock.isFinal(pending), not the reported generation's history row. Inactive ↔ pending are the only state changes without a new generation, so the two agree everywhere else, and the history row is pruned after 24h while the effect can stay held.Round 3
Third stack review (2026-12-03). One commit per item, each with a test that fails without its fix (checked by reverting or mutating the non-test files), plus two test-only follow-ups (
8b00c81: three source-read tests build their own server and now give it the rule engine E2 requires;e7abcf9: U1's test compares the rule's actions by ID, since the create response and GET can list them in different orders).dd1f123: a NUL in a rule's name, description orwhen, or in an action's target or params, answered 500 (22021/22P05). Every rule and action save now answers 422 with the field path.43d6911: the agent'splugin,GET /api/rules?source=, a rule's effectsstateand the effector actions'effectare checked against their closed sets first (400 on the user routes, 422 on the agent route, as it answers a bad cursor). An unknown source or state no longer answers an empty 200 (this is also the should-fix item for/rules/{id}/effects).8690182: a schema with a lone surrogate escape or invalid UTF-8 is decoded and re-encoded (U+FFFD), as the rest of the registration is; any other schema is stored as sent.1b4f1ff: identities are capped at 1024 bytes (422 at save, flagged in preview, the action's error at evaluation), and each rule's evaluation of a subject runs in a savepoint, so one rule's data error doesn't roll back the others.4e8d2b8: expressions are at most 8192 characters (422 on every save and on preview), the cache is also bounded by 1 MiB of expression text, and previews compile without adding to it.30843d6:DeleteAgentlists the rules again under their locks, andDeleteActionshare-locks the action's agent first, the order the other action saves use.bf32018:RecheckRuleActionsupdates in id order, andDeleteAgentlocks the deleted rules' actions in id order before deleting them (40P01 before).bb4a844: both share-lock the live agent row first (lockLiveAgent, shared withRegister): 404 and nothing written once the delete wins.563697f),44d15cb: keys hash into 256 stripes taken once per transaction in ascending order (evaluate every rule, lock, then apply), and a target resolving to more than 1000 identities for one subject is the target's error.f3f3443: sweep and backfill record a failing subject as an error of its rules and go on (SweepResult.Failed).Entry.Behind),0403063: a give-up recordsundelivered_generation,undelivered_atandundelivered_reasonand leavesapplied_as the agent last reported it, so the fetched effect is behind and the agent applies it on resync. The agent's report of that generation (or a later one), or a later generation's successful delivery, clears it. The user's effect view shows it asdelivery-failed.?state=matches the internal state (#616, with #608's mapping),60516f1: the filter maps the document states (inactivecoverspending); any other value,pendingincluded, is a 422.684eec4: the writers record onecomponents.changedoutbox row in their own transaction (whenEffectorDomainEvents()), which the dispatcher turns into arules.components-changedjob that pages through the streams and writes asubject-changedrow for each one whose latest evidence links a component.847c7d2: on a server without the rule engine, every rule and rule action write, and an agent delete that would delete rules, answers 503; reads and preview still work.whenisn't watched (#610),4a694f4: the watch followsDependsOnNowalone, so the example in the spec matches after the sweep at +25h.observed-atpoisons the effect's reads (#616),4d434b4: converted to UTC and a 400 outside the years 1 to 9999.enableddisables the rule (#622),d8c3950:enabledis required (422 for no body,{},nullor a misspelled key). No other effectors body has a plain bool whose zero value is destructive: rule create already usesbool, andpublish-targets/supports-exceptionsare the agent's declaration, where false is a valid default.Round 3 choices
evaluateRules. Only data errors (SQLSTATE classes 22, 23 and 54) are isolated: they roll back that rule's changes and the jobs it decided, and are recorded as its (or its action's) error with the SQLSTATE, while the database's message goes to the log. Any other error still fails the whole evaluation, so River retries it.EffectKeyStripes) and a cap of 1000 targets per action and subject (MaxTargetsPerAction). A transaction holds at most 256 of these locks; unrelated keys that share a stripe only serialize. Stripes are taken once, in one global order, because taking them per call would let two actions of one evaluation take them out of order; a later call that needs a stripe it didn't take up front fails instead.undelivered_generation,undelivered_at,undelivered_reason) rather than a status value or the error records, soapplied_*stays exactly what the agent reported, and the agent wire format and SDK don't change. The user API's effect gains an optionaldelivery-failedblock (generation,at,reason).observed-atmore than 5 minutes ahead of the API's clock is ignored (applied-atis then the time of the report), not clamped.subject-changedrows, so the existing dispatcher evaluates them with its usual dedup and its handling of an evaluation that's already running. The job does nothing while no evidence rule is enabled. Writers: component PUT (only when the title or the defined component changes), component DELETE, SSP DELETE andoscal importof an SSP.PUT .../system-implementationisn't one: GORM upserts only the foreign key of existing components, checked with a request that renames one. Creating a component changes no existing document either.requireEngine), rather than leaving the routes unregistered, so a client gets an explanation.applyChangeand the agent'sdeleteRulenow fail rather than skip without a lifecycle. The helm chart runs one API deployment with oneapi.worker.enabledsetting, so no deployment topology has API-only replicas taking rule writes.Why
Stack re-review 2026-12-03; each finding confirmed at #631.
Choices
defaultinstead of honouring it. The doc never allowed one. Neither plugin sets one: in effector-slack-notify and effector-github-settings, the rootobject()ininternal/params.gohas no default.ReconcileSubjectexplains why the other lockers can't close a cycle:- tick, redeliver and status reports lock one effect;
- rule changes lock the rule row first;
-
DeleteAgentlocks the rules first;- Prune skips locked rows.
UniqueOpts{ByArgs: true}. River's default unique states includecompleted, so a fast backfill that already finished isn't run again. A backfill without an outbox row (event id 0) stays non-unique.scheduled_atcomes from River's clock afterWorkreturns, so rounding the requested time alone wouldn't line the two up.filter(c, "k" in c.labels).map(c, c.labels["k"])stays guarded (TestCompileTargets).Compatibility
pkg/effector/paramsandpkg/effector/targetsare public. Fixes 1–3 only reject input the docs never allowed. The effectors stack isn't released yet.lld/ui.md(RulePreview.vue) now listserror-count/errors-truncatedfor the UI work that follows the api stack.rules.BackfillArgs.event_idisomitempty, and jobs without it decode as before.sdk/don't change. A give-up no longer writesapplied_status: unknown; rows written that way before this change aren't migrated (the effectors stack isn't released). The user API's effect gains an optionaldelivery-failedblock, and the UI should show it where it showedunknown. New nullableccf_effectscolumns come from AutoMigrate. Rule writes, and an agent delete that deletes rules, answer 503 on a server without the rule engine. Bad list filters that used to answer 500 or an empty 200 now answer 400 or 422.Tests
1.
TestNormalizeBaseURL: zone cases.2.
TestValidateSchemaRejects: trailing value,}and].3.
TestValidateSchemaRejects: root default.4.
TestStepTransitionServiceRecordsDomainEvents(new, sqlite): one subject-changed row per evidence write with effectors on, none with them off.5.
TestPreviewLimits,TestPreview(service) and the handler'sTestPreview: count and truncation.6.
TestConcurrentReconcilesDontDeadlock(new) andTestPruneSkipsLockedEffects(new).7.
TestTriggerChangeDropsPendingSubjectsandTestTargetChangeDropsPendingSubjects(new).TestActionsassertsTargetChanged.8.
TestStorableText(new) andTestRejectionReason: NUL and invalid UTF-8.9.
TestBackfillIsOneJobPerOutboxRow(new, dispatch suite),TestEngineJobParamsandTestRuleChangeJobsAreWrittenToTheOutbox: event id.10.
TestParseDuration: 3650d, 87600h and 3649d24h pass; 3651d, 87601h, 3650d23h and 3650d2562047h fail.11.
TestCreateRuleSourceReadFailsClosed(new unit test; it fails if the error branch allows) andTestSourceReadFailsClosed.12.
TestChangesNeedSourceRead: the action PUT.13. Three new tests. Each fails without the fix: the save doesn't wait for the agent's row, or the delete answers 204.
-
TestRuleSaveRacingAgentDelete: a save waits for the delete's agent lock, then gets 422 and nothing is saved.-
TestActionSaveRacingAgentDelete: the same for POST and PUT (repoint).-
TestDeleteAgentRacingRuleSave: the delete waits for an uncommitted save, then gets 409 listing its rule, and the agent stays active.TestDeleteAgentWithRulesstill gets its 409.14.
TestExpiryDuplicate: snoozed just after the expiry, 1s after (no retry), and more than 1s after (retry).15.
TestFinishedReportAfterResume(new): an unreported finished generation,max_repeatsraised, thenappliedfor that generation.- Expected: the effect leaves the held set and the held digest is the empty set's.
- The next tick delivers
repeatedwith stateactive.TestRaisingMaxRepeatsResumesandTestRepeatChangeAtMaxnow expectfinisheduntil the repeat.16.
TestTargetWarningsGivenConditionandTestUnguardedMapLookupWarnings: the shadowing cases, and that the shadowed lookup fails at runtime.The unit tests for 1–4, 8, 10, 11, 14 and 16 were checked to fail without their fix (11 by flipping the error branch).
Round 2 (each fails without its fix, checked by reverting the non-test files; M3 by deleting the scrub):
TestAgentTextInAJobErrorIsStorable(worker, a NUL in a verify answer; an unrelated job still completes),TestStorableErrors(unit),TestTransportErrorIsStorable, and a NUL case inTestVerify.TestDispatchFoldsIdenticalEngineJobs(21000 before).TestNULInAgentText(handler: registration, status report, heartbeat),TestStorableRegistration,TestStorableStatusReport,TestValidateHeartbeat.TestNormalizeReport_ScrubsActionConfigFlags.TestPruneDeletedRulesSkipsLockedEffects,TestDeleteAgentEffectorLocksEffectsInIDOrder(40P01 before).TestActionSaveRacingRuleDelete(create, change, delete: 404, no live action, no change applied),TestRuleDeleteRacingRuleDelete,TestSaveRacingRuleEnable(trigger change, action create, target change: the change is applied with the enabled rule).TestSaveOnDeactivatedAgent(POST /rules and a target-only PUT on a deactivated agent by ID; 422 once deleted). The agent-delete race tests expect the new message.TestAgentDeleteRacingRegistration(the delete waits for the registration, then 204; 40P01 and a 500 before) andTestRegistrationRacingAgentDelete(known and new instance: the registration waits, then 401, nothing stored).TestPruneSkipsAnInstanceBeingRegistered,TestRegistrationRacingPrune(the registration survives),TestPruneRacingAgentDelete(40P01 before).TestClearedReportWhilePending(adapted from the reviewer's probe: gen 2appliedwhile pending drops it from the held set and the desired held digest is the empty set's).The race tests are deterministic: a test transaction or a paused gorm callback holds one side, and the test waits for the other on
pg_stat_activitybefore releasing it.Round 3 (each fails without its fix, checked by reverting or mutating the non-test files):
TestNULInSavedTextIsUnprocessable(every rule and action save route).TestListFiltersRejectBadValues(user routes),TestListEffectsRejectsBadFilters(agent route).TestStorableRegistrationSchema(unit),TestUnstorableSchemaBytes(handler).TestOverLongIdentityIsAnInvalidTarget,TestDataErrorInOneRuleSparesTheOthers(a trigger rejects one rule's insert with 22023; the other rule's match commits),TestOverLongFixedIdentity(422 at save).TestExpressionLengthAndCacheBytes,TestCompileUnknownKindAndCacheBound(unit),TestPreviewDoesNotCachePrograms(handler unit),TestOverLongExpression(7 save and preview routes answer 422).TestDeleteAgentRacingActionDelete(each half of the fix alone passes it; it fails with both removed).TestRegistrationRacingOtherAgentDelete(40P01 every time before).TestEffectorWritesRacingAgentDelete(base URL and resync).TestEvaluationLocksAreBoundedByStripes(an evaluation over 2000 keys with room for 1000 locks; 53200 before),TestTargetsOverTheCapAreAnError,TestEffectKeyStripes,TestTargetsPerActionAreCapped.TestSweepGoesPastAFailingSubject,TestBackfillGoesPastAFailingSubject.TestGiveUpIsNotAReport(the real Deliverer gives up generation 2, the effect the agent fetches is behind by the agent'sEntry.Behindcopied verbatim, the agent's report of 2 releases it and clears the record, and a later generation's delivery clears one too),TestRenderEffectShowsDeliveryFailed.TestSupersededAndNotReady,TestResponsesandTestTransportErrorIsStorablenow expect the undelivered record instead ofunknown.TestListEffectsFiltersByDocumentState(?state=inactivereturns a held pending effect;?state=pendingis a 422).TestComponentEditsReEvaluateTheirEvidence(oscal handler: a component PUT that renames it and moves it to another defined component makes a rule oversubject.componentsmatch without new evidence, and its DELETE unmatches it; a PUT that changes neither, or one on a server without domain events, records nothing),TestDeletingAnSSPReEvaluatesItsComponents,TestImportedSSPReEvaluatesItsComponents(cmd/oscal),TestComponentsChangedReEvaluatesLinkedStreams(worker: the row becomes the job, and the job asks only for the streams whose latest evidence links the component),TestEngineJobParams.TestRuleWritesNeedTheRuleEngine(with no lifecycle: rule POST, PUT, enable, DELETE, the three action routes and the agent delete with and withoutconfirmanswer 503, and nothing changes; reads, preview and deleting an agent no rule uses still work).TestErroringNowDependentWhenIsWatched.TestObservedAtOutOfRange(three out-of-range values answer 400 and every read stays 200; a value a day ahead is ignored, a minute ahead is kept).TestEnabledIsRequired.Gate
Local, on this branch at
8b00c81, and ate7abcf9(a test-only change) the RulesApi suite again, three times (-count=3):go build ./...,go vet ./...,go vet -tags integration ./...,gofmt -l(clean),make test;make swag(regenerated docs committed),go mod tidy;go test -tags integration -p 1 -count=1 -timeout 60m ./internal/service/effects/... ./internal/service/effector/... ./internal/service/rules/... ./internal/service/worker/... ./internal/service/outbox/... ./internal/api/handler/... ./cmd/oscal/...(this includesinternal/api/handler/oscalandcmd/oscal);make lint, with golangci-lint v2.15.0 rebuilt with go1.27.4 (the installed one is built with go1.26 and refuses go 1.27.4): 6 issues, all in files this PR doesn't touch (reflect.Ptrinline ininternal/service/relational/workflows, deprecatedProfileIDin twointernal/service/workerrisk tests). CI's golangci-lint passes.CI on
e7abcf9(run 47224529256): green.ci / required,ci / make,ci / go,ci / golangci-lint,ci / image, actionlint, pr-title, osv-scan and preview tags passed; the preview image, plugin and policies jobs and release-checks were skipped, as they are on an unlabelled PR. (ci / makefailed on8b00c81on U1's test comparing actions by position;e7abcf9fixes it.)Size
Counted: 5984 lines (5550 added + 434 removed, tests and docs included, generated swagger excluded); round 3 adds 2986 of them (2807 + 179). The
size-exceptionlabel is set because the repo owner asked for one PR.Decisions to confirm
exists(c, "k" in c.labels) && exists(c, c.labels["k"] == "x")doesn't warn, as before. This keeps the filter-then-map idiom guarded.ComponentDefinitionLabel, written by subject templates) are part of evidence documents too, and their writers record nothing. Round 3 only covers the system component writers the spec lists..env.example).applied(before:unknown), and the give-up in the newdelivery-failedblock, which the UI doesn't show yet (ui follow-up).Not changed
Nothing: all 16 round-1 findings reproduced at #631 and are fixed here, every round-2 item (B1, M1–M9, docs) is implemented, and every round-3 item (U1–U5, L1–L4, J1, P1–P2, E1–E3, A1–A2) is implemented.
🤖 Generated with Claude Code