Skip to content

state_exec: S-expression DSL engine (Phases 1-7 + docs & integration tests) - #93

Merged
transfix merged 23 commits into
masterfrom
feature/state-exec-phase1-2
May 25, 2026
Merged

transfix merged 23 commits into
masterfrom
feature/state-exec-phase1-2

Conversation

@transfix

Copy link
Copy Markdown
Owner

Summary

Complete port of the txwtf.cfos Python S-expression DSL to C++20, built on cvc::state.

Phases implemented (all 36 steps)

Phase Components Tests
1 — Foundation state_list, state_memory_manager, core types, parser 96
2 — Evaluators builtins, evaluator, stackless_evaluator, codec 167
3 — Async task<T>, async_evaluator, async_stackless_evaluator 59
4 — Scheduler process, memory_tracker, scheduler, async_scheduler 93
5 — Intrinsics 35 DSL intrinsics, resource_policy, stdlib (41 functions) 133
6 — Distributed exec_coordinator (election, submit, migrate, admin) 61
7 — Polish CMake flags, Doxygen headers, benchmarks 7
Integration ACL, migration, messaging, E2E scenarios 39

Total: 655 state_exec tests, 1919 tests overall (0 failures)

Documentation

  • docs/STATE_EXEC_DEVELOPER_GUIDE.md: Comprehensive developer guide with working C++ and DSL examples
  • docs/roadmap/STATE_EXEC_PORTING_PLAN.md: Full design document (36 steps)
  • docs/roadmap/STATE_EXEC_ROADMAP.md: Status tracker

Integration tests cover

  • ACL: UID/GID inheritance through spawn/fork, multi-user coexistence, resource policy enforcement, cross-node admin controls, leader handoff
  • Migration: inter-node migration preserving identity/priority, self-migration pattern, migration stats
  • Messaging: msg-send, message counting, producer-consumer via state tree, cross-node heartbeat/status
  • E2E: concurrent programs, process monitoring (ps/inspect), language features (while, for, lambda, let, dict), resource limits, scheduler-stats from DSL

transfix added 23 commits May 24, 2026 00:43
Phase 1 — Foundation (96 tests):
- state_list: thread-safe doubly-linked list with O(1) splice (20 tests)
- state_eviction_store + state_memory_manager: LRU eviction (20 tests)
- state_exec/types: 11-variant value_t, environment, closure (26 tests)
- state_exec/parser: S-expression parser (30 tests)

Phase 2 — Evaluators + Built-ins (108 tests):
- builtins: 35+ operators — arithmetic, comparison, string, list, dict,
  OOP (send with class/super chain), higher-order, type predicates (38 tests)
- evaluator: sync recursive evaluator with 15 special forms, closures,
  defclass/defmacro, macro expansion with re-evaluation (39 tests)
- stackless_evaluator: explicit-stack evaluator with phase-driven dispatch,
  serializable state, step-by-step execution (31 tests)

Key fixes:
- pop_frame/push_frame take value_t by value (prevent dangling ref on stack realloc)
- Macro expansion re-evaluates substituted template (standard Lisp semantics)
- volrover3 Qt tests: set QT_QPA_PLATFORM=offscreen for headless CI

Porting plan + roadmap docs added to docs/roadmap/.
All 1468 tests pass (0 failures).
Add state_value_codec for round-tripping DSL values, environments, and
evaluator state through cvc::state subtrees:

- state_value_codec.h/cpp: encode/decode APIs for value_t (all 11
  variants), environment scope chains, eval_frame stack, evaluator_state.
  Uses findDescendant() for read-only child lookups (children() returns
  full qualified names). Uses state_list for ordered containers.

- state_exec_codec_test.cpp (59 tests):
  * ValueCodecTest (19): nil, bool, int, double, string, symbol, list,
    dict, closure, native_fn, mixed structures
  * EnvironmentCodecTest (4): null, single scope, chain, native_fn skip
  * EvaluatorStateCodecTest (4): completed, paused, pause-resume, macros
  * CrossEvaluatorTest (32): sync vs stackless evaluator consistency on
    literals, arithmetic, comparison, control flow, closures, recursion,
    loops, macros, data structures, Fibonacci

Known limitation: environment_ptr identity across stack frames is not
preserved during serialization (each frame gets independent copies).
Tracked for Phase 3 identity-dedup codec.

Phase 2 total: 167 tests (38 builtins + 39 evaluator + 31 stackless +
23 value codec + 4 eval state + 32 cross-evaluator).
Full regression: 1527 tests, 0 failures.
Add task<T> coroutine return type with lazy execution and continuation-based
symmetric transfer.  Implement async_evaluator (recursive coroutine evaluator)
and async_stackless_evaluator (coroutine wrapper for stackless evaluator).

Components:
- task.h: task<T>, task<void>, suspend_point, sync_wait()
- async_evaluator: all special forms as coroutines, (await expr) support,
  sync_evaluate/sync_evaluate_script blocking wrappers
- async_stackless_evaluator: wraps stackless_evaluator with task<bool> step()
  and task<value_t> run() coroutine interface

Tests (59 total):
- TaskTest: 6 (value, void, chaining, exceptions, suspend, move-only)
- AsyncEvaluatorTest: 32 (full coverage mirroring sync evaluator)
- AsyncStacklessTest: 18 (atoms through Fibonacci, step API, max_steps)
- AsyncCrossEvaluatorTest: 3 (all 4 evaluator variants produce identical results)

Total project tests: 1586 (all passing)
Add process management, memory tracking, and sync/async schedulers with
three scheduling policies, signal handling, resource limit enforcement,
and process forking.

Components:
- process.h/cpp: process struct, process_status enum, elapsed time tracking
- memory_tracker.h/cpp: per-process memory accounting (write/delete/
  overwrite/release/fork ownership tracking)
- scheduler.h/cpp: sync scheduler with round_robin, priority, priority_rr
  policies; process submission, stepping, run loop; signal handling with
  save/restore; resource limits (max_steps, max_time, max_memory,
  max_messages); process forking with state deep copy
- async_scheduler.h/cpp: async variant with coroutine step()/run(),
  sync wrappers; same semantics as sync scheduler

Tests (93 total):
- ProcessStatusTest: 5 (to_string, parse, elapsed time, step count)
- MemoryTrackerTest: 11 (write, overwrite, delete, release, fork, clear)
- SchedulerTest: 53 (execution, policies, control, limits, signals, fork,
  loops, lambdas, Fibonacci, string ops, concurrent, expression API)
- SchedulerPolicyTest: 2 (priority, priority_rr)
- AsyncSchedulerTest: 18 (matching sync tests + coroutine API)
- CrossSchedulerTest: 2 (sync vs async consistency)

Known: scheduler serialization deferred to Phase 5 (requires state integration)

Total project tests: 1679 (all passing)
Implement state_exec Phase 5: State Integration + Intrinsics.

New headers:
  - intrinsics.h: intrinsics_context struct, register_intrinsics()
  - resource_policy.h: resource_policy, process_limits, validate_limits()
  - stdlib.h: stdlib_registry with module registration + import

New implementations:
  - intrinsics.cpp: 35 DSL intrinsics covering state tree (get/set/
    exists/delete/children/data), scheduler (spawn/fork/kill/pause/
    resume/ps/inspect), resource queries (memory/time/message/step),
    system identity (cluster-id/node-id/scheduler-stats), expiry
    (expire/expire-at/has-expiry/is-expired/clear-expiry/sweep),
    and messaging (msg-send)
  - resource_policy.cpp: validate_limits() with strict/clamp/warn modes
  - stdlib.cpp: 3 built-in modules:
    * string (12 functions: split, join, replace, trim, upper, lower,
      starts-with, ends-with, contains, substring, char-at, length)
    * math (16 functions: sqrt, abs, floor, ceil, round, pow, log,
      sin, cos, tan, min, max, clamp, pi, e, random)
    * collections (13 functions: map, filter, reduce, zip, flatten,
      sort, reverse, range, unique, dict-keys, dict-values, dict-merge)

Tests: 133 new tests across 14 test suites in
  state_exec_intrinsics_test.cpp. Full regression: 1812/1812 pass.
