Add support for custom validators to GatewayStruct - #315
Merged
Conversation
Contributor
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #315 +/- ##
==========================================
+ Coverage 87.92% 88.34% +0.41%
==========================================
Files 143 144 +1
Lines 15061 15658 +597
Branches 1446 1475 +29
==========================================
+ Hits 13243 13833 +590
- Misses 1818 1825 +7 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
timkpaine
reviewed
Aug 11, 2026
arhamchopra
force-pushed
the
ac/structs
branch
from
August 11, 2026 20:58
73b0e05 to
926c99b
Compare
arhamchopra
marked this pull request as ready for review
August 12, 2026 12:46
arhamchopra
requested review from
emilybarrettp72,
feussy,
hintse,
ptomecek and
vstolin
as code owners
August 12, 2026 12:46
Signed-off-by: Arham Chopra <arham.chopra@cubistsystematic.com>
Signed-off-by: Arham Chopra <arham.chopra@cubistsystematic.com>
Signed-off-by: Arham Chopra <arham.chopra@cubistsystematic.com>
Dispatch the _validate_gateway_struct_after hook on the concrete struct type so a subclass instance in a base-annotated field cannot bypass its own rules, matching the dispatch already used for registered validators. Require an "after" validator to return an instance of the validated class, and only reject a None return when the incoming value was not itself None so a null input reports a type error rather than blaming the validator. Cache the MRO-resolved validators as a tuple and sample the registry version before the walk, so the resolved list cannot be mutated through the returned reference and a racing registration cannot publish a stale list stamped current. Factor the id/timestamp scrub into _scrub_identity and apply it both before and after the "before" validators, so one cannot reinstate a caller-supplied id. Honor force_new_id and force_new_timestamp for instance input by rebuilding the struct, since scrubbing in place would mutate the caller's object and strand it in the lookup registry under its old id. Document that only ValueError and AssertionError reach the client as a 422, that registering on a shared base instruments every struct in the process, and correct the validation entry points named in the docs. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com>
timkpaine
added a commit
that referenced
this pull request
Aug 14, 2026
Brings in the GatewayStruct validator registry (#315) along with the two copier update rounds and the state API work. Resolved a conflict in .github/workflows/build.yaml: took main's re-indented test job, which corrects steps that sat at four spaces while their neighbours used six, then re-applied v3's junit upload fix from f757918 so the test job keeps path/files at junit.xml rather than reverting to the '**/junit.xml' glob. The build job's junit steps are new from main and are left as main has them. Signed-off-by: Tim Paine <3105306+timkpaine@users.noreply.github.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Adds a lightweight, dynamic validator registry to
GatewayStruct. Application code (or other modules/structs) can attach validation and normalization/enrichment logic to a struct type at runtime — using arbitrary callables (lambdas, bound methods) — without subclassing or hand-writing pydantic validators. Validators run automatically during pydantic validation.Following the pydantic model, a validator both validates and may transform: it receives a value, returns the (possibly transformed) value, and raises to reject. There is a single concept (no separate "transformer") with
before/aftermodes.New APIs on
GatewayStruct:add_validator(fn, *, mode="after")— registerfn(value) -> value. The validator returns the (possibly transformed) value and raises (e.g.ValueError) to reject the input (surfaced by the REST API as a422).mode="before"(alias"pre") runs on the raw input (e.g. a dict) prior to construction — useful for accepting legacy/aliased shapes;mode="after"(alias"post", the default) runs on the constructed struct. Returnsfn, so it works as a bare decorator (@S.add_validator) or a decorator factory (@S.add_validator(mode="before")).clear_validators(*, mode=None)— remove registrations;mode=Noneclears both, otherwise justbefore/preorafter/post(teardown / idempotency when registering dynamically at graph-build time).Behavior:
_validate_gateway_struct), which is the robust funnel: subclasses frequently override_validate_gateway_struct_afterwithout callingsuper(), which would bypass an after-hook-based registry — running here avoids that.beforevalidators → construct →aftervalidators → the struct's_validate_gateway_struct_afterhook. Becauseaftervalidators run before the hook, they may normalize data that the hook then checks./send,model_validate,TypeAdapter, JSON snapshot replay) and for nested structs when a containing struct is validated. It does not run on native (non-pydantic) construction.Safety / guards:
Noneraises a clear error (a validator must return the value; otherwise pydantic would silently yieldNone).modeand callable-ness are validated at registration (fail-fast).Type of Change
Checklist
make lint) — ruff check + format clean; PR only touches Pythonmake test)tests/utils/struct/test_validators_registry.py(~30 cases:before/aftertransform + raise-to-reject,pre/postaliases, MRO aggregation, sibling isolation, decorator (bare + factory), bound-method validator, nested firing,None-guard, override-without-super()regression, after-validators-run-before-after-hook,clear_validators(all + by mode), invalid-mode / non-callable rejection, manual_run_validatorson the CSP path)docs/wiki/Develop.md