Repository navigation
fix(genome): Fix-1 — capability honesty + bucket-key + concurrent submit safety (task #236) - #1580
Conversation
…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]>
|
Re-review round 2 — closing 6 of 7 BLOCKs from the three reviewers (R1 math/VDD-honesty, R2 architecture, R3 concurrency). Pushed commit R1 (math/VDD) — both BLOCKs closed:
R2 (architecture) — all 3 BLOCKs closed:
R3 (concurrency) — BLOCK addressed with honest caveat:
LGTMs:
Tests: training_trigger 9 → 12 unit + 1 stress; fine_tuning 73 → 76. All passing under default |
…rnor migration (R2-LGTM2)
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
gpt-4o-mini) to aTensor::randsynthetic-base trainersupported_base_model_prefixes: vec![SYNTHETIC_BASE_PREFIX]— explicit synthetic-onlysupports_validation: trueis a lie — actor never readsvalidation_split, hardcodesfinal_validation_loss: Nonefalseuntil train_epoch grows a validation passBucketKey = (persona_id, trait_kind)rejects legitimate multi-base submits as InconsistentBucket → silent data lossbase_modelinto the key:BucketKey = (persona_id, trait_kind, base_model). Drop the runtime coherence check; the key IS the coherence guaranteeself.buckets.remove(&key)after.awaiton success path silently deletes a concurrent submit's accumulated datatokio::sync::Mutexserializes submit + flush. Different keys still concurrentsequence_length: u32from wire →Tensor::randon tokio worker → mega-alloc DoS vectorMAX_SEQUENCE_LENGTH = 8192+MAX_BATCH_SIZE = 256validated synchronously inspawn_jobHeadline behavioral changes
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 substitutioncapabilities_reject_non_synthetic_base_via_prefix_match— directly verifiesgpt-4o-mini/qwen3.5-4b/mistral-large-latestdo NOT match local-candledifferent_base_models_create_separate_buckets— pins new correct A4 behavior: 2 buckets, both submits succeedinconsistent_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. Assertsdispatched + 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 validationPlus: 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:
tokio::sync::Mutex(await-safe). Verify holding across.awaitis correct, not deadlock-prone, and doesn't leak gate entries unboundedly (thesubmit_gatesDashMap 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?Remaining backlog (queued PRs)
trained_tokens+ M2 RecordingFineTuningAdapter conservation test + M3 pad-as-target maskEngramAttributionmetadata (philosophical doctrine call)