# Cognivision Baseball backend: design **Status:** proposed, updated 2026-10-22. **Inputs:** - *Cognivision Baseball Backend Specification*, the frontend team's spec: 30 endpoints in 4 milestones. - The ML engineer's swing analysis payload contract `1.0`. - `AI-coach-agent/docs/SWING_REPORT_API.md`. **Conventions:** - JSON keys are `snake_case`. - URL paths are `kebab-case` under `/v1`. - Ids are UUIDs. - Times are ISO 8601 UTC. **Scope:** - The app talks to the ML API directly; this backend never calls it. - The backend stores accounts, teams, media and sessions. - The backend hosts the AI coach endpoint. That endpoint turns an ML payload into the swing report and saves it on the session. ## 1. What we need | Need | Choice | Notes | |---|---|---| | Database | PostgreSQL 16 on Neon or Supabase (not decided yet) | Plain Postgres only, so either provider works. Connection is configured by `DATABASE_URL`. | | Storage bucket | One private DigitalOcean Spaces bucket | S3-compatible: presigned URLs, HEAD, delete. Configured with `STORAGE_ENDPOINT`, `STORAGE_BUCKET`, `STORAGE_KEY`, `STORAGE_SECRET`. | | API service | Python 3.11, FastAPI, SQLAlchemy 2 (async, asyncpg), Alembic, Pydantic v2 | One deployable. It imports the `ai_coach` package in-process for the swing report. | | Scheduled job | The same codebase, run on a schedule (`python -m app.jobs.cleanup`) | Cleans up unattached uploads, abandoned sessions, deleted media and old idempotency keys. | | LLM | Gemini, through the existing `ai_coach` package | Writes the coaching text only. Code computes scores and ratings, and a rule-based fallback is always available. | | Push | Firebase Cloud Messaging (also delivers to APNs) | Milestone 3. | | Email | One transactional provider (SES or Resend) | Password reset, milestone 4. | | Payments | App Store Server API and Google Play Developer API | Pro plan, milestone 4. | ### Bucket layout and rules ``` / videos/{account_id}/{upload_id}.{mp4|mov} thumbnails/{account_id}/{upload_id}.jpg ``` - The bucket is private, so files have no public URLs. - Uploads use a presigned PUT valid for 15 minutes. Playback uses a presigned GET valid for 1 hour. - Videos must be `video/mp4` or `video/quicktime`, at most 250 MB and 60 s. Thumbnails must be `image/jpeg`. - `POST /v1/sessions` checks size and type with a HEAD request. Anything that breaks a limit is refused and deleted. - The app may also hand the ML API a presigned GET URL to the uploaded video. How the ML API receives the video is not the backend's concern. ## 2. How a swing becomes a report ``` App Backend Spaces |-- POST /v1/uploads (video, thumb) ->| create upload rows | |<- presigned PUT URLs ---------------| | |-- PUT video and thumbnail ------------------------------------------------------>| |-- POST /v1/sessions (marks, athlete) ->| plan check, HEAD both objects | |<- 201 session (status: pending) -------| | | | |-- ML API (not ours) -> contract 1.0 payload | | | |-- POST /v1/sessions/{id}/swing-report (payload) ->| validate the contract | | | add level, height and hand from the session athlete | | score, rate, focus area (code); text (Gemini or rules) | | save payload and report on the session |<- 200 swing report -------------------------------| | ``` - **The session is created first,** so the plan limit and the media checks happen before any analysis. - **Athlete details:** - `level` and `height_cm` come from the session snapshot. - `batting_hand` comes from the ML payload, because it is the side actually used on that swing. When the payload has none, the backend falls back to the session's `bats`, then infers it from `lead_foot`. - The ML API therefore needs no extra fields. - **The ML payload is stored with the report.** The report can be regenerated when benchmarks or coach rules change, without the ML API. - **Sending the same `analysis_id` and `analysis_revision` again returns the stored report.** An older revision is refused with 409. - **A session with no report after 24 h is abandoned.** The cleanup job deletes it with its media. - **Only sessions with a report count toward the free plan** (3 a week). ## 3. Database schema Twelve tables cover all four milestones. Derived values are not stored; each is one query in its repository: - **session status:** `pending` until `analyzed_at` is set, then `done` - **plan:** from active subscriptions - **roster:** from `accounts.team_id` - **coach queue:** sessions with no review - **ordinal and previous session** | Table | Columns | Keys and indexes | Milestone | |---|---|---|---| | `accounts` | `id`, `email citext`, `password_hash null`, `role` (player, coach), `focus` (h, p, both), `name`, `age null`, `height_cm null`, `weight_kg null`, `bats` (L, R, S) `null`, `throws` (L, R) `null`, `level null`, `unit` (imperial, metric), `private_videos`, `team_id null`, `created_at`, `updated_at` | `email` unique. `team_id` is an FK to `teams` with `on delete set null`, used by players only. Index on `team_id`. | 1 | | `refresh_tokens` | `id`, `account_id`, `token_hash`, `family_id`, `expires_at`, `revoked_at null`, `created_at` | `token_hash` unique. If a revoked token is reused, every token in its `family_id` is revoked. | 1 | | `teams` | `id`, `code`, `name`, `coach_id`, `coaching` (h, p, both), `created_at`, `updated_at` | `code` unique and `coach_id` unique, so there is one team per coach. The coach's name comes from `accounts.name`. | 1 | | `uploads` | `id`, `owner_id`, `kind` (video, thumbnail), `object_key`, `content_type`, `size_bytes`, `created_at`, `attached_at null` | `object_key` unique. Partial index on `created_at` where `attached_at is null`. | 2 | | `sessions` | `id`, `owner_id`, `is_self`, `athlete jsonb` (snapshot), `mode` (h, p), `video_upload_id`, `thumbnail_upload_id null`, `duration_sec`, `fps`, `marks jsonb`, `analysis_id null`, `analysis_revision null`, `measurement_payload jsonb null`, `report jsonb null`, `overall_score` (generated from `report`), `created_at`, `analyzed_at null`, `deleted_at null` | Indexes: (`owner_id`, `mode`, `created_at desc`); a partial index on (`owner_id`, `analyzed_at`) where it is not deleted; a partial index on `created_at` where `analyzed_at is null`. | 2 | | `drill_logs` | `id`, `owner_id`, `session_id null`, `drill_id`, `reps`, `day date`, `created_at` | Index on (`owner_id`, `day`). | 2 | | `idempotency_keys` | `account_id`, `key`, `request_hash`, `response_status`, `response_body jsonb`, `created_at` | Primary key (`account_id`, `key`). Purged after 24 h. Used by `POST /sessions` and `POST /drill-logs`. | 2 | | `reviews` | `session_id`, `coach_id`, `cue`, `drill_id`, `verdicts jsonb`, `created_at`, `updated_at` | Primary key on `session_id`, so one review per session. | 3 | | `devices` | `id`, `account_id`, `platform` (ios, android), `push_token`, `created_at`, `last_seen_at` | `push_token` unique. | 3 | | `auth_identities` | `id`, `account_id`, `provider` (apple, google), `subject`, `created_at` | Unique on (`provider`, `subject`). | 4 | | `password_resets` | `id`, `account_id`, `token_hash`, `expires_at`, `used_at null` | `token_hash` unique. | 4 | | `subscriptions` | `id`, `account_id`, `platform`, `product_id`, `original_transaction_id`, `status`, `expires_at`, `updated_at` | `original_transaction_id` unique. The plan is `pro` when an active row has `expires_at > now()`. | 4 | Every FK from a child to `accounts` uses `on delete cascade`, so account deletion is a single delete plus media removal. `sessions.marks`: ```json { "contact_frame": 84, "contact_offset": -2, "contact_source": "detected", "stride_start_frame": 58, "stride_end_frame": 79, "pitcher_direction": { "from": [0.56, 0.86], "to": [0.90, 0.64] } } ``` `sessions.athlete` is a snapshot of the person on camera. `level` is one of `youth`, `high_school`, `college` or `adult`: ```json { "name": "Ahmed Rehman", "age": 15, "height_cm": 168, "weight_kg": 60, "bats": "R", "throws": "R", "level": "high_school" } ``` ## 4. API Every endpoint in the frontend spec is covered, plus the AI coach endpoint (H1). | # | Method and path | Purpose | Who | Milestone | |---|---|---|---|---| | A1 | `POST /v1/auth/register` | Create an account | public | 1 | | A2 | `POST /v1/auth/login` | Sign in | public | 1 | | A3 | `POST /v1/auth/social` | Apple or Google sign-in | public | 4 | | A4 | `POST /v1/auth/refresh` | Rotate tokens | refresh token | 1 | | A5 | `POST /v1/auth/logout` | Revoke the refresh token | bearer | 1 | | A6 | `POST /v1/auth/password/forgot` | Send a reset email | public | 4 | | A7 | `POST /v1/auth/password/reset` | Set a new password | public | 4 | | B1 | `GET /v1/me` | Account, team and entitlement | bearer | 1 | | B2 | `PATCH /v1/me` | Role (onboarding only), focus, profile, unit, private videos | bearer | 1 | | B3 | `POST /v1/devices` | Register a push token | bearer | 3 | | B4 | `DELETE /v1/devices/{push_token}` | Remove a push token | bearer | 3 | | B5 | `DELETE /v1/me` | Delete the account and its media | bearer | 4 | | C1 | `POST /v1/teams` | Create or update the coach's team | coach | 1 | | C2 | `GET /v1/teams/lookup?code=` | Team summary by code | bearer | 1 | | C3 | `POST /v1/teams/{code}/join` | Join a team | player | 1 | | C4 | `DELETE /v1/me/team` | Leave the team | player | 1 | | D1 | `POST /v1/uploads` | Get a presigned upload URL | bearer | 2 | | D2 | `POST /v1/sessions` | Create a session (plan check, media check) | bearer | 2 | | H1 | `POST /v1/sessions/{id}/swing-report` | **AI coach:** ML payload in, swing report out, saved on the session | owner | 2 | | D3 | `GET /v1/sessions/{id}` | Session, report, media URLs, previous, ordinal | owner or team coach | 2 | | D4 | `GET /v1/sessions` | Session list (filters, cursor) | bearer | 2 | | D5 | `DELETE /v1/sessions/{id}` | Soft-delete a session and its media | owner | 2 | | D6 | `GET /v1/catalog/metrics` | Metric names, groups, drills | bearer | 4 | | E1 | `POST /v1/drill-logs` | Log a set | bearer | 2 | | E2 | `GET /v1/drill-logs?from=&to=` | Logs in a date range | bearer | 2 | | F1 | `GET /v1/coach/roster` | Players with last-session summaries | coach | 3 | | F2 | `GET /v1/coach/players/{player_id}/sessions` | A player's own sessions | coach | 3 | | F3 | `GET /v1/coach/queue` | Open and reviewed-today sessions | coach | 3 | | F4 | `POST /v1/sessions/{id}/review` | Send or overwrite a review, then push to the player | team coach | 3 | | G1 | `GET /v1/me/entitlement` | Plan and weekly usage | bearer | 4 | | G2 | `POST /v1/billing/receipts` | Validate a store purchase | bearer | 4 | | G3 | `POST /v1/billing/webhooks/{provider}` | Renewal, cancel and refund events | provider signature | 4 | **H1 behaviour:** - The body is one contract `1.0` payload. - **422** when the payload breaks a contract rule, or when the session mode is pitching (`MODE_NOT_SUPPORTED`) until pitching measurements exist. - **409** when the revision is older than the stored one. - **402** when the free plan is used up. **Errors** use one envelope everywhere: `{ "error": { "code": "EMAIL_TAKEN", "message": "...", "fields": {...} } }`. The codes are the ones in the frontend spec. **Lists** return `{ "items": [...], "next_cursor": null }`, with `limit` defaulting to 50 and capped at 200. ### Session response (D3) `report` is exactly the H1 response, and is `null` while `status` is `pending`. ```json { "session": { "id": "6f1c...", "owner_id": "8f3c...", "is_self": true, "mode": "h", "status": "done", "created_at": "2026-10-22T10:12:03Z", "analyzed_at": "2026-10-22T10:12:41Z", "athlete": { "name": "Ahmed Rehman", "age": 15, "height_cm": 168, "weight_kg": 60, "bats": "R", "throws": "R", "level": "high_school" }, "duration_sec": 3.87, "fps": 30, "marks": { "contact_frame": 84, "contact_offset": -2, "contact_source": "detected", "stride_start_frame": 58, "stride_end_frame": 79, "pitcher_direction": { "from": [0.56, 0.86], "to": [0.90, 0.64] } }, "report": { "overall_score": 55, "overview": {}, "groups": [], "focus_area": {}, "measurements": [], "data_quality": [] }, "review": null, "media": { "video_url": "https://...", "thumbnail_url": "https://...", "expires_at": "2026-10-22T11:12:03Z" }, "previous": { "id": "5a2b...", "overall_score": 52, "created_at": "2026-10-20T09:00:00Z" }, "ordinal": 4 } } ``` The `report` keys are shown empty here only to save space; the full shape is in `AI-coach-agent/docs/SWING_REPORT_API.md`. ## 5. Folder structure (controller, service, repository) ``` backend/ app/ main.py builds the app: routers, error handlers, middleware core/ config.py settings from environment variables (pydantic-settings) database.py async engine and session factory security.py argon2id hashing, JWT issue and verify errors.py AppError and its subclasses, plus the one error envelope dependencies.py current_account, require_role, pagination params pagination.py cursor encoding and decoding common/ base_model.py SQLAlchemy Base, uuid primary key, timestamp mixin base_repository.py generic get, list, create, update, delete, written once schemas.py Page[T] and ErrorResponse modules/ auth/ controller.py service.py repository.py schemas.py models.py accounts/ controller.py service.py repository.py schemas.py models.py teams/ controller.py service.py repository.py schemas.py models.py uploads/ controller.py service.py repository.py schemas.py models.py sessions/ controller.py service.py repository.py schemas.py models.py swing_reports/ controller.py service.py schemas.py (H1; calls ai_coach, saves through the sessions repository) drills/ controller.py service.py repository.py schemas.py models.py reviews/ controller.py service.py repository.py schemas.py models.py coach/ controller.py service.py schemas.py (reuses the sessions, teams and reviews repositories) devices/ controller.py service.py repository.py schemas.py models.py billing/ controller.py service.py repository.py schemas.py models.py integrations/ storage.py Spaces: presigned PUT and GET, HEAD, delete push.py FCM sender email.py transactional email app_store.py play_store.py jobs/ cleanup.py unattached uploads, abandoned sessions, deleted media, idempotency keys migrations/ Alembic tests/ unit/ services with fake repositories integration/ repositories and controllers against a test Postgres pyproject.toml Dockerfile ``` Each layer has one job: - **Controller:** HTTP only. It validates the request with Pydantic, calls one service method and returns the response. - **Service:** business rules: plan limit, role lock, mark order, coach access, review overwrite, revision order and push. - **Repository:** database only. Each one extends `BaseRepository[Model]`, so CRUD exists once, and adds only its own queries, such as `roster_for_coach`, `queue_for_team` or `previous_session`. - **Dependencies are injected** with FastAPI `Depends`. Tests swap in fake repositories and integrations without patching. ### Swing report logic (`AI-coach-agent`, used as a library) The report logic stays in the `ai_coach` package. The backend imports it, so there is one implementation and no extra network hop. ``` AI-coach-agent/src/ai_coach/swing_report/ service.py build_report(payload, athlete): validate, score, rate, focus area, Gemini text, guardrails, rules fallback repository.py benchmark registry and drill library, read from the knowledge YAML files scoring.py score and rating formulas (pure functions) schemas.py contract 1.0 input and swing report output (Pydantic) AI-coach-agent/src/ai_coach/knowledge/benchmarks.yaml OBP intervals by metric, batting hand and level, versioned ``` ## 6. Notes for the frontend 1. **Keys:** the API sends and accepts `snake_case`. Mapping to camelCase belongs to the app's own adapter. 2. **Analysis flow:** - Create the session (D2). - Call the ML API and wait for it to finish. - Post the ML payload, unchanged, to H1. - Show H1's response. There is no polling and no `queued` or `processing` status. 3. **Report shape:** the analysis is the swing report: - `report.overall_score` - `report.groups`, each with a score and a rating - `report.focus_area` - `report.measurements` 4. **Drill ids:** drills are referenced by id (for example `hit_13`) in drill logs and reviews. Review `verdicts` are keyed by `metric_id`. 5. **Hitting only for now:** H1 returns 422 `MODE_NOT_SUPPORTED` for pitching sessions. ## 7. Still open - **Neon or Supabase:** the code uses plain Postgres, so this is a deploy-time choice. - **The frontend spec's questions Q1 to Q15** (billing, consent, second-team behaviour, retention): we follow the spec's recommendations unless the product owner changes them. - **`front_foot_down` definition** from the ML engineer. This affects one benchmark.