behavior-contracts 0.11.8 → 0.11.10

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 (45) 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-go-typed.d.ts +0 -6
  8. package/dist/generator/emit-shared-go-typed.d.ts.map +1 -1
  9. package/dist/generator/emit-shared-go-typed.js +0 -116
  10. package/dist/generator/emit-shared-go-typed.js.map +1 -1
  11. package/dist/generator/emit-shared-rust-typed.d.ts +0 -3
  12. package/dist/generator/emit-shared-rust-typed.d.ts.map +1 -1
  13. package/dist/generator/emit-shared-rust-typed.js +0 -15
  14. package/dist/generator/emit-shared-rust-typed.js.map +1 -1
  15. package/dist/generator/emit-typed-native-go.d.ts +1 -12
  16. package/dist/generator/emit-typed-native-go.d.ts.map +1 -1
  17. package/dist/generator/emit-typed-native-go.js +15 -451
  18. package/dist/generator/emit-typed-native-go.js.map +1 -1
  19. package/dist/generator/emit-typed-native-rust.d.ts +1 -13
  20. package/dist/generator/emit-typed-native-rust.d.ts.map +1 -1
  21. package/dist/generator/emit-typed-native-rust.js +168 -510
  22. package/dist/generator/emit-typed-native-rust.js.map +1 -1
  23. package/dist/generator/index.d.ts +2 -2
  24. package/dist/generator/index.d.ts.map +1 -1
  25. package/dist/generator/index.js +2 -2
  26. package/dist/generator/index.js.map +1 -1
  27. package/dist/generator/typed.d.ts +1 -25
  28. package/dist/generator/typed.d.ts.map +1 -1
  29. package/dist/generator/typed.js +0 -31
  30. package/dist/generator/typed.js.map +1 -1
  31. package/dist/lowering.d.ts.map +1 -1
  32. package/dist/lowering.js +10 -3
  33. package/dist/lowering.js.map +1 -1
  34. package/dist/runtime.d.ts +1 -1
  35. package/dist/runtime.d.ts.map +1 -1
  36. package/dist/runtime.js +1 -1
  37. package/dist/runtime.js.map +1 -1
  38. package/dist/spec-versions.d.ts +1 -1
  39. package/dist/spec-versions.js +1 -1
  40. package/dist/spec-versions.js.map +1 -1
  41. package/dist/type-gate.d.ts +13 -1
  42. package/dist/type-gate.d.ts.map +1 -1
  43. package/dist/type-gate.js +29 -2
  44. package/dist/type-gate.js.map +1 -1
  45. 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, rustCellRead, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, materializeExpr, } = rustTypedInternals;
11
+ const { typeRefIsCopy, rustFieldName, renderTypeRef, typedCell, typedFieldAccess, serializeTyped, emitTypeDecls, emitDefaults, emitTypedValue, rustCellRead, checkOutputFieldType, emitMarshallers, emitMarshalHelpers, } = 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
@@ -61,9 +61,8 @@ pub struct ErrorDetail {
61
61
  // covered runner returns \`Result<T, BehaviorError>\` over THIS local type instead of a bc-runtime
62
62
  // failure, so the fully-covered module imports ZERO bc runtime. Codes match run_behavior verbatim
63
63
  // (byte-equal). \`detail\` carries the leaf's structured Error Value across the seam so a caller can
64
- // log / skip / repair / migrate rather than parse a message. The observe companion (test glue, a
65
- // super:: submodule) bridges this local error to the bc-runtime failure at the observe boundary —
66
- // the covered module itself stays runtime-free.
64
+ // log / skip / repair / migrate rather than parse a message. The covered module stays runtime-free:
65
+ // nothing in it converts this local error into a bc-runtime failure.
67
66
  #[derive(Debug, Clone)]
68
67
  pub struct BehaviorError {
69
68
  pub code: String,
@@ -166,7 +165,7 @@ function pascal(s) {
166
165
  * resolveLeafSymbol — the op-agnostic transport symbol a covered leaf (= catalog component) is called
167
166
  * through at its execution point. A consumer-supplied override (`leafTransport.symbols[component]`) wins;
168
167
  * else the in-package DEFAULT convention `leaf_<sanitizedComponent>`. This is the ONE place leaf→symbol
169
- * resolution lives (SSoT) — the runner call sites, the import block, and the test observe transport fns
168
+ * resolution lives (SSoT) — the runner call sites and the import block
170
169
  * all read it. There is no per-node handler indirection: the leaf is one transport, not one method per node.
171
170
  */
172
171
  function resolveLeafSymbol(component, leaf, specSymbol) {
@@ -1233,15 +1232,13 @@ function coveredMapNode(n, bodyIds, comp) {
1233
1232
  if (n === null || typeof n !== "object" || !("map" in n))
1234
1233
  return false;
1235
1234
  const m = n.map;
1236
- // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182: a
1237
- // guarded map WITH `into` is covered when the guard-skipped element has a well-defined skip value — the
1238
- // into field is OPT (skip → None, #177) OR relationKind:connection (skip → the empty connection
1239
- // {items:[],cursor:null}, #182). Byte-equal to run_behavior applyInto (opt-into → null / connection-into
1240
- // → unproducedValue("connection")). A REQUIRED non-connection into → run_behavior FAILS MISSING_PROP on a
1241
- // skipped element, so fail-close is byte-equal. over element type must be statically resolvable: prior-node
1242
- // arr field, or an input array port carrying `elemType` (BC does not infer — consumer-interface C3).
1243
- if (m.when !== undefined && m.into !== undefined && !guardedMapIntoIsCoverable(n, comp))
1244
- return false;
1235
+ // #108 (rust twin of the go predicate): a guarded map (`when`) IS covered with NO `into`. #177/#182/#232:
1236
+ // a `map...into` ALWAYS has a well-defined unproduced value for the into field — OPT (unproduced → None,
1237
+ // #177) OR relationKind:connection (unproduced → the empty connection {items:[],cursor:null}, #182).
1238
+ // Byte-equal to run_behavior applyInto. The type gate (`mapIntoHoldsUnproduced`, run for every component
1239
+ // at the codegen entry) rejects anything else BEFORE any emitter sees it (#232). over element type must be
1240
+ // statically resolvable: prior-node arr field, or an input array port carrying `elemType` (BC does not
1241
+ // infer — consumer-interface C3).
1245
1242
  if (m.relationKind !== undefined && m.relationKind !== "connection")
1246
1243
  return false;
1247
1244
  // A map node must carry an outType (its ELEMENT type per the recorder SoT — authoring.ts recordMap
@@ -1458,23 +1455,6 @@ function inputPortRustType(schema, plan, where = "input port") {
1458
1455
  throw new GeneratorFailure("UNSUPPORTED_NODE_STRAIGHTLINE", `rust typed-native (runtime-free): ${where} is OPTIONAL (declared {opt:…}) but its inner type ${JSON.stringify(schema?.type)} has no native Rust lowering, so "absent" has no native representation. Declare an elemType for an array/map, or use a natively-lowerable scalar.`);
1459
1456
  return "Value";
1460
1457
  }
1461
- /** The scalar kind an input port declares, or undefined if it is not a native scalar. */
1462
- function inputScalarKind(schema) {
1463
- switch (schema?.type) {
1464
- case "string":
1465
- case "literal": // a `"literal"` union is a constrained String (see inputPortRustType).
1466
- return "String";
1467
- case "int":
1468
- return "i64";
1469
- case "float":
1470
- case "number": // a `"number"` port is the FLOAT channel (run_behavior: number → float / f64).
1471
- return "f64";
1472
- case "bool":
1473
- return "bool";
1474
- default:
1475
- return undefined;
1476
- }
1477
- }
1478
1458
  /** A ref resolver for native lowering: given a ref head + remaining field path, return a native scalar
1479
1459
  * Rust expression (typed input field / prior-node typed struct scalar / element binding field), or null
1480
1460
  * when the ref does not resolve to a REQUIRED (non-opt) native scalar (then the caller falls back to the
@@ -1555,19 +1535,8 @@ function movableRefs(comp) {
1555
1535
  function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1556
1536
  const ep = execPlan(comp);
1557
1537
  const order = ep.order;
1558
- const hasConcurrency = ep.parallelStageOf.size > 0;
1559
1538
  const fn = sanitize(comp.name);
1560
1539
  const isAsync = ap.runnerIsAsync;
1561
- // bc#97: the async runner awaits each async handler at its call site (derived per-node). A real-
1562
- // concurrency stage (bc#87) dispatches handlers from scoped std threads — that mechanism cannot host
1563
- // `.await` (a std thread is not an async task). Fail closed LOUDLY (rather than emit code that won't
1564
- // compile) iff the runner is async AND has a concurrency stage. NOTE: with per-node granularity a
1565
- // consumer CAN keep a concurrency-stage component sync (declare only its OTHER terminals async) — only
1566
- // a component that both concurrency-stages AND awaits is rejected. Async + concurrent-stage (issuing
1567
- // the stage's futures with join!) is a documented follow-up.
1568
- if (isAsync && hasConcurrency) {
1569
- 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.`);
1570
- }
1571
1540
  const typedNodes = new Map();
1572
1541
  // #125: control-gate は typeless(typedNodes に載せない)。map ノードは produced-array ref に正規化
1573
1542
  // (recorder SoT の element outType を {arr:element} へラップ / legacy {arr} はそのまま)。
@@ -1608,7 +1577,11 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1608
1577
  lines.push(`// results are typed struct cells; a relation child reads the parent's REAL struct result via`);
1609
1578
  lines.push(`// direct field access (child-present decision from the real parent value — relation /`);
1610
1579
  lines.push(`// connection converge). A real-concurrency stage (bc#87) is static parallel orchestration —`);
1611
- lines.push(`// scoped worker threads (bounded by the static plan.concurrency) call the transport; preflight +`);
1580
+ // #231: the dispatch MECHANISM a stage uses is derived from its members' async-ness (a std thread cannot
1581
+ // host `.await`), so the banner names the one this component actually emits.
1582
+ lines.push([...new Set(ep.parallelStageOf.values())].some((s) => stageAwaits(comp, s, ap))
1583
+ ? `// the stage's futures joined (bounded by the static plan.concurrency) call the transport; preflight +`
1584
+ : `// scoped worker threads (bounded by the static plan.concurrency) call the transport; preflight +`);
1612
1585
  lines.push(`// interpret are committed in ascending index order so the value / op multiset / failure`);
1613
1586
  lines.push(`// precedence byte-match run_behavior. The output is a typed struct/value assembled by struct`);
1614
1587
  lines.push(`// literal + field access — the consumer keeps it native.`);
@@ -1643,7 +1616,7 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1643
1616
  const i = order[k];
1644
1617
  const stage = ep.parallelStageOf.get(i);
1645
1618
  if (stage !== undefined && stage[0] === i) {
1646
- lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt, leaf));
1619
+ lines.push(emitParallelStageArm(comp, stage, k, ep.concurrency, metas, typedNodes, plan, priorNodeAt, leaf, ap));
1647
1620
  k += stage.length - 1;
1648
1621
  continue;
1649
1622
  }
@@ -1762,21 +1735,36 @@ function emitNativeRawRunner(comp, plan, ap, leaf, declared) {
1762
1735
  return lines.join("\n");
1763
1736
  }
1764
1737
  /**
1765
- * emitParallelStageArm (bc#87/#94, rust CONCRETE) — EXPLICIT static parallel orchestration for a real-
1766
- * concurrency stage. Reproduces run_plan_parallel's deterministic protocol so the observed value / op
1738
+ * stageAwaits (#231) — the ONE derivation of a real-concurrency stage's dispatch MECHANISM: a std thread
1739
+ * cannot host `.await`, so a stage dispatches by joining its members' futures iff ANY member awaits, and
1740
+ * by scoped std threads otherwise. Read per-node from the SHARED language-agnostic async propagation pass
1741
+ * (async-plan.ts) — the same SSoT the sequential arms consume. A no-dispatch member (cond / pure-expression
1742
+ * map) has no catalog component, so `nodeIsAsync` is false for it and it never flips the mechanism.
1743
+ */
1744
+ function stageAwaits(comp, stage, ap) {
1745
+ return stage.some((i) => ap.nodeIsAsync(comp.body[i].id));
1746
+ }
1747
+ /**
1748
+ * emitParallelStageArm (bc#87/#94/#231, rust CONCRETE) — EXPLICIT static parallel orchestration for a
1749
+ * real-concurrency stage. Reproduces run_plan_parallel's deterministic protocol so the observed value / op
1767
1750
  * multiset / failure precedence byte-match run_behavior:
1768
1751
  * 1. PREFLIGHT (ascending): parent-produced gate + build each member's CONCRETE ports struct.
1769
- * 2. DISPATCH (bounded scoped threads): share `&H` (the concrete trait; `H: Sync`), pull runnable
1770
- * members from a shared atomic cursor in ascending order, call the concrete node_* method. Each
1771
- * concrete row lands in a per-member Mutex slot (None = unknown component).
1752
+ * 2. DISPATCH (bounded — ONE phase, two mechanisms picked by the members' derived async-ness):
1753
+ * - SYNC members: scoped std threads pull runnable members from a shared atomic cursor in ascending
1754
+ * order and call the leaf transport. Each result wire lands in a per-member Mutex slot.
1755
+ * - ASYNC members (#231): a std thread cannot host `.await`, so the stage's FUTURES are joined
1756
+ * instead — one lazily-built future per RUNNABLE member (a skipped member gets no future at all),
1757
+ * driven by a `std::future::poll_fn` scheduler that admits members in ascending order and keeps at
1758
+ * most `workers` of them in flight. A future that is never polled has never started, so "in flight"
1759
+ * IS "admitted and unsettled" — that is how the static bound is enforced without a runtime, without
1760
+ * the `futures` crate and without boxing. Each result lands in a per-member plain Option slot (the
1761
+ * scheduler is one task on one thread — no lock to take).
1772
1762
  * 3. COMMIT (ascending index): interpret policy + move the concrete row into the outType cell —
1773
- * lowest-index failure wins.
1763
+ * lowest-index failure wins. IDENTICAL for both mechanisms (only the slot read differs).
1774
1764
  */
1775
- function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt, leaf) {
1765
+ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes, plan, priorNodeAt, leaf, ap) {
1776
1766
  const lines = [];
1777
1767
  const ids = stage.map((i) => comp.body[i].id);
1778
- lines.push(` // ── bc#87 real-concurrency stage {${ids.map((x) => rustStrLit(x)).join(", ")}} — static parallel`);
1779
- lines.push(` // orchestration (scoped threads, bound=${concurrency}); preflight+commit in ascending index order.`);
1780
1768
  // #125/#108: a stage member may be a cond node — a pure Expression (NO handler/dispatch). The scoped-
1781
1769
  // thread orchestration governs only the componentRef fan-out members; a cond is settled in ascending
1782
1770
  // preflight order — BEFORE any dispatch — via the SAME emitCondArm the sequential path uses (no forked
@@ -1790,6 +1778,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1790
1778
  const noDispatch = (i) => "cond" in comp.body[i] || ("map" in comp.body[i] && mapTransformExpr(comp.body[i].map) !== undefined);
1791
1779
  const condMembers = stage.filter(noDispatch);
1792
1780
  const refMembers = stage.filter((i) => !noDispatch(i));
1781
+ const stageIsAsync = stageAwaits(comp, stage, ap);
1782
+ lines.push(` // ── bc#87 real-concurrency stage {${ids.map((x) => rustStrLit(x)).join(", ")}} — static parallel`);
1783
+ lines.push(` // orchestration (${stageIsAsync ? "joined futures" : "scoped threads"}, bound=${concurrency}); preflight+commit in ascending index order.`);
1793
1784
  for (const i of condMembers) {
1794
1785
  const n = comp.body[i];
1795
1786
  lines.push("cond" in n
@@ -1797,9 +1788,9 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1797
1788
  : // 純式 map は leaf を呼ばないので async 性を持たない(sync 既定)。
1798
1789
  emitMapArm(comp, n, atPos + stage.indexOf(i), typedNodes, plan, priorNodeAt, leaf, false, metas[i].policy));
1799
1790
  }
1800
- // A cond-ONLY stage carries no handler fan-out — the conds above ARE the whole stage. Skip the scoped-
1801
- // thread orchestration block entirely (an empty one is dead scaffolding clippy rejects: never_loop /
1802
- // match_single_binding on a zero-job scope).
1791
+ // A cond-ONLY stage carries no handler fan-out — the conds above ARE the whole stage. Skip the dispatch
1792
+ // block entirely (an empty one is dead scaffolding clippy rejects: never_loop / match_single_binding on
1793
+ // a zero-job scope, and a zero-member poll_fn scheduler is likewise dead).
1803
1794
  if (refMembers.length === 0)
1804
1795
  return lines.join("\n");
1805
1796
  lines.push(` {`);
@@ -1853,63 +1844,137 @@ function emitParallelStageArm(comp, stage, atPos, concurrency, metas, typedNodes
1853
1844
  for (const c of closers)
1854
1845
  lines.push(c);
1855
1846
  }
1856
- // 2) DISPATCH (bounded scoped threads). Each worker calls the leaf TRANSPORT directly for its member's
1857
- // CONCRETE ports and stores the returned wire in its slot. #125: the fan-out (slots / jobs / workers)
1858
- // spans the COMPONENTREF members only — a control gate dispatches no handler (committed in preflight
1859
- // above), so it is not a scoped-thread job. The wire's concrete type is inferred from the transport's
1860
- // return (Result<_, BehaviorError>); it impls Send so it crosses the scoped threads.
1847
+ // 2) DISPATCH (bounded). Each runnable member calls the leaf TRANSPORT directly for its CONCRETE ports
1848
+ // and stores the returned wire in its slot; the ascending COMMIT phase de-boxes it (so the WIRE — not
1849
+ // the decode — is what crosses the dispatch). #125: the fan-out (slots / jobs / workers) spans the
1850
+ // COMPONENTREF members only — a control gate dispatches no handler (committed in preflight above), so it
1851
+ // is not a job. The wire's concrete type is inferred from the transport's return
1852
+ // (Result<_, BehaviorError>).
1861
1853
  const nMembers = refMembers.length;
1862
1854
  const boundN = Math.min(concurrency, nMembers);
1863
1855
  const jobsVar = `jobs_${sanitize(comp.name)}`;
1864
- for (const i of refMembers) {
1865
- const s = sanitize(comp.body[i].id);
1866
- // every member's thread returns the result WIRE; the ascending COMMIT phase de-boxes it (so the wire —
1867
- // not the decode — is what crosses the scoped threads).
1868
- lines.push(` let slot_${s}: std::sync::Mutex<Option<Result<_, BehaviorError>>> = std::sync::Mutex::new(None);`);
1869
- }
1870
- lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1871
- refMembers.forEach((i, slot) => {
1872
- const s = sanitize(comp.body[i].id);
1873
- lines.push(` if payload_${s}.lock().unwrap().is_some() { ${jobsVar}.push(${slot}); }`);
1874
- });
1875
- lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
1876
- lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
1877
- lines.push(` std::thread::scope(|scope| {`);
1878
- lines.push(` for _ in 0..workers {`);
1879
- lines.push(` scope.spawn(|| loop {`);
1880
- lines.push(` let j = cursor.fetch_add(1, std::sync::atomic::Ordering::SeqCst);`);
1881
- lines.push(` if j >= ${jobsVar}.len() { break; }`);
1882
- lines.push(` let slot = ${jobsVar}[j];`);
1883
- lines.push(` match slot {`);
1884
- refMembers.forEach((i, slot) => {
1856
+ // the RUNNABLE-member job list + the static bound are mechanism-independent: both dispatch forms pull
1857
+ // jobs in ascending order and hold at most `workers` of them at a time. It is built BEFORE any payload is
1858
+ // taken — TAKING the payload is what dispatch does, so the list has to be read off the intact payloads.
1859
+ const emitJobList = () => {
1860
+ lines.push(` let mut ${jobsVar}: Vec<usize> = Vec::new();`);
1861
+ refMembers.forEach((i, slot) => {
1862
+ lines.push(` if payload_${sanitize(comp.body[i].id)}.lock().unwrap().is_some() { ${jobsVar}.push(${slot}); }`);
1863
+ });
1864
+ };
1865
+ const leafSym = (i) => {
1885
1866
  const node = comp.body[i];
1886
- const s = sanitize(node.id);
1887
- // DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports,
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).
1890
- const call = `${resolveLeafSymbol(node.component, leaf, node.leafSymbol)}(payload)`;
1891
- lines.push(` ${slot} => {`);
1892
- lines.push(` let payload = payload_${s}.lock().unwrap().take().expect("runnable member has ports");`);
1893
- lines.push(` let row = ${call};`);
1894
- lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1895
- lines.push(` }`);
1896
- });
1897
- lines.push(` _ => unreachable!(),`);
1898
- lines.push(` };`);
1899
- lines.push(` });`);
1900
- lines.push(` }`);
1901
- lines.push(` });`);
1902
- // 3) COMMIT (ascending index): interpret + move the concrete row into the outType cell.
1867
+ return resolveLeafSymbol(node.component, leaf, node.leafSymbol);
1868
+ };
1869
+ if (stageIsAsync) {
1870
+ // #231 ASYNC dispatch: one future per RUNNABLE member (a skipped member's `payload_<s>` is None, so
1871
+ // `Option::map` yields NO future — it is never constructed and never polled), pinned on the stack. An
1872
+ // async member's future IS the transport call; a SYNC member in the same stage is wrapped in an async
1873
+ // block so it starts when the scheduler admits it (calling it eagerly would ignore the bound). The
1874
+ // scheduler below is the join: it admits members in ASCENDING order, keeps at most `workers` in flight
1875
+ // (a future that has not been polled has not started), and settles each into a plain Option slot — one
1876
+ // task on one thread, so no lock. No `futures` crate, no boxing: every future is a concrete stack type.
1877
+ // The future MOVES the payload out of its slot (same take-not-clone as the scoped-thread arm).
1878
+ emitJobList();
1879
+ for (const i of refMembers) {
1880
+ const s = sanitize(comp.body[i].id);
1881
+ const taken = `payload_${s}.lock().unwrap().take()`;
1882
+ const fut = ap.nodeIsAsync(comp.body[i].id)
1883
+ ? `${taken}.map(${leafSym(i)})`
1884
+ : `${taken}.map(|payload| async move { ${leafSym(i)}(payload) })`;
1885
+ lines.push(` let mut fut_${s} = std::pin::pin!(${fut});`);
1886
+ lines.push(` let mut slot_${s}: Option<Result<_, BehaviorError>> = None;`);
1887
+ }
1888
+ lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
1889
+ lines.push(` let mut settled = [false; ${nMembers}];`);
1890
+ lines.push(` let mut admitted = 0usize;`);
1891
+ lines.push(` let mut in_flight = 0usize;`);
1892
+ lines.push(` std::future::poll_fn(|cx| {`);
1893
+ lines.push(` loop {`);
1894
+ lines.push(` while in_flight < workers && admitted < ${jobsVar}.len() {`);
1895
+ lines.push(` admitted += 1;`);
1896
+ lines.push(` in_flight += 1;`);
1897
+ lines.push(` }`);
1898
+ lines.push(` let mut progressed = false;`);
1899
+ lines.push(` for (j, slot) in ${jobsVar}.iter().copied().enumerate().take(admitted) {`);
1900
+ lines.push(` if settled[j] { continue; }`);
1901
+ lines.push(` let ready = match slot {`);
1902
+ refMembers.forEach((i, slot) => {
1903
+ const s = sanitize(comp.body[i].id);
1904
+ lines.push(` ${slot} => {`);
1905
+ lines.push(` let f = fut_${s}.as_mut().as_pin_mut().expect("runnable member has a future");`);
1906
+ lines.push(` match std::future::Future::poll(f, cx) {`);
1907
+ lines.push(` std::task::Poll::Ready(r) => {`);
1908
+ lines.push(` slot_${s} = Some(r);`);
1909
+ lines.push(` true`);
1910
+ lines.push(` }`);
1911
+ lines.push(` std::task::Poll::Pending => false,`);
1912
+ lines.push(` }`);
1913
+ lines.push(` }`);
1914
+ });
1915
+ lines.push(` _ => unreachable!(),`);
1916
+ lines.push(` };`);
1917
+ lines.push(` if ready {`);
1918
+ lines.push(` settled[j] = true;`);
1919
+ lines.push(` in_flight -= 1;`);
1920
+ lines.push(` progressed = true;`);
1921
+ lines.push(` }`);
1922
+ lines.push(` }`);
1923
+ lines.push(` if admitted == ${jobsVar}.len() && in_flight == 0 {`);
1924
+ lines.push(` return std::task::Poll::Ready(());`);
1925
+ lines.push(` }`);
1926
+ lines.push(` if !progressed { return std::task::Poll::Pending; }`);
1927
+ lines.push(` }`);
1928
+ lines.push(` })`);
1929
+ lines.push(` .await;`);
1930
+ }
1931
+ else {
1932
+ // SYNC dispatch: bounded scoped std threads pulling from a shared atomic cursor in ascending order.
1933
+ // The result wire impls Send so it crosses the scoped threads.
1934
+ for (const i of refMembers) {
1935
+ lines.push(` let slot_${sanitize(comp.body[i].id)}: std::sync::Mutex<Option<Result<_, BehaviorError>>> = std::sync::Mutex::new(None);`);
1936
+ }
1937
+ emitJobList();
1938
+ lines.push(` let cursor = std::sync::atomic::AtomicUsize::new(0);`);
1939
+ lines.push(` let workers = ${boundN}usize.min(${jobsVar}.len());`);
1940
+ lines.push(` std::thread::scope(|scope| {`);
1941
+ lines.push(` for _ in 0..workers {`);
1942
+ lines.push(` scope.spawn(|| loop {`);
1943
+ lines.push(` let j = cursor.fetch_add(1, std::sync::atomic::Ordering::SeqCst);`);
1944
+ lines.push(` if j >= ${jobsVar}.len() { break; }`);
1945
+ lines.push(` let slot = ${jobsVar}[j];`);
1946
+ lines.push(` match slot {`);
1947
+ refMembers.forEach((i, slot) => {
1948
+ const s = sanitize(comp.body[i].id);
1949
+ // DIRECT leaf transport call — ONE op-agnostic symbol, ONE WireRow payload (the preflight-built ports,
1950
+ // MOVED into the owned-arg call — the worker that wins the slot takes it). No `bound` (BC's internal
1951
+ // produced/skip gate is already applied in preflight — the leaf never sees it).
1952
+ lines.push(` ${slot} => {`);
1953
+ lines.push(` let payload = payload_${s}.lock().unwrap().take().expect("runnable member has ports");`);
1954
+ lines.push(` let row = ${leafSym(i)}(payload);`);
1955
+ lines.push(` *slot_${s}.lock().unwrap() = Some(row);`);
1956
+ lines.push(` }`);
1957
+ });
1958
+ lines.push(` _ => unreachable!(),`);
1959
+ lines.push(` };`);
1960
+ lines.push(` });`);
1961
+ lines.push(` }`);
1962
+ lines.push(` });`);
1963
+ }
1964
+ // 3) COMMIT (ascending index): interpret + move the concrete row into the outType cell. IDENTICAL for
1965
+ // both dispatch mechanisms — only the slot read differs (a joined-futures slot needs no lock).
1903
1966
  refMembers.forEach((i) => {
1904
1967
  const node = comp.body[i];
1905
1968
  const meta = metas[i];
1906
1969
  const s = sanitize(node.id);
1907
1970
  const ref = typedNodes.get(node.id);
1908
1971
  // 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).
1972
+ // out of the stage (the payload was already taken at dispatch, so it can no longer answer that).
1910
1973
  // 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();`);
1974
+ // whole body, which outlives the borrow the body needs. A joined-futures slot is a plain Option (one
1975
+ // task on one thread), so it takes without a lock.
1976
+ const takeSlot = stageIsAsync ? `slot_${s}.take()` : `slot_${s}.lock().unwrap().take()`;
1977
+ lines.push(` let taken_${s} = ${takeSlot};`);
1913
1978
  lines.push(` if let Some(out_${s}) = taken_${s} {`);
1914
1979
  if (meta.policy === "continue") {
1915
1980
  // continue: a member whose COMPONENT failed commits no Port. A de-box mismatch still propagates —
@@ -2660,413 +2725,6 @@ use std::cell::RefCell;`;
2660
2725
  ];
2661
2726
  return `${sections.filter((x) => !!x).join("\n\n")}\n`;
2662
2727
  }
2663
- /**
2664
- * rustTypedNativeObserve — the TEST-ONLY observe companion (a submodule string the test harness writes
2665
- * alongside the covered module). It carries the typed->Value serializers (ser_*) + the SCRIPTED analog of
2666
- * the consumer's leaf transport symbols: free \`leaf_<comp>\` fns that drain a shared scripted static and
2667
- * return the scripted wire (so the covered module's transport calls resolve to real fns), + an
2668
- * observe_native_raw dispatch that fills the static from the per-case spec, decodes the generic input into
2669
- * the concrete InNR_<comp>, drives the module-private struct runner, and serializes its result to a
2670
- * canonical Value for the equivalence pin. Lives OUTSIDE the covered module so the module stays literal
2671
- * whole-file zero (the ser_* / decode helpers are test glue, never on the consumer's read hot path).
2672
- */
2673
- export function rustTypedNativeObserve(ir, ioModel = "sync", leaf, declared) {
2674
- const components = ir.components;
2675
- const native = components.filter(isNativeRaw);
2676
- const plan = buildTypePlan(ir);
2677
- const needSync = native.some((c) => concurrencyPlan(c) !== null);
2678
- const serializers = emitSerializers(plan);
2679
- const marshallers = emitMarshallers(plan);
2680
- // bc#97: the observe glue must MATCH the covered module's per-node async-ness — the scripted handler's
2681
- // node_* methods are `async fn` exactly where the trait's are, and observe_native_raw awaits an async
2682
- // runner. Built from the SAME SSoT propagation pass the covered emitter used, so glue never drifts.
2683
- const asyncPlans = buildAsyncPlans(ir, ioModel);
2684
- const anyAsyncRunner = native.some((c) => asyncPlans.get(c.name).runnerIsAsync);
2685
- // ── per-component input decoders: generic &[(String,Value)] -> concrete InNR_<comp> (test glue). ──
2686
- const inDecoders = native.map((c) => emitInDecoder(c, plan, declared)).join("\n\n");
2687
- // every covered node returns a WireValue the inline de-box classifies — so the scripted wire adapter is
2688
- // needed whenever any component has a handler node.
2689
- const anyDeBox = native.some((c) => c.body.some((n) => !("cond" in n)));
2690
- // value_to_wire (TEST glue): builds the covered module's BC-OWNED concrete `WireValue` from a scripted bc
2691
- // `Value` — the test-harness analog of the consumer's real transport (which builds `WireValue` as it reads
2692
- // the producer). Numbers ride in their declared type (WireValue::Int / WireValue::Float) — nothing parses;
2693
- // the wire tags + classification live ONCE in the covered module's WireValue (probe_*_at), so this only
2694
- // CONSTRUCTS — a scripted wrong-variant value maps to the corresponding WireValue variant and the covered
2695
- // de-box classifies it (TYPE_MISMATCH ≡ run_behavior), no separate scripted classifier.
2696
- const wireAdapter = anyDeBox
2697
- ? `// ── value_to_wire (TEST glue): scripted bc Value -> the covered module's BC-owned WireValue ──
2698
- fn value_to_wire(v: &Value) -> WireValue {
2699
- match v {
2700
- Value::Null => WireValue::Null,
2701
- Value::Bool(b) => WireValue::Bool(*b),
2702
- Value::Int(n) => WireValue::Int(*n),
2703
- Value::Float(f) => WireValue::Float(*f),
2704
- Value::Str(s) => WireValue::Str(Cow::Owned(s.clone())),
2705
- Value::Arr(items) => WireValue::List(WireList { items: items.iter().map(value_to_wire).collect() }),
2706
- Value::Obj(pairs) => WireValue::Row(WireRow {
2707
- entries: pairs.iter().map(|(k, vv)| (Cow::Owned(k.clone()), value_to_wire(vv))).collect(),
2708
- }),
2709
- }
2710
- }`
2711
- : "";
2712
- // ── op-agnostic leaf TRANSPORT fns (TEST glue) — the scripted analog of the consumer's transport
2713
- // symbols. ONE free `leaf_<component>` per DISTINCT covered leaf (catalog component) in the IR (a
2714
- // per-module leaf has one consistent shape — verified), draining the shared scripted-outcome static and
2715
- // returning the scripted wire in EXACTLY the shape the removed per-node trait method returned. bc#87
2716
- // parallel scoped threads share the static (Mutex-guarded); cases run sequentially so a shared static is
2717
- // fine. Echo (#129/#141) reads the spread port params directly. ──
2718
- // ONE free transport per DISTINCT SPEC-fixed SYMBOL (#176/#183), UNIFORM signature
2719
- // `<sym>(payload: WireRow) -> Result<WireValue, BehaviorError>`: value_to_wire is recursive, so a
2720
- // batched/fanout `Value::Arr` result becomes a `WireValue::List` (a `Value::Null` element → WireValue::Null,
2721
- // the dangling marker) and a single result a scalar/row wire — ONE signature serves every cardinality. Echo
2722
- // (#129/#141) reads the port back FROM THE PAYLOAD BY NAME. A spec-named leaf used in MULTIPLE roles is
2723
- // emitted ONCE; two nodes → same symbol but DIFFERENT catalog is a LOUD collision (never silent).
2724
- const transportFns = [];
2725
- const bySym = new Map();
2726
- for (const c of native) {
2727
- const ap = asyncPlans.get(c.name);
2728
- const typedNodes = new Map();
2729
- for (const n of c.body)
2730
- if (!isControlGate(n))
2731
- typedNodes.set(n.id, "map" in n ? mapNodeArrRef(n, plan) : deriveTypeRef(n.outType, plan)); // #125: control-gate typeless; map は produced-array ref に正規化
2732
- for (const n of c.body) {
2733
- if ("cond" in n)
2734
- continue; // #108: a cond node has no leaf (pure Expression) — no transport fn.
2735
- // #225: 純式 map も Component を呼ばないので transport fn を持たない(cond と同じ)。
2736
- if ("map" in n && mapTransformExpr(n.map) !== undefined)
2737
- continue;
2738
- const catalog = ("fanout" in n ? n.fanout.component : "map" in n ? n.map.component : n.component);
2739
- const specSym = "fanout" in n ? n.fanout.leafSymbol : "map" in n ? n.map.leafSymbol : n.leafSymbol;
2740
- const sym = resolveLeafSymbol(catalog, leaf, specSym);
2741
- const isAsync = ap.nodeIsAsync(n.id);
2742
- // echo branches (point/componentRef nodes only — a batched/fanout node returns a WireList, not a port).
2743
- const echo = [];
2744
- if (!("fanout" in n) && !("map" in n)) {
2745
- const node = n;
2746
- const crNarrowed = nodeNarrowedPaths(c, node);
2747
- const ref = typedNodes.get(n.id);
2748
- if (ref.kind === "named") {
2749
- const decl = findDecl(plan, ref.name);
2750
- const field = decl !== undefined && decl.fields.length === 1 ? decl.fields[0] : undefined;
2751
- const fieldRust = field !== undefined ? renderTypeRef(field.type) : null;
2752
- const recordRust = renderTypeRef(ref);
2753
- for (const pn of Object.keys(node.ports)) {
2754
- let portRust = null;
2755
- try {
2756
- portRust = portFieldRustType(node.ports[pn], c, plan, typedNodes, inputPortTypeRef(node.portSchemas?.[pn], plan), `echo port '${pn}'`, { narrowed: crNarrowed });
2757
- }
2758
- catch {
2759
- portRust = null;
2760
- }
2761
- if (portRust === recordRust) {
2762
- // the port IS the whole record → echo its payload wire DIRECTLY (matching run_behavior's echo:port).
2763
- echo.push(` if echo == ${rustStrLit(pn)} {\n if let Some(v) = payload.take(${rustStrLit(pn)}) {\n return Ok(v);\n }\n }`);
2764
- }
2765
- else if (fieldRust !== null && field !== undefined && portRust === fieldRust) {
2766
- // a scalar port wraps into the record's single field ({v: <port wire>}) — mirrors the scripted `wrap`.
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 }`);
2768
- }
2769
- }
2770
- }
2771
- else if (ref.kind === "arr" && Object.prototype.hasOwnProperty.call(node.ports, "items")) {
2772
- // #129: an arr node with an `items` port echoes the payload's items wire (a WireList) so the
2773
- // node→leaf array dataflow test is non-vacuous.
2774
- echo.push(` if echo == "items" {\n if let Some(v) = payload.take("items") {\n return Ok(v);\n }\n }`);
2775
- }
2776
- }
2777
- const prev = bySym.get(sym);
2778
- if (prev !== undefined) {
2779
- // #176/#183: a spec-fixed symbol MUST map to exactly ONE leaf. The same leaf in multiple roles shares
2780
- // ONE transport — accumulate its echo branches. Two DIFFERENT catalog components → same symbol is a
2781
- // codegen error (never silent).
2782
- if (prev.catalog !== catalog)
2783
- throw new GeneratorFailure("DUPLICATE_COMPONENT", `rust typed-native observe: leaf transport symbol '${sym}' resolves to TWO different catalog components ('${prev.catalog}' and '${catalog}') — a spec-fixed leaf symbol must map to ONE leaf (collision, fail-closed).`);
2784
- for (const e of echo)
2785
- if (!prev.echo.includes(e))
2786
- prev.echo.push(e);
2787
- continue;
2788
- }
2789
- bySym.set(sym, { catalog, async: isAsync, echo });
2790
- }
2791
- }
2792
- for (const [sym, le] of bySym) {
2793
- const fnKw = le.async ? "pub async fn" : "pub fn";
2794
- const hasEcho = le.echo.length > 0;
2795
- const echoBind = hasEcho ? "echo" : "_echo";
2796
- const echoBlock = hasEcho ? `${le.echo.join("\n")}\n` : "";
2797
- transportFns.push(`${fnKw} ${sym}(${hasEcho ? "mut payload" : "_payload"}: WireRow) -> Result<WireValue, BehaviorError> {
2798
- let (is_err, err, ok, ${echoBind}) = next_scripted(${rustStrLit(le.catalog)}).ok_or_else(|| unknown_component(${rustStrLit(le.catalog)}))?;
2799
- if is_err {
2800
- return Err(leaf_failure(err));
2801
- }
2802
- ${echoBlock} Ok(value_to_wire(&ok.unwrap_or(Value::Null)))
2803
- }`);
2804
- }
2805
- const arms = native
2806
- .map((c) => {
2807
- const outRef = c.outputType !== undefined ? deriveTypeRef(c.outputType, plan) : undefined;
2808
- const ser = outRef ? serializeTyped("tv", outRef, plan) : "tv";
2809
- // bc#90 / runtime-free: the covered runner returns the module-LOCAL `BehaviorError` (via super::*);
2810
- // bridge it to the bc-runtime `behavior_contracts::BehaviorError` at the observe boundary (same
2811
- // code/message) so the conformance harness (main.rs) reads the stable code without the covered
2812
- // module ever touching bc runtime. decode_* is test glue and returns the local error too.
2813
- // bc#97: an async runner returns a Future — drive it to completion with the std-only block-on
2814
- // (bc_block_on) so observe_native_raw keeps its SYNC external signature (the harness is unchanged).
2815
- // The scripted async node_* return ready values, so the future needs no real executor / no runtime.
2816
- // #192: decode the generic test input into the entry's POSITIONAL args (test glue), then call the
2817
- // 1:1 entry positionally (box removed). A no-input entry is called with no args (no decoder).
2818
- const args = entryPortOrder(c, declared).map((p) => rustFieldName(p));
2819
- const runnerCall = `super::${rustFieldName(c.name)}(${args.join(", ")})`;
2820
- const driven = asyncPlans.get(c.name).runnerIsAsync ? `bc_block_on(${runnerCall})` : runnerCall;
2821
- const decode = args.length === 0 ? "" : ` let (${args.join(", ")},) = decode_${sanitize(c.name)}(input).map_err(to_rt_err)?;\n`;
2822
- const unusedInput = args.length === 0 ? " let _ = input;\n" : "";
2823
- return ` ${rustStrLit(c.name)} => {\n${decode}${unusedInput} let tv = ${driven}.map_err(to_rt_err)?;\n Ok(${ser})\n }`;
2824
- })
2825
- .join("\n");
2826
- // the scripted-outcome source is a MODULE-LEVEL static (Mutex<Option<HashMap>> + AtomicUsize), NOT a
2827
- // per-call handler object: the free transport fns drain it, and observe_native_raw resets+fills it from
2828
- // the per-case handlers spec before driving the runner. A static (not thread_local) so the bc#87 parallel
2829
- // scoped threads — which call the transport fns concurrently — share it (Mutex-guarded). Cases run
2830
- // sequentially in the harness, so one shared static per case is fine.
2831
- const adapter = `// SCRIPTED_QUEUES — the shared scripted-outcome source the free leaf transport fns drain (TEST glue).
2832
- // { "<component>": (queue, single) }. reset+filled per case by observe_native_raw. \`Mutex::new(None)\` is
2833
- // a const initializer (no LazyLock/OnceLock needed). SCRIPTED_SEEN mirrors the old probe counter.
2834
- static SCRIPTED_QUEUES: std::sync::Mutex<Option<std::collections::HashMap<String, (Vec<serde_json::Value>, bool)>>> =
2835
- std::sync::Mutex::new(None);
2836
- #[allow(dead_code)]
2837
- static SCRIPTED_SEEN: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
2838
-
2839
- // fill_scripted — reset + load the shared static from the JSON handlers spec: { "<component>": {ok|error}
2840
- // | [ {ok|error}, … ] }.
2841
- fn fill_scripted(spec: &serde_json::Map<String, serde_json::Value>) {
2842
- let mut map = std::collections::HashMap::new();
2843
- for (name, raw) in spec {
2844
- let (items, single) = match raw {
2845
- serde_json::Value::Array(a) => (a.clone(), false),
2846
- other => (vec![other.clone()], true),
2847
- };
2848
- map.insert(name.clone(), (items, single));
2849
- }
2850
- *SCRIPTED_QUEUES.lock().unwrap() = Some(map);
2851
- SCRIPTED_SEEN.store(0, std::sync::atomic::Ordering::SeqCst);
2852
- }
2853
-
2854
- // next_scripted — drain one scripted outcome for a component (last entry repeats — mirrors the reference
2855
- // scripted handlers); None when the component has no scripted queue. Returns (is_error, err, ok_value,
2856
- // echo). The bc#87 parallel-stage runner calls the transport fns from multiple threads, so the drain is
2857
- // Mutex-guarded. #129: \`echo\` carries the reference scriptedHandlers' \`echo\` directive (e.g. "items")
2858
- // so a scripted node can ECHO a named input PORT back — used to make the node→leaf array dataflow test
2859
- // non-vacuous (the leaf returns its \`items\` port; a dropped/boxed array diverges).
2860
- fn next_scripted(component: &str) -> Option<(bool, String, Option<Value>, String)> {
2861
- SCRIPTED_SEEN.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2862
- let mut guard = SCRIPTED_QUEUES.lock().unwrap();
2863
- let map = guard.as_mut()?;
2864
- let (queue, single) = map.get_mut(component)?;
2865
- let raw = if *single || queue.len() <= 1 { queue[0].clone() } else { queue.remove(0) };
2866
- // normalize echo:port to the port NAME X so a de-box handler's echo comparison fires;
2867
- // echo:items already names the port directly.
2868
- let echo = {
2869
- let e = raw.get("echo").and_then(|e| e.as_str()).unwrap_or("");
2870
- if e == "port" { raw.get("port").and_then(|p| p.as_str()).unwrap_or("").to_string() } else { e.to_string() }
2871
- };
2872
- if let Some(okv) = raw.get("ok") {
2873
- let v = behavior_contracts::decode_value(okv).expect("decode ok");
2874
- Some((false, String::new(), Some(v), echo))
2875
- } else {
2876
- let e = raw.get("error").and_then(|e| e.as_str()).unwrap_or("").to_string();
2877
- Some((true, e, None, echo))
2878
- }
2879
- }`;
2880
- void needSync;
2881
- return `// GENERATED test-only observe companion (bc#77/#94) — NOT part of the covered module. Serializes the
2882
- // struct-native runner's result to a canonical Value for the equivalence pin, and carries the SCRIPTED
2883
- // analog of the consumer's leaf transport symbols: free \`leaf_<comp>\` fns that drain a shared scripted
2884
- // static and return the scripted wire (exactly the shape the removed per-node trait method returned). The
2885
- // consumer never uses this (it keeps the model native + supplies its own transport fns over its own wire
2886
- // payload); it exists only so the test harness can byte-compare the STRUCT-only covered read against
2887
- // run_behavior. A submodule of the covered module (reads its pub entry fns + the CONCRETE
2888
- // structs — incl. the LOCAL BehaviorError — via super::*, and its \`leaf_<comp>\` fns resolve the covered
2889
- // module's transport calls). bc#90 / runtime-free: the covered module's BehaviorError is LOCAL, so this
2890
- // test-glue companion refers to it via super::* (as \`BehaviorError\`) and refers to the bc-runtime failure
2891
- // type FULLY-QUALIFIED (\`behavior_contracts::BehaviorError\`) only where it bridges at the observe boundary.
2892
- // The transport-fn signatures spread the port fields, so they carry \`&String\`/\`&Vec\` params and (for
2893
- // point reads) many args — clippy::ptr_arg / too_many_arguments are TEST-glue-only allows here.
2894
- #![allow(dead_code, unused_imports, unused_variables, non_snake_case, clippy::ptr_arg, clippy::too_many_arguments, clippy::needless_lifetimes, clippy::type_complexity)]
2895
- use behavior_contracts::Value;
2896
- use super::*;
2897
-
2898
- // bridge the covered module's LOCAL BehaviorError (super::BehaviorError) to the bc-runtime failure type
2899
- // the conformance harness reads (same code + message + structured detail) — the ONLY place the two meet
2900
- // (test glue). The de-box's structured Error Value is carried over so the harness can assert it.
2901
- fn to_rt_err(e: BehaviorError) -> behavior_contracts::BehaviorError {
2902
- let mut rt = behavior_contracts::BehaviorError::new(e.code, e.message);
2903
- if let Some(d) = e.detail {
2904
- let d = *d;
2905
- rt.detail = Some(Box::new(behavior_contracts::ErrorDetail {
2906
- kind: d.kind.map(|k| match k {
2907
- ErrorKind::TypeMismatch => behavior_contracts::ErrorKind::TypeMismatch,
2908
- ErrorKind::MissingField => behavior_contracts::ErrorKind::MissingField,
2909
- ErrorKind::Overflow => behavior_contracts::ErrorKind::Overflow,
2910
- }),
2911
- model: d.model,
2912
- field: d.field,
2913
- expected_type: d.expected_type,
2914
- actual_wire_type: d.actual_wire_type,
2915
- raw_value: d.raw_value,
2916
- context: d.context,
2917
- }));
2918
- }
2919
- rt
2920
- }
2921
- ${anyAsyncRunner
2922
- ? `// bc#97 (TEST glue) — a minimal std-only block-on that drives an async runner Future to completion so
2923
- // observe_native_raw stays sync-callable (the harness never changes). The covered async fn's futures are
2924
- // ready (the scripted handler does no real I/O), so a no-op waker + spin poll resolves in one step. This
2925
- // lives ONLY in the observe companion — the covered module itself imports zero runtime.
2926
- fn bc_block_on<F: std::future::Future>(mut fut: F) -> F::Output {
2927
- use std::task::{Context, Poll, RawWaker, RawWakerVTable, Waker};
2928
- fn noop(_: *const ()) {}
2929
- fn clone(_: *const ()) -> RawWaker {
2930
- RawWaker::new(std::ptr::null(), &VTABLE)
2931
- }
2932
- static VTABLE: RawWakerVTable = RawWakerVTable::new(clone, noop, noop, noop);
2933
- let waker = unsafe { Waker::from_raw(RawWaker::new(std::ptr::null(), &VTABLE)) };
2934
- let mut cx = Context::from_waker(&waker);
2935
- // SAFETY: fut is owned on the stack and never moved after pinning (it is dropped at scope end).
2936
- let mut fut = unsafe { std::pin::Pin::new_unchecked(&mut fut) };
2937
- loop {
2938
- match fut.as_mut().poll(&mut cx) {
2939
- Poll::Ready(v) => return v,
2940
- Poll::Pending => std::thread::yield_now(),
2941
- }
2942
- }
2943
- }`
2944
- : ""}
2945
-
2946
- ${serializers}
2947
-
2948
- // Value -> typed struct marshallers for the concrete-row decode (TEST glue only).
2949
- ${marshallers}
2950
-
2951
- ${emitMarshalHelpers()}
2952
-
2953
- // input decoders (generic &[(String,Value)] -> concrete InNR_<comp>; TEST glue, one decode at the boundary).
2954
- ${inDecoders}
2955
-
2956
- // scripted wire adapter (TEST glue) — wraps a scripted Value as a WireValue the generated inline de-box probes.
2957
- ${wireAdapter}
2958
-
2959
- ${adapter}
2960
-
2961
- // scripted leaf transport fns (one per covered leaf — the free op-agnostic transport the covered runner
2962
- // calls directly; test glue draining the shared scripted static).
2963
- ${transportFns.join("\n\n")}
2964
-
2965
- // observe_native_raw resets+fills the shared scripted static from the per-case handlers spec, then drives
2966
- // the covered struct-native runner and serializes to a canonical Value (test only). No handler object is
2967
- // passed — the runner calls the free \`leaf_<comp>\` transport fns above directly.
2968
- pub fn observe_native_raw(
2969
- name: &str,
2970
- spec: &serde_json::Map<String, serde_json::Value>,
2971
- input: &[(String, Value)],
2972
- ) -> Result<Value, behavior_contracts::BehaviorError> {
2973
- fill_scripted(spec);
2974
- match name {
2975
- ${arms}
2976
- other => Err(behavior_contracts::BehaviorError::new("UNKNOWN_ENTRY", format!("component '{other}' is not a covered read (fail-closed)"))),
2977
- }
2978
- }
2979
- `;
2980
- }
2981
- /** emitInDecoder — a TEST-glue decoder `decode_<comp>(input) -> Result<(<positional args...>,), BehaviorError>`.
2982
- * Reads each declared input port from the generic &[(String,Value)] into a local (= the entry's positional
2983
- * param; scalar → typed read; value-typed → the raw wire clone), returned as a tuple the observe companion
2984
- * destructures and passes positionally to the 1:1 entry (#192, box removed). A missing key leaves Default
2985
- * (every covered input is required + supplied by the corpus). Lives ONLY in the observe companion. */
2986
- function emitInDecoder(comp, plan, declared) {
2987
- const ports = entryPortOrder(comp, declared);
2988
- if (ports.length === 0 || comp.inputPorts === undefined)
2989
- return ""; // no input → observe calls the entry with no args.
2990
- const args = ports.map((p) => rustFieldName(p));
2991
- const types = ports.map((p) => inputPortRustType(comp.inputPorts[p], plan, `input port '${p}' of component '${comp.name}'`));
2992
- const lines = [];
2993
- // trailing comma → always a tuple (never a parenthesized single value).
2994
- lines.push(`fn decode_${sanitize(comp.name)}(input: &[(String, Value)]) -> Result<(${types.join(", ")},), BehaviorError> {`);
2995
- // neutral init per port: a SCALAR `value` port renders as bare `WireValue` (no Default) — init it
2996
- // with `WireValue::Null`, the SAME value-kind neutral the covered emitter uses for value cells (the
2997
- // cellInit SSoT above). Every other port type (scalar, Vec<WireValue>, Option<…>) has a Default.
2998
- ports.forEach((p, i) => lines.push(` let mut ${args[i]}: ${types[i]} = ${comp.inputPorts[p]?.type === "value" ? "WireValue::Null" : "Default::default()"};`));
2999
- // an if/else-if chain (clippy-clean regardless of port count — a single-arm `match` trips single_match).
3000
- lines.push(` for (k, v) in input {`);
3001
- ports.forEach((p, i) => {
3002
- const field = args[i];
3003
- const schema = comp.inputPorts[p];
3004
- const scalar = inputScalarKind(schema);
3005
- const et = schema.elemType;
3006
- const head = i === 0 ? " if" : " } else if";
3007
- lines.push(`${head} k == ${rustStrLit(p)} {`);
3008
- if ((schema?.type === "array" || schema?.type === "arr") && et !== undefined) {
3009
- // #108: decode the boxed Value::Arr into the native Vec<ElemT> (test glue — materialize each elem).
3010
- // bc#156: a `value[]` element is BC's opaque wire — decode it with the BC-owned value_to_wire
3011
- // constructor (the SAME wire the output de-box uses), NOT the typed materializer (WireValue is not a
3012
- // de-box target). This is the generic bound-value list built from a heterogeneous / empty input array.
3013
- const elemRef = deriveTypeRef(et, plan);
3014
- const elemTy = renderTypeRef(elemRef);
3015
- const mat = elemRef.kind === "value" ? "value_to_wire(ev)" : materializeExpr("ev", elemRef, plan);
3016
- lines.push(` match v {`);
3017
- lines.push(` Value::Arr(a) => {`);
3018
- lines.push(` let mut dec: Vec<${elemTy}> = Vec::with_capacity(a.len());`);
3019
- lines.push(` for ev in a.iter() { dec.push(${mat}); }`);
3020
- // #177 (A): an OPTIONAL array port field is `Option<Vec<E>>` (inputPortTypeRef opt), so wrap in Some.
3021
- lines.push(` ${field} = ${inputPortIsOptional(schema) ? "Some(dec)" : "dec"};`);
3022
- lines.push(` }`);
3023
- lines.push(` other => return Err(marshal_type_error(${rustStrLit(`decode input ${p}: expected array, got `)}, other.type_name())),`);
3024
- lines.push(` }`);
3025
- }
3026
- else if (schema?.type === "value") {
3027
- // bc#156: a scalar `value` port — the raw bound value as BC's opaque wire (value_to_wire).
3028
- lines.push(` ${field} = value_to_wire(v);`);
3029
- }
3030
- else if (schema?.type === "map" && et !== undefined) {
3031
- // #108-map: decode the boxed Value::Obj into the native BTreeMap<String, V> (test glue — the input
3032
- // map port carries a declared elemType). materializeExpr covers the map de-box (obj → BTreeMap).
3033
- // #209: a map whose VALUE type is the opaque `value` decodes with the BC-owned value_to_wire — the
3034
- // SAME rule the `value[]` array branch above and the scalar `value` branch apply (`value` is
3035
- // input-only, so the typed materializer stays fail-closed for it).
3036
- const valRef = deriveTypeRef(et, plan);
3037
- if (valRef.kind === "value") {
3038
- lines.push(` let mut mv: std::collections::BTreeMap<String, WireValue> = std::collections::BTreeMap::new();`);
3039
- lines.push(` if let Value::Obj(mo) = v { for (mk, mvv) in mo.iter() { mv.insert(mk.clone(), value_to_wire(mvv)); } }`);
3040
- lines.push(` ${field} = mv;`);
3041
- }
3042
- else {
3043
- const mapRef = { kind: "map", value: valRef };
3044
- lines.push(` ${field} = ${materializeExpr("v", mapRef, plan)};`);
3045
- }
3046
- }
3047
- else if (inputPortIsOptional(schema)) {
3048
- // #139: an OPTIONAL scalar port decodes into Option<T> via the inputPortTypeRef SSoT (a present key
3049
- // materializes Some(v); an absent key never enters this block, leaving the Default None).
3050
- lines.push(` ${field} = ${materializeExpr("v", inputPortTypeRef(schema, plan), plan)};`);
3051
- }
3052
- else if (scalar === undefined) {
3053
- lines.push(` ${field} = v.clone();`);
3054
- }
3055
- else {
3056
- const pat = scalar === "String" ? "Value::Str(sv)" : scalar === "i64" ? "Value::Int(sv)" : scalar === "f64" ? "Value::Float(sv)" : "Value::Bool(sv)";
3057
- const label = scalar === "String" ? "string" : scalar === "i64" ? "int" : scalar === "f64" ? "float" : "bool";
3058
- const bind = scalar === "String" ? "sv.clone()" : "*sv";
3059
- // bc#90 / runtime-free: build the module-LOCAL BehaviorError (TYPE_MISMATCH) via the local
3060
- // marshal_type_error helper — decode_* returns the local error, bridged at the observe boundary.
3061
- lines.push(` match v { ${pat} => ${field} = ${bind}, other => return Err(marshal_type_error(${rustStrLit(`decode input ${p}: expected ${label}, got `)}, other.type_name())) }`);
3062
- }
3063
- });
3064
- lines.push(` }`);
3065
- lines.push(` }`);
3066
- lines.push(` Ok((${args.join(", ")},))`);
3067
- lines.push(`}`);
3068
- return lines.join("\n");
3069
- }
3070
2728
  export const rustTypedNativeEmitter = {
3071
2729
  language: "rust-typed-native",
3072
2730
  classification: "codegen", // native: 型付きフラットコード生成・IR/dict 非在(#128/A6)