Skip to content

Conversions follow Python's rule: cross-category is an error - #714

Merged
David-Noble-at-work merged 6 commits into
developfrom
lossless-conversions
Aug 27, 2026
Merged

David-Noble-at-work merged 6 commits into
developfrom
lossless-conversions

Conversation

@David-Noble-at-work

Copy link
Copy Markdown
Contributor

Closes #709. Depends on #713, merged in.

convertDirect asked Go whether the source was ConvertibleTo the target and converted if so. Go's answer is
about representability, not meaning, and it says yes to conversions that silently produce a value nobody
wrote.

Four defects, found while scoping

Conversion Was What happened
int64(65) → string "A" the rune at that code point
int64(300) → int8 44 wraparound
int64(-1) → uint8 255 sign reinterpreted
float64(3.9) → int 3 fraction discarded

All silent. float64 → string and bool → string were already refused because Go permits neither — and that
contrast is what made the integer cases read as deliberate.

The rule

Starlark is Python-shaped, so conversions answer to Python's rule rather than Go's:

A cross-category conversion is an error whatever the value. Within the integer category, the value must be
in range.

Why category and not a round trip. A round-trip rule accepts float(3.0) → int, since it survives the
trip, while refusing 3.9. Python rejects both — [1,2,3][1.0] is a TypeError though 1.0 is integral. A
rule that takes 3.0 and refuses 3.9 is one no author can predict.

Integer → string is refused by kind, not by range. 65 round-trips back to 65 and 0 round-trips
through "\x00", so only the kinds tell the truth.

file.mkdir(mode=0o644) reaches an os.FileMode — a uint32 — so integer-to-integer in range cannot be
refused by kind either. That pair is why the rule needs both halves.

Two more defects, found after the rule was written and passing

The rule was implemented, merged, and covered by eight tests. Enumerating the full numeric surface — rather
than the six cases the rule was written from — found two more still standing.

float64(1e40) → float32 yielded +Inf. Unguarded: losesMeaning covered int→string, float→int, and
int→int, and never looked at float→float.

uint64(max) → int64 yielded -1. This one is not missing coverage but a hole in the method. The
round-trip check converts and converts back — and signed and unsigned of equal width share a bit pattern, so
MaxUint64 → -1 → MaxUint64 compares equal and passes. The check only ever worked when the widths differed.
More rows in the same shape would never have found it.

integerLosesValue now asks about sign directly before falling back to the round trip.

Precision versus magnitude is the design content of the float fix, and it is Python's line:
struct.pack('f', 0.1) succeeds and quietly stores 0.100000001490116; 1e40 raises struct.error. So
0.1 → float32 still converts and 1e40 → float32 does not.

A refused conversion names the remedy

int64 value is neither assignable nor convertible to string is Go's vocabulary for a Starlark author's
mistake — it says what failed, not what to write. explainRefusal answers each shape the way Python does,
naming a function Starlark has:

param msg: cannot use int64 where string is wanted: write str(x) to render it
a float64 cannot be interpreted as int: write int(x) to truncate it deliberately
300 is out of range for int8

The test asserts the guidance, matching write str(x) rather than string. A test matching only
string passes whether the message helps or not.

Tests

TestNumericSemantics_MatchPython — 17 rows, accepting and refusing. A rule stated only by its refusals
cannot be checked for overreach. Each row names the Python behavior it mirrors, and that string prints on
failure.

TestNumericSemantics_DeliberateDeviationsFromPython — the four places we knowingly differ.
bool ↔ int is stricter than Python, whose bool is an int subclass ([1,2,3][True] == 2);
string ↔ []byte is looser, since Python requires .encode(). Splitting these out is the point: a
deviation recorded only in prose is an assumption, and here changing one is a decision someone makes on
purpose rather than a test quietly going green.

Plus the six original rows, written before the fix and each proved failing first, and print(42) at the
Starlark surface — which was blocked on #713 and previously printed *.

Also included

convert_struct_test.go hydrated a struct from a map with a literal float64 reaching an int field. Its own
doc comment said "an int from a JSON float64", so it encoded the compensation #711 removed rather than a
contract. Now json.Number("3").

Verified

make check, make test-race, make test-scenario — all pass.

David Noble added 6 commits August 27, 2026 00:50
KNOWN RED. Blocked on #711; see the bottom of this message.

convertDirect asked Go whether the source was ConvertibleTo the target and converted
if so. Go answers a question about REPRESENTABILITY, not meaning, and says yes to four
conversions that silently produce a value nobody wrote:

  int64(65)    -> string   "A"     the rune at that code point
  int64(300)   -> int8     44      wraparound
  int64(-1)    -> uint8    255     sign reinterpreted
  float64(3.9) -> int      3       fraction discarded

float64->string and bool->string were already rejected, because Go permits neither --
and that contrast is what made the integer cases read as deliberate.

The rule is python's, because starlark is python-shaped
  A cross-category conversion is an error whatever the value, and within the integer
  category the value must be in range. Category is decided by kind; range is the only
  question a value gets asked, and only integer-to-integer asks it.

Why category and not a round-trip test
  A round-trip rule would ACCEPT float(3.0) -> int, since it survives the trip, while
  refusing 3.9. Python rejects both: [1,2,3][1.0] is a TypeError though 1.0 is integral.
  A rule that takes 3.0 and refuses 3.9 is one no author can predict.

  int -> string still needs rejecting BY KIND rather than by range: 65 round-trips back
  to 65, and 0 round-trips through "\x00", so only the kinds tell the truth.

  file.mkdir(mode=0o644) reaches an os.FileMode -- a uint32 -- so integer-to-integer in
  range cannot be rejected by kind either. That pair is why the rule needs both halves.

The strictness is fair because starlark has str(), int(), and float(). An author who
means "65" writes str(65); one who means 3 writes int(3.9).

Tests were written BEFORE the fix
  Six cases, each failing for its documented reason, now passing. On the previous two
  branches every test written after its fix had to be re-proved by breaking the fix --
  and the second time that deadlocked the build. Writing them first makes the proof free.

Why this is red
  Five save/load tests now fail with `param mode: float64 ... fs.FileMode`. Not a defect
  in the rule: LoadGraph decodes json with plain json.Unmarshal, so every reloaded number
  is a float64, and Convert had been truncating it back. Removing the truncation exposes
  it. That is #711 -- it also changes recomputed checksums, so it reaches graph identity
  -- and it lands first.

  Also outstanding here, not on #711: convert_struct_test.go hydrates a struct from a map
  with a literal float64 reaching an int field, no json involved. That test encodes the
  old lenient contract.
Eight rows, each naming the change that turns it red. Two carry weight beyond regression:

  Row 4, float64(3.0) -> int refused, IS the ruling made executable. A round-trip rule
  accepts 3.0 and refuses 3.9; the category rule refuses both. Nothing else in the suite
  distinguishes them, so without this row the guard could be "simplified" back into the
  unpredictable version with every other test still green.

  Row 7, the counterweight: 0o644 -> uint32, int64 -> float64, and string <-> []byte all
  still convert. A rule that rejects everything is not a rule, and file.mkdir(mode=0o644)
  depends on integer-to-integer in range. It passed before the fix and must after.

Also records what is NOT covered: bool-where-an-integer-is-wanted stays rejected though
python allows it, string <-> []byte stays implicit though python does not, and the
container paths are covered by construction because they funnel through convertDirect.
…on rules

The conflict was in convert.go and was expected: both branches added a step to the same
conversion ladder. Resolved by keeping BOTH, because they are complementary rather than
competing.

  tryParseSerializedNumber (#713) reads a serialized number AGAINST its field.
  losesMeaning (#709) refuses conversions that change meaning.

Neither subsumes the other. Verified after resolving: both are wired into Convert, each
of the four functions appears exactly once, and the suite left exactly one failure --
convert_struct_test.go, which is what step 8's measurement predicted before the merge.
…s missed

Enumerating every numeric conversion class -- rather than the six the rule was written
from -- found two silent defects still standing:

  float64(1e40) -> float32   yielded +Inf. Unguarded: losesMeaning covered int->string,
                             float->int, and int->int, and never looked at float->float.

  uint64(max)   -> int64     yielded -1. Not an omission but a hole in the METHOD: the
                             round-trip check converts and converts back, and signed and
                             unsigned of EQUAL WIDTH share a bit pattern, so MaxUint64 ->
                             -1 -> MaxUint64 compares equal. The check only ever worked
                             when the widths differed.

integerLosesValue now asks about sign directly before falling back to the round trip. The
float case takes python's distinction rather than Go's: PRECISION may be lost, MAGNITUDE
may not. struct.pack('f', 0.1) succeeds and quietly stores 0.100000001490116; 1e40 raises
struct.error. So 0.1 -> float32 still converts and 1e40 -> float32 does not.

Two tests, deliberately separated
  TestNumericSemantics_MatchPython is 17 rows covering the whole surface, accepting AND
  refusing -- a rule stated only by its refusals cannot be checked for overreach. Each row
  names the python behavior it mirrors, and that string prints on failure.

  TestNumericSemantics_DeliberateDeviationsFromPython is the four places we knowingly
  differ. bool <-> int is STRICTER than python, whose bool is an int subclass, so
  [1,2,3][True] == 2. string <-> []byte is LOOSER, since python requires .encode().

  Splitting them is the point: a deviation recorded only in prose is an assumption. In the
  second table, changing one is a decision someone makes on purpose rather than a test
  quietly going green.

Also: a refused conversion now names the remedy. "int64 value is neither assignable nor
convertible to string" is Go's vocabulary for a starlark author's mistake -- it says what
failed and not what to write. explainRefusal answers each shape the way python does,
naming a function starlark has: write str(x), write int(x), or 300 is out of range for
int8. The test asserts the GUIDANCE, not the refusal.

And convert_struct_test.go hydrated a struct from a map with a literal float64 reaching an
int field. Its own doc comment said "an int from a JSON float64", so it encoded the
compensation #711 removed rather than a contract. Now json.Number("3").
Row 8 of the test plan was blocked on #711: print(42) did not fail, it printed "*". The
integer reached reflect.Value.Convert, where int64 counts as convertible to string and
yields the RUNE at that code point. It is now refused, and the fixture pins the exact
guidance a script author sees:

  param msg: cannot use int64 where string is wanted: write str(x) to render it

rather than the word "string", which would pass whether the message helped or not.

The bool case moved to its own fixture instead of sharing one. An integer is refused BY
RULE and a bool BY THE LANGUAGE -- Go permits no bool-to-string conversion at all. Sharing
a file hides which is which, and therefore which one a regression could silently remove.
gocyclo put losesMeaning at 17. The complexity was not in the logic but in its spelling:
`(isSignedInteger(k) || isUnsignedInteger(k))` appeared four times across two functions,
and every occurrence was a branch gocyclo had to count.

isInteger and isFloat name what those pairs meant, and the rule collapses into a switch
that states the contract directly:

  destination string   + integer source   -> refused, a rune nobody asked for
  destination integer  + float source     -> refused, fractional or not
  integer -> integer                      -> the one pair whose value decides
  float   -> float                        -> refused on overflow, not on precision

No behavior change: the 17 rows of TestNumericSemantics_MatchPython and the 4 of
TestNumericSemantics_DeliberateDeviationsFromPython are what would catch one, and both
pass unchanged. check, test-race, and test-scenario all green.
@David-Noble-at-work David-Noble-at-work self-assigned this Aug 27, 2026
@David-Noble-at-work
David-Noble-at-work merged commit a730b82 into develop Aug 27, 2026
12 checks passed
@David-Noble-at-work
David-Noble-at-work deleted the lossless-conversions branch August 27, 2026 20:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

int passed where a string is expected is silently converted to a rune: print(65) emits "A"

1 participant