Skip to content

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

Merged
joelteply merged 3 commits into
canaryfrom
fix/training-trigger-and-adapter-honesty
Jun 9, 2026
Merged

joelteply merged 3 commits into
canaryfrom
fix/training-trigger-and-adapter-honesty

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Fix-1 of the canary-quality cleanup (task #236)

Addresses 6 of 13 BLOCK findings from the 3-reviewer adversarial pass on PRs #1574–#1579. Lands into canary. The three remaining fix-up PRs (Fix-2 honest metrics, Fix-3 defense, Fix-4 polish) follow.

This PR closes the most severe findings: the LocalCandleFineTuner silently winning every coordinator selection, the BucketKey shape silently dropping multi-base submits, and the concurrent-submit races that violate the trigger module's own no-data-loss contract.

Findings closed in this PR

ID Class Finding Fix
A1 Architecture LocalCandleFineTuner wildcard prefixes + locality bonus silently route every request (including gpt-4o-mini) to a Tensor::rand synthetic-base trainer supported_base_model_prefixes: vec![SYNTHETIC_BASE_PREFIX] — explicit synthetic-only
A2 Architecture supports_validation: true is a lie — actor never reads validation_split, hardcodes final_validation_loss: None Flip to false until train_epoch grows a validation pass
A4 Architecture BucketKey = (persona_id, trait_kind) rejects legitimate multi-base submits as InconsistentBucket → silent data loss Promote base_model into the key: BucketKey = (persona_id, trait_kind, base_model). Drop the runtime coherence check; the key IS the coherence guarantee
C1 Concurrency self.buckets.remove(&key) after .await on success path silently deletes a concurrent submit's accumulated data Per-key tokio::sync::Mutex serializes submit + flush. Different keys still concurrent
C2 Concurrency Restore-on-dispatch-failure either drops examples (if concurrent success removed the key) or commingles them under whoever-arrived-first's policy params Same per-key gate. The restore path is now sole-tenant of its key
C5 Concurrency Uncapped sequence_length: u32 from wire → Tensor::rand on tokio worker → mega-alloc DoS vector MAX_SEQUENCE_LENGTH = 8192 + MAX_BATCH_SIZE = 256 validated synchronously in spawn_job

Headline behavioral changes

Before: LocalCandleFineTuner advertises wildcard base + supports_validation=true
        → coordinator picks it for every request including gpt-4o-mini
        → silent substitution of Tensor::rand for the requested base model
After:  LocalCandleFineTuner advertises ["synthetic"] + supports_validation=false
        → coordinator only picks it for synthetic-prefixed bases
        → real-base requests fail loudly or route to a cloud adapter
Before: BucketKey = (persona, trait)
        Same persona + same trait + different base_model → InconsistentBucket reject
        → second submit's curated examples silently dropped
After:  BucketKey = (persona, trait, base_model)
        Same persona + same trait + different base_model → two distinct buckets
        → both submits succeed, both train independently
Before: submit drains bucket, drops entry guard, awaits dispatch, then:
          success → unconditional remove() (kills concurrent submit B's data)
          failure → get_mut() restore (may commingle or hit None)
After:   submit acquires per-key Mutex, holds across drain + dispatch + remove/restore
        Concurrent submits to same key serialize; sum-of-(dispatched + pending)
        is conserved

Tests

Total: training_trigger 9→11, fine_tuning 69→73, all passing.

New tests pinning the fixes:

  • capabilities_advertise_only_synthetic_base — pins post-fix capability shape so a future regression can't re-introduce silent substitution
  • capabilities_reject_non_synthetic_base_via_prefix_match — directly verifies gpt-4o-mini / qwen3.5-4b / mistral-large-latest do NOT match local-candle
  • different_base_models_create_separate_buckets — pins new correct A4 behavior: 2 buckets, both submits succeed
  • inconsistent_source_in_same_bucket_is_rejected — proves source coherence is STILL enforced (base_model leaving the coherence check didn't drop source coherence with it)
  • concurrent_submits_to_same_key_serialize_without_loss — the load-bearing C1+C2 fix verification. Two concurrent tasks submit to the same key, one fires + one accumulates. Asserts dispatched + pending == total_submitted. A regression in either C1 or C2 would fail this exactly.
  • sequence_length_above_cap_rejected_synchronously + sequence_length_zero_rejected_synchronously + batch_size_above_cap_rejected_synchronously — C5 cap validation

Plus: deleted inconsistent_base_model_in_same_bucket_is_rejected (no longer the behavior).

Adversarial review notes

Bring back the same 3-reviewer lens (math/VDD, architecture, concurrency) focused on this diff. The headline things to refute:

  • The per-key gate uses tokio::sync::Mutex (await-safe). Verify holding across .await is correct, not deadlock-prone, and doesn't leak gate entries unboundedly (the submit_gates DashMap grows per unique key seen).
  • supported_base_model_prefixes: vec!["synthetic"] — is "synthetic" the right discriminator? Could a real cloud model ever have "synthetic" as a prefix?
  • MAX_SEQUENCE_LENGTH = 8192 — is this past every real LoRA context (Qwen 3.5 / Llama 3 / Mistral) we'd want to train against? Or too tight?
  • The concurrent test asserts conservation but doesn't exercise the failure path (restore-on-failure under concurrent submit). Should add a follow-up if reviewers want it; it requires a dispatch-failing adapter fixture which lands cleaner in Fix-2.

Remaining backlog (queued PRs)

  • Fix-2 — M1 honest trained_tokens + M2 RecordingFineTuningAdapter conservation test + M3 pad-as-target mask
  • Fix-3 — C3 cancel mid-epoch + C4 bounded LRU job table + C6 quarantine + C8 spawn_blocking semaphore
  • Fix-4 — A5 required schedule/lora + A6 simplified coordinator.select + A7 typed JobCreateResult use + C7 early-cancel Running flicker
  • Deferred to teacher-synthesis slice — A3 typed EngramAttribution metadata (philosophical doctrine call)

…nt 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]>
…view (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]>
@joelteply

Copy link
Copy Markdown
Contributor Author

Re-review round 2 — closing 6 of 7 BLOCKs from the three reviewers (R1 math/VDD-honesty, R2 architecture, R3 concurrency). Pushed commit 0f6dc13dd. Reviewer findings + closures:

R1 (math/VDD) — both BLOCKs closed:

  • B1 cap-boundary asymmetry → sequence_length_at_cap_accepted + batch_size_at_cap_accepted (pin the inclusive semantic, not just rejection)
  • B2 missing batch_size_zero_rejected → added (symmetric with sequence_length)

R2 (architecture) — all 3 BLOCKs closed:

  • B1 submit_gates unbounded growth → try_evict_gate with Arc::strong_count == 1 check after successful dispatch (in both submit + flush)
  • B2 incomplete coherence (lora/schedule/etc. silently first-arrival-wins) → symmetric runtime coherence checks for lora, schedule, validation_split, local_artifact_dir, preferred_provider. Required PartialEq on LoRAHyperparams + ScheduleParams (ts-rs bindings regenerated)
  • B3 SYNTHETIC_BASE_PREFIX not discoverable → re-exported from genome::fine_tuning::mod.rs + CoordinatorError::NoCapableAdapter now carries supported_prefixes: Vec<(provider_id, Vec<prefix>)> so the error message surfaces the exact prefix string a caller needs

R3 (concurrency) — BLOCK addressed with honest caveat:

  • The concurrency test was a no-op (current_thread + zero yields in dispatch chain). Moved behind #[cfg(feature = "stress-tests")] mod stress per CLAUDE.md test discipline, used multi-thread runtime + YieldingRecordingAdapter that yields + sleeps 5ms in create_job to actually exercise dispatch interleaving. Captures the dispatched TrainingDataset for true conservation accounting (vs the tautological trained_tokens > 0 of the unit-test VDD).

    Honest caveat in the test comment: this is a smoke-level conservation check, NOT a deterministic race-exercise. Even with the gate disabled, fire-loads kept absorbing accumulators in a steady-state cycle so conservation held. A tokio::sync::Notify-based deterministic test that pauses the dispatch .await while a contending submit lands an accumulator (then asserts that accumulator survives the fire-load's remove) lands in Fix-3 alongside the RecordingFineTuningAdapter promotion to a system fixture.

LGTMs:

  • R2-LGTM2 MAX_SEQUENCE_LENGTH not from SubstrateGovernor → comment added pointing at future governor migration; code change deferred (DoS protection ≠ LCD default; different doctrine class)
  • R3-LGTMs: gate semantics + cap placement confirmed correct, no fix needed

Tests: training_trigger 9 → 12 unit + 1 stress; fine_tuning 73 → 76. All passing under default cargo test and --features stress-tests.

@joelteply
joelteply merged commit 7c67258 into canary Jun 9, 2026
1 check passed
@joelteply
joelteply deleted the fix/training-trigger-and-adapter-honesty branch June 9, 2026 17:46
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