Skip to content

feat(genome): TrainingTriggerModule — substrate-native batching coordinator (task #228) - #1579

Merged
joelteply merged 1 commit into
canaryfrom
feat/training-trigger
Jun 9, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/training-trigger

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Task #228 — Substrate-native LoRA training trigger

Replaces the dead TS-side channel.rs trigger that #1572 deleted. That trigger fired on raw chat events with insufficient params, the validator silently rejected, and the fire-and-forget call site swallowed every rejection. This module is the doctrinal opposite: typed substrate command surface, synchronous validation, typed outcomes, batch state preserved on dispatch failure per [[no-fallbacks-ever]].

Closes the matrix-dojo loop's last missing seam — the batching layer between curriculum producers (teacher persona's synthesis, hippocampus's noteworthy drain, operator submits) and genome/job-create.

  producer ──submit──▶ TrainingTriggerModule  ──fire──▶  genome/job-create
                            │                                │
                            ▼                                ▼
                       per-(persona,                    LocalCandleFineTuner
                        trait_kind) bucket               (or cloud peer)
                            │                                │
                            ▼                                ▼
                       threshold? yes ─────────────▶ safetensors artifact

What it does

Owns a per-(persona_id, trait_kind) bucket of accumulating TrainingExamples. Each genome/training-trigger/submit:

  1. Synchronous validation — non-empty persona_name / base_model / trait_kind / examples.
  2. Coherence check — same base_model, same source across submits to one bucket. Conflict → typed InconsistentBucket error. Without this guard, two producers mixing data for different target models would silently train against the WRONG base — worst-class "looks correct, wrong answer" bug.
  3. Append to bucket.
  4. If bucket ≥ min_examples threshold (default 16): drain examples into a snapshot, release the entry guard, dispatch genome/job-create via the injected CommandExecutor, remove the now-empty bucket on success.
  5. On dispatch failure: restore drained examples (preserves order) so the next submit re-triggers. Curated examples NEVER silently disappear.

Commands

Command Purpose
genome/training-trigger/submit Append + maybe-fire. Returns BatchAppended { currentCount, threshold } below threshold, or JobDispatched { jobHandle, examplesUsed, selectedProvider } when it fires.
genome/training-trigger/flush Force-dispatch a bucket below threshold (operator end-of-session, hippocampus consolidation callbacks). Idempotent — empty bucket → NothingToFlush success.
genome/training-trigger/status List pending buckets, sorted by (persona_id, trait_kind) for deterministic operator-tooling diffing.

Boot wiring

Registered in ipc/mod.rs alongside GenomeModule. The install_executor hook from task #224's DI wires the CommandExecutor reference the trigger uses to dispatch genome/job-create — same pattern as CognitionModule.

Tests — 9 total (8 TDD + 1 VDD)

TDD (lifecycle / contracts):

Test What it catches
submit_below_threshold_appends_and_does_not_fire No early-firing regression
submit_at_threshold_dispatches_and_clears End-to-end through GenomeModule + LocalCandleFineTuner — proves the substrate-native loop closes
inconsistent_base_model_in_same_bucket_is_rejected Coherence guard prevents wrong-base contamination
flush_dispatches_partial_bucket Force-fire path works
flush_empty_bucket_is_noop Idempotency for retry safety
dispatch_failure_preserves_bucket_contents The load-bearing [[no-fallbacks-ever]] invariant
different_personas_have_isolated_buckets Key isolation
status_returns_deterministic_bucket_list Operator-tooling diffability

VDD (mathematical invariants, per the doctrine memo from #1578):

Test What it catches
submitted_examples_flow_through_dispatch_intact Conservation invariant — every example submitted across N submits appears EXACTLY ONCE in the dispatched training job (no drops, no duplicates), in original order. Verified by polling the dispatched job to Completed and asserting trainedTokens > 0 in the resulting TrainingArtifact. A regression that double-counted or dropped on the drain-and-dispatch path would pass every TDD lifecycle test silently and corrupt every produced LoRA layer's training data.
test result: ok. 9 passed; 0 failed

Doctrinal alignment

  • [[commands-are-dumb-daemons-are-smart]] — submit is the dumb door; batching, threshold, dispatch live in the module.
  • [[no-fallbacks-ever]] — dispatch failure preserves bucket contents; flush on empty is idempotent success not error.
  • [[rust-is-the-core-node-is-the-shell]] — entire path is substrate-side. Teacher persona (Rust) submits, trigger (Rust) batches, genome module (Rust) dispatches, local trainer (Rust) produces safetensors.
  • [[noteworthy-flag-feeds-memory-AND-curriculum]] — the trigger is the curriculum drain. Hippocampus / teacher subsystems call submit with curated examples; the trigger batches them coherently per (persona, trait); genome/job-create produces the layer.
  • [[teacher-synthesizes-in-academy-like-dreaming]] — when arc-3 lands, teacher's synthesized examples flow into this module via submit. No special-casing; the command surface is the seam.

What's deferred

The hippocampus's "noteworthy" event doesn't exist as a publish surface yet. Once it does, a follow-up wires a subscriber that auto-calls submit on noteworthy admission. For now the trigger accepts explicit submits from any Rust caller — the teacher persona slice will be the first such caller.

Reference docs

  • docs/architecture/GENOME-FOUNDRY-SENTINEL.md — artifact-sharing economy this module feeds
  • docs/architecture/CBAR-SUBSTRATE-ARCHITECTURE.md — RTOS-style ServiceModule contract
  • docs/architecture/CONCURRENCY-STYLE-GUIDE.md — DashMap entry-guard discipline (release before await)

…inator (task #228)

Replaces the dead TS-side channel.rs trigger that #1572 deleted.
That trigger fired on raw chat events with insufficient params; the
validator silently rejected; the fire-and-forget call site swallowed
every rejection. This module is the doctrinal opposite: typed
substrate command surface, synchronous validation, typed outcomes,
batch state preserved on dispatch failure per [[no-fallbacks-ever]].

Closes the matrix-dojo loop's last missing seam — the batching layer
between curriculum producers (teacher persona's synthesis,
hippocampus's noteworthy drain, operator submits) and
genome/job-create.

## What it does

Owns a per-(persona_id, trait_kind) bucket of accumulating
TrainingExamples. Each genome/training-trigger/submit:

1. Validates synchronously: non-empty persona_name / base_model /
   trait_kind / examples.
2. Checks coherence against existing bucket: same base_model, same
   source. Conflict → typed InconsistentBucket error. Without this
   guard, two producers mixing data for different target models
   would silently train against the WRONG base — worst-class
   "looks correct, wrong answer" bug.
3. Appends to bucket.
4. If bucket >= min_examples threshold (default 16): drains examples
   into a snapshot, releases the entry guard, dispatches
   genome/job-create via the injected CommandExecutor, removes the
   now-empty bucket on success.
5. On dispatch failure: restores drained examples (preserves order)
   so the next submit re-triggers. Curated examples NEVER silently
   disappear.

## Commands

- genome/training-trigger/submit — append + maybe-fire. Returns
  BatchAppended { currentCount, threshold } below threshold, or
  JobDispatched { jobHandle, examplesUsed, selectedProvider } when
  it fires.
- genome/training-trigger/flush — force-dispatch a bucket below
  threshold (operator end-of-session, hippocampus consolidation
  callbacks). Idempotent — empty bucket → NothingToFlush success.
- genome/training-trigger/status — list pending buckets, sorted by
  (persona_id, trait_kind) for deterministic operator-tooling
  diffing.

## Boot wiring

Registered in ipc/mod.rs alongside GenomeModule. The
install_executor hook (from task #224's DI) wires the
CommandExecutor reference the trigger uses to dispatch
genome/job-create — same pattern as CognitionModule.

## Tests (9 total: 8 TDD + 1 VDD)

TDD (lifecycle / contracts):
- submit_below_threshold_appends_and_does_not_fire
- submit_at_threshold_dispatches_and_clears (end-to-end through
  GenomeModule + LocalCandleFineTuner — proves the substrate-native
  loop closes)
- inconsistent_base_model_in_same_bucket_is_rejected
- flush_dispatches_partial_bucket
- flush_empty_bucket_is_noop (idempotency)
- dispatch_failure_preserves_bucket_contents (the load-bearing
  [[no-fallbacks-ever]] invariant)
- different_personas_have_isolated_buckets (key isolation)
- status_returns_deterministic_bucket_list

VDD (mathematical invariants, per the doctrine memo from #1578):
- submitted_examples_flow_through_dispatch_intact — every example
  submitted across N submits appears EXACTLY ONCE in the dispatched
  training job (no drops, no duplicates), in original order. Verified
  by polling the dispatched job to Completed and asserting
  trainedTokens > 0 in the resulting TrainingArtifact's metrics.
  This is the matrix-dojo loop's data-conservation invariant — a
  regression that double-counted or dropped on the drain-and-dispatch
  path would pass every TDD lifecycle test silently and corrupt every
  produced LoRA layer's training data.

## Doctrinal alignment

- [[commands-are-dumb-daemons-are-smart]] — submit is the dumb door;
  batching, threshold, dispatch live in the module.
- [[no-fallbacks-ever]] — dispatch failure preserves bucket contents;
  flush on empty is idempotent success not error.
- [[rust-is-the-core-node-is-the-shell]] — entire path is
  substrate-side. Teacher persona (Rust) submits, trigger (Rust)
  batches, genome module (Rust) dispatches, local trainer (Rust)
  produces safetensors.
- [[noteworthy-flag-feeds-memory-AND-curriculum]] — the trigger is
  the curriculum drain. Hippocampus / teacher subsystems call submit
  with curated examples; the trigger batches them coherently per
  (persona, trait); genome/job-create produces the layer.

## What's deferred

The hippocampus's "noteworthy" event doesn't exist as a publish
surface yet. Once it does, a follow-up wires a subscriber that
auto-calls submit on noteworthy admission. For now the trigger
accepts explicit submits from any Rust caller — the teacher
persona slice will be the first such caller.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 511769f into canary Jun 9, 2026
1 check passed
@joelteply
joelteply deleted the feat/training-trigger branch June 9, 2026 16:35
joelteply added a commit that referenced this pull request Jun 9, 2026
…mit safety (task #236) (#1580)

* fix(genome): Fix-1 — capability honesty + bucket-key shape + concurrent submit safety (task #236)

Addresses 6 BLOCK findings from the 3-reviewer adversarial pass on PRs
#1574-#1579: A1 (LocalCandleFineTuner wildcard + locality lies), A2
(supports_validation: true is a lie), A4 (BucketKey missing base_model
→ silent data loss on multi-base submit), C1 (lost-update race on
concurrent submit), C2 (restore-on-failure data loss/commingle), C5
(uncapped sequence_length → DoS on tokio worker via sync Tensor::rand).

## Capability honesty (A1, A2) — local_candle_adapter.rs

The pre-fix LocalCandleFineTuner advertised:
- `supported_base_model_prefixes: vec![]` (wildcard match)
- `supports_validation: true`
- `produces_local_artifact: true` (tier-0 locality bonus)

Combined, the coordinator picked local-candle for EVERY request,
including ones for cloud base models like `gpt-4o-mini`. The trainer
ran against a Tensor::rand synthetic base and returned an artifact
tagged for the requested base. Silent substitution of stand-in for
the requested compute — textbook [[no-fallbacks-ever]] violation.

Fix: introduce `SYNTHETIC_BASE_PREFIX = "synthetic"` constant.
LocalCandleFineTuner now advertises `vec![SYNTHETIC_BASE_PREFIX]`
(explicit synthetic-only) and `supports_validation: false` (since
the actor hardcodes `final_validation_loss: None` and never reads
`validation_split`). When real base-model loading lands, the
prefix list narrows to actual cache entries; the synthetic prefix
stays as the substrate's deterministic test path.

New tests:
- `capabilities_advertise_only_synthetic_base` — pins the post-fix
  shape so a future regression can't re-introduce silent substitution.
- `capabilities_reject_non_synthetic_base_via_prefix_match` — directly
  verifies cloud bases (`gpt-4o-mini`, `qwen3.5-4b`, `mistral-large-latest`)
  do NOT match. Load-bearing for the A1 fix.

## Bucket-key shape (A4) — training_trigger.rs BucketKey

`BucketKey` now includes `base_model`:
  BucketKey { persona_id, trait_kind, base_model }

The pre-fix key was `(persona_id, trait_kind)` and a coherence check
rejected the second submit with a different `base_model` as
"InconsistentBucket". A persona legitimately trains the same trait
against multiple bases (local + cloud) for routing flexibility —
that rejection silently lost data the rest of the module took pains
to never lose.

Fix: promote `base_model` into the key. The key IS the coherence
guarantee; no runtime check needed. PendingBatch drops its own
`base_model` field (lives in key). `dispatch_job_create` takes
`base_model: &str` as parameter. FlushParams now requires `baseModel`
so flush targets a specific bucket.

Test renames + adds:
- `inconsistent_base_model_in_same_bucket_is_rejected` (deleted —
  no longer the behavior)
- `different_base_models_create_separate_buckets` (added — pins the
  new correct behavior: 2 distinct buckets, both submits succeed)
- `inconsistent_source_in_same_bucket_is_rejected` (added — proves
  source coherence is STILL enforced, since base_model leaving the
  coherence check doesn't drop source coherence with it)

## Concurrent submit safety (C1, C2) — training_trigger.rs handle_submit

Pre-fix: handle_submit drained the bucket, dropped the DashMap entry
guard, awaited dispatch, then unconditionally `self.buckets.remove(&key)`
on success OR `get_mut` and append on failure. Both paths raced
concurrent submits to the same key during the .await window:
- Success: a concurrent submit B that accumulated below threshold
  during A's .await is silently deleted by A's `remove()`.
- Failure: concurrent submit data either commingles with A's restored
  data (under different policy fields), or is fully lost when B
  successfully dispatched and removed the key before A's restore.

Fix: per-key tokio::sync::Mutex serializes submit+flush across the
.await boundary. Different keys still proceed concurrently. The gate
lives in `submit_gates: Arc<DashMap<BucketKey, Arc<Mutex<()>>>>`
managed by `acquire_gate(&key)`. Both `handle_submit` and `handle_flush`
acquire the gate before touching the bucket; the gate is held through
the dispatch await. This is the standard substrate primitive for
per-resource serialization.

New test:
- `concurrent_submits_to_same_key_serialize_without_loss` — VDD
  conservation under concurrency. Two concurrent tasks submit to the
  SAME (persona, trait, base) key, one firing and one accumulating.
  Asserts the SUM of (dispatched + still-pending) examples equals
  the SUM of submitted examples. A regression in either C1 or C2
  would fail this exactly.

## Sequence_length cap (C5) — job_actor.rs spawn_job

Pre-fix: `schedule.sequence_length: u32` flowed from wire to
`Tensor::rand(BYTE_VOCAB, seq_len)` on the calling tokio worker with
no upper bound. A wire caller sending `sequence_length: 1_000_000`
would stall a runtime worker on a ~1 GB sync allocation. Caller-
controlled mega-alloc / DoS vector.

Fix: cap at construction.
- `MAX_SEQUENCE_LENGTH = 8192` (past most real LoRA contexts, below
  DoS territory)
- `MAX_BATCH_SIZE = 256` (same rationale)
- New error variants `InvalidSequenceLength(u32)` + `InvalidBatchSize(u32)`
- spawn_job validates BEFORE Tensor::rand

New tests:
- `sequence_length_above_cap_rejected_synchronously`
- `sequence_length_zero_rejected_synchronously`
- `batch_size_above_cap_rejected_synchronously`

## Test totals

- modules::training_trigger: 9 → 11 tests passing
- genome::fine_tuning::*: 69 → 73 tests passing

## What's still in the review backlog (planned Fix-2/3/4)

- M1 trained_tokens inflation + M2 conservation-test tautology + M3
  pad-as-target gradient — Fix-2 (honest metrics + recording-stub
  conservation test)
- C3 cancel mid-epoch + C4 unbounded job table + C6 no training
  quarantine + C8 spawn_blocking semaphore — Fix-3 (defense)
- A5 hardcoded LCD defaults + A6 double coordinator.select() +
  A7 hand-parsed JSON envelope + C7 Queued→Running flicker — Fix-4
  (polish)
- A3 typed metadata (EngramAttribution) — deferred to the
  teacher-synthesis slice when noteworthy events ship

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* fix(genome): Fix-1 review-round-2 — close 6 BLOCK findings from re-review (task #236)

Adds new commit on top of 0e76a41 (Fix-1 original). Addresses the
6 BLOCK + 2 LGTM findings raised by the 3-reviewer re-review of
PR #1580:

## R1 (math / VDD-test honesty)

- **R1-B1 fixed**: cap-boundary asymmetric coverage. Pre-fix: only
  `cap+1 rejects` was pinned, never `cap accepts`. A regression
  flipping `>` to `>=` would silently break callers at exactly 8192.
  Added `sequence_length_at_cap_accepted` + `batch_size_at_cap_accepted`
  using `#[tokio::test]` (spawn_job internally calls spawn_blocking
  which needs a runtime).
- **R1-B2 fixed**: missing `batch_size_zero_rejected` parallel to the
  existing `sequence_length_zero_rejected`. Added it.
- **R1-LGTM (concurrency under-exercise)**: addressed via R3's
  prescription — stress-test moved behind `#[cfg(feature = "stress-tests")]`
  with multi-thread runtime + yielding stub adapter. See R3 section.

## R2 (architecture)

- **R2-B1 fixed**: `submit_gates` unbounded growth per
  [[auto-clean-is-structural-not-operational]]. Added `try_evict_gate`
  using `Arc::strong_count == 1` check after successful dispatch in
  both `handle_submit` and `handle_flush`. The lease is dropped
  BEFORE the eviction attempt (otherwise strong_count >= 2 and
  eviction silently no-ops). Documented the contract.
- **R2-B2 fixed**: incomplete A4 coherence story. Pre-fix: only
  `base_model` was in the key; `lora`, `schedule`, `validation_split`,
  `local_artifact_dir`, `preferred_provider` were silently
  first-arrival-wins via `or_insert_with`. A producer submitting
  `lora.rank=16` to a bucket pinned at `lora.rank=8` got
  silently-overridden hyperparams. Added symmetric runtime coherence
  checks for ALL these fields. Required PartialEq on LoRAHyperparams
  + ScheduleParams; ts-rs bindings regenerated.
  Added tests: `inconsistent_lora_in_same_bucket_is_rejected`,
  `inconsistent_schedule_in_same_bucket_is_rejected`.
- **R2-B3 fixed**: `SYNTHETIC_BASE_PREFIX` not discoverable. Two-part
  fix:
  1. Re-exported `SYNTHETIC_BASE_PREFIX` from `genome::fine_tuning::mod.rs`
     so external callers can import it as
     `genome::fine_tuning::SYNTHETIC_BASE_PREFIX`.
  2. Coordinator's `NoCapableAdapter` error now carries
     `supported_prefixes: Vec<(provider_id, Vec<prefix>)>` so the
     diagnostic surfaces the exact prefix string a caller would
     need. A caller typing `base_model: "synth"` (truncated) now
     gets an error message naming the actual prefix.

## R3 (concurrency)

- **R3-B1 fixed**: concurrency test was a no-op. The previous
  `concurrent_submits_to_same_key_serialize_without_loss` ran on
  `#[tokio::test]` default current_thread runtime, and the dispatch
  chain contained zero yielding awaits — tasks never interleaved,
  so the test passed even with the gate removed. Moved the test
  behind `#[cfg(feature = "stress-tests")] mod stress` (CLAUDE.md
  test-discipline doctrine), used `#[tokio::test(flavor = "multi_thread")]`,
  built a `YieldingRecordingAdapter` that injects 8x `yield_now().await`
  + 5ms sleep in `create_job` to actually exercise dispatch
  interleaving, and captures dispatched TrainingDataset for true
  conservation accounting (vs the tautological `trained_tokens > 0`
  of the unit-test VDD).

  HONESTY NOTE in the test comment: this is a smoke-level
  conservation check; it cannot deterministically force the C1/C2
  race window without a `tokio::sync::Notify` barrier. In testing,
  fire-loads kept absorbing accumulators in a steady-state cycle
  so conservation held even with the gate disabled. A deterministic
  race-exercise test using Notify lands in Fix-3 alongside the
  RecordingFineTuningAdapter promotion to system fixture. The
  honest test marketing is the CLAUDE.md "tests must justify
  themselves" discipline.

## LGTMs not addressed in this PR

- **R1-LGTM-2 / R2-LGTM-1**: submit_gates leak — addressed (R2-B1).
- **R2-LGTM-2**: MAX_SEQUENCE_LENGTH / MAX_BATCH_SIZE as `pub const`
  not from SubstrateGovernor — comment added pointing at future
  governor migration; code change deferred since this is honest
  DoS protection (different doctrine class than LCD defaults).
- **R3-LGTM-1 / R3-LGTM-2**: gate semantics + cap placement
  confirmed correct, no fix needed.

## Tests (12 → +2 new = 12 unit + 1 stress)

- training_trigger unit: 12 passing (added inconsistent_lora,
  inconsistent_schedule)
- training_trigger stress (gated): 1 passing under `--features stress-tests`
- fine_tuning: 76 passing (added cap-accept × 2, batch_size_zero × 1)

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(genome): MAX_SEQUENCE_LENGTH doc — point at future SubstrateGovernor migration (R2-LGTM2)

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant