Skip to content
This repository was archived by the owner on Apr 25, 2025. It is now read-only.
This repository was archived by the owner on Apr 25, 2025. It is now read-only.

Does the combo of subtyping and unreachable code require actual type inference? #516

Closed

Description

@fitzgen

Consider the following example. I've annotated it with the operand stack in between each opcode twice:

  1. Once with the appendix's algorithm.
  2. A second time with wasm-smith's "actual" stack.

The difference is that the appendix algorithm truncates the stack after unreachable code, letting subsequent pops materialize their expected types, while wasm-smith maintains the "actual" stack going into the unreachable code.

AFAICT, the formal typing rules don't actually mandate the appendix's operand stack truncation. There has never been divergence between the two approaches until now, with the introduction of subtyping.

In the following example, the br 0 makes the subsequent code unreachable. The appendix will additionally truncate the stack. Next, the br_on_null is typed [anyref anyref] -> [anyref (ref any)] due to the type of its label. With wasm-smith's actual stack, this type checks fine because structref <: anyref combined with the rules for subtyping between instructions. For the appendix algorithm, we have an empty stack in unreachable code, so when the br_on_null wants to pop the anyref that the label demands, it does, and then when it pushes it back onto the stack, it pushes an anyref. Not a structref. This is the source of the divergence between the two approaches. Finally, the br_on_cast_fail observes the "actual" structref, triggering a type mismatch: expected structref, found anyref error in the appendix algorithm.

(module
  (func (param anyref) (result anyref)
    ;; 0x1b: appendix: []
    ;;         actual: []
    ref.null struct
    ;; 0x1d: appendix: [structref]
    ;;         actual: [structref]
    local.get 0
    ;; 0x1f: appendix: [structref anyref]
    ;;         actual: [structref anyref]
    br 0
    ;; 0x21: appendix: []
    ;;         actual: [structref]
    local.get 0
    ;; 0x23: appendix: [anyref]
    ;;         actual: [structref anyref]
    br_on_null 0
    ;; 0x25: appendix: [anyref (ref any)]
    ;;         actual: [structref (ref any)]
    drop
    ;; 0x26: appendix: [anyref]
    ;;         actual: [structref]
    br_on_cast_fail 0  structref structref
  )
)

The reference interpreter, and wasmparser, report the type mismatch error and consider the example invalid. But despite that, it isn't clear to me that it really is invalid.

Firefox and wasm-smith consider the example valid.

If this example is valid, then it seems like popping from an empty operand stack in unreachable code would have to, in this case, produce a value that is constrained to be some subtype of anyref but not necessarily exactly anyref and then the subsequent br_on_cast_fail would add a second constraint that the value is additionally a subtype of structref, and then implementations would need to solve these constraints to determine validity. But that kind of constraint solving and "real" type inference is something that we intentionally avoid requiring in Wasm validation. So if this example is currently valid, it seems like we want to do something to avoid the need for this kind of constraint solving.

Concrete Questions

  1. the actual formal typing rules don't mandate the appendix's operand stack truncation

    Is this statement true or false?

  2. Is the example valid or invalid?

Thanks for your time!

Activity

  1. tlively commented on Feb 6, 2024

    @tlively
  2. fitzgen commented on Feb 6, 2024

    @fitzgen
    Author
  3. tlively commented on Feb 6, 2024

    @tlively
    Member

    I don't think this really gets to the crux of the issue, but I'm curious about how keeping the stack like you describe can ever work. For example, this is perfectly valid:

    block
     f32.const 1.0
     f32.const 2.0
     br 0
     i32.add
     drop
    end
    

    Wouldn't keeping the stack around produce an error about the i32.add having f32 operands?

  4. fitzgen commented on Feb 6, 2024

    @fitzgen
    ContributorAuthor

    Wouldn't keeping the stack around produce an error about the i32.add having f32 operands?

    I guess the difference is that wasm-smith is generating valid Wasm modules, not validating arbitrary Wasm modules. Given your example, it does seem like truncation is necessary for a validator.

    So I guess the question is: is truncation necessary for generators? I think this is equivalent to asking whether we can add an unreachable anywhere in a valid function body and still end up with a valid function body.

  5. rossberg commented on Feb 6, 2024

    @rossberg
    Member

    First of all, the fact that the example is rejected has nothing to do with unreachable code or "stack truncation". The following sequence is invalid regardless of what's before it:

    (local.get 0)
    (br_on_null 0)
    (drop)
    (br_on_cast_fail 0 structref structref)
    

    The reason is that after the br_on_null the two topmost values on the stack are two anyrefs (assuming both local 0 and label 0 have type anyref, as in your example). Because the typing rule is:

    • br_on_null $𝑙 : [𝑡* (ref null ℎ𝑡)] → [𝑡* (ref ℎ𝑡)]
      • if $𝑙 : [𝑡*]

    Note how the stack result is determined (and fixed) by the type of $𝑙. (A more permissive rule would be possible, but would be more complicated yet only rarely more useful in practice. Edit: well, possible except for the loss of principal types.)

    As for truncating the stack, that is "mandated" by the spec in so far as the declarative type of br allows consuming an arbitrary number of virtual values from the stack:

    • br $𝑙 : [𝑡₁* 𝑡*] → [𝑡₂*]
      • if $𝑙 : [𝑡*]

    There are infinitely many ways to instantiate the 𝑡₁* and 𝑡₂* in this rule, but an algorithm always needs to make the most general choice, otherwise it wouldn't be complete. And the most general algorithmic solution is to pop everything currently the stack because after that the algorithm can successfully pop any type it wants, especially bottom, which is at least as permissive as anything that could have been on the stack before.

    A simple example demonstrating this would be

    (func
      (i32.const 0)
      (br 0)
      (ref.is_null)
      (drop)
    )
    

    An algorithm that does not "truncate" the stack would incorrectly reject this.

    As an aside, the algorithm from the Appendix does not just truncate the stack, it replaces it with the polymorphic stack. So a more faithful way to annotate the example above e.g. would be

    ;; []
    (i32.const 0)
    ;; [i32]
    (br 0)
    ;; [...]
    (ref.is_null)
    ;; [... i32]
    (drop)
    ;; [...]
    

    where "..." denotes the polymorphic bottom of the stack, from which arbitrary types can be drawn.

    An alternative is to annotate the actual instruction types:

    (i32.const 0)  ;; [] → [i32]
    (br 0)         ;; [i32] → [bot]
    (ref.is_null)  ;; [bot] → [i32]
    (drop)         ;; [i32] → []
    

    Here, the output of each type must match up with the input of the next. For br, 𝑡₁* was instantiated with i32 and 𝑡₂* with bot. Any reference type would also work instead of bot, but that would require guessing ahead.

    So, to summarise the answers to your questions:

    1. Yes and no: there would be other ways to formulate an algorithm (e.g., with search and backtracking), but for simple forward checking like with the Appendix' algorithm, you have to truncate.

    2. The example is invalid, but for unrelated reasons.

    And to the question in the issue's subject: no, forward checking is enough. The principal types property of the Wasm type system (esp the "Closed Principal Forward Types" theorem) ensures that.

    Finally, Firefox and wasm-smith seem to have bugs in their validators, but from your example alone it is unclear whether they are related to stack polymorphism.

  6. fitzgen commented on Feb 7, 2024

    @fitzgen
    ContributorAuthor

    Thanks for the explanation, and pointing out the root issue with the br_on_null.

    In wasmparser we were doing

    push_operands(pop_operands(label_types))
    

    instead of

    pop_operands(label_types)
    push_operands(label_types)
    

    in some places where we shouldn't have. That caused us to consider the following valid:

    (module
      (func (param anyref) (result anyref)
        ref.null struct
        local.get 0
        br_on_null 0
        drop
        br_on_cast_fail 0  structref structref
      )
    )
    

    but then adding an unreachable just after the ref.null struct would make us consider it invalid and it seemed wrong to me that inserting an unreachable anywhere would ever make a Wasm invalid.

    Glad that things have been cleared up!

    FWIW, Firefox seems to have a similar bug. Filed https://bugzilla.mozilla.org/show_bug.cgi?id=1879096 for them.

    Thanks again!

  7. rossberg commented on Feb 7, 2024

    @rossberg
    Member

    Can I motivate you to add a test for this to the Wasm test suite? :)

  8. fitzgen commented on Feb 7, 2024

    @fitzgen
    ContributorAuthor

    Writing one already :)

  9. added a commit that references this issue on Feb 7, 2024
  10. fitzgen commented on Feb 7, 2024

    @fitzgen
    ContributorAuthor
  11. added a commit that references this issue on Feb 7, 2024
  12. tlively commented on Feb 7, 2024

    @tlively
    Member

    Just a note that local.tee can be susceptible to similar problems! The type it leaves on the stack is the type of the local, not the type of the teed operand.

  13. 21 remaining items

  14. tlively commented on Mar 12, 2024

    @tlively
    Member

    For your implementation as described in the OP, yes, I can see that this would cause problems. But I think you could resolve them by using the stack-truncating algorithm as described in the appendix. It might also be necessary to update the algorithm from the appendix to say that it should always pop bottom types (e.g. (ref none) instead of anyref) so that discovering a tighter constraint on a type later will never be a problem.

  15. fitzgen commented on Mar 13, 2024

    @fitzgen
    ContributorAuthor

    It might also be necessary to update the algorithm from the appendix to say that it should always pop bottom types (e.g. (ref none) instead of anyref) so that discovering a tighter constraint on a type later will never be a problem.

    Ah! This is a good insight, thanks for sharing. Popping bottom types from unreachable operand stacks should indeed solve this issue.

  16. titzer commented on Mar 13, 2024

    @titzer
    Contributor

    In the Wizard code validator, (almost) every pop from the value stack has an expected type[1]. The control stack stores a top limit, and if popping would cross the top limit, then it checks if the current control stack entry is in the unreachable state, and then allows it (popping a value of the expected type if so). This replaced a bunch of logic that previously did different things if the current control entry was reachable or not. Popping the control stack then resets reachability to what it was in the previous control scope.

    [1] A couple exceptions are the numeric select instruction and ref.as_non_null and br_on_non_null, which do actually check for unreachable.

  17. tlively commented on Mar 15, 2024

    @tlively
    Member

    It might also be necessary to update the algorithm from the appendix to say that it should always pop bottom types (e.g. (ref none) instead of anyref) so that discovering a tighter constraint on a type later will never be a problem.

    It turns out that the validation algorithm in the appendix already pops the real bottom type Bot, which is even more bottom than (ref none), so it doesn't need to be updated. But it also means that my suggested algorithm is not permissive enough. For example, this should be a valid instruction sequence after my suggested changes to br_if typing:

    block (result anyref)
     block (result funcref)
      unreachable
      i32.const 0
      br_if 0 ;; now [bot i32] -> [bot], previously [bot i32] -> [funcref]
      i32.const 0
      br_if 1 ;; now [bot i32] -> [bot], previously invalid because [funcref] </: [anyref]
      unreachable
     end
     unreachable
    end
  18. tlively commented on Mar 15, 2024

    @tlively
    Member

    I've created a PR that shows the concrete modifications we would like to make to the spec: #532. I recommend that we continue the discussion there, since the original question here has been resolved.

  19. rossberg commented on Mar 15, 2024

    @rossberg
    Member

    [Sorry for the delay, I’m at a conference right now, and no time to reply earlier.]

    @tlively:

    my understanding is that we could both have principal types and preserve type information in these instructions if we relaxed our principal types rule to allow bounds on type variables. Is that correct? If so, is there a good reason we might not want to do that?

    Good question. Unfortunately, that wouldn’t quite match the definition of principal type. And indeed it would make the notion somewhat useless for the original reason we cared about it, as a criterion for type annotations. That’s because subtyping constraints are very (too) powerful – you can encode random stuff in them. For example, with a <: b ∧ b <: a you can effectively express equivalence, meaning that it is a free pass to move almost all structural information "to the side”, thereby justifying dropping most type annotations.

    Instead of “every legal type is a (supertype of a) substitution instance of the principal type” you’ll have “every legal type is a solution to a set of inequations”, which is a rather big qualitative difference and does not constrain much at all anymore.

    Equality vs inequality constraints also make a huge difference algorithmically, because subtype constraints tend to accumulate. Closely related to the discussion, this not-so-fine line is what made “full” type inference for functional languages practical, while it explodes for languages with subtyping. And the seemingly innocent relaxation we're discussing, which essentially expands inference to subtyping, would be crossing that exact line.

    We don't support loop parameters

    Okay, but then, the aforementioned issues aside, aren't you basically suggesting to tailor the Wasm specification for one algorithm that isn’t even correct/complete for Wasm as it stands, and by means of a change that will be moot once it is made so? Would you really argue that is sufficient motivation?

    I’d be very hesitant to make such a change at the last minute, with such unclear repercussions to the fabric of the type system.

  20. titzer commented on Mar 15, 2024

    @titzer
    Contributor

    I updated Wizard's code validator to comply with the new test that was added. It was doing the wrong thing according to the spec, preserving types on the stack after br_if_non_null. Popping and then repushing the label's args was already necessary to comply with br_if's rules, for which I believe there were already tests. So in that sense I'm totally fine with the current rules for new branches, as they are consistent with existing branches.

    However, I do get @tlively 's point better now. The obvious implementation in a abstract-interpretation-based validator (which all production algorithms are, for efficiency) is to just leave types on the stack; that's most efficient and most precise. It concerns me a bit that we're losing type information for a type-system consistency property like principal types. It also seems to me that no abstract-interpretation-based approach is going to be solving a constraint system; that only seems to come up with bottom types due to unreachable. In practice what they are going to do is try to pop label args, and if that fails because it goes into a polymorphic part of the stack, they'll default to the label's arg types and continue forward with those.

    It's a little concerning that we're hitting issues with this now; the spec tests have really poor coverage and yet implementations are relying on them to know if they've gotten things right. We need more effort here to test more cases, maybe even automatically generating many possible combinations or even fuzzing. Implementations will continue to get subtle details like this wrong and rely on tests to find issues.

  21. tlively commented on Mar 15, 2024

    @tlively
    Member

    That’s because subtyping constraints are very (too) powerful – you can encode random stuff in them...

    If I’m not mistaken, the form of subtyping constraints I have in mind where upper bounds must be closed, i.e. cannot themselves contain type variables, is much less powerful. The system of inequalities it allows you to form is just an independent collection of closed upper bounds for each type variable, so it is trivially solved with GLB calculations. And we already depend on those for typing br_table, so that shouldn’t be a problem. Note that this holds even with the bottom type due to unreachability.

    However, I do get @tlively 's point better now. The obvious implementation in an abstract-interpretation-based validator (which all production algorithms are, for efficiency) is to just leave types on the stack; that's most efficient and most precise.

    Yes, exactly :)

    It's a little concerning that we're hitting issues with this now; the spec tests have really poor coverage...

    The biggest problem is that AFAIK no implementation contributes their own tests back upstream as spec tests, so for many of us the spec tests become merely a box to check to finish a proposal. We will be able to start contributing some of Binaryen’s tests upstream soon.

  22. titzer commented on Mar 15, 2024

    @titzer
    Contributor

    @tlively I had a separate offline conversation with Nick and the need for a combined regression suite seems to be universally felt. What I've done in Wizard has often been to slice and dice spec tests into smaller units and write my own .wast tests, in addition to internal unit tests. It'd be great if we could pool them all somehow.

  23. rossberg commented on Mar 19, 2024

    @rossberg
    Member

    @titzer:

    It concerns me a bit that we're losing type information for a type-system consistency property

    We are already doing the same for select, for example, in order to avoid the need for lub's. Type systems are always compromises between precision and other factors like simplicity.

    It also seems to me that no abstract-interpretation-based approach is going to be solving a constraint system

    Well, no, abstract interpretation is using a fixpoint iteration (because loops, joins, and such). But that's what @tlively tries to avoid – which is exactly what would get us a constraint system instead (solving which, btw, will also require a fixpoint iteration, over the constraints).

    @tlively:

    If I’m not mistaken, the form of subtyping constraints I have in mind where upper bounds must be closed, i.e. cannot themselves contain type variables, is much less powerful.

    That wouldn't work, unfortunately. Since the same type can flow through multiple such instructions in an instruction sequence, you'd need to be able to accumulate multiple constraints on the same variable – or alternatively, allow constraints relating variables to other variables. Because instruction types have both co- and contra-variance, I'm also 99% sure you'd need both upper and lower bounds. I don't think you can get away with closed bounds either, because of composition (afaict, closed bounds are never enough for such systems). Somebody would have to work through the proofs to figure all this out, and that's no longer trivial.

    The fact that all this is non-obvious is alone reason to be uncomfortable. The current rules are at least conservative.

  24. tlively commented on Mar 19, 2024

    @tlively
    Member

    @rossberg, have you had a chance to take a look at the PR I uploaded making this concrete? It would be helpful if you could explain the problems you see with the proposed change in particular, rather than with having type bounds generally.

    That wouldn't work, unfortunately. Since the same type can flow through multiple such instructions in an instruction sequence, you'd need to be able to accumulate multiple constraints on the same variable...

    Do you agree that accumulating multiple constraints would be fine if they were all closed upper bounds?

    I don't think you can get away with closed bounds either, because of composition (afaict, closed bounds are never enough for such systems).

    The only sources of nontrivial bounds we need are branch target types for the conditional branch instructions and local types for local.tee. Both are always closed, and I don't see how composition comes into it. Can you explain more?

  25. titzer commented on Mar 19, 2024

    @titzer
    Contributor

    Well, no, abstract interpretation is using a fixpoint iteration (because loops, joins, and such). But that's what @tlively tries to avoid – which is exactly what would get us a constraint system instead (solving which, btw, will also require a fixpoint iteration, over the constraints).

    Actually I don't think this is true for Wasm loops. Loops have type annotations, so the only part of the stack that can be polymorphic is due to unreachable code before the loop leaving (potentially constrained) type variables on the stack. But looping back to the start of the loop can only happen within the loop, and the polymorphic part of the stack before the loop cannot be modified (or even accessed--it's a validation error to do that); there are no additional constraints to merge back in when coming back.

  26. tlively commented on Mar 19, 2024

    @tlively
    Member

    The proposed change really has nothing to do with fixed point computations at all, and I regret ever bringing them up. The goal is to eliminate unnecessary casts, not to eliminate the need for fixed point computations. The fixed point algorithm I previously described was a way to eliminate some of the same unnecessary casts.

  27. rossberg commented on Mar 20, 2024

    @rossberg
    Member

    @tlively:

    @rossberg, have you had a chance to take a look at the PR I uploaded making this concrete? It would be helpful if you could explain the problems you see with the proposed change in particular, rather than with having type bounds generally.

    I looked at the PR, but I'm not sure that helps. The difficulty is the principal type property, which isn't gonna work as currently spelled in the PR.

    The only sources of nontrivial bounds we need are branch target types for the conditional branch instructions and local types for local.tee. Both are always closed, and I don't see how composition comes into it.

    Composition meaning sequencing.

    Every type annotation will also contribute constraints. For example, when the result of a br_if flows into a select, you get a new constraint on the prior variable from select's annotation.

    In some cases these constraints are only partial, i.e., have different structure. For example, when the result of br_if flows into extern.convert_any, the combined constraint is gonna be something like α <: (ref β any), where β abstracts nullability. Similarly for other cases where other variables come into play. This is not closed. (And it probably implies the need for bounds on other variable classes as well.)

    The proposed change really has nothing to do with fixed point computations at all, and I regret ever bringing them up. The goal is to eliminate unnecessary casts, not to eliminate the need for fixed point computations.

    Well, we arrived at the current semantics after extensive and controversial discussion, which already considered all this at length. Usually we avoid revisiting such discussions unless there are significant new findings – double so this late in the game. It doesn't sound like you think there are?

    @titzer:

    Actually I don't think this is true for Wasm loops. Loops have type annotations

    The annotations on loops are of course just as imprecise as the ones we are discussing. Any analysis that wants to reconstruct "precise" types, as with abstract interpretation, would of course not use them. Unless they do not care about more precise types than whatever the type system specifies, but then the point of discussion is moot as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions