Skip to content

std.random should generate the requested type instead of fixing results at i32 #2279

Closed

Description

@ehartford

std.random fixes its public generated-value type at i32: next_i32(), range_i32(lo: i32, hi: i32), and an i32 seed. Callers needing another type must convert the result or write their own RNG adapter. Eric identified this as the bug while reviewing the Goose benchmark port: the RNG should generate the requested type instead of making every consumer cast an implementation-chosen integer width.

The internal state width and the public generated-value type are separate facts. An RNG may use a fixed unsigned state internally without exposing that representation as the only result type.

Evidence

At repository HEAD 5cb113bce720dba2907801293378aa80f4467afb, lib/std/random.w declares:

pub fn next_i32 -> i32
pub fn range_i32(lo: i32, hi: i32) -> i32

Minimal reproduction, run with installed with v0.15.3.0:

use std.random
let hi: i64 = 1099511627776
let value: i64 = range_i32(0, hi)
print(value)

The call rejects the i64 upper bound as an implicit narrowing to the API's i32 parameter. This interval cannot be generated by producing an i32 first and widening it afterward.

For a smaller destination the same API imposes consumer-side ceremony:

builder.push_byte(range_i32(97, 123) as u8)

This spelling also appears in docs/spec/toolchain/with_oneliners.md. In the in-progress Goose port, a copied xs_mod(state: u64, modulus: i64) -> i64 helper similarly forces narrowing casts at i32, i16 and u8 consumers. It is another instance of the API problem, not evidence that random values intrinsically need i64.

Expected

Typed/generic generation, with the requested result type inferred from bounds or a destination wherever one meaning is forced. Integer generation should cover signed and unsigned widths; floating-point generation should produce the requested float type with a declared distribution. Other generatable types should have a deliberate extension mechanism rather than require casting a raw integer. Exact API spelling is left to implementation/design; this issue does not claim a new spelling is already specified.

The mission is the governing requirement: when the program already determines the type, forcing its programmer to restate a conversion is a compiler/library defect. The current inventory in docs/spec/stdlib/libstd-spec.md lists the i32-only helpers; it does not already promise a generic API. This is the maintainer-requested correction to that surface, not a request to weaken the general integer conversion rule.

Acceptance

  • Generate the requested numeric type directly, including intervals wider than i32, without consumer casts when context determines the type.
  • Verify inference from typed bounds and owned destination contexts, and keep explicit type arguments available for genuinely ambiguous calls.
  • Test signed/unsigned extremes, small widths, float endpoints, seeded reproducibility and bounded distribution. Do not implement bounded generation by overflowing signed subtraction/absolute value or by silently introducing modulo bias.
  • Keep legacy width-specific functions compatible if retained, and migrate callers when the generic surface is ready.
  • For the Goose benchmark adapter, preserve the upstream unsigned xorshift and modulo sequence exactly so comparison checksums remain valid; that deterministic benchmark mapping must not be confused with a general unbiased range generator.

Related: #1058 concerns INT32_MIN overflow inside existing range_i32/chance; it is distinct from the missing typed surface and needs coverage when that implementation is changed.

Workaround currently used: explicit conversions in the draft benchmark adapter/ports. No RNG implementation fix was made in this task, per Eric's instruction to file the bug.

Activity

  1. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Triage 2026-10-25, with v0.15.3.0 (main a261b65): reproduced. lib/std/random.w still exposes seed(seed_value: i32), next_i32() -> i32, range_i32(lo: i32, hi: i32) and now range_isize; no function generates the type its use demands.

    pre-release: Eric called this the bug, the module is small, and the shape follows his parse-by-use direction (one generic method typed by use, never a width in the name).

  2. ehartford commented on Oct 25, 2026

    @ehartford
    ContributorAuthor

    Fix campaign 2026-10-25: flagged human attn needed. This is an API and language-mechanism decision, not a bug with one exact line.

    What I found. lib/std/random.w exposes seed(i32), next_i32, range_i32, range_isize and chance. A range typed by its use needs a function generic over every integer width (and a float form). Std has no way to write that today: no integer trait or numeric bound exists (trait Int/Numeric appear nowhere in lib/std), and parse[T] is a compiler-typed builtin, not a std generic.

    Brief.

    1. Others. Zig: intRangeAtMost(r, comptime T: type, at_least: T, at_most: T) T (unbiased; …Biased variants named apart), generic over the integer type. Swift: T.random(in: lo..<hi) on every FixedWidthInteger, typed by the range. Go: rand.IntN(n int), plus rand.N[Int intType](n Int) Int generic over integer kinds. Rust std: random<T>(dist) typed by the distribution.
    2. Spec. libstd-spec.md:75 lists only seed, seed_now, next_i32, range_i32, chance. Nothing promises a generic surface; the mechanism (a numeric bound usable in std generics) is not specified either.
    3. Mission fit. A width in the name and a cast at every use is the ceremony the mission names. The With-y shape is parse-by-use: one random.range(lo, hi) typed by its bounds or destination (let b: u8 = random.range('a', 'z' + 1)), plus random.next[T]() where nothing else forces the type.
    4. Prediction (80%). Eric rules range(lo, hi) generic over integer and float types, typed by use, unbiased (rejection sampling, never modulo), with the width-named functions removed once callers migrate.

    Narrowest open question. Which mechanism carries "generic over integer types" in std: (a) a numeric trait (Integer/Float) that std generics can bound on, which is a language feature, or (b) random.range as a compiler-typed builtin as parse is? (a) serves every numeric library after it; (b) is quicker and adds a second special case.

    Left on do-before-release.

  3. ehartford commented on Oct 26, 2026

    @ehartford
    ContributorAuthor

    Correction to my comment above: parse[T] is not a compiler-typed builtin. No such thing exists (the only parser was std.string.parse(s) -> i32), and #598 rules out type arguments at call sites. #959 now adds a std trait Parse implemented per numeric type plus str.parse[T: Parse]() -> Option[T], typed by its use (D160, delegated). So option (b) in the question above was based on a mistake. A trait std generics can bound on, as Parse is, is the mechanism that exists today. A random.range generic over numeric types would need a trait with arithmetic, which std does not have, so the question stands narrowed to that.

  4. ehartford commented on Oct 26, 2026

    @ehartford
    ContributorAuthor

    Implemented on branch fix-2279 (1fb11b1), stacked on fix-2326b: next[T: Random]() -> T and range[T: Random](lo: T, hi: T) -> T, typed by the use or the bounds. No arithmetic trait was needed after all: each Random impl is concrete (every integer type up to 64 bits, f32, f64) and draws through one 64-bit helper, the way #959's Parse works, and a generic result binds from its demand. seed takes a u64; the i32 helpers are gone and their users call range. Recorded as D162 (delegated: the brief was 80% and this is not interop, ownership or safety; I should not have parked it). Test: behav_2279_random_draws_the_demanded_type.

  5. ehartford commented on Oct 26, 2026

    @ehartford
    ContributorAuthor

    Fixed on main by 763bdd8 (stack #2749 via #2747, battery GREEN on its top 41f0547: behavior-tests 1953 files ok, gate, uat and battery-checks green).

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions