diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift index bd018db189..cd31b0c96a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2Contracts.swift @@ -794,9 +794,102 @@ public enum CBv2Event: Sendable { case finished(reason: CBv2FinishReason, usage: CBv2Usage) } +/// Engine-side per-request timing and step-participation counters, exported +/// once on the terminal `CBv2Usage`. NUMERICS ONLY: never token ids, text, +/// hashes, or pointers — the provider copies this verbatim onto the wire. +/// +/// Instants are nanosecond OFFSETS from the engine enqueue instant in the +/// `DispatchTime.now().uptimeNanoseconds` domain (the loop's existing +/// convention). `0` means "not observed"; every observed offset is clamped +/// to `>= 1`. Durations (`*NanosSum`, `pausedNanos`, `detokDelayFirstNanos`, +/// `prefix*Nanos`) are plain elapsed nanoseconds. +/// +/// Stamps are written only by the engine thread and reuse the step's +/// existing clock reads (`CBv2InFlightStep.wallStartedNanos` at launch, the +/// readback-done instant in `finalize`) — no per-row clock reads. +public struct CBv2RequestTiming: Sendable, Equatable { + /// First step whose plan included this row (`wallStartedNanos` of that + /// step). Queue wait == this value. + public var admittedNanos: UInt64 = 0 + /// Per-layer KV state allocated (`ensureKVState`). + public var kvAllocatedNanos: UInt64 = 0 + /// First step whose plan included one of this row's prefill chunks + /// (`wallStartedNanos` of that step). + public var prefillFirstLaunchNanos: UInt64 = 0 + /// Finalize of the step where `numComputedTokens >= promptTokens`. + public var promptComputedNanos: UInt64 = 0 + /// Finalize of the step that confirmed the first generated token + /// (engine-side; excludes the detokenization hop). + public var firstTokenNanos: UInt64 = 0 + /// `finishRequest` instant. + public var finishedNanos: UInt64 = 0 + /// Waiting→running crossings after the first admission (preemption + /// and capacity requeues). + public var readmissions: UInt32 = 0 + public var preemptions: UInt32 = 0 + public var capacityRequeues: UInt32 = 0 + /// Prefill chunk forwards launched for this row (all shapes). + public var prefillChunks: UInt32 = 0 + /// Of `prefillChunks`, those that rode a rectangular `[B, chunk]` cohort. + public var packedPrefillChunks: UInt32 = 0 + /// Of `prefillChunks`, those carrying image spans. + public var visionChunks: UInt32 = 0 + /// Of `prefillChunks`, solo chunks wider than `prefillChunkSize` (the + /// solo-prefill stripe). + public var soloStripeChunks: UInt32 = 0 + public var prefillChunkTokensMax: UInt32 = 0 + /// Finalized steps in which this row confirmed a token beyond its first + /// (an MTP verify round with ≥1 confirmed token counts once). + public var decodeSteps: UInt32 = 0 + /// Of the participated steps, those launched on the chained-decode path. + public var chainedDecodeSteps: UInt32 = 0 + /// Σ over participated steps of the token-producing row count. + public var batchRowsSum: UInt64 = 0 + public var batchRowsMin: UInt32 = 0 + public var batchRowsMax: UInt32 = 0 + /// Σ (readback-done instant − `wallStartedNanos`) over participated steps. + public var stepLatencyNanosSum: UInt64 = 0 + public var stepLatencyNanosMax: UInt64 = 0 + public var mtpRounds: UInt32 = 0 + public var mtpProposed: UInt32 = 0 + public var mtpAccepted: UInt32 = 0 + /// Total backpressure-paused time and pause transitions. + public var pausedNanos: UInt64 = 0 + public var pauseCount: UInt32 = 0 + /// FIRST token only, passthrough rows: engine confirm → detokenized + /// emit, measured inside the output stream's existing lock. + public var detokDelayFirstNanos: UInt64 = 0 + /// Submit-thread prefix-cache lookup duration (hashing + lookup + plan). + public var prefixLookupNanos: UInt64 = 0 + /// `applyAdoption` duration on the engine thread. + public var prefixAdoptionNanos: UInt64 = 0 + public init() {} +} + +/// Immutable heap box for `CBv2Usage.timing`. Keeps `CBv2Usage` — and every +/// enum/struct/`async let` result that carries it — one pointer larger +/// instead of ~170 bytes larger: the Swift 6.3 runtime frees `async let` +/// result buffers above a size threshold out of order ("freed pointer was +/// not the last allocation" in `asyncLet_finish_after_task_completion`), +/// reproduced on the UNMODIFIED engine by padding a test result struct. +/// Allocated only when `timing` is written (once per request at finish — +/// never on the step path); the zero value is a shared instance. +final class CBv2RequestTimingBox: Sendable { + let value: CBv2RequestTiming + init(_ value: CBv2RequestTiming) { self.value = value } + static let zero = CBv2RequestTimingBox(CBv2RequestTiming()) +} + public struct CBv2Usage: Sendable { public var promptTokens: Int public var completionTokens: Int + /// Engine per-request timing (defaulted; folded in at `finishRequest`). + /// Boxed storage — see `CBv2RequestTimingBox`. + public var timing: CBv2RequestTiming { + get { timingBox.value } + set { timingBox = CBv2RequestTimingBox(newValue) } + } + private var timingBox: CBv2RequestTimingBox = .zero /// Final per-request prefix lookup/adoption result. This describes the /// in-memory engine tier only; SSD staging remains a provider concern. public var prefixCacheOutcome: CBv2PrefixCacheOutcome @@ -889,10 +982,18 @@ public struct CBv2CapacitySnapshot: Sendable { /// direct liveness/wedge signal (a stalled engine stops incrementing) /// instead of proxying via event counts. public var stepsExecuted: Int + /// Cumulative Σ over finalized steps of (readback-done instant − + /// `wallStartedNanos`), i.e. launch→confirm wall time. Monotonic; + /// `stepWallNanosTotal / stepsExecuted` is the mean step latency. + public var stepWallNanosTotal: UInt64 = 0 + /// Cumulative Σ over finalized steps of rows that confirmed a token + /// beyond their first (decode rows). Monotonic; + /// `decodeRowsTotal / stepsExecuted` is the mean decode batch size. + public var decodeRowsTotal: UInt64 = 0 public init( activeRequests: Int, waitingRequests: Int, kvBytesInUse: Int, kvBytesCapacity: Int, kvBytesBackendCapacity: Int = 0, kvBytesReserved: Int = 0, activeTokens: Int, - stepsExecuted: Int = 0 + stepsExecuted: Int = 0, stepWallNanosTotal: UInt64 = 0, decodeRowsTotal: UInt64 = 0 ) { self.activeRequests = activeRequests self.waitingRequests = waitingRequests @@ -902,6 +1003,8 @@ public struct CBv2CapacitySnapshot: Sendable { self.kvBytesReserved = kvBytesReserved self.activeTokens = activeTokens self.stepsExecuted = stepsExecuted + self.stepWallNanosTotal = stepWallNanosTotal + self.decodeRowsTotal = decodeRowsTotal } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2RequestTiming+Stamps.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2RequestTiming+Stamps.swift new file mode 100644 index 0000000000..44b664c12b --- /dev/null +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/CBv2RequestTiming+Stamps.swift @@ -0,0 +1,135 @@ +// Copyright © 2026 Eigen Labs. +// +// ContinuousBatchingV2 — per-request timing stamps (`CBv2RequestTiming`). +// +// Every helper here is ENGINE-THREAD ONLY and writes plain integer fields on +// the `CBv2ScheduledRequest` already in hand: no allocation, no lock, no +// clock read. Instants come from the step's existing clock reads +// (`CBv2InFlightStep.wallStartedNanos` at launch, `readbackDoneNanos` set once +// in `finalize`) and are stored as offsets from `enqueuedNanos`. An observed +// offset is clamped to `>= 1` so `0` always means "not observed". + +import Foundation + +extension CBv2ScheduledRequest { + + /// Offset of `nowNanos` from the enqueue instant, never 0 once observed. + @inline(__always) + func timingOffset(_ nowNanos: UInt64) -> UInt64 { + max(1, nowNanos &- enqueuedNanos) + } + + /// First step whose plan included this row (`wallStartedNanos` of that + /// step). Idempotent: re-admissions after preemption / capacity requeue + /// keep the first stamp and are counted in `readmissions` instead. + /// + /// A prefix-cache hit allocates KV at enqueue-time adoption, BEFORE any + /// plan includes the row; the exported contract requires + /// `admitted <= kvAllocated`, so an earlier allocation stamp is raised + /// to the admission instant here (once, on the first admission only). + /// The adoption itself stays evidenced by `prefixAdoptionNanos > 0`. + @inline(__always) + func stampAdmission(launchNanos: UInt64) { + if timing.admittedNanos == 0 { + timing.admittedNanos = timingOffset(launchNanos) + if timing.kvAllocatedNanos != 0, timing.kvAllocatedNanos < timing.admittedNanos { + timing.kvAllocatedNanos = timing.admittedNanos + } + } + } + + /// Per-layer KV state allocated. Idempotent (a preempted row + /// re-allocates; the first allocation is the one that explains TTFT). + @inline(__always) + func stampKVAllocated(nowNanos: UInt64) { + if timing.kvAllocatedNanos == 0 { + timing.kvAllocatedNanos = timingOffset(nowNanos) + } + } + + /// One prefill chunk forward launched for this row this step. + @inline(__always) + func stampPrefillChunkLaunch( + tokens: Int, packed: Bool, vision: Bool, stripe: Bool, launchNanos: UInt64 + ) { + if timing.prefillFirstLaunchNanos == 0 { + timing.prefillFirstLaunchNanos = timingOffset(launchNanos) + } + timing.prefillChunks &+= 1 + if packed { timing.packedPrefillChunks &+= 1 } + if vision { timing.visionChunks &+= 1 } + if stripe { timing.soloStripeChunks &+= 1 } + let width = UInt32(clamping: tokens) + if width > timing.prefillChunkTokensMax { timing.prefillChunkTokensMax = width } + } + + /// The row confirmed token(s) in a finalized step: batch-size and + /// launch→confirm latency aggregates. `batchRows` is the step's + /// token-producing row count; the latency is the step's readback-done + /// instant minus its launch instant (both already read). + @inline(__always) + func recordStepParticipation(step: CBv2InFlightStep, batchRows: Int) { + let rows = UInt32(clamping: batchRows) + timing.batchRowsSum &+= UInt64(rows) + if timing.batchRowsMin == 0 || rows < timing.batchRowsMin { + timing.batchRowsMin = rows + } + if rows > timing.batchRowsMax { timing.batchRowsMax = rows } + let latency = step.readbackDoneNanos &- step.wallStartedNanos + timing.stepLatencyNanosSum &+= latency + if latency > timing.stepLatencyNanosMax { timing.stepLatencyNanosMax = latency } + if step.chained { timing.chainedDecodeSteps &+= 1 } + } + + /// The step that confirmed this row's FIRST generated token: the prompt + /// is fully computed and the engine-side TTFT is observed (both at the + /// readback-done instant). + @inline(__always) + func stampFirstToken(readbackDoneNanos: UInt64) { + let offset = timingOffset(readbackDoneNanos) + if timing.promptComputedNanos == 0 { timing.promptComputedNanos = offset } + if timing.firstTokenNanos == 0 { timing.firstTokenNanos = offset } + } + + /// One MTP verify round finalized for this row. + @inline(__always) + func recordMTPRound(drafted: Int, accepted: Int) { + timing.mtpRounds &+= 1 + timing.mtpProposed &+= UInt32(clamping: drafted) + timing.mtpAccepted &+= UInt32(clamping: accepted) + } + + /// Backpressure pause / resume on the engine thread (monotonic instants + /// from the loop's injectable clock; the paused interval is a duration, + /// so the clock domain is irrelevant). + func recordPaused(now: ContinuousClock.Instant) { + guard pausedSince == nil else { return } + pausedSince = now + timing.pauseCount &+= 1 + } + + func recordResumed(now: ContinuousClock.Instant) { + guard let since = pausedSince else { return } + pausedSince = nil + timing.pausedNanos &+= Self.nanoseconds(now - since) + } + + /// Fold the terminal instant and the scheduler's own counters into the + /// exported struct. Called once, in `finishRequest`. + func exportTiming(finishedNanos: UInt64) -> CBv2RequestTiming { + var exported = timing + exported.finishedNanos = timingOffset(finishedNanos) + exported.preemptions = UInt32(clamping: preemptionCount) + return exported + } + + private static func nanoseconds(_ duration: Duration) -> UInt64 { + guard duration > .zero else { return 0 } + let components = duration.components + let seconds = UInt64(clamping: components.seconds) + let (whole, overflow) = seconds.multipliedReportingOverflow(by: 1_000_000_000) + guard !overflow else { return UInt64.max } + let fractional = UInt64(clamping: components.attoseconds / 1_000_000_000) + return whole &+ fractional + } +} diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift index 0f45d289b3..2ac57bf577 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineLoopV2.swift @@ -19,6 +19,7 @@ import Foundation import MLX +import os // MARK: - Model interface (WS-F adapters / WS-G fixtures conform) @@ -358,6 +359,15 @@ final class CBv2InFlightStep { /// Host wall clock captured before graph construction for controller /// attribution at the existing finalize boundary. let wallStartedNanos: UInt64 + /// The ONE unconditional timing read in `finalize`, taken right after + /// the host readback; every per-row stamp of that finalize reuses it. + var readbackDoneNanos: UInt64 = 0 + /// Launched on the chained-decode fast path (per-request + /// `chainedDecodeSteps` telemetry). + var chained = false + /// Rows that confirm tokens when this step finalizes: sampled rows plus + /// MTP verify rows (confirmed by the accept walk, not the sampler). + var tokenProducingRows: Int { sampledRows.count + (mtpRound?.verify?.rows.count ?? 0) } var mtpMeasurement: CBv2MTPStepMeasurement? /// KV states whose release is fenced behind this step's completion. /// `rollbackOne` scrubs the wasted-token KV tail before release; @@ -428,6 +438,8 @@ struct CBv2PrefixLookup: @unchecked Sendable { let adoption: CBv2PrefixAdoption? let outcome: CBv2PrefixCacheOutcome let matchedTokens: Int + /// Submit-thread lookup duration (`CBv2RequestTiming.prefixLookupNanos`). + var lookupNanos: UInt64 = 0 } struct CBv2PrefixUsage { @@ -687,6 +699,36 @@ public final class EngineLoopV2: @unchecked Sendable { public private(set) var stepCount = 0 public private(set) var chainedStepCount = 0 public private(set) var preemptionCount = 0 + /// Cumulative step telemetry published on `CBv2CapacitySnapshot` + /// (`publishGauges`): Σ launch→readback-done wall nanos over finalized + /// steps, and Σ rows that confirmed a non-first token. Engine-thread + /// owned, monotonic, two plain `+=` per finalize. (internal(set): the + /// MTP accept walk in EngineLoopV2+MTPFinalize.swift counts here too.) + public private(set) var stepWallNanosTotal: UInt64 = 0 + public internal(set) var decodeRowsTotal: UInt64 = 0 + /// Timing-read reuse windows (engine thread only). `launchClockNanos` + /// is the in-progress launch's `wallStartedNanos` (so `ensureKVState` + /// stamps KV allocation without its own read); `finalizeClockNanos` is + /// the in-progress finalize's readback-done instant (so finishes + /// driven by that finalize stamp `finishedNanos` without a read). + /// Zero outside those windows, where a fresh read is taken instead. + /// `boundaryClockNanos` covers step-boundary finishes (cancel / lease + /// expiry): ONE lazily-taken read per step shared by every row finished + /// there, none when nothing finishes; reset at the top of `engineStep`. + var launchClockNanos: UInt64 = 0 + var finalizeClockNanos: UInt64 = 0 + var boundaryClockNanos: UInt64 = 0 + + @inline(__always) + private func boundaryFinishNanos() -> UInt64 { + if boundaryClockNanos == 0 { + boundaryClockNanos = DispatchTime.now().uptimeNanoseconds + } + return boundaryClockNanos + } + /// Instruments "step" intervals. Zero cost unless a signpost consumer is + /// attached (`isEnabled` guards both ends). + static let signposter = OSSignposter(subsystem: "com.darkbloom.engine", category: "cbv2") /// Packed-prefill EXECUTION evidence (`CBv2PackedPrefillActivity`). /// Incremented in `executeMixed` at the rectangular forward itself, so a /// capability that is claimed but never exercised leaves both at zero. @@ -846,8 +888,13 @@ public final class EngineLoopV2: @unchecked Sendable { return } draining = true + // One read (per clock domain) for every waiting row the + // drain cancels. + let drainNanos = DispatchTime.now().uptimeNanoseconds + let drainNow = config.clock.now() for rec in scheduler.waiting { - finishRequest(rec.id, reason: .cancelled) + finishRequest( + rec.id, reason: .cancelled, nowNanos: drainNanos, now: drainNow) } publishGauges() drainWaiters.append(waiter) @@ -1236,7 +1283,8 @@ public final class EngineLoopV2: @unchecked Sendable { return } do { - try scheduler.enqueue(request) + let record = try scheduler.enqueue(request) + record.timing.prefixLookupNanos = prefixLookup.lookupNanos armLease(for: request) detokenizers[request.id] = detokenizerFactory.makeDetokenizer(stopStrings: request.stopStrings) @@ -1382,6 +1430,7 @@ public final class EngineLoopV2: @unchecked Sendable { do { let record = try scheduler.enqueue(request) + record.timing.prefixLookupNanos = prefixLookup.lookupNanos let hasPrefixPreview = prefixLookup.adoption != nil if let adoption = prefixLookup.adoption { // Projection needs only immutable plan metadata. @@ -1611,6 +1660,7 @@ public final class EngineLoopV2: @unchecked Sendable { _ adoption: CBv2PrefixAdoption, requestID: CBv2RequestID ) -> Bool { + let adoptionStartedNanos = DispatchTime.now().uptimeNanoseconds defer { prefixCache?.endAdoption( requestID: adoption.requestID, tokens: adoption.tokens, matched: adoption.matched, @@ -1620,6 +1670,21 @@ public final class EngineLoopV2: @unchecked Sendable { markPrefixAdoptionFailed(requestID, outcome: .adoptionFailed) return false } + // Once per adoption (not per step): the reserve + backend adoption + // duration, success or fallback alike. A successful adoption IS the + // row's KV allocation (`ensureKVState` finds it), stamped from the + // same read — and raised to the admission instant by + // `stampAdmission` at first launch, since adoption precedes the + // first plan and the exported contract requires + // `admitted <= kvAllocated`. + defer { + let adoptionEndedNanos = DispatchTime.now().uptimeNanoseconds + rec.timing.prefixAdoptionNanos = max( + 1, adoptionEndedNanos &- adoptionStartedNanos) + if kvStates[requestID] != nil { + rec.stampKVAllocated(nowNanos: adoptionEndedNanos) + } + } if let capacity { do { // Frozen replay physically owns full K/V through M from the @@ -1731,6 +1796,7 @@ public final class EngineLoopV2: @unchecked Sendable { let now = config.clock.now() if paused { scheduler.pause(id) + scheduler.record(for: id)?.recordPaused(now: now) // Arm the backpressure lease and suspend the progress lease: // a request blocked on a slow consumer is not an engine stall. if var lease = leasesByID[id] { @@ -1739,6 +1805,7 @@ public final class EngineLoopV2: @unchecked Sendable { } } else { scheduler.resume(id) + scheduler.record(for: id)?.recordResumed(now: now) // Clear the backpressure lease and grant a fresh progress // window — the paused interval was not the engine's fault. if var lease = leasesByID[id] { @@ -1761,7 +1828,12 @@ public final class EngineLoopV2: @unchecked Sendable { } let stepStart = CBv2StepProfiler.enabled ? CFAbsoluteTimeGetCurrent() : 0 markStepStarted() + // Instruments-only step interval: both ends gated on `isEnabled`, so + // an unattached process pays one static bool read per step. + let signposter = Self.signposter + let signpostState = signposter.isEnabled ? signposter.beginInterval("step") : nil defer { + if let signpostState { signposter.endInterval("step", signpostState) } markStepEnded() if CBv2StepProfiler.enabled { CBv2StepProfiler.record( @@ -1773,7 +1845,8 @@ public final class EngineLoopV2: @unchecked Sendable { // stamping, and the finalize-time progress refresh — so lease gaps are // exactly one step apart (never widened by extra clock reads). let stepNow = config.clock.now() - processCancellations() + boundaryClockNanos = 0 // see `boundaryFinishNanos` + processCancellations(now: stepNow) processLeaseExpiry(now: stepNow) // Chained decode fast path: build step N+1 on step N's lazy tokens. @@ -1902,7 +1975,7 @@ public final class EngineLoopV2: @unchecked Sendable { // running rows in markAdmitted below. let waitingBeforePlan = Set(scheduler.waiting.map(\.id)) let plan = scheduler.plan() - handlePreemptions(plan.preemptions) + handlePreemptions(plan.preemptions, now: stepNow) guard !plan.assignments.isEmpty else { publishGauges() scheduleIdleRecheck() @@ -2331,6 +2404,7 @@ public final class EngineLoopV2: @unchecked Sendable { wallStartedNanos: wallStartedNanos) if let stepLogprobs { step.logprobSegments = [stepLogprobs] } step.recurrentEvaluations = recurrent + step.chained = true return step } @@ -2341,6 +2415,8 @@ public final class EngineLoopV2: @unchecked Sendable { /// `samples` predicate are structurally wrong for speculative tokens). func executeMixed(_ plan: CBv2StepPlan) -> CBv2InFlightStep? { let wallStartedNanos = DispatchTime.now().uptimeNanoseconds + launchClockNanos = wallStartedNanos + defer { launchClockNanos = 0 } struct RowWork { let rec: CBv2ScheduledRequest let start: Int @@ -2353,6 +2429,7 @@ public final class EngineLoopV2: @unchecked Sendable { work.reserveCapacity(plan.assignments.count) for (id, n) in plan.assignments { guard let rec = scheduler.record(for: id) else { continue } + rec.stampAdmission(launchNanos: wallStartedNanos) guard ensureKVState(rec) != nil else { continue } // error-finished let start = rec.numComputedTokens - n // pre-optimistic-advance position // The step samples iff it computes through the last known token. @@ -2385,6 +2462,15 @@ public final class EngineLoopV2: @unchecked Sendable { var decodeSampled: MLXArray? var logprobSegments: [CBv2StepLogprobs] = [] if !decodeRows.isEmpty { + // A one-token prompt (or a one-token final prompt chunk) is + // decode-SHAPED but still computes prompt tokens: count it as + // the row's prefill chunk so `prefillChunks >= 1` holds for + // every request. One compare per decode row, no allocation. + for row in decodeRows where row.start < row.rec.request.promptTokens.count { + row.rec.stampPrefillChunkLaunch( + tokens: 1, packed: false, vision: false, stripe: false, + launchNanos: wallStartedNanos) + } let inputs = MLXArray(decodeRows.map { Int32($0.rec.tokens[$0.start]) }) .reshaped([decodeRows.count, 1]) let decodeIDs = decodeRows.map(\.rec.id) @@ -2433,6 +2519,14 @@ public final class EngineLoopV2: @unchecked Sendable { // A multimodal request's text-only chunks remain packable. // A span-bearing chunk needs explicit rectangular embedding // and row-mask capability from both model and cache provider. + // KNOWN LIMITATION (pre-existing; not changed by the timing + // series): `chunkContext` is nil for `.causal` multimodal + // input, so a causal span chunk classifies as text here — + // packed without embedding splicing — and its launch stamp + // records the path taken (`vision: false`). The shipped + // causal model (Qwen) never reaches the packed cohort: the + // recurrent/position gate below forces its solo path. Span + // PRESENCE is `hasSpans(start:count:)` if this is revisited. let hasSpan = multimodalByID[row.rec.id]?.chunkContext( start: row.start, count: row.count) != nil @@ -2528,6 +2622,11 @@ public final class EngineLoopV2: @unchecked Sendable { evalTargets.append(output) } packedIDs.formUnion(group.rows.map(\.rec.id)) + for (index, row) in group.rows.enumerated() { + row.rec.stampPrefillChunkLaunch( + tokens: row.count, packed: true, vision: spanContexts[index] != nil, + stripe: false, launchNanos: wallStartedNanos) + } // Evidence, recorded where the rectangular forward actually // happened — never at the capability gate. packedPrefillRowsExecuted += group.rows.count @@ -2544,9 +2643,16 @@ public final class EngineLoopV2: @unchecked Sendable { let requirement: CBv2PrefillRequirement = row.samples ? .lastPositionLogits : .evaluationOnly let output: MLXArray - if let multimodal = multimodalByID[rec.id], - !multimodal.spansInChunk(start: row.start, count: row.count).isEmpty - { + // ONE `multimodalByID` lookup per prefill row, reused below; the + // span test iterates spans without allocating and runs only for + // rows that carry multimodal input. + let multimodal = multimodalByID[rec.id] + let visionChunk = multimodal?.hasSpans(start: row.start, count: row.count) ?? false + rec.stampPrefillChunkLaunch( + tokens: row.count, packed: false, vision: visionChunk, + stripe: !visionChunk && row.count > scheduler.config.prefillChunkSize, + launchNanos: wallStartedNanos) + if visionChunk, let multimodal { // Vision chunk (contains image spans): the NEW pinned path — // spliced input embeddings + span attention masks. Chunks of // the SAME request without spans fall through to the @@ -2796,13 +2902,25 @@ public final class EngineLoopV2: @unchecked Sendable { var host: [Int32] = [] if let tokens = step.sampledTokens { host = tokens.asArray(Int32.self) + CBv2CoreInstrumentation.recordHostSync() } else if !step.evalTargets.isEmpty { eval(step.evalTargets) + CBv2CoreInstrumentation.recordHostSync() } if CBv2StepProfiler.enabled { CBv2StepProfiler.record( "v2.readback.wait", seconds: CFAbsoluteTimeGetCurrent() - readbackStart) } + // THE one unconditional timing read of finalize: the readback-done + // instant. Every per-row stamp below, the cumulative step wall, and + // finishes driven by this finalize reuse it (no per-row reads). + let readbackDoneNanos = DispatchTime.now().uptimeNanoseconds + step.readbackDoneNanos = readbackDoneNanos + stepWallNanosTotal = Self.saturatingAdd( + stepWallNanosTotal, readbackDoneNanos &- step.wallStartedNanos) + finalizeClockNanos = readbackDoneNanos + defer { finalizeClockNanos = 0 } + let tokenProducingRows = step.tokenProducingRows if !step.sampledRows.isEmpty { sampler.confirmSampledTokens( host.map(Int.init), requestIDs: step.sampledRows) @@ -2857,7 +2975,17 @@ public final class EngineLoopV2: @unchecked Sendable { guard let rec = scheduler.record(for: id) else { continue } finalizedPlainWork = true let token = Int(host[i]) + let firstToken = rec.generatedTokenCount == 0 scheduler.recordSampled(id: id, token: token) + // Timing stamps on the record already in hand (field writes on + // an existing object; the instant is the readback read above). + rec.recordStepParticipation(step: step, batchRows: tokenProducingRows) + if firstToken { + rec.stampFirstToken(readbackDoneNanos: readbackDoneNanos) + } else { + rec.timing.decodeSteps &+= 1 + decodeRowsTotal = Self.saturatingAdd(decodeRowsTotal, 1) + } if let constraintFailure = sampler.tokenConstraintFailure(for: id) { finishRequest(id, reason: .error(constraintFailure)) continue @@ -2887,7 +3015,10 @@ public final class EngineLoopV2: @unchecked Sendable { var matchedStopString = false if rec.request.stopStrings.isEmpty { let stream = stream(for: id) - stream?.reserveEmission() + // First token only: arm the detok-delay probe under the + // reservation's own lock acquisition (measured in `emit`). + stream?.reserveEmission( + firstEmissionArmedNanos: firstToken ? readbackDoneNanos : 0) detokQueue.async { let text = isStopToken ? "" : (detokenizer?.push([token]) ?? "") stream?.emit( @@ -3016,7 +3147,17 @@ public final class EngineLoopV2: @unchecked Sendable { // MARK: Request completion - func finishRequest(_ id: CBv2RequestID, reason: CBv2FinishReason) { + /// `nowNanos`: the caller's already-taken timing instant (a step + /// boundary finishing several rows shares ONE read). Absent, the + /// in-progress finalize / launch read is reused; a fresh read is the + /// last resort (direct callers outside any step). `now`: the step's + /// boundary `ContinuousClock` read (`stepNow`), used only to close a + /// paused row's backpressure interval — absent, one read per paused + /// finish. + func finishRequest( + _ id: CBv2RequestID, reason: CBv2FinishReason, nowNanos: UInt64? = nil, + now: ContinuousClock.Instant? = nil + ) { // Ids are legally reusable after finish: drop the per-id capacity // requeue count on EVERY finish path (including the error-finish // that exhausted it), or a reused id inherits the previous @@ -3061,23 +3202,47 @@ public final class EngineLoopV2: @unchecked Sendable { let stream = stream(for: id) let detokenizer = detokenizers.removeValue(forKey: id) prefixUsageByID[id]?.boundarySplits = rec.prefixReplayBoundarySplits - let usage = takePrefixUsage( + var usage = takePrefixUsage( requestID: id, promptTokens: rec.request.promptTokens.count, completionTokens: rec.generatedTokenCount) + // Fold the per-request timing in ONCE. The instant is, in order: + // the caller's boundary read (cancel / lease expiry share one per + // step), the in-progress finalize's readback-done read, the + // in-progress launch's wall-start read (allocation failure), and + // only for direct callers outside any step a fresh read. + // Cost model: the `usage.timing` setter boxes the struct — ONE + // `CBv2RequestTimingBox` allocation per request lifetime, at the + // single assignment on whichever delivery path runs (synchronous + // below, or async at delivery once the detok delay is folded in); + // never on the step path. The raw value travels unboxed until then. + if rec.pausedSince != nil { rec.recordResumed(now: now ?? config.clock.now()) } + let exportedTiming = rec.exportTiming( + finishedNanos: nowNanos + ?? (finalizeClockNanos != 0 + ? finalizeClockNanos + : launchClockNanos != 0 + ? launchClockNanos : DispatchTime.now().uptimeNanoseconds)) let usesAsyncDetokenization = rec.request.stopStrings.isEmpty + if !usesAsyncDetokenization { usage.timing = exportedTiming } // the ONE box let terminalQueue = detokQueue - let terminalDelivery: () -> Void = { + let terminalDelivery: () -> Void = { [usage, exportedTiming] in // Passthrough requests emit deltas on the detok queue; the // trailing flush + terminal MUST ride the same queue so they land // AFTER those deltas (FIFO ordering). Stop-string requests stay - // synchronous. + // synchronous. The first-token detok delay is read from the + // stream (its own lock) at delivery time — after the deferred + // first emit by FIFO — never from the scheduler record. if usesAsyncDetokenization { terminalQueue.async { let trailing = detokenizer?.flush() ?? "" if !trailing.isEmpty { stream?.emit(.delta(text: trailing, tokens: [], logprobs: nil)) } - stream?.finish(reason: reason, usage: usage) + var timing = exportedTiming + timing.detokDelayFirstNanos = stream?.firstEmissionDelayNanos ?? 0 + var delivered = usage + delivered.timing = timing // the ONE box + stream?.finish(reason: reason, usage: delivered) } } else { let trailing = detokenizer?.flush() ?? "" @@ -3319,7 +3484,7 @@ public final class EngineLoopV2: @unchecked Sendable { // MARK: Boundary housekeeping - private func processCancellations() { + private func processCancellations(now: ContinuousClock.Instant) { stateLock.lock() let cancels = pendingCancels stateLock.unlock() @@ -3339,7 +3504,8 @@ public final class EngineLoopV2: @unchecked Sendable { continue } if scheduler.record(for: id) != nil { - finishRequest(id, reason: .cancelled) + finishRequest( + id, reason: .cancelled, nowNanos: boundaryFinishNanos(), now: now) resolved[id] = cancelledGeneration } } @@ -3421,6 +3587,15 @@ public final class EngineLoopV2: @unchecked Sendable { } else if waitingBefore.contains(id) { lease.markReadmitted(now: now) leasesByID[id] = lease + // Timing: a waiting→running crossing AFTER the first launch + // stamp is a re-admission (preemption / capacity requeue). + // The first admission itself is stamped at launch from + // `wallStartedNanos`. Cost model: this `record(for:)` runs + // only on a waiting→running crossing (an event), never per + // row per steady-state step. + if let rec = scheduler.record(for: id), rec.timing.admittedNanos != 0 { + rec.timing.readmissions &+= 1 + } } } } @@ -3447,7 +3622,9 @@ public final class EngineLoopV2: @unchecked Sendable { } } for (id, cause) in expired { - finishRequest(id, reason: leaseFinishReason(for: cause)) + finishRequest( + id, reason: leaseFinishReason(for: cause), nowNanos: boundaryFinishNanos(), + now: now) } } @@ -3467,14 +3644,15 @@ public final class EngineLoopV2: @unchecked Sendable { } } - private func handlePreemptions(_ ids: [CBv2RequestID]) { + private func handlePreemptions(_ ids: [CBv2RequestID], now: ContinuousClock.Instant) { // Preemption only happens on the non-chained path, where the // previous step was finalized first — no in-flight step can // reference these states, so the release is immediate. The // scheduler already released the capacity reservations and requeued // the victims (generated tokens kept). assert(inFlight == nil, "preemption with a step in flight") - let now = config.clock.now() + // `now` is the step's boundary read (`stepNow`): no second clock + // read for the preemption instant. for id in ids { preemptionCount += 1 // A preempted request recomputes from scratch — any adopted @@ -3537,6 +3715,11 @@ public final class EngineLoopV2: @unchecked Sendable { } kvStates[rec.id] = state capacityRequeues.removeValue(forKey: rec.id) + // Inside a launch the step's `wallStartedNanos` is reused; the + // fallback read covers direct (test) callers only. + rec.stampKVAllocated( + nowNanos: launchClockNanos != 0 + ? launchClockNanos : DispatchTime.now().uptimeNanoseconds) return state } catch let kvError as CBv2KVError { if case .capacityExhausted = kvError { @@ -3544,6 +3727,7 @@ public final class EngineLoopV2: @unchecked Sendable { if attempts < Self.maxCapacityRequeues, scheduler.requeueOnCapacity(rec.id) { capacityRequeues[rec.id] = attempts + 1 capacityRequeueCount += 1 + rec.timing.capacityRequeues &+= 1 mtp?.invalidateCarry(rec.id) // preempted-style restart // Preempted-style lease reset too: requeueOnCapacity // rewound numComputedTokens to zero, so rewind the @@ -3693,7 +3877,9 @@ public final class EngineLoopV2: @unchecked Sendable { kvBytesBackendCapacity: backend.bytesCapacity, kvBytesReserved: reservedBytes, activeTokens: scheduler.activeTokens, - stepsExecuted: stepCount)) + stepsExecuted: stepCount, + stepWallNanosTotal: stepWallNanosTotal, + decodeRowsTotal: decodeRowsTotal)) } private static func saturatingAdd(_ lhs: Int, _ rhs: Int) -> Int { @@ -3701,6 +3887,13 @@ public final class EngineLoopV2: @unchecked Sendable { return overflow ? Int.max : value } + /// Cumulative counters (`stepWallNanosTotal`, `decodeRowsTotal`) must + /// never decrease: pin at `.max` instead of wrapping. + static func saturatingAdd(_ lhs: UInt64, _ rhs: UInt64) -> UInt64 { + let (value, overflow) = lhs.addingReportingOverflow(rhs) + return overflow ? UInt64.max : value + } + static func positionOffset(_ state: [CBv2SequenceKV?]) -> Int { guard let row = state.compactMap({ $0 }).first else { preconditionFailure("CBv2 position state has no owning attention row") diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift index 210e41502d..053d23dd79 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/EngineV2.swift @@ -680,6 +680,17 @@ public final class EngineV2: CBv2Engine, @unchecked Sendable { /// The lookup pin travels with the adoption; the loop balances it in /// every outcome. private func makePrefixLookup(for request: CBv2Request) -> CBv2PrefixLookup { + // Submit-thread duration of hashing + lookup + plan derivation + // (`CBv2RequestTiming.prefixLookupNanos`); rides the lookup into + // `enqueue` so no engine-queue clock read is needed. + guard prefixCache != nil else { return resolvePrefixLookup(for: request) } + let started = DispatchTime.now().uptimeNanoseconds + var lookup = resolvePrefixLookup(for: request) + lookup.lookupNanos = max(1, DispatchTime.now().uptimeNanoseconds &- started) + return lookup + } + + private func resolvePrefixLookup(for request: CBv2Request) -> CBv2PrefixLookup { guard let prefixCache else { return CBv2PrefixLookup(adoption: nil, outcome: .disabled, matchedTokens: 0) } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/LogitsPipelineV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/LogitsPipelineV2.swift index b8f07deab3..db382a9526 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/LogitsPipelineV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/LogitsPipelineV2.swift @@ -512,10 +512,15 @@ public enum CBv2Logprobs { public static func assemble( _ gathered: Gathered, sampledTokens: [Int], topLogprobsPerRow: [Int] ) -> [CBv2TokenLogprob?] { + // Three host readbacks per logprob segment, each counted (gated + // like every CBv2 sync point; the arrays are already evaluated). let chosen = gathered.chosen.asArray(Float.self) + CBv2CoreInstrumentation.recordHostSync() let k = gathered.topValues.dim(-1) let values = gathered.topValues.asArray(Float.self) + CBv2CoreInstrumentation.recordHostSync() let indices = gathered.topIndices.asArray(Int32.self) + CBv2CoreInstrumentation.recordHostSync() var out = [CBv2TokenLogprob?]() out.reserveCapacity(sampledTokens.count) for row in 0 ..< sampledTokens.count { diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift index 15527fd6b5..321ff88cd6 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTP.swift @@ -15,6 +15,8 @@ extension EngineLoopV2 { func executeMTPRound(_ plan: CBv2StepPlan) -> CBv2InFlightStep? { guard let mtp else { return executeMixed(plan) } let wallStartedNanos = DispatchTime.now().uptimeNanoseconds + launchClockNanos = wallStartedNanos + defer { launchClockNanos = 0 } // A per-row reserve retry can demote a round after the step-global // preflight. Demote all round rows so the target still sees one L=1 @@ -29,15 +31,27 @@ extension EngineLoopV2 { let buildStart = CBv2StepProfiler.enabled ? CFAbsoluteTimeGetCurrent() : 0 let work = mtpPrepareRoundWork( - plan, driver: mtp, demoteAllRounds: demoteAllRounds) + plan, driver: mtp, demoteAllRounds: demoteAllRounds, + launchNanos: wallStartedNanos) guard !work.isEmpty else { // Undo optimistic scheduler advances before pending samples can // block waiting admission. scheduler.rollback(plan) return nil } + // Timing stamps mirror `executeMixed`: admission was stamped in + // `mtpPrepareRoundWork` (before `ensureKVState`); solo prefill + // chunks are stamped inside `mtpBuildRoundGraph`, where each row's + // multimodal input is already bound (MTP rounds never pack). Only + // the decode-shaped one-token prompt chunk is stamped here: one + // compare per decode row, no lookup, no allocation. + for row in work where row.isDecode && row.start < row.rec.request.promptTokens.count { + row.rec.stampPrefillChunkLaunch( + tokens: 1, packed: false, vision: false, stripe: false, + launchNanos: wallStartedNanos) + } - let graph = mtpBuildRoundGraph(work, driver: mtp) + let graph = mtpBuildRoundGraph(work, driver: mtp, launchNanos: wallStartedNanos) scheduler.markPendingSamples(ids: graph.sampledRows) if let verify = graph.verify { scheduler.markPendingSamples( diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift index 5d4765bb9a..c329168e8a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPExecution.swift @@ -60,13 +60,19 @@ extension EngineLoopV2 { func mtpPrepareRoundWork( _ plan: CBv2StepPlan, driver mtp: CBv2MTPRoundDriver, - demoteAllRounds: Bool + demoteAllRounds: Bool, + launchNanos: UInt64 ) -> [CBv2MTPRowWork] { var work: [CBv2MTPRowWork] = [] work.reserveCapacity(plan.assignments.count) for (id, assignedTokens) in plan.assignments { guard let rec = scheduler.record(for: id) else { continue } + // Admission stamp BEFORE `ensureKVState`, mirroring + // `executeMixed`: a capacity-requeued row is then already + // stamped, so its next waiting→running crossing counts as a + // re-admission on both launch paths (same `readmissions`). + rec.stampAdmission(launchNanos: launchNanos) guard ensureKVState(rec) != nil else { continue } var count = assignedTokens var preserveHistorySeed = false @@ -117,7 +123,7 @@ extension EngineLoopV2 { } func mtpBuildRoundGraph( - _ work: [CBv2MTPRowWork], driver mtp: CBv2MTPRoundDriver + _ work: [CBv2MTPRowWork], driver mtp: CBv2MTPRoundDriver, launchNanos: UInt64 ) -> CBv2MTPGraphBuild { var cacheInnerState: [MLXArray] = [] var logprobSegments: [CBv2StepLogprobs] = [] @@ -241,9 +247,17 @@ extension EngineLoopV2 { row.samples ? .lastPositionLogits : .evaluationOnly let output: MLXArray var observedHidden: MLXArray? - if let multimodal = multimodalByID[rec.id], - !multimodal.spansInChunk(start: row.start, count: row.count).isEmpty - { + // ONE `multimodalByID` lookup per prefill row; the span test + // iterates spans without allocating and runs only for rows that + // carry multimodal input. The row's prefill-chunk timing stamp + // rides the same binding (mirrors `executeMixed`). + let multimodal = multimodalByID[rec.id] + let visionChunk = multimodal?.hasSpans(start: row.start, count: row.count) ?? false + rec.stampPrefillChunkLaunch( + tokens: row.count, packed: false, vision: visionChunk, + stripe: !visionChunk && row.count > scheduler.config.prefillChunkSize, + launchNanos: launchNanos) + if visionChunk, let multimodal { let forward = multimodalChunkForward( tokens: inputs, start: row.start, count: row.count, id: rec.id, multimodal: multimodal, caches: caches, @@ -546,7 +560,11 @@ extension EngineLoopV2 { // false everywhere else, so contiguous stays byte-identical. guard backend.requiresMaterializedSnapshots else { return } let unfenceable = CBv2MTPCaptureFence.publish(captured) - if !unfenceable.isEmpty { eval(unfenceable) } + if !unfenceable.isEmpty { + // The fence contract's blunt fallback: one host sync, counted. + eval(unfenceable) + CBv2CoreInstrumentation.recordHostSync() + } } } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift index 45f43753fa..d45541b5fe 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPFinalize.swift @@ -39,6 +39,7 @@ extension EngineLoopV2 { if let seedHidden = round.seedHidden { let seedPolicyTopTwo = round.seedPolicyTopTwoValues?.asArray(Float.self) + if seedPolicyTopTwo != nil { CBv2CoreInstrumentation.recordHostSync() } for (id, decodeIndex) in round.seedRows { guard !step.discard.contains(id), let rec = scheduler.record(for: id) @@ -59,8 +60,18 @@ extension EngineLoopV2 { guard let verify = round.verify else { return } let k = verify.k + // Host readbacks of the MTP round, each counted: an MTP-round + // finalize adds up to three syncs to the step's one (seed policy + // margin above, acceptance packet, verify policy margin). Serial + // target verification adds one blocking eval per column at launch + // (`EngineLoopV2+MTPTargetVerification`); a logprob segment adds + // three readbacks (`CBv2Logprobs.assemble`); a round whose capture + // could not be fenced adds one blocking eval (`CBv2MTPCaptureFence` + // fallback in `EngineLoopV2+MTPExecution`). let host = verify.acceptancePacket.asArray(Int32.self) + CBv2CoreInstrumentation.recordHostSync() let policyTopTwoHost = verify.policyTopTwoValues?.asArray(Float.self) + if policyTopTwoHost != nil { CBv2CoreInstrumentation.recordHostSync() } let draftCount = verify.rows.count * k let targetWidth = 1 + k var anyRejected = false @@ -257,6 +268,14 @@ extension EngineLoopV2 { } let observedAccepted = min(accepted, confirmed) + // Per-request timing: this verify row confirmed at the step's + // readback-done instant (already read by `finalize`). + rec.recordStepParticipation(step: step, batchRows: step.tokenProducingRows) + rec.recordMTPRound(drafted: k, accepted: observedAccepted) + if confirmed > 0 { + rec.timing.decodeSteps &+= 1 + decodeRowsTotal = Self.saturatingAdd(decodeRowsTotal, 1) + } mtp.recordRound( drafted: k, accepted: observedAccepted, emitted: confirmed) let rejectionObserved = accepted < k && confirmed > accepted diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift index e24eb0f109..c21dd5af9a 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MTP/EngineLoopV2+MTPTargetVerification.swift @@ -175,6 +175,8 @@ extension EngineLoopV2 { eval( [columnScores, output.lastHidden] + eagerCacheInnerState(caches) + recurrentArrays) + // One blocking evaluation per serial verify column, counted. + CBv2CoreInstrumentation.recordHostSync() scoreColumnsAccum.append(columnScores) hiddenColumns.append(output.lastHidden) } diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift index 7c587c8070..68c5a681c5 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/MultimodalV2.swift @@ -315,6 +315,17 @@ struct CBv2ResolvedMultimodal: @unchecked Sendable { } } + /// True when any span intersects `[start, start + count)` — the same + /// test `spansInChunk` applies, without building the array or slicing + /// embeddings. For per-row-per-step classification on the engine thread. + func hasSpans(start: Int, count: Int) -> Bool { + let end = start + count + // Exactly `spansInChunk`'s non-empty test (`lo < hi`), so degenerate + // ranges agree: an empty chunk never intersects and a zero-length + // span never counts. + return spans.contains { max(start, $0.tokenOffset) < min(end, $0.end) } + } + /// True when `position` lies inside a coalesced image block. Used by the /// engine's decode-row classification: a length-1 span landing on the /// FINAL prompt token produces an assignment shaped exactly like a decode diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/OutputStreamV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/OutputStreamV2.swift index 2f3b601e10..eb83d99f50 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/OutputStreamV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/OutputStreamV2.swift @@ -43,6 +43,14 @@ public final class CBv2OutputStream: @unchecked Sendable { /// queue could generate far past `capacity` before the buffer ever /// fills enough to fire the pause (PR#62 review). private var pendingEmissions = 0 + /// First-token detokenization delay probe (`CBv2RequestTiming + /// .detokDelayFirstNanos`). Armed ONCE by the engine thread inside + /// `reserveEmission` with the readback-done instant of the step that + /// confirmed the first token; the matching deferred `emit` on the + /// detokenization queue reads the clock under this same lock and stores + /// the delay. Never touches scheduler state from the detok queue. + private var firstEmissionArmedNanos: UInt64 = 0 + private var _firstEmissionDelayNanos: UInt64 = 0 private let capacity: Int private var lowWatermark: Int { max(0, capacity / 2) } @@ -74,10 +82,17 @@ public final class CBv2OutputStream: @unchecked Sendable { /// emit is deferred — a slow detokenizer or consumer pauses the request /// exactly as the synchronous path does (PR#62 review). Every /// reservation must be balanced by exactly one consuming emit. - public func reserveEmission() { + /// + /// `firstEmissionArmedNanos` (non-zero only for the FIRST token of a + /// passthrough request) arms the detok-delay probe under the same lock + /// acquisition — no extra lock traffic on the step path. + public func reserveEmission(firstEmissionArmedNanos: UInt64 = 0) { var firePause = false lock.lock() pendingEmissions += 1 + if firstEmissionArmedNanos != 0, _firstEmissionDelayNanos == 0 { + self.firstEmissionArmedNanos = firstEmissionArmedNanos + } if !pausedForBackpressure, !finished, buffer.count + pendingEmissions >= capacity { pausedForBackpressure = true firePause = true @@ -96,6 +111,12 @@ public final class CBv2OutputStream: @unchecked Sendable { var fireResume = false lock.lock() if consumingReservation { pendingEmissions = max(0, pendingEmissions - 1) } + if firstEmissionArmedNanos != 0 { + // First token only: one clock read on the detokenization queue. + _firstEmissionDelayNanos = max( + 1, DispatchTime.now().uptimeNanoseconds &- firstEmissionArmedNanos) + firstEmissionArmedNanos = 0 + } if finished { lock.unlock() return @@ -132,6 +153,14 @@ public final class CBv2OutputStream: @unchecked Sendable { emit(.finished(reason: reason, usage: usage)) } + /// Engine confirm → deferred emit delay of the first token (0 until the + /// deferred emit ran, or for streams that never armed the probe). + var firstEmissionDelayNanos: UInt64 { + lock.lock() + defer { lock.unlock() } + return _firstEmissionDelayNanos + } + /// True once a terminal event has been enqueued. public var isFinished: Bool { lock.lock() diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift index 27d32d11df..cecd916949 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/SchedulerV2.swift @@ -53,6 +53,16 @@ public final class CBv2ScheduledRequest { /// Monotonic admission sequence — FCFS tie-break within a priority class. public let arrivalSeq: UInt64 public let submittedAt: Date + /// Engine enqueue instant (`DispatchTime.now().uptimeNanoseconds`, ONE + /// read in `SchedulerV2.enqueue`). Every `CBv2RequestTiming` offset is + /// measured from here using the step's existing clock reads. + public internal(set) var enqueuedNanos: UInt64 + /// Per-request timing stamps and step-participation counters. Engine + /// thread only; exported once on the terminal usage (see + /// `CBv2RequestTiming+Stamps.swift`). + internal var timing = CBv2RequestTiming() + /// Backpressure pause start (monotonic), nil while running. + internal var pausedSince: ContinuousClock.Instant? /// Prompt + confirmed generated tokens. public internal(set) var tokens: [Int] @@ -90,10 +100,14 @@ public final class CBv2ScheduledRequest { /// bidirectional attention needs all of its keys in one forward. public let multimodalBlocks: [CBv2ImageSpan] - init(request: CBv2Request, arrivalSeq: UInt64, submittedAt: Date) { + init( + request: CBv2Request, arrivalSeq: UInt64, submittedAt: Date, + enqueuedNanos: UInt64 = 0 + ) { self.request = request self.arrivalSeq = arrivalSeq self.submittedAt = submittedAt + self.enqueuedNanos = enqueuedNanos self.tokens = request.promptTokens self.multimodalBlocks = request.multimodal?.attention == .bidirectionalSpans ? CBv2MultimodalPlan.coalescedBlocks(spans: request.multimodal?.spans ?? []) @@ -265,8 +279,10 @@ public final class SchedulerV2 { guard waiting.count < config.maxWaiting else { throw CBv2KVError.capacityExhausted(needed: 1, available: 0) } + // ONE monotonic read per enqueue: the origin of every timing offset. let record = CBv2ScheduledRequest( - request: request, arrivalSeq: nextArrivalSeq, submittedAt: now) + request: request, arrivalSeq: nextArrivalSeq, submittedAt: now, + enqueuedNanos: DispatchTime.now().uptimeNanoseconds) nextArrivalSeq += 1 byID[request.id] = record insertWaiting(record, preemptedRequeue: false) diff --git a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift index 9569710168..5e92a9dd7e 100644 --- a/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift +++ b/Libraries/MLXLMCommon/ContinuousBatchingV2/SequenceKV/FullSequenceKV.swift @@ -39,7 +39,15 @@ public enum CBv2CoreInstrumentation { return _positionOffsetsHostRebuilds } + /// Gate for `recordHostSync`: the engine's finalize readbacks count + /// only while a test has switched counting on. Off (the default) the + /// step path pays one static bool read per readback and never touches + /// the lock — the same pattern as the engine's signposter gate. Tests + /// flip it on before stepping and reset it afterwards. + nonisolated(unsafe) static var countingEnabled = false + static func recordHostSync() { + guard countingEnabled else { return } lock.lock() defer { lock.unlock() } _hostSyncs += 1 diff --git a/Tests/MLXLMTests/CBv2CoreTests.swift b/Tests/MLXLMTests/CBv2CoreTests.swift index 0e58316682..da41aa0bdc 100644 --- a/Tests/MLXLMTests/CBv2CoreTests.swift +++ b/Tests/MLXLMTests/CBv2CoreTests.swift @@ -886,9 +886,12 @@ struct CBv2CoreLayerCacheTests { #expect(cache.offset == 10) } - /// A 10-step decode performs ZERO host syncs and ZERO host rebuilds of - /// positionOffsets from CBv2 core code (report 10 §4 invariant 7 + the - /// engine-thread discipline: graph-build only in the step loop). + /// A 10-step decode performs ZERO host rebuilds of positionOffsets from + /// CBv2 core code (report 10 §4 invariant 7 + the engine-thread + /// discipline: graph-build only in the step loop). The process-global + /// host-sync counter is NOT asserted here — concurrent swift-testing + /// engine suites make it racy; the serial XCTest timing suite asserts + /// it exactly, one sync per executed engine step. @Test func decodeLoopPerformsNoHostSyncsOrRebuilds() { MLXRandom.seed(5) let cache = CBv2LayerCache(layerIndex: 0, kind: kind) @@ -905,7 +908,6 @@ struct CBv2CoreLayerCacheTests { ) } - let syncsBefore = CBv2CoreInstrumentation.hostSyncs let rebuildsBefore = cache.positionOffsetsHostRebuilds var outputs: [MLXArray] = [] @@ -918,7 +920,6 @@ struct CBv2CoreLayerCacheTests { asyncEval(outputs.last!, cache.innerState()) } - #expect(CBv2CoreInstrumentation.hostSyncs - syncsBefore == 0) #expect(cache.positionOffsetsHostRebuilds - rebuildsBefore == 0) // Materialize at the end (outside the step loop) and sanity-check. diff --git a/Tests/MLXLMTests/CBv2MTPRoundSmokeTests.swift b/Tests/MLXLMTests/CBv2MTPRoundSmokeTests.swift index 18f61e9490..3b804ca1d4 100644 --- a/Tests/MLXLMTests/CBv2MTPRoundSmokeTests.swift +++ b/Tests/MLXLMTests/CBv2MTPRoundSmokeTests.swift @@ -213,6 +213,55 @@ struct CBv2MTPRoundSmokeTests { #expect(1 + metrics.seedSteps + metrics.emittedTokens <= 40) } + // MARK: - (1b) Per-request timing sees the rounds + + @Test func perRequestTimingCountsRounds() async throws { + let fixture = try makeFixture() + let prompt = makePromptTokens(length: 24, seed: 12, vocabSize: vocabSize) + let on = try makeEngine(fixture, mtp: true, verificationMode: .automatic) + CBv2CoreInstrumentation.countingEnabled = true + defer { CBv2CoreInstrumentation.countingEnabled = false } + let syncsBefore = CBv2CoreInstrumentation.hostSyncs + let speculative = try await run(on, greedyRequest(id: 1, prompt: prompt, maxTokens: 40)) + let metrics = try #require(on.mtpMetricsSnapshot()) + await on.shutdown() // the drain completes only with no step in flight + let syncs = CBv2CoreInstrumentation.hostSyncs - syncsBefore + let stepsExecuted = on.capacity().stepsExecuted + + // Host-sync multiplier on the MTP path: every executed step performs + // its ONE finalize readback; an MTP-round finalize adds up to three + // more (seed policy margin, acceptance packet, verify policy margin); + // serial target verification adds one blocking eval per verify + // column at launch; a round whose capture could not be fenced adds + // one blocking eval (never on the contiguous/paged backends that + // exist today); a logprob segment adds three readbacks (none here — + // no row asks for logprobs). So + // steps ≤ syncs ≤ steps + seedSteps + 2 × rounds + serialColumns + // + captureFallbackRounds. + // Only the lower bound is asserted here: the counter is + // process-global and swift-testing runs other engine suites + // concurrently (the exact per-step equality is asserted by the + // serial XCTest timing suite). + #expect(syncs >= stepsExecuted, "one finalize readback per executed step") + + #expect(speculative.finishReason == .length) + let t = try #require(speculative.usage).timing + #expect(t.mtpRounds > 0, "the round loop must be visible per request") + #expect(t.mtpAccepted <= t.mtpProposed) + // Alone in the engine, the per-request tallies ARE the engine's + // cumulative round metrics (both recorded in the same verify walk). + #expect(t.mtpRounds == UInt32(metrics.rounds)) + #expect(t.mtpProposed == UInt32(metrics.draftedTokens)) + #expect(t.mtpAccepted == UInt32(metrics.acceptedTokens)) + // The exported phase order holds on the MTP launch path too. + #expect(t.admittedNanos > 0) + #expect(t.admittedNanos <= t.kvAllocatedNanos) + #expect(t.kvAllocatedNanos <= t.prefillFirstLaunchNanos) + #expect(t.prefillFirstLaunchNanos <= t.promptComputedNanos) + #expect(t.promptComputedNanos <= t.firstTokenNanos) + #expect(t.firstTokenNanos <= t.finishedNanos) + } + // MARK: - (2) Mixed batch: verify rows + a prefilling neighbor @Test func mixedBatchWithPrefillNeighborStaysTokenExact() async throws { diff --git a/Tests/MLXLMTests/CBv2MultimodalTests.swift b/Tests/MLXLMTests/CBv2MultimodalTests.swift index e66ab4c49f..b8ad9483ae 100644 --- a/Tests/MLXLMTests/CBv2MultimodalTests.swift +++ b/Tests/MLXLMTests/CBv2MultimodalTests.swift @@ -1042,6 +1042,43 @@ final class CBv2MultimodalTests: XCTestCase { request: request, arrivalSeq: 0, submittedAt: Date()) } + // MARK: - hasSpans ≡ !spansInChunk.isEmpty on degenerate ranges + + func testHasSpansMatchesSpansInChunkOnDegenerateRanges() { + // Direct construction: resolution rejects a zero-length span, but + // the engine-thread predicate must agree with `spansInChunk` for + // every range shape it can be handed. + func resolved(_ spans: [CBv2ImageSpan]) -> CBv2ResolvedMultimodal { + CBv2ResolvedMultimodal( + spans: spans, attention: .causal, blocks: spans, + embeddings: spans.map { MLXArray.zeros([1, $0.length, 4]) }, + deepstackEmbeddings: []) + } + let positive = resolved([CBv2ImageSpan(tokenOffset: 4, length: 6)]) // [4, 10) + let zeroLength = resolved([CBv2ImageSpan(tokenOffset: 6, length: 0)]) + let cases: [(multimodal: CBv2ResolvedMultimodal, start: Int, count: Int, label: String)] = [ + (positive, 6, 0, "empty chunk inside a positive span"), + (positive, 4, 0, "empty chunk at the span start"), + (zeroLength, 0, 16, "zero-length span inside a chunk"), + (zeroLength, 6, 0, "empty chunk at a zero-length span"), + (positive, 0, 4, "chunk ending exactly at the span start"), + (positive, 10, 6, "chunk starting exactly at the span end"), + (positive, 0, 5, "chunk overlapping the span head"), + (positive, 9, 8, "chunk overlapping the span tail"), + (positive, 0, 16, "chunk containing the span"), + (positive, 5, 2, "chunk inside the span"), + ] + for (multimodal, start, count, label) in cases { + XCTAssertEqual( + multimodal.hasSpans(start: start, count: count), + !multimodal.spansInChunk(start: start, count: count).isEmpty, + label) + } + XCTAssertFalse(positive.hasSpans(start: 6, count: 0), "empty chunk never intersects") + XCTAssertFalse(zeroLength.hasSpans(start: 0, count: 16), "zero-length span never counts") + XCTAssertTrue(positive.hasSpans(start: 5, count: 2), "genuine overlap") + } + // MARK: - (e) Submit-time rejections private func makeCacheProvider(_ model: TinyTestModel) -> CBv2LayerCacheBank { diff --git a/Tests/MLXLMTests/CBv2RequestTimingTests.swift b/Tests/MLXLMTests/CBv2RequestTimingTests.swift new file mode 100644 index 0000000000..9d4e5eba25 --- /dev/null +++ b/Tests/MLXLMTests/CBv2RequestTimingTests.swift @@ -0,0 +1,451 @@ +// Copyright © 2026 Eigen Labs. +// +// ContinuousBatchingV2 — per-request timing (`CBv2RequestTiming`) and the +// cumulative step counters on `CBv2CapacitySnapshot`. +// +// Runs on the scripted no-weights harness (`CBv2SchedHarness`): the model +// emits next-token = (input + 1) % vocab, so every completion count is exact +// and the timing invariants below are deterministic in STRUCTURE (ordering, +// counts) while the nanosecond values are merely required to be observed. + +import Foundation +import MLX +import XCTest + +@testable import MLXLMCommon + +final class CBv2RequestTimingTests: XCTestCase { + + // Host-sync counting is gated off on the step path; this suite (serial + // XCTest) switches it on per test and asserts one sync per step. + override func setUp() { + super.setUp() + CBv2CoreInstrumentation.countingEnabled = true + } + + override func tearDown() { + CBv2CoreInstrumentation.countingEnabled = false + super.tearDown() + } + + private func timing(_ collected: CBv2SchedCollected, _ label: String) throws + -> CBv2RequestTiming + { + let usage = try XCTUnwrap(collected.usage, "\(label): terminal usage missing") + return usage.timing + } + + /// The phase stamps every finished request must satisfy, in order — + /// the chain the coordinator validates on the exported profile: + /// admitted ≤ kvAllocated ≤ prefillFirstLaunch ≤ promptComputed ≤ + /// firstToken ≤ finished. + private func assertPhaseOrdering(_ t: CBv2RequestTiming, _ label: String) { + XCTAssertGreaterThan(t.admittedNanos, 0, "\(label): admitted") + // KV is allocated at first launch (`ensureKVState`) or, for a prefix + // hit, at enqueue-time adoption — which `stampAdmission` raises to + // the admission instant, so the stamp never precedes admission and + // always precedes the prompt being confirmed computed. + XCTAssertGreaterThan(t.kvAllocatedNanos, 0, "\(label): kv allocated") + XCTAssertLessThanOrEqual( + t.admittedNanos, t.kvAllocatedNanos, "\(label): admitted ≤ kv") + XCTAssertLessThanOrEqual( + t.kvAllocatedNanos, t.prefillFirstLaunchNanos, "\(label): kv ≤ prefill launch") + XCTAssertLessThanOrEqual( + t.kvAllocatedNanos, t.promptComputedNanos, "\(label): kv ≤ promptComputed") + XCTAssertGreaterThanOrEqual( + t.prefillFirstLaunchNanos, t.admittedNanos, "\(label): prefill ≥ admitted") + XCTAssertGreaterThanOrEqual( + t.promptComputedNanos, t.prefillFirstLaunchNanos, + "\(label): promptComputed ≥ prefill launch") + XCTAssertGreaterThanOrEqual( + t.firstTokenNanos, t.promptComputedNanos, "\(label): firstToken ≥ promptComputed") + XCTAssertGreaterThanOrEqual( + t.finishedNanos, t.firstTokenNanos, "\(label): finished ≥ firstToken") + } + + // MARK: B = 1 + + func testSingleDecodeRunPopulatesTiming() async throws { + let harness = CBv2SchedHarness() + let request = CBv2SchedFixtures.request(prompt: [3], maxTokens: 8) + let collected = await cbv2SchedCollect(try harness.engine.submit(request)) + XCTAssertEqual(collected.finishReason, .length) + XCTAssertEqual(collected.usage?.completionTokens, 8) + let t = try timing(collected, "B=1") + + assertPhaseOrdering(t, "B=1") + // The final (only) prefill chunk samples the first token, so the + // prompt is computed exactly when the first token is confirmed. + XCTAssertEqual(t.promptComputedNanos, t.firstTokenNanos) + + XCTAssertEqual(t.prefillChunks, 1) + XCTAssertEqual(t.packedPrefillChunks, 0) + XCTAssertEqual(t.visionChunks, 0) + XCTAssertEqual(t.soloStripeChunks, 0) + XCTAssertEqual(t.prefillChunkTokensMax, 1) + + // Every token beyond the first came from a decode step; the wasted + // chained step after `.length` is discarded, never counted. + XCTAssertEqual(t.decodeSteps, 7, "decodeSteps == completion − 1") + XCTAssertGreaterThanOrEqual(t.chainedDecodeSteps, 1, "steady decode chains") + XCTAssertLessThanOrEqual(t.chainedDecodeSteps, t.decodeSteps) + + // Alone in the engine: batch size 1 in all 8 participated steps. + XCTAssertEqual(t.batchRowsMin, 1) + XCTAssertEqual(t.batchRowsMax, 1) + XCTAssertEqual(t.batchRowsSum, 8) + XCTAssertGreaterThan(t.stepLatencyNanosSum, 0) + XCTAssertGreaterThan(t.stepLatencyNanosMax, 0) + XCTAssertLessThanOrEqual(t.stepLatencyNanosMax, t.stepLatencyNanosSum) + + XCTAssertEqual(t.readmissions, 0) + XCTAssertEqual(t.preemptions, 0) + XCTAssertEqual(t.capacityRequeues, 0) + XCTAssertEqual(t.mtpRounds, 0) + XCTAssertEqual(t.mtpProposed, 0) + XCTAssertEqual(t.mtpAccepted, 0) + XCTAssertEqual(t.pauseCount, 0) + XCTAssertEqual(t.pausedNanos, 0) + // Passthrough request: the first token's detok hop was measured. + XCTAssertGreaterThan(t.detokDelayFirstNanos, 0) + // No prefix cache configured: nothing to time. + XCTAssertEqual(t.prefixLookupNanos, 0) + XCTAssertEqual(t.prefixAdoptionNanos, 0) + + // Cumulative counters after a quiescent single run. + let released = await cbv2SchedWait { harness.backend.liveStates == 0 } + XCTAssertTrue(released) + let snapshot = harness.engine.capacity() + XCTAssertGreaterThan(snapshot.stepsExecuted, 0) + XCTAssertGreaterThan(snapshot.stepWallNanosTotal, 0) + XCTAssertEqual(snapshot.decodeRowsTotal, UInt64(t.decodeSteps)) + XCTAssertGreaterThanOrEqual(snapshot.stepWallNanosTotal, t.stepLatencyNanosSum) + } + + // MARK: B = 4 + + func testBatchedDecodeRunPopulatesTimingWithoutHostSyncs() async throws { + let harness = CBv2SchedHarness() + let requests = [ + CBv2SchedFixtures.request(prompt: [3], maxTokens: 10), + CBv2SchedFixtures.request(prompt: [20, 21], maxTokens: 12), + CBv2SchedFixtures.request(prompt: [40, 41, 42], maxTokens: 9), + CBv2SchedFixtures.request(prompt: [50], maxTokens: 11), + ] + let syncsBefore = CBv2CoreInstrumentation.hostSyncs + let streams = try requests.map { try harness.engine.submit($0) } + var collected: [CBv2SchedCollected] = [] + await withTaskGroup(of: (Int, CBv2SchedCollected).self) { group in + for (index, stream) in streams.enumerated() { + group.addTask { (index, await cbv2SchedCollect(stream)) } + } + var byIndex: [Int: CBv2SchedCollected] = [:] + for await (index, out) in group { byIndex[index] = out } + collected = (0 ..< streams.count).map { byIndex[$0]! } + } + // Host-sync accounting is asserted below, once every step is fenced. + + var totalDecodeSteps: UInt64 = 0 + var widestBatch: UInt32 = 0 + var maxLatencySum: UInt64 = 0 + for (request, out) in zip(requests, collected) { + let label = "request \(request.id)" + XCTAssertEqual(out.finishReason, .length, label) + XCTAssertEqual(out.usage?.completionTokens, request.maxTokens, label) + let t = try timing(out, label) + assertPhaseOrdering(t, label) + XCTAssertEqual(t.prefillChunks, 1, label) + XCTAssertEqual(t.prefillChunkTokensMax, UInt32(request.promptTokens.count), label) + XCTAssertEqual(t.decodeSteps, UInt32(request.maxTokens - 1), label) + XCTAssertGreaterThanOrEqual(t.batchRowsMin, 1, label) + XCTAssertGreaterThanOrEqual(t.batchRowsMax, t.batchRowsMin, label) + XCTAssertLessThanOrEqual(t.batchRowsMax, 4, label) + // Σ batch rows over decodeSteps + 1 participated steps is bounded + // by min × steps ≤ Σ ≤ max × steps. + let steps = UInt64(t.decodeSteps + 1) + XCTAssertGreaterThanOrEqual(t.batchRowsSum, UInt64(t.batchRowsMin) * steps, label) + XCTAssertLessThanOrEqual(t.batchRowsSum, UInt64(t.batchRowsMax) * steps, label) + XCTAssertGreaterThan(t.stepLatencyNanosSum, 0, label) + XCTAssertGreaterThan(t.detokDelayFirstNanos, 0, label) + XCTAssertEqual(t.readmissions, 0, label) + XCTAssertEqual(t.preemptions, 0, label) + totalDecodeSteps += UInt64(t.decodeSteps) + widestBatch = max(widestBatch, t.batchRowsMax) + maxLatencySum = max(maxLatencySum, t.stepLatencyNanosSum) + } + XCTAssertGreaterThanOrEqual(widestBatch, 2, "four concurrent rows must batch") + + let released = await cbv2SchedWait { harness.backend.liveStates == 0 } + XCTAssertTrue(released) + let snapshot = harness.engine.capacity() + // Timing is always on and adds no host sync: the step loop's ONLY + // CBv2 sync is the finalize readback — exactly one per executed step + // (every launched step is finalized once; all fenced by now). No + // row asks for logprobs (three readbacks per segment) and MTP is + // off, so the per-step formula is exactly 1. Any sync introduced + // later breaks this equality. + XCTAssertEqual( + CBv2CoreInstrumentation.hostSyncs - syncsBefore, snapshot.stepsExecuted, + "one host sync per executed step") + XCTAssertEqual( + snapshot.decodeRowsTotal, totalDecodeSteps, + "decodeRowsTotal == Σ per-request decodeSteps") + XCTAssertGreaterThanOrEqual(snapshot.stepWallNanosTotal, maxLatencySum) + XCTAssertGreaterThan(snapshot.stepsExecuted, 0) + } + + // MARK: Prefill shapes + + func testMultiChunkPrefillCountsEveryChunk() async throws { + let harness = CBv2SchedHarness( + schedulerConfig: CBv2SchedulerConfig( + maxConcurrentRequests: 4, maxBatchedTokensPerStep: 64, prefillChunkSize: 16, + maxWaiting: 8)) + let request = CBv2SchedFixtures.request(prompt: Array(0 ..< 40), maxTokens: 3) + let collected = await cbv2SchedCollect(try harness.engine.submit(request)) + XCTAssertEqual(collected.tokens, [40, 41, 42]) + let t = try timing(collected, "chunked") + + assertPhaseOrdering(t, "chunked") + XCTAssertEqual(t.prefillChunks, 3, "16 + 16 + 8") + XCTAssertEqual(t.prefillChunkTokensMax, 16) + XCTAssertEqual(t.packedPrefillChunks, 0) + XCTAssertEqual(t.soloStripeChunks, 0, "no stripe armed: nothing wider than a chunk") + XCTAssertEqual(t.decodeSteps, 2) + XCTAssertEqual(t.promptComputedNanos, t.firstTokenNanos) + // Two non-sampling chunks precede the sampling one: the first + // launch strictly precedes the prompt-computed confirmation. + XCTAssertLessThan(t.prefillFirstLaunchNanos, t.promptComputedNanos) + } + + func testSoloPrefillStripeIsCounted() async throws { + let harness = CBv2SchedHarness( + schedulerConfig: CBv2SchedulerConfig( + maxConcurrentRequests: 4, maxBatchedTokensPerStep: 64, prefillChunkSize: 16, + soloPrefillStripeTokens: 32, maxWaiting: 8)) + let request = CBv2SchedFixtures.request(prompt: Array(0 ..< 40), maxTokens: 2) + let collected = await cbv2SchedCollect(try harness.engine.submit(request)) + XCTAssertEqual(collected.tokens, [40, 41]) + let t = try timing(collected, "stripe") + XCTAssertGreaterThanOrEqual(t.soloStripeChunks, 1, "a solo row takes the stripe") + XCTAssertEqual(t.prefillChunkTokensMax, 32) + XCTAssertEqual(t.prefillChunks, 2, "32 + 8") + } + + // MARK: Detokenization paths + + func testStopStringRequestLeavesDetokDelayUnobserved() async throws { + let harness = CBv2SchedHarness(stopTrigger: 20) + let request = CBv2SchedFixtures.request( + prompt: [17], maxTokens: 100, stopStrings: [""]) + let collected = await cbv2SchedCollect(try harness.engine.submit(request)) + XCTAssertEqual(collected.tokens, [18, 19, 20]) + XCTAssertEqual(collected.finishReason, .stop) + let t = try timing(collected, "stop-string") + assertPhaseOrdering(t, "stop-string") + XCTAssertEqual(t.decodeSteps, 2) + // Synchronous detokenization on the engine thread: no deferred hop + // to measure, so the passthrough-only probe stays unobserved. + XCTAssertEqual(t.detokDelayFirstNanos, 0) + } + + // MARK: Terminal before first token + + func testCancelDuringPrefillLeavesFirstTokenUnobserved() async throws { + // Ten [1, 16] prefill chunks, one per step, each held ~50 ms inside + // the scripted forward: the cancel lands after the first chunk + // launched and long before the sampling chunk could finalize. + let harness = CBv2SchedHarness( + schedulerConfig: CBv2SchedulerConfig( + maxConcurrentRequests: 4, maxBatchedTokensPerStep: 64, prefillChunkSize: 16, + maxWaiting: 8)) + harness.model.forwardDelay = 0.05 + let request = CBv2SchedFixtures.request(prompt: Array(0 ..< 160), maxTokens: 4) + let stream = try harness.engine.submit(request) + let collector = Task { await cbv2SchedCollect(stream) } + let launched = await cbv2SchedWait { harness.engine.stepCount >= 1 } + XCTAssertTrue(launched, "first prefill chunk must launch") + harness.engine.cancel(request.id) + let collected = await collector.value + + XCTAssertEqual(collected.finishReason, .cancelled) + XCTAssertTrue(collected.tokens.isEmpty, "cancelled mid-prefill: no tokens") + let t = try timing(collected, "cancel-in-prefill") + + // Never observed: the prompt was not computed through and no token + // was confirmed or detokenized. + XCTAssertEqual(t.promptComputedNanos, 0) + XCTAssertEqual(t.firstTokenNanos, 0) + XCTAssertEqual(t.decodeSteps, 0) + XCTAssertEqual(t.detokDelayFirstNanos, 0) + + // Observed and ordered: admitted ≤ kvAllocated ≤ prefillFirstLaunch + // ≤ finished (the coordinator validates every PRESENT pair). + XCTAssertGreaterThan(t.admittedNanos, 0) + XCTAssertGreaterThan(t.kvAllocatedNanos, 0) + XCTAssertGreaterThan(t.prefillFirstLaunchNanos, 0) + XCTAssertGreaterThan(t.finishedNanos, 0) + XCTAssertLessThanOrEqual(t.admittedNanos, t.kvAllocatedNanos) + XCTAssertLessThanOrEqual(t.kvAllocatedNanos, t.prefillFirstLaunchNanos) + XCTAssertLessThanOrEqual(t.prefillFirstLaunchNanos, t.finishedNanos) + + XCTAssertGreaterThanOrEqual(t.prefillChunks, 1, "at least the launched chunk") + XCTAssertLessThan(t.prefillChunks, 10, "cancelled before the prompt was through") + XCTAssertEqual(t.prefillChunkTokensMax, 16) + + let released = await cbv2SchedWait { harness.backend.liveStates == 0 } + XCTAssertTrue(released, "cancelled request's KV must be freed") + } + + // MARK: Re-admission, preemption, backpressure + + func testPreemptedRequestCountsPreemptionAndReadmission() async throws { + // Same fixture as the loop suite's preemption test: a 12-token soft + // ledger cannot hold two 10-token rows, so the younger is preempted + // mid-decode, re-prefills (kept tokens), and finishes seamlessly. + let harness = CBv2SchedHarness(backendCapacity: 200) + let older = CBv2SchedFixtures.request(prompt: [1, 2, 3, 4], maxTokens: 6) + let younger = CBv2SchedFixtures.request(prompt: [40, 41, 42, 43], maxTokens: 6) + let olderStream = try harness.engine.submit(older) + let youngerStream = try harness.engine.submit(younger) + let olderTask = Task { await cbv2SchedCollect(olderStream) } + let youngerTask = Task { await cbv2SchedCollect(youngerStream) } + let olderCollected = await olderTask.value + let youngerCollected = await youngerTask.value + XCTAssertEqual(olderCollected.tokens, [5, 6, 7, 8, 9, 10]) + XCTAssertEqual(youngerCollected.tokens, [44, 45, 46, 47, 48, 49]) + XCTAssertGreaterThan(harness.engine.preemptionCount, 0) + + let olderTiming = try timing(olderCollected, "older") + let youngerTiming = try timing(youngerCollected, "younger") + assertPhaseOrdering(olderTiming, "older") + assertPhaseOrdering(youngerTiming, "younger") + XCTAssertEqual(olderTiming.decodeSteps, 5, "every non-first token is a decode step") + XCTAssertEqual(youngerTiming.decodeSteps, 5, "every non-first token is a decode step") + + var victims = 0 + for t in [olderTiming, youngerTiming] where t.preemptions > 0 { + victims += 1 + XCTAssertGreaterThanOrEqual(t.readmissions, t.preemptions, "each preemption re-admits") + XCTAssertGreaterThanOrEqual(t.prefillChunks, 2, "re-prefill launches a new chunk") + } + XCTAssertGreaterThan(victims, 0, "capacity forces at least one preemption") + } + + func testBackpressurePauseIsAccounted() async throws { + let harness = CBv2SchedHarness( + loopConfig: CBv2EngineLoopConfig(eventBufferCapacity: 4)) + let slow = CBv2SchedFixtures.request(prompt: [1], maxTokens: 30) + let fast = CBv2SchedFixtures.request(prompt: [20], maxTokens: 30) + let slowStream = try harness.engine.submit(slow) + let fastStream = try harness.engine.submit(fast) + + let fastOut = await cbv2SchedCollect(fastStream) + XCTAssertEqual(fastOut.finishReason, .length) + let paused = await cbv2SchedWait { + harness.engine.loopForTesting.pausedIDsSnapshot() == [slow.id] + } + XCTAssertTrue(paused, "slow stream must be paused while unread") + // Hold the pause long enough to be measurable, then drain. + try await Task.sleep(nanoseconds: 20_000_000) + let slowOut = await cbv2SchedCollect(slowStream) + XCTAssertEqual(slowOut.finishReason, .length) + + let t = try timing(slowOut, "slow") + XCTAssertGreaterThanOrEqual(t.pauseCount, 1) + XCTAssertGreaterThanOrEqual(t.pausedNanos, 10_000_000, "≥ 10 ms of the 20 ms hold") + XCTAssertEqual(try timing(fastOut, "fast").pauseCount, 0) + // Let the last chained step finalize before the next test measures + // the process-global host-sync counter. + let released = await cbv2SchedWait { harness.backend.liveStates == 0 } + XCTAssertTrue(released) + } + + // MARK: Prefix cache + + func testPrefixHitRecordsLookupAndAdoptionDurations() async throws { + let prefixCache = CBv2SchedScriptedPrefixCache(matched: 2) + let harness = CBv2SchedHarness( + schedulerConfig: CBv2SchedulerConfig(enablePrefixCache: true), + prefixCache: prefixCache) + let request = CBv2SchedFixtures.request(prompt: [1, 2, 3, 4], maxTokens: 3) + let collected = await cbv2SchedCollect(try harness.engine.submit(request)) + XCTAssertEqual(collected.tokens, [5, 6, 7]) + XCTAssertEqual(collected.usage?.prefixCacheOutcome, .hit) + let t = try timing(collected, "prefix hit") + assertPhaseOrdering(t, "prefix hit") + XCTAssertGreaterThan(t.prefixLookupNanos, 0, "submit-thread lookup timed") + XCTAssertGreaterThan(t.prefixAdoptionNanos, 0, "applyAdoption timed") + // Adoption allocates KV at enqueue, before the first plan; the + // exported stamp is raised to the admission instant so the + // coordinator's `admitted ≤ kvAllocated` order holds. The adoption + // itself is evidenced by `prefixAdoptionNanos > 0` above. + XCTAssertEqual( + t.kvAllocatedNanos, t.admittedNanos, "adopted KV stamp raised to admission") + XCTAssertEqual(t.prefillChunks, 1, "only the un-adopted tail is prefilled") + } + + // MARK: Cumulative counters + + func testCumulativeStepCountersAreMonotonic() async throws { + let harness = CBv2SchedHarness() + let request = CBv2SchedFixtures.request(prompt: [7], maxTokens: 40) + let stream = try harness.engine.submit(request) + let collector = Task { await cbv2SchedCollect(stream) } + + var samples: [CBv2CapacitySnapshot] = [] + let deadline = Date().addingTimeInterval(5) + while Date() < deadline { + samples.append(harness.engine.capacity()) + if let last = samples.last, last.activeRequests == 0, samples.count > 10 { break } + try await Task.sleep(nanoseconds: 500_000) + } + let collected = await collector.value + XCTAssertEqual(collected.finishReason, .length) + samples.append(harness.engine.capacity()) + + XCTAssertGreaterThan(samples.count, 2, "sampled the run while it was live") + for (previous, next) in zip(samples, samples.dropFirst()) { + XCTAssertGreaterThanOrEqual(next.stepsExecuted, previous.stepsExecuted) + XCTAssertGreaterThanOrEqual(next.stepWallNanosTotal, previous.stepWallNanosTotal) + XCTAssertGreaterThanOrEqual(next.decodeRowsTotal, previous.decodeRowsTotal) + } + let t = try timing(collected, "monotonic") + let final = try XCTUnwrap(samples.last) + XCTAssertEqual(final.decodeRowsTotal, UInt64(t.decodeSteps)) + XCTAssertGreaterThan(final.stepWallNanosTotal, 0) + } + + // MARK: Contract shape + + func testTimingIsEquatableAndNumericOnly() { + var a = CBv2RequestTiming() + XCTAssertEqual(a, CBv2RequestTiming(), "defaults are all zero") + a.admittedNanos = 5 + a.decodeSteps = 3 + a.batchRowsSum = 12 + let b = a + XCTAssertEqual(a, b, "value round trip") + a.mtpAccepted += 1 + XCTAssertNotEqual(a, b) + + // Confidentiality guard: the struct carries unsigned integers only — + // no token ids, text, hashes, or pointers can ever ride it. + let children = Mirror(reflecting: CBv2RequestTiming()).children + XCTAssertEqual(children.count, 29, "field count pinned to the contract") + for child in children { + XCTAssertTrue( + child.value is UInt64 || child.value is UInt32, + "\(child.label ?? "?") must be UInt64/UInt32, got \(type(of: child.value))") + } + + // Defaulted additions keep the existing usage/snapshot shapes intact. + let usage = CBv2Usage(promptTokens: 1, completionTokens: 2) + XCTAssertEqual(usage.timing, CBv2RequestTiming()) + let snapshot = CBv2CapacitySnapshot( + activeRequests: 0, waitingRequests: 0, kvBytesInUse: 0, kvBytesCapacity: 0, + activeTokens: 0) + XCTAssertEqual(snapshot.stepWallNanosTotal, 0) + XCTAssertEqual(snapshot.decodeRowsTotal, 0) + } +}