Skip to content

Commit d0c3b07

Browse files
committed
수정: 멈춘 자식 worker 가 원인을 말하게 한다
Linux CI 에서 eager 자식이 기한을 통째로 쓰고도 끝나지 않는 실패가 남아 있었다. bounded join 과 main thread warm import 를 넣고도 재현됐고, 남는 것은 평평한 실패 코드와 elapsed 뿐이라 어디서 섰는지 지목할 수 없었다. 가설로 두 번 틀렸으므로 진단을 먼저 세운다. `describeStalledThread` 를 `processLifecycle` 에 두고 owner 와 eager 두 자식이 공유한다. join 이 만료됐는데 worker 가 살아 있으면 그 thread 의 frame 을 파일, 줄, 함수로 요약해 자식 stderr 로 낸다. 공개 payload 에는 싣지 않으므로 외부 메시지 계약은 그대로다. 자식이 침묵하던 원인 자체도 고친다. 기존 실패 경로는 worker 가 살아 있으면 결과를 아예 보내지 않았다. 그런데 worker 는 결과를 리스트에만 넣고 connection 을 만지지 않으므로 보내도 경합이 없다. 보내지 않는 동안 부모는 원인 대신 자기 기한이 다 찰 때까지 침묵을 받았다. 회귀 2 건으로 요약이 실제 blocking frame 을 가리키는지와 알 수 없는 thread 에서 진단이 먼저 죽지 않는지 고정했다. dataHub 회귀 322 건 통과와 환경 의존 2 건 skip, 게이트 lint 와 architecture-l0-l15 통과를 확인했다.
1 parent 1e6bf5b commit d0c3b07

5 files changed

Lines changed: 149 additions & 33 deletions

File tree

‎src/dartlab/dataHub/isolation/eagerProcess.py‎

Lines changed: 29 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,10 @@
8282
_safeErrorCode,
8383
_strictJson,
8484
)
85-
from dartlab.dataHub.isolation.processLifecycle import becomeProcessGroupLeader
85+
from dartlab.dataHub.isolation.processLifecycle import (
86+
becomeProcessGroupLeader,
87+
describeStalledThread,
88+
)
8689
from dartlab.dataHub.paging.runtime import (
8790
MAX_OWNER_PROCESS_REQUEST_BYTES,
8891
requireDeadline,
@@ -748,28 +751,37 @@ def runWorker() -> None:
748751
joinSeconds = max(0.0, workDeadline - time.perf_counter())
749752
worker.join(timeout=joinSeconds)
750753
if worker.is_alive():
754+
# 멈춘 지점을 자식 stderr 로 남긴다. 부모가 받는 것은 평평한 실패 코드라
755+
# 여기서 잡지 않으면 어디서 섰는지 영영 알 수 없다.
756+
print(
757+
f"[dataHub] eager worker stalled at {describeStalledThread(worker.ident)}",
758+
file=sys.stderr,
759+
flush=True,
760+
)
751761
raise RuntimeError("EAGER_PROCESS_WORKER_DID_NOT_FINISH")
752762
if len(output) != 1:
753763
raise RuntimeError("EAGER_PROCESS_WORKER_RESULT_INVALID")
754764
sendConnection.send_bytes(_strictJson(output[0]))
755765
except BaseException as error:
756-
if worker is None or not worker.is_alive():
757-
try:
758-
sendConnection.send_bytes(
759-
_strictJson(
760-
{
761-
"artifactId": artifactId,
762-
"byteCount": None,
763-
"digest": None,
764-
"errorCode": _safeErrorCode(error),
765-
"kind": "result",
766-
"rowCount": None,
767-
"status": "failed",
768-
}
769-
)
766+
# worker 는 결과를 `output` 리스트에만 넣고 이 connection 을 만지지 않는다.
767+
# 그래서 worker 가 아직 살아 있어도 여기서 실패를 보내는 것이 안전하다.
768+
# 보내지 않으면 부모는 원인 대신 자기 기한이 다 찰 때까지 침묵을 받는다.
769+
try:
770+
sendConnection.send_bytes(
771+
_strictJson(
772+
{
773+
"artifactId": artifactId,
774+
"byteCount": None,
775+
"digest": None,
776+
"errorCode": _safeErrorCode(error),
777+
"kind": "result",
778+
"rowCount": None,
779+
"status": "failed",
780+
}
770781
)
771-
except BaseException:
772-
pass
782+
)
783+
except BaseException:
784+
pass
773785
finally:
774786
workerGate.set()
775787
sendConnection.close()

‎src/dartlab/dataHub/isolation/ownerProcessChild.py‎

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import hashlib
1111
import importlib
1212
import os
13+
import sys
1314
import threading
1415
import time
1516
from multiprocessing.connection import Connection
@@ -29,6 +30,7 @@
2930
)
3031
from dartlab.dataHub.isolation.processLifecycle import (
3132
becomeProcessGroupLeader,
33+
describeStalledThread,
3234
)
3335
from dartlab.dataHub.telemetry import dataHubLogger, recordFailure
3436

@@ -193,28 +195,37 @@ def runWorker() -> None:
193195
joinSeconds = max(0.0, workDeadline - time.perf_counter())
194196
worker.join(timeout=joinSeconds)
195197
if worker.is_alive():
198+
# 멈춘 지점을 자식 stderr 로 남긴다. 부모가 받는 것은 평평한 실패 코드라
199+
# 여기서 잡지 않으면 어디서 섰는지 영영 알 수 없다.
200+
print(
201+
f"[dataHub] owner worker stalled at {describeStalledThread(worker.ident)}",
202+
file=sys.stderr,
203+
flush=True,
204+
)
196205
raise RuntimeError("OWNER_PROCESS_WORKER_DID_NOT_FINISH")
197206
if len(output) != 1:
198207
raise RuntimeError("OWNER_PROCESS_WORKER_RESULT_INVALID")
199208
sendConnection.send_bytes(_strictJson(output[0]))
200209
except BaseException as error:
201-
if worker is None or not worker.is_alive():
202-
try:
203-
sendConnection.send_bytes(
204-
_strictJson(
205-
{
206-
"artifactId": artifactId,
207-
"byteCount": None,
208-
"digest": None,
209-
"errorCode": _safeErrorCode(error),
210-
"kind": "result",
211-
"rowCount": None,
212-
"status": "failed",
213-
}
214-
)
210+
# worker 는 결과를 `output` 리스트에만 넣고 이 connection 을 만지지 않는다.
211+
# 그래서 worker 가 아직 살아 있어도 여기서 실패를 보내는 것이 안전하다.
212+
# 보내지 않으면 부모는 원인 대신 자기 기한이 다 찰 때까지 침묵을 받는다.
213+
try:
214+
sendConnection.send_bytes(
215+
_strictJson(
216+
{
217+
"artifactId": artifactId,
218+
"byteCount": None,
219+
"digest": None,
220+
"errorCode": _safeErrorCode(error),
221+
"kind": "result",
222+
"rowCount": None,
223+
"status": "failed",
224+
}
215225
)
216-
except BaseException:
217-
pass
226+
)
227+
except BaseException:
228+
pass
218229
finally:
219230
workerGate.set()
220231
sendConnection.close()

‎src/dartlab/dataHub/isolation/processLifecycle.py‎

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,60 @@
1212

1313
import os
1414
import signal
15+
import sys
1516
import time
17+
import traceback
18+
from pathlib import Path
19+
20+
_STALL_FRAME_LIMIT = 6
21+
22+
23+
def describeStalledThread(threadIdent: int | None) -> str:
24+
"""기한을 넘긴 worker thread 가 서 있는 지점을 한 줄로 요약한다.
25+
26+
Capabilities:
27+
살아 있는 thread 의 현재 frame 을 잡아 파일명, 줄번호, 함수명으로 압축한다.
28+
29+
AIContext:
30+
자식이 기한을 다 쓰고도 끝나지 않을 때 부모가 받는 것은 평평한 실패 코드뿐이라
31+
어디서 멈췄는지 알 수 없다. 이 요약이 그 공백을 메운다.
32+
33+
Guide:
34+
반환값은 진단용이라 자식 stderr 로 내보내고 공개 payload 에는 싣지 않는다.
35+
36+
When:
37+
`Thread.join(timeout=...)` 이 만료됐는데 thread 가 여전히 살아 있을 때.
38+
39+
How:
40+
`sys._current_frames()` 에서 해당 ident 의 frame 을 찾아 안쪽 몇 개만 남긴다.
41+
42+
Requires:
43+
`threading.Thread.ident`. `native_id` 는 frame 표의 키가 아니라 쓸 수 없다.
44+
45+
Raises:
46+
올리지 않는다. 진단 경로가 진단 대상보다 먼저 죽으면 안 된다.
47+
48+
Example:
49+
``describeStalledThread(worker.ident)``.
50+
51+
See Also:
52+
``waitProcessGroupZero``.
53+
"""
54+
55+
if threadIdent is None:
56+
return "thread-ident-unavailable"
57+
try:
58+
frame = sys._current_frames().get(threadIdent)
59+
except Exception:
60+
return "thread-frames-unavailable"
61+
if frame is None:
62+
return "thread-gone"
63+
try:
64+
stack = traceback.extract_stack(frame)
65+
except Exception:
66+
return "thread-stack-unavailable"
67+
tail = stack[-_STALL_FRAME_LIMIT:]
68+
return " <- ".join(f"{Path(item.filename).name}:{item.lineno}:{item.name}" for item in reversed(tail))
1669

1770

1871
def becomeProcessGroupLeader() -> bool:
@@ -137,6 +190,7 @@ def stopProcessGroup(pid: int | None, deadline: float) -> tuple[str, ...]:
137190

138191
__all__ = [
139192
"becomeProcessGroupLeader",
193+
"describeStalledThread",
140194
"processGroupAlive",
141195
"stopProcessGroup",
142196
"waitProcessGroupZero",

‎src/dartlab/dataHub/paging/resource/api.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,7 @@
136136

137137
_log = dataHubLogger(__name__)
138138

139+
139140
def executeInitialResourcePaging(
140141
assetIds: Sequence[str],
141142
query: DataQuery,
@@ -280,6 +281,7 @@ def executeInitialResourcePaging(
280281
resolvedAssets=len(resolved),
281282
)
282283

284+
283285
def resumeResourcePaging(token: str, *, deadline: float, startedAt: float | None = None) -> DataResult:
284286
"""Token private state를 catalog lookup 없이 복원해 다음 multiplex page를 반환한다."""
285287

‎tests/dataHub/test_processLifecycle.py‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,3 +50,40 @@ def testWaitReturnsImmediatelyForReleasedGroup() -> None:
5050
startedAt = time.perf_counter()
5151
assert waitProcessGroupZero(None, startedAt + 5) is True
5252
assert time.perf_counter() - startedAt < 1.0
53+
54+
55+
def testStalledThreadDescriptionPointsAtTheBlockingFrame() -> None:
56+
"""멈춘 thread 요약은 그 thread 가 실제로 서 있는 파일과 줄을 가리킨다."""
57+
58+
import threading
59+
60+
from dartlab.dataHub.isolation.processLifecycle import describeStalledThread
61+
62+
release = threading.Event()
63+
64+
def blocked() -> None:
65+
release.wait(timeout=5.0)
66+
67+
worker = threading.Thread(target=blocked, daemon=True)
68+
worker.start()
69+
try:
70+
deadline = time.perf_counter() + 2.0
71+
summary = ""
72+
while time.perf_counter() < deadline:
73+
summary = describeStalledThread(worker.ident)
74+
if "blocked" in summary:
75+
break
76+
assert "blocked" in summary
77+
assert "test_processLifecycle.py" in summary
78+
finally:
79+
release.set()
80+
worker.join(timeout=5.0)
81+
82+
83+
def testStalledThreadDescriptionNeverRaisesOnUnknownThread() -> None:
84+
"""진단 경로가 진단 대상보다 먼저 죽으면 안 된다."""
85+
86+
from dartlab.dataHub.isolation.processLifecycle import describeStalledThread
87+
88+
assert describeStalledThread(None) == "thread-ident-unavailable"
89+
assert describeStalledThread(-1) == "thread-gone"

0 commit comments

Comments
 (0)