r/learnrust • • Jan 11 '24

Why does Rust produce inconsistent results?

So, for the first time in a decade of programming in various languages, I'm getting intermittently wrong results from execution. Specifically, I run the same non-network program with the same input and get different results.

I plan to hunt this down, paring the example down, etc. Really, I'm trying to understand why Rust allows this? I thought consistency was part of it's zen.

The core data structures are a cyclic tree of nodes, with each node having a three character identifier, and identifiers for the left and right:

type NodeList = HashMap<String, (String, String)>

Also, I have a mutating vector of positions for simultaneously walking the nodes. That is, for each item in the vector, change it's string pointer to point to the corresponding node table's left or right entry. The suspicious code for this:

let mut positions : Vec<&str> = ....
...
for pos in &mut positions {

let p = next_position(pos, lr, &nodes); *pos = p; }

When I run with the same data, I get different results.

  • Why?

  • Why does Rust allow it to compile?

The full code

https://gist.github.com/merriam/d5f63bc6cb279812396006ca1010fe6a

The output

General output with lots of debug information:

One version ends with

After 2 steps, next char is L, positions are ["11Z", "22C"]

After 4 steps, next char is L, positions are ["11Z", "22B"]

Final positions are ["11Z", "22Z"]

Ran for after 6 steps.

or sometimes

After 3 steps, next char is R, positions are ["22Z", "11B"]

Final positions are ["22Z", "11Z"]

Ran for after 6 steps.

The input

https://gist.github.com/merriam/23a4ce77889436d09966423b3429f6d5

LR

11A = (11B, XXX)

11B = (XXX, 11Z) 11Z = (11B, XXX) 22A = (22B, XXX) 22B = (22C, 22C) 22C = (22Z, 22Z) 22Z = (22B, 22B) XXX = (XXX, XXX)

0 Upvotes

17 comments sorted by

63

u/cafce25 Jan 11 '24 edited Jan 11 '24

Your output relies on the order of HashMap keys, but it's not guaranteed (and in fact randomized by the current implementation). You could use a BTreeMap instead to get a deterministic outcome.

8

u/shaleh Jan 12 '24

This is correct.

Python earlier than 3.7 (I think?) also did not use a stable hash. Putting things in and pulling out of dictionaries were used as cheap randomization historically.

3

u/AdvanceAdvance Jan 12 '24

Correct about Python. A faster algorithm for hashes ('dict') was introduced in the main Python 3.6 (cPython), and had the side effect of being stable. After some handwringing and time for the various other implementations to adopt (numPy, IronPython, Jython, etc., etc.), stability became part of the 3.7 standard expectations.

2

u/AdvanceAdvance Jan 12 '24

Thank you for your help. Yes, I am surprised by that, and languages have been switching to stable hashes as the newer algoritms provide stability as side effect of improved speed and concurrency.

That said, the order issue is only within the Vec<&str>, I do not iterate over the node HashMap.

OK, I'll divide and conquer it.

Again, thank you for your time.

1

u/sw17ch Jan 12 '24

Your start_string_iter is created by iterating over the keys of the node hashmap.

38

u/algebraicstonehenge Jan 11 '24

And this is explicitly on purpose to avoid hashdos attacks. In this case, consistency can actually hurt.

7

u/N-partEpoxy Jan 11 '24

Or a different Hasher.

1

u/Alfrheim Jan 12 '24

I was going to write that. Actually that is a behavior in many other languages .

19

u/volitional_decisions Jan 11 '24

Yes, non-deterministic code will provide non-deterministic results.

4

u/AdvanceAdvance Jan 12 '24

I'm sorry. Could you be more vague?

3

u/bleachisback Jan 12 '24

Rust HashMap implementation by default has a random state to avoid attackers being able to guess hashes and initiate hash DoS attacks

1

u/bhones Jan 15 '24

Yes, actually..

3

u/izerth Jan 12 '24

Doing Advent of Code, I see from the data.  Good way to learn the quirks of a language.

2

u/AdvanceAdvance Jan 12 '24

Yes. A day with VSCode, a day writing the whole code with pencil and paper first, a day of fully test driven style, and day 8 was supposed to be in Rust. I'm hoping to get through it for a day with CursorLess, a day with Swift, some days exploring "associative" level multiprocessing in various languages, and a day with Elixer.

I actually finish is it about one year in three. Unfortunately the base contest usually devolves into obscure math and hidden edge cases.

1

u/nicholsz Jan 13 '24

Advent of Code is definitely Rust's most common use case (at least that's what I use it for)

-2

u/Long_Investment7667 Jan 11 '24

What is meant by „one version ends …“ ? Version of the program? Version of the input? Different times?

0

u/[deleted] Jan 12 '24

[deleted]

2

u/AdvanceAdvance Jan 13 '24

Thank you for the insight.

This problem was the hash iteration (guaranteed-ish unordered) into a vector (guaranteed ordered) via collect():

let start_string_iter = nodes.keys().filter(|key| key.ends_with('A'));
let mut positions = start_string_iter
.map(|s| s.as_str())
.collect::<Vec<&str>>();

The particular test data yields one answer about 90% of the time, so not too likely to lead to the sniggly errors that occur only one test cycle in ten. The only solutions off hand:

  • Live with the error path, the current solution.

  • Create a type distinction between ordered and unordered, which places a load on developers to eliminate a rare issue. Alternately, use funky transformations to track indeterminate values during compilation, remove indeterminism by sorts or other actions, and disallow using indeterminate values.

  • Use an external Tarsier to watch for instances where an unordered to ordered conversion occurs and then calls an ordered effect (like print) before a loosing its unordered ability (like sort). This is the "load the smarts into an external tool" approach.

Oddly, I find the most valuable error path elimination in Rust is one that all the languages shoudl grab: passing collections in a non-mutable method. Being sure that a hash parameter cannot be modified, and that it's contents cannot be modified from that parameter, is extremely valuable.

I am old. I remember when the standards committee allowed 'non-const consts' to gut the idea of const in C++.