behavior-contracts 0.11.7 → 0.11.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/behavior.d.ts +20 -0
  2. package/dist/behavior.d.ts.map +1 -1
  3. package/dist/behavior.js +40 -4
  4. package/dist/behavior.js.map +1 -1
  5. package/dist/generator/async-plan.js +4 -3
  6. package/dist/generator/async-plan.js.map +1 -1
  7. package/dist/generator/emit-shared-rust-typed.d.ts +13 -1
  8. package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
  9. package/dist/generator/emit-shared-rust-typed.js +21 -7
  10. package/dist/generator/emit-shared-rust-typed.js.map +1 -1
  11. package/dist/generator/emit-shared-typescript-typed.d.ts.map +1 -1
  12. package/dist/generator/emit-shared-typescript-typed.js +11 -1
  13. package/dist/generator/emit-shared-typescript-typed.js.map +1 -1
  14. package/dist/generator/emit-straightline-typed-typescript.d.ts.map +1 -1
  15. package/dist/generator/emit-straightline-typed-typescript.js +3 -43
  16. package/dist/generator/emit-straightline-typed-typescript.js.map +1 -1
  17. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  18. package/dist/generator/emit-typed-native-go.js +104 -87
  19. package/dist/generator/emit-typed-native-go.js.map +1 -1
  20. package/dist/generator/emit-typed-native-rust.d.ts +1 -1
  21. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  22. package/dist/generator/emit-typed-native-rust.js +426 -290
  23. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  24. package/dist/generator/typed.d.ts +1 -25
  25. package/dist/generator/typed.d.ts.map +1 -1
  26. package/dist/generator/typed.js +0 -31
  27. package/dist/generator/typed.js.map +1 -1
  28. package/dist/lowering.d.ts.map +1 -1
  29. package/dist/lowering.js +10 -3
  30. package/dist/lowering.js.map +1 -1
  31. package/dist/runtime.d.ts +1 -1
  32. package/dist/runtime.d.ts.map +1 -1
  33. package/dist/runtime.js +1 -1
  34. package/dist/runtime.js.map +1 -1
  35. package/dist/spec-versions.d.ts +1 -1
  36. package/dist/spec-versions.js +1 -1
  37. package/dist/spec-versions.js.map +1 -1
  38. package/dist/type-gate.d.ts +13 -1
  39. package/dist/type-gate.d.ts.map +1 -1
  40. package/dist/type-gate.js +29 -2
  41. package/dist/type-gate.js.map +1 -1
  42. package/package.json +2 -2
@@ -2,13 +2,13 @@ import { entryPortOrder, GeneratorFailure } from "./core.js";
2
2
  import { mapTransformExpr, isControlGate, mapNodeElemIsOpaqueWire, nodeWirePassthrough } from "../behavior.js";
3
3
  import { rustStraightlineInternals } from "./emit-shared-rust.js";
4
4
  import { rustTypedInternals } from "./emit-shared-rust-typed.js";
5
- import { buildTypePlan, deriveTypeRef, findDecl, guardedMapIntoIsCoverable, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
5
+ import { buildTypePlan, deriveTypeRef, findDecl, inputPortIsOptional, inputPortTypeRef } from "./typed.js";
6
6
  import { concurrencyPlan, execPlan, analyzeSequentialOps, opsLiteralOf, classifyExpr, nodeNarrowedPaths } from "./straightline.js";
7
7
  import { NativeExprCompiler } from "./native-expr.js";
8
8
  import { buildAsyncPlans } from "./async-plan.js";
9
9
  import { buildDeBoxPlan, buildWirePlan, notationOfRef } from "./emit-shared-debox.js";
10
10
  const { sanitize, rustStrLit } = rustStraightlineInternals;
11
- const { typeRefIsCopy, rustFieldName, renderTypeRef, typedCell, typedFieldAccess, serializeTyped, emitTypeDecls, emitDefaults, emitSerializers, emitTypedValue, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, materializeExpr, } = rustTypedInternals;
11
+ const { typeRefIsCopy, rustFieldName, renderTypeRef, typedCell, typedFieldAccess, serializeTyped, emitTypeDecls, emitDefaults, emitSerializers, emitTypedValue, rustCellRead, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, materializeExpr, } = rustTypedInternals;
12
12
  /** rustErr — build the LOCAL concrete error value for a behavior/plan failure on the covered read
13
13
  * plane (runtime-free). The covered module declares a local `BehaviorError` (see emitBehaviorErrorType);
14
14
  * the runner returns `Result<_, BehaviorError>` over THAT local type. This REPLACES the old
@@ -115,12 +115,12 @@ fn op_failed(node: &str, policy: &str, e: BehaviorError) -> BehaviorError {
115
115
  }
116
116
  }
117
117
 
118
- // de_type_mismatch / de_missing_field / de_overflow — the de-box mismatch failures the generated decode
118
+ // de_type_mismatch / de_missing_field — the de-box mismatch failures the generated decode
119
119
  // produces (scp-error.md "The Error Value"). Codes are byte-equal to the runtime outType check
120
120
  // (TYPE_MISMATCH / MISSING_PROP) so the covered read stays equivalent to run_behavior; detail.kind
121
- // distinguishes typeMismatch / missingField / overflow.
121
+ // distinguishes typeMismatch / missingField.
122
122
  #[allow(dead_code)]
123
- fn de_type_mismatch(model: &str, field: &str, expected: &str, actual_wire: String, raw: String) -> BehaviorError {
123
+ fn de_type_mismatch(model: &str, field: &str, expected: &str, actual_wire: &str, raw: Cow<'static, str>) -> BehaviorError {
124
124
  BehaviorError::with_detail(
125
125
  "TYPE_MISMATCH",
126
126
  format!("node '{model}': {field}: expected {expected}, got {actual_wire}"),
@@ -129,8 +129,8 @@ fn de_type_mismatch(model: &str, field: &str, expected: &str, actual_wire: Strin
129
129
  model: Some(model.to_string()),
130
130
  field: Some(field.to_string()),
131
131
  expected_type: Some(expected.to_string()),
132
- actual_wire_type: Some(actual_wire),
133
- raw_value: Some(raw),
132
+ actual_wire_type: Some(actual_wire.to_string()),
133
+ raw_value: Some(raw.into_owned()),
134
134
  context: std::collections::BTreeMap::new(),
135
135
  },
136
136
  )
@@ -151,24 +151,6 @@ fn de_missing_field(model: &str, field: &str, expected: &str) -> BehaviorError {
151
151
  context: std::collections::BTreeMap::new(),
152
152
  },
153
153
  )
154
- }
155
-
156
- #[allow(dead_code)]
157
- fn de_overflow(model: &str, field: &str, expected: &str, actual_wire: String, raw: String) -> BehaviorError {
158
- let message = format!("node '{model}': {field}: {raw} is outside the range of {expected}");
159
- BehaviorError::with_detail(
160
- "TYPE_MISMATCH",
161
- message,
162
- ErrorDetail {
163
- kind: Some(ErrorKind::Overflow),
164
- model: Some(model.to_string()),
165
- field: Some(field.to_string()),
166
- expected_type: Some(expected.to_string()),
167
- actual_wire_type: Some(actual_wire),
168
- raw_value: Some(raw),
169
- context: std::collections::BTreeMap::new(),
170
- },
171
- )
172
154
  }`;
173
155
  }
174
156
  /** emitBehaviorErrorType — the FULL local error layer (type defs THEN constructors) baked into the covered
@@ -207,7 +189,7 @@ function rustPayloadRow(entries) {
207
189
  * handler contract; the aligned result is a `WireValue::List` the runner reads via its `.items`.
208
190
  */
209
191
  function rustPayloadBatch(itemsExpr) {
210
- return `WireRow { entries: vec![("items".to_string(), WireValue::List(WireList { items: ${itemsExpr} }))] }`;
192
+ return `WireRow { entries: vec![(Cow::Borrowed("items"), WireValue::List(WireList { items: ${itemsExpr} }))] }`;
211
193
  }
212
194
  /** rustListItems — extract the aligned per-element wires (a `Vec<WireValue>`) from a batched/fanout transport
213
195
  * result (a `WireValue::List`); a non-list result yields an empty Vec → caught by the alignment length check. */
@@ -219,7 +201,7 @@ function rustListItems(wvExpr) {
219
201
  // A covered record read returns the consumer's WIRE (a value implementing WireRow), and the generated
220
202
  // decode probes it per field from the declared type. The consumer supplies variant classification (a
221
203
  // probe reports the producer's own wire tag as a free string); the generated code owns strictness —
222
- // required/optional, present/absent, error assembly, fail-closed. The seam stays native: Probe/NumProbe
204
+ // required/optional, present/absent, error assembly, fail-closed. The seam stays native: Probe
223
205
  // are concrete enums and WireRow/WireList are monomorphized via mutual associated types (Row/List), so no
224
206
  // boxed Value / dyn / Box crosses the boundary.
225
207
  /** emitRustProbeWireTypes — the once-per-module probe enums + the BC-OWNED concrete wire types + their
@@ -227,39 +209,40 @@ function rustListItems(wvExpr) {
227
209
  * result the consumer's SINGLE op-agnostic transport builds and returns; the consumer implements NOTHING
228
210
  * over it (no trait, no probe protocol). The generated inline de-box reads it via these inherent methods —
229
211
  * static typed extraction lowers the generic result to the covered plane's typed values immediately, so no
230
- * dynamic value crosses the covered/hot plane (bc#87). Numbers ride as raw text so BC owns overflow. */
212
+ * dynamic value crosses the covered/hot plane (bc#87). Numbers ride NATIVE (i64 / f64) — nothing to parse. */
231
213
  function emitRustProbeWireTypes(clone) {
232
214
  // bc#156: WireValue is a port field (Vec<WireValue>) when a `value` input port exists — the ports struct
233
215
  // derives Clone (bc#87 parallel dispatch) and the port init clones the input, so WireValue/WireRow/WireList
234
216
  // must be Clone THEN. A value-free module never clones the wire (return-only), so the derive is omitted to
235
217
  // keep those generated modules byte-identical to pre-#156.
236
218
  const cloneDerive = clone ? "#[derive(Clone)]\n" : "";
237
- return `// Probe<T> / NumProbe — the outcome of classifying one wire attribute against a declared type. Got carries
238
- // the matched value (a NumProbe's raw numeric text, which the de-box parses + range-checks so overflow is
239
- // BC's to detect); actual_wire_type is the producer's own wire tag (S/N/BOOL/M/L/NULL); raw_value is the
240
- // offending value stringified. Concrete enums — no boxed runtime value.
219
+ return `// Probe<T> — the outcome of classifying one wire attribute against a declared type. Got carries
220
+ // the matched value MOVED OUT of the wire (a number arrives already native, so there is nothing to parse
221
+ // and no range check to fail); actual_wire_type is the producer's own wire tag
222
+ // (S/N/BOOL/M/L/NULL), a \`&'static str\` so classifying costs NO allocation; raw_value is the offending
223
+ // value, borrowed when it is a fixed word. Concrete enums — no boxed runtime value.
224
+ //
225
+ // NO CLONE. Classification CONSUMES the wire: the transport's result is an owned local that is dead the
226
+ // moment it is de-boxed, so every string / row / list is MOVED into the typed value. A \`.clone()\` here
227
+ // would deep-copy the whole result set once per node boundary — that is a heap copy of every cell, it
228
+ // scales with node count, and it is what made a generated native read lose to an interpreter. The purity
229
+ // gate rejects \`.clone()\` and per-call \`.to_string()\` in this module; keep it that way.
241
230
  pub enum Probe<T> {
242
231
  Got(T),
243
- Wrong { actual_wire_type: String, raw_value: String },
244
- Null { actual_wire_type: String, raw_value: String },
245
- Absent,
246
- }
247
-
248
- pub enum NumProbe {
249
- Got { raw: String, actual_wire_type: String },
250
- Wrong { actual_wire_type: String, raw_value: String },
251
- Null { actual_wire_type: String, raw_value: String },
232
+ Wrong { actual_wire_type: &'static str, raw_value: Cow<'static, str> },
233
+ Null { actual_wire_type: &'static str, raw_value: Cow<'static, str> },
252
234
  Absent,
253
235
  }
254
236
 
255
237
  // WireValue — the BC-OWNED, BC-GENERATED, self-contained (runtime-free) generic result the consumer's
256
238
  // single op-agnostic transport returns. The consumer BUILDS it as it reads the producer (the raw I/O act)
257
- // — WireValue::Str/Num/Bool/Null/Row/List, or the int()/float() constructors — and implements NOTHING over
258
- // it. Numbers carry raw text (BC parses + range-checks → overflow is BC's to detect). A composite is a
259
- // nested WireRow / WireList. NO trait, NO consumer classification protocol.
239
+ // — WireValue::Str/Int/Float/Bool/Null/Row/List, or the int()/float() constructors — and implements NOTHING
240
+ // over it. Numbers are NATIVE (i64 / f64): the producer's own integer reaches the de-box unparsed. A
241
+ // composite is a nested WireRow / WireList. NO trait, NO consumer classification protocol.
260
242
  ${cloneDerive}pub enum WireValue {
261
- Str(String),
262
- Num(String),
243
+ Str(Cow<'static, str>),
244
+ Int(i64),
245
+ Float(f64),
263
246
  Bool(bool),
264
247
  Null,
265
248
  Row(WireRow),
@@ -267,11 +250,15 @@ ${cloneDerive}pub enum WireValue {
267
250
  }
268
251
 
269
252
  // WireRow / WireList — a wire map (a DynamoDB "M") / wire array (an "L"). Native Vec-backed; the generated
270
- // de-box probes them by declared field / element and owns strictness (required/optional, present/absent,
271
- // error assembly). row/list probes return a BORROW (Probe<&WireRow>/Probe<&WireList>) so nested decode is
272
- // zero-copy — only leaf scalars are cloned into the covered typed struct.
253
+ // de-box drains them by declared field / element and owns strictness (required/optional, present/absent,
254
+ // error assembly).
255
+ //
256
+ // A key is \`Cow<'static, str>\`: the field names BC generates are compile-time constants and ride as
257
+ // \`Cow::Borrowed\` (zero allocation, however many times a payload is built), while a producer-supplied key
258
+ // read at run time rides as \`Cow::Owned\`. The same holds for Str — a generated SQL literal costs
259
+ // nothing per call, a value read off the wire owns its text.
273
260
  ${cloneDerive}pub struct WireRow {
274
- pub entries: Vec<(String, WireValue)>,
261
+ pub entries: Vec<(Cow<'static, str>, WireValue)>,
275
262
  }
276
263
 
277
264
  ${cloneDerive}pub struct WireList {
@@ -279,138 +266,99 @@ ${cloneDerive}pub struct WireList {
279
266
  }
280
267
 
281
268
  impl WireValue {
282
- // constructors the consumer's transport uses to build numeric results (numbers ride as raw text).
269
+ // constructors the consumer's transport uses to build numeric results (i64 / f64, carried natively).
283
270
  pub fn int(n: i64) -> Self {
284
- WireValue::Num(n.to_string())
271
+ WireValue::Int(n)
285
272
  }
286
273
  pub fn float(n: f64) -> Self {
287
- WireValue::Num(n.to_string())
288
- }
289
- // the top result is always present (Some(self)); the field/elem probes share the same classifiers.
290
- pub fn as_string(&self) -> Probe<String> {
291
- probe_string_at(Some(self))
292
- }
293
- pub fn as_number(&self) -> NumProbe {
294
- probe_number_at(Some(self))
295
- }
296
- pub fn as_bool(&self) -> Probe<bool> {
297
- probe_bool_at(Some(self))
298
- }
299
- pub fn as_row(&self) -> Probe<&WireRow> {
300
- probe_row_at(Some(self))
301
- }
302
- pub fn as_list(&self) -> Probe<&WireList> {
303
- probe_list_at(Some(self))
274
+ WireValue::Float(n)
304
275
  }
305
276
  fn tag(&self) -> &'static str {
306
277
  match self {
307
278
  WireValue::Str(_) => "S",
308
- WireValue::Num(_) => "N",
279
+ WireValue::Int(_) | WireValue::Float(_) => "N",
309
280
  WireValue::Bool(_) => "BOOL",
310
281
  WireValue::Null => "NULL",
311
282
  WireValue::Row(_) => "M",
312
283
  WireValue::List(_) => "L",
313
284
  }
314
285
  }
315
- fn raw(&self) -> String {
286
+ // the offending value as text, for a failure detail. CONSUMES the value (the cold path owns it by
287
+ // then), so reporting a wrong string moves it out instead of copying it.
288
+ fn into_raw(self) -> Cow<'static, str> {
316
289
  match self {
317
- WireValue::Str(s) => s.clone(),
318
- WireValue::Num(s) => s.clone(),
319
- WireValue::Bool(b) => b.to_string(),
320
- WireValue::Null => "null".to_string(),
321
- WireValue::Row(_) | WireValue::List(_) => "[composite]".to_string(),
290
+ WireValue::Str(s) => s,
291
+ WireValue::Int(n) => Cow::Owned(n.to_string()),
292
+ WireValue::Float(f) => Cow::Owned(f.to_string()),
293
+ WireValue::Bool(b) => Cow::Owned(b.to_string()),
294
+ WireValue::Null => Cow::Borrowed("null"),
295
+ WireValue::Row(_) | WireValue::List(_) => Cow::Borrowed("[composite]"),
322
296
  }
323
297
  }
324
298
  }
325
299
 
326
300
  impl WireRow {
327
- fn get(&self, field: &str) -> Option<&WireValue> {
328
- self.entries.iter().find(|(k, _)| k.as_str() == field).map(|(_, v)| v)
329
- }
330
- pub fn keys(&self) -> Vec<String> {
331
- self.entries.iter().map(|(k, _)| k.clone()).collect()
332
- }
333
- pub fn probe_string(&self, field: &str) -> Probe<String> {
334
- probe_string_at(self.get(field))
335
- }
336
- pub fn probe_number(&self, field: &str) -> NumProbe {
337
- probe_number_at(self.get(field))
338
- }
339
- pub fn probe_bool(&self, field: &str) -> Probe<bool> {
340
- probe_bool_at(self.get(field))
341
- }
342
- pub fn probe_row(&self, field: &str) -> Probe<&WireRow> {
343
- probe_row_at(self.get(field))
344
- }
345
- pub fn probe_list(&self, field: &str) -> Probe<&WireList> {
346
- probe_list_at(self.get(field))
301
+ // Move the value at \`field\` OUT of the row (or None when the producer did not send it). The de-box
302
+ // reads each declared field exactly once, so taking is always right — and it is what keeps a cell
303
+ // from being copied: the String travels from the wire into the typed struct without a heap copy.
304
+ // Undeclared extras are simply left behind with the row.
305
+ pub fn take(&mut self, field: &str) -> Option<WireValue> {
306
+ self.entries.iter().position(|(k, _)| k == field).map(|i| self.entries.swap_remove(i).1)
347
307
  }
348
308
  }
349
309
 
350
- impl WireList {
351
- pub fn len(&self) -> usize {
352
- self.items.len()
353
- }
354
- pub fn is_empty(&self) -> bool {
355
- self.items.is_empty()
356
- }
357
- pub fn elem_string(&self, i: usize) -> Probe<String> {
358
- probe_string_at(self.items.get(i))
359
- }
360
- pub fn elem_number(&self, i: usize) -> NumProbe {
361
- probe_number_at(self.items.get(i))
362
- }
363
- pub fn elem_bool(&self, i: usize) -> Probe<bool> {
364
- probe_bool_at(self.items.get(i))
365
- }
366
- pub fn elem_row(&self, i: usize) -> Probe<&WireRow> {
367
- probe_row_at(self.items.get(i))
368
- }
369
- pub fn elem_list(&self, i: usize) -> Probe<&WireList> {
370
- probe_list_at(self.items.get(i))
310
+ // the ONE classifier per kind, over an OWNED Option<WireValue> (None = absent attribute/element). The
311
+ // BC-owned WireValue variant IS the wire tag — no consumer classification. Each takes the value BY VALUE
312
+ // and hands the match MOVED OUT: de-boxing a result never copies a cell, a row, or a list.
313
+ pub fn probe_string_at(v: Option<WireValue>) -> Probe<Cow<'static, str>> {
314
+ match v {
315
+ None => Probe::Absent,
316
+ Some(WireValue::Str(s)) => Probe::Got(s),
317
+ Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
318
+ Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
371
319
  }
372
320
  }
373
-
374
- // the ONE classifier per kind, over an Option<&WireValue> (None = absent attribute/element). The BC-owned
375
- // WireValue variant IS the wire tag — no consumer classification.
376
- fn probe_string_at(v: Option<&WireValue>) -> Probe<String> {
321
+ pub fn probe_int_at(v: Option<WireValue>) -> Probe<i64> {
377
322
  match v {
378
323
  None => Probe::Absent,
379
- Some(WireValue::Str(s)) => Probe::Got(s.clone()),
380
- Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL".to_string(), raw_value: "null".to_string() },
381
- Some(o) => Probe::Wrong { actual_wire_type: o.tag().to_string(), raw_value: o.raw() },
324
+ Some(WireValue::Int(n)) => Probe::Got(n),
325
+ Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
326
+ Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
382
327
  }
383
328
  }
384
- fn probe_number_at(v: Option<&WireValue>) -> NumProbe {
329
+ // a float position accepts an int and widens it — the same widening the interpreter's outType check does,
330
+ // so the generated read and run_behavior agree on an integral value in a float field.
331
+ pub fn probe_float_at(v: Option<WireValue>) -> Probe<f64> {
385
332
  match v {
386
- None => NumProbe::Absent,
387
- Some(WireValue::Num(s)) => NumProbe::Got { raw: s.clone(), actual_wire_type: "N".to_string() },
388
- Some(WireValue::Null) => NumProbe::Null { actual_wire_type: "NULL".to_string(), raw_value: "null".to_string() },
389
- Some(o) => NumProbe::Wrong { actual_wire_type: o.tag().to_string(), raw_value: o.raw() },
333
+ None => Probe::Absent,
334
+ Some(WireValue::Float(f)) => Probe::Got(f),
335
+ Some(WireValue::Int(n)) => Probe::Got(n as f64),
336
+ Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
337
+ Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
390
338
  }
391
339
  }
392
- fn probe_bool_at(v: Option<&WireValue>) -> Probe<bool> {
340
+ pub fn probe_bool_at(v: Option<WireValue>) -> Probe<bool> {
393
341
  match v {
394
342
  None => Probe::Absent,
395
- Some(WireValue::Bool(b)) => Probe::Got(*b),
396
- Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL".to_string(), raw_value: "null".to_string() },
397
- Some(o) => Probe::Wrong { actual_wire_type: o.tag().to_string(), raw_value: o.raw() },
343
+ Some(WireValue::Bool(b)) => Probe::Got(b),
344
+ Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
345
+ Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
398
346
  }
399
347
  }
400
- fn probe_row_at(v: Option<&WireValue>) -> Probe<&WireRow> {
348
+ pub fn probe_row_at(v: Option<WireValue>) -> Probe<WireRow> {
401
349
  match v {
402
350
  None => Probe::Absent,
403
351
  Some(WireValue::Row(r)) => Probe::Got(r),
404
- Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL".to_string(), raw_value: "null".to_string() },
405
- Some(o) => Probe::Wrong { actual_wire_type: o.tag().to_string(), raw_value: o.raw() },
352
+ Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
353
+ Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
406
354
  }
407
355
  }
408
- fn probe_list_at(v: Option<&WireValue>) -> Probe<&WireList> {
356
+ pub fn probe_list_at(v: Option<WireValue>) -> Probe<WireList> {
409
357
  match v {
410
358
  None => Probe::Absent,
411
359
  Some(WireValue::List(l)) => Probe::Got(l),
412
- Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL".to_string(), raw_value: "null".to_string() },
413
- Some(o) => Probe::Wrong { actual_wire_type: o.tag().to_string(), raw_value: o.raw() },
360
+ Some(WireValue::Null) => Probe::Null { actual_wire_type: "NULL", raw_value: Cow::Borrowed("null") },
361
+ Some(o) => Probe::Wrong { actual_wire_type: o.tag(), raw_value: o.into_raw() },
414
362
  }
415
363
  }`;
416
364
  }
@@ -424,12 +372,12 @@ fn probe_list_at(v: Option<&WireValue>) -> Probe<&WireList> {
424
372
  * nested collection to a nested loop. A required-position mismatch does `return Err(de_*(...))` (fail
425
373
  * closed, propagating the structured Error Value from the enclosing runner); an optional position
426
374
  * (optDepth>0) maps absent/null to the all-None value. `ctr` hands out unique temp names (`sub2`, `l3`,
427
- * `m4`, `i3`, `k4`) so nested blocks never collide. `idxExpr` is the element index / map-key argument the
428
- * enclosing list / map loop supplies (empty for top / field). Mirrors the interpreter's outType check +
375
+ * `m4`, `e3`, `k4`) so nested blocks never collide. Every position consumes an OWNED value the enclosing
376
+ * position moved out, so the decode copies nothing. Mirrors the interpreter's outType check +
429
377
  * the (now-deleted) per-position decoders, but TOTAL over the grammar (opt(named)/arr(arr)/map(opt)…) and
430
378
  * inlined — the type is baked all the way through by the TS compiler, not the target monomorphizer.
431
379
  */
432
- function renderRustDeBox(plan, srcExpr, ctr, indent, fail, idxExpr = "") {
380
+ function renderRustDeBox(plan, srcExpr, ctr, indent, fail) {
433
381
  const I = indent;
434
382
  const I1 = indent + " ";
435
383
  const id = ctr.n++;
@@ -440,16 +388,17 @@ function renderRustDeBox(plan, srcExpr, ctr, indent, fail, idxExpr = "") {
440
388
  const mismatch = fail(`de_type_mismatch(${ml}, ${fl}, ${nl}, actual_wire_type, raw_value)`);
441
389
  const missing = fail(`de_missing_field(${ml}, ${fl}, ${nl})`);
442
390
  // the probe expression for this node's access + a value-kind suffix (string/number/bool/row/list).
391
+ // Every access hands the classifier an OWNED Option<WireValue>: a top / element / map value is already
392
+ // moved out by the enclosing position, and a field is MOVED OUT of its row by `take`. Nothing borrows,
393
+ // so nothing has to be copied to be kept.
443
394
  const probe = (suffix) => {
444
395
  switch (plan.access.from) {
445
396
  case "top":
446
- return `${srcExpr}.as_${suffix}()`;
447
- case "field":
448
- return `${srcExpr}.probe_${suffix}(${rustStrLit(plan.access.key)})`;
449
397
  case "elem":
450
- return `${srcExpr}.elem_${suffix}(${idxExpr})`;
451
398
  case "mapval":
452
- return `${srcExpr}.probe_${suffix}(${idxExpr})`;
399
+ return `probe_${suffix}_at(Some(${srcExpr}))`;
400
+ case "field":
401
+ return `probe_${suffix}_at(${srcExpr}.take(${rustStrLit(plan.access.key)}))`;
453
402
  }
454
403
  };
455
404
  // wrap the decoded value in optDepth `Some(...)` layers (present ⇒ Some^N(v); absent/null ⇒ None).
@@ -466,30 +415,32 @@ function renderRustDeBox(plan, srcExpr, ctr, indent, fail, idxExpr = "") {
466
415
  : `${I1}Probe::Wrong { actual_wire_type, raw_value }\n${I1}| Probe::Null { actual_wire_type, raw_value } => ${mismatch},\n${I1}Probe::Absent => ${missing},`;
467
416
  if (plan.k === "scalar") {
468
417
  if (plan.scalar === "int" || plan.scalar === "float") {
469
- const rustT = plan.scalar === "int" ? "i64" : "f64";
470
- const numArms = opt
471
- ? `${I1}NumProbe::Wrong { actual_wire_type, raw_value } => ${mismatch},\n${I1}NumProbe::Null { .. } | NumProbe::Absent => None,`
472
- : `${I1}NumProbe::Wrong { actual_wire_type, raw_value }\n${I1}| NumProbe::Null { actual_wire_type, raw_value } => ${mismatch},\n${I1}NumProbe::Absent => ${missing},`;
473
- return `match ${probe("number")} {
474
- ${I1}NumProbe::Got { raw, actual_wire_type } => match raw.parse::<${rustT}>() {
475
- ${I1} Ok(n) => ${wrapSome("n")},
476
- ${I1} Err(_) => ${fail(`de_overflow(${ml}, ${fl}, ${nl}, actual_wire_type, raw)`)},
477
- ${I1}},
478
- ${numArms}
418
+ return `match ${probe(plan.scalar)} {
419
+ ${I1}Probe::Got(v) => ${wrapSome("v")},
420
+ ${probeArms}
479
421
  ${I}}`;
480
422
  }
481
- const meth = plan.scalar === "string" ? "string" : "bool";
482
- return `match ${probe(meth)} {
423
+ if (plan.scalar === "string") {
424
+ // Cow → the struct's owned String: `into_owned()` on the producer's own text is a MOVE, not a copy.
425
+ return `match ${probe("string")} {
426
+ ${I1}Probe::Got(v) => ${wrapSome("v.into_owned()")},
427
+ ${probeArms}
428
+ ${I}}`;
429
+ }
430
+ return `match ${probe("bool")} {
483
431
  ${I1}Probe::Got(v) => ${wrapSome("v")},
484
432
  ${probeArms}
485
433
  ${I}}`;
486
434
  }
487
435
  if (plan.k === "record") {
436
+ // Each declared field is MOVED OUT of the row by `take` (see the wire seam) — the row is consumed field
437
+ // by field into the typed struct. `mut` only when there is a field to take (an empty record takes none).
438
+ const bind = plan.fields.length > 0 ? `mut sub${id}` : `sub${id}`;
488
439
  const fieldInits = plan.fields
489
440
  .map((f) => `${I1} ${rustFieldName(f.name)}: ${renderRustDeBox(f.plan, `sub${id}`, ctr, `${I1} `, fail)},`)
490
441
  .join("\n");
491
442
  return `match ${probe("row")} {
492
- ${I1}Probe::Got(sub${id}) => ${wrapSome(`${plan.typeName} {
443
+ ${I1}Probe::Got(${bind}) => ${wrapSome(`${plan.typeName} {
493
444
  ${fieldInits}
494
445
  ${I1}}`)},
495
446
  ${probeArms}
@@ -497,27 +448,28 @@ ${I}}`;
497
448
  }
498
449
  if (plan.k === "list" && plan.elem.k === "value") {
499
450
  // bc#164: `{arr:"value"}` output-passthrough — the result wire is a list of OPAQUE values; validate the
500
- // container is a list, then take its items AS-IS (clone, no per-element de-box / no re-box). The elements
451
+ // container is a list, then MOVE its items across as-is (no per-element de-box / no re-box). The elements
501
452
  // stay `WireValue` so a downstream op-agnostic leaf consumes them with no per-op `typed→Value` re-box.
502
453
  return `match ${probe("list")} {
503
- ${I1}Probe::Got(l${id}) => ${wrapSome(`l${id}.items.clone()`)},
454
+ ${I1}Probe::Got(l${id}) => ${wrapSome(`l${id}.items`)},
504
455
  ${probeArms}
505
456
  ${I}}`;
506
457
  }
507
458
  if (plan.k === "value") {
508
459
  // bc#164: a bare `value` output-passthrough (top position) — the whole result wire crosses UNCHANGED
509
- // (clone), no probe, no de-box. (elem-position `value` is handled by the list branch above; field/mapval
460
+ // (moved), no probe, no de-box. (elem-position `value` is handled by the list branch above; field/mapval
510
461
  // never carry `value` — buildWirePlan does not relax those positions.)
511
462
  if (plan.access.from !== "top")
512
463
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust de-box: a 'value' node at a non-top position (${plan.access.from}) is not a legal passthrough shape`);
513
- return `${srcExpr}.clone()`;
464
+ return srcExpr;
514
465
  }
515
466
  if (plan.k === "list") {
516
- const elemExpr = renderRustDeBox(plan.elem, `l${id}`, ctr, `${I1} `, fail, `i${id}`);
467
+ // Consume the list: each element is MOVED into the element de-box, so a row never gets copied to be read.
468
+ const elemExpr = renderRustDeBox(plan.elem, `e${id}`, ctr, `${I1} `, fail);
517
469
  return `match ${probe("list")} {
518
470
  ${I1}Probe::Got(l${id}) => ${wrapSome(`{
519
- ${I1} let mut acc${id} = Vec::with_capacity(l${id}.len());
520
- ${I1} for i${id} in 0..l${id}.len() {
471
+ ${I1} let mut acc${id} = Vec::with_capacity(l${id}.items.len());
472
+ ${I1} for e${id} in l${id}.items {
521
473
  ${I1} acc${id}.push(${elemExpr});
522
474
  ${I1} }
523
475
  ${I1} acc${id}
@@ -525,14 +477,15 @@ ${I1}}`)},
525
477
  ${probeArms}
526
478
  ${I}}`;
527
479
  }
528
- // map(V): the wire value is a producer map (a DynamoDB "M"); enumerate its keys, decode each value as V.
529
- const valExpr = renderRustDeBox(plan.value, `m${id}`, ctr, `${I1} `, fail, `&k${id}`);
480
+ // map(V): the wire value is a producer map (a DynamoDB "M"); consume its entries, decode each value as V.
481
+ // Both halves move: the key becomes the BTreeMap's owned String, the value goes straight into the de-box.
482
+ const valExpr = renderRustDeBox(plan.value, `mv${id}`, ctr, `${I1} `, fail);
530
483
  return `match ${probe("row")} {
531
484
  ${I1}Probe::Got(m${id}) => ${wrapSome(`{
532
485
  ${I1} let mut acc${id} = std::collections::BTreeMap::new();
533
- ${I1} for k${id} in m${id}.keys() {
486
+ ${I1} for (k${id}, mv${id}) in m${id}.entries {
534
487
  ${I1} let v${id} = ${valExpr};
535
- ${I1} acc${id}.insert(k${id}, v${id});
488
+ ${I1} acc${id}.insert(k${id}.into_owned(), v${id});
536
489
  ${I1} }
537
490
  ${I1} acc${id}
538
491
  ${I1}}`)},
@@ -558,16 +511,31 @@ ${I}}`;
558
511
  * pass-through (null stays null), the write-side mirror of the read de-box's opt (`wrapSome`).
559
512
  * `depth` names the per-element closure binding uniquely across nesting.
560
513
  */
514
+ /** rustStaticStrLit — the bare `&'static str` behind a RENDERED string literal (`"…".to_string()`), or
515
+ * undefined when the expression is a computed String. The ONE unpeel: a literal that is about to become
516
+ * a wire value or a concat part never needs the owned String the expression renderer produced. */
517
+ function rustStaticStrLit(expr) {
518
+ const m = /^(".*")\.to_string\(\)$/.exec(expr);
519
+ return m ? m[1] : undefined;
520
+ }
521
+ /** rustStrWireBox — a string crossing INTO the wire. A value fixed at generation time rides as
522
+ * `Cow::Borrowed` (the SQL text / a literal port costs NO allocation, however many times the payload is
523
+ * built); anything else converts with `.into()`, which MOVES an owned String rather than copying it. */
524
+ function rustStrWireBox(src) {
525
+ const lit = rustStaticStrLit(src);
526
+ return lit !== undefined ? `WireValue::Str(Cow::Borrowed(${lit}))` : `WireValue::Str(${src}.into())`;
527
+ }
561
528
  /** rustScalarWireCtor — the WireValue constructor for a portable scalar (the ONE mapping; used both as
562
- * `Ctor(x)` and, point-free, as a `.map(Ctor)` argument in the clippy-clean list box). */
529
+ * `Ctor(x)` and, point-free, as a `.map(Ctor)` argument in the clippy-clean list box). A string does NOT
530
+ * come through here — it goes through {@link rustStrWireBox}, which keeps a literal borrowed. */
563
531
  function rustScalarWireCtor(scalar) {
564
532
  switch (scalar) {
565
533
  case "string":
566
534
  return "WireValue::Str";
567
535
  case "int":
568
- return "WireValue::int";
536
+ return "WireValue::Int";
569
537
  case "float":
570
- return "WireValue::float";
538
+ return "WireValue::Float";
571
539
  case "bool":
572
540
  return "WireValue::Bool";
573
541
  default:
@@ -585,11 +553,13 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
585
553
  // strip the source's OWN outer parens before wrapping in the ctor — `WireValue::Str(("a"+x))` is
586
554
  // `clippy::double_parens`; `WireValue::Str("a"+x)` is clean (the ctor call already parenthesizes).
587
555
  if (plan.k === "scalar")
588
- return `${rustScalarWireCtor(plan.scalar)}(${rustStripOuterParens(baseSrc)})`;
556
+ return plan.scalar === "string"
557
+ ? rustStrWireBox(rustStripOuterParens(baseSrc))
558
+ : `${rustScalarWireCtor(plan.scalar)}(${rustStripOuterParens(baseSrc)})`;
589
559
  if (plan.k === "record") {
590
560
  // typed struct → wire map: box each declared field off its native struct field (moving it out of the owned
591
561
  // srcExpr — no probe), assemble a WireRow of (name, WireValue) in declared-field order.
592
- const entries = plan.fields.map((f) => `(${rustStrLit(f.name)}.to_string(), ${renderRustWireBox(f.plan, `${baseSrc}.${rustFieldName(f.name)}`, depth + 1)})`);
562
+ const entries = plan.fields.map((f) => `(Cow::Borrowed(${rustStrLit(f.name)}), ${renderRustWireBox(f.plan, `${baseSrc}.${rustFieldName(f.name)}`, depth + 1)})`);
593
563
  return `WireValue::Row(WireRow { entries: vec![${entries.join(", ")}] })`;
594
564
  }
595
565
  if (plan.k === "list") {
@@ -601,7 +571,7 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
601
571
  // (`.map(WireValue::Str)` not `.map(|e| WireValue::Str(e))` — `clippy::redundant_closure`).
602
572
  if (elemBox === e)
603
573
  return `WireValue::List(WireList { items: ${baseSrc} })`;
604
- const scalarCtor = plan.elem.optDepth === 0 && plan.elem.k === "scalar" ? rustScalarWireCtor(plan.elem.scalar) : undefined;
574
+ const scalarCtor = plan.elem.optDepth === 0 && plan.elem.k === "scalar" && plan.elem.scalar !== "string" ? rustScalarWireCtor(plan.elem.scalar) : undefined;
605
575
  const mapper = scalarCtor !== undefined ? scalarCtor : `|${e}| ${elemBox}`;
606
576
  return `WireValue::List(WireList { items: ${baseSrc}.into_iter().map(${mapper}).collect() })`;
607
577
  }
@@ -610,7 +580,8 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
610
580
  // declared map<V> is the dynamic-keyed twin of a record — the READ side de-boxes a WireRow INTO map<V>
611
581
  // the SAME way, emit-shared-debox `mapval`). Box EACH entry's VALUE recursively (box-once, no round-trip);
612
582
  // keys carried as dynamic strings. BTreeMap<String,_> iterates in ascending key order, so the WireRow is
613
- // deterministic (matching the rust typed map's canonical key order).
583
+ // deterministic (matching the rust typed map's canonical key order). A declared map's keys are runtime
584
+ // data, so they cross as owned wire keys (unlike a generated field name, which stays borrowed).
614
585
  const k = `k${depth}`;
615
586
  const v = `v${depth}`;
616
587
  const valBox = renderRustWireBox(plan.value, v, depth + 1);
@@ -618,8 +589,8 @@ function renderRustWireBox(plan, srcExpr, depth = 0) {
618
589
  // collect the pairs directly (clippy rejects `.map(|(k, v)| (k, v))` as an identity map). Same rule
619
590
  // as the list branch's identity short-circuit above — box-once, no re-wrap.
620
591
  if (valBox === v)
621
- return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().collect() })`;
622
- return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (${k}, ${valBox})).collect() })`;
592
+ return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (Cow::Owned(${k}), ${v})).collect() })`;
593
+ return `WireValue::Row(WireRow { entries: ${baseSrc}.into_iter().map(|(${k}, ${v})| (Cow::Owned(${k}), ${valBox})).collect() })`;
623
594
  }
624
595
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust wire box: unexpected plan kind '${plan.k}'`);
625
596
  };
@@ -678,6 +649,11 @@ function rustOwn(guard, ownArrays) {
678
649
  return `${expr}.clone()`;
679
650
  };
680
651
  }
652
+ /** rustMoved — the ownership renderer for a head that was MOVED out of its cell: the value is already
653
+ * owned, so the leaf adds nothing. (rustOwn's clone/deref exist only because a borrow cannot be kept.) */
654
+ function rustMoved() {
655
+ return (expr) => expr;
656
+ }
681
657
  /** nativeResolveHead — the ONE ref-head resolver the runtime-free native-expr compiler reads (cond `if`/
682
658
  * branches, a map/fanout `when` guard, AND a port). A head is a `$as` element binding, a prior body node's
683
659
  * typed cell (behind a RefCell borrow guard), or an input port (a by-value struct field). #139: the input
@@ -690,11 +666,17 @@ function nativeResolveHead(comp, plan, typedNodes, isPrior, opts) {
690
666
  }
691
667
  if (isPrior(head)) {
692
668
  const ref = typedNodes.get(head);
669
+ // This node's result has exactly one reader (movableCells) — take it out of the cell instead of
670
+ // copying it. The wire enum has no Default, so a `value` cell swaps in the null wire to move.
671
+ if (opts?.moveHeads?.has(head) === true)
672
+ return { expr: rustCellRead(head, ref, false, opts.moveHeads), ref, own: rustMoved() };
693
673
  return { expr: `${typedCell(head)}.borrow()`, ref, own: rustOwn(true, ownArrays) };
694
674
  }
695
675
  const ref = inputPortTypeRef(comp.inputPorts?.[head], plan);
696
676
  if (ref === undefined)
697
677
  return null;
678
+ if (opts?.moveHeads?.has(head) === true)
679
+ return { expr: rustFieldName(head), ref, own: rustMoved() };
698
680
  // #192: the input port is a positional PARAMETER of the entry (box removed) — read it by param name
699
681
  // (= rustFieldName(port), the single input-ref name source; same owned-value semantics as `in_.field`).
700
682
  return { expr: rustFieldName(head), ref, own: rustOwn(false, ownArrays) };
@@ -808,17 +790,14 @@ function makeRustExprBackend(resolveHead, plan) {
808
790
  // native String concat via a `[&str; N].concat()` — a string-literal part (`"…".to_string()`) is
809
791
  // used as the bare `"…"` &str; any other owned String is borrowed with `.as_str()`. This shape is
810
792
  // clippy-clean (no to_string_in_format_args / single_char_push_str / unnecessary_to_string).
811
- const refs = parts.map((p) => {
812
- const m = /^(".*")\.to_string\(\)$/.exec(p);
813
- return m ? m[1] : `(${p}).as_str()`;
814
- });
793
+ const refs = parts.map((p) => rustStaticStrLit(p) ?? `(${p}).as_str()`);
815
794
  return `[${refs.join(", ")}].concat()`;
816
795
  },
817
796
  notOp: (a) => `(!${a})`,
818
797
  structLit: (name, inits) => `${name} { ${inits.map((i) => `${rustFieldName(i.field)}: ${i.expr}`).join(", ")} }`,
819
798
  arrLit: (elemTy, items) => `{ let __v: Vec<${elemTy}> = vec![${items.join(", ")}]; __v }`,
820
799
  // #209: the opaque wire built directly from an inline composite literal at a `value` port.
821
- wireRowLit: (entries) => `WireValue::Row(WireRow { entries: vec![${entries.map((e) => `(${rustStrLit(e.key)}.to_string(), ${e.expr})`).join(", ")}] })`,
800
+ wireRowLit: (entries) => `WireValue::Row(WireRow { entries: vec![${entries.map((e) => `(Cow::Borrowed(${rustStrLit(e.key)}), ${e.expr})`).join(", ")}] })`,
822
801
  wireListLit: (items) => `WireValue::List(WireList { items: vec![${items.join(", ")}] })`,
823
802
  // #209: a string-keyed map literal — a BTreeMap built from statically known entries (key order is the
824
803
  // BTreeMap's own code-point order, matching the canonical serialization).
@@ -1254,15 +1233,13 @@ function coveredMapNode(n, bodyIds, comp) {
1254
1233
  if (n === null || typeof n !== "object" || !("map" in n))
1255
1234
  return false;
1256
1235
  const m = n.map;
1257
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182: a
1258
- // guarded map WITH `into` is covered when the guard-skipped element has a well-defined skip value — the
1259
- // into field is OPT (skip → None, #177) OR relationKind:connection (skip → the empty connection
1260
- // {items:[],cursor:null}, #182). Byte-equal to run_behavior applyInto (opt-into → null / connection-into
1261
- // → unproducedValue("connection")). A REQUIRED non-connection into → run_behavior FAILS MISSING_PROP on a
1262
- // skipped element, so fail-close is byte-equal. over element type must be statically resolvable: prior-node
1263
- // arr field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1264
- if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
1265
- return false;
1236
+ // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182/#232:
1237
+ // a `map...into` ALWAYS has a well-defined unproduced value for the into field — OPT (unproduced → None,
1238
+ // #177) OR relationKind:connection (unproduced → the empty connection {items:[],cursor:null}, #182).
1239
+ // Byte-equal to run_behavior applyInto. The type gate (`mapIntoHoldsUnproduced`, run for every component
1240
+ // at the codegen entry) rejects anything else BEFORE any emitter sees it (#232). over element type must be
1241
+ // statically resolvable: prior-node arr field, or an input array port carrying `elemType` (BC does not
1242
+ // infer — consumer-interface C3).
1266
1243
  if (m.relationKind !== undefined && m.relationKind !== "connection")
1267
1244
  return false;
1268
1245
  // A map node must carry an outType (its ELEMENT type per the recorder SoT — authoring.ts recordMap
@@ -1519,34 +1496,82 @@ function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected,
1519
1496
  if (c.stmts.length > 0)
1520
1497
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): port '${pn}' ${JSON.stringify(expr)} lowers to a FALLIBLE expression (INT_OVERFLOW / NAN_OR_INF / MOD_ZERO / PRECISION_LOSS) — statements with an early error-return, which a transport payload literal cannot host. Use a non-fallible port expression.`);
1521
1498
  const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), c.expr);
1522
- return `(${rustStrLit(pn)}.to_string(), ${boxed})`;
1499
+ return `(Cow::Borrowed(${rustStrLit(pn)}), ${boxed})`;
1523
1500
  }
1524
1501
  // ── the combined runner (STRUCT-returning; INLINE sequential; native ports in; concrete row out) ──
1525
1502
  function rustScalar(s) {
1526
1503
  return s === "string" ? "String" : s === "int" ? "i64" : s === "float" ? "f64" : "bool";
1527
1504
  }
1505
+ /**
1506
+ * movableRefs — the values (a body node's RESULT, or an input port) with exactly ONE reader in the whole
1507
+ * component, so that reader can take the value by MOVE instead of copying it.
1508
+ *
1509
+ * Handing a prior node's result to a downstream leaf is where a result set would otherwise be deep-copied:
1510
+ * a `Vec<WireValue>` clone re-allocates every string in every row, once per node boundary. Counting the
1511
+ * readers statically says when copying is unnecessary — which, in a read chain, is the normal case.
1512
+ *
1513
+ * A read is counted from the ONE place a value can be referenced: a `{ref}` / `{refOpt}` path whose head
1514
+ * names a body node or an input port (ports, guards, map sources, the output value), plus the parent read
1515
+ * a bindField performs. Two reads (or none) ⇒ not movable. A read nested inside a `map` / `fanout` element
1516
+ * body runs once PER ELEMENT, so it counts as many — a single textual site is not a single read there.
1517
+ */
1518
+ function movableRefs(comp) {
1519
+ const counts = new Map();
1520
+ const bump = (head, times) => {
1521
+ counts.set(head, (counts.get(head) ?? 0) + times);
1522
+ };
1523
+ const walk = (n, times) => {
1524
+ if (Array.isArray(n)) {
1525
+ for (const e of n)
1526
+ walk(e, times);
1527
+ return;
1528
+ }
1529
+ if (n === null || typeof n !== "object")
1530
+ return;
1531
+ const rec = n;
1532
+ const keys = Object.keys(rec);
1533
+ if (keys.length === 1 && (keys[0] === "ref" || keys[0] === "refOpt")) {
1534
+ const path = rec[keys[0]];
1535
+ if (Array.isArray(path) && typeof path[0] === "string")
1536
+ bump(path[0], times);
1537
+ return;
1538
+ }
1539
+ // an element body repeats: everything under a map / fanout is read once per element.
1540
+ const repeats = times === 1 && ("map" in rec || "fanout" in rec) ? 2 : times;
1541
+ for (const k of keys)
1542
+ walk(rec[k], repeats);
1543
+ };
1544
+ walk(comp.body, 1);
1545
+ walk(comp.output, 1);
1546
+ for (const nd of comp.body) {
1547
+ const cr = nd;
1548
+ if (cr.parent !== undefined && cr.bindField !== undefined)
1549
+ bump(cr.parent, 1);
1550
+ }
1551
+ return new Set([...counts].filter(([, c]) => c === 1).map(([id]) => id));
1552
+ }
1528
1553
  function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1529
1554
  const ep = execPlan(comp);
1530
1555
  const order = ep.order;
1531
- const hasConcurrency = ep.parallelStageOf.size > 0;
1532
1556
  const fn = sanitize(comp.name);
1533
1557
  const isAsync = ap.runnerIsAsync;
1534
- // bc#97: the async runner awaits each async handler at its call site (derived per-node). A real-
1535
- // concurrency stage (bc#87) dispatches handlers from scoped std threads — that mechanism cannot host
1536
- // `.await` (a std thread is not an async task). Fail closed LOUDLY (rather than emit code that won't
1537
- // compile) iff the runner is async AND has a concurrency stage. NOTE: with per-node granularity a
1538
- // consumer CAN keep a concurrency-stage component sync (declare only its OTHER terminals async) — only
1539
- // a component that both concurrency-stages AND awaits is rejected. Async + concurrent-stage (issuing
1540
- // the stage's futures with join!) is a documented follow-up.
1541
- if (isAsync && hasConcurrency) {
1542
- throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native async (bc#97): component '${comp.name}' has a bc#87 real-concurrency stage AND an async terminal handler, but a scoped-std-thread stage cannot host \`.await\`. Async + concurrent-stage (join! over the stage's futures) is a follow-up — declare this component's terminals sync, or split the concurrency stage.`);
1543
- }
1544
1558
  const typedNodes = new Map();
1545
1559
  // #125: control-gate は typeless(typedNodes に載せない)。map ノードは produced-array ref に正規化
1546
1560
  // (recorder SoT の element outType を {arr:element} へラップ / legacy {arr} はそのまま)。
1547
1561
  for (const n of comp.body)
1548
1562
  if (!isControlGate(n))
1549
1563
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
1564
+ // Single-reader results are handed on by MOVE (see movableCells). A parallel stage builds its members'
1565
+ // payloads inside a scoped-thread closure, so a read there is not the plain sequential read the count
1566
+ // assumed — drop every head a stage member reads and let those copy.
1567
+ const moveHeads = movableRefs(comp);
1568
+ for (const [i] of ep.parallelStageOf) {
1569
+ for (const pn of Object.keys(comp.body[i].ports ?? {})) {
1570
+ const e = classifyExpr(comp.body[i].ports[pn]);
1571
+ if (e.kind === "ref")
1572
+ moveHeads.delete(e.path[0]);
1573
+ }
1574
+ }
1550
1575
  // the ops literal comes from the SHARED derivation (opsLiteralOf): a local "read cr.policy / cr.parent"
1551
1576
  // copy silently drops a MAP's / FANOUT's policy and parent (they live under map./fanout.), which would
1552
1577
  // make canSkip — and therefore the produced-aware output — disagree with the go surface on the same IR.
@@ -1570,7 +1595,11 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1570
1595
  lines.push(`// results are typed struct cells; a relation child reads the parent's REAL struct result via`);
1571
1596
  lines.push(`// direct field access (child-present decision from the real parent value — relation /`);
1572
1597
  lines.push(`// connection converge). A real-concurrency stage (bc#87) is static parallel orchestration —`);
1573
- lines.push(`// scoped worker threads (bounded by the static plan.concurrency) call the transport; preflight +`);
1598
+ // #231: the dispatch MECHANISM a stage uses is derived from its members' async-ness (a std thread cannot
1599
+ // host `.await`), so the banner names the one this component actually emits.
1600
+ lines.push([...new Set(ep.parallelStageOf.values())].some((s) => stageAwaits(comp, s, ap))
1601
+ ? `// the stage's futures joined (bounded by the static plan.concurrency) call the transport; preflight +`
1602
+ : `// scoped worker threads (bounded by the static plan.concurrency) call the transport; preflight +`);
1574
1603
  lines.push(`// interpret are committed in ascending index order so the value / op multiset / failure`);
1575
1604
  lines.push(`// precedence byte-match run_behavior. The output is a typed struct/value assembled by struct`);
1576
1605
  lines.push(`// literal + field access — the consumer keeps it native.`);
@@ -1605,7 +1634,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1605
1634
  const i = order[k];
1606
1635
  const stage = ep.parallelStageOf.get(i);
1607
1636
  if (stage !== undefined && stage[0] === i) {
1608
- lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt, leaf));
1637
+ lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt, leaf, ap));
1609
1638
  k += stage.length - 1;
1610
1639
  continue;
1611
1640
  }
@@ -1664,7 +1693,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1664
1693
  }
1665
1694
  }
1666
1695
  const narrowed = nodeNarrowedPaths(comp, node);
1667
- const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1696
+ const fields = portNames.map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, k), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed, moveHeads }));
1668
1697
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1669
1698
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
1670
1699
  // directly (no `.await`). The runner being `async fn` does not force every call site to await.
@@ -1713,8 +1742,8 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1713
1742
  }
1714
1743
  }
1715
1744
  const out = skippable.size > 0
1716
- ? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind, comp.name, "<output>")
1717
- : emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>");
1745
+ ? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind, comp.name, "<output>", moveHeads)
1746
+ : emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>", moveHeads);
1718
1747
  // top-level output that is a bare node-result (not an obj/arr assembly): its honest `ref` must equal the
1719
1748
  // declared component output type, or the emitted `let __out = …; Ok(__out)` return does not compile.
1720
1749
  checkOutputFieldType(comp.name, "<output>", outRef, out.ref, plan);
@@ -1724,21 +1753,36 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1724
1753
  return lines.join("\n");
1725
1754
  }
1726
1755
  /**
1727
- * emitParallelStageArm (bc#87/#94, rust CONCRETE) — EXPLICIT static parallel orchestration for a real-
1728
- * concurrency stage. Reproduces run_plan_parallel's deterministic protocol so the observed value / op
1756
+ * stageAwaits (#231) — the ONE derivation of a real-concurrency stage's dispatch MECHANISM: a std thread
1757
+ * cannot host `.await`, so a stage dispatches by joining its members' futures iff ANY member awaits, and
1758
+ * by scoped std threads otherwise. Read per-node from the SHARED language-agnostic async propagation pass
1759
+ * (async-plan.ts) — the same SSoT the sequential arms consume. A no-dispatch member (cond / pure-expression
1760
+ * map) has no catalog component, so `nodeIsAsync` is false for it and it never flips the mechanism.
1761
+ */
1762
+ function stageAwaits(comp, stage, ap) {
1763
+ return stage.some((i) => ap.nodeIsAsync(comp.body[i].id));
1764
+ }
1765
+ /**
1766
+ * emitParallelStageArm (bc#87/#94/#231, rust CONCRETE) — EXPLICIT static parallel orchestration for a
1767
+ * real-concurrency stage. Reproduces run_plan_parallel's deterministic protocol so the observed value / op
1729
1768
  * multiset / failure precedence byte-match run_behavior:
1730
1769
  * 1. PREFLIGHT (ascending): parent-produced gate + build each member's CONCRETE ports struct.
1731
- * 2. DISPATCH (bounded scoped threads): share `&H` (the concrete trait; `H: Sync`), pull runnable
1732
- * members from a shared atomic cursor in ascending order, call the concrete node_* method. Each
1733
- * concrete row lands in a per-member Mutex slot (None = unknown component).
1770
+ * 2. DISPATCH (bounded — ONE phase, two mechanisms picked by the members' derived async-ness):
1771
+ * - SYNC members: scoped std threads pull runnable members from a shared atomic cursor in ascending
1772
+ * order and call the leaf transport. Each result wire lands in a per-member Mutex slot.
1773
+ * - ASYNC members (#231): a std thread cannot host `.await`, so the stage's FUTURES are joined
1774
+ * instead — one lazily-built future per RUNNABLE member (a skipped member gets no future at all),
1775
+ * driven by a `std::future::poll_fn` scheduler that admits members in ascending order and keeps at
1776
+ * most `workers` of them in flight. A future that is never polled has never started, so "in flight"
1777
+ * IS "admitted and unsettled" — that is how the static bound is enforced without a runtime, without
1778
+ * the `futures` crate and without boxing. Each result lands in a per-member plain Option slot (the
1779
+ * scheduler is one task on one thread — no lock to take).
1734
1780
  * 3. COMMIT (ascending index): interpret policy + move the concrete row into the outType cell —
1735
- * lowest-index failure wins.
1781
+ * lowest-index failure wins. IDENTICAL for both mechanisms (only the slot read differs).
1736
1782
  */
1737
- function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt, leaf) {
1783
+ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt, leaf, ap) {
1738
1784
  const lines = [];
1739
1785
  const ids = stage.map((i) => comp.body[i].id);
1740
- lines.push(` // ── bc#87 real-concurrency stage {${ids.map((x) => rustStrLit(x)).join(", ")}} — static parallel`);
1741
- lines.push(` // orchestration (scoped threads, bound=${concurrency}); preflight+commit in ascending index order.`);
1742
1786
  // #125/#108: a stage member may be a cond node — a pure Expression (NO handler/dispatch). The scoped-
1743
1787
  // thread orchestration governs only the componentRef fan-out members; a cond is settled in ascending
1744
1788
  // preflight order — BEFORE any dispatch — via the SAME emitCondArm the sequential path uses (no forked
@@ -1752,6 +1796,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1752
1796
  const noDispatch = (i) => "cond" in comp.body[i] || ("map" in comp.body[i] && mapTransformExpr(comp.body[i].map) !== undefined);
1753
1797
  const condMembers = stage.filter(noDispatch);
1754
1798
  const refMembers = stage.filter((i) => !noDispatch(i));
1799
+ const stageIsAsync = stageAwaits(comp, stage, ap);
1800
+ lines.push(` // ── bc#87 real-concurrency stage {${ids.map((x) => rustStrLit(x)).join(", ")}} — static parallel`);
1801
+ lines.push(` // orchestration (${stageIsAsync ? "joined futures" : "scoped threads"}, bound=${concurrency}); preflight+commit in ascending index order.`);
1755
1802
  for (const i of condMembers) {
1756
1803
  const n = comp.body[i];
1757
1804
  lines.push("cond" in n
@@ -1759,9 +1806,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1759
1806
  : // 純式 map は leaf を呼ばないので async 性を持たない(sync 既定)。
1760
1807
  emitMapArm(comp, n, atPos + stage.indexOf(i), typedNodes, plan, priorNodeAt, leaf, false, metas[i].policy));
1761
1808
  }
1762
- // A cond-ONLY stage carries no handler fan-out — the conds above ARE the whole stage. Skip the scoped-
1763
- // thread orchestration block entirely (an empty one is dead scaffolding clippy rejects: never_loop /
1764
- // match_single_binding on a zero-job scope).
1809
+ // A cond-ONLY stage carries no handler fan-out — the conds above ARE the whole stage. Skip the dispatch
1810
+ // block entirely (an empty one is dead scaffolding clippy rejects: never_loop / match_single_binding on
1811
+ // a zero-job scope, and a zero-member poll_fn scheduler is likewise dead).
1765
1812
  if (refMembers.length === 0)
1766
1813
  return lines.join("\n");
1767
1814
  lines.push(` {`);
@@ -1785,7 +1832,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1785
1832
  // it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
1786
1833
  // dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
1787
1834
  if (gated) {
1788
- lines.push(` let mut payload_${s}: Option<WireRow> = None;`);
1835
+ lines.push(` let payload_${s}: std::sync::Mutex<Option<WireRow>> = std::sync::Mutex::new(None);`);
1789
1836
  lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
1790
1837
  closers.unshift(`${ind}}`);
1791
1838
  ind += " ";
@@ -1807,68 +1854,146 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1807
1854
  const narrowed = nodeNarrowedPaths(comp, node);
1808
1855
  const fields = Object.keys(node.ports).map((pn) => emitPortWireField(pn, node.ports[pn], comp, plan, typedNodes, (h) => priorNodeAt(h, atPos), inputPortTypeRef(node.portSchemas?.[pn], plan), { narrowed }));
1809
1856
  if (gated) {
1810
- lines.push(`${ind}payload_${s} = Some(${rustPayloadRow(fields)});`);
1857
+ lines.push(`${ind}*payload_${s}.lock().unwrap() = Some(${rustPayloadRow(fields)});`);
1811
1858
  }
1812
1859
  else {
1813
- lines.push(`${ind}let payload_${s}: Option<WireRow> = Some(${rustPayloadRow(fields)});`);
1860
+ lines.push(`${ind}let payload_${s}: std::sync::Mutex<Option<WireRow>> = std::sync::Mutex::new(Some(${rustPayloadRow(fields)}));`);
1814
1861
  }
1815
1862
  for (const c of closers)
1816
1863
  lines.push(c);
1817
1864
  }
1818
- // 2) DISPATCH (bounded scoped threads). Each worker calls the leaf TRANSPORT directly for its member's
1819
- // CONCRETE ports and stores the returned wire in its slot. #125: the fan-out (slots / jobs / workers)
1820
- // spans the COMPONENTREF members only — a control gate dispatches no handler (committed in preflight
1821
- // above), so it is not a scoped-thread job. The wire's concrete type is inferred from the transport's
1822
- // return (Result<_, BehaviorError>); it impls Send so it crosses the scoped threads.
1865
+ // 2) DISPATCH (bounded). Each runnable member calls the leaf TRANSPORT directly for its CONCRETE ports
1866
+ // and stores the returned wire in its slot; the ascending COMMIT phase de-boxes it (so the WIRE — not
1867
+ // the decode — is what crosses the dispatch). #125: the fan-out (slots / jobs / workers) spans the
1868
+ // COMPONENTREF members only — a control gate dispatches no handler (committed in preflight above), so it
1869
+ // is not a job. The wire's concrete type is inferred from the transport's return
1870
+ // (Result<_, BehaviorError>).
1823
1871
  const nMembers = refMembers.length;
1824
1872
  const boundN = Math.min(concurrency, nMembers);
1825
1873
  const jobsVar = `jobs_${sanitize(comp.name)}`;
1826
- for (const i of refMembers) {
1827
- const s = sanitize(comp.body[i].id);
1828
- // every member's thread returns the result WIRE; the ascending COMMIT phase de-boxes it (so the wire —
1829
- // not the decode — is what crosses the scoped threads).
1830
- lines.push(` let slot_${s}: std::sync::Mutex<Option<Result<_, BehaviorError>>> = std::sync::Mutex::new(None);`);
1831
- }
1832
- lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1833
- refMembers.forEach((i, slot) => {
1834
- const s = sanitize(comp.body[i].id);
1835
- lines.push(` if payload_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
1836
- });
1837
- lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
1838
- lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
1839
- lines.push(` std::thread::scope(|scope| {`);
1840
- lines.push(` for _ in 0..workers {`);
1841
- lines.push(` scope.spawn(|| loop {`);
1842
- lines.push(` let j = cursor.fetch_add(1, std::sync::atomic::Ordering::SeqCst);`);
1843
- lines.push(` if j >= ${jobsVar}.len() { break; }`);
1844
- lines.push(` let slot = ${jobsVar}[j];`);
1845
- lines.push(` match slot {`);
1846
- refMembers.forEach((i, slot) => {
1874
+ // the RUNNABLE-member job list + the static bound are mechanism-independent: both dispatch forms pull
1875
+ // jobs in ascending order and hold at most `workers` of them at a time. It is built BEFORE any payload is
1876
+ // taken — TAKING the payload is what dispatch does, so the list has to be read off the intact payloads.
1877
+ const emitJobList = () => {
1878
+ lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1879
+ refMembers.forEach((i, slot) => {
1880
+ lines.push(` if payload_${sanitize(comp.body[i].id)}.lock().unwrap().is_some() { ${jobsVar}.push(${slot}); }`);
1881
+ });
1882
+ };
1883
+ const leafSym = (i) => {
1847
1884
  const node = comp.body[i];
1848
- const s = sanitize(node.id);
1849
- // DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports,
1850
- // cloned into the owned-arg call). No `bound` (BC's internal produced/skip gate is already applied in
1851
- // preflight — the leaf never sees it).
1852
- const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload)`;
1853
- lines.push(` ${slot} => {`);
1854
- lines.push(` let payload = payload_${s}.as_ref().expect("runnable member has ports").clone();`);
1855
- lines.push(` let row = ${call};`);
1856
- lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1857
- lines.push(` }`);
1858
- });
1859
- lines.push(` _ => unreachable!(),`);
1860
- lines.push(` };`);
1861
- lines.push(` });`);
1862
- lines.push(` }`);
1863
- lines.push(` });`);
1864
- // 3) COMMIT (ascending index): interpret + move the concrete row into the outType cell.
1885
+ return resolveLeafSymbol(node.component, leaf, node.leafSymbol);
1886
+ };
1887
+ if (stageIsAsync) {
1888
+ // #231 ASYNC dispatch: one future per RUNNABLE member (a skipped member's `payload_<s>` is None, so
1889
+ // `Option::map` yields NO future — it is never constructed and never polled), pinned on the stack. An
1890
+ // async member's future IS the transport call; a SYNC member in the same stage is wrapped in an async
1891
+ // block so it starts when the scheduler admits it (calling it eagerly would ignore the bound). The
1892
+ // scheduler below is the join: it admits members in ASCENDING order, keeps at most `workers` in flight
1893
+ // (a future that has not been polled has not started), and settles each into a plain Option slot — one
1894
+ // task on one thread, so no lock. No `futures` crate, no boxing: every future is a concrete stack type.
1895
+ // The future MOVES the payload out of its slot (same take-not-clone as the scoped-thread arm).
1896
+ emitJobList();
1897
+ for (const i of refMembers) {
1898
+ const s = sanitize(comp.body[i].id);
1899
+ const taken = `payload_${s}.lock().unwrap().take()`;
1900
+ const fut = ap.nodeIsAsync(comp.body[i].id)
1901
+ ? `${taken}.map(${leafSym(i)})`
1902
+ : `${taken}.map(|payload| async move { ${leafSym(i)}(payload) })`;
1903
+ lines.push(` let mut fut_${s} = std::pin::pin!(${fut});`);
1904
+ lines.push(` let mut slot_${s}: Option<Result<_, BehaviorError>> = None;`);
1905
+ }
1906
+ lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
1907
+ lines.push(` let mut settled = [false; ${nMembers}];`);
1908
+ lines.push(` let mut admitted = 0usize;`);
1909
+ lines.push(` let mut in_flight = 0usize;`);
1910
+ lines.push(` std::future::poll_fn(|cx| {`);
1911
+ lines.push(` loop {`);
1912
+ lines.push(` while in_flight < workers && admitted < ${jobsVar}.len() {`);
1913
+ lines.push(` admitted += 1;`);
1914
+ lines.push(` in_flight += 1;`);
1915
+ lines.push(` }`);
1916
+ lines.push(` let mut progressed = false;`);
1917
+ lines.push(` for (j, slot) in ${jobsVar}.iter().copied().enumerate().take(admitted) {`);
1918
+ lines.push(` if settled[j] { continue; }`);
1919
+ lines.push(` let ready = match slot {`);
1920
+ refMembers.forEach((i, slot) => {
1921
+ const s = sanitize(comp.body[i].id);
1922
+ lines.push(` ${slot} => {`);
1923
+ lines.push(` let f = fut_${s}.as_mut().as_pin_mut().expect("runnable member has a future");`);
1924
+ lines.push(` match std::future::Future::poll(f, cx) {`);
1925
+ lines.push(` std::task::Poll::Ready(r) => {`);
1926
+ lines.push(` slot_${s} = Some(r);`);
1927
+ lines.push(` true`);
1928
+ lines.push(` }`);
1929
+ lines.push(` std::task::Poll::Pending => false,`);
1930
+ lines.push(` }`);
1931
+ lines.push(` }`);
1932
+ });
1933
+ lines.push(` _ => unreachable!(),`);
1934
+ lines.push(` };`);
1935
+ lines.push(` if ready {`);
1936
+ lines.push(` settled[j] = true;`);
1937
+ lines.push(` in_flight -= 1;`);
1938
+ lines.push(` progressed = true;`);
1939
+ lines.push(` }`);
1940
+ lines.push(` }`);
1941
+ lines.push(` if admitted == ${jobsVar}.len() && in_flight == 0 {`);
1942
+ lines.push(` return std::task::Poll::Ready(());`);
1943
+ lines.push(` }`);
1944
+ lines.push(` if !progressed { return std::task::Poll::Pending; }`);
1945
+ lines.push(` }`);
1946
+ lines.push(` })`);
1947
+ lines.push(` .await;`);
1948
+ }
1949
+ else {
1950
+ // SYNC dispatch: bounded scoped std threads pulling from a shared atomic cursor in ascending order.
1951
+ // The result wire impls Send so it crosses the scoped threads.
1952
+ for (const i of refMembers) {
1953
+ lines.push(` let slot_${sanitize(comp.body[i].id)}: std::sync::Mutex<Option<Result<_, BehaviorError>>> = std::sync::Mutex::new(None);`);
1954
+ }
1955
+ emitJobList();
1956
+ lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
1957
+ lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
1958
+ lines.push(` std::thread::scope(|scope| {`);
1959
+ lines.push(` for _ in 0..workers {`);
1960
+ lines.push(` scope.spawn(|| loop {`);
1961
+ lines.push(` let j = cursor.fetch_add(1, std::sync::atomic::Ordering::SeqCst);`);
1962
+ lines.push(` if j >= ${jobsVar}.len() { break; }`);
1963
+ lines.push(` let slot = ${jobsVar}[j];`);
1964
+ lines.push(` match slot {`);
1965
+ refMembers.forEach((i, slot) => {
1966
+ const s = sanitize(comp.body[i].id);
1967
+ // DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports,
1968
+ // MOVED into the owned-arg call — the worker that wins the slot takes it). No `bound` (BC's internal
1969
+ // produced/skip gate is already applied in preflight — the leaf never sees it).
1970
+ lines.push(` ${slot} => {`);
1971
+ lines.push(` let payload = payload_${s}.lock().unwrap().take().expect("runnable member has ports");`);
1972
+ lines.push(` let row = ${leafSym(i)}(payload);`);
1973
+ lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1974
+ lines.push(` }`);
1975
+ });
1976
+ lines.push(` _ => unreachable!(),`);
1977
+ lines.push(` };`);
1978
+ lines.push(` });`);
1979
+ lines.push(` }`);
1980
+ lines.push(` });`);
1981
+ }
1982
+ // 3) COMMIT (ascending index): interpret + move the concrete row into the outType cell. IDENTICAL for
1983
+ // both dispatch mechanisms — only the slot read differs (a joined-futures slot needs no lock).
1865
1984
  refMembers.forEach((i) => {
1866
1985
  const node = comp.body[i];
1867
1986
  const meta = metas[i];
1868
1987
  const s = sanitize(node.id);
1869
1988
  const ref = typedNodes.get(node.id);
1870
- lines.push(` if payload_${s}.is_some() {`);
1871
- lines.push(` let out_${s} = slot_${s}.lock().unwrap().take().expect("runnable member wrote its slot");`);
1989
+ // A member that ran wrote its slot; taking it is both the "did it run" test and the move of the wire
1990
+ // out of the stage (the payload was already taken at dispatch, so it can no longer answer that).
1991
+ // bind first: an `if let` scrutinee keeps its temporaries — including the MutexGuard — alive for the
1992
+ // whole body, which outlives the borrow the body needs. A joined-futures slot is a plain Option (one
1993
+ // task on one thread), so it takes without a lock.
1994
+ const takeSlot = stageIsAsync ? `slot_${s}.take()` : `slot_${s}.lock().unwrap().take()`;
1995
+ lines.push(` let taken_${s} = ${takeSlot};`);
1996
+ lines.push(` if let Some(out_${s}) = taken_${s} {`);
1872
1997
  if (meta.policy === "continue") {
1873
1998
  // continue: a member whose COMPONENT failed commits no Port. A de-box mismatch still propagates —
1874
1999
  // the interpreter's outType check sits outside the policy interpretation (see the sequential arm).
@@ -2341,13 +2466,13 @@ function emitCondArm(comp, node, atPos, typedNodes, plan, priorNodeAt) {
2341
2466
  /**
2342
2467
  * emitProducedAwareValue — the #86 part 1 produced-aware output lowering (rust twin of the go one).
2343
2468
  */
2344
- function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath) {
2469
+ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath, moveHeads) {
2345
2470
  const e = classifyExpr(node);
2346
2471
  if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
2347
2472
  const head = e.path[0];
2348
2473
  const baseRef = typedNodes.get(head);
2349
2474
  if (skippable.has(head)) {
2350
- const base = `${typedCell(head)}.borrow().clone()`;
2475
+ const base = rustCellRead(head, baseRef, false, moveHeads);
2351
2476
  const { expr, ref } = typedFieldAccess(base, baseRef, e.path.slice(1), plan);
2352
2477
  // The value actually placed into this output field is `producedExpr` — its type is `ref`, opt-wrapped
2353
2478
  // by valueLeafProduced iff the field is opt and the value is not (matching Some(...)). Compare its
@@ -2371,7 +2496,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2371
2496
  };
2372
2497
  }
2373
2498
  const isBareCopyScalar = e.path.length === 1 && baseRef.kind === "scalar" && (baseRef.scalar === "int" || baseRef.scalar === "float" || baseRef.scalar === "bool");
2374
- const base = isBareCopyScalar ? `*${typedCell(head)}.borrow()` : `${typedCell(head)}.borrow().clone()`;
2499
+ const base = rustCellRead(head, baseRef, isBareCopyScalar, moveHeads);
2375
2500
  const { expr, ref } = typedFieldAccess(base, baseRef, e.path.slice(1), plan);
2376
2501
  // Non-skippable node-result: its `ref` is returned honestly (not laundered), so the placing site — the
2377
2502
  // obj-field assembly below, or the top-level call — runs checkOutputFieldType against the field type.
@@ -2384,7 +2509,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2384
2509
  const fields = node.obj;
2385
2510
  const inits = decl.fields.map((f) => {
2386
2511
  const childPath = fieldPath === "" ? f.name : `${fieldPath}.${f.name}`;
2387
- const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath);
2512
+ const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath, moveHeads);
2388
2513
  // Non-skippable field: sub.ref is the honest value type → catches a Vec-depth mismatch here. A
2389
2514
  // skippable field launders sub.ref to expected, but its own produced-arm check (above) already fired.
2390
2515
  checkOutputFieldType(compName, childPath, f.type, sub.ref, plan);
@@ -2393,7 +2518,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2393
2518
  return { expr: `${expected.name} { ${inits.join(", ")} }`, ref: expected };
2394
2519
  }
2395
2520
  }
2396
- return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath);
2521
+ return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath, moveHeads);
2397
2522
  }
2398
2523
  function valueLeafProduced(expr, ref, expected) {
2399
2524
  if (expected && expected.kind === "opt") {
@@ -2431,7 +2556,7 @@ fn leaf_failure(message: impl Into<String>) -> BehaviorError {
2431
2556
  /**
2432
2557
  * rustSharedWireTypesModule (#165, rust twin of goSharedWireTypesPackage) — the BC-GENERATED shared module
2433
2558
  * content emitted when the covered module is generated with --shared-types-import. Carries the SAME wire seam
2434
- * the covered module emits in-crate when the flag is absent (Probe/NumProbe + WireValue/WireRow/WireList +
2559
+ * the covered module emits in-crate when the flag is absent (Probe + WireValue/WireRow/WireList +
2435
2560
  * the probe classifiers) so a separate leaf-transport crate can take a `WireRow` payload + build+return
2436
2561
  * `WireValue` (and the covered module reference them) without an import cycle. #183: the transport ABI is the
2437
2562
  * generic `WireRow` payload built inline at the call site — there are NO per-node/per-role batch ports structs
@@ -2448,6 +2573,8 @@ export function rustSharedWireTypesModule() {
2448
2573
 
2449
2574
  // Local concrete failure type (runtime-free) — the covered runner + the transport crate share it. Only the
2450
2575
  // TYPE lives here; the de-box/op-failure CONSTRUCTORS stay in the covered module (they are called there).
2576
+ use std::borrow::Cow;
2577
+
2451
2578
  ${emitErrorTypeDefs()}
2452
2579
 
2453
2580
  ${emitRustProbeWireTypes(true)}
@@ -2501,7 +2628,7 @@ ${emitStructSurface([])}
2501
2628
  // WireValue/WireRow/WireList traits) is emitted once whenever any handler node exists.
2502
2629
  const anyWire = native.some((c) => c.body.some((n) => !("cond" in n)));
2503
2630
  // #165: --shared-types-import parity with go. When set, the BC-OWNED wire types (WireValue/WireRow/
2504
- // WireList + Probe/NumProbe) AND the batched-map/fanout batch ports structs (the ONLY structs that cross
2631
+ // WireList + Probe) AND the batched-map/fanout batch ports structs (the ONLY structs that cross
2505
2632
  // the leaf-transport boundary as a whole value) live in the SHARED crate/module at that path; the covered
2506
2633
  // module IMPORTS them (`use <path>::*;`) instead of defining them locally — so a separate transport crate
2507
2634
  // can return the shared WireValue with NO import cycle (covered → tx → shared, no back-edge). Absent →
@@ -2549,7 +2676,7 @@ ${emitStructSurface([])}
2549
2676
  return undefined;
2550
2677
  return `// op-agnostic leaf transport symbols (consumer-supplied) — called directly at each covered node.\nuse ${leaf.import}::{${[...syms].sort().join(", ")}};`;
2551
2678
  })();
2552
- // #165: --shared-types-import — bring the BC-OWNED wire types (WireValue/WireRow/WireList + Probe/NumProbe)
2679
+ // #165: --shared-types-import — bring the BC-OWNED wire types (WireValue/WireRow/WireList + Probe)
2553
2680
  // and the batched/fanout batch ports structs into scope from the shared crate/module (a glob `use`, so no
2554
2681
  // reference site is qualified). The covered module defines NONE of them locally; a separate transport crate
2555
2682
  // returns the SAME shared WireValue with no import cycle. Absent → in-crate (byte-identical to before).
@@ -2575,8 +2702,17 @@ ${emitStructSurface([])}
2575
2702
  // parent value — relation / connection converge with run_behavior (fixes #323/#74). The exposed API
2576
2703
  // is the 1:1 entry <method>(<positional params>) -> Result<T, BehaviorError> (the InNR_<comp> box removed);
2577
2704
  // the consumer supplies the leaf transport symbols (default in-scope names leaf_<comp>, or a leafTransport
2578
- // import). This module
2579
- // is FULLY NATIVE: a naive grep for boxing primitives OR for the bc-runtime crate finds nothing, by design.
2705
+ // import).
2706
+ //
2707
+ // NO CLONE, NO PER-CALL ALLOCATION — the two rules this module is generated under:
2708
+ // - Everything fixed at generation time (SQL text, port names, field names) rides as \`&'static str\`
2709
+ // behind \`Cow::Borrowed\`, so building a payload allocates nothing for it, however often it is called.
2710
+ // - De-boxing CONSUMES the transport's wire: every string, row and list is MOVED into the typed value.
2711
+ // A \`.clone()\` on this path deep-copies the result set once per node boundary and scales with node
2712
+ // count — it is the difference between beating a hand-written driver and losing to an interpreter.
2713
+ // The codegen purity gate rejects \`.clone()\` and per-call \`.to_string()\` here, and the cost is confirmed
2714
+ // by benchmark, not by asserting it in this comment.
2715
+ use std::borrow::Cow;
2580
2716
  use std::cell::RefCell;`;
2581
2717
  const sections = [
2582
2718
  banner,
@@ -2636,7 +2772,7 @@ export function rustTypedNativeObserve(ir, ioModel = "sync", leaf, declared) {
2636
2772
  const anyDeBox = native.some((c) => c.body.some((n) => !("cond" in n)));
2637
2773
  // value_to_wire (TEST glue): builds the covered module's BC-OWNED concrete `WireValue` from a scripted bc
2638
2774
  // `Value` — the test-harness analog of the consumer's real transport (which builds `WireValue` as it reads
2639
- // the producer). Numbers ride as raw text (WireValue::Num), matching how the de-box parses + range-checks;
2775
+ // the producer). Numbers ride in their declared type (WireValue::Int / WireValue::Float) — nothing parses;
2640
2776
  // the wire tags + classification live ONCE in the covered module's WireValue (probe_*_at), so this only
2641
2777
  // CONSTRUCTS — a scripted wrong-variant value maps to the corresponding WireValue variant and the covered
2642
2778
  // de-box classifies it (TYPE_MISMATCH ≡ run_behavior), no separate scripted classifier.
@@ -2646,12 +2782,12 @@ fn value_to_wire(v: &Value) -> WireValue {
2646
2782
  match v {
2647
2783
  Value::Null => WireValue::Null,
2648
2784
  Value::Bool(b) => WireValue::Bool(*b),
2649
- Value::Int(n) => WireValue::Num(n.to_string()),
2650
- Value::Float(f) => WireValue::Num(f.to_string()),
2651
- Value::Str(s) => WireValue::Str(s.clone()),
2785
+ Value::Int(n) => WireValue::Int(*n),
2786
+ Value::Float(f) => WireValue::Float(*f),
2787
+ Value::Str(s) => WireValue::Str(Cow::Owned(s.clone())),
2652
2788
  Value::Arr(items) => WireValue::List(WireList { items: items.iter().map(value_to_wire).collect() }),
2653
2789
  Value::Obj(pairs) => WireValue::Row(WireRow {
2654
- entries: pairs.iter().map(|(k, vv)| (k.clone(), value_to_wire(vv))).collect(),
2790
+ entries: pairs.iter().map(|(k, vv)| (Cow::Owned(k.clone()), value_to_wire(vv))).collect(),
2655
2791
  }),
2656
2792
  }
2657
2793
  }`
@@ -2707,18 +2843,18 @@ fn value_to_wire(v: &Value) -> WireValue {
2707
2843
  }
2708
2844
  if (portRust === recordRust) {
2709
2845
  // the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
2710
- echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == ${rustStrLit(pn)}) {\n return Ok(v.clone());\n }\n }`);
2846
+ echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(v) = payload.take(${rustStrLit(pn)}) {\n return Ok(v);\n }\n }`);
2711
2847
  }
2712
2848
  else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2713
2849
  // a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
2714
- echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == ${rustStrLit(pn)}) {\n return Ok(WireValue::Row(WireRow { entries: vec![(${rustStrLit(field.name)}.to_string(), v.clone())] }));\n }\n }`);
2850
+ echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(v) = payload.take(${rustStrLit(pn)}) {\n return Ok(WireValue::Row(WireRow { entries: vec![(Cow::Borrowed(${rustStrLit(field.name)}), v)] }));\n }\n }`);
2715
2851
  }
2716
2852
  }
2717
2853
  }
2718
2854
  else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2719
2855
  // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
2720
2856
  // node→leaf array dataflow test is non-vacuous.
2721
- echo.push(` if echo == "items" {\n if let Some((_, v)) = payload.entries.iter().find(|(__k, _)| __k.as_str() == "items") {\n return Ok(v.clone());\n }\n }`);
2857
+ echo.push(` if echo == "items" {\n if let Some(v) = payload.take("items") {\n return Ok(v);\n }\n }`);
2722
2858
  }
2723
2859
  }
2724
2860
  const prev = bySym.get(sym);
@@ -2741,7 +2877,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2741
2877
  const hasEcho = le.echo.length > 0;
2742
2878
  const echoBind = hasEcho ? "echo" : "_echo";
2743
2879
  const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
2744
- transportFns.push(`${fnKw} ${sym}(${hasEcho ? "payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2880
+ transportFns.push(`${fnKw} ${sym}(${hasEcho ? "mut payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2745
2881
  let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
2746
2882
  if is_err {
2747
2883
  return Err(leaf_failure(err));