운영 점검 결함 수정: 감독 주기 충돌, 로그인 확인 지연, 비용 단가
Some checks failed
API contract / OpenAPI type drift (push) Failing after 6m30s
Some checks failed
API contract / OpenAPI type drift (push) Failing after 6m30s
- 감독·연구 생성 주기: 교육과정 공백·근거 묶음 제출 번호 지문이 저장 내용 전체(상태·불확실도·영향 학습자 수·근거 포인터)를 덮게 해, 9월 근거 링크 변경 뒤 매시 반복되던 제출 번호 충돌과 코호트 롤백을 없앤다. - 세션 복원: last_seen_at 갱신을 60초 간격으로 묶어 로그인 요청마다 생기던 확정 쓰기 2회를 줄인다. 관리자 권한 승격은 즉시 반영한다. - 비용: OpenAI API gpt-5.6-terra 공식 표준 단가(2026-07-30부터)를 참조 단가에 추가해 관리자 비용 화면의 $0 표시를 바로잡는다. - 음성 합성 실패(502) 원인을 서버 기록에 남긴다.
This commit is contained in:
parent
cc4a943ad8
commit
7facf961c5
8 changed files with 566 additions and 10 deletions
|
|
@ -25,6 +25,10 @@ from .services import notifications
|
|||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 로그인된 요청마다 last_seen_at을 확정 쓰기(fsync)하면 NAS 볼륨 지연이 그대로
|
||||
# 요청 지연으로 전가된다. 이 간격 안에서는 재갱신을 건너뛴다.
|
||||
_LAST_SEEN_WRITE_INTERVAL_SECONDS = 60
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class SessionUser:
|
||||
|
|
@ -2257,8 +2261,13 @@ async def get_session(raw_sid: str | None) -> SessionUser | None:
|
|||
stored_admin_access,
|
||||
)
|
||||
await conn.execute(
|
||||
"UPDATE app.auth_session SET last_seen_at = now() WHERE sid_hash = $1",
|
||||
"""
|
||||
UPDATE app.auth_session SET last_seen_at = now()
|
||||
WHERE sid_hash = $1
|
||||
AND last_seen_at < now() - make_interval(secs => $2)
|
||||
""",
|
||||
key,
|
||||
_LAST_SEEN_WRITE_INTERVAL_SECONDS,
|
||||
)
|
||||
await conn.execute(
|
||||
"""
|
||||
|
|
@ -2273,9 +2282,15 @@ async def get_session(raw_sid: str | None) -> SessionUser | None:
|
|||
ELSE updated_at
|
||||
END
|
||||
WHERE user_id = $1
|
||||
AND (
|
||||
last_seen_at IS NULL
|
||||
OR last_seen_at < now() - make_interval(secs => $3)
|
||||
OR ($2 AND NOT admin_access)
|
||||
)
|
||||
""",
|
||||
row["user_id"],
|
||||
effective_admin_access,
|
||||
_LAST_SEEN_WRITE_INTERVAL_SECONDS,
|
||||
)
|
||||
return SessionUser(
|
||||
user_id=str(row["user_id"]),
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import asyncio
|
|||
import json
|
||||
import hashlib
|
||||
import hmac
|
||||
import logging
|
||||
import time
|
||||
from dataclasses import dataclass, field as dataclass_field
|
||||
from typing import Optional
|
||||
|
|
@ -69,6 +70,7 @@ from ..services.voice_runtime import (
|
|||
from ..store import InProcSession, TurnRecord, store
|
||||
|
||||
router = APIRouter(prefix="/voice", tags=["voice"])
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class VoiceSpeechRequest(BaseModel):
|
||||
|
|
@ -297,6 +299,13 @@ async def voice_speech(
|
|||
detail=str(exc),
|
||||
) from exc
|
||||
except Exception as exc:
|
||||
logger.warning(
|
||||
"TTS 합성 실패: session=%s turn=%s error=%s: %s",
|
||||
body.session_id,
|
||||
body.turn_seq,
|
||||
type(exc).__name__,
|
||||
exc,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_502_BAD_GATEWAY,
|
||||
detail=f"TTS failed: {exc}",
|
||||
|
|
|
|||
|
|
@ -3,7 +3,8 @@
|
|||
``cost_usd``를 직접 반환하는 Claude CLI는 SDK가 계산한 호출별 추정값을 그대로
|
||||
기록한다. Codex/Agy처럼 토큰만 반환하는 구독형 CLI와 Anthropic Messages API는
|
||||
호출 시점의 공식 공개 단가로 USD 상당액을 계산한다. 어느 쪽도 청구서 실비가
|
||||
아니며 비교·예산 관측용 추정 비용이다.
|
||||
아니며 비교·예산 관측용 추정 비용이다. OpenAI API처럼 토큰만 기록되고
|
||||
``cost_usd``가 0으로 남는 provider도 공식 API 참조단가로 같은 방식으로 환산한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
|
@ -24,6 +25,8 @@ OPENAI_CREDIT_VALUE_URL = (
|
|||
"https://help.openai.com/en/articles/20001147-codex-credits-for-students"
|
||||
)
|
||||
ANTHROPIC_PRICING_URL = "https://platform.claude.com/docs/en/about-claude/pricing"
|
||||
OPENAI_API_PRICING_URL = "https://developers.openai.com/api/docs/pricing"
|
||||
OPENAI_56_TERRA_PRICE_START = date(2026, 7, 30)
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
|
@ -225,6 +228,25 @@ def _rate(
|
|||
OPENAI_CODEX_RATE_URL,
|
||||
)
|
||||
|
||||
if provider_key == "openai":
|
||||
if model_key == "gpt-5.6-terra" or model_key.startswith("gpt-5.6-terra-"):
|
||||
if priced_on < OPENAI_56_TERRA_PRICE_START:
|
||||
return None
|
||||
# 장문(>272K 입력) 할증은 반영하지 않는다: 관리자 집계가 여러 턴의
|
||||
# 토큰 합계를 넘길 수 있어 요청 단위 272K 기준을 판별할 수 없고,
|
||||
# 이 앱의 턴은 평균 입력 약 2.5K 토큰으로 할증 구간에 들지 않는다.
|
||||
return ModelRate(
|
||||
2.00,
|
||||
12.00,
|
||||
0.20,
|
||||
"openai-api-gpt-5.6-terra-standard@2026-07-30",
|
||||
(
|
||||
"OpenAI API gpt-5.6-terra 표준 단가(272K 이하 입력)"
|
||||
" · 입력 $2/M · 캐시 $0.2/M · 출력 $12/M"
|
||||
),
|
||||
OPENAI_API_PRICING_URL,
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
|
||||
|
|
@ -280,6 +302,7 @@ __all__ = [
|
|||
"ANTHROPIC_PRICING_URL",
|
||||
"CostEstimate",
|
||||
"GOOGLE_PRICING_URL",
|
||||
"OPENAI_API_PRICING_URL",
|
||||
"OPENAI_CODEX_RATE_URL",
|
||||
"OPENAI_CREDIT_VALUE_URL",
|
||||
"RATE_CARD_VERSION",
|
||||
|
|
|
|||
|
|
@ -657,11 +657,32 @@ async def produce_supervision_cycle(
|
|||
gap_groups[(item.competency_id, gap_kind)].append(item)
|
||||
for (competency_id, gap_kind), items in sorted(gap_groups.items()):
|
||||
evidence = [(item.learner_id, item.signal.evidence[0]) for item in items]
|
||||
status = (
|
||||
"observed"
|
||||
if len({item.learner_id for item in items}) >= 2
|
||||
else "monitoring"
|
||||
)
|
||||
uncertainty = max(item.signal.uncertainty for item in items)
|
||||
affected_learner_count = len({item.learner_id for item in items})
|
||||
# 지문은 신호 번호뿐 아니라 실제로 저장되는 내용(상태·불확실도·
|
||||
# 영향 학습자 수·근거 포인터 전체)을 전부 덮어야 한다. 그렇지 않으면
|
||||
# 근거 링크 형식만 바뀌어도 같은 제출 번호에 다른 내용이 들어가
|
||||
# SupervisionResearchConflictError로 코호트 트랜잭션이 롤백된다.
|
||||
gap_fingerprint = _canonical_hash(
|
||||
[
|
||||
competency_id,
|
||||
gap_kind,
|
||||
[item.signal.signal_id for item in items],
|
||||
status,
|
||||
uncertainty,
|
||||
affected_learner_count,
|
||||
[
|
||||
{
|
||||
"learner_id": str(learner_id),
|
||||
**pointer.model_dump(mode="json"),
|
||||
}
|
||||
for learner_id, pointer in evidence
|
||||
],
|
||||
]
|
||||
)
|
||||
result = await supervision_research_store.append_curriculum_gap(
|
||||
|
|
@ -677,11 +698,9 @@ async def produce_supervision_cycle(
|
|||
cohort_id=cohort_id,
|
||||
competency_id=competency_id,
|
||||
gap_kind=gap_kind,
|
||||
status="observed"
|
||||
if len({item.learner_id for item in items}) >= 2
|
||||
else "monitoring",
|
||||
uncertainty=max(item.signal.uncertainty for item in items),
|
||||
affected_learner_count=len({item.learner_id for item in items}),
|
||||
status=status,
|
||||
uncertainty=uncertainty,
|
||||
affected_learner_count=affected_learner_count,
|
||||
evidence=evidence,
|
||||
)
|
||||
gap_results.append(result)
|
||||
|
|
@ -689,15 +708,30 @@ async def produce_supervision_cycle(
|
|||
manifest_input = derive_manifest_input(await _load_manifest_rows(conn, cohort_id))
|
||||
manifest_result: dict[str, Any] | None = None
|
||||
if manifest_input is not None:
|
||||
# source_fingerprint는 이벤트 번호만 덮는다(derive_manifest_input의 기존
|
||||
# 의미 유지). 제출 번호는 그 위에 근거 포인터(route_hint 포함)까지 덮는
|
||||
# 별도 지문을 써서, 저장되는 내용과 제출 번호가 항상 함께 바뀌게 한다.
|
||||
manifest_submission_fingerprint = _canonical_hash(
|
||||
[
|
||||
manifest_input.source_fingerprint,
|
||||
{
|
||||
domain: [str(learner_id), pointer.model_dump(mode="json")]
|
||||
for domain, (
|
||||
learner_id,
|
||||
pointer,
|
||||
) in manifest_input.source_by_domain.items()
|
||||
},
|
||||
]
|
||||
)
|
||||
manifest_result = await supervision_research_store.append_phase3_manifest(
|
||||
conn,
|
||||
submission_id=uuid5(
|
||||
_PRODUCER_NAMESPACE,
|
||||
f"manifest-submission:{cohort_id}:{manifest_input.source_fingerprint}",
|
||||
f"manifest-submission:{cohort_id}:{manifest_submission_fingerprint}",
|
||||
),
|
||||
manifest_id=uuid5(
|
||||
_PRODUCER_NAMESPACE,
|
||||
f"manifest:{cohort_id}:{manifest_input.source_fingerprint}",
|
||||
f"manifest:{cohort_id}:{manifest_submission_fingerprint}",
|
||||
),
|
||||
cohort_id=cohort_id,
|
||||
artifacts=manifest_input.artifacts,
|
||||
|
|
|
|||
|
|
@ -248,6 +248,68 @@ class AuthIdentityAliasTest(unittest.IsolatedAsyncioTestCase):
|
|||
self.assertIn("s.login_email", conn.query)
|
||||
self.assertIn("canonical_email", conn.query)
|
||||
|
||||
async def test_restored_session_gates_last_seen_writes_by_interval(self) -> None:
|
||||
canonical = managed_user()
|
||||
|
||||
class Conn:
|
||||
def __init__(self) -> None:
|
||||
self.executed: list[tuple[str, tuple[Any, ...]]] = []
|
||||
|
||||
async def fetchrow(self, query: str, *args: Any) -> dict[str, Any]:
|
||||
return {
|
||||
"expires_at": datetime.fromtimestamp(
|
||||
time.time() + 3600, tz=timezone.utc
|
||||
),
|
||||
"user_id": canonical.user_id,
|
||||
"login_email": canonical.email,
|
||||
"canonical_email": canonical.email,
|
||||
"display_name": canonical.display_name,
|
||||
"role": "admin",
|
||||
"admin_access": True,
|
||||
"learner_feedback_enabled": True,
|
||||
"account_status": "approved",
|
||||
"cohort": "owner",
|
||||
"consent_at": datetime.fromtimestamp(1.0, tz=timezone.utc),
|
||||
"profile_completed_at": datetime.fromtimestamp(
|
||||
1.0, tz=timezone.utc
|
||||
),
|
||||
}
|
||||
|
||||
async def execute(self, query: str, *args: Any) -> str:
|
||||
self.executed.append((query, args))
|
||||
return "UPDATE 1"
|
||||
|
||||
conn = Conn()
|
||||
with (
|
||||
patched_settings(auth_super_admin_emails=[canonical.email]),
|
||||
patch.object(auth_sessions, "get_pool", return_value=FakePool(conn)),
|
||||
):
|
||||
restored = await auth_sessions.get_session("opaque-session")
|
||||
|
||||
self.assertIsNotNone(restored)
|
||||
self.assertEqual(len(conn.executed), 2)
|
||||
|
||||
session_query, session_args = conn.executed[0]
|
||||
self.assertIn("app.auth_session", session_query)
|
||||
self.assertIn(
|
||||
"last_seen_at < now() - make_interval(secs => $2)", session_query
|
||||
)
|
||||
self.assertEqual(
|
||||
session_args, (auth_sessions._sid_hash("opaque-session"), 60)
|
||||
)
|
||||
self.assertEqual(auth_sessions._LAST_SEEN_WRITE_INTERVAL_SECONDS, 60)
|
||||
|
||||
user_query, user_args = conn.executed[1]
|
||||
self.assertIn("app.app_user", user_query)
|
||||
self.assertIn(
|
||||
"last_seen_at < now() - make_interval(secs => $3)", user_query
|
||||
)
|
||||
self.assertIn("($2 AND NOT admin_access)", user_query)
|
||||
self.assertEqual(
|
||||
user_args,
|
||||
(canonical.user_id, True, auth_sessions._LAST_SEEN_WRITE_INTERVAL_SECONDS),
|
||||
)
|
||||
|
||||
async def test_me_response_uses_canonical_entitlement_not_login_email(self) -> None:
|
||||
canonical = managed_user()
|
||||
session_user = auth_sessions.SessionUser(
|
||||
|
|
|
|||
|
|
@ -115,6 +115,69 @@ class LlmPricingTest(unittest.TestCase):
|
|||
self.assertEqual(estimate.cost_usd, 0.0000705)
|
||||
self.assertIn("크레딧 환산", estimate.rate_label)
|
||||
|
||||
def test_openai_api_gpt_5_6_terra_standard_rate(self) -> None:
|
||||
estimate = estimate_reference_cost(
|
||||
provider="openai",
|
||||
model="gpt-5.6-terra",
|
||||
tokens_in=1_000_000,
|
||||
tokens_out=100_000,
|
||||
priced_at=date(2026, 10, 25),
|
||||
)
|
||||
|
||||
self.assertIsNotNone(estimate)
|
||||
assert estimate is not None
|
||||
self.assertEqual(estimate.cost_usd, 3.20)
|
||||
self.assertIn("openai-api-gpt-5.6-terra-standard@2026-07-30", estimate.rate_id)
|
||||
|
||||
def test_openai_api_gpt_5_6_terra_accounts_for_cached_input(self) -> None:
|
||||
estimate = estimate_reference_cost(
|
||||
provider="openai",
|
||||
model="gpt-5.6-terra",
|
||||
tokens_in=1_000_000,
|
||||
cached_input_tokens=200_000,
|
||||
tokens_out=100_000,
|
||||
priced_at=date(2026, 10, 25),
|
||||
)
|
||||
|
||||
self.assertIsNotNone(estimate)
|
||||
assert estimate is not None
|
||||
self.assertEqual(estimate.cost_usd, 2.84)
|
||||
|
||||
def test_openai_api_gpt_5_6_terra_is_unavailable_before_price_start(self) -> None:
|
||||
estimate = estimate_reference_cost(
|
||||
provider="openai",
|
||||
model="gpt-5.6-terra",
|
||||
tokens_in=1_000_000,
|
||||
tokens_out=100_000,
|
||||
priced_at=date(2026, 7, 29),
|
||||
)
|
||||
|
||||
self.assertIsNone(estimate)
|
||||
|
||||
def test_openai_api_gpt_5_6_terra_matches_dated_suffix(self) -> None:
|
||||
estimate = estimate_reference_cost(
|
||||
provider="openai",
|
||||
model="gpt-5.6-terra-2026-08-01",
|
||||
tokens_in=1_000,
|
||||
tokens_out=100,
|
||||
priced_at=date(2026, 10, 25),
|
||||
)
|
||||
|
||||
self.assertIsNotNone(estimate)
|
||||
assert estimate is not None
|
||||
self.assertEqual(estimate.cost_usd, 0.0032)
|
||||
|
||||
def test_openai_other_model_does_not_invent_a_price(self) -> None:
|
||||
estimate = estimate_reference_cost(
|
||||
provider="openai",
|
||||
model="gpt-5.6-sol",
|
||||
tokens_in=1_000,
|
||||
tokens_out=100,
|
||||
priced_at=date(2026, 10, 25),
|
||||
)
|
||||
|
||||
self.assertIsNone(estimate)
|
||||
|
||||
def test_unknown_model_does_not_invent_a_price(self) -> None:
|
||||
estimate = estimate_reference_cost(
|
||||
provider="agy_cli",
|
||||
|
|
|
|||
|
|
@ -1,11 +1,18 @@
|
|||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
from contextlib import ExitStack
|
||||
from unittest import IsolatedAsyncioTestCase, TestCase
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from uuid import UUID
|
||||
from uuid import UUID, uuid5
|
||||
|
||||
from .contracts.supervision_research import LedgerEvidencePointer
|
||||
from .services import supervision_research_store
|
||||
from .services.supervision_research_producer import (
|
||||
_PRODUCER_NAMESPACE,
|
||||
_canonical_hash,
|
||||
_load_attention_rows,
|
||||
_signal_id,
|
||||
derive_attention_signals,
|
||||
derive_manifest_input,
|
||||
produce_all_active_cohorts_once,
|
||||
|
|
@ -542,3 +549,267 @@ class SupervisionResearchProducerCycleTest(IsolatedAsyncioTestCase):
|
|||
self.assertFalse(result["clinical_claim_allowed"])
|
||||
append_attention.assert_awaited_once()
|
||||
append_gap.assert_awaited_once()
|
||||
|
||||
@staticmethod
|
||||
def _off_track_trajectory_rows() -> dict[str, list[Mapping[str, object]]]:
|
||||
return {
|
||||
"trajectory_rows": [
|
||||
{
|
||||
"learner_id": LEARNER_A,
|
||||
"revision_id": UUID("70000000-0000-0000-0000-000000000001"),
|
||||
"anchor_session_id": SESSION_A,
|
||||
"revision_no": 1,
|
||||
"assessment": {
|
||||
"sessions": [
|
||||
{
|
||||
"session_no": 1,
|
||||
"status": "off_track",
|
||||
"axes": [{"uncertainty": 0.5}],
|
||||
}
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
"rupture_rows": [],
|
||||
"calibration_rows": [],
|
||||
"transfer_rows": [],
|
||||
"practice_rows": [],
|
||||
}
|
||||
|
||||
async def _run_gap_cycle(self, *, route_hint: str | None) -> dict[str, object]:
|
||||
append_attention = AsyncMock(
|
||||
return_value={"submission_id": UUID(int=1), "snapshot_id": UUID(int=2)}
|
||||
)
|
||||
append_gap = AsyncMock(
|
||||
return_value={"submission_id": UUID(int=3), "gap_snapshot_id": UUID(int=4)}
|
||||
)
|
||||
conn = AsyncMock()
|
||||
patches = [
|
||||
patch(
|
||||
"app.services.supervision_research_producer._load_attention_rows",
|
||||
AsyncMock(return_value=self._off_track_trajectory_rows()),
|
||||
),
|
||||
patch(
|
||||
"app.services.supervision_research_producer._load_manifest_rows",
|
||||
AsyncMock(return_value={}),
|
||||
),
|
||||
patch(
|
||||
"app.services.supervision_research_producer.supervision_research_store.append_attention_snapshot",
|
||||
append_attention,
|
||||
),
|
||||
patch(
|
||||
"app.services.supervision_research_producer.supervision_research_store.append_curriculum_gap",
|
||||
append_gap,
|
||||
),
|
||||
]
|
||||
if route_hint is not None:
|
||||
patches.append(
|
||||
patch(
|
||||
"app.services.supervision_research_producer._route",
|
||||
return_value=route_hint,
|
||||
)
|
||||
)
|
||||
with ExitStack() as stack:
|
||||
for one_patch in patches:
|
||||
stack.enter_context(one_patch)
|
||||
await produce_supervision_cycle(conn, cohort_id="cohort-a")
|
||||
return append_gap.await_args.kwargs
|
||||
|
||||
async def test_gap_submission_id_changes_when_evidence_route_changes(
|
||||
self,
|
||||
) -> None:
|
||||
"""신호 번호는 같고 근거 포인터의 route_hint만 달라지면 공백 제출 번호도 달라야 한다."""
|
||||
old = await self._run_gap_cycle(route_hint="/teacher/sessions/old-route")
|
||||
new = await self._run_gap_cycle(
|
||||
route_hint="/teach/session/new-route/review"
|
||||
)
|
||||
|
||||
self.assertNotEqual(old["submission_id"], new["submission_id"])
|
||||
self.assertNotEqual(old["gap_snapshot_id"], new["gap_snapshot_id"])
|
||||
|
||||
async def test_gap_submission_is_idempotent_for_identical_input(self) -> None:
|
||||
first = await self._run_gap_cycle(route_hint=None)
|
||||
second = await self._run_gap_cycle(route_hint=None)
|
||||
|
||||
self.assertEqual(first["submission_id"], second["submission_id"])
|
||||
self.assertEqual(first["gap_snapshot_id"], second["gap_snapshot_id"])
|
||||
|
||||
@staticmethod
|
||||
def _manifest_rows() -> dict[str, list[Mapping[str, object]]]:
|
||||
return {
|
||||
domain: [
|
||||
{
|
||||
"event_id": UUID(f"60000000-0000-0000-0000-{index:012d}"),
|
||||
"learner_id": LEARNER_A,
|
||||
"session_id": SESSION_A,
|
||||
}
|
||||
]
|
||||
for index, domain in enumerate(
|
||||
("alliance", "rupture", "transfer", "calibration"), start=1
|
||||
)
|
||||
}
|
||||
|
||||
async def _run_manifest_cycle(self, *, route_hint: str | None) -> dict[str, object]:
|
||||
append_manifest = AsyncMock(
|
||||
return_value={"submission_id": UUID(int=5), "manifest_id": UUID(int=6)}
|
||||
)
|
||||
conn = AsyncMock()
|
||||
patches = [
|
||||
patch(
|
||||
"app.services.supervision_research_producer._load_attention_rows",
|
||||
AsyncMock(
|
||||
return_value={
|
||||
"trajectory_rows": [],
|
||||
"rupture_rows": [],
|
||||
"calibration_rows": [],
|
||||
"transfer_rows": [],
|
||||
"practice_rows": [],
|
||||
}
|
||||
),
|
||||
),
|
||||
patch(
|
||||
"app.services.supervision_research_producer._load_manifest_rows",
|
||||
AsyncMock(return_value=self._manifest_rows()),
|
||||
),
|
||||
patch(
|
||||
"app.services.supervision_research_producer.supervision_research_store.append_phase3_manifest",
|
||||
append_manifest,
|
||||
),
|
||||
]
|
||||
if route_hint is not None:
|
||||
patches.append(
|
||||
patch(
|
||||
"app.services.supervision_research_producer._route",
|
||||
return_value=route_hint,
|
||||
)
|
||||
)
|
||||
with ExitStack() as stack:
|
||||
for one_patch in patches:
|
||||
stack.enter_context(one_patch)
|
||||
await produce_supervision_cycle(conn, cohort_id="cohort-a")
|
||||
return append_manifest.await_args.kwargs
|
||||
|
||||
async def test_manifest_submission_id_changes_when_evidence_route_changes(
|
||||
self,
|
||||
) -> None:
|
||||
"""근거 묶음도 신호(이벤트) 번호는 같고 route_hint만 달라지면 제출 번호가 달라야 한다."""
|
||||
old = await self._run_manifest_cycle(route_hint="/teacher/sessions/old-route")
|
||||
new = await self._run_manifest_cycle(
|
||||
route_hint="/teach/session/new-route/review"
|
||||
)
|
||||
|
||||
self.assertNotEqual(old["submission_id"], new["submission_id"])
|
||||
self.assertNotEqual(old["manifest_id"], new["manifest_id"])
|
||||
|
||||
async def test_manifest_submission_is_idempotent_for_identical_input(
|
||||
self,
|
||||
) -> None:
|
||||
first = await self._run_manifest_cycle(route_hint=None)
|
||||
second = await self._run_manifest_cycle(route_hint=None)
|
||||
|
||||
self.assertEqual(first["submission_id"], second["submission_id"])
|
||||
self.assertEqual(first["manifest_id"], second["manifest_id"])
|
||||
|
||||
async def test_new_cycle_appends_new_submission_when_old_route_already_stored(
|
||||
self,
|
||||
) -> None:
|
||||
"""운영에 저장된 옛 링크 행이 있어도 새 주기는 충돌 없이 새 번호로 append한다.
|
||||
|
||||
2026-09-09 커밋(1306c524)으로 `_route()` 근거 링크 형식이 바뀌기 전에는
|
||||
교육과정 공백 제출 번호 지문이 신호 번호만 덮어서, 내용(route)만 바뀐
|
||||
재실행이 같은 제출 번호에 다른 내용을 넣어 SupervisionResearchConflictError로
|
||||
충돌했다. 수정 후에는 포인터 내용까지 지문에 들어가므로 새 번호로
|
||||
충돌 없이 append된다.
|
||||
"""
|
||||
revision_id = UUID("70000000-0000-0000-0000-000000000001")
|
||||
old_pointer = LedgerEvidencePointer(
|
||||
ledger="outcome_trajectory_revision",
|
||||
event_id=str(revision_id),
|
||||
session_id=str(SESSION_A),
|
||||
route_hint=f"/teacher/sessions/{SESSION_A}",
|
||||
)
|
||||
old_signal_id = _signal_id("trajectory", revision_id, "off_track")
|
||||
old_gap_fingerprint = _canonical_hash(
|
||||
["competency.outcome_monitoring", "coverage", [old_signal_id]]
|
||||
)
|
||||
old_submission_id = uuid5(
|
||||
_PRODUCER_NAMESPACE, f"gap-submission:cohort-a:{old_gap_fingerprint}"
|
||||
)
|
||||
old_gap_snapshot_id = uuid5(
|
||||
_PRODUCER_NAMESPACE, f"gap-snapshot:cohort-a:{old_gap_fingerprint}"
|
||||
)
|
||||
|
||||
conn = _FakeCurriculumGapConn()
|
||||
await supervision_research_store.append_curriculum_gap(
|
||||
conn,
|
||||
submission_id=old_submission_id,
|
||||
gap_snapshot_id=old_gap_snapshot_id,
|
||||
cohort_id="cohort-a",
|
||||
competency_id="competency.outcome_monitoring",
|
||||
gap_kind="coverage",
|
||||
status="monitoring",
|
||||
uncertainty=0.5,
|
||||
affected_learner_count=1,
|
||||
evidence=[(LEARNER_A, old_pointer)],
|
||||
)
|
||||
|
||||
append_attention = AsyncMock(
|
||||
return_value={"submission_id": UUID(int=1), "snapshot_id": UUID(int=2)}
|
||||
)
|
||||
with (
|
||||
patch(
|
||||
"app.services.supervision_research_producer._load_attention_rows",
|
||||
AsyncMock(return_value=self._off_track_trajectory_rows()),
|
||||
),
|
||||
patch(
|
||||
"app.services.supervision_research_producer._load_manifest_rows",
|
||||
AsyncMock(return_value={}),
|
||||
),
|
||||
patch(
|
||||
"app.services.supervision_research_producer.supervision_research_store.append_attention_snapshot",
|
||||
append_attention,
|
||||
),
|
||||
):
|
||||
result = await produce_supervision_cycle(conn, cohort_id="cohort-a")
|
||||
|
||||
self.assertEqual(len(result["curriculum_gaps"]), 1)
|
||||
gap_result = result["curriculum_gaps"][0]
|
||||
self.assertFalse(gap_result["idempotent_replay"])
|
||||
self.assertNotEqual(gap_result["submission_id"], old_submission_id)
|
||||
self.assertNotEqual(gap_result["gap_snapshot_id"], old_gap_snapshot_id)
|
||||
|
||||
|
||||
class _FakeCurriculumGapConn:
|
||||
"""교육과정 공백 제출 번호 충돌 검사만 재현하는 최소 모의 커넥션."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.gap_rows: dict[UUID, tuple[UUID, str]] = {}
|
||||
self.pointer_rows: dict[UUID, str] = {}
|
||||
|
||||
async def execute(self, query: str, *args: object) -> None:
|
||||
if "pg_advisory_xact_lock" in query:
|
||||
return
|
||||
if "INSERT INTO app.supervision_evidence_pointer" in query:
|
||||
pointer_id = args[0]
|
||||
content_hash = args[8]
|
||||
self.pointer_rows.setdefault(pointer_id, content_hash)
|
||||
return
|
||||
if "INSERT INTO app.supervision_curriculum_gap_snapshot" in query:
|
||||
gap_snapshot_id, submission_id, content_hash = args[0], args[1], args[2]
|
||||
self.gap_rows[submission_id] = (gap_snapshot_id, content_hash)
|
||||
return
|
||||
raise AssertionError(f"unexpected execute: {query}")
|
||||
|
||||
async def fetchrow(self, query: str, *args: object) -> Mapping[str, object] | None:
|
||||
if "app.supervision_curriculum_gap_snapshot" in query:
|
||||
submission_id = args[0]
|
||||
if submission_id in self.gap_rows:
|
||||
gap_snapshot_id, content_hash = self.gap_rows[submission_id]
|
||||
return {"gap_snapshot_id": gap_snapshot_id, "content_hash": content_hash}
|
||||
return None
|
||||
if "app.supervision_evidence_pointer" in query:
|
||||
pointer_id = args[0]
|
||||
if pointer_id in self.pointer_rows:
|
||||
return {"content_hash": self.pointer_rows[pointer_id]}
|
||||
return None
|
||||
raise AssertionError(f"unexpected fetchrow: {query}")
|
||||
|
|
|
|||
|
|
@ -380,6 +380,85 @@ class VoiceWebSocketContractTest(unittest.IsolatedAsyncioTestCase):
|
|||
self.assertEqual(response.headers["x-vignette-tts-provider"], "openai")
|
||||
self.assertEqual(synthesized, [("내담자 응답", VOICE_PRESET)])
|
||||
|
||||
async def test_text_turn_speech_logs_warning_and_returns_502_on_tts_failure(
|
||||
self,
|
||||
) -> None:
|
||||
session = SimpleNamespace(
|
||||
persona=SimpleNamespace(code="P1"),
|
||||
turns=[
|
||||
TurnRecord(
|
||||
turn_seq=4,
|
||||
speaker="client",
|
||||
stage="초기",
|
||||
text="내담자 응답",
|
||||
text_masked="내담자 응답",
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
async def synthesize(text: str, voice: VoicePreset):
|
||||
raise RuntimeError("upstream tts outage")
|
||||
yield # pragma: no cover - makes this an async generator
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
voice_routes,
|
||||
"_practice_access_error",
|
||||
AsyncMock(return_value=None),
|
||||
),
|
||||
patch.object(
|
||||
voice_routes.turn_runtime,
|
||||
"load_owned_session",
|
||||
AsyncMock(return_value=(session, None)),
|
||||
),
|
||||
patch.object(
|
||||
voice_routes,
|
||||
"_resolve_session_voice",
|
||||
AsyncMock(return_value=VOICE_PRESET),
|
||||
),
|
||||
patch.object(
|
||||
voice_routes.voice_service,
|
||||
"is_available",
|
||||
return_value=True,
|
||||
),
|
||||
patch.object(
|
||||
voice_routes.voice_service,
|
||||
"tts_provider",
|
||||
return_value="openai",
|
||||
),
|
||||
patch.object(
|
||||
voice_routes.voice_service,
|
||||
"tts_available",
|
||||
return_value=True,
|
||||
),
|
||||
patch.object(
|
||||
voice_routes.voice_service,
|
||||
"tts_provider_for_voice",
|
||||
return_value="openai",
|
||||
),
|
||||
patch.object(
|
||||
voice_routes.voice_service,
|
||||
"synthesize_stream",
|
||||
new=synthesize,
|
||||
),
|
||||
self.assertLogs(voice_routes.logger, level="WARNING") as captured,
|
||||
):
|
||||
with self.assertRaises(HTTPException) as raised:
|
||||
await voice_routes.voice_speech(
|
||||
voice_routes.VoiceSpeechRequest(
|
||||
session_id=SESSION_ID, turn_seq=4
|
||||
),
|
||||
_principal(),
|
||||
)
|
||||
|
||||
self.assertEqual(raised.exception.status_code, 502)
|
||||
self.assertTrue(
|
||||
any("TTS 합성 실패" in message for message in captured.output)
|
||||
)
|
||||
self.assertTrue(
|
||||
any("upstream tts outage" in message for message in captured.output)
|
||||
)
|
||||
|
||||
async def test_audio_start_binary_chunks_audio_end_ping_close_contract(
|
||||
self,
|
||||
) -> None:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue