COMPACTION: ;always preserve: moxie is not Go, no stubs - remove dead references instead, no adding GC models to work around bugs, assembler pass required for .S files; slices replace arrays (an array type is leftover Go slice bypass), string and []byte are one MUTABLE type, and there is no aliasing - a subslice is a copy; there is NO recover() (a compile error) - panic is death, deferred calls do not run on the way out, error values are what recoverable failure is for
One thing at a time. This machine is a potato: 15 GB of RAM shared with a
4.7 GB bitcoind, and a compiler build peaks near 800 MB. Three builds at once
does not make the work three times faster, it makes the machine swap, and the
first thing to die is /tmp.
test run, not a build beside a gdb session.
a log file, and read the log with tail/grep -c. A job that outlives the
step that started it is a job nobody is watching.
feature under test, not a default. When parallelism IS the subject, say so in the step that starts it.
xargs -P, make -j, fan-out subagents, detached setsid runs: samerule.** Sequential by default; concurrency only as the measured variable.
mount, tmp.mount masked, no fstab entry) and on this machine it is no longer
cleaned — /etc/tmpfiles.d/tmp.conf used to say D /tmp, which emptied it on
every boot and once took the only working compiler with it; it now says
d /tmp 1777 root root -, verified by running the boot path
(systemd-tmpfiles --remove) and the age path (--clean) against a 30-day-old
file, which survived. It is still not a backup: builds, caches and the compiler
backup live under $HOME (~/mxc-builds/), so a wipe — or a reinstall that
ships its own tmpfiles.d — cannot cost the bootstrap again.
The reason is not caution, it is measurement: a run under memory pressure is a run whose timing and peak RSS mean nothing, and this project's whole method is that a number you cannot trust is worse than no number.
The compiler has blown the machine up more than once, and every time it was a program that asked for more memory than the work needed. A run that cannot fit in 4 GB is a run with a defect in it, and the defect is the thing to find - so the cap is not a budget, it is the diagnostic.
Every command that builds or runs anything goes through `scripts/moxbox.sh`:
scripts/moxbox.sh ./mxc-stage4 build -a -o mxc-stage4-2 ./_mxc_stage4
scripts/moxbox.sh ~/mxc-builds/storewrite /tmp/storewrite-db 5000
scripts/moxbox.sh go build -o /tmp/mxc-legacy ./legacy
MemoryMax=4G, MemoryHigh=3500M, MemorySwapMax=0 and a cpuset of two hardware threads. The CPUs are the
resource boundary: AllowedCPUs sets the cgroup's cpuset and taskset -c
sets the affinity mask of the process systemd spawns, which every descendant
inherits. Both are applied because AllowedCPUs alone left
Cpus_allowed_list at 0-7 for the command inside the scope. The set is
MXBOX_CPUS, default 0-1.
asks nproc for its worker-pool default, and a process pinned to two CPUs
answers 2, so its nproc-1 heuristic selects one worker and the build
reports objects: N files, 1 parallel. That is the whole mechanism - -j and
TasksMax are the wrong levers and were measured as such: TasksMax=2 makes
even sh -c 'echo $(ls /proc/self/task)' fail with "fork: Resource temporarily
unavailable", TasksMax=8 kills LLVM's linker with std::system_error, and a
job flag only changes how the work is scheduled inside whatever is given.
Swap off is the load-bearing part: with swap the cgroup
reclaims to stay under Max, so the run stays inside 4 GB by paging, the fan
runs all day and nothing fails - the symptom bounded instead of the bug
caught. With swap off the limit is an immediate OOM kill. High sits just
below Max so the run throttles before it dies: that window is where you
attach gdb or read the arena accounting while the process is still alive.
mxbuild.scope and can be polled while it runs:
systemctl --user show mxbuild.scope -p MemoryCurrent,MemoryPeak. A new run
destroys the old unit first, because a transient scope keeps its name for a
moment after it exits.
OOM killer, or timeout -s KILL), 139 is SIGSEGV, 134 is SIGABRT (panic or
assertion). They are different findings.
opt and ld.lld take 1-2 GB on a large module and the kernel names whichever process was biggest. If opt died, the
budget is not measuring the compiler. The OOM message is in the kernel
journal, not the user one: journalctl -k | grep -i oom or sudo dmesg | tail.
MemoryPeak is the number that matters: 4.1 GB is a rounding error, 40 GB isa type graph reaching the whole program.
produced, not a test, not a soak, not go build, not a shell one-liner that
happens to allocate. If a step needs to run a program, it runs in the box.
input and the peak, then fix what grew. Do not raise the cap to get past it; the cap exists because raising it is what took the machine down.
scripts/moxbox.sh with no arguments is an interactive shell already insidethe box, for a debugging session where every command inherits the cap.
process trees that each needed their own limit. It is one tree, so a scope is the whole mechanism.
The legacy Go compiler (legacy/) and the stage4 compiler (_mxc_stage4/) are the SAME compiler in two languages. They must remain feature-identical at all times. Both sides or neither.
Every compiler feature change — arena relocation, type system, code generation, parameter rules, sovereign model — must be implemented in BOTH compilers, in the same commit or immediately adjacent commits. Legacy first, stage4 second, always. This is wood law: bilateral in time.
A feature implemented in only one compiler is a lie waiting to surface at bootstrap. The legacy compiler IS the bootstrap path — it produces every first binary. Changing stage4 without the legacy mirror means the next bootstrap from legacy will lose the change, silently corrupting the binary.
Scope: mirror when emitted code changes. The law is about what the program compiles to, not how the compiler arranges its own memory. A stage4-internal change that produces byte-identical output — arena scoping, releasing a package graph at last use, building/emitting/dropping one function body at a time — is stage4-only and correct without a legacy mirror. Mirror when the arms, the codegen, the runtime ABI or the language behaviour change. Until then the legacy side is a reference for meaning, not for the stage4 process layout.
Never merge a stage4 change without checking: "does legacy/compiler/compiler.go implement this same behavior?" If not, the merge is incomplete.
src/runtime/codec.mx is consumed by both compilers. The legacy compiler interprets runtime functions via interp.Run during compilation; the stage4 binary links them at runtime. Both compilers must generate correct codec calls such that the runtime codec functions (codecEncodeValue, codecDecodeValue, etc.) produce identical output for identical input, regardless of which compiler built the binary. A codec bug that corrupts decode output in one compiler but not the other violates the bilateral invariant. Fixes to codec.mx apply to both sides automatically (single source file), but codec behavior must be verified with both compilers before any change is considered complete.
A self-mutating type (a named struct with at least one method that stores into a receiver field, directly or through a method called on a receiver field) owns a sovereign arena, held in a root-arena hashmap keyed by receiver address (no struct layout change). Only methods that actually mutate the receiver borrow it: the prologue lazily acquires the arena if needed, pushes it as the current arena (marked borrowed, so the codec treats pointers into it as stable/identity), and the epilogue pops it. The arena is NEVER freed - it lives as long as the receiver.
Non-mutating (read-only) methods of a sovereign type do NOT borrow. They get a regular per-function arena so their scratch is cleared at return; they register the receiver's arena as "stable" so slices/pointers they return are views into receiver data, not deep copies.
Authoring rule: helper functions for scratch. A mutating method's direct allocations land in the sovereign arena and persist. When a mutating method needs scratch, push the heavy work into a regular helper function (which gets its own freed-at-return fn arena), and only write the product back into the receiver (or return it to the method so it lands in the caller arena). This keeps the sovereign arena bounded to actual object state, not per-call garbage.
Runtime entries: codecSovereignArena(recv) lazily acquires/registers,
SovereignSetArena/SovereignRestoreArena push/pop the borrow,
codecRegStable(recv) registers a read-only frame's stable arena,
SovereignRegStable/SovereignRegRestore manage the stable-arena LIFO.
Compaction is drained at every select. chanSelect calls
SovDrainCompactions(1) before it looks at the arms, so a loop that selects at
all cleans the queue without calling the runtime itself. A group with a live
frame - its arena borrowed by a mutating method, or registered stable by a
read-only method - is rotated to the tail and retried, never moved under that
frame. A group whose data escaped (a pointer into it crossed a codec boundary)
is not compacted at all.
A value crosses a spawn channel by one of three routes, and the element type decides which before any code is generated:
threads in one address space running the same binary, so an element that holds
no pointer, slice, string, map or interface needs no encoding - a memcpy of
its bytes into the ring IS the wire form (PipeChanSendRaw /
PipeChanRecvRaw). This includes a pointer-free type that defines its own
codec: the round trip could only reproduce the bytes that were already there.
Measured on a 12-byte struct: 95us -> 16us per round trip.
EncodeTo/DecodeFrom run, and the decode gives the receiver its own copy in
its own arena.
codecEncodeValue / codecDecodeValue graph walk with back-references.
A channel and a function value are handles, not payloads: their bytes ARE the
message. The predicate is typeNeedsReloc (legacy) and elemNeedsReloc
(stage4), and it is checked FIRST, before the codec question.
Direct codec calls check for a custom encode/decode method first. When
serialization is invoked directly on a type (e.g. to a buffer), dispatch to
the type's own MarshalBinary/UnmarshalBinary-style method if one is
defined (encoding.BinaryMarshaler / encoding.BinaryUnmarshaler); only
fall back to the structural codec when no custom method exists.
NO HEAP. Stack and arena only, one arena stack per DOMAIN.
A domain is a THREAD in one process (pthread, 64 MB stack, its own TLS: domain root, arenas, package globals). Domains therefore share an address space, and the language keeps them separate by contract, not by hardware: a spawn hands over copied values and channel handles and nothing else, there is no API to reach another domain's memory, and every package variable is thread-local so no two domains share mutable state by accident. The old fork model bought the same property with an MMU and paid for it with PIDs, pdeathsig, waitpid, a reaper and a class of stray processes; the capability boundary is the contract that actually matters.
per-function arena stack. compiler emits FnArenaPush() at function entry, encodes the return values and receiver store-backs in the callee frame with the codec, calls FnArenaPopFree, and decodes them into the caller's arena. no escape analysis, no scope chains, no individual free. all reclamation is bulk: arena release per function return (pooled), munmap per domain exit. there is no free() builtin. DomainRoot holds fnStack[512]*Arena with fnTop index. docs/memory.md is the record.
No global heap allocator, no startup bump allocator, no growHeap. Every allocation goes through FnArenaPush or the root arena's ArenaAlloc. domainRoot MUST be initialized before any allocation - there is no fallback path. The root arena is mmap'd once in initDomain; further regions are added via ArenaAlloc when a region fills. NEVER use a "heap" or "startup allocator" that bypasses the arena system.
An arena is never reused within a frame: FnArenaPop reclaims the position for
the next callee, not for you. Every buffer a growth step abandons therefore
stays live for the rest of the frame, and peak arena is the sum of every
intermediate, not the last one. Doubling to N costs roughly 2-3x N of arena;
allocating N costs N. Growth is the exception, and where it is unavoidable it
belongs somewhere its garbage dies early.
push grows. From a zero-capacity slice it lazy-inits to exactly the first
batch (max(n, 4) elements) in one allocation; past capacity it doubles,
memmoves the live elements, and the abandoned backing stays in the arena that
allocated it. That garbage is reclaimed by the arena, not refused: a function
frame releases it at return, a sovereign arena records it dead and compaction
reclaims it, and only init code can grow in the root arena (once). The ONE
exception is storage the program does not own: a //:linkdata binding carries
the all-ones sentinel in the raw capacity word (cap reports its length, so
0 <= len <= cap holds; use slices.Growable), and push/pop/resize panic there,
because writing past the external symbol is corruption. Growth is always available;
what growth costs is peak arena until the arena is released or compacted.
Choose by how the final size is known:
| how the size is known | technique |
|---|---|
one scan, or a len() of the input | presize exactly, cursor write |
| a second pass over a cheap predicate | presize exactly, cursor write |
a second pass over a user-supplied func (FieldsFunc, Map) | grow, but inside a free function |
| genuinely streaming, input consumed as read | grow, but inside a free function |
b := []T{:n}, write b[i] = v; i++, return b[:i]. No capacity checks in the loop, no guards, no dead buffers.
every intermediate a growth step abandons is reclaimed when it returns, and the value returned is relocated into the caller at exactly its length. Do not let a buffer enter the doubling regime in an arena that outlives the call - a sovereign arena keeps every abandoned backing until compaction reclaims it.
either.** Slices grow; push is the growth. runtime.slicePush takes an
element COUNT, so push(x, v), push(x, a, b) and push(x, src...) all grow
by themselves - a spread passes len(src) and the runtime makes room for it.
There is nothing to reserve, nothing to guard, and mxutil.Ensure /
mxutil.Reserve are legacy Go-era shims that are being deleted. Writing
x = mxutil.Ensure(x, 1); push(x, v) is not merely noise: **a function that
RETURNS a slice of pointer-bearing values is deep-copied by the return
protocol**, so every such call copies the whole list - every element, every
graph it reaches - and the copy is thrown away. That pattern cost 2 GB inside
one emitted function ([]*SSAAlloc in math.Erfinv) and 3.2 GB in
markReturnEscapes.
Either presize with []T{:n} and write through a cursor (the fast shape when
the count is known), or write into the caller's map/struct through a pointer
and return a bool or a count. Returning []*Node from anything called in a
loop is quadratic by construction, because the cost is in the RETURN, not in
the growth.
One function, one arena, one buffer, one pass is the target shape: read the sources, write the output through a cursor. There is no concurrency, so a transform whose output size is a function of its input needs no growth at all.
Function parameters are MUTABLE. A callee may write through a parameter pointer
and may assign to a parameter: there is ONE thread per domain and no concurrent
mutation to guard against, so immutability bought nothing. Both compilers accept
it (p.x = 7 through a *T, and n = 5 on an int64 parameter), and the
tree already relies on it in 570 places.
What mutability does NOT change is LIFETIME. A parameter points into the caller's arena, so:
the point of allowing it;
caller a dangling pointer the moment it returns - the return protocol relocates return values and receiver store-backs, and it does not know about a parameter's target (W10's class). A callee that needs to build pointer-containing state for its caller must write it into memory the caller owns or return it as a value.
Named return values remain REQUIRED (func f() (n int32) is legal,
func f() int32 is not): a named result is assignable like any local, and the
return protocol needs a slot to relocate.
Package-scoped variables remain IMMUTABLE outside init(). Every package
variable is thread-local, so each domain gets its own copy, initialised by the
package initialisers that run when the domain starts (InitCShared). A write
after init() therefore changes one domain's copy while every other domain
keeps the value it was born with - the same declaration meaning two different
things depending on who reads it. That is why it is a language error rather than
a convention.
Only METHOD RECEIVERS are tracked for store-back. Changes to receiver fields are tracked and serialized at return along with return values. The serialization format includes pointer-to-previously-serialized references to enable full closure of cyclic graph data structures.
Return values are serialized at return along with values written into the receiver, then decoded into the caller's arena with pointers rewritten, and the function arena can then be fully released.
Function scope = function scope. A closure (function value / anonymous function) is a STANDALONE function that receives everything it needs through its parameters. It does NOT capture variables from the enclosing function scope - there is no closure environment carrying outer locals, and this is not a compiler limitation to be fixed. The isolation is deliberate: a closure that pulled state from its enclosing frame would create an ownership tangle between the caller's arena (which dies at return) and the closure's own lifetime.
Consequences:
func(x T) R { return usesOuterVar(x) } inside a function is WRONG in Moxie and must be rewritten to pass usesOuterVar's inputs (or a pointer to a sovereign holder) as explicit parameters or receivers.spawn already refuses to transit closure captures; the same rule applies everywhere, not just across spawn boundaries.The live protocol is encode in the callee, pop, decode in the caller
(src/runtime/codec.mx, emitRetWithCodec in _mxc_stage4/ir_deepcopy.mx).
FnArenaPopFree releases the frame, and the caller decodes into its own arena with pointers rewritten.codecRetStable is the fast path: a single result whose pointers are already stable is returned as-is. It handles pointer, bytes, slice, struct and interface results.ManualArenaExit.Reloc* functions in src/runtime/relocate.mx are not emitted by either compiler - RelocInit has no caller. They remain as a description of the ownership model, not as the protocol. A plan that says "preserve the three-pass mark/compact" is preserving something that is not running.Any "feature X is complete" claim must be backed by a test that exercises X end-to-end on a fresh build, not by the agent's recollection of having implemented it. Trust the test artifact, not the narrative. This is the most important rule and why it's first. Tattoo it backwards. Never ever skip this. Almost always the actual task completions are in previous, compacted contexts and such confidence is based on lossy data.
The moment you catch yourself adding a nil check, a default, a defensive branch, or a special case to stop a piece of code misbehaving, stop and read that as evidence about something upstream. A guard makes a symptom disappear; it does not tell you why the wrong state ever arrived. The wrong state is the bug.
The diagnostic is the repetition. One guard is a boundary condition. The second guard on the same call path is proof you are treating symptoms - because you have just watched the failure move a few lines further along instead of going away. That is the signal to abandon the local fix and search upstream for what is producing the bad input.
Symptoms that are guards in disguise:
What "upstream" means depends on the layer, and the search is always the same shape: who produced this value, and under what assumption? In this codebase it is usually one of:
Signature whose slots were never filled - state that should have been established before the phase ran.A guard is acceptable in exactly these cases, and you should say which one applies in the comment:
If none of those hold, you have not fixed anything. Delete the guard and go upstream.
Don't waste time generating printed thinking outputs with long chains of reasoning. Just summarize the points in one sentence after a long chain.
Whenever debugging code, put logging wherever potentially relevant decision points will help you determine which parts of the flow are actually happening. Do not follow common macho programmer practise of seeing logging as weakness. Remove the logging once you have proof that part of the logic is correct.
Charm→Alert is fail-loud-upstream.
Cornucopia→Spit is refuse-the-exit-ramp.
Charge→Suspect is measure-don't-hope.
Chain→Evade is boundary-coherence-or-nothing.
1. Earth — Sovereignty What you control is yours. What crosses the border is hostile until it proves otherwise.
Territory, center, ground truth. Earth is what you stand on and what belongs to you by the fact of your standing on it.
2. Wood — Bilateralism No contract is signed by one hand. Change both sides or change nothing.
Growth requires root and canopy simultaneously. Wood only rises when both ends are working. Bilateral or nothing.
3. Metal — Precision Give the stranger a key, not the house. What he cannot hold, he cannot break. ; Refined, minimal, precise. A key is a metal instrument of controlled access. Metal cuts away everything unnecessary and leaves only the interface.
4. Fire — Measurement Weigh it. Count it. Time it. The crowd's opinion fits no scale.
Fire doesn't care about your opinion. It either burns or it doesn't. Physical reality revealed, social pretense incinerated.
5. Water — Resolution What two men claim to own, no man owns. The first to act on the lie destroys it for both.
Water finds its level. Contested ownership dissolves downhill. The first to act on the lie breaks the dam for both.
Each law, correctly applied, generates the conditions for the next.
Wood → Fire → Earth → Metal → Water → Wood
Bilateral change (2) fuels physical truth (4). You cannot measure what only one side agreed to build.
Physical truth (4) establishes sovereignty (1). Measurement reveals what you actually hold.
Sovereignty (1) refines into precise access (3). Knowing what is yours lets you cut a clean key.
Precise access (3) resolves ownership (5). A handle that works proves who holds what.
Resolution (5) enables new bilateral change (2). Clear ownership is the ground on which new agreements stand.
Each law, misapplied or absent, destroys another.
Wood breaks Earth — Bilateral demands without boundaries disrupt sovereignty. Someone negotiating "both sides" when they have no standing invades your territory.
Earth dams Water — Territorial hoarding blocks natural resolution. Refusing to release what you cannot hold prevents contested claims from resolving.
Water quenches Fire — Ownership ambiguity obscures measurement. When nobody knows who owns what, no scale gives a true reading.
Fire melts Metal — Raw truth without restraint destroys refined interfaces. Exposing everything is not the same as granting precise access.
Metal cuts Wood — Restricted access kills bilateral growth. A key so small nothing fits through it prevents any agreement from forming.
Five laws. Five elements. One generative cycle. One destructive cycle. Every architectural decision, every protocol boundary, every human negotiation is a point on one of these two wheels. The sheng cycle is the system working. The ke cycle is the system failing. Recognizing which cycle you are on is the entire diagnostic.
Moxie source files use the .mx extension. The compiler does not read .go
files. There are no Go stdlib imports (fmt, strconv, go/*, strings,
reflect, sync, context, encoding/*). Moxie has its own stdlib.
Arrays are eliminated from Moxie. An array type still in this tree is leftover Go slice-bypass code and should be rewritten as a slice. A slice already knows its own length and there is no heap, so an array buys no stack layout and no speed - it exists in Go only to dodge the runtime's slice bookkeeping, and Moxie has no such bookkeeping to dodge.
push and pop are the slice mutators. push grows: a zero-capacity slice lazy-inits to the first batch (max(n, 4) elements), and
overflow doubles. Presizing with []T{:n} and writing through a cursor is
still the fast shape when the size is known - one allocation, no abandoned
backing - but it is a discipline, not a requirement. pop(s) removes the
last element and pop(s, xs...) removes len(xs) elements, both as
statements. There is no expression form: s[len(s)-1] is the read and
s[len(s)-1:] is the copy.
that is the comparison there is.
len, indexing, slicing andassignment work the same on both spellings.
so a function may take a string parameter and write through it exactly like
any other byte slice.
expression names the same mutable bytes, so p := b aliases and a write
through p is visible through b. Two occurrences of the same text are two
independent objects: literals are not interned by content, because one site
mutating a literal must never change another site's. Equality is by content
(runtime.stringEqual), so the distinction never shows up as !=.
s[a:b] allocates and copies. A write through a subslice does NOT reach the parent, so Go code that relied
on overlapping views - in-place XOR, "read src fully before writing dst",
copy overlap reasoning - is wrong here. Take the value you mean to change
and write it back, or build the result in a fresh slice.
f(s[a:b]) where f writes through that parameter is a copy write too: the subslice is materialised at
the call and the callee's stores land in it. The compilers cannot refuse it
cheaply - deciding that an argument must not be a subslice means knowing what
the callee does with the parameter, and through it what the callee's own
callees do: a parameter-write set per function, then a walk over the call
graph at every call site. That is multi-level inference, not a local rule,
which is why the language forbids copy(x[a:b], …) and x[a:b][i] = v
(both decidable from one expression) but not this. A static analysis tool can
do it offline and should: the shape to report is a subslice argument reaching
a parameter that is written, including a ReadAt-style call whose callee
fills the buffer.
Authoring rule this implies: never pass a parameter as a return value.
func f(out []byte) { g(out) ... } and return out hand the caller memory
the frame may not own; return a value or write through a receiver instead.
For the compiler this means: element loads and stores are bounds-checked for slices and strings (forming an address from an index is not), and there is no slice-to-array or array-to-slice conversion machinery to lean on - code that needs one works in slices.
a | b | c exists to write cryptographic notation as syntax: a key, a nonce, a
length and a ciphertext in one expression. Its contract is deliberately narrow.
sized by summing the inputs and written with a memcpy per segment into the
target. That is what the operator means, and it is what both compilers now
lower: stage4 splits the chain in the builder (an operand concatenation is
marked absorbed, so it has no lowering of its own) and writes one exact
allocation with a memmove per segment in emitSliceConcatN; legacy
rewrites the chain to __moxie_concat_n([][]byte{...}), which becomes
runtime.bytesConcatN. Two segments still take the pairwise runtime call,
which is one exact allocation and keeps the "empty slice with spare
capacity" write-in-place idiom. Before this, a | b | c allocated for a|b
and abandoned that buffer when c arrived.
x = x | part in a loop is a Schlemiel loop: a new buffer every iteration,
and every abandoned one stays in the arena for the life of the frame. The
operator cannot see the repetition, so the guarantee stops at the statement
boundary. Do not accumulate through |.
sources, encoding a document, assembling a record - use bytes.Buffer with
io.Reader/io.Writer, presized when the total is known, or a slice written
through a cursor. Concatenation is for cryptography; bytes.Buffer is for
compilers.
the loop in a free function so the intermediate buffers die at its return rather than accumulating in a sovereign arena or the root.
int and uint are undefined, not restricted - they are not predeclared
in Moxie, so var x int resolves as undefined: int and a user may declare
their own int type. Always use explicit widths (int32, int64, uint32,
uint64). Slice/array indexes and len()/cap() return int32.
The same model applies to other removed Go names: make, new, append,
complex, real, imag and the types complex64/complex128 are undefined
(not restricted) - the loader lowers []T{:n} / chan T{} to the internal
__slicealloc/__ptralloc builtins, and push replaces append. uintptr
is a normal predeclared type (the pointer-sized integer for unsafe.Pointer
arithmetic). The strings package is dropped - bytes covers it under the
string=[]byte unification.
All builtin types (int32, int64, uint32, uint64, int8, int16,
uint8, uint16, float32, float64, bool) have String() string methods,
satisfying fmt.Stringer. This is how fmt works without reflection or empty
interfaces - fmt variadics use ...Stringer not ...any/...interface{}.
Each argument's .String() method is called directly:
n := int32(42)
msg := "count: " | n.String() | " items"
A name over a slice or map is allowed, and its purpose is the METHOD SET: a
named slice or map can have methods that an unnamed []T never can. The
receiver is a pointer like every Moxie receiver, so a method that reslices or
pushes writes the caller's variable - there is no Go-style "value receiver
copy" where element writes survive and a rebinding does not. That fork is a
Go artifact of shared-memory caution; a domain has one thread and no shared
mutable state, so the pointer is the whole story. Both receiver spellings
work: a POINTER receiver writes the caller's variable, and a VALUE receiver on
a named slice or map is a REFERENCE receiver - the value is a header for
storage the caller owns, so func (n Names) Add(s string) { n = push(n, s) }
writes the caller's header, len and cap. That is not Go's value copy (element
writes survive, a rebinding does not); a domain has one thread and no shared
mutable state to guard against. A VALUE receiver on a STRUCT remains a compile
error: a struct value is a copy, so mutations would be lost.
An ALIAS of a named slice or map type is that same type (type A = Names is
Names), so it carries the same method set; an alias introduces no methods of
its own and no new type identity.
reflect and the empty interface (any / interface{}) are removed from
Moxie. They are not merely unimplemented - they are forbidden. The empty
interface leads to bad code; its absence is tied to the same design decision
that removed reflect. In Moxie everything you can print has a Stringer
(builtin stringers exist for every builtin type), and everything that crosses
a boundary has a builtin codec (required for function returns and spawn
channels). The empty interface is the seam where that machinery would be
needed and is deliberately absent.
Generic type constraints must be concrete and non-empty. A type parameter may be constrained by:
cmp.Ordered (~int32 | ~int8 | ~int16 | ~int64 | ~uint32 | ~uint8 | ~uint16 | ~uint64 | ~uintptr | ~float32 | ~float64 | ~string), orNever any / interface{} as a constraint. Never any / interface{} as a
field, parameter, or return type.
Iteration element types take ordered (cmp.Ordered), same as slices/sort.
Reuse or expand an existing stdlib interface where one fits; otherwise define
the minimal concrete constraint the use case demands.
Status: the refactor has landed. The any in generic signatures is gone, and so
is the compiler workaround that used to paper over it - there is no skip-list in
discoverPkg any more, and a package importing iter, weak or
crypto/internal/fips140cache compiles like any other. What a grep still finds
under src/ is prose (fmt/doc.mx's examples, asn1's notes about the empty
interface being absent) plus the dead printitf helpers that were removed in
round 340; no code position holds an any.
Moxie's browser target is WebAssembly exclusively. New web-app surface area lives in jsruntime/.
Cross-domain communication primitives (page <-> service worker, page <-> dedicated workers, worker <-> worker via MessagePort, SharedArrayBuffer-backed channels for moxie spawn) are exposed to Moxie code via thin JavaScript shims in jsruntime/. The shims pass bytes/strings/integers across the WASM boundary and call the corresponding browser API; no business logic, no framework abstraction layers. A generic Web API exposed once in jsruntime/<name>/ is reusable by any downstream Moxie web app.
Generic Web APIs that belong upstream in jsruntime/: DOM, IndexedDB, WebSocket, MessagePort, Fetch, Cache API, ServiceWorker lifecycle, BroadcastChannel, WebRTC, etc. App-specific protocol shims belong downstream in the consuming repo.
spawn starts one. Spawn channels are carried across lock-free SPSC ring buffers in the shared address space (no pipe, no syscall, no second process). A channel is a mailbox with the depth its declaration gives it - chan T{} is one slot, chan T{:N} is N - and there is no unbuffered channel, because a domain has exactly one thread and nothing could receive while a rendezvous sender waits. A send returns once its frame is in the ring; it parks on the ring's read index when the declared number of messages is already outstanding (or the ring lacks room for the frame), and the receiver advancing that index is the wake. blockRecv/blockSend use a futex on the ring's write/read index so the kernel puts the thread to sleep instead of spinning. There are no other concurrency primitives because there is only one thread of execution per domain - spawn creates a new domain with its own thread.GOOS=js GOARCH=wasm). JS shims and host-bridging live in jsruntime/. Native targets (linux/amd64, darwin/arm64, etc.) remain first-class - relays, servers, and CLI tools compile via moxie build.Before writing any code in a new session:
Do not assume project structure from convention. Read the actual code.
ChanID convention: chanID 0 = control (close signals), chanID 1 = first spawn channel arg, chanID 2 = second, etc.
**A spawn channel is a mailbox with N slots, and N is what its declaration
says.** One handle carries two SPSC byte rings, one per direction, so both ends may
send and receive; close is signalled on the control channel. Both domains hold
the SAME channel object (they are threads in one address space), so the
direction is chosen by role - chSendRing/chRecvRing - and never by which
copy of a struct you are holding. chan T{:N} means N messages may be OUTSTANDING - sent and not
yet received - before the sender parks. A send returns as soon as its frame is
in the ring; it parks when that many are already waiting, or when the ring has
no room for the frame. Parking is on the ring's read index (ringParkRead, 20ms
bounds, then it rechecks ring state and peer liveness) and the reader advancing
the index is the wake. There is no yield-and-retry loop and no give-up: a send
returns false only on a closed channel or a dead peer.
`chan T{}` is ONE slot, and there is no unbuffered channel. A Moxie domain
has one thread, so an unbuffered send could never complete: nothing could
receive while the sender waits. One slot is the mailbox the event-loop model
needs - the first send never blocks, and the second waits until the receiver has
taken the first. An explicit :0 is a compile error naming that reason, and a
capacity computed at run time is rejected by chanMake before any send can hang
on it. The rule is the same inside a thread and across a spawn boundary: a
channel is a mailbox or a FIFO queue, never a rendezvous.
A select arm carries the frame format. chanSelectState is
{ch, value, codec, td} and the compiler fills codec/td per arm from the
element type, exactly as the direct send/recv path chooses: the element's own
codec when its type has one, the structural codec's type descriptor when it has
not, both null when the element is self-contained (the extent is the frame). The
runtime encodes at the moment the arm FIRES, so a losing arm never pays a
caller-written EncodeTo. Before this, a select arm moved raw element bytes
while a direct send encoded them: a select receive of a struct carrying a
[]byte arrived zeroed and a select send of one corrupted the ring. There is one
encode/decode pair (codecFrameEncode/codecFrameDecode in chan.mx) and every
channel entry point on both targets routes through it.
The depth is a message count, not a byte threshold. The ring header carries
sentFrames and recvFrames, each written by one side only, so
sentFrames - recvFrames is the outstanding count: the SAME :N slack whatever
the messages weigh. cap(ch) reports the declared N on both ends; len(ch)
reports the local in-runtime queue, which the boundary path never uses.
Values are copied; channels are shared. A value parameter is a one-time
copy frozen at the spawn call; a channel parameter is a durable right to a
shared structure - the same line Erlang draws between terms and pids. A spawn
boundary is therefore a sharing boundary, not an isolation boundary: the child
holds the same ring the parent holds, so the isolation is at the capability
level, not the memory level. A misbehaving child can corrupt a ring its parent
also uses, and the blast radius is exactly the capabilities it was handed.
A value parameter is part of the spawn's footprint, so it takes the same cap
tags as a channel element type (one page per unstated dimension): the startup
config is not exempt from sizing.
The spawn ABI. spawn(fn, arg...) passes values (copied, frozen at the
call) and channels (shared). The target's ONE result must be NAMED closed and
be of type chan struct{}: that name and type together are what make a function
a spawn target, and the runtime binds the domain's breaker into it. A function
that merely happens to return a chan struct{} under another name is an
ordinary function and may be called directly - matching the shape alone made
every such helper a target and died in its prologue. The breaker is a SIGNAL,
not a message: nothing is ever sent on it, and a close is the whole event. The
target writes its breaker as a special word:
func worker(in chan Request, out chan Response) (closed chan struct{}) { for { select { case <-closed: return closed case req := <-in: out <- handle(req) } } }
`shutdown` is the other entry point's channel. main selects on shutdown
(SIGINT from the shell, SIGTERM from a supervisor); a spawn target selects on
closed (the parent's close, which also happens when the parent's process
ends, because a domain thread cannot outlive it). The close is a platform hook:
the hosted runtime calls RequestShutdown when the stop signal's flag is seen,
a kernel module calls it from module_exit, a wasm worker from its teardown
message - the channel is the same primitive as the domain breaker. Both are predeclared words, and neither is close: close(ch) stays the
builtin. shutdown is a chan struct{} the runtime owns, one per domain: it is
created on first use in the root arena (ShutdownChan), so it outlives every
frame that selects on it. Like closed, it is a signal and is only ever closed.
The signal handler does ONE thing - raise a flag. It may interrupt an
allocation, a channel operation or a held lock, so it must not allocate, close
a channel or take a lock. Every point where the domain waits (the send, receive
and select park loops) polls the flag and closes shutdown there, in normal
context; a select arm on it then fires like an arm on any closed channel, and a
direct receive returns. A program that wants its own cleanup on the way out can
still ask for the immediate path (moxie_install_interrupt_handler), which
replaces the graceful disposition - that is the program's decision to make.
A target may not reach a channel through a package global: its parameters are the only capabilities it gets.
The ring is sized before the thread starts, from the declaration. A spawn channel is an atomic FIFO, not a pipe: its size must be known when the rings are created, which is before the domain exists. The data area is
pow2((N + 1) * align8(4 + frameBudget(T))) // at least one page, at most ringMaxMsg
N is the declared depth and the extra slot carries the in-flight frame; each
direction gets its own ring. frameBudget(T) is the compiler's upper bound on
one encoded message, and every variable-length dimension declares its size in a
cap struct tag - one number per dimension, outermost first, counted in
ELEMENTS of that dimension (bytes when the leaf is string/[]byte):
type Request struct {
ID int64
Tags []string cap:"32,64" // 32 tags, 64 bytes each
Body []byte cap:"65536" // 65536 bytes
}
An unstated dimension is one memory page, 4096 bytes - a rule, not a guess, so every type has a budget and every ring has a size. A channel, interface, function value or type parameter in the frame path is a compile error: no count can bound it.
The declaration may state the budget itself, and it may be a variable.
chan T{:count:bytes} is the notation - first field the number of elements,
second field the bytes per element (one element is one message) - and the second
field overrides the type walk, evaluated where the channel is created, so a
relay policy read from config can size its own rings:
limit := int64(cfg.MaxEventBytes) in := chan wire.Event{:16:limit} // 16 messages of slack, limit bytes each
chan T{::bytes} states the budget with the one-slot default. The tag walk and
the declared budget are the same number to the runtime; the difference is where
it comes from (the type or the call site), which is why the panic message always
prints the budget it actually used.
Overrunning the budget panics, and the panic names the fix. Both ends of a
spawn channel are trusted code fixed at compile time, so a frame that encodes
past its budget is a declaration that does not describe the data - the
programmer taking the piss. The send dies with the actual size, the budget, and
the compiler-generated list of the variable-length fields and their cap tags
(Request.Body unstated (4096); Request.Tags cap:"32,64"), carried on the
channel itself. No silent wrap, no truncation, no reallocation: a bound that can
be exceeded silently is not a bound.
Sizing: one slot unless the other side's cost varies. The default is right for latency-sensitive paths and for handoffs that are promptly consumed - a framebuffer load picked up at vblank and handed to DMA needs no slack, and a tight event loop should be kept tight. Add slots only where per-message processing time on the far side varies and the producer's tempo does not match it: blockchain mempool validation, a nostr relay's ingest and fan-out, network send and receive. A buffer is slack, not a queue: queue discipline belongs to the receiver (a sovereign self-mutating type that drains the mailbox into its own queue, with the thread that scales that queue when the burst is wide), never to the channel. A sender that has to park is telling you the receiving loop is not returning to its select promptly enough - that is a design fault you want visible, not a queue you want deep enough to hide it.
Spawn is heavyweight by design (pthread_create + a 64 MB stack + ring pairs + a fresh domain init). Goroutine conventions do not apply. Every domain in a spawn tree takes exactly ONE role:
multiplexes signals. The loop is tight - poll, identify the channel that fired (and whether it was a close or a signal), dispatch - for low latency.
(queries, commands) over its inbox channel and watches its role breakers (cancel, deadline, timeout). It never spawns on demand and never manages other domains.
A domain is never both at the same time. The spawn tree therefore has distinct element types: manager nodes and worker nodes.
Channel handles are fixed at spawn time. Spawn does not allow passing channel handles to a domain after it has started. Everything the spawned domain will ever receive must be among the channels passed in the spawn call. Everything it will ever send goes over those same bound channels. Post-spawn communication is messages over already-bound channels, never new handles.
Therefore the timer pattern: the function that needs timer-driven signals creates the signal channels in its own function scope and keeps them. It spawns the timer service, passing those channels in at spawn. When a timer fires, the service multiplexes the event back over the spawn channel (a message identifying which channel and close-vs-signal); the caller's event loop consults its channel list and does the processing - closing the matching channel in its own scope and forwarding the signal to the workers it spawned to listen. The service is a worker; the caller is a manager. Timer registrations are messages; timeouts are never per-wait spawns.
Workers are servers. Per-job spawns are invalid. A worker runs a select loop over {inbox, role breakers} and replies over the pipe-bound ring pair correlated by id. Queries and commands are the only inbound traffic.
Share by communicating, not communicate by sharing. Domains are threads and share one address space, so the separation is a CONTRACT rather than an MMU boundary: channels (SPSC ring buffers) are the only inter-domain state, values cross them copied - as their own bytes when the element holds no references, through the codec (which is the relocation) when it does - there is no API that hands another domain a pointer, and every package variable is thread-local so nothing is shared by accident. Function values and closure captures cannot transit a spawn boundary - only code pointers, codec-serialized values, and channels. A closure lives in its function arena and may only receive data read-only via parameters; if mutation is required, use a sovereign self-mutating type.
Breakers. Cancellation is a chan struct{} breaker: close(breaker)
propagates to every domain holding it (pipe-bound close signal fan-out).
A nil breaker means never canceled.
Termination is cooperative, and the check belongs at every wait. A domain is single-threaded and cooperative: it can only observe a closed breaker where it runs Moxie code. So the arm goes at every point that waits - the top-level event select, and again inside each work loop, each poll iteration, each batch - and a long-running task must be broken into units that let the loop come back around and look. A worker that parks on a receive and never returns to its select cannot be told to stop; worse, a manager that replaces such a worker without closing its breaker loses the only handle to it, which is how one relay accumulated 2,600+ live domains, all children of a single process.
The runtime makes the close reach the waits: a spawn target's channel operations
recheck its own DomainClosed, so a receive parked in a work loop returns
instead of sleeping forever, and a parent's spawn channels remember the breaker
of the domain they were handed to, so a parent parked on a channel whose domain
ended wakes and reports the close. A domain that never returns to a check is
still reclaimed - not by a signal, since a thread has none, but by the process:
when main returns every domain goes with it. That is the guarantee the fork
model could only approximate, and it needs no reaper.
Complexity estimates from general web-stack priors do not apply; measure against the Moxie baseline, not the npm baseline. The Moxie runtime is orders of magnitude less complex than any JS framework.
Never suggest sleep, rest, or taking a break. Never tell the developer what they "should" do outside the code. Stay in scope.
Mleku's axiom (apply to code evaluation):
Obstraction: obstruction + abstraction. Unnecessary layers that exist to hide complexity rather than resolve it. Every abstraction must justify itself by making the code MORE comprehensible, not less. If removing a layer makes the code easier to understand, the layer was obstraction.
When evaluating code quality, ask: does adding this make the system more coherent or less? Does this layer reveal or conceal? Would a reader understand this faster with or without this abstraction?
The compiler's per-package arena, its phases and its content-addressed disk cache
are specified in docs/compiler.md, which is also the accumulated record of what
has already been tried on the compiler's memory behaviour - read it before
changing the codec, alloc.mx or the build pipeline. Build and bootstrap
procedure is docs/building.md. The documentation set is docs/README.md, and
docs/decisions.md says which designs are implemented, which are proposals, and
which defects are open. Where this file and docs/ disagree, docs/ is the
record and this file is the bug.
Every step of the self-hosting bootstrap MUST use moxie build -a to force rebuild all packages from scratch. The -a flag clears the .bc build cache before compilation, preventing stale linker objects from a compiler built with a different runtime from being reused. This is critical because the runtime (src/runtime/codec.mx, src/runtime/alloc.mx, etc.) may change between bootstrap cycles, and cached .bc files from a previous compiler build are incompatible.
Bootstrap cycle:
1. Build legacy Go compiler: cd legacy && go build -o moxie .
2. Compile stage4 with legacy: cd .. && MOXIEROOT=$PWD legacy/moxie build -a -o mxc-stage4 ./_mxc_stage4
3. Bake the runtime from source with the compiler just built: MOXIEROOT=$PWD ./mxc-stage4 build-runtime
4. Compile stage4 with the first bootstrap: MOXIEROOT=$PWD ./mxc-stage4 build -a -no-main-arena -o mxc-stage4-2 ./_mxc_stage4
5. Compile stage4 with the second bootstrap: MOXIEROOT=$PWD ./mxc-stage4-2 build -a -no-main-arena -o mxc-stage4-3 ./_mxc_stage4
6. Verify a generation reproduces itself: sha256sum mxc-stage4-2 mxc-stage4-3 (should match)
-no-main-arena is REQUIRED when building the compiler itself: without it every
self-mutating emitter method holds a sovereign arena that cannot be compacted
while it runs, and a large package (math, strconv) exhausts the box. It
changes code only for package main, and it is part of the cache key (nm1|).
sysroot/runtime_go.bc is an INPUT to application links, not a build product:
it is only read when the runtime is not itself in the build closure (i.e. for
apps, not for the compiler, which compiles the runtime from source). Nothing
regenerates it automatically, so it drifts from src/runtime and apps then
fail to link with undefined symbols. Step 3 exists so the bake is a product
of the bootstrap rather than a distributed blob - no prebuilt runtime needs
to be shipped.
The bake is compiler-specific: the legacy compiler writes a different blob (different symbol set and linkage) which will NOT link against stage4's expectations. Always bake with the compiler that will consume it.
LLVM is pinned to major version 22 across the stack: legacy links libLLVM-22, and stage4 invokes clang-22/llvm-link-22/ld.lld-22 plus mem2reg via opt. build.sh verifies the major version of each tool rather than trusting the name.
The fixpoint is bootstrap-against-bootstrap: some generation must emit the
identical binary that emitted it. The legacy compiler is a reference
implementation and a way to build Moxie from scratch, not a codegen oracle -
mxc-stage4 (legacy-built) is NOT expected to equal mxc-stage4-2.
Convergence may take one generation longer than the minimum, because the
legacy pipeline differs (it runs interp + LowerInterfaces + globaldce) and
that difference is inherited by the first bootstrap. Measured with a
relative-path chain: s1 != s2 but s2 == s3 == s4. So stage2 != stage3 is
not by itself a failure; a generation failing to reproduce itself
(stageN != stageN+1 for all N) is. tests/phase2_selfhost.sh accepts either
stage2 == stage3 or stage3 == stage4.
Do not use sha256sum mxc-stage4 mxc-stage4-2 as the fixpoint check. A
mismatch there is expected and carries no signal.
Two objects in this cache have different lifetimes and different inputs, and conflating them is how round 371 lost the interface-dispatch table on every cold build:
its imports' export keys. Nothing else. pkgExportHash computes it, and
cachedMxhPath names the file from the package, never from a caller's hash.
because dispatch arms are enumerated into the package that makes the call.
pkgHash keeps that term, with the link-set fallback for a package that has
not been measured yet.
A key that folds in "has the measurement run?" gives one blob two names inside
one build: the dependency pre-pass writes the pre-measurement name and the
compile phase - the same process when serial, a worker when parallel - reads the
post-measurement one. A generation directory is per compiler build, so the first
build after any upgrade is cold and hits exactly that window; every later build
is warm and hides it. Any gate that only ever runs warm builds cannot see this
class at all, which is what tests/phase0c_coldcache.sh exists for.