# Document Quiz Import — developer flow
Approved developer flow. Browser evidence was captured on 21 September 2026; the flow was reviewed against implementation commit `be6fe524` on 23 September 2026.

## Main flow

```mermaid
flowchart TD
    A["Instructor creates a document quiz"] --> B["Select question PDF"]
    B --> C["API authorizes instructor and issues presigned upload URL"]
    C --> D["Browser uploads directly to private R2 pending object"]
    D --> E["Browser confirms upload with upload token"]
    E --> F["API records processing job; starts task after DB commit"]
    F --> G["PDF task reads and validates file; retains valid PDF"]
    G --> H{"How to enter answers?"}
    H -->|Manual| M["Instructor enters answer rows"]
    H -->|AI| I["Select answer file; upload directly to R2; confirm upload"]
    I --> J["Answer task retains file and reads both files"]
    J --> K["Gemini extracts rows using the effective key selected by tenant key mode"]
    K --> L["Store answer_draft in quiz_documents"]
    L --> M
    M --> N["Review or correct rows; click Save answers"]
    N --> O["API validates rows; saves question records; clears draft"]
    O --> P["Student opens available quiz"]
    P --> Q["Download question PDF; render answer controls"]
    Q --> R["Submit responses through existing grading flow"]
    G -.->|Invalid PDF or timeout| X["Mark failed; preserve previous valid PDF"]
    K -.->|Missing key, extraction error or timeout| Y["Mark failed; preserve saved answers"]
    X --> B
    Y -->|Upload answer file again| I
    Y -->|Manual entry with valid PDF| M
```

## Upload and background processing

The same upload protocol is used separately for the question PDF and answer file.

```mermaid
sequenceDiagram
    actor Instructor
    participant UI as Instructor browser
    participant API as Backend API
    participant DB as PostgreSQL
    participant R2 as Private R2
    participant Task as In-process background task
    participant AI as Gemini
    Instructor->>UI: Select file and click Upload
    UI->>API: Request upload URL (slot, filename, size)
    API->>API: Check tenant, ownership, feature flag and idle state
    API->>DB: Record pending upload token and key
    API-->>UI: Presigned PUT URL and upload token
    UI->>R2: Upload file bytes
    UI->>API: Confirm completion with token
    API->>DB: Set job_id, processing status and start time
    Note over API,Task: Dispatch only after transaction commits
    API->>Task: Start task with captured tenant context
    API-->>UI: Return processing state
    Task->>R2: Copy candidate to server-owned final key and read bytes
    alt Question PDF
        Task->>Task: Validate PDF and count pages
        Task->>DB: Attach valid PDF metadata; mark ready
    else Answer file
        Task->>DB: Attach accepted answer file metadata
        Task->>R2: Read retained question PDF
        Task->>AI: Send both files using the effective platform or tenant Gemini key
        AI-->>Task: Extracted answer rows
        Task->>DB: Store answer_draft; mark ready
    end
    Note over Task,DB: Apply result only for current, unexpired processing job
    Task->>R2: Clean pending and replaced objects
    loop While UI sees processing
        UI->>API: Poll document review
        API->>DB: Read state; expire timed-out job if needed
        API-->>UI: Status, error, PDF and answer draft
    end
    Instructor->>UI: Review and Save answers
    UI->>API: Save corrected rows
    API->>DB: Save question records and clear answer_draft
```

## What developers need to know

- **Files:** R2 holds bytes; PostgreSQL holds file metadata, job state and AI draft.
- **Draft versus saved answers:** AI output is stored in `answer_draft`. Instructor edits remain browser-local until Save writes the normal question records.
- **Processing status:** `idle / ready / failed → processing → ready | failed`. Both PDF validation and AI extraction use it, including re-upload after a ready or failed run. `ready` does not mean answers were reviewed or saved.
- **Closing the page:** polling stops; the backend task continues while its process remains alive. Reopening loads stored state.
- **Backend restart:** tasks are not durable. Polling or a later action detects timeout. There is no automatic resume.
- **Recovery:** select and upload the answer file again, or enter answers manually once a valid question PDF exists. There is no extraction-only retry endpoint.
- **Concurrency:** short database locks protect mutations; the current job ID and timeout prevent stale results from overwriting newer work.
- **Student access:** the student receives the question PDF and answer controls. The answer source file and extraction draft are instructor-only; grading uses saved answers.
- **Storage prefix:** `tenants/{tenant_id}/quiz-documents/{quiz_nanoid}/`, with `pending/`, `files/` and `answers/` subfolders.

## Code entry points

| Responsibility | File |
| --- | --- |
| Upload controls, polling and review | apps/frontend/src/pages/Instructor/CourseDetail/sections/DocumentQuizEditor.tsx |
| Instructor API routes | apps/backend/app/routers/v1/instructor.py |
| Upload lifecycle and background tasks | apps/backend/app/services/quiz_document.py |
| Timeout and answer validation | apps/backend/app/services/document_answers.py |
| Gemini extraction | apps/backend/app/services/document_extraction.py |
| Document state and draft model | apps/backend/app/models/quiz_document.py |