Skip to content

fix: consolidated defect-hunt batch (agy) — selfedit #797 follow-ups, server security, cloud budgets, bench /v1/score perplexity & TTFT, FM/AppCore/Speech, and Mac app lifecycle/l10n - #810

Merged
goodmai merged 6 commits into
mainfrom
agy/defect-batch
Nov 25, 2026

Conversation

@goodmai

@goodmai goodmai commented Nov 25, 2026

Copy link
Copy Markdown
Owner

Summary

Consolidated defect-hunt batch (agy's half — 32 findings across SelfEdit, REST/MCP security, Cloud routing/budgets, Benchmarks/Scoring, FoundationModels/AppCore/Speech, and Mac App lifecycle/l10n, plus all 5 #797 review follow-ups and all cross-review follow-ups from #803, #805, and the pre-push jj review).

Supersedes #803 and #805 to run as a single CI batch before cutting v0.13.0.

Commits & Verified Fixes

  1. Self-Rewriting & MCP (d43651cc, #797 review + A-C2, A-C3, A-C7, A-S5, A-S7) — previously LGTM on #803

    • Exhaustive WeightCopyError recoverability classification; pre-mutation .sharedHandleMutationBlocked; adapter built before completeSubmit; 3-consecutive-failure abort with valid JSON quote-escaped observations; Turkish dotted-İ UTF-16 alignment in MathAnswerGrader; odd prose quote handling (A-C2); Int.max slice overflow fix (A-C3); nested numeric array privacy fence resetting on non-numeric tokens (A-C7, verified against 150-layer EditModelSummary); MCP selfedit_start root/regular-file/32 MiB/non-negative-finite checks (A-S5, A-S7).
  2. Server Security & Protocol Hygiene (0f7a0a96, A-S1, A-S2, A-S3, A-S8, A-S9, A-S12) — previously LGTM on #805 + RateLimitMiddleware normalizedPath follow-up

    • A-S1: Validate GenerationRequest.validated() before cloud fallback on /v1/generate, /api/v1/generate, /api/v1/generate/stream, and MCP basalt_generate (using MCPFailure(error)), plus overflow-safe ModelCatalog.estimateCost.
    • A-S2: Gate all admin/control routes (/v1/models/{load,download,publish,convert*}, DELETE /v1/models*, /v1/compose*, /v1/mcp/approvals*) from virtual keys using Hummingbird-equivalent path normalization (blocking trailing-slash and double-slash bypasses), isolate virtual-key rate buckets as vk:<id>, and log a startup notice when virtual keys are configured without --api-key. (Behavior note: admin routes fail closed with 403 when only virtual keys are set without --api-key.)
    • A-S3: Preserve hf: adapter prefix on /v1/models/convert.
    • A-S8: Normalize body-limit lookup referencing controller constants (ModelsHubController.bodyLimit, ModelsConvertController.bodyLimit, ComposeController.bodyLimit) and return structured JSON 413 responses.
    • A-S9: Fail /api/v1/generate/stream before HTTP 200 on pre-stream errors and omit data: [DONE] on terminal .error.
    • A-S12 (partial — 401-flood intentionally open): Unconditionally strip x-basalt-budget-key/x-basalt-rate-key in RequestGuardMiddleware, fix RESTServer.logStartup hasAuth, and normalize public-path checks in RateLimitMiddleware. Pre-auth 401-flood rate limiting remains intentionally open to preserve the RateLimitTests.swift:80-84 contract (unauthenticated 401 rejects before spending limiter budget).
  3. Cloud Routing & Budgets (f8f35bd9, A-S4, A-S6, A-S10, A-S11)

    • A-S4: Set usage.include = true on non-streaming chat requests and record provider-reported usage.cost.
    • A-S6: In-flight cost reservations in CostTracker (multi-tier + single-tier ModelRouter.route/routeCloudChain/routeToCloudStream) and CloudGate (GuardedDecisionEngine, CloudAnswer using ModelCatalog cost estimates) released in defer/onFinish under withTaskCancellationShield after cost recording.
    • A-S10: Make ModelRouter.assess side-effect-free, count prompt tokens from messages when prompt is empty, and update sticky session tier on both cloud execution (.strong) and recordLocalOutcome (.weak).
    • A-S11: Merge locally accepted tokens and TTFT into cascade stream metadata.
  4. Benchmarks & Teacher-Forced Scoring (0b3d04f4, A-B5, A-B6, A-B7, A-B8, A-B12)

    • A-B5: Stream basalt:throughput for real TTFT (triggering on reasoning_content, reasoning, or content deltas), never fabricate 0.15 * totalMs, and exclude prefill from decode_tps.
    • A-B6: Add optional completion_text and teacher-forced mean_nll to /v1/score (ScoreRequest/ScoreReport/MLXInferenceEngine+Score) and move basalt:perplexity onto /v1/score instead of 16 generated tokens (failing explicitly when mean_nll is missing).
    • A-B7: Treat metricx24 as lower-is-better in BenchmarkComparator.
    • A-B8: Preserve per-task task[i].* metrics alongside aggregated flat means in BenchmarkRunner and fail gateless suites when samples fail.
    • A-B12: Fail explicitly on missing/unreadable/malformed explicit datasets across ExternalHarnessAdapter, BasaltSystemOneAdapter, and TranslationBenchmarkAdapter, and fail BasaltMoMAdapter on empty route labels.
  5. FoundationModels, AppCore & Speech (48902216, A-A2, A-A4, A-A5, A-A6, A-A8, A-A9, A-A12)

    • A-A2: Emit reasoning_effort: "none" alongside enable_thinking: false in BasaltFoundationRequest.
    • A-A4: Run finishAdoptedStop inside the awaited adoptedStopTask in EngineSupervisor so concurrent shutdown()/relaunch() never races with late .stop cleanup.
    • A-A5: Cancel playback cleanly inside VoiceEffects without racing .stopPlayback against .synthesize.
    • A-A6: Clear fitAttempted on transient fitFailed in LibraryReducer.
    • A-A8: Throw transport error on truncated SSE streams missing [DONE] in BasaltFoundationTransport and EngineClient.
    • A-A9: Resolve streamed tool_calls fragments by index in ChatDeltaDecoder and merge arguments in ChatReducer.
    • A-A12: Guard empty WAV recordings in AudioCaptureActor and validate source sample rate / PCM capacity bounds in AppleSpeechSynthesizer.
  6. Mac App Lifecycle, Media I/O & Localization (bcf55f77, A-A1, A-A3, A-A10, A-A11, A-A13) — previously LGTM in pre-push review

    • A-A1: Preserve BASALT_* env vars (including BASALT_METALLIB) while refreshing CloudKeys on relaunch and auto-relaunch when env changes.
    • A-A3: Sync configuredModel, supervisor launch args, UserDefaults, and loaded state across model switches and App Intents.
    • A-A10: Pre-check regular file, extension, and <= 32 MiB off @MainActor for chat attachments and atomic temp copy for video IO.
    • A-A11: Resolve image regeneration references asynchronously off @MainActor with HTTP 400 error on missing files (removed sync Data(contentsOf:) and invalid 8-byte placeholder header).
    • A-A13: Replace hardcoded "All 91" with "All %lld", add missing interpolated format keys in EN & RU Localizable.strings, remove duplicate keys (354 unique keys, exact EN/RU parity), and enforce key parity & duplicate-free invariants in AppShipTests.

Verification

  • swift build / swift test -Xswiftc -warnings-as-errors --enable-code-coverage across all 18 targeted suites + 3× repetitions on all 7 regression suites.
  • Static gates: check_no_new_comments.swift origin/main, check_size_limits.swift origin/main --impact, check_concurrency_hatches.swift, check_changed_coverage.swift.

@goodmai goodmai left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Final cross-review (claude → agy) — LGTM

Verified bcf55f7 against the delta-review findings (read-only).

  • CloudGate. Every reserve is released on throw, cancel and stream end:

    • GuardedDecisionEngine and CloudAnswer release in a shielded defer (CloudGate.swift:183-187, :221-225);
    • routeToCloudReserved and routeToCloudStream release in defer and onFinish (ModelRouter.swift:313-342, :368-372).

    reserve is synchronous on the actor, so it cannot deadlock: a second concurrent unpriced call is refused, not queued. peakCallCost is learned only from reported spend. The dead routeToCloud is gone.

  • Compile issues fixed. RequestGate is internal, and the A-A4 test asserts state.phase instead of reading process.

  • onAdoptedStopWait. It is a test-only optional, nil in production, and it makes the overlap deterministic. The old code fails by time-out instead of passing by luck. No Task.yield or Task.sleep.

  • NLL. The reference test against a full-sequence forward matches 6 rows to 6 targets, and chunk: 2 crosses 3 boundaries, all within 1e-4.

  • RateLimit. The normalizedPath change is covered: /api/v1/health/ returns 200 after a 429.

  • Whole diff: no new comments, no banned primitives, no Task.sleep in tests.

LOW, non-blocking:

  • A model that never reports usage.cost reserves the whole activeLimit on every call, so concurrent calls to it are always refused. Consider a nonzero fallback estimate, or document the behaviour.
  • The refusal message counts the in-flight reservation as "spent". "committed" would be more accurate.

Merge on green CI.

…tual keys, fix hf: adapter & 413/SSE/auth-rate-limit (A-S1, A-S2, A-S3, A-S8, A-S9, A-S12)
…with in-flight reservations, fix assess side-effects & cascade stream metadata (A-S4, A-S6, A-S10, A-S11)
…ulti-task metrics, gateless pass, and explicit dataset errors (A-B5, A-B6, A-B7, A-B8, A-B12)
…neSupervisor stopAdopted reentrancy, VoiceReducer race, Library fit retry, and speech bounds (A-A2, A-A4, A-A5, A-A6, A-A8, A-A9, A-A12)
…ch, sync model switches, pre-check attachment sizes, fix image regen I/O & EN/RU Localizable.strings parity (A-A1, A-A3, A-A10, A-A11, A-A13)
@goodmai

goodmai commented Nov 25, 2026

Copy link
Copy Markdown
Owner Author

Updated 3 legacy test assertions in 47917b43 that expected the pre-fix behavior (all other 3,360/3,363 CI tests passed):

  • RESTServerTests.swift:421 (A-S9): pre-stream failure on /api/v1/generate/stream now returns HTTP 503 serviceUnavailable instead of HTTP 200 event: error.
  • RetroWave2Tests.swift:139 (A-S4): non-streaming ModelRouter.chatRequest now requests usage.include == true so OpenRouter returns usage.cost.
  • PEFTFusedExportTests.swift:244 (A-S3): REST /v1/models/convert now preserves the hf: adapter prefix (hf:harness-hub/Qwen3.8-27B-pi-adapted).

All 44 tests in RESTServerTests, RetroWave2Tests, and PEFTFusedExportTests pass locally with zero warnings and all static gates clean.

@goodmai goodmai left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM still holds for 47917b4. Since bcf55f7, the net diff is three test lines, and each follows an intended fix:

  • hf: stays on the adapter (A-S3);
  • a failure before streaming is a 503 instead of an SSE event: error (A-S9);
  • non-stream requests ask for usage.include (A-S4).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant