Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

fix: when Ling hears the meeting and is briefly too busy, it tries again for about 15 s instead of losing the line

wquguru70df016a25ab
diff --git a/Sources/Cicada/Ling.swift b/Sources/Cicada/Ling.swift
index bdaead6..c096ce2 100644
--- a/Sources/Cicada/Ling.swift
+++ b/Sources/Cicada/Ling.swift
@@ -483,9 +483,10 @@ final class LingClient: ObservableObject {
// MARK: Chat
/// One chat completion. `content` goes in the system message, `instruction` is the fixed user
- /// message. Notes retry 429s with backoff; translation and speak-back fail fast so the caller
- /// can fall back to another translator. `audio` (a WAV) goes in the user message before the
- /// instruction, for Ming's audio model (Ling only: `hearsAudio`).
+ /// message. Notes and heard audio retry 429s with backoff (`retryWaits`); the rest fail fast so
+ /// the caller can fall back to another translator. A 429 holds every request start for a while
+ /// (`rateLimited`), and a retry keeps its place in the queue, so lines stay in order. `audio` (a
+ /// WAV) goes in the user message before the instruction, for Ming's audio model (Ling only: `hearsAudio`).
func chat(content: String, instruction: String, priority: Priority, json: Bool = false,
maxTokens: Int = 1024, timeout: TimeInterval = 30, model: String? = nil, audio: Data? = nil,
role: String? = nil, patient: Bool = false, onQueued: ((Double) -> Void)? = nil) async throws -> String {
@@ -512,10 +513,13 @@ final class LingClient: ObservableObject {
]
c.shape(&body, maxTokens: maxTokens, templateKwargs: !noTemplateKwargs)
if json { body["response_format"] = ["type": "json_object"] }
- let waits = Self.retryWaits(priority, patient: patient)
+ let waits = Self.retryWaits(priority, audio: audio != nil, patient: patient)
+ var ticket: Int?
for attempt in 1...(waits.count + 1) {
+ // One that wouldn't retry fails at once while the service is cooling down: its caller falls back.
+ if waits.isEmpty && pausedUntil > Date() { throw Failure.rateLimited }
let asked = Date()
- await acquire(priority)
+ ticket = await acquire(priority, ticket: ticket)
let queued = Date().timeIntervalSince(asked)
onQueued?(queued)
let started = Date()
@@ -543,25 +547,56 @@ final class LingClient: ObservableObject {
report(call, priority, at: started, queued: queued, outcome: Self.name(failure))
observe(failure, audio: audio != nil, generation: generation)
guard failure == .rateLimited else { throw failure }
- guard attempt <= waits.count else {
+ let wait = rateLimited(waits.isEmpty ? 1 : waits[min(attempt, waits.count) - 1], retryAfter: lastRetryAfter)
+ guard attempt <= waits.count, let wait else {
rateLimitedAt = Date()
throw failure
}
- let wait = waits[attempt - 1] + Double.random(in: 0...0.5)
+ // No sleep here: the gate holds every start until the pause is over.
debugLog("ling: \(priority) 429, retry in \(String(format: "%.1f", wait)) s")
- try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))
}
}
throw Failure.rateLimited
}
- /// Seconds to wait before each retry of a 429. Notes retry a few times; translation and
- /// speak-back fail fast so the caller can fall back. `patient` (the final notes) keeps at it for
- /// about a minute: a model limited upstream (OpenRouter's Ling 3.1 by DeepInfra, 2026-11) came
- /// back after ~15 s, and a meeting left without its notes is worse than notes a little late.
- nonisolated static func retryWaits(_ priority: Priority, patient: Bool = false) -> [Double] {
- guard priority == .notes else { return [] }
- return patient ? [1, 2, 4, 8, 16, 30] : [1, 2, 4]
+ /// Seconds to wait before each retry of a 429. Notes retry a few times; text translation and
+ /// speak-back fail fast so the caller can fall back, except heard audio. A meeting's (先用○○听,
+ /// and every Intel Mac): there a lost reply loses the words, not just their translation, and
+ /// Ling's 429s came in runs of up to ~10 s (2026-11), so it keeps at it for about 15 s. What the
+ /// user says retries once: late into the room is worse than a short "try again". `patient` (the
+ /// final notes) keeps at it for about a minute: a model limited upstream (OpenRouter's Ling 3.1
+ /// by DeepInfra, 2026-11) came back after ~15 s, and a meeting left without its notes is worse
+ /// than notes a little late.
+ nonisolated static func retryWaits(_ priority: Priority, audio: Bool = false, patient: Bool = false) -> [Double] {
+ switch priority {
+ case .notes: return patient ? [1, 2, 4, 8, 16, 30] : [1, 2, 4]
+ case .translate: return audio ? [1, 2, 4, 8] : []
+ case .speak: return audio ? [1] : []
+ }
+ }
+
+ /// Longest Retry-After worth waiting for; longer is an outage, not a busy moment.
+ nonisolated static let maxPause: Double = 30
+
+ /// A Retry-After header in seconds: a number, or an HTTP date. nil when absent or unreadable.
+ nonisolated static func retryAfterSeconds(_ value: String?, now: Date = Date()) -> Double? {
+ guard let value = value?.trimmingCharacters(in: .whitespaces), !value.isEmpty else { return nil }
+ if let seconds = Double(value) { return max(0, seconds) }
+ let f = DateFormatter()
+ f.locale = Locale(identifier: "en_US_POSIX")
+ f.timeZone = TimeZone(identifier: "GMT")
+ f.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
+ return f.date(from: value).map { max(0, $0.timeIntervalSince(now)) }
+ }
+
+ /// After a 429: no request starts for `backoff` seconds, or as long as the service asked
+ /// (Retry-After; Ling sends none), plus a little jitter. The queue waits at the gate instead of
+ /// each request spending its retries on the same limit. nil when the service asks for longer
+ /// than `maxPause`: that is an outage (the gate still holds for `maxPause`).
+ private func rateLimited(_ backoff: Double, retryAfter: Double?) -> Double? {
+ let wait = max(backoff, retryAfter ?? 0) + Double.random(in: 0...0.5)
+ pausedUntil = max(pausedUntil, Date().addingTimeInterval(min(wait, Self.maxPause)))
+ return wait <= Self.maxPause ? wait : nil
}
/// Every request, for diagnostics (timings and token counts only).
@@ -728,6 +763,8 @@ final class LingClient: ObservableObject {
return (text.trimmingCharacters(in: .whitespacesAndNewlines), root["language"] as? String)
} catch let failure as Failure {
report(call, .translate, at: started, queued: queued, outcome: Self.name(failure))
+ // The server's limit is shared: the rest of the queue waits it out too.
+ if failure == .rateLimited { _ = rateLimited(1, retryAfter: lastRetryAfter) }
throw failure
} catch {
report(call, .translate, at: started, queued: queued, outcome: "parse")
@@ -828,7 +865,9 @@ final class LingClient: ObservableObject {
case 401, 403:
if keyState != .invalid { keyState = .invalid }
throw Failure.invalidKey
- case 429: throw Failure.rateLimited
+ case 429:
+ lastRetryAfter = Self.retryAfterSeconds((response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Retry-After"))
+ throw Failure.rateLimited
default:
debugLog("ling: HTTP \(code)")
throw Failure.http(code)
@@ -841,28 +880,40 @@ final class LingClient: ObservableObject {
private var waiting: [(priority: Priority, seq: Int, resume: CheckedContinuation<Void, Never>)] = []
private var seq = 0
private var pumping = false
-
- private func acquire(_ priority: Priority) async {
- if waiting.isEmpty && Date().timeIntervalSince(lastStart) >= provider.spacing {
+ /// After a 429 no request starts before this (`rateLimited`).
+ private var pausedUntil = Date.distantPast
+ /// The last 429's Retry-After in seconds, nil when it sent none (Ling doesn't). Read right
+ /// after the throw, with no suspension in between, so it is that request's.
+ private var lastRetryAfter: Double?
+
+ /// Waits for this request's turn to start. `ticket` is a retry's first one, which keeps its
+ /// place ahead of requests queued after it. Returns the ticket.
+ @discardableResult
+ private func acquire(_ priority: Priority, ticket: Int? = nil) async -> Int {
+ let n: Int
+ if let ticket { n = ticket } else { seq += 1; n = seq }
+ if waiting.isEmpty && Date().timeIntervalSince(lastStart) >= provider.spacing && pausedUntil <= Date() {
lastStart = Date()
- return
+ return n
}
- seq += 1
- let n = seq
await withCheckedContinuation { cont in
waiting.append((priority, n, cont))
pump()
}
+ return n
}
private func pump() {
guard !pumping, !waiting.isEmpty else { return }
pumping = true
- let wait = max(0, provider.spacing - Date().timeIntervalSince(lastStart))
+ let now = Date()
+ let wait = max(0, provider.spacing - now.timeIntervalSince(lastStart), pausedUntil.timeIntervalSince(now))
DispatchQueue.main.asyncAfter(deadline: .now() + wait) { [weak self] in
MainActor.assumeIsolated {
guard let self else { return }
self.pumping = false
+ // A 429 came in while this one waited: wait out the pause first.
+ if self.pausedUntil > Date() { self.pump(); return }
guard let i = self.waiting.indices.min(by: {
(self.waiting[$0].priority, self.waiting[$0].seq) < (self.waiting[$1].priority, self.waiting[$1].seq)
}) else { return }
diff --git a/Sources/Cicada/ListenEngine.swift b/Sources/Cicada/ListenEngine.swift
index 40b333c..08c38bf 100644
--- a/Sources/Cicada/ListenEngine.swift
+++ b/Sources/Cicada/ListenEngine.swift
@@ -1127,8 +1127,9 @@ final class ListenEngine {
let heard: CloudHeard?
do {
heard = try await translator.hear(wav: wav, seconds: seconds, target: self.resolvedTarget, hint: self.cloudHint)
- } catch LingClient.Failure.rateLimited {
- // Ling's ~2 requests a second are shared with notes and translation: one more try.
+ } catch LingClient.Failure.rateLimited where translator.ling.transcribes {
+ // A chat to the audio model retries 429s itself (LingClient.retryWaits); a
+ // custom speech server's transcription doesn't: one more try.
try await Task.sleep(for: .seconds(1))
heard = try await translator.hear(wav: wav, seconds: seconds, target: self.resolvedTarget, hint: self.cloudHint)
}
diff --git a/Tests/CicadaTests/LingTests.swift b/Tests/CicadaTests/LingTests.swift
index af2eb23..0967dba 100644
--- a/Tests/CicadaTests/LingTests.swift
+++ b/Tests/CicadaTests/LingTests.swift
@@ -103,6 +103,43 @@ final class LingStub: URLProtocol, @unchecked Sendable {
#expect((50...70).contains(patient.reduce(0, +)))
}
+ @Test func heardAudioRetriesAndTextFailsFast() {
+ #expect(LingClient.retryWaits(.translate, audio: true) == [1, 2, 4, 8])
+ #expect(LingClient.retryWaits(.speak, audio: true) == [1])
+ #expect(LingClient.retryWaits(.translate, audio: false).isEmpty)
+ }
+
+ @Test func retryAfterIsSecondsOrADate() {
+ #expect(LingClient.retryAfterSeconds("5") == 5)
+ #expect(LingClient.retryAfterSeconds(nil) == nil)
+ #expect(LingClient.retryAfterSeconds("soon") == nil)
+ let now = Date(timeIntervalSince1970: 1_700_000_000) // Tue, 14 Nov 2023 22:13:20 GMT
+ #expect(LingClient.retryAfterSeconds("Tue, 14 Nov 2023 22:13:30 GMT", now: now) == 10)
+ }
+
+ @Test func heardAudioOutlastsA429AndTextFallsBackMeanwhile() async throws {
+ LingStub.reset(200, "")
+ var first = true
+ LingStub.respond = { _ in
+ if first { first = false; return (429, "{}") }
+ return (200, LingStub.chatReply("ORIGINAL: hi\nTRANSLATION: 你好"))
+ }
+ let ling = client()
+ async let heard = ling.chat(content: "x", instruction: "Hear.", priority: .translate, audio: Data([0, 1]))
+ // The 429 pauses the gate: a text translation now fails at once (its caller uses Google)
+ // instead of spending the pause in the queue.
+ try await Task.sleep(for: .milliseconds(300))
+ await #expect(throws: LingClient.Failure.rateLimited) {
+ try await ling.chat(content: "y", instruction: "Translate.", priority: .translate)
+ }
+ let reply = try await heard
+ #expect(reply.hasPrefix("ORIGINAL"))
+ #expect(LingStub.seen.count == 2)
+ let gap = LingStub.seen[1].at.timeIntervalSince(LingStub.seen[0].at)
+ #expect(gap >= 1 && gap < 2)
+ #expect(ling.rateLimitedAt == nil)
+ }
+
// MARK: Key file
@Test func keyFileIsOnlyForThisUser() throws {