From 1f8867cb1a1cbf3b31e4c04a7743f7dc4cd42126 Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Sun, 15 Nov 2026 22:49:06 +0530 Subject: [PATCH 1/3] feat: replace archived pyrofork with wzgram, and move to Python 3.15 pyrofork's repository is archived and its last stable release was 2025-12-10, so nothing after that is available. wzgram is the maintained fork. Version goes to 2.5.0 with it. No source change was needed for the swap. The wzgram wheel ships the `pyrogram` package and aliases `wzgram` to it through a meta-path finder, so all 47 `from pyrogram import ...` lines keep working -- verified by module identity, which is what keeps isinstance checks against a single Message class. The interpreter moves to 3.15 as well, which is what unblocks WarpCrypto: it publishes no cp314 Windows wheel from 2.0.8 onward, while wzgram raised its floor to >=2.0.8 in 3.1.5, so an unpinned install on Windows/3.14 silently backtracked to wzgram 3.1.4. On 3.15 every wheel exists, so the install is binary-only and needs no compiler anywhere. Two hazards the swap introduces, neither visible from the diff, both found by testing rather than reading: * A pyrofork session file cannot be opened by wzgram -- pyrofork writes schema v4, wzgram v8, and the migration aborts with "table update_state already exists". Opening the file is the first thing a client does, so the bot never starts. Sessions must be deleted, not migrated. * Installing wzgram over pyrofork leaves both distributions owning one site-packages/pyrogram directory. The result is deceptive: it imports successfully while the bot cannot start, because the leftover directory without its __init__.py is an empty namespace package. `import pyrogram` passes and `from pyrogram import Client` fails. update.py reports a session file the library refuses to open, asked of the library on a snapshot rather than inferred from the stored version -- the number does not identify the format, so pyrofork's v4 is unreadable while wzgram's v6 and v7 migrate. The snapshot goes through SQLite's backup API so it includes committed pages still sitting in the -wal sidecar, which an unclean stop leaves behind; copying the main file alone made a sound session look corrupt and would have told an operator to delete a recoverable authorisation. It also validates by importing the startup chain with placeholder configuration, since compileall and a bare `import Thunder` both pass on a tree whose imports cannot resolve. 3.15 also requires PYYAML_FORCE_LIBYAML=0 for the dev install (no cp315 wheel, and the sdist needs MSVC on Windows); documented for both POSIX and PowerShell, since the shell form that works on one is invalid in the other and Windows is where the workaround is needed. The README's Railyard badge is removed: it advertised a path nothing else in the tree documented. The CI include: leg goes too, having named a second Python version that only duplicated the primary combination. Verified on CPython 3.15.2 on Linux and Windows: suite green, ruff clean, all runtime dependencies install binary-only, and against the live bot 8/8 clients connect, /status reports 2.5.0, and a real 3.86 GB file streams over HTTP Range -- 7/7 unaligned ranges byte-exact, with the same sha256 on both platforms. Every new assertion was mutation-tested against the defect it names. --- .github/workflows/tests.yml | 15 +-- .python-version | 2 +- AGENTS.md | 29 ++++-- Dockerfile | 2 +- README.md | 28 ++++-- Thunder/__init__.py | 2 +- Thunder/__main__.py | 2 +- pyproject.toml | 2 +- requirements-dev.txt | 3 + requirements.txt | 6 +- tests/test_ci_workflow.py | 123 ++++++++++++++++++++++-- tests/test_deployment_entrypoints.py | 3 +- tests/test_runtime_safety.py | 61 ++++++++++++ tests/test_update_safety.py | 125 ++++++++++++++++++++++++ update.py | 139 ++++++++++++++++++++++++++- 15 files changed, 502 insertions(+), 40 deletions(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 34b82412..4ef83725 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -29,12 +29,9 @@ jobs: # Windows earns its place: the uvloop marker and update.py's chmod # fallback never execute on Linux. os: [ubuntu-latest, windows-latest] - python-version: ["3.13"] - include: - # The image pins 3.13, but the project documents 3.13+ support and the - # dependencies float, so this is what proves the promise still holds. - - os: ubuntu-latest - python-version: "3.14" + # Must match .python-version and the Dockerfile's minor; + # tests/test_ci_workflow.py asserts that. + python-version: ["3.15"] runs-on: ${{ matrix.os }} timeout-minutes: 20 steps: @@ -43,6 +40,10 @@ jobs: with: python-version: ${{ matrix.python-version }} - name: Install + # PyYAML has no cp315 wheel; without this it builds its C extension, + # which needs MSVC on Windows. + env: + PYYAML_FORCE_LIBYAML: "0" run: | python -m pip install --upgrade pip pip install -r requirements-dev.txt @@ -103,7 +104,7 @@ jobs: -e OWNER_ID=1 \ -e DATABASE_URL=mongodb://localhost:27017/smoke \ fyaz05/thunder:test python -c \ - "import Thunder, Thunder.__main__, uvloop, tgcrypto, aiohttp; print('ok', Thunder.__version__)" + "import Thunder, Thunder.__main__, uvloop, warpcrypto, aiohttp; print('ok', Thunder.__version__)" - name: Publish # Only reached once the smoke test passed, and only for a push event: a # pull request never receives secrets. Rebuilds from the cache the tested diff --git a/.python-version b/.python-version index 3a4f41ef..230693c3 100644 --- a/.python-version +++ b/.python-version @@ -1 +1 @@ -3.13 \ No newline at end of file +3.15 \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md index f4d0fd3f..837c2f30 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,6 +1,6 @@ # AGENTS.md — Thunder File-to-Link Bot -Python 3.13+ Telegram bot converting files to direct HTTP links. Uses Pyrofork, aiohttp, MongoDB, uvloop. +Python 3.15 Telegram bot converting files to direct HTTP links. Uses wzgram, aiohttp, MongoDB, uvloop. ## Run @@ -15,7 +15,8 @@ python3 update.py # Update only (rolls back if the new tree is unusable ```bash pip install -r requirements.txt -# aiohttp, cloudscraper, Jinja2, pyrofork, pymongo, psutil, python-dotenv, speedtest-cli, tgcrypto-pyrofork +# aiohttp, cloudscraper, Jinja2, wzgram, pymongo, psutil, python-dotenv, speedtest-cli +# wzgram ships the "pyrogram" package (and aliases "wzgram" to it), so imports are unchanged. # uvloop (non-Windows/Cygwin only, requirements.txt marker); asyncio loop elsewhere ``` @@ -95,15 +96,26 @@ Copy `config_sample.env` → `config.env`. Required vars: `API_ID`, `API_HASH`, ## Testing ```bash -pip install -r requirements-dev.txt +PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX python -m pytest -q # ~20s on Linux, ~45s on Windows; no credentials needed python -m ruff check . # config lives in pyproject.toml ``` +On Windows the variable is set first, since `VAR=value cmd` is not valid there: + +```powershell +$env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt +``` + +The env var is required on 3.15: PyYAML has no `cp315` wheel and compiles its C +extension by default, which needs MSVC on Windows. A cached wheel from an earlier +build can make a plain install appear to work — use `--no-cache-dir` to check. + Covers request parsing, slot conservation and truncation on the streaming routes, the import cycle, database naming, /status before startup, update.py preconditions and rollback, plugin handler registration, the CI -workflow's invariants, and .gitignore hygiene. +workflow's invariants, .gitignore hygiene, and the interpreter/requirements +guards that keep this file's own claims true. `pytest` and `ruff` both read `pyproject.toml`; there is no `pytest.ini`. @@ -116,11 +128,14 @@ CI notices a bad upstream release. Every command below was run to confirm it wor and leaves no lock file: ```bash -uv venv .venv --python 3.13 # ~0.15s -uv pip install --python .venv/bin/python -r requirements-dev.txt # ~3s first time +uv venv .venv --python 3.15 # ~0.15s +PYYAML_FORCE_LIBYAML=0 uv pip install --python .venv/bin/python -r requirements-dev.txt uvx ruff check . # ~0.1s, no install needed ``` +The same env var applies to `uv pip install`: it builds the same sdist, and on +Windows it is set the same way as above. + On Windows the interpreter is `.venv\Scripts\python.exe`. `uv pip install` runs in well under a second once anything is installed; the first install after creating the environment takes a few seconds. Re-running it is safe. @@ -131,7 +146,7 @@ One caveat if you deploy from this checkout: `uv venv` creates an environment cleanest result comes from seeding pip in the first place: ```bash -uv venv --seed .venv --python 3.13 # includes pip +uv venv --seed .venv --python 3.15 # includes pip ``` ## Debugging diff --git a/Dockerfile b/Dockerfile index 102291b2..51ab5c14 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM python:3.13-slim +FROM python:3.15-slim ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 diff --git a/README.md b/README.md index b3814715..3128fe85 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,4 @@

- -[![Deploy to Railyard](https://app.railyard.run/deploy/badge)](https://app.railyard.run/deploy?repo=https://github.com/fyaz05/FileToLink) Thunder Logo

⚡ Thunder

@@ -10,8 +8,8 @@

- Python Version - Pyrofork + Python Version + wzgram License Telegram Channel

@@ -136,7 +134,7 @@ Copy `config_sample.env` to `config.env` and fill in your values. | `MAX_BATCH_FILES` | Maximum files in batch processing | `50` | | `CHANNEL` | Allow processing messages from channels | `False` | | `BANNED_CHANNELS` | Blocked channel IDs | *(empty)* | -| `SLEEP_THRESHOLD` | Pyrogram flood-wait threshold | `600` | +| `SLEEP_THRESHOLD` | Flood-wait threshold in seconds | `600` | | `WORKERS` | Async workers | `8` | | `NAME` | Bot name; also the MongoDB database name (unsafe chars become `_`) | `ThunderF2L` | | `BIND_ADDRESS` | Bind address | `0.0.0.0` | @@ -287,7 +285,7 @@ This section covers the complete setup process for deploying Thunder, from prere | Requirement | Description | Source | | :--- | :--- | :--- | -| Python 3.13 | Programming language | [python.org](https://python.org) | +| Python 3.15 | Programming language | [python.org](https://python.org) | | MongoDB | Database | [mongodb.com](https://mongodb.com) | | Telegram API | API credentials | [my.telegram.org](https://my.telegram.org/apps) | | Bot Token | From @BotFather | [@BotFather](https://t.me/BotFather) | @@ -578,6 +576,11 @@ A: Your browser likely doesn't support the file's audio or video format (codec). **Q: Why does the bot sometimes become unresponsive?** A: This is likely a **Telegram Flood Wait**. To prevent spam, Telegram temporarily limits accounts that make too many requests. The bot is designed to handle this automatically by pausing and will resume on its own once the limit is lifted. +**Q: On shutdown I see `Task was destroyed but it is pending!` — is something broken?** +A: No, if `✓ Database connection closed` was printed first. The Telegram library leaves its +media sessions open on teardown; the bot still closes the database and exits cleanly. Expect +six of them per download and none if nothing was streamed. + #### **Performance** **Q: How can I fix slow download and streaming speeds?** @@ -605,10 +608,17 @@ Contributions are welcome! Please follow these steps: 2. Create a new feature branch (`git checkout -b feature/amazing-feature`). 3. Make your change and run the suite and linter: ```bash - pip install -r requirements-dev.txt + PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX python -m pytest -q python -m ruff check . ``` + On Windows, where that assignment is not valid syntax, set it first: + ```powershell + $env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt + ``` + The env var is needed on Python 3.15: PyYAML ships no `cp315` wheel and compiles + its C extension by default, which requires MSVC on Windows. This selects the + pure-Python fallback instead. 4. Commit your changes (`git commit -m 'Add some amazing feature'`). 5. Push to the branch (`git push origin feature/amazing-feature`). 6. Open a Pull Request. @@ -622,10 +632,10 @@ Licensed under the [Apache License 2.0](LICENSE). See the `LICENSE` file for det ## Acknowledgments -- [Pyrofork](https://github.com/Mayuri-Chan/pyrofork) - Telegram MTProto API Framework +- [wzgram](https://github.com/rjriajul/wzgram) - Telegram MTProto API Framework - [aiohttp](https://github.com/aio-libs/aiohttp) - Asynchronous HTTP Client/Server - [PyMongo](https://github.com/mongodb/mongo-python-driver) - Asynchronous MongoDB Driver -- [TgCrypto](https://github.com/wulan17/tgcrypto-pyrofork) - High-performance cryptography library +- [WarpCrypto](https://github.com/rjriajul/warpcrypto) - High-performance cryptography library (Rust) ## ⚠️ Disclaimer diff --git a/Thunder/__init__.py b/Thunder/__init__.py index d9af44e8..7e1a281d 100644 --- a/Thunder/__init__.py +++ b/Thunder/__init__.py @@ -2,4 +2,4 @@ import time StartTime = time.time() -__version__ = "2.1.0" +__version__ = "2.5.0" diff --git a/Thunder/__main__.py b/Thunder/__main__.py index b9e5ecee..20835a47 100644 --- a/Thunder/__main__.py +++ b/Thunder/__main__.py @@ -12,7 +12,7 @@ from pathlib import Path -# Pyrofork binds a client to the loop current at creation and Thunder.bot +# wzgram binds a client to the loop current at creation and Thunder.bot # creates it on import, so the loop has to exist before these imports. try: from uvloop import install diff --git a/pyproject.toml b/pyproject.toml index 76c0a735..bb17b864 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ [tool.ruff] line-length = 120 -target-version = "py313" +target-version = "py315" [tool.ruff.lint] # E4 stays out on purpose: __main__.py imports after creating the event loop, diff --git a/requirements-dev.txt b/requirements-dev.txt index b222cdad..5c951364 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,4 +4,7 @@ pytest-asyncio # Lint gate (config in pyproject.toml), run locally and in CI. ruff # tests/test_ci_workflow.py parses the workflow files to check their invariants. +# No cp315 wheel, and the sdist needs MSVC on Windows, so install as: +# PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX +# $env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt # Windows pyyaml diff --git a/requirements.txt b/requirements.txt index 08b84617..e3cd9466 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,12 +2,12 @@ aiohttp>=3.14 cloudscraper Jinja2 -pyrofork +# Maintained Pyrogram fork. Imports stay `pyrogram`: the wheel ships that +# package and aliases `wzgram` to it, so no source change is needed. +wzgram pymongo psutil python-dotenv speedtest-cli -# Fork provides cp313/cp314 wheels (avoids C toolchain at build time) and imports as "tgcrypto". -tgcrypto-pyrofork # uvloop is Unix-only; bot falls back to standard asyncio on Windows. uvloop>=0.22.1; sys_platform != "win32" and sys_platform != "cygwin" diff --git a/tests/test_ci_workflow.py b/tests/test_ci_workflow.py index 81ec061f..aaa2551c 100644 --- a/tests/test_ci_workflow.py +++ b/tests/test_ci_workflow.py @@ -22,6 +22,11 @@ PINNED_ACTION = re.compile(r"^[^@\s]+@[0-9a-f]{40}$") PUSH_EVENT = "github.event_name == 'push'" +# The single interpreter the project ships. Read from .python-version rather than +# written twice, so a version bump has one place to change and this suite reports +# the drift instead of hiding it. +PRIMARY_PYTHON = (REPO / ".python-version").read_text(encoding="utf-8").strip() + def load(path: Path): return yaml.safe_load(path.read_text(encoding="utf-8")) @@ -123,17 +128,35 @@ def test_the_suite_runs_on_both_operating_systems(): assert any(os_name.startswith("windows") for os_name in matrix["os"]), ( "the uvloop marker and update.py's chmod fallback only run on Windows" ) - assert "3.13" in [str(value) for value in matrix["python-version"]] + assert PRIMARY_PYTHON in [str(value) for value in matrix["python-version"]] + +def test_the_tested_python_is_the_one_the_project_ships(): + """`.python-version`, the Dockerfile and the CI matrix must name one version. -def test_the_documented_python_range_is_actually_tested(): - """README says 3.13+; a floating dependency can quietly drop the newer one.""" + Three files describe the interpreter; they can drift apart silently. + """ matrix = workflow()["jobs"]["test"]["strategy"]["matrix"] tested = {str(value) for value in matrix["python-version"]} tested |= {str(entry["python-version"]) for entry in matrix.get("include", [])} - assert "3.14" in tested, ( - "3.14 was deferred only until uvloop shipped cp314 wheels, which it now " - "does; the range is documented, so it is tested" + + stated = (REPO / ".python-version").read_text(encoding="utf-8").strip() + + assert stated in tested, ( + f".python-version says {stated!r} but CI tests {sorted(tested)}; one of " + "them is describing a version nobody runs" + ) + + # Parse the FROM line rather than reading the first line, which breaks on a + # `# syntax=` directive and would accept a version named only in a comment. + base_images = re.findall(r"^FROM\s+(\S+)", (REPO / "Dockerfile").read_text(encoding="utf-8"), + flags=re.MULTILINE | re.IGNORECASE) + assert base_images, "the Dockerfile has no FROM line" + minor = ".".join(stated.split(".")[:2]) + assert any(re.fullmatch(rf"python:{re.escape(minor)}(\.\d+)?-\w+", image) + for image in base_images), ( + f"the Dockerfile builds from {base_images}, not from the {minor} that " + ".python-version and CI agree on" ) @@ -256,3 +279,91 @@ def test_dependabot_only_tracks_actions(): assert ecosystems == {"github-actions"}, ( "app dependencies float by policy, so only the pinned actions need updates" ) + + +def test_the_archived_library_stays_out_of_the_requirements(): + """The retired distributions must not return, and wzgram must stay named. + + wzgram ships the `pyrogram` package, so every import keeps working and + nothing else in the tree mentions the old names -- a revert of this file + would be silent until a deployment broke. + """ + def package_name(entry: str) -> str: + # PEP 503: comparison is case-insensitive and -/_/. are interchangeable, + # so `Pyrofork` must not slip past a check for `pyrofork`. + raw = re.split(r"[<>=!~;\[ (]", entry.strip(), maxsplit=1)[0] + return re.sub(r"[-_.]+", "-", raw).lower() + + entries = [ + line.strip() for line in + (REPO / "requirements.txt").read_text(encoding="utf-8").splitlines() + if line.strip() and not line.lstrip().startswith("#") + ] + names = {package_name(entry) for entry in entries} + + for retired in ("pyrofork", "tgcrypto-pyrofork"): + assert retired not in names, f"{retired} is retired; wzgram replaces it" + + assert "wzgram" in names, ( + "wzgram must be requested explicitly; it is the maintained fork the " + "`pyrogram` imports resolve through" + ) + + +def test_the_crypto_backend_is_checked_in_the_image(): + """The smoke test must prove the crypto backend shipped. + + Its import list is the only place asserting the backend is present in the + built image, so a stale name there surfaces only when the image fails to start. + """ + steps = workflow()["jobs"]["build"]["steps"] + runs = [step for step in steps if "docker run" in str(step.get("run", ""))] + assert runs, "the image is never run, so nothing proves it starts" + + # Read the parsed `run` values: a commented-out smoke test still matches a + # text search while executing nothing. + commands = " ".join(str(step["run"]) for step in runs) + imports = [line for line in commands.splitlines() if "import Thunder" in line] + assert imports, "the smoke test no longer imports the app" + + assert any("warpcrypto" in line for line in imports), \ + "the smoke test does not import warpcrypto, so nothing proves the backend shipped" + assert not any("tgcrypto" in line for line in imports), \ + "tgcrypto is no longer a dependency; importing it would fail the gate" + + +def test_the_dev_install_is_documented_the_way_ci_does_it(): + """The documented dev installs must match what CI does. + + PyYAML has no cp315 wheel and its sdist needs MSVC on Windows, so the + documented install fails locally while CI passes, unless the env var is set. + Asserted against the runnable command rather than the file text, since the + prose around it also names the variable. + + Either spelling counts: `VAR=0 cmd` on POSIX and `$env:VAR = "0"; cmd` on + Windows, which is the only form that works in PowerShell. + """ + # Matches both `PYYAML_FORCE_LIBYAML=0` and `$env:PYYAML_FORCE_LIBYAML = "0"`. + sets_the_var = re.compile(r"PYYAML_FORCE_LIBYAML\s*=\s*[\"']?0") + + for relative in ("requirements-dev.txt", "AGENTS.md", "README.md"): + text = (REPO / relative).read_text(encoding="utf-8") + assert sets_the_var.search(text), ( + f"{relative} no longer tells the reader to set PYYAML_FORCE_LIBYAML=0, " + "so a dev install on 3.15 fails where CI succeeds" + ) + commands = [line.strip() for line in text.splitlines() + if "install" in line and "requirements-dev" in line + and not line.lstrip().startswith("#")] + for command in commands: + assert sets_the_var.search(command), ( + f"{relative} documents `{command}` without setting the env var, " + "which fails on 3.15; both the pip and uv forms need it" + ) + + install = next(step for step in workflow()["jobs"]["test"]["steps"] + if step.get("name") == "Install") + assert (install.get("env") or {}).get("PYYAML_FORCE_LIBYAML") == "0", ( + "the CI install step dropped the env var, so the job would fail on the " + "sdist build it is documented to avoid" + ) diff --git a/tests/test_deployment_entrypoints.py b/tests/test_deployment_entrypoints.py index 65831efb..b1816990 100644 --- a/tests/test_deployment_entrypoints.py +++ b/tests/test_deployment_entrypoints.py @@ -21,5 +21,6 @@ def test_platform_files_consumed_at_deploy_time_still_exist(): target = REPO / name assert target.is_file(), f"{name} is read by the deploy platform, not by our code" + # Local tooling and buildpack deploys read this; the Docker image does not. assert (REPO / ".python-version").read_text(encoding="utf-8").strip(), \ - "Heroku reads this to pick the interpreter" + "uv and buildpack-based deploys read this to pick the interpreter" diff --git a/tests/test_runtime_safety.py b/tests/test_runtime_safety.py index d95c8b0d..5495cef0 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -201,3 +201,64 @@ def test_restart_never_execs_a_path_that_does_not_exist(): assert "shutil.which" in restart, "the shell must be located, not assumed" assert "sys.executable" in restart, \ "there must be a fallback that works without bash" + + +def test_update_validation_imports_the_startup_chain_not_just_the_package(): + """Validation must import names the app actually uses, and supply config. + + Two failures it has to catch, both of which leave a tree that compiles: + + * a directory left importable but empty by an in-place upgrade, where + `import pyrogram` exits 0 and `from pyrogram import Client` fails; + * an unresolvable import in a startup module, which leaves `import Thunder` + working while the bot cannot start. + + And one it must not cause: those startup modules read configuration when + imported, while `_run_update` moves config.env aside before validating, so the + probe has to supply placeholders or a good update would be rolled back. + """ + import importlib.util + + spec = importlib.util.spec_from_file_location("_update_under_test", REPO / "update.py") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + calls = [] + + class FakeCompleted: + returncode = 0 + stderr = b"" + stdout = b"" + + def fake_run(command, **kwargs): + calls.append((command, kwargs)) + return FakeCompleted() + + original = module.srun + try: + module.srun = fake_run + assert module._validate() is True + finally: + module.srun = original + + assert any("compileall" in " ".join(str(a) for a in cmd) for cmd, _ in calls), \ + "syntax checking is still worth doing" + + probe_calls = [(cmd, kw) for cmd, kw in calls if "-c" in cmd] + assert probe_calls, "validation must run an import probe, not only compile" + probe, kwargs = probe_calls[0] + probe = " ".join(str(a) for a in probe) + + for needed in ("from pyrogram import", "Client", "warpcrypto", "Thunder.bot", + "Thunder.__main__"): + assert needed in probe, ( + f"the probe omits {needed}: the startup chain must be imported, since " + "an unresolvable import there compiles and only fails at next startup" + ) + + env = kwargs.get("env") or {} + for needed in ("API_ID", "API_HASH", "BOT_TOKEN", "BIN_CHANNEL", "DATABASE_URL"): + assert env.get(needed), ( + f"the probe runs without {needed}, so importing the startup modules " + "fails whenever config.env is absent -- which is when _validate runs" + ) diff --git a/tests/test_update_safety.py b/tests/test_update_safety.py index 70769caf..ae0df01a 100644 --- a/tests/test_update_safety.py +++ b/tests/test_update_safety.py @@ -1,4 +1,6 @@ """Verify update.py preconditions and rollback in isolated project copies.""" +import importlib.util +import sqlite3 import subprocess import sys @@ -6,6 +8,129 @@ run_update) +def _load_update(): + """Import update.py so its helpers can be called directly.""" + from pathlib import Path + + repo = Path(__file__).resolve().parent.parent + spec = importlib.util.spec_from_file_location("_update_under_test", repo / "update.py") + module = importlib.util.module_from_spec(spec) + sys.path.insert(0, str(repo)) + spec.loader.exec_module(module) + return module + + +SESSIONS_COLS = ("dc_id INTEGER PRIMARY KEY, api_id INTEGER, test_mode INTEGER, " + "auth_key BLOB, date INTEGER, user_id INTEGER, is_bot INTEGER") +SESSIONS_COLS_V7 = SESSIONS_COLS + ", server_address TEXT, port INTEGER" + + +def _write_session(path, version, columns=SESSIONS_COLS, update_state=True, + username_peer_id=False, extra_columns=0): + """Write a session shaped the way `version` expects. + + The layout matters: a session's stored version does not identify its format, + so a fixture has to be built per version rather than stamped with a number. + """ + connection = sqlite3.connect(str(path)) + connection.execute(f"CREATE TABLE sessions ({columns})") + connection.execute( + "CREATE TABLE peers (id INTEGER PRIMARY KEY, access_hash INTEGER, " + "type INTEGER NOT NULL, phone_number TEXT, last_update_on INTEGER)") + connection.execute( + "CREATE TABLE usernames (id INTEGER, username TEXT" + f"{', peer_id INTEGER' if username_peer_id else ''})") + if update_state: + connection.execute( + "CREATE TABLE update_state (id INTEGER PRIMARY KEY, pts INTEGER, " + "qts INTEGER, date INTEGER, seq INTEGER)") + connection.execute("CREATE TABLE version (number INTEGER)") + connection.execute("INSERT INTO version VALUES (?)", (version,)) + placeholders = ", ".join(["2", "123456", "0", "?", "0", "1", "1"] + ["NULL"] * extra_columns) + connection.execute(f"INSERT INTO sessions VALUES ({placeholders})", (b"x" * 256,)) + connection.commit() + connection.close() + + +def test_only_sessions_the_library_cannot_open_are_reported(tmp_path, monkeypatch): + """Report the files the installed library refuses, not every schema difference. + + A stored version does not identify a session's format, so comparing it would + condemn files that open fine -- wzgram reads v6 and v7 by migrating them -- and + miss the pyrofork v4 file, whose layout its v4 migration cannot apply. The + library is the only authority, so update.py tries it on a copy. + """ + module = _load_update() + monkeypatch.chdir(tmp_path) + + # A pyrofork-shaped v4: its own step 4 already created update_state, which + # wzgram's step 4 re-creates without IF NOT EXISTS, so open() raises. + _write_session(tmp_path / "pyrofork.session", 4) + # Migratable: one step behind, shaped as that version leaves it. + _write_session(tmp_path / "migratable.session", 7, SESSIONS_COLS_V7, + username_peer_id=True, extra_columns=2) + _write_session(tmp_path / "current.session", 8, SESSIONS_COLS_V7, + username_peer_id=True, extra_columns=2) + (tmp_path / "garbage.session").write_bytes(b"not a database at all") + (tmp_path / "notes.txt").write_text("ignore me") + + found = module._stale_sessions() + + assert any("pyrofork.session" in entry for entry in found), \ + "a session the library cannot open must be reported before it breaks startup" + assert not any("migratable.session" in entry for entry in found), \ + "a session the library migrates must not be reported; deleting it logs the bot out" + assert not any("current.session" in entry for entry in found), \ + "the current session must not be reported" + assert not any("garbage" in entry for entry in found), \ + "a file that is not a session database must be skipped, not crash the update" + assert not any("notes" in entry for entry in found), "only *.session files are sessions" + + +def test_an_uncheckpointed_session_is_not_reported_as_unreadable(tmp_path, monkeypatch): + """A session whose pages are still in the -wal sidecar must survive the check. + + An unclean stop leaves committed schema in `name.session-wal`, and SQLite keeps + the database valid there -- the main file alone looks empty. Copying only that + file gives the probe no `version` table, so a perfectly good session is reported + as incompatible and the operator is told to delete their authorisation. Read + through the WAL instead, which the snapshot does. + """ + module = _load_update() + monkeypatch.chdir(tmp_path) + + connection = sqlite3.connect(str(tmp_path / "unclean.session")) + connection.execute("PRAGMA journal_mode=WAL") + connection.execute(f"CREATE TABLE sessions ({SESSIONS_COLS_V7})") + connection.execute( + "CREATE TABLE peers (id INTEGER PRIMARY KEY, access_hash INTEGER, " + "type INTEGER NOT NULL, phone_number TEXT, last_update_on INTEGER)") + connection.execute("CREATE TABLE usernames (id INTEGER, username TEXT, peer_id INTEGER)") + connection.execute( + "CREATE TABLE update_state (id INTEGER PRIMARY KEY, pts INTEGER, " + "qts INTEGER, date INTEGER, seq INTEGER)") + connection.execute("CREATE TABLE version (number INTEGER)") + connection.execute("INSERT INTO version VALUES (8)") + connection.execute( + "INSERT INTO sessions VALUES (2, 123456, 0, ?, 0, 1, 1, NULL, NULL)", + (b"x" * 256,)) + connection.commit() + # Left open and uncheckpointed: the committed pages live in the -wal sidecar, + # which is what an unclean stop leaves behind. + try: + assert (tmp_path / "unclean.session-wal").exists(), \ + "the fixture needs a WAL sidecar to be meaningful" + + found = module._stale_sessions() + + assert not any("unclean.session" in entry for entry in found), ( + "a session readable through its WAL was reported as unreadable; the " + "snapshot must include committed WAL content, not just the main file" + ) + finally: + connection.close() + + def test_refuses_when_upstream_unset(): sandbox = make_sandbox() try: diff --git a/update.py b/update.py index 88b16344..bd9fb8aa 100644 --- a/update.py +++ b/update.py @@ -1,10 +1,12 @@ from fnmatch import fnmatch from os import chmod, environ, listdir, path, remove, replace, rmdir -from pathlib import PurePath +from pathlib import Path, PurePath from shutil import copytree, ignore_patterns, rmtree +from sqlite3 import connect as sqlite_connect from stat import S_IWRITE from subprocess import run as srun from sys import executable, exit +from tempfile import TemporaryDirectory from dotenv import load_dotenv @@ -219,7 +221,27 @@ def _install_requirements() -> bool: return True +# Placeholders for the probe below. Thunder.vars validates its configuration when +# imported, and _run_update moves config.env aside before validating, so the child +# process would otherwise fail on a perfectly good tree. The CI smoke test uses the +# same values to import the app in the image; none of them reach the network. +_PROBE_ENV = { + "API_ID": "123456", + "API_HASH": "0123456789abcdef0123456789abcdef", + "BOT_TOKEN": "123456:AA" + "x" * 30, + "BIN_CHANNEL": "-1001234567890", + "OWNER_ID": "123456", + "DATABASE_URL": "mongodb://localhost:27017/probe", +} + + def _validate() -> bool: + """Confirm the tree compiles and can import what it will load at startup. + + compileall alone passes on an environment whose packages are broken -- every + file can still compile while the bot cannot start -- so the import probe is + what catches it. + """ try: result = srun( [executable, "-m", "compileall", "-q", "Thunder", "update.py"], @@ -228,7 +250,109 @@ def _validate() -> bool: except OSError as e: logger.error(f"Could not run compileall: {e}") return False - return result.returncode == 0 + if result.returncode != 0: + return False + + try: + # Import the startup chain, not just the package: a syntactically valid + # but unresolvable import in Thunder.bot or Thunder.__main__ compiles and + # leaves `import Thunder` working, while the bot cannot start. Binding + # names also catches a directory left empty by an in-place upgrade, which + # imports as a namespace package. + probe = srun( + [executable, "-c", + "from pyrogram import Client, filters, enums; " + "import warpcrypto, Thunder, Thunder.bot, Thunder.__main__"], + capture_output=True, + env={**environ, **_PROBE_ENV}, + ) + except OSError as e: + logger.error(f"Could not import the application: {e}") + return False + if probe.returncode != 0: + tail = (probe.stderr or b"").decode("utf-8", "replace").strip().splitlines() + logger.error( + "The updated tree cannot import its dependencies: " + f"{tail[-1] if tail else 'no output'}. Recreate the environment " + "(`uv venv --seed .venv`) rather than installing over the old one." + ) + return False + return True + + +def _stale_sessions() -> list[str]: + """*.session files the installed library refuses to open. + + Reported, never deleted: the file holds the bot's authorisation, so the + operator removes it. Such a file fails at startup rather than re-authorising. + + Asked of the library rather than inferred from the stored schema version. The + number does not identify the format: pyrofork wrote v4 with a layout wzgram's + v4 migration cannot apply, while wzgram reads v6 and v7 by migrating them, so + comparing versions would condemn files that open fine and miss files that do + not. The library is tried on a copy, so the original is untouched. + """ + try: + import asyncio + from pyrogram.storage import FileStorage + except Exception: + return [] + + stale: list[str] = [] + + def snapshot(source: str, destination: str) -> bool: + """Write a consistent copy of a SQLite database, WAL included. + + Copying the file alone loses committed pages still held in the -wal + sidecar, which an unclean stop leaves behind: the copy then has no + `version` table and looks corrupt when it is only uncheckpointed. The + backup API reads through the WAL, so the copy is a real snapshot. + """ + origin = sqlite_connect(f"file:{source}?mode=ro", uri=True) + try: + target = sqlite_connect(destination) + try: + origin.backup(target) + finally: + target.close() + finally: + origin.close() + return True + + async def unreadable(source: str) -> bool: + """Snapshot the session, open the copy, and report whether it failed.""" + with TemporaryDirectory(prefix="thunder-session-check-") as holder: + copy = path.join(holder, "probe.session") + try: + snapshot(source, copy) + except Exception: + # Cannot snapshot it, so say nothing: an inconclusive answer must + # not send the operator to delete a session that may be fine. + return False + storage = FileStorage("probe", Path(holder)) + try: + await storage.open() + return False + except Exception: + return True + finally: + try: + await storage.conn.close() + except Exception: + pass + + for name in listdir("."): + if not name.endswith(".session"): + continue + try: + with open(name, "rb") as handle: + if handle.read(15) != b"SQLite format 3": + continue + if asyncio.run(unreadable(name)): + stale.append(name) + except Exception: + continue + return stale def _run_update(repo: str, branch: str) -> bool | None: @@ -266,6 +390,17 @@ def _run_update(repo: str, branch: str) -> bool | None: return False logger.info("Successfully updated with Latest Updates!") + + # Advisory: never turns a good update into a failed one. + try: + for stale in _stale_sessions(): + logger.warning( + f"Session {stale} cannot be read by the installed library; " + "delete it and restart to re-authorise from BOT_TOKEN." + ) + except Exception: + logger.debug("Could not check session compatibility", exc_info=True) + return True finally: # replace, not rename: on Windows rename raises FileExistsError if the From 581b0a0a61b186881f3e48483c905aa3730c490d Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Mon, 16 Nov 2026 12:36:18 +0530 Subject: [PATCH 2/3] refactor: drop a return value the caller ignores MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `snapshot` returned True unconditionally and both callers discarded it. Removing it is the whole change; the docstring and behaviour are untouched. Found while rechecking the branch for anything overlooked. Also verified in that pass, each by measurement rather than by reading: * The snapshot handles the real session filename. Thunder's is "Web Streamer .session", with a space, and every earlier fixture was space-free — so a URI that mishandled it would have made the whole check silently inert. Tested against the production name plus `%`, `&`, `'`, `(`, `[`, `;`, `=`, `@`, `$`, `,`, accented characters and a numeric multi-client name: all flagged correctly, and a file that cannot be snapshotted is still skipped rather than reported. * The check keeps its teeth. A pyrofork-shaped v4 session is still reported both normally and in the crash state (WAL present, -shm removed), so the WAL fix made the check more accurate without making it permissive. * A true unclean stop is handled. Killing a writer with SIGKILL leaves the WAL uncheckpointed and the -shm stale; that session is not reported. * The placeholder credentials never leave the process. Blocking sockets at the socket layer showed exactly one connection during the probe, to 127.0.0.1 on an ephemeral port: the event loop's self-pipe from `asyncio.new_event_loop()`. No Telegram DC and no MongoDB. `StreamBot` is constructed but never started — is_connected and is_initialized are both None. * `_stale_sessions` cannot fail a good update: its only call site is wrapped, and it runs after validation passes, so it is absent from the rollback path. * Repeated `asyncio.run` is safe here (update.py is a synchronous script), and a nested call would raise rather than hang — covered by that same guard. --- update.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/update.py b/update.py index bd9fb8aa..4c52e142 100644 --- a/update.py +++ b/update.py @@ -300,7 +300,7 @@ def _stale_sessions() -> list[str]: stale: list[str] = [] - def snapshot(source: str, destination: str) -> bool: + def snapshot(source: str, destination: str) -> None: """Write a consistent copy of a SQLite database, WAL included. Copying the file alone loses committed pages still held in the -wal @@ -317,7 +317,6 @@ def snapshot(source: str, destination: str) -> bool: target.close() finally: origin.close() - return True async def unreadable(source: str) -> bool: """Snapshot the session, open the copy, and report whether it failed.""" From e8403d8e6f48448a5a2b1d05cf9f375fd59f71ba Mon Sep 17 00:00:00 2001 From: fyaz05 Date: Mon, 16 Nov 2026 13:30:33 +0530 Subject: [PATCH 3/3] style: cut narration from the comments and docs The text added by this branch had grown into commentary: restating what the code already says, explaining the same fact more than once, and justifying decisions rather than recording the one non-obvious thing. The clearest case was in requirements.txt, where `wzgram` sat under three lines explaining that it ships the `pyrogram` package and aliases `wzgram` to it. That belongs in a commit message, not beside a package name -- the list is a list. Others: the PyYAML explanation appeared at full length in four places and now appears once in AGENTS.md with a one-line reason elsewhere; two test docstrings enumerated the failure modes their assertions already name; the probe's placeholder comment justified the values rather than saying what they are for. Net 111 lines removed, 73 added. No assertion, guard or behaviour changed -- the suite is unchanged at 151 passed / 1 skipped, ruff clean. --- AGENTS.md | 16 ++++++------ README.md | 12 ++++----- requirements-dev.txt | 5 ++-- requirements.txt | 2 -- tests/test_ci_workflow.py | 49 +++++++++++++----------------------- tests/test_runtime_safety.py | 29 ++++++++------------- tests/test_update_safety.py | 30 +++++++++------------- update.py | 41 +++++++++++++----------------- 8 files changed, 73 insertions(+), 111 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 837c2f30..992f39aa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -16,7 +16,6 @@ python3 update.py # Update only (rolls back if the new tree is unusable ```bash pip install -r requirements.txt # aiohttp, cloudscraper, Jinja2, wzgram, pymongo, psutil, python-dotenv, speedtest-cli -# wzgram ships the "pyrogram" package (and aliases "wzgram" to it), so imports are unchanged. # uvloop (non-Windows/Cygwin only, requirements.txt marker); asyncio loop elsewhere ``` @@ -101,21 +100,21 @@ python -m pytest -q # ~20s on Linux, ~45s on Windows; no credentials ne python -m ruff check . # config lives in pyproject.toml ``` -On Windows the variable is set first, since `VAR=value cmd` is not valid there: +PyYAML has no `cp315` wheel, so the env var is required; on Windows set it first, +since `VAR=value cmd` is not valid there: ```powershell $env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt ``` -The env var is required on 3.15: PyYAML has no `cp315` wheel and compiles its C -extension by default, which needs MSVC on Windows. A cached wheel from an earlier -build can make a plain install appear to work — use `--no-cache-dir` to check. +A cached wheel from an earlier build can make a plain install appear to work — use +`--no-cache-dir` to check. Covers request parsing, slot conservation and truncation on the streaming routes, the import cycle, database naming, /status before startup, update.py preconditions and rollback, plugin handler registration, the CI -workflow's invariants, .gitignore hygiene, and the interpreter/requirements -guards that keep this file's own claims true. +workflow's invariants, .gitignore hygiene, and the interpreter and requirements +guards. `pytest` and `ruff` both read `pyproject.toml`; there is no `pytest.ini`. @@ -133,8 +132,7 @@ PYYAML_FORCE_LIBYAML=0 uv pip install --python .venv/bin/python -r requirements- uvx ruff check . # ~0.1s, no install needed ``` -The same env var applies to `uv pip install`: it builds the same sdist, and on -Windows it is set the same way as above. +The same env var applies to `uv pip install`, which builds the same sdist. On Windows the interpreter is `.venv\Scripts\python.exe`. `uv pip install` runs in well under a second once anything is installed; the first install after creating diff --git a/README.md b/README.md index 3128fe85..2d6887fe 100644 --- a/README.md +++ b/README.md @@ -577,9 +577,9 @@ A: Your browser likely doesn't support the file's audio or video format (codec). A: This is likely a **Telegram Flood Wait**. To prevent spam, Telegram temporarily limits accounts that make too many requests. The bot is designed to handle this automatically by pausing and will resume on its own once the limit is lifted. **Q: On shutdown I see `Task was destroyed but it is pending!` — is something broken?** -A: No, if `✓ Database connection closed` was printed first. The Telegram library leaves its -media sessions open on teardown; the bot still closes the database and exits cleanly. Expect -six of them per download and none if nothing was streamed. +A: No, if `✓ Database connection closed` was printed first. The library leaves its media +sessions open on teardown; the bot still exits cleanly. Expect six after a download, none if +nothing was streamed. #### **Performance** @@ -612,13 +612,11 @@ Contributions are welcome! Please follow these steps: python -m pytest -q python -m ruff check . ``` - On Windows, where that assignment is not valid syntax, set it first: + The env var is needed on Python 3.15 (no `cp315` wheel). On Windows, where that + assignment is not valid, set it first: ```powershell $env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt ``` - The env var is needed on Python 3.15: PyYAML ships no `cp315` wheel and compiles - its C extension by default, which requires MSVC on Windows. This selects the - pure-Python fallback instead. 4. Commit your changes (`git commit -m 'Add some amazing feature'`). 5. Push to the branch (`git push origin feature/amazing-feature`). 6. Open a Pull Request. diff --git a/requirements-dev.txt b/requirements-dev.txt index 5c951364..fd32c8c0 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -4,7 +4,6 @@ pytest-asyncio # Lint gate (config in pyproject.toml), run locally and in CI. ruff # tests/test_ci_workflow.py parses the workflow files to check their invariants. -# No cp315 wheel, and the sdist needs MSVC on Windows, so install as: -# PYYAML_FORCE_LIBYAML=0 pip install -r requirements-dev.txt # POSIX -# $env:PYYAML_FORCE_LIBYAML = "0"; pip install -r requirements-dev.txt # Windows +# No cp315 wheel: install with PYYAML_FORCE_LIBYAML=0, or the sdist build needs +# MSVC on Windows. pyyaml diff --git a/requirements.txt b/requirements.txt index e3cd9466..1cef8b82 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,8 +2,6 @@ aiohttp>=3.14 cloudscraper Jinja2 -# Maintained Pyrogram fork. Imports stay `pyrogram`: the wheel ships that -# package and aliases `wzgram` to it, so no source change is needed. wzgram pymongo psutil diff --git a/tests/test_ci_workflow.py b/tests/test_ci_workflow.py index aaa2551c..ae3f47dd 100644 --- a/tests/test_ci_workflow.py +++ b/tests/test_ci_workflow.py @@ -22,9 +22,8 @@ PINNED_ACTION = re.compile(r"^[^@\s]+@[0-9a-f]{40}$") PUSH_EVENT = "github.event_name == 'push'" -# The single interpreter the project ships. Read from .python-version rather than -# written twice, so a version bump has one place to change and this suite reports -# the drift instead of hiding it. +# The interpreter the project ships, read from .python-version rather than written +# twice, so a version bump has one place to change. PRIMARY_PYTHON = (REPO / ".python-version").read_text(encoding="utf-8").strip() @@ -132,9 +131,9 @@ def test_the_suite_runs_on_both_operating_systems(): def test_the_tested_python_is_the_one_the_project_ships(): - """`.python-version`, the Dockerfile and the CI matrix must name one version. + """`.python-version`, the Dockerfile and CI must name one version. - Three files describe the interpreter; they can drift apart silently. + Three files describe the interpreter and can drift apart silently. """ matrix = workflow()["jobs"]["test"]["strategy"]["matrix"] tested = {str(value) for value in matrix["python-version"]} @@ -142,22 +141,18 @@ def test_the_tested_python_is_the_one_the_project_ships(): stated = (REPO / ".python-version").read_text(encoding="utf-8").strip() - assert stated in tested, ( - f".python-version says {stated!r} but CI tests {sorted(tested)}; one of " - "them is describing a version nobody runs" - ) + assert stated in tested, \ + f".python-version says {stated!r} but CI tests {sorted(tested)}" - # Parse the FROM line rather than reading the first line, which breaks on a - # `# syntax=` directive and would accept a version named only in a comment. + # Parse FROM rather than reading line 0: a `# syntax=` directive would break + # that, and a substring test would accept a version named only in a comment. base_images = re.findall(r"^FROM\s+(\S+)", (REPO / "Dockerfile").read_text(encoding="utf-8"), flags=re.MULTILINE | re.IGNORECASE) assert base_images, "the Dockerfile has no FROM line" minor = ".".join(stated.split(".")[:2]) assert any(re.fullmatch(rf"python:{re.escape(minor)}(\.\d+)?-\w+", image) - for image in base_images), ( - f"the Dockerfile builds from {base_images}, not from the {minor} that " - ".python-version and CI agree on" - ) + for image in base_images), \ + f"the Dockerfile builds from {base_images}, not {minor}" def test_a_weekly_run_guards_the_floating_dependencies(): @@ -284,13 +279,12 @@ def test_dependabot_only_tracks_actions(): def test_the_archived_library_stays_out_of_the_requirements(): """The retired distributions must not return, and wzgram must stay named. - wzgram ships the `pyrogram` package, so every import keeps working and - nothing else in the tree mentions the old names -- a revert of this file + Nothing else in the tree mentions the old names, so a revert of this file would be silent until a deployment broke. """ def package_name(entry: str) -> str: - # PEP 503: comparison is case-insensitive and -/_/. are interchangeable, - # so `Pyrofork` must not slip past a check for `pyrofork`. + # PEP 503: case-insensitive, and -/_/. are interchangeable, so `Pyrofork` + # must not slip past a check for `pyrofork`. raw = re.split(r"[<>=!~;\[ (]", entry.strip(), maxsplit=1)[0] return re.sub(r"[-_.]+", "-", raw).lower() @@ -304,16 +298,13 @@ def package_name(entry: str) -> str: for retired in ("pyrofork", "tgcrypto-pyrofork"): assert retired not in names, f"{retired} is retired; wzgram replaces it" - assert "wzgram" in names, ( - "wzgram must be requested explicitly; it is the maintained fork the " - "`pyrogram` imports resolve through" - ) + assert "wzgram" in names, "wzgram is what the `pyrogram` imports resolve through" def test_the_crypto_backend_is_checked_in_the_image(): """The smoke test must prove the crypto backend shipped. - Its import list is the only place asserting the backend is present in the + The import list is the only place asserting the backend is present in the built image, so a stale name there surfaces only when the image fails to start. """ steps = workflow()["jobs"]["build"]["steps"] @@ -335,13 +326,9 @@ def test_the_crypto_backend_is_checked_in_the_image(): def test_the_dev_install_is_documented_the_way_ci_does_it(): """The documented dev installs must match what CI does. - PyYAML has no cp315 wheel and its sdist needs MSVC on Windows, so the - documented install fails locally while CI passes, unless the env var is set. - Asserted against the runnable command rather than the file text, since the - prose around it also names the variable. - - Either spelling counts: `VAR=0 cmd` on POSIX and `$env:VAR = "0"; cmd` on - Windows, which is the only form that works in PowerShell. + PyYAML has no cp315 wheel, so the documented install needs the env var or it + fails locally while CI passes. Either spelling counts: `VAR=0 cmd` on POSIX, + `$env:VAR = "0"; cmd` in PowerShell. """ # Matches both `PYYAML_FORCE_LIBYAML=0` and `$env:PYYAML_FORCE_LIBYAML = "0"`. sets_the_var = re.compile(r"PYYAML_FORCE_LIBYAML\s*=\s*[\"']?0") diff --git a/tests/test_runtime_safety.py b/tests/test_runtime_safety.py index 5495cef0..e1a9c581 100644 --- a/tests/test_runtime_safety.py +++ b/tests/test_runtime_safety.py @@ -204,18 +204,17 @@ def test_restart_never_execs_a_path_that_does_not_exist(): def test_update_validation_imports_the_startup_chain_not_just_the_package(): - """Validation must import names the app actually uses, and supply config. + """Validation must import the names the app uses, and supply configuration. - Two failures it has to catch, both of which leave a tree that compiles: + Two failures it has to catch, both leaving a tree that compiles: a package + directory left empty by an in-place upgrade, where `import pyrogram` succeeds + and `from pyrogram import Client` fails; and an unresolvable import in a + startup module, which leaves `import Thunder` working while the bot cannot + start. - * a directory left importable but empty by an in-place upgrade, where - `import pyrogram` exits 0 and `from pyrogram import Client` fails; - * an unresolvable import in a startup module, which leaves `import Thunder` - working while the bot cannot start. - - And one it must not cause: those startup modules read configuration when - imported, while `_run_update` moves config.env aside before validating, so the - probe has to supply placeholders or a good update would be rolled back. + And one it must not cause: those modules read configuration when imported, + while `_run_update` moves config.env aside first, so the probe needs + placeholders or it would fail on a good tree and roll it back. """ import importlib.util @@ -251,14 +250,8 @@ def fake_run(command, **kwargs): for needed in ("from pyrogram import", "Client", "warpcrypto", "Thunder.bot", "Thunder.__main__"): - assert needed in probe, ( - f"the probe omits {needed}: the startup chain must be imported, since " - "an unresolvable import there compiles and only fails at next startup" - ) + assert needed in probe, f"the probe omits {needed}" env = kwargs.get("env") or {} for needed in ("API_ID", "API_HASH", "BOT_TOKEN", "BIN_CHANNEL", "DATABASE_URL"): - assert env.get(needed), ( - f"the probe runs without {needed}, so importing the startup modules " - "fails whenever config.env is absent -- which is when _validate runs" - ) + assert env.get(needed), f"the probe runs without {needed}" diff --git a/tests/test_update_safety.py b/tests/test_update_safety.py index ae0df01a..f8a9eb98 100644 --- a/tests/test_update_safety.py +++ b/tests/test_update_safety.py @@ -27,11 +27,8 @@ def _load_update(): def _write_session(path, version, columns=SESSIONS_COLS, update_state=True, username_peer_id=False, extra_columns=0): - """Write a session shaped the way `version` expects. - - The layout matters: a session's stored version does not identify its format, - so a fixture has to be built per version rather than stamped with a number. - """ + """Write a session. `columns` shapes it, since the stored version does not + identify the layout: a fixture has to match the format it claims.""" connection = sqlite3.connect(str(path)) connection.execute(f"CREATE TABLE sessions ({columns})") connection.execute( @@ -53,18 +50,17 @@ def _write_session(path, version, columns=SESSIONS_COLS, update_state=True, def test_only_sessions_the_library_cannot_open_are_reported(tmp_path, monkeypatch): - """Report the files the installed library refuses, not every schema difference. + """Report the files the library refuses, not every schema difference. - A stored version does not identify a session's format, so comparing it would - condemn files that open fine -- wzgram reads v6 and v7 by migrating them -- and - miss the pyrofork v4 file, whose layout its v4 migration cannot apply. The - library is the only authority, so update.py tries it on a copy. + A stored version does not identify a session's format: wzgram migrates v6 and + v7, while pyrofork's v4 layout fails to migrate. The library is the only + authority, so update.py tries it on a snapshot. """ module = _load_update() monkeypatch.chdir(tmp_path) - # A pyrofork-shaped v4: its own step 4 already created update_state, which - # wzgram's step 4 re-creates without IF NOT EXISTS, so open() raises. + # pyrofork's shape: its step 4 already created update_state, which wzgram's + # step 4 re-creates without IF NOT EXISTS, so open() raises. _write_session(tmp_path / "pyrofork.session", 4) # Migratable: one step behind, shaped as that version leaves it. _write_session(tmp_path / "migratable.session", 7, SESSIONS_COLS_V7, @@ -77,7 +73,7 @@ def test_only_sessions_the_library_cannot_open_are_reported(tmp_path, monkeypatc found = module._stale_sessions() assert any("pyrofork.session" in entry for entry in found), \ - "a session the library cannot open must be reported before it breaks startup" + "a session the library cannot open must be reported" assert not any("migratable.session" in entry for entry in found), \ "a session the library migrates must not be reported; deleting it logs the bot out" assert not any("current.session" in entry for entry in found), \ @@ -90,11 +86,9 @@ def test_only_sessions_the_library_cannot_open_are_reported(tmp_path, monkeypatc def test_an_uncheckpointed_session_is_not_reported_as_unreadable(tmp_path, monkeypatch): """A session whose pages are still in the -wal sidecar must survive the check. - An unclean stop leaves committed schema in `name.session-wal`, and SQLite keeps - the database valid there -- the main file alone looks empty. Copying only that - file gives the probe no `version` table, so a perfectly good session is reported - as incompatible and the operator is told to delete their authorisation. Read - through the WAL instead, which the snapshot does. + An unclean stop leaves committed schema there and the main file looks empty. + Copying only that file gives the probe no `version` table, so a good session is + reported as incompatible and the operator is told to delete their authorisation. """ module = _load_update() monkeypatch.chdir(tmp_path) diff --git a/update.py b/update.py index 4c52e142..cbb0ee79 100644 --- a/update.py +++ b/update.py @@ -221,10 +221,9 @@ def _install_requirements() -> bool: return True -# Placeholders for the probe below. Thunder.vars validates its configuration when -# imported, and _run_update moves config.env aside before validating, so the child -# process would otherwise fail on a perfectly good tree. The CI smoke test uses the -# same values to import the app in the image; none of them reach the network. +# Placeholders for the probe below: Thunder.vars validates its configuration at +# import, and _run_update moves config.env aside before validating, so the child +# would otherwise fail on a good tree. The CI smoke test uses the same values. _PROBE_ENV = { "API_ID": "123456", "API_HASH": "0123456789abcdef0123456789abcdef", @@ -236,11 +235,10 @@ def _install_requirements() -> bool: def _validate() -> bool: - """Confirm the tree compiles and can import what it will load at startup. + """Confirm the tree compiles and can import what startup needs. - compileall alone passes on an environment whose packages are broken -- every - file can still compile while the bot cannot start -- so the import probe is - what catches it. + compileall alone passes on an environment whose packages are broken, so the + import probe is what catches it. """ try: result = srun( @@ -254,11 +252,10 @@ def _validate() -> bool: return False try: - # Import the startup chain, not just the package: a syntactically valid - # but unresolvable import in Thunder.bot or Thunder.__main__ compiles and - # leaves `import Thunder` working, while the bot cannot start. Binding - # names also catches a directory left empty by an in-place upgrade, which - # imports as a namespace package. + # The startup chain, not just the package: an unresolvable import in + # Thunder.bot or Thunder.__main__ compiles and leaves `import Thunder` + # working, while the bot cannot start. Binding names also catches a + # directory left empty by an in-place upgrade (a namespace package). probe = srun( [executable, "-c", "from pyrogram import Client, filters, enums; " @@ -284,13 +281,12 @@ def _stale_sessions() -> list[str]: """*.session files the installed library refuses to open. Reported, never deleted: the file holds the bot's authorisation, so the - operator removes it. Such a file fails at startup rather than re-authorising. + operator removes it. - Asked of the library rather than inferred from the stored schema version. The - number does not identify the format: pyrofork wrote v4 with a layout wzgram's - v4 migration cannot apply, while wzgram reads v6 and v7 by migrating them, so - comparing versions would condemn files that open fine and miss files that do - not. The library is tried on a copy, so the original is untouched. + Asked of the library rather than inferred from the stored schema version, which + does not identify the format -- pyrofork's v4 layout fails to migrate while + wzgram migrates v6 and v7. The library is tried on a snapshot, so the original + is untouched. """ try: import asyncio @@ -303,10 +299,9 @@ def _stale_sessions() -> list[str]: def snapshot(source: str, destination: str) -> None: """Write a consistent copy of a SQLite database, WAL included. - Copying the file alone loses committed pages still held in the -wal - sidecar, which an unclean stop leaves behind: the copy then has no - `version` table and looks corrupt when it is only uncheckpointed. The - backup API reads through the WAL, so the copy is a real snapshot. + Copying the file alone loses committed pages still in the -wal sidecar, + which an unclean stop leaves behind: the copy then looks corrupt when it is + only uncheckpointed. The backup API reads through the WAL. """ origin = sqlite_connect(f"file:{source}?mode=ro", uri=True) try: