github-actions[bot] commited on
Commit
7a3215f
·
1 Parent(s): 3ee736f

Automated Deploy: 8f8167dc5709c2ea13b6f4ea7a93cc50c9b953cd

Browse files
Files changed (34) hide show
  1. backend/.env.example +11 -0
  2. backend/README.md +96 -0
  3. backend/app/core/config.py +16 -0
  4. backend/app/core/database.py +8 -1
  5. backend/app/core/dependencies.py +5 -2
  6. backend/app/core/errors.py +22 -2
  7. backend/app/jobs/cleanup.py +4 -0
  8. backend/app/main.py +19 -4
  9. backend/app/models.py +2 -1
  10. backend/app/modules/api_audit/__init__.py +1 -0
  11. backend/app/modules/api_audit/controller.py +47 -0
  12. backend/app/modules/api_audit/middleware.py +172 -0
  13. backend/app/modules/api_audit/models.py +36 -0
  14. backend/app/modules/api_audit/repository.py +28 -0
  15. backend/app/modules/api_audit/schemas.py +34 -0
  16. backend/app/modules/api_audit/service.py +47 -0
  17. backend/app/modules/swing_reports/controller.py +1 -1
  18. backend/app/modules/swing_reports/service.py +14 -1
  19. backend/docs/openapi.json +1174 -505
  20. backend/migrations/versions/20261028_7e83a6c10b42_api_request_logs.py +49 -0
  21. backend/tests/integration/test_api_audit.py +220 -0
  22. backend/tests/integration/test_api_audit_read.py +104 -0
  23. backend/tests/integration/test_cleanup.py +3 -3
  24. backend/tests/integration/test_health.py +22 -0
  25. backend/tests/integration/test_swing_reports.py +29 -0
  26. baseball_batting/automatic_pitcher_direction.py +214 -0
  27. baseball_batting/camera_up.py +12 -1
  28. baseball_batting/camera_up_worker.py +6 -0
  29. baseball_batting/motion_api.py +4 -0
  30. baseball_batting/motion_export.py +5 -1
  31. docs/APP_API_INTEGRATION.md +9 -0
  32. docs/MOTION_PLAYER_API.md +8 -1
  33. docs/PITCHER_FLOOR_DIRECTION.md +52 -2
  34. tests/test_automatic_pitcher_direction.py +168 -0
backend/.env.example CHANGED
@@ -42,3 +42,14 @@ COACH_LOG_LEVEL=INFO
42
  COACH_TRACING=false
43
  LANGSMITH_API_KEY=
44
  LANGSMITH_PROJECT=ai-coach
 
 
 
 
 
 
 
 
 
 
 
 
42
  COACH_TRACING=false
43
  LANGSMITH_API_KEY=
44
  LANGSMITH_PROJECT=ai-coach
45
+
46
+ # Private database audit of every backend HTTP request/response (apply migrations first).
47
+ API_AUDIT_ENABLED=true
48
+ API_AUDIT_MAX_BODY_BYTES=1048576
49
+ API_AUDIT_WRITE_TIMEOUT_S=2
50
+ API_AUDIT_RETENTION_DAYS=30
51
+ # Set this to the deployed Git commit/build identifier for incident correlation.
52
+ SERVICE_VERSION=0.1.0
53
+
54
+ # Trusted operator account UUIDs allowed to GET /v1/admin/api-logs. Empty denies everyone.
55
+ API_AUDIT_READER_ACCOUNT_IDS=[]
backend/README.md CHANGED
@@ -68,3 +68,99 @@ build arguments. Without the JSON secret, startup still supports an existing cre
68
 
69
  The repository's root Dockerfile and existing Hugging Face deployment run the separate GPU analysis API;
70
  this setup requires deploying `backend/Dockerfile` with Space `app_port: 8000`.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68
 
69
  The repository's root Dockerfile and existing Hugging Face deployment run the separate GPU analysis API;
70
  this setup requires deploying `backend/Dockerfile` with Space `app_port: 8000`.
71
+
72
+ ## API request/response diagnostics
73
+
74
+ Apply `alembic upgrade head` before deploying this version. The `api_request_logs`
75
+ table records every HTTP call handled by this backend, including failed validation,
76
+ authentication failures, unknown routes, health checks, and repeated requests.
77
+ The separate GPU API and standalone coach API do not write to this backend table;
78
+ the ML payload forwarded to the swing-report endpoint is captured here in full
79
+ within the configured JSON size limit.
80
+
81
+ Each row includes the request ID (also returned as `X-Request-Id`), timestamp,
82
+ method, route/path, authenticated account ID when available, session/analysis ID
83
+ and revision, HTTP status, duration, error code/type, service build version,
84
+ selected headers, query parameters, and sanitized request/response JSON. For a
85
+ swing report this includes event times, measurement values and quality reasons,
86
+ benchmarks, scores, chosen focus/drill, provider/fallback metadata, and generated
87
+ coaching text. The logger does not change measurement or scoring logic.
88
+
89
+ `request_payload` and `response_payload` contain `capture_status`,
90
+ `observed_bytes`, and `body`. JSON bodies up to `API_AUDIT_MAX_BODY_BYTES` (default
91
+ 1 MiB per direction) are captured. Larger bodies are marked `truncated` and their
92
+ body is omitted, never stored as an invalid partial JSON document. Malformed JSON,
93
+ binary/media bodies, and unread/incomplete streams are explicitly marked. Video
94
+ bytes are never buffered for logging. Passwords, tokens, authorization, cookies,
95
+ receipts, webhook encoded data, emails, phone numbers, and URLs are redacted;
96
+ athlete measurements and report text remain diagnostic data. Restrict database
97
+ access to these records; audit browsing is restricted to explicitly allowlisted accounts.
98
+
99
+ Writes use their own transaction after handling the request, so application
100
+ rollbacks do not erase diagnostics. They are best-effort with a bounded timeout
101
+ (default two seconds): a database outage or full audit table does not replace the
102
+ API response. Such failures emit `api_audit_write_failed` with request ID and
103
+ exception class only. No database logger can guarantee a row during a database
104
+ outage or process termination. The hourly cleanup command removes records older
105
+ than `API_AUDIT_RETENTION_DAYS` (default 30). Set `SERVICE_VERSION` to the deployed
106
+ commit/build ID. `API_AUDIT_ENABLED=false` disables collection.
107
+
108
+ Find a reported analysis:
109
+
110
+ ```sql
111
+ SELECT created_at, request_id, session_id, analysis_id, analysis_revision,
112
+ status_code, duration_ms, service_version,
113
+ request_payload->'body' AS input,
114
+ response_payload->'body' AS output
115
+ FROM api_request_logs
116
+ WHERE analysis_id = 'analysis_001'
117
+ ORDER BY created_at DESC;
118
+ ```
119
+
120
+ Trace a request or recent failures:
121
+
122
+ ```sql
123
+ SELECT * FROM api_request_logs WHERE request_id = 'request-id-from-response';
124
+ SELECT created_at, request_id, route, status_code, error_code, response_payload
125
+ FROM api_request_logs
126
+ WHERE status_code >= 400
127
+ ORDER BY created_at DESC LIMIT 100;
128
+ ```
129
+
130
+ A repeated analysis revision can legitimately return an older stored report; the
131
+ request log retains each submitted payload and the actual returned response so
132
+ that difference can be investigated.
133
+
134
+ ### Read logs through the API
135
+
136
+ Set `API_AUDIT_READER_ACCOUNT_IDS` to a JSON array of trusted operator account UUIDs
137
+ and restart the backend. The default empty list denies access to everyone. Player
138
+ or coach status alone does not grant access. Use the operator's normal access JWT:
139
+
140
+ ```dotenv
141
+ API_AUDIT_READER_ACCOUNT_IDS=["YOUR-OPERATOR-ACCOUNT-UUID"]
142
+ ```
143
+
144
+ - `GET /v1/admin/api-logs`: newest-first metadata, with `items` and `next_cursor`.
145
+ Filters: `request_id`, `session_id`, `analysis_id`, `account_id`, `status_code`,
146
+ `method` (uppercase), `route` (exact route template), `since`, and `until`.
147
+ Date filters apply to `created_at`, are timezone-aware, and use an inclusive
148
+ `since` and exclusive `until`. `limit` defaults to 50, maximum 200. Pass
149
+ `next_cursor` as `cursor` with the same filters to fetch another page.
150
+ - `GET /v1/admin/api-logs/{log_id}`: metadata plus saved sanitized request/response
151
+ bodies, selected headers, and query parameters. Use the log row's `id`, not its
152
+ `request_id`, for this URL.
153
+
154
+ ```bash
155
+ curl "$API_BASE_URL/v1/admin/api-logs?analysis_id=analysis_001&limit=20" \
156
+ -H "Authorization: Bearer $ACCESS_TOKEN"
157
+ curl "$API_BASE_URL/v1/admin/api-logs/$LOG_ID" \
158
+ -H "Authorization: Bearer $ACCESS_TOKEN"
159
+ ```
160
+
161
+ Returns 401 without valid authentication, 403 without allowlist access, 400 for
162
+ invalid filters, and 404 for a missing/expired log ID. Successful responses use
163
+ `Cache-Control: no-store`. Lists omit payload columns; fetch individual records to
164
+ inspect bodies. Log reads are themselves audited, but their response bodies are
165
+ marked `omitted_audit_read` to avoid recursively duplicating saved payloads.
166
+ No additional database migration is needed beyond the original audit-log table.
backend/app/core/config.py CHANGED
@@ -2,7 +2,9 @@
2
 
3
  from functools import lru_cache
4
  from typing import Literal
 
5
 
 
6
  from pydantic_settings import BaseSettings, SettingsConfigDict
7
 
8
 
@@ -13,7 +15,21 @@ class Settings(BaseSettings):
13
 
14
  # Postgres (asyncpg driver), e.g. postgresql+asyncpg://user:pass@host/db
15
  database_url: str = "postgresql+asyncpg://app:app@localhost:55440/app_dev"
 
 
16
  database_pool_size: int = 5
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  # Tokens
19
  jwt_secret: str = "change-me"
 
2
 
3
  from functools import lru_cache
4
  from typing import Literal
5
+ from uuid import UUID
6
 
7
+ from pydantic import Field
8
  from pydantic_settings import BaseSettings, SettingsConfigDict
9
 
10
 
 
15
 
16
  # Postgres (asyncpg driver), e.g. postgresql+asyncpg://user:pass@host/db
17
  database_url: str = "postgresql+asyncpg://app:app@localhost:55440/app_dev"
18
+ # Connections per API process = pool_size + max_overflow. Keep the total under the database's client limit
19
+ # (Supabase's session pooler allows 15 across every client); extra requests wait up to pool_timeout_s.
20
  database_pool_size: int = 5
21
+ database_max_overflow: int = 5
22
+ database_pool_timeout_s: float = 30.0
23
+ # Set true when DATABASE_URL points at a transaction-mode pooler (Supabase port 6543), which cannot keep
24
+ # prepared statements between transactions.
25
+ database_transaction_pooler: bool = False
26
+
27
+ api_audit_reader_account_ids: list[UUID] = Field(default_factory=list)
28
+ api_audit_enabled: bool = True
29
+ api_audit_max_body_bytes: int = Field(default=1048576, ge=1024, le=16777216)
30
+ api_audit_write_timeout_s: float = Field(default=2.0, gt=0, le=30)
31
+ api_audit_retention_days: int = Field(default=30, ge=1, le=365)
32
+ service_version: str = "0.1.0"
33
 
34
  # Tokens
35
  jwt_secret: str = "change-me"
backend/app/core/database.py CHANGED
@@ -1,5 +1,6 @@
1
  """Async engine, session factory and the per-request unit of work."""
2
 
 
3
  from collections.abc import AsyncIterator
4
  from functools import lru_cache
5
 
@@ -11,7 +12,13 @@ from app.core.config import get_settings
11
  @lru_cache
12
  def get_engine() -> AsyncEngine:
13
  settings = get_settings()
14
- return create_async_engine(settings.database_url, pool_size=settings.database_pool_size, pool_pre_ping=True)
 
 
 
 
 
 
15
 
16
 
17
  @lru_cache
 
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
 
 
12
  @lru_cache
13
  def get_engine() -> AsyncEngine:
14
  settings = get_settings()
15
+ connect_args = {}
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
backend/app/core/dependencies.py CHANGED
@@ -3,7 +3,7 @@
3
  from typing import Annotated
4
  from uuid import UUID
5
 
6
- from fastapi import Depends, Header
7
  from sqlalchemy.ext.asyncio import AsyncSession
8
 
9
  from app.core.database import get_db
@@ -24,10 +24,13 @@ def current_account_id(authorization: Annotated[str | None, Header()] = None) ->
24
  return decode_access_token(authorization[7:].strip())
25
 
26
 
27
- async def current_account(db: Db, account_id: Annotated[UUID, Depends(current_account_id)]) -> Account:
 
 
28
  account = await db.get(Account, account_id)
29
  if account is None:
30
  raise Unauthenticated()
 
31
  return account
32
 
33
 
 
3
  from typing import Annotated
4
  from uuid import UUID
5
 
6
+ from fastapi import Depends, Header, Request
7
  from sqlalchemy.ext.asyncio import AsyncSession
8
 
9
  from app.core.database import get_db
 
24
  return decode_access_token(authorization[7:].strip())
25
 
26
 
27
+ async def current_account(
28
+ db: Db, account_id: Annotated[UUID, Depends(current_account_id)], request: Request,
29
+ ) -> Account:
30
  account = await db.get(Account, account_id)
31
  if account is None:
32
  raise Unauthenticated()
33
+ request.state.audit_account_id = account.id
34
  return account
35
 
36
 
backend/app/core/errors.py CHANGED
@@ -9,6 +9,8 @@ import logging
9
  from fastapi import FastAPI, Request
10
  from fastapi.exceptions import RequestValidationError
11
  from fastapi.responses import JSONResponse
 
 
12
  from starlette.exceptions import HTTPException as StarletteHTTPException
13
 
14
  log = logging.getLogger(__name__)
@@ -100,7 +102,25 @@ def register_error_handlers(app: FastAPI) -> None:
100
  fields.setdefault(_field_path(tuple(err.get("loc", ()))), err.get("msg", "Invalid value."))
101
  return JSONResponse(_body(ValidationFailed.code, ValidationFailed.message, fields), status_code=400)
102
 
 
 
 
 
 
 
103
  @app.exception_handler(Exception)
104
  async def _unexpected(_: Request, exc: Exception) -> JSONResponse:
105
- log.exception("unhandled error", exc_info=exc)
106
- return JSONResponse(_body(AppError.code, AppError.message), status_code=500)
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  from fastapi import FastAPI, Request
10
  from fastapi.exceptions import RequestValidationError
11
  from fastapi.responses import JSONResponse
12
+ from sqlalchemy.exc import DBAPIError
13
+ from sqlalchemy.exc import TimeoutError as SQLAlchemyTimeoutError
14
  from starlette.exceptions import HTTPException as StarletteHTTPException
15
 
16
  log = logging.getLogger(__name__)
 
102
  fields.setdefault(_field_path(tuple(err.get("loc", ()))), err.get("msg", "Invalid value."))
103
  return JSONResponse(_body(ValidationFailed.code, ValidationFailed.message, fields), status_code=400)
104
 
105
+ @app.exception_handler(SQLAlchemyTimeoutError)
106
+ async def _pool_exhausted(_: Request, exc: SQLAlchemyTimeoutError) -> JSONResponse:
107
+ log.warning("database pool exhausted: %s", exc)
108
+ return JSONResponse(_body(ServiceUnavailable.code, ServiceUnavailable.message), status_code=503,
109
+ headers={"Retry-After": "2"})
110
+
111
  @app.exception_handler(Exception)
112
  async def _unexpected(_: Request, exc: Exception) -> JSONResponse:
113
+ return unexpected_error_response(exc)
114
+
115
+
116
+ DB_BUSY_MARKERS = ("max clients reached", "too many connections", "remaining connection slots")
117
+
118
+
119
+ def unexpected_error_response(exc: Exception) -> JSONResponse:
120
+ """500 for bugs; 503 (retryable) when the database has no free connection."""
121
+ if isinstance(exc, DBAPIError) and any(m in str(exc).lower() for m in DB_BUSY_MARKERS):
122
+ log.warning("database has no free connection: %s", str(exc).splitlines()[0])
123
+ return JSONResponse(_body(ServiceUnavailable.code, ServiceUnavailable.message), status_code=503,
124
+ headers={"Retry-After": "2"})
125
+ log.exception("unhandled error", exc_info=exc)
126
+ return JSONResponse(_body(AppError.code, AppError.message), status_code=500)
backend/app/jobs/cleanup.py CHANGED
@@ -16,6 +16,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
16
  from app.core.config import get_settings
17
  from app.core.database import get_session_factory
18
  from app.integrations.storage import StorageClient, get_storage
 
19
  from app.modules.idempotency.models import IdempotencyKey
20
  from app.modules.sessions.models import SwingSession
21
  from app.modules.uploads.models import Upload
@@ -51,6 +52,8 @@ async def run_cleanup(db: AsyncSession, storage: StorageClient, now: datetime |
51
  await db.execute(delete(Upload).where(Upload.id.in_([id_ for id_, _ in uploads])))
52
  keys = await db.execute(delete(IdempotencyKey).where(
53
  IdempotencyKey.created_at < now - timedelta(hours=settings.idempotency_ttl_h)))
 
 
54
  await db.commit()
55
 
56
  counts = {
@@ -59,6 +62,7 @@ async def run_cleanup(db: AsyncSession, storage: StorageClient, now: datetime |
59
  "deleted_sessions": sum(1 for row in sessions if row[1] is not None),
60
  "objects": len(uploads),
61
  "idempotency_keys": keys.rowcount or 0,
 
62
  }
63
  log.info("cleanup done: %s", counts)
64
  return counts
 
16
  from app.core.config import get_settings
17
  from app.core.database import get_session_factory
18
  from app.integrations.storage import StorageClient, get_storage
19
+ from app.modules.api_audit.models import ApiRequestLog
20
  from app.modules.idempotency.models import IdempotencyKey
21
  from app.modules.sessions.models import SwingSession
22
  from app.modules.uploads.models import Upload
 
52
  await db.execute(delete(Upload).where(Upload.id.in_([id_ for id_, _ in uploads])))
53
  keys = await db.execute(delete(IdempotencyKey).where(
54
  IdempotencyKey.created_at < now - timedelta(hours=settings.idempotency_ttl_h)))
55
+ audit = await db.execute(delete(ApiRequestLog).where(
56
+ ApiRequestLog.created_at < now - timedelta(days=settings.api_audit_retention_days)))
57
  await db.commit()
58
 
59
  counts = {
 
62
  "deleted_sessions": sum(1 for row in sessions if row[1] is not None),
63
  "objects": len(uploads),
64
  "idempotency_keys": keys.rowcount or 0,
65
+ "api_request_logs": audit.rowcount or 0,
66
  }
67
  log.info("cleanup done: %s", counts)
68
  return counts
backend/app/main.py CHANGED
@@ -1,15 +1,19 @@
1
  """Application factory: routers, error envelope, request ids."""
2
 
 
3
  import uuid
4
 
 
5
  from ai_coach.swing_report.schemas import SwingAnalysisPayload, SwingReport
6
  from fastapi import FastAPI, Request
7
  from fastapi.openapi.utils import get_openapi
8
  from pydantic.json_schema import models_json_schema
9
 
10
  from app.core.config import get_settings
11
- from app.core.errors import register_error_handlers
12
  from app.modules.accounts.controller import router as accounts_router
 
 
13
  from app.modules.auth.controller import router as auth_router
14
  from app.modules.billing.controller import router as billing_router
15
  from app.modules.catalog.controller import router as catalog_router
@@ -24,12 +28,14 @@ from app.modules.uploads.controller import router as uploads_router
24
 
25
  ROUTERS = (
26
  auth_router, accounts_router, teams_router, uploads_router, sessions_router, swing_reports_router,
27
- drills_router, reviews_router, coach_router, devices_router, billing_router, catalog_router,
28
  )
29
 
30
 
31
  def create_app() -> FastAPI:
32
  settings = get_settings()
 
 
33
  app = FastAPI(
34
  title="Cognivision Baseball API",
35
  version="0.1.0",
@@ -40,12 +46,21 @@ def create_app() -> FastAPI:
40
 
41
  @app.middleware("http")
42
  async def request_id(request: Request, call_next):
43
- rid = request.headers.get("x-request-id") or uuid.uuid4().hex
 
44
  request.state.request_id = rid
45
- response = await call_next(request)
 
 
 
 
46
  response.headers["X-Request-Id"] = rid
47
  return response
48
 
 
 
 
 
49
  @app.get("/healthz", include_in_schema=False)
50
  async def healthz() -> dict:
51
  return {"status": "ok"}
 
1
  """Application factory: routers, error envelope, request ids."""
2
 
3
+ import re
4
  import uuid
5
 
6
+ from ai_coach.config import get_settings as get_coach_settings
7
  from ai_coach.swing_report.schemas import SwingAnalysisPayload, SwingReport
8
  from fastapi import FastAPI, Request
9
  from fastapi.openapi.utils import get_openapi
10
  from pydantic.json_schema import models_json_schema
11
 
12
  from app.core.config import get_settings
13
+ from app.core.errors import register_error_handlers, unexpected_error_response
14
  from app.modules.accounts.controller import router as accounts_router
15
+ from app.modules.api_audit.controller import router as audit_router
16
+ from app.modules.api_audit.middleware import ApiAuditMiddleware
17
  from app.modules.auth.controller import router as auth_router
18
  from app.modules.billing.controller import router as billing_router
19
  from app.modules.catalog.controller import router as catalog_router
 
28
 
29
  ROUTERS = (
30
  auth_router, accounts_router, teams_router, uploads_router, sessions_router, swing_reports_router,
31
+ drills_router, reviews_router, coach_router, devices_router, billing_router, catalog_router, audit_router,
32
  )
33
 
34
 
35
  def create_app() -> FastAPI:
36
  settings = get_settings()
37
+ if settings.env == "prod" and not get_coach_settings().llm_enabled:
38
+ raise RuntimeError("GOOGLE_API_KEY is not set: the AI coach cannot write coaching text in production.")
39
  app = FastAPI(
40
  title="Cognivision Baseball API",
41
  version="0.1.0",
 
46
 
47
  @app.middleware("http")
48
  async def request_id(request: Request, call_next):
49
+ supplied = request.headers.get("x-request-id", "")
50
+ rid = supplied if re.fullmatch(r"[A-Za-z0-9_.:-]{1,128}", supplied) else uuid.uuid4().hex
51
  request.state.request_id = rid
52
+ try:
53
+ response = await call_next(request)
54
+ except Exception as exc: # handled here so error responses carry the request id too
55
+ request.state.audit_exception_type = type(exc).__name__
56
+ response = unexpected_error_response(exc)
57
  response.headers["X-Request-Id"] = rid
58
  return response
59
 
60
+ if settings.api_audit_enabled:
61
+ app.add_middleware(ApiAuditMiddleware, max_body_bytes=settings.api_audit_max_body_bytes,
62
+ service_version=settings.service_version)
63
+
64
  @app.get("/healthz", include_in_schema=False)
65
  async def healthz() -> dict:
66
  return {"status": "ok"}
backend/app/models.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  from app.common.base_model import Base
4
  from app.modules.accounts.models import Account
 
5
  from app.modules.auth.models import AuthIdentity, PasswordReset, RefreshToken
6
  from app.modules.billing.models import Subscription
7
  from app.modules.devices.models import Device
@@ -14,5 +15,5 @@ from app.modules.uploads.models import Upload
14
 
15
  __all__ = [
16
  "Base", "Account", "AuthIdentity", "PasswordReset", "RefreshToken", "Subscription", "Device", "DrillLog",
17
- "IdempotencyKey", "Review", "SwingSession", "Team", "Upload",
18
  ]
 
2
 
3
  from app.common.base_model import Base
4
  from app.modules.accounts.models import Account
5
+ from app.modules.api_audit.models import ApiRequestLog
6
  from app.modules.auth.models import AuthIdentity, PasswordReset, RefreshToken
7
  from app.modules.billing.models import Subscription
8
  from app.modules.devices.models import Device
 
15
 
16
  __all__ = [
17
  "Base", "Account", "AuthIdentity", "PasswordReset", "RefreshToken", "Subscription", "Device", "DrillLog",
18
+ "IdempotencyKey", "Review", "SwingSession", "Team", "Upload", "ApiRequestLog",
19
  ]
backend/app/modules/api_audit/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ """Private operational audit records; no public read endpoint."""
backend/app/modules/api_audit/controller.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Operator-only audit browsing using an explicit server-side account allowlist."""
2
+
3
+ from datetime import datetime
4
+ from typing import Annotated, Literal
5
+ from uuid import UUID
6
+
7
+ from fastapi import APIRouter, Depends, Query, Request, Response
8
+
9
+ from app.common.schemas import Page
10
+ from app.core.config import get_settings
11
+ from app.core.dependencies import CurrentAccount, Db, Paging
12
+ from app.core.errors import Forbidden
13
+ from app.modules.api_audit.schemas import AuditLogDetail, AuditLogSummary
14
+ from app.modules.api_audit.service import AuditLogService
15
+
16
+
17
+ def require_audit_access(request: Request, response: Response, account: CurrentAccount) -> None:
18
+ if account.id not in get_settings().api_audit_reader_account_ids:
19
+ raise Forbidden("You do not have access to API logs.")
20
+ request.state.audit_omit_response = True
21
+ response.headers["Cache-Control"] = "no-store"
22
+
23
+
24
+ router = APIRouter(prefix="/v1/admin/api-logs", tags=["API logs"], dependencies=[Depends(require_audit_access)])
25
+
26
+
27
+ @router.get("", response_model=Page[AuditLogSummary])
28
+ async def list_logs(
29
+ db: Db, paging: Paging,
30
+ request_id: Annotated[str | None, Query(max_length=128)] = None,
31
+ session_id: UUID | None = None,
32
+ analysis_id: Annotated[str | None, Query(max_length=256)] = None,
33
+ account_id: UUID | None = None,
34
+ status_code: Annotated[int | None, Query(ge=100, le=599)] = None,
35
+ method: Literal["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"] | None = None,
36
+ route: Annotated[str | None, Query(max_length=512)] = None,
37
+ since: datetime | None = None, until: datetime | None = None,
38
+ ) -> Page[AuditLogSummary]:
39
+ return await AuditLogService(db).list(paging, {
40
+ "request_id": request_id, "session_id": session_id, "analysis_id": analysis_id,
41
+ "account_id": account_id, "status_code": status_code, "method": method, "route": route,
42
+ }, since, until)
43
+
44
+
45
+ @router.get("/{log_id}", response_model=AuditLogDetail)
46
+ async def get_log(log_id: UUID, db: Db) -> AuditLogDetail:
47
+ return await AuditLogService(db).get(log_id)
backend/app/modules/api_audit/middleware.py ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Observe ASGI messages without changing response bytes or buffering video streams."""
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+ import re
7
+ import time
8
+ import uuid
9
+ from collections import deque
10
+ from datetime import UTC, datetime
11
+ from urllib.parse import parse_qs
12
+
13
+ from app.modules.api_audit.service import write_record
14
+
15
+ REDACTED = "[REDACTED]"
16
+ SAFE_HEADERS = {"content-type", "content-length", "x-request-id", "retry-after"}
17
+ SENSITIVE = re.compile(
18
+ r"password|token|secret|credential|authorization|cookie|signature|receipt|privatekey|apikey", re.I)
19
+ URL = re.compile(r"https?://[^\s\"<>]+", re.I)
20
+ BEARER = re.compile(r"\bBearer\s+\S+", re.I)
21
+ KEY = re.compile(r"AIza[0-9A-Za-z_-]{20,}|lsv2_[a-z]{2}_[0-9A-Za-z_]{16,}")
22
+
23
+
24
+ def sanitize(value, depth=0):
25
+ if depth > 40:
26
+ return "[DEPTH LIMIT]"
27
+ if isinstance(value, dict):
28
+ return {str(k).replace("\x00", "[NUL]"): REDACTED if SENSITIVE.search(re.sub(r"[^a-z0-9]", "", str(k).lower()))
29
+ or str(k).lower() in {"email", "phone", "signedpayload", "data"} else sanitize(v, depth + 1)
30
+ for k, v in value.items()}
31
+ if isinstance(value, list):
32
+ return [sanitize(v, depth + 1) for v in value]
33
+ if isinstance(value, str):
34
+ # URLs may contain storage credentials or reset tokens, including in their path.
35
+ return KEY.sub(REDACTED, BEARER.sub(REDACTED, URL.sub("[URL REDACTED]", value.replace("\x00", "[NUL]"))))
36
+ if isinstance(value, float) and not math.isfinite(value):
37
+ return "[NONFINITE NUMBER]"
38
+ return value
39
+
40
+
41
+ class Capture:
42
+ def __init__(self, content_type, limit):
43
+ self.json = content_type.split(";", 1)[0].strip().lower().endswith(("/json", "+json"))
44
+ self.limit = limit
45
+ self.buffer = bytearray()
46
+ self.size = 0
47
+ self.complete = False
48
+
49
+ def feed(self, body, complete):
50
+ self.size += len(body)
51
+ if self.json and len(self.buffer) < self.limit:
52
+ self.buffer.extend(body[:self.limit - len(self.buffer)])
53
+ self.complete = complete
54
+
55
+ def result(self):
56
+ status = ("incomplete" if not self.complete else "empty" if not self.size else
57
+ "non_json" if not self.json else "truncated" if self.size > self.limit else "captured")
58
+ body = None
59
+ if status == "captured":
60
+ try:
61
+ body = sanitize(json.loads(self.buffer, parse_constant=lambda _: (_ for _ in ()).throw(ValueError())))
62
+ except (ValueError, UnicodeError, RecursionError):
63
+ status = "invalid_json"
64
+ return {"capture_status": status, "observed_bytes": self.size, "body": body}
65
+
66
+
67
+ def headers(raw):
68
+ selected = {k.decode("latin1").lower(): sanitize(v.decode("latin1"))
69
+ for k, v in raw if k.decode("latin1").lower() in SAFE_HEADERS}
70
+ for key, value in raw:
71
+ if key.lower() == b"idempotency-key":
72
+ selected["idempotency-key-sha256"] = hashlib.sha256(value).hexdigest()
73
+ return selected
74
+
75
+
76
+ def as_uuid(value):
77
+ try:
78
+ return uuid.UUID(str(value))
79
+ except (ValueError, TypeError, AttributeError):
80
+ return None
81
+
82
+
83
+ class ApiAuditMiddleware:
84
+ def __init__(self, app, *, max_body_bytes=1048576, service_version="unknown", writer=write_record):
85
+ self.app = app
86
+ self.limit = max_body_bytes
87
+ self.version = service_version
88
+ self.writer = writer
89
+
90
+ async def __call__(self, scope, receive, send):
91
+ if scope["type"] != "http":
92
+ return await self.app(scope, receive, send)
93
+ started_at, started = datetime.now(UTC), time.monotonic()
94
+ incoming = headers(scope.get("headers", []))
95
+ request = Capture(incoming.get("content-type", ""), self.limit)
96
+ response = Capture("", self.limit)
97
+ outgoing, status, exception = {}, 500, None
98
+ replay = deque()
99
+ state = scope.setdefault("state", {})
100
+ # A server-generated ID is available even if routing fails before the app middleware.
101
+ state.setdefault("request_id", uuid.uuid4().hex)
102
+
103
+ async def observed_receive():
104
+ if replay:
105
+ return replay.popleft()
106
+ message = await receive()
107
+ if message["type"] == "http.request":
108
+ request.feed(message.get("body", b""), not message.get("more_body", False))
109
+ return message
110
+
111
+ async def observed_send(message):
112
+ nonlocal outgoing, status, response
113
+ if message["type"] == "http.response.start":
114
+ status = message["status"]
115
+ outgoing = headers(message.get("headers", []))
116
+ response = Capture("" if state.get("audit_omit_response") else outgoing.get("content-type", ""),
117
+ self.limit)
118
+ elif message["type"] == "http.response.body":
119
+ response.feed(message.get("body", b""), not message.get("more_body", False))
120
+ await send(message)
121
+
122
+ try:
123
+ # Small JSON bodies are captured even for early 401/404 responses. Replay unchanged.
124
+ if request.json:
125
+ while not request.complete and request.size <= self.limit:
126
+ message = await receive()
127
+ replay.append(message)
128
+ if message["type"] != "http.request":
129
+ break
130
+ request.feed(message.get("body", b""), not message.get("more_body", False))
131
+ await self.app(scope, observed_receive, observed_send)
132
+ except BaseException as exc:
133
+ exception = type(exc).__name__
134
+ raise
135
+ finally:
136
+ request_body, response_body = request.result(), response.result()
137
+ if state.get("audit_omit_response"):
138
+ response_body["capture_status"] = "omitted_audit_read"
139
+ body = request_body.get("body")
140
+ body = body if isinstance(body, dict) else {}
141
+ result = response_body.get("body")
142
+ result = result if isinstance(result, dict) else {}
143
+ params = scope.get("path_params", {})
144
+ route = getattr(scope.get("route"), "path", None)
145
+ # Device removal puts the push credential in the URL. Store the template instead.
146
+ path = scope.get("path", "")
147
+ if any(SENSITIVE.search(k) for k in params) or path.startswith("/v1/devices/"):
148
+ path = route or "/v1/devices/[REDACTED]"
149
+ error = result.get("error")
150
+ session = result.get("session")
151
+ session = session if isinstance(session, dict) else {}
152
+ report = session.get("report") or result.get("report")
153
+ report = report if isinstance(report, dict) else {}
154
+ analysis_id = body.get("analysis_id") or result.get("analysis_id") or report.get("analysis_id")
155
+ revision = body.get("analysis_revision", result.get("analysis_revision", report.get("analysis_revision")))
156
+ await self.writer({
157
+ "request_id": str(state.get("request_id"))[:128], "started_at": started_at,
158
+ "method": scope["method"][:16], "path": sanitize(path)[:2048], "route": route,
159
+ "status_code": status, "duration_ms": round((time.monotonic() - started) * 1000, 3),
160
+ "account_id": as_uuid(state.get("audit_account_id")),
161
+ "session_id": as_uuid(params.get("session_id") or body.get("session_id") or session.get("id")),
162
+ "analysis_id": analysis_id[:256] if isinstance(analysis_id, str) else None,
163
+ "analysis_revision": revision if type(revision) is int and 0 <= revision < 2147483648 else None,
164
+ "request_headers": incoming,
165
+ "query_params": sanitize(parse_qs(
166
+ scope.get("query_string", b"").decode("utf-8", errors="replace"))),
167
+ "request_payload": request_body, "response_headers": outgoing, "response_payload": response_body,
168
+ "error_code": str(error.get("code"))[:128] if isinstance(error, dict) else None,
169
+ "exception_type": exception or state.get("audit_exception_type"),
170
+ "response_complete": response.complete,
171
+ "service_version": self.version[:128],
172
+ })
backend/app/modules/api_audit/models.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One request/response record per backend HTTP call, independent of its transaction."""
2
+
3
+ from datetime import datetime
4
+ from uuid import UUID
5
+
6
+ from sqlalchemy import Boolean, DateTime, Float, Index, Integer, String
7
+ from sqlalchemy.dialects.postgresql import JSONB
8
+ from sqlalchemy.orm import Mapped, mapped_column
9
+
10
+ from app.common.base_model import Base, CreatedAtMixin, IdMixin
11
+
12
+
13
+ class ApiRequestLog(IdMixin, CreatedAtMixin, Base):
14
+ __tablename__ = "api_request_logs"
15
+ __table_args__ = (Index("ix_api_request_logs_created_at", "created_at"),)
16
+
17
+ request_id: Mapped[str] = mapped_column(String(128), index=True)
18
+ started_at: Mapped[datetime] = mapped_column(DateTime(timezone=True))
19
+ method: Mapped[str] = mapped_column(String(16))
20
+ path: Mapped[str] = mapped_column(String(2048))
21
+ route: Mapped[str | None] = mapped_column(String(512), index=True)
22
+ status_code: Mapped[int] = mapped_column(Integer, index=True)
23
+ duration_ms: Mapped[float] = mapped_column(Float)
24
+ account_id: Mapped[UUID | None] = mapped_column(index=True)
25
+ session_id: Mapped[UUID | None] = mapped_column(index=True)
26
+ analysis_id: Mapped[str | None] = mapped_column(String(256), index=True)
27
+ analysis_revision: Mapped[int | None] = mapped_column(Integer)
28
+ request_headers: Mapped[dict] = mapped_column(JSONB)
29
+ query_params: Mapped[dict] = mapped_column(JSONB)
30
+ request_payload: Mapped[dict] = mapped_column(JSONB)
31
+ response_headers: Mapped[dict] = mapped_column(JSONB)
32
+ response_payload: Mapped[dict] = mapped_column(JSONB)
33
+ error_code: Mapped[str | None] = mapped_column(String(128))
34
+ exception_type: Mapped[str | None] = mapped_column(String(128))
35
+ response_complete: Mapped[bool] = mapped_column(Boolean)
36
+ service_version: Mapped[str] = mapped_column(String(128))
backend/app/modules/api_audit/repository.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Cursor-ordered audit queries; payload columns are excluded from list queries."""
2
+
3
+ from sqlalchemy import select, tuple_
4
+ from sqlalchemy.orm import load_only
5
+
6
+ from app.common.base_repository import BaseRepository
7
+ from app.modules.api_audit.models import ApiRequestLog
8
+ from app.modules.api_audit.schemas import AuditLogSummary
9
+
10
+
11
+ class AuditLogRepository(BaseRepository[ApiRequestLog]):
12
+ model = ApiRequestLog
13
+
14
+ async def search(self, paging, filters, since, until):
15
+ model = self.model
16
+ query = select(model).options(load_only(*(getattr(model, k) for k in AuditLogSummary.model_fields)))
17
+ for key, value in filters.items():
18
+ if value is not None:
19
+ query = query.where(getattr(model, key) == value)
20
+ if since is not None:
21
+ query = query.where(model.created_at >= since)
22
+ if until is not None:
23
+ query = query.where(model.created_at < until)
24
+ if paging.cursor:
25
+ query = query.where(tuple_(model.created_at, model.id) <
26
+ tuple_(paging.cursor.created_at, paging.cursor.id))
27
+ query = query.order_by(model.created_at.desc(), model.id.desc()).limit(paging.limit + 1)
28
+ return list(await self.session.scalars(query))
backend/app/modules/api_audit/schemas.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Metadata for log lists and full sanitized bodies for individual records."""
2
+
3
+ from datetime import datetime
4
+ from uuid import UUID
5
+
6
+ from app.common.schemas import ResponseModel
7
+
8
+
9
+ class AuditLogSummary(ResponseModel):
10
+ id: UUID
11
+ created_at: datetime
12
+ started_at: datetime
13
+ request_id: str
14
+ method: str
15
+ path: str
16
+ route: str | None
17
+ status_code: int
18
+ duration_ms: float
19
+ account_id: UUID | None
20
+ session_id: UUID | None
21
+ analysis_id: str | None
22
+ analysis_revision: int | None
23
+ error_code: str | None
24
+ exception_type: str | None
25
+ response_complete: bool
26
+ service_version: str
27
+
28
+
29
+ class AuditLogDetail(AuditLogSummary):
30
+ request_headers: dict
31
+ query_params: dict
32
+ request_payload: dict
33
+ response_headers: dict
34
+ response_payload: dict
backend/app/modules/api_audit/service.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bounded, independent database writes: audit failures never replace an API result."""
2
+
3
+ import asyncio
4
+ 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 encode_cursor
11
+ from app.modules.api_audit.models import ApiRequestLog
12
+ from app.modules.api_audit.repository import AuditLogRepository
13
+ from app.modules.api_audit.schemas import AuditLogDetail, AuditLogSummary
14
+
15
+ log = logging.getLogger(__name__)
16
+
17
+
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:
25
+ # Do not print payloads, connection strings, SQL parameters or exception messages.
26
+ log.error("api_audit_write_failed request_id=%s error_type=%s", record["request_id"], type(exc).__name__)
27
+
28
+
29
+ class AuditLogService:
30
+ def __init__(self, db):
31
+ self.repo = AuditLogRepository(db)
32
+
33
+ async def list(self, paging, filters, since=None, until=None):
34
+ if any(t is not None and t.utcoffset() is None for t in (since, until)):
35
+ raise ValidationFailed(fields={"date_range": "Use timestamps with a timezone."})
36
+ if since is not None and until is not None and since >= until:
37
+ raise ValidationFailed(fields={"until": "Must be after since."})
38
+ if paging.cursor and paging.cursor.created_at.utcoffset() is None:
39
+ raise ValidationFailed(fields={"cursor": "Cursor timestamp needs a timezone."})
40
+ rows = await self.repo.search(paging, filters, since, until)
41
+ more = len(rows) > paging.limit
42
+ rows = rows[:paging.limit]
43
+ return Page[AuditLogSummary](items=[AuditLogSummary.model_validate(row) for row in rows],
44
+ next_cursor=encode_cursor(rows[-1].created_at, rows[-1].id) if more else None)
45
+
46
+ async def get(self, log_id):
47
+ return AuditLogDetail.model_validate(await self.repo.get_or_404(log_id))
backend/app/modules/swing_reports/controller.py CHANGED
@@ -33,5 +33,5 @@ async def create_swing_report(
33
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
34
  payload: Annotated[Any, Body()],
35
  ) -> dict:
36
- request_id = request.headers.get("x-request-id") or uuid.uuid4().hex
37
  return await service.create(account, session_id, payload, request_id)
 
33
  service: Annotated[SwingReportService, Depends(get_swing_report_service)],
34
  payload: Annotated[Any, Body()],
35
  ) -> dict:
36
+ request_id = getattr(request.state, "request_id", None) or uuid.uuid4().hex
37
  return await service.create(account, session_id, payload, request_id)
backend/app/modules/swing_reports/service.py CHANGED
@@ -11,10 +11,12 @@ from datetime import UTC, datetime
11
  from typing import Any
12
  from uuid import UUID
13
 
 
14
  from ai_coach.swing_report import AthleteContext, InvalidPayload, build_report, validate_payload
15
  from sqlalchemy.ext.asyncio import AsyncSession
16
 
17
- from app.core.errors import Conflict, Forbidden, NotFound, Unprocessable
 
18
  from app.modules.accounts.models import Account
19
  from app.modules.billing.entitlement import EntitlementService
20
  from app.modules.swing_reports.repository import SwingReportRepository
@@ -38,6 +40,16 @@ def athlete_context(snapshot: dict | None) -> AthleteContext:
38
  level=level if level in LEVELS else None, height_cm=height_cm)
39
 
40
 
 
 
 
 
 
 
 
 
 
 
41
  class SwingReportService:
42
  def __init__(self, db: AsyncSession, builder: ReportBuilder = build_report):
43
  self.db = db
@@ -66,6 +78,7 @@ class SwingReportService:
66
  return session.report
67
  if parsed.analysis_revision < (session.analysis_revision or 0):
68
  raise Conflict("A newer revision of this analysis has already been reported.", code="STALE_REVISION")
 
69
  if session.analyzed_at is None:
70
  await self.entitlements.ensure_can_analyze(account.id)
71
 
 
11
  from typing import Any
12
  from uuid import UUID
13
 
14
+ from ai_coach.config import get_settings as get_coach_settings
15
  from ai_coach.swing_report import AthleteContext, InvalidPayload, build_report, validate_payload
16
  from sqlalchemy.ext.asyncio import AsyncSession
17
 
18
+ from app.core.config import get_settings
19
+ from app.core.errors import Conflict, Forbidden, NotFound, ServiceUnavailable, Unprocessable
20
  from app.modules.accounts.models import Account
21
  from app.modules.billing.entitlement import EntitlementService
22
  from app.modules.swing_reports.repository import SwingReportRepository
 
40
  level=level if level in LEVELS else None, height_cm=height_cm)
41
 
42
 
43
+ def ensure_coach_configured() -> None:
44
+ """The coaching text must come from Gemini: a missing key is a configuration error, never a silent fallback.
45
+
46
+ Tests (ENV=test) are exempt so they never call the model.
47
+ """
48
+ if get_settings().env != "test" and not get_coach_settings().llm_enabled:
49
+ raise ServiceUnavailable("The AI coach is not configured. Please try again later.",
50
+ code="COACH_NOT_CONFIGURED")
51
+
52
+
53
  class SwingReportService:
54
  def __init__(self, db: AsyncSession, builder: ReportBuilder = build_report):
55
  self.db = db
 
78
  return session.report
79
  if parsed.analysis_revision < (session.analysis_revision or 0):
80
  raise Conflict("A newer revision of this analysis has already been reported.", code="STALE_REVISION")
81
+ ensure_coach_configured()
82
  if session.analyzed_at is None:
83
  await self.entitlements.ensure_can_analyze(account.id)
84
 
backend/docs/openapi.json CHANGED
@@ -2261,6 +2261,324 @@
2261
  }
2262
  }
2263
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2264
  }
2265
  },
2266
  "components": {
@@ -4953,728 +5271,1079 @@
4953
  "type": "string",
4954
  "title": "Refresh Token"
4955
  },
4956
- "expires_in": {
4957
- "type": "integer",
4958
- "title": "Expires In"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4959
  }
4960
  },
4961
- "type": "object",
4962
  "required": [
4963
- "access_token",
4964
- "refresh_token",
4965
- "expires_in"
 
 
 
 
4966
  ],
4967
- "title": "TokensOut"
 
4968
  },
4969
- "UploadIn": {
 
4970
  "properties": {
4971
- "kind": {
4972
- "type": "string",
4973
- "enum": [
4974
- "video",
4975
- "thumbnail"
 
 
 
 
 
 
 
 
 
 
 
 
 
4976
  ],
4977
- "title": "Kind"
4978
  },
4979
- "content_type": {
4980
- "type": "string",
4981
- "maxLength": 40,
4982
- "minLength": 1,
4983
- "title": "Content Type"
 
 
 
 
 
 
 
 
 
4984
  },
4985
- "size_bytes": {
4986
- "type": "integer",
4987
- "exclusiveMinimum": 0.0,
4988
- "title": "Size Bytes"
 
 
 
 
 
 
 
4989
  },
4990
- "duration_sec": {
4991
  "anyOf": [
4992
  {
4993
- "type": "number",
4994
- "exclusiveMinimum": 0.0
4995
  },
4996
  {
4997
  "type": "null"
4998
  }
4999
  ],
5000
- "title": "Duration Sec"
5001
  }
5002
  },
5003
- "additionalProperties": false,
5004
- "type": "object",
5005
  "required": [
5006
- "kind",
5007
- "content_type",
5008
- "size_bytes"
 
 
5009
  ],
5010
- "title": "UploadIn"
 
5011
  },
5012
- "UploadOut": {
 
5013
  "properties": {
5014
- "upload_id": {
5015
- "type": "string",
5016
- "format": "uuid",
5017
- "title": "Upload Id"
5018
- },
5019
- "url": {
5020
- "type": "string",
5021
- "title": "Url"
5022
  },
5023
- "headers": {
5024
- "additionalProperties": {
5025
- "type": "string"
5026
- },
5027
- "type": "object",
5028
- "title": "Headers"
5029
  },
5030
- "expires_at": {
5031
- "type": "string",
5032
- "format": "date-time",
5033
- "title": "Expires At"
5034
- }
5035
- },
5036
- "type": "object",
5037
- "required": [
5038
- "upload_id",
5039
- "url",
5040
- "headers",
5041
- "expires_at"
5042
- ],
5043
- "title": "UploadOut"
5044
- },
5045
- "UserBody": {
5046
- "properties": {
5047
- "user": {
5048
- "$ref": "#/components/schemas/UserOut"
5049
  }
5050
  },
5051
- "type": "object",
5052
  "required": [
5053
- "user"
 
 
5054
  ],
5055
- "title": "UserBody"
 
5056
  },
5057
- "UserOut": {
 
5058
  "properties": {
5059
- "id": {
5060
- "type": "string",
5061
- "format": "uuid",
5062
- "title": "Id"
5063
- },
5064
- "email": {
5065
- "type": "string",
5066
- "title": "Email"
5067
- },
5068
- "role": {
5069
- "type": "string",
5070
- "title": "Role"
5071
  },
5072
- "focus": {
5073
- "type": "string",
5074
- "title": "Focus"
 
 
 
 
 
 
5075
  },
5076
- "profile": {
5077
- "$ref": "#/components/schemas/ProfileOut"
 
 
 
 
 
 
 
 
5078
  },
5079
  "unit": {
5080
- "type": "string",
5081
- "title": "Unit"
 
 
 
 
5082
  },
5083
- "private_videos": {
5084
- "type": "boolean",
5085
- "title": "Private Videos"
 
 
 
 
 
 
 
 
 
 
 
 
 
5086
  },
5087
- "team_code": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5088
  "anyOf": [
5089
  {
 
 
 
 
 
5090
  "type": "string"
5091
  },
5092
  {
5093
  "type": "null"
5094
  }
5095
  ],
5096
- "title": "Team Code"
 
5097
  },
5098
- "created_at": {
5099
- "type": "string",
5100
- "format": "date-time",
5101
- "title": "Created At"
5102
- }
5103
- },
5104
- "type": "object",
5105
- "required": [
5106
- "id",
5107
- "email",
5108
- "role",
5109
- "focus",
5110
- "profile",
5111
- "unit",
5112
- "private_videos",
5113
- "team_code",
5114
- "created_at"
5115
- ],
5116
- "title": "UserOut"
5117
- },
5118
- "WebhookAck": {
5119
- "properties": {},
5120
- "type": "object",
5121
- "title": "WebhookAck"
5122
- },
5123
- "ErrorResponse": {
5124
- "type": "object",
5125
- "required": [
5126
- "error"
5127
- ],
5128
- "properties": {
5129
- "error": {
5130
- "type": "object",
5131
- "required": [
5132
- "code",
5133
- "message"
5134
  ],
5135
- "properties": {
5136
- "code": {
5137
- "type": "string",
5138
- "examples": [
5139
- "VALIDATION",
5140
- "NOT_FOUND",
5141
- "PLAN_LIMIT"
5142
- ]
5143
- },
5144
- "message": {
5145
- "type": "string",
5146
- "description": "Safe to show in the app"
5147
- },
5148
- "fields": {
5149
- "type": "object",
5150
- "additionalProperties": {
5151
- "type": "string"
5152
- },
5153
- "description": "Field path -> problem, for validation errors"
5154
- }
5155
- }
5156
- }
5157
- }
5158
- },
5159
- "ApprovedBenchmark": {
5160
- "additionalProperties": false,
5161
- "properties": {
5162
- "benchmark_id": {
5163
- "minLength": 1,
5164
- "pattern": "\\S",
5165
- "title": "Benchmark Id",
5166
- "type": "string"
5167
- },
5168
- "version": {
5169
- "minLength": 1,
5170
- "pattern": "\\S",
5171
- "title": "Version",
5172
  "type": "string"
5173
  },
5174
- "kind": {
5175
- "const": "reference_interval",
5176
- "title": "Kind",
 
 
 
 
5177
  "type": "string"
5178
  },
5179
- "lower": {
5180
  "anyOf": [
5181
  {
 
 
5182
  "type": "number"
5183
  },
5184
  {
5185
  "type": "null"
5186
  }
5187
  ],
5188
- "title": "Lower"
5189
  },
5190
- "upper": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5191
  "anyOf": [
5192
  {
5193
- "type": "number"
5194
  },
5195
  {
5196
  "type": "null"
5197
  }
5198
- ],
5199
- "title": "Upper"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5200
  },
5201
- "unit": {
5202
- "enum": [
5203
- "deg",
5204
- "cm"
5205
- ],
5206
- "title": "Unit",
5207
  "type": "string"
5208
  },
5209
- "source_reference": {
 
 
 
 
 
5210
  "minLength": 1,
5211
  "pattern": "\\S",
5212
- "title": "Source Reference",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5213
  "type": "string"
 
 
 
 
 
 
 
 
 
 
 
5214
  }
5215
  },
5216
  "required": [
5217
- "benchmark_id",
5218
- "version",
5219
- "kind",
5220
- "lower",
5221
- "upper",
5222
- "unit",
5223
- "source_reference"
 
 
 
5224
  ],
5225
- "title": "ApprovedBenchmark",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5226
  "type": "object"
5227
  },
5228
- "Athlete": {
5229
  "additionalProperties": false,
5230
  "properties": {
5231
- "athlete_id": {
5232
- "minLength": 1,
5233
- "pattern": "\\S",
5234
- "title": "Athlete Id",
 
 
 
5235
  "type": "string"
5236
  },
5237
- "batting_hand": {
5238
  "anyOf": [
5239
  {
5240
- "enum": [
5241
- "left",
5242
- "right"
5243
- ],
5244
- "type": "string"
5245
  },
5246
  {
5247
  "type": "null"
5248
  }
5249
  ],
5250
- "title": "Batting Hand"
5251
  },
5252
- "lead_foot": {
5253
  "anyOf": [
5254
  {
5255
- "enum": [
5256
- "left",
5257
- "right"
5258
- ],
5259
- "type": "string"
5260
  },
5261
  {
5262
  "type": "null"
5263
  }
5264
  ],
5265
- "title": "Lead Foot"
5266
  },
5267
- "age_years": {
5268
  "anyOf": [
5269
  {
5270
- "minimum": 0,
5271
- "type": "integer"
 
 
 
 
5272
  },
5273
  {
5274
  "type": "null"
5275
  }
5276
  ],
5277
- "title": "Age Years"
5278
  },
5279
- "height_cm": {
5280
- "anyOf": [
5281
- {
5282
- "exclusiveMinimum": 0,
5283
- "type": "number"
5284
- },
5285
- {
5286
- "type": "null"
5287
- }
5288
- ],
5289
- "title": "Height Cm"
 
 
 
 
 
 
 
 
 
 
 
5290
  }
5291
  },
5292
  "required": [
5293
- "athlete_id",
5294
- "batting_hand",
5295
- "lead_foot",
5296
- "age_years",
5297
- "height_cm"
5298
  ],
5299
- "title": "Athlete",
5300
  "type": "object"
5301
  },
5302
- "Events": {
5303
- "additionalProperties": false,
5304
  "properties": {
5305
- "stride_start": {
5306
- "$ref": "#/components/schemas/SwingEvent"
 
 
5307
  },
5308
- "front_foot_down": {
5309
- "$ref": "#/components/schemas/SwingEvent"
 
 
5310
  },
5311
- "contact": {
5312
- "$ref": "#/components/schemas/SwingEvent"
5313
- }
5314
- },
5315
- "required": [
5316
- "stride_start",
5317
- "front_foot_down",
5318
- "contact"
5319
- ],
5320
- "title": "Events",
5321
- "type": "object"
5322
- },
5323
- "Measurement": {
5324
- "additionalProperties": false,
5325
- "properties": {
5326
- "metric_id": {
5327
- "enum": [
5328
- "hip_shoulder_separation_at_foot_down",
5329
- "stride_relative_length",
5330
- "hip_shoulder_separation_at_contact"
5331
- ],
5332
- "title": "Metric Id",
5333
- "type": "string"
5334
  },
5335
- "group": {
5336
- "enum": [
5337
- "balance_load",
5338
- "stride",
5339
- "power_move",
5340
- "contact_follow_through"
5341
- ],
5342
- "title": "Group",
5343
- "type": "string"
5344
  },
5345
- "value": {
 
 
 
 
 
 
 
 
5346
  "anyOf": [
5347
  {
5348
- "type": "number"
5349
  },
5350
  {
5351
  "type": "null"
5352
  }
5353
  ],
5354
- "title": "Value"
5355
  },
5356
- "unit": {
5357
- "enum": [
5358
- "deg",
5359
- "cm"
5360
- ],
5361
- "title": "Unit",
5362
- "type": "string"
5363
  },
5364
- "event_id": {
 
 
 
 
5365
  "anyOf": [
5366
  {
5367
- "enum": [
5368
- "stride_start",
5369
- "front_foot_down",
5370
- "contact"
5371
- ],
5372
- "type": "string"
5373
  },
5374
  {
5375
  "type": "null"
5376
  }
5377
  ],
5378
- "default": null,
5379
- "title": "Event Id"
5380
  },
5381
- "start_event_id": {
5382
  "anyOf": [
5383
  {
5384
- "enum": [
5385
- "stride_start",
5386
- "front_foot_down",
5387
- "contact"
5388
- ],
5389
- "type": "string"
5390
  },
5391
  {
5392
  "type": "null"
5393
  }
5394
  ],
5395
- "default": null,
5396
- "title": "Start Event Id"
5397
  },
5398
- "end_event_id": {
5399
  "anyOf": [
5400
  {
5401
- "enum": [
5402
- "stride_start",
5403
- "front_foot_down",
5404
- "contact"
5405
- ],
5406
  "type": "string"
5407
  },
5408
  {
5409
  "type": "null"
5410
  }
5411
  ],
5412
- "default": null,
5413
- "title": "End Event Id"
5414
- },
5415
- "reference": {
5416
- "enum": [
5417
- "signed_horizontal_shoulder_minus_hip_heading",
5418
- "lead_ankle_displacement_relative_to_rear_ankle"
5419
- ],
5420
- "title": "Reference",
5421
- "type": "string"
5422
  },
5423
- "status": {
5424
- "enum": [
5425
- "available",
5426
- "limited",
5427
- "unavailable"
 
 
 
5428
  ],
5429
- "title": "Status",
5430
- "type": "string"
5431
  },
5432
- "confidence": {
5433
  "anyOf": [
5434
  {
5435
- "maximum": 1,
5436
- "minimum": 0,
5437
- "type": "number"
5438
  },
5439
  {
5440
  "type": "null"
5441
  }
5442
  ],
5443
- "title": "Confidence"
5444
- },
5445
- "uses_interpolated_input": {
5446
- "title": "Uses Interpolated Input",
5447
- "type": "boolean"
5448
  },
5449
- "reasons": {
5450
- "items": {
5451
- "enum": [
5452
- "contact_not_verified",
5453
- "contact_not_applicable",
5454
- "event_not_detected",
5455
- "event_timing_uncertain",
5456
- "required_event_unavailable",
5457
- "required_event_limited",
5458
- "lead_foot_unknown",
5459
- "required_landmarks_unusable",
5460
- "ground_plane_unknown",
5461
- "scale_is_model_estimated",
5462
- "scale_unknown",
5463
- "excessive_interpolation",
5464
- "occlusion_unresolved",
5465
- "temporal_inconsistency"
5466
- ],
5467
- "type": "string"
5468
- },
5469
- "title": "Reasons",
5470
- "type": "array"
5471
- },
5472
- "benchmark": {
5473
  "anyOf": [
5474
  {
5475
- "$ref": "#/components/schemas/ApprovedBenchmark"
5476
  },
5477
  {
5478
  "type": "null"
5479
  }
5480
- ]
 
 
 
 
 
 
 
 
 
5481
  }
5482
  },
 
5483
  "required": [
5484
- "metric_id",
5485
- "group",
5486
- "value",
5487
- "unit",
5488
- "reference",
5489
- "status",
5490
- "confidence",
5491
- "uses_interpolated_input",
5492
- "reasons",
5493
- "benchmark"
 
 
 
 
 
 
 
5494
  ],
5495
- "title": "Measurement",
5496
- "type": "object"
5497
  },
5498
- "SwingAnalysisPayload": {
5499
- "additionalProperties": false,
5500
  "properties": {
5501
- "schema_version": {
5502
- "const": "1.0",
5503
- "title": "Schema Version",
5504
- "type": "string"
5505
  },
5506
- "analysis_id": {
5507
- "minLength": 1,
5508
- "pattern": "\\S",
5509
- "title": "Analysis Id",
5510
- "type": "string"
5511
  },
5512
- "analysis_revision": {
5513
- "minimum": 1,
5514
- "title": "Analysis Revision",
5515
- "type": "integer"
5516
  },
5517
- "swing_id": {
5518
- "minLength": 1,
5519
- "pattern": "\\S",
5520
- "title": "Swing Id",
5521
- "type": "string"
5522
  },
5523
- "status": {
5524
- "const": "completed",
5525
- "title": "Status",
5526
- "type": "string"
5527
  },
5528
- "athlete": {
5529
- "$ref": "#/components/schemas/Athlete"
 
5530
  },
5531
- "context": {
5532
- "$ref": "#/components/schemas/SwingContext"
 
 
 
 
 
 
 
 
5533
  },
5534
- "measurement_definitions_version": {
5535
- "const": "1.0",
5536
- "title": "Measurement Definitions Version",
5537
- "type": "string"
5538
  },
5539
- "events": {
5540
- "$ref": "#/components/schemas/Events"
 
5541
  },
5542
- "measurements": {
5543
- "items": {
5544
- "$ref": "#/components/schemas/Measurement"
5545
- },
5546
- "minItems": 1,
5547
- "title": "Measurements",
5548
- "type": "array"
5549
- }
5550
- },
5551
- "required": [
5552
- "schema_version",
5553
- "analysis_id",
5554
- "analysis_revision",
5555
- "swing_id",
5556
- "status",
5557
- "athlete",
5558
- "context",
5559
- "measurement_definitions_version",
5560
- "events",
5561
- "measurements"
5562
- ],
5563
- "title": "SwingAnalysisPayload",
5564
- "type": "object"
5565
- },
5566
- "SwingContext": {
5567
- "additionalProperties": false,
5568
- "properties": {
5569
- "sport": {
5570
- "const": "baseball",
5571
- "title": "Sport",
5572
- "type": "string"
5573
  },
5574
- "practice_type": {
5575
- "enum": [
5576
- "tee",
5577
- "front_toss",
5578
- "side_toss",
5579
- "pitching_machine",
5580
- "live_pitching",
5581
- "game",
5582
- "dry_swing",
5583
- "unknown"
5584
  ],
5585
- "title": "Practice Type",
5586
- "type": "string"
5587
- }
5588
- },
5589
- "required": [
5590
- "sport",
5591
- "practice_type"
5592
- ],
5593
- "title": "SwingContext",
5594
- "type": "object"
5595
- },
5596
- "SwingEvent": {
5597
- "additionalProperties": false,
5598
- "properties": {
5599
- "status": {
5600
- "enum": [
5601
- "available",
5602
- "limited",
5603
- "unavailable"
5604
  ],
5605
- "title": "Status",
5606
- "type": "string"
5607
  },
5608
- "video_time_s": {
5609
  "anyOf": [
5610
  {
5611
- "type": "number"
5612
  },
5613
  {
5614
  "type": "null"
5615
  }
5616
  ],
5617
- "title": "Video Time S"
5618
  },
5619
- "capture_time_s": {
5620
  "anyOf": [
5621
  {
5622
- "type": "number"
5623
  },
5624
  {
5625
  "type": "null"
5626
  }
5627
  ],
5628
- "title": "Capture Time S"
5629
  },
5630
- "source": {
5631
  "anyOf": [
5632
  {
5633
- "enum": [
5634
- "manual_review",
5635
- "pose_estimated",
5636
- "bat_ball_detector"
5637
- ],
5638
  "type": "string"
5639
  },
5640
  {
5641
  "type": "null"
5642
  }
5643
  ],
5644
- "title": "Source"
5645
  },
5646
- "reasons": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5647
  "items": {
5648
- "enum": [
5649
- "contact_not_verified",
5650
- "contact_not_applicable",
5651
- "event_not_detected",
5652
- "event_timing_uncertain",
5653
- "required_event_unavailable",
5654
- "required_event_limited",
5655
- "lead_foot_unknown",
5656
- "required_landmarks_unusable",
5657
- "ground_plane_unknown",
5658
- "scale_is_model_estimated",
5659
- "scale_unknown",
5660
- "excessive_interpolation",
5661
- "occlusion_unresolved",
5662
- "temporal_inconsistency"
5663
- ],
5664
- "type": "string"
5665
  },
5666
- "title": "Reasons",
5667
- "type": "array"
 
 
 
 
 
 
 
 
 
 
 
5668
  }
5669
  },
 
5670
  "required": [
5671
- "status",
5672
- "video_time_s",
5673
- "capture_time_s",
5674
- "source"
5675
  ],
5676
- "title": "SwingEvent",
5677
- "type": "object"
5678
  }
5679
  }
5680
  }
 
2261
  }
2262
  }
2263
  }
2264
+ },
2265
+ "/v1/admin/api-logs": {
2266
+ "get": {
2267
+ "tags": [
2268
+ "API logs"
2269
+ ],
2270
+ "summary": "List Logs",
2271
+ "operationId": "list_logs_v1_admin_api_logs_get",
2272
+ "parameters": [
2273
+ {
2274
+ "name": "request_id",
2275
+ "in": "query",
2276
+ "required": false,
2277
+ "schema": {
2278
+ "anyOf": [
2279
+ {
2280
+ "type": "string",
2281
+ "maxLength": 128
2282
+ },
2283
+ {
2284
+ "type": "null"
2285
+ }
2286
+ ],
2287
+ "title": "Request Id"
2288
+ }
2289
+ },
2290
+ {
2291
+ "name": "session_id",
2292
+ "in": "query",
2293
+ "required": false,
2294
+ "schema": {
2295
+ "anyOf": [
2296
+ {
2297
+ "type": "string",
2298
+ "format": "uuid"
2299
+ },
2300
+ {
2301
+ "type": "null"
2302
+ }
2303
+ ],
2304
+ "title": "Session Id"
2305
+ }
2306
+ },
2307
+ {
2308
+ "name": "analysis_id",
2309
+ "in": "query",
2310
+ "required": false,
2311
+ "schema": {
2312
+ "anyOf": [
2313
+ {
2314
+ "type": "string",
2315
+ "maxLength": 256
2316
+ },
2317
+ {
2318
+ "type": "null"
2319
+ }
2320
+ ],
2321
+ "title": "Analysis Id"
2322
+ }
2323
+ },
2324
+ {
2325
+ "name": "account_id",
2326
+ "in": "query",
2327
+ "required": false,
2328
+ "schema": {
2329
+ "anyOf": [
2330
+ {
2331
+ "type": "string",
2332
+ "format": "uuid"
2333
+ },
2334
+ {
2335
+ "type": "null"
2336
+ }
2337
+ ],
2338
+ "title": "Account Id"
2339
+ }
2340
+ },
2341
+ {
2342
+ "name": "status_code",
2343
+ "in": "query",
2344
+ "required": false,
2345
+ "schema": {
2346
+ "anyOf": [
2347
+ {
2348
+ "type": "integer",
2349
+ "maximum": 599,
2350
+ "minimum": 100
2351
+ },
2352
+ {
2353
+ "type": "null"
2354
+ }
2355
+ ],
2356
+ "title": "Status Code"
2357
+ }
2358
+ },
2359
+ {
2360
+ "name": "method",
2361
+ "in": "query",
2362
+ "required": false,
2363
+ "schema": {
2364
+ "anyOf": [
2365
+ {
2366
+ "enum": [
2367
+ "GET",
2368
+ "POST",
2369
+ "PUT",
2370
+ "PATCH",
2371
+ "DELETE",
2372
+ "HEAD",
2373
+ "OPTIONS"
2374
+ ],
2375
+ "type": "string"
2376
+ },
2377
+ {
2378
+ "type": "null"
2379
+ }
2380
+ ],
2381
+ "title": "Method"
2382
+ }
2383
+ },
2384
+ {
2385
+ "name": "route",
2386
+ "in": "query",
2387
+ "required": false,
2388
+ "schema": {
2389
+ "anyOf": [
2390
+ {
2391
+ "type": "string",
2392
+ "maxLength": 512
2393
+ },
2394
+ {
2395
+ "type": "null"
2396
+ }
2397
+ ],
2398
+ "title": "Route"
2399
+ }
2400
+ },
2401
+ {
2402
+ "name": "since",
2403
+ "in": "query",
2404
+ "required": false,
2405
+ "schema": {
2406
+ "anyOf": [
2407
+ {
2408
+ "type": "string",
2409
+ "format": "date-time"
2410
+ },
2411
+ {
2412
+ "type": "null"
2413
+ }
2414
+ ],
2415
+ "title": "Since"
2416
+ }
2417
+ },
2418
+ {
2419
+ "name": "until",
2420
+ "in": "query",
2421
+ "required": false,
2422
+ "schema": {
2423
+ "anyOf": [
2424
+ {
2425
+ "type": "string",
2426
+ "format": "date-time"
2427
+ },
2428
+ {
2429
+ "type": "null"
2430
+ }
2431
+ ],
2432
+ "title": "Until"
2433
+ }
2434
+ },
2435
+ {
2436
+ "name": "limit",
2437
+ "in": "query",
2438
+ "required": false,
2439
+ "schema": {
2440
+ "type": "integer",
2441
+ "maximum": 200,
2442
+ "minimum": 1,
2443
+ "default": 50,
2444
+ "title": "Limit"
2445
+ }
2446
+ },
2447
+ {
2448
+ "name": "cursor",
2449
+ "in": "query",
2450
+ "required": false,
2451
+ "schema": {
2452
+ "anyOf": [
2453
+ {
2454
+ "type": "string"
2455
+ },
2456
+ {
2457
+ "type": "null"
2458
+ }
2459
+ ],
2460
+ "title": "Cursor"
2461
+ }
2462
+ },
2463
+ {
2464
+ "name": "authorization",
2465
+ "in": "header",
2466
+ "required": false,
2467
+ "schema": {
2468
+ "anyOf": [
2469
+ {
2470
+ "type": "string"
2471
+ },
2472
+ {
2473
+ "type": "null"
2474
+ }
2475
+ ],
2476
+ "title": "Authorization"
2477
+ }
2478
+ }
2479
+ ],
2480
+ "responses": {
2481
+ "200": {
2482
+ "description": "Successful Response",
2483
+ "content": {
2484
+ "application/json": {
2485
+ "schema": {
2486
+ "$ref": "#/components/schemas/Page_AuditLogSummary_"
2487
+ }
2488
+ }
2489
+ }
2490
+ },
2491
+ "400": {
2492
+ "description": "Error",
2493
+ "content": {
2494
+ "application/json": {
2495
+ "schema": {
2496
+ "$ref": "#/components/schemas/ErrorResponse"
2497
+ }
2498
+ }
2499
+ }
2500
+ },
2501
+ "default": {
2502
+ "description": "Error",
2503
+ "content": {
2504
+ "application/json": {
2505
+ "schema": {
2506
+ "$ref": "#/components/schemas/ErrorResponse"
2507
+ }
2508
+ }
2509
+ }
2510
+ }
2511
+ }
2512
+ }
2513
+ },
2514
+ "/v1/admin/api-logs/{log_id}": {
2515
+ "get": {
2516
+ "tags": [
2517
+ "API logs"
2518
+ ],
2519
+ "summary": "Get Log",
2520
+ "operationId": "get_log_v1_admin_api_logs__log_id__get",
2521
+ "parameters": [
2522
+ {
2523
+ "name": "log_id",
2524
+ "in": "path",
2525
+ "required": true,
2526
+ "schema": {
2527
+ "type": "string",
2528
+ "format": "uuid",
2529
+ "title": "Log Id"
2530
+ }
2531
+ },
2532
+ {
2533
+ "name": "authorization",
2534
+ "in": "header",
2535
+ "required": false,
2536
+ "schema": {
2537
+ "anyOf": [
2538
+ {
2539
+ "type": "string"
2540
+ },
2541
+ {
2542
+ "type": "null"
2543
+ }
2544
+ ],
2545
+ "title": "Authorization"
2546
+ }
2547
+ }
2548
+ ],
2549
+ "responses": {
2550
+ "200": {
2551
+ "description": "Successful Response",
2552
+ "content": {
2553
+ "application/json": {
2554
+ "schema": {
2555
+ "$ref": "#/components/schemas/AuditLogDetail"
2556
+ }
2557
+ }
2558
+ }
2559
+ },
2560
+ "400": {
2561
+ "description": "Error",
2562
+ "content": {
2563
+ "application/json": {
2564
+ "schema": {
2565
+ "$ref": "#/components/schemas/ErrorResponse"
2566
+ }
2567
+ }
2568
+ }
2569
+ },
2570
+ "default": {
2571
+ "description": "Error",
2572
+ "content": {
2573
+ "application/json": {
2574
+ "schema": {
2575
+ "$ref": "#/components/schemas/ErrorResponse"
2576
+ }
2577
+ }
2578
+ }
2579
+ }
2580
+ }
2581
+ }
2582
  }
2583
  },
2584
  "components": {
 
5271
  "type": "string",
5272
  "title": "Refresh Token"
5273
  },
5274
+ "expires_in": {
5275
+ "type": "integer",
5276
+ "title": "Expires In"
5277
+ }
5278
+ },
5279
+ "type": "object",
5280
+ "required": [
5281
+ "access_token",
5282
+ "refresh_token",
5283
+ "expires_in"
5284
+ ],
5285
+ "title": "TokensOut"
5286
+ },
5287
+ "UploadIn": {
5288
+ "properties": {
5289
+ "kind": {
5290
+ "type": "string",
5291
+ "enum": [
5292
+ "video",
5293
+ "thumbnail"
5294
+ ],
5295
+ "title": "Kind"
5296
+ },
5297
+ "content_type": {
5298
+ "type": "string",
5299
+ "maxLength": 40,
5300
+ "minLength": 1,
5301
+ "title": "Content Type"
5302
+ },
5303
+ "size_bytes": {
5304
+ "type": "integer",
5305
+ "exclusiveMinimum": 0.0,
5306
+ "title": "Size Bytes"
5307
+ },
5308
+ "duration_sec": {
5309
+ "anyOf": [
5310
+ {
5311
+ "type": "number",
5312
+ "exclusiveMinimum": 0.0
5313
+ },
5314
+ {
5315
+ "type": "null"
5316
+ }
5317
+ ],
5318
+ "title": "Duration Sec"
5319
+ }
5320
+ },
5321
+ "additionalProperties": false,
5322
+ "type": "object",
5323
+ "required": [
5324
+ "kind",
5325
+ "content_type",
5326
+ "size_bytes"
5327
+ ],
5328
+ "title": "UploadIn"
5329
+ },
5330
+ "UploadOut": {
5331
+ "properties": {
5332
+ "upload_id": {
5333
+ "type": "string",
5334
+ "format": "uuid",
5335
+ "title": "Upload Id"
5336
+ },
5337
+ "url": {
5338
+ "type": "string",
5339
+ "title": "Url"
5340
+ },
5341
+ "headers": {
5342
+ "additionalProperties": {
5343
+ "type": "string"
5344
+ },
5345
+ "type": "object",
5346
+ "title": "Headers"
5347
+ },
5348
+ "expires_at": {
5349
+ "type": "string",
5350
+ "format": "date-time",
5351
+ "title": "Expires At"
5352
+ }
5353
+ },
5354
+ "type": "object",
5355
+ "required": [
5356
+ "upload_id",
5357
+ "url",
5358
+ "headers",
5359
+ "expires_at"
5360
+ ],
5361
+ "title": "UploadOut"
5362
+ },
5363
+ "UserBody": {
5364
+ "properties": {
5365
+ "user": {
5366
+ "$ref": "#/components/schemas/UserOut"
5367
+ }
5368
+ },
5369
+ "type": "object",
5370
+ "required": [
5371
+ "user"
5372
+ ],
5373
+ "title": "UserBody"
5374
+ },
5375
+ "UserOut": {
5376
+ "properties": {
5377
+ "id": {
5378
+ "type": "string",
5379
+ "format": "uuid",
5380
+ "title": "Id"
5381
+ },
5382
+ "email": {
5383
+ "type": "string",
5384
+ "title": "Email"
5385
+ },
5386
+ "role": {
5387
+ "type": "string",
5388
+ "title": "Role"
5389
+ },
5390
+ "focus": {
5391
+ "type": "string",
5392
+ "title": "Focus"
5393
+ },
5394
+ "profile": {
5395
+ "$ref": "#/components/schemas/ProfileOut"
5396
+ },
5397
+ "unit": {
5398
+ "type": "string",
5399
+ "title": "Unit"
5400
+ },
5401
+ "private_videos": {
5402
+ "type": "boolean",
5403
+ "title": "Private Videos"
5404
+ },
5405
+ "team_code": {
5406
+ "anyOf": [
5407
+ {
5408
+ "type": "string"
5409
+ },
5410
+ {
5411
+ "type": "null"
5412
+ }
5413
+ ],
5414
+ "title": "Team Code"
5415
+ },
5416
+ "created_at": {
5417
+ "type": "string",
5418
+ "format": "date-time",
5419
+ "title": "Created At"
5420
+ }
5421
+ },
5422
+ "type": "object",
5423
+ "required": [
5424
+ "id",
5425
+ "email",
5426
+ "role",
5427
+ "focus",
5428
+ "profile",
5429
+ "unit",
5430
+ "private_videos",
5431
+ "team_code",
5432
+ "created_at"
5433
+ ],
5434
+ "title": "UserOut"
5435
+ },
5436
+ "WebhookAck": {
5437
+ "properties": {},
5438
+ "type": "object",
5439
+ "title": "WebhookAck"
5440
+ },
5441
+ "ErrorResponse": {
5442
+ "type": "object",
5443
+ "required": [
5444
+ "error"
5445
+ ],
5446
+ "properties": {
5447
+ "error": {
5448
+ "type": "object",
5449
+ "required": [
5450
+ "code",
5451
+ "message"
5452
+ ],
5453
+ "properties": {
5454
+ "code": {
5455
+ "type": "string",
5456
+ "examples": [
5457
+ "VALIDATION",
5458
+ "NOT_FOUND",
5459
+ "PLAN_LIMIT"
5460
+ ]
5461
+ },
5462
+ "message": {
5463
+ "type": "string",
5464
+ "description": "Safe to show in the app"
5465
+ },
5466
+ "fields": {
5467
+ "type": "object",
5468
+ "additionalProperties": {
5469
+ "type": "string"
5470
+ },
5471
+ "description": "Field path -> problem, for validation errors"
5472
+ }
5473
+ }
5474
+ }
5475
+ }
5476
+ },
5477
+ "ApprovedBenchmark": {
5478
+ "additionalProperties": false,
5479
+ "properties": {
5480
+ "benchmark_id": {
5481
+ "minLength": 1,
5482
+ "pattern": "\\S",
5483
+ "title": "Benchmark Id",
5484
+ "type": "string"
5485
+ },
5486
+ "version": {
5487
+ "minLength": 1,
5488
+ "pattern": "\\S",
5489
+ "title": "Version",
5490
+ "type": "string"
5491
+ },
5492
+ "kind": {
5493
+ "const": "reference_interval",
5494
+ "title": "Kind",
5495
+ "type": "string"
5496
+ },
5497
+ "lower": {
5498
+ "anyOf": [
5499
+ {
5500
+ "type": "number"
5501
+ },
5502
+ {
5503
+ "type": "null"
5504
+ }
5505
+ ],
5506
+ "title": "Lower"
5507
+ },
5508
+ "upper": {
5509
+ "anyOf": [
5510
+ {
5511
+ "type": "number"
5512
+ },
5513
+ {
5514
+ "type": "null"
5515
+ }
5516
+ ],
5517
+ "title": "Upper"
5518
+ },
5519
+ "unit": {
5520
+ "enum": [
5521
+ "deg",
5522
+ "cm"
5523
+ ],
5524
+ "title": "Unit",
5525
+ "type": "string"
5526
+ },
5527
+ "source_reference": {
5528
+ "minLength": 1,
5529
+ "pattern": "\\S",
5530
+ "title": "Source Reference",
5531
+ "type": "string"
5532
  }
5533
  },
 
5534
  "required": [
5535
+ "benchmark_id",
5536
+ "version",
5537
+ "kind",
5538
+ "lower",
5539
+ "upper",
5540
+ "unit",
5541
+ "source_reference"
5542
  ],
5543
+ "title": "ApprovedBenchmark",
5544
+ "type": "object"
5545
  },
5546
+ "Athlete": {
5547
+ "additionalProperties": false,
5548
  "properties": {
5549
+ "athlete_id": {
5550
+ "minLength": 1,
5551
+ "pattern": "\\S",
5552
+ "title": "Athlete Id",
5553
+ "type": "string"
5554
+ },
5555
+ "batting_hand": {
5556
+ "anyOf": [
5557
+ {
5558
+ "enum": [
5559
+ "left",
5560
+ "right"
5561
+ ],
5562
+ "type": "string"
5563
+ },
5564
+ {
5565
+ "type": "null"
5566
+ }
5567
  ],
5568
+ "title": "Batting Hand"
5569
  },
5570
+ "lead_foot": {
5571
+ "anyOf": [
5572
+ {
5573
+ "enum": [
5574
+ "left",
5575
+ "right"
5576
+ ],
5577
+ "type": "string"
5578
+ },
5579
+ {
5580
+ "type": "null"
5581
+ }
5582
+ ],
5583
+ "title": "Lead Foot"
5584
  },
5585
+ "age_years": {
5586
+ "anyOf": [
5587
+ {
5588
+ "minimum": 0,
5589
+ "type": "integer"
5590
+ },
5591
+ {
5592
+ "type": "null"
5593
+ }
5594
+ ],
5595
+ "title": "Age Years"
5596
  },
5597
+ "height_cm": {
5598
  "anyOf": [
5599
  {
5600
+ "exclusiveMinimum": 0,
5601
+ "type": "number"
5602
  },
5603
  {
5604
  "type": "null"
5605
  }
5606
  ],
5607
+ "title": "Height Cm"
5608
  }
5609
  },
 
 
5610
  "required": [
5611
+ "athlete_id",
5612
+ "batting_hand",
5613
+ "lead_foot",
5614
+ "age_years",
5615
+ "height_cm"
5616
  ],
5617
+ "title": "Athlete",
5618
+ "type": "object"
5619
  },
5620
+ "Events": {
5621
+ "additionalProperties": false,
5622
  "properties": {
5623
+ "stride_start": {
5624
+ "$ref": "#/components/schemas/SwingEvent"
 
 
 
 
 
 
5625
  },
5626
+ "front_foot_down": {
5627
+ "$ref": "#/components/schemas/SwingEvent"
 
 
 
 
5628
  },
5629
+ "contact": {
5630
+ "$ref": "#/components/schemas/SwingEvent"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5631
  }
5632
  },
 
5633
  "required": [
5634
+ "stride_start",
5635
+ "front_foot_down",
5636
+ "contact"
5637
  ],
5638
+ "title": "Events",
5639
+ "type": "object"
5640
  },
5641
+ "Measurement": {
5642
+ "additionalProperties": false,
5643
  "properties": {
5644
+ "metric_id": {
5645
+ "enum": [
5646
+ "hip_shoulder_separation_at_foot_down",
5647
+ "stride_relative_length",
5648
+ "hip_shoulder_separation_at_contact"
5649
+ ],
5650
+ "title": "Metric Id",
5651
+ "type": "string"
 
 
 
 
5652
  },
5653
+ "group": {
5654
+ "enum": [
5655
+ "balance_load",
5656
+ "stride",
5657
+ "power_move",
5658
+ "contact_follow_through"
5659
+ ],
5660
+ "title": "Group",
5661
+ "type": "string"
5662
  },
5663
+ "value": {
5664
+ "anyOf": [
5665
+ {
5666
+ "type": "number"
5667
+ },
5668
+ {
5669
+ "type": "null"
5670
+ }
5671
+ ],
5672
+ "title": "Value"
5673
  },
5674
  "unit": {
5675
+ "enum": [
5676
+ "deg",
5677
+ "cm"
5678
+ ],
5679
+ "title": "Unit",
5680
+ "type": "string"
5681
  },
5682
+ "event_id": {
5683
+ "anyOf": [
5684
+ {
5685
+ "enum": [
5686
+ "stride_start",
5687
+ "front_foot_down",
5688
+ "contact"
5689
+ ],
5690
+ "type": "string"
5691
+ },
5692
+ {
5693
+ "type": "null"
5694
+ }
5695
+ ],
5696
+ "default": null,
5697
+ "title": "Event Id"
5698
  },
5699
+ "start_event_id": {
5700
+ "anyOf": [
5701
+ {
5702
+ "enum": [
5703
+ "stride_start",
5704
+ "front_foot_down",
5705
+ "contact"
5706
+ ],
5707
+ "type": "string"
5708
+ },
5709
+ {
5710
+ "type": "null"
5711
+ }
5712
+ ],
5713
+ "default": null,
5714
+ "title": "Start Event Id"
5715
+ },
5716
+ "end_event_id": {
5717
  "anyOf": [
5718
  {
5719
+ "enum": [
5720
+ "stride_start",
5721
+ "front_foot_down",
5722
+ "contact"
5723
+ ],
5724
  "type": "string"
5725
  },
5726
  {
5727
  "type": "null"
5728
  }
5729
  ],
5730
+ "default": null,
5731
+ "title": "End Event Id"
5732
  },
5733
+ "reference": {
5734
+ "enum": [
5735
+ "signed_horizontal_shoulder_minus_hip_heading",
5736
+ "lead_ankle_displacement_relative_to_rear_ankle"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5737
  ],
5738
+ "title": "Reference",
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5739
  "type": "string"
5740
  },
5741
+ "status": {
5742
+ "enum": [
5743
+ "available",
5744
+ "limited",
5745
+ "unavailable"
5746
+ ],
5747
+ "title": "Status",
5748
  "type": "string"
5749
  },
5750
+ "confidence": {
5751
  "anyOf": [
5752
  {
5753
+ "maximum": 1,
5754
+ "minimum": 0,
5755
  "type": "number"
5756
  },
5757
  {
5758
  "type": "null"
5759
  }
5760
  ],
5761
+ "title": "Confidence"
5762
  },
5763
+ "uses_interpolated_input": {
5764
+ "title": "Uses Interpolated Input",
5765
+ "type": "boolean"
5766
+ },
5767
+ "reasons": {
5768
+ "items": {
5769
+ "enum": [
5770
+ "contact_not_verified",
5771
+ "contact_not_applicable",
5772
+ "event_not_detected",
5773
+ "event_timing_uncertain",
5774
+ "required_event_unavailable",
5775
+ "required_event_limited",
5776
+ "lead_foot_unknown",
5777
+ "required_landmarks_unusable",
5778
+ "ground_plane_unknown",
5779
+ "scale_is_model_estimated",
5780
+ "scale_unknown",
5781
+ "excessive_interpolation",
5782
+ "occlusion_unresolved",
5783
+ "temporal_inconsistency"
5784
+ ],
5785
+ "type": "string"
5786
+ },
5787
+ "title": "Reasons",
5788
+ "type": "array"
5789
+ },
5790
+ "benchmark": {
5791
  "anyOf": [
5792
  {
5793
+ "$ref": "#/components/schemas/ApprovedBenchmark"
5794
  },
5795
  {
5796
  "type": "null"
5797
  }
5798
+ ]
5799
+ }
5800
+ },
5801
+ "required": [
5802
+ "metric_id",
5803
+ "group",
5804
+ "value",
5805
+ "unit",
5806
+ "reference",
5807
+ "status",
5808
+ "confidence",
5809
+ "uses_interpolated_input",
5810
+ "reasons",
5811
+ "benchmark"
5812
+ ],
5813
+ "title": "Measurement",
5814
+ "type": "object"
5815
+ },
5816
+ "SwingAnalysisPayload": {
5817
+ "additionalProperties": false,
5818
+ "properties": {
5819
+ "schema_version": {
5820
+ "const": "1.0",
5821
+ "title": "Schema Version",
5822
+ "type": "string"
5823
  },
5824
+ "analysis_id": {
5825
+ "minLength": 1,
5826
+ "pattern": "\\S",
5827
+ "title": "Analysis Id",
 
 
5828
  "type": "string"
5829
  },
5830
+ "analysis_revision": {
5831
+ "minimum": 1,
5832
+ "title": "Analysis Revision",
5833
+ "type": "integer"
5834
+ },
5835
+ "swing_id": {
5836
  "minLength": 1,
5837
  "pattern": "\\S",
5838
+ "title": "Swing Id",
5839
+ "type": "string"
5840
+ },
5841
+ "status": {
5842
+ "const": "completed",
5843
+ "title": "Status",
5844
+ "type": "string"
5845
+ },
5846
+ "athlete": {
5847
+ "$ref": "#/components/schemas/Athlete"
5848
+ },
5849
+ "context": {
5850
+ "$ref": "#/components/schemas/SwingContext"
5851
+ },
5852
+ "measurement_definitions_version": {
5853
+ "const": "1.0",
5854
+ "title": "Measurement Definitions Version",
5855
  "type": "string"
5856
+ },
5857
+ "events": {
5858
+ "$ref": "#/components/schemas/Events"
5859
+ },
5860
+ "measurements": {
5861
+ "items": {
5862
+ "$ref": "#/components/schemas/Measurement"
5863
+ },
5864
+ "minItems": 1,
5865
+ "title": "Measurements",
5866
+ "type": "array"
5867
  }
5868
  },
5869
  "required": [
5870
+ "schema_version",
5871
+ "analysis_id",
5872
+ "analysis_revision",
5873
+ "swing_id",
5874
+ "status",
5875
+ "athlete",
5876
+ "context",
5877
+ "measurement_definitions_version",
5878
+ "events",
5879
+ "measurements"
5880
  ],
5881
+ "title": "SwingAnalysisPayload",
5882
+ "type": "object"
5883
+ },
5884
+ "SwingContext": {
5885
+ "additionalProperties": false,
5886
+ "properties": {
5887
+ "sport": {
5888
+ "const": "baseball",
5889
+ "title": "Sport",
5890
+ "type": "string"
5891
+ },
5892
+ "practice_type": {
5893
+ "enum": [
5894
+ "tee",
5895
+ "front_toss",
5896
+ "side_toss",
5897
+ "pitching_machine",
5898
+ "live_pitching",
5899
+ "game",
5900
+ "dry_swing",
5901
+ "unknown"
5902
+ ],
5903
+ "title": "Practice Type",
5904
+ "type": "string"
5905
+ }
5906
+ },
5907
+ "required": [
5908
+ "sport",
5909
+ "practice_type"
5910
+ ],
5911
+ "title": "SwingContext",
5912
  "type": "object"
5913
  },
5914
+ "SwingEvent": {
5915
  "additionalProperties": false,
5916
  "properties": {
5917
+ "status": {
5918
+ "enum": [
5919
+ "available",
5920
+ "limited",
5921
+ "unavailable"
5922
+ ],
5923
+ "title": "Status",
5924
  "type": "string"
5925
  },
5926
+ "video_time_s": {
5927
  "anyOf": [
5928
  {
5929
+ "type": "number"
 
 
 
 
5930
  },
5931
  {
5932
  "type": "null"
5933
  }
5934
  ],
5935
+ "title": "Video Time S"
5936
  },
5937
+ "capture_time_s": {
5938
  "anyOf": [
5939
  {
5940
+ "type": "number"
 
 
 
 
5941
  },
5942
  {
5943
  "type": "null"
5944
  }
5945
  ],
5946
+ "title": "Capture Time S"
5947
  },
5948
+ "source": {
5949
  "anyOf": [
5950
  {
5951
+ "enum": [
5952
+ "manual_review",
5953
+ "pose_estimated",
5954
+ "bat_ball_detector"
5955
+ ],
5956
+ "type": "string"
5957
  },
5958
  {
5959
  "type": "null"
5960
  }
5961
  ],
5962
+ "title": "Source"
5963
  },
5964
+ "reasons": {
5965
+ "items": {
5966
+ "enum": [
5967
+ "contact_not_verified",
5968
+ "contact_not_applicable",
5969
+ "event_not_detected",
5970
+ "event_timing_uncertain",
5971
+ "required_event_unavailable",
5972
+ "required_event_limited",
5973
+ "lead_foot_unknown",
5974
+ "required_landmarks_unusable",
5975
+ "ground_plane_unknown",
5976
+ "scale_is_model_estimated",
5977
+ "scale_unknown",
5978
+ "excessive_interpolation",
5979
+ "occlusion_unresolved",
5980
+ "temporal_inconsistency"
5981
+ ],
5982
+ "type": "string"
5983
+ },
5984
+ "title": "Reasons",
5985
+ "type": "array"
5986
  }
5987
  },
5988
  "required": [
5989
+ "status",
5990
+ "video_time_s",
5991
+ "capture_time_s",
5992
+ "source"
 
5993
  ],
5994
+ "title": "SwingEvent",
5995
  "type": "object"
5996
  },
5997
+ "AuditLogSummary": {
 
5998
  "properties": {
5999
+ "id": {
6000
+ "type": "string",
6001
+ "format": "uuid",
6002
+ "title": "Id"
6003
  },
6004
+ "created_at": {
6005
+ "type": "string",
6006
+ "format": "date-time",
6007
+ "title": "Created At"
6008
  },
6009
+ "started_at": {
6010
+ "type": "string",
6011
+ "format": "date-time",
6012
+ "title": "Started At"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6013
  },
6014
+ "request_id": {
6015
+ "type": "string",
6016
+ "title": "Request Id"
 
 
 
 
 
 
6017
  },
6018
+ "method": {
6019
+ "type": "string",
6020
+ "title": "Method"
6021
+ },
6022
+ "path": {
6023
+ "type": "string",
6024
+ "title": "Path"
6025
+ },
6026
+ "route": {
6027
  "anyOf": [
6028
  {
6029
+ "type": "string"
6030
  },
6031
  {
6032
  "type": "null"
6033
  }
6034
  ],
6035
+ "title": "Route"
6036
  },
6037
+ "status_code": {
6038
+ "type": "integer",
6039
+ "title": "Status Code"
 
 
 
 
6040
  },
6041
+ "duration_ms": {
6042
+ "type": "number",
6043
+ "title": "Duration Ms"
6044
+ },
6045
+ "account_id": {
6046
  "anyOf": [
6047
  {
6048
+ "type": "string",
6049
+ "format": "uuid"
 
 
 
 
6050
  },
6051
  {
6052
  "type": "null"
6053
  }
6054
  ],
6055
+ "title": "Account Id"
 
6056
  },
6057
+ "session_id": {
6058
  "anyOf": [
6059
  {
6060
+ "type": "string",
6061
+ "format": "uuid"
 
 
 
 
6062
  },
6063
  {
6064
  "type": "null"
6065
  }
6066
  ],
6067
+ "title": "Session Id"
 
6068
  },
6069
+ "analysis_id": {
6070
  "anyOf": [
6071
  {
 
 
 
 
 
6072
  "type": "string"
6073
  },
6074
  {
6075
  "type": "null"
6076
  }
6077
  ],
6078
+ "title": "Analysis Id"
 
 
 
 
 
 
 
 
 
6079
  },
6080
+ "analysis_revision": {
6081
+ "anyOf": [
6082
+ {
6083
+ "type": "integer"
6084
+ },
6085
+ {
6086
+ "type": "null"
6087
+ }
6088
  ],
6089
+ "title": "Analysis Revision"
 
6090
  },
6091
+ "error_code": {
6092
  "anyOf": [
6093
  {
6094
+ "type": "string"
 
 
6095
  },
6096
  {
6097
  "type": "null"
6098
  }
6099
  ],
6100
+ "title": "Error Code"
 
 
 
 
6101
  },
6102
+ "exception_type": {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6103
  "anyOf": [
6104
  {
6105
+ "type": "string"
6106
  },
6107
  {
6108
  "type": "null"
6109
  }
6110
+ ],
6111
+ "title": "Exception Type"
6112
+ },
6113
+ "response_complete": {
6114
+ "type": "boolean",
6115
+ "title": "Response Complete"
6116
+ },
6117
+ "service_version": {
6118
+ "type": "string",
6119
+ "title": "Service Version"
6120
  }
6121
  },
6122
+ "type": "object",
6123
  "required": [
6124
+ "id",
6125
+ "created_at",
6126
+ "started_at",
6127
+ "request_id",
6128
+ "method",
6129
+ "path",
6130
+ "route",
6131
+ "status_code",
6132
+ "duration_ms",
6133
+ "account_id",
6134
+ "session_id",
6135
+ "analysis_id",
6136
+ "analysis_revision",
6137
+ "error_code",
6138
+ "exception_type",
6139
+ "response_complete",
6140
+ "service_version"
6141
  ],
6142
+ "title": "AuditLogSummary"
 
6143
  },
6144
+ "AuditLogDetail": {
 
6145
  "properties": {
6146
+ "id": {
6147
+ "type": "string",
6148
+ "format": "uuid",
6149
+ "title": "Id"
6150
  },
6151
+ "created_at": {
6152
+ "type": "string",
6153
+ "format": "date-time",
6154
+ "title": "Created At"
 
6155
  },
6156
+ "started_at": {
6157
+ "type": "string",
6158
+ "format": "date-time",
6159
+ "title": "Started At"
6160
  },
6161
+ "request_id": {
6162
+ "type": "string",
6163
+ "title": "Request Id"
 
 
6164
  },
6165
+ "method": {
6166
+ "type": "string",
6167
+ "title": "Method"
 
6168
  },
6169
+ "path": {
6170
+ "type": "string",
6171
+ "title": "Path"
6172
  },
6173
+ "route": {
6174
+ "anyOf": [
6175
+ {
6176
+ "type": "string"
6177
+ },
6178
+ {
6179
+ "type": "null"
6180
+ }
6181
+ ],
6182
+ "title": "Route"
6183
  },
6184
+ "status_code": {
6185
+ "type": "integer",
6186
+ "title": "Status Code"
 
6187
  },
6188
+ "duration_ms": {
6189
+ "type": "number",
6190
+ "title": "Duration Ms"
6191
  },
6192
+ "account_id": {
6193
+ "anyOf": [
6194
+ {
6195
+ "type": "string",
6196
+ "format": "uuid"
6197
+ },
6198
+ {
6199
+ "type": "null"
6200
+ }
6201
+ ],
6202
+ "title": "Account Id"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6203
  },
6204
+ "session_id": {
6205
+ "anyOf": [
6206
+ {
6207
+ "type": "string",
6208
+ "format": "uuid"
6209
+ },
6210
+ {
6211
+ "type": "null"
6212
+ }
 
6213
  ],
6214
+ "title": "Session Id"
6215
+ },
6216
+ "analysis_id": {
6217
+ "anyOf": [
6218
+ {
6219
+ "type": "string"
6220
+ },
6221
+ {
6222
+ "type": "null"
6223
+ }
 
 
 
 
 
 
 
 
 
6224
  ],
6225
+ "title": "Analysis Id"
 
6226
  },
6227
+ "analysis_revision": {
6228
  "anyOf": [
6229
  {
6230
+ "type": "integer"
6231
  },
6232
  {
6233
  "type": "null"
6234
  }
6235
  ],
6236
+ "title": "Analysis Revision"
6237
  },
6238
+ "error_code": {
6239
  "anyOf": [
6240
  {
6241
+ "type": "string"
6242
  },
6243
  {
6244
  "type": "null"
6245
  }
6246
  ],
6247
+ "title": "Error Code"
6248
  },
6249
+ "exception_type": {
6250
  "anyOf": [
6251
  {
 
 
 
 
 
6252
  "type": "string"
6253
  },
6254
  {
6255
  "type": "null"
6256
  }
6257
  ],
6258
+ "title": "Exception Type"
6259
  },
6260
+ "response_complete": {
6261
+ "type": "boolean",
6262
+ "title": "Response Complete"
6263
+ },
6264
+ "service_version": {
6265
+ "type": "string",
6266
+ "title": "Service Version"
6267
+ },
6268
+ "request_headers": {
6269
+ "additionalProperties": true,
6270
+ "type": "object",
6271
+ "title": "Request Headers"
6272
+ },
6273
+ "query_params": {
6274
+ "additionalProperties": true,
6275
+ "type": "object",
6276
+ "title": "Query Params"
6277
+ },
6278
+ "request_payload": {
6279
+ "additionalProperties": true,
6280
+ "type": "object",
6281
+ "title": "Request Payload"
6282
+ },
6283
+ "response_headers": {
6284
+ "additionalProperties": true,
6285
+ "type": "object",
6286
+ "title": "Response Headers"
6287
+ },
6288
+ "response_payload": {
6289
+ "additionalProperties": true,
6290
+ "type": "object",
6291
+ "title": "Response Payload"
6292
+ }
6293
+ },
6294
+ "type": "object",
6295
+ "required": [
6296
+ "id",
6297
+ "created_at",
6298
+ "started_at",
6299
+ "request_id",
6300
+ "method",
6301
+ "path",
6302
+ "route",
6303
+ "status_code",
6304
+ "duration_ms",
6305
+ "account_id",
6306
+ "session_id",
6307
+ "analysis_id",
6308
+ "analysis_revision",
6309
+ "error_code",
6310
+ "exception_type",
6311
+ "response_complete",
6312
+ "service_version",
6313
+ "request_headers",
6314
+ "query_params",
6315
+ "request_payload",
6316
+ "response_headers",
6317
+ "response_payload"
6318
+ ],
6319
+ "title": "AuditLogDetail"
6320
+ },
6321
+ "Page_AuditLogSummary_": {
6322
+ "properties": {
6323
+ "items": {
6324
  "items": {
6325
+ "$ref": "#/components/schemas/AuditLogSummary"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6326
  },
6327
+ "type": "array",
6328
+ "title": "Items"
6329
+ },
6330
+ "next_cursor": {
6331
+ "anyOf": [
6332
+ {
6333
+ "type": "string"
6334
+ },
6335
+ {
6336
+ "type": "null"
6337
+ }
6338
+ ],
6339
+ "title": "Next Cursor"
6340
  }
6341
  },
6342
+ "type": "object",
6343
  "required": [
6344
+ "items"
 
 
 
6345
  ],
6346
+ "title": "Page[AuditLogSummary]"
 
6347
  }
6348
  }
6349
  }
backend/migrations/versions/20261028_7e83a6c10b42_api_request_logs.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persist sanitized API request/response diagnostics.
2
+
3
+ Revision ID: 7e83a6c10b42
4
+ Revises: 264767a56154
5
+ """
6
+
7
+ import sqlalchemy as sa
8
+ from alembic import op
9
+ from sqlalchemy.dialects import postgresql
10
+
11
+ revision = "7e83a6c10b42"
12
+ down_revision = "264767a56154"
13
+ branch_labels = None
14
+ depends_on = None
15
+
16
+
17
+ def upgrade() -> None:
18
+ op.create_table(
19
+ "api_request_logs",
20
+ sa.Column("id", sa.UUID(), server_default=sa.text("gen_random_uuid()"), nullable=False),
21
+ sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
22
+ sa.Column("request_id", sa.String(128), nullable=False),
23
+ sa.Column("started_at", sa.DateTime(timezone=True), nullable=False),
24
+ sa.Column("method", sa.String(16), nullable=False),
25
+ sa.Column("path", sa.String(2048), nullable=False),
26
+ sa.Column("route", sa.String(512)),
27
+ sa.Column("status_code", sa.Integer(), nullable=False),
28
+ sa.Column("duration_ms", sa.Float(), nullable=False),
29
+ sa.Column("account_id", sa.UUID()),
30
+ sa.Column("session_id", sa.UUID()),
31
+ sa.Column("analysis_id", sa.String(256)),
32
+ sa.Column("analysis_revision", sa.Integer()),
33
+ sa.Column("request_headers", postgresql.JSONB(), nullable=False),
34
+ sa.Column("query_params", postgresql.JSONB(), nullable=False),
35
+ sa.Column("request_payload", postgresql.JSONB(), nullable=False),
36
+ sa.Column("response_headers", postgresql.JSONB(), nullable=False),
37
+ sa.Column("response_payload", postgresql.JSONB(), nullable=False),
38
+ sa.Column("error_code", sa.String(128)),
39
+ sa.Column("exception_type", sa.String(128)),
40
+ sa.Column("response_complete", sa.Boolean(), nullable=False),
41
+ sa.Column("service_version", sa.String(128), nullable=False),
42
+ sa.PrimaryKeyConstraint("id", name="pk_api_request_logs"),
43
+ )
44
+ for column in ("created_at", "request_id", "route", "status_code", "account_id", "session_id", "analysis_id"):
45
+ op.create_index(f"ix_api_request_logs_{column}", "api_request_logs", [column])
46
+
47
+
48
+ def downgrade() -> None:
49
+ op.drop_table("api_request_logs")
backend/tests/integration/test_api_audit.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Audit persistence, exact analysis bodies, failures, redaction and bounded capture."""
2
+
3
+ import json
4
+ from datetime import UTC, datetime, timedelta
5
+
6
+ import pytest
7
+ from sqlalchemy import select, update
8
+
9
+ from app.core.database import get_session_factory
10
+ from app.integrations.storage import get_storage
11
+ from app.jobs.cleanup import run_cleanup
12
+ from app.modules.api_audit.middleware import ApiAuditMiddleware, Capture, sanitize
13
+ from app.modules.api_audit.models import ApiRequestLog
14
+ from app.modules.api_audit.service import write_record
15
+ from tests.helpers import PASSWORD, register
16
+ from tests.integration.test_swing_reports import PAYLOAD, make_account, make_session, url
17
+
18
+
19
+ async def records():
20
+ async with get_session_factory()() as db:
21
+ return list(await db.scalars(select(ApiRequestLog).order_by(ApiRequestLog.created_at)))
22
+
23
+
24
+ async def test_auth_payloads_are_redacted(client):
25
+ account = await register(client)
26
+ row = (await records())[-1]
27
+ assert row.status_code == 201 and row.route == '/v1/auth/register'
28
+ assert row.request_payload['body']['password'] == '[REDACTED]'
29
+ assert row.response_payload['body']['tokens'] == '[REDACTED]'
30
+ raw = json.dumps(row.request_payload) + json.dumps(row.response_payload)
31
+ assert PASSWORD not in raw and account['tokens']['access_token'] not in raw
32
+ assert row.response_complete and row.duration_ms >= 0
33
+ assert row.request_id == row.response_headers['x-request-id']
34
+
35
+
36
+ async def test_swing_report_stores_exact_measurements_and_result(client):
37
+ owner, h = await make_account()
38
+ sid = await make_session(owner)
39
+ response = await client.post(url(sid), json=PAYLOAD, headers={**h, 'X-Request-ID': 'audit-report'})
40
+ assert response.status_code == 200
41
+ row = (await records())[-1]
42
+ assert row.request_payload['body'] == PAYLOAD
43
+ assert row.response_payload['body'] == response.json()
44
+ assert row.account_id == owner and row.session_id == sid
45
+ assert row.analysis_id == PAYLOAD['analysis_id'] and row.analysis_revision == 1
46
+ assert row.request_id == response.json()['meta']['request_id'] == 'audit-report'
47
+ assert 'authorization' not in row.request_headers
48
+ # Repeated requests must remain separate observations, even for a cached report.
49
+ await client.post(url(sid), json=PAYLOAD, headers=h)
50
+ assert len(await records()) == 2
51
+ fetched = await client.get(f'/v1/sessions/{sid}', headers=h)
52
+ assert fetched.status_code == 200
53
+ row = (await records())[-1]
54
+ assert row.analysis_id == PAYLOAD['analysis_id'] and row.analysis_revision == 1
55
+
56
+
57
+ async def test_invalid_payload_survives_request_rollback(client):
58
+ owner, h = await make_account()
59
+ sid = await make_session(owner)
60
+ p = {**PAYLOAD, 'measurements': []}
61
+ response = await client.post(url(sid), json=p, headers=h)
62
+ assert response.status_code == 422
63
+ row = (await records())[-1]
64
+ assert row.error_code == 'INVALID_PAYLOAD'
65
+ assert row.request_payload['body'] == p
66
+ assert row.response_payload['body'] == response.json()
67
+
68
+
69
+ async def test_early_auth_and_unknown_routes_are_logged(client):
70
+ response = await client.post('/v1/sessions', json={'fps': 30})
71
+ assert response.status_code == 401
72
+ await client.get('/missing', params={'token': 'secret-query', 'mode': 'h'})
73
+ rows = await records()
74
+ assert rows[0].request_payload['body'] == {'fps': 30}
75
+ assert rows[0].account_id is None
76
+ assert rows[1].status_code == 404
77
+ assert rows[1].query_params == {'token': '[REDACTED]', 'mode': ['h']}
78
+
79
+
80
+ async def test_push_token_in_url_is_not_stored(client):
81
+ await client.delete('/v1/devices/private-push-token')
82
+ raw = str((await records())[-1].path)
83
+ assert 'private-push-token' not in raw
84
+
85
+
86
+ async def test_malformed_json_never_stores_raw_secrets(client):
87
+ await client.post('/v1/auth/login', content='{"password":"private-value",',
88
+ headers={'Content-Type': 'application/json'})
89
+ row = (await records())[-1]
90
+ assert row.request_payload['capture_status'] == 'invalid_json'
91
+ assert row.request_payload['body'] is None
92
+ assert 'private-value' not in json.dumps(row.response_payload)
93
+
94
+
95
+ async def test_audit_retention(client):
96
+ await client.get('/healthz')
97
+ async with get_session_factory()() as db:
98
+ await db.execute(update(ApiRequestLog).values(created_at=datetime.now(UTC) - timedelta(days=31)))
99
+ await db.commit()
100
+ await client.get('/healthz')
101
+ async with get_session_factory()() as db:
102
+ counts = await run_cleanup(db, get_storage())
103
+ assert counts['api_request_logs'] == 1
104
+ assert len(await records()) == 1
105
+
106
+
107
+ async def test_audit_storage_failure_does_not_raise(monkeypatch, caplog):
108
+ from app.modules.api_audit import service
109
+
110
+ def fail():
111
+ raise RuntimeError('private database credential')
112
+
113
+ monkeypatch.setattr(service, 'get_session_factory', fail)
114
+ await write_record({'request_id': 'failure-test'})
115
+ assert 'api_audit_write_failed' in caplog.text
116
+ assert 'private database credential' not in caplog.text
117
+
118
+
119
+ async def test_asgi_streaming_bytes_preserved_and_bounded():
120
+ writes, sent = [], []
121
+ chunks = [b'{"value":', b'"' + b'x' * 100 + b'"}']
122
+ incoming = iter([{'type': 'http.request', 'body': q, 'more_body': i == 0} for i, q in enumerate(chunks)])
123
+
124
+ async def receive():
125
+ return next(incoming)
126
+
127
+ async def send(message):
128
+ sent.append(message)
129
+
130
+ async def writer(row):
131
+ writes.append(row)
132
+
133
+ async def app(scope, receive, send):
134
+ actual = bytearray()
135
+ while True:
136
+ message = await receive()
137
+ actual.extend(message['body'])
138
+ if not message.get('more_body'):
139
+ break
140
+ assert actual == b''.join(chunks)
141
+ await send({'type': 'http.response.start', 'status': 200,
142
+ 'headers': [(b'content-type', b'application/json')]})
143
+ for i, chunk in enumerate(chunks):
144
+ await send({'type': 'http.response.body', 'body': chunk, 'more_body': i == 0})
145
+
146
+ middleware = ApiAuditMiddleware(app, max_body_bytes=16, writer=writer)
147
+ await middleware({'type': 'http', 'method': 'POST', 'path': '/test',
148
+ 'headers': [(b'content-type', b'application/json')]}, receive, send)
149
+ assert b''.join(m.get('body', b'') for m in sent) == b''.join(chunks)
150
+ assert len(writes) == 1
151
+ assert writes[0]['request_payload']['capture_status'] == 'truncated'
152
+ assert writes[0]['response_payload']['capture_status'] == 'truncated'
153
+ assert writes[0]['response_complete']
154
+
155
+
156
+ @pytest.mark.parametrize('kind', ['video/mp4', 'multipart/form-data; boundary=x'])
157
+ def test_binary_capture_does_not_buffer(kind):
158
+ capture = Capture(kind, 1024)
159
+ capture.feed(b'private-video' * 1000, True)
160
+ assert not capture.buffer
161
+ assert capture.result()['capture_status'] == 'non_json'
162
+
163
+
164
+ def test_nested_secrets_and_urls_are_redacted():
165
+ data = {'groups': [{'score': 85, 'apiKey': 'secret', 'source': 'https://host/path?X-Amz-Signature=secret'}],
166
+ 'SignedPayload': 'receipt', 'note': 'Bearer private', 'weight_kg': 75}
167
+ result = sanitize(data)
168
+ assert result['groups'][0]['score'] == 85
169
+ assert 'secret' not in json.dumps(result) and 'private' not in json.dumps(result)
170
+ assert result['weight_kg'] == 75
171
+
172
+
173
+ async def test_unhandled_error_is_recorded_without_exception_message(client, app):
174
+ async def fail():
175
+ raise RuntimeError('private runtime credential')
176
+
177
+ app.add_api_route('/audit-test-failure', fail)
178
+ try:
179
+ response = await client.get('/audit-test-failure')
180
+ assert response.status_code == 500
181
+ row = (await records())[-1]
182
+ assert row.status_code == 500 and row.exception_type == 'RuntimeError'
183
+ assert row.response_payload['body'] == response.json()
184
+ assert 'private runtime credential' not in json.dumps(row.response_payload)
185
+ finally:
186
+ app.router.routes[:] = [r for r in app.router.routes if getattr(r, 'path', '') != '/audit-test-failure']
187
+
188
+
189
+ async def test_database_audit_failure_preserves_http_response(client, monkeypatch):
190
+ from app.modules.api_audit import service
191
+
192
+ def fail():
193
+ raise RuntimeError('database unavailable')
194
+
195
+ monkeypatch.setattr(service, 'get_session_factory', fail)
196
+ response = await client.get('/healthz')
197
+ assert response.status_code == 200 and response.json() == {'status': 'ok'}
198
+
199
+
200
+ async def test_parallel_calls_have_independent_records(client):
201
+ import asyncio
202
+
203
+ responses = await asyncio.gather(*(client.get('/healthz') for _ in range(12)))
204
+ rows = await records()
205
+ assert len(rows) == 12
206
+ assert {r.request_id for r in rows} == {r.headers['x-request-id'] for r in responses}
207
+
208
+
209
+ def test_database_json_edge_values_are_safe():
210
+ result = sanitize({'nul\x00key': '\x00value', 'number': float('inf')})
211
+ assert result == {'nul[NUL]key': '[NUL]value', 'number': '[NONFINITE NUMBER]'}
212
+
213
+
214
+ def test_idempotency_header_is_correlatable_without_storing_the_key():
215
+ import hashlib
216
+
217
+ from app.modules.api_audit.middleware import headers
218
+
219
+ out = headers([(b'idempotency-key', b'retry-key'), (b'authorization', b'Bearer private')])
220
+ assert out == {'idempotency-key-sha256': hashlib.sha256(b'retry-key').hexdigest()}
backend/tests/integration/test_api_audit_read.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Only server-allowlisted accounts can browse sanitized request logs."""
2
+
3
+ import uuid
4
+ from datetime import UTC, datetime, timedelta
5
+
6
+ import pytest
7
+ from sqlalchemy import select
8
+
9
+ from app.core.config import get_settings
10
+ from app.core.database import get_session_factory
11
+ from app.modules.api_audit.models import ApiRequestLog
12
+ from tests.factories import make_account
13
+
14
+ BASE = '/v1/admin/api-logs'
15
+
16
+
17
+ @pytest.fixture
18
+ async def operator(monkeypatch):
19
+ user = await make_account()
20
+ monkeypatch.setattr(get_settings(), 'api_audit_reader_account_ids', [user['id']])
21
+ return user
22
+
23
+
24
+ async def rows():
25
+ async with get_session_factory()() as db:
26
+ return list(await db.scalars(select(ApiRequestLog).order_by(ApiRequestLog.created_at)))
27
+
28
+
29
+ async def test_access_denied_by_default_and_for_coach(client, monkeypatch):
30
+ monkeypatch.setattr(get_settings(), 'api_audit_reader_account_ids', [])
31
+ assert (await client.get(BASE)).status_code == 401
32
+ for role in ('player', 'coach'):
33
+ user = await make_account(role=role)
34
+ assert (await client.get(BASE, headers=user['headers'])).status_code == 403
35
+ assert (await client.get(f'{BASE}/{uuid.uuid4()}', headers=user['headers'])).status_code == 403
36
+
37
+
38
+ async def test_list_and_detail_with_no_recursive_payloads(client, operator):
39
+ response = await client.post('/v1/auth/login', json={'email': 'no@example.com', 'password': 'private-password'})
40
+ entry = (await rows())[-1]
41
+ h = operator['headers']
42
+ listed = await client.get(BASE, headers=h, params={'request_id': response.headers['x-request-id']})
43
+ assert listed.status_code == 200
44
+ assert listed.headers['cache-control'] == 'no-store'
45
+ item = listed.json()['items'][0]
46
+ assert item['id'] == str(entry.id) and item['status_code'] == response.status_code
47
+ assert 'request_payload' not in item and 'response_payload' not in item
48
+ detail = await client.get(f'{BASE}/{entry.id}', headers=h)
49
+ assert detail.status_code == 200 and detail.headers['cache-control'] == 'no-store'
50
+ assert detail.json()['request_payload']['body']['password'] == '[REDACTED]'
51
+ assert detail.json()['response_payload']['body'] == response.json()
52
+ assert 'private-password' not in detail.text
53
+ read_logs = [r for r in await rows() if r.path.startswith(BASE)]
54
+ assert len(read_logs) == 2
55
+ assert all(r.account_id == operator['id'] and r.status_code == 200 for r in read_logs)
56
+ assert all(r.response_payload['capture_status'] == 'omitted_audit_read' for r in read_logs)
57
+ assert all(r.response_payload['body'] is None for r in read_logs)
58
+
59
+
60
+ async def test_cursor_pagination_is_stable_with_timestamp_ties(client, operator):
61
+ for _ in range(3):
62
+ await client.get('/healthz', headers={'X-Request-Id': 'page-test'})
63
+ original = await rows()
64
+ async with get_session_factory()() as db:
65
+ await db.execute(ApiRequestLog.__table__.update().values(created_at=datetime.now(UTC)))
66
+ await db.commit()
67
+ params = {'request_id': 'page-test', 'limit': 2}
68
+ first = (await client.get(BASE, headers=operator['headers'], params=params)).json()
69
+ assert len(first['items']) == 2 and first['next_cursor']
70
+ second = (await client.get(BASE, headers=operator['headers'],
71
+ params={**params, 'cursor': first['next_cursor']})).json()
72
+ assert len(second['items']) == 1 and second['next_cursor'] is None
73
+ ids = [r['id'] for page in (first, second) for r in page['items']]
74
+ assert len(set(ids)) == 3 and set(ids) == {str(r.id) for r in original}
75
+
76
+
77
+ async def test_filters(client, operator):
78
+ from tests.integration.test_swing_reports import PAYLOAD, make_session, url
79
+
80
+ sid = await make_session(operator['id'])
81
+ response = await client.post(url(sid), json=PAYLOAD, headers=operator['headers'])
82
+ assert response.status_code == 200
83
+ params = {'session_id': str(sid), 'analysis_id': PAYLOAD['analysis_id'],
84
+ 'account_id': str(operator['id']), 'status_code': 200, 'method': 'POST',
85
+ 'route': '/v1/sessions/{session_id}/swing-report',
86
+ 'since': (datetime.now(UTC) - timedelta(hours=1)).isoformat(),
87
+ 'until': (datetime.now(UTC) + timedelta(hours=1)).isoformat()}
88
+ listed = await client.get(BASE, headers=operator['headers'], params=params)
89
+ assert listed.status_code == 200 and len(listed.json()['items']) == 1
90
+ params['status_code'] = 422
91
+ assert (await client.get(BASE, headers=operator['headers'], params=params)).json()['items'] == []
92
+
93
+
94
+ @pytest.mark.parametrize('params', [
95
+ {'limit': 0}, {'limit': 201}, {'status_code': 600}, {'session_id': 'bad'},
96
+ {'cursor': 'bad'}, {'since': '2026-10-29T00:00:00'},
97
+ {'since': '2026-10-29T00:00:00Z', 'until': '2026-10-28T00:00:00Z'},
98
+ ])
99
+ async def test_invalid_filters(client, operator, params):
100
+ assert (await client.get(BASE, headers=operator['headers'], params=params)).status_code == 400
101
+
102
+
103
+ async def test_missing_record(client, operator):
104
+ assert (await client.get(f'{BASE}/{uuid.uuid4()}', headers=operator['headers'])).status_code == 404
backend/tests/integration/test_cleanup.py CHANGED
@@ -65,7 +65,7 @@ async def test_cleanup_removes_expired_rows_and_objects(client):
65
 
66
  counts = await _cleanup(later)
67
  assert counts == {"unattached_uploads": 1, "pending_sessions": 1, "deleted_sessions": 1, "objects": 5,
68
- "idempotency_keys": 1}
69
  for key in [stale_key, *abandoned_keys, *old_deleted_keys]:
70
  assert await storage.head(key) is None, key
71
  async with get_session_factory()() as db:
@@ -77,7 +77,7 @@ async def test_cleanup_removes_expired_rows_and_objects(client):
77
  assert await _count(IdempotencyKey) == 0
78
 
79
  assert await _cleanup(later) == {"unattached_uploads": 0, "pending_sessions": 0, "deleted_sessions": 0,
80
- "objects": 0, "idempotency_keys": 0}
81
 
82
 
83
  async def test_cleanup_keeps_recent_data(client):
@@ -86,5 +86,5 @@ async def test_cleanup_keeps_recent_data(client):
86
  await create_session(client, {**player["headers"], "Idempotency-Key": "k2"})
87
  counts = await _cleanup(datetime.now(UTC) + timedelta(hours=23))
88
  assert counts == {"unattached_uploads": 0, "pending_sessions": 0, "deleted_sessions": 0, "objects": 0,
89
- "idempotency_keys": 0}
90
  assert await _count(SwingSession) == 1 and await _count(Upload) == 3
 
65
 
66
  counts = await _cleanup(later)
67
  assert counts == {"unattached_uploads": 1, "pending_sessions": 1, "deleted_sessions": 1, "objects": 5,
68
+ "idempotency_keys": 1, "api_request_logs": 0}
69
  for key in [stale_key, *abandoned_keys, *old_deleted_keys]:
70
  assert await storage.head(key) is None, key
71
  async with get_session_factory()() as db:
 
77
  assert await _count(IdempotencyKey) == 0
78
 
79
  assert await _cleanup(later) == {"unattached_uploads": 0, "pending_sessions": 0, "deleted_sessions": 0,
80
+ "objects": 0, "idempotency_keys": 0, "api_request_logs": 0}
81
 
82
 
83
  async def test_cleanup_keeps_recent_data(client):
 
86
  await create_session(client, {**player["headers"], "Idempotency-Key": "k2"})
87
  counts = await _cleanup(datetime.now(UTC) + timedelta(hours=23))
88
  assert counts == {"unattached_uploads": 0, "pending_sessions": 0, "deleted_sessions": 0, "objects": 0,
89
+ "idempotency_keys": 0, "api_request_logs": 0}
90
  assert await _count(SwingSession) == 1 and await _count(Upload) == 3
backend/tests/integration/test_health.py CHANGED
@@ -26,3 +26,25 @@ async def test_openapi_documents_the_real_error_envelope_and_report(client):
26
  report_op = spec["paths"]["/v1/sessions/{session_id}/swing-report"]["post"]
27
  assert report_op["requestBody"]["content"]["application/json"]["schema"]["$ref"].endswith("SwingAnalysisPayload")
28
  assert schemas["SessionOut"]["properties"]["report"]["anyOf"][0]["$ref"].endswith("SwingReport")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  report_op = spec["paths"]["/v1/sessions/{session_id}/swing-report"]["post"]
27
  assert report_op["requestBody"]["content"]["application/json"]["schema"]["$ref"].endswith("SwingAnalysisPayload")
28
  assert schemas["SessionOut"]["properties"]["report"]["anyOf"][0]["$ref"].endswith("SwingReport")
29
+
30
+
31
+ def _raise(exc: Exception):
32
+ async def endpoint():
33
+ raise exc
34
+ return endpoint
35
+
36
+
37
+ async def test_database_busy_and_bugs_use_the_envelope_with_request_id(app, client):
38
+ from sqlalchemy.exc import DBAPIError
39
+ from sqlalchemy.exc import TimeoutError as PoolTimeout
40
+
41
+ busy = DBAPIError("SELECT 1", {}, Exception("(EMAXCONNSESSION) max clients reached in session mode"))
42
+ app.add_api_route("/_test/db-busy", _raise(busy))
43
+ app.add_api_route("/_test/pool-timeout", _raise(PoolTimeout("QueuePool limit reached")))
44
+ app.add_api_route("/_test/bug", _raise(RuntimeError("boom")))
45
+ for path, status, code in (("/_test/db-busy", 503, "UNAVAILABLE"), ("/_test/pool-timeout", 503, "UNAVAILABLE"),
46
+ ("/_test/bug", 500, "INTERNAL")):
47
+ response = await client.get(path, headers={"X-Request-Id": "rid-1"})
48
+ assert response.status_code == status, path
49
+ assert response.json()["error"]["code"] == code
50
+ assert response.headers["X-Request-Id"] == "rid-1"
backend/tests/integration/test_swing_reports.py CHANGED
@@ -279,3 +279,32 @@ async def test_payload_batting_hand_wins(client):
279
  sid = await make_session(owner, athlete={**ATHLETE, "bats": "L"})
280
  response = await client.post(url(sid), json=PAYLOAD, headers=headers)
281
  assert response.json()["measurements"][0]["benchmark"]["benchmark_id"].endswith(".right.college")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
279
  sid = await make_session(owner, athlete={**ATHLETE, "bats": "L"})
280
  response = await client.post(url(sid), json=PAYLOAD, headers=headers)
281
  assert response.json()["measurements"][0]["benchmark"]["benchmark_id"].endswith(".right.college")
282
+
283
+
284
+ async def test_missing_gemini_key_is_an_error_not_a_template_report(client, monkeypatch):
285
+ from ai_coach.config import get_settings as get_coach_settings
286
+
287
+ from app.core.config import get_settings
288
+
289
+ monkeypatch.setattr(get_settings(), "env", "dev")
290
+ monkeypatch.setattr(get_coach_settings(), "google_api_key", None)
291
+ owner, headers = await make_account()
292
+ sid = await make_session(owner)
293
+ response = await client.post(url(sid), json=PAYLOAD, headers=headers)
294
+ assert response.status_code == 503
295
+ assert response.json()["error"]["code"] == "COACH_NOT_CONFIGURED"
296
+ row = await load_session(sid)
297
+ assert row.report is None and row.analyzed_at is None # nothing saved, nothing counted toward the plan
298
+
299
+
300
+ def test_production_refuses_to_start_without_gemini_key(monkeypatch):
301
+ import pytest
302
+ from ai_coach.config import get_settings as get_coach_settings
303
+
304
+ from app.core.config import get_settings
305
+ from app.main import create_app
306
+
307
+ monkeypatch.setattr(get_settings(), "env", "prod")
308
+ monkeypatch.setattr(get_coach_settings(), "google_api_key", None)
309
+ with pytest.raises(RuntimeError, match="GOOGLE_API_KEY"):
310
+ create_app()
baseball_batting/automatic_pitcher_direction.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Automatic, conditional field direction from a visible home-plate outline.
2
+
3
+ No stance or stride defines the field axis. Camera height cancels when the
4
+ outline is intersected with a level floor. Shape/temporal checks are engineering
5
+ checks, not a calibrated probability or proof that a practice plate is aligned.
6
+ """
7
+ from pathlib import Path
8
+ import math
9
+ import numpy as np
10
+ from .camera_up_provider import CAMERA_FRAME
11
+ from .storage import sha256_file
12
+
13
+ METHOD = 'automatic_home_plate_floor_geometry_v1'
14
+ # Clockwise outline in arbitrary units: broad front edge, sides, rear point.
15
+ # Direction toward the pitcher is negative template Y, not toward the rear tip.
16
+ TEMPLATE = np.array([[-.5, 0], [.5, 0], [.5, .5], [0, 1], [-.5, .5]])
17
+ LIMITS = {'sample_count': 9, 'minimum_frames': 3, 'minimum_coverage': .5,
18
+ 'maximum_shape_error': .065, 'maximum_direction_spread_deg': 8.,
19
+ 'maximum_sensitivity_deg': 10., 'minimum_outline_area_px': 160.,
20
+ 'maximum_candidates_per_frame': 24}
21
+
22
+
23
+ def reference(reason='home_plate_not_detected'):
24
+ return dict(status='unknown', pitcher_vector=None, pitcher_source=None,
25
+ coordinate_frame=CAMERA_FRAME, method=METHOD, automatic=True,
26
+ applied=False, reliable=False, confidence=None,
27
+ accuracy_validated=False, reason_code=reason, limits=dict(LIMITS),
28
+ implementation_sha256=sha256_file(Path(__file__)),
29
+ assumptions=['visible_object_is_home_plate', 'plate_is_aligned_toward_pitcher',
30
+ 'plate_lies_on_level_floor'],
31
+ plate_alignment_verified=False,
32
+ reliability_kind='shape_temporal_and_sensitivity_checks; not validated accuracy')
33
+
34
+
35
+ def outlines(image, athlete_box=None):
36
+ """Bounded white convex pentagon proposals, in original upright pixels."""
37
+ import cv2
38
+ h, w = image.shape[:2]
39
+ scale = min(1., 1280 / max(h, w))
40
+ small = cv2.resize(image, (round(w*scale), round(h*scale)), interpolation=cv2.INTER_AREA)
41
+ hsv = cv2.cvtColor(small, cv2.COLOR_BGR2HSV)
42
+ proposals = []
43
+ for brightness in (120, 165, 205):
44
+ mask = ((hsv[:, :, 1] < 95) & (hsv[:, :, 2] >= brightness)).astype('uint8') * 255
45
+ contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
46
+ for contour in sorted(contours, key=cv2.contourArea, reverse=True)[:100]:
47
+ area = cv2.contourArea(contour)
48
+ if not LIMITS['minimum_outline_area_px'] <= area <= .08*small.shape[0]*small.shape[1]:
49
+ continue
50
+ perimeter = cv2.arcLength(contour, True)
51
+ for epsilon in (.012, .02, .03):
52
+ polygon = cv2.approxPolyDP(contour, epsilon*perimeter, True)
53
+ if len(polygon) != 5 or not cv2.isContourConvex(polygon):
54
+ continue
55
+ p = polygon[:, 0, :].astype(float)/scale
56
+ if np.any(p < 2) or np.any(p[:, 0] > w-3) or np.any(p[:, 1] > h-3):
57
+ continue # A clipped silhouette is not a complete plate.
58
+ if athlete_box is not None:
59
+ x1, y1, x2, y2 = athlete_box
60
+ if np.any((p[:, 0] >= x1) & (p[:, 0] <= x2) & (p[:, 1] >= y1) & (p[:, 1] <= y2)):
61
+ continue
62
+ if any(np.linalg.norm(p.mean(0)-q.mean(0)) < 5/scale for q in proposals):
63
+ continue
64
+ proposals.append(p)
65
+ break
66
+ return proposals[:LIMITS['maximum_candidates_per_frame']]
67
+
68
+
69
+ def fit_outline(pixels, camera, up):
70
+ """Recover direction by fitting the known plate shape on the floor."""
71
+ from .pitcher_direction import _rays, _unit, Unreliable
72
+ rays, _ = _rays(pixels, camera)
73
+ up = _unit(up)
74
+ incidence = _unit(rays) @ up
75
+ if np.any(incidence >= -math.sin(math.radians(5))):
76
+ raise Unreliable('plate_too_near_horizon')
77
+ points = -rays/(rays @ up)[:, None]
78
+ template = TEMPLATE-TEMPLATE.mean(0)
79
+ fits = []
80
+ for reverse in (False, True):
81
+ order = np.arange(5)[::-1] if reverse else np.arange(5)
82
+ for offset in range(5):
83
+ ordered = points[np.roll(order, offset)]
84
+ centred = ordered-ordered.mean(0)
85
+ u, s, vt = np.linalg.svd(template.T @ centred, full_matrices=False)
86
+ rotation = u @ vt
87
+ scale = s.sum()/np.sum(template**2)
88
+ error = np.linalg.norm(centred-scale*template @ rotation)/np.linalg.norm(centred)
89
+ fits.append((float(error), _unit(-rotation[1])))
90
+ fits.sort(key=lambda item: item[0])
91
+ best_error, direction = fits[0]
92
+ if best_error > LIMITS['maximum_shape_error']:
93
+ raise Unreliable('outline_does_not_match_home_plate')
94
+ for error, other in fits[1:]:
95
+ if error <= best_error+.025 and np.dot(direction, other) < math.cos(math.radians(10)):
96
+ raise Unreliable('plate_orientation_ambiguous')
97
+ return direction, best_error
98
+
99
+
100
+ def checked_outline(pixels, camera, up, up_spread):
101
+ """Reject directions unstable to pixel, lens, or vertical perturbations."""
102
+ from .pitcher_direction import _unit, Unreliable
103
+ vector, error = fit_outline(pixels, camera, up)
104
+ up = _unit(up)
105
+ axis = np.eye(3)[np.argmin(np.abs(up))]
106
+ a = _unit(axis-np.dot(axis, up)*up)
107
+ b = np.cross(up, a)
108
+ directions = [vector]
109
+ # These perturbations are a stress test, not estimated confidence bounds.
110
+ for theta in np.linspace(0, 2*np.pi, 8, endpoint=False):
111
+ tilted = math.cos(up_spread)*up + math.sin(up_spread)*(math.cos(theta)*a+math.sin(theta)*b)
112
+ directions.append(fit_outline(pixels, camera, tilted)[0])
113
+ for factor in (.9, 1.1):
114
+ changed = camera.model_copy(update={'fx':camera.fx*factor, 'fy':camera.fy*factor})
115
+ directions.append(fit_outline(pixels, changed, up)[0])
116
+ for corner in range(5):
117
+ for dx, dy in ((-1, -1), (-1, 1), (1, -1), (1, 1)):
118
+ changed = np.array(pixels, copy=True)
119
+ changed[corner] += [dx, dy]
120
+ directions.append(fit_outline(changed, camera, up)[0])
121
+ spread = float(np.degrees(np.arccos(np.clip(np.asarray(directions) @ vector, -1, 1))).max())
122
+ if spread > LIMITS['maximum_sensitivity_deg']:
123
+ raise Unreliable('plate_direction_unstable')
124
+ return vector, error, spread
125
+
126
+
127
+ def estimate(video, capture, options, up_reference, track=None, progress=lambda *a: None):
128
+ """Run automatically when neither direction nor floor points were supplied."""
129
+ import cv2
130
+ from .ingest import iter_frames
131
+ from .camera_up import sample_indices
132
+ from .motion_contract import MotionCamera
133
+ from .pitcher_direction import Unreliable, _unit
134
+ out = reference()
135
+ if options.camera_stability == 'moving':
136
+ return reference('camera_moving')
137
+ if options.up_vector is None:
138
+ return reference('automatic_up_unavailable')
139
+ if up_reference.get('status') == 'estimated' and not up_reference.get('reliable'):
140
+ return reference('automatic_up_unreliable')
141
+ camera = options.camera
142
+ if camera is None:
143
+ data = up_reference.get('estimated_camera')
144
+ if data is None:
145
+ return reference('automatic_camera_calibration_unavailable')
146
+ camera = MotionCamera.model_validate(data)
147
+ out['camera_calibration'] = camera.model_dump(mode='json')
148
+ out['camera_calibration_accuracy_verified'] = False
149
+ ids = sample_indices(capture, LIMITS['sample_count'])
150
+ if len(ids) < LIMITS['minimum_frames']:
151
+ return reference('insufficient_video_frames')
152
+ uncertainty = up_reference.get('maximum_model_uncertainty_deg', 1.)
153
+ deviation = up_reference.get('maximum_deviation_deg', 0.)
154
+ if uncertainty is None or deviation is None or not np.isfinite(uncertainty+deviation):
155
+ return reference('automatic_up_uncertainty_unavailable')
156
+ up_spread = math.radians(max(1., uncertainty+deviation))
157
+ accepted, rows = [], []
158
+ progress('pitcher_direction_estimation', 0, len(ids))
159
+ try:
160
+ for i, _, _, image in iter_frames(video, capture['rotation_degrees']):
161
+ if i not in ids:
162
+ continue
163
+ box = track['boxes'][i] if track and 'boxes' in track else None
164
+ matches = []
165
+ candidates = outlines(image, box)
166
+ for pixels in candidates:
167
+ try:
168
+ vector, error, spread = checked_outline(pixels, camera, options.up_vector, up_spread)
169
+ matches.append(dict(source_frame_index=i, pitcher_vector=vector.tolist(),
170
+ corners=pixels.tolist(), shape_error=error,
171
+ maximum_sensitivity_deg=spread))
172
+ except (Unreliable, ValueError, np.linalg.LinAlgError, cv2.error):
173
+ continue
174
+ row = dict(source_frame_index=i, candidate_count=len(candidates), matched_plate_count=len(matches))
175
+ # Multiple plausible plates do not establish which one is in use.
176
+ if len(matches) == 1:
177
+ accepted.append(matches[0])
178
+ row.update(matches[0])
179
+ rows.append(row)
180
+ progress('pitcher_direction_estimation', len(rows), len(ids))
181
+ if i == ids[-1]:
182
+ break
183
+ except (ValueError, cv2.error) as error:
184
+ out.update(reason_code='automatic_direction_image_processing_failed', error_type=type(error).__name__)
185
+ return out
186
+ out.update(frames=rows, sampled_frame_count=len(rows), accepted_frame_count=len(accepted))
187
+ if any(row['matched_plate_count'] > 1 for row in rows):
188
+ out['reason_code'] = 'multiple_home_plates_ambiguous'
189
+ return out
190
+ if len(accepted) < max(LIMITS['minimum_frames'], math.ceil(.6*len(ids))):
191
+ out['reason_code'] = 'insufficient_clear_home_plate_frames'
192
+ return out
193
+ vectors = np.array([row['pitcher_vector'] for row in accepted])
194
+ # Never flip signs or average contradictory estimates into a confident axis.
195
+ if np.any(vectors @ vectors.T < math.cos(math.radians(LIMITS['maximum_direction_spread_deg']))):
196
+ out['reason_code'] = 'inconsistent_home_plate_direction'
197
+ return out
198
+ centres = np.array([np.mean(row['corners'], axis=0) for row in accepted])
199
+ w, h = image.shape[1], image.shape[0]
200
+ if np.max(np.linalg.norm(centres-centres[0], axis=1)) > .01*math.hypot(w, h):
201
+ out['reason_code'] = 'plate_or_camera_moved'
202
+ return out
203
+ frames = capture['frames']
204
+ duration = frames[-1]['playback_s']-frames[0]['playback_s']
205
+ coverage = (frames[accepted[-1]['source_frame_index']]['playback_s']-
206
+ frames[accepted[0]['source_frame_index']]['playback_s'])/duration if duration > 0 else 0.
207
+ out['temporal_coverage_fraction'] = coverage
208
+ if coverage < LIMITS['minimum_coverage']:
209
+ out['reason_code'] = 'insufficient_plate_temporal_coverage'
210
+ return out
211
+ out.update(status='estimated', pitcher_vector=_unit(vectors.mean(0)).tolist(),
212
+ pitcher_source='Automatically detected home-plate outline; estimated camera and floor geometry; plate alignment assumed',
213
+ applied=True, reliable=True, reason_code=None)
214
+ return out
baseball_batting/camera_up.py CHANGED
@@ -105,6 +105,17 @@ def consensus(rows,capture,options):
105
  out['reason_code']='insufficient_camera_up_temporal_coverage';return out
106
  source='GeoCalib pinhole image calibration; multi-frame camera-up consensus (estimated)'
107
  out.update(status='estimated',up_vector=vector.tolist(),up_source=source,applied=True,reliable=True,reason_code=None)
 
 
 
 
 
 
 
 
 
 
 
108
  return out
109
 
110
 
@@ -134,7 +145,7 @@ def estimate(job,video,capture,models,options,track,progress):
134
  out=consensus(rows,capture,options)
135
  out.update(provider_revision=REVISION,weights_sha256=provider['weights_sha256'],
136
  implementation_sha256=implementation_hash(),inference_seed=0,
137
- camera_intrinsics_policy='calibration nuisance only; body-model intrinsics unchanged')
138
  except (OSError,ValueError,KeyError,subprocess.SubprocessError) as error:
139
  out=reference(options,'camera_up_estimation_failed');out['error_type']=type(error).__name__
140
  atomic_json(job/'camera-up-private.json',out)
 
105
  out['reason_code']='insufficient_camera_up_temporal_coverage';return out
106
  source='GeoCalib pinhole image calibration; multi-frame camera-up consensus (estimated)'
107
  out.update(status='estimated',up_vector=vector.tolist(),up_source=source,applied=True,reliable=True,reason_code=None)
108
+ # Lens estimates support automatic scene geometry only. They do not replace
109
+ # the reconstruction model's intrinsics or become user-verified calibration.
110
+ cameras=np.asarray([r['estimated_intrinsics'] for r in accepted if 'estimated_intrinsics' in r],float)
111
+ if cameras.shape==(len(accepted),3,3) and np.isfinite(cameras).all():
112
+ focal=cameras[:,[0,1],[0,1]]
113
+ centre=np.median(cameras,axis=0)
114
+ if np.all(focal>0) and np.max(np.abs(focal/centre[[0,1],[0,1]]-1))<=.15:
115
+ out['estimated_camera']={'fx':float(centre[0,0]),'fy':float(centre[1,1]),
116
+ 'cx':float(centre[0,2]),'cy':float(centre[1,2]),
117
+ 'source':'GeoCalib accepted scene frames; median estimated intrinsics',
118
+ 'calibration_status':'estimated'}
119
  return out
120
 
121
 
 
145
  out=consensus(rows,capture,options)
146
  out.update(provider_revision=REVISION,weights_sha256=provider['weights_sha256'],
147
  implementation_sha256=implementation_hash(),inference_seed=0,
148
+ camera_intrinsics_policy='estimated scene geometry only; body-model intrinsics unchanged')
149
  except (OSError,ValueError,KeyError,subprocess.SubprocessError) as error:
150
  out=reference(options,'camera_up_estimation_failed');out['error_type']=type(error).__name__
151
  atomic_json(job/'camera-up-private.json',out)
baseball_batting/camera_up_worker.py CHANGED
@@ -110,6 +110,12 @@ def run(request,device='cuda'):
110
  torch.manual_seed(0)
111
  result=model.calibrate(tensor,camera_model='pinhole',priors=priors)
112
  item=diagnostics(result,prepared,mask,valid)
 
 
 
 
 
 
113
  if item['valid_rectification_fraction']<.9:item['reason_code']='insufficient_valid_rectified_image'
114
  rows.append({**base,**item})
115
  del result,tensor
 
110
  torch.manual_seed(0)
111
  result=model.calibrate(tensor,camera_model='pinhole',priors=priors)
112
  item=diagnostics(result,prepared,mask,valid)
113
+ if request['camera'] is None:
114
+ # Return lens estimates in source pixels, not the resized inference grid.
115
+ k=result['camera'].K.detach().cpu().numpy()[0].astype(float)
116
+ k[0]*=image.shape[1]/prepared.shape[1]
117
+ k[1]*=image.shape[0]/prepared.shape[0]
118
+ item['estimated_intrinsics']=k.tolist()
119
  if item['valid_rectification_fraction']<.9:item['reason_code']='insufficient_valid_rectified_image'
120
  rows.append({**base,**item})
121
  del result,tensor
baseball_batting/motion_api.py CHANGED
@@ -101,6 +101,10 @@ def register(app,service,authenticated):
101
  'refinement_observations':'RTMW image landmarks and forward/backward optical flow; soft constraints',
102
  'refinement_accuracy_validated':False,'camera_distortion_model':'Brown-Conrady k1 k2 p1 p2 k3',
103
  'automatic_camera_up':camera_up_status(settings.model_root),
 
 
 
 
104
  'pitcher_direction_from_floor_points':{'supported':True,'method':'two_floor_points_ray_plane_v1',
105
  'input':'options.pitcher_floor_points','calibration_required':'camera.calibration_status=calibrated',
106
  'camera_frame':'upright_camera_x_right_y_down_z_away'},
 
101
  'refinement_observations':'RTMW image landmarks and forward/backward optical flow; soft constraints',
102
  'refinement_accuracy_validated':False,'camera_distortion_model':'Brown-Conrady k1 k2 p1 p2 k3',
103
  'automatic_camera_up':camera_up_status(settings.model_root),
104
+ 'automatic_pitcher_direction':{'supported':True,'automatic_when_missing':True,
105
+ 'method':'automatic_home_plate_floor_geometry_v1','accuracy_validated':False,
106
+ 'requires_user_direction_input':False,
107
+ 'unknown_when':'no clear consistent aligned home plate or usable camera/up estimate'},
108
  'pitcher_direction_from_floor_points':{'supported':True,'method':'two_floor_points_ray_plane_v1',
109
  'input':'options.pitcher_floor_points','calibration_required':'camera.calibration_status=calibrated',
110
  'camera_frame':'upright_camera_x_right_y_down_z_away'},
baseball_batting/motion_export.py CHANGED
@@ -151,6 +151,9 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
151
  calculation_options=calculation_options.model_copy(update={'camera_stability':'moving'})
152
  from .pitcher_direction import resolve as resolve_pitcher_direction
153
  pitcher_reference=resolve_pitcher_direction(calculation_options,capture,up_reference)
 
 
 
154
  if options.pitcher_vector is None and pitcher_reference['status']=='estimated' and pitcher_reference['reliable'] is True:
155
  calculation_options=calculation_options.model_copy(update={
156
  'pitcher_vector':tuple(pitcher_reference['pitcher_vector']),
@@ -252,7 +255,8 @@ def export_motion(job,video,capture,raw,options,model,lineage,*,retention_s=8640
252
  if (pitcher_reference['status']=='estimated' and details['value'] is not None and key in
253
  ('hip_heading_deg','shoulder_heading_deg','left_foot_heading_deg','right_foot_heading_deg',
254
  'stride_relative_forward_cm','stride_relative_lateral_cm')):
255
- details['quality_flags'].append('pitcher_reference_estimated_from_floor_points')
 
256
  summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
257
  'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
258
  'source_samples':[stamp(i) for i in metric.source_frame_ids]})
 
151
  calculation_options=calculation_options.model_copy(update={'camera_stability':'moving'})
152
  from .pitcher_direction import resolve as resolve_pitcher_direction
153
  pitcher_reference=resolve_pitcher_direction(calculation_options,capture,up_reference)
154
+ if options.pitcher_vector is None and options.pitcher_floor_points is None:
155
+ from .automatic_pitcher_direction import estimate as estimate_pitcher_direction
156
+ pitcher_reference=estimate_pitcher_direction(video,capture,calculation_options,up_reference,track,progress)
157
  if options.pitcher_vector is None and pitcher_reference['status']=='estimated' and pitcher_reference['reliable'] is True:
158
  calculation_options=calculation_options.model_copy(update={
159
  'pitcher_vector':tuple(pitcher_reference['pitcher_vector']),
 
255
  if (pitcher_reference['status']=='estimated' and details['value'] is not None and key in
256
  ('hip_heading_deg','shoulder_heading_deg','left_foot_heading_deg','right_foot_heading_deg',
257
  'stride_relative_forward_cm','stride_relative_lateral_cm')):
258
+ details['quality_flags'].append('pitcher_reference_estimated_from_home_plate' if pitcher_reference.get('automatic')
259
+ else 'pitcher_reference_estimated_from_floor_points')
260
  summaries.append({**metadata,**details,'metric_id':key,'reference_frame':metric.reference,
261
  'uses_interpolated_input':interpolation,'reasons':[metric.reason_code] if metric.reason_code else [],
262
  'source_samples':[stamp(i) for i in metric.source_frame_ids]})
docs/APP_API_INTEGRATION.md CHANGED
@@ -186,6 +186,15 @@ Example **only when the uploader confirms these recording facts**:
186
 
187
  Other supported calibration inputs: `camera`, `up_vector`/`up_source`,
188
  `pitcher_vector`/`pitcher_source`, and `scale_factor`/`scale_source`/`scale_status`.
 
 
 
 
 
 
 
 
 
189
  Keep manual calibration overrides in a reviewed flow, not frontend guesses.
190
  Camera-up is now estimated automatically when omitted; explicit `up_vector`
191
  and `up_source` always take priority. Many body angles still require verified
 
186
 
187
  Other supported calibration inputs: `camera`, `up_vector`/`up_source`,
188
  `pitcher_vector`/`pitcher_source`, and `scale_factor`/`scale_source`/`scale_status`.
189
+ Normal uploads should omit `pitcher_vector`, `pitcher_source`, and
190
+ `pitcher_floor_points`. When all are absent, both models automatically attempt
191
+ to find a home plate in the video and estimate the direction from its outline.
192
+ No user clicks, direction numbers, or calibration form are required. The existing
193
+ GeoCalib provider supplies missing camera/up estimates; it must be installed on
194
+ the server. Missing or ambiguous evidence returns an unknown direction without
195
+ interrupting the job or requesting user input. This does not bypass the existing
196
+ camera-stability requirements for measurements. See
197
+ [automatic direction behavior and limitations](PITCHER_FLOOR_DIRECTION.md#automatic-direction-default).
198
  Keep manual calibration overrides in a reviewed flow, not frontend guesses.
199
  Camera-up is now estimated automatically when omitted; explicit `up_vector`
200
  and `up_source` always take priority. Many body angles still require verified
docs/MOTION_PLAYER_API.md CHANGED
@@ -112,7 +112,14 @@ pitcher direction may be supplied before vertical is resolved. See
112
  [automatic camera-up estimation](CAMERA_UP_ESTIMATION.md) for coordinates,
113
  acceptance checks, FE labels and the `up_estimation.enabled` opt-out.
114
 
115
- To derive field direction, send `pitcher_floor_points` with `source_frame_index`,
 
 
 
 
 
 
 
116
  `near_batter` and `toward_pitcher` in upright source pixels. This uses supplied
117
  camera calibration marked `camera.calibration_status: "calibrated"` and supplied
118
  or accepted estimated up. Explicit pitcher vectors take priority. Returned
 
112
  [automatic camera-up estimation](CAMERA_UP_ESTIMATION.md) for coordinates,
113
  acceptance checks, FE labels and the `up_estimation.enabled` opt-out.
114
 
115
+ When no pitcher vector or floor points are supplied, the pipeline automatically
116
+ attempts to identify a home-plate outline across sampled frames and derive its
117
+ direction using the camera/up estimates. No direction input is required. Missing
118
+ or ambiguous evidence leaves the direction unknown without stopping the job.
119
+ The plate must be aligned with the intended pitcher; this assumption and the
120
+ unvalidated accuracy are reported in `coordinates.pitcher_estimation`.
121
+
122
+ For an optional manual override, send `pitcher_floor_points` with `source_frame_index`,
123
  `near_batter` and `toward_pitcher` in upright source pixels. This uses supplied
124
  camera calibration marked `camera.calibration_status: "calibrated"` and supplied
125
  or accepted estimated up. Explicit pitcher vectors take priority. Returned
docs/PITCHER_FLOOR_DIRECTION.md CHANGED
@@ -2,6 +2,56 @@
2
 
3
  Motion API 1.14.0 · SAM 3D Body and GVHMR · 19 October 2026
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  Use the existing `/v1/motion-analyses` upload and `/revisions` routes. Select a
6
  decoded source frame and two points **on the same level floor**: first near the
7
  batter, then farther along the floor toward the pitcher. They need not be at
@@ -59,8 +109,8 @@ unreliable or missing up reference leaves the floor direction unknown.
59
  `calibration_status` does not change existing body reconstruction or up
60
  estimation. Older motion requests continue to work, defaulting it to `unknown`;
61
  they cannot silently promote a guessed focal length into floor calibration.
62
- SAM/GVHMR body-model intrinsics and GeoCalib's internal focal estimate are not
63
- substituted for the required declared calibration. This option belongs to the
64
  motion API; legacy SAM/coaching request contracts remain separate.
65
 
66
  ## Frontend coordinate mapping
 
2
 
3
  Motion API 1.14.0 · SAM 3D Body and GVHMR · 19 October 2026
4
 
5
+ ## Automatic direction (default)
6
+
7
+ Updated 29 October 2026. Normal motion uploads omit `pitcher_vector`,
8
+ `pitcher_source`, and `pitcher_floor_points`. Both SAM and GVHMR automatically
9
+ attempt `automatic_home_plate_floor_geometry_v1` before calculating/exporting
10
+ measurements. There are no new request fields, user prompts, external calls,
11
+ model downloads, or plate-detector dependencies.
12
+
13
+ The existing GeoCalib worker supplies an accepted up direction and estimated
14
+ camera intrinsics in original upright pixels. The default automatic path needs
15
+ that server-side provider installed. It does not require users to calibrate the
16
+ camera. Provided camera/up overrides can also be used. Estimated intrinsics
17
+ remain labelled estimated and do not replace the body model's camera.
18
+
19
+ The detector samples nine frames, proposes bright, low-saturation convex
20
+ five-corner outlines outside the tracked athlete, and fits the known home-plate
21
+ shape on the estimated level floor. Its broad front edge defines the direction
22
+ toward the pitcher. It checks corner/lens/up perturbations, requires agreement
23
+ over at least 60% of sampled frames (minimum three) and half the recording, and
24
+ rejects multiple matching plates, direction disagreement, and observed plate
25
+ movement. It never defines the field axis using the player's stance or stride.
26
+
27
+ On acceptance, `coordinates.pitcher_estimation` contains `automatic: true`,
28
+ `status: estimated`, the method, detected corners/source frame indices, camera
29
+ source, shape errors, sensitivity diagnostics and assumptions. Effective
30
+ `pipeline.calculation_inputs` receive the vector and generated source; submitted
31
+ `pipeline.inputs` remain unchanged. Relevant measurements carry
32
+ `pitcher_reference_estimated_from_home_plate`. Existing replay/recalculation uses
33
+ the same effective vector. Explicit vectors and manual floor selections retain
34
+ precedence for existing clients.
35
+
36
+ **Limits:** this is a conservative geometric detector, not a trained semantic
37
+ home-plate classifier. It assumes that a matching plate is on level ground and
38
+ aligned with the intended pitcher. It cannot independently verify that alignment
39
+ or reject every unrelated plate-shaped object. Small, dirty, obscured, dark,
40
+ nonstandard, or poorly resolved plates may be rejected. No plate/reference,
41
+ missing camera-up provider, or inconsistent geometry leaves the direction null;
42
+ normal motion export continues, with field-dependent measurements unavailable.
43
+ An accepted direction does not mark the camera fixed or bypass existing scale,
44
+ timing, or measurement checks. Camera movement declared or detected by refinement
45
+ blocks this automatic reference.
46
+
47
+ `accuracy_validated` remains false and `confidence` remains null. Thresholds and
48
+ sensitivity tests are not accuracy guarantees. Synthetic projected scenes test
49
+ geometry, abstention, and artifact consistency; independently labelled real
50
+ recordings are still required to measure accuracy and false positives. Removing
51
+ manual fields from the UI does not imply every recording yields a direction.
52
+
53
+ ## Optional manual override
54
+
55
  Use the existing `/v1/motion-analyses` upload and `/revisions` routes. Select a
56
  decoded source frame and two points **on the same level floor**: first near the
57
  batter, then farther along the floor toward the pitcher. They need not be at
 
109
  `calibration_status` does not change existing body reconstruction or up
110
  estimation. Older motion requests continue to work, defaulting it to `unknown`;
111
  they cannot silently promote a guessed focal length into floor calibration.
112
+ For this manual floor-point path, SAM/GVHMR body-model intrinsics and GeoCalib's
113
+ internal focal estimate are not substituted for the required declared calibration. This option belongs to the
114
  motion API; legacy SAM/coaching request contracts remain separate.
115
 
116
  ## Frontend coordinate mapping
tests/test_automatic_pitcher_direction.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Independent projected geometry and video-level automatic direction checks.
2
+
3
+ Synthetic accuracy verifies geometry, not home-plate recognition in real footage.
4
+ """
5
+ import json
6
+ import av
7
+ import cv2
8
+ import numpy as np
9
+ import pytest
10
+ from scipy.spatial.transform import Rotation
11
+ from baseball_batting.automatic_pitcher_direction import outlines, fit_outline, checked_outline, estimate, METHOD
12
+ from baseball_batting.motion_contract import MotionInput, MotionCamera
13
+ from baseball_batting.geometry import project
14
+ from baseball_batting.ingest import ingest
15
+ from baseball_batting.motion_export import export_motion, reproduce_measurements
16
+ from baseball_batting.camera_up import consensus
17
+ from baseball_batting.pitcher_direction import Unreliable
18
+ from test_motion_player import raw_for
19
+ from test_camera_up import evidence, capture as up_capture
20
+
21
+
22
+ K = np.array([[1200., 0, 640], [0, 1200, 360], [0, 0, 1]])
23
+ CAMERA = MotionCamera(fx=1200, fy=1200, cx=640, cy=360, source='Synthetic camera truth', calibration_status='calibrated')
24
+
25
+
26
+ def plate(angle=30., tilt=(0, 0, 0)):
27
+ # Physical front-left, front-right, rear-right, rear tip, rear-left corners.
28
+ # Independently expressed in metres; do not import the production template.
29
+ corners = np.array([[-.2159, 0], [.2159, 0], [.2159, .2159], [0, .4318], [-.2159, .2159]])
30
+ direction = np.array([np.cos(np.radians(angle)), 0., np.sin(np.radians(angle))])
31
+ across = np.cross([0, -1, 0], direction)
32
+ points = [0, 1, 4.5]+corners[:, 0, None]*across-corners[:, 1, None]*direction
33
+ rotation = Rotation.from_euler('xyz', tilt, degrees=True).as_matrix()
34
+ return project(points @ rotation.T, K), rotation @ direction, rotation @ [0., -1., 0.]
35
+
36
+
37
+ def frame(angle=30., rectangle=False):
38
+ image = np.full((720, 1280, 3), (20, 65, 30), np.uint8)
39
+ if rectangle:
40
+ cv2.rectangle(image, (500, 500), (650, 570), (240, 240, 240), -1)
41
+ else:
42
+ pixels, _, _ = plate(angle)
43
+ cv2.fillConvexPoly(image, np.rint(pixels).astype('int32'), (240, 240, 240))
44
+ return image
45
+
46
+
47
+ def video_file(tmp_path, angles=None, rectangle=False):
48
+ path = tmp_path/'plate.mp4'
49
+ with av.open(str(path), 'w') as output:
50
+ stream = output.add_stream('libx264', rate=30)
51
+ stream.width, stream.height, stream.pix_fmt = 1280, 720, 'yuv420p'
52
+ stream.options = {'crf':'0', 'bf':'0'}
53
+ for angle in angles or [30.]*13:
54
+ for packet in stream.encode(av.VideoFrame.from_ndarray(frame(angle, rectangle), format='bgr24')):
55
+ output.mux(packet)
56
+ for packet in stream.encode():
57
+ output.mux(packet)
58
+ return path
59
+
60
+
61
+ def automatic_up():
62
+ return {'status':'estimated', 'reliable':True, 'up_vector':[0, -1, 0],
63
+ 'up_source':'Synthetic image-provider output', 'coordinate_frame':'upright_camera_x_right_y_down_z_away',
64
+ 'maximum_model_uncertainty_deg':1., 'maximum_deviation_deg':0.,
65
+ 'estimated_camera':{**CAMERA.model_dump(), 'calibration_status':'estimated'}}
66
+
67
+
68
+ @pytest.mark.parametrize('angle', [0, 30, 60, 90, 135, 180, 225, 270])
69
+ @pytest.mark.parametrize('tilt', [(0, 0, 0), (4, -8, 12)])
70
+ def test_plate_geometry_recovers_true_direction_with_tilt_and_unknown_corner_order(angle, tilt):
71
+ pixels, truth, up = plate(angle, tilt)
72
+ for order in (pixels, np.roll(pixels, 2, axis=0), pixels[::-1]):
73
+ direction, error = fit_outline(order, CAMERA, up)
74
+ np.testing.assert_allclose(direction, truth, atol=1e-10)
75
+ assert error < 1e-10
76
+
77
+
78
+ @pytest.mark.parametrize('angle', [0, 30, 60, 135, 180, 225])
79
+ def test_pixel_detector_and_sensitivity_checks_recover_rendered_direction(angle):
80
+ proposals = outlines(frame(angle))
81
+ assert len(proposals) == 1
82
+ direction, error, spread = checked_outline(proposals[0], CAMERA, [0, -1, 0], np.radians(1))
83
+ _, truth, _ = plate(angle)
84
+ assert np.degrees(np.arccos(np.clip(direction @ truth, -1, 1))) < 2
85
+ assert error < .065 and spread < 10
86
+
87
+
88
+ def test_rectangles_people_and_regular_pentagons_do_not_supply_a_direction():
89
+ assert outlines(frame(rectangle=True)) == []
90
+ assert outlines(frame(), [0, 0, 1280, 720]) == []
91
+ angles = np.arange(5)*2*np.pi/5
92
+ floor = np.stack([.3*np.cos(angles), np.ones(5), 4.5+.3*np.sin(angles)], axis=1)
93
+ with pytest.raises(Unreliable, match='does_not_match'):
94
+ fit_outline(project(floor, K), CAMERA, [0, -1, 0])
95
+
96
+
97
+ def test_default_request_uses_automatic_camera_and_no_direction_inputs(tmp_path):
98
+ path = video_file(tmp_path)
99
+ options = MotionInput() # No direction, handedness, camera or floor-point input.
100
+ capture = ingest(path, options.metadata())
101
+ calculated = options.model_copy(update={'up_vector':(0, -1, 0), 'up_source':'Automatic image estimate'})
102
+ result = estimate(path, capture, calculated, automatic_up())
103
+ assert result['status'] == 'estimated', result
104
+ assert result['automatic'] and result['method'] == METHOD and result['applied']
105
+ assert result['confidence'] is None and result['accuracy_validated'] is False
106
+ assert result['camera_calibration']['calibration_status'] == 'estimated'
107
+ assert options.pitcher_vector is None and options.camera is None
108
+ assert result['temporal_coverage_fraction'] == 1
109
+
110
+
111
+ def test_missing_references_and_unclear_video_return_unknown_without_user_prompts(tmp_path):
112
+ options = MotionInput()
113
+ assert estimate(None, None, options, {})['reason_code'] == 'automatic_up_unavailable'
114
+ options = options.model_copy(update={'up_vector':(0, -1, 0), 'up_source':'Automatic'})
115
+ assert estimate(None, None, options, {})['reason_code'] == 'automatic_camera_calibration_unavailable'
116
+ path = video_file(tmp_path, rectangle=True)
117
+ out = estimate(path, ingest(path, {}), options, automatic_up())
118
+ assert out['status'] == 'unknown' and out['pitcher_vector'] is None
119
+ assert not out['applied']
120
+
121
+
122
+ def test_contradictory_directions_are_not_averaged(tmp_path):
123
+ path = video_file(tmp_path, angles=[30.]*6+[210.]*7)
124
+ options = MotionInput(up_vector=[0,-1,0], up_source='Synthetic gravity')
125
+ out = estimate(path, ingest(path, {}), options, automatic_up())
126
+ assert out['status'] == 'unknown' and out['reason_code'] == 'inconsistent_home_plate_direction', out
127
+
128
+
129
+ def test_multiple_visible_plates_are_ambiguous(tmp_path, monkeypatch):
130
+ path = video_file(tmp_path)
131
+ one, _, _ = plate()
132
+ monkeypatch.setattr('baseball_batting.automatic_pitcher_direction.outlines', lambda *a: [one, one.copy()])
133
+ out = estimate(path, ingest(path, {}), MotionInput(up_vector=[0,-1,0], up_source='Test'), automatic_up())
134
+ assert out['reason_code'] == 'multiple_home_plates_ambiguous' and not out['applied']
135
+
136
+
137
+ @pytest.mark.parametrize('model', ['sam3d', 'gvhmr'])
138
+ def test_export_applies_automatic_reference_and_replays_identical_measurements(tmp_path, model):
139
+ path = video_file(tmp_path)
140
+ options = MotionInput(model=model, annotated_videos=False, single_swing=True,
141
+ camera_stability='fixed_verified')
142
+ capture = ingest(path, options.metadata())
143
+ manifest = export_motion(tmp_path, path, capture, raw_for(capture), options, {'name':'synthetic'},
144
+ {'analysis_id':'auto-plate', 'analysis_revision':1}, up_reference=automatic_up())
145
+ ref = manifest.coordinates['pitcher_estimation']
146
+ assert ref['status'] == 'estimated', ref
147
+ assert manifest.pipeline['inputs']['pitcher_vector'] is None
148
+ assert manifest.pipeline['inputs']['camera'] is None
149
+ assert manifest.pipeline['calculation_inputs']['pitcher_vector'] == ref['pitcher_vector']
150
+ report = json.loads((tmp_path/'measurements.json').read_text())
151
+ assert report['pitcher_reference'] == ref
152
+ flags = [f for m in report['summaries'] for f in m['quality_flags']]
153
+ assert 'pitcher_reference_estimated_from_home_plate' in flags
154
+ assert 'pitcher_reference_estimated_from_floor_points' not in flags
155
+ reproduced = reproduce_measurements(manifest, tmp_path/'motion.jsonl')
156
+ expected = {(s.rep,m.key):m.value for group in reproduced.values() for s in group for m in s.measurements}
157
+ for row in report['summaries']:
158
+ value = expected[row['rep'],row['metric_id']]
159
+ assert row['value'] == pytest.approx(value) if value is not None else row['value'] is None
160
+
161
+
162
+ def test_only_consistent_accepted_camera_estimates_are_available_for_scene_geometry():
163
+ rows = [evidence(i, estimated_intrinsics=K.tolist()) for i in range(7)]
164
+ result = consensus(rows, up_capture(), MotionInput())
165
+ assert result['estimated_camera']['fx'] == 1200
166
+ assert result['estimated_camera']['calibration_status'] == 'estimated'
167
+ rows[0]['estimated_intrinsics'] = (K*np.array([[2,1,1],[1,2,1],[1,1,1]])).tolist()
168
+ assert 'estimated_camera' not in consensus(rows, up_capture(), MotionInput())