behavior-contracts 0.11.7 → 0.11.8

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.
@@ -8,7 +8,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}
421
+ ${I}}`;
422
+ }
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}
479
428
  ${I}}`;
480
429
  }
481
- const meth = plan.scalar === "string" ? "string" : "bool";
482
- return `match ${probe(meth)} {
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).
@@ -1519,12 +1498,60 @@ function emitPortWireField(pn, expr, comp, plan, typedNodes, isPrior, expected,
1519
1498
  if (c.stmts.length > 0)
1520
1499
  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
1500
  const boxed = renderRustWireBox(buildWirePlan(c.ref, { from: "top" }, { model: "port", field: pn, plan }, "in"), c.expr);
1522
- return `(${rustStrLit(pn)}.to_string(), ${boxed})`;
1501
+ return `(Cow::Borrowed(${rustStrLit(pn)}), ${boxed})`;
1523
1502
  }
1524
1503
  // ── the combined runner (STRUCT-returning; INLINE sequential; native ports in; concrete row out) ──
1525
1504
  function rustScalar(s) {
1526
1505
  return s === "string" ? "String" : s === "int" ? "i64" : s === "float" ? "f64" : "bool";
1527
1506
  }
1507
+ /**
1508
+ * movableRefs — the values (a body node's RESULT, or an input port) with exactly ONE reader in the whole
1509
+ * component, so that reader can take the value by MOVE instead of copying it.
1510
+ *
1511
+ * Handing a prior node's result to a downstream leaf is where a result set would otherwise be deep-copied:
1512
+ * a `Vec<WireValue>` clone re-allocates every string in every row, once per node boundary. Counting the
1513
+ * readers statically says when copying is unnecessary — which, in a read chain, is the normal case.
1514
+ *
1515
+ * A read is counted from the ONE place a value can be referenced: a `{ref}` / `{refOpt}` path whose head
1516
+ * names a body node or an input port (ports, guards, map sources, the output value), plus the parent read
1517
+ * a bindField performs. Two reads (or none) ⇒ not movable. A read nested inside a `map` / `fanout` element
1518
+ * body runs once PER ELEMENT, so it counts as many — a single textual site is not a single read there.
1519
+ */
1520
+ function movableRefs(comp) {
1521
+ const counts = new Map();
1522
+ const bump = (head, times) => {
1523
+ counts.set(head, (counts.get(head) ?? 0) + times);
1524
+ };
1525
+ const walk = (n, times) => {
1526
+ if (Array.isArray(n)) {
1527
+ for (const e of n)
1528
+ walk(e, times);
1529
+ return;
1530
+ }
1531
+ if (n === null || typeof n !== "object")
1532
+ return;
1533
+ const rec = n;
1534
+ const keys = Object.keys(rec);
1535
+ if (keys.length === 1 && (keys[0] === "ref" || keys[0] === "refOpt")) {
1536
+ const path = rec[keys[0]];
1537
+ if (Array.isArray(path) && typeof path[0] === "string")
1538
+ bump(path[0], times);
1539
+ return;
1540
+ }
1541
+ // an element body repeats: everything under a map / fanout is read once per element.
1542
+ const repeats = times === 1 && ("map" in rec || "fanout" in rec) ? 2 : times;
1543
+ for (const k of keys)
1544
+ walk(rec[k], repeats);
1545
+ };
1546
+ walk(comp.body, 1);
1547
+ walk(comp.output, 1);
1548
+ for (const nd of comp.body) {
1549
+ const cr = nd;
1550
+ if (cr.parent !== undefined && cr.bindField !== undefined)
1551
+ bump(cr.parent, 1);
1552
+ }
1553
+ return new Set([...counts].filter(([, c]) => c === 1).map(([id]) => id));
1554
+ }
1528
1555
  function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1529
1556
  const ep = execPlan(comp);
1530
1557
  const order = ep.order;
@@ -1547,6 +1574,17 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1547
1574
  for (const n of comp.body)
1548
1575
  if (!isControlGate(n))
1549
1576
  typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan));
1577
+ // Single-reader results are handed on by MOVE (see movableCells). A parallel stage builds its members'
1578
+ // payloads inside a scoped-thread closure, so a read there is not the plain sequential read the count
1579
+ // assumed — drop every head a stage member reads and let those copy.
1580
+ const moveHeads = movableRefs(comp);
1581
+ for (const [i] of ep.parallelStageOf) {
1582
+ for (const pn of Object.keys(comp.body[i].ports ?? {})) {
1583
+ const e = classifyExpr(comp.body[i].ports[pn]);
1584
+ if (e.kind === "ref")
1585
+ moveHeads.delete(e.path[0]);
1586
+ }
1587
+ }
1550
1588
  // the ops literal comes from the SHARED derivation (opsLiteralOf): a local "read cr.policy / cr.parent"
1551
1589
  // copy silently drops a MAP's / FANOUT's policy and parent (they live under map./fanout.), which would
1552
1590
  // make canSkip — and therefore the produced-aware output — disagree with the go surface on the same IR.
@@ -1664,7 +1702,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1664
1702
  }
1665
1703
  }
1666
1704
  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 }));
1705
+ 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
1706
  // bc#97: derived per-node await — this point-read's future is awaited HERE (its result-consumption
1669
1707
  // point) iff THIS node's terminal handler is async. A sync handler in the same async runner is called
1670
1708
  // directly (no `.await`). The runner being `async fn` does not force every call site to await.
@@ -1713,8 +1751,8 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1713
1751
  }
1714
1752
  }
1715
1753
  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>");
1754
+ ? emitProducedAwareValue(comp.output, outRef, typedNodes, plan, skippable, skippableKind, comp.name, "<output>", moveHeads)
1755
+ : emitTypedValue(comp.output, outRef, typedNodes, plan, comp.name, "<output>", moveHeads);
1718
1756
  // top-level output that is a bare node-result (not an obj/arr assembly): its honest `ref` must equal the
1719
1757
  // declared component output type, or the emitted `let __out = …; Ok(__out)` return does not compile.
1720
1758
  checkOutputFieldType(comp.name, "<output>", outRef, out.ref, plan);
@@ -1785,7 +1823,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1785
1823
  // it is a plain local inside the produced block — NOT a stage-scoped mut (nothing captures it) and no
1786
1824
  // dead None init. A control-gate parent needs no bound at all (produced_<gate> already carries the skip).
1787
1825
  if (gated) {
1788
- lines.push(` let mut payload_${s}: Option<WireRow> = None;`);
1826
+ lines.push(` let payload_${s}: std::sync::Mutex<Option<WireRow>> = std::sync::Mutex::new(None);`);
1789
1827
  lines.push(`${ind}if produced_${sanitize(node.parent)}.get() {`);
1790
1828
  closers.unshift(`${ind}}`);
1791
1829
  ind += " ";
@@ -1807,10 +1845,10 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1807
1845
  const narrowed = nodeNarrowedPaths(comp, node);
1808
1846
  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
1847
  if (gated) {
1810
- lines.push(`${ind}payload_${s} = Some(${rustPayloadRow(fields)});`);
1848
+ lines.push(`${ind}*payload_${s}.lock().unwrap() = Some(${rustPayloadRow(fields)});`);
1811
1849
  }
1812
1850
  else {
1813
- lines.push(`${ind}let payload_${s}: Option<WireRow> = Some(${rustPayloadRow(fields)});`);
1851
+ lines.push(`${ind}let payload_${s}: std::sync::Mutex<Option<WireRow>> = std::sync::Mutex::new(Some(${rustPayloadRow(fields)}));`);
1814
1852
  }
1815
1853
  for (const c of closers)
1816
1854
  lines.push(c);
@@ -1832,7 +1870,7 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1832
1870
  lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1833
1871
  refMembers.forEach((i, slot) => {
1834
1872
  const s = sanitize(comp.body[i].id);
1835
- lines.push(` if payload_${s}.is_some() { ${jobsVar}.push(${slot}); }`);
1873
+ lines.push(` if payload_${s}.lock().unwrap().is_some() { ${jobsVar}.push(${slot}); }`);
1836
1874
  });
1837
1875
  lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
1838
1876
  lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
@@ -1847,11 +1885,11 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1847
1885
  const node = comp.body[i];
1848
1886
  const s = sanitize(node.id);
1849
1887
  // 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).
1888
+ // MOVED into the owned-arg call — the worker that wins the slot takes it). No `bound` (BC's internal
1889
+ // produced/skip gate is already applied in preflight — the leaf never sees it).
1852
1890
  const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload)`;
