Have Single and Populated fail instead of skipping#19489
Have Single and Populated fail instead of skipping#19489chescock wants to merge 8 commits intobevyengine:mainfrom
Single and Populated fail instead of skipping#19489Conversation
alice-i-cecile
left a comment
There was a problem hiding this comment.
Unfortunately I think that this is the right call. It's clear, consistent and the error messages will guide users to discover how to do this. If we're loudly failing for resources, we should do the same here.
When<Single<D, F>> isn't that bad to write, and it does make it clearer what's going on.
|
#19490 is important for reviewers to consider when deciding how they feel about this behavior. |
Co-authored-by: Alice Cecile <alice.i.cecile@gmail.com>
# Conflicts: # crates/bevy_input_focus/src/lib.rs
# Conflicts: # crates/bevy_ecs/src/schedule/executor/mod.rs
There was a problem hiding this comment.
In general, not a fan of how we are going back-and-forth on the failure behavior of Single.
In spirit of #14275, I can imagine a future API change where we invert the default again and make all Res, Single, and Populated params skip instead of fail with a new wrapper like Required<Res<&TestComponent>> to explicitly make it panic.
Since 2 maintainers have approved this, I trust this is the right call. But I personally would not merge it because I believe Bevy should generally make panicky APIs opt-in, not opt-out.
Yeah, I agree that the constant breaking changes are bad! I'm optimistic that this will be the end of them, though. The last changes were made late in the release cycle when we wanted to get something working, and there wasn't time for a lot of debate or for big changes like introducing
In case it helps, note that parameter validation errors do go through the error handler. If you set a non-panicking |
|
That's a very fair point! I would still want Note: Since all my dependencies would still expect failing |
|
Hmm, I like |
|
Per @viridia, |
|
We had a good long bikeshed about this last night. This is effectively our current approach (with slightly different keywords):
This PR advocates instead for this, for consistency:
But some other people (@janhohenheim especially) want to invert this:
And other people (@CorvusPrudens) want to have more semantic options:
This last one would require the default error handler to have the power to differentiate error coming from I'd like to point out that both the My proposal would be to commit to the semantics defined by this PR, which error by default, and then as follow up work to improve the information on our error types so that the default error handler can implement more complex behavior. |
|
I'd like to respond to @janhohenheim as well.
I don't think you should be able to "opt-in" to panicking on the local level; panic behavior should be controlled centrally by the end-user app, not by libraries. And whether panics are opt-in or opt-out on the global level doesn't really matter, because it's easy to change as a blanket policy. What we are talking about here is opt-in/opt-out local error semantics, which is different. Not every error is a panic, and errors still exist no matter what you choose to do with them. Hot take: I do actually think errors should be opt-out, which is to say errors should be handled explicitly. When errors are opt-in it's way to easy to make mistakes and not realize it, especially as a beginner. |
|
Extremely good assessment! I think my only remaining issue is that I don’t see a way to say "This
All in all, that temporary hit in usability until the error handler becomes more flexible could be worth it in the long run. I think you’ve convinced me that this PR may be a good path forward 🙂 |
# Objective Regardless of where we land on #19489, `When` as a system param wrapper is a touch verbose. In many cases, users may find themselves liberally applying `When` to their fallible system params. I believe that `If` maintains the same semantics in a smaller and more readable package, and therefore should replace `When`. ## Showcase `When`: ```rs fn fallible_params(player: When<Single<&mut Velocity, With<Player>>>, gravity: When<Res<Gravity>>) {} ``` `If`: ```rs fn fallible_params(player: If<Single<&mut Velocity, With<Player>>>, gravity: If<Res<Gravity>>) {} ```
# Objective Regardless of where we land on bevyengine#19489, `When` as a system param wrapper is a touch verbose. In many cases, users may find themselves liberally applying `When` to their fallible system params. I believe that `If` maintains the same semantics in a smaller and more readable package, and therefore should replace `When`. ## Showcase `When`: ```rs fn fallible_params(player: When<Single<&mut Velocity, With<Player>>>, gravity: When<Res<Gravity>>) {} ``` `If`: ```rs fn fallible_params(player: If<Single<&mut Velocity, With<Player>>>, gravity: If<Res<Gravity>>) {} ```
This is the bikeshed of all time, but I needed to bring this up before it became a breaking change. In my opinion, `Allow<Disabled>` sounds better than `Allows<Disabled>`. I don't think there's a 1-to-1 comparison in other query keywords yet, but there's the hypothetical `Expect` in [the discussion on #19489](#19489 (comment)), as opposed to `Expects`. `Allows` hasn't been in a release yet, so it's free to change until 0.17 comes out.
|
Personally while Single version was panicking, i asked ai to write macro for me that looked like this: use your_crate::silent; // your proc macro crate
#[silent]
fn my_system(
player: Single<&Player>,
camera: Single<&Camera>,
other_things: Query<Entity, ...>
) {
// ...
}and it unravels to this: fn my_system(
player: Option<Single<&Player>>,
camera: Option<Single<&Camera>>,
other_things: Query<Entity, ...>
) {
let Some(player) = player else { return; };
let Some(camera) = camera else { return; };
// ...
}and macro itself looked something like this: use proc_macro::TokenStream;
use quote::{quote, format_ident};
use syn::{
parse_macro_input, FnArg, ItemFn, Pat, PatIdent, PatType, Type, TypePath,
};
#[proc_macro_attribute]
pub fn silent(_attr: TokenStream, item: TokenStream) -> TokenStream {
// Parse the input function
let mut input_fn = parse_macro_input!(item as ItemFn);
// Collect the names of parameters to unwrap, and modify them to Option<Single<T>>
let mut unwrap_pats = vec![];
for input in &mut input_fn.sig.inputs {
if let FnArg::Typed(PatType { pat, ty, .. }) = input {
// Check if type is `Single<...>`
if let Type::Path(TypePath { path, .. }) = &**ty {
let segments = &path.segments;
if segments.len() == 1 && segments[0].ident == "Single" {
// Change type to Option<Single<...>>
*ty = syn::parse_quote! { Option<#ty> };
// Extract the variable name from the pattern
if let Pat::Ident(PatIdent { ident, .. }) = &**pat {
unwrap_pats.push(ident.clone());
}
}
}
}
}
// Insert early return code at the beginning of the function block:
// let Some(param) = param else { return; };
let mut unwrap_stmts = vec![];
for var in unwrap_pats {
unwrap_stmts.push(quote! {
let Some(#var) = #var else { return; };
});
}
let orig_block = &input_fn.block;
input_fn.block = Box::new(syn::parse_quote!({
#(#unwrap_stmts)*
#orig_block
}));
TokenStream::from(quote! { #input_fn })
}and that way i could choose what option of system i wanted - panicking or not. I dont think that macro is a good solution to this in particular because it feels more magic than the rest of bevy. maybe instead introduce |
|
Cutting from the 0.17 milestone. It's not critical that we make a decision now, and I don't think we should ship a change to make this fail without a corresponding way to downgrade failures from panics in the default error handler. |
|
I think that's a fair decision. I will try to prioritize the work for error-levels, I think that will make this decision a lot easier. |
Objective
Change the behavior of
SingleandPopulatedto fail validation instead of skipping systems. Users who want the skipping behavior can recover it by wrapping them inWhen<T>.This is a very controversial change, and there has been a lot of discussion about it! See some discussion on #18504 (comment), which was spun out into #18516, and some later discussion on #18927 (comment).
I'll try to summarize the arguments here so we don't need to repeat all of them in comments, but let me know if I'm missing or misrepresenting anything and I'll try to update the summary. (And maintainers should feel free to update it!)
Pros
Singleis useful for asserting invariants about your model, just as the failingResparameter is useful.If we don't change the behavior here, we may need to offer another way to do that.
Currently users need to remember the behavior separately for each kind of system parameter, but with this change they would know that systems skip if and only if they write
When.SingleandReswill be important.I expect users to first learn about resources as a separate concept, and later learn that resources are just a special kind of entity. It will be helpful to be able to teach "
Resis just a special kind ofSingle" without needing to qualify "except that it fails instead of skipping".Regardless of the failure behavior,
Singleis more convenient thanQuerywhen you know you have exactly one entity, so it will be used when the user expects it never to fail. Most of the uses in the Bevy examples are in this category! If it does fail, then this is something the user didn't expect and we should inform them. If they do want to skip the system at that point, the error message can guide them to addWhen. And global error handlers can be used to ensure that anything missed still won't crash the game.Most code that uses Bevy hasn't been written yet!
Cons
Singleis unnecessary now that we have fallible systems.Users can use an ordinary
Queryparameter and write a simplelet value = query.single()?to get erroring behavior, but there is no concise way to get skipping behavior.The skipping behavior is much more useful than the failing behavior, and will be needed more often. We don't want Bevy to have a reputation for requiring useless boilerplate for common tasks!
Singleis very new, and we should take time to learn how it's being used in practice before making big changes.Singlewas introduced in 15.0 with the skipping behavior, and was changed to panic in 15.1 with no workaround. This was a major pain for users who had been eager to use the skipping behavior. The skipping behavior was just restored in 16.0, and breaking it again in 17.0 would be really irritating for some of our most enthusiastic users.Solution
Change the behavior of
SingleandPopulatedto fail validation instead of skipping systems.Wrap them in
Whenwhere needed to fix tests.