Skip to content

feat(genome): fine-tuning subsystem — trait + coordinator + ServiceModule + OpenAI + local skeleton (task #230) - #1574

Merged
joelteply merged 2 commits into
canaryfrom
feat/fine-tuning-subsystem
Jun 9, 2026
Merged

joelteply merged 2 commits into
canaryfrom
feat/fine-tuning-subsystem

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Brings the model-touchpoint architecture together: the persona never names a provider; the substrate picks. Two commits stacked on canary:

  1. Trait + types + registry + OpenAI adapter — typed wire surfaces, FineTuningAdapter trait, FineTuningRegistry, first working cloud adapter
  2. Coordinator + ServiceModule + local skeleton + boot wiring — FineTuningCoordinator selection logic, GenomeModule ServiceModule handling genome/job-{create,status,cancel}, LocalCandleFineTuner skeleton with honest "not yet" semantics, conditional adapter registration in start_server

After merge a persona's Commands.execute('genome/job-create', request) lands in Rust, the coordinator picks an adapter by capability + locality, the adapter creates the job, the substrate returns a typed JobHandle.

What lands

Trait family

pub trait FineTuningAdapter: Send + Sync {
    fn capabilities(&self) -> FineTuningCapabilities;
    async fn create_job(&self, req: TrainingJobRequest) -> Result<JobHandle, FineTuningError>;
    async fn poll(&self, h: &JobHandle) -> Result<TrainingStatus, FineTuningError>;
    async fn cancel(&self, h: &JobHandle) -> Result<(), FineTuningError>;
}

Same async-trait + Arc<dyn> shape as AIProviderAdapter for inference. Errors are typed: InvalidRequest / MissingCredentials / ProviderRejected / Transient / MalformedResponse / LocalTrainerFailed / UnknownHandle.

Typed wire surfaces (8 ts-rs exports)

TrainingJobRequest, TrainingDataset, TrainingExample, TrainingSource (teacher_synthesized / operator_curated / raw / mesh_inherited), LoRAHyperparams, ScheduleParams, JobHandle, TrainingStatus, TrainingArtifact, JobMetrics. No serde_json::Value pass-through across boundaries.

Coordinator

Stateless selector with deterministic ordering:

  1. Filter by hard capability match (base prefix, LoRA, validation)
  2. Honor preferred_provider when capable; otherwise typed PreferredUnavailable
  3. Rank by locality (produces_local_artifact=true beats cloud)
  4. Alphabetical tie-break

The locality rule pins the matrix-dojo doctrine — training data stays on-substrate when local capacity exists.

Adapters

  • OpenAIFineTuningAdapter — working. Uploads dataset via /v1/files, creates job, polls, cancels. Maps OpenAI's status strings to typed TrainingStatus. HTTP error taxonomy (4xx → ProviderRejected, 5xx → Transient).
  • LocalCandleFineTuner — skeleton. Returns typed LocalTrainerFailed with pointers to follow-up tasks #231/#232/#233. Architectural slot is visible; math not implemented. Per [[no-fallbacks-ever]]: honest "not yet" beats fabricated success.

GenomeModule ServiceModule

Three commands: genome/job-create / genome/job-status / genome/job-cancel. Narrow dispatch per [[commands-are-dumb-daemons-are-smart]]: validate → ask coordinator → call adapter → return. All errors return as {success: false, error, errorKind} envelopes; the slug taxonomy mirrors the typed FineTuningError variant set so TS-side callers branch on errorKind not on string parsing.

Boot wiring

start_server builds the registry, conditionally registers OpenAIFineTuningAdapter when OPENAI_API_KEY is present, always registers LocalCandleFineTuner (skeleton slot stays visible), then registers GenomeModule on top.

Verified

cargo check -p continuum-core --lib --features metal,accelerate                 -> clean
cargo test  -p continuum-core --lib --features metal,accelerate
  genome::fine_tuning::                                                         -> 34/34
  modules::genome::                                                             -> 5/5

39 new tests across types/adapter/registry/coordinator/openai/local-skeleton/ServiceModule, plus 9 ts-rs binding tests for the protocol exports. Covers: trait object-safety + dyn dispatch; registry lookup + re-registration returns prior; 8 coordinator selection invariants pinned individually; OpenAI HTTP status mapping + error kind taxonomy; ServiceModule envelope contract + preferred-provider honoring + UnknownHandle slug.

Doctrinal alignment

  • [[commands-are-dumb-daemons-are-smart]] — GenomeModule is narrow. Selection logic lives in FineTuningCoordinator; future cost/pressure/reputation signals slot in there.
  • [[no-fallbacks-ever]] — LocalCandleFineTuner returns typed LocalTrainerFailed instead of silent fallback. PreferredUnavailable is the typed answer to "honor my preference or tell me why you can't."
  • [[matrix-dojo-layer-loading-as-substrate-primitive]] — coordinator's locality preference keeps training data on-substrate.
  • [[inference-is-an-adapter-always-in-the-loop]] extended: fine-tuning is also an adapter, always in the loop.
  • [[rust-is-the-core-node-is-the-shell]] — genome/job-create is now Rust. The TS-side src/commands/genome/job-create/ becomes deletable in a follow-up.

Follow-ups (filed)

  • #231 LocalCandleFineTuner: LoRA module + autograd (math 1/3)
  • #232 LocalCandleFineTuner: data loader + AdamW + training loop (math 2/3)
  • #233 LocalCandleFineTuner: job lifecycle actor + safetensors output (math 3/3)
  • 5 more cloud adapters (Mistral / Anthropic / Fireworks / DeepSeek / Together) — each ~250 LOC mirroring the OpenAI pattern, registers with one line in start_server

Test plan

  • Library compiles clean on canary base
  • Runtime + module test suites green
  • New genome::fine_tuning:: and modules::genome:: tests green (39/39)
  • ts-rs bindings regenerate without conflict (9 new files in protocol/typescript/genome/fine_tuning/)
  • Joel signed off on shape ("Yeah please do" — merge)

🤖 Generated with Claude Code

joelteply and others added 2 commits June 9, 2026 01:56
…AI adapter (task #230, Stage 1)

Lays the substrate-side architectural seam for the continuous-learning
loop: noteworthy engrams → teacher-synthesized curriculum →
fine-tuning subsystem → LoRA artifact → forge/alloy provenance →
genome paging → mesh sharing.

Joel's framing on this stage: "make a glorious fine tuning subsystem
per our awesome continuous learning. Modular code." This commit
lands the modular pieces; the local Candle trainer + remaining cloud
adapters + the academy/teacher pipeline are follow-up PRs that plug
into the seams this commit defines.

## What lands

### `core/continuum-core/src/genome/fine_tuning/`

A new submodule under the existing `genome/` cache + paging
infrastructure. Four files:

- **`mod.rs`** — doctrine doc explaining where this module sits in
  the continuous-learning loop. Stage 3 of 6: takes a curated
  dataset + hyperparams + provider preference, runs a job, returns
  a `TrainingArtifact` that forge / alloy / paging consume.

- **`types.rs`** — typed wire surfaces. Every field that crosses an
  adapter boundary is typed at compile time; no `serde_json::Value`
  pass-through except for opt-in dataset-example metadata:
  - `TrainingJobRequest` (persona_id, base_model, trait_kind,
    dataset, optional hyperparams)
  - `TrainingDataset` + `TrainingExample` + `TrainingSource` enum
    (`teacher_synthesized` / `operator_curated` / `raw` /
    `mesh_inherited`) — source provenance is load-bearing for the
    substrate's reputation signal
  - `LoRAHyperparams` + `ScheduleParams`
  - `JobHandle` (provider_id + provider_job_id + local UUID)
  - `TrainingStatus` tagged enum (Queued / Running / Completed /
    Failed / Cancelled) — terminal `Completed` carries the
    `TrainingArtifact`
  - `TrainingArtifact` + `JobMetrics`
  All structs ts-rs export to `protocol/typescript/genome/fine_tuning/`
  so TS-side consumers get matching types automatically.

- **`adapter.rs`** — the `FineTuningAdapter` trait + typed
  `FineTuningError` taxonomy (`InvalidRequest` /
  `MissingCredentials` / `ProviderRejected` / `Transient` /
  `MalformedResponse` / `LocalTrainerFailed` / `UnknownHandle`).
  Same async-trait + `Arc<dyn ...>` shape that `AIProviderAdapter`
  in `ai/adapter.rs` uses for inference — the substrate's two
  model-touchpoint seams now mirror each other. Trait is
  object-safe; covered by a stub-adapter dyn-dispatch test.

- **`registry.rs`** — `FineTuningRegistry` keyed by `provider_id`.
  Same pattern as the inference `AdapterRegistry`. Re-registering
  the same provider returns the prior entry so callers can shut it
  down cleanly (proven by `re_register_returns_prior` test, written
  to catch the "silently lying about lookup success" pattern Stage
  B was about removing).

### `core/continuum-core/src/genome/fine_tuning/openai_adapter.rs`

First concrete adapter — proves the trait fits a real provider's
shape. Implements:

- `create_job` — uploads dataset as JSONL via `/v1/files`
  (purpose=fine-tune), then POSTs `/v1/fine_tuning/jobs`. Schedule
  hyperparams pass through to OpenAI's `hyperparameters` field when
  the caller supplied them; otherwise OpenAI picks defaults.
- `poll` — GETs `/v1/fine_tuning/jobs/{id}`, maps OpenAI's status
  string set (`validating_files` / `queued` / `running` /
  `succeeded` / `failed` / `cancelled`) to typed `TrainingStatus`
  variants. Terminal `succeeded` builds the `TrainingArtifact` from
  `fine_tuned_model` + `trained_tokens`. OpenAI doesn't ship weights
  back; `local_path` stays `None`.
- `cancel` — POSTs the cancel endpoint.

Provider/error mapping is conservative: 4xx → `ProviderRejected`
(don't retry without fixing the request), 5xx → `Transient`
(backoff + retry is appropriate), JSON shape mismatch →
`MalformedResponse`. 429 is currently mapped to `ProviderRejected`
because the OpenAI docs class it as a quota / config issue, not a
transient outage — pinned by test so a future flip to `Transient`
is a conscious choice.

### Cargo dependency

Adds `multipart` to the existing `reqwest` feature list for the
`/v1/files` upload step. No new top-level dep.

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate   -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate
    genome::fine_tuning::                                            -> 22/22

The 22 tests cover:
- `types`: 11 (ts-rs binding generation pinned per struct + the
  three hand-written invariant tests — TrainingSource snake_case,
  TrainingStatus tagged shape + camelCase fields, LoRA hyperparam
  camelCase serialization)
- `adapter`: 2 (trait object-safety + end-to-end stub roundtrip
  through create/poll/cancel)
- `registry`: 2 (lookup by provider_id + re-register returns prior)
- `openai_adapter`: 4 (status mapping covers all documented states +
  HTTP error taxonomy + provider_id mismatch returns UnknownHandle +
  capabilities pin)

## What's next (Stage 2+ of #230)

Each is a small, focused PR that drops into the seam this commit
defines:

- Mistral adapter (OpenAI-API-compatible mostly; quirk handling for
  Mistral's job lifecycle differences)
- Anthropic adapter
- Fireworks / DeepSeek / Together adapters
- `LocalCandleFineTuner` — the substrate-native sibling. Uses the
  existing `inference/lora.rs` weight-merge math, adds the
  optimizer loop. This is where the matrix-dojo + teacher-synthesis
  doctrines actually compound — in-process training closes the loop
  between persona experience and persona capability without any
  cloud-provider hop.
- Rust `genome/job-create` ServiceModule — narrow command on top of
  this trait; replaces the dead trigger we deleted in PR #1572.

## Doctrinal alignment

- `[[teacher-synthesizes-in-academy-like-dreaming]]` — the
  `TrainingSource::TeacherSynthesized` variant exists specifically
  to mark academy-synthesized datasets distinct from raw operator
  corpora; substrate-side reputation can branch on this.
- `[[noteworthy-flag-feeds-memory-AND-curriculum]]` — the doctrine
  doc in `mod.rs` names this as the upstream of the curriculum
  drain; this PR doesn't wire that drain yet but the
  `TrainingJobRequest` is shaped to accept it.
- `[[matrix-dojo-layer-loading-as-substrate-primitive]]` — the
  `TrainingArtifact` flows directly into the existing
  `persona/genome_paging.rs` LRU-managed working set; no new layer
  in between.
- `[[mesh-of-lessons-cross-persona-curricula]]` — `TrainingSource::MeshInherited`
  is the typed marker that the substrate can use to attribute
  cross-persona curriculum sharing.
- `[[rust-is-the-core-node-is-the-shell]]` — the 6 TS LoRA-trainer
  adapters in `src/daemons/ai-provider-daemon/adapters/*/server/*FineTuningAdapter.ts`
  become individually deletable as each Rust adapter lands.
- `[[no-fallbacks-ever]]` — every adapter method returns a typed
  `FineTuningError` variant. No silent skip; no `Ok(())` on a job
  that didn't actually start (the cautionary tale being the dead
  channel.rs trigger from PR #1572).
- `[[every-error-is-an-opportunity-to-battle-harden]]` — the error
  taxonomy distinguishes retriable (`Transient`) from terminal
  (`ProviderRejected` / `MalformedResponse` / `LocalTrainerFailed`)
  so the substrate-side dispatcher branches correctly on first
  failure, not after a thousand burned retries.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…uner skeleton — the unification

Stacks on top of `feat/fine-tuning-subsystem` (which lands the trait
+ types + registry + OpenAI adapter). This commit wires the dispatch
seam: a `genome/*` ServiceModule on top of a typed coordinator that
abstracts provider selection across local / grid / cloud.

Joel's framing: "Finally bringing it all together into a performant
concurrent rtos abstracting provider whether local, grid or cloud."
The convergence:

- Inference: `AIProviderAdapter` trait, 9 cloud providers + local
  llamacpp + cross-grid airc-remote (#108) all behind one Arc<dyn>
- Fine-tuning: `FineTuningAdapter` trait, 1 cloud impl (OpenAI) +
  local-candle skeleton + future cross-grid airc-remote, all
  behind one Arc<dyn>
- Both seam into the same RTOS substrate: `ServiceModule` + `tick` +
  `install_executor` + `PressureBroker` + `TokioConcurrencyPolicy`
- Persona never names a provider; substrate picks per request

## What lands

### `core/continuum-core/src/genome/fine_tuning/coordinator.rs`

`FineTuningCoordinator` — stateless selector consulting an
`Arc<FineTuningRegistry>`. Algorithm:

1. **Filter** by hard capability match: base_model prefix (empty Vec
   = wildcard for local Candle), `supports_lora` if request has
   LoRA hyperparams, `supports_validation` if dataset's
   validation_split > 0.
2. **Honor preferred_provider** when supplied AND capable. When the
   preference is registered but NOT capable for this request,
   return typed `PreferredUnavailable` with the diagnostic — no
   silent fallback to a different provider ([[no-fallbacks-ever]]).
3. **Otherwise rank by locality**: adapters with
   `produces_local_artifact=true` beat cloud. Tier 0 = local; tier
   1 = cloud.
4. **Alphabetical tie-break** within tier. Stable, no hidden
   ordering.

9 unit tests cover each rule independently. The locality rule is
load-bearing for the matrix-dojo doctrine — pinning it now keeps
training data on-substrate when local capacity exists.

### `core/continuum-core/src/genome/fine_tuning/local_candle_adapter.rs`

`LocalCandleFineTuner` — substrate-native LoRA trainer skeleton.
Honest "not yet" semantics per [[no-fallbacks-ever]] + the
cautionary tale of the dead `channel.rs` trigger we deleted in PR
#1572:

- Exists as a real registered adapter (the architectural slot is
  visible to the coordinator + telemetry + operator)
- `create_job` returns `FineTuningError::LocalTrainerFailed` with
  pointers to follow-up tasks #231/#232/#233 — explicit "math not
  implemented" instead of fabricated success
- `poll` / `cancel` correctly reject unknown handles with
  `UnknownHandle` instead of fabricating a `TrainingStatus`
- Capabilities advertise the eventual real shape
  (`produces_local_artifact=true` so locality preference fires;
  wildcard base prefixes; LoRA + validation supported), so swapping
  the math in later requires no call-site changes

When tasks #231-#233 land the optimizer loop, this struct fills in
place. The trait + the dispatch + the boot wiring all stay.

### `core/continuum-core/src/modules/genome.rs`

`GenomeModule` ServiceModule. Three commands:

- `genome/job-create` — coordinator picks provider, adapter creates
  job. Returns `{success, result: {handle, selectedProvider}}` so
  callers see which provider got picked (important for telemetry +
  operator validation of the locality preference).
- `genome/job-status` — adapter looked up by `handle.provider_id`,
  polls, returns typed `TrainingStatus`.
- `genome/job-cancel` — same lookup, cancels.

Per [[commands-are-dumb-daemons-are-smart]] the module is narrow.
All errors return as `{success: false, error, errorKind}` so TS-side
callers can branch on the typed `errorKind` slug
(`InvalidRequest` / `MissingCredentials` / `ProviderRejected` /
`Transient` / `MalformedResponse` / `LocalTrainerFailed` /
`UnknownHandle`) without parsing free-form text.

### `start_server` boot wiring (`ipc/mod.rs`)

Builds a `FineTuningRegistry`, conditionally registers
`OpenAIFineTuningAdapter` when `OPENAI_API_KEY` is set, always
registers `LocalCandleFineTuner`, then registers the `GenomeModule`
backed by the populated registry. Mistral / Anthropic / Fireworks /
DeepSeek / Together adapters plug in here as their impls land — same
pattern, gated on the matching `*_API_KEY` secret.

### `core/continuum-core/Cargo.toml`

Adds `multipart` to `reqwest` features (carried over from the
stacked-below PR; OpenAI's `/v1/files` upload needs it).

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate    -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate
    genome::fine_tuning::                                             -> 34/34
    modules::genome::                                                 -> 5/5

39 new tests across the stack. Covers: trait object-safety + dyn
dispatch; registry lookup + re-registration; coordinator selection
rules (8 distinct invariants); OpenAI HTTP status mapping + provider
slug taxonomy; ServiceModule wire shape + envelope contract +
preferred-provider honoring.

## Doctrinal alignment

- `[[commands-are-dumb-daemons-are-smart]]` — `GenomeModule` is
  narrow (validate → look up adapter → dispatch). All smart logic
  (capability filter, locality preference, future cost/pressure
  signals) lives in `FineTuningCoordinator` + the adapter impls.
- `[[no-fallbacks-ever]]` — `LocalCandleFineTuner` skeleton returns
  typed `LocalTrainerFailed` instead of silently picking cloud or
  fabricating success. `PreferredUnavailable` is the typed answer
  to "honor my preference or tell me why you can't."
- `[[matrix-dojo-layer-loading-as-substrate-primitive]]` — the
  coordinator's locality rank ensures training data stays
  on-substrate when local capacity exists.
- `[[inference-is-an-adapter-always-in-the-loop]]` extended: fine-
  tuning is also an adapter, always in the loop. The coordinator
  is the substrate's typed answer to "which adapter?"
- `[[rust-is-the-core-node-is-the-shell]]` — `genome/job-create`
  now exists as a Rust ServiceModule. The TS-side equivalent in
  `src/commands/genome/job-create/` is no longer authoritative;
  follow-up PR can delete it once Node clients route through the
  Rust path.

## Follow-ups (already filed)

- #231: `LocalCandleFineTuner` LoRA module + autograd (math 1/3)
- #232: data loader + AdamW + training loop (math 2/3)
- #233: job lifecycle actor + safetensors output (math 3/3)
- 5 more cloud adapters (Mistral / Anthropic / Fireworks / DeepSeek
  / Together) — each ~250 LOC mirroring the OpenAI pattern, slots
  into the existing boot wiring with a one-line registration

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 7ff541c into canary Jun 9, 2026
1 check passed
@joelteply
joelteply deleted the feat/fine-tuning-subsystem branch June 9, 2026 14:39
joelteply added a commit that referenced this pull request Jun 9, 2026
…spec init + autograd (task #231) (#1575)

First of three follow-ups (#231 + #232 + #233) that fill in the
math layer of the LocalCandleFineTuner skeleton landed in PR #1574.
This commit builds the trainable LoRA module — the substrate-native
sibling to inference/lora.rs (which handles the load + merge path
post-training).

## What lands

core/continuum-core/src/genome/fine_tuning/lora_module.rs (~470 LOC)

LoRAModule: one trainable LoRA layer wrapping a frozen base linear
weight. Holds the base as a plain Tensor (no autograd) plus two
trainable candle_core::Var matrices A and B.

Math (matches inference/lora.rs::merge_lora_weight exactly):

  y = x · W^T + (alpha/rank) · (x · A^T) · B^T

  W: base weight   [out_features, in_features]   (frozen)
  A: down-project  [rank, in_features]            (trainable)
  B: up-project    [out_features, rank]           (trainable)

Init policy per the LoRA paper (Hu et al. 2021):
- A ~ Kaiming uniform, bound = √(1/in_features)
- B = zeros

This makes the initial delta exactly zero so the model behaves
identically to the frozen base at step 0. Training perturbs A and B
away from this fixed point. Any other init (B random, A zero) would
either cause divergence from the base at init or eliminate gradient
signal — the test suite pins both invariants.

Typed LoRAError taxonomy:
- InvalidRank(0) — would produce zero-sized A/B (no learning capacity)
- InvalidAlpha(0) — would zero the scale factor (delta never affects forward)
- BaseWeightShape{actual} — non-2-D base weight gets a typed error
  before the first forward, not an opaque Candle matmul error later

## Why a struct + forward, not impl candle_nn::Module

candle_nn::Module forward signature does not carry training-vs-eval
state. The optimizer + training loop (#232) needs a forward_train
distinction (dropout active during training). Cleaner to compose
this as a plain struct with an explicit forward now; #232 adds the
training/eval variants if dropout becomes needed.

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate                              -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate genome::fine_tuning::lora_module -> 8/8

The 8 tests pin every load-bearing invariant:
- rank_zero_rejected: typed InvalidRank
- alpha_zero_rejected: typed InvalidAlpha
- non_2d_base_weight_rejected: typed BaseWeightShape
- b_is_zero_initialized_so_initial_delta_is_zero: forward at init == base forward
- a_init_is_non_trivial: A has non-zero values so gradient signal flows through B
- forward_preserves_leading_dims_and_maps_in_to_out: shape contract on [batch, seq, in_features] -> [batch, seq, out_features]
- scale_factor_matches_inference_side_convention: scale == alpha/rank, same as inference/lora.rs
- forward_with_perturbed_ab_diverges_from_base_by_scaled_delta: end-to-end math integration with known A,B values producing exact expected output

The shape contract test is load-bearing for the matrix-dojo
doctrine: A future refactor that swaps in/out axes would silently
produce wrong-shaped activations that crash downstream layers in
the training loop (#232) and corrupt the safetensors output (#233).
Pinning shape at the module boundary catches this at the unit-test
level, not at integration-test time.

The init-zero-delta test is load-bearing for convergence: the LoRA
paper specifically calls out that B=0 init is what makes training
stable. A future refactor that initializes B with noise would
silently regress training quality.

The math integration test forces A and B to known non-zero values
and computes the expected output by hand — proves the implementation
matches the paper formula exactly. This is the contract with
inference/lora.rs::merge_lora_weight; if either side drifts, layers
trained here would behave differently at inference time.

## Doctrinal alignment

- [[matrix-dojo-layer-loading-as-substrate-primitive]]: the
  tensors produced here use the SAME layout as inference/lora.rs
  consumes (A: [rank, in_features], B: [out_features, rank],
  scale: alpha/rank). After #233 wires safetensors output, layers
  trained by this module load unchanged into the existing
  inference + paging path.
- [[no-fallbacks-ever]]: rank=0, alpha=0, non-2-D base weight all
  return typed errors at construction. No opaque tensor errors
  surfacing at the first forward pass.
- [[every-error-is-an-opportunity-to-battle-harden]]: the
  init-zero-delta test catches a class of regression (silent
  changes to B init policy) that would otherwise only show up as
  poor convergence in production training runs.

## What is next (#232 + #233)

- #232: data loader (TrainingExample -> tokenized batches) +
  AdamW optimizer + epoch-major training loop with gradient
  accumulation and validation pass. Consumes LoRAModule from this
  PR.
- #233: job lifecycle actor (in-process DashMap + watch channel)
  + safetensors writeout to TrainingArtifact.local_path. Closes
  the LocalCandleFineTuner so create_job actually starts a
  training run instead of returning LocalTrainerFailed.

Co-authored-by: Claude Opus 4.7 <[email protected]>
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