Web target, plan 5a: the store, queries, spawn and destroy, batches
This plan builds the first of slice 5's three plans. The page gets manifoldx's entity store: the export writes it as ecs.bin, frame code reads and writes component arrays through queries with numpy expressions, spawns from a geometry library and destroys, moves single entities through their handles, and three.js draws one instanced mesh per geometry and material. On the desktop, a query starts returning only the entities that have its components. It ends with examples/web_crowd.py replaying with no mismatch in Node and in Chromium, and one draw call per batch.
examples/web_crowd.py with manifoldx export --web: Space spawns a ring of boxes, a query system drifts them, boxes that fall below y = -10 are destroyed, a click picks the box under the crosshair and paints it gold. The Python replay, the Node replay and the Chromium replay trace the same store frame by frame, and the page draws one call per (geometry, material) batch.
architecturePython writes the store's arrays below the high-water mark into ecs.bin, its layouts into state.json, and under --web a glb that is a library of geometries and materials by id with no entity nodes. manifoldx.js holds a Store of typed arrays with the desktop's slot rules and command flush, and the Query, accessor, field view and entity handle objects the transpiled code calls. pyrt.js gains NdArray and $rt.nd, numpy's element-wise rules on typed arrays. types.py and transpile.py type and emit queries, fields, arrays, component constructors, spawn and destroy. scene.js keeps one InstancedMesh per batch, rebuilt when the store's version moves.
techPython 3.13 and numpy 2; plain ES modules; Node 20+ for node --test and the replay; three.js 0.186.1 as vendored; Playwright with Chromium in the existing browser CI job on lavapipe.
spec.knowledge/analysis/2026-11-07-web-target-slice5-design.html (approved; sections 05, 10 to 13, Q3 and Q8 of section 16)
builds onplan 1, plan 2 and plan 3, all on main. This plan's branch is feat/web-target-5a; its PR targets main. Plans 5b (events and widgets) and 5c (skinned entities and the second consumer) follow it.
code it changessrc/manifoldx/ecs.py, src/manifoldx/gltf/engine_export.py, src/manifoldx/gltf/writer.py, src/manifoldx/web/: snapshot.py, export.py, reach.py, types.py, transpile.py, replay.py, and in js/: pyrt.js, manifoldx.js, scene.js, browser.js, replay.mjs. New: examples/web_crowd.py, benchmarks/suites/web.py.
Done when
The spec's criterion for 5a, as tests
examples/web_crowd.py (boxes spawned by a key, drifting by a query system, destroyed when they fall, picked and highlighted) replays with no mismatch: compare(replay_python(...), replay_node(...)) is None in tests/web/test_web_crowd.py, and the Chromium trace of the same script compares None against Python in tests/web/browser/test_web_crowd_page.py. In that page, renderer.info.render.calls for a frame equals the number of non-empty batches. The breaking tests of task 11 each make compare fail. CI's test and browser jobs are green.
Global constraints
- Functional parity (spec section 02): every runtime feature the page gains behaves as the desktop's. Where the desktop lacks a form the page needs, it lands on the desktop first, in the same task, with a desktop test.
- No app JavaScript: nothing here asks an app author to write JS.
- Same slots, same order: the page's
spawnpicks slots asEntityStore.spawndoes (src/manifoldx/ecs.py:68-79), itsdestroydedupes and skips dead slots asEntityStore.destroydoes (:111-121). - Writes land when the desktop lands them: query writes and
destroyqueue and apply at the flush after every system;spawn, handle writes andset_materialare immediate (Engine._draw_frame,src/manifoldx/engine.py:1202-1259). - Each numpy operation writes a new typed array of the result's dtype, rounding as numpy does; no fusion (spec section 15).
manifoldx.jsandpyrt.jsimport neither three.js nor a DOM name, so the Node replay keeps working.export_gltffor other tools keeps its nodes:tests/test_gltf_engine.py,tests/test_gltf_scene.pyandtests/test_gltf_writer.pypass unchanged.- An export error names the Python file and line, and what to write instead where one form exists, as the subset's errors do today.
- Node and Playwright are test dependencies only; tests skip with
node not found,playwright not installedorchromium not installed, and the browser job fails on any skip. - Shared host: each task's verify runs only the tests covering it.
make testand the browser job run in CI. - manifoldx is public: no consumer's repository, people, places, domains or machines in code, tests, commits or PR text. Say "the second consumer", "a third consumer".
- Commits are conventional and end with the co-author line; stage files by name; scratch goes under pytest's
tmp_pathor the system temp dir, never in the repo.
Review focus
- A slot freed and refilled in the same frame (a box destroyed by the fall system while Space spawns): the destroy lands at the flush, so the spawn takes a fresh slot this frame and the freed slot only on a later spawn, in the desktop's order (free list from its end, reversed). test in task 4 (the seeded sequence) and task 11 (the script)
- A query naming a component no entity has, or one registered after the export:
len(q)is 0, a field reads as a(0, c)array, and a write queues nothing that changes the store; an unregistered name matches nothing rather than raising. tests in tasks 1 and 7 - Spawning past the capacity the page loaded (the export had 6 entities, the app spawns 500): the page's arrays grow by doubling, keep every row and membership bit, and past
max_entitiesthrow the desktop's message word for word. test in task 4 - A batch that empties (the last gold box falls, or
set_materialmoves the only member out): itsInstancedMeshdraws nothing (count0, not drawn), and a later member reuses it; no stale instance is left at its old matrix. test in task 10 - NaN or infinity in a component row (a division by a zero velocity):
ecs.bincarries the bits, and both traces write the value as"nan","inf"or"-inf", so JSON (which has no NaN) does not turn it intonullon one side only. test in task 4
File structure
| file | responsibility |
|---|---|
| src/manifoldx/ecs.py | EntityStore._members and the filtering query (task 1); _FieldView[:, j], a column view (task 7) |
| src/manifoldx/web/snapshot.py | ecs_bytes(engine) -> (header, bytes); the {"__geometry": id} value form; origin in the engine dict; components on system roots |
| src/manifoldx/web/export.py | Built.ecs, ecs.bin in write_version, the glb in library mode |
| src/manifoldx/gltf/engine_export.py, writer.py | export_engine(..., library=False); build_glb(..., geometries=None) and mx_geometries in the scene's extras |
| src/manifoldx/web/js/manifoldx.js | Store, traceStore, Query, Accessor, FieldView, EntityHandle, engine.spawn, engine.destroy, the flush in step |
| src/manifoldx/web/js/pyrt.js | NdArray and $rt.nd; $rt.component(name, values) |
| src/manifoldx/web/types.py | the kinds nd, query, accessor, field, component; GEOMETRY; the surface of handles, spawn, destroy, camera.up |
| src/manifoldx/web/transpile.py | array expressions to $rt.nd.*; query field reads and queued writes; component constructors; spawn's n= |
| src/manifoldx/web/reach.py | a system's query is allowed; Root.components; component classes are not app classes |
| src/manifoldx/web/replay.py | store_trace(store); the flush after the systems |
| src/manifoldx/web/js/scene.js | the geometry library, one InstancedMesh per batch, materialOf from the store |
| src/manifoldx/web/js/browser.js, replay.mjs | ecs.bin loaded; __mx.renderer; per-frame timings for the bench |
| examples/web_crowd.py | the public example the done criterion replays |
| tests/test_ecs.py | membership and the column view on the desktop |
| tests/web/test_ecs_snapshot.py, test_store.py, test_ndarray.py, test_queries.py, test_spawn.py, test_handles.py, test_web_crowd.py | Python tests, most through Node (run_both, replay_node) |
| tests/web/apps/drift.py, spawner.py, handles.py | small test apps for tasks 7 to 9 |
| tests/web/js/scene.test.mjs | the batches, in Node |
| tests/web/browser/test_web_crowd_page.py | Chromium: the replay, draw calls, materials read from the batch |
| benchmarks/suites/web.py | the web-crowd case |
Tasks
1Desktop: a query returns only the entities with its components (changes behaviour)ecs.py · tests/test_ecs.py · CHANGELOG.md
This task changes the desktop's behaviour, as the maintainer settled in Q3: today EntityStore.get_component_view returns every alive entity whatever the query (src/manifoldx/ecs.py:123-127). An app whose query names a component some entities lack writes those entities' rows today and skips them after this task, and its len(q) changes. It goes first so every later task builds on the fixed rule.
interfaces
EntityStore as it is · produces EntityStore._members: dict[str, np.ndarray], a bool array of max_entities per registered component, allocated by register_component; spawn(n, **component_data) sets the bit of every given component and of Transform when registered, and clears every other component's bit at the slots it fills; get_component_view(names) returns the alive entities whose bit is set for every name, ascending; a name that is not registered matches nothing; names == [] keeps returning every alive entity- Write the failing tests in
tests/test_ecs.py. They describe the new rule; today the first fails with 5 entities instead of 3, which is the old behaviour written down first: - Run
uv run pytest tests/test_ecs.py -q: the five new tests fail (the second, third and fourth on a missing_membersor on lengths). - Implement in
src/manifoldx/ecs.py.register_componentaddsself._members[name] = np.zeros(self.max_entities, bool).spawn, after it picksindices: for every registered name,self._members[name][indices] = name in component_data or name == "Transform".get_component_view: start fromself._alive.copy(), and for each name AND its member array, or return an empty view when the name is not registered; the indices arenp.flatnonzero(mask)(int64, ascending, asnp.wheregave). Update the docstring ofget_component_viewto say what it now does. - Run
uv run pytest tests/test_ecs.py tests/test_systems.py tests/test_commands.py tests/test_command_queueing.py tests/test_engine.py -q: all pass. A test of these that relied on the old rule is a finding: report it in the commit body and fix the test only when the test, not the rule, is wrong. - Find which examples and demos relied on the old rule. Save this script outside the repo (the system temp dir) and run it from the worktree, once on
mainand once on this branch, withnice; it fires each app's startup on a headless device (lavapipe is enough) and prints, per system, how many entities its query sees: Diff the two outputs. Every line whose count changed is an app that relied on the old rule: check that its system still does what it should (most name onlyTransform, which every entity has). Fix an app only if it breaks, in this task, and list the diff in the commit body. - Add to
CHANGELOG.mdunder[Unreleased],### Changed:A system's query returns only the alive entities that have every component it names, as its docstring said; before, it returned every alive entity. An app whose query names a component some entities lack no longer writes their rows, and len(query) counts only the matching entities (#140). - Commit:
fix(ecs): a query returns only the entities that have its components (#140).
uv run pytest tests/test_ecs.py tests/test_systems.py tests/test_commands.py tests/test_command_queueing.py tests/test_engine.py -q: all pass, the five new tests included. The audit's diff is in the commit body. Revert the get_component_view change once: test_a_query_returns_only_entities_with_all_its_components fails.
2The store crosses: ecs.bin, layouts, geometry values, the originweb/snapshot.py · web/export.py · web/types.py · tests/web/test_ecs_snapshot.py
interfaces
EntityStore._members (task 1), _Writer.value (src/manifoldx/web/snapshot.py:156), build_export and write_version (src/manifoldx/web/export.py:66, :178) · produces ecs_bytes(engine) -> tuple[dict, bytes] in snapshot.py; state.json gains "ecs": {"max_entities", "high_water", "free": [int], "alive": [offset, nbytes], "components": [{"name", "dtype": "f4"|"u4", "cols", "fields": {field: [col, size]}, "rows": [offset, nbytes], "members": [offset, nbytes]}]}; Built.ecs: bytes, written as ecs.bin by write_version beside state.json; the engine dict gains "origin": [x, z]; the value form {"__geometry": id}; GEOMETRY = obj("manifoldx.Geometry") in types.py, which LiveTypes.of gives a geometry- Write the failing tests in
tests/web/test_ecs_snapshot.py, on an app written intotmp_paththat spawns a ground (Mesh, Material, Transform), three boxes with aVelocity(Component)ofv: Vector3, destroys one at setup withengine.store.destroy, and holds a geometry no entity uses in a module globalCRATEthat a system reads: - Run
uv run pytest tests/web/test_ecs_snapshot.py -q: fails (noecskey, noecs.bin). - Implement
ecs_bytes. Layout ofecs.bin: the alive mask as uint8 for slots[0, high_water), then per registered component, in the store's registration order, its rows[0, high_water)row-major little-endian in its dtype, then its member bits as uint8; every block starts on a multiple of 4 (zero padding).fields: Transform's from its columns with both spellings, Meshgeometry_id, Materialmaterial_id, aComponentsubclass's_layout(src/manifoldx/components.py:94-100), an@engine.componentclass's_component_start_idx(src/manifoldx/ecs.py:603-609); a dtype other than float32 or uint32 raisesSnapshotError(f"the component {name}", f"dtype {dtype}; ecs.bin carries float32 and uint32 and it")so the message reads as the test says.snapshot()puts the header under"ecs"andbuild_exportkeeps the bytes inBuilt.ecs. - In
_Writer.value, before the dict branch: a value whoseidis inengine._geometry_registry._object_to_id, a dict with a 2-d"positions"array, or an object withto_geometrybecomes{"__geometry": engine._geometry_registry.register(v)}, so the library glb (task 3) writes it. InLiveTypes.of, the same values type asGEOMETRY. The engine dict gains"origin": [float(x), float(z)]fromengine._origin. - In
manifoldx.js'sload, a{"__geometry": id}value resolves throughresolve("geometry", id), which returns one frozen{geometry_id: id}per id. - Run
uv run pytest tests/web/test_ecs_snapshot.py tests/web/test_snapshot.py tests/web/test_build_export.py -q: all pass. - Commit:
feat(web): the entity store crosses to the page as ecs.bin.
uv run pytest tests/web/test_ecs_snapshot.py tests/web/test_snapshot.py tests/web/test_build_export.py -q: all pass, the four new tests included.
3Under --web the glb is a library of geometries and materialsgltf/engine_export.py · gltf/writer.py · web/export.py · tests/test_gltf_library.py
interfaces
export_engine (src/manifoldx/gltf/engine_export.py:110), build_glb and _Writer (src/manifoldx/gltf/writer.py:25), the geometries task 2 registers · produces export_engine(engine, path, *, ..., library=False); build_glb(nodes, *, ..., geometries=None), geometries being [(id, geometry)] written once each as a glTF mesh with one primitive, no material and no node, mapped in the scene's extras as "mx_geometries": {str(id): mesh index}; every glTF material carries "extras": {"mx": {"vertex_colors": bool}}; build_export calls export_engine(..., library=True)- Write the failing tests in
tests/test_gltf_library.py, reading the glb withtests/gltf_helpers.py'sloadandaccessor, on a headless engine with a ground and two boxes sharing a cube, a sphere geometry registered but drawn by no entity, two phong materials and oneStandardMaterialwithvertex_colors=Trueon a geometry with colours: - Run
uv run pytest tests/test_gltf_library.py -q: fails on the unknownlibraryargument. - Implement.
_Writer.library(id, geometry)writes the accessors withCOLOR_0whenever the geometry hascolors(_Writer.geometrywithcolors=True), adds a mesh, and records the id;_materialsetsout["extras"] = {"mx": {"vertex_colors": bool(getattr(mat, "vertex_colors", False)) and getattr(mat, "albedo_map", None) is None}}, the rulenode()uses today (writer.py:148-149).export_engine(..., library=True)passes no nodes andgeometries=every(id, geo)ofengine._geometry_registry._geometriesexcept the named built-ins (reg._name_to_id: the sprite quad and axis lines are not meshes), still writes lights, environment, scene extras and every material, and keepscode_report. An entity drawn without a mesh (point cloud, label, volume) is still reported as dropped, asnodes()reports it today; move that check into a helper both paths call.build_exportpasseslibrary=True. - Run
uv run pytest tests/test_gltf_library.py tests/test_gltf_engine.py tests/test_gltf_scene.py tests/test_gltf_writer.py -q: all pass. - Commit:
feat(gltf): a library mode that writes geometries and materials by id.
uv run pytest tests/test_gltf_library.py tests/test_gltf_engine.py tests/test_gltf_scene.py tests/test_gltf_writer.py -q: all pass; git diff main -- tests/test_gltf_engine.py tests/test_gltf_scene.py tests/test_gltf_writer.py is empty. The page does not read the library until task 10, so tests/web/browser is not run here.
4The page's Store, its flush, and the store in the tracejs/manifoldx.js · js/replay.mjs · js/browser.js · web/replay.py · tests/web/test_store.py
interfaces
"ecs" header and ecs.bin (task 2) · produces JS class Store: static load(header, buffer: ArrayBuffer) -> Store; maxEntities, highWater, capacity, alive: Uint8Array, free: number[], version: number (bumped by spawn, destroy and any write to Mesh or Material), dirty: [lo, hi] | null (the slots whose Transform rows changed since takeDirty()); layout(name) -> {dtype, cols, fields} | undefined; column(name) -> Float32Array | Uint32Array; member(name) -> Uint8Array; spawn(n, rows: Map<string, TypedArray>) -> Int32Array (each array n × cols); destroy(indices), immediate; query(names) -> Int32Array; write(name, index, col, values), immediate; queueUpdate(name, indices, colStart, colEnd, data: Float32Array); queueDestroy(indices); flush(); takeDirty() · traceStore(store) -> {alive, free, high_water, rows} · loadApp(state, modules, {ecs, ...}) sets engine.store; step(app, dt) ends with engine.store.flush() · Python replay.store_trace(store) -> dict, the same form; replay_python flushes engine.commands after the systems and both traces gain "store"- Write the failing tests in
tests/web/test_store.py. A helperrun_store_ops(ops, max_entities)runs a list of operations in Node againstStore(an empty store with Transform and Velocity layouts, built withStore.loadfrom a header ofhigh_water0) and returns the state after each; the same ops run on anEntityStore: Every index is belowmax_entities, as on the desktop. In Node an index at or past the page's current capacity is a dead slot and is skipped, as the desktop skips a dead one. - Run
uv run pytest tests/web/test_store.py -q: fails,Storeis not exported. - Implement
Storeinmanifoldx.js.spawn:k = min(n, free.length), reused are the lastkoffreereversed, then the lowest dead slots not among them, growing the arrays first when the fresh slots reachcapacity(double, at mostmaxEntities, copying rows and member bits); when fewer thanndead slots exist withinmaxEntities, throwRuntimeError's message above as anError(the runtime's Python-exception mapping, asraises.py's test shows). Member bits: set for each name inrowsand for Transform, cleared for the others.destroy: sort and dedupe, keep alive ones, clearalive, push tofreeascending.query: the alive slots belowhighWaterwhose bit is set for every name, ascending; an unknown name gives an emptyInt32Array.flushapplies the queue in order, an update writingdatainto columns[colStart, colEnd)of each index's row (cast by the column's typed array), then clears it. Digest past 1,000 alive entities: the alive rows of a component, row-major, viewed as uint32 wordsw[i];d = Σ w[i]·(i+1) mod 2^32(JS:(d + Math.imul(w, i + 1)) >>> 0; numpy: uint64 products masked to 32 bits, summed, mod 2^32). - Wire it:
loadAppbuildsengine.store = Store.load(state.ecs, options.ecs);replay.mjs'sloadreadsecs.binwithreadFileSyncand passes its buffer;browser.js'sloadVersionfetches${base}ecs.binas anArrayBuffer;traceEntryaddsstore: traceStore(engine.store);stepcallsengine.store.flush()after the systems. Inreplay.py,replay_pythoncallsengine.commands.execute(engine.store); engine.commands.clear()afterrun_all, as_draw_framedoes (src/manifoldx/engine.py:1252-1253), and adds"store": store_trace(engine.store). Update the replay docstring's trace form. - Run
uv run pytest tests/web/test_store.py tests/web/test_replay.py tests/web/test_frames.py -q: all pass; web_walk's replay now compares the store too. - Break it once: make
spawntake the free list from its start;test_the_page_picks_slots_as_the_desktopfails. Restore it. - Commit:
feat(web): the page's entity store, its flush, and the store in the trace.
uv run pytest tests/web/test_store.py tests/web/test_replay.py tests/web/test_frames.py -q: all pass. node out/replay.mjs on a fresh export --web examples/web_walk.py out/ still prints its roots and state.
5Arrays I: NdArray, constructors, element-wise operators, numpy 2's dtypesweb/types.py · web/transpile.py · js/pyrt.js · tests/web/test_ndarray.py
interfaces
Ty, arith_dtype, TypeEnv.binop and lib_call (src/manifoldx/web/types.py:43, :190, :1012, :837), _Module.e_BinOp, e_UnaryOp, compare, lib_call (src/manifoldx/web/transpile.py:891, :960, :983, :1188) · produces Ty gains rank: int | None = None; nd(dtype, rank) -> Ty, kind "nd", dtype among "f32" "f64" "bool" "i32"; nd_dtype(op, a, b) -> str | None, numpy 2's promotion · pyrt: class NdArray {data, shape, dtype}, C-contiguous; $rt.nd.asnd(x) (a Float32Array or Float64Array, the existing vec, as rank 1); $rt.nd.add sub mul div pow neg abs lt le gt ge eq ne and or not; $rt.nd.zeros ones full (shape, dtype), $rt.nd.arange(start, stop, step, dtype); $rt.nd.tolist(a); NdArray.prototype.toJSON for the trace- Write the failing parity tests in
tests/web/test_ndarray.py, astests/web/test_numpy.pydoes, each amain()returning plain values through.tolist(), compared bit for bit: - Run
uv run pytest tests/web/test_ndarray.py -q: fails at transpiling. - Types:
np.zeros,np.onesandnp.fullwith a tuple shape type asnd(dtype, len(shape)), with an int shape stayvecwhen the dtype is a float (today's form) and arend(dtype, 1)forboolandint32;np.arangewith adtypeargument isnd.TypeEnv.binop: anndon either side with annd, avecor a number givesnd(nd_dtype(...), max rank); comparisons givend("bool", rank);& | ~only on bool.nd_dtypefollows numpy 2: f32 with f32 or a Python number is f32; f64 anywhere is f64; i32 with a Python int is i32, with a Python float, with f32 or with/is f64; bool in arithmetic fails the export. - Transpile: every operator on an
ndbecomes$rt.nd.<op>(a, b);abs(a)becomes$rt.nd.abs(a);a.tolist()becomes$rt.nd.tolist(a).**with a constant exponent of 2, 0.5 or -1 becomesmul(a, a),$rt.nd.sqrtordiv(1, a)in the result's dtype; any other exponent fails with the message above. - Runtime: each operation allocates the result's typed array (
Float32Arrayfor f32, so every element rounds), broadcasting a scalar, a trailing row and equal shapes, else throwing the message above. Pythonintscalars againsti32wrap to int32 as numpy does (| 0). - Run the same command: all pass. Then run
uv run pytest tests/web/test_numpy.py -q: the existingveccases still pass. - Commit:
feat(web): numpy arrays of any rank in frame code, element-wise.
uv run pytest tests/web/test_ndarray.py tests/web/test_numpy.py tests/web/test_types.py -q: all pass, the breaking test included.
6Arrays II: functions, reductions, stacking, indexing copiesweb/types.py · web/transpile.py · js/pyrt.js · tests/web/test_ndarray.py
interfaces
nd and $rt.nd · produces $rt.nd.sin cos sqrt exp floor clip minimum maximum; $rt.nd.where(cond) (a tuple of index arrays, as numpy) and $rt.nd.where(cond, x, y); $rt.nd.norm(a, axis); $rt.nd.sum mean min max(a, axis) with axis null, 0 or 1; $rt.nd.argmin argmax(a); $rt.nd.stack(list, axis), $rt.nd.column_stack(list); $rt.nd.getitem(a, key) for an int, [:, j], a bool mask or an index array, each a copy; len(a), a.shape, float(a[i]), int(...)- Add the failing parity cases to
tests/web/test_ndarray.py: each function on float64 and float32 arrays of shape(k, 3)withkin 1, 7, 9 and 300 (below, inside and past numpy's pairwise blocks of 8 and 128);np.linalg.norm(a, axis=1);np.sum,np.mean,np.min,np.maxwithaxis=None,0and1;np.where(m)andnp.where(m, a, np.inf);np.clip(a, -1.0, 1.0);np.stack([x, y, z], axis=1)andnp.column_stack;np.argminwith a tie (numpy takes the first) and with a NaN (numpy takes the NaN's index);a[2],a[:, 1],a[a[:, 1] > 0.5],a[np.array([2, 0])]. Plus: - Run
uv run pytest tests/web/test_ndarray.py -q: the new cases fail. - Implement. Reductions follow numpy's order so float32 sums round alike:
axis=1on a(k, c)array sums each row left to right;axis=0adds row after row;axis=Noneuses numpy's pairwise sum over the flat array (numpy/_core/src/umath/loops_utils.h.src,pairwise_sum): fewer than 8 elements left to right, up to 128 with eight accumulators combined as((r0+r1)+(r2+r3))+((r4+r5)+(r6+r7))and the rest added left to right, above 128 split atn / 2rounded down to a multiple of 8 and recurse; every addition rounds to the dtype.meanis that sum divided by the count.norm(a, axis=1)issqrt(sum(a * a, axis=1))with those roundings.minandmaxpropagate NaN.sin cos expon f32 compute in float64 and round; on f64 they areMath.sin, as today's scalar math is. Thewherechoose form follows task 5's dtype rules (a Pythonnp.infkeeps f32). Indexing returns new arrays;a[i]of a rank-1 array is a number (anumwith the array's dtype). ASubscriptstore on anndfails with the message above. The.sum(),.min(),.max(),.mean()method forms fail naming thenp.function. - Run the same command: all pass. Write the transcendental count into this plan's departures section.
- Commit:
feat(web): numpy functions, reductions and indexing in frame code.
uv run pytest tests/web/test_ndarray.py tests/web/test_numpy.py -q: all pass; change the pairwise block size from 8 to 4 once and the k = 9 float32 sum differs.
7Queries in systems: accessors, field views, queued writesecs.py · web/reach.py · web/types.py · web/transpile.py · web/snapshot.py · js/manifoldx.js · tests/web/test_queries.py · tests/web/apps/drift.py
interfaces
Store (task 4), nd (tasks 5, 6), System.component_names (src/manifoldx/systems.py:16), Reach._query (src/manifoldx/web/reach.py:367) · produces desktop: _FieldView.__getitem__((slice(None), j)), a one-column field view, so q[Transform].pos[:, 1] < -10.0 gives entity indices · Root.components: tuple[str, ...] from the live system; state.json roots gain "components" · types: query(components), accessor(component), field(component, name, start, size); the first parameter of a system root types as its query · JS: class Query (get(name) -> Accessor, length, iteration over indices), class Accessor (field(name) -> FieldView), class FieldView (data -> NdArray f32 (k, size), col(j), add sub mul div radd rsub rtruediv returning f32 NdArray, lt le gt ge returning the entity indices as an i32 NdArray, set(v), iadd isub imul, which queue); step passes new Query(store, r.components, engine) to each system- Desktop first. Write
test_a_column_of_a_field_compares_to_entity_indicesintests/test_ecs.py: three entities at y = 0, -20 and 5, the second not first in the store; inside a system,q[Transform].pos[:, 1] < -10.0equalsnp.array([that index]), andq[Transform].pos[:, 1].datais(3, 1). Run it: fails withTypeError: '_FieldView' object is not subscriptable. Implement__getitem__for a key(slice(None), j)with an intjin range, returning_FieldView(store, indices, component, col_start + j, col_start + j + 1, field_name, commands); any other key raisesTypeError("a field view takes [:, j], one column"). Run it: passes. - Write
tests/web/apps/drift.py: aVelocity(Component)withv: Vector3; setup spawns a ground without Velocity and 12 boxes with velocities fromnp.linspace; systemdrift(q: Query[Transform, Velocity], dt)doesq[Velocity].v += GRAVITY * dt(GRAVITYa float32(3,)global),q[Transform].pos += q[Velocity].v * dtandq[Transform].rot += SPIN(a float32 quaternion global); a second systemwatch(q: Query[Transform, Velocity], dt)storesfloat(np.sum(q[Transform].pos.data, axis=None))andlen(q)inengine.state, reading whatdriftqueued (the old rows); a third,low(q: Query[Transform], dt), storeslen(q[Transform].pos[:, 1] < 0.0). Then the failing tests intests/web/test_queries.py: - Run
uv run pytest tests/web/test_queries.py tests/test_ecs.py -q: the web tests fail on the reach errorcomponent queries are not supported in the browser yet. - Reach and types. Remove
Reach._query's error;find_rootsfillsRoot.componentsfromSystem.component_names, andsnapshotwrites it on each root. InTypeEnv, the first parameter of a system root types asquery(components)(the live registration, soQuery[...],mx.Query[...]or no annotation all work);q[X]whereXnamesTransform,Mesh,Materialor aComponentsubclass types asaccessor(name); an attribute of an accessor types asfield(...)from the layouts task 2 writes (the same table, built from the live classes);field.dataisnd("f32", 2); arithmetic with a field follows_FieldView: the other side is cast to float32 first and the result isnd("f32", 2)(src/manifoldx/ecs.py:269-307);< <= > >=givend("i32", 1), the entity indices;field[:, j]is a one-column field;len(q)is an int andfor i in qbinds ints. A field innp.*or with unary minus fails naming.data. - Transpile.
q[Transform]becomesq.get("Transform");.poson an accessor.field("pos");x.pos = von an accessor.field("pos").set(v);x.pos += v.field("pos").iadd(v), likewise-=and*=;/=becomes.set(f.rtruediv...)as Python falls back to__truediv__then the setter;rot +=composes with_quat_multiply(other, current)(src/manifoldx/ecs.py:332-354) in float32, each product and sum rounded, then normalised with a zero norm kept as 1. The runtime classes follow the interfaces;setand the in-place forms callstore.queueUpdatewith the field's columns. - Run
uv run pytest tests/web/test_queries.py tests/test_ecs.py tests/web/test_replay.py -q: all pass. - Commit the desktop change and the web change separately:
feat(ecs): a field view takes [:, j], one column, thenfeat(web): component queries in systems, with queued writes.
uv run pytest tests/web/test_queries.py tests/test_ecs.py tests/web/test_replay.py tests/web/test_reach.py -q: all pass, the breaking test included.
8Entity handles in frame code; set_material through the store; #153, #154web/types.py · web/transpile.py · js/manifoldx.js · tests/web/test_handles.py · tests/web/apps/handles.py
interfaces
Store.write and queueDestroy (task 4), the engine dict's origin (task 2), EntityHandle and _TransformProxy (src/manifoldx/engine.py:25-160) · produces JS class EntityHandle (index, transform, set_material(m), destroy(free_geometry = true)), class TransformProxy (pos: a new Float64Array(3), row plus [ox, 0, oz]; setting it stores v - offset rounded to float32; rot, scale: new Float32Arrays; setting them writes at once); resolve("entity", i) returns one EntityHandle per index; engine.set_material(entity, material) writes the Material column at once, bumps store.version, keeps the ["material", i, id] log entry, and throws set_material: entity ${i} is not alive as the desktop raises · types: RUNTIME_SURFACE for manifoldx.engine.EntityHandle and manifoldx.engine._TransformProxy; WRITABLE gains the proxy's pos rot scale and the camera's up (#153); a write to a field of a material fails with the set_material hint (#154)- Write
tests/web/apps/handles.py: 8 crates spawned at setup, their handles in a list of app objects (Cratewithentity,phase); a system moves each crate in a circle withc.entity.transform.pos = (x, y, z)from floats, spins it withc.entity.transform.rot = Transform.rotation(y=angle), scales it fromscale's read value, paints the crate under a timer withc.entity.set_material(RED), and at frame 50 destroys crate 3 withcrates[3].entity.destroy();engine.camera.upis written each frame. A second copy of the app callsengine.set_origin(5000.0, -3000.0)(src/manifoldx/engine.py:705) at setup before the spawns. Then the failing tests intests/web/test_handles.py: - Run
uv run pytest tests/web/test_handles.py -q: fails at the export (transformon an EntityHandle types as unknown). - Implement the surface and the runtime classes.
EntityHandle.destroyqueues the index for the flush and frees nothing (the library keeps the geometry, spec section 05).transform.pos[1] = ychanges only the returned copy, as on the desktop: no special case. The material hint is a branch in the write check ofReach._attributefor receivers of amanifoldx.resourcesmaterial class. - Run
uv run pytest tests/web/test_handles.py tests/web/test_replay.py tests/web/test_state_access.py -q: all pass. - Commit:
feat(web): entity handles in frame code, set_material through the store (#153, #154).
uv run pytest tests/web/test_handles.py tests/web/test_replay.py tests/web/test_state_access.py -q: all pass.
9Spawn and destroy in frame code, from the geometry libraryweb/types.py · web/reach.py · web/transpile.py · js/pyrt.js · js/manifoldx.js · tests/web/test_spawn.py · tests/web/apps/spawner.py
interfaces
Store.spawn and queueDestroy (task 4), GEOMETRY and {"__geometry": id} (task 2), EntityHandle (task 8), Engine.spawn and Engine.destroy (src/manifoldx/engine.py:1030, :1123) · produces pyrt $rt.component(name, values: Map), a plain record {component, values}; types: Ty("component", name=...) for a call of Transform, Mesh, Material or a Component subclass, TypeEnv.components: dict[str, str] (qualname to store name) for the app's Component subclasses, which are not app classes and are never transpiled; RUNTIME_SURFACE Engine.spawn returning the handle (or None) and Engine.destroy; RUNTIME_KEYWORDS = {"manifoldx.Engine.spawn": ("n",)}, passed as a final {n: k} · JS engine.spawn(...components, opts), engine.destroy(x)- Write
tests/web/apps/spawner.py:CUBEandBALLgeometries as module globals, no entity drawingBALLat setup; onjust_pressed("Space")a system spawns 20 boxes withengine.spawn(Mesh(CUBE), Material(BLUE), Transform(pos=ring, scale=(0.4, 0.4, 0.4)), Life(t=2.0), n=20)whereringis(20, 3)float64 fromnp.cosandnp.sinofnp.arange; on"b"one ball withengine.spawn(Mesh(BALL), Material(RED), Transform(pos=(0.0, 2.0, 0.0))), keeping its handle inengine.state's app object; a systemage(q: Query[Life], dt)doesq[Life].t -= dtandengine.destroy(q[Life].t <= 0.0); on"x"the ball's handle is destroyed;n=0is spawned once and its result (None) stored. Then the failing tests intests/web/test_spawn.py: - Run
uv run pytest tests/web/test_spawn.py -q: fails at the export. - Types and reach. In
TypeEnv._class, a class whose live object subclassesmanifoldx.components.Componentis recorded incomponentsand not as aClassInfo; a call of it types asTy("component", name=cls.__name__); so do the setup-importedTransform,MeshandMaterial(resolved throughlibrary_classtomanifoldx.components.*).Mesh(x)needsxtypedGEOMETRY;Material(m)a material handle. - Transpile. A component call becomes
$rt.component("Transform", new Map([["pos", ...]])): keywords by name, positional arguments mapped topos rot scalefor Transform,geometryfor Mesh,materialfor Material; aComponentsubclass takes keywords only, as its__init__. A call to a runtime-surface function listed inRUNTIME_KEYWORDSpasses its keywords as a final object literal. - Runtime.
engine.spawnmirrorsEngine.spawnand eachget_data: Transform's defaults (scale 1, w 1), itspos,rot,scalebroadcast tonrows, cast to float32, the origin subtracted in float64 from a givenpos(engine.py:1066-1072); Mesh and Material rows of the geometry and material id; a Component's fields byComponent.get_data's rules (components.py:123-158), fields missing from the call taking the class default the layout carries (add"defaults"to the component's header entry in task 2's form). It callsstore.spawnat once and returnsresolve("entity", first), ornullforn0.engine.destroy(x): null does nothing, a boolNdArraygives its true positions, an i32NdArray, array orInt32Arrayits values; non-empty, it queues. - Run
uv run pytest tests/web/test_spawn.py tests/web/test_queries.py tests/web/test_handles.py -q: all pass. - Commit:
feat(web): spawn and destroy in frame code, from the geometry library.
uv run pytest tests/web/test_spawn.py tests/web/test_queries.py tests/web/test_handles.py tests/web/test_ecs_snapshot.py -q: all pass.
10The page draws instanced batches from the storejs/scene.js · js/browser.js · tests/web/js/scene.test.mjs
interfaces
Store with version and takeDirty() (task 4), buildScene (src/manifoldx/web/js/scene.js:124) · produces buildScene(THREE, gltf, renderer) reads extras.mx_geometries into geometries: Map<id, BufferGeometry>; the MxScene gains batches: Map<"gid:mid", InstancedMesh> and sync(engine) also syncs batches from engine.store; materialOf(entity) reads the store's Material column; entities, setMaterial and resetMaterials are removed, and browser.js drops the setMaterial hook and the resetMaterials() call (browser.js:140, :241); __mx.renderer is the renderer- Rewrite the scene tests that read
entitiesor callsetMaterialandresetMaterials(tests/web/js/scene.test.mjs:56,:67,:249), and add, on the web_walk export (six boxes, a ground, one cube geometry, eight materials): - Run
uv run pytest tests/web/test_node_suites.py -q: the scene suite fails. - Implement in
scene.js. At load, eachmx_geometriesentry's glTF mesh gives itsBufferGeometry(gltf.parser.getDependency("mesh", index)).sync: whenstore.versiondiffers from the last seen, one pass over the alive slots with a Mesh bit and a geometry id other than 0 rebuilds each batch's member list, keyed`${gid}:${mid}`; a batch is created on first use with the drawn material (materials.get(mid), or a white basic material for id 0, as the desktop draws a mesh without a Material), cloned withvertexColorson when the material'suserData.mx.vertex_colorsis true and the geometry has colour; capacity doubles;countis the member count andvisibleiscount > 0; all members' matrices are written. Otherwise only members instore.takeDirty()'s range are rewritten. A batch whose matrices changed setsinstanceMatrix.needsUpdateand recomputes its bounding sphere. Withextras.shadowsevery batch casts and receives, and the shadow fit (fitShadow) runs after the first batch sync, soauto_fitsees the batches. - Run
uv run pytest tests/web/test_node_suites.py -q: all pass. - Commit:
feat(web): the page draws one instanced mesh per geometry and material.
uv run pytest tests/web/test_node_suites.py -q: all pass. Chromium, draw calls and the visual check run in task 12.
11examples/web_crowd.py, its Node replay and the breaking testsexamples/web_crowd.py · tests/web/test_web_crowd.py · examples/README.md
interfaces
examples/web_crowd.py, public, and tests/web/test_web_crowd.py with script(seed, n) -> list[Frame], PATHS, and the fixtures crowd_export and crowd_python_trace the browser test reuses- Write
examples/web_crowd.py, in the style ofexamples/web_walk.py(a module docstring with the controls and both commands, constants at the top, plain functions):- A ground (Mesh, Material, Transform, no Velocity) and a fixed camera looking at the origin from
(0, 12, 22); aVelocity(Component)withv: Vector3;CUBEa module global; three box materials andGOLD. spawn_wave(q: Query[Transform], dt): onjust_pressed("Space"), 24 boxes on a ring of radius4 + waveat height 6 with outward velocities, materialwave % 3, all fromnp.arange,np.cos,np.sinandnp.column_stackon float64, in oneengine.spawn(..., n=24);engine.state["waves"]counts them.drift(q: Query[Transform, Velocity], dt): gravity intov,pos += v * dt, a spin intorot, andengine.destroy(q[Transform].pos[:, 1] < -10.0).pick(q: Query[Transform, Velocity], dt), afterdrift, so it reads the rows before the flush: on a left click, the ray fromengine.camerathroughengine.input.mouse_pos(camera.fov,engine.w,engine.h), the boxes' distances to it withnp.linalg.norm(..., axis=1),np.whereto putnp.infon misses,np.argmin; the hit box turnsGOLDwithengine.set_material, the previous one gets its material back;engine.state["picked"]holds the entity index or None.- A panel with ValueDisplays: boxes alive (
lenof a query read in a system and kept inengine.state), waves, picked.
- A ground (Mesh, Material, Transform, no Velocity) and a fixed camera looking at the origin from
- Write the failing tests in
tests/web/test_web_crowd.py. The script, seeded, of 600 frames: Space at frames 5, 6 and 200 (two waves in a row, one after the first fell), left clicks at pixel positions over a box on frames 40, 41 (the same box twice) and 120, a click on the sky at 150, a resize to 640×400 at frame 300, Space at 301: - Run
uv run pytest tests/web/test_web_crowd.py -q; fix what the replay finds in the task that owns it (and note it in that task's departure lines), until all pass. - Add the example to
examples/README.md's list besideweb_walk.py. - Commit:
feat(examples): web_crowd, the ECS in the page end to end.
uv run pytest tests/web/test_web_crowd.py -q: all pass, four breaking cases included. uv run python examples/web_crowd.py opens a window where Space, falling and clicking work, checked by its --render --duration 2 MP4 or manifoldx look under manifoldx run on a host with a GPU or lavapipe.
12Chromium: web_crowd's replay, one draw call per batch, materials from the batchtests/web/browser/test_web_crowd_page.py · tests/web/browser/conftest.py · js/browser.js
interfaces
tests/web/browser/conftest.py (served, open_page, _export), test_page.py's tick and drive patterns, task 11's script and Python trace, __mx.renderer (task 10) · produces crowd_export in the browser conftest; Chromium checks the replay cannot see- Write
tests/web/browser/test_web_crowd_page.py: - Run
uv run pytest tests/web/browser/test_web_crowd_page.py tests/web/browser/test_page.py tests/web/browser/test_visual.py -von a host with Chromium and lavapipe. Each failure is a defect of an earlier task or of the page: fix it there, and note in the departures section what the browser forced. - Break one once: drop the
store.versioncheck so membership never rebuilds after load;test_an_entitys_material_is_read_from_its_batchfails. Restore it. - Commit:
test(web): web_crowd in Chromium, draw calls and batch materials.
uv run pytest tests/web/browser/test_web_crowd_page.py tests/web/browser/test_page.py tests/web/browser/test_visual.py tests/web/browser/test_run_web.py -v: all pass with no skips on a host with Chromium; otherwise push and read the browser job, which fails on any skip.
13The web-crowd bench case and the docsbenchmarks/suites/web.py · js/browser.js · know-how/web-export.md · know-how/benchmarking.md · CHANGELOG.md · AGENTS.md
interfaces
@case registry (benchmarks/harness.py), everything above · produces @case("web", "web-crowd", sizes=[1_000, 10_000], smoke=100) returning {"ms": page work per frame, "calls": draw calls}; __mx.frameMs, {work, render} of the last tick in milliseconds (work from the frame's start to the batch sync's end, render the renderer.render call)- In
browser.js'srunFrame, time the frame withperformance.now()intomx.frameMs. - Write
benchmarks/suites/web.py: the case writes an app into a temp dir that spawnsnboxes at setup in one batch with aVelocity, and a query system moving all of them every frame; exports it, serves it, opens headless Chromium with Playwright, runs 60 manual ticks, and returns the medianworkand the last tick's draw calls. Without Playwright or Chromium it raises, which the harness reports as the case's error (benchmarks/__main__.py:46). It reports and does not gate (spec section 11). - Run
uv run python -m benchmarks web --case web-crowd --sizes 1000once; with Chromium it prints a row withcalls2 (the batch and nothing else; the app has no ground). - Docs.
know-how/web-export.md:ecs.binin the folder listing; a section "Entities in the page" (queries filter by component, the field view's desktop semantics including[:, j], what queues and what is immediate, spawn from geometries the export saw, handles, the array subset and its errors, batches and draw calls); the trace'sstore.know-how/benchmarking.md: thewebsuite.CHANGELOG.mdunder[Unreleased],### Added: the store in the page, queries, arrays, spawn and destroy, handles, instanced batches,libraryglTF mode,_FieldView[:, j],examples/web_crowd.py.AGENTS.md's web target line: plan 5a and its path. - Commit:
docs(web): entities in the page, the web-crowd bench.
uv run pytest tests/test_benchmarks.py -q, which runs every case at its smoke size: passes, the new case reporting an error rather than failing where Chromium is missing. The know-how's commands run as written.
Where this plan departs from the spec
- A query types from the live registration, not from its annotation. Section 05 says a query parameter types as
Query[A, B]. The engine already parses the annotation when it registers the system (src/manifoldx/engine.py:537-559) and keeps the names onSystem.component_names(src/manifoldx/systems.py:16); task 7 types the parameter from those, soQuery[...],mx.Query[...]and the desktop's own spellings all work without the transpiler resolving them. - A field keeps the desktop's operators, not an array's. Section 05 reads a field as a
(k, c)array. On the desktop it is a_FieldView: arithmetic casts the other side to float32 before operating (src/manifoldx/ecs.py:269-307), so a float64 operand does not promote; comparisons return entity indices, not a mask (:309-324); it has no unary minus and numpy functions do not take it. The page mirrors that, and.datais the array. field[:, j]lands on the desktop (task 7). The spec'sengine.destroy(q[Transform].pos[:, 1] < -10.0)raisesTypeErroron the desktop today, since_FieldViewhas no__getitem__; andpos.data[:, 1] < -10.0is a mask over query rows, whichEngine.destroywould read as slots (src/manifoldx/engine.py:1129-1131). A one-column view keeps the spec's line and its meaning.- Mesh and Material columns are uint32. Section 05 says float32 for every built-in;
Mesh.registerandMaterial.registeruseu4(src/manifoldx/components.py:327,:368).ecs.bincarries both dtypes. - The existing
vecstays a bare typed array.NdArrayis for arrays of rank 2, of bool or int32, and the results of operations involving one;$rt.ndtakes aFloat32ArrayorFloat64Arrayas rank 1. Plans 1 to 3's vectors (the camera's, an app'snp.array([...])) and their tests do not change. **takes the exponents 2, 0.5 and -1 only (task 5). numpy computes those three exactly as square, square root and reciprocal; any other power of a float32 array goes throughpowf, which the page cannot match bit for bit. The error says to multiply.np.argminandnp.argmaxjoin the subset (task 6). Section 05's list has no way to pick the nearest of many; web_crowd's pick needs one.- Float32
sin,cosandexpmay differ in the last float32 bit (task 6). numpy runs its own float32 kernels; the page computes in float64 and rounds. Task 6 measures the count on 10,000 values and writes it here. web_crowd keeps its trigonometry on float64. Measured bytests/web/test_ndarray.py:233on 10,000 float32 values fromnp.linspace(-50, 50)(numpy 2.4.4, an AVX-512 Skylake host):sindiffers in 1,592 values andcosin 1,596, each by one float32 step;expdiffers in 4,037: 3,946 by one step and 91 by two. numpy's float32expis itself up to two steps from the correctly rounded value, which the page gives, so the plan's "at most one step" holds for sin and cos only, and the test allows exp two (ULPS,:153). In float64, V8 against numpy on the same values: sin 340, cos 359 and exp 1,150 differ, each by one step. The counts depend on the CPU's kernels, so the test prints them and asserts only the bound. @,np.eyeandrandomwait for their plans. Section 05 lists@on stacks andnp.eyein the array subset; section 12 gives@to 5c withset_joints, its only user.random.Randombelongs to 5b.- The library maps geometry ids in the scene's extras. Section 10 says each geometry is written "with
extras.mx.geometry"; task 3 writes"mx_geometries": {id: mesh index}beside the existing"mx_materials"(src/manifoldx/gltf/writer.py:30-40), so the page finds every geometry without walking meshes. The named built-ins (the sprite quad and axis lines,src/manifoldx/resources.py:1497-1501) are left out: they are not drawn as meshes. - Vertex colours ride on the geometry and a flag on the material. Today a mesh is written per (geometry, material) and
COLOR_0only when its material uses colours (writer.py:148-151); a library has no pairs, soCOLOR_0goes with any coloured geometry and the material says whether to use it. resetMaterials()and thesetMaterialhook go away (task 10). Plan 3 added them so a kept scene underrun --webmatched a rebuilt one (src/manifoldx/web/js/scene.js:166-185); materials now live in the store, which every version loads afresh, and batches rebuild when the store's version moves.- The origin crosses (task 2). A handle's
posis in world coordinates, the store's row relative toengine._origin(src/manifoldx/engine.py:25-45);state.json's engine dict gainsorigin. - The Python replay flushes after the systems (task 4).
replay_pythonran the systems only (src/manifoldx/web/replay.py:178); queued writes now matter, so it flushes as_draw_framedoes. - The store's digest is defined (task 4). Section 10 traces "a digest past 1,000 entities" without a formula; the weighted sum of uint32 words mod 2^32 is exact in numpy and in JS.
spawn'sn=crosses as a trailing options object (task 9). Runtime-surface calls took no keywords (src/manifoldx/web/transpile.py:1185);RUNTIME_KEYWORDSnames the ones that do.- Component classes are records, not transpiled classes (task 9). An app's
Componentsubclass has a library base and annotation-driven storage (src/manifoldx/components.py:81-101); the page needs its layout, whichecs.bin's header carries, and its constructor, which$rt.componentgives. - #153 and #154 ride in 5a (task 8). The spec puts them in slice 5 without a plan; task 8 edits the same tables.
- The
web-crowdbench lands in 5a (task 13). Section 11 names the case without a plan; it measures the batches this plan builds. - One of task 1's five tests passes before the change (task 1).
test_transform_is_a_member_when_not_given(tests/test_ecs.py:342) checks a length the old rule also gives, since every alive entity matched; it guards the new rule's Transform bit and was not a fail-first test. The other four failed on lengths. examples/point_cloud.pybroke under the new rule and was fixed (task 1). Itsgravityquery namesScalarValue, which the star lacks, so it sees 10002 entities, not 10003, and its velocities array, sized per store slot, no longer broadcast; it is now one row per query row (examples/point_cloud.py:135). The audit's other 40 apps that ran kept their counts.- build_export, not snapshot(), puts the store's header under
"ecs"(task 2).ecs_bytesreturns the bytes and the header together, andsnapshot()returns only JSON, sobuild_exportcalls it beside the snapshot (src/manifoldx/web/export.py:122), as it adds"gui". - The dtype error reads as the snapshot's other errors (task 2).
SnapshotErrorjoins its two parts with a colon, so the line isthe component Flags: dtype int64; ecs.bin carries float32 and uint32 and it cannot cross to the browser(src/manifoldx/web/snapshot.py:290), and the test asserts that. - Task 2's fixture builds with
capture_engineandbuild_export(task 2). Afterexport_webthe app's module is no longersys.modules["__main__"], so the fixture keeps it and readsmain.CRATE(tests/web/test_ecs_snapshot.py:43). Two tests were added: the Node replay resolvesCRATEto{geometry_id}(:115), and a store of 3 entities, whose blocks need padding, keeps every block on a multiple of 4 (:128); with 4 entities the padding mutation passed. - Library mode reports the materials its entities draw (task 3). With no nodes, the notes
node()adds per drawn entity (PhongMaterialapproximated, a material with no glTF equivalent dropped) were gone fromscene.export-report.json;build_glbtakesdrawn_materials, each meshed entity's material, and reports their notes as a node's (src/manifoldx/gltf/engine_export.py:132,tests/test_gltf_library.py:101). An entity with no Material is not among them: the page draws it white itself. - Task 3's tests read the glb through pygltflib's objects (task 3).
tests/gltf_helpers.py'sloadreturns aGLTF2, so the tests readg.scenes[0].extrasandprim.attributes.COLOR_0, not dicts. The fixture also draws the coloured geometry, so the no-library case counts 4 entity nodes, not 3, and a seventh test checks that a point cloud's entities are still reported as dropped. - From task 3 to task 10 the page draws no entities (task 3).
build_exportwrites the library, whichscene.jsreads only from task 10, so three Node tests fail in between:tests/web/js/scene.test.mjs:56,:67and:249, the ones task 10 rewrites.tests/web/test_node_suites.pyis red on this branch until then; the rest oftests/weboutsidebrowser/passes. - The page's
set_materialwrites the Material column from task 4 (task 4). Once both traces carried the store, web_walk's replay differed at frame 41 (store.rows.Material[4][0]: 8 != 5): the desktop writes the column at once and the page only logged.engine.set_materialnow callsstore.write("Material", ...)(src/manifoldx/web/js/manifoldx.js:488), which bumpsversion; task 8 still owns the handle form and thenot aliveerror. - A state without
"ecs"loads withengine.storenull (task 4). The hand-built states oftests/web/js/runtime.test.mjshave no store;loadAppsetsnullfor them (manifoldx.js:120),stepskips the flush andtraceEntrywritesstore: null(:601). The web_walk entry test now expectsstore(tests/web/js/runtime.test.mjs:317). - The page's starting capacity is the export's high-water mark (task 4), at least 1 so doubling moves (
manifoldx.js:140);dirtyis half-open,[lo, hi).tests/web/test_store.py:197adds a sixth test: a query takes the alive members, an unknown name matches nothing. $rt.nd's operations take the dtype as a last argument (task 5). The page cannot tell a Python2from2.0, and numpy 2 givesint32 * 2int32 butint32 * 2.0float64, and compares a float32 array against0.1rounded to float32. So the transpiler passes the dtype numpy computes in:$rt.nd.add(a, b, "f32"),$rt.nd.gt(a, b, "f32")(src/manifoldx/web/transpile.py:975). Each operation casts both operands to that dtype on entry (src/manifoldx/web/js/pyrt.js:257).a ** 2becomes$rt.nd.square(a, d), soais evaluated once; there is no$rt.nd.pow.- The unrounded-float32 breaking test patches the last operation (task 5). Since each operation casts its operands to float32, a
mulleft unrounded is rounded again by the nextadd, with the same bits: a double holds a float32 product exactly.tests/web/test_ndarray.py:41patchesnd.sub, the last step off32_scalar, and that one differs. Turning off float32 casting inCASTfailsf32_compareandarange_f32. - A comparison with a bare vector gives a bool nd (task 5).
compare_maskscomparesnp.arange(0.0, 8.0, 1.0), a vec, so comparisons,**,&and|with a vec give an nd (src/manifoldx/web/types.py:1088);+ - * /between vecs and numbers stay vec. Three cases were added:f32_compare,arange_f32andzeros_bool_int.np.fullwithout a dtype needs a float fill (an int fill would be int64).a += bon an nd fails the export and says to build a new array (transpile.py:632), because numpy writes in place and keeps the dtype. A broadcast takes a scalar, equal shapes or a shape that ends the other; a dimension of 1 throws numpy's message (pyrt.js:244). - sin, cos and exp are compared within steps, the other functions bit for bit (task 6).
test_transcendentals_within_a_step(tests/web/test_ndarray.py:167) holds float32 toULPSand float64 to one step.where_choose(:132) clamps thenp.infit chooses withnp.minimumbefore the trace, because JSON has no infinity and JS writes it asnull; the division after it shows that float32 stayed float32. - Integer arrays are int32 in the page (task 6).
np.arrayof a list of ints with no dtype isnd("i32", 1), though numpy makes int64 (src/manifoldx/web/types.py:975). The same holds fornp.where(m)'s index arrays, and for annp.sum,np.minornp.maxof an int32 or bool array, which add and compare in int32. The two dtypes promote alike against float32, float64 and Python numbers, and differ only past 2^31.np.sumof a bool array counts it (sum_mask,:188).np.nanjoins the constants (types.py:654). - The array subset's edges (task 6).
np.stackandnp.column_stacktake rank-1 arrays (src/manifoldx/web/js/pyrt.js:418).np.linalg.normtakesaxisby keyword only, since its second positional argument isord. Reductions takeaxisNone, 0 or 1.a.shapeis a fresh list. A bare vector indexed by an nd (v[v > 1.0],v[np.array([2, 0])]) goes through$rt.nd.getitem(vec_mask,:187, failed before the fix). An index past the end throws numpy'sIndexErrorword for word (:198). The functions get the dtype as their last argument, as in task 5 (src/manifoldx/web/transpile.py:1349). - The desktop read no Component subclass field through a query (task 7).
ComponentAccessor.__getattr__looked fields up only among@engine.componentclasses, soq[Velocity].vraisedAttributeErrorfor aComponentsubclass, the form AGENTS.md recommends and drift.py uses. It now reads the class's_layoutfirst (src/manifoldx/ecs.py:537), a commit of its own before[:, j]. - Component subclasses are found in task 7, not task 9 (task 7).
q[Velocity]needs the component's store name and layout, soTypeEnv._classrecords aComponentsubclass incomponentsand its live class incomponent_classes, and makes noClassInfo(src/manifoldx/web/types.py:834,:862). The field table the snapshot writes moved totypes.component_fields(:262), so types and ecs.bin read one table. - A field view's edges (task 7). A comparison takes a one-column field on the left (
q[X].f[:, j] < x), since the desktop's mask of a wider field does not index its entities (types.py:1360). A number may stand left of a field (radd, rsub, mul, rtruediv), an array may not: numpy's operator would run instead of the field's (:1444).f /= xis.idiv, the quotient by__truediv__then set, not rtruediv as the step says (src/manifoldx/web/js/manifoldx.js:448); a/=on a local holding a field fails, since Python rebinds it to an array. Mesh and Material fields fail the export: their ids are uint32 and frame code reads them through handles. A write into a column (q[X].f[:, j] += x) fails, as the desktop raises TypeError; a field in a numpy function or a builtin, even nested (float(np.sum(q[X].v))), fails naming.data(transpile.py:1463). - A handler's query is typed and read-only (task 7). A handler registered with
Query[...]gets(payload, view)on the desktop; its root carries the components (src/manifoldx/web/reach.py:249),firepasses aQuery, and any write through it fails with "a write through an event handler's query, which is read-only" (transpile.py:691). - The query test of plan 1 became a typing test (task 7).
test_a_system_that_uses_its_query_failsasserted the error this task removes;test_a_systems_query_types_from_its_registration(tests/web/test_reach.py:183) checks the parameter's type and that iterating it binds ints. Transform.rotation(x, y, z)joins frame code (task 8). handles.py spins its crates with it, as the step says, and nothing could call it:$rt.quat_eulercomputes it as numpy does for Python numbers, in float64 then float32 (src/manifoldx/web/js/pyrt.js:141; typed atsrc/manifoldx/web/types.py:1612, emitted atsrc/manifoldx/web/transpile.py:1520). Numbers only:euler=and float32 scalars fail the export.- A handle's transform takes numbers and arrays, and
+=writes back (task 8). The camera's vector fields keep their object and must get float32 vectors; the proxy's setters runnp.asarray, so they take a tuple of numbers or a 1-d array of either float dtype (transpile.py:788).t.pos += vreads a copy and Python writes the sum back through the setter, so it emitst.pos = viadd(t.pos, v)(transpile.py:691). - The handle's own
set_materialkeeps no record (task 8).EntityHandle.set_materialwrites the column and does not check that the entity is alive, as the desktop's; onlyengine.set_materiallogs["material", ...]and throwsValueError: set_material: entity N is not alive(src/manifoldx/web/js/manifoldx.js:535,:694). handles.py'swatchcounts its query, so a destroy applied at once instead of at the flush is a mismatch. - Two export cases moved off
camera.up(task 8).test_a_runtime_write_the_page_does_not_apply_fails_the_exportusedupas a field the page ignores; with #153 it is written, so the cases uselayersandzoom(tests/web/test_export_web.py:795). The browser test #153 asks for is not written here; task 12 runs Chromium. - A Component subclass setup never registered is registered at its first spawn (task 9). The desktop's
Engine.spawnregisters it then, so the trace's rows gain it at that frame; registering it at export would show it from frame 0. Reach records the subclasses reached code constructs (src/manifoldx/web/reach.py:337),state.json'secsgains"spawnable", their layouts (src/manifoldx/web/snapshot.py:324), andStore.registeradds their zeroed columns on first use (src/manifoldx/web/js/manifoldx.js:185). Every component entry gains"defaults", as the step says. The built-ins need none of this: the engine registers them at construction. A query of a component never registered still fails as the desktop's does (ValueError: Component Life not registeredon the field), so spawner.py callsLife.register(engine.store)at setup. - A global's live type survives an unknown initializer (task 9).
CUBE = cube(...)joined its live type (a geometry) with the call's inferred type, unknown, which absorbed it, soMesh(CUBE)could not see a geometry. A reached global's value comes from the snapshot, so an unknown inference now leaves the live type (src/manifoldx/web/types.py:1896). The same fix typesmat = mx.material.basic(...), #154's own example: its write now gets theset_materialhint instead of "annotatemat", and the case moved from the unknown-type test totest_a_material_write_points_at_set_material(tests/web/test_export_web.py:791). - The ball's handle lives in a module global, not in engine.state (task 9). The Python trace writes
engine.stateas JSON and refuses an app object (replay._plain), so spawner.py keepsGameas a global. Its fields are annotated at class level (tests/web/apps/spawner.py:26): an annotation in an__init__that only setup runs is never read, soself.ball: EntityHandle | None = Nonethere types as None. A setup-imported class of the runtime surface (EntityHandle) is now an annotation the model reads (types.py:1066), and a method call on a value that may be None, after a None test, emits as an object's (transpile.py:1648). - spawner.py also moves the origin and counts after age (task 9).
engine.set_origin(1000.5, -2000.25)at setup makes a spawned pos world coordinates, so a page that forgot to subtract the origin mismatches;count, afterage, reads the boxes in the frame age destroys them, so a destroy applied at once mismatches. Geometry and material ids: the export registers a geometry no entity drew when the snapshot meets it, the Python replay when frame code first spawns it, so the two agree only while one such geometry is first used per run in walk order; spawner.py has one (BALL). - engine.spawn and engine.destroy check their arguments (task 9).
engine.spawntakes components andn=, an int;engine.destroyone array of entity indices, a bool mask, a list of ints or None (transpile.py:1427). A component's values are numbers, a 1-d array or a tuple of numbers;Mesh()of a call fails as a geometry built in frame code, of anything else not typed a geometry as "not a geometry the export saw";Material()takes a material made at setup (:1450). - Verify against
origin/main(tasks 1 and 3). A localmainref may lag the remote; the audit's before run and task 3'sgit diff mainusedorigin/main. - Batches also rebuild on another store (task 10). A version swapped in under
run --webloads a newStorewhoseversionstarts at 0 again, so a kept scene could see the same number and keep the old version's batches;syncrebuilds when the store object or its version changes (src/manifoldx/web/js/scene.js:217), which is whatresetMaterials()did.tests/web/js/scene.test.mjs:429loads the export twice and checks a gold box goes back to its batch. Task 12 needs a new damage fortest_run_web.py's no-opresetMaterialsbreaking test (tests/web/browser/test_run_web.py:149,:159): droppingstore !== seenis the one the Node test catches. - The shadow fit waits for the first sync (task 10).
buildSceneno longer fits the sun; the firstsync(engine)does, after the batches, once, and only then sets every mesh to cast and receive (scene.js:308). The two stand-in shadow tests sync before they read the shadow camera (tests/web/js/scene.test.mjs:353), and a new test puts a sun and shadows on web_walk's glb and checks the auto fit reaches a box moved to x = 80. - What a batch skips and refuses (task 10). A Mesh row whose geometry id is not in
mx_geometries(a named built-in, which task 3 leaves out) is not drawn (scene.js:226); a Material id not inmx_materialsthrowsmaterial N is not in the exported scene(:158), as the oldsetMaterialdid. A slot without a Material bit draws white whatever its column holds.disposealso frees the library geometries, the vertex-colour copies, the white material and each batch's instance buffer (:293).createEngine'ssetMaterialhook stays inmanifoldx.js, whichtests/web/js/runtime.test.mjs:193covers; onlybrowser.jsdrops it. - The scene suite also loads spawner.py's export (task 10). web_walk draws its only geometry, so the step's "a spawn of a library geometry no entity used at export draws" runs on
tests/web/apps/spawner.py's BALL, exported by a new session fixture (tests/web/test_node_suites.py:99,MX_SPAWNER_EXPORT). Five more tests than the step lists: the library geometries and no entity nodes, a batch past its capacity, a destroyed entity leaving its batch, a mesh with no Material drawn white, and the swapped store above. - The browser tests still read the old scene (task 10).
tests/web/browser/test_page.py:190and:217look for meshes under glTF nodes markedextras.mxand read__mx.scene.entities, andtest_run_web.py:149and:159readentitiesand stubresetMaterials; none of these exist after task 10. They were not run here (no Chromium in tasks 10 and 11): task 12 rewrites them against__mx.scene.batchesandmaterialOf. - The Python replay registers ids as the export does (task 11, fixing task 9). web_crowd's replay differed at frame 40 (
log[0][2]: 4 != 5): the export's snapshot registers every material and geometry it meets in walk order (the three colours, then GOLD), the desktop at first use (a colour per wave, GOLD at the first pick).replay_pythonnow runs the export's reach and snapshot after setup and drops the result, so its registries hold the export's ids before any frame (src/manifoldx/web/replay.py:169). Task 9's caveat (ids agree only while one such geometry is first used per run in walk order) no longer holds: the ids agree in any order. The desktop app outside a replay still registers at first use; ids are labels, so nothing an app sees changes. - A global's live type also survives an inference that holds unknown (task 11, widening task 9's fix).
COLORS = [mx.material.phong(...), ...]inferredlist[unknown], which is known, so it joined the livelist[obj PhongMaterial]andMaterial(COLORS[k])failed as not a material made at setup. The test is now_vague(t), unknown at any depth (src/manifoldx/web/types.py:216,:1900). - web_crowd annotates the ray (task 11).
d = ray(...)leftdunknown althoughrayreturnslist[float]by annotation, and the error then namednp.linalg.norm() of unknowntwo lines later, notd; the example writesd: list[float] = ray(...)(examples/web_crowd.py:114). Not chased here: a typing gap for a later task. - web_crowd has a Wave component, and pick's query names it (task 11). Giving the previous box its colour back needs that box's colour, and frame code cannot read a Mesh or Material column (task 7).
Wave(Component)withk: Floatholds the colour's index;pick(q: Query[Transform, Velocity, Wave])reads it for the hit row (examples/web_crowd.py:42,:104).engine.state["picked_k"]keeps it until the next pick. A picked box that falls is unpicked the frame after its destroy, so a restore never names a dead entity. - web_crowd shows the fastest fall, for the unrounded-product break (task 11). Every float32 product web_crowd made landed in a Float32Array column or a cast at the next operation's entry, so a
$rt.nd.mulleft unrounded changed nothing in the trace.engine.state["fall"]is-float(step[argmin])ofv.data[:, 1] * dt, a value read straight out of a float32 product, and the panel shows it (examples/web_crowd.py:82). With the break the replay differs at frame 5 (state.fall: -0.05000000447034836 != -0.05). The other three: the free list from its start at frame 200 (store.alive[1]: 25 != 1), query writes at once at frame 5 (drift'spos += v * dtread the newv), queries unfiltered at frame 0 (the ground counted). - The script's numbers (task 11). Gravity is 6 m/s² so the first rings live about 2.9 s (they are destroyed between frames 7 and 199, and frame 150's sky click restores a live box); the click pixels were measured by projecting the Python trace's rows through the camera (
tests/web/test_web_crowd.py,CLICKS). The seeded part is the pointer's wander between clicks. A seventh test checks the fixture is the generator's. - examples/README.md had no list (task 11). It names no example, web_walk included; it gains a short section, "Exported to the web", naming both.
- No page defect surfaced in Chromium (task 12).
test_web_crowd_page.py's three tests passed at first run on SwiftShader; what failed were tests written against the scene before task 10. A batch's material is checked through the instance three.js draws:BATCHES_OFfinds the batches whose instance matrix sits at the entity's Transform row (tests/web/browser/conftest.py:70), shared bytest_page.py,test_run_web.pyand the new file. The plan's break (nostore.versioncheck) fails both batch tests: no box is drawn after load.crowd_exportis a session fixture of the browser conftest built with_export(:162); the script,PATHS,SPACEandCLICKScome fromtests/web/test_web_crowd.py. The visual-parity test is not a fourth test in the new file:test_visual.pyruns as it was, itslit_yardandweb_walkmeans withinTHRESHOLDthrough batches. - The scene has no meshes before the first tick (task 12). Batches are built at the first
sync, andmaterialOfreads the store that sync saw, so before any tick it isnull.test_visual.py'sSWAP_BASICbreak found no mesh to swap and the scene stayed within the threshold; it now swaps the library's materials in__mx.scene.materials, which the batches take at the first sync (tests/web/browser/test_visual.py:106).test_run_web.py'sruntime_material_resetticks once before it reads (tests/web/browser/test_run_web.py:135). - test_page.py's swapped-entities break became a batch-key break (task 12). The page has no map from entities to meshes to swap;
test_break_batches_ignore_materials(tests/web/browser/test_page.py:207) serves ascene.jswhose batches all key on material 0, so every box draws white while the trace andmaterialOfstill match, and the material check fails. - The identity break needs equal versions in Chromium (task 12). Dropping
store !== seenfromsyncis not seen by the run --web test as written: the old store is at version 1 after thehwrite, the new one at 0, so the version test alone rebuilds.runtime_material_reset(same_version=True)sets the old store's version back to 0 after the write, and the kept-scene test runs both ways (tests/web/browser/test_run_web.py:162);test_break_batches_kept_across_stores(:166) serves the damagedscene.jsand fails onmaterial. - #153's browser test runs on handles.py (task 12).
tests/web/apps/handles.pyalready writesengine.camera.upeach frame;test_a_system_writes_camera_up_and_three_follows(tests/web/browser/test_page.py:367) checks the three.js camera'supafter each of 20 ticks against the Python replay of the page's frames. - The web-crowd case draws one call, not two (task 13). The step expects
calls2 and gives the reason "the batch and nothing else; the app has no ground", which is one call; the run printscalls=1. The bench app has no sun, so no shadow pass either. - The smoke test runs the web case through the harness (task 13).
test_case_runs_at_smoke_sizecalls each case directly, and thetestCI job has no browser group, so for thewebsuite it goes throughrun([c], smoke=True)and accepts a time or the errorRuntimeError: playwright not installedorchromium not installed(tests/test_benchmarks.py:25).SUITESgainsweb(benchmarks/__main__.py:28), sotest_every_suite_has_casessees it. The case keeps its own copy of the browser conftest's SwiftShader flags and manual-mode init script:benchmarks/does not import tests. __mx.frameMsstarts as null (task 13), set by each framerunFrameruns (src/manifoldx/web/js/browser.js:39,:193); a frame that throws or is frozen leaves the last value.
Self-review
- Spec coverage, 5a of section 12: desktop component membership (task 1),
ecs.bin(2), the library glb (3), the page's Store and flush (4), the array subset (5, 6;@andnp.eyeto 5c), entity handles (8), instanced batches (10),examples/web_crowd.pyreplayed in Node (11) and Chromium with the draw-call test (12). Section 13's items for 5a: array parity (5, 6), the store againstEntityStore(4), the web_crowd replay with a read-after-write frame, a destroy and respawn, aset_materialacross batches and a resize (11), the breaking tests that 5a can own (4, 5, 7, 11), the draw calls and batch materials in Chromium (12),test_visual.pyon a batched scene (12), membership on the desktop with the old behaviour as a failing test first (1). Section 11's budget: theweb-crowdcase (13). - Names across tasks:
_members(1) in 2 and 4; the"ecs"header and{"__geometry": id}(2) in 4 and 9;mx_geometries(3) in 10;Store,queueUpdate,queueDestroy,write,version,takeDirty(4) in 7 to 10;ndand$rt.nd(5, 6) in 7, 9 and 11;Root.componentsandQuery(7) in 9 and 11;EntityHandle(8) returned byspawn(9);__mx.renderer(10) in 12 and 13. - Proportion: code is given for tests whose assertions carry values and for the audit script; implementations are named by signature and the rules the desktop code fixes, with the file and line to copy them from.