diff --git a/.claude/agents/server-tests.md b/.claude/agents/server-tests.md index b0bfbf2e..d44f219c 100644 --- a/.claude/agents/server-tests.md +++ b/.claude/agents/server-tests.md @@ -4,7 +4,7 @@ description: Integrity of the server test suite itself. Use to check that a test tools: Read, Glob, Grep, Bash, Edit, Write --- -You own `server/tests/`. 3857 tests; `pytest -q -n auto`, bare, is exactly what CI runs. +You own `server/tests/`. 3877 tests; `pytest -q -n auto`, bare, is exactly what CI runs. Not `python -m pytest` for the gate: the `-m` form puts the current directory on `sys.path`, so a test that leans on it passes here and fails at collection on CI (`CLAUDE.md`, «Commands»; #310, #314). diff --git a/.claude/skills/gates/SKILL.md b/.claude/skills/gates/SKILL.md index 8c0b2b8a..840da9b4 100644 --- a/.claude/skills/gates/SKILL.md +++ b/.claude/skills/gates/SKILL.md @@ -27,7 +27,7 @@ that happens and names both trees (#312). after ruff — the owner asked for it through that day's audit (#210) — and still worth running before a push: seconds here, minutes there. It is the thing that reproduces the «🗓 Четверти» crash. -3. `pytest -q -n auto`, bare, from `server/` with its venv active — 3857 tests today, six of +3. `pytest -q -n auto`, bare, from `server/` with its venv active — 3877 tests today, six of them skipped unless a host is running (`-m host`, CI's «Host» job), plus eleven PostgreSQL-only lock checks skipped on SQLite, and **the exact command CI runs**. Not `python -m pytest`: the `-m` form puts the current diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 837ebf94..6965c4d6 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -10,37 +10,35 @@ version: 2 # # The Android versions in libs.versions.toml are not invented: they are carried # over from projects that build on them, and the catalog's header names the -# source of each. That is why updates are grouped and capped — five open pull -# requests carrying Compose alphas one at a time is a lottery, not an update. +# source of each. One weekly version cohort targets dev, so four updaters do +# not recreate separate branch queues after a consolidation. Production still +# receives a separately checked promotion. Security updates keep GitHub's +# separate default-branch queue. # # The labels are the project's own families, `type:` and `area:`, and each one # has to exist already: Dependabot skips a label the repository does not have, # without a word. It asked for `dependencies`, `android`, `server`, `vercel` # and `ci` for months, none of which existed, and every bump arrived bare # (#162). -updates: - - package-ecosystem: gradle - directory: /android +multi-ecosystem-groups: + dependencies: schedule: interval: weekly day: monday - open-pull-requests-limit: 5 + target-branch: dev + milestone: 7 labels: - type:chore + pull-request-branch-name: + prefix: work + +updates: + - package-ecosystem: gradle + directory: /android + multi-ecosystem-group: dependencies + patterns: ["*"] + labels: - area:android - groups: - androidx: - patterns: - - androidx.* - testing: - patterns: - - junit:* - - org.robolectric:* - network: - patterns: - - com.squareup.retrofit2:* - - com.squareup.okhttp3:* - - org.jetbrains.kotlinx:kotlinx-serialization* ignore: # AGP, Kotlin and KSP move together and only by hand: AGP 9 compiles # Kotlin itself, and the KSP version is tied to the compiler's. The three @@ -60,28 +58,10 @@ updates: - package-ecosystem: pip directory: /server - schedule: - interval: weekly - day: monday - open-pull-requests-limit: 5 + multi-ecosystem-group: dependencies + patterns: ["*"] labels: - - type:chore - area:server - groups: - testing: - patterns: - - pytest* - - ruff - runtime: - patterns: - - fastapi - - uvicorn* - - pydantic* - - sqlalchemy* - - alembic - - httpx - - asyncpg - - aiosqlite # The lock Vercel installs: requirements.txt, compiled by `uv pip compile` # from requirements.in (#192). `uv` rather than `pip`, because the uv updater @@ -97,18 +77,14 @@ updates: # else touches the lock alone. - package-ecosystem: uv directory: / - schedule: - interval: weekly - day: monday - open-pull-requests-limit: 3 + multi-ecosystem-group: dependencies + patterns: ["*"] labels: - - type:chore - area:server - package-ecosystem: github-actions directory: / - schedule: - interval: monthly + multi-ecosystem-group: dependencies + patterns: ["*"] labels: - - type:chore - area:ci diff --git a/.github/workflows/apk.yml b/.github/workflows/apk.yml index 87c5d403..1db5a94b 100644 --- a/.github/workflows/apk.yml +++ b/.github/workflows/apk.yml @@ -32,6 +32,10 @@ on: description: "versionCode to stamp (blank = this run's number)" type: string required: false + expected_commit: + description: "Refuse before signing if this ref no longer resolves to the expected full SHA" + type: string + required: false push: tags: ["v*"] @@ -64,6 +68,18 @@ jobs: steps: - uses: actions/checkout@v7 + - name: Validate requested source + id: source + env: + EXPECTED_COMMIT: ${{ inputs.expected_commit }} + run: | + if [ -n "$EXPECTED_COMMIT" ]; then + if [[ ! "$EXPECTED_COMMIT" =~ ^[0-9a-f]{40}$ ]] || [ "$GITHUB_SHA" != "$EXPECTED_COMMIT" ]; then + echo "::error::The ref no longer matches the requested source commit." + exit 1 + fi + fi + - uses: actions/setup-java@v6 with: distribution: temurin diff --git a/CLAUDE.md b/CLAUDE.md index 5d0fa6c9..4cfa29fe 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -55,6 +55,8 @@ compiled from `requirements-host.in` against `requirements.txt` by the command i header, for every platform, so the two cannot disagree (`test_host_image.py`); the root `Dockerfile` and CI's «Host» job install both, and Vercel neither sees nor imports it. +- Serialize pyvoy receive delivery and keep ASGI Future completions valid across cancellation; observe abandoned sends and stop only idle WatchClass on disconnect (`test_host.py`, #728). + ## Commands Python 3.11+ (`.python-version` says 3.12, CI runs 3.12), JDK 21, Android SDK with @@ -68,7 +70,7 @@ Server, from `server/`: `conftest.py` refuses to start when it would (#312) - **`ruff check app tests scripts migrations`** — exactly what CI lints; `ruff check .` from `server/` covers the same tree -- **`pytest -q -n auto`** — 3857 tests, six of them skipped unless a +- **`pytest -q -n auto`** — 3877 tests, six of them skipped unless a host is running (`-m host`, CI's «Host» job), plus eleven PostgreSQL-only lock checks skipped on SQLite, and **the exact command CI runs**. Not `python -m pytest`, which is what this line used to say: the `-m` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 590c14bf..7e658b35 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -44,7 +44,7 @@ cp .env.example .env # BOT_TOKEN and OWNER_IDS are your own | --- | --- | | `ruff check app tests scripts migrations` | lints the server — exactly what CI runs | | `python -m mypy` | one question of all 242 modules: does anything reach for an attribute its type does not have? | -| `pytest -q -n auto` | the server tests, 3857 of them — the exact command CI runs. Not `python -m pytest`: the `-m` form puts the current directory on `sys.path`, so a test that imports another passes locally and fails on CI | +| `pytest -q -n auto` | the server tests, 3877 of them — the exact command CI runs. Not `python -m pytest`: the `-m` form puts the current directory on `sys.path`, so a test that imports another passes locally and fails on CI | | `python -m pytest -q tests/test_schedule.py -k parity` | one file, one test | | `python scripts/check_test_counts.py server --junit work/pytest.xml` | compare the completed full server report with `docs/counts.json` | | `python -m uvicorn app.main:app --reload` | run the server | diff --git a/HANDOVER.md b/HANDOVER.md index a49f09e9..4442d5d1 100644 --- a/HANDOVER.md +++ b/HANDOVER.md @@ -6,27 +6,20 @@ place without reopening or redoing anything. What every batch before the last two added is in [docs/history.md](docs/history.md), newest first. -Last updated: **11 November 2026**. The last verified release is55b4c799, -PR#722/#377/#723, pinned to checked head7cf8fc31. PR CI42863457188 and main -CI42864594364 passed; production READY on the exact merge, all three aliases -resolved to it and returned warmup200/status ok/API1/schema0019/v2 true. The -post-warmup/mainCI error/fatal30m query had no matching groups. Issues377/723closed. -All owned checkouts and main/dev refs were fast-forwarded, unrelated work retained. - -Current batch: work/master-dev-flow-724 in the isolated task-parent checkout, -milestone13, based on that merge. The owner now requests master/dev/one working -branch, Actions on dev, analysis/preservation of Claude Code branch features and -Android Studio Emulator verification. Task1 recovers missing diary behavior#725 -and prepares tested promotion; Task2 resolves eight dependency PRs and final ref -cleanup. Complete corrected SQLite3857/Android1823 and Ruff/mypy242 are green locally. -One independent review and its single major-fix pass are complete. PR726 is a -draft into dev; CI42904034514 passed on checked head7a049119. Emulator installation, -startup and the first two local onboarding screens were observed on API37; -onboarding completion and guide navigation remain unverified. Dev requires PR/CI, -and automatic merged-working-branch cleanup is enabled with persistent protection -read back. Rename, dev/master CI and production remain delivery gates. -Both owned PostgreSQL clusters remain stopped with -data retained. UI inputs require the shared queue's explicit grant. +Last updated: **11 November 2026**. This committed #724 snapshot +records the integrated dependency cohort, the recovered host-cancellation fix#728 +and its measured verification below. Current facts are 3877server/ +1823Android cases; no migration or installed-v1 contract changes are included. +The previous production anchor is Task1's master4dbfe33f (PR726/727), whose CI, +four-alias production and signed APK44/Studio startup proof are recorded below. + +This source batch was built on work/dependencies-724 from dev5d55a542 and existing +dependency milestone7. Its linked working/promotion PRs and [#724](https://github.com/lumenpearson/lessons/issues/724) +carry the final merge identities, exact-head/dev/master CI, production and safe +ref-retirement readbacks after those actions occur. The issue stays open until +all of them, including actual Studio Emulator verification, are complete. +All worktree files and private WIP must survive consolidation. UI input requires +the shared queue's explicit grant; elapsed time never grants access. **Historical opening, recorded on 18 October.** The dated context below is preserved for the programme's decisions; the current commit, verification and @@ -339,12 +332,112 @@ broke or would have broken a running deployment). **The board is the owner's pro local one fills it with `gh`, by the rule in the project's README, as «The board» in the `github-pr` skill says. -## What the last session added: preserve branch work and test integration on dev +## What the last session added: integrate the dependency cohort and retain branch work + +- #724, dependency milestone7: eight original Dependabot heads are folded into + one working branch from dev, retaining their commits as merge parents: + Gradle9.9.0 (#713), pyvoy1.4.0 (#712), AGP9.5.1 (#711), OkHttp5.5.1 (#668), + DataStore1.3.0 (#667), pydantic-settings2.16.2 (#666), FastAPI0.162.0 (#665) + and Sentry2.72.0 (#664). No version or tag is invented for this batch. +- The requirement mirrors move together. Regenerated Linux/runtime and universal + host locks agree on pyqwest0.14.0; Windows selects winloop and excludes uvloop, + while Linux selects uvloop. The original host proposal failed that Windows + control and shared-pin/mirror checks: RED3failed/14passed/1skipped, then18passed. + The installed host uses Envoy1.40.2 and winloop0.8.3; versions come from the + resolved locks, not a separately floating install. +- Real Windows host checks exposed #728 before release. Both pyvoy1.3 and1.4 + can complete a receive Future after its consumer was cancelled, logging + InvalidStateError. Both winloop versions reproduced it; one initially clean + old-loop run did not establish a version-specific fix. A shield alone still + left idle asynchronous generators running at shutdown and is not clean proof. +- Pyvoy's own entry now retains a pending receive across consumer cancellation + and retry. A disconnect observed by its separate monitor cancels the idle + request so WatchClass closes promptly. The generic host/Vercel/fallback path + and lifespan remain unchanged. Genuine behavior RED3failed/1control to the + initial focused40passed holds Future completion/retry, stream closure, body + order and exception identity; vendor files and logger configuration stay intact. +- A further boundary regression first failed2cases with2stream controls: unary + REST/RPC work must retain its own disconnect handling. Request cancellation is + now limited to POST WatchClass at its native and mounted paths. Final focused + host/lock/mirror checks43passed; no unrelated request is cancelled by the adapter. +- Pending sends need the same protection: pyvoy also completes their Future after + request cancellation. Three failing callback cases became green while preserving + normal message/error identity: delivered/reset completions are observed, and an + unexpected failure still reaches the loop exception handler. Final focused + host/lock/mirror checks47passed; expected client resets are not server faults. +- Actual final Windows network checks: pyvoy6passed and hypercorn6passed on + the finished receive/send adapter. Each host + exits0, releases its port and logs no ERROR/traceback/running-generator error. + Tests use isolated SQLite fixtures, fake local settings and a disabled bot. +- Complete SQLite: 3860passed/17skipped/15warnings in + 2107.94s; 3877unique JUnit cases, zero failures/errors. Bare + pytest-q-nauto uses eight workers, owned Python3.12 and actual Git Bash. + 1486 tracked input hashes remain unchanged throughout the full run. + Ruff and mypy242 are clean. Serial native test/assembleDebug/assembleRelease/ + detekt: initial dependency build6m36s/300executed44cache, then the + corrected final repeat BUILD SUCCESSFUL in 1m 7s; 1823logical JVM cases across five modules, + zero failures/errors/skips. Current measured facts and report comparisons + follow those completed runs; final document checks are recorded with the PR. +- Dependabot version updates use one weekly multi-ecosystem cohort targeting + dev/M7 with the work prefix, preserving Android ignore rules and area labels. + Production still requires its own reviewed promotion. Security updates retain + GitHub's separate default-branch queue; the version grouping is not a promise + to disable or cap security work. +- Pre-review documentation/CI checks197passed71.65s and both completed-report count + comparisons passed. The source-pinned debug APK from commit9cb93f13 installed + on the retained API37 AVD launched by Android Studio Device Manager. Actual + Welcome/Home/Launcher/reopen Welcome were observed; the foreground package + was the debug application and PID3237 remained the same, with zero crash entries. + No Continue/Terms/account control was pressed. The own Emulator closed normally; + its two process IDs disappeared, ADB was empty and AVD data remained. UI lease93 + was explicitly released. Production-signed APK verification follows promotion. +- One fresh independent review found a receive-delivery race and gaps in the + one-off retirement proposal. The single corrective pass serializes readers: + RED2failed/1control, then50focusedpassed46.11s. Existing CI workflow tests hold + an optional expected_commit guard before signing inputs: RED4, then17passed14.02s. + Both actual Windows hosts again pass6RPCtests each and exit cleanly. The final + full server/native results above refer to this corrected snapshot. +- Private retirement guards now bind the exact Task2 review/base/corrective head, + latest working/promotion PR CI, all eight original live PR dispositions and + actual retained signed-APK install/Studio observations. A coordinated window + reserves indexes, ownership and HEADs; prepared Git transactions fence new + reflog work before deleting refs. Ordinary nonsecret untracked WIP is hashed; + sensitive/ignored categories remain untouched, outside byte-identity claims. + Remote master/dev updates are temporarily blocked by one owned no-bypass rule; + only that rule is removed afterward, retaining original protections. The live + reversible preflight verified both applied rules and unchanged branch pins. +- Two transport minors remain deferred in full: terminal exceptional receive + completion ownership/replay, and broad abandoned-send OSError classification. + Current native receive callbacks normally deliver events and the known dropped + send uses ClientDisconnectedError; no broader failure coverage is claimed. + The pre-review debug Studio proof uses9cb93f13; this correction leaves Android + source unchanged. Production-signed APK/Studio verification remains a release gate. +- Ref retirement remains gated by the actual release and independent review. + Preserve all refs and reflog-only history in a verified restorable bundle, + copy tracked local WIP, retain every worktree's files/index, and detach only + at the same preserved commit. Known expected-tip deletes must refuse drift; + master/dev cannot enter either delete payload. The one-off safety contracts + pass102cases155.11s across preservation, release and signing-operator guards, + including main/linked Git layouts, late writer/reflog/WIP drift, exact review/PR + identities, underlying Studio records and exclusive dispatch receipt claims. + No unique branch work is discarded just to reach a branch count. + +This committed snapshot describes the verified implementation. The actual +working/promotion PR identities, exact-head/dev/master CI, final production +SHA/alias/log readback, dependency PR dispositions and final local/remote branch +lists are the live delivery record on [#724](https://github.com/lumenpearson/lessons/issues/724) +and its linked PR descriptions. Do not close #724 until those gates and actual +Studio Emulator checks are complete; no standalone close-out PR replaces them. +Studio input requires the shared queue's explicit grant. Full onboarding, real +provider/account flows, physical devices, widget sizes and a fresh PostgreSQL +suite are not claimed by the local dependency gates above. + + +## What the session before it added: preserve branch work and test integration on dev - #724, milestone13: owner requests master/dev/one temporary working branch on - GitHub and locally; Claude Code work is owned work to reconcile. Task1 prepares - the workflow/feature transition; Task2 separately integrates eight dependency - heads and finishes emulator/ref cleanup. #724 is not closed by Task1 alone. + GitHub and locally; Claude Code work is owned work to reconcile. Task1 delivered + the workflow/feature transition; Task2 is the separate dependency/ref batch above. #724 is not closed by Task1 alone. - Read-only inventory found65 contained refs, eight dependency heads, three absent pending designs and four unique historical bot commits. A complete verified Git bundle and exact local-WIP copy precede ref cleanup. No worktree files are @@ -383,20 +476,31 @@ local one fills it with `gh`, by the rule in the project's README, as «The boar 15 warnings in 1985.24 seconds; 3857 unique cases, zero failures/errors. Corrected native four gates: BUILD SUCCESSFUL in 2m 53s; 1823 logical cases. Eighteen source/test/workflow hashes - match. Current counts come from those reports; final docs/UI/delivery follow. + match. These are the completed Task1 reports; current Task2 facts are above. No second independent review or fresh PostgreSQL/live-provider claim is made. - Deferred review minors: source-set/dated branch prose, and the cross-repository 304 regression/stale config comment. Repository signing keys remain untouched; the ordinary committed workflow's input guard is not absolute protection from a collaborator rewriting a workflow. Secure environment provisioning and removal of unrestricted stored copies require a separate safe credential operation. -- Facts/current declarations 3857/1823 follow successful complete reports; - both report comparisons passed. Final counts/gates/instruction/CI/import checks: - corrected197 passed in 163.70s. Emulator evidence precedes - delivery. Working-to-dev and dev-to-master have separate pinned CI gates; - actual rename/settings/production proof belongs in the PR descriptions. - Task1's default-target promotion carries `Closes #725` and `Refs #724`; read - issue state back after merge, keeping #724 open until Task2 is complete. +- Task1 measured declarations3857/1823 and both report comparisons passed; + corrected final documentation checks197passed163.70s and current2passed11.91s. +- Delivered11November: working PR726 pinned27cca6e9 passed CI42967237838 and + merged to dev5d55a542; dev-push CI42968049528 passed. GitHub renamed the default + branch to master and Vercel Production tracking persisted master. Promotion727 + passed CI42969998768 and merged to master4dbfe33f; masterCI42970855052 passed. + Both persistent branches remain protected, working cleanup is enabled and + issue725 read back closed/completed. Task1 alone leaves724 open for Task2. +- Production4dbfe33f was READY; all four retained/new aliases matched and warmups + returned200/ok/API1/schema0019/v2true. Deployment-scoped error/fatal groups were + empty after CI and native checks, a point-in-time observation rather than soak. +- Signed APK workflow42972263205 passed on that exact master. The retained + production package0.1.0/code44 has a verified non-debug signature and embedded + source match. On the Studio-launched API37 AVD, install/Welcome/Home/reopen + completed with the release process identified and an empty crash buffer. + That release run pressed no Continue/Terms control; onboarding/provider/guide + coverage remains bounded. The own Emulator stopped normally, its data remained + and the shared UI lease was released. Final external proof is on PR726/727. SDK tools/emulator are prepared in a separate F-drive SDK because the legacy executables fail to launch and C has limited space. Existing SDKs, AVDs and @@ -415,81 +519,6 @@ No model/schema/dependency change is included in Task1. No new full PostgreSQL, real diary/Telegram or installed physical-device proof is claimed. The original backlog bugs remain queued after the owner's explicit branch-flow work. -## What the session before it added: optional notices preserve committed v1 replies - -- #377 and its review-discovered #723, existing milestone13; #377 promoted to status:now under delegated priority: - reproducible saved-write500 without real credentials, while next-labelled bugs - require external OTP, cron changes or the approved Android transport migration. -- Existing edit and decision notification seams contain ordinary bot-construction, - delivery and close failures after commit. Close is attempted once when a bot - exists; cancellation still propagates. No new factory or domain-rule copy. -- Homework, substitution, event, day and decision DTOs are prepared before notice - I/O. A failed subscriber lookup can expire ORM state without breaking the reply; - the logged class identifier is captured before optional work. -- Focused RED:10failed/16controls/26cases24.73s; GREEN26passed21.52s. - Real ASGI controls hold one saved row/audit, recipients, delivery and close counts, - four expired-session edit replies, six cancellation cases and an uncommitted - failing write that still propagates and rolls back before any bot is constructed. -- Initially reviewed snapshot c720fa2e, complete SQLite: 3828 passed, 17 skipped, 15 warnings in 2243.43 seconds; 3845 unique JUnit cases, zero failures/errors. Local bare pytest -q -n8, - owned JUnit report and verified Git Bash; Ruffclean/mypy242clean. Four frozen - production/test hashes match the tested snapshot. -- Native test/assembleDebug/assembleRelease/detekt: BUILD SUCCESSFUL in 37s. - Complete Android reports1817logicalcases/fivemodules, no failures/errors/skips. - JDK21/isolatedSDK/offline/twoworkers/2GiBheap; APKs built, not installed. -- Facts/current declarations 3845/1817 follow those complete reports. Final - document/schema/count/reference/path/gate checks:215passed/twowarnings127.79s; - both completed-report comparisons pass. Independent review follows before - publication; exact-head CI, pinned merge, main CI and production proof - are delivery gates, recorded in this PR description after completion. - -### Independent review and logging correction - -Fresh independent Astra review of c720fa2e found no Critical, one Important and -two Minor findings. The installed HTTP/Telegram exception chain can contain a -credential-bearing URL. Issue #723/M13 was filed before the production correction; -PR#722 carries closure for both #377 and #723. No actual production leak is asserted. - -- One TDD pass extends the existing lifecycle/expiry cases with synthetic-marker - assertions over formatted warnings, including exception chains. RED7failed/ - 19controls17.68s; GREEN26passed17.33s. No new logical cases were added. -- Three v1-executed warning paths now log exception types and existing context, - without exception values, traceback or stack data. The shared subscriber logger - also improves its other callers; direct unrelated v2/cron logging is not audited. -- Corrected full SQLite: 3828 passed, 17 skipped, 15 warnings in 2259.20 seconds; 3845 unique JUnit cases, zero failures/errors. All five frozen - production/test hashes match; local bare pytest -q -n8/Git Bash/own environment. -- Corrected serial native all four gates: BUILD SUCCESSFUL in 9s;1817logicalcases/ - fivemodules/268XMLreports, zero failures/errors/skips. Both APKs built, not installed. -- Current facts3845/1817 follow these corrected reports; both comparisons pass. - Ruff/mypy242 are clean. Final corrected document/schema/count/reference/path/ - gate checks:215passed/twowarnings139.92s. - -No second independent review is claimed. Two Minor findings are deferred: the -decision lifecycle matrix omits the who assertion (the implementation returns the -correct value), and the UI-pause sentence below is broader than the actual pause. -The opening/ledger and continued work refer to UI access only. Bounded waits, -delivery guarantees and independent database-read/commit-acknowledgement failures -retain their separate semantics. Exact-head CI/review, pinned merge, main CI and -production proof remain delivery gates, recorded in PR#722 after completion. - -No schema, model, dependency, protobuf or Android production changes. V1 response -fields/statuses remain compatible with installed APKs. #371's Telegram network -deadline is separate: no bounded-wait claim. No new full PostgreSQL run, real -Telegram send, real-diary or installed-device flow is claimed. Both owned PG -clusters remain stopped with data retained; foreign work and local evidence stay. -No UI APIs were used; the queue's version26 grants another session exclusive UI, -and this session remains paused until a coordinated grant. Project6Done board -visibility and the earlier generated-report ignore Minor remain outside this batch. - -Released as PR#722, pinned to checked head7cf8fc31, merge55b4c799. -PR CI42863457188 and main CI42864594364 passed: Server3828passed/17skipped, -Android1817 and both Host jobs; Contract path-filtered skipped. Automatic Codex -review on the exact head completed without findings; formal reviews/threads were -empty. Production was READY on that merge; all three aliases independently -resolved to it and returned warmup200/status ok/API1/schema0019/v2 true. A -deployment-scoped error/fatal30m query after warmups/mainCI had no matching groups. -#377 and #723 read back closed/completed; four owned checkouts and main/dev refs -fast-forwarded. No second review or new full PostgreSQL run was claimed. - ## The milestones **The milestones as they are now.** The owner renamed all nine on 25 September 2026, so that @@ -2131,7 +2160,7 @@ The gates, both halves (`CLAUDE.md` requires running both if you touched both): ```bash cd server && ruff check app tests scripts migrations # clean -cd server && pytest -q -n auto # 3857 tests, ~38 min on Windows +cd server && pytest -q -n auto # 3877 tests, ~38 min on Windows cd server && python -m mypy # clean, 242 modules cd android && ./gradlew test # 1823 tests across the five modules cd android && ./gradlew detekt # nothing beyond the five baselines diff --git a/README.md b/README.md index 00c815fb..175c3545 100644 --- a/README.md +++ b/README.md @@ -221,7 +221,7 @@ Read this before planning a release. | --- | --- | | `ruff check app tests scripts migrations` | clean | | `python -m mypy` | clean, 242 modules — asks whether anything reaches for an attribute that does not exist | -| `pytest -q -n auto` | 3857 tests, green — the command CI runs, on SQLite; on PostgreSQL by hand only (below) | +| `pytest -q -n auto` | 3877 tests, green — the command CI runs, on SQLite; on PostgreSQL by hand only (below) | | buf lint, buf breaking, the generated-code check | CI's «Contract (Buf)» job, only when the contract changes. Its first run was this sub-project's pull request, where breaking was skipped because main had no contract yet | | v2 over REST and Connect | seventy-five methods served beside v1, every unary one: `GetScheduleWindow`, `GetMe`, `GetDiaryCapabilities` and `CreateDevice` (3a), the journal, the class's phones and the subjects (3b-1), the bells, the timetable and the class with its terms (3b-2), the access requests, whose Telegram notice goes out after the commit, and the school directory (3b-3), a phone's own: its link, the calendar feed, its tasks and its homework ticks (3b-4), the homework and the events, whose notices to the class go out after the commit (3b-5), the days and the substitutions, told to the class the same way (3b-6), a diary session and the reads of one pupil, with what each diary has declared from the registry's table (3b-7), and the family's corrections over the diary, a batch at a time, all or none (3b-8), each tested both ways in-process and against v1's own answer where v1 has one; no APK calls them yet | | The host target and `WatchClass` | `python -m app.host`, under pyvoy and under hypercorn, started on SQLite by CI's «Host» job and asked over native gRPC: a unary call, a method the contract lacks, `WatchClass` hearing an ORM write, a bulk write and a bell change, a revoked phone cut off, and a forged `X-Forwarded-For` throttled all the same; the bus and the stream are tested in-process too. The image was built and run by hand once (at `261450e`, with a throwaway PostgreSQL 18: the same six live tests passed under both servers, and grpcurl was answered over native gRPC), and nothing builds it routinely; the host is deployed nowhere, and no phone streams yet | diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index 2e7cd8aa..21840d17 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -38,7 +38,7 @@ # okhttp 5.2.0, kotlinx-serialization-json 1.9.1) that do not exist in any # repository. Verify a version against its repository before adding it here. [versions] -agp = "9.4.1" +agp = "9.5.1" kotlin = "2.4.21" ksp = "2.3.12" @@ -54,11 +54,11 @@ graphicsShapes = "1.1.0" glance = "1.3.0-alpha02" room = "2.8.5" -datastore = "1.2.0" +datastore = "1.3.0" work = "2.12.0" retrofit = "3.0.0" -okhttp = "5.5.0" +okhttp = "5.5.1" serialization = "1.9.0" coroutines = "1.11.0" diff --git a/android/gradle/wrapper/gradle-wrapper.jar b/android/gradle/wrapper/gradle-wrapper.jar index 9fa7f288..51cbd2a6 100644 Binary files a/android/gradle/wrapper/gradle-wrapper.jar and b/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 1a31fd1b..325da1a4 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -1,6 +1,6 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-9.8.1-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-9.9.0-bin.zip networkTimeout=10000 validateDistributionUrl=true zipStoreBase=GRADLE_USER_HOME diff --git a/docs/architecture.md b/docs/architecture.md index 620c49e9..e294788d 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1010,7 +1010,7 @@ with the host. ## Testing -3857 tests on the server, 1823 on Android; `pytest -q -n auto` and `./gradlew test`, both +3877 tests on the server, 1823 on Android; `pytest -q -n auto` and `./gradlew test`, both offline, both in CI. On Android that is `:core:model` 145, `:core:data` 644, `:core:designsystem` 205, `:widget` 126, `:app` 703 (#325). diff --git a/docs/branch-work-inventory.md b/docs/branch-work-inventory.md index eaa0bc98..6b1c999f 100644 --- a/docs/branch-work-inventory.md +++ b/docs/branch-work-inventory.md @@ -106,11 +106,32 @@ recoverable even where newer shared rules supersede their implementation. ## Dependency heads, a separate integration batch -Eight open PRs were found: Gradle wrapper713, pyvoy712, AGP711, network668, -DataStore667, pydantic-settings666, FastAPI665 and Sentry664. Their source heads -remain intact until the declared versions are installed and complete gates pass. -The workflow transition does not claim they have been integrated. A dependency -update that cannot build is not silently discarded to satisfy a branch count. +The eight original PR heads are folded into the dependency batch as merge +parents: wrapper713, pyvoy712, AGP711, network668, DataStore667, +pydantic-settings666, FastAPI665 and Sentry664. Requirement mirrors and the +Linux/universal locks are reconciled before release; Windows/Linux loop markers +are held by the existing host-image tests. Real host checks also exposed728, +whose pyvoy receive/send completion and WatchClass disconnect correction is +covered before shipping the bumps. + +Their final GitHub dispositions and exact production/ref-retirement readback are +recorded on #724 and the linked integration/promotion PRs. Retire a ref only when +its exact current tip is in verified production and in a restorable all-ref and +reflog bundle. An advanced or unknown tip requires analysis; a branch count is +never a reason to discard it. Keep local WIP/index/files, detaching an old +worktree only at its same retained commit. Expected-tip deletes exclude master/dev. A coordinated window reserves local +indexes, ownership and HEADs; prepared transactions refuse unbundled reflog work +before deleting refs. One temporary owned update rule freezes both remote keeper +branches without bypass while atomic expected-tip deletes retire the other refs; +only that temporary rule is removed, with original protections read back intact. +Hash eligible regular tracked/untracked WIP. Sensitive files and ignored private, +environment and build categories stay in place without a byte-identity claim. + +Future version bumps use one weekly multi-ecosystem cohort targeting dev/M7 with +the work prefix. GitHub security updates retain their separate default-branch +queue; they are not disabled to enforce a permanent global branch-count cap. +Idle development has two persistent refs; an actual temporary working branch is +the third and is deleted after its checked merge into dev. ## Final branch contract diff --git a/docs/counts.json b/docs/counts.json index d024d0e1..29a96d2a 100644 --- a/docs/counts.json +++ b/docs/counts.json @@ -9,5 +9,5 @@ }, "total": 1823 }, - "server": 3857 + "server": 3877 } diff --git a/docs/deploy.md b/docs/deploy.md index ac50d316..5eea8724 100644 --- a/docs/deploy.md +++ b/docs/deploy.md @@ -89,6 +89,42 @@ limit with an alert set on it**, so that a busy month raises a warning rather th Or it wants the VPS of option 2, which has no allowance to run out of. Hobby is enough to try the project out by yourself. +### Releasing through dev and master + +One temporary working branch targets `dev`. Merge only its checked head after +the complete applicable CI jobs and review pass, then wait for the resulting +dev-push CI. Promote `dev` to `master` in a separate pull request and verify that +promotion's head again. Keep both persistent branches; automatic cleanup applies +to the merged working branch. Do not reset dev to a production merge commit. + +Vercel's Production environment must match `master`, with production aliases +assigned automatically. A successful build is only part of the release: after +master-push CI, read the production deployment's actual source SHA and target, +and verify every API hostname installed APKs can retain. Each alias must point to +that deployment and answer the warmup with the expected API/schema capabilities. + +**A retained branch alias does not follow a branch rename.** The old `git-main` +alias stayed on its previous deployment during #724's cutover. Reassign that +compatibility alias to each newly verified master deployment, then read it back; +checking the canonical hostname and new `git-master` alias alone misses old phones. +Keep protected aliases protected. Their unauthenticated login redirect is not an +application failure: use an authorized verification connection and never publish +its temporary access URL, headers or credentials. Finish with deployment-scoped +error/fatal logs after the warmups and CI; an empty query is a point-in-time check. + +Release automation passes the full expected source SHA in the existing APK +workflow's optional `expected_commit` input. The workflow compares it with the +actual GITHUB_SHA before supplying signing inputs; a ref that advanced refuses +before signing. Blank input retains ordinary manual-run behavior. The operator +claims its uncertain dispatch receipt exclusively and reads back the exact run, +so concurrent invocations or a timed-out response cannot submit twice blindly. + +The exact merge, CI runs and production readback belong in the release PR's +description and its tracking issue. The committed handover records the tested +features and links to that delivery record; it cannot know its own future merge +SHA. A release is not complete until those external outcomes are read back. + + ### Secrets **Never send a token in a conversation, a commit or an issue.** The token gives full control diff --git a/docs/history.md b/docs/history.md index dd02d74e..8efbab19 100644 --- a/docs/history.md +++ b/docs/history.md @@ -28,6 +28,82 @@ the conventions of the file it was written in: --- +## What the batch before added: optional notices preserve committed v1 replies + +- #377 and its review-discovered #723, existing milestone13; #377 promoted to status:now under delegated priority: + reproducible saved-write500 without real credentials, while next-labelled bugs + require external OTP, cron changes or the approved Android transport migration. +- Existing edit and decision notification seams contain ordinary bot-construction, + delivery and close failures after commit. Close is attempted once when a bot + exists; cancellation still propagates. No new factory or domain-rule copy. +- Homework, substitution, event, day and decision DTOs are prepared before notice + I/O. A failed subscriber lookup can expire ORM state without breaking the reply; + the logged class identifier is captured before optional work. +- Focused RED:10failed/16controls/26cases24.73s; GREEN26passed21.52s. + Real ASGI controls hold one saved row/audit, recipients, delivery and close counts, + four expired-session edit replies, six cancellation cases and an uncommitted + failing write that still propagates and rolls back before any bot is constructed. +- Initially reviewed snapshot c720fa2e, complete SQLite: 3828 passed, 17 skipped, 15 warnings in 2243.43 seconds; 3845 unique JUnit cases, zero failures/errors. Local bare pytest -q -n8, + owned JUnit report and verified Git Bash; Ruffclean/mypy242clean. Four frozen + production/test hashes match the tested snapshot. +- Native test/assembleDebug/assembleRelease/detekt: BUILD SUCCESSFUL in 37s. + Complete Android reports1817logicalcases/fivemodules, no failures/errors/skips. + JDK21/isolatedSDK/offline/twoworkers/2GiBheap; APKs built, not installed. +- Facts/current declarations 3845/1817 follow those complete reports. Final + document/schema/count/reference/path/gate checks:215passed/twowarnings127.79s; + both completed-report comparisons pass. Independent review follows before + publication; exact-head CI, pinned merge, main CI and production proof + are delivery gates, recorded in this PR description after completion. + +### Independent review and logging correction + +Fresh independent Astra review of c720fa2e found no Critical, one Important and +two Minor findings. The installed HTTP/Telegram exception chain can contain a +credential-bearing URL. Issue #723/M13 was filed before the production correction; +PR#722 carries closure for both #377 and #723. No actual production leak is asserted. + +- One TDD pass extends the existing lifecycle/expiry cases with synthetic-marker + assertions over formatted warnings, including exception chains. RED7failed/ + 19controls17.68s; GREEN26passed17.33s. No new logical cases were added. +- Three v1-executed warning paths now log exception types and existing context, + without exception values, traceback or stack data. The shared subscriber logger + also improves its other callers; direct unrelated v2/cron logging is not audited. +- Corrected full SQLite: 3828 passed, 17 skipped, 15 warnings in 2259.20 seconds; 3845 unique JUnit cases, zero failures/errors. All five frozen + production/test hashes match; local bare pytest -q -n8/Git Bash/own environment. +- Corrected serial native all four gates: BUILD SUCCESSFUL in 9s;1817logicalcases/ + fivemodules/268XMLreports, zero failures/errors/skips. Both APKs built, not installed. +- Current facts3845/1817 follow these corrected reports; both comparisons pass. + Ruff/mypy242 are clean. Final corrected document/schema/count/reference/path/ + gate checks:215passed/twowarnings139.92s. + +No second independent review is claimed. Two Minor findings are deferred: the +decision lifecycle matrix omits the who assertion (the implementation returns the +correct value), and the UI-pause sentence below is broader than the actual pause. +The opening/ledger and continued work refer to UI access only. Bounded waits, +delivery guarantees and independent database-read/commit-acknowledgement failures +retain their separate semantics. Exact-head CI/review, pinned merge, main CI and +production proof remain delivery gates, recorded in PR#722 after completion. + +No schema, model, dependency, protobuf or Android production changes. V1 response +fields/statuses remain compatible with installed APKs. #371's Telegram network +deadline is separate: no bounded-wait claim. No new full PostgreSQL run, real +Telegram send, real-diary or installed-device flow is claimed. Both owned PG +clusters remain stopped with data retained; foreign work and local evidence stay. +No UI APIs were used; the queue's version26 grants another session exclusive UI, +and this session remains paused until a coordinated grant. Project6Done board +visibility and the earlier generated-report ignore Minor remain outside this batch. + +Released as PR#722, pinned to checked head7cf8fc31, merge55b4c799. +PR CI42863457188 and main CI42864594364 passed: Server3828passed/17skipped, +Android1817 and both Host jobs; Contract path-filtered skipped. Automatic Codex +review on the exact head completed without findings; formal reviews/threads were +empty. Production was READY on that merge; all three aliases independently +resolved to it and returned warmup200/status ok/API1/schema0019/v2 true. A +deployment-scoped error/fatal30m query after warmups/mainCI had no matching groups. +#377 and #723 read back closed/completed; four owned checkouts and main/dev refs +fast-forwarded. No second review or new full PostgreSQL run was claimed. + + ## What the batch before added: detekt baseline rewrites stay within reviewed budgets - #635, existing milestone13: the existing pure JVM core:model suite checks every diff --git a/docs/specs/2026-11-10-master-dev-flow-plan.md b/docs/specs/2026-11-10-master-dev-flow-plan.md index 7c8d8aad..86cb8e00 100644 --- a/docs/specs/2026-11-10-master-dev-flow-plan.md +++ b/docs/specs/2026-11-10-master-dev-flow-plan.md @@ -55,10 +55,10 @@ their server API remains compatible and their guide retains its bundled fallback pushes and master-only signing; observe RED, then minimal implementation/GREEN. - [x] Run affected suites, Ruff/mypy; freeze source/test inputs. Complete server, native4gates, report writer/count comparisons and final document checks. -- [ ] Update in-batch HANDOVER including prior722 release; commit owned files, +- [x] Update in-batch HANDOVER including prior722 release; commit owned files, task-done and fresh whole-branch independent review; one major-fix pass if needed. -- [ ] Draft/ready PR into dev, milestone13, exact-head CI/review, pinned merge. -- [ ] Verify dev CI; coordinated GitHub rename/rules/Vercel branch cutover, pinned +- [x] Draft/ready PR into dev, milestone13, exact-head CI/review, pinned merge. +- [x] Verify dev CI; coordinated GitHub rename/rules/Vercel branch cutover, pinned dev-to-master promotion, master CI and production SHA/aliases/warmups/log counts. ### Task 2: Integrate dependency heads and retire redundant refs @@ -69,11 +69,11 @@ dependency configuration, current documentation and counts. **Interfaces:** Consumes verified master/dev fromTask1. Original dependency commits remain traceable. Resolving build incompatibilities cannot weaken tests/budgets. -- [ ] Read current PR heads/diffs; fold original commits with conflict resolution +- [x] Read current PR heads/diffs; fold original commits with conflict resolution that preserves previous dependency updates. Install only declared versions. -- [ ] Run affected checks while integrating, then complete server/native gates, +- [x] Run affected checks while integrating, then complete server/native gates, measured facts and final docs on the finished snapshot. -- [ ] Obtain coordinated UI grant for pinned APK; Android Studio Emulator smoke +- [x] Obtain coordinated UI grant for pinned APK; Android Studio Emulator smoke tests record actual app startup/navigation and tested limitations; release UI. - [ ] Independent review, green exact-head CI, dev merge/CI and master promotion/ CI/production verification; read back dependency PR dispositions. diff --git a/requirements.in b/requirements.in index 6a286cec..4b6b9f40 100644 --- a/requirements.in +++ b/requirements.in @@ -30,12 +30,12 @@ # # asyncpg only: the serverless database is Postgres, and aiosqlite would be # dead weight in the function bundle. -fastapi>=0.143.0 +fastapi>=0.162.0 aiogram>=3.31.0 sqlalchemy[asyncio]>=2.1.4 asyncpg>=0.32.0 pydantic>=2.13.5 -pydantic-settings>=2.15.0 +pydantic-settings>=2.16.2 # The DI container in server/app/di.py. Pure Python, and 26 ms on top of # fastapi and sqlalchemy on a cold start — measured, because this bundle pays # for every import on every one of them. @@ -54,4 +54,4 @@ connectrpc>=0.12.1 protobuf-py>=0.6.0 # Errors and a sample of timings, to Sentry; imported only where SENTRY_DSN # is set, so a deployment without it pays nothing on its cold start. -sentry-sdk>=2.71.0 +sentry-sdk>=2.72.0 diff --git a/requirements.txt b/requirements.txt index 9835c0ab..c8b5cf4e 100644 --- a/requirements.txt +++ b/requirements.txt @@ -36,7 +36,7 @@ cryptography==50.0.2 # via -r requirements.in dishka==1.10.1 # via -r requirements.in -fastapi==0.143.0 +fastapi==0.162.0 # via -r requirements.in frozenlist==1.8.0 # via @@ -85,13 +85,13 @@ pydantic==2.13.5 # pydantic-settings pydantic-core==2.46.5 # via pydantic -pydantic-settings==2.15.0 +pydantic-settings==2.16.2 # via -r requirements.in -pyqwest==0.11.0 +pyqwest==0.14.0 # via connectrpc python-dotenv==1.2.3 # via pydantic-settings -sentry-sdk==2.71.0 +sentry-sdk==2.72.0 # via -r requirements.in sqlalchemy==2.1.4 # via -r requirements.in @@ -108,6 +108,7 @@ typing-extensions==4.16.0 # protobuf-py # pydantic # pydantic-core + # pydantic-settings # sqlalchemy # starlette # typing-inspection diff --git a/server/app/host.py b/server/app/host.py index 26b052cc..a6eaebe5 100644 --- a/server/app/host.py +++ b/server/app/host.py @@ -51,7 +51,7 @@ GRPC_ROOT = "/lessons.v2." #: The app pyvoy loads into Envoy, by name. -ENTRY = "app.host:application" +ENTRY = "app.host:pyvoy_application" #: The servers this module can run, the first by default. SERVERS = ("pyvoy", "hypercorn") @@ -114,6 +114,68 @@ async def application(scope: Scope, receive: Receive, send: Send) -> None: await main(scope, receive, send) +def _observe_cancelled_send(completed: asyncio.Future[None]) -> None: + """A closed client is expected; an unrelated send failure must still be reported.""" + if completed.cancelled(): + return + failure = completed.exception() + if failure is not None and not isinstance(failure, OSError): + completed.get_loop().call_exception_handler( + { + "message": "pyvoy send failed after its caller was cancelled", + "exception": failure, + "future": completed, + } + ) + + +async def pyvoy_application(scope: Scope, receive: Receive, send: Send) -> None: + """Keep pyvoy's ASGI completions valid when a request or monitor is cancelled.""" + if scope["type"] != "http": + await application(scope, receive, send) + return + pending: asyncio.Future[MutableMapping[str, Any]] | None = None + receive_lock = asyncio.Lock() + request_task = asyncio.current_task() + watch_path = "/lessons.v2.WatchService/WatchClass" + cancel_on_disconnect = scope.get("method") == "POST" and scope.get("path") in ( + watch_path, "/api/rpc" + watch_path + ) + + async def protected_receive() -> MutableMapping[str, Any]: + nonlocal pending + # Deliver each event once, retaining the native read if its waiter leaves. + # Pyvoy 1.3/1.4 still complete a cancelled consumer's Future (#728). + async with receive_lock: + if pending is None: + pending = asyncio.ensure_future(receive()) + message = await asyncio.shield(pending) + pending = None + if ( + cancel_on_disconnect + and message["type"] == "http.disconnect" + and request_task is not None + and asyncio.current_task() is not request_task + ): + # Connect's monitor only sets a flag; an idle WatchClass would not + # inspect it until the next heartbeat, outliving pyvoy's shutdown. + # Unary work retains the application's own disconnect handling. + request_task.cancel() + return message + + async def protected_send(message: MutableMapping[str, Any]) -> None: + completion = asyncio.ensure_future(send(message)) + try: + await asyncio.shield(completion) + except asyncio.CancelledError: + # The native send callback still completes after a caller leaves, + # including a closed-client OSError that nobody can await now. + completion.add_done_callback(_observe_cancelled_send) + raise + + await application(scope, protected_receive, protected_send) + + def envoy_config(config: dict[str, Any]) -> dict[str, Any]: """pyvoy's Envoy configuration, with the client's address taken from the connection. diff --git a/server/pyproject.toml b/server/pyproject.toml index cb20593a..2bee9691 100644 --- a/server/pyproject.toml +++ b/server/pyproject.toml @@ -4,7 +4,7 @@ version = "0.1.0" description = "API + Telegram admin bot for the Lessons school diary app" requires-python = ">=3.11" dependencies = [ - "fastapi>=0.143.0", + "fastapi>=0.162.0", "uvicorn[standard]>=0.30", # 3.31 is the floor, not a preference: it is the first release to carry # Bot API 9.3's ``InlineKeyboardButton.style``, and on anything older every @@ -15,7 +15,7 @@ dependencies = [ "aiosqlite>=0.20", "asyncpg>=0.32.0", "pydantic>=2.13.5", - "pydantic-settings>=2.15.0", + "pydantic-settings>=2.16.2", # The container both shells draw a session from (app/di.py). Wanted for # aiogram as much as for FastAPI: `Depends` cannot serve a bot handler, and # this project is two shells over one implementation, so «a session for one @@ -56,7 +56,7 @@ dependencies = [ # nothing on its cold start. No extra: the FastAPI integration is in the # package, and the `fastapi` extra would only ask for FastAPI, which is # above. The floor is the release that was current when this was written. - "sentry-sdk>=2.71.0", + "sentry-sdk>=2.72.0", # Schema changes. Not in requirements.txt: migrations are run from a # workstation against the database, never from inside a request, and the # function bundle is smaller without it. diff --git a/server/requirements-host.in b/server/requirements-host.in index 37d31190..81d5d772 100644 --- a/server/requirements-host.in +++ b/server/requirements-host.in @@ -20,10 +20,10 @@ # the image's Debian has. # # pyvoy is Envoy with the app inside it: HTTP/2 with prior knowledge, -# trailers, gzip. The floor is the release app/host.py was written against: +# trailers, gzip. The integration began on 1.3.0: # the stdout and stderr defaults it overrides and the Envoy configuration it # corrects were both read from 1.3.0. The 5 October spike ran native gRPC and # a stream on 1.2.0 (docs/specs/2026-10-03-one-contract-design.md). -pyvoy>=1.3.0 +pyvoy>=1.4.0 # The fallback the same spike proved: `python -m app.host --server hypercorn`. hypercorn>=0.18.0 diff --git a/server/requirements-host.txt b/server/requirements-host.txt index 7f781533..6398a0bb 100644 --- a/server/requirements-host.txt +++ b/server/requirements-host.txt @@ -1,6 +1,6 @@ # This file was autogenerated by uv via the following command: # uv pip compile requirements-host.in -c ../requirements.txt --python-version 3.12 --universal --output-file requirements-host.txt -envoy-server==1.39.3 +envoy-server==1.40.2 # via pyvoy find-libpython==0.5.1 # via pyvoy @@ -23,11 +23,11 @@ opentelemetry-api==1.45.0 # pyqwest priority==2.0.0 # via hypercorn -pyqwest==0.11.0 +pyqwest==0.14.0 # via # -c ../requirements.txt # pyvoy -pyvoy==1.3.0 +pyvoy==1.4.0 # via -r requirements-host.in pyyaml==6.0.3 # via pyvoy @@ -37,7 +37,7 @@ typing-extensions==4.16.0 # opentelemetry-api uvloop==0.23.0 ; sys_platform != 'win32' # via pyvoy -winloop==0.7.2 ; sys_platform == 'win32' +winloop==0.8.3 ; sys_platform == 'win32' # via pyvoy wsproto==1.3.2 # via hypercorn diff --git a/server/tests/test_ci_required.py b/server/tests/test_ci_required.py index 7f9a4e2b..d1c08f3b 100644 --- a/server/tests/test_ci_required.py +++ b/server/tests/test_ci_required.py @@ -74,6 +74,31 @@ def test_production_signing_admits_only_master_and_version_tags(ref, allowed, tm assert ("SIGNING_ALLOWED" in result.stdout) is allowed +@pytest.mark.parametrize( + "expected,actual,allowed", + [("", "a" * 40, True), ("a" * 40, "a" * 40, True), + ("a" * 40, "b" * 40, False), ("not-a-commit", "a" * 40, False)], +) +def test_requested_apk_source_is_checked_before_signing(expected, actual, allowed) -> None: + apk = yaml.safe_load((ROOT / ".github/workflows/apk.yml").read_text(encoding="utf-8")) + events = apk.get("on") or apk[True] + assert events["workflow_dispatch"]["inputs"].get("expected_commit", {}).get("type") == "string" + steps = apk["jobs"]["build"]["steps"] + source = next((step for step in steps if step.get("id") == "source"), None) + assert source is not None, "A moving master ref must be checked before signing inputs" + assert source["env"]["EXPECTED_COMMIT"] == "${{ inputs.expected_commit }}" + keystore_index = next(i for i, step in enumerate(steps) if step.get("id") == "keystore") + assert steps.index(source) < keystore_index + bash = shutil.which("bash") + assert bash is not None + result = subprocess.run( + [bash, "-c", source["run"]], + env={**os.environ, "EXPECTED_COMMIT": expected, "GITHUB_SHA": actual}, + capture_output=True, text=True, check=False, + ) + assert (result.returncode == 0) is allowed, result.stdout + result.stderr + + def test_the_summary_job_needs_every_other_job_and_runs_whatever_they_ended_as() -> None: jobs = _jobs() summary = jobs["ci"] diff --git a/server/tests/test_host.py b/server/tests/test_host.py index 2196f6ba..789c1731 100644 --- a/server/tests/test_host.py +++ b/server/tests/test_host.py @@ -12,7 +12,9 @@ from __future__ import annotations import asyncio +import contextlib import copy +import importlib import os import struct import subprocess @@ -31,6 +33,336 @@ SERVER = Path(__file__).resolve().parents[1] +def _pyvoy_entry(): + module, name = host.ENTRY.split(":") + return getattr(importlib.import_module(module), name) + + +@pytest.mark.parametrize("retry", [False, True], ids=["response-ended", "receive-retried"]) +async def test_cancelled_pyvoy_receive_still_accepts_the_servers_completion(monkeypatch, retry): + """Pyvoy completes its receive Future even after the consumer is cancelled (#728).""" + pending = asyncio.get_running_loop().create_future() + called = asyncio.Event() + calls = 0 + event = {"type": "http.disconnect"} + + def receive(): + nonlocal calls + calls += 1 + called.set() + return pending + + async def app(scope, read, send): + reader = asyncio.ensure_future(read()) + await called.wait() + reader.cancel() + with pytest.raises(asyncio.CancelledError): + await reader + # This is pyvoy's callback, without timing or a native library dependency. + pending.set_result(event) + if retry: + assert await read() is event + + monkeypatch.setattr(host, "_main_app", lambda: app) + await _pyvoy_entry()({"type": "http", "path": "/stream"}, receive, None) + assert calls == 1 + + +async def test_pyvoy_concurrent_readers_consume_each_body_event_once(monkeypatch): + native = asyncio.Queue() + events = [ + {"type": "http.request", "body": b"one", "more_body": True}, + {"type": "http.request", "body": b"two", "more_body": False}, + ] + + def receive(): + future = asyncio.get_running_loop().create_future() + native.put_nowait(future) + return future + + async def app(scope, read, send): + first = asyncio.create_task(read()) + second = asyncio.create_task(read()) + try: + (await asyncio.wait_for(native.get(), 1)).set_result(events[0]) + assert await first is events[0] + await asyncio.sleep(0) + assert not second.done(), "A body event must not be broadcast to another reader" + (await asyncio.wait_for(native.get(), 1)).set_result(events[1]) + assert await second is events[1] + finally: + for task in (first, second): + task.cancel() + await asyncio.gather(first, second, return_exceptions=True) + + monkeypatch.setattr(host, "_main_app", lambda: app) + await _pyvoy_entry()({"type": "http", "path": "/body"}, receive, None) + + +async def test_pyvoy_reader_reentry_cannot_clear_another_readers_next_event(monkeypatch): + native = asyncio.Queue() + events = [{"type": "http.request", "body": str(i).encode()} for i in range(3)] + + def receive(): + future = asyncio.get_running_loop().create_future() + native.put_nowait(future) + return future + + async def app(scope, read, send): + async def twice(): + return [await read(), await read()] + + first = asyncio.create_task(twice()) + second = asyncio.create_task(read()) + try: + (await asyncio.wait_for(native.get(), 1)).set_result(events[0]) + (await asyncio.wait_for(native.get(), 1)).set_result(events[1]) + assert await second is events[1] + (await asyncio.wait_for(native.get(), 1)).set_result(events[2]) + assert await first == [events[0], events[2]] + finally: + for task in (first, second): + task.cancel() + await asyncio.gather(first, second, return_exceptions=True) + + monkeypatch.setattr(host, "_main_app", lambda: app) + await _pyvoy_entry()({"type": "http", "path": "/body"}, receive, None) + + +async def test_pyvoy_waiting_reader_keeps_the_event_when_the_first_is_cancelled(monkeypatch): + native = asyncio.Queue() + event = {"type": "http.request", "body": b"one"} + + def receive(): + future = asyncio.get_running_loop().create_future() + native.put_nowait(future) + return future + + async def app(scope, read, send): + first = asyncio.create_task(read()) + second = asyncio.create_task(read()) + try: + pending = await asyncio.wait_for(native.get(), 1) + first.cancel() + with pytest.raises(asyncio.CancelledError): + await first + assert not pending.cancelled() + pending.set_result(event) + assert await second is event + assert native.empty() + finally: + for task in (first, second): + task.cancel() + await asyncio.gather(first, second, return_exceptions=True) + + monkeypatch.setattr(host, "_main_app", lambda: app) + await _pyvoy_entry()({"type": "http", "path": "/body"}, receive, None) + + +@pytest.mark.parametrize( + "path", ["/lessons.v2.WatchService/WatchClass", "/api/rpc/lessons.v2.WatchService/WatchClass"] +) +async def test_pyvoy_disconnect_stops_a_stream_waiting_for_its_next_message(monkeypatch, path): + pending = asyncio.get_running_loop().create_future() + reading = asyncio.Event() + closed = asyncio.Event() + + def receive(): + reading.set() + return pending + + async def messages(): + try: + yield b"first" + await asyncio.Event().wait() + finally: + closed.set() + + async def app(scope, read, send): + monitor = asyncio.ensure_future(read()) + try: + async with contextlib.aclosing(messages()) as stream: + async for _message in stream: + pass + finally: + monitor.cancel() + with contextlib.suppress(asyncio.CancelledError): + await monitor + + monkeypatch.setattr(host, "_main_app", lambda: app) + request = asyncio.create_task( + _pyvoy_entry()({"type": "http", "method": "POST", "path": path}, receive, None) + ) + try: + await asyncio.wait_for(reading.wait(), 1) + pending.set_result({"type": "http.disconnect"}) + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(asyncio.shield(request), 1) + assert closed.is_set() + finally: + request.cancel() + with contextlib.suppress(asyncio.CancelledError): + await request + + +@pytest.mark.parametrize("path", ["/api/v1/homework", "/api/rpc/lessons.v2.MeService/GetMe"]) +async def test_pyvoy_unary_disconnect_keeps_the_applications_own_handling(monkeypatch, path): + pending = asyncio.get_running_loop().create_future() + reading = asyncio.Event() + observed = asyncio.Event() + finish = asyncio.Event() + + def receive(): + reading.set() + return pending + + async def app(scope, read, send): + async def monitor(): + await read() + observed.set() + + monitor_task = asyncio.create_task(monitor()) + try: + await finish.wait() + finally: + monitor_task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await monitor_task + + monkeypatch.setattr(host, "_main_app", lambda: app) + request = asyncio.create_task( + _pyvoy_entry()({"type": "http", "method": "POST", "path": path}, receive, None) + ) + try: + await asyncio.wait_for(reading.wait(), 1) + pending.set_result({"type": "http.disconnect"}) + await asyncio.wait_for(observed.wait(), 1) + assert request.cancelling() == 0, "The host must not cancel unrelated unary work" + finish.set() + await request + finally: + request.cancel() + with contextlib.suppress(asyncio.CancelledError): + await request + + +async def test_pyvoy_receive_preserves_body_order_and_exception_identity(monkeypatch): + events = [ + {"type": "http.request", "body": b"one", "more_body": True}, + {"type": "http.request", "body": b"two", "more_body": False}, + ] + failure = OSError("the test transport failed") + calls = 0 + + def receive(): + nonlocal calls + pending = asyncio.get_running_loop().create_future() + calls += 1 + if calls <= len(events): + pending.set_result(events[calls - 1]) + else: + pending.set_exception(failure) + return pending + + async def app(scope, read, send): + assert await read() is events[0] + assert await read() is events[1] + with pytest.raises(OSError) as raised: + await read() + assert raised.value is failure + + monkeypatch.setattr(host, "_main_app", lambda: app) + await _pyvoy_entry()({"type": "http", "path": "/body"}, receive, None) + assert calls == 3 + + +@pytest.mark.parametrize("completion", ["delivered", "reset", "unexpected"]) +async def test_pyvoy_send_completion_outlives_its_cancelled_caller(monkeypatch, completion): + loop = asyncio.get_running_loop() + received = loop.create_future() + reading, sending, observed = asyncio.Event(), asyncio.Event(), asyncio.Event() + errors = [] + previous_handler = loop.get_exception_handler() + loop.set_exception_handler(lambda _loop, context: errors.append(context)) + + class CompletedSend(asyncio.Future[None]): + def exception(self): + failure = super().exception() + observed.set() + return failure + + sent = CompletedSend() + + def receive(): + reading.set() + return received + + def send(message): + sending.set() + return sent + + async def app(scope, read, write): + monitor = asyncio.ensure_future(read()) + try: + await write({"type": "http.response.body", "body": b"frame", "more_body": True}) + finally: + monitor.cancel() + with contextlib.suppress(asyncio.CancelledError): + await monitor + + monkeypatch.setattr(host, "_main_app", lambda: app) + request = asyncio.create_task( + _pyvoy_entry()( + {"type": "http", "method": "POST", "path": "/lessons.v2.WatchService/WatchClass"}, + receive, + send, + ) + ) + try: + await asyncio.wait_for(reading.wait(), 1) + await asyncio.wait_for(sending.wait(), 1) + received.set_result({"type": "http.disconnect"}) + with pytest.raises(asyncio.CancelledError): + await asyncio.wait_for(request, 1) + failure = None + if completion == "delivered": + sent.set_result(None) + else: + failure = ( + BrokenPipeError("the test client reset its stream") + if completion == "reset" else ValueError("the test transport failed") + ) + sent.set_exception(failure) + await asyncio.wait_for(observed.wait(), 1) + assert [context["exception"] for context in errors] == ( + [failure] if completion == "unexpected" else [] + ) + finally: + request.cancel() + with contextlib.suppress(asyncio.CancelledError): + await request + loop.set_exception_handler(previous_handler) + + +async def test_pyvoy_send_preserves_message_and_exception_identity(monkeypatch): + message = {"type": "http.response.body", "body": b"frame", "more_body": True} + failure = OSError("the test transport failed") + + def send(actual): + assert actual is message + future = asyncio.get_running_loop().create_future() + future.set_exception(failure) + return future + + async def app(scope, read, write): + with pytest.raises(OSError) as raised: + await write(message) + assert raised.value is failure + + monkeypatch.setattr(host, "_main_app", lambda: app) + await _pyvoy_entry()({"type": "http", "method": "POST", "path": "/api/v1/homework"}, None, send) + + async def _ask( path: str, content_type: str, body: bytes, *, http_version: str = "2" ) -> tuple[int, bytes, dict[bytes, bytes]]: diff --git a/server/tests/test_host_image.py b/server/tests/test_host_image.py index a60b576b..458ecbf5 100644 --- a/server/tests/test_host_image.py +++ b/server/tests/test_host_image.py @@ -16,6 +16,8 @@ import tomllib from pathlib import Path +import pytest +from packaging.markers import default_environment from packaging.requirements import Requirement from packaging.utils import NormalizedName, canonicalize_name @@ -110,6 +112,32 @@ def test_every_package_both_locks_pin_is_pinned_at_one_version() -> None: ) +@pytest.mark.parametrize( + ("platform", "selected", "excluded"), + [ + pytest.param( + {"sys_platform": "win32", "os_name": "nt", "platform_system": "Windows"}, + "winloop", "uvloop", id="windows", + ), + pytest.param( + {"sys_platform": "linux", "os_name": "posix", "platform_system": "Linux"}, + "uvloop", "winloop", id="linux", + ), + ], +) +def test_the_host_lock_selects_its_platform_loop( + platform: dict[str, str], selected: str, excluded: str, +) -> None: + environment = {**default_environment(), **platform} + active = set() + for line in _requirements(HOST_LOCK): + requirement = Requirement(line) + if requirement.marker is None or requirement.marker.evaluate(environment): + active.add(canonicalize_name(requirement.name)) + assert selected in active, f"{platform['sys_platform']} must install {selected}" + assert excluded not in active, f"{platform['sys_platform']} cannot install {excluded}" + + def test_vercel_s_lock_and_its_input_carry_nothing_of_the_host_s() -> None: """Vercel installs requirements.txt, and app.main is its cold start: a server package there is weight on every request and a reason it could be