Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/VQuantKit/Lab/VQQuantJobs.swift3// Description: Quant Lab jobs: start, follow with progress, cancel (CONTRACT §4.1).4import Foundation56public struct VQQuantJob: Sendable, Equatable, Identifiable, VQJSONDecodable {7 public enum Status: String, Sendable, Hashable, CaseIterable {8 case running, done, error9 /// The server restarted while the job ran.10 case interrupted11 /// Stopped by the person (lab engines only). A cancelled job keeps no result.12 case cancelled13 }14 public var id: String15 /// Tool (engine) id.16 public var tool: String17 /// The validated input the server recorded (defaults written out).18 public var params: VQJSONObject19 public var status: VQOpen<Status>20 public var startedAt: Date?21 public var finishedAt: Date?22 public var error: String?23 /// 0–1; nil for legacy tools and until the engine reports.24 public var progress: Double?25 public var engineVersion: String?26 /// nil while running.27 public var durationMs: Double?28 public var projectId: String?29 /// The conversation whose agent ran it (`run_quant_engine`).30 public var sessionId: String?31 public var cancellable: Bool32 /// Python source of a legacy job (detail route only).33 public var code: String?34 /// The raw result (detail route only): `lab/1` for lab engines, the tool's own shape for legacy tools.35 public var result: VQJSON?3637 public init(json j: VQJSON) {38 id = j.str("id"); tool = j.str("tool"); params = j.dict("params"); status = j.open("status", .running)39 startedAt = j.date("startedAt"); finishedAt = j.date("finishedAt"); error = j.optStr("error"); progress = j.num("progress")40 engineVersion = j.optStr("engineVersion"); durationMs = j.num("durationMs"); projectId = j.optStr("projectId"); sessionId = j.optStr("sessionId")41 cancellable = j.flag("cancellable"); code = j.optStr("code"); result = j["result"].flatMap { $0.isNull ? nil : $0 }42 }4344 public var isRunning: Bool { status == .running }45 /// Finished, whatever the outcome (an unknown status counts as finished: nothing more will come).46 public var isFinished: Bool { !isRunning }47 /// The result in the generic schema; nil for a legacy tool, a running job, or a job without result.48 public var labResult: VQLabResult? { VQLabResult.ifLab(result) }49 /// The sentence to show when the job did not produce a result.50 public var failureMessage: String? {51 if let error, status != .done { return error }52 if let r = result, r["success"] == .bool(false) { return r.optStr("error") }53 return nil54 }55}5657public struct VQQuantJobList: Sendable, Equatable, VQJSONDecodable {58 public var jobs: [VQQuantJob]59 public var running: Int60 public init(json j: VQJSON) { jobs = j.models("jobs"); running = j.int("running") ?? 0 }61}6263public struct VQLabClient: Sendable {64 public let client: VQClient65 public let clock: any VQClock66 public init(client: VQClient, clock: any VQClock = VQSystemClock()) { self.client = client; self.clock = clock }6768 public func catalog() async throws -> VQLabCatalog { try await client.decode(.get("/api/quant/tools")) }6970 /// Starts a computation (202). `params` should come from `VQLabForm.validate()`; the server validates again (40071 /// with a sentence) and refuses above three running jobs per person (429).72 public func start(tool: String, params: VQJSONObject, projectId: String? = nil) async throws -> VQQuantJob {73 var body: VQJSONObject = ["tool": .string(tool), "params": .object(params)]74 if let projectId { body["projectId"] = .string(projectId) }75 let j = try await client.json(VQRequest(.post, "/api/quant/jobs", body: .object(body)))76 return VQQuantJob(json: j["job"] ?? j)77 }7879 /// The job with its result.80 public func job(_ id: String) async throws -> VQQuantJob {81 let j = try await client.json(.get("/api/quant/jobs/\(VQRequest.segment(id))", timeout: 60))82 return VQQuantJob(json: j["job"] ?? j)83 }8485 /// Summaries (no result), newest first.86 public func jobs() async throws -> VQQuantJobList { try await client.decode(.get("/api/quant/jobs")) }8788 public enum CancelOutcome: Sendable, Equatable {89 case cancelled(VQQuantJob)90 /// A legacy tool: it cannot be stopped.91 case notCancellable92 /// It had already finished with this status.93 case notRunning(status: String)94 }9596 /// Stops a running lab job. `VQError.notFound` when the job does not exist.97 public func cancel(_ id: String) async throws -> CancelOutcome {98 do {99 let j = try await client.json(VQRequest(.post, "/api/quant/jobs/\(VQRequest.segment(id))/cancel"))100 return .cancelled(VQQuantJob(json: j["job"] ?? j))101 } catch let e as VQError where e.kind == .conflict {102 if e.message == "not_cancellable" { return .notCancellable }103 return .notRunning(status: e.body?.optStr("status") ?? "")104 }105 }106107 public func delete(_ id: String) async throws {108 try await client.data(VQRequest(.delete, "/api/quant/jobs/\(VQRequest.segment(id))"))109 }110111 /// Follows a job until it finishes: yields each state that differs from the previous one (progress included) and112 /// ends after the first finished state. Transient failures are retried; cancelling the consuming task stops the113 /// polling (it does **not** cancel the job — call `cancel(_:)` for that).114 /// The sync stream's `quant_jobs` hints make polling unnecessary for lists; this is for the job being watched.115 public func follow(_ id: String, every interval: TimeInterval = 1.0, maxConsecutiveFailures: Int = 5) -> AsyncThrowingStream<VQQuantJob, Error> {116 let me = self117 return AsyncThrowingStream { continuation in118 let task = Task {119 var last: VQQuantJob?120 var failures = 0121 while !Task.isCancelled {122 do {123 let job = try await me.job(id)124 failures = 0125 if job != last { continuation.yield(job); last = job }126 if job.isFinished { continuation.finish(); return }127 } catch let e as VQError where e.isTransient {128 failures += 1129 if failures > maxConsecutiveFailures { continuation.finish(throwing: e); return }130 } catch {131 continuation.finish(throwing: error); return132 }133 do { try await me.clock.sleep(seconds: interval) } catch { break }134 }135 continuation.finish()136 }137 continuation.onTermination = { _ in task.cancel() }138 }139 }140141 /// Starts a job and returns its final state.142 public func run(tool: String, params: VQJSONObject, projectId: String? = nil, every interval: TimeInterval = 1.0, onProgress: (@Sendable (VQQuantJob) -> Void)? = nil) async throws -> VQQuantJob {143 var job = try await start(tool: tool, params: params, projectId: projectId)144 onProgress?(job)145 if job.isFinished { return try await self.job(job.id) }146 for try await state in follow(job.id, every: interval) { job = state; onProgress?(state) }147 return job148 }149}150