process-bigraph 1.10.1__tar.gz → 1.11.1__tar.gz

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 (85) hide show
  1. {process_bigraph-1.10.1/process_bigraph.egg-info → process_bigraph-1.11.1}/PKG-INFO +4 -6
  2. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/__init__.py +0 -1
  3. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/composite.py +229 -35
  4. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/holes.py +8 -53
  5. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/nextflow.py +31 -5
  6. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/scheduling.py +144 -6
  7. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualizations/time_series.py +7 -2
  8. {process_bigraph-1.10.1 → process_bigraph-1.11.1/process_bigraph.egg-info}/PKG-INFO +4 -6
  9. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph.egg-info/SOURCES.txt +3 -5
  10. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph.egg-info/requires.txt +4 -5
  11. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/pyproject.toml +23 -6
  12. process_bigraph-1.11.1/tests/test_heap_scheduler.py +123 -0
  13. process_bigraph-1.11.1/tests/test_wire_step_layers_root_trigger.py +116 -0
  14. process_bigraph-1.10.1/process_bigraph/audit_contracts.py +0 -128
  15. process_bigraph-1.10.1/process_bigraph/composite_audit.py +0 -193
  16. process_bigraph-1.10.1/process_bigraph/contract_drift.py +0 -253
  17. process_bigraph-1.10.1/process_bigraph/contract_strict.py +0 -176
  18. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/AUTHORS.md +0 -0
  19. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/LICENSE +0 -0
  20. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/README.md +0 -0
  21. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/artifacts.py +0 -0
  22. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/bundle.py +0 -0
  23. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/composite_discovery.py +0 -0
  24. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/composite_generator.py +0 -0
  25. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/composite_spec.py +0 -0
  26. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/config_helpers.py +0 -0
  27. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/core_introspection.py +0 -0
  28. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/draft_process.py +0 -0
  29. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/emitter.py +0 -0
  30. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/events.py +0 -0
  31. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/experiments/__init__.py +0 -0
  32. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/experiments/minimal_gillespie.py +0 -0
  33. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/nextflow_deploy.py +0 -0
  34. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/orchestration.py +0 -0
  35. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/plumbing.py +0 -0
  36. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/__init__.py +0 -0
  37. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/bigraphical_reactive_system.py +0 -0
  38. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/cached.py +0 -0
  39. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/dynamic_structure.py +0 -0
  40. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/examples.py +0 -0
  41. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/growth_division.py +0 -0
  42. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/parameter_scan.py +0 -0
  43. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/reaction.py +0 -0
  44. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/processes/simulation.py +0 -0
  45. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/__init__.py +0 -0
  46. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/_git_worker.py +0 -0
  47. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/clusters/__init__.py +0 -0
  48. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/clusters/ec2_ssm.py +0 -0
  49. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/git.py +0 -0
  50. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/parallel.py +0 -0
  51. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/pool.py +0 -0
  52. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/ray.py +0 -0
  53. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/rest.py +0 -0
  54. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/protocols/session.py +0 -0
  55. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/run_composite.py +0 -0
  56. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/run_step.py +0 -0
  57. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/server/__init__.py +0 -0
  58. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/server/rest.py +0 -0
  59. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/server/start.py +0 -0
  60. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/templates.py +0 -0
  61. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/types/__init__.py +0 -0
  62. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/types/process.py +0 -0
  63. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualization.py +0 -0
  64. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualizations/__init__.py +0 -0
  65. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualizations/distribution.py +0 -0
  66. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualizations/heatmap.py +0 -0
  67. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualizations/param_vs_observable.py +0 -0
  68. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualizations/phase_space.py +0 -0
  69. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/visualizations/timeseries_from_observables.py +0 -0
  70. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/wiring_translator.py +0 -0
  71. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/workflow/__init__.py +0 -0
  72. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/workflow/backend.py +0 -0
  73. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/workflow/provision.py +0 -0
  74. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/workflow/recipe.py +0 -0
  75. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph/workflow/tasks.py +0 -0
  76. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph.egg-info/dependency_links.txt +0 -0
  77. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/process_bigraph.egg-info/top_level.txt +0 -0
  78. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/setup.cfg +0 -0
  79. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/tests/test_composite_generator_analyses.py +0 -0
  80. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/tests/test_global_time_precision_default.py +0 -0
  81. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/tests/test_initial_state_precedence.py +0 -0
  82. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/tests/test_multirate_scheduling.py +0 -0
  83. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/tests/test_process_decorator.py +0 -0
  84. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/tests/test_reaction_step.py +0 -0
  85. {process_bigraph-1.10.1 → process_bigraph-1.11.1}/tests/test_units.py +0 -0
@@ -1,18 +1,16 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: process-bigraph
3
- Version: 1.10.1
3
+ Version: 1.11.1
4
4
  Summary: protocol and execution for compositional systems biology
5
5
  Requires-Python: >=3.11
6
6
  Description-Content-Type: text/markdown
7
7
  License-File: LICENSE
8
8
  License-File: AUTHORS.md
9
- Requires-Dist: bigraph-schema>=1.8.1
9
+ Requires-Dist: bigraph-schema<1.8.4,>=1.8.1
10
10
  Requires-Dist: requests>=2.31
11
- Requires-Dist: matplotlib
12
11
  Requires-Dist: pint>=0.24.4
13
- Requires-Dist: scipy>=1.8
14
- Requires-Dist: pandas
15
- Requires-Dist: sympy
12
+ Provides-Extra: viz
13
+ Requires-Dist: matplotlib; extra == "viz"
16
14
  Provides-Extra: ray
17
15
  Requires-Dist: ray>=2.10; extra == "ray"
18
16
  Provides-Extra: server-rest
@@ -79,7 +79,6 @@ from process_bigraph.holes import UnfilledHoleError # noqa: F401
79
79
  from process_bigraph.templates import ( # noqa: F401
80
80
  open_sites, required_open_sites, is_ground_document, fill_template, template_document,
81
81
  )
82
- from bigraph_schema.matching import find_candidates # noqa: F401
83
82
  from process_bigraph.emitter import Emitter, gather_emitter_results, generate_emitter_state # noqa: F401
84
83
  from process_bigraph.types import StepLink, ProcessLink, CompositeLink # noqa: F401
85
84
  from process_bigraph import core_introspection # noqa: F401
@@ -15,6 +15,8 @@ Used as part of the Vivarium 2.0 ecosystem for modular biological modeling.
15
15
  import os
16
16
  import json
17
17
  import math
18
+ import warnings
19
+ import heapq
18
20
  import inspect
19
21
  import time as _time
20
22
  import contextvars
@@ -1254,17 +1256,6 @@ def _project_process_update(update_results: Any, args: Tuple[Any, str, Any]) ->
1254
1256
  to the previous per-call closure.
1255
1257
  """
1256
1258
  composite, ports_key, process_path = args
1257
- strict = getattr(composite, '_contract_strict', 'off')
1258
- if strict != 'off':
1259
- # v1: only a dict delta is post-checked; list-form (multi-update) is left unchecked.
1260
- compiled = composite._compiled_contracts.get(process_path)
1261
- if compiled is not None and isinstance(update_results, dict):
1262
- from process_bigraph.contract_strict import check_post, handle_violations
1263
- inputs = composite._cached_view(process_path)
1264
- fails = check_post(compiled, inputs, update_results)
1265
- handle_violations(fails, mode=strict, phase='post', path=process_path,
1266
- cls='process', emitter=composite._em,
1267
- global_time=composite.state.get('global_time', 0.0) if isinstance(composite.state, dict) else 0.0)
1268
1259
  if not isinstance(update_results, list):
1269
1260
  update_results = [update_results]
1270
1261
  return [
@@ -1323,6 +1314,14 @@ class Composite(Process):
1323
1314
  },
1324
1315
  'global_time_precision': 'maybe[float]',
1325
1316
  'run_steps_on_init': 'boolean{false}',
1317
+ # Non-deterministic step-cycle policy (issue #30): 'raise' (default) |
1318
+ # 'warn'. A zero-time step cycle whose members share a priority has no
1319
+ # priority-fixed order, so building rejects it by default (issue #233).
1320
+ # 'warn' opts into a warning and builds anyway, for a document whose
1321
+ # wiring forms such a cycle and whose author accepts the scheduler's
1322
+ # fallback ordering. Unset here, the PROCESS_BIGRAPH_CYCLE_POLICY env
1323
+ # var is consulted; otherwise 'raise'.
1324
+ 'cycle_policy': 'maybe[string]',
1326
1325
  # Inner-layer parallelism: when True, run_steps fans out the
1327
1326
  # steps in each layer across a ThreadPoolExecutor. Threads
1328
1327
  # share memory and don't trigger the daemon-process restriction,
@@ -1332,8 +1331,6 @@ class Composite(Process):
1332
1331
  # step hot path releases the GIL (numpy / scipy / numba / C
1333
1332
  # extensions: yes; pure-Python loops: no).
1334
1333
  'parallel_steps': 'boolean{false}',
1335
- # Runtime contract checking: off (default, zero-cost) | record | raise.
1336
- 'contract_strict': 'string{off}',
1337
1334
  'orchestration': 'string{temporal}',
1338
1335
  # Time-scheduled processes: when True, the per-tick `run` loop
1339
1336
  # fans out invocations across a thread pool. Right tool when
@@ -1344,6 +1341,22 @@ class Composite(Process):
1344
1341
  # parallel_steps and bounded by parallel_workers.
1345
1342
  'parallel_processes': 'boolean{false}',
1346
1343
  'parallel_workers': 'maybe[integer]',
1344
+ # Temporal-scheduler strategy for the serial per-tick loop:
1345
+ # 'scan' — the original loop that calls run_process on every
1346
+ # process every tick (O(P) per tick; O(P^2) total when
1347
+ # intervals differ, because tick count grows with P).
1348
+ # 'heap' — an event min-heap keyed on each process's next due time:
1349
+ # pop only the due processes, skip the wasted input slice
1350
+ # for a process whose next step overruns the run horizon,
1351
+ # and drop such a process until the next run() (it cannot
1352
+ # fire again this run). ~O(P log P); bit-identical to 'scan'.
1353
+ # 5x-55x faster on many-rate composites, ~5% slower on
1354
+ # single-rate ones (heap bookkeeping with nothing to gain).
1355
+ # 'auto' — (default) use 'heap' when the composite has more than one
1356
+ # distinct process interval, else 'scan'. Never engages for
1357
+ # parallel_processes or runtime-batched (tick_lifecycle)
1358
+ # composites, which keep the scan path.
1359
+ 'scheduler': 'string{auto}',
1347
1360
  # When True, ``initialize`` trusts ``state`` as-is and skips the
1348
1361
  # per-process ``link_state`` + ``combine`` pass that normally
1349
1362
  # seeds initial values. Set this when loading from a saved
@@ -1586,12 +1599,18 @@ class Composite(Process):
1586
1599
  # field in interface_schema for the rationale (threading vs.
1587
1600
  # multiprocessing for inner parallelism).
1588
1601
  self._parallel_steps = bool(self.config.get('parallel_steps', False))
1589
- self._contract_strict = self.config.get('contract_strict') or getattr(self.core, 'contract_strict', 'off')
1590
- self._compiled_contracts = {}
1591
1602
  self._parallel_processes = bool(self.config.get('parallel_processes', False))
1592
1603
  self._parallel_workers = self.config.get('parallel_workers')
1593
1604
  self._step_executor = None # lazy: created on first run_steps need
1594
1605
 
1606
+ # Temporal scheduler strategy (see the 'scheduler' config field).
1607
+ self._scheduler_mode = self.config.get('scheduler') or 'auto'
1608
+ if self._scheduler_mode not in ('auto', 'heap', 'scan'):
1609
+ raise ValueError(
1610
+ f"scheduler must be 'auto', 'heap' or 'scan', got {self._scheduler_mode!r}")
1611
+ self._use_heap = False # decided per run() in _decide_scheduler
1612
+ self._event_heap = None # event min-heap, (re)built lazily by the heap path
1613
+
1595
1614
  # Initialize a "front" dictionary tracking the next update time and update data per process.
1596
1615
  self.front = {
1597
1616
  path: empty_front(self.state['global_time'])
@@ -2081,27 +2100,16 @@ class Composite(Process):
2081
2100
  path for any path not present.
2082
2101
  """
2083
2102
  self._compiled_links = {}
2084
- self._compiled_contracts = {}
2085
2103
 
2086
2104
  for path in list(self.process_paths) + list(self.step_paths):
2087
2105
  compiled = self.core.precompile_link(
2088
2106
  self.schema, self.state, path)
2089
2107
  if compiled is not None:
2090
2108
  self._compiled_links[path] = compiled
2091
- if self._contract_strict != 'off':
2092
- try:
2093
- from process_bigraph.contract_strict import compile_contract
2094
- node = self.state
2095
- for key in path:
2096
- node = node[key]
2097
- self._compiled_contracts[path] = compile_contract(node['instance'].describe_contract())
2098
- except Exception: # noqa: BLE001 - a process without a readable contract is simply unchecked
2099
- self._compiled_contracts[path] = None
2100
2109
 
2101
2110
  def _invalidate_caches(self) -> None:
2102
2111
  """Invalidate precompiled link caches, forcing rebuild on next use."""
2103
2112
  self._compiled_links = {}
2104
- self._compiled_contracts = {}
2105
2113
  self._runtime_partition_cache = None
2106
2114
 
2107
2115
  def _cached_view(self, path: Tuple[str, ...]) -> Dict[str, Any]:
@@ -2505,7 +2513,7 @@ class Composite(Process):
2505
2513
  return '/'.join(str(part) for part in step_key)
2506
2514
  return str(step_key)
2507
2515
  rendered = ' -> '.join(_name(step_key) for step_key in cycle)
2508
- raise ValueError(
2516
+ message = (
2509
2517
  f'non-deterministic step dependency cycle detected: '
2510
2518
  f'{rendered}. These steps form a zero-time feedback cycle AND '
2511
2519
  f'share a priority, so their evaluation order would depend on '
@@ -2516,6 +2524,26 @@ class Composite(Process):
2516
2524
  f'deterministically), removing one of the mutual input/output '
2517
2525
  f'wirings, or modelling the feedback as a Process with a '
2518
2526
  f'non-zero time interval.')
2527
+ # Issue #30: an author who accepts such a cycle can opt into a
2528
+ # warning instead of the raise. Resolution: the Composite's own
2529
+ # ``config['cycle_policy']`` wins; otherwise the
2530
+ # ``PROCESS_BIGRAPH_CYCLE_POLICY`` env var; otherwise ``'raise'``.
2531
+ # Anything but an explicit ``'warn'`` fails CLOSED (raises), so a
2532
+ # typo never silently drops the guard. In warn mode the cycle is
2533
+ # ordered by ``determine_steps``' priority/``repr`` fallback, which
2534
+ # is deterministic across processes (#284) but arbitrary — distinct
2535
+ # priorities still give a meaningful order.
2536
+ policy = (self.config.get('cycle_policy')
2537
+ or os.environ.get('PROCESS_BIGRAPH_CYCLE_POLICY')
2538
+ or 'raise')
2539
+ if str(policy).strip().lower() == 'warn':
2540
+ warnings.warn(
2541
+ message + ' Proceeding because cycle_policy="warn": the '
2542
+ 'scheduler orders this cycle deterministically but '
2543
+ 'arbitrarily.',
2544
+ stacklevel=2)
2545
+ else:
2546
+ raise ValueError(message)
2519
2547
 
2520
2548
  # Initialize trigger fulfillment state and steps remaining
2521
2549
  self.reset_step_state(self.step_paths)
@@ -2815,6 +2843,8 @@ class Composite(Process):
2815
2843
  if em.detail_timing:
2816
2844
  self._profile_per_process = True
2817
2845
  self._run_ticks = 0 # per-Composite, so nested runs do not clobber the outer count
2846
+ self._event_heap = None # (re)built lazily by the heap path
2847
+ self._use_heap = self._decide_scheduler()
2818
2848
  # Rate limit: emit this pair if it is the first run on this Composite or
2819
2849
  # ``heartbeat_s`` has elapsed since the last emitted pair. An error at
2820
2850
  # the end overrides the decision (see ``finally``), because a failure is
@@ -2906,6 +2936,32 @@ class Composite(Process):
2906
2936
  self.run_steps(self.to_run)
2907
2937
  self.to_run = []
2908
2938
 
2939
+ def _decide_scheduler(self) -> bool:
2940
+ """Decide whether this run() uses the event-heap tick loop.
2941
+
2942
+ Called once per run(). The heap path is only safe/beneficial for the
2943
+ serial, non-runtime-batched loop; parallel_processes and tick_lifecycle
2944
+ (sharded/Ray) composites keep the scan path. In 'auto' mode the heap is
2945
+ used only when more than one distinct process interval is present (a
2946
+ single-rate composite gains nothing and pays heap bookkeeping)."""
2947
+ if self._scheduler_mode == 'scan':
2948
+ return False
2949
+ if self._parallel_processes:
2950
+ return False
2951
+ managed, groups = self._partition_processes_by_runtime()
2952
+ if managed or groups:
2953
+ return False
2954
+ if self._scheduler_mode == 'heap':
2955
+ return True
2956
+ # 'auto': use the heap only for genuinely multi-rate composites.
2957
+ seen = set()
2958
+ for path in self.process_paths:
2959
+ process = get_path(self.state, path)
2960
+ seen.add(process.get('interval'))
2961
+ if len(seen) > 1:
2962
+ return True
2963
+ return False
2964
+
2909
2965
  def advance_tick(self, end_time: float, force_complete: bool):
2910
2966
  """Execute ONE temporal tick toward ``end_time`` — the body of the
2911
2967
  event-scheduling loop. Returns ``(halted, force_complete)``: ``halted``
@@ -2913,6 +2969,10 @@ class Composite(Process):
2913
2969
  ``force_complete`` is returned because the tick may clear it. The
2914
2970
  ``temporal`` strategy drives this in a loop while ``Composite`` owns the
2915
2971
  tick mechanics (front, invoke, apply), keeping strategies thin."""
2972
+ # Event-heap scheduler (O(P log P) vs the O(P) per-tick scan below).
2973
+ # Decided once per run() in _decide_scheduler.
2974
+ if self._use_heap:
2975
+ return self._advance_tick_heap(end_time, force_complete)
2916
2976
  full_step = math.inf
2917
2977
  self._run_ticks = getattr(self, '_run_ticks', 0) + 1
2918
2978
  self._em.heartbeat(global_time=self.state['global_time'])
@@ -2981,6 +3041,126 @@ class Composite(Process):
2981
3041
 
2982
3042
  return False, force_complete
2983
3043
 
3044
+ def _advance_tick_heap(self, end_time: float, force_complete: bool):
3045
+ """Event-min-heap equivalent of ``advance_tick``.
3046
+
3047
+ Same semantics, but the O(P) per-tick scans (discover due processes,
3048
+ compute the not-due ``full_step`` floor, find the next event, and
3049
+ collect applicable updates) become heap pops. Entries are
3050
+ ``(time, seq, path)``; a popped entry is stale (skipped) when it no
3051
+ longer matches ``self.front[path]['time']`` (lazy deletion). The heap
3052
+ is rebuilt whenever structure changes (``self._event_heap = None``)."""
3053
+ full_step = math.inf
3054
+ self._run_ticks = getattr(self, '_run_ticks', 0) + 1
3055
+ self._em.heartbeat(global_time=self.state['global_time'])
3056
+ gt = self.state['global_time']
3057
+
3058
+ h = self._event_heap
3059
+ if h is None:
3060
+ # Mirror run_process's lazy front init: a newly added process path
3061
+ # (e.g. a division daughter) may be in process_paths but not yet in
3062
+ # front. empty_front schedules it at the current time (due now),
3063
+ # matching stock behavior.
3064
+ for p in self.process_paths:
3065
+ if p not in self.front:
3066
+ self.front[p] = empty_front(self.state['global_time'])
3067
+ h = self._event_heap = [
3068
+ (self.front[p]['time'], i, p)
3069
+ for i, p in enumerate(self.process_paths)]
3070
+ heapq.heapify(h)
3071
+ self._heap_seq = len(h)
3072
+
3073
+ # Discover due processes (front time <= gt) via heap pops.
3074
+ due = []
3075
+ while h and h[0][0] <= gt:
3076
+ t, _s, p = heapq.heappop(h)
3077
+ fp = self.front.get(p)
3078
+ if fp is None or fp['time'] != t:
3079
+ continue # stale entry
3080
+ due.append(p)
3081
+ # Not-due floor on full_step = (min remaining event time) - gt.
3082
+ if h:
3083
+ delay = h[0][0] - gt
3084
+ if delay < full_step:
3085
+ full_step = delay
3086
+ # Run due processes (run_process folds their futures into full_step,
3087
+ # incl. the future>end_time guard), then re-push their new times.
3088
+ for p in due:
3089
+ process = get_path(self.state, p)
3090
+ full_step = self.run_process(p, process, end_time, full_step, force_complete)
3091
+ fp = self.front[p]
3092
+ if fp['time'] > gt:
3093
+ # Advanced normally — reschedule at its next event time.
3094
+ heapq.heappush(h, (fp['time'], self._heap_seq, p))
3095
+ self._heap_seq += 1
3096
+ elif not force_complete and fp['time'] + process['interval'] > end_time:
3097
+ # Horizon overrun: front['time'] did not advance and the next
3098
+ # step falls past this run's end. It cannot fire again this run,
3099
+ # so DROP it from the heap instead of re-popping it every
3100
+ # remaining tick (this is what kills the O(P x tail-ticks)
3101
+ # re-examination). The heap is rebuilt at the next run() from
3102
+ # ``front``, so the process returns deferred exactly as before.
3103
+ pass
3104
+ else:
3105
+ # Did not advance but not a horizon overrun (rare catch-up) —
3106
+ # keep it schedulable so it can fire again.
3107
+ heapq.heappush(h, (fp['time'], self._heap_seq, p))
3108
+ self._heap_seq += 1
3109
+
3110
+ if full_step == math.inf:
3111
+ next_event = end_time
3112
+ if h and h[0][0] < next_event:
3113
+ next_event = h[0][0]
3114
+ self.state['global_time'] = next_event
3115
+
3116
+ elif self.state['global_time'] + full_step <= end_time:
3117
+ self.state['global_time'] += full_step
3118
+ new_gt = self.state['global_time']
3119
+ updates = []
3120
+ update_paths_local = []
3121
+ # Applicable updates: front time <= new_gt. Pop them, collect any
3122
+ # pending delta, and re-push (they stay scheduled for their next run).
3123
+ apply_batch = []
3124
+ while h and h[0][0] <= new_gt:
3125
+ t, _s, p = heapq.heappop(h)
3126
+ fp = self.front.get(p)
3127
+ if fp is None or fp['time'] != t:
3128
+ continue
3129
+ apply_batch.append((p, fp))
3130
+ for p, fp in apply_batch:
3131
+ if fp['update']:
3132
+ updates.append(fp['update'])
3133
+ fp['update'] = {}
3134
+ update_paths_local.append(p)
3135
+ heapq.heappush(h, (fp['time'], self._heap_seq, p))
3136
+ self._heap_seq += 1
3137
+
3138
+ fw_start = _time.monotonic()
3139
+ self._flush_protocol_runtimes()
3140
+ update_paths = self.apply_updates(updates)
3141
+ update_paths.append(('global_time',))
3142
+ self.expire_process_paths(update_paths)
3143
+ self.steps_run = set()
3144
+ if (getattr(self, '_halt_after_structural', False)
3145
+ and getattr(self, '_last_apply_structural', False)):
3146
+ self._event_heap = None # structure changed — rebuild next run
3147
+ self.framework_time += _time.monotonic() - fw_start
3148
+ return True, force_complete
3149
+ self.trigger_steps(update_paths)
3150
+ # A structural apply can add/remove process paths; drop the heap so
3151
+ # it rebuilds from the new front on the next tick.
3152
+ if getattr(self, '_last_apply_structural', False):
3153
+ self._event_heap = None
3154
+ self.framework_time += _time.monotonic() - fw_start
3155
+
3156
+ else:
3157
+ self.state['global_time'] = end_time
3158
+
3159
+ if force_complete and self.state['global_time'] == end_time:
3160
+ force_complete = False
3161
+
3162
+ return False, force_complete
3163
+
2984
3164
  def timing_summary(self) -> TimingSummary:
2985
3165
  """Return a ``TimingSummary`` describing the most recent ``run()`` call.
2986
3166
 
@@ -3194,6 +3374,28 @@ class Composite(Process):
3194
3374
  process_time = self.front[path]['time']
3195
3375
 
3196
3376
  if process_time <= self.state['global_time']:
3377
+ # Heap path only: skip the wasted input slice for a process whose
3378
+ # next step overruns the run horizon. Such a process is deferred to
3379
+ # the next run() anyway (its update is skipped and front['time']
3380
+ # stays put), so the slice here would be discarded — yet the code
3381
+ # below slices BEFORE the future>end_time guard, so without this a
3382
+ # large-interval process is re-sliced every remaining tick (O(P x
3383
+ # ticks) waste; ~99% of all view-slicing on many-rate runs). Only
3384
+ # sound when the interval cannot change, i.e. the default
3385
+ # (non-adaptive) calculate_timestep; adaptive processes and the scan
3386
+ # path keep the original behavior.
3387
+ if (self._use_heap
3388
+ and 'future' not in self.front[path]
3389
+ and type(process['instance']).calculate_timestep
3390
+ is Process.calculate_timestep):
3391
+ prospective = process_time + process['interval']
3392
+ if self.global_time_precision:
3393
+ prospective = round(prospective, self.global_time_precision)
3394
+ if not force_complete and prospective > end_time:
3395
+ delay = prospective - self.state['global_time']
3396
+ if delay < full_step:
3397
+ full_step = delay
3398
+ return full_step
3197
3399
  # Use future state if already scheduled and saved
3198
3400
  if 'future' in self.front[path]:
3199
3401
  future_front = self.front[path].pop('future')
@@ -3384,14 +3586,6 @@ class Composite(Process):
3384
3586
  # summary of the state it was handed (process_bigraph.events), then
3385
3587
  # re-raise the ORIGINAL exception unchanged -- callers may classify
3386
3588
  # control-flow exceptions by type, so the type must propagate as is.
3387
- if self._contract_strict != 'off':
3388
- compiled = self._compiled_contracts.get(path)
3389
- if compiled is not None:
3390
- from process_bigraph.contract_strict import check_pre, handle_violations
3391
- fails = check_pre(compiled, clean_state)
3392
- handle_violations(fails, mode=self._contract_strict, phase='pre', path=path,
3393
- cls=type(process['instance']).__name__, emitter=self._em,
3394
- global_time=self.state.get('global_time', 0.0) if isinstance(self.state, dict) else 0.0)
3395
3589
  t0 = _time.monotonic()
3396
3590
  try:
3397
3591
  update = process['instance'].invoke(clean_state, interval)
@@ -4,32 +4,23 @@ A *draft* in this framework is a process-slot left as an open **hole** — a
4
4
  ``Site`` whose ``_sort`` is a :class:`~bigraph_schema.contract.ProcessContract`.
5
5
  ``Composite`` refuses to build while a required hole is open; instead of the
6
6
  opaque ``KeyError: 'data'`` an unfilled address site used to raise, it raises an
7
- :class:`UnfilledHoleError` that names, per hole, its path, the contract it
8
- requires (typed face + conditions), and the registered processes that would fill
9
- it (:func:`~bigraph_schema.matching.find_candidates`).
10
-
11
- The report is best-effort on candidates: ``find_candidates`` reads a process's
12
- contract by instantiating it with empty config and skips any that need real
13
- config, so the candidate list may be empty — the guaranteed content is the hole
14
- path and its required contract. A candidate-finder failure never masks the
15
- primary "not ground" error.
7
+ :class:`UnfilledHoleError` that names, per hole, its path and the contract it
8
+ requires (typed face + conditions).
16
9
  """
17
10
  from __future__ import annotations
18
11
 
19
- from dataclasses import dataclass, field
12
+ from dataclasses import dataclass
20
13
  from typing import Any, List, Optional, Sequence, Tuple
21
14
 
22
15
  from bigraph_schema.assembly import contract_of
23
- from bigraph_schema.matching import find_candidates
24
16
 
25
17
 
26
18
  @dataclass
27
19
  class HoleReport:
28
- """One unfilled hole: where it is, what it requires, and what fills it."""
20
+ """One unfilled hole: where it is and what contract it requires."""
29
21
 
30
22
  path: Tuple[str, ...]
31
23
  contract: Optional[Any] = None # ProcessContract | None
32
- candidates: List[Any] = field(default_factory=list) # [CandidateMatch]
33
24
 
34
25
 
35
26
  class UnfilledHoleError(ValueError):
@@ -58,7 +49,6 @@ class UnfilledHoleError(ValueError):
58
49
  lines.append("")
59
50
  lines.append(f" • {'/'.join(hole.path)}")
60
51
  lines.extend(_render_requires(hole.contract, self._core))
61
- lines.extend(_render_candidates(hole.candidates))
62
52
  return "\n".join(lines)
63
53
 
64
54
 
@@ -67,16 +57,14 @@ def build_unfilled_hole_error(
67
57
  ) -> UnfilledHoleError:
68
58
  """Build an :class:`UnfilledHoleError` from ``(path, site)`` pairs.
69
59
 
70
- For each hole, resolve the contract it requires (``contract_of``) and the
71
- admissible candidates (``find_candidates``). Both are wrapped so a failure in
72
- either never masks the primary "not ground" report; an unsorted hole simply
73
- reports no contract and no candidates.
60
+ For each hole, resolve the contract it requires (``contract_of``), wrapped so
61
+ a failure never masks the primary "not ground" report; an unsorted hole simply
62
+ reports no contract.
74
63
  """
75
64
  reports = []
76
65
  for path, site in unfilled_sites:
77
66
  contract = _safe_contract_of(core, site)
78
- candidates = _safe_candidates(core, site) if contract is not None else []
79
- reports.append(HoleReport(tuple(path), contract, candidates))
67
+ reports.append(HoleReport(tuple(path), contract))
80
68
  return UnfilledHoleError(reports, core=core)
81
69
 
82
70
 
@@ -87,13 +75,6 @@ def _safe_contract_of(core, site):
87
75
  return None
88
76
 
89
77
 
90
- def _safe_candidates(core, site):
91
- try:
92
- return list(find_candidates(core, site) or [])
93
- except Exception: # noqa: BLE001 - candidate-finding never masks the primary error
94
- return []
95
-
96
-
97
78
  def _render_requires(contract, core=None) -> List[str]:
98
79
  if contract is None:
99
80
  return [" requires: no contract declared (unsorted hole)"]
@@ -140,29 +121,3 @@ def _fmt_port(schema, core=None) -> str:
140
121
  except Exception: # noqa: BLE001 - fall back to the class name, never a repr
141
122
  pass
142
123
  return type(schema).__name__.lower()
143
-
144
-
145
- def _render_candidates(candidates) -> List[str]:
146
- if not candidates:
147
- return [" candidates: (no admissible registered process found)"]
148
- lines = [" candidates:"]
149
- for candidate in candidates:
150
- if getattr(candidate, "match", None) == "full":
151
- lines.append(f" ✓ {candidate.address} (full match)")
152
- else:
153
- why = _fmt_fails(getattr(candidate, "fails", []) or [])
154
- lines.append(f" ~ {candidate.address} (partial: {why})")
155
- return lines
156
-
157
-
158
- def _fmt_fails(fails) -> str:
159
- """The failing conditions of a near-miss, by name — never a raw dict dump."""
160
- if not fails:
161
- return "near-miss"
162
- parts = []
163
- for fail in fails:
164
- if isinstance(fail, dict):
165
- parts.append(str(fail.get("condition", fail.get("detail", fail))))
166
- else:
167
- parts.append(str(fail))
168
- return "; ".join(parts)
@@ -207,7 +207,7 @@ def _script_body(instance: Any,
207
207
  f'--in {port}="${{{port}}}"' for port in inputs_wires
208
208
  )
209
209
  out_flags = ' '.join(
210
- f'--out {port}={port}.json' for port in outputs_wires
210
+ f'--out {port}=.{port}.json' for port in outputs_wires
211
211
  )
212
212
  parts = [
213
213
  f'{python} -m process_bigraph.run_step',
@@ -336,7 +336,12 @@ def _process_block(step_name: str,
336
336
  lines.append(' output:')
337
337
  for port in outputs_wires:
338
338
  if port not in class_overrides and uses_run_step:
339
- decl = f'path "{port}.json"'
339
+ # run_step writes the value manifest as a DOTFILE (.<port>.json;
340
+ # see _script_body). Dotfiles keep an override glob on the SAME
341
+ # port (e.g. `path "sweep_*"`) from also matching the manifest --
342
+ # which would collide an N->1 gather. An explicit (non-glob) decl
343
+ # still captures the dotfile, so plain 1->1 wires are unaffected.
344
+ decl = f'path ".{port}.json"'
340
345
  else:
341
346
  decl = _port_to_nextflow_decl(
342
347
  port, step_outputs_schema.get(port, {}), class_overrides)
@@ -546,6 +551,21 @@ def render_composite(composite: Any, options: Optional[Dict[str, Any]] = None) -
546
551
  workflow_name = options.get('workflow_name', 'main')
547
552
  header = options.get('header', 'nextflow.enable.dsl=2\n')
548
553
  python = options.get('python', 'python')
554
+ name_prefix = options.get('_name_prefix', '')
555
+
556
+ def _proc_name(path: Path) -> str:
557
+ """Process name made globally unique by the ancestor sub-workflow prefix.
558
+
559
+ Nextflow DSL2 process names are GLOBAL. ``_path_to_step_name`` only makes
560
+ a FULL path unique, but the recursive sub-composite render sees inner-only
561
+ paths, so two sibling sub-composites that each contain a like-named step
562
+ (e.g. ``lineage_s0``) would emit the same ``process`` twice and DSL2 would
563
+ not compile. ``_name_prefix`` carries the chain of enclosing
564
+ composite-node names (``runs_v0`` -> ``runs_v0_lineage_s0``). Channel and
565
+ variable names are workflow-local and are deliberately NOT prefixed.
566
+ """
567
+ base = _path_to_step_name(path)
568
+ return f'{name_prefix}_{base}' if name_prefix else base
549
569
 
550
570
  step_paths = composite.step_paths
551
571
  step_dependencies = getattr(composite, 'step_dependencies', {}) or {}
@@ -611,13 +631,13 @@ def render_composite(composite: Any, options: Optional[Dict[str, Any]] = None) -
611
631
  for step_path in order:
612
632
  if step_path not in step_paths:
613
633
  # A composite node: reserve its ordered slot; the loop below fills it.
614
- workflow_lines.append(f'@@SUBWF:{_path_to_step_name(step_path)}@@')
634
+ workflow_lines.append(f'@@SUBWF:{_proc_name(step_path)}@@')
615
635
  continue
616
636
  step = step_paths[step_path]
617
637
  instance = step['instance']
618
638
  inputs_wires = step.get('inputs') or {}
619
639
  outputs_wires = step.get('outputs') or {}
620
- name = _path_to_step_name(step_path)
640
+ name = _proc_name(step_path)
621
641
 
622
642
  if _is_plumbing(instance):
623
643
  workflow_lines.append(
@@ -690,7 +710,7 @@ def render_composite(composite: Any, options: Optional[Dict[str, Any]] = None) -
690
710
  instance = node.get('instance')
691
711
  if not isinstance(instance, _Composite):
692
712
  continue
693
- name = _path_to_step_name(node_path)
713
+ name = _proc_name(node_path)
694
714
  inputs_wires = node.get('inputs') or {}
695
715
  outputs_wires = node.get('outputs') or {}
696
716
  inner_steps = getattr(instance, 'step_paths', {}) or {}
@@ -702,6 +722,12 @@ def render_composite(composite: Any, options: Optional[Dict[str, Any]] = None) -
702
722
  if nest and inner_steps:
703
723
  sub_opts = dict(options)
704
724
  sub_opts['workflow_name'] = name
725
+ # Thread the (already-prefixed) sub-workflow name down as the prefix
726
+ # for every process DEFINED inside it, so a sibling sub-composite's
727
+ # like-named step becomes a distinct global process name. `name`
728
+ # itself is globally unique (it carries this scope's own prefix), so
729
+ # the inner scope accumulates the full ancestor chain.
730
+ sub_opts['_name_prefix'] = name
705
731
  sub_opts['_emit_ports'] = list(outputs_wires)
706
732
  sub_opts['_take_ports'] = list(inputs_wires)
707
733
  sub_text = render_composite(instance, {**sub_opts, 'header': ''})