[fix] solution/backend: 카카오 콜백 대기 문구를 늦어질 때만 — 3.5초 안에 끝나면 바로 답

콜백이 켜져 있으면 무조건 "확인하고 있어요" 부터 나가서, 1초면 끝나는 답에도
대기 문구가 먼저 붙었다 — 사장님에게는 두 번 말하는 봇이다(2026-10-02 체감 지적).

- kakao_bot.py: FAST_REPLY_SEC(3.5초) 안에 끝나면 일반 응답, 넘으면 useCallback 즉답 후
  같은 작업을 콜백으로 이어 보냄. shield 로 취소하지 않는다 — 다시 돌리면 도구가 두 번 실행될 수 있다
- docs/AGENT.md: 콜백 흐름 갱신, 콜백 블록의 일반 응답은 개발 채널 실측 전이라는 주의

test_kakao_webhook 44 passed. 전체 1045 passed · 48 failed(gemini·search_console·weather_notes —
변경 전에도 같은 48건 실패, 이번 변경과 무관)

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
HyeongBaeYangandClaude Opus 5.5 committed 2026-10-21 14:15:14 +09:00
1 parent c7749662fd
commit 42803de966
3 files changed
+89 -23

No files matched your search

+12 -3
View File
@@ -428,11 +428,20 @@ URL 만 알면 누구나 이 엔드포인트를 때릴 수 있고, `userRequest.
```
카카오 → 우리 발화 + callbackUrl
우리 → 카카오 {"version":"2.0","useCallback":true,"data":{"text":"확인하고 있어요…"}} (즉답)
… 백그라운드에서 답을 만든다 (상한 45초)
우리 → 카카오 POST callbackUrl {"version":"2.0","template":{…}} (완성분)
… 답을 만들기 시작하고 FAST_REPLY_SEC(3.5초)까지 기다린다
(빨리 끝남) 우리 → 카카오 {"version":"2.0","template":{…}} (바로 답, 콜백 안 씀)
(늦어짐) 우리 → 카카오 {"version":"2.0","useCallback":true,"data":{"text":"확인하고 있어요…"}} (즉답)
… 같은 작업을 끝까지 기다린다 (처음부터 상한 45초)
우리 → 카카오 POST callbackUrl {"version":"2.0","template":{…}} (완성분)
```
★ **대기 문구는 늦어질 때만 나간다**(2026-10-02). 예전엔 콜백이 켜져 있으면 무조건 대기 문구부터
보내서, 1초면 끝나는 답에도 "확인하고 있어요" 가 먼저 붙었다 — 사장님에게는 두 번 말하는 봇이다.
★ 3.5초를 넘겨도 작업을 **취소하지 않고**(`asyncio.shield`) 그 작업의 결과를 콜백으로 보낸다.
취소하고 다시 돌리면 도구(값 바꾸기·발행 접수)가 두 번 실행될 수 있다.
★ 콜백이 켜진 블록에서 `useCallback` 없이 일반 응답을 주는 것은 개발 채널에서 실제로 확인한 뒤
운영에 올린다 — 카카오 문서상 허용이지만 이 레포에서 아직 실측하지 않았다.
★ 콜백 주소는 **1분 · 1회**만 유효하다. 전송에 실패해도 **재시도하지 않는다** — 두 번째 POST 는
어차피 거절되고, 사장님에게는 이미 "확인하고 있어요" 가 가 있다.
+26 -9
View File
@@ -12,8 +12,10 @@
★ 5초 벽: 오픈빌더의 스킬 타임아웃은 **5초**다. 넘기면 카카오가 끊어 사장님에게는
**말없이 실패하는 봇**이 된다.
→ 오픈빌더 스킬 설정에서 **콜백 사용**을 켜면 요청에 `userRequest.callbackUrl` 이 실려 온다.
그때는 `{"useCallback": true}` 로 **즉답**하고, 답을 다 만든 뒤 그 주소로 따로 보낸다.
콜백 주소는 **1분 · 1회**만 유효하다.
그때도 `FAST_REPLY_SEC` 안에 끝나면 **답을 바로** 준다. 넘을 때만 `{"useCallback": true}` 로
대기 문구를 즉답하고, 답을 다 만든 뒤 그 주소로 따로 보낸다. 콜백 주소는 **1분 · 1회**만 유효하다.
예전엔 콜백이 켜져 있으면 무조건 대기 문구부터 나가서, 1초면 끝나는 답에도 "확인하고 있어요"
가 먼저 붙었다(2026-10-02, 사장님 체감 지적).
→ 콜백이 꺼져 있으면 예전처럼 동기로 답하되 `DEADLINE_SEC` 로 끊는다. 실측(2026-09-22):
필드 43개 + fact 수십 개가 실린 실제 프롬프트는 4초를 넘겼다 — 개발 중 재본
1.3~2.4초는 항목 두 개짜리 장난감 프롬프트였다.
@@ -36,6 +38,8 @@ router = APIRouter(prefix="/v1/agent/kakao", tags=["Agent"])
DEADLINE_SEC = 4.5
# 콜백이 켜져 있을 때의 상한. 콜백 주소가 1분간 유효하므로 그 안에서 넉넉히 잡는다.
CALLBACK_DEADLINE_SEC = 45.0
# 콜백이 켜져 있어도 이 안에 끝나면 대기 문구 없이 바로 답한다. 5초 벽에서 왕복 몫을 남긴다.
FAST_REPLY_SEC = 3.5
_TIMEOUT_TEXT = "확인하는 데 시간이 조금 걸리네요. 잠시 뒤 다시 말씀해 주세요."
_ERROR_TEXT = "지금은 처리할 수 없어요. 잠시 뒤 다시 말씀해 주세요."
@@ -102,10 +106,13 @@ def _authorize(secret_in_path: str | None, header_secret: str | None, body: dict
async def _answer(utterance: str, speaker: str, deadline: float, app_user_id: str = '') -> dict:
return await _settle(asyncio.ensure_future(channel.handle(utterance, speaker, app_user_id)), deadline)
async def _settle(task: asyncio.Future, deadline: float) -> dict:
"""대화 한 턴을 SkillResponse 로. 어떤 실패도 문구로 바꾼다."""
try:
answer = await asyncio.wait_for(
channel.handle(utterance, speaker, app_user_id), timeout=deadline)
answer = await asyncio.wait_for(task, timeout=deadline)
except asyncio.TimeoutError:
LOG.w("[agent/kakao] 응답 시간 초과 — 안내로 끊음")
return _reply(_TIMEOUT_TEXT)
@@ -159,12 +166,12 @@ async def _approve_click(extra: dict, speaker: str) -> dict:
return _reply_from(answer)
async def _push(callback_url: str, utterance: str, speaker: str, app_user_id: str = '') -> None:
"""답을 다 만든 뒤 콜백 주소로 보낸다.
async def _push(callback_url: str, task: asyncio.Future, deadline: float) -> None:
"""이미 돌고 있는 대화 한 턴이 끝나기를 기다렸다가 콜백 주소로 보낸다.
★ 주소는 1분 · 1회만 유효하다. 실패해도 재시도하지 않는다 — 두 번째 POST 는 어차피
거절되고, 사장님에게는 이미 "확인하고 있어요" 가 가 있다."""
payload = await _answer(utterance, speaker, CALLBACK_DEADLINE_SEC, app_user_id)
payload = await _settle(task, deadline)
try:
async with httpx.AsyncClient(timeout=10.0) as client:
res = await client.post(callback_url, json=payload)
@@ -212,8 +219,18 @@ async def _handle(body: dict, tasks: BackgroundTasks) -> dict:
LOG.i(f"[agent/kakao] 요청 — callbackUrl={'있음' if callback_url else '없음'} "
f"block={(request.get('block') or {}).get('name')!r}")
if callback_url:
tasks.add_task(_push, callback_url, utterance, speaker, app_user_id)
return {"version": "2.0", "useCallback": True, "data": {"text": _WAIT_TEXT}}
# ★ 기다리는 동안 작업을 취소하지 않는다(shield) — 늦어지면 같은 작업을 콜백으로 이어 보낸다.
# 취소하고 다시 돌리면 도구가 두 번 실행될 수 있다.
task = asyncio.ensure_future(channel.handle(utterance, speaker, app_user_id))
try:
answer = await asyncio.wait_for(asyncio.shield(task), timeout=FAST_REPLY_SEC)
except asyncio.TimeoutError:
tasks.add_task(_push, callback_url, task, CALLBACK_DEADLINE_SEC - FAST_REPLY_SEC)
return {"version": "2.0", "useCallback": True, "data": {"text": _WAIT_TEXT}}
except Exception as ex: # noqa: BLE001 — 메신저에서는 500 도 침묵으로 보인다
LOG.w(f"[agent/kakao] 처리 실패: {type(ex).__name__}: {ex}")
return _reply(_ERROR_TEXT)
return _reply_from(answer)
return await _answer(utterance, speaker, DEADLINE_SEC, app_user_id)
+51 -11
View File
@@ -317,19 +317,55 @@ async def test_목록은_발행_여부를_같이_말한다(client, auth_headers,
# ── 콜백 (5초 벽 넘기) ───────────────────────────────────────────────────
async def test_콜백이_켜져_있으면_즉답하고_뒤에서_마저_만든다(client, auth_headers, db_engine, monkeypatch):
"""오픈빌더 스킬 타임아웃은 5초다."""
async def test_콜백이_켜져_있어도_빨리_끝나면_대기_문구_없이_바로_답한다(client, db_engine, monkeypatch):
"""1초면 끝나는 답에 "확인하고 있어요" 가 먼저 붙으면 사장님에게는 두 번 말하는 봇이다."""
import router.v1.agent.kakao_bot as bot
pushed = AsyncMock()
monkeypatch.setattr(bot, "_push", pushed)
payload = body("안녕", "콜백-빠른-발화자")
payload["userRequest"]["callbackUrl"] = "https://callback.example/one-shot"
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=payload)
assert "useCallback" not in res.json()
assert "연결" in said(res)
pushed.assert_not_awaited() # 콜백 주소는 쓰지 않는다
async def test_콜백이_켜져_있고_늦어지면_즉답하고_같은_작업을_콜백으로_보낸다(client, monkeypatch):
"""오픈빌더 스킬 타임아웃은 5초다. 늦어진 작업은 취소하지 않고 끝난 결과를 콜백으로 보낸다."""
import asyncio
import router.v1.agent.kakao_bot as bot
runs = []
async def slow_handle(utterance, speaker, app_user_id=""):
runs.append(utterance)
await asyncio.sleep(0.2)
return channel._say("늦은 답")
monkeypatch.setattr(bot.channel, "handle", slow_handle)
monkeypatch.setattr(bot, "FAST_REPLY_SEC", 0.05)
sent = {}
async def fake_push(callback_url, utterance, speaker, app_user_id=""):
sent["url"] = callback_url
sent["payload"] = await bot._answer(utterance, speaker, 5.0)
class FakeClient:
async def __aenter__(self):
return self
monkeypatch.setattr(bot, "_push", fake_push)
async def __aexit__(self, *_):
return False
payload = body("안녕", "콜백-발화자")
async def post(self, url, json):
sent["url"], sent["payload"] = url, json
return SimpleNamespace(status_code=200)
# 테스트 클라이언트도 httpx 라 모듈 전체가 아니라 bot 이 보는 이름만 바꾼다.
monkeypatch.setattr(bot, "httpx", SimpleNamespace(AsyncClient=lambda **_kw: FakeClient()))
payload = body("휴무 바꿔줘", "콜백-느린-발화자")
payload["userRequest"]["callbackUrl"] = "https://callback.example/one-shot"
res = await client.post(PATH, headers={"X-Agent-Secret": SECRET}, json=payload)
@@ -338,9 +374,10 @@ async def test_콜백이_켜져_있으면_즉답하고_뒤에서_마저_만든
assert res.json()["data"]["text"]
assert "template" not in res.json()
# 실제 답은 콜백으로 간다.
# 실제 답은 콜백으로 가고, 작업은 한 번만 돌았다.
assert sent["url"] == "https://callback.example/one-shot"
assert "연결" in sent["payload"]["template"]["outputs"][0]["simpleText"]["text"]
assert sent["payload"]["template"]["outputs"][0]["simpleText"]["text"] == "늦은 답"
assert runs == ["휴무 바꿔줘"]
async def test_콜백이_없으면_예전처럼_동기로_답한다(client, db_engine):
@@ -353,7 +390,10 @@ async def test_콜백_전송이_실패해도_터지지_않는다(monkeypatch):
"""주소는 1분 · 1회다."""
import router.v1.agent.kakao_bot as bot
monkeypatch.setattr(bot, "_answer", AsyncMock(return_value=bot._reply("답")))
import asyncio
done = asyncio.get_running_loop().create_future()
done.set_result(channel._say("답"))
class Boom:
async def __aenter__(self):
@@ -363,7 +403,7 @@ async def test_콜백_전송이_실패해도_터지지_않는다(monkeypatch):
return False
monkeypatch.setattr(bot.httpx, "AsyncClient", lambda **_kw: Boom())
await bot._push("https://callback.example/x", "안녕", "누구") # 예외가 새 나오지 않는다
await bot._push("https://callback.example/x", done, 1.0) # 예외가 새 나오지 않는다
# ── 여러 가게 ────────────────────────────────────────────────────────────