Convert scheduler and async_scheduler process storage from
unordered_map<int, process> to unordered_map<int, process_ptr>
where process_ptr = shared_ptr<process>. This prevents dangling
pointers when map rehash/erase invalidates iterators.

- Add process_ptr alias and make_process() factory to process.h
- Update intrinsics_context::proc from raw pointer to shared_ptr
- Update scheduler.cpp and async_scheduler.cpp access patterns
- Update test fixtures to use process_ptr
- 1812/1812 tests pass
Implements Steps 28-33 of the state_exec porting plan:

Step 28 - Scheduling coordination messages:
  - Bully-style leader election via OOB state_messages
  - Coordinator heartbeat with scheduler stats
  - Leader handoff protocol
  - Membership event integration (dead/evicted triggers re-election)

Step 29 - Process submission via messages:
  - Local submission with resource_policy validation
  - Remote forwarding to leader node
  - Submit request/response protocol over message bus

Step 30 - Process migration:
  - Pause, serialize metadata, send migrate message
  - Target ingests process data and sends migrate-ack
  - Full migration protocol with error handling

Step 31 - Cross-cluster observation:
  - ps_all() aggregates local + remote process lists
  - cluster_stats() merges scheduler stats across nodes
  - Status broadcast for periodic state distribution

Step 32 - Admin controls:
  - Local pause/resume/kill via scheduler
  - Remote control commands via message bus
  - Cluster-wide policy updates via MIME_EXEC_POLICY
  - Leader handoff for orderly transfer

Step 33 - Integration tests:
  - 61 tests covering all coordinator functionality
  - Two-coordinator simulation for cross-node scenarios
  - Serialization round-trip tests for all wire formats
  - End-to-end scenarios (submit+run+observe, resource limits,
    fork, pause/resume/kill, multi-node aggregation, dead cleanup)

New files:
  - inc/cvc/state_exec/exec_coordinator.h (273 lines)
  - src/cvc/state_exec/exec_coordinator.cpp (1301 lines)
  - src/cvc/tests/state_exec_coordinator_test.cpp (1297 lines)

Content types: MIME_EXEC_ELECTION, MIME_EXEC_HEARTBEAT,
MIME_EXEC_SUBMIT, MIME_EXEC_MIGRATE, MIME_EXEC_CONTROL,
MIME_EXEC_STATUS, MIME_EXEC_POLICY

Full regression: 1873/1873 tests pass
Step 34 — CMake integration:
  - Add CVC_STATE_EXEC and CVC_STATE_MEMORY_MANAGER options (default ON)
  - Conditional source filtering: exclude state_exec/ sources when OFF
  - Conditional test targets: wrap all state_exec/memory_manager test
    add_executable, target_link_libraries, target_compile_features,
    and gtest_discover_tests in if(CVC_STATE_EXEC)/if(CVC_STATE_MEMORY_MANAGER)
  - Add target_compile_definitions for public CVC_STATE_EXEC and
    CVC_STATE_MEMORY_MANAGER preprocessor symbols

Step 35 — Documentation:
  - Add @file/@brief Doxygen comments to all 17 state_exec headers
  - Cover types, parser, builtins, evaluator, stackless_evaluator,
    state_value_codec, task, async_evaluator, async_stackless_evaluator,
    process, memory_tracker, scheduler, async_scheduler, intrinsics,
    resource_policy, stdlib, exec_coordinator

Step 36 — Benchmark:
  - New state_exec_bench_test.cpp (7 tests, gated on CVC_STATE_EXEC_BENCH=1)
  - Performance: parse throughput, eval arithmetic loop, eval fib(15)
  - Scheduler: 500-process round-robin throughput
  - Memory pressure: 200 processes hitting step limits
  - High concurrency: 1000 short-lived process flood
  - Deep recursion: mutual recursion stress test

Full regression: 1880/1880 tests pass, 0 failures.
Update Phase 6 (Steps 28-33) and Phase 7 (Steps 34-36) with completion
marks, implementation details, test counts, and commit hashes.

Add summary table: 616 state_exec tests across 7 phases, 1880/1880
full regression passing.
- Add comprehensive developer guide (docs/STATE_EXEC_DEVELOPER_GUIDE.md)
  covering all subsystems with working C++ and DSL examples:
  quick start, language reference, scheduler API, process management,
  state tree, messaging, resource policies, distributed execution,
  migration, access control, stdlib, and architecture reference.

- Add 39 integration tests (state_exec_integration_test.cpp):
  * ACL: UID/GID inheritance, spawn inherits parent UID, fork inherits
    UID/GID/priority, identity via C++ API and intrinsics
  * Cluster ACL: resource policy limits, clamping, UID preservation,
    cross-node admin kill/pause/resume, policy broadcast, leader handoff
  * Migration: inter-node migration preserving UID/GID/priority,
    self-migration pattern, migration stats tracking, error cases
  * Messaging: msg-send delivery, message count tracking, message limits,
    producer-consumer via state tree, spawn+communicate, content types
  * Cross-node: heartbeat exchange, status broadcast, submit-run-observe,
    cluster stats aggregation
  * E2E: concurrent fibonacci+factorial, process monitoring via ps/inspect,
    while/for loops, lambda calls, let bindings, dict operations,
    resource limits, scheduler-stats from DSL

- Update STATE_EXEC_ROADMAP.md: mark phases 5-7 complete with test counts

- Wire state_exec_integration_test into CMake (all 5 blocks)

Test results: 1919 passed, 0 failed (39 new integration tests)
…rarchy, delegation security, coordinated messaging

40 new tests across 7 test suites:

- LargeDataObjectTest (5): 10KB string values, boost::any data objects,
  50x overwrite stability, 64KB shard payloads, 20x 32KB batches

- ContentionTest (5): 10 nodes same path, 10 nodes different paths,
  10x10 burst writes, 10-thread concurrent ingestion, sequential
  escalating conflict with deterministic LWW resolution

- ClusterHierarchyTest (8): root-to-child delegation, undelegated paths
  stay local, multi-cluster delegation routing, enforcement rejects
  remote writes to delegated subtrees, allows undelegated paths,
  revocation brings subtrees back, child cluster local writes,
  2-node child cluster replication via pump_all

- DelegationSecurityTest (8): write policy denies unauthorized nodes,
  empty writer set lockdown, longest-prefix policy matching,
  uncovered paths permissive by default, combined delegation +
  write policy enforcement, per-user workspace isolation,
  binary data with write policy, delegation lease expiry

- MultiNodeReplicationTest (4): 3-node write-and-replicate,
  multi-node different-path fan-out, deterministic conflict
  convergence via ingest_remote, sequential overwrite propagation

- CoordinatedMessagingTest (7): producer-consumer state coordination,
  map-reduce with state tree, N-worker pool with msg-send,
  spawn workers, progress tracking, two-process document assembly,
  Fibonacci computation with state + messaging notification

- CoordinatorClusterIntegrationTest (3): 10-job batch submission,
  resource policy enforcement, process listing via coordinator

Total: 1959 tests (40 new), 1 pre-existing failure unrelated.
Expands the Leader Election section with full protocol documentation:
- Triggers (startup, leader death, explicit request, bully response)
- Message format (election-start, election-alive, election-victory)
- Winner determination (priority first, node_id tiebreaker)
- Protocol flow diagram
- State transition table
- Heartbeat mechanism
- Configuration options
- Voluntary handoff and single-node behavior
- evaluator.cpp: Replace std::jthread (unavailable on Apple Clang)
  with std::thread + std::atomic<bool> for timeout support.

- async_evaluator.cpp: Flatten evaluate_script coroutine to inline
  the evaluate logic directly, avoiding an extra coroutine nesting
  layer that causes 'bad variant access' on MSVC due to symmetric
  transfer depth issues.

- task.h: Clean up sync_wait() with explicit first-resume + done()
  loop and diagnostic for missing return_value.
…atch

- Fix message dedup in state_cluster_shard: auto-generate message_id
  with static atomic counter when empty
- Add max_message_bytes limit across process, scheduler, async_scheduler,
  resource_policy, and intrinsics (message-bytes, message-bytes-limit)
- Implement chroot mechanism: root_path in execute_options/process,
  apply_chroot() for path confinement, state-root-path intrinsic
