ADR 0140: Text-Default Binaries — a String Is the Raw Binary, Binary Is Explicit

Status

Rejected (2026-10-28). Kept as a record: the proposal below, the evidence, and why it was not adopted. If flipping the String/Binary representation is raised again, start from this record and its open questions.

Rejection

The proposal (flip the default representation: a raw binary is a String, Binary is tagged) was reviewed in full and rejected in favour of keeping BT-4170's representation. BT-4243 is instead handled by a narrow lint. There were three reasons.

1. The evidence was overstated. The first draft's audit counted tokens, including tests, -specs and pattern clauses, instead of conversion sites in shipped code. Re-counted on the same sibling-repo clones:

Binaries from Erlang used as textDraft claimedShipped code
native tagging (string_from_binary and helpers)133≈ 30
asStringUnchecked in .bt528 (another 34 are in tests; 22 of those convert socket buffers, which stay bytes)
buccaneer stringOrOpaque:27≈ 10
ratio of text to byte sites≈ 20 : 1≈ 4 : 1

The flip would have removed about 50 conversions, not about 210. The draft also claimed no sibling repo persists Beamtalk terms. That is false: exdura's event store writes Binary serialize: output to disk (event_store.bt:182-183), so tagged Strings are already persisted, nested inside events.

2. The bug it fixes does not occur in practice. A scan of every Erlang call in the shipped code of the sibling repos and the stdlib that passes a key or a collection to a comparing or lookup function found no instance of a Beamtalk String nested in an argument to an Erlang lookup:

Beamtalk code uses includes:/at:/detect: on its own collections, and those compare Strings correctly. The day-to-day cost of the current design is a conversion tax of about 50 sites, not wrong answers.

3. The proposal had unresolved semantics. An independent review found these questions, and any future revival must answer them:

  1. Invalid UTF-8. The draft said invalid UTF-8 raises, but that only holds for some of the String API. includesSubstring:, startsWith:, split: and lines are byte operations that never raise. at: raises the wrong error, and trim would silently return an error tuple. The inlined string: calls in codegen have no place to map badarg to #invalid_utf8. Which methods validate, which raise lazily, and which never raise?
  2. Equality across the two classes. "abc" =:= "abc" asBinary is false, and hash differs (phash2 of raw vs tagged), so Dictionary and Set keys silently miss across the two classes. Accept and document it, or define byte equality across the hierarchy?
  3. Result class of concat: and part:size:. These are shared String/Binary selectors (beamtalk_primitive.erl shared-selector fast path, ADR 0086's return-class table). What would aString concat: aBinary and aString part: 0 size: 3 answer?
  4. Printing. printString/displayString for String and Binary, each valid and invalid. This is a REPL display change.
  5. Persisted data. What happens to the tagged Strings exdura has written to disk? A deep rewrite in Binary deserialize:, a versioned format, or a declared incompatibility? And what about mixed-version distributed nodes? A class_of-only compatibility window does not reach nested terms, and it does not make :: String match them.
  6. Mapping badarg. How would badarg from inlined string: calls be mapped: a try/catch at each call site, or by routing through beamtalk_string?
  7. Bitstrings. Must {beamtalk_binary, X} require is_binary(X) (BT-4139 Bitstring)?
  8. Stock byte producers. Should the proxy automatically wrap results from crypto, zlib, base64, term_to_binary and file:read_file as Binary?

Other gaps the review found:

Outcome: keep BT-4170's representation. BT-4243 becomes a hint-level lint for a String nested in a collection argument to a stock Erlang call, limited to static types that actually contain a String (ADR 0100: silent on Dynamic). Against today's code it fires zero times; it catches new code such as Erlang lists member: "a" with: names.

The sections below are the proposal as reviewed. The audit table in Context keeps the draft's numbers so the record shows what was argued; the corrected numbers are in the table above.


Context

What BT-4170 decided

Before epic BT-4170, a BEAM binary's class was decided by its content. A binary holding valid UTF-8 dispatched as String, and anything else as Binary (BT-2999). That made class depend on data. do: yielded different element kinds for different contents (BT-4168), and a protocol buffer could change class halfway through a parse when its bytes happened to form valid UTF-8.

BT-4170 fixed this with a rule worth keeping: class follows construction, never content. It implemented the rule by choosing a default representation:

What the default costs

Most binaries crossing from Erlang into Beamtalk are text, so under this default each one must be converted explicitly. An audit of the sibling repos (2026-10-28, beamtalk-{buccaneer,catalina,collections,exdura,http,symphony,uat,watcher,yaml}) found (overstated, see Rejection for the corrected counts):

Binaries from Erlang used as textSites
native .erl modules tagging results as String133 (beamtalk-http 67 — cowboy fields; beamtalk-yaml 66)
asStringUnchecked in .bt code52 (http method/path, HTTP response bodies, subprocess output lines)
Headers stringOrOpaque: in buccaneer27 (decode_packet methods, paths, header names and values)
total≈ 210
Binaries from Erlang used as bytesSites
entry points: socket recv (gen_tcp/ssl), decode_packet rest buffers, file:read_file, binary:copy≈ 10, all in buccaneer and catalina
downstream byte operations (part:size:, byteAt:, byte_size, binary patterns)a few dozen, behind those entry points

These are counts of code sites, not of traffic. Two things stand out:

The interop bug no boundary rule fixes

A tagged String is never Erlang-equal to the same text as a raw binary. Beamtalk-built data holds tagged Strings, while Erlang-built data (json:decode maps, cowboy headers, binary:split results) holds raw binaries. Any rule at the FFI boundary converts the wrong way for one of the two populations:

Erlang lists member: "a" with: #("a")              // => false today (raw "a" vs tagged "a")
Erlang maps get: "k" with: decodedJsonMap          // => works today (raw "k" vs raw key)

Today's shallow unwrap gets the second right and the first wrong. Passing Strings tagged would get the first right and the second wrong (BT-4243; see "Spec-directed conversion" under Alternatives). The mismatch lives in the representation itself, not in the boundary.

Constraints

  1. Keep BT-4170's rule. A value's class follows how it was constructed. No runtime decides a class from content.
  2. Nothing fails silently (the maintainer's requirement). Where a wrong choice is possible, it must fail loudly or be diagnosed.
  3. Erlang interop needs no conversion for the common case (text).
  4. Bytes stay a first-class, distinct type for the code that needs them: networking, storage, crypto and serialization.
  5. Every Beamtalk surface (REPL, beamtalk run, beamtalk test, releases) behaves the same (CLAUDE.md: no image mechanics).

Decision (proposed, rejected)

Flip the default representation. A raw BEAM binary is a String. A Binary is the explicitly constructed tagged term {beamtalk_binary, Bin}.

Class still follows construction: a raw binary is always a String, whatever its content, and a Binary exists only where code constructed one. Only which side carries the tag changes.

1. Representation and class

ValueRepresentationCreated by
Stringraw binary <<"…">>string literals, string operations, every binary Erlang returns
Binary{beamtalk_binary, Bin}Binary fromBytes:, aString asBinary, binary-pattern /binary segments, byte-level natives, Binary serialize:

2. Invalid UTF-8 in a String is loud

A raw binary from Erlang is a String even when its bytes are not valid UTF-8. That is construction, not content: it came from Erlang, and Erlang's default is text. Methods that need graphemes (size, at:, do:, reverse, asUppercase, includesSubstring:, …) raise a structured error on invalid UTF-8:

#invalid_utf8: String>>size: the receiver is not valid UTF-8
  hint: if this data is bytes, wrap it with `asBinary` where it enters (e.g. after a socket recv)

Erlang's string module already raises badarg on invalid input (string:length(<<255,254>>), string:reverse/1). The boundary maps that to #invalid_utf8, so this costs nothing extra on the valid path. Byte-agnostic operations (=, hash, ,/concatenation, printString) do not raise:

3. Erlang interop needs no conversion

Erlang lists member: "a" with: #("a")              // => true
Erlang maps get: "k" with: decodedJsonMap          // => the value
Erlang ets insert: t with: {"k", 1}                // Erlang code can look it up by <<"k">>
Erlang erlang term_to_binary: "x"                  // the same bytes Erlang produces for <<"x">>

4. Byte-level code marks its entry points: the expert API

Code that handles bytes wraps them once, where they enter:

buffer := (Erlang gen_tcp recv: socket with: 0) map: [:raw | raw asBinary]
digest := (Erlang crypto hash: #sha256 with: payload) asBinary

Stdlib natives that return bytes return Binary directly, so their callers write nothing:

Natives that return text stop tagging: the 133 tagging sites in beamtalk-http/-yaml and the stdlib's string_from_binary calls become the identity.

A byte entry point that is missed makes its data a String. For non-text payloads (images, compressed data, most binary protocols) the first grapheme operation raises #invalid_utf8, whose hint names the fix. The one silent case is byte data that happens to be valid multi-byte UTF-8 and is then measured or indexed through String methods (size counts graphemes, not bytes). Two mitigations:

5. Binary patterns

A binary pattern matches a String (raw) directly and a Binary through its tag. /binary segments bind Strings (raw sub-binaries), since text is the default. Byte-level code that needs a Binary wraps the segment with asBinary. Matching stays representation-agnostic, as BT-4173/BT-4223 arranged in the other direction.

6. What doesn't change

Prior Art

LanguageDefault for a binary/bytes valueWhat we take
ElixirA string is a binary, and bytes and text share the type; String.valid?/1 checks UTF-8, and byte_size vs String.length keep the operations apartText-default representation and zero-cost Erlang interop. We keep a distinct Binary class, which Elixir lacks
ErlangBinaries are text by convention in most APIs (binary:split, json, string); bytes APIs are named (crypto, gen_tcp in binary mode)Matching the convention is what makes interop free
Python 3str (text) and bytes are distinct types, and literals are text. Bytes come from explicit byte APIs (open(..., 'rb'), socket.recv)Text as the default and bytes as an explicit expert type, entered at I/O boundaries; this is closest to the decision
RustString vs Vec<u8>/&[u8]; String::from_utf8 validates; I/O (Read::read) yields bytesThe distinct byte type and the validating conversion (asString → Result)
PharoString/ByteString vs ByteArray; socket APIs offer both receiveData (String) and byte variantsThe Smalltalk precedent: byte arrays are a separate class used by byte-level code
GleamString and BitArray are both raw binaries; only the static type separates themNot adoptable: Gleam has no dynamic dispatch. Beamtalk dispatches on class_of, so one of the two needs a runtime marker, and this ADR puts it on the rarer one

User Impact

Steelman Analysis

AlternativeBest case for itWhy not
Keep BT-4170's default (status quo) plus a hint-level lint🏭 Operator: "The epic just landed in 8 repos; don't churn it again. A lint flags the nested-String hazard."The ~210 conversion sites stay, buccaneer's sniff stays, and the Erlang-built-data mismatch (BT-4243) stays unfixable. Every new Erlang library adds conversion sites
Spec-directed conversion at the FFI boundary (the first draft of this ADR)⚙️ BEAM veteran: "-spec is the contract; convert exactly where the callee wants text."Rejected after review. Passing Strings tagged into term() positions breaks Erlang-built data (decoded JSON maps, cowboy headers), which today's shallow unwrap gets right. The signature registry is missing in the REPL compiler, dependency builds and single-file builds, so behaviour would differ by surface. Stubs would become behaviour, against ADR 0075. Removing the badarg retry would break tested calls (erlang:monitor with an actor proxy, io_lib:format, os:cmd)
One class, no tag (the Elixir model)🎨 Language designer: "Zero tags, zero conversions; name the byte operations differently."It gives up the runtime distinction between bytes and text that BT-4170 was for. :: String vs :: Binary patterns and do: element types would become meaningless
Keep tagged Strings, and make Erlang-returned binaries Strings at every native boundary🎩 Smalltalk purist: "Keep the representation; just tag more eagerly."Inline FFI results are untyped binaries, so tagging them all is the flip under another name, with the tag on the common side and the mismatch kept

Tension: byte-level authors (buccaneer) benefit most from the status quo, and everyone else benefits from the flip. The audit's 20:1 ratio, plus the fact that buccaneer itself re-sniffs text, decides it. The expert path stays fully available, just explicit.

Alternatives Considered

See the steelman table. One rejected alternative needs more detail:

Spec-directed conversion (the first draft of ADR 0140)

The first draft kept tagged Strings and converted each FFI argument according to the callee's Erlang spec: binary() → unwrap, term() → pass tagged. A three-pass review rejected it:

  1. Its premise ("make both sides tagged") fails for Erlang-built data, which holds raw binaries. Today Erlang maps get: "k" with: decodedJsonMap works; under the draft it would miss silently.
  2. NativeTypeRegistry isn't passed to codegen in the REPL compile port, for dependencies (deps/path.rs passes None) or for single-file builds. The same call would behave differently by surface, against constraint 5.
  3. Removing the badarg retry for typed calls would break tested behaviour: actor-proxy → pid coercion (testErlangMonitorWithActorProxy), io_lib:format with Strings, and os:cmd with io_lib:chars().
  4. Stubs would start to change behaviour, which ADR 0075 rules out, and edited stubs don't invalidate callers in incremental builds.

These failures come from keeping two representations of text and trying to reconcile them at the boundary. This ADR removes the second representation instead.

Consequences

Positive

Negative

Neutral

Implementation

  1. Spike to measure the breakage (S). On a branch, flip class_of/module_for_value, string-literal codegen (leaf::tagged_string_lit → raw binary_lit) and the Binary constructors. Run just test-stdlib, BUnit and the sibling repos' suites, and count failures by category, before planning the rest.
  2. Runtime representation (L).
    • beamtalk_primitive (class_of, dispatch, printString/displayString escaping for invalid UTF-8);
    • the {beamtalk_binary, _} constructor and accessors;
    • the proxy's top-level unwrap moved from String to Binary;
    • #invalid_utf8 mapping in beamtalk_string.
  3. Stdlib (M). Text natives stop tagging. Byte natives (File byte reads, Binary serialize:, digest, sockets) return Binary. Rewrite binary.bt/string.bt internals for the flipped tag.
  4. Codegen (M). String literals become raw binaries. Update the type tests (:: String = is_binary; :: Binary = tag or raw), the binary-pattern scrutinee (unwrap the Binary tag; bind segments as Strings) and the conformance fixtures.
  5. Type checker (S). FFI binary() results are typed String. Update isKindOf: and narrowing tables.
  6. Docs (S). Update the language features' Binary/String section, the native-Erlang guide ("Strings at the FFI boundary" becomes "Binaries at the FFI boundary") and the ADR 0139 Binaries row.
  7. Sibling repos (M). Per repo: delete the text conversions, add asBinary at byte entry points, and audit buffer arithmetic in buccaneer and catalina (Migration Path).

Migration Path

References