Skip to content

loader: annotation-driven input + return validation - #70943

Open
dwoz wants to merge 25 commits into
saltstack:3008.xfrom
dwoz:loader-validation
Open

dwoz wants to merge 25 commits into
saltstack:3008.xfrom
dwoz:loader-validation

Conversation

@dwoz

@dwoz dwoz commented Nov 25, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes #70942.

Adds annotation-driven input and return validation for Salt's loader dispatch. Module authors write plain Python signatures with type hints and the loader validates / coerces inputs and (for state modules) returns on every dispatch. Opt-in via four loader_validate_*_mode opts; default behavior (all off) is unchanged on upgrade.

# A module author's typed signature
def installed(name: str, version: str | None = None, pkgs: list[str] | None = None): ...

With loader_validate_wire_input_mode: enforce:

  • salt '*' pkg.installed version=1.2 → 1.2 becomes "1.2" (coerced to str)
  • salt '*' pkg.installed version=['a','b'] → SaltInvocationError naming the offending kwarg at the originating module

What ships

  • Dispatch validation (salt/loader/validation.py) called from LoadedFunc.__call__ / LoadedCoro.__call__ — annotation-driven, no per-function decorators.
  • 2×2 opt grid — wire vs internal × input vs return, each off/warn/enforce/strict. Trust-tier split lets operators enforce at the boundary without paying overhead on hundreds of internal __salt__[...] dispatches per state chunk.
  • Per-loader overrides (loader_validate_overrides dict) for surgical tuning: states strict while grains off during module migration.
  • Hand-rolled startup validator (salt/config/loader_validation.py) matches salt/config/worker_pools.py convention — accumulates errors, raises once at LazyLoader.__init__. Catches typos in mode values and unknown loader names loudly rather than silently falling back to off.
  • Return contract system (salt/loader/contracts/) — StateReturn pinned on the states loader; two-tier (factory contract + per-function registry); honors module-declared -> SomeSubclass refinements as long as they are subclasses of the base contract.
  • Custom pydantic types (salt/loader/annotations/) — MinionID, Port, Duration, ByteSize as a demonstration set. More to follow as module authors need them.

What's intentionally not shipped

  • Not forcing pydantic as a hard import. salt.utils.versions.reqs.pydantic gates the whole layer; when pydantic is unavailable (older base-requirements state) the layer is a no-op. Add SafeDict/SafeList pillar wrapping with Pydantic secrets, output redaction, and no_log #68907 brought pydantic to 3008.x; master's merge-forward brings it here.
  • No existing module is annotated. This PR ships the mechanism and lets module authors migrate incrementally.
  • No per-kind contracts beyond StateReturn yet. beacons, tops, grains, pillars, matchers, outputters etc. have scaffolding but no contracts populated — each is its own small follow-up once a shape firms up.
  • Config-file-wide schema is explicitly out of scope. Research at agents/reports/nested_config_precedents.md confirmed Salt's modern convention is flat-prefix opts with hand-rolled validators, not nested config roots or schema libraries.

Test plan

  • Unit tests: 149, ~4s runtime (tests/pytests/unit/loader/test_validation.py, tests/pytests/unit/loader_types/test_types.py, tests/pytests/unit/config/test_loader_validation.py)
  • Functional tests: 16, ~2s runtime (tests/pytests/functional/loader/test_validation.py — real LazyLoader dispatch, no daemon)
  • Integration tests: 11, ~60s runtime (tests/pytests/integration/loader/test_validation.py — full publish path through real minion)
  • Pre-commit clean (black, isort, pylint, bandit, docstrings)
  • CI with test:full label

Operational notes

  • Default opts all off — zero behavioral change on upgrade.
  • Four modes: off, warn (log + pass through), enforce (raise SaltInvocationError), strict (enforce + require every param to be annotated).
  • Rollout patterns the opt grid unlocks:
    • State returns only, free bug catching: wire_return=enforce, everything else off.
    • Boundary-strict, trust internals: wire_*=strict, internals off.
    • Observability everywhere: all four = warn.
    • CI / dev, whole surface typed: all four = strict.

Audits

Performance and memory audits ran against the branch. Reports in agents/reports/:

  • validation_perf_audit.md — ~2-4μs per dispatch in off mode; strict-mode missing-annotations check cached on the function (fixed in follow-up commit); no startup-cost issues.
  • validation_memory_audit.md — no unbounded growth; per-function caches die with their functions on module reload. One concurrency hazard flagged (concurrent first-dispatchers can both build a pydantic model; loser's is GC'd — not a leak, documented as intentional).
  • nested_config_precedents.md — prior-art research on Salt config conventions. Drove the flat-opt + narrow-override-dict shape over a fully nested config root.

Follow-ups (not in this PR)

  • Populate per-kind contracts for beacons, tops, grains, pillars, matchers, outputters.
  • Populate per-function registries for runners, wheels, returners as shapes firm up.
  • Additional salt.loader.annotations types (PillarPath, GrainTarget, Jid, PkgVersion, SaltUrl) as module authors need them.
  • Incremental annotation of existing modules (one module at a time).
  • opts.get-RLock-per-dispatch optimization — defer until annotation adoption produces real dispatch volume (currently ~2-4μs per dispatch in off mode, below noise).

@dwoz
dwoz requested a review from a team as a code owner November 25, 2026 05:08
@dwoz dwoz added the test:full Run the full test suite label Nov 25, 2026
@dwoz dwoz added this to the Potassium v3009.0 milestone Nov 25, 2026
dwoz added a commit to dwoz/salt that referenced this pull request Nov 25, 2026
@dwoz
dwoz force-pushed the loader-validation branch from b59ed2f to 36bb264 Compare November 25, 2026 05:40
dwoz added a commit to dwoz/salt that referenced this pull request Nov 25, 2026
@dwoz
dwoz changed the base branch from master to 3008.x November 25, 2026 05:40
@dwoz dwoz modified the milestones: Potassium v3009.0, Argon v3008.7 Nov 25, 2026
dwoz added a commit to dwoz/salt that referenced this pull request Nov 25, 2026
twangboy
twangboy previously approved these changes Nov 25, 2026
Comment thread salt/loader/contracts/states.py Resolved
Comment thread salt/loader/lazy.py Resolved
dwoz added 25 commits November 25, 2026 16:04
Adds salt.loader.validation, hooked into LazyLoader._load_module, which
wraps functions with type annotations using pydantic. Gated by the new
loader_validate_mode opt (off/warn/strict, default off) so behavior is
unchanged until an operator opts in.

Annotation-driven -- no per-function decorators. Honors the Salt
aesthetic that modules are plain Python functions; wrapping happens at
the single chokepoint every exec/state/runner/wheel call flows through,
so core modules, saltext.*, and third-party _modules/ all get the same
treatment without each having to know about this mechanism.

Reserved kwargs injected by the publish layer and state compiler
(__pub_*, __id__, __sls__, ...) are filtered out of validation input
and forwarded unchanged to the wrapped function. State functions
(salt.states.*) additionally get StateReturn contract enforcement so
returns with result='True' (string) instead of True (bool) fail at
the offending module, not three layers downstream.

Pydantic is imported optionally; when unavailable the hook is a no-op.
The hand-written list in the first commit had two fabricated entries
(__pub_master, __pub_metadata) that don't exist, two wrong-category
entries (__low__ and __running__ are module globals set via
inject_globals, not kwargs), and was missing ~11 real reserved keys
including __pub_minion_is_target, __pub_resource_target*, __prereq__,
__prerequiring__, __sls_included_from__, and __umask__.

salt.state.STATE_RUNTIME_KEYWORDS is the canonical set the state
compiler uses; filter to dunder-named entries (plain-name runtime
keywords like failhard/onlyif/retry are stripped by the state compiler
before dispatch and never reach the loader). Deferred import avoids
a circular: salt.state imports salt.loader which imports this module.

Additionally, pattern-match __pub_* at split time to catch keys the
publish layer injects but the state compiler doesn't know about
(__pub_schedule, __pub_stamp) -- some modules like salt/modules/junos.py
intentionally read __pub_schedule from **kwargs.
Replaces the load-time setattr-walk with call-time validation inside
LoadedFunc.__call__ / LoadedCoro.__call__. Every loader dispatch already
flows through this chokepoint, so the walk-module logic was redundant.

Output contracts are now pinned per loader-kind by the factories in
salt/loader/__init__.py. salt.loader.states() passes
output_contract=StateReturn; everything else passes nothing. This
decouples "what's a state loader" from the tag string and makes it easy
to add contracts for beacons/tops/pillars/grains later without touching
LoadedFunc. LazyLoader.__init__ gains output_contract=None.

Input model is built lazily on first call per function and cached on the
function via __salt_validate_model__ -- only functions actually invoked
pay the model-build cost, versus eager wrap-at-load for every annotated
function in every loaded module.

validation.py drops wrap_module/wrap_callable and the dir()-walk / re-
export-filtering machinery. New surface is just validate_inputs() +
validate_return(). No module-object mutation.

Direct import of a module (e.g. 'from salt.modules.cp import get_file')
gets the raw function -- consistent with the existing story that outside
a loader context, modules are in degraded mode anyway (no __opts__, etc).
Old 'strict' is renamed to 'enforce' -- same behavior: validation
failures raise SaltInvocationError, but functions without annotations
pass through untouched.

New 'strict' adds the stronger semantic: every loader-dispatched function
must declare type annotations on all non-var parameters. First call to
any function that doesn't meet the bar raises SaltInvocationError with
the list of missing params. *args / **kwargs don't count (they can't be
pydantic-validated anyway).

Intended split: 'enforce' is the production knob ("loud failures where
we have contracts"); 'strict' is the dev / CI knob ("I require the whole
surface to be typed"). The four-level progression is now:

  off     -> no validation
  warn    -> validate, log + pass through on failure
  enforce -> validate, raise on failure
  strict  -> enforce + require annotations on every param
Replace single loader_validate_mode opt with two independent knobs:

* loader_validate_input_mode (off/warn/enforce/strict, default off) --
  governs validate_inputs() called from LoadedFunc.__call__. The
  'strict' level requires every loader-dispatched function to carry
  annotations on all non-var parameters.

* loader_validate_return_mode (off/warn/enforce, default off) --
  governs validate_return() against the loader's output_contract.
  No 'strict' level: contracts are factory-pinned, not annotation-
  driven, so the stricter semantic doesn't apply.

Input and return validation are different problems. Input validation
requires module-author migration to add annotations; return-contract
validation needs nothing from authors because the contract is pinned
on the states loader by the factory. An operator should be able to flip
return-contract enforcement on day one of this landing without first
having to annotate the entire exec/state surface -- and that's not
expressible with one shared knob.

Rollout patterns the split unlocks:

  input=off,     return=enforce  -- "catch state-return bugs now,
                                     migrate inputs later"
  input=warn,    return=enforce  -- "observe input failures while
                                     hard-enforcing returns"
  input=strict,  return=enforce  -- dev / CI: whole surface typed
  input=off,     return=warn     -- LTS: log without breaking
Seed the salt.types package with four demonstration types that cover
the two patterns a module author will encounter when adding typed
signatures:

* Annotated pattern (MinionID, Port) -- type alias combining an existing
  primitive with pydantic.Field or an AfterValidator. One line per type.
  Reads as a type at the call site.

* Custom core-schema pattern (Duration, ByteSize) -- class with
  __get_pydantic_core_schema__ that owns multi-form coercion. Accepts
  several surface representations (e.g. '30s' / '5m' / 3600 /
  'PT1H30M' for Duration; '500MB' / '1.5GiB' / 4096 / '4KiB' for
  ByteSize) and stores a canonical form (timedelta, int bytes).

Both patterns round-trip through model_json_schema() with title,
description, and examples, so published schemas carry usage hints
rather than bare primitive declarations.

Not a comprehensive library -- this is a demonstration of the pattern
and a starting point. Follow-ups by module as the loader validation
rolls out: PillarPath, GrainTarget, Jid, PkgVersion, SaltUrl, etc.

The pydantic import is optional; when absent the types alias to their
underlying primitives so imports from salt.types don't break modules
that don't actually dispatch through the validating loader.
The salt.types package shadowed Python's stdlib 'types' module in any
code path that depends on stdlib types.* and runs with salt/ on
sys.path as a top-level location. Pre-commit's docstring checker
tripped on this -- it runs salt/version.py as a script, and the
import chain argparse -> re -> enum -> 'from types import
MappingProxyType, DynamicClassAttribute' resolved 'types' to
salt/types/__init__.py instead of stdlib.

A similar collision also bit salt/loader/__init__.py's
'types.SimpleNamespace' call once salt.loader.types existed as a
submodule: Python's auto-binding of submodule-as-attribute rebinds
the parent package's 'types' attribute to the submodule once anyone
imports salt.loader.types, overwriting the parent's stdlib 'types'
import.

Renaming to salt.loader.annotations sidesteps both collisions:
'annotations' is not a stdlib module name, and the nested location
keeps the feature scoped to the loader-validation story.

Imports change from:
    from salt.types import Duration, ByteSize, MinionID
to:
    from salt.loader.annotations import Duration, ByteSize, MinionID
Introduce salt.loader.contracts as the Salt-owned home for return
contracts. Modules conform; they do not declare their own wholesale.

Two tiers:

1. Factory-pinned output_contract (universal per loader-kind). Same
   mechanism as before. StateReturn moves from salt.loader.validation
   into salt.loader.contracts.states (re-exported from validation for
   backward compat).

2. Per-function return_registry on LazyLoader -- a {"module.func":
   ReturnModel} dict for loader kinds where returns vary per function
   (runners, wheels, returners, auth, sdb, cache, executors,
   fileservers). Looked up by the loader-qualified function name at
   dispatch time. Scaffolding only in this commit; no entries yet.

Modules may still declare a more-specific return via -> SomeSubModel
annotation, provided it is a strict pydantic subclass of the base
contract. The loader honors the refinement and validates against the
more-specific type. Declarations incompatible with the base raise
SaltInvocationError at dispatch time -- no silent drift from Salt's
floor.

strict return mode now mirrors strict input mode: every loader-
dispatched function must be reachable through some contract (factory,
registry, or declared refinement). Un-contracted functions raise. That
is the discovery sensor for "Salt does not yet know what this returns"
-- turn strict on in CI, collect the gaps, work the list down by
adding registry entries as the shapes firm up.

Resolution precedence (first match wins):

  factory_contract + module declares a subclass of it   -> module's type
  factory_contract alone                                -> factory_contract
  registry entry + module declares a subclass of it     -> module's type
  registry entry alone                                  -> registry entry
  module declares only                                  -> module's type
  nothing + strict                                      -> raise
  nothing + non-strict                                  -> no validation

Resolved contract is cached per-function via __salt_return_contract__
so subsequent calls short-circuit. Incompatible-refinement errors are
not cached -- they re-raise every call so authors fix the declaration.
Replaces the three hand-rolled try/except ImportError + HAS_PYDANTIC
flags (salt.loader.validation, salt.loader.contracts.states,
salt.loader.annotations) with the existing Salt-wide convention:

    from salt.utils.versions import reqs
    if reqs.pydantic:
        from pydantic import ...

Registers "pydantic" in versions.DEPS_MAP so reqs.pydantic resolves via
the default module / version getters. Single source of truth for the
has-depend check; no drift risk between files. Also exposes version
comparison for free (e.g. reqs.pydantic >= "2.6") when a future
behavior needs to gate on a specific pydantic version.

Tests migrate from `validation.HAS_PYDANTIC` to `reqs.pydantic`
directly. The HAS_PYDANTIC symbol is removed everywhere -- it was
module-private branch state, never a stable API.
End-to-end coverage through a real minion's LazyLoader dispatch via
LoadedFunc.__call__ -- proves the publish layer, reserved-kwarg
injection, CLI-string coercion, and SaltInvocationError propagation
are all wired together. Complements the unit tests at
tests/pytests/unit/loader/test_validation.py which cover the
validation functions in isolation.

Two minion fixtures (module-scoped):

* input_enforce_minion -- loader_validate_input_mode=enforce.
  Covers:
  - valid annotated input passes through
  - CLI-string coercion ("42" -> 42, "true" -> True)
  - unparseable types raise SaltInvocationError
  - unannotated test modules unaffected
  - core test.ping unaffected (regression gate)
  - publish-layer __pub_* kwargs reach functions via **kwargs

* return_enforce_minion -- loader_validate_return_mode=enforce.
  Covers:
  - state function matching StateReturn contract passes
  - state function missing required 'comment' field triggers
    contract-violation error through state.single dispatch

A test exec module and a test state module are dropped into the
master's state tree and synced to the minion via saltutil.sync_*.
Total run time ~36s for the 8 tests.
Split the two mode opts (loader_validate_input_mode,
loader_validate_return_mode) into four, one per (scope x direction)
cell:

  loader_validate_wire_input_mode
  loader_validate_wire_return_mode
  loader_validate_internal_input_mode
  loader_validate_internal_return_mode

All default "off". Operators pick exactly the trust tier and direction
they want to enforce.

Scope is a trust-boundary concept, not a per-dispatch concept. Wire
loaders receive user input directly (filtered minion_mods, states,
runners, wheels); internal loaders back __salt__/__utils__ inside
shipped-code composition. Different change rates, different trust
levels, and -- in practice -- different performance profiles: a
highstate run does hundreds of internal __salt__ lookups per chunk,
and validating each one is wasted cycles once the boundary has
already been checked.

Implementation:

* salt/loader/lazy.py:LazyLoader gains is_wire_loader=False flag.
  LoadedFunc.__call__ / LoadedCoro.__call__ pick the scope prefix
  ("wire" vs "internal") from self.loader.is_wire_loader and read
  the corresponding opt pair.

* salt/loader/__init__.py flips is_wire_loader=True on the four
  user-input-gateway factories:
    - minion_mods -- only on the return (filtered) loader; the
      inner salt_dunder (unfiltered, becomes __salt__) stays
      is_wire_loader=False.
    - states, wheels, runner (salt-run / salt-api surface).

* salt/config/__init__.py registers the four opts in VALID_OPTS,
  DEFAULT_MINION_OPTS, DEFAULT_MASTER_OPTS.

Example rollout patterns:
  boundary-strict, trust internals:   wire_*=strict, internal_*=off
  state returns only, free gain:      wire_return=enforce, rest off
  observability everywhere:           wire_*=warn, internal_*=warn
  dev / CI, whole surface typed:      all four =strict

Integration tests (tests/pytests/integration/loader/test_validation.py)
add a TestScopeDistinction class that exercises the same state body
calling __salt__["validation_demo.typed"](count="not-a-number"):
  - wire_only_minion: inner call unvalidated; state succeeds.
  - wire_and_internal_minion: inner call raises; state fails.
Adds named loaders and a per-loader override dict on top of the four
tier-default opts, with a hand-rolled startup validator that catches
typos and malformed structure before dispatch.

Design shift from a nested config root to flat tier opts plus a
narrow override dict was driven by research into Salt's existing
config conventions (see agents/reports/nested_config_precedents.md):

* Modern Salt (post-3007 cluster_*, worker_pools, topology_*) uses
  flat-prefix sibling opts, not nested roots.
* Existing nested opts (log_granular_levels, external_auth, schedule)
  only type-check the top-level dict; interior typos silently no-op.
  For loader-validation modes the same silent-drop would be
  unacceptable -- an operator setting "enforcee" and believing
  validation is on when it isn't.
* Schema libraries haven't stuck in Salt core: salt/utils/schema.py
  (2014) never reached the config-load path; marshmallow (saltstack#4352) was
  rejected. Modern validators are hand-rolled accumulators matching
  salt/config/worker_pools.py:validate_worker_pools_config.

What's in this commit:

* salt/loader/lazy.py: LazyLoader gains a .name kwarg for logical
  identity; _resolve_validate_mode() picks override > tier > off.
* salt/loader/__init__.py: factories set loader names:
    minion_mods (filtered)     -> "wire_salt"
    minion_mods (inner dunder) -> "salt_dunder"
    states                     -> "states"
    runner                     -> "runners"
    wheels                     -> "wheels"
* salt/config/__init__.py: register loader_validate_overrides opt
  (dict, default {}).
* salt/config/loader_validation.py: new, hand-rolled
  validate_loader_validation_opts(opts). Checks every tier opt's mode
  value is one of {off,warn,enforce,strict}; checks every override
  key is a KNOWN_LOADER_NAME; checks every override direction key is
  {input_mode,return_mode}; accumulates errors, raises once with the
  full list. Cached via sentinel key so sibling LazyLoaders don't
  re-run against the same opts dict.
* LazyLoader.__init__ calls the validator -- typos surface at daemon
  startup, not silently at dispatch.
* Unit tests at tests/pytests/unit/config/test_loader_validation.py
  (22 cases covering validator + resolver behavior).
* Integration test TestPerLoaderOverride: tier default warn, per-
  loader override on "states" promotes return validation to enforce;
  bad_return state fails rather than logging + passing through.

Example config:

    loader_validate_wire_input_mode: warn
    loader_validate_wire_return_mode: warn
    loader_validate_internal_input_mode: off
    loader_validate_internal_return_mode: off

    loader_validate_overrides:
      states:
        return_mode: enforce      # promote returns to hard-enforce
      grains:
        input_mode: off           # skip during module migration

Known-loader-name set includes only the five named in this commit.
As more factories get names, both the set and the override acceptance
grow together -- preventing the silent-drop on an override key that
targets an unnamed (pre-migration) loader.
Fills the middle tier between unit (isolated validation functions)
and integration (full daemon through publish). Spins up a real
LazyLoader in-process against test modules written to a tmp dir --
exercises the actual LoadedFunc.__call__ dispatch, _resolve_validate_mode,
and the config validator wire-up, with no daemon startup overhead and
no /tmp/stsuite stale-scripts footgun.

16 tests covering:

* Input validation modes through real dispatch: off / warn / enforce /
  strict, coercion behavior, reserved-kwarg passthrough, unannotated-
  function behavior per mode.
* Return validation through a real states loader with StateReturn
  output_contract pinned: good return passes, bad return raises in
  enforce / logs in warn.
* Scope distinction: two loaders over the same module, one wire one
  internal, verified to read separate opt cells from the same opts
  dict.
* Per-loader overrides: both promotion (warn tier default -> enforce
  for states) and relaxation (enforce tier default -> off for
  wire_salt).
* Startup validator wire-up: bogus mode value / unknown override
  loader name raises at LazyLoader.__init__, not at first dispatch.

Run time: ~2s for the full file (vs ~60s for the integration suite).
Fixes three concerns surfaced by the perf and memory audits (reports
in agents/reports/).

1. **Delete the broken startup sentinel.**
   validate_loader_validation_opts() was caching a success marker on
   the opts dict via ``opts[_VALIDATED_SENTINEL] = True`` to
   short-circuit the ~25 LazyLoader-constructor calls at daemon
   startup. Two problems:
   - It leaked into ``salt '*' config.items`` output because OptsDict
     iteration walks the parent chain's ``_local``. Users would see
     ``_salt_loader_validation_opts_validated: True`` in their config
     dump.
   - It didn't actually cache across sibling loaders. safe_opts_copy
     creates OptsDict siblings (not parent-child) off a cached root;
     sibling ``_local`` state is invisible to peer lookups. All ~25
     loaders re-ran validation anyway.
   The ~25-125us total cost is noise. Delete the sentinel; always run.

2. **Cache _missing_annotations on the function.**
   Strict-mode dispatch called _missing_annotations on every call
   without caching, burning ~100-200us of inspect.signature overhead
   per dispatch -- 10x the rest of the validation path. Same
   ``__salt_*`` attribute-cache pattern the rest of the module uses.
   Stored as ``fn.__salt_missing_annotations__``; falls back to
   re-walking for unsettable callables (C builtins, functools.partial).

3. **Document the intentional non-lock on cache-attribute writes.**
   Both _set_cache (input model) and _get_or_resolve_return_contract
   write ``fn.__salt_*__`` without locks. Concurrent first-dispatchers
   can both resolve; loser's model is unreferenced and GC'd. Not a
   correctness bug and not worth a lock; add comments so future
   readers don't wonder.

One new unit test covers the _missing_annotations cache behavior.
166 unit+functional tests still pass. Integration suite unchanged.

Not addressed in this commit: the per-call opts.get overhead
(~2-4us/dispatch × 4 calls). Real but small and only pays off once
annotation adoption produces real dispatch volume; defer until then.
The 3008.x branch runs a ruff-incremental hook not present on master.
Seven violations in files added by this branch, now fixed:

salt/loader/annotations/__init__.py:
  RUF012 Duration._UNITS, ByteSize._MULTIPLIERS -- annotate ClassVar
  RUF022 __all__ not sorted -- sort alphabetically

tests/pytests/integration/loader/test_validation.py:
  RUF021 chained `a and b or c and d` -- parenthesize

tests/pytests/unit/config/test_loader_validation.py:
  PT011 broad pytest.raises(ValueError) -- add match= parameter (x2)

tests/pytests/unit/loader/test_validation.py:
  PT018 compound assertion -- split into two assert statements
The 3008.x branch shipped two config mechanisms for loader validation:
four tier-wide opts (loader_validate_{wire,internal}_{input,return}_mode)
gated by a per-loader is_wire_loader flag, and a per-loader overrides
dict keyed by LazyLoader.name. The dict superseded the tier opts for
every real rollout pattern, and keeping both made "which setting wins"
harder to explain.

Drop the tier opts entirely and keep loader_validate_overrides as the
sole knob. LazyLoader.is_wire_loader becomes dead code and is removed;
LazyLoader.name is now the only config-targeting attribute.

* salt/config: drop loader_validate_{wire,internal}_{input,return}_mode
  from VALID_OPTS and both DEFAULT dicts; update the validator to check
  only the overrides dict.
* salt/loader/lazy.py: simplify _resolve_validate_mode to read directly
  from loader_validate_overrides[<name>][<direction>_mode] and return
  "off" when the loader has no name or no entry.
* salt/loader/__init__.py: drop is_wire_loader=True from the four
  factory calls (minion_mods filtered, states, runners, wheels); keep
  the name= kwargs they already set.
* salt/loader/validation.py: update docstring to describe the overrides
  dict and the five known loader names.
* tests/pytests/unit/config/test_loader_validation.py: drop
  TestTierDefaults; keep overrides-dict coverage and update TestResolver
  for the new three-arg resolver signature.
* tests/pytests/functional/loader/test_validation.py: rewrite tier-opt
  callsites to use loader_validate_overrides syntax; replace the
  wire-vs-internal scope-distinction test with a per-loader-name
  lookup test.
* tests/pytests/integration/loader/test_validation.py: collapse the
  wire-only / wire-and-internal minion fixtures into the two surviving
  input/return enforce minions; convert all tier-opt overrides to the
  nested dict shape; keep the TestPerLoaderOverride scenario.

Unit + functional: 236 passed, 2 skipped (unchanged). Integration
TestInputEnforce: 6 passed.
Operator- and module-author-facing reference for the
loader_validate_overrides opt, annotation patterns, salt.loader.annotations
types, and the StateReturn contract. Cross-linked from the state-writing
and execution-module-writing refs.
Flow-style (inline ``{...}``) is inconsistent with Salt config
convention -- rest of the docs and conf/master / conf/minion use
block style throughout. Compactness isn't worth the mismatch
when operators copy-paste into their own config files.
Adds a fleet-wide baseline so operators don't have to enumerate every
loader name just to say "warn everywhere" or "strict everywhere".

Config shape and resolution:

    loader_validate_defaults:
      input_mode: warn
      return_mode: warn
    loader_validate_overrides:
      states:
        return_mode: enforce   # promotes states.return_mode above the warn default

Resolution order (first hit wins):
  1. loader_validate_overrides[<name>][<direction>_mode]
  2. loader_validate_defaults[<direction>_mode]
  3. "off"

Shipped with the same hand-rolled accumulator validator as
loader_validate_overrides. Typos in mode values or direction keys
raise at LazyLoader.__init__ rather than silently falling back to "off".

Factored the validation of a direction-map (``{input_mode, return_mode}``
subdict) out of the override loop so both opts share it.

Collapses most worked-config examples in the docs: observability-
everywhere, CI-full-typing, and LTS-warn-everywhere drop from
5 loaders enumerated to one three-line defaults block.
Three spots needed the new opt added:
  - Troubleshooting error-messages section (startup-raise examples)
  - Startup-failures paragraph
  - Pydantic-optional operational note
  - Changelog entry

Plus added the "must be a dict, got <type>" error pattern that the
validator emits for both opts when given a scalar or list.
Stacked definition-list terms (two labels on separate lines with a
shared indented explanation below) parse as "unexpected indentation"
under docutils / sphinx-build -W. The CI docs builds and tarball-build
cascade both failed on this -- the man-page build is where -W bites.

Fix: collapse each pair of error labels into a single definition
entry and mention the equivalent loader_validate_defaults error in
the body text instead.
Addresses two review comments from @charzl on saltstack#70943.

1) validate_inputs now preserves unannotated params and **kwargs
   extras. The previous implementation rebuilt the call from
   validated.model_fields, which drops anything the model doesn't
   know about:
     def install(name: str, **kw): install("x", refresh=True)
     # was: refresh lost
     def f(a: int, b): f(1, 2)
     # was: TypeError: missing 'b'
   Now: original args/kwargs are preserved; only the specific slots
   the pydantic model knows about are replaced with coerced values.
   Positional stays positional, keyword stays keyword, *args / **kwargs
   catchalls pass through unchanged.

2) State-system helper functions skip the StateReturn contract.
   mod_init, mod_aggregate, mod_run_check, and mod_run_check_cmd
   dispatch through the states loader but return bool / low-chunk
   dict / skip-signal -- not StateReturn-shaped. With
   loader_validate_overrides.states.return_mode=enforce the previous
   implementation would SaltInvocationError on all four. Skip by
   function basename at the top of validate_return.
   mod_watch and mod_beacon DO return real state dicts and stay
   validated.

Four new tests cover the input passthrough cases (positional,
unannotated-mixed, **kwargs, *args); two parametrized cases cover
the state-helper skip and the mod_watch/mod_beacon still-validates
behavior.
Two follow-ups from @charzl review:

1. YAML / salt-api / SLS content commonly parses ``version: 1.2`` as
   a Python float even when the target function declares
   ``version: str``. The user-facing doc claims
   ``salt '*' pkg.installed version=1.2`` coerces to ``"1.2"``; pydantic
   2 lax mode rejects it without ``coerce_numbers_to_str=True`` in the
   ConfigDict. Enabled on SALT_VALIDATE_CONFIG so the documented
   coercion story actually works for the CLI/YAML cases that produce
   this bug.

2. ``_coerced_kwargs`` was left behind after the args/kwargs
   passthrough rewrite in b790b84. The current validate_inputs
   mutates the original args/kwargs in place and never calls it.
   Removed.

Also: explicitly verified (not changed) that the _STATE_HELPER_FUNCS
skip in validate_return fires under ``loader_validate_defaults``
too -- the skip checks fn_name's last segment regardless of where
the mode came from, so mod_init / mod_aggregate don't trip over
``loader_validate_defaults.return_mode=enforce``. New test proves
the number-to-str path; existing state-helper tests already cover
that one.
The unit tests added alongside the three review-fix commits exercise
validate_inputs / validate_return in isolation. They prove the
mechanisms work but not that they actually run under real
LoadedFunc.__call__ dispatch. These functional tests dispatch through
a real LazyLoader so the fixes are regression-guarded end-to-end:

TestStateHelperSkipThroughDispatch (6 cases)
  - mod_init / mod_aggregate / mod_run_check / mod_run_check_cmd
    under loader_validate_overrides.states.return_mode=enforce
  - mod_init / mod_aggregate also under loader_validate_defaults.
    return_mode=enforce (the scenario charzl called out specifically)
  - Sanity: regular state functions (good / bad) still validate.

TestInputPassthroughThroughDispatch (2 cases)
  - def mixed(annotated: int, unannotated) -- the unannotated slot
    must reach the function body. Without the fix the function
    raises TypeError because the arg was dropped.
  - def install(name: str, **kwargs) -- **kwargs contents must reach
    the function body. Without the fix the extras were dropped.

TestNumberToStrCoercionThroughDispatch (2 cases)
  - version=1.2 (float) must arrive as "1.2" (str). Without
    coerce_numbers_to_str=True in SALT_VALIDATE_CONFIG, pydantic
    rejects float->str and SaltInvocationError propagates.
  - version=42 (int) must arrive as "42" (str). Same path.

All assertions inspect the function's actual return value, which
proves the function was invoked with the expected args, not just
that validate_inputs returned a plausible shape. Each test exercises
the full dispatch path including the _resolve_validate_mode lookup,
validate_inputs, fn(*args, **kwargs), and validate_return.

Also factored two small helpers (_wire_salt_overrides,
_states_overrides) to keep fixture setup terse.

This branch was previously deployed

1 inactive deployment
ci — 996d6296 Deployed Nov 26, 2026 by dwoz via Build Onedir Packages / DEB (x86_64) #29712
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

test:full Run the full test suite

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: loader dispatch accepts untyped user input; type mismatches surface silently or deep in module bodies

3 participants