- Implement state-watch/state-unwatch reactive intrinsics:
  - Connect boost::signals2 valueChanged to scheduler event queue
  - Scheduler dispatches watch handlers at step boundaries
  - Full stack save/restore for handler execution context
  - Route events through scheduler::queue_watch_event() for correct
    process targeting
- Add 12 new integration tests (50 total):
  - MessageBytesLimitKillsProcess
  - HostReceivesPrintMessagesFromDSL
  - ChrootIntegrationTest (5 tests)
  - StateWatchTest (4 tests)
- Update developer guide with print pattern and bytes limit docs
Demonstrate non-polling producer-consumer patterns with state-watch:

1. ReactiveProducerConsumer: producer writes items, consumer appends
   each to a log reactively via watch handler
2. EventCounter: counts state changes by appending a tick mark per event
3. CascadingWatchPipeline: stage1 watches input, stage2 watches stage1
   — a single write cascades through the entire pipeline
4. WatchFirstNThenUnsubscribe: handler processes first 2 events then
   calls state-unwatch to self-unsubscribe
5. TwoProcessReactiveCoordination: worker process watches for requests
   and writes results; requester process reads the result

All examples use state-watch for reactive dispatch instead of polling.
55 tests total across 10 suites, all passing.
…m signal lambda

The boost::signals2 signal callback captured a value_t (containing
shared_ptr<closure>) which caused ABI issues on macOS, resulting in
SEGFAULT when the handler dispatched.

Fix: store watch handlers in a separate watch_handlers map on the
process struct, keyed by watch_id. The signal lambda now captures
only POD types (ints, strings, raw scheduler pointer). At dispatch
time, handle_watch_event looks up the handler from the map.

Also adds register_watch_handler/unregister_watch_handler methods
to both scheduler and async_scheduler so handlers are stored on
the scheduler's own process object (not the intrinsics_context copy).
Remove std::string and all non-POD types from signal slot lambda captures.
The watch_event struct now carries only watch_id; the watched path is
stored alongside the handler in process::watch_handler_entry and looked
up at dispatch time.  This eliminates all potential ABI issues with
boost::signals2 slot storage on macOS / Apple Clang.
boost::signals2 signal slot connections cause SEGFAULT on macOS / Apple
Clang regardless of lambda capture contents.  Replace the signal-based
notification mechanism with a polling approach:

- scheduler::poll_watches() checks all watched paths for value changes
  before each step, queuing watch_events when values differ from the
  stored last_value snapshot.
- watch_handler_entry now carries {handler, path, last_value}.
- No boost::signals2::connect() calls in intrinsic_state_watch.
- set_watch_root() lets the scheduler access the state tree for polling.

All 321 state_exec tests pass (55 integration + 40 advanced + 93
scheduler + 133 intrinsics).
Instead of building a call expression (__watch_handler__ path value)
and going through the evaluator's symbol-lookup + function-call path,
directly extract the closure's params/body/env and push the body
onto the stack with params bound.  This mirrors what call_closure()
does internally and avoids whatever code path triggers SEGFAULT on
macOS / Apple Clang.
…sage

state_message is defined as 'struct' in state_message.h but was
forward-declared as 'class' in exec_coordinator.h and
state_telemetry_aggregator.h.  On MSVC, this causes different name
mangling (V for class vs U for struct), resulting in LNK2019 for
exec_coordinator::on_message.
…te_script

Make evaluate_script a non-coroutine that parses the script then
delegates to evaluate(). Moving the parser/vector work out of the
coroutine frame avoids an MSVC bug where complex locals in the
coroutine body corrupt the frame, causing 'bad variant access' when
symmetric transfer completes.

Also change evaluate() to take value_t by value so the coroutine frame
owns the parameter — prevents dangling references when evaluate_script
returns the task before it is resumed.
@transfix
transfix force-pushed the feature/state-exec-phase1-2 branch from 39da475 to 62619b7 Compare May 25, 2026 06:46
@transfix
transfix merged commit 8c064db into master May 25, 2026
27 of 28 checks passed
@transfix
transfix deleted the feature/state-exec-phase1-2 branch May 25, 2026 07:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant