Parameter validation for filter and test plugins

While for modules there’s the argument spec to validate parameters, and for many plugin types there’s the Ansible configuration manager (which uses the plugin’s DOCUMENTATION), and even for action plugins there’s ActionBase.validate_argument_spec() by now, there is no “official” way to validate arguments for filter and test plugins. In the collections I maintain, there’s a huge amount of always somewhat different and still related validation code in filter and test plugins - sometimes arguments are validated more strictly, sometimes not so strictly, and sometimes not at all. Especially when checking more complex input this can easily result in way more code for validation than for the actual plugin implementation.

While recently reviewing a PR which added a new argument to an existing filter, I thought a bit more about this and got an idea: namely to use type hints, and create a decorator that validates the passed values according to the type hints. There does exist a Python library to do this (typeguard), but I don’t really want to add another dependency (especially not for existing plugins), and also the way this validation likely works is not always what users expect. For example, isinstance(True, int) is True and isinstance("foobar", Sequence) is True, but usually you don’t want booleans to be accepted for integers and strings (and byte strings) as sequences.

I started prototyping a PR for community.general that provides two decorators filter_type_checking and test_type_checking (in plugins/plugin_utils/_typecheck.py) that do exactly this: Add type checking helpers for filters and tests by felixfontein · Pull Request #13401 · ansible-collections/community.general · GitHub

The current implementation handles the most important types that appear, including typed dicts, literals, and more complex things like dict[str, list[dict[int, Literal["foo", "bar"] | bool]]]. It uses is_sequence to test for Sequence (so no strings and bytes matching), and explicitly rejects booleans when checking for int. (You can always do Sequence | str | bytes or int | bool if you really want to include such types.) One goal was also to produce (somewhat) nice error messages on validation failures (that includes calling the first argument ‘the filter input’ or ‘the value to test’ instead of by its name).

First, what do you think about this? The PR adjusts c.g’s test plugins to use this new validation, and Comparing type-check...type-check-2 · felixfontein/community.general · GitHub does the same for all filter plugins. (Some validation is now more strict, some more lenient, like accepting sequences or mappings instead of list and dict.)

Then I’m also thinking of being able to use this in other collections. For that, it needs to be available as a public interface (and I think community.general is the wrong place for that). What do you think of another “library” community collection, say community.library_type_checking_v1 (similar to community.library_inventory_filtering_v1), that provides such tooling for other collections so that not everyone has to re-invent the wheel? (I’d probably pick ansible-core 2.16 as a minimum supported version, since ansible-core 2.16 and 2.17 require Python 3.10+ on the controller, and Python 3.10 already supports most of the things needed, except for Required/NotRequired for TypedDict.)

(To make this explicit: this does not check whether DOCUMENTATION agrees with the type signatures. Also if an unsupported type is encountered, the decorator raises an exception, so the sanity tests will complain about the plugin file being unimportable. That way you cannot accidentally use a type hint that’s not supported.)

My take on this is that filters and especially test plugins should not return errors at all. They should return values.
How users can deal with failing filter? I bet they will not be able to see / understand that error is comming from filter, and from which one (if several are used) just because error messages are not user friendly.

I’m not sure what you mean. Returning values instead of errors when errors happens sounds wrong to me. Also error messages that mention the plugin name and type (which ansible-core already does by itself) generally tell users that this is happening in a filter or test.

Try

ansible localhost -m debug -a 'msg={{ 23 | flatten }}'

for example. The error message Task failed: Finalization of task args for 'ansible.builtin.debug' failed: Error while resolving value for 'msg': The filter plugin 'ansible.builtin.flatten' failed: 'int' object is not iterable is already pretty helpful IMO.

Going one step further, it might be interesting to have more fine-grained validations, for example a param is an int but the logic of the plugin requires it to be non-negative (>= 0). That’s not something the proposed decorators will give us, but it might be quite useful.

I mean that

A shared helper for type checks sounds useful, since it would keep validation consistent across filters and tests. Clear error messages would also make it easier for users to spot a wrong input type quickly.

While for flatten this would work, I think this is a total antipattern. Wrong input should result in errors (unless explicitly configured to not), not simply being ignored. This only results in follow-up situations that are way harder to debug / understand.