1853
1891
  lines.push(` ${slot} => {`);
1854
- lines.push(` let payload = payload_${s}.as_ref().expect("runnable member has ports").clone();`);
1892
+ lines.push(` let payload = payload_${s}.lock().unwrap().take().expect("runnable member has ports");`);
1855
1893
  lines.push(` let row = ${call};`);
1856
1894
  lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1857
1895
  lines.push(` }`);
@@ -1867,8 +1905,12 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1867
1905
  const meta = metas[i];
1868
1906
  const s = sanitize(node.id);
1869
1907
  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");`);
1908
+ // A member that ran wrote its slot; taking it is both the "did it run" test and the move of the wire
1909
+ // out of the stage (the payload was already taken by the worker, so it can no longer answer that).
1910
+ // bind first: an `if let` scrutinee keeps its temporaries — including the MutexGuard — alive for the
1911
+ // whole body, which outlives the borrow the body needs.
1912
+ lines.push(` let taken_${s} = slot_${s}.lock().unwrap().take();`);
1913
+ lines.push(` if let Some(out_${s}) = taken_${s} {`);
1872
1914
  if (meta.policy === "continue") {
1873
1915
  // continue: a member whose COMPONENT failed commits no Port. A de-box mismatch still propagates —
1874
1916
  // the interpreter's outType check sits outside the policy interpretation (see the sequential arm).
@@ -2341,13 +2383,13 @@ function emitCondArm(comp, node, atPos, typedNodes, plan, priorNodeAt) {
2341
2383
  /**
2342
2384
  * emitProducedAwareValue — the #86 part 1 produced-aware output lowering (rust twin of the go one).
2343
2385
  */
2344
- function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath) {
2386
+ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, skippableKind, compName, fieldPath, moveHeads) {
2345
2387
  const e = classifyExpr(node);
2346
2388
  if (e.kind === "ref" && e.path.length >= 1 && typedNodes.has(e.path[0])) {
2347
2389
  const head = e.path[0];
2348
2390
  const baseRef = typedNodes.get(head);
2349
2391
  if (skippable.has(head)) {
2350
- const base = `${typedCell(head)}.borrow().clone()`;
2392
+ const base = rustCellRead(head, baseRef, false, moveHeads);
2351
2393
  const { expr, ref } = typedFieldAccess(base, baseRef, e.path.slice(1), plan);
2352
2394
  // The value actually placed into this output field is `producedExpr` — its type is `ref`, opt-wrapped
2353
2395
  // by valueLeafProduced iff the field is opt and the value is not (matching Some(...)). Compare its
@@ -2371,7 +2413,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2371
2413
  };
2372
2414
  }
2373
2415
  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()`;
2416
+ const base = rustCellRead(head, baseRef, isBareCopyScalar, moveHeads);
2375
2417
  const { expr, ref } = typedFieldAccess(base, baseRef, e.path.slice(1), plan);
2376
2418
  // Non-skippable node-result: its `ref` is returned honestly (not laundered), so the placing site — the
2377
2419
  // obj-field assembly below, or the top-level call — runs checkOutputFieldType against the field type.
@@ -2384,7 +2426,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2384
2426
  const fields = node.obj;
2385
2427
  const inits = decl.fields.map((f) => {
2386
2428
  const childPath = fieldPath === "" ? f.name : `${fieldPath}.${f.name}`;
2387
- const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath);
2429
+ const sub = emitProducedAwareValue(fields[f.name], f.type, typedNodes, plan, skippable, skippableKind, compName, childPath, moveHeads);
2388
2430
  // Non-skippable field: sub.ref is the honest value type → catches a Vec-depth mismatch here. A
2389
2431
  // skippable field launders sub.ref to expected, but its own produced-arm check (above) already fired.
2390
2432
  checkOutputFieldType(compName, childPath, f.type, sub.ref, plan);
@@ -2393,7 +2435,7 @@ function emitProducedAwareValue(node, expected, typedNodes, plan, skippable, ski
2393
2435
  return { expr: `${expected.name} { ${inits.join(", ")} }`, ref: expected };
2394
2436
  }
2395
2437
  }
2396
- return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath);
2438
+ return emitTypedValue(node, expected, typedNodes, plan, compName, fieldPath, moveHeads);
2397
2439
  }
2398
2440
  function valueLeafProduced(expr, ref, expected) {
2399
2441
  if (expected && expected.kind === "opt") {
@@ -2431,7 +2473,7 @@ fn leaf_failure(message: impl Into<String>) -> BehaviorError {
2431
2473
  /**
2432
2474
  * rustSharedWireTypesModule (#165, rust twin of goSharedWireTypesPackage) — the BC-GENERATED shared module
2433
2475
  * 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 +
2476
+ * the covered module emits in-crate when the flag is absent (Probe + WireValue/WireRow/WireList +
2435
2477
  * the probe classifiers) so a separate leaf-transport crate can take a `WireRow` payload + build+return
2436
2478
  * `WireValue` (and the covered module reference them) without an import cycle. #183: the transport ABI is the
2437
2479
  * generic `WireRow` payload built inline at the call site — there are NO per-node/per-role batch ports structs
@@ -2448,6 +2490,8 @@ export function rustSharedWireTypesModule() {
2448
2490
 
2449
2491
  // Local concrete failure type (runtime-free) — the covered runner + the transport crate share it. Only the
2450
2492
  // TYPE lives here; the de-box/op-failure CONSTRUCTORS stay in the covered module (they are called there).
2493
+ use std::borrow::Cow;
2494
+
2451
2495
  ${emitErrorTypeDefs()}
2452
2496
 
2453
2497
  ${emitRustProbeWireTypes(true)}
@@ -2501,7 +2545,7 @@ ${emitStructSurface([])}
2501
2545
  // WireValue/WireRow/WireList traits) is emitted once whenever any handler node exists.
2502
2546
  const anyWire = native.some((c) => c.body.some((n) => !("cond" in n)));
2503
2547
  // #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
2548
+ // WireList + Probe) AND the batched-map/fanout batch ports structs (the ONLY structs that cross
2505
2549
  // the leaf-transport boundary as a whole value) live in the SHARED crate/module at that path; the covered
2506
2550
  // module IMPORTS them (`use <path>::*;`) instead of defining them locally — so a separate transport crate
2507
2551
  // can return the shared WireValue with NO import cycle (covered → tx → shared, no back-edge). Absent →
@@ -2549,7 +2593,7 @@ ${emitStructSurface([])}
2549
2593
  return undefined;
2550
2594
  return `// op-agnostic leaf transport symbols (consumer-supplied) — called directly at each covered node.\nuse ${leaf.import}::{${[...syms].sort().join(", ")}};`;
2551
2595
  })();
2552
- // #165: --shared-types-import — bring the BC-OWNED wire types (WireValue/WireRow/WireList + Probe/NumProbe)
2596
+ // #165: --shared-types-import — bring the BC-OWNED wire types (WireValue/WireRow/WireList + Probe)
2553
2597
  // and the batched/fanout batch ports structs into scope from the shared crate/module (a glob `use`, so no
2554
2598
  // reference site is qualified). The covered module defines NONE of them locally; a separate transport crate
2555
2599
  // returns the SAME shared WireValue with no import cycle. Absent → in-crate (byte-identical to before).
@@ -2575,8 +2619,17 @@ ${emitStructSurface([])}
2575
2619
  // parent value — relation / connection converge with run_behavior (fixes #323/#74). The exposed API
2576
2620
  // is the 1:1 entry <method>(<positional params>) -> Result<T, BehaviorError> (the InNR_<comp> box removed);
2577
2621
  // 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.
2622
+ // import).
2623
+ //
2624
+ // NO CLONE, NO PER-CALL ALLOCATION — the two rules this module is generated under:
2625
+ // - Everything fixed at generation time (SQL text, port names, field names) rides as \`&'static str\`
2626
+ // behind \`Cow::Borrowed\`, so building a payload allocates nothing for it, however often it is called.
2627
+ // - De-boxing CONSUMES the transport's wire: every string, row and list is MOVED into the typed value.
2628
+ // A \`.clone()\` on this path deep-copies the result set once per node boundary and scales with node
2629
+ // count — it is the difference between beating a hand-written driver and losing to an interpreter.
2630
+ // The codegen purity gate rejects \`.clone()\` and per-call \`.to_string()\` here, and the cost is confirmed
2631
+ // by benchmark, not by asserting it in this comment.
2632
+ use std::borrow::Cow;
2580
2633
  use std::cell::RefCell;`;
2581
2634
  const sections = [
2582
2635
  banner,
@@ -2636,7 +2689,7 @@ export function rustTypedNativeObserve(ir, ioModel = "sync", leaf, declared) {
2636
2689
  const anyDeBox = native.some((c) => c.body.some((n) => !("cond" in n)));
2637
2690
  // value_to_wire (TEST glue): builds the covered module's BC-OWNED concrete `WireValue` from a scripted bc
2638
2691
  // `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;
2692
+ // the producer). Numbers ride in their declared type (WireValue::Int / WireValue::Float) — nothing parses;
2640
2693
  // the wire tags + classification live ONCE in the covered module's WireValue (probe_*_at), so this only
2641
2694
  // CONSTRUCTS — a scripted wrong-variant value maps to the corresponding WireValue variant and the covered
2642
2695
  // de-box classifies it (TYPE_MISMATCH ≡ run_behavior), no separate scripted classifier.
@@ -2646,12 +2699,12 @@ fn value_to_wire(v: &Value) -> WireValue {
2646
2699
  match v {
2647
2700
  Value::Null => WireValue::Null,
2648
2701
  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()),
2702
+ Value::Int(n) => WireValue::Int(*n),
2703
+ Value::Float(f) => WireValue::Float(*f),
2704
+ Value::Str(s) => WireValue::Str(Cow::Owned(s.clone())),
2652
2705
  Value::Arr(items) => WireValue::List(WireList { items: items.iter().map(value_to_wire).collect() }),
2653
2706
  Value::Obj(pairs) => WireValue::Row(WireRow {
2654
- entries: pairs.iter().map(|(k, vv)| (k.clone(), value_to_wire(vv))).collect(),
2707
+ entries: pairs.iter().map(|(k, vv)| (Cow::Owned(k.clone()), value_to_wire(vv))).collect(),
2655
2708
  }),
2656
2709
  }
2657
2710
  }`
@@ -2707,18 +2760,18 @@ fn value_to_wire(v: &Value) -> WireValue {
2707
2760
  }
2708
2761
  if (portRust === recordRust) {
2709
2762
  // 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 }`);
2763
+ echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(v) = payload.take(${rustStrLit(pn)}) {\n return Ok(v);\n }\n }`);
2711
2764
  }
2712
2765
  else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2713
2766
  // 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 }`);
2767
+ 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
2768
  }
2716
2769
  }
2717
2770
  }
2718
2771
  else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2719
2772
  // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
2720
2773
  // 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 }`);
2774
+ echo.push(` if echo == "items" {\n if let Some(v) = payload.take("items") {\n return Ok(v);\n }\n }`);
2722
2775
  }
2723
2776
  }
2724
2777
  const prev = bySym.get(sym);
@@ -2741,7 +2794,7 @@ fn value_to_wire(v: &Value) -> WireValue {
2741
2794
  const hasEcho = le.echo.length > 0;
2742
2795
  const echoBind = hasEcho ? "echo" : "_echo";
2743
2796
  const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
2744
- transportFns.push(`${fnKw} ${sym}(${hasEcho ? "payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2797
+ transportFns.push(`${fnKw} ${sym}(${hasEcho ? "mut payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2745
2798
  let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
2746
2799
  if is_err {
2747
2800
  return Err(leaf_failure(err));