diff --git a/CHANGELOG.rst b/CHANGELOG.rst index 5de080d..b6ff82c 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -1,6 +1,31 @@ Changelog ========= +0.4.1 +----- + +This release adds persistent task execution and SSH host-key fingerprint +display, and updates herethere. + +* Added ``tasks_here.TaskRunner`` for persistent sequential task execution, + with retries, pause/resume, progress inspection, and recovery after app restart +* Added ``TaskRunner.export_results()`` to save task results as a JSON file + for download from the device +* Added the SSH host-key SHA-256 fingerprint to the connection screen +* Updated ``herethere`` to 0.3.3, adding optional SSH host-key verification + and ``%there put`` / ``Client.put()`` for transferring local Python values + into the remote live namespace + +0.4.0 +----- + +This release adds support for running local AI models directly on Android +with Google's LiteRT LM. + +* Added LiteRT LM support for on-device language and multimodal models +* Added ``ml_here`` helpers for downloading and managing models from Hugging Face +* Added LiteRT LM usage guidance to the packaged ``pythonhere`` agent skill + 0.3.1 ----- diff --git a/buildozer.spec b/buildozer.spec index 877a0b3..fa026bf 100644 --- a/buildozer.spec +++ b/buildozer.spec @@ -38,7 +38,7 @@ requirements = # herethere dependencies asyncssh==2.23.1, python-dotenv==1.2.2, - herethere==0.3.2, + herethere==0.3.3, # asyncssh dependencies cryptography, typing_extensions, @@ -58,6 +58,7 @@ requirements = idna==3.18, # https://github.com/kivy/python-for-android/issues/3098 filetype==1.2.0, + persist-queue==1.1.0, litert_lm_api==0.16.0, diff --git a/examples/README.md b/examples/README.md index 1128ea9..4b2287a 100644 --- a/examples/README.md +++ b/examples/README.md @@ -32,8 +32,15 @@ THERE_USERNAME=here # Password, as set in PythonHere app Settings section THERE_PASSWORD=xxx + +# Optional: verify the server fingerprint shown on the app's connection screen. +# THERE_HOST_KEY_SHA256=SHA256: ``` +Host-key verification is optional. Leave the line commented out unless you want +to enable it; see the [connection settings](commands.md#there-env-example) for +details. + ## When using with Docker Content of **examples** directory are not preserved. diff --git a/examples/commands.md b/examples/commands.md index 181c3d8..88bd39e 100644 --- a/examples/commands.md +++ b/examples/commands.md @@ -49,8 +49,21 @@ THERE_USERNAME=here # Password, as set in PythonHere app Settings section THERE_PASSWORD=xxx + +# Optional: verify the server fingerprint shown on the app's connection screen. +# THERE_HOST_KEY_SHA256=SHA256: ``` +Host-key verification is optional; leave the line commented out for the usual +connection setup. To enable it, copy the SSH host-key fingerprint from +PythonHere's connection screen, replace the placeholder, and uncomment the line. +The client then checks the fingerprint before authentication on every connection +and reconnect. This setting works with both Jupyter and the `there` CLI. + +The fingerprint stays the same when the device's IP address changes. If the SSH +host key is replaced or regenerated, compare the new fingerprint with the one +shown in the app before updating the config. + +++ ## %there group of commands @@ -125,6 +138,32 @@ root_size Use `%there get` for small and inspectable values. For large text, binary data, images, CSV files, or directories, write a remote file and use `%there download`. +### put + +Transfer a local notebook variable into PythonHere's live Python namespace: + +```{code-cell} +config = {"temperature": 0.2, "top_k": 40} +%there put config +``` + +The variable is then available to code running on the device: + +```{code-cell} +%%there +print(config) +``` + +An optional second name sets the remote variable name: + +```{code-cell} +local_tasks = [{"id": "a", "value": 1}, {"id": "b", "value": 2}] +%there put local_tasks device_tasks +``` + +`put` takes a local variable name, not an expression. Use it for small or +medium in-memory values. For large data or files, use `%there upload`. + ### kv ```{code-cell} diff --git a/examples/diy_app_inspector.md b/examples/diy_app_inspector.md new file mode 100644 index 0000000..cd0f295 --- /dev/null +++ b/examples/diy_app_inspector.md @@ -0,0 +1,504 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# DIY #1: App Inspector + +Companion notebook for the video [*Android DIY #1 — Where did that app come from?*](https://youtube.com/shorts/-wIceFaHI9w) + +Let's explore installed apps with PythonHere, see which installers Android associates with them, and build an interactive app browser. + +## Connect to Android + +Connect PythonHere to your phone and access Android's `PackageManager` to inspect installed apps. + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +```{code-cell} ipython3 +%%there +from jnius import autoclass +from kivy.logger import Logger + +activity = autoclass("org.kivy.android.PythonActivity").mActivity +pm = activity.getPackageManager() +PackageManager = autoclass("android.content.pm.PackageManager") +ApplicationInfo = autoclass("android.content.pm.ApplicationInfo") +VERSION = autoclass("android.os.Build$VERSION") +print(PackageManager) +``` + +## Collect apps and installation sources + +Use Android's `PackageManager` to list installed apps and find their recorded installers. We'll use this information to group apps by installation source. + +```{code-cell} ipython3 +%%there +def installer_name(package): + try: + if VERSION.SDK_INT >= 30: + source = pm.getInstallSourceInfo(package) + return str(source.getInstallingPackageName() or "") + return str(pm.getInstallerPackageName(package) or "") + except Exception as exc: + Logger.warning(f"Packages: Install source unavailable for {package}: {exc}") + return "" + +print("PythonHere app installer is", installer_name("me.herethere.pythonhere")) +``` + +```{code-cell} ipython3 +%%there +packages = pm.getInstalledPackages(0) + +apps = [] +for package in packages: + info = package.applicationInfo + apps.append({ + "label": str(pm.getApplicationLabel(info)), + "package": str(package.packageName), + "system": bool(info.flags & ( + ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_UPDATED_SYSTEM_APP + )), + "installer": installer_name(str(package.packageName)), + }) +apps.sort(key=lambda row: (row["label"].casefold(), row["package"])) +print(f"{len(apps)} visible apps") +``` + +## Group apps by installer + +Group apps by their recorded installer, so we can explore which apps belong to each source. + +```{code-cell} ipython3 +%%there +apps_by_installer = {} +for row in apps: + installer = row["installer"] + if installer not in apps_by_installer: + apps_by_installer[installer] = [] + apps_by_installer[installer].append(row) + +print(f"{len(apps_by_installer)} installer groups") +``` + +## Show readable installer names + +Android identifies installers by package IDs, such as `com.android.vending` for Google Play Store. + +Let's show readable names where available and count the apps associated with each installer. + +```{code-cell} ipython3 +%%there +app_labels = {} +for row in apps: + app_labels[row["package"]] = row["label"] + +installers = [] +for package, installed_apps in apps_by_installer.items(): + if package: + label = app_labels.get(package) or package + else: + label = "No recorded installer" + installers.append({ + "package": package, + "label": label, + "count": len(installed_apps), + }) + +installers.sort(key=lambda installer: installer["label"].casefold()) +for installer in installers: + print(f"{installer['label']} ({installer['count']})") + print(f" {installer['package'] or '(not recorded)'}") +``` + +## Explore apps from one installer + +Let's look at apps associated with a particular installer. + +The example uses Samsung's `com.samsung.android.app.omcagent`. You can choose any installer from your own results. + +```{code-cell} ipython3 +%%there +selected_installer = "com.samsung.android.app.omcagent" +selected_apps = apps_by_installer.get(selected_installer, []) +print(f"{len(selected_apps)} apps") +for row in selected_apps: + print(f'{row["label"]:<32} {row["package"]}') +if not selected_apps: + print("No apps for this installer. Choose a package ID from the installer list above.") +``` + +## Open Android's App info + +Let's make each app card clickable, so tapping it opens Android's built-in **App info** screen. + +```{code-cell} ipython3 +%%there +from datetime import datetime + +from android.runnable import run_on_ui_thread +from kivy.clock import Clock +from kivy.properties import ObjectProperty, StringProperty +from kivy.uix.boxlayout import BoxLayout +from kivy.uix.behaviors import ButtonBehavior +from kivy.uix.label import Label +from kivy.uix.spinner import SpinnerOption + + +Intent = autoclass("android.content.Intent") +Uri = autoclass("android.net.Uri") +PythonActivity = autoclass("org.kivy.android.PythonActivity") +settings_status = {} + + +@run_on_ui_thread +def open_app_settings(package): + """Open Android's app-info page for the tapped card.""" + try: + activity = PythonActivity.mActivity + intent = Intent("android.settings.APPLICATION_DETAILS_SETTINGS") + intent.setData(Uri.parse("package:" + package)) + activity.startActivity(intent) + settings_status.update(ok=True, package=package, error=None) + except Exception as exc: + Logger.exception("Packages: Could not open app settings") + settings_status.update(ok=False, package=package, error=str(exc)) + Clock.schedule_once(show_settings_error) + + +def show_settings_error(_): + package_ui.ids.status.text = "Could not open app settings" + +# open_app_settings("me.herethere.pythonhere") +``` + +## Load app icons + +Use `PackageManager` to get each app's icon and display it in Kivy. We'll cache the icons to keep scrolling smooth. + +```{code-cell} ipython3 +%%there +from io import BytesIO +from kivy.core.image import Image as CoreImage + +Bitmap = autoclass("android.graphics.Bitmap") +BitmapConfig = autoclass("android.graphics.Bitmap$Config") +CompressFormat = autoclass("android.graphics.Bitmap$CompressFormat") +Canvas = autoclass("android.graphics.Canvas") +ByteArrayOutputStream = autoclass("java.io.ByteArrayOutputStream") + +icon_textures = {} # Reuse icons when a card appears again. +icon_errors = {} + + +def get_app_icon(package): + if package not in icon_textures and package not in icon_errors: + try: + drawable = pm.getApplicationIcon(package) + if drawable is None: # The optional mock has no real icons. + icon_errors[package] = "No Android icon" + return None + bitmap = Bitmap.createBitmap(64, 64, BitmapConfig.ARGB_8888) + stream = ByteArrayOutputStream() + try: + drawable.setBounds(0, 0, 64, 64) + drawable.draw(Canvas(bitmap)) + bitmap.compress(CompressFormat.PNG, 100, stream) + png = bytes(value & 0xFF for value in stream.toByteArray()) + finally: + stream.close() + bitmap.recycle() + icon_textures[package] = CoreImage(BytesIO(png), ext="png").texture + except Exception as exc: + Logger.exception(f"Packages: Icon unavailable for {package}") + icon_errors[package] = str(exc) + return icon_textures.get(package) +``` + +## Create app cards + +Each card will show an app's icon, name, package ID, version, and installation date. + +We'll use Kivy's `RecycleView` to make the list scrollable. Tap a card to open **App info**. + +```{code-cell} ipython3 +%%there +# Appearance is defined in the KV cell below. +class InstallerOption(SpinnerOption): + pass + + +class CardLabel(Label): + pass + +class InstallerCard(ButtonBehavior, BoxLayout): + title = StringProperty("") + package = StringProperty("") + initials = StringProperty("") + icon_texture = ObjectProperty(None, allownone=True) + summary = StringProperty("") + installed_text = StringProperty("") + + def on_package(self, *_): + # RecycleView calls this when the card is assigned another app. + self.icon_texture = get_app_icon(self.package) if self.package else None + + def on_release(self): + open_app_settings(self.package) +``` + +## Add an installer dropdown + +Create a dropdown with **All apps** and the available installers. Show the number of apps next to each option. + +```{code-cell} ipython3 +%%there +installer_options = {f"All apps ({len(apps)})": None} +for installer in installers: + name = installer["label"] + matching_names = [item for item in installers if item["label"] == name] + if len(matching_names) > 1: + name += f" [{installer['package']}]" + option = f"{name} ({installer['count']})" + installer_options[option] = installer["package"] +``` + +## Filter apps by installer + +Update the app list whenever an installer is selected from the dropdown. + +```{code-cell} ipython3 +%%there +# Called when the dropdown selection changes. +def render_packages(*_): + installer = installer_options[package_ui.ids.installer.text] + if installer is None: + matching_apps = apps + source_text = "All recorded install sources" + else: + matching_apps = apps_by_installer.get(installer, []) + source_text = installer or "Installer unknown" + package_ui.ids.source.text = source_text + count_text = f"{len(matching_apps)} apps" + package_ui.ids.status.text = ( + f"Demo data / {count_text}" if getattr(pm, "is_demo", False) else count_text + ) + cards = [] + for row in matching_apps: + detail = package_details.get(row["package"], {}) + summary = "System app" if row["system"] else "App" + if detail.get("version"): + summary += " / v" + detail["version"] + installed = detail.get("installed") + if installed: + installed_text = "Installed on " + installed + else: + installed_text = "Install date unavailable" + cards.append({ + "title": row["label"], + "package": row["package"], + "initials": row["label"][:2].upper(), + "summary": summary, + "installed_text": installed_text, + }) + package_ui.ids.results.data = cards + package_ui.ids.results.scroll_y = 1 +``` + +## Build the Android interface + +Use Kivy's KV language for the dropdown, scrollable cards, colors, and layout. + +```{code-cell} ipython3 +%%there kv -c +#:import dp kivy.metrics.dp +#:import rgba kivy.utils.get_color_from_hex + +# Shared text style keeps individual labels short. +: + font_size: '14sp' + color: rgba('#BDCCE3') + halign: 'left' + valign: 'middle' + text_size: self.size + shorten: True + shorten_from: 'right' + +: + height: dp(54) + font_size: '17sp' + halign: 'left' + padding: dp(18), 0 + text_size: self.width - dp(36), None + background_normal: '' + background_down: '' + background_color: rgba('#1F4D52') if self.state == 'down' else rgba('#171F2E') + color: rgba('#E0F0FF') + +: + orientation: 'vertical' + padding: dp(16) + spacing: dp(6) + size_hint_y: None + height: dp(164) + canvas.before: + Color: + rgba: rgba('#1F404A') if self.state == 'down' else rgba('#171F2E') + RoundedRectangle: + pos: self.pos + size: self.size + radius: [dp(16)] + BoxLayout: + size_hint_y: None + height: dp(44) + spacing: dp(12) + FloatLayout: + size_hint_x: None + width: dp(44) + Image: + texture: root.icon_texture + allow_stretch: True + size_hint: None, None + size: dp(40), dp(40) + pos_hint: {'center_x': 0.5, 'center_y': 0.5} + opacity: 1 if root.icon_texture else 0 + CardLabel: + text: root.initials if not root.icon_texture else '' + font_size: '20sp' + bold: True + color: rgba('#1AE6BD') + halign: 'center' + pos_hint: {'center_x': 0.5, 'center_y': 0.5} + CardLabel: + text: root.title + font_size: '21sp' + bold: True + color: 1, 1, 1, 1 + CardLabel: + text: root.package + font_size: '12sp' + color: rgba('#8FA8C9') + size_hint_y: None + height: dp(20) + CardLabel: + text: root.summary + font_size: '12sp' + color: rgba('#1AE6BD') + size_hint_y: None + height: dp(20) + CardLabel: + text: root.installed_text + valign: 'top' + max_lines: 2 + +BoxLayout: + orientation: 'vertical' + padding: dp(18), dp(14) + spacing: dp(10) + canvas.before: + Color: + rgba: rgba('#090D16') + Rectangle: + pos: self.pos + size: self.size + Spinner: + id: installer + font_size: '18sp' + size_hint_y: None + height: dp(58) + background_normal: '' + background_color: rgba('#171F2E') + color: rgba('#1AE6BD') + Label: + id: source + font_size: '11sp' + color: rgba('#8FA8C9') + halign: 'left' + text_size: self.size + valign: 'middle' + size_hint_y: None + height: dp(22) + shorten: True + shorten_from: 'right' + Label: + id: status + font_size: '18sp' + bold: True + halign: 'left' + text_size: self.size + size_hint_y: None + height: dp(28) + RecycleView: + id: results + viewclass: 'InstallerCard' + do_scroll_x: False + RecycleBoxLayout: + default_size: None, dp(164) + default_size_hint: 1, None + size_hint_y: None + height: self.minimum_height + orientation: 'vertical' + spacing: dp(10) +``` + +## Show the browser on the phone + +Browse installed apps, check their versions and installation dates, and filter them by installer. Tap an app to open its **App info** screen, then use Android Back to return. + +```{code-cell} ipython3 +%%there +# Read app versions and install dates. +package_details = {} +package_detail_errors = [] + +for package in packages: + name = str(package.packageName) + try: + installed = "" + if package.firstInstallTime: + installed = datetime.fromtimestamp( + package.firstInstallTime / 1000 + ).strftime("%Y-%m-%d") + package_details[name] = { + "version": str(package.versionName or ""), + "installed": installed, + } + except Exception as exc: + Logger.warning(f"Packages: Details unavailable for {name}: {exc}") + package_detail_errors.append({"package": name, "error": str(exc)}) + +print(next(iter(package_details.items()))) +print("Errors:", package_detail_errors) +``` + +```{code-cell} ipython3 +%%there +package_ui = root +spinner = package_ui.ids.installer +spinner.option_cls = InstallerOption +spinner.values = list(installer_options) + +spinner.text = spinner.values[0] # All apps +spinner.bind(text=render_packages) +render_packages() +``` + +## Preview the result + +Take a screenshot of the Android screen and display it here in Jupyter. + +```{code-cell} ipython3 +%there -d 1 screenshot -w 200 +``` diff --git a/examples/litert.md b/examples/litert.md new file mode 100644 index 0000000..b60ef3e --- /dev/null +++ b/examples/litert.md @@ -0,0 +1,137 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# On-device AI with LiteRT + +PythonHere bundles the +[LiteRT-LM](https://github.com/google-ai-edge/LiteRT-LM) Python library in its +Android app, so `.litertlm` models can run directly on the device. After a +model has been downloaded, inference does not require a network connection. + +PythonHere also provides +[model helpers](https://github.com/b3b/pythonhere/tree/master/pythonhere/ml_here) +for managing model storage and downloading model files from Hugging Face. +This example covers every public helper, then loads a small language model and +generates text with LiteRT-LM. Refer to the LiteRT-LM documentation for its +full inference API, including sampling, streaming, and benchmarking. + +For an interactive vision-language example using the Android camera, see the +[LiteRT multimodal lab](litert_multimodal_lab.md), the companion notebook for +the video *Run multimodal AI on Android with Python and LiteRT*. + +## Connect to PythonHere + +Load the Jupyter extension and connect to a running PythonHere app: + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +## Inspect model storage + +`models_directory()` returns PythonHere's platform-specific model directory. +`model_path()` builds the managed path for a particular Hugging Face model, +and `discover_models()` lists models already present on the device. + +```{code-cell} ipython3 +%%there +from pprint import pprint as pp +from ml_here import ( + discover_models, + download_hf_model, + model_path, + models_directory, + require_model, +) + +MODEL_REPO = "litert-community/SmolLM2-135M-Instruct" +MODEL_FILE = "SmolLM2_135M_Instruct.litertlm" + +print(f"Model directory: {models_directory(create=True)}") +print(f"Managed path: {model_path(MODEL_REPO, MODEL_FILE)}") +print("Available LiteRT-LM models:") +pp(discover_models()) +``` + +## Download the model + +`download_hf_model()` downloads the model into its managed path. Downloads +can be resumed, and an existing verified file is reused. Because downloading +may take time, this cell runs on a worker so the Android UI stays responsive. + +```{code-cell} ipython3 +%%there --worker +def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + +downloaded_path = download_hf_model( + repo_id=MODEL_REPO, + filename=MODEL_FILE, + progress=report_progress, +) + +print(f"\nDownloaded model: {downloaded_path}") +``` + +`require_model()` returns the model path if the file is available and raises +`FileNotFoundError` otherwise. Discover the device again to confirm that the +downloaded model is now included: + +```{code-cell} ipython3 +%%there +model_file = require_model(MODEL_REPO, MODEL_FILE) +print(f"Required model: {model_file}") +print("Available LiteRT-LM models:") +pp(discover_models()) +``` + +## Load the model + +Model loading and inference can block the app's UI thread, so they also run +with `%%there --worker`. + +```{code-cell} ipython3 +%%there --worker +import litert_lm + +engine = litert_lm.Engine(model_file) +pp(engine) +``` + +## Generate text + +Create a conversation and send a prompt. The model runs locally in the +PythonHere app, and only the generated response is returned to Jupyter. + +```{code-cell} ipython3 +%%there --worker +with engine.create_conversation( + max_output_tokens=128, +) as conversation: + response = conversation.send_message( + "What is the Kivy framework? Answer in one short paragraph." + ) + pp(response["content"][0]["text"]) +``` + +## Clean up + +Close the engine to release its native resources when it is no longer needed: + +```{code-cell} ipython3 +%%there --worker +engine.close() +``` diff --git a/examples/litert_evals/README.md b/examples/litert_evals/README.md new file mode 100644 index 0000000..81c1019 --- /dev/null +++ b/examples/litert_evals/README.md @@ -0,0 +1,36 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Benchmarks with Pydantic Evals + +Companion notebooks for the [YouTube video](https://youtu.be/CSwZkyGWrhU). + +Test a model's Python skills from Jupyter, with inference running locally on +Android through PythonHere. Use Pydantic Evals to run a Python quiz, check +answers, and report results, then build custom evaluators for code-reasoning +tasks and programming challenges. For longer experiments, Task Runner generates +answers in the background on Android so you can fetch and evaluate them later. + +## Notebooks + +1. [Python quiz](quiz.md) +2. [CruxEval](cruxeval.md) +3. [LeetCode](leetcode.md) + +## Resources + +- [Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/) +- [LiteRT-LM](https://github.com/google-ai-edge/LiteRT-LM) +- [Qwen2.5-Coder-3B-Instruct (LiteRT-LM)](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct) +- [CruxEval dataset](https://huggingface.co/datasets/cruxeval-org/cruxeval) +- [LeetCode dataset](https://huggingface.co/datasets/newfacade/LeetCodeDataset) diff --git a/examples/litert_evals/cruxeval.md b/examples/litert_evals/cruxeval.md new file mode 100644 index 0000000..c2892f7 --- /dev/null +++ b/examples/litert_evals/cruxeval.md @@ -0,0 +1,407 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# CruxEval + +Companion notebook for the video [*Benchmarking Local AI on Android with PythonHere and Pydantic Evals*](https://youtu.be/CSwZkyGWrhU). + +Ask a model to predict Python function outputs from the +[CruxEval dataset](https://huggingface.co/datasets/cruxeval-org/cruxeval). +Generate answers in the background on Android, then score them locally with +[Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/). + +## Connect and configure + +```{code-cell} ipython3 +# %pip install pydantic-evals datasets +``` + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +We use the [LiteRT-LM version of Qwen2.5-Coder-3B-Instruct](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct) +with greedy decoding (`top_k=1`), seed 42, +and a 128-token answer limit. `%there put` copies the run name and settings +to the device. + +`LIMIT=None` selects all 800 cases; set it to `3` for a short run. Reuse +`RUN_NAME` to resume, or choose a new name when changing the model, settings, +or selected cases. `REVISION` pins the dataset version. + +```{code-cell} ipython3 +import os +RUN_NAME = "cruxeval-qwen-direct-greedy-full-001" +LIMIT = None # All cases. +REVISION = "b96af0450242eb4da433032b90998f25588a5d0f" +settings = { + "model_repo": "litert-community/Qwen2.5-Coder-3B-Instruct", + "model_file": "Qwen2.5_Coder_3B_It.litertlm", + "sampler": {"temperature": 1.0, "top_p": 1.0, "top_k": 1, "seed": 42}, + "max_output_tokens": 128, +} +hf_token = os.environ.get("HF_TOKEN") + +%there put RUN_NAME +%there put settings +%there put hf_token +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from ml_here import download_hf_model, require_model + +try: + model = require_model(settings["model_repo"], settings["model_file"]) +except FileNotFoundError: + def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + model = download_hf_model( + repo_id=settings["model_repo"], + filename=settings["model_file"], + token=hf_token, + progress=report_progress, + ) + +print(model) +``` + +## Load dataset and build prompts + +Each problem provides a function, an input, and an expected output. We use the +[CruxEval-O direct prompt](https://github.com/facebookresearch/cruxeval/blob/main/prompts.py) +to ask for the output; the expected answer stays local for scoring. + +```{code-cell} ipython3 +import ast +from datasets import load_dataset +from pprint import pprint as pp + +rows = load_dataset("cruxeval-org/cruxeval", revision=REVISION, split="test") +if LIMIT is not None: + rows = rows.select(range(LIMIT)) +problems = [dict(row) for row in rows] +assert len({p["id"] for p in problems}) == len(problems) +for p in problems: + ast.literal_eval(p["output"]) +pp(f"Selected {len(problems)} cases") +``` + +```{code-cell} ipython3 +def make_crux_prompt(inputs): + code, input = inputs["code"], inputs["input"] + instructions = ( + "You are given a Python function and an assertion containing an input " + "to the function. Complete the assertion with a literal (no unsimplified " + "expressions, no function calls) containing the output when executing " + "the provided code on the given input, even if the function is incorrect " + "or incomplete. Do NOT output any extra information. Provide the full " + "assertion with the correct output in [ANSWER] and [/ANSWER] tags, " + "following the examples." + ) + + return f"""{instructions} + +[PYTHON] +def f(n): + return n +assert f(17) == ?? +[/PYTHON] +[ANSWER] +assert f(17) == 17 +[/ANSWER] + +[PYTHON] +def f(s): + return s + "a" +assert f("x9j") == ?? +[/PYTHON] +[ANSWER] +assert f("x9j") == "x9ja" +[/ANSWER] + +[PYTHON] +{code} +assert f({input}) == ?? +[/PYTHON] +[ANSWER] +""" +``` + +```{code-cell} ipython3 +tasks = [{"id": p["id"], "prompt": make_crux_prompt(p)} for p in problems] +print(tasks[0]["prompt"]) +``` + +## Start/resume answers generation run + +`TaskRunner` saves answers on the device and continues after the notebook +disconnects. Reopening the same run resumes unfinished tasks. The engine is +shared across tasks, with a fresh conversation for each answer. + +```{code-cell} ipython3 +%there put tasks +``` + +```{code-cell} ipython3 +%%there +from tasks_here import TaskRunner, TaskRunExistsError + +try: + crux_runner = TaskRunner.create(RUN_NAME, max_attempts=3, metadata=settings) +except TaskRunExistsError: + crux_runner = TaskRunner.open(RUN_NAME) +if crux_runner.metadata != settings: + raise ValueError("Device settings differ; choose a new RUN_NAME") +existing = [r["task"] for r in crux_runner.results()] +if existing and existing != tasks: + raise ValueError("Device tasks differ; choose a new RUN_NAME") +if not existing: + crux_runner.add(tasks) +print(crux_runner.status()) +``` + +```{code-cell} ipython3 +%%there +import litert_lm +from ml_here import require_model + +def crux_setup(): + global crux_engine + if globals().get("crux_engine") is not None: + raise RuntimeError("Close previous crux_engine using the last cell before resuming") + crux_engine = litert_lm.Engine( + require_model(settings["model_repo"], settings["model_file"]), + backend=litert_lm.Backend.GPU(), enable_benchmark=True, + ) + return crux_engine + +def crux_execute(task, engine): + with engine.create_conversation( + sampler_config=litert_lm.SamplerConfig(**settings["sampler"]), + max_output_tokens=settings["max_output_tokens"], + ) as conversation: + response = conversation.send_message(task["prompt"]) + try: + info = conversation.get_benchmark_info() + benchmark = {k: getattr(info, k) for k in ( + "init_time_in_second", "time_to_first_token_in_second", + "last_prefill_token_count", "last_prefill_tokens_per_second", + "last_decode_token_count", "last_decode_tokens_per_second", + )} + benchmark_error = None + except Exception as exc: + benchmark, benchmark_error = None, str(exc) + return { + "output": "".join(b["text"] for b in response["content"] if "text" in b), + "benchmark": benchmark, "benchmark_error": benchmark_error, + } + +if not crux_runner.is_running(): + crux_runner.start(crux_execute, setup=crux_setup) +print(crux_runner.status()) +``` + +## Check progress and fetch the results + +You can fetch and score completed answers while generation continues. After +reconnecting, rerun the configuration and run-opening cells to access the saved +run; there is no need to start generation again just to retrieve answers. + +```{code-cell} ipython3 +%there get crux_runner.status() +``` + +```{code-cell} ipython3 +results = %there get crux_runner.results() +``` + +```{code-cell} ipython3 +pp(results[-1]) +``` + +## Score fetched answers locally + +Score `results` directly. TaskRunner keeps results on the phone, so you can +fetch them again later. No model calls or generated-code execution during scoring. + +We build a Pydantic Evals `Dataset` from completed answers and use a custom +`Evaluator` to extract each predicted Python literal and compare its value. +The report separates incorrect values from invalid answers that cannot be +parsed, such as unfinished literals or extra explanation. + +`generation_s` is elapsed time measured by TaskRunner around the final +`crux_execute` call on the device, including conversation setup and cleanup. +Engine loading and earlier retries are excluded. `decode_tokens_s` is the +decoding speed reported by LiteRT's benchmark. + +```{code-cell} ipython3 +import ast +import io +import tokenize +from dataclasses import dataclass + +from pydantic_evals import Case, Dataset, increment_eval_metric +from pydantic_evals.evaluators import Evaluator, EvaluationReason + + +def extract_crux_output(text): + # LiteRT returns the stop marker as text; upstream generation strips it. + candidate = text.split("[/ANSWER]", 1)[0] + if "[ANSWER]" in candidate: + candidate = candidate.split("[ANSWER]", 1)[1] + + # Find the assertion separator without splitting == inside quoted strings. + if candidate.strip().startswith("assert "): + lines = candidate.splitlines(keepends=True) + for token in tokenize.generate_tokens(io.StringIO(candidate).readline): + if token.type == tokenize.OP and token.string == "==": + row, column = token.end + candidate = "".join(lines[row - 1:])[column:] + break + + return ast.literal_eval(candidate.strip()) + + +@dataclass +class CruxLiteralMatch(Evaluator): + def evaluate(self, ctx): + expected = ast.literal_eval(ctx.expected_output) + + try: + actual = extract_crux_output(ctx.output) + except (SyntaxError, ValueError, TypeError, RecursionError, tokenize.TokenError) as exc: + return { + "passed": EvaluationReason(False, f"Invalid answer: {exc}"), + "failure": "invalid", + } + + if actual != expected: + return { + "passed": EvaluationReason( + False, + f"actual={actual!r}, expected={expected!r}", + ), + "failure": "incorrect", + } + + return {"passed": True} +``` + +```{code-cell} ipython3 +from collections import Counter +from pydantic_evals.evaluators import ReportEvaluator, ReportEvaluatorContext +from pydantic_evals.reporting.analyses import TableResult + +@dataclass +class CruxSummary(ReportEvaluator): + def evaluate(self, ctx: ReportEvaluatorContext): + counts = Counter() + + for case in ctx.report.cases: + assertion = case.assertions["passed"] + + if assertion.value: + counts["passed"] += 1 + else: + failure = case.labels.get("failure") + if failure is None: + raise ValueError( + f"Missing failure label for {case.name}" + ) + counts[failure.value] += 1 + + total = len(ctx.report.cases) + + return TableResult( + title="CruxEval results", + columns=["Scored", "Passed", "Pass rate", "Incorrect", "Invalid"], + rows=[[ + total, + counts["passed"], + f"{counts['passed'] / total:.1%}" if total else "N/A", + counts["incorrect"], + counts["invalid"], + ]], + ) +``` + +```{code-cell} ipython3 +answers = {r["id"]: r["result"]["output"] for r in results if r["status"] == "done"} +completed = {r["id"]: r for r in results if r["status"] == "done"} + +def saved_answer(case_id): + record = completed[case_id] + if record.get("duration") is not None: + increment_eval_metric("generation_s", record["duration"]) + benchmark = record["result"].get("benchmark") or {} + speed = benchmark.get("last_decode_tokens_per_second") + if speed is not None: + increment_eval_metric("decode_tokens_s", speed) + return answers[case_id] + +dataset = Dataset( + name="cruxeval_o_literal_demo", + cases=[Case(name=p["id"], inputs=p["id"], expected_output=p["output"]) + for p in problems if p["id"] in answers], + evaluators=[CruxLiteralMatch()], + report_evaluators=[CruxSummary()], +) +if not dataset.cases: + raise RuntimeError("No completed answers; check device status/errors") +report = await dataset.evaluate(saved_answer, max_concurrency=1) + +#report.print(include_durations=False, include_averages=True, include_reasons=True) +from dataclasses import replace +# Show the first eight cases; CruxSummary above covers all scored cases. +preview = replace(report, cases=report.cases[:8]) +preview.print(include_durations=False, include_averages=False, include_analyses=True, include_reasons=True) +``` + +```{code-cell} ipython3 +from rich.console import Console +from rich.table import Table +from rich.text import Text + +invalid = [ + c for c in report.cases + if c.labels.get("failure") is not None + and c.labels["failure"].value == "invalid" +] + +table = Table(title="Invalid answers") +table.add_column("Case", style="dim") +table.add_column("Output", overflow="fold") + +for case in invalid: + table.add_row( + case.name, + Text(repr(case.output)), + ) + +Console().print(table) +``` + +## Close the engine + +```{code-cell} ipython3 +%%there --worker +if globals().get("crux_engine"): + crux_engine.close() + crux_engine = None +``` diff --git a/examples/litert_evals/leetcode.md b/examples/litert_evals/leetcode.md new file mode 100644 index 0000000..fc63cb2 --- /dev/null +++ b/examples/litert_evals/leetcode.md @@ -0,0 +1,414 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# LeetCode + +Companion notebook for the video [*Benchmarking Local AI on Android with PythonHere and Pydantic Evals*](https://youtu.be/CSwZkyGWrhU). + +Generate Python solutions on Android using +[newfacade/LeetCodeDataset](https://huggingface.co/datasets/newfacade/LeetCodeDataset), +then run the dataset's tests locally with +[Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/). + +## Connect and configure + +```{code-cell} ipython3 +# %pip install pydantic-evals datasets +``` + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +We use the [LiteRT-LM version of Qwen2.5-Coder-3B-Instruct](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct) +with greedy decoding (`top_k=1`), seed 42, +and a 1,000-token answer limit. `%there put` copies the run name and settings +to the device. + +`LIMIT=None` selects the full test split; set it to `3` for a short run. +Reuse `RUN_NAME` to resume, or choose a new name when changing settings or +selected cases. `REVISION` pins the dataset version. + +```{code-cell} ipython3 +import os +RUN_NAME = "leetcode-qwen-greedy-full-001" +LIMIT = None # All cases. +REVISION = "215604aeed660029df7de2fea5a4d7b6ed476a08" +settings = { + "model_repo": "litert-community/Qwen2.5-Coder-3B-Instruct", + "model_file": "Qwen2.5_Coder_3B_It.litertlm", + "sampler": {"temperature": 1.0, "top_p": 1.0, "top_k": 1, "seed": 42}, + "max_output_tokens": 1000, + "dataset_revision": REVISION, +} +hf_token = os.environ.get("HF_TOKEN") + +%there put RUN_NAME +%there put settings +%there put hf_token +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from ml_here import download_hf_model, require_model + +try: + model = require_model(settings["model_repo"], settings["model_file"]) +except FileNotFoundError: + def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + model = download_hf_model( + repo_id=settings["model_repo"], + filename=settings["model_file"], + token=hf_token, + progress=report_progress, + ) + +print(model) +``` + +## Load dataset and build prompts + +We send each problem's original `query` to the model. Tests stay local and +are used only for scoring. Inspect one prompt and its tests below. + +```{code-cell} ipython3 +from datasets import load_dataset +from pprint import pprint as pp + +rows = load_dataset("newfacade/LeetCodeDataset", revision=REVISION, split="test") +if LIMIT is not None: + rows = rows.select(range(LIMIT)) +problems = [dict(row) for row in rows] +assert problems, "No cases selected" +assert len({p["task_id"] for p in problems}) == len(problems) +pp(f"Selected {len(problems)} cases") +``` + +```{code-cell} ipython3 +print(problems[0]["query"]) +``` + +```{code-cell} ipython3 +print(problems[0]["test"]) +``` + +```{code-cell} ipython3 +tasks = [ + {"id": p["task_id"], "prompt": p["query"], + "metadata": {"difficulty": p["difficulty"].lower()}} + for p in problems +] +``` + +## Start/resume answers generation run + +`TaskRunner` saves answers on the device and continues after the notebook +disconnects. Starting the same named run processes unfinished tasks. The engine +is shared across tasks, with a fresh conversation for each solution. + +```{code-cell} ipython3 +%there put tasks +``` + +```{code-cell} ipython3 +%%there +from tasks_here import TaskRunner, TaskRunExistsError + +try: + leetcode_runner = TaskRunner.create(RUN_NAME, max_attempts=3, metadata=settings) +except TaskRunExistsError: + leetcode_runner = TaskRunner.open(RUN_NAME) + +existing = [r["task"] for r in leetcode_runner.results()] +if not existing: + leetcode_runner.add(tasks) + +``` + +```{code-cell} ipython3 +%%there +import litert_lm +from ml_here import require_model + +def leetcode_setup(): + global leetcode_engine + if globals().get("leetcode_engine") is not None: + raise RuntimeError("Close previous leetcode_engine using the last cell before resuming") + leetcode_engine = litert_lm.Engine( + require_model(settings["model_repo"], settings["model_file"]), + backend=litert_lm.Backend.GPU(), enable_benchmark=True, + ) + return leetcode_engine + +def leetcode_execute(task, engine): + with engine.create_conversation( + sampler_config=litert_lm.SamplerConfig(**settings["sampler"]), + max_output_tokens=settings["max_output_tokens"], + ) as conversation: + response = conversation.send_message(task["prompt"]) + try: + info = conversation.get_benchmark_info() + benchmark = {k: getattr(info, k) for k in ( + "init_time_in_second", "time_to_first_token_in_second", + "last_prefill_token_count", "last_prefill_tokens_per_second", + "last_decode_token_count", "last_decode_tokens_per_second", + )} + benchmark_error = None + except Exception as exc: + benchmark, benchmark_error = None, str(exc) + return { + "output": "".join(b["text"] for b in response["content"] if "text" in b), + "benchmark": benchmark, "benchmark_error": benchmark_error, + } + +if not leetcode_runner.is_running(): + leetcode_runner.start(leetcode_execute, setup=leetcode_setup) +print(leetcode_runner.status()) +``` + +## Check progress and fetch the results + +Completed answers can be fetched and scored while generation continues. +After reconnecting, rerun the configuration and run-opening cells to retrieve +saved answers without starting generation again. + +```{code-cell} ipython3 +%there get leetcode_runner.status() +``` + +```{code-cell} ipython3 +results = %there get leetcode_runner.results() +``` + +```{code-cell} ipython3 +pp(results[-1]) +``` + +## Score fetched answers locally + +We build a Pydantic Evals `Dataset` from completed answers. The custom +`LeetCodePass` evaluator extracts Python code and runs each solution with its +tests in a local subprocess, with a 10-second timeout. The difficulty summary +separates passes, assertion failures, invalid answers, syntax errors, runtime +errors, and timeouts. + +`generation_s` is TaskRunner's elapsed time around the final `leetcode_execute` +call on the device, including conversation setup and cleanup but excluding +engine loading and earlier retries. `decode_tokens_s` is the decoding speed +reported by LiteRT's benchmark. + +```{code-cell} ipython3 +import sys +import json +import re +import subprocess +from dataclasses import dataclass + +from pydantic_evals import Case, Dataset, increment_eval_metric +from pydantic_evals.evaluators import Evaluator, EvaluationReason + + +def extract_python_code(text): + fences = re.findall(r"```([^\n`]*)\n(.*?)```", text, flags=re.DOTALL) + if fences: + if len(fences) != 1 or fences[0][0].strip().lower() not in {"", "python", "py"}: + raise ValueError("Expected one Python code block") + code = fences[0][1].strip() + elif "```" in text: + raise ValueError("Incomplete code block") + else: + code = text.strip() + if not code: + raise ValueError("Empty code") + return code + + +def execute_problem(problem, code, timeout): + program = "\n".join([ + problem["prompt"], code, problem["test"], + f"check({problem['entry_point']})", + ]) + # Report success only after the complete program and tests return. + harness = f''' +import json +try: + exec(compile({program!r}, "", "exec"), {{}}) +except SyntaxError as exc: + result = {{"outcome": "syntax_error", "error": str(exc)}} +except AssertionError as exc: + result = {{"outcome": "test_failed", "error": "AssertionError: " + str(exc)}} +except BaseException as exc: + result = {{"outcome": "runtime_error", "error": type(exc).__name__ + ": " + str(exc)}} +else: + result = {{"outcome": "passed"}} +print("__TEST_RESULT__" + json.dumps(result)) +''' + try: + process = subprocess.run( + [sys.executable, "-I", "-"], input=harness, + text=True, capture_output=True, timeout=timeout, + ) + except subprocess.TimeoutExpired: + return {"outcome": "timeout", "error": f"Exceeded {timeout:g} seconds"} + for line in reversed(process.stdout.splitlines()): + if line.startswith("__TEST_RESULT__"): + return json.loads(line[len("__TEST_RESULT__"):]) + return {"outcome": "runtime_error", "error": process.stderr.strip() or "Tests did not finish"} + + +@dataclass +class LeetCodePass(Evaluator): + problems: dict + timeout: float = 10.0 + + def evaluate(self, ctx): + try: + code = extract_python_code(ctx.output) + except ValueError as exc: + return { + "passed": EvaluationReason(False, str(exc)), + "failure": "invalid", + } + + problem = self.problems[ctx.inputs] + result = execute_problem(problem, code, self.timeout) + if result["outcome"] == "passed": + return {"passed": True} + return { + "passed": EvaluationReason(False, result.get("error") or result["outcome"]), + "failure": result["outcome"], + } +``` + +```{code-cell} ipython3 +from collections import Counter +from pydantic_evals.evaluators import ReportEvaluator, ReportEvaluatorContext +from pydantic_evals.reporting.analyses import TableResult + + +@dataclass +class LeetCodeSummary(ReportEvaluator): + def evaluate(self, ctx: ReportEvaluatorContext): + categories = ["passed", "test_failed", "invalid", "syntax_error", + "runtime_error", "timeout"] + rows = [] + for difficulty in ["all", "easy", "medium", "hard"]: + cases = [c for c in ctx.report.cases + if difficulty == "all" or c.metadata["difficulty"] == difficulty] + if not cases: + continue + counts = Counter() + for case in cases: + if case.assertions["passed"].value: + counts["passed"] += 1 + else: + counts[case.labels["failure"].value] += 1 + rows.append([difficulty, len(cases), + *[round(100 * counts[name] / len(cases), 1) + for name in categories]]) + return TableResult( + title="LeetCode results by difficulty", + columns=["Difficulty", "N", "Passed %", "Assertion %", "Invalid %", + "Syntax %", "Runtime %", "Timeout %"], + rows=rows, + ) +``` + +```{code-cell} ipython3 +problems_by_id = {p["task_id"]: p for p in problems} +completed = {r["id"]: r for r in results if r["status"] == "done"} +for case_id, record in completed.items(): + if case_id not in problems_by_id or record["task"]["prompt"] != problems_by_id[case_id]["query"]: + raise ValueError("Fetched tasks differ from selected dataset") + +def saved_answer(case_id): + record = completed[case_id] + if record.get("duration") is not None: + increment_eval_metric("generation_s", record["duration"]) + benchmark = record["result"].get("benchmark") or {} + speed = benchmark.get("last_decode_tokens_per_second") + if speed is not None: + increment_eval_metric("decode_tokens_s", speed) + return record["result"]["output"] + +dataset = Dataset( + name="pythonhere-leetcode", + cases=[Case(name=p["task_id"], inputs=p["task_id"], + metadata={"difficulty": p["difficulty"].lower()}) + for p in problems if p["task_id"] in completed], + evaluators=[LeetCodePass(problems_by_id)], + report_evaluators=[LeetCodeSummary()], +) +if not dataset.cases: + raise RuntimeError("No completed answers; check device status/errors") +report = await dataset.evaluate(saved_answer, max_concurrency=1) + +# report.print(include_durations=False, include_averages=True, include_reasons=True) +from dataclasses import replace +# Show the first eight cases; LeetCodeSummary covers all scored cases. +preview = replace(report, cases=report.cases[:8]) +preview.print(include_durations=False, include_averages=False, include_analyses=True, include_reasons=True) +``` + +Show bad answers that are missing `class Solution`. + +```{code-cell} ipython3 +from rich.console import Console +from rich.table import Table +from rich.text import Text + +weird = [ + r["result"]["output"] + for r in results + if r["status"] == "done" + and "class Solution" not in r["result"]["output"] +] + +table = Table(title=f"Unexpected outputs ({len(weird)})") +table.add_column("#", style="dim", justify="right") +table.add_column("Output", overflow="fold") + +for r in results: + if r["status"] == "done": + s = r["result"]["output"] + if "class Solution" not in s: + table.add_row(r["id"], Text(repr(s[:300]))) + +Console().print(table) +``` + +Another bad answer from the video starts with `class Solution`, but keeps +adding nested loops until the output is cut off. Show that problem's saved answer: + +```{code-cell} ipython3 +example_id = "find-the-lexicographically-largest-string-from-the-box-i" +if example_id in completed: + print(completed[example_id]["result"]["output"]) +else: + print(f"No saved answer for {example_id} in this run.") +``` + +## Close the engine + +```{code-cell} ipython3 +%%there --worker +if globals().get("leetcode_engine") is not None: + leetcode_engine.close() + leetcode_engine = None +``` diff --git a/examples/litert_evals/quiz.md b/examples/litert_evals/quiz.md new file mode 100644 index 0000000..053a335 --- /dev/null +++ b/examples/litert_evals/quiz.md @@ -0,0 +1,286 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Quiz + +Companion notebook for the video [*Benchmarking Local AI on Android with PythonHere and Pydantic Evals*](https://youtu.be/CSwZkyGWrhU). + +Run a six-question Python quiz against a model on your Android device, then +score its answers locally with [Pydantic Evals](https://pydantic.dev/docs/ai/evals/evals/). + +## Connect and configure + +```{code-cell} ipython3 +# %pip install pydantic-evals +``` + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +```{code-cell} ipython3 +from herethere.everywhere import ConnectionConfig +from herethere.there import Client + +client = Client() +await client.connect(ConnectionConfig.load(path="there.env", prefix="there")) +await client.ping() +``` + +We use the [LiteRT-LM version of Qwen2.5-Coder-3B-Instruct](https://huggingface.co/litert-community/Qwen2.5-Coder-3B-Instruct), with greedy decoding +and a 16-token answer limit. `%there put` copies these settings to the device for model loading and inference. + +```{code-cell} ipython3 +import os + +settings = { + "model_repo": "litert-community/Qwen2.5-Coder-3B-Instruct", + "model_file": "Qwen2.5_Coder_3B_It.litertlm", + "sampler": {"temperature": 1.0, "top_p": 1.0, "top_k": 1, "seed": 42}, + "max_output_tokens": 16, +} +hf_token = os.environ.get("HF_TOKEN") + +%there put settings +%there put hf_token +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from ml_here import download_hf_model, require_model +try: + model = require_model(settings["model_repo"], settings["model_file"]) +except FileNotFoundError: + def report_progress(value): + if value.percent is not None: + print(f"\rDownloading: {value.percent:.1f}%", end="", flush=True) + + model = download_hf_model( + repo_id=settings["model_repo"], + filename=settings["model_file"], + token=hf_token, + progress=report_progress, + ) + +print(model) +``` + +## Load the model + +The engine stays loaded across questions, but each answer uses a fresh +conversation so questions are answered independently. + +```{code-cell} ipython3 +%%there --worker +import litert_lm +from ml_here import require_model + +if globals().get("quiz_engine") is not None: + quiz_engine.close() +quiz_engine = None + +quiz_engine = litert_lm.Engine( + require_model(settings["model_repo"], settings["model_file"]), + backend=litert_lm.Backend.GPU(), +) + +def quiz_answer(prompt): + with quiz_engine.create_conversation( + sampler_config=litert_lm.SamplerConfig(**settings["sampler"]), + max_output_tokens=settings["max_output_tokens"], + ) as conversation: + response = conversation.send_message(prompt) + return "".join(block["text"] for block in response["content"] if "text" in block) + +print(quiz_engine) +``` + +## Define questions + +For this simple quiz, we define the questions directly in a Pydantic Evals +`Dataset`. Each `Case` contains a question, answer choices, and the expected +letter; `EqualsExpected()` scores the model's response against that letter. + +```{code-cell} ipython3 +from typing_extensions import TypedDict + +from pydantic_evals import Case, Dataset +from pydantic_evals.evaluators import EqualsExpected + + +class QuestionInputs(TypedDict): + question: str + options: dict[str, str] + + +dataset = Dataset[QuestionInputs, str, None]( + name="python-quiz", + cases=[ + Case( + name="mutable-container", + inputs={ + "question": "Which built-in type is mutable?", + "options": { + "A": "tuple", + "B": "list", + "C": "str", + "D": "int", + }, + }, + expected_output="B", + ), + Case( + name="floor-division", + inputs={ + "question": "What is the value of 7 // 2 in Python 3?", + "options": { + "A": "3.5", + "B": "4", + "C": "2", + "D": "3", + }, + }, + expected_output="D", + ), + Case( + name="list-alias", + inputs={ + "question": ( + "What does this print?\n\n" + "a = [1, 2]\n" + "b = a\n" + "b.append(3)\n" + "print(a)" + ), + "options": { + "A": "[1, 2, 3]", + "B": "[1, 2]", + "C": "[3]", + "D": "None", + }, + }, + expected_output="A", + ), + Case( + name="empty-set", + inputs={ + "question": "Which expression creates an empty set?", + "options": { + "A": "{}", + "B": "[]", + "C": "set()", + "D": "()", + }, + }, + expected_output="C", + ), + Case( + name="mutable-default", + inputs={ + "question": ( + "What does the second call print?\n\n" + "def add(x, items=[]):\n" + " items.append(x)\n" + " return items\n\n" + "add(1)\n" + "print(add(2))" + ), + "options": { + "A": "[2]", + "B": "[1, 2]", + "C": "[]", + "D": "Raises TypeError", + }, + }, + expected_output="B", + ), + Case( + name="unpacking-comprehension-315", + inputs={ + "question": ( + "In Python 3.15, what does this print?\n\n" + "groups = [[1, 2], [3]]\n" + "print([*group for group in groups])" + ), + "options": { + "A": "SyntaxError", + "B": "[[1, 2], [3]]", + "C": "[1, 2, 3]", + "D": "TypeError", + }, + }, + expected_output="C", + ), + ], + evaluators=[EqualsExpected()], +) +``` + +## Define the task + +```{code-cell} ipython3 +def build_prompt(inputs: QuestionInputs) -> str: + options = "\n".join( + f"{letter}: {inputs['options'][letter]}" + for letter in "ABCD" + ) + return ( + "Answer the Python multiple-choice question.\n" + "Exactly one option is correct.\n" + "Reply with only A, B, C, or D. Do not explain.\n\n" + f"{inputs['question'].rstrip()}\n\n" + f"{options}\n\n" + "Answer:" + ) + +async def answer_question(inputs: QuestionInputs) -> str: + prompt = build_prompt(inputs) + response = await client.get_worker(f"quiz_answer({prompt!r})") + return response.strip() +``` + +Inspect the prompt and try one question: + +```{code-cell} ipython3 +example = dataset.cases[0] +print(build_prompt(example.inputs)) +``` + +```{code-cell} ipython3 +print(repr(await answer_question(example.inputs))) +``` + +## Run and inspect + +Scoring requires the expected letter alone, ignoring surrounding whitespace. +Extra explanation counts as a failed answer. Report durations include the client round trip. + +```{code-cell} ipython3 +report = await dataset.evaluate(answer_question, max_concurrency=1) +report.print(include_input=True, include_output=True, include_expected_output=True) +``` + +## Close the model and client + +```{code-cell} ipython3 +%%there --worker +quiz_engine.close() +quiz_engine = None +``` + +```{code-cell} ipython3 +await client.disconnect() +``` diff --git a/examples/litert_multimodal_lab.md b/examples/litert_multimodal_lab.md new file mode 100644 index 0000000..e0a97af --- /dev/null +++ b/examples/litert_multimodal_lab.md @@ -0,0 +1,388 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# LiteRT multimodal lab + +Companion notebook for the video [*Run multimodal AI on Android with Python and LiteRT*](https://youtu.be/w_RZ0Y29A7I). + +## Connect to PythonHere + +```{code-cell} ipython3 +%load_ext pythonhere +%connect-there +``` + +## Show download progress + +```{code-cell} ipython3 +%%there kv +: + size_hint: .82, .82 + pos_hint: {'center_x': .5, 'center_y': .5} + + canvas: + Color: + rgba: .45, .52, .50, .16 + + Line: + width: dp(5) + circle: + self.center_x, \ + self.center_y, \ + min(self.width, self.height) * .34, \ + 0, \ + 360 + + Color: + rgba: .30, .40, .37, .95 if root.value > 0 else 0 + + Line: + width: dp(10) if root.value >= 100 else dp(9) + circle: + self.center_x, \ + self.center_y, \ + min(self.width, self.height) * .34, \ + 105, \ + 105 + 360 * min(max(root.value, 0), 100) / 100 + + Label: + text: "Ready" if root.value >= 100 else f"{root.value:3.0f}%" + font_size: min(root.width, root.height) * (.11 if root.value >= 100 else .13) + color: .25, .32, .30, .95 + center: root.center +``` + +```{code-cell} ipython3 +%%there +from kivy.properties import NumericProperty +from kivy.uix.widget import Widget + + +class DownloadProgress(Widget): + value = NumericProperty(0) + +root.clear_widgets() +progress = DownloadProgress() +root.add_widget(progress) +``` + +## Download the model + +```{code-cell} ipython3 +%%there --worker +from pprint import pprint as pp +from kivy.clock import mainthread +from ml_here import download_hf_model, require_model + +MODEL_REPO = "litert-community/SmolVLM2-500M" +MODEL_FILE = "SmolVLM2-500M.litertlm" + + +@mainthread +def update_progress(value): + progress.value = value.percent or 0.0 + + +download_hf_model( + repo_id=MODEL_REPO, + filename=MODEL_FILE, + progress=update_progress, +) + +pp(require_model(MODEL_REPO, MODEL_FILE)) +``` + +## Load the model + +```{code-cell} ipython3 +%%there --worker +import litert_lm +engine = litert_lm.Engine( + require_model(MODEL_REPO, MODEL_FILE), + backend=litert_lm.Backend.GPU(), + vision_backend=litert_lm.Backend.GPU(), + enable_benchmark=True, +) +pp(engine) +``` + +## Generate text + +### Create a streaming output view + +```{code-cell} ipython3 +%%there kv +: + size_hint: .88, .7 + pos_hint: {'center_x': .5, 'center_y': .5} + + Label: + markup: True + text: root.text + font_size: dp(21) + halign: "left" + valign: "top" + text_size: root.width, None + pos: root.pos + size: root.size +``` + +```{code-cell} ipython3 +%%there +from kivy.properties import StringProperty +from kivy.uix.widget import Widget +from kivy.clock import mainthread + + +class ModelOutput(Widget): + text = StringProperty("") + committed = StringProperty("") + newest = StringProperty("") + + @mainthread + def append_chunk(self, chunk): + self.committed += self.newest + self.newest = chunk + self.text = ( + f"[color=#E8EEF3]{self.committed}[/color]" + f"[color=#FFD343][b]{self.newest}[/b][/color]" + ) + +root.clear_widgets() +output = ModelOutput() +root.add_widget(output) +``` + +### Ask a text question + +```{code-cell} ipython3 +%%there --worker + +sampler = litert_lm.SamplerConfig( + temperature=0.7, + top_p=0.9, + top_k=40, +) + +with engine.create_conversation( + sampler_config=sampler, + max_output_tokens=128, +) as conversation: + for chunk in conversation.send_message_async( + "What is on-device AI? Give a direct answer in one short paragraph." + ): + output.append_chunk(chunk["content"][0]["text"]) + info = conversation.get_benchmark_info() + output.append_chunk("") +``` + +### Show benchmark results + +```{code-cell} ipython3 +%%there +print( + "\n\tBenchmark info for the conversation\n" + f"Init: {info.init_time_in_second:.2f}s\n" + f"TTFT: {info.time_to_first_token_in_second:.2f}s\n" + f"Prefill: {info.last_prefill_token_count} tokens " + f"@ {info.last_prefill_tokens_per_second:.1f} tok/s\n" + f"Decode: {info.last_decode_token_count} tokens " + f"@ {info.last_decode_tokens_per_second:.1f} tok/s" +) +``` + +## Describe a camera photo + +### Request camera permission + +```{code-cell} ipython3 +%%there +from threading import Event +from android.permissions import Permission, request_permission + +done = Event() +request_permission(Permission.CAMERA, lambda *_: done.set()) +done.wait() +``` + +### Preview and capture a photo + +```{code-cell} ipython3 +%%there kv +AnchorLayout: + anchor_x: "center" + anchor_y: "center" + + Camera: + id: camera + play: True + resolution: (640, 480) + fit_mode: "contain" + + size_hint: None, None + height: min(root.width, root.height * 3 / 4) + width: self.height * 4 / 3 + + canvas.before: + PushMatrix + Rotate: + angle: -90 + origin: self.center + + canvas.after: + PopMatrix +``` + +```{code-cell} ipython3 +%%there +camera = root.ids.camera +camera.play = False +``` + +```{code-cell} ipython3 +%%there +from os.path import abspath, getsize +from PIL import Image + +texture = camera.texture +image = Image.frombytes("RGBA", texture.size, texture.pixels) + +# Kivy textures use a bottom-left origin. +image = image.transpose(Image.Transpose.FLIP_TOP_BOTTOM) + +# Match the rotation applied to the Android camera preview. +image = image.rotate(-90, expand=True).convert("RGB") + +photo_path = abspath("from_camera.jpg") +image.save(photo_path, quality=90) + +print(f"Photo: {photo_path}") +print( + f"Image: {image.width} × {image.height}, " + f"{image.mode}, {getsize(photo_path) / 1024:.1f} KiB" +) +``` + +### Generate a description + +```{code-cell} ipython3 +%%there --worker +sampler = litert_lm.SamplerConfig( + temperature=0.7, + top_p=0.9, + top_k=40, +) + +with engine.create_conversation( + sampler_config=sampler, + max_output_tokens=96, +) as conversation: + response = conversation.send_message( + litert_lm.Contents.of( + "Describe the main object in this image clearly and concisely in 2-3 sentences.", + litert_lm.Content.ImageFile(absolute_path=photo_path), + ) + ) + print(response["content"][0]["text"]) +``` + +## Explore sampling variability + +### Generate responses with different temperatures and seeds + +```{code-cell} ipython3 +%%there --worker +prompt = ( + "Describe the main object in this image clearly and concisely " + "in 2-3 sentences." +) + +temperatures = [0.2, 0.5, 0.7, 1.0] +seeds = [1, 7, 42, 123, 999] + +experiment_results = [] + +for temperature in temperatures: + for seed in seeds: + sampler = litert_lm.SamplerConfig( + temperature=temperature, + top_p=0.9, + top_k=40, + seed=seed, + ) + + with engine.create_conversation( + sampler_config=sampler, + max_output_tokens=96, + ) as conversation: + response = conversation.send_message( + litert_lm.Contents.of( + prompt, + litert_lm.Content.ImageFile(absolute_path=photo_path), + ) + ) + + info = conversation.get_benchmark_info() + + experiment_results.append({ + "temperature": temperature, + "seed": seed, + "output": response["content"][0]["text"].strip(), + "ttft_s": info.time_to_first_token_in_second, + "prefill_tokens": info.last_prefill_token_count, + "prefill_tok_s": info.last_prefill_tokens_per_second, + "decode_tokens": info.last_decode_token_count, + "decode_tok_s": info.last_decode_tokens_per_second, + }) + +print(f"Done: {len(experiment_results)} runs") +``` + +### Compare the outputs + +```{code-cell} ipython3 +import pandas as pd + +experiment_results = %there get experiment_results + +df = pd.DataFrame(experiment_results) + +display( + df[ + [ + "temperature", + "seed", + "decode_tokens", + "output", + ] + ].style + .format({ + "temperature": "{:.1f}", + }) + .set_properties( + subset=["output"], + **{ + "white-space": "pre-wrap", + "text-align": "left", + }, + ) + .hide(axis="index") +) +``` + +## Clean up + +```{code-cell} ipython3 +%%there --worker +engine.close() +``` diff --git a/examples/tasks.md b/examples/tasks.md new file mode 100644 index 0000000..2f5bdcc --- /dev/null +++ b/examples/tasks.md @@ -0,0 +1,272 @@ +--- +jupytext: + text_representation: + extension: .md + format_name: myst + format_version: 0.13 + jupytext_version: 1.19.3 +kernelspec: + display_name: Python 3 (ipykernel) + language: python + name: python3 +--- + +# Durable sequential tasks + +`TaskRunner` runs tasks one at a time in the PythonHere process and persists +their inputs, results, errors, and retry state. Work continues if Jupyter +disconnects. After PythonHere restarts, completed tasks remain complete and an +interrupted task becomes runnable again. + +## Connect to PythonHere + +```{code-cell} python +%load_ext pythonhere +%connect-there +``` + +## Submit and start work + +Every task needs a unique nonempty string `id`. Tasks and returned results must +contain plain JSON-compatible values. If `"squares-example"` already exists +from an earlier attempt, use a new name or delete the old run with the +[cleanup cell](#clean-up) at the end. + +```{code-cell} python +%%there +import time + +from tasks_here import TaskRunner + + +def execute_task(task, context): + time.sleep(1) + if task["value"] == 5: + raise ValueError("Intentional example failure for value 5") + return { + "value": task["value"], + "square": task["value"] ** 2, + } + + +runner = TaskRunner.create("squares-example", max_attempts=3) +runner.add([{"id": str(value), "value": value} for value in range(1, 11)]) +runner.start(execute_task) +``` + +`start()` returns promptly while tasks run one at a time in a background thread. +The task for value `5` deliberately fails. With `max_attempts=3`, the runner +tries it three times before marking it failed; the other nine tasks still run. +Including retries, this example takes about twelve seconds. Tasks continue +running between notebook cells, so the run may already be completed when you +inspect it. + +## Inspect progress and results + +```{code-cell} python +status = %there get runner.status() +status +``` + +You can inspect results before the whole run finishes: + +```{code-cell} python +:tags: ["hide-output"] +results = %there get runner.results() +results +``` + +To wait briefly before checking progress again: + +```{code-cell} python +%%there --worker +runner.wait(timeout=1) +print(runner.status()) +``` + +This waits at most one second and returns sooner if the worker has stopped. + +## Pause and resume (optional) + +While tasks are still running, you can pause them. `pause()` lets the current +task finish, and `wait()` waits for the pause to take effect: + +```{code-cell} python +%%there --worker +runner.pause() +runner.wait() +print(runner.status()) +``` + +Resume any pending tasks with the same executor. Completed tasks are kept: + +```{code-cell} python +%%there +runner.start(execute_task) +``` + +If all tasks have already completed, there is nothing left to pause or resume. + +## Wait for completion + +Wait for all remaining work, then show the final counts. `--worker` keeps the +app's UI responsive while this cell waits: + +```{code-cell} python +%%there --worker +runner.wait() +status = runner.status() +print("State:", status["state"]) +print("Completed:", status["completed"], "of", status["total"]) +print("Failed:", status["failed"]) +``` + +Expected output: + +```text +State: completed +Completed: 9 of 10 +Failed: 1 +``` + +`wait()` returns when the worker stops. A `completed` state means all tasks +have been processed, including any that exhausted their retries; it does not +mean every task succeeded. Inspect the deliberately failed task: + +```{code-cell} python +failures = %there get runner.failed() +failures +``` + +The failed record has `id: "5"`, `attempt_count: 3`, `failure_count: 3`, +and the intentional `ValueError`. The other nine tasks have their square results. + +## Export results + +For larger results, export a JSON snapshot on the device and download the file: + +```{code-cell} python +%%there --worker +runner.export_results("task-results.json") +``` + +```{code-cell} python +%there download task-results.json ./task-results.json +``` + +Load the downloaded file in the notebook: + +```{code-cell} python +import json + +with open("task-results.json", encoding="utf-8") as f: + results = json.load(f) +``` + +The export includes all task records, including pending and failed tasks, in +submission order. Export after completion for final results, or during execution +for a snapshot. Relative paths use the device's current working directory, +which is PythonHere's upload directory by default. For large runs, exporting +and downloading a file avoids transferring all results through `%there get`. + +## Reopen after PythonHere restarts + +The task list and results are persistent, but Python callables and other runtime +objects are not. After restarting PythonHere, reconnect, recreate the executor, +open the named run, and start it again. Completed tasks are kept; only +unfinished work runs again. If all ten tasks already finished, the run stays +completed. + +In this walkthrough, all tasks have already finished. Reopening shows that +the results and the failed task survived the restart. The task that exhausted +its retries stays failed; calling `start()` does not retry it again. To try recovery of unfinished work separately, +restart the app while a fresh run is executing, then reconnect and run this cell: + +```{code-cell} python +%%there +import time + +from tasks_here import TaskRunner + + +def execute_task(task, context): + time.sleep(1) + if task["value"] == 5: + raise ValueError("Intentional example failure for value 5") + return { + "value": task["value"], + "square": task["value"] ** 2, + } + + +runner = TaskRunner.open("squares-example") +runner.start(execute_task) +``` + +Wait for any unfinished work, then inspect the saved results: + +```{code-cell} python +%%there --worker +runner.wait() +print(runner.status()) +``` + +```{code-cell} python +:tags: ["hide-output"] +saved_results = %there get runner.results() +saved_results +``` + +Execution is at least once. If PythonHere stops after an executor begins but +before its result is committed, that task can run again. Executors with +irreversible side effects should therefore be idempotent or check durable state +before applying those effects. + +## Optional: reuse runtime resources + +The executor always receives a second argument. It is `None` when `start()` has +no setup callback. For expensive runtime resources, create them once per worker +session and reuse the returned context for every task and retry: + +```python +def setup(): + return create_runtime() + + +def execute_with_runtime(task, runtime): + return runtime.process(task) + + +runner.start(execute_with_runtime, setup=setup) +``` + +Setup runs in the background worker thread, so `start()` still returns promptly. +While setup executes, `runner.status()["state"]` is `"setting_up"`; after setup +succeeds it becomes `"running"` before the first task is claimed. +If pause is requested while setup is running, setup finishes and the worker exits +before claiming a task. A later `start()` calls setup again. Context is runtime +state: it is not persisted or included in results, and the runner does not close +it automatically. Applications that require deterministic resource cleanup must +manage that cleanup themselves. + +## Clean up + +When you are done inspecting the completed run, you can delete it to repeat +this example with the same name. Skip this cell to keep its saved results. +This deletes only `"squares-example"` and its tasks/results; other runs and +exported JSON files are untouched. + +```{code-cell} python +%%there --worker +from tasks_here import TaskRunner, TaskRunNotFoundError + +try: + saved_run = TaskRunner.open("squares-example") +except TaskRunNotFoundError: + print("The example run has already been deleted.") +else: + saved_run.delete() + print("Example run deleted. You can now run the example again.") +``` + +A running task run cannot be deleted. Finish or pause it first. diff --git a/examples/there-cli.md b/examples/there-cli.md index ee954d6..e3fb7c1 100644 --- a/examples/there-cli.md +++ b/examples/there-cli.md @@ -11,7 +11,7 @@ codes. ## Connect to the app Start PythonHere on the target device, then work from a directory containing a -[`there.env`](https://herethere.me/pythonhere/examples/commands.html#there-env-example) +[`there.env`](commands.md#there-env-example) connection file, or one of its descendants. Check the installed interface and target readiness: diff --git a/pyproject.toml b/pyproject.toml index 14fdd16..e9bc903 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -22,10 +22,11 @@ classifiers = [ "Programming Language :: Python :: 3.14", ] dependencies = [ - "herethere[magic]>=0.3.2", + "herethere[magic]>=0.3.3", "ipython", "ipywidgets", "Pillow", + "persist-queue==1.1.0", ] [project.optional-dependencies] diff --git a/pythonhere/.agents/skills/pythonhere/SKILL.md b/pythonhere/.agents/skills/pythonhere/SKILL.md index 0a9c6fd..9d73a29 100644 --- a/pythonhere/.agents/skills/pythonhere/SKILL.md +++ b/pythonhere/.agents/skills/pythonhere/SKILL.md @@ -1,6 +1,6 @@ --- name: pythonhere -description: "Build, inspect, and debug PythonHere applications by executing Python through the `there` CLI in an already-running Kivy/Python-for-Android process. Use when a task targets a PythonHere device or `there.env` connection and involves live Kivy UI, KV language, Android APIs, Pyjnius, permissions, installed Android packages, media/files, Plyer device features, BLE with able, MIDI with midistream, or on-device AI with LiteRT-LM and `.litertlm` models." +description: "Build, inspect, and debug PythonHere applications by executing Python through the `there` CLI in an already-running Kivy/Python-for-Android process. Use when a task targets a PythonHere device or `there.env` connection and involves live Kivy UI, KV language, Android APIs, Pyjnius, permissions, installed Android packages, media/files, Plyer device features, BLE with able, MIDI with midistream, durable on-device task runs, or on-device AI with LiteRT-LM and `.litertlm` models." --- # Operate PythonHere with `there` @@ -42,6 +42,8 @@ when the task depends on it broadly or requires its exact current contents. - Consult [midi.md](references/midi.md) for MIDI or synthesizer work. - Consult [litert.md](references/litert.md) for PythonHere's ML model helpers and LiteRT-LM usage. +- Consult [tasks.md](references/tasks.md) for durable sequential work that must + continue after a client disconnect or recover after PythonHere restarts. Combine references when a feature genuinely needs details from several concerns; for example, an Android gallery may need permission, MediaStore, and diff --git a/pythonhere/.agents/skills/pythonhere/references/tasks.md b/pythonhere/.agents/skills/pythonhere/references/tasks.md new file mode 100644 index 0000000..dc5aaad --- /dev/null +++ b/pythonhere/.agents/skills/pythonhere/references/tasks.md @@ -0,0 +1,58 @@ +# Durable task runs + +Use `TaskRunner` for sequential work that must continue after the client +disconnects, retain progress across a PythonHere restart, or retry individual +items. + +## Start a run + +```python +from tasks_here import TaskRunner + +runner = TaskRunner.create("data-import", max_attempts=3) +runner.add([ + {"id": "part-1", "path": "one.json"}, + {"id": "part-2", "path": "two.json"}, +]) +runner.start(execute_task) +``` + +Tasks and results must contain plain JSON-compatible values. Every task needs a +unique nonempty string `id`. `start()` returns promptly and processes one task +at a time. Preserve the runner in a named global when later commands need it. + +Inspect `runner.status()`, `runner.results()`, `runner.get(id)`, or +`runner.failed()` through normal `there get` calls. `pause()` finishes the +current item and stops before claiming another. + +## Wait and inspect the outcome + +After starting the runner, wait in bounded intervals through the CLI: + +```bash +there --json --timeout 60 get --worker \ + "{'stopped': runner.wait(timeout=50), 'status': runner.status()}" +``` + +Here, `--worker` keeps the wait off the app's event loop. +Keep the CLI timeout longer than the wait timeout to allow time for connection +and response. If `stopped` is `false`, tasks continue running; repeat the command +to wait again. A `true` value only means the worker is no longer running (or was +never started), not that every task succeeded. Inspect `status.state`, +`status.failed`, and `status.worker_error`. A `completed` state includes tasks +that exhausted their retries; inspect `runner.failed()` for their errors. + +## Resume after restart + +After PythonHere restarts, reopen the named run, recreate resources and the +executor callable, then restart execution: + +```python +runner = TaskRunner.open("data-import") +runner.start(execute_task) +``` + +Execution is at least once: an item interrupted by process death can run again. +Make irreversible executor side effects idempotent or check their durable state +before applying them. The executor runs in a background thread; marshal Kivy UI +access to the main thread according to `kivy-runtime.md`. diff --git a/pythonhere/main.py b/pythonhere/main.py index 959219f..1c03c9b 100644 --- a/pythonhere/main.py +++ b/pythonhere/main.py @@ -26,6 +26,7 @@ from kivy.clock import Clock from kivy.config import Config, ConfigParser from kivy.logger import Logger +from kivy.properties import StringProperty # pylint: disable=no-name-in-module from patches_here import monkeypatch_kivy from server_here import run_ssh_server from window_here import reset_window_environment @@ -42,6 +43,8 @@ def configure_logging(): class PythonHereApp(App): """PythonHere main app.""" + ssh_host_key_sha256 = StringProperty("") + def __init__(self): super().__init__() self.server_task: asyncio.Task | None = None diff --git a/pythonhere/server_here.py b/pythonhere/server_here.py index 4975c44..c5bd62b 100644 --- a/pythonhere/server_here.py +++ b/pythonhere/server_here.py @@ -39,6 +39,7 @@ async def run_ssh_server(app): namespace=app.ssh_server_namespace, server_factory=PythonHereServer, ) + app.ssh_host_key_sha256 = server.host_key_sha256 except Exception as exc: Logger.error("PythonHere: SSH server start error") Logger.exception(exc) diff --git a/pythonhere/tasks_here.py b/pythonhere/tasks_here.py new file mode 100644 index 0000000..b32c508 --- /dev/null +++ b/pythonhere/tasks_here.py @@ -0,0 +1,1292 @@ +"""Durable sequential task execution for PythonHere. + +TaskRunner provides persistent named runs with retries, progress inspection, +and at-least-once recovery after process interruption. + +An optional setup callback can create runtime state once per worker session:: + + def setup(): + return create_runtime() + + def execute_task(task, runtime): + return runtime.process(task) + + runner.start(execute_task, setup=setup) + +Without setup, the executor still receives a second argument, whose value is +``None``:: + + def execute_task(task, context): + return task["value"] * 2 + + runner.start(execute_task) +""" + +from __future__ import annotations + +import copy +import json +import logging +import os +import re +import shutil +import sys +import threading +import time +import traceback +from collections.abc import Callable, Iterable, Mapping +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +from persistqueue import SQLiteAckQueue +from persistqueue.exceptions import Empty + +# pylint: disable=too-many-lines + +__all__ = [ + "TaskRunner", + "TaskRunnerError", + "TaskRunExistsError", + "TaskRunNotFoundError", + "DuplicateTaskError", + "TaskSubmissionError", + "TaskRunnerAlreadyRunningError", + "TaskRunnerBusyError", + "TaskRunnerClosedError", + "task_runs_directory", +] + + +log = logging.getLogger(__name__) + +_SCHEMA_VERSION = 1 +_RUN_NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*$") + +# persist-queue SQLiteAckQueue status values in 1.1.0. +# Keep these local rather than importing a private implementation class. +_PQ_INITED = "0" +_PQ_READY = "1" +_PQ_UNACK = "2" +_PQ_ACKED = "5" +_PQ_FAILED = "9" + +_REGISTRY_LOCK = threading.RLock() +_INSTANCES: dict[str, TaskRunner] = {} + +# Runs are exclusive process-wide by default so separate workloads cannot +# accidentally compete for a shared device or another constrained resource. +# Set exclusive=False when parallel independent runners are explicitly desired. +_EXECUTION_OWNER: dict[str, str] = {} + + +class TaskRunnerError(RuntimeError): + """Base error for TaskRunner.""" + + +class TaskRunExistsError(TaskRunnerError): + """A run with this name already exists.""" + + +class TaskRunNotFoundError(TaskRunnerError): + """The requested run does not exist.""" + + +class DuplicateTaskError(TaskRunnerError): + """A task id already exists in the run.""" + + +class TaskSubmissionError(TaskRunnerError): + """Storage failed during submission; inspect the run before resubmitting.""" + + def __init__(self, submitted_ids: list[str]): + self.submitted_ids = submitted_ids + super().__init__( + f"Submission failed after {len(submitted_ids)} confirmed writes; " + "inspect get(id) before resubmitting missing tasks" + ) + + +class TaskRunnerAlreadyRunningError(TaskRunnerError): + """This runner already has an active worker.""" + + +class TaskRunnerBusyError(TaskRunnerError): + """Another exclusive TaskRunner is already executing.""" + + +class TaskRunnerClosedError(TaskRunnerError): + """Operation attempted on a closed runner.""" + + +def _utc_now() -> str: + return datetime.now(timezone.utc).isoformat() + + +def task_runs_directory() -> Path: + """ + Return the default persistent TaskRunner directory. + + Override with PYTHONHERE_TASKS_DIR when needed. Android uses the current + application's private files directory; desktop uses its user data directory. + """ + configured = os.environ.get("PYTHONHERE_TASKS_DIR") + if configured: + return Path(configured).expanduser().resolve() + + if sys.platform == "android" or "ANDROID_ARGUMENT" in os.environ: + from android.storage import app_storage_path + + return Path(app_storage_path()) / "task-runs" + data_home = os.environ.get("XDG_DATA_HOME") + base = Path(data_home).expanduser() if data_home else Path.home() / ".local/share" + return base / "pythonhere/task-runs" + + +def _plain_value(value: Any) -> Any: + """Validate and snapshot portable values before writing or invoking user code.""" + + def check(item): + if item is None or isinstance(item, (bool, int, float, str)): + return + if isinstance(item, list): + for child in item: + check(child) + return + if isinstance(item, dict) and all(isinstance(key, str) for key in item): + for child in item.values(): + check(child) + return + raise TypeError("Tasks and results must contain plain JSON-compatible values") + + check(value) + return json.loads(json.dumps(value, allow_nan=False)) + + +def _normalize_root(root: str | os.PathLike[str] | None) -> Path: + if root is None: + return task_runs_directory() + return Path(root).expanduser().resolve() + + +def _validate_name(name: str) -> str: + if not isinstance(name, str) or not _RUN_NAME_RE.fullmatch(name): + raise ValueError(r"TaskRunner name must match [A-Za-z0-9][A-Za-z0-9._-]*") + if name in {".", ".."}: + raise ValueError("Invalid TaskRunner name") + return name + + +def _run_path(name: str, root: Path) -> Path: + return root / _validate_name(name) + + +def _registry_key(path: Path) -> str: + return str(path.resolve()) + + +def _atomic_write_json( + path: Path, value: Mapping[str, Any] | list[dict[str, Any]] +) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + + tmp = path.with_name(f".{path.name}.tmp-{os.getpid()}-{threading.get_ident()}") + + try: + with tmp.open("w", encoding="utf-8") as f: + json.dump( + value, + f, + indent=2, + sort_keys=True, + ensure_ascii=False, + ) + f.write("\n") + f.flush() + os.fsync(f.fileno()) + + os.replace(tmp, path) + finally: + try: + tmp.unlink() + except FileNotFoundError: + pass + + +def _read_json(path: Path) -> dict[str, Any]: + try: + with path.open("r", encoding="utf-8") as f: + value = json.load(f) + except FileNotFoundError as exc: + raise TaskRunNotFoundError(f"Task run metadata not found: {path}") from exc + + if not isinstance(value, dict): + raise TaskRunnerError(f"Invalid TaskRunner metadata: {path}") + + return value + + +def _status_name(status: Any) -> str: + status = str(status) + + if status in {_PQ_INITED, _PQ_READY}: + return "pending" + if status == _PQ_UNACK: + return "running" + if status == _PQ_ACKED: + return "done" + if status == _PQ_FAILED: + return "failed" + + return f"unknown:{status}" + + +class TaskRunner: + """ + Durable single-worker task runner. + + Use create() and open() instead of constructing this class directly. + + A run stores each task, its attempt history, result/error information, and + queue status on disk. SQLiteAckQueue provides durable acknowledgement and + recovery of tasks that were in-flight when the process died. + """ + + def __init__( + self, + *, + name: str, + root: Path, + metadata: dict[str, Any], + auto_resume: bool, + ) -> None: + self.name = name + self.root = root + self.path = _run_path(name, root) + self._meta_path = self.path / "meta.json" + self._queue_path = self.path / "queue" + + self.max_attempts = int(metadata["max_attempts"]) + self.exclusive = bool(metadata.get("exclusive", True)) + self._user_metadata = copy.deepcopy(metadata.get("metadata") or {}) + + self._lock = threading.RLock() + self._pause_requested = threading.Event() + self._thread: threading.Thread | None = None + self._current_task_id: str | None = None + self._current_pqid: int | None = None + self._closed = False + self._worker_error: dict[str, Any] | None = None + + self._state = str(metadata.get("state", "idle")) + self._created_at = str(metadata.get("created_at", _utc_now())) + + self.path.mkdir(parents=True, exist_ok=True) + + self._queue = SQLiteAckQueue( + str(self._queue_path), + auto_resume=auto_resume, + multithreading=True, + ) + + # There are two small commit windows: + # + # 1. result persisted, process dies before ack() + # 2. final error persisted, process dies before ack_failed() + # + # auto_resume makes both rows READY. Repair their queue status from the + # durable record so already committed work is not needlessly rerun. + self._recover_committed_records() + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + @classmethod + def create( # pylint: disable=too-many-arguments + cls, + name: str, + *, + max_attempts: int = 3, + metadata: Mapping[str, Any] | None = None, + root: str | os.PathLike[str] | None = None, + exclusive: bool = True, + ) -> TaskRunner: + """ + Create a new durable named run. + + Raises TaskRunExistsError when the name already exists. + """ + name = _validate_name(name) + root_path = _normalize_root(root) + path = _run_path(name, root_path) + key = _registry_key(path) + + if ( + not isinstance(max_attempts, int) + or isinstance(max_attempts, bool) + or max_attempts < 1 + ): + raise ValueError("max_attempts must be a positive integer") + + # Use the same portable value contract for user metadata. + user_metadata = _plain_value(dict(metadata or {})) + with _REGISTRY_LOCK: + if key in _INSTANCES or path.exists(): + raise TaskRunExistsError(f"Task run {name!r} already exists") + + path.mkdir(parents=True, exist_ok=False) + + created_at = _utc_now() + initial_meta = { + "schema_version": _SCHEMA_VERSION, + "name": name, + "created_at": created_at, + "updated_at": created_at, + "max_attempts": int(max_attempts), + "exclusive": bool(exclusive), + "state": "idle", + "metadata": user_metadata, + "summary": { + "total": 0, + "pending": 0, + "running": 0, + "completed": 0, + "failed": 0, + "progress": 0.0, + }, + "worker_error": None, + } + + try: + _atomic_write_json(path / "meta.json", initial_meta) + runner = cls( + name=name, + root=root_path, + metadata=initial_meta, + auto_resume=False, + ) + except Exception: + shutil.rmtree(path, ignore_errors=True) + raise + + _INSTANCES[key] = runner + + runner._refresh_meta(state="idle") + return runner + + @classmethod + def open( + cls, + name: str, + *, + root: str | os.PathLike[str] | None = None, + ) -> TaskRunner: + """ + Open an existing run. + + If this Python process already has the run open, the existing object is + returned. This is important: creating a second SQLiteAckQueue with + auto_resume=True while the first runner is actively executing could + reset its in-flight row. + """ + name = _validate_name(name) + root_path = _normalize_root(root) + path = _run_path(name, root_path) + key = _registry_key(path) + + with _REGISTRY_LOCK: + existing = _INSTANCES.get(key) + if existing is not None and not existing._closed: + return existing + + meta_path = path / "meta.json" + if not meta_path.exists(): + raise TaskRunNotFoundError(f"Task run {name!r} does not exist") + + metadata = _read_json(meta_path) + + if metadata.get("schema_version") != _SCHEMA_VERSION: + raise TaskRunnerError( + f"Unsupported TaskRunner schema version: " + f"{metadata.get('schema_version')!r}" + ) + + if metadata.get("name") != name: + raise TaskRunnerError( + f"TaskRunner metadata name mismatch in {meta_path}" + ) + + runner = cls( + name=name, + root=root_path, + metadata=metadata, + auto_resume=True, + ) + _INSTANCES[key] = runner + + counts = runner._counts() + previous_state = str(metadata.get("state", "idle")) + + if counts["total"] and ( + counts["completed"] + counts["failed"] == counts["total"] + ): + state = "completed" + elif previous_state == "paused": + state = "paused" + elif previous_state == "idle": + state = "idle" + else: + # A previous process said it was running (or was already marked + # interrupted), but this process has no worker for it. + state = "interrupted" + + runner._refresh_meta(state=state) + return runner + + @classmethod + def list( + cls, + *, + root: str | os.PathLike[str] | None = None, + ) -> list[dict[str, Any]]: + """ + List persisted runs without reopening their queues. + + Reading meta.json rather than constructing SQLiteAckQueue instances is + intentional: list() must never trigger auto-resume on a live run. + """ + root_path = _normalize_root(root) + if not root_path.exists(): + return [] + + result: list[dict[str, Any]] = [] + + for path in root_path.iterdir(): + if not path.is_dir(): + continue + + meta_path = path / "meta.json" + if not meta_path.is_file(): + continue + + try: + meta = _read_json(meta_path) + except Exception: + log.exception( + "TaskRunner: could not read metadata from %s", + meta_path, + ) + continue + + key = _registry_key(path) + with _REGISTRY_LOCK: + live = _INSTANCES.get(key) + + if live is not None and not live._closed: + try: + result.append(live.status()) + continue + except Exception: + log.exception( + "TaskRunner: could not inspect live run %s", + path.name, + ) + + summary = dict(meta.get("summary") or {}) + state = str(meta.get("state", "idle")) + + # Active states in persisted metadata cannot still be active in + # this process if no registered live instance exists. + if state in {"running", "setting_up"}: + state = "interrupted" + + result.append( + { + "name": meta.get("name", path.name), + "state": state, + "max_attempts": meta.get("max_attempts"), + "exclusive": meta.get("exclusive", True), + "created_at": meta.get("created_at"), + "updated_at": meta.get("updated_at"), + "metadata": copy.deepcopy(meta.get("metadata") or {}), + **summary, + } + ) + + result.sort( + key=lambda item: str(item.get("updated_at") or ""), + reverse=True, + ) + return result + + def close(self) -> None: + """ + Close local SQLite resources. + + A running worker cannot be closed. Closing does not delete the run. + """ + with self._lock: + self._ensure_open() + if self.is_running(): + raise TaskRunnerAlreadyRunningError("Cannot close a running TaskRunner") + + self._queue.close() + self._closed = True + + key = _registry_key(self.path) + with _REGISTRY_LOCK: + if _INSTANCES.get(key) is self: + _INSTANCES.pop(key, None) + + def delete(self) -> None: + """ + Permanently delete this run and all stored tasks/results. + + The runner must not be active. + """ + with self._lock: + self._ensure_open() + if self.is_running(): + raise TaskRunnerAlreadyRunningError( + "Cannot delete a running TaskRunner" + ) + + path = self.path + self.close() + shutil.rmtree(path) + + def __enter__(self) -> TaskRunner: + self._ensure_open() + return self + + def __exit__(self, exc_type, exc, tb) -> None: + self.close() + + # ------------------------------------------------------------------ + # Submission and execution + # ------------------------------------------------------------------ + + def add(self, tasks: Iterable[Mapping[str, Any]]) -> int: + """ + Durably add tasks. + + Each task must be a mapping containing a non-empty string ``id``. + Duplicate ids are rejected across the whole run. + + Validation failures write nothing. Storage failures may commit a prefix; + TaskSubmissionError reports confirmed IDs. Inspect get(id) before retrying. + Returns the number of tasks added. + """ + with self._lock: + self._ensure_open() + + if self.is_running(): + raise TaskRunnerAlreadyRunningError( + "Cannot add tasks while the runner is active" + ) + + existing_ids = { + record["task_id"] + for record in self._all_queue_records() + if isinstance(record.get("task_id"), str) + } + + prepared: list[dict[str, Any]] = [] + submitted_ids: set[str] = set() + + for original in tasks: + if not isinstance(original, Mapping): + raise TypeError( + f"Task must be a mapping, got {type(original).__name__}" + ) + + task = _plain_value(dict(original)) + task_id = task.get("id") + + if not isinstance(task_id, str) or not task_id: + raise ValueError("Each task must contain a non-empty string 'id'") + + if task_id in existing_ids or task_id in submitted_ids: + raise DuplicateTaskError(f"Duplicate task id: {task_id!r}") + + prepared.append( + { + "schema_version": _SCHEMA_VERSION, + "task_id": task_id, + "task": task, + "created_at": _utc_now(), + "attempts": [], + "result_present": False, + "result": None, + "completed_at": None, + } + ) + submitted_ids.add(task_id) + + confirmed_ids = [] + try: + for record in prepared: + self._queue.put(record) + confirmed_ids.append(record["task_id"]) + + if prepared: + self._pause_requested.clear() + self._worker_error = None + self._refresh_meta(state="idle") + except Exception as exc: + raise TaskSubmissionError(confirmed_ids) from exc + + return len(prepared) + + def start( + self, + execute: Callable[[dict[str, Any], Any], Any], + *, + setup: Callable[[], Any] | None = None, + ) -> TaskRunner: + """ + Start/resume sequential execution in a daemon background thread. + + The method returns immediately. + + ``setup()``, when supplied, runs once in the worker thread before any + task is claimed. Its return value is passed unchanged to every + ``execute(task, context)`` call in that worker session. Without setup, + context is ``None``. Executors must return plain JSON-compatible data. + Executor and result-validation errors consume the max_attempts failure + budget. Interrupted executions do not consume it. Retries run after + later ready rows, wrapping to the beginning when needed. + + The runner does not retain or clean up context after the worker exits. + Applications remain responsible for deterministic resource cleanup. + """ + if not callable(execute): + raise TypeError("execute must be callable") + if setup is not None and not callable(setup): + raise TypeError("setup must be callable or None") + + with self._lock: + self._ensure_open() + + if self.is_running(): + raise TaskRunnerAlreadyRunningError( + f"Task run {self.name!r} is already running" + ) + + # Repair a stale unack row left by an unexpected worker-thread + # failure in the same process, then repair any committed-but-not- + # acked records. + self._queue.resume_unack_tasks() + self._recover_committed_records() + + counts = self._counts() + if counts["pending"] == 0: + state = "completed" if counts["total"] > 0 else "idle" + self._refresh_meta(state=state) + return self + + self._claim_execution() + + try: + self._pause_requested.clear() + self._worker_error = None + self._current_task_id = None + self._current_pqid = None + initial_state = "setting_up" if setup is not None else "running" + self._refresh_meta(state=initial_state) + + thread = threading.Thread( + target=self._run_loop, + args=(execute, setup), + name=f"TaskRunner[{self.name}]", + daemon=True, + ) + self._thread = thread + + thread.start() + except Exception: + self._thread = None + self._release_execution() + self._state = "interrupted" + try: + self._refresh_meta(state="interrupted") + except Exception: + log.exception( + "TaskRunner %s: could not persist start failure", + self.name, + ) + raise + + return self + + def pause(self) -> None: + """ + Request a graceful pause. + + The current execute() call is not cancelled. The worker finishes the + current attempt and stops before taking another task. + """ + with self._lock: + self._ensure_open() + + if self.is_running(): + self._pause_requested.set() + else: + counts = self._counts() + if counts["pending"] > 0: + self._refresh_meta(state="paused") + + def wait(self, timeout: float | None = None) -> bool: + """ + Wait for the current worker thread. + + Returns True if it is no longer running, False on timeout. + """ + with self._lock: + self._ensure_open() + thread = self._thread + + if thread is None: + return True + + thread.join(timeout) + return not thread.is_alive() + + def is_running(self) -> bool: + thread = self._thread + return thread is not None and thread.is_alive() + + # ------------------------------------------------------------------ + # Inspection + # ------------------------------------------------------------------ + + @property + def metadata(self) -> dict[str, Any]: + return copy.deepcopy(self._user_metadata) + + def status(self) -> dict[str, Any]: + """Return a small plain dictionary suitable for ``%there get``.""" + with self._lock: + self._ensure_open() + + counts = self._counts() + + if self.is_running(): + state = "setting_up" if self._state == "setting_up" else "running" + elif ( + counts["total"] > 0 + and counts["completed"] + counts["failed"] == counts["total"] + ): + state = "completed" + else: + state = self._state + if state in {"running", "setting_up"}: + state = "interrupted" + + return { + "name": self.name, + "state": state, + **counts, + "current": self._current_task_id, + "pause_requested": self._pause_requested.is_set(), + "max_attempts": self.max_attempts, + "exclusive": self.exclusive, + "created_at": self._created_at, + "updated_at": self._meta_updated_at(), + "metadata": copy.deepcopy(self._user_metadata), + "worker_error": copy.deepcopy(self._worker_error), + "path": str(self.path), + } + + def results(self) -> list[dict[str, Any]]: + """ + Return all task records in submission order. + + This intentionally includes pending/running/failed tasks so the caller + can inspect a run before it is complete. + """ + with self._lock: + self._ensure_open() + rows = sorted(self._queue.queue(), key=lambda row: row["id"]) + return [self._public_record(row) for row in rows] + + def export_results(self, path: str | os.PathLike[str]) -> Path: + """Atomically save a results snapshot as UTF-8 JSON and return its path. + + Includes all task records in submission order, just like results(). + Relative paths use the current working directory (PythonHere's upload + directory by default), for retrieval with ``%there download``. + Parent directories are created and an existing file is replaced only + after a successful write. Run with ``%%there --worker`` for large runs. + + This avoids a large ``%there get`` response, but still materializes the + complete results snapshot in device memory. + """ + snapshot = self.results() + destination = Path(path) + _atomic_write_json(destination, snapshot) + return destination + + def failed(self) -> list[dict[str, Any]]: + """Return permanently failed task records.""" + return [record for record in self.results() if record["status"] == "failed"] + + def get(self, task_id: str) -> dict[str, Any] | None: + """Return one task record by logical id, or None if not found.""" + if not isinstance(task_id, str): + raise TypeError("task_id must be a string") + + with self._lock: + self._ensure_open() + + for row in self._queue.queue(): + data = row.get("data") + if isinstance(data, dict) and data.get("task_id") == task_id: + return self._public_record(row) + + return None + + # ------------------------------------------------------------------ + # Worker internals + # ------------------------------------------------------------------ + + def _run_loop( # noqa: PLR0912, PLR0915 # pylint: disable=too-many-locals,too-many-branches,too-many-statements + self, + execute: Callable[[dict[str, Any], Any], Any], + setup: Callable[[], Any] | None, + ) -> None: + final_state = "interrupted" + + previous_id = None + phase = "setup" + try: + context = setup() if setup is not None else None + phase = "execution" + + if setup is not None: + with self._lock: + self._refresh_meta(state="running") + + while True: + with self._lock: + if self._pause_requested.is_set(): + break + try: + item = self._queue.get( + block=False, + raw=True, + id=previous_id, + next_in_order=previous_id is not None, + ) + except Empty: + final_state = "completed" + break + self._current_pqid = int(item["pqid"]) + + pqid = int(item["pqid"]) + previous_id = pqid + record = item["data"] + + if not isinstance(record, dict): + # This should never happen for a TaskRunner-created queue. + self._queue.ack_failed(id=pqid) + log.error( + "TaskRunner %s: invalid queue record %r", + self.name, + record, + ) + continue + + task = record.get("task") + task_id = record.get("task_id") + + if not isinstance(task, dict) or not isinstance(task_id, str): + self._queue.ack_failed(id=pqid) + log.error( + "TaskRunner %s: invalid task record pqid=%s", + self.name, + pqid, + ) + continue + + attempt_number = len(record.get("attempts") or []) + 1 + attempt = { + "number": attempt_number, + "started_at": _utc_now(), + "finished_at": None, + "duration": None, + "error": None, + } + + record.setdefault("attempts", []).append(attempt) + + with self._lock: + self._current_task_id = task_id + self._current_pqid = pqid + # Commit "attempt started" before entering arbitrary user + # code. A process kill from this point onward is visible + # during recovery. + self._queue.update({"pqid": pqid, "data": record}) + self._refresh_meta(state="running") + + started = time.monotonic() + log.info( + "TaskRunner %s: starting %s attempt %d/%d", + self.name, + task_id, + attempt_number, + self.max_attempts, + ) + + try: + result = _plain_value(execute(copy.deepcopy(task), context)) + except Exception as exc: + duration = time.monotonic() - started + + with self._lock: + attempt["finished_at"] = _utc_now() + attempt["duration"] = duration + attempt["error"] = { + "type": type(exc).__name__, + "message": str(exc), + "traceback": traceback.format_exc(), + } + + record["last_error"] = copy.deepcopy(attempt["error"]) + self._queue.update({"pqid": pqid, "data": record}) + + failure_count = self._failure_count(record) + + if failure_count >= self.max_attempts: + self._queue.ack_failed(id=pqid) + log.exception( + "TaskRunner %s: task %s failed " + "permanently after %d failures", + self.name, + task_id, + failure_count, + ) + else: + self._queue.nack(id=pqid) + log.warning( + "TaskRunner %s: task %s failed " + "(failure %d/%d, execution attempt %d): %s", + self.name, + task_id, + failure_count, + self.max_attempts, + attempt_number, + exc, + ) + + self._current_task_id = None + self._current_pqid = None + self._refresh_meta(state="running") + + else: + duration = time.monotonic() - started + + with self._lock: + attempt["finished_at"] = _utc_now() + attempt["duration"] = duration + record["result"] = result + record["result_present"] = True + record["completed_at"] = _utc_now() + record.pop("last_error", None) + + # Commit result before ack. If the process dies in the + # tiny window before ack(), open() recognizes this + # durable completion and repairs the queue status. + self._queue.update({"pqid": pqid, "data": record}) + self._queue.ack(id=pqid) + + self._current_task_id = None + self._current_pqid = None + self._refresh_meta(state="running") + + log.info( + "TaskRunner %s: completed %s in %.3fs", + self.name, + task_id, + duration, + ) + + if self._pause_requested.is_set(): + final_state = "paused" + + except BaseException as exc: + # Unexpected failures of runner machinery should not lose the + # currently claimed queue item. Return it to READY when possible. + if phase == "setup": + log.exception("TaskRunner %s: setup failed", self.name) + else: + log.exception( + "TaskRunner %s: worker stopped unexpectedly", + self.name, + ) + + with self._lock: + self._worker_error = { + "type": type(exc).__name__, + "message": str(exc), + "traceback": traceback.format_exc(), + "time": _utc_now(), + } + + if self._current_pqid is not None: + try: + self._queue.nack(id=self._current_pqid) + except Exception: + log.exception( + "TaskRunner %s: could not nack interrupted pqid=%s", + self.name, + self._current_pqid, + ) + + self._current_task_id = None + self._current_pqid = None + + final_state = "interrupted" + + finally: + with self._lock: + self._current_task_id = None + self._current_pqid = None + + # If no runnable work is left, terminal status wins over + # "paused". + try: + counts = self._counts() + if ( + counts["total"] > 0 + and counts["completed"] + counts["failed"] == counts["total"] + ): + final_state = "completed" + except Exception: + log.exception( + "TaskRunner %s: could not compute final status", + self.name, + ) + + try: + self._refresh_meta(state=final_state) + except Exception: + log.exception( + "TaskRunner %s: could not persist final metadata", + self.name, + ) + + self._release_execution() + + # ------------------------------------------------------------------ + # Persistence helpers + # ------------------------------------------------------------------ + + def _recover_committed_records(self) -> None: + """ + Repair READY rows whose result/final failure was already persisted. + + SQLiteAckQueue auto-resume intentionally turns old UNACK rows back to + READY. Usually they should be rerun. The exception is when TaskRunner + already committed a successful result or the final failed attempt and + the old process died immediately before ack()/ack_failed(). + """ + for row in self._queue.queue(): + if str(row.get("status")) not in { + _PQ_INITED, + _PQ_READY, + }: + continue + + pqid = int(row["id"]) + record = row.get("data") + + if not isinstance(record, dict): + continue + + if record.get("result_present") is True and record.get("completed_at"): + self._queue.ack(id=pqid) + continue + + attempts = record.get("attempts") + if not isinstance(attempts, list) or not attempts: + continue + + last_attempt = attempts[-1] + if not isinstance(last_attempt, dict): + continue + + # A process kill is an interrupted execution attempt, not an + # executor failure. Preserve it in history, but do not consume the + # max_attempts failure budget. + if ( + last_attempt.get("started_at") + and not last_attempt.get("finished_at") + and last_attempt.get("error") is None + and not last_attempt.get("interrupted_at") + ): + last_attempt["interrupted_at"] = _utc_now() + last_attempt["interrupted"] = True + self._queue.update({"pqid": pqid, "data": record}) + + if self._failure_count(record) >= self.max_attempts: + self._queue.ack_failed(id=pqid) + + # ack() and ack_failed() normally follow get(), which already removed + # the item from qsize(). Recovered items were put back into READY by + # auto-resume, so recalculate the public pending counter after repair. + self._queue.resume_unack_tasks() + + @staticmethod + def _failure_count(record: Mapping[str, Any]) -> int: + attempts = record.get("attempts") + if not isinstance(attempts, list): + return 0 + + return sum( + 1 + for attempt in attempts + if isinstance(attempt, dict) + and attempt.get("finished_at") + and attempt.get("error") is not None + ) + + def _all_queue_records(self) -> list[dict[str, Any]]: + records: list[dict[str, Any]] = [] + + for row in self._queue.queue(): + data = row.get("data") + if isinstance(data, dict): + records.append(data) + + return records + + def _counts(self) -> dict[str, Any]: + # Public count helpers do not deserialize prompts or results. qsize() + # includes persist-queue's newly inserted and retry-ready rows. + pending = self._queue.qsize() + running = self._queue.unack_count() + completed = self._queue.acked_count() + failed = self._queue.ack_failed_count() + + total = pending + running + completed + failed + terminal = completed + failed + + return { + "total": total, + "pending": pending, + "running": running, + "completed": completed, + "failed": failed, + "progress": (terminal / total) if total else 0.0, + } + + def _public_record( + self, + row: Mapping[str, Any], + ) -> dict[str, Any]: + record = row.get("data") + + if not isinstance(record, dict): + return { + "id": None, + "status": _status_name(row.get("status")), + "task": None, + "result": None, + "attempt_count": 0, + "attempts": [], + "error": { + "type": "TaskRunnerRecordError", + "message": "Invalid persisted task record", + }, + } + + attempts = copy.deepcopy(record.get("attempts") or []) + + durations = [ + attempt.get("duration") + for attempt in attempts + if isinstance(attempt, dict) + and isinstance(attempt.get("duration"), (int, float)) + ] + + result_present = bool(record.get("result_present")) + + return { + "id": record.get("task_id"), + "status": _status_name(row.get("status")), + "task": copy.deepcopy(record.get("task")), + "result": (copy.deepcopy(record.get("result")) if result_present else None), + "result_present": result_present, + "attempt_count": len(attempts), + "failure_count": self._failure_count(record), + "attempts": attempts, + "duration": durations[-1] if durations else None, + "total_duration": sum(durations), + "error": copy.deepcopy(record.get("last_error")), + "created_at": record.get("created_at"), + "completed_at": record.get("completed_at"), + } + + def _refresh_meta(self, *, state: str | None = None) -> None: + if state is not None: + self._state = state + + now = _utc_now() + counts = self._counts() + + meta = { + "schema_version": _SCHEMA_VERSION, + "name": self.name, + "created_at": self._created_at, + "updated_at": now, + "max_attempts": self.max_attempts, + "exclusive": self.exclusive, + "state": self._state, + "metadata": copy.deepcopy(self._user_metadata), + "summary": counts, + "worker_error": copy.deepcopy(self._worker_error), + } + + _atomic_write_json(self._meta_path, meta) + + def _meta_updated_at(self) -> str | None: + try: + return _read_json(self._meta_path).get("updated_at") + except Exception: + return None + + # ------------------------------------------------------------------ + # Process-wide execution ownership + # ------------------------------------------------------------------ + + def _claim_execution(self) -> None: + if not self.exclusive: + return + + key = _registry_key(self.path) + + with _REGISTRY_LOCK: + owner = _EXECUTION_OWNER.get("path") + if owner is not None and owner != key: + owner_name = Path(owner).name + raise TaskRunnerBusyError( + f"Another exclusive task run is active: {owner_name!r}" + ) + + _EXECUTION_OWNER["path"] = key + + def _release_execution(self) -> None: + if not self.exclusive: + return + + key = _registry_key(self.path) + + with _REGISTRY_LOCK: + if _EXECUTION_OWNER.get("path") == key: + _EXECUTION_OWNER.pop("path") + + def _ensure_open(self) -> None: + if self._closed: + raise TaskRunnerClosedError(f"Task run {self.name!r} is closed") diff --git a/pythonhere/ui_here/connection_address_here.kv b/pythonhere/ui_here/connection_address_here.kv index 1ba4271..fa7f7e3 100644 --- a/pythonhere/ui_here/connection_address_here.kv +++ b/pythonhere/ui_here/connection_address_here.kv @@ -1,6 +1,9 @@ #:kivy 1.0 #:import ConnectionAddressLabel ui_here.connection_address_here.ConnectionAddressLabel #:import ConnectionAddressInfoBox ui_here.connection_address_here.ConnectionAddressInfoBox +#:import dp kivy.metrics.dp +#:import kivy_data_dir kivy.kivy_data_dir +#:import join os.path.join : text: f"{tc('↳', 3)} {tc(self.address, 2)} ({self.interface})" @@ -22,6 +25,7 @@ font_size: "30sp" ScrollView: + id: address_scroll do_scroll_x: False size_hint: 1, 1 @@ -30,3 +34,39 @@ orientation: "vertical" size_hint: 1, None height: self.minimum_size[1] + + BoxLayout: + id: fingerprint_footer + orientation: "vertical" + size_hint: 1, None + height: self.minimum_height + spacing: dp(6) + padding: 0, dp(16), dp(20), dp(20) + canvas.before: + Color: + rgba: 0.20, 0.24, 0.27, 1 + Line: + points: self.x, self.y + self.height, self.x + self.width - dp(20), self.y + self.height + width: dp(0.5) + + Label: + id: fingerprint_heading + text: "SSH host key fingerprint" + size_hint: 1, None + text_size: self.width, None + height: self.texture_size[1] + halign: "left" + font_size: "15sp" + color: 0.60, 0.64, 0.67, 1 + + Label: + id: fingerprint_value + text: app.ssh_host_key_sha256 + markup: False + size_hint: 1, None + text_size: self.width, None + height: self.texture_size[1] + halign: "left" + font_name: join(kivy_data_dir, 'fonts', 'RobotoMono-Regular.ttf') + font_size: "16sp" + color: 0.91, 0.94, 0.96, 1 diff --git a/tests/test_main.py b/tests/test_main.py index 72ce4b7..07dfe70 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -7,7 +7,13 @@ import pytest from asyncssh import PermissionDenied from enum_here import ScreenName, ServerState +from kivy.clock import Clock +from kivy.core.window import Window +from kivy.graphics import Line +from kivy.metrics import dp +from kivy.uix.label import Label from main import PythonHereApp, configure_logging, main +from ui_here.connection_address_here import ConnectionAddressInfoBox from ui_here.server_screen_here import ServerScreenManager from version_here import __version__ @@ -69,6 +75,111 @@ def test_server_screen_update_states(mocker): unschedule.assert_called_once_with(screen.update_event) +@pytest.mark.asyncio +async def test_connection_screen_shows_full_fingerprint_and_wraps(app_instance): + screen = app_instance.root.ids.here_screen_manager.get_screen(ServerState.ready) + box = next( + widget + for widget in screen.walk() + if isinstance(widget, ConnectionAddressInfoBox) + ) + fingerprint = app_instance.ssh_host_key_sha256 + assert fingerprint.startswith("SHA256:") + label = next( + widget + for widget in box.walk() + if isinstance(widget, Label) and widget.text == fingerprint + ) + assert not label.markup + + app_instance.ssh_host_key_sha256 = "SHA256:" + "a" * 43 + assert label.text == app_instance.ssh_host_key_sha256 + label.size_hint_x = None + label.width = 160 + label.texture_update() + Clock.tick() + + assert label.texture_size[0] <= label.width + assert label.texture_size[1] > label.font_size * 2 + assert label.height == label.texture_size[1] + + +@pytest.mark.asyncio +async def test_fingerprint_footer_stays_fixed_on_scroll_resize_and_navigation( + app_instance, +): + manager = app_instance.root.ids.here_screen_manager + manager.current = ServerState.ready + panel = manager.current_screen.children[0] + footer = panel.ids.fingerprint_footer + scroll = panel.ids.address_scroll + heading = panel.ids.fingerprint_heading + value = panel.ids.fingerprint_value + assert footer.parent is panel + assert scroll.parent is panel + assert not any( + isinstance(widget, Label) and "THERE_HOST_KEY_SHA256" in widget.text + for widget in panel.walk() + ) + for number in range(40): + panel.ids.address_list.add_widget( + Label(text=f"Address {number}", size_hint_y=None, height=dp(30)) + ) + + wrapped_height = None + for size in ((320, 640), (800, 480), (320, 640)): + Window.size = size + for _ in range(8): + await asyncio.sleep(0.02) + assert panel.width == pytest.approx(size[0]), ( + Window.size, + app_instance.root.size, + panel.size, + value.size, + ) + assert footer.y == pytest.approx(panel.y) + assert footer.height == pytest.approx(footer.minimum_height) + assert scroll.height > 0 + assert scroll.y == pytest.approx(footer.y + footer.height) + assert value.height == value.texture_size[1] + if size[0] == 320: + wrapped_height = value.height + else: + assert value.height < wrapped_height + + before_scroll = tuple(footer.pos), tuple(footer.size) + scroll.scroll_y = 0 + for _ in range(3): + await asyncio.sleep(0.02) + assert (tuple(footer.pos), tuple(footer.size)) == before_scroll + + for _ in range(3): + app_instance.root.switch_screen(ScreenName.settings) + await asyncio.sleep(0.02) + app_instance.root.switch_screen(ScreenName.here) + for _ in range(3): + await asyncio.sleep(0.02) + dividers = [ + instruction + for instruction in footer.canvas.before.children + if isinstance(instruction, Line) + ] + assert len(dividers) == 1 + divider = dividers[0] + assert divider.points == pytest.approx( + [ + footer.x, + footer.y + footer.height, + footer.x + footer.width - dp(20), + footer.y + footer.height, + ] + ) + assert heading.y + heading.height <= divider.points[1] - dp(16) + + # Allow the final screen transition to complete as it does in normal use. + await asyncio.sleep(0.5) + + @pytest.mark.asyncio async def test_code_line_executed(capfd, app_instance, there): await there.runcode("print('hello there')") diff --git a/tests/test_pythonhere_skill.py b/tests/test_pythonhere_skill.py index 98f077e..1345189 100644 --- a/tests/test_pythonhere_skill.py +++ b/tests/test_pythonhere_skill.py @@ -22,8 +22,9 @@ "litert.md", "midi.md", "plyer.md", + "tasks.md", } -RUNTIME_PROMPT_NAMES = REFERENCE_NAMES - {"litert.md"} +RUNTIME_PROMPT_NAMES = REFERENCE_NAMES - {"litert.md", "tasks.md"} def test_pythonhere_skill_files_exist(): diff --git a/tests/test_server_here.py b/tests/test_server_here.py index 761cce9..acf9c44 100644 --- a/tests/test_server_here.py +++ b/tests/test_server_here.py @@ -72,6 +72,8 @@ async def test_run_ssh_server_clears_config_ready_after_start_error(mocker): @pytest.mark.asyncio async def test_run_ssh_server_reports_wait_closed_error(mocker): class BrokenServer: + host_key_sha256 = "SHA256:test" + async def wait_closed(self): raise RuntimeError("server failed") @@ -84,6 +86,7 @@ async def wait_closed(self): start_server.assert_called_once() assert app.ssh_server_started.is_set() + assert app.ssh_host_key_sha256 == "SHA256:test" exception = show_exception_popup.call_args.args[0] assert isinstance(exception, RuntimeError) assert str(exception) == "server failed" @@ -124,6 +127,9 @@ async def test_new_host_key_is_ed25519_and_legacy_key_is_untouched( host_key = tmp_path / "ssh_host_key" assert asyncssh.read_private_key(host_key).get_algorithm() == "ssh-ed25519" + assert app.ssh_host_key_sha256 == asyncssh.read_private_key( + host_key + ).get_fingerprint("sha256") assert legacy_key.read_bytes() == legacy_contents running_app.on_ssh_connection_made.assert_called_once_with() finally: diff --git a/tests/test_tasks_here.py b/tests/test_tasks_here.py new file mode 100644 index 0000000..3939383 --- /dev/null +++ b/tests/test_tasks_here.py @@ -0,0 +1,684 @@ +"""Tests for the durable sequential task runner.""" + +import json +import subprocess +import sys +import threading +from types import ModuleType + +import pytest + + +@pytest.fixture +def module(): + import tasks_here as module + + yield module + for runner in list(module._INSTANCES.values()): + runner.pause() + assert runner.wait(5) + runner.close() + + +@pytest.fixture +def runner(module, tmp_path): + return module.TaskRunner.create("test", root=tmp_path) + + +def finish(runner, execute, *, setup=None): + runner.start(execute, setup=setup) + assert runner.wait(5) + assert runner.status()["worker_error"] is None + + +def test_export_results_snapshot(runner, tmp_path): + runner.add([{"id": "a", "text": "Привет 🌍"}, {"id": "b"}]) + destination = tmp_path / "exports" / "results.json" + assert runner.export_results(destination) == destination + assert json.loads(destination.read_text(encoding="utf-8")) == runner.results() + assert "Привет 🌍" in destination.read_text(encoding="utf-8") + + finish(runner, lambda task, context: task["id"]) + runner.export_results(str(destination)) + records = json.loads(destination.read_text(encoding="utf-8")) + assert [record["result"] for record in records] == ["a", "b"] + assert all(record["status"] == "done" for record in records) + + +def test_export_results_empty(runner, tmp_path): + destination = runner.export_results(tmp_path / "empty.json") + assert json.loads(destination.read_text(encoding="utf-8")) == [] + + +def test_export_results_write_failure_preserves_file(runner, tmp_path, monkeypatch): + destination = tmp_path / "results.json" + destination.write_text("previous export", encoding="utf-8") + + def fail_dump(value, stream, **kwargs): + stream.write("partial") + raise OSError("disk full") + + monkeypatch.setattr(json, "dump", fail_dump) + with pytest.raises(OSError, match="disk full"): + runner.export_results(destination) + assert destination.read_text(encoding="utf-8") == "previous export" + assert list(tmp_path.glob(".results.json.tmp-*")) == [] + + +def test_retry_order_and_reopen(module, runner, tmp_path): + runner.add([{"id": "a"}, {"id": "b"}]) + calls = [] + + def execute(task, context): + assert context is None + calls.append(task["id"]) + if task["id"] == "a" and calls.count("a") == 1: + raise ValueError("temporary") + return task["id"] + + finish(runner, execute) + assert calls == ["a", "b", "a"] + runner.close() + reopened = module.TaskRunner.open("test", root=tmp_path) + assert reopened.status()["completed"] == 2 + assert reopened.get("a")["failure_count"] == 1 + assert [r["result"] for r in reopened.results()] == ["a", "b"] + + +def test_invalid_result_and_mutated_input_do_not_stop_run(runner): + runner.add([{"id": "bad"}, {"id": "good"}]) + + def execute(task, context): + assert context is None + if task["id"] == "bad": + task["oops"] = lambda: None + return lambda: None + return None + + finish(runner, execute) + assert runner.get("bad")["failure_count"] == 3 + assert runner.get("bad")["task"] == {"id": "bad"} + assert runner.get("bad")["status"] == "failed" + assert runner.get("good")["result_present"] is True + assert runner.status()["state"] == "completed" + + +@pytest.mark.parametrize( + "bad", + [ + {"id": "b", "value": lambda: None}, + {"id": "a"}, + {"value": 1}, + {"id": "b", "value": float("nan")}, + ], +) +def test_batch_validation_writes_nothing(runner, bad): + with pytest.raises((TypeError, ValueError, RuntimeError)): + runner.add([{"id": "a"}, bad]) + assert runner.status()["total"] == 0 + + +def test_storage_failure_reports_partial_submission(module, runner, monkeypatch): + put = runner._queue.put + + def broken_put(record): + if record["task_id"] == "b": + raise OSError("disk full") + return put(record) + + with monkeypatch.context() as patch: + patch.setattr(runner._queue, "put", broken_put) + with pytest.raises(module.TaskSubmissionError) as exc: + runner.add([{"id": "a"}, {"id": "b"}]) + assert exc.value.submitted_ids == ["a"] + assert runner.get("a") is not None + assert runner.get("b") is None + runner.add([{"id": "b"}]) + finish(runner, lambda task, context: task["id"]) + assert runner.status()["completed"] == 2 + + +def test_counts_do_not_load_payloads(runner, monkeypatch): + runner.add([{"id": "a"}]) + runner.start(lambda task, context: "ok") + assert runner.wait(5) + + def forbidden(): + pytest.fail("status deserialized queue payloads") + + monkeypatch.setattr(runner._queue, "queue", forbidden) + assert runner.status()["completed"] == 1 + runner._refresh_meta() + + +def test_pending_count_uses_public_queue_size(runner, monkeypatch): + runner.add([{"id": "a"}]) + monkeypatch.setattr(runner._queue, "qsize", lambda: 7) + + def forbidden(): + pytest.fail("pending count used ready_count instead of qsize") + + monkeypatch.setattr(runner._queue, "ready_count", forbidden) + assert runner.status()["pending"] == 7 + + +def test_results_are_sorted_by_queue_id(runner, monkeypatch): + runner.add([{"id": "a"}, {"id": "b"}, {"id": "c"}]) + queue = runner._queue.queue + monkeypatch.setattr(runner._queue, "queue", lambda: list(reversed(queue()))) + assert [record["id"] for record in runner.results()] == ["a", "b", "c"] + + +def test_start_failure_releases_execution(module, runner, tmp_path, monkeypatch): + runner.add([{"id": "a"}]) + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "b"}]) + + def broken_meta(**kwargs): + raise OSError("disk full") + + with monkeypatch.context() as patch: + patch.setattr(runner, "_refresh_meta", broken_meta) + with pytest.raises(OSError): + runner.start(lambda task, context: None) + finish(other, lambda task, context: "ok") + finish(runner, lambda task, context: "ok") + + +def test_pause_and_same_process_open(module, runner, tmp_path): + entered = threading.Event() + release = threading.Event() + runner.add([{"id": "a"}, {"id": "b"}]) + + def execute(task, context): + assert context is None + entered.set() + assert release.wait(5) + return task["id"] + + runner.start(execute) + try: + assert entered.wait(5) + assert module.TaskRunner.open("test", root=tmp_path) is runner + runner.pause() + finally: + release.set() + assert runner.wait(5) + assert runner.status()["state"] == "paused" + assert runner.get("b")["attempt_count"] == 0 + finish(runner, lambda task, context: task["id"]) + + +def test_setup_context_is_shared_unvalidated_and_on_worker_thread(runner): + runner.add([{"id": "a"}, {"id": "b"}]) + setup_threads = [] + execute_threads = [] + contexts = [] + setup_calls = [] + lock = threading.Lock() + + def setup(): + setup_calls.append(True) + setup_threads.append(threading.get_ident()) + return {"lock": lock, "callable": lambda: 42} + + def execute(task, context): + contexts.append(context) + execute_threads.append(threading.get_ident()) + assert context["lock"] is lock + assert context["callable"]() == 42 + return task["id"] + + finish(runner, execute, setup=setup) + + assert len(setup_calls) == 1 + assert setup_threads[0] != threading.main_thread().ident + assert execute_threads == [setup_threads[0], setup_threads[0]] + assert contexts[0] is contexts[1] + + +def test_context_survives_executor_retry(runner): + runner.add([{"id": "a"}]) + contexts = [] + + def execute(task, context): + contexts.append(context) + if len(contexts) == 1: + raise RuntimeError("temporary") + return task["id"] + + finish(runner, execute, setup=object) + + assert len(contexts) == 2 + assert contexts[0] is contexts[1] + assert runner.get("a")["failure_count"] == 1 + + +def test_setup_failure_preserves_tasks_and_releases_execution( + module, runner, tmp_path, caplog +): + runner.add([{"id": "a"}, {"id": "b"}]) + caplog.set_level("ERROR", logger=module.__name__) + + def fail_setup(): + raise RuntimeError("setup failed") + + runner.start(lambda task, context: task["id"], setup=fail_setup) + assert runner.wait(5) + + status = runner.status() + assert status["state"] == "interrupted" + assert status["pending"] == 2 + assert status["worker_error"]["type"] == "RuntimeError" + assert status["worker_error"]["message"] == "setup failed" + assert all(record["attempt_count"] == 0 for record in runner.results()) + assert "TaskRunner test: setup failed" in caplog.messages + + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "other"}]) + finish(other, lambda task, context: task["id"]) + + setup_calls = [] + + def setup(): + setup_calls.append(True) + return "ready" + + finish(runner, lambda task, context: context, setup=setup) + assert len(setup_calls) == 1 + assert runner.status()["worker_error"] is None + assert [record["result"] for record in runner.results()] == ["ready", "ready"] + + +def test_pause_during_setup_is_responsive_and_claims_no_task(module, runner, tmp_path): + entered = threading.Event() + release = threading.Event() + contexts = [] + executor_calls = [] + runner.add([{"id": "a"}, {"id": "b"}]) + + def setup(): + context = object() + contexts.append(context) + entered.set() + assert release.wait(5) + return context + + runner.start(lambda task, context: executor_calls.append(task["id"]), setup=setup) + try: + assert entered.wait(5) + assert module.TaskRunner.open("test", root=tmp_path) is runner + status = runner.status() + assert status["state"] == "setting_up" + assert status["current"] is None + assert all(record["attempt_count"] == 0 for record in runner.results()) + assert runner.wait(0.01) is False + + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "other"}]) + with pytest.raises(module.TaskRunnerBusyError): + other.start(lambda task, context: None) + + runner.pause() + finally: + release.set() + + assert runner.wait(5) + assert runner.status()["state"] == "paused" + assert executor_calls == [] + assert all(record["attempt_count"] == 0 for record in runner.results()) + + finish( + runner, + lambda task, context: task["id"], + setup=lambda: contexts.append(object()) or contexts[-1], + ) + assert len(contexts) == 2 + assert contexts[0] is not contexts[1] + + +def test_setup_status_transitions_to_running_before_task(runner): + setup_entered = threading.Event() + release_setup = threading.Event() + execute_entered = threading.Event() + release_execute = threading.Event() + runner.add([{"id": "a"}, {"id": "b"}]) + + def setup(): + setup_entered.set() + assert release_setup.wait(5) + return object() + + def execute(task, context): + execute_entered.set() + assert release_execute.wait(5) + return task["id"] + + runner.start(execute, setup=setup) + try: + assert setup_entered.wait(5) + setting_up = runner.status() + assert setting_up["state"] == "setting_up" + assert setting_up["pending"] == 2 + assert setting_up["running"] == 0 + assert setting_up["current"] is None + + release_setup.set() + assert execute_entered.wait(5) + running = runner.status() + assert running["state"] == "running" + assert running["running"] == 1 + assert running["current"] == "a" + finally: + release_setup.set() + release_execute.set() + + assert runner.wait(5) + assert runner.status()["state"] == "completed" + + +def test_no_setup_goes_directly_to_running(runner): + entered = threading.Event() + release = threading.Event() + runner.add([{"id": "a"}]) + + def execute(task, context): + assert context is None + entered.set() + assert release.wait(5) + return task["id"] + + runner.start(execute) + try: + assert entered.wait(5) + assert runner.status()["state"] == "running" + finally: + release.set() + + assert runner.wait(5) + + +def test_setup_failure_takes_precedence_over_pause(runner): + entered = threading.Event() + release = threading.Event() + runner.add([{"id": "a"}]) + + def setup(): + entered.set() + assert release.wait(5) + raise RuntimeError("failed after pause") + + runner.start(lambda task, context: None, setup=setup) + try: + assert entered.wait(5) + assert runner.status()["state"] == "setting_up" + runner.pause() + finally: + release.set() + + assert runner.wait(5) + status = runner.status() + assert status["state"] == "interrupted" + assert status["worker_error"]["message"] == "failed after pause" + assert runner.get("a")["attempt_count"] == 0 + + +def test_no_work_and_rejected_starts_do_not_call_setup(module, tmp_path): + setup_calls = [] + + def setup(): + setup_calls.append(True) + + empty = module.TaskRunner.create("empty", root=tmp_path) + empty.start(lambda task, context: None, setup=setup) + assert empty.status()["state"] == "idle" + + completed = module.TaskRunner.create("completed", root=tmp_path) + completed.add([{"id": "a"}]) + finish(completed, lambda task, context: None) + completed.start(lambda task, context: None, setup=setup) + assert completed.status()["state"] == "completed" + + active = module.TaskRunner.create("active", root=tmp_path) + active.add([{"id": "a"}]) + entered = threading.Event() + release = threading.Event() + + def blocking_setup(): + entered.set() + assert release.wait(5) + + active.start(lambda task, context: None, setup=blocking_setup) + try: + assert entered.wait(5) + with pytest.raises(module.TaskRunnerAlreadyRunningError): + active.start(lambda task, context: None, setup=setup) + + blocked = module.TaskRunner.create("blocked", root=tmp_path) + blocked.add([{"id": "a"}]) + with pytest.raises(module.TaskRunnerBusyError): + blocked.start(lambda task, context: None, setup=setup) + finally: + active.pause() + release.set() + assert active.wait(5) + + closed = module.TaskRunner.create("closed", root=tmp_path) + closed.add([{"id": "a"}]) + closed.close() + with pytest.raises(module.TaskRunnerClosedError): + closed.start(lambda task, context: None, setup=setup) + + assert setup_calls == [] + + +def test_callback_validation_and_falsey_setup(module, runner, tmp_path): + runner.add([{"id": "a"}]) + before = runner.results() + + with pytest.raises(TypeError, match="execute must be callable"): + runner.start(None) + with pytest.raises(TypeError, match="setup must be callable or None"): + runner.start(lambda task, context: None, setup=object()) + + assert runner.results() == before + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "b"}]) + finish(other, lambda task, context: None) + + class FalseySetup: + def __init__(self): + self.calls = 0 + + def __bool__(self): + return False + + def __call__(self): + self.calls += 1 + + setup = FalseySetup() + contexts = [] + finish( + runner, + lambda task, context: contexts.append(context), + setup=setup, + ) + assert setup.calls == 1 + assert contexts == [None] + + +def test_setup_failure_preserves_partially_completed_run(module, tmp_path): + runner = module.TaskRunner.create("mixed", root=tmp_path, max_attempts=1) + runner.add([{"id": "a"}, {"id": "b"}, {"id": "c"}]) + + def execute(task, context): + if task["id"] == "b": + runner.pause() + raise ValueError("permanent") + return task["id"] + + finish(runner, execute) + assert [record["status"] for record in runner.results()] == [ + "done", + "failed", + "pending", + ] + before = runner.results() + + def fail_setup(): + raise RuntimeError("cannot initialize") + + runner.start(lambda task, context: task["id"], setup=fail_setup) + assert runner.wait(5) + assert runner.results() == before + assert runner.status()["state"] == "interrupted" + + calls = [] + finish( + runner, + lambda task, context: calls.append(task["id"]) or task["id"], + setup=object, + ) + assert calls == ["c"] + assert runner.status()["worker_error"] is None + + +@pytest.mark.parametrize("point", ["execute", "ack", "ack_failed"]) +def test_abrupt_process_death(module, tmp_path, point): + code = """import sys, os +from pythonhere.tasks_here import TaskRunner as T +r = T.create("crash", root=sys.argv[1], max_attempts=1) +r.add([{"id":"a"}, {"id":"b"}, {"id":"c"}]) +point = sys.argv[2] +if point != "execute": + original = getattr(r._queue, point) + def stop(*args, **kwargs): + if r._current_task_id == "b": + os._exit(17) + return original(*args, **kwargs) + setattr(r._queue, point, stop) +def execute(task, context): + assert context == "child-context" + if task["id"] == "b": + if point == "execute": os._exit(17) + if point == "ack_failed": raise ValueError("permanent") + return task["id"] +r.start(execute, setup=lambda: "child-context") +r.wait(5) +""" + child = subprocess.run( + [sys.executable, "-c", code, str(tmp_path), point], timeout=10, check=False + ) + assert child.returncode == 17 + runner = module.TaskRunner.open("crash", root=tmp_path) + assert runner.get("a")["status"] == "done" + expected = {"execute": "pending", "ack": "done", "ack_failed": "failed"}[point] + assert runner.get("b")["status"] == expected + expected_recovery = { + "execute": {"pending": 2, "completed": 1, "failed": 0, "progress": 1 / 3}, + "ack": {"pending": 1, "completed": 2, "failed": 0, "progress": 2 / 3}, + "ack_failed": { + "pending": 1, + "completed": 1, + "failed": 1, + "progress": 2 / 3, + }, + }[point] + recovered_status = runner.status() + assert recovered_status["total"] == 3 + assert recovered_status["running"] == 0 + assert recovered_status["state"] == "interrupted" + for key, value in expected_recovery.items(): + assert recovered_status[key] == value + calls = [] + + def execute_recovered(task, context): + assert context == "parent-context" + calls.append(task["id"]) + return task["id"] + + finish( + runner, + execute_recovered, + setup=lambda: "parent-context", + ) + assert calls == (["b", "c"] if point == "execute" else ["c"]) + final_status = runner.status() + assert final_status["total"] == 3 + assert final_status["pending"] == 0 + assert final_status["running"] == 0 + assert final_status["completed"] == (2 if point == "ack_failed" else 3) + assert final_status["failed"] == (1 if point == "ack_failed" else 0) + assert final_status["progress"] == 1.0 + assert final_status["state"] == "completed" + if point == "execute": + assert runner.get("b")["attempt_count"] == 2 + assert runner.get("b")["failure_count"] == 0 + assert runner.get("b")["attempts"][0]["interrupted"] is True + + +def test_storage_paths(module, tmp_path, monkeypatch): + monkeypatch.delenv("PYTHONHERE_TASKS_DIR", raising=False) + monkeypatch.delenv("ANDROID_ARGUMENT", raising=False) + monkeypatch.setenv("XDG_DATA_HOME", str(tmp_path)) + assert module.task_runs_directory() == tmp_path / "pythonhere/task-runs" + android = ModuleType("android") + storage = ModuleType("android.storage") + storage.app_storage_path = lambda: str(tmp_path / "actual-package") + monkeypatch.setitem(sys.modules, "android", android) + monkeypatch.setitem(sys.modules, "android.storage", storage) + monkeypatch.setenv("ANDROID_ARGUMENT", "1") + assert module.task_runs_directory() == tmp_path / "actual-package/task-runs" + monkeypatch.setenv("PYTHONHERE_TASKS_DIR", str(tmp_path / "override")) + assert module.task_runs_directory() == tmp_path / "override" + + +def test_stale_setting_up_state_is_interrupted(module, runner, tmp_path): + runner.add([{"id": "a"}]) + runner._refresh_meta(state="setting_up") + assert runner.status()["state"] == "interrupted" + runner.close() + + listed = next(item for item in module.TaskRunner.list(root=tmp_path)) + assert listed["state"] == "interrupted" + + reopened = module.TaskRunner.open("test", root=tmp_path) + assert reopened.status()["state"] == "interrupted" + + +def test_thread_start_failure_releases_execution(module, runner, tmp_path, monkeypatch): + runner.add([{"id": "a"}]) + + def broken_start(thread): + raise RuntimeError("cannot start thread") + + with monkeypatch.context() as patch: + patch.setattr(threading.Thread, "start", broken_start) + with pytest.raises(RuntimeError): + runner.start(lambda task, context: None, setup=object) + assert runner.status()["state"] == "interrupted" + assert module._read_json(runner._meta_path)["state"] == "interrupted" + other = module.TaskRunner.create("other", root=tmp_path) + other.add([{"id": "b"}]) + finish(other, lambda task, context: None) + finish(runner, lambda task, context: None) + + +def test_result_storage_failure_is_recoverable(runner, monkeypatch): + runner.add([{"id": "a"}, {"id": "b"}]) + update = runner._queue.update + + def broken_update(item, *args, **kwargs): + if item["data"].get("result_present"): + raise OSError("disk full") + return update(item, *args, **kwargs) + + with monkeypatch.context() as patch: + patch.setattr(runner._queue, "update", broken_update) + runner.start(lambda task, context: "ok") + assert runner.wait(5) + assert runner.status()["state"] == "interrupted" + assert runner.status()["worker_error"]["type"] == "OSError" + assert runner.get("b")["attempt_count"] == 0 + finish(runner, lambda task, context: "ok") + assert runner.status()["completed"] == 2 diff --git a/uv.lock b/uv.lock index 15181d2..a17150e 100644 --- a/uv.lock +++ b/uv.lock @@ -613,16 +613,16 @@ wheels = [ [[package]] name = "herethere" -version = "0.3.2" +version = "0.3.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "asyncssh", marker = "sys_platform == 'linux'" }, { name = "click", marker = "sys_platform == 'linux'" }, { name = "python-dotenv", marker = "sys_platform == 'linux'" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/2d/ef/241312c499ea63089cd8133f102322f8d4824d87d70431cfe52b3009c338/herethere-0.3.2.tar.gz", hash = "sha256:24c5e8d319103d0a8dc4fac9b3b267051c1395065d2990a449fa48a7bd2c0844", size = 63022, upload-time = "2026-08-24T16:33:11.802Z" } +sdist = { url = "https://files.pythonhosted.org/packages/8c/d5/df9024a5d2a43298cbeb5a644a8a0c1db4c929d93194fb031038d32f9c17/herethere-0.3.3.tar.gz", hash = "sha256:cd5e75289a49cad5205eaaaa92ed755b311cc940d87e937ee68a13b5a0df91bc", size = 66772, upload-time = "2026-10-14T17:59:54.388Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/41/b9/94950a1cb3fd7160d5684f86fb241f160a7e5004b1d02d83efe72ccace00/herethere-0.3.2-py3-none-any.whl", hash = "sha256:aeb24092eaa612d5f1f1ebabd6fa627509ce8d4f02fd6d13e32b218643e457ca", size = 65178, upload-time = "2026-08-24T16:33:10.712Z" }, + { url = "https://files.pythonhosted.org/packages/24/fd/abf0ad9ec2d35c159f60efef81f79c61f9cea3a1169c08c830f4875d2fd8/herethere-0.3.3-py3-none-any.whl", hash = "sha256:46037e0db517535882f9378961453758b55f15a57ae0de4a2646c741aac1ae00", size = 68014, upload-time = "2026-10-14T17:59:53.411Z" }, ] [package.optional-dependencies] @@ -1346,6 +1346,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/99/5d/8268b644392ee874ee82a635cd0df1773de230bde356c38de28e298392cc/parso-0.8.7-py2.py3-none-any.whl", hash = "sha256:a8926eb2a1b915486941fdbd31e86a4baf88fe8c210f25f2f35ecec5b574ca1c", size = 107025, upload-time = "2026-05-01T23:12:58.867Z" }, ] +[[package]] +name = "persist-queue" +version = "1.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/2f/9e/865b2a173a272d2f52b0f50534e13c38c159877251a987e0863fc7376acd/persist_queue-1.1.0.tar.gz", hash = "sha256:4c042a3d39c9af4fa24497da76697fb4fff7abe6af04bcf55f099e0c23bc2c67", size = 39294, upload-time = "2025-10-25T13:21:28.339Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/07/88/7248345679ad5001cdc0211eb83303c62659f86ae7024170c0bc0afd4e4e/persist_queue-1.1.0-py3-none-any.whl", hash = "sha256:be431ad90cd57621be5563dcd2424e21d81db3bb8cdfb918ade722369d640763", size = 53076, upload-time = "2025-10-25T13:21:26.577Z" }, +] + [[package]] name = "pexpect" version = "4.9.0" @@ -1640,6 +1649,7 @@ dependencies = [ { name = "ipython", version = "8.39.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version < '3.11' and sys_platform == 'linux'" }, { name = "ipython", version = "9.13.0", source = { registry = "https://pypi.org/simple" }, marker = "python_full_version >= '3.11' and sys_platform == 'linux'" }, { name = "ipywidgets", marker = "sys_platform == 'linux'" }, + { name = "persist-queue", marker = "sys_platform == 'linux'" }, { name = "pillow", marker = "sys_platform == 'linux'" }, ] @@ -1677,10 +1687,11 @@ docker = [ [package.metadata] requires-dist = [ - { name = "herethere", extras = ["magic"], specifier = ">=0.3.2" }, + { name = "herethere", extras = ["magic"], specifier = ">=0.3.3" }, { name = "ipython" }, { name = "ipywidgets" }, { name = "litert-lm-api", marker = "extra == 'litert'", specifier = "==0.16.0" }, + { name = "persist-queue", specifier = "==1.1.0" }, { name = "pillow" }, { name = "requests", marker = "extra == 'litert'" }, ]