@senpi/runtime 3.0.217 → 3.0.218

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.
@@ -22,6 +22,10 @@ Optional keys:
22
22
  state_history_max_count — state series bound; default 0 = history disabled.
23
23
  max_ticks — stop after N ticks; absent = run until stopped. A validation
24
24
  run sets 1; production leaves it absent.
25
+ class_mb — the simulation scanner's memory class in MB. Present: the
26
+ process is held to it (see simulation_limits) and a
27
+ MemoryError in a tick exits with CLASS_EXCEEDED_EXIT_CODE.
28
+ Absent: no limit.
25
29
 
26
30
  Delivery sink is wired when EXTERNAL_SCANNER_ID and SIGNAL_INGESTION_URL are set in
27
31
  the environment. If either is absent the scaffold runs with the default no-op sink
@@ -85,6 +89,9 @@ def _main(argv=None) -> int:
85
89
  import scaffold as scaffold_pkg
86
90
  from scaffold import ScanEntrypointError, ScanSignatureError
87
91
  from scaffold.loop_primitives import log_event
92
+ from scaffold.simulation_limits import CLASS_EXCEEDED_EXIT_CODE, hold_to_class
93
+
94
+ class_mb = hold_to_class(config)
88
95
 
89
96
  # Resolve run_scaffold via the package symbol so a test stub patched onto the
90
97
  # package (or this module) is picked up.
@@ -146,7 +153,10 @@ def _main(argv=None) -> int:
146
153
  state_history_max_count=state_history_max_count,
147
154
  sink=sink,
148
155
  max_ticks=max_ticks,
156
+ memory_error_ends_run=class_mb is not None,
149
157
  )
158
+ except MemoryError:
159
+ return CLASS_EXCEEDED_EXIT_CODE
150
160
  except (ScanEntrypointError, ScanSignatureError, ValueError) as exc:
151
161
  # The full chain, not just the message. `import_entrypoint` raises `from exc`, so the real
152
162
  # cause — the missing sibling, the undefined name, the file and line it happened in — hangs
@@ -54,6 +54,7 @@ from typing import Any, Dict, List, Optional, Tuple
54
54
 
55
55
  from . import http_post
56
56
  from .signal_envelope import candidate_to_signal
57
+ from .simulation_limits import hold_to_class
57
58
  from .tick_metrics import TickMetrics, cpu_seconds, measure_tick # noqa: F401
58
59
 
59
60
  PROBE_TICKS = 3
@@ -983,7 +984,7 @@ class _ProbeSink:
983
984
  pass
984
985
 
985
986
 
986
- def run_probe(config: Dict[str, Any]) -> Dict[str, Any]:
987
+ def run_probe(config: Dict[str, Any], class_mb: Optional[int] = None) -> Dict[str, Any]:
987
988
  from . import scaffold as scaffold_mod
988
989
 
989
990
  sink = _ProbeSink()
@@ -1005,8 +1006,11 @@ def run_probe(config: Dict[str, Any]) -> Dict[str, Any]:
1005
1006
  install_signal_handlers=False,
1006
1007
  dry_run=True,
1007
1008
  back_to_back=True,
1009
+ memory_error_ends_run=class_mb is not None,
1008
1010
  )
1009
1011
  except BaseException as exc: # noqa: BLE001 — a scanner may raise anything at all
1012
+ if class_mb is not None and isinstance(exc, MemoryError):
1013
+ return _unmeasured("the scanner went past its {} MB class".format(class_mb))
1010
1014
  return _unmeasured("the probe did not start: {}: {}".format(type(exc).__name__, str(exc)[:300]))
1011
1015
  finally:
1012
1016
  http_post.PREFLIGHT = False
@@ -1172,8 +1176,9 @@ def main(argv: Optional[List[str]] = None) -> int:
1172
1176
  sys.stdout.write(json.dumps({"ok": False, "reason": "bad_config", "detail": str(exc)}))
1173
1177
  return 0
1174
1178
 
1179
+ class_mb = hold_to_class(config)
1175
1180
  if probe:
1176
- _emit(run_probe(config), config)
1181
+ _emit(run_probe(config, class_mb=class_mb), config)
1177
1182
  return 0
1178
1183
  result = run_preflight(config)
1179
1184
  if result.get("ok") and config.get("measure"):
@@ -141,6 +141,7 @@ def run_scaffold(
141
141
  senpi_mcp: Optional[Any] = None,
142
142
  dry_run: bool = False,
143
143
  back_to_back: bool = False,
144
+ memory_error_ends_run: bool = False,
144
145
  ) -> int:
145
146
  """Load the author's entrypoint and run its scan() on an interval loop (v2).
146
147
 
@@ -172,6 +173,11 @@ def run_scaffold(
172
173
  dry_run: Sets ctx.dry_run. True only during validation.
173
174
  back_to_back: Start each tick as soon as the last one ends, without waiting out the
174
175
  interval. ctx.interval_seconds is unchanged.
176
+ memory_error_ends_run:
177
+ Raise a MemoryError from loading author code or from any part of a tick
178
+ (scan, state commit, sink) instead of recording a failure, and log
179
+ `scaffold_class_exceeded` with the tick (0 while loading).
180
+ True when the scanner is held to a class (see simulation_limits).
175
181
  install_signal_handlers:
176
182
  Install SIGTERM/SIGINT graceful-stop handlers. False for tests.
177
183
 
@@ -196,8 +202,17 @@ def run_scaffold(
196
202
  if inputs is None:
197
203
  inputs = {}
198
204
 
205
+ def ends_run(exc: BaseException) -> bool:
206
+ return memory_error_ends_run and isinstance(exc, MemoryError)
207
+
199
208
  # Import and locate scan — any failure raises before tick 1.
200
- module = import_entrypoint(path, entrypoint)
209
+ try:
210
+ module = import_entrypoint(path, entrypoint)
211
+ except ScanEntrypointError as exc:
212
+ if exc.__cause__ is not None and ends_run(exc.__cause__):
213
+ log_event("scaffold_class_exceeded", tick=0, error=str(exc.__cause__))
214
+ raise exc.__cause__
215
+ raise
201
216
  scan = locate_scan(module)
202
217
  verify_scan_signature(scan)
203
218
 
@@ -313,6 +328,8 @@ def run_scaffold(
313
328
  reason=str(exc),
314
329
  )
315
330
  except Exception as exc: # noqa: BLE001 — author bug must not crash scaffold
331
+ if ends_run(exc):
332
+ raise
316
333
  tick_status = "error"
317
334
  candidates = []
318
335
  tick_error = {
@@ -361,6 +378,8 @@ def run_scaffold(
361
378
  try:
362
379
  ctx.state.commit()
363
380
  except Exception as commit_exc: # noqa: BLE001
381
+ if ends_run(commit_exc):
382
+ raise
364
383
  committed = False
365
384
  ctx.state.rollback()
366
385
  log_event(
@@ -391,6 +410,8 @@ def run_scaffold(
391
410
  )
392
411
  report = sink(candidates, summary=ctx._summary, tick=tick)
393
412
  except Exception as sink_exc: # noqa: BLE001
413
+ if ends_run(sink_exc):
414
+ raise
394
415
  log_event(
395
416
  "scaffold_sink_error",
396
417
  tick=tick_count,
@@ -431,6 +452,10 @@ def run_scaffold(
431
452
  **({"rejected_count": rejected_count} if rejected_count else {}),
432
453
  )
433
454
 
455
+ except MemoryError as exc:
456
+ if memory_error_ends_run:
457
+ log_event("scaffold_class_exceeded", tick=tick_count, error=str(exc))
458
+ raise
434
459
  except _TickTimeout as late_exc:
435
460
  # A SIGALRM queued by the OS, delivered after the inner try/except
436
461
  # exited (e.g. during commit, sink, or log_event). Absorb it: the
@@ -0,0 +1,51 @@
1
+ """Hold a simulation scanner to the memory class it declared.
2
+
3
+ The launch config's optional `class_mb` is the class. With one, the process gets
4
+ RLIMIT_DATA at the class, a lower CPU priority and a higher OOM kill priority,
5
+ all before author code loads, and a MemoryError at a tick boundary ends the run
6
+ with CLASS_EXCEEDED_EXIT_CODE. Without one the scanner runs unlimited.
7
+ """
8
+
9
+ import os
10
+ import resource
11
+ from typing import Any, Mapping, Optional
12
+
13
+ from .loop_primitives import log_event
14
+
15
+ CLASS_EXCEEDED_EXIT_CODE = 86
16
+ NICENESS = 10
17
+ OOM_SCORE_ADJ = 1000
18
+ _MIB = 1024 * 1024
19
+ # OpenBLAS reserves a buffer per thread when numpy loads, one thread per CPU the
20
+ # container sees. On a many-core host that alone passes a small class, and OpenBLAS
21
+ # aborts the process instead of raising MemoryError.
22
+ _ONE_THREAD = ("OPENBLAS_NUM_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS")
23
+
24
+
25
+ def hold_to_class(config: Mapping[str, Any]) -> Optional[int]:
26
+ """Apply the launch config's class to this process. Returns the class, or None."""
27
+ raw = config.get("class_mb")
28
+ if raw is None:
29
+ return None
30
+ if isinstance(raw, bool) or not isinstance(raw, int) or raw <= 0:
31
+ log_event("simulation_class_invalid", value=repr(raw)[:100])
32
+ return None
33
+
34
+ for variable in _ONE_THREAD:
35
+ os.environ[variable] = "1"
36
+ limit = raw * _MIB
37
+ try:
38
+ resource.setrlimit(resource.RLIMIT_DATA, (limit, limit))
39
+ except (OSError, ValueError) as exc:
40
+ log_event("simulation_class_not_applied", class_mb=raw, error=str(exc))
41
+ try:
42
+ os.setpriority(os.PRIO_PROCESS, 0, max(NICENESS, os.getpriority(os.PRIO_PROCESS, 0)))
43
+ except OSError as exc:
44
+ log_event("simulation_priority_not_lowered", error=str(exc))
45
+ try:
46
+ with open("/proc/self/oom_score_adj", "w", encoding="ascii") as handle:
47
+ handle.write(str(OOM_SCORE_ADJ))
48
+ except OSError:
49
+ pass
50
+ log_event("simulation_class_applied", class_mb=raw)
51
+ return raw
@@ -2,7 +2,7 @@
2
2
  "id": "runtime",
3
3
  "name": "Senpi Runtime",
4
4
  "description": "Senpi runtime plugin for OpenClaw. Orchestrates scanners, LLM-based trade decisions, and a DSL trailing stop-loss exit engine.",
5
- "version": "3.0.217",
5
+ "version": "3.0.218",
6
6
  "commandAliases": [
7
7
  {
8
8
  "name": "senpi"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@senpi/runtime",
3
- "version": "3.0.217",
3
+ "version": "3.0.218",
4
4
  "description": "Senpi runtime plugin for OpenClaw",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",