← 제작기

죽은 소켓과 생각하는 모델

중국어 말하기 시험 모의고사 앱이 있습니다. 시작을 누르면 모델에게 문항을 만들어 달라고 하고, 답변을 녹음해 다시 모델에게 채점을 맡깁니다. 8월 20일에 처음으로 실제 시험 한 회차를 끝까지 돌렸습니다.

그 뒤로 문항이 만들어지지 않았습니다. 화면에는 이렇게 떴습니다.

끝내지 못했습니다 — Software caused connection abort

첫 번째 진단

화면의 문장은 연결이 끊겼다고 말하고 있었고, 실제로 끊길 만한 이유가 코드에 두 가지나 있었습니다.

하나는 화면이 꺼진다는 것이었습니다. 앱은 시험 중에 화면이 꺼지지 않게 붙잡아 두는데, 그 대상이 질문 재생 · 준비 · 녹음 세 단계뿐이었습니다. 처음 그 목록을 쓸 때의 관심사는 "응시자가 30분 동안 화면을 만지지 않는다"였으니 자연스러운 선택이었습니다. 아무도 화면을 만지지 않으면서 네트워크 호출은 붙들고 있는 단계는 출제와 채점인데, 그 둘이 빠져 있었습니다.

다른 하나는 재시도가 없다는 것이었습니다. 클라이언트는 429 와 5xx 는 다시 시도하면서 IOException 은 아예 잡지 않았습니다. 끊긴 소켓은 첫 시도에서 그대로 위로 던져져 회차를 끝냈습니다. 이 앱에서 재시도가 가장 잘 통할 실패에 정작 재시도가 없었던 셈입니다.

둘 다 진짜 결함이어서 둘 다 고쳤습니다. 그때는 기기가 손에 없어서 빌드되는 것까지만 보고 넘어갔습니다.

두 번째 진단

기기에서 돌려 보니 여전히 실패했습니다.

여기서 코드를 더 파는 대신 재 보기로 했습니다. 먼저 화면입니다. 화면이 정말 꺼지지 않는지를 앱이 아니라 운영체제에게 물었습니다.

앱 윈도우 fl=0x81810180        → FLAG_KEEP_SCREEN_ON(0x80) 켜짐
dumpsys power                  → SCREEN_BRIGHT_WAKE_LOCK
                                  ws=WorkSource{com.tscrehearsal}

화면은 꺼지지 않고 있었으니 수정은 효과가 있었는데, 실패는 그대로였습니다. 그렇다면 무엇이 실패한 것일까요. 로그에 남은 DNS 요청 시각 세 개가 답을 알려 줬습니다.

23:52:38   23:55:48   23:59:13
           └ 190s ┘   └ 205s ┘

read timeout 180s + backoff 10s / 25s

계산이 정확히 맞았습니다. 세 번 모두 읽기 타임아웃이었고, 재시도는 설계대로 돌았습니다. 연결은 살아 있었고 답이 오지 않았을 뿐이었습니다. 마지막으로 기기와 네트워크를 의심에서 지웠습니다. 키 없이 같은 휴대폰에서 같은 호스트에 요청하면 0.2초 만에 403 이 옵니다(맥에서는 0.17초). 요청은 나가고 서버는 받는데, 그 뒤가 없었습니다.

화면 문구도 사람을 엉뚱한 곳으로 보내고 있었습니다. 첫 수정에서 넣은 문장은 "화면이 꺼지거나 네트워크가 바뀌면 연결이 끊길 수 있습니다"였습니다. 재 보니 화면도 네트워크도 멀쩡했는데, 그 문장은 멀쩡한 것을 고치러 가라고 말하고 있었습니다. 지금은 소켓 계층이 던진 예외로 구분합니다. SocketTimeoutException 이면 "요청은 나갔지만 답이 오지 않았습니다"를, 그 밖의 IOException 이면 예전의 연결 끊김 문구를 보여 줍니다.

원인이 무엇이었는지는 모른다

여기서 밝혀낸 것은 그 주소가 응답을 멈췄다는 사실 하나뿐입니다. 20일에는 통했고 그 뒤로는 통하지 않습니다. 왜인지는 이 저장소가 알 수 있는 범위 밖입니다.

출시 노트 초안에 저는 "구글이 쓰던 API 를 닫으면서"라고 적었습니다. 그럴듯하고 아마 맞을 것입니다. 그래도 타임아웃은 서비스 종료 공지가 아닙니다. 공개되는 글에 관측하지 않은 원인을 사실처럼 적는 셈이어서 그 문장을 지우고 "쓰던 주소가 응답하지 않아"로 바꿨습니다. 사용자에게 필요한 정보도 어차피 그쪽입니다.

주소보다 응답 방식을 바꿨다

대안은 같은 서비스의 스트리밍 엔드포인트였습니다. 응답을 한 번에 받는 대신 data: 로 시작하는 줄 조각으로 받아 도착한 순서대로 잇습니다.

이 이야기의 요점이 여기에 있습니다. 한 번에 받는 방식과 스트리밍의 차이는 속도보다, 실패했을 때 무엇이라도 알려 주느냐에 있습니다.

한 번에 받는 호출은 모델이 다 끝낼 때까지 연결을 잡고 있다가 결과를 한꺼번에 보내기 때문에, 3분 동안 생각하는 모델과 죽은 소켓이 타임아웃 입장에서는 똑같이 보입니다. 둘 다 "180초 동안 아무것도 오지 않았다"입니다. 스트리밍은 토큰이 나올 때마다 보내 주고, 그때마다 소켓의 대기 시간이 처음부터 다시 셉니다. 살아 있으면 살아 있다고 알려 줍니다.

제가 한 일은 고장 난 것을 고치는 일과 거리가 멀었습니다. 침묵밖에 내놓지 못하던 구조를, 살아 있다는 신호를 계속 보내는 구조로 바꾼 것입니다. 원인을 밝히지 못했는데도 진척이 있었던 이유가 이것입니다.

옮기고도 똑같았다

스트리밍으로 옮긴 첫 판은 증상이 그대로였습니다. 첫 바이트가 오기까지 200초가 넘게 걸렸습니다.

이유는 한 줄이었습니다. 이 모델은 답하기 전에 생각하는 단계가 있는데, 생각하는 동안에는 SSE 이벤트를 하나도 보내지 않습니다. 그 구간에서는 스트리밍도 한 번에 받는 방식과 똑같습니다. thinkingConfig.thinkingBudget = 0 을 넣고 나서야 옮긴 보람이 있었습니다. 대체 모델은 생각 단계가 아예 없어서 이 필드를 보내면 400 이 나므로, 모델에 따라 나눠서 보냅니다.

새 구조는 새로운 실패를 들여온다

며칠 뒤 사용자 화면에 이런 오류가 떴습니다.

응답을 해석하지 못했습니다:
model did not return JSON (len=16) — { "questions":"

받은 16자는 잘못된 JSON 이 아니라 제대로 만들어진 JSON 의 앞부분입니다. 스트림이 중간에 끊겼는데 HTTP 상태는 이미 200 이었기 때문에, 파서에게는 "모델이 이상한 것을 내놓았다"로만 보였습니다. 그 문장을 읽은 사람은 모델의 출력 형식을 의심하러 갑니다. 실제로는 전송이 끊긴 것이고, 요청에는 아무 문제가 없으며, 다시 하면 되는 일입니다.

한 번에 받을 때는 없던 실패입니다. 그때는 통째로 오거나 아예 오지 않았지, 반쯤 오는 일은 없었습니다. 진행 상황을 볼 수 있게 된 대가로 일부만 오는 실패를 떠안은 셈입니다.

서버는 응답이 끝났다는 것을 finishReason 으로 표시합니다. 본문이 끝날 때까지 그 표시가 없으면 끝난 것이 아니므로, 파서가 텍스트와 함께 "끝났는지"도 돌려주게 하고, 끝나지 않았으면 전송 실패로 처리해 다시 시도합니다. 순서에 함정이 하나 있었습니다. 끝났는지 확인하는 일은 "내용이 없으니 건너뛴다"보다 먼저 해야 합니다. 스트림을 끝내는 조각은 대개 끝난 이유만 있고 새 텍스트가 없어서, 순서가 반대면 끝났다는 유일한 표시를 놓칩니다.

주석이 코드가 하지 않는 일을 설명하고 있었다

같은 주에 503(백엔드 혼잡)도 다시 왔습니다. 설계는 이랬습니다. 503 은 오래 기다려도 소용없으니 짧게 다시 걸고, 재시도를 다 쓰면 더 가벼운 모델로 바꿔서 회차를 살린다. 주석에도 그렇게 적혀 있었습니다.

그 전환은 한 번도 실행된 적이 없었습니다.

repeat(RETRIES) { attempt ->
    ...
    if (attempt == RETRIES - 1) throw e     // 마지막 시도는 여기서 나간다
    if (e.status == 503) { ... }            // 그래서 여기 못 온다
}
// 루프 뒤: 모델을 바꾸고 처음부터 다시     // 여기는 더더욱

마지막 시도가 반복문 밖으로 예외를 던져 버려서, 503 을 따로 다루는 이유의 전부인 그 전환에 닿지 못했습니다. 주석은 코드가 하지 않는 일을 설명하고 있었고, 그래서 읽을 때마다 맞는 것처럼 보였습니다.

고치고 나니 두 번째 문제가 보였습니다. 모델 전환이 호출 단위가 아니라 클라이언트 단위였습니다. 채점은 8개를 동시에 돌리는데, 여럿이 함께 503 을 맞으면 하나만 모델을 바꾸고 나머지 일곱은 "이미 전환 중"으로 읽고 포기합니다. 8문항 가운데 1문항만 채점되는 셈이어서, "실패한 회차보다 채점된 회차가 낫다"는 취지가 정확히 뒤집힙니다.

고친 것이 만들어 낸 것들

한 번에 몰아서 하던 출제를 문항 자리마다 한 번씩으로 나눴습니다. 몰아서 하는 호출은 답하기 전에 출력 토큰을 전부 만들어야 해서, 백엔드가 바쁠 때 거절당하기 딱 좋은 모양입니다. 그 대신 요청 수가 늘었고(간단 시험 8건에서 13건, 전체 시험 27건에서 48건), 그 전제 위에 서 있던 시작 화면의 요청 수와 비용 추정도 함께 고쳐야 했습니다.

나누면서 함께 드러난 문제들이 있습니다.

  • 취소가 회차를 망칠 수 있었습니다. 출제 작업의 catch 가 CancellationException 까지 잡아서 "취소"가 "끝내지 못했습니다"로 보였습니다. 더 나쁜 것은 그 작업이 블로킹 읽기 안에서 최대 180초를 더 기다리다 깨어난다는 점입니다. 그사이 새 회차를 시작했다면, 끝났어야 할 작업이 살아 있는 회차를 실패로 만듭니다.
  • 모델이 돌려준 번호를 그대로 믿고 있었습니다. 문항 자리마다 한 번씩 부르게 된 뒤에도 응답 안의 index 를 썼는데, 프롬프트 예시가 "index":0 이어서 모델이 그것을 따라 쓰면 문항이 엉뚱한 자리로 들어가 버려집니다. 앞의 호출 비용을 모두 치른 뒤에 회차가 거절되는 셈입니다.
  • 진행 표시가 시험의 크기를 잘못 알려 줬습니다. 간단 시험은 7문항인데 출제 화면에 0 / 6 이라고 떴습니다. 전체 수를 호출할 자리 수로 세고 있었는데, 제1부는 고정 문항이라 호출이 없어서 6 이 된 것입니다. 사용자가 방금 누른 버튼은 7문항이라고 했는데 다음 화면이 6 이라고 하는 셈입니다. 제1부 문항도 엄연히 문항입니다. 이미 만들어져 있을 뿐이므로, 빼지 않고 세기의 출발점으로 두었습니다.

형제 저장소

이 앱은 iOS 판과 안드로이드 판이 따로 있습니다. 같은 날 둘 다 같은 문제를 겪었고, iOS 에서 먼저 옮긴 뒤 안드로이드가 따라 옮겼습니다.

흥미로운 것은 그다음부터 방향이 반대가 됐다는 점입니다. 잘린 스트림도, 닿지 못하는 503 전환도 실제로 겪은 것은 안드로이드를 쓰던 사용자였습니다. 확인해 보니 iOS 에도 같은 결함이 같은 자리에 있었습니다. 한쪽에서 찾은 것을 다른 쪽에서 찾아보는 일이 두 번 모두 성과를 냈습니다. 이식한 코드는 버그도 함께 옮겨 갑니다.

아직 확인하지 않은 것

정직하게 적어 둡니다. 새 엔드포인트로 오디오가 실려 나가는 것까지는 확인했습니다. 사용자가 실제 기기에서 채점까지 끝까지 돌렸지만, 그 회차에서 사용자는 말을 하지 않았습니다. 소리가 없으면 설계대로 발음 점수를 null 로 돌려주므로, 통한 것은 오디오 전송이지 발음 판정이 아닙니다. 채점기가 새 엔드포인트를 통해 실제로 소리를 듣는지는 여전히 확인하지 못했고, 503 전환과 설정 화면의 경고 배너는 코드만 있을 뿐 한 번도 실행된 적이 없습니다.


정리하면

  • 침묵은 아무것도 알려 주지 않습니다. 응답을 한 번에 받는 구조에서는 생각 중인 서버와 죽은 서버를 구별할 수 없습니다.
  • 진단이 되지 않을 때는 시스템이 신호를 내게 만듭니다. 원인을 짐작해 고치는 것보다 신호가 나오는 구조로 바꾸는 편이 빠를 때가 있습니다.
  • 수정이 효과가 있었는지와 증상이 사라졌는지는 다른 질문입니다. 화면 붙잡기는 성공했고 실패는 그대로였습니다. 둘을 따로 재지 않았다면 멀쩡한 수정을 의심했을 것입니다.
  • 틀린 진단은 코드보다 문구에 더 오래 남습니다. 원인을 지목하는 문장은 읽는 사람을 그쪽으로 보냅니다.
  • 관측하지 않은 원인은 공개되는 글에 적지 않습니다. 타임아웃은 서비스 종료 공지가 아닙니다.
  • 구조를 바꾸면 실패의 모양도 바뀝니다. 일부만 오는 응답은 스트리밍이 가져온 새로운 실패이고, 예전 파서에게는 형식 오류로 보입니다.
  • 주석은 코드가 하지 않는 일도 설명할 수 있습니다. 그 경로가 실제로 실행된 적이 있는지부터 묻습니다.
  • 이식한 코드는 버그도 함께 옮겨 갑니다. 한쪽에서 찾은 결함은 형제 저장소의 같은 자리에서도 찾아봅니다.

같은 앱에서 채점기가 소리를 듣는지 실측으로 확인한 이야기는 채점기가 소리를 듣는가에, 그럴듯한 진단을 두 번 하고 두 번 틀린 이야기는 고쳤는데 스택이 그대로였다에 있습니다. 재는 도구를 먼저 의심해야 했던 사례는 흔들린 건 곡선이 아니라 재는 자였다에 적어 두었습니다.

I have an app that runs mock Chinese speaking tests. Press start and it asks a model to write the questions; you record your answers and the model grades them. On 20 August it ran a full sitting end to end for the first time.

After that, no questions came. The screen said:

Couldn't finish — Software caused connection abort

The first diagnosis

The sentence said the connection dropped, and the code had reasons to drop one. Two of them.

One was the screen turning off. The app holds the screen awake during a test, but the list of phases that did so was playing the question · preparing · recording. That made sense when the list was written — the worry then was a candidate not touching the screen for thirty minutes. But the phases where nobody touches the screen and a network call is in flight are question generation and scoring. Those two were missing.

The other was no retry. The client retried 429 and 5xx while never catching IOException at all. A dropped socket was rethrown on the first attempt and ended the sitting — the failure most likely to be cured by a retry was the one failure with no retry.

Both were real defects and both got fixed. I had no device on hand, so I stopped at a clean build.

The second diagnosis

On a device, it failed exactly as before.

Rather than dig further into the code, I measured. The screen first — asking the OS, not the app, whether it was really staying on.

app window fl=0x81810180      → FLAG_KEEP_SCREEN_ON(0x80) set
dumpsys power                 → SCREEN_BRIGHT_WAKE_LOCK
                                 ws=WorkSource{com.tscrehearsal}

The screen was staying on. The fix had worked and the failure had not moved. So what was failing? Three DNS timestamps in the log answered.

23:52:38   23:55:48   23:59:13
           └ 190s ┘   └ 205s ┘

read timeout 180s + backoff 10s / 25s

An exact match. All three were read timeouts and the retries had run as designed. Nothing was dropping; nothing was answering. Last, I ruled out the phone and the network — with no key, the same handset gets a 403 in 0.2s from the same host (0.17s from the Mac). The request leaves, the server takes it, and then nothing.

Meanwhile the on-screen message was sending people to the wrong place. The sentence added by that first fix read "the connection can drop if the screen turns off or the network changes". Measurement said the screen and the network were both fine — and that sentence was telling the reader to go fix something that wasn't broken. It now splits on the exception the socket layer threw: SocketTimeoutException gets "the request went out and no answer came", anything else gets the old dropped-connection wording.

So what was the cause? I don't know

What I established is one fact: that address stopped answering. It worked on the 20th and it doesn't now. Why is outside what this repository can see.

My draft release note said "when Google closed the API we were using". It's plausible, and it may well be true. But a timeout is not a deprecation notice. Publishing an unobserved cause as fact is exactly the habit worth not having, so it came out in favour of "the address we were using stopped responding" — which is the part a user needs anyway.

Not a new address — a new shape

The alternative was the same service's streaming endpoint. Instead of one response at the end, you get data: line fragments and join them in arrival order.

This is the point of the whole story. The difference between batch and streaming isn't speed; it's whether failure can speak.

A batch call holds the connection until the model has finished, then sends everything at once. Which means a model thinking for three minutes and a dead socket look identical to a timeout. Both are "nothing arrived for 180 seconds". Streaming pushes a token as soon as there is one, and each one resets the socket's clock — if it's alive, it says so.

So what I did was not repair the broken thing. I replaced a structure that could only produce silence with one that keeps saying it is alive. That is why progress was possible without ever finding the cause.

The move changed nothing at first

The first streaming build had exactly the same symptom: over 200 seconds to the first byte.

The reason was one line. This model reasons before it answers, and it emits no SSE events at all while reasoning. Through that stretch, streaming is indistinguishable from batch. Only with thinkingConfig.thinkingBudget = 0 did the migration buy anything. The fallback model has no reasoning stage and rejects the field with a 400, so it is sent conditionally.

A new structure brings new failures

Days later, a user's screen showed this:

Couldn't parse the response:
model did not return JSON (len=16) — { "questions":"

Those 16 characters are not malformed JSON. They are the beginning of well-formed JSON. The stream was cut mid-flight, but HTTP had already said 200, so to the parser it looked like the model had emitted something strange. A reader of that sentence goes off to suspect the model's output format. In fact the transfer was cut, the request was fine, and trying again would work.

Batch never failed this way. A response arrived whole or not at all; it never arrived half. Partial failure is what the observability cost.

The server marks the end with finishReason. If it never appears, the response never ended — so the parser returns "did it finish" alongside the text, and an unfinished one is thrown as a transfer failure and retried. One ordering trap: the completion check has to happen before the "no content here, skip" branch. The chunk that ends a stream usually carries the reason and no new text, so the wrong order misses the only marker of completion.

A comment describing what the code did not do

That same week, 503s (backend overloaded) came back. The design: don't wait on a 503, retry briefly, and when the retries are gone, switch to a lighter model and save the sitting. The comment said so too.

That switch had never once executed.

repeat(RETRIES) { attempt ->
    ...
    if (attempt == RETRIES - 1) throw e     // the last attempt leaves here
    if (e.status == 503) { ... }            // so this is never reached
}
// after the loop: switch model, restart    // let alone this

The final attempt threw out of the loop, never reaching the very transition that gives 503 its special handling. The comment described what the code did not do, which is why it read correctly every time.

Fixing it exposed a second fault: the switch was per client, not per call. Scoring runs eight calls at once; when they all hit 503 together, one switches models and the other seven read "already on fallback" and give up. One of eight items gets graded — the exact inverse of "a graded sitting beats a dead one".

What the fix created

Question generation moved from one bulk call to one call per slot. A bulk call has to produce every output token before it answers, which is precisely the shape a busy backend refuses. The cost is more requests (a short test 8→13, a full one 27→48), which meant the start screen's request count and cost estimate — both resting on the old assumption — had to be corrected too.

And splitting it up shook out more.

  • Cancelling could kill a sitting. The generation job's catch caught CancellationException too, so "cancelled" showed as "couldn't finish". Worse, that job then sleeps up to another 180 seconds inside a blocking read before waking — and if a new sitting has started by then, a dead job fails a live sitting.
  • The model's own index was trusted. Even one-call-per-slot, the index in the reply was used — and since the prompt's example shows "index":0, a model copying it drops the question into the wrong slot, where it is discarded. The sitting is rejected after every earlier call has been paid for.
  • Progress misreported the size of the test. A short test is 7 questions, and the screen said "0 / 6". The total counted slots to call, and Part 1 is fixed text with no call. The button the user just pressed said 7; the next screen said 6. A Part 1 question is still a question — it isn't uncounted, it's the starting point of the count.

The sibling repository

This app has separate iOS and Android editions. Both were hit the same day; iOS moved first and Android ported the move across.

What's interesting is that the direction then reversed. The truncated stream and the unreachable 503 fallback were both seen by a user on Android — and both turned out to exist at the same spot in the iOS code. Looking for a freshly found defect in the sibling paid off twice: ported code ports its bugs.

What I have not seen

Stated plainly: audio does now go out over the new endpoint — a user ran a sitting through scoring on a real device. But in that sitting they didn't speak. Silence returns a null pronunciation score by design, so what was proven is the audio transfer, not the pronunciation judgement. Whether the grader actually hears through the new endpoint is still unverified, and the 503 fallback and its settings-screen warning exist only as code — neither has ever run.


In short

  • Silence says nothing. When the response arrives all at once, a thinking server and a dead one are indistinguishable.
  • When you can't diagnose, make the system speak. Changing the shape until signal comes out can beat guessing at causes.
  • "Did the fix work" and "did the symptom go" are different questions. Keeping the screen awake succeeded while the failure stayed — measuring them separately is what kept a good fix from being doubted.
  • A wrong diagnosis outlives its code in the wording. A sentence that names a cause sends the reader there.
  • Don't publish a cause you didn't observe. A timeout is not a deprecation notice.
  • Change the structure and you change the failures. Partial responses came with streaming, and to the old parser they look like a format error.
  • A comment can describe what the code doesn't do. Ask whether that path has ever actually executed.
  • Ported code ports its bugs. A defect found on one side is worth looking for at the same spot on the other.

Measuring whether the grader in this same app really listens is in Whether the Grader Listens; two plausible diagnoses that were both wrong are in The Stack Did Not Move. The case for suspecting the instrument first is in It Was the Instrument Shaking, Not the Curve.