Skip to content

Typst panic on comparison function #6285

Closed

Description

@Trebor-Huang

Description

The sorted function on arrays sometimes panics with the message

thread 'main' panicked at library/core/src/slice/sort/shared/smallsort.rs:865:5:
user-provided comparison function does not correctly implement a total order

when a key argument is provided. It seems that #5627 resolves this, but for a different purpose, i.e. to allow custom comparison functions in typst. Here the bug is a panic even without such custom comparison. I'm not sufficiently familiar with the codebase so might as well confirm. In any case, using a key argument to sort the array should never raise this error because built-in typst values should have correctly implemented total orders.

Somewhat minimized example:

#let translation-table = state("translations", ())
#let add-entry(zh, en) = translation-table.update(it => {
  it.push((zh, en))
  it
})
#let translate(zh, en) = [#zh #en #add-entry(zh,en)]

#translate[语境][context]
#translate[原始表达式][raw term]
#translate[判值相等][judgmental equality]
#translate[元理论][metatheory]
#translate[归纳递归类型族][indexed inductive-recursive type]
#translate[归纳类型族][indexed inductive type].
#translate[语境性][contextual]
#translate[宇宙][universe]
#translate[累积][cumulation]
#translate[正规形式][normal form]
#translate[中性形式][neutral form]
#translate[更名][renaming]
#translate[典范形式][canonical form]
#translate[语义][semantics]
#translate[解释][interpretation]
#translate[模型][model]
#translate[自洽][consistent]


#translate[我][] // Empty! Seems to panic only when the items are added in specific orders.


#translate[相容][consistent]
#translate[独立][independent]
#translate[反模型][contermodel]

#context {
  let final = translation-table.final().sorted(key : ((zh, en)) => en.text)
  for (zh, en) in final [
    / #zh: #en

  ]
}

Reproduction URL

No response

Operating system

No response

Typst version

  • I am using the latest version of Typst

Activity

  1. added
    bug
    on May 16, 2025
  2. added
    crash
    scripting
    on May 16, 2025
  3. Enivex commented on May 16, 2025

    @Enivex
    Collaborator

    Is it reproducible without using context?

  4. PgBiel commented on May 17, 2025

    @PgBiel
    Contributor

    It is a bug because the compiler itself is crashing instead of printing an error.

    Note that the error you mention already exists:

    Error: cannot compare none and string
       ╭─[/main.typ:8:2]
       │
     8 │ #("a", none).sorted()
    ───╯

    The problem is that the error appears to be delayed, and Typst still tries to compare until that particular comparison is reached, leading to the panic, which would explain why it is only sometimes triggered. In fact, the key function isn't required to reproduce the bug.

    This appears to be a minimal reproducer:

    #(("a", "b", "c", "d", "e", "z") * 3 + ("c", none, "a")).sorted()
    Prior example

    Based on the example, this seems to be a (maybe not the most) minimal reproducer:

    #(
      "context",
      "raw term",
      "judgmental equality",
      "metatheory",
      "indexed inductive-recursive type",
      "indexed inductive type",
      "contextual",
      "universe",
      "cumulation",
      "normal form",
      "neutral form",
      "renaming",
      "canonical form",
      "semantics",
      "interpretation",
      "model",
      "consistent",
      
      
      // commenting 'none' fixes it
      none,
      
      
      "consistent",
      "independent",
      "contermodel",
    ).sorted()

    This panics with panicked at 'user-provided comparison function does not correctly implement a total order'.

  5. laurmaedje commented on May 19, 2025

    @laurmaedje
    Member

    Fixing our comparison logic won't mean we can fix user provided comparison logic, which would be required to drop glidesort.

  6. laurmaedje commented on May 19, 2025

    @laurmaedje
    Member

    The example case is just a user providing a bogus comparison function. The std version will panic, while the glidesort variant will just return bogus. The former is not acceptable for us, but the second is okay --- it's user error.

  7. Enivex commented on May 19, 2025

    @Enivex
    Collaborator

    Wouldn't silently returning something incorrect be worse? The problem here seems to mostly be that it's panicking instead of erroring.

  8. laurmaedje commented on May 19, 2025

    @laurmaedje
    Member

    It's not okay for the compiler to panic. It is a bug: It crashes typst watch, it is not displayed in IDEs as an error, it crashes the web app compiler, etc. Meanwhile, a bad sorting result is not that big of a big deal imo if you provide a bad comparison function. An error would be even better of course, but it's already much better than a compiler panic. A compiler panic is the equivalent of a Rust internal compiler error (ICE).

  9. Enivex commented on May 19, 2025

    @Enivex
    Collaborator

    I didn't mean to imply a panic was ok. Just that making it silently return something incorrect sounds like a bandaid fix.

  10. laurmaedje commented on May 19, 2025

    @laurmaedje
    Member

    I was mostly responding to this.

    Exactly. Second one is worse.

    I'm sorry if the response came off in a gruff way.

  11. RungeCC commented on Nov 11, 2025

    @RungeCC
    Contributor

    The latest version of Typst still crashes on this. Perhaps the quickest fix is

    1. to replace the built-in comparison function branches with glidesort as well, but this only addresses the surface issue.

    Fundamentally, Typst's Value only implements a partial order (through ops::compare). Under certain reasonable safety principles, it should not use any implementations requiring total order (notice glidesort has the same requirements although it does not panic on this).

    Two other potential approaches come to mind:

    1. Use or rewrite a crate like try_partialord that allows fallible comparisons while working with PartialOrd. The advantage is that we could detect cases where user-provided comparison functions may not model Ord and issue warnings. However, this might introduce additional dependencies, and, requires further research.
    2. Keep glidesort for the by cases, but implement a total order for typst_library::foundations::Value. This feels somewhat hacky, but is relatively easier to implement. Incomparable values would be ordered based on their ad hoc (or, hardcoded?) indices in the Value enum (with special care for floating-point numbers).

    I personally lean toward option 1., but remain open to discussion.

    Gently ping @laurmaedje

  12. laurmaedje commented on Nov 12, 2025

    @laurmaedje
    Member

    Could you expand on option 1? I'm not sure exactly what you're imagining.

  13. RungeCC commented on Nov 12, 2025

    @RungeCC
    Contributor

    So for example in try_partialord, try_sort could retrun InvalidOrderError if partial_cmp results a None value.

    In general, for user provided comparision, the best thing we could do is given a warning/error if internal invariant of a certain sort algorithm is detected violated (for type models PartialOrd, the only possible case is partial_cmp return None, but user provided comparision may not models PartialOrd as well); for typst internal Value, result of try_sort could be ignored since we know that such error is always generated from trying to compare incomparable values (but not from violating, for example, transitivity or duality), either values of incomparable types, or floating-point values, and then will be a typst syntax error (so, in this sense, it's just like use glidesort).

    Perhaps the most urgent thing right now is to apply option 0 to fix the crash. We may consider other options later, since the behavior of typst under such errors should not be guaranteed.

    CC: @laurmaedje

  14. laurmaedje commented on Nov 24, 2025

    @laurmaedje
    Member

    Perhaps the most urgent thing right now is to apply option 0 to fix the crash.

    Agreed.

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

    bugcrashscripting

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions