github-actions[bot] commited on
Commit
be69d1e
·
1 Parent(s): 6437539

Automated Deploy: 4a6a58c601a16c2489b51a7644dbeed2347a2eb2

Browse files
AI-coach-agent/docs/SWING_REPORT_API.md CHANGED
@@ -19,7 +19,7 @@ Authorization: Bearer <access_token>
19
  ```
20
 
21
  - The request body is the ML API's `SwingAnalysisPayload` (contract `1.0`), unchanged.
22
- - The response is `200` with the report below. The call is synchronous and takes a few seconds. The report is also saved on the session, and `GET /v1/sessions/{id}` returns it as `report`.
23
  - The backend takes `level` and `height_cm` from the session's athlete, so the ML payload needs no extra fields. `batting_hand` comes from the payload's `athlete.batting_hand` when set (it is the side actually analysed), otherwise from the session athlete's `bats` (L or R), otherwise from the payload's `lead_foot`.
24
  - Sending the same `analysis_id` + `analysis_revision` again returns the stored report, with no new model call.
25
  - An older revision is refused with `409`.
 
19
  ```
20
 
21
  - The request body is the ML API's `SwingAnalysisPayload` (contract `1.0`), unchanged.
22
+ - By default the report is queued: the response is `202` `{session_id, status}` and the owner is notified when the report is saved (see `backend/docs/FRONTEND_INTEGRATION.md` §5). With `?queue=false` the call is synchronous: the response is `200` with the report below and takes a few seconds. The report is also saved on the session, and `GET /v1/sessions/{id}` returns it as `report`.
23
  - The backend takes `level` and `height_cm` from the session's athlete, so the ML payload needs no extra fields. `batting_hand` comes from the payload's `athlete.batting_hand` when set (it is the side actually analysed), otherwise from the session athlete's `bats` (L or R), otherwise from the payload's `lead_foot`.
24
  - Sending the same `analysis_id` + `analysis_revision` again returns the stored report, with no new model call.
25
  - An older revision is refused with `409`.
backend/app/core/database.py CHANGED
@@ -1,13 +1,24 @@
1
- """Async engine, session factory and the per-request unit of work."""
2
 
 
 
 
 
 
3
  import uuid
4
  from collections.abc import AsyncIterator
5
  from functools import lru_cache
6
 
 
 
 
7
  from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
8
 
9
  from app.core.config import get_settings
10
 
 
 
 
11
 
12
  @lru_cache
13
  def get_engine() -> AsyncEngine:
@@ -16,9 +27,30 @@ def get_engine() -> AsyncEngine:
16
  if settings.database_transaction_pooler:
17
  connect_args = {"statement_cache_size": 0,
18
  "prepared_statement_name_func": lambda: f"__asyncpg_{uuid.uuid4().hex}__"}
19
- return create_async_engine(
20
  settings.database_url, pool_size=settings.database_pool_size, max_overflow=settings.database_max_overflow,
21
- pool_timeout=settings.database_pool_timeout_s, pool_pre_ping=True, connect_args=connect_args)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
 
23
 
24
  @lru_cache
@@ -26,9 +58,15 @@ def get_session_factory() -> async_sessionmaker[AsyncSession]:
26
  return async_sessionmaker(get_engine(), expire_on_commit=False)
27
 
28
 
29
- async def get_db() -> AsyncIterator[AsyncSession]:
30
- """One transaction per request: commit when the handler succeeds, roll back on any error."""
31
- async with get_session_factory()() as session:
 
 
 
 
 
 
32
  try:
33
  yield session
34
  await session.commit()
 
1
+ """Async engine, session factory and the per-request unit of work.
2
 
3
+ The database is a network hop away, so each round trip costs far more than the query itself. Requests therefore
4
+ avoid the round trips that carry no query: the per-checkout ping, and BEGIN/COMMIT around reads.
5
+ """
6
+
7
+ import time
8
  import uuid
9
  from collections.abc import AsyncIterator
10
  from functools import lru_cache
11
 
12
+ from fastapi import Request
13
+ from sqlalchemy import event
14
+ from sqlalchemy.exc import DisconnectionError
15
  from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine
16
 
17
  from app.core.config import get_settings
18
 
19
+ # A connection used this recently is assumed alive; one idle for longer is pinged before reuse.
20
+ IDLE_PING_AFTER_S = 30.0
21
+
22
 
23
  @lru_cache
24
  def get_engine() -> AsyncEngine:
 
27
  if settings.database_transaction_pooler:
28
  connect_args = {"statement_cache_size": 0,
29
  "prepared_statement_name_func": lambda: f"__asyncpg_{uuid.uuid4().hex}__"}
30
+ engine = create_async_engine(
31
  settings.database_url, pool_size=settings.database_pool_size, max_overflow=settings.database_max_overflow,
32
+ pool_timeout=settings.database_pool_timeout_s, connect_args=connect_args)
33
+
34
+ # pool_pre_ping costs three round trips (BEGIN, ping, ROLLBACK) on every checkout, so ping idle connections only.
35
+ @event.listens_for(engine.sync_engine, "checkin")
36
+ def mark_idle(dbapi_connection, record):
37
+ record.info["idle_since"] = time.monotonic()
38
+
39
+ @event.listens_for(engine.sync_engine, "checkout")
40
+ def ping_if_idle(dbapi_connection, record, proxy):
41
+ if time.monotonic() - record.info.get("idle_since", float("inf")) > IDLE_PING_AFTER_S:
42
+ try:
43
+ dbapi_connection.ping()
44
+ except Exception as exc:
45
+ raise DisconnectionError() from exc # the pool discards it and checks out a fresh connection
46
+
47
+ return engine
48
+
49
+
50
+ @lru_cache
51
+ def get_autocommit_engine() -> AsyncEngine:
52
+ """The same pool without BEGIN/COMMIT: for reads and single-statement writes."""
53
+ return get_engine().execution_options(isolation_level="AUTOCOMMIT")
54
 
55
 
56
  @lru_cache
 
58
  return async_sessionmaker(get_engine(), expire_on_commit=False)
59
 
60
 
61
+ async def get_db(request: Request) -> AsyncIterator[AsyncSession]:
62
+ """One transaction per request: commit when the handler succeeds, roll back on any error.
63
+
64
+ GET and HEAD run in autocommit. They only read, and under READ COMMITTED each statement sees its own snapshot
65
+ with or without a transaction, so this saves two round trips and changes no result. A GET handler that
66
+ writes more than one statement must not rely on this session for atomicity.
67
+ """
68
+ read_only = request.method in ("GET", "HEAD")
69
+ async with get_session_factory()(**({"bind": get_autocommit_engine()} if read_only else {})) as session:
70
  try:
71
  yield session
72
  await session.commit()
backend/app/main.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  import re
4
  import uuid
 
5
 
6
  from ai_coach.config import get_settings as get_coach_settings
7
  from ai_coach.pitch_report.v1_1.contract import PitchPayload
@@ -31,6 +32,7 @@ from app.modules.reporting.controller import router as reporting_router
31
  from app.modules.reviews.controller import router as reviews_router
32
  from app.modules.sessions.controller import router as sessions_router
33
  from app.modules.settings.controller import router as settings_router
 
34
  from app.modules.swing_reports.controller import pitch_router as pitch_reports_router
35
  from app.modules.swing_reports.controller import router as swing_reports_router
36
  from app.modules.teams.controller import router as teams_router
@@ -46,6 +48,12 @@ ROUTERS = (
46
  )
47
 
48
 
 
 
 
 
 
 
49
  def create_app() -> FastAPI:
50
  settings = get_settings()
51
  if settings.env == "prod" and not get_coach_settings().llm_enabled:
@@ -53,6 +61,7 @@ def create_app() -> FastAPI:
53
  app = FastAPI(
54
  title="Cognivision Baseball API",
55
  version="0.1.0",
 
56
  docs_url=None if settings.env == "prod" else "/docs",
57
  openapi_url=None if settings.env == "prod" else "/openapi.json",
58
  )
 
2
 
3
  import re
4
  import uuid
5
+ from contextlib import asynccontextmanager
6
 
7
  from ai_coach.config import get_settings as get_coach_settings
8
  from ai_coach.pitch_report.v1_1.contract import PitchPayload
 
32
  from app.modules.reviews.controller import router as reviews_router
33
  from app.modules.sessions.controller import router as sessions_router
34
  from app.modules.settings.controller import router as settings_router
35
+ from app.modules.swing_reports import queue as report_queue
36
  from app.modules.swing_reports.controller import pitch_router as pitch_reports_router
37
  from app.modules.swing_reports.controller import router as swing_reports_router
38
  from app.modules.teams.controller import router as teams_router
 
48
  )
49
 
50
 
51
+ @asynccontextmanager
52
+ async def lifespan(app: FastAPI):
53
+ report_queue.kick() # pick up reports that were still queued when the last process stopped
54
+ yield
55
+
56
+
57
  def create_app() -> FastAPI:
58
  settings = get_settings()
59
  if settings.env == "prod" and not get_coach_settings().llm_enabled:
 
61
  app = FastAPI(
62
  title="Cognivision Baseball API",
63
  version="0.1.0",
64
+ lifespan=lifespan,
65
  docs_url=None if settings.env == "prod" else "/docs",
66
  openapi_url=None if settings.env == "prod" else "/openapi.json",
67
  )
backend/app/modules/accounts/service.py CHANGED
@@ -55,7 +55,9 @@ class AccountService:
55
  access = CoachAccessOut(status=latest.status, code=latest.code, sent_at=latest.created_at)
56
  capabilities = CapabilitiesOut(player=account.role == "player", coach=staff is not None,
57
  academy_admin=staff is not None and staff.is_admin, corporate_view=False)
58
- return MeOut(user=await self.user(account), team=team,
 
 
59
  entitlement=await EntitlementService(self.db).get(account.id),
60
  academy=academy, coach_access=access, capabilities=capabilities)
61
 
 
55
  access = CoachAccessOut(status=latest.status, code=latest.code, sent_at=latest.created_at)
56
  capabilities = CapabilitiesOut(player=account.role == "player", coach=staff is not None,
57
  academy_admin=staff is not None and staff.is_admin, corporate_view=False)
58
+ # A player's team was just loaded, so its code needs no second query.
59
+ user = UserOut.build(account, team.code) if team and account.role == "player" else await self.user(account)
60
+ return MeOut(user=user, team=team,
61
  entitlement=await EntitlementService(self.db).get(account.id),
62
  academy=academy, coach_access=access, capabilities=capabilities)
63
 
backend/app/modules/api_audit/service.py CHANGED
@@ -5,7 +5,7 @@ import logging
5
 
6
  from app.common.schemas import Page
7
  from app.core.config import get_settings
8
- from app.core.database import get_session_factory
9
  from app.core.errors import ValidationFailed
10
  from app.core.pagination import paginate
11
  from app.modules.api_audit.models import ApiRequestLog
@@ -18,7 +18,8 @@ log = logging.getLogger(__name__)
18
  async def write_record(record: dict) -> None:
19
  try:
20
  async with asyncio.timeout(get_settings().api_audit_write_timeout_s):
21
- async with get_session_factory()() as db:
 
22
  db.add(ApiRequestLog(**record))
23
  await db.commit()
24
  except Exception as exc:
 
5
 
6
  from app.common.schemas import Page
7
  from app.core.config import get_settings
8
+ from app.core.database import get_autocommit_engine, get_session_factory
9
  from app.core.errors import ValidationFailed
10
  from app.core.pagination import paginate
11
  from app.modules.api_audit.models import ApiRequestLog
 
18
  async def write_record(record: dict) -> None:
19
  try:
20
  async with asyncio.timeout(get_settings().api_audit_write_timeout_s):
21
+ # One INSERT is atomic on its own; autocommit saves the BEGIN and COMMIT round trips.
22
+ async with get_session_factory()(bind=get_autocommit_engine()) as db:
23
  db.add(ApiRequestLog(**record))
24
  await db.commit()
25
  except Exception as exc:
backend/app/modules/billing/entitlement.py CHANGED
@@ -34,20 +34,20 @@ class Entitlement(ResponseModel):
34
  class EntitlementService:
35
  db: AsyncSession
36
 
37
- async def is_pro(self, account_id: UUID) -> bool:
38
- now = datetime.now(UTC)
39
- return bool(await self.db.scalar(select(exists().where(
40
- Subscription.account_id == account_id,
41
- Subscription.status.in_(("active", "grace")),
42
- Subscription.expires_at > now,
43
- ))))
44
-
45
  async def get(self, account_id: UUID) -> Entitlement:
46
  settings = get_settings()
47
- since = datetime.now(UTC) - timedelta(days=settings.entitlement_window_days)
48
- used = await self.db.scalar(select(func.count()).where(
49
- SwingSession.owner_id == account_id, SwingSession.analyzed_at >= since)) or 0
50
- if await self.is_pro(account_id):
 
 
 
 
 
 
 
 
51
  return Entitlement(plan="pro", weekly_limit=None, used_this_week=used, left=None,
52
  window_days=settings.entitlement_window_days)
53
  limit = FREE_WEEKLY_LIMIT
 
34
  class EntitlementService:
35
  db: AsyncSession
36
 
 
 
 
 
 
 
 
 
37
  async def get(self, account_id: UUID) -> Entitlement:
38
  settings = get_settings()
39
+ now = datetime.now(UTC)
40
+ # One statement for both facts: each extra statement is a network round trip.
41
+ used, pro = (await self.db.execute(select(
42
+ select(func.count()).where(
43
+ SwingSession.owner_id == account_id,
44
+ SwingSession.analyzed_at >= now - timedelta(days=settings.entitlement_window_days)).scalar_subquery(),
45
+ exists().where(
46
+ Subscription.account_id == account_id,
47
+ Subscription.status.in_(("active", "grace")),
48
+ Subscription.expires_at > now),
49
+ ))).one()
50
+ if pro:
51
  return Entitlement(plan="pro", weekly_limit=None, used_this_week=used, left=None,
52
  window_days=settings.entitlement_window_days)
53
  limit = FREE_WEEKLY_LIMIT
backend/app/modules/sessions/models.py CHANGED
@@ -25,6 +25,9 @@ from app.common.base_model import Base, CreatedAtMixin, IdMixin
25
  class SwingSession(IdMixin, CreatedAtMixin, Base):
26
  """One recorded rep. status is derived: pending until analyzed_at is set, then done.
27
 
 
 
 
28
  athlete is a snapshot of the person on camera; marks are the user's four marks;
29
  measurement_payload is the ML API's contract 1.0 payload; report is the AI coach swing report.
30
  """
@@ -36,6 +39,7 @@ class SwingSession(IdMixin, CreatedAtMixin, Base):
36
  Index("ix_sessions_owner_id_analyzed_at", "owner_id", "analyzed_at",
37
  postgresql_where=text("deleted_at IS NULL")),
38
  Index("ix_sessions_pending_created_at", "created_at", postgresql_where=text("analyzed_at IS NULL")),
 
39
  )
40
 
41
  owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))
@@ -55,8 +59,15 @@ class SwingSession(IdMixin, CreatedAtMixin, Base):
55
  SmallInteger, Computed("((report ->> 'overall_score'))::smallint", persisted=True)
56
  )
57
  analyzed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
 
 
 
58
  deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
59
 
60
  @property
61
  def status(self) -> str:
62
- return "done" if self.analyzed_at else "pending"
 
 
 
 
 
25
  class SwingSession(IdMixin, CreatedAtMixin, Base):
26
  """One recorded rep. status is derived: pending until analyzed_at is set, then done.
27
 
28
+ queued_payload holds an ML payload waiting for the report worker (status queued); report_error is the code of
29
+ the last queued build that failed (status failed until a report exists).
30
+
31
  athlete is a snapshot of the person on camera; marks are the user's four marks;
32
  measurement_payload is the ML API's contract 1.0 payload; report is the AI coach swing report.
33
  """
 
39
  Index("ix_sessions_owner_id_analyzed_at", "owner_id", "analyzed_at",
40
  postgresql_where=text("deleted_at IS NULL")),
41
  Index("ix_sessions_pending_created_at", "created_at", postgresql_where=text("analyzed_at IS NULL")),
42
+ Index("ix_sessions_queued_created_at", "created_at", postgresql_where=text("queued_payload IS NOT NULL")),
43
  )
44
 
45
  owner_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), ForeignKey("accounts.id", ondelete="CASCADE"))
 
59
  SmallInteger, Computed("((report ->> 'overall_score'))::smallint", persisted=True)
60
  )
61
  analyzed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
62
+ # none_as_null: clearing it must store SQL NULL, because the queue is "queued_payload IS NOT NULL".
63
+ queued_payload: Mapped[dict | None] = mapped_column(JSONB(none_as_null=True))
64
+ report_error: Mapped[str | None] = mapped_column(String(64))
65
  deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
66
 
67
  @property
68
  def status(self) -> str:
69
+ if self.queued_payload is not None:
70
+ return "queued"
71
+ if self.analyzed_at:
72
+ return "done"
73
+ return "failed" if self.report_error else "pending"
backend/app/modules/sessions/schemas.py CHANGED
@@ -116,6 +116,7 @@ class SessionOut(ResponseModel):
116
  fps: int
117
  marks: dict
118
  report: dict | None
 
119
  review: ReviewOut | None
120
  media: MediaOut
121
  previous: PreviousOut | None
 
116
  fps: int
117
  marks: dict
118
  report: dict | None
119
+ report_error: str | None = None
120
  review: ReviewOut | None
121
  media: MediaOut
122
  previous: PreviousOut | None
backend/app/modules/sessions/service.py CHANGED
@@ -181,7 +181,8 @@ class SessionService:
181
  created_at=s.created_at, analyzed_at=s.analyzed_at,
182
  athlete=s.athlete if include_body_data else _without_body_data(s.athlete),
183
  duration_sec=float(s.duration_sec), fps=s.fps, marks=s.marks,
184
- report=report_for_read(s.mode, s.report, s.measurement_payload), review=review,
 
185
  media=MediaOut(
186
  video_url=self.storage.presign_get(keys[s.video_upload_id]),
187
  thumbnail_url=self.storage.presign_get(thumb_key) if thumb_key else None,
 
181
  created_at=s.created_at, analyzed_at=s.analyzed_at,
182
  athlete=s.athlete if include_body_data else _without_body_data(s.athlete),
183
  duration_sec=float(s.duration_sec), fps=s.fps, marks=s.marks,
184
+ report=report_for_read(s.mode, s.report, s.measurement_payload), report_error=s.report_error,
185
+ review=review,
186
  media=MediaOut(
187
  video_url=self.storage.presign_get(keys[s.video_upload_id]),
188
  thumbnail_url=self.storage.presign_get(thumb_key) if thumb_key else None,
backend/app/modules/swing_reports/controller.py CHANGED
@@ -1,6 +1,10 @@
1
  """H1: POST /v1/sessions/{session_id}/swing-report (contract 1.0/1.1) and /pitch-report (pitch-1.1).
2
 
3
  The body is the ML API's payload, unchanged. Pitch-1.1 returns the pitching report extension.
 
 
 
 
4
  """
5
 
6
  import uuid
@@ -9,9 +13,12 @@ from uuid import UUID
9
 
10
  from ai_coach.pitch_report.v1_1.schemas import PitchReport
11
  from fastapi import APIRouter, Body, Depends, Request
 
12
 
 
13
  from app.core.dependencies import CurrentAccount, Db
14
  from app.core.errors import TooLarge
 
15
  from app.modules.swing_reports.schemas import SwingReportOut
16
  from app.modules.swing_reports.service import SwingReportService
17
 
@@ -21,10 +28,28 @@ pitch_router = APIRouter(prefix="/v1", tags=["pitch reports"])
21
  MAX_PAYLOAD_BYTES = 256 * 1024 # a contract payload is a few kilobytes
22
 
23
 
 
 
 
 
 
 
 
 
24
  def get_swing_report_service(db: Db) -> SwingReportService:
25
  return SwingReportService(db)
26
 
27
 
 
 
 
 
 
 
 
 
 
 
28
  @pitch_router.post("/sessions/{session_id}/pitch-report/retry-coaching", response_model=PitchReport,
29
  response_model_exclude_unset=True)
30
  async def retry_pitch_coaching(
@@ -42,24 +67,26 @@ async def payload_size_ok(request: Request) -> None:
42
  raise TooLarge("The payload is too large.")
43
 
44
 
45
- @router.post("/sessions/{session_id}/swing-report", response_model=SwingReportOut,
46
  dependencies=[Depends(payload_size_ok)])
47
  async def create_swing_report(
48
- session_id: UUID, request: Request, account: CurrentAccount,
49
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
50
- payload: Annotated[Any, Body()],
51
- ) -> dict:
52
  request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
53
- return await service.create(account, session_id, payload, request_id)
 
54
 
55
 
56
  @pitch_router.post("/sessions/{session_id}/pitch-report", response_model=PitchReport | SwingReportOut,
57
- response_model_exclude_unset=True,
58
  dependencies=[Depends(payload_size_ok)])
59
  async def create_pitch_report(
60
- session_id: UUID, request: Request, account: CurrentAccount,
61
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
62
- payload: Annotated[Any, Body()],
63
- ) -> dict:
64
  request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
65
- return await service.create_pitch(account, session_id, payload, request_id)
 
 
1
  """H1: POST /v1/sessions/{session_id}/swing-report (contract 1.0/1.1) and /pitch-report (pitch-1.1).
2
 
3
  The body is the ML API's payload, unchanged. Pitch-1.1 returns the pitching report extension.
4
+
5
+ By default the report is built in the background: the response is 202 with the session status, and the owner gets
6
+ a "result" notification when the report is saved (or when the build failed). ?queue=false builds it in the request
7
+ and returns the report (200), for a caller that waits on screen.
8
  """
9
 
10
  import uuid
 
13
 
14
  from ai_coach.pitch_report.v1_1.schemas import PitchReport
15
  from fastapi import APIRouter, Body, Depends, Request
16
+ from fastapi.responses import JSONResponse
17
 
18
+ from app.common.schemas import ResponseModel
19
  from app.core.dependencies import CurrentAccount, Db
20
  from app.core.errors import TooLarge
21
+ from app.modules.swing_reports import queue as report_queue
22
  from app.modules.swing_reports.schemas import SwingReportOut
23
  from app.modules.swing_reports.service import SwingReportService
24
 
 
28
  MAX_PAYLOAD_BYTES = 256 * 1024 # a contract payload is a few kilobytes
29
 
30
 
31
+ class ReportQueued(ResponseModel):
32
+ session_id: UUID
33
+ status: str # "queued", or "done" when this revision already has its report
34
+
35
+
36
+ QUEUED = {202: {"model": ReportQueued, "description": "Queued (the default): the report is built in the background"}}
37
+
38
+
39
  def get_swing_report_service(db: Db) -> SwingReportService:
40
  return SwingReportService(db)
41
 
42
 
43
+ async def _respond(db: Db, session_id: UUID, report: dict | None, queue: bool):
44
+ if not queue:
45
+ return report
46
+ if report is None:
47
+ await db.commit() # the worker must see the queued payload before it is woken
48
+ report_queue.kick()
49
+ return JSONResponse(ReportQueued(session_id=session_id, status="queued" if report is None else "done")
50
+ .model_dump(mode="json"), status_code=202)
51
+
52
+
53
  @pitch_router.post("/sessions/{session_id}/pitch-report/retry-coaching", response_model=PitchReport,
54
  response_model_exclude_unset=True)
55
  async def retry_pitch_coaching(
 
67
  raise TooLarge("The payload is too large.")
68
 
69
 
70
+ @router.post("/sessions/{session_id}/swing-report", response_model=SwingReportOut, responses=QUEUED,
71
  dependencies=[Depends(payload_size_ok)])
72
  async def create_swing_report(
73
+ session_id: UUID, request: Request, account: CurrentAccount, db: Db,
74
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
75
+ payload: Annotated[Any, Body()], queue: bool = True,
76
+ ):
77
  request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
78
+ return await _respond(db, session_id, await service.create(account, session_id, payload, request_id, queue=queue),
79
+ queue)
80
 
81
 
82
  @pitch_router.post("/sessions/{session_id}/pitch-report", response_model=PitchReport | SwingReportOut,
83
+ response_model_exclude_unset=True, responses=QUEUED,
84
  dependencies=[Depends(payload_size_ok)])
85
  async def create_pitch_report(
86
+ session_id: UUID, request: Request, account: CurrentAccount, db: Db,
87
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
88
+ payload: Annotated[Any, Body()], queue: bool = True,
89
+ ):
90
  request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
91
+ return await _respond(
92
+ db, session_id, await service.create_pitch(account, session_id, payload, request_id, queue=queue), queue)
backend/app/modules/swing_reports/queue.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The report queue worker: background tasks in the API process that build queued reports one at a time.
2
+
3
+ The queue is the sessions table (queued_payload), so it survives restarts and needs no extra service. kick() is
4
+ called after a payload is queued and once at startup. Rows are claimed with FOR UPDATE SKIP LOCKED, so several API
5
+ processes can run workers side by side.
6
+ """
7
+
8
+ import asyncio
9
+ import logging
10
+
11
+ from app.core.database import get_session_factory
12
+ from app.integrations.push import get_push_client
13
+ from app.modules.swing_reports.service import SwingReportService
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+ # Reports built at once per API process. Each holds one database connection and one model call for its build,
18
+ # so this stays well under the connection pool.
19
+ MAX_WORKERS = 2
20
+ WORKERS: set[asyncio.Task] = set()
21
+
22
+
23
+ async def build_next() -> bool:
24
+ async with get_session_factory()() as db:
25
+ built = await SwingReportService(db).build_next_queued(get_push_client())
26
+ await db.commit()
27
+ return built
28
+
29
+
30
+ async def _drain() -> None:
31
+ task = asyncio.current_task()
32
+ try:
33
+ while True:
34
+ while await build_next():
35
+ pass
36
+ # Leave the pool before the last look: a payload queued during the empty poll above either finds room
37
+ # for its own worker or is caught here.
38
+ WORKERS.discard(task)
39
+ if not await build_next():
40
+ return
41
+ WORKERS.add(task)
42
+ except Exception:
43
+ log.exception("report worker stopped; queued sessions wait for the next kick or restart")
44
+ finally:
45
+ WORKERS.discard(task)
46
+
47
+
48
+ def kick() -> None:
49
+ """Make sure a worker is looking at the queue. Call after the queued payload is committed."""
50
+ if len(WORKERS) < MAX_WORKERS:
51
+ WORKERS.add(asyncio.create_task(_drain()))
backend/app/modules/swing_reports/repository.py CHANGED
@@ -1,6 +1,6 @@
1
  from uuid import UUID
2
 
3
- from sqlalchemy import select
4
 
5
  from app.common.base_repository import BaseRepository
6
  from app.modules.sessions.models import SwingSession
@@ -15,3 +15,16 @@ class SwingReportRepository(BaseRepository[SwingSession]):
15
  select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None))
16
  .with_for_update())
17
  return result.scalars().first()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from uuid import UUID
2
 
3
+ from sqlalchemy import func, select
4
 
5
  from app.common.base_repository import BaseRepository
6
  from app.modules.sessions.models import SwingSession
 
15
  select(SwingSession).where(SwingSession.id == session_id, SwingSession.deleted_at.is_(None))
16
  .with_for_update())
17
  return result.scalars().first()
18
+
19
+ async def next_queued(self) -> SwingSession | None:
20
+ """The oldest queued session no other worker holds, locked until this worker commits."""
21
+ return await self.session.scalar(
22
+ select(SwingSession).where(SwingSession.queued_payload.is_not(None), SwingSession.deleted_at.is_(None))
23
+ .order_by(SwingSession.created_at, SwingSession.id).limit(1).with_for_update(skip_locked=True))
24
+
25
+ async def queued_first_reports(self, owner_id: UUID, except_id: UUID) -> int:
26
+ """Queued sessions that will each use one analysis from the plan once they are built."""
27
+ return await self.session.scalar(select(func.count()).where(
28
+ SwingSession.owner_id == owner_id, SwingSession.queued_payload.is_not(None),
29
+ SwingSession.analyzed_at.is_(None), SwingSession.deleted_at.is_(None),
30
+ SwingSession.id != except_id)) or 0
backend/app/modules/swing_reports/service.py CHANGED
@@ -7,9 +7,14 @@ Revision rules: the same analysis_id and revision returns the stored report (no
7
  revision is refused (STALE_REVISION); a higher one rebuilds and replaces; another analysis_id is refused
8
  (ANALYSIS_MISMATCH). Only the first report of a session counts toward the plan.
9
  An obsolete pitch-1.1 report is rebuilt from the same saved measurements to remove legacy visual coaching.
 
 
 
 
10
  """
11
 
12
  import asyncio
 
13
  from collections.abc import Callable
14
  from dataclasses import dataclass
15
  from datetime import UTC, datetime
@@ -22,11 +27,14 @@ from ai_coach.swing_report import AthleteContext, InvalidPayload, build_report,
22
  from sqlalchemy.ext.asyncio import AsyncSession
23
 
24
  from app.common.consent import analysis_consent_blocked
 
25
  from app.core.config import get_settings
26
- from app.core.errors import Conflict, Forbidden, NotFound, ServiceUnavailable, Unprocessable
27
  from app.integrations.pitching_reports import obsolete_pitch_coaching
 
28
  from app.modules.accounts.models import Account
29
  from app.modules.billing.entitlement import EntitlementService
 
30
  from app.modules.swing_reports.repository import SwingReportRepository
31
 
32
  LEVELS = ("youth", "high_school", "college", "adult")
@@ -34,6 +42,8 @@ HANDS = {"R": "right", "L": "left"}
34
 
35
  ReportBuilder = Callable[..., dict]
36
 
 
 
37
 
38
  def athlete_context(snapshot: dict | None) -> AthleteContext:
39
  """Session athlete snapshot -> library context. Switch hitters (S) have no fixed side; the payload says which."""
@@ -103,19 +113,51 @@ PITCH = ReportKind(mode="p", validate=validate_pitch_payload, contract="pitch an
103
 
104
 
105
  class SwingReportService:
106
- def __init__(self, db: AsyncSession, builder: ReportBuilder = build_report,
107
- pitch_builder: ReportBuilder = build_pitch_report):
108
  self.db = db
109
  self.sessions = SwingReportRepository(db)
110
  self.entitlements = EntitlementService(db)
111
- self.builder = builder
112
- self.pitch_builder = pitch_builder
 
 
 
 
 
113
 
114
- async def create(self, account: Account, session_id: UUID, payload: Any, request_id: str | None) -> dict:
115
- return await self._create(SWING, self.builder, account, session_id, payload, request_id)
 
116
 
117
- async def create_pitch(self, account: Account, session_id: UUID, payload: Any, request_id: str | None) -> dict:
118
- return await self._create(PITCH, self.pitch_builder, account, session_id, payload, request_id)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
119
 
120
  async def retry_pitch_coaching(self, account: Account, session_id: UUID, request_id: str | None,
121
  *, refresh: bool = False) -> dict:
@@ -146,7 +188,7 @@ class SwingReportService:
146
  return report
147
 
148
  async def _create(self, kind: ReportKind, builder: ReportBuilder, account: Account, session_id: UUID,
149
- payload: Any, request_id: str | None) -> dict:
150
  session = await self.sessions.get_for_update(session_id)
151
  if session is None:
152
  raise NotFound("We couldn't find that session.")
@@ -178,7 +220,16 @@ class SwingReportService:
178
  raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
179
  ensure_coach_configured()
180
  if session.analyzed_at is None:
181
- await self.entitlements.ensure_can_analyze(account.id)
 
 
 
 
 
 
 
 
 
182
 
183
  try:
184
  report = await asyncio.to_thread(builder, payload, athlete_context(session.athlete),
@@ -186,13 +237,16 @@ class SwingReportService:
186
  except InvalidPayload as exc: # defensive: the builder re-validates
187
  raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc
188
 
 
 
 
 
189
  marks = {**(session.marks or {}), **kind.marks(parsed.events)}
190
- if evidence_pitch:
191
  for key in ("contact_frame", "contact_offset", "contact_source", "stride_start_frame", "stride_end_frame",
192
  "peak_knee_height_frame", "foot_plant_frame", "ball_release_frame"):
193
  marks.pop(key, None)
194
  await self.sessions.update(
195
  session, measurement_payload=payload, report=report, analysis_id=parsed.analysis_id,
196
  analysis_revision=parsed.analysis_revision, marks=marks,
197
- analyzed_at=session.analyzed_at or datetime.now(UTC))
198
- return report
 
7
  revision is refused (STALE_REVISION); a higher one rebuilds and replaces; another analysis_id is refused
8
  (ANALYSIS_MISMATCH). Only the first report of a session counts toward the plan.
9
  An obsolete pitch-1.1 report is rebuilt from the same saved measurements to remove legacy visual coaching.
10
+
11
+ With queue=True (the endpoints' default) the same checks run in the request, but the build is left to the report
12
+ worker (queue.py): the
13
+ payload is stored on the session, the request returns at once and the owner is notified when the report is saved.
14
  """
15
 
16
  import asyncio
17
+ import logging
18
  from collections.abc import Callable
19
  from dataclasses import dataclass
20
  from datetime import UTC, datetime
 
27
  from sqlalchemy.ext.asyncio import AsyncSession
28
 
29
  from app.common.consent import analysis_consent_blocked
30
+ from app.common.notify import notify
31
  from app.core.config import get_settings
32
+ from app.core.errors import Conflict, Forbidden, NotFound, PlanLimitReached, ServiceUnavailable, Unprocessable
33
  from app.integrations.pitching_reports import obsolete_pitch_coaching
34
+ from app.integrations.push import PushClient
35
  from app.modules.accounts.models import Account
36
  from app.modules.billing.entitlement import EntitlementService
37
+ from app.modules.sessions.models import SwingSession
38
  from app.modules.swing_reports.repository import SwingReportRepository
39
 
40
  LEVELS = ("youth", "high_school", "college", "adult")
 
42
 
43
  ReportBuilder = Callable[..., dict]
44
 
45
+ log = logging.getLogger(__name__)
46
+
47
 
48
  def athlete_context(snapshot: dict | None) -> AthleteContext:
49
  """Session athlete snapshot -> library context. Switch hitters (S) have no fixed side; the payload says which."""
 
113
 
114
 
115
  class SwingReportService:
116
+ def __init__(self, db: AsyncSession, builder: ReportBuilder | None = None,
117
+ pitch_builder: ReportBuilder | None = None):
118
  self.db = db
119
  self.sessions = SwingReportRepository(db)
120
  self.entitlements = EntitlementService(db)
121
+ self.builder = builder or build_report
122
+ self.pitch_builder = pitch_builder or build_pitch_report
123
+
124
+ async def create(self, account: Account, session_id: UUID, payload: Any, request_id: str | None,
125
+ *, queue: bool = False) -> dict | None:
126
+ """The report, or None when it was queued (queue=True and a build is needed)."""
127
+ return await self._create(SWING, self.builder, account, session_id, payload, request_id, queue)
128
 
129
+ async def create_pitch(self, account: Account, session_id: UUID, payload: Any, request_id: str | None,
130
+ *, queue: bool = False) -> dict | None:
131
+ return await self._create(PITCH, self.pitch_builder, account, session_id, payload, request_id, queue)
132
 
133
+ async def build_next_queued(self, push: PushClient | None) -> bool:
134
+ """Worker step: build the oldest queued report, save it and tell the owner. False when nothing is queued.
135
+
136
+ The row stays locked for the whole build, so a crash leaves the session queued for the next worker.
137
+ """
138
+ session = await self.sessions.next_queued()
139
+ if session is None:
140
+ return False
141
+ kind, builder = (PITCH, self.pitch_builder) if session.mode == "p" else (SWING, self.builder)
142
+ payload, noun = session.queued_payload, "pitch" if session.mode == "p" else "swing"
143
+ try:
144
+ parsed, problems = kind.validate(payload)
145
+ if parsed is None:
146
+ raise InvalidPayload(problems)
147
+ report = await asyncio.to_thread(builder, payload, athlete_context(session.athlete),
148
+ request_id=f"queue-{session.id}")
149
+ except Exception:
150
+ # Failed builds leave the queue, so one bad payload cannot block it; the app posts again to retry.
151
+ log.exception("queued report for session %s failed", session.id)
152
+ await self.sessions.update(session, queued_payload=None, report_error="REPORT_FAILED")
153
+ outcome, title, body = "failed", f"We couldn't finish your {noun} report", "Open the app to try again."
154
+ else:
155
+ await self._save(session, kind, parsed, payload, report)
156
+ outcome, title, body = "ready", f"Your {noun} report is ready", "Tap to see your score and focus."
157
+ await notify(self.db, push, session.owner_id, kind="result", title=title, body=body,
158
+ target={"session_id": session.id, "mode": session.mode, "outcome": outcome},
159
+ event_key=f"report:{session.id}:{(payload or {}).get('analysis_revision')}:{outcome}")
160
+ return True
161
 
162
  async def retry_pitch_coaching(self, account: Account, session_id: UUID, request_id: str | None,
163
  *, refresh: bool = False) -> dict:
 
188
  return report
189
 
190
  async def _create(self, kind: ReportKind, builder: ReportBuilder, account: Account, session_id: UUID,
191
+ payload: Any, request_id: str | None, queue: bool = False) -> dict | None:
192
  session = await self.sessions.get_for_update(session_id)
193
  if session is None:
194
  raise NotFound("We couldn't find that session.")
 
220
  raise Forbidden("Please accept the analysis consent to continue.", code="CONSENT_REQUIRED")
221
  ensure_coach_configured()
222
  if session.analyzed_at is None:
223
+ entitlement = await self.entitlements.get(account.id)
224
+ # Queued first reports have not been counted yet, so they are reserved here.
225
+ # shortcut: two posts for different sessions at the same instant can each take the last analysis;
226
+ # lock the account row here if the limit must be exact.
227
+ waiting = await self.sessions.queued_first_reports(account.id, session.id) if queue else 0
228
+ if entitlement.left is not None and entitlement.left - waiting <= 0:
229
+ raise PlanLimitReached()
230
+ if queue:
231
+ await self.sessions.update(session, queued_payload=payload, report_error=None)
232
+ return None
233
 
234
  try:
235
  report = await asyncio.to_thread(builder, payload, athlete_context(session.athlete),
 
237
  except InvalidPayload as exc: # defensive: the builder re-validates
238
  raise Unprocessable(str(exc), code="INVALID_PAYLOAD", fields=exc.problems) from exc
239
 
240
+ await self._save(session, kind, parsed, payload, report)
241
+ return report
242
+
243
+ async def _save(self, session: SwingSession, kind: ReportKind, parsed: Any, payload: Any, report: dict) -> None:
244
  marks = {**(session.marks or {}), **kind.marks(parsed.events)}
245
+ if kind.mode == "p" and parsed.schema_version == "pitch-1.1":
246
  for key in ("contact_frame", "contact_offset", "contact_source", "stride_start_frame", "stride_end_frame",
247
  "peak_knee_height_frame", "foot_plant_frame", "ball_release_frame"):
248
  marks.pop(key, None)
249
  await self.sessions.update(
250
  session, measurement_payload=payload, report=report, analysis_id=parsed.analysis_id,
251
  analysis_revision=parsed.analysis_revision, marks=marks,
252
+ analyzed_at=session.analyzed_at or datetime.now(UTC), queued_payload=None, report_error=None)
 
backend/docs/FRONTEND_INTEGRATION.md CHANGED
@@ -163,7 +163,14 @@ The app calls the ML API itself. Our backend never calls the ML API: the app for
163
  - For `is_self: true`, send `athlete: null`; the server snapshots the profile.
164
  - For someone else's swing, send `{name, age, height_cm, weight_kg, bats, throws, level}`; all are required.
165
  - **Plan:** the free plan allows 20 analysed swings in a rolling 7 days, counting swings filmed for someone else. Step 3 returns 402 `PLAN_LIMIT` before anything is stored. Pending sessions that never get a report don't count, and are deleted with their media after 24 h.
166
- - **No polling:** the Analyzing screen waits on steps 4 and 5. There is no `queued` or `processing` status: a session is `pending` until its report exists, then `done`.
 
 
 
 
 
 
 
167
  - **Pitching:** for a `mode:"p"` session, step 5 is `POST /v1/sessions/{id}/pitch-report` with the ML pitch payload (contract `pitch-1.1`, see `AI-coach-agent/docs/PITCH_REPORT_API.md`). It returns the pitching report, with the groups `gather`, `stride_plant`, `rotation_release` and `release_finish`, and the same revision, plan and consent rules. Posting to the wrong endpoint for the session mode returns 422 `MODE_NOT_SUPPORTED`. The throwing side comes from the payload's `athlete.throwing_hand`, then the session athlete's `throws`.
168
  - **Re-analysis:** post a payload with a higher `analysis_revision` and the same `analysis_id`.
169
  - Re-posting the same id and revision is safe: it returns the stored report.
 
163
  - For `is_self: true`, send `athlete: null`; the server snapshots the profile.
164
  - For someone else's swing, send `{name, age, height_cm, weight_kg, bats, throws, level}`; all are required.
165
  - **Plan:** the free plan allows 20 analysed swings in a rolling 7 days, counting swings filmed for someone else. Step 3 returns 402 `PLAN_LIMIT` before anything is stored. Pending sessions that never get a report don't count, and are deleted with their media after 24 h.
166
+ - **Reports are queued (default):** step 5 (`/swing-report` or `/pitch-report`) does not return the report. The player can keep recording swing after swing and does not have to keep the screen open.
167
+ - The checks run in the request, so 402, 403, 409 and 422 answer immediately.
168
+ - The response is **202** `{"session_id":"...","status":"queued"}`. The status is `"done"` when this revision already has its report; nothing is queued then.
169
+ - The backend builds queued reports in the background, oldest first. There is no limit on how many a player can queue, apart from the plan: queued swings count toward the weekly limit as soon as they are queued.
170
+ - When a report is saved the owner gets a notification of kind `result` with `target: {"session_id", "mode", "outcome":"ready"}` and a push (unless `notify_results` is off). Route it to Result by `session_id` (§14.5), then read the report from `GET /v1/sessions/{id}`.
171
+ - If the build fails the notification has `outcome:"failed"`, and the session shows `status:"failed"` with `report_error:"REPORT_FAILED"`. Post the payload again to retry.
172
+ - Session statuses are `pending` (no payload posted yet), `queued`, `done` and `failed`, on `GET /v1/sessions/{id}` and the session list.
173
+ - **Waiting on screen instead:** add `?queue=false` to step 5. The report is built in the request and returned with **200**, as before; no notification is sent. **App builds released before queueing must add `?queue=false` or handle the 202**, otherwise they receive no report body.
174
  - **Pitching:** for a `mode:"p"` session, step 5 is `POST /v1/sessions/{id}/pitch-report` with the ML pitch payload (contract `pitch-1.1`, see `AI-coach-agent/docs/PITCH_REPORT_API.md`). It returns the pitching report, with the groups `gather`, `stride_plant`, `rotation_release` and `release_finish`, and the same revision, plan and consent rules. Posting to the wrong endpoint for the session mode returns 422 `MODE_NOT_SUPPORTED`. The throwing side comes from the payload's `athlete.throwing_hand`, then the session athlete's `throws`.
175
  - **Re-analysis:** post a payload with a higher `analysis_revision` and the same `analysis_id`.
176
  - Re-posting the same id and revision is safe: it returns the stored report.
backend/docs/openapi.json CHANGED
@@ -1256,6 +1256,16 @@
1256
  "title": "Session Id"
1257
  }
1258
  },
 
 
 
 
 
 
 
 
 
 
1259
  {
1260
  "name": "authorization",
1261
  "in": "header",
@@ -1294,6 +1304,16 @@
1294
  }
1295
  }
1296
  },
 
 
 
 
 
 
 
 
 
 
1297
  "400": {
1298
  "description": "Error",
1299
  "content": {
@@ -1414,6 +1434,16 @@
1414
  "title": "Session Id"
1415
  }
1416
  },
 
 
 
 
 
 
 
 
 
 
1417
  {
1418
  "name": "authorization",
1419
  "in": "header",
@@ -1460,6 +1490,16 @@
1460
  }
1461
  }
1462
  },
 
 
 
 
 
 
 
 
 
 
1463
  "400": {
1464
  "description": "Error",
1465
  "content": {
@@ -13353,6 +13393,25 @@
13353
  "title": "ReportMeta",
13354
  "type": "object"
13355
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13356
  "RequestOut": {
13357
  "properties": {
13358
  "id": {
@@ -14176,6 +14235,17 @@
14176
  ],
14177
  "description": "Null while status is pending"
14178
  },
 
 
 
 
 
 
 
 
 
 
 
14179
  "review": {
14180
  "anyOf": [
14181
  {
 
1256
  "title": "Session Id"
1257
  }
1258
  },
1259
+ {
1260
+ "name": "queue",
1261
+ "in": "query",
1262
+ "required": false,
1263
+ "schema": {
1264
+ "type": "boolean",
1265
+ "default": true,
1266
+ "title": "Queue"
1267
+ }
1268
+ },
1269
  {
1270
  "name": "authorization",
1271
  "in": "header",
 
1304
  }
1305
  }
1306
  },
1307
+ "202": {
1308
+ "description": "Queued (the default): the report is built in the background",
1309
+ "content": {
1310
+ "application/json": {
1311
+ "schema": {
1312
+ "$ref": "#/components/schemas/ReportQueued"
1313
+ }
1314
+ }
1315
+ }
1316
+ },
1317
  "400": {
1318
  "description": "Error",
1319
  "content": {
 
1434
  "title": "Session Id"
1435
  }
1436
  },
1437
+ {
1438
+ "name": "queue",
1439
+ "in": "query",
1440
+ "required": false,
1441
+ "schema": {
1442
+ "type": "boolean",
1443
+ "default": true,
1444
+ "title": "Queue"
1445
+ }
1446
+ },
1447
  {
1448
  "name": "authorization",
1449
  "in": "header",
 
1490
  }
1491
  }
1492
  },
1493
+ "202": {
1494
+ "description": "Queued (the default): the report is built in the background",
1495
+ "content": {
1496
+ "application/json": {
1497
+ "schema": {
1498
+ "$ref": "#/components/schemas/ReportQueued"
1499
+ }
1500
+ }
1501
+ }
1502
+ },
1503
  "400": {
1504
  "description": "Error",
1505
  "content": {
 
13393
  "title": "ReportMeta",
13394
  "type": "object"
13395
  },
13396
+ "ReportQueued": {
13397
+ "properties": {
13398
+ "session_id": {
13399
+ "type": "string",
13400
+ "format": "uuid",
13401
+ "title": "Session Id"
13402
+ },
13403
+ "status": {
13404
+ "type": "string",
13405
+ "title": "Status"
13406
+ }
13407
+ },
13408
+ "type": "object",
13409
+ "required": [
13410
+ "session_id",
13411
+ "status"
13412
+ ],
13413
+ "title": "ReportQueued"
13414
+ },
13415
  "RequestOut": {
13416
  "properties": {
13417
  "id": {
 
14235
  ],
14236
  "description": "Null while status is pending"
14237
  },
14238
+ "report_error": {
14239
+ "anyOf": [
14240
+ {
14241
+ "type": "string"
14242
+ },
14243
+ {
14244
+ "type": "null"
14245
+ }
14246
+ ],
14247
+ "title": "Report Error"
14248
+ },
14249
  "review": {
14250
  "anyOf": [
14251
  {
backend/e2e/qa_coach_loop.py CHANGED
@@ -193,7 +193,7 @@ def make_session(acct: dict, *, is_self=True, analyse=True, tag="") -> dict:
193
  p["swing_id"] = f"swing_{RUN_ID}_{tag}"
194
  # vary the value a bit so scores/deltas differ
195
  p["measurements"][0]["value"] = {"a": 28, "b": 45, "c": 10}.get(tag[-1:], 28)
196
- r = call("POST", f"/v1/sessions/{s['id']}/swing-report", acct["token"], json=p)
197
  check(f"POST swing-report {tag}", r.status_code == 200, r)
198
  s["report"] = r.json() if r.status_code == 200 else None
199
  time.sleep(1.1) # distinct created_at for ordering checks
 
193
  p["swing_id"] = f"swing_{RUN_ID}_{tag}"
194
  # vary the value a bit so scores/deltas differ
195
  p["measurements"][0]["value"] = {"a": 28, "b": 45, "c": 10}.get(tag[-1:], 28)
196
+ r = call("POST", f"/v1/sessions/{s['id']}/swing-report?queue=false", acct["token"], json=p)
197
  check(f"POST swing-report {tag}", r.status_code == 200, r)
198
  s["report"] = r.json() if r.status_code == 200 else None
199
  time.sleep(1.1) # distinct created_at for ordering checks
backend/e2e/qa_coaching_workflow.py CHANGED
@@ -188,7 +188,7 @@ def make_session(acct: dict, *, tag="", mode="h") -> dict:
188
  p = copy.deepcopy(PAYLOAD)
189
  p["analysis_id"] = f"qa_{RUN_ID}_{tag}"
190
  p["swing_id"] = f"swing_{RUN_ID}_{tag}"
191
- r = call("POST", f"/v1/sessions/{s['id']}/swing-report", acct, json=p)
192
  check(f"POST swing-report {tag}", r.status_code == 200, r)
193
  s["report"] = r.json() if r.status_code == 200 else None
194
  return s
 
188
  p = copy.deepcopy(PAYLOAD)
189
  p["analysis_id"] = f"qa_{RUN_ID}_{tag}"
190
  p["swing_id"] = f"swing_{RUN_ID}_{tag}"
191
+ r = call("POST", f"/v1/sessions/{s['id']}/swing-report?queue=false", acct, json=p)
192
  check(f"POST swing-report {tag}", r.status_code == 200, r)
193
  s["report"] = r.json() if r.status_code == 200 else None
194
  return s
backend/e2e/qa_sessions_reports.py CHANGED
@@ -239,7 +239,7 @@ def payload(sep=3, analysis_id=None, rev=1, hand="right", lead="left", stride=24
239
 
240
 
241
  def post_report(acct, sid, body, **kw) -> httpx.Response:
242
- return call("POST", f"/v1/sessions/{sid}/swing-report", acct["token"], json=body, **kw)
243
 
244
 
245
  TOP_KEYS = {"schema_version", "analysis_id", "analysis_revision", "overall_score", "overall_score_is_tentative",
 
239
 
240
 
241
  def post_report(acct, sid, body, **kw) -> httpx.Response:
242
+ return call("POST", f"/v1/sessions/{sid}/swing-report?queue=false", acct["token"], json=body, **kw)
243
 
244
 
245
  TOP_KEYS = {"schema_version", "analysis_id", "analysis_revision", "overall_score", "overall_score_is_tentative",
backend/migrations/versions/20261117_b4d2f6a81c35_report_queue.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Report queue: a payload waiting for the report worker and the last failure code, on the session.
2
+
3
+ Revision ID: b4d2f6a81c35
4
+ Revises: 9c1e5a7b3d20
5
+ Create Date: 2026-11-17 21:30:00
6
+ """
7
+ from collections.abc import Sequence
8
+
9
+ import sqlalchemy as sa
10
+ from alembic import op
11
+ from sqlalchemy.dialects import postgresql
12
+
13
+ revision: str = 'b4d2f6a81c35'
14
+ down_revision: str | None = '9c1e5a7b3d20'
15
+ branch_labels: str | Sequence[str] | None = None
16
+ depends_on: str | Sequence[str] | None = None
17
+
18
+
19
+ def upgrade() -> None:
20
+ op.add_column('sessions', sa.Column('queued_payload', postgresql.JSONB(astext_type=sa.Text()), nullable=True))
21
+ op.add_column('sessions', sa.Column('report_error', sa.String(length=64), nullable=True))
22
+ op.create_index('ix_sessions_queued_created_at', 'sessions', ['created_at'], unique=False,
23
+ postgresql_where=sa.text('queued_payload IS NOT NULL'))
24
+
25
+
26
+ def downgrade() -> None:
27
+ op.drop_index('ix_sessions_queued_created_at', table_name='sessions',
28
+ postgresql_where=sa.text('queued_payload IS NOT NULL'))
29
+ op.drop_column('sessions', 'report_error')
30
+ op.drop_column('sessions', 'queued_payload')
backend/tests/integration/test_database.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The request unit of work: reads carry no transaction round trips, and a dropped idle connection is replaced."""
2
+
3
+ from sqlalchemy import NullPool, event, text
4
+ from sqlalchemy.ext.asyncio import create_async_engine
5
+
6
+ from app.core import database
7
+ from app.core.config import get_settings
8
+ from app.core.database import get_engine
9
+ from tests.helpers import register
10
+
11
+
12
+ async def test_reads_skip_begin_and_commit_but_writes_stay_transactional(client):
13
+ user = await register(client)
14
+ seen = []
15
+ engine = get_engine().sync_engine
16
+
17
+ def record(conn, *_):
18
+ seen.append(conn.get_execution_options().get("isolation_level"))
19
+
20
+ event.listen(engine, "before_cursor_execute", record)
21
+ try:
22
+ assert (await client.get("/v1/me/entitlement", headers=user["headers"])).status_code == 200
23
+ assert seen and set(seen) == {"AUTOCOMMIT"} # the request's queries and its audit insert
24
+ seen.clear()
25
+ assert (await client.patch("/v1/me", headers=user["headers"], json={"unit": "metric"})).status_code == 200
26
+ assert None in seen # the write runs in a real transaction
27
+ finally:
28
+ event.remove(engine, "before_cursor_execute", record)
29
+
30
+
31
+ async def test_failed_write_is_rolled_back(client):
32
+ user = await register(client)
33
+ taken = (await register(client))["user"]["email"]
34
+ response = await client.post("/v1/auth/register", json={"email": taken, "password": "correct-horse-9",
35
+ "role": "player"})
36
+ assert response.status_code == 409
37
+ assert (await client.get("/v1/me", headers=user["headers"])).status_code == 200
38
+
39
+
40
+ async def test_dropped_idle_connection_is_replaced(client, monkeypatch):
41
+ user = await register(client)
42
+ monkeypatch.setattr(database, "IDLE_PING_AFTER_S", -1.0) # every pooled connection counts as idle
43
+ await get_engine().dispose()
44
+ assert (await client.get("/v1/me", headers=user["headers"])).status_code == 200 # fills the pool
45
+ outside = create_async_engine(get_settings().database_url, poolclass=NullPool) # not one of the pooled ones
46
+ async with outside.connect() as conn:
47
+ await conn.execute(text(
48
+ "SELECT pg_terminate_backend(pid) FROM pg_stat_activity "
49
+ "WHERE datname = current_database() AND pid <> pg_backend_pid()"))
50
+ # Without the idle ping this request would fail on a dead pooled connection.
51
+ assert (await client.get("/v1/me", headers=user["headers"])).status_code == 200
backend/tests/integration/test_pitching_flow.py CHANGED
@@ -18,10 +18,15 @@ def payload(sid, **changes):
18
  return data
19
 
20
 
21
- def url(sid):
22
  return f"/v1/sessions/{sid}/pitch-report"
23
 
24
 
 
 
 
 
 
25
  async def test_retry_unavailable_ai_preserves_evidence_usage_and_is_idempotent(client, monkeypatch):
26
  from ai_coach.pitch_report.v1_1 import service as coach_service
27
  from ai_coach.pitch_report.v1_1.coaching import VERSION
@@ -47,16 +52,16 @@ async def test_retry_unavailable_ai_preserves_evidence_usage_and_is_idempotent(c
47
  "fallback_reason": None, "text_rejections": {}}
48
 
49
  monkeypatch.setattr(coach_service, "generate_coaching", generated)
50
- retry = await client.post(url(sid) + "/retry-coaching", headers=player["headers"])
51
  assert retry.status_code == 200, retry.text
52
  assert retry.json()["coaching"]["status"] == "generated"
53
  saved = await load_session(sid)
54
  assert saved.measurement_payload == p and saved.analyzed_at == analyzed_at
55
  assert saved.report == retry.json()
56
  assert (await client.get("/v1/me/entitlement", headers=player["headers"])).json() == entitlement
57
- again = await client.post(url(sid) + "/retry-coaching", headers=player["headers"])
58
  assert again.json() == retry.json() and len(calls) == 1
59
- refreshed = await client.post(url(sid) + "/retry-coaching?refresh=true", headers=player["headers"])
60
  assert refreshed.status_code == 200 and len(calls) == 2
61
  latest = await load_session(sid)
62
  assert latest.measurement_payload == p and latest.analyzed_at == analyzed_at
@@ -66,14 +71,14 @@ async def test_retry_unavailable_ai_preserves_evidence_usage_and_is_idempotent(c
66
  async def test_retry_coaching_requires_owner_pitch_and_existing_report(client):
67
  owner, other = await make_account(), await make_account()
68
  sid = await make_session(owner["id"], mode="p")
69
- target = url(sid) + "/retry-coaching"
70
  assert (await client.post(target)).status_code == 401
71
  assert (await client.post(target, headers=other["headers"])).status_code == 403
72
  assert (await client.post(target, headers=owner["headers"])).status_code == 409
73
- missing = url(uuid.uuid4()) + "/retry-coaching"
74
  assert (await client.post(missing, headers=owner["headers"])).status_code == 404
75
  hitting = await make_session(owner["id"], mode="h")
76
- assert (await client.post(url(hitting) + "/retry-coaching", headers=owner["headers"])).status_code == 422
77
 
78
 
79
  async def test_retry_coaching_checks_current_consent_and_configuration(client, monkeypatch):
@@ -87,7 +92,7 @@ async def test_retry_coaching_checks_current_consent_and_configuration(client, m
87
  return True
88
 
89
  monkeypatch.setattr(service, "analysis_consent_blocked", blocked)
90
- target = url(sid) + "/retry-coaching"
91
  assert (await client.post(target, headers=owner["headers"])).status_code == 403
92
 
93
  async def allowed(*args):
@@ -204,7 +209,7 @@ async def test_pitch_create_and_retry_use_ml_facts_and_ignore_saved_visual_claim
204
  "observations": [{"topic": topic, "status": "observed", "description": "LEGACY_VISUAL_CLAIM",
205
  "evidence_frames": [10, 11]} for topic in ("loading", "plant", "rotation", "finish")],
206
  })
207
- for target, body in ((url(sid), p), (url(sid) + "/retry-coaching", None)):
208
  response = await client.post(target, json=body, headers=owner["headers"])
209
  assert response.status_code == 200, response.text
210
  report = response.json()
@@ -255,7 +260,7 @@ async def test_obsolete_pitch_coaching_is_rebuilt_without_new_analysis(
255
  return original_generate(parsed, rubric, **kwargs)
256
 
257
  monkeypatch.setattr(coach_service, "generate_coaching", capture)
258
- target = url(sid) + "/retry-coaching" if retry else url(sid)
259
  response = await client.post(target, json=None if retry else p, headers=owner["headers"])
260
  assert response.status_code == 200, response.text
261
  report = response.json()
 
18
  return data
19
 
20
 
21
+ def base(sid):
22
  return f"/v1/sessions/{sid}/pitch-report"
23
 
24
 
25
+ def url(sid):
26
+ """Build in the request (queue=false): these tests assert on the returned report."""
27
+ return base(sid) + "?queue=false"
28
+
29
+
30
  async def test_retry_unavailable_ai_preserves_evidence_usage_and_is_idempotent(client, monkeypatch):
31
  from ai_coach.pitch_report.v1_1 import service as coach_service
32
  from ai_coach.pitch_report.v1_1.coaching import VERSION
 
52
  "fallback_reason": None, "text_rejections": {}}
53
 
54
  monkeypatch.setattr(coach_service, "generate_coaching", generated)
55
+ retry = await client.post(base(sid) + "/retry-coaching", headers=player["headers"])
56
  assert retry.status_code == 200, retry.text
57
  assert retry.json()["coaching"]["status"] == "generated"
58
  saved = await load_session(sid)
59
  assert saved.measurement_payload == p and saved.analyzed_at == analyzed_at
60
  assert saved.report == retry.json()
61
  assert (await client.get("/v1/me/entitlement", headers=player["headers"])).json() == entitlement
62
+ again = await client.post(base(sid) + "/retry-coaching", headers=player["headers"])
63
  assert again.json() == retry.json() and len(calls) == 1
64
+ refreshed = await client.post(base(sid) + "/retry-coaching?refresh=true", headers=player["headers"])
65
  assert refreshed.status_code == 200 and len(calls) == 2
66
  latest = await load_session(sid)
67
  assert latest.measurement_payload == p and latest.analyzed_at == analyzed_at
 
71
  async def test_retry_coaching_requires_owner_pitch_and_existing_report(client):
72
  owner, other = await make_account(), await make_account()
73
  sid = await make_session(owner["id"], mode="p")
74
+ target = base(sid) + "/retry-coaching"
75
  assert (await client.post(target)).status_code == 401
76
  assert (await client.post(target, headers=other["headers"])).status_code == 403
77
  assert (await client.post(target, headers=owner["headers"])).status_code == 409
78
+ missing = base(uuid.uuid4()) + "/retry-coaching"
79
  assert (await client.post(missing, headers=owner["headers"])).status_code == 404
80
  hitting = await make_session(owner["id"], mode="h")
81
+ assert (await client.post(base(hitting) + "/retry-coaching", headers=owner["headers"])).status_code == 422
82
 
83
 
84
  async def test_retry_coaching_checks_current_consent_and_configuration(client, monkeypatch):
 
92
  return True
93
 
94
  monkeypatch.setattr(service, "analysis_consent_blocked", blocked)
95
+ target = base(sid) + "/retry-coaching"
96
  assert (await client.post(target, headers=owner["headers"])).status_code == 403
97
 
98
  async def allowed(*args):
 
209
  "observations": [{"topic": topic, "status": "observed", "description": "LEGACY_VISUAL_CLAIM",
210
  "evidence_frames": [10, 11]} for topic in ("loading", "plant", "rotation", "finish")],
211
  })
212
+ for target, body in ((url(sid), p), (base(sid) + "/retry-coaching", None)):
213
  response = await client.post(target, json=body, headers=owner["headers"])
214
  assert response.status_code == 200, response.text
215
  report = response.json()
 
260
  return original_generate(parsed, rubric, **kwargs)
261
 
262
  monkeypatch.setattr(coach_service, "generate_coaching", capture)
263
+ target = base(sid) + "/retry-coaching" if retry else url(sid)
264
  response = await client.post(target, json=None if retry else p, headers=owner["headers"])
265
  assert response.status_code == 200, response.text
266
  report = response.json()
backend/tests/integration/test_pitching_openapi.py CHANGED
@@ -89,7 +89,8 @@ async def test_real_requests_reports_and_session_envelopes_validate_against_open
89
  path = "/v1/sessions/{session_id}/" + ("swing-report" if kind == "hitting" else "pitch-report")
90
  operation = spec["paths"][path]["post"]
91
  assert_valid(spec, operation["requestBody"]["content"]["application/json"]["schema"], payload)
92
- response = await client.post(path.format(session_id=sid), json=payload, headers=owner["headers"])
 
93
  assert response.status_code == 200, response.text
94
  report = response.json()
95
  assert_valid(spec, operation["responses"]["200"]["content"]["application/json"]["schema"], report)
 
89
  path = "/v1/sessions/{session_id}/" + ("swing-report" if kind == "hitting" else "pitch-report")
90
  operation = spec["paths"][path]["post"]
91
  assert_valid(spec, operation["requestBody"]["content"]["application/json"]["schema"], payload)
92
+ response = await client.post(path.format(session_id=sid), params={"queue": "false"}, json=payload,
93
+ headers=owner["headers"])
94
  assert response.status_code == 200, response.text
95
  report = response.json()
96
  assert_valid(spec, operation["responses"]["200"]["content"]["application/json"]["schema"], report)
backend/tests/integration/test_pitching_report_provenance.py CHANGED
@@ -11,7 +11,7 @@ from app.core.database import get_session_factory
11
  from app.modules.sessions.models import SwingSession
12
  from tests.factories import make_account
13
  from tests.integration.test_coach import _team_with_player
14
- from tests.integration.test_pitching_flow import payload, url
15
  from tests.integration.test_swing_reports import load_session, make_session
16
 
17
  MARKER = "OBSOLETE_PITCHING_ADVICE"
@@ -113,7 +113,7 @@ async def test_old_ml_prompt_refreshes_on_explicit_report_write(client, monkeypa
113
  return original(parsed, rubric, **kwargs)
114
 
115
  monkeypatch.setattr(coach_service, "generate_coaching", capture)
116
- response = await client.post(url(sid) + ("/retry-coaching" if retry else ""),
117
  json=None if retry else p, headers=owner["headers"])
118
  assert response.status_code == 200, response.text
119
  report = response.json()
@@ -167,7 +167,7 @@ async def test_current_hitting_and_legacy_reports_remain_identical_on_get(client
167
  owner = await make_account()
168
  sid = await make_session(owner["id"], mode="h" if kind == "hitting" else "p")
169
  p = copy.deepcopy(PAYLOAD if kind == "hitting" else PITCH if kind == "legacy_pitch" else payload(sid))
170
- target = f"/v1/sessions/{sid}/swing-report" if kind == "hitting" else url(sid)
171
  response = await client.post(target, json=p, headers=owner["headers"])
172
  assert response.status_code == 200, response.text
173
  report = response.json()
 
11
  from app.modules.sessions.models import SwingSession
12
  from tests.factories import make_account
13
  from tests.integration.test_coach import _team_with_player
14
+ from tests.integration.test_pitching_flow import base, payload, url
15
  from tests.integration.test_swing_reports import load_session, make_session
16
 
17
  MARKER = "OBSOLETE_PITCHING_ADVICE"
 
113
  return original(parsed, rubric, **kwargs)
114
 
115
  monkeypatch.setattr(coach_service, "generate_coaching", capture)
116
+ response = await client.post(base(sid) + "/retry-coaching" if retry else url(sid),
117
  json=None if retry else p, headers=owner["headers"])
118
  assert response.status_code == 200, response.text
119
  report = response.json()
 
167
  owner = await make_account()
168
  sid = await make_session(owner["id"], mode="h" if kind == "hitting" else "p")
169
  p = copy.deepcopy(PAYLOAD if kind == "hitting" else PITCH if kind == "legacy_pitch" else payload(sid))
170
+ target = f"/v1/sessions/{sid}/swing-report?queue=false" if kind == "hitting" else url(sid)
171
  response = await client.post(target, json=p, headers=owner["headers"])
172
  assert response.status_code == 200, response.text
173
  report = response.json()
backend/tests/integration/test_qa_security.py CHANGED
@@ -254,7 +254,8 @@ async def test_swing_report_blocked_after_consent_withdrawn(client):
254
  json={"version": "1.0", "accepted": True})).status_code == 201
255
  sid = await make_session(player["id"], analyzed=False)
256
  assert (await client.delete("/v1/me/consent", headers=player["headers"])).status_code == 204
257
- response = await client.post(f"/v1/sessions/{sid}/swing-report", headers=player["headers"], json=PAYLOAD)
 
258
  assert response.status_code == 403, response.text
259
 
260
 
 
254
  json={"version": "1.0", "accepted": True})).status_code == 201
255
  sid = await make_session(player["id"], analyzed=False)
256
  assert (await client.delete("/v1/me/consent", headers=player["headers"])).status_code == 204
257
+ response = await client.post(f"/v1/sessions/{sid}/swing-report?queue=false", headers=player["headers"],
258
+ json=PAYLOAD)
259
  assert response.status_code == 403, response.text
260
 
261
 
backend/tests/integration/test_report_queue.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Queued reports (the default): POST .../swing-report stores the payload, a background worker builds the report and
2
+ the owner is notified."""
3
+
4
+ import asyncio
5
+
6
+ from app.modules.billing import entitlement
7
+ from app.modules.swing_reports import queue
8
+ from app.modules.swing_reports import service as report_service
9
+ from tests.factories import set_session
10
+ from tests.integration.test_swing_reports import PAYLOAD, load_session, make_account, make_session, payload
11
+
12
+
13
+ def url(session_id) -> str:
14
+ return f"/v1/sessions/{session_id}/swing-report"
15
+
16
+
17
+ async def workers_done() -> None:
18
+ while queue.WORKERS:
19
+ await asyncio.gather(*list(queue.WORKERS))
20
+
21
+
22
+ async def results(client, headers) -> list[dict]:
23
+ items = (await client.get("/v1/notifications", headers=headers)).json()["items"]
24
+ return [n for n in items if n["kind"] == "result"]
25
+
26
+
27
+ async def test_many_swings_are_queued_built_and_each_notified(client):
28
+ owner, headers = await make_account()
29
+ sids = [await make_session(owner) for _ in range(5)]
30
+ for sid in sids:
31
+ response = await client.post(url(sid), json=PAYLOAD, headers=headers)
32
+ assert response.status_code == 202, response.text
33
+ assert response.json() == {"session_id": str(sid), "status": "queued"}
34
+ await workers_done()
35
+
36
+ for sid in sids:
37
+ row = await load_session(sid)
38
+ assert row.status == "done" and row.report["overall_score"] == 78
39
+ assert row.measurement_payload == PAYLOAD and row.queued_payload is None and row.analyzed_at is not None
40
+ detail = (await client.get(f"/v1/sessions/{sid}", headers=headers)).json()["session"]
41
+ assert detail["status"] == "done" and detail["report_error"] is None
42
+ notes = await results(client, headers)
43
+ assert {n["target"]["session_id"] for n in notes} == {str(s) for s in sids}
44
+ assert all(n["title"] == "Your swing report is ready" and n["target"]["outcome"] == "ready" for n in notes)
45
+
46
+
47
+ async def test_queued_session_reads_as_queued_until_built(client, monkeypatch):
48
+ monkeypatch.setattr(queue, "kick", lambda: None) # no worker yet
49
+ owner, headers = await make_account()
50
+ sid = await make_session(owner)
51
+ assert (await client.post(url(sid), json=PAYLOAD, headers=headers)).status_code == 202
52
+ detail = (await client.get(f"/v1/sessions/{sid}", headers=headers)).json()["session"]
53
+ assert detail["status"] == "queued" and detail["report"] is None
54
+ listed = (await client.get("/v1/sessions", headers=headers)).json()["items"]
55
+ assert [s["status"] for s in listed] == ["queued"]
56
+
57
+ monkeypatch.undo()
58
+ queue.kick() # what startup does for work left by the last process
59
+ await workers_done()
60
+ assert (await load_session(sid)).status == "done"
61
+
62
+
63
+ async def test_checks_still_answer_in_the_request(client):
64
+ owner, headers = await make_account()
65
+ sid = await make_session(owner)
66
+ bad = await client.post(url(sid), json=payload(schema_version="9"), headers=headers)
67
+ assert bad.status_code == 422 and bad.json()["error"]["code"] == "INVALID_PAYLOAD"
68
+ _, other = await make_account()
69
+ assert (await client.post(url(sid), json=PAYLOAD, headers=other)).status_code == 403
70
+ assert (await load_session(sid)).queued_payload is None
71
+
72
+
73
+ async def test_reported_revision_is_not_queued_again(client):
74
+ owner, headers = await make_account()
75
+ sid = await make_session(owner)
76
+ assert (await client.post(url(sid), params={"queue": "false"}, json=PAYLOAD, headers=headers)).status_code == 200
77
+ again = await client.post(url(sid), json=PAYLOAD, headers=headers)
78
+ assert again.status_code == 202 and again.json()["status"] == "done"
79
+ await workers_done()
80
+ assert await results(client, headers) == [] # the synchronous call and the repeat notify nobody
81
+
82
+
83
+ async def test_failed_build_is_reported_and_can_be_retried(client, monkeypatch):
84
+ def broken(*args, **kwargs):
85
+ raise RuntimeError("model down")
86
+
87
+ monkeypatch.setattr(report_service, "build_report", broken)
88
+ owner, headers = await make_account()
89
+ bad, good = await make_session(owner), await make_session(owner)
90
+ assert (await client.post(url(bad), json=PAYLOAD, headers=headers)).status_code == 202
91
+ await workers_done()
92
+ detail = (await client.get(f"/v1/sessions/{bad}", headers=headers)).json()["session"]
93
+ assert detail["status"] == "failed" and detail["report_error"] == "REPORT_FAILED" and detail["report"] is None
94
+ [note] = await results(client, headers)
95
+ assert note["title"] == "We couldn't finish your swing report" and note["target"]["outcome"] == "failed"
96
+
97
+ monkeypatch.undo() # a failed build does not block the queue, and the same session can be posted again
98
+ for sid in (good, bad):
99
+ assert (await client.post(url(sid), json=PAYLOAD, headers=headers)).status_code == 202
100
+ await workers_done()
101
+ assert [(await load_session(s)).status for s in (good, bad)] == ["done", "done"]
102
+ assert (await load_session(bad)).report_error is None
103
+ assert len(await results(client, headers)) == 3
104
+
105
+
106
+ async def test_queued_swings_reserve_the_plan(client, monkeypatch):
107
+ monkeypatch.setattr(entitlement, "FREE_WEEKLY_LIMIT", 2)
108
+ monkeypatch.setattr(queue, "kick", lambda: None)
109
+ owner, headers = await make_account()
110
+ first, second, third = [await make_session(owner) for _ in range(3)]
111
+ for sid in (first, second):
112
+ assert (await client.post(url(sid), json=PAYLOAD, headers=headers)).status_code == 202
113
+ over = await client.post(url(third), json=PAYLOAD, headers=headers)
114
+ assert over.status_code == 402 and over.json()["error"]["code"] == "PLAN_LIMIT"
115
+ await set_session(first, queued_payload=None)
116
+ await set_session(second, queued_payload=None)
backend/tests/integration/test_swing_reports.py CHANGED
@@ -81,7 +81,7 @@ async def load_session(session_id: uuid.UUID) -> SwingSession:
81
 
82
 
83
  def url(session_id) -> str:
84
- return f"/v1/sessions/{session_id}/swing-report"
85
 
86
 
87
  @pytest.fixture
 
81
 
82
 
83
  def url(session_id) -> str:
84
+ return f"/v1/sessions/{session_id}/swing-report?queue=false"
85
 
86
 
87
  @pytest.fixture
docs/PITCHING_APP_INTEGRATION.md CHANGED
@@ -20,6 +20,8 @@ Reuse account authentication, presigned uploads, video playback/frame selection,
20
  | Report | Four pitching group IDs; nullable scores, values, focus and drill; generated/unavailable coaching states |
21
  | Retry | `/v1/sessions/{id}/pitch-report/retry-coaching`; reruns interpretation from saved ML evidence |
22
 
 
 
23
  There is no mobile Gemini call and no new AI-provider key for the app. The backend generates and stores coaching when `/pitch-report` is called.
24
 
25
  ## Services and authentication
 
20
  | Report | Four pitching group IDs; nullable scores, values, focus and drill; generated/unavailable coaching states |
21
  | Retry | `/v1/sessions/{id}/pitch-report/retry-coaching`; reruns interpretation from saved ML evidence |
22
 
23
+ `/pitch-report` queues the report by default (202, then a `result` notification); add `?queue=false` to wait for the report in the request as described below. See `backend/docs/FRONTEND_INTEGRATION.md` §5.
24
+
25
  There is no mobile Gemini call and no new AI-provider key for the app. The backend generates and stores coaching when `/pitch-report` is called.
26
 
27
  ## Services and authentication