fromscratch-pystack 0.5.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fromscratch_pystack-0.5.0.dist-info/METADATA +510 -0
- fromscratch_pystack-0.5.0.dist-info/RECORD +43 -0
- fromscratch_pystack-0.5.0.dist-info/WHEEL +4 -0
- fromscratch_pystack-0.5.0.dist-info/entry_points.txt +3 -0
- fromscratch_pystack-0.5.0.dist-info/licenses/LICENSE +21 -0
- pystack/__init__.py +1 -0
- pystack/_version.py +24 -0
- pystack/adapters/__init__.py +1 -0
- pystack/adapters/db_storage.py +157 -0
- pystack/adapters/os_pebble.py +118 -0
- pystack/adapters/pebble_db.py +85 -0
- pystack/cli.py +127 -0
- pystack/environment.py +272 -0
- pystack/plugins/__init__.py +1 -0
- pystack/plugins/_dbcrash_child.py +56 -0
- pystack/plugins/_schedagents.py +37 -0
- pystack/plugins/_schedalerts.py +103 -0
- pystack/plugins/_schedweb.py +79 -0
- pystack/plugins/_shared.py +26 -0
- pystack/plugins/_webdemo.py +171 -0
- pystack/plugins/base.py +201 -0
- pystack/plugins/coldb_plugin.py +165 -0
- pystack/plugins/crypto_plugin.py +115 -0
- pystack/plugins/docdb_plugin.py +172 -0
- pystack/plugins/git_plugin.py +94 -0
- pystack/plugins/graphdb_plugin.py +206 -0
- pystack/plugins/kv_plugin.py +156 -0
- pystack/plugins/llm_plugin.py +102 -0
- pystack/plugins/mq_plugin.py +290 -0
- pystack/plugins/net_plugin.py +247 -0
- pystack/plugins/pydb_plugin.py +111 -0
- pystack/plugins/registry.py +150 -0
- pystack/plugins/sched_plugin.py +235 -0
- pystack/plugins/search_plugin.py +151 -0
- pystack/plugins/tsdb_plugin.py +175 -0
- pystack/plugins/vecdb_plugin.py +168 -0
- pystack/plugins/web_plugin.py +95 -0
- pystack/py.typed +0 -0
- pystack/web/__init__.py +1 -0
- pystack/web/app.py +138 -0
- pystack/web/static/app.js +105 -0
- pystack/web/static/style.css +158 -0
- pystack/web/templates/index.html +59 -0
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""PyDB integration plugin for PyStack.
|
|
2
|
+
|
|
3
|
+
PyDB itself is wired in through the environment (the ``sql`` command and the
|
|
4
|
+
Pebble ``db`` module); this plugin adds the shell demos that show off what
|
|
5
|
+
PyDB can do.
|
|
6
|
+
|
|
7
|
+
Shell command ``dbcrash`` pulls the plug on a journalled database. A helper
|
|
8
|
+
program writes three job runs in the journal "diary", starts a fourth and
|
|
9
|
+
dies before finishing it, like a power cut. We check it really died that
|
|
10
|
+
way (it exits with an unusual code, 9, because an ordinary error exits with
|
|
11
|
+
1), then reopen the folder: recovery reads the diary, puts back the three
|
|
12
|
+
finished runs, and leaves out the one that was never signed off. If the
|
|
13
|
+
helper failed some other way, we say so and show its last error lines.
|
|
14
|
+
|
|
15
|
+
This plugin has no Pebble module.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
from datetime import date
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from pydb.database import Database
|
|
25
|
+
from pydb.record import Value
|
|
26
|
+
from pydb.types import to_iso
|
|
27
|
+
|
|
28
|
+
from pystack.plugins._dbcrash_child import CRASH_EXIT_CODE, TABLE, UNFINISHED_RUN
|
|
29
|
+
from pystack.plugins.base import Plugin, PluginInfo, ShellCommand
|
|
30
|
+
|
|
31
|
+
CHILD_MODULE = "pystack.plugins._dbcrash_child"
|
|
32
|
+
CHILD_TIMEOUT = 20
|
|
33
|
+
ERROR_LINES = 5
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _show(value: Value) -> str:
|
|
37
|
+
"""Return *value* as text, with dates and timestamps in their ISO form."""
|
|
38
|
+
return to_iso(value) if isinstance(value, date) else str(value)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def child_command(folder: Path) -> list[str]:
|
|
42
|
+
"""Return the command that runs the crashing helper on *folder*."""
|
|
43
|
+
return [sys.executable, "-m", CHILD_MODULE, str(folder)]
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def recovery_lines(folder: Path) -> list[str]:
|
|
47
|
+
"""Reopen *folder* and describe every job run that recovery brought back."""
|
|
48
|
+
lines = ["Reopening the folder -- recovery reads the journal diary:"]
|
|
49
|
+
with Database(folder, journal=True) as db:
|
|
50
|
+
runs = db.get_table(TABLE)
|
|
51
|
+
records = runs.select()
|
|
52
|
+
lines.extend(
|
|
53
|
+
f" job {r.record_id}: {r['job']} ran on {_show(r['run_date'])}, "
|
|
54
|
+
f"started {_show(r['started'])}"
|
|
55
|
+
for r in records
|
|
56
|
+
)
|
|
57
|
+
if all(r["job"] != UNFINISHED_RUN[0] for r in records):
|
|
58
|
+
lines.append("job 4: never committed, so it's gone")
|
|
59
|
+
else:
|
|
60
|
+
lines.append("job 4: survived -- that should never happen!")
|
|
61
|
+
lines.append(f"The next new job run gets ID {runs.next_id}.")
|
|
62
|
+
return lines
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _dbcrash_cmd(_args: list[str]) -> str:
|
|
66
|
+
"""Crash a helper mid-transaction, reopen its database and report what survived."""
|
|
67
|
+
lines = ["Starting a helper program that writes job runs to a journalled database..."]
|
|
68
|
+
with tempfile.TemporaryDirectory() as tmp:
|
|
69
|
+
folder = Path(tmp) / "jobs-db"
|
|
70
|
+
result = subprocess.run(
|
|
71
|
+
child_command(folder),
|
|
72
|
+
check=False,
|
|
73
|
+
capture_output=True,
|
|
74
|
+
text=True,
|
|
75
|
+
timeout=CHILD_TIMEOUT,
|
|
76
|
+
)
|
|
77
|
+
if result.returncode != CRASH_EXIT_CODE:
|
|
78
|
+
lines.append(
|
|
79
|
+
f"The helper program stopped unexpectedly (exit code {result.returncode}) "
|
|
80
|
+
"instead of crashing in the middle of job 4, so there is nothing to recover."
|
|
81
|
+
)
|
|
82
|
+
lines.extend(f" {line}" for line in result.stderr.strip().splitlines()[-ERROR_LINES:])
|
|
83
|
+
return "\n".join(lines)
|
|
84
|
+
lines.append(
|
|
85
|
+
f"The helper program crashed (exit code {result.returncode}) in the middle of job 4."
|
|
86
|
+
)
|
|
87
|
+
lines.append("")
|
|
88
|
+
lines.extend(recovery_lines(folder))
|
|
89
|
+
return "\n".join(lines)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
class PyDBPlugin(Plugin):
|
|
93
|
+
"""Add PyDB's shell demos to PyStack (currently ``dbcrash``)."""
|
|
94
|
+
|
|
95
|
+
def info(self) -> PluginInfo:
|
|
96
|
+
"""Return plugin metadata."""
|
|
97
|
+
return PluginInfo(
|
|
98
|
+
name="PyDB",
|
|
99
|
+
description="Crash-recovery demo for PyDB's journal",
|
|
100
|
+
version="0.1.0",
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
def shell_commands(self) -> list[ShellCommand]:
|
|
104
|
+
"""Return the dbcrash shell command."""
|
|
105
|
+
return [
|
|
106
|
+
ShellCommand(
|
|
107
|
+
name="dbcrash",
|
|
108
|
+
handler=_dbcrash_cmd,
|
|
109
|
+
help_text="Crash a journalled PyDB mid-transaction and watch it recover",
|
|
110
|
+
),
|
|
111
|
+
]
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
"""Plugin registry -- discover and activate plugins.
|
|
2
|
+
|
|
3
|
+
The registry loads plugins, calls their hooks, and wires them into
|
|
4
|
+
the PyStack environment. Plugins are registered manually via
|
|
5
|
+
``register()`` or discovered via Python entry points.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import importlib.metadata
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
from pebble import StdlibModule
|
|
12
|
+
from py_os.shell import Shell
|
|
13
|
+
|
|
14
|
+
from pystack.plugins.base import Plugin, PluginInfo, shell_handler
|
|
15
|
+
|
|
16
|
+
ENTRY_POINT_GROUP = "pystack.plugins"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class PluginRegistry:
|
|
20
|
+
"""Manage plugin lifecycle: registration, activation, and listing.
|
|
21
|
+
|
|
22
|
+
Plugins register shell commands, Pebble stdlib modules, and can
|
|
23
|
+
run custom boot logic.
|
|
24
|
+
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
__slots__ = ("_pebble_modules", "_plugins")
|
|
28
|
+
|
|
29
|
+
def __init__(self) -> None:
|
|
30
|
+
"""Create an empty plugin registry."""
|
|
31
|
+
self._plugins: list[Plugin] = []
|
|
32
|
+
self._pebble_modules: dict[str, StdlibModule] = {}
|
|
33
|
+
|
|
34
|
+
@property
|
|
35
|
+
def plugins(self) -> list[Plugin]:
|
|
36
|
+
"""Return all registered plugins."""
|
|
37
|
+
return list(self._plugins)
|
|
38
|
+
|
|
39
|
+
def register(self, plugin: Plugin) -> None:
|
|
40
|
+
"""Register a plugin manually.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
plugin: The plugin instance to register.
|
|
44
|
+
|
|
45
|
+
"""
|
|
46
|
+
self._plugins.append(plugin)
|
|
47
|
+
|
|
48
|
+
def discover(self) -> int:
|
|
49
|
+
"""Discover and register plugins via Python entry points.
|
|
50
|
+
|
|
51
|
+
Scans ``pystack.plugins`` entry point group. Each entry point
|
|
52
|
+
should resolve to a Plugin subclass.
|
|
53
|
+
|
|
54
|
+
Returns:
|
|
55
|
+
The number of plugins discovered.
|
|
56
|
+
|
|
57
|
+
"""
|
|
58
|
+
count = 0
|
|
59
|
+
eps = importlib.metadata.entry_points()
|
|
60
|
+
for ep in eps.select(group=ENTRY_POINT_GROUP):
|
|
61
|
+
plugin_cls = ep.load()
|
|
62
|
+
if isinstance(plugin_cls, type) and issubclass(plugin_cls, Plugin):
|
|
63
|
+
self.register(plugin_cls())
|
|
64
|
+
count += 1
|
|
65
|
+
return count
|
|
66
|
+
|
|
67
|
+
def activate_all(self, shell: Shell | None = None, data_dir: Path | None = None) -> None:
|
|
68
|
+
"""Activate all registered plugins.
|
|
69
|
+
|
|
70
|
+
Registers shell commands and Pebble modules, then calls each
|
|
71
|
+
plugin's ``load_state()`` (when there is a data folder) and
|
|
72
|
+
``on_boot()`` hooks.
|
|
73
|
+
|
|
74
|
+
Args:
|
|
75
|
+
shell: The PyOS shell to register commands in (optional).
|
|
76
|
+
data_dir: The environment's data folder; each plugin loads from
|
|
77
|
+
``data_dir / plugin.pebble_module_name()``. ``None`` skips
|
|
78
|
+
loading.
|
|
79
|
+
|
|
80
|
+
"""
|
|
81
|
+
for plugin in self._plugins:
|
|
82
|
+
# Register shell commands, each wrapped in a safety net so a bad
|
|
83
|
+
# argument prints an error instead of crashing the shell.
|
|
84
|
+
if shell is not None:
|
|
85
|
+
for cmd in plugin.shell_commands():
|
|
86
|
+
shell._commands[cmd.name] = shell_handler(cmd.handler) # noqa: SLF001
|
|
87
|
+
|
|
88
|
+
# Collect the plugin's Pebble module. It's handed to Pebble with
|
|
89
|
+
# each run (never written into Pebble's shared table), so two
|
|
90
|
+
# environments can't see each other's modules.
|
|
91
|
+
stdlib = plugin.pebble_stdlib()
|
|
92
|
+
if stdlib is not None:
|
|
93
|
+
self._pebble_modules[plugin.pebble_module_name()] = stdlib
|
|
94
|
+
|
|
95
|
+
# Load saved data, then run custom boot logic.
|
|
96
|
+
if data_dir is not None:
|
|
97
|
+
plugin.load_state(data_dir / plugin.pebble_module_name())
|
|
98
|
+
plugin.on_boot()
|
|
99
|
+
|
|
100
|
+
def save_all(self, data_dir: Path) -> list[tuple[str, Exception]]:
|
|
101
|
+
"""Ask every plugin to save, carrying on past failures.
|
|
102
|
+
|
|
103
|
+
Args:
|
|
104
|
+
data_dir: The environment's data folder.
|
|
105
|
+
|
|
106
|
+
Returns:
|
|
107
|
+
``(plugin module name, error)`` for each plugin that failed.
|
|
108
|
+
|
|
109
|
+
"""
|
|
110
|
+
failures: list[tuple[str, Exception]] = []
|
|
111
|
+
for plugin in self._plugins:
|
|
112
|
+
name = plugin.pebble_module_name()
|
|
113
|
+
try:
|
|
114
|
+
plugin.save_state(data_dir / name)
|
|
115
|
+
except Exception as exc: # noqa: BLE001 -- reported by the caller
|
|
116
|
+
failures.append((name, exc))
|
|
117
|
+
return failures
|
|
118
|
+
|
|
119
|
+
def shutdown_all(self) -> list[tuple[str, Exception]]:
|
|
120
|
+
"""Call every plugin's ``on_shutdown()``, carrying on past failures.
|
|
121
|
+
|
|
122
|
+
Returns:
|
|
123
|
+
``(plugin module name, error)`` for each plugin that failed.
|
|
124
|
+
|
|
125
|
+
"""
|
|
126
|
+
failures: list[tuple[str, Exception]] = []
|
|
127
|
+
for plugin in self._plugins:
|
|
128
|
+
try:
|
|
129
|
+
plugin.on_shutdown()
|
|
130
|
+
except Exception as exc: # noqa: BLE001 -- reported by the caller
|
|
131
|
+
failures.append((plugin.pebble_module_name(), exc))
|
|
132
|
+
return failures
|
|
133
|
+
|
|
134
|
+
def pebble_modules(self) -> dict[str, StdlibModule]:
|
|
135
|
+
"""Return the Pebble modules of every activated plugin, by import name.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
A new dict mapping each module name (e.g. ``"kv"``) to its module.
|
|
139
|
+
|
|
140
|
+
"""
|
|
141
|
+
return dict(self._pebble_modules)
|
|
142
|
+
|
|
143
|
+
def list_plugins(self) -> list[PluginInfo]:
|
|
144
|
+
"""Return info for all registered plugins.
|
|
145
|
+
|
|
146
|
+
Returns:
|
|
147
|
+
A list of PluginInfo objects.
|
|
148
|
+
|
|
149
|
+
"""
|
|
150
|
+
return [p.info() for p in self._plugins]
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""PyScheduler integration plugin for PyStack.
|
|
2
|
+
|
|
3
|
+
PyScheduler is a job scheduler, like the timetable and the conductor of
|
|
4
|
+
an orchestra rolled into one: it knows which jobs play when, waits for
|
|
5
|
+
each one's cue (its dependencies), and gives a wobbly player one more go
|
|
6
|
+
(a retry).
|
|
7
|
+
|
|
8
|
+
Shell command ``sched`` runs a tiny nightly chain in a temporary folder.
|
|
9
|
+
It writes a config with three jobs in a row (``extract``, then
|
|
10
|
+
``transform``, then ``load``) plus a ``cleanup`` job that only runs if
|
|
11
|
+
``load`` fails. ``transform`` always fails its first attempt and passes
|
|
12
|
+
its retry, so you can watch a retry happen. The scheduler starts
|
|
13
|
+
in-process on PyNet's event loop with its HTTP API; we trigger the chain
|
|
14
|
+
for a fixed run date, wait for it, and print the board. Then we stop the
|
|
15
|
+
scheduler and start a brand-new one on the same state folder: the runs
|
|
16
|
+
are still there, because every change was written to its journalled
|
|
17
|
+
PyDB store first.
|
|
18
|
+
|
|
19
|
+
Shell command ``schedagents`` (in ``_schedagents.py``) runs a scheduler
|
|
20
|
+
with two remote agents, one pinned job and one job that needs the ``gpu``
|
|
21
|
+
tag, and prints which agent ran each.
|
|
22
|
+
|
|
23
|
+
Shell command ``schedalerts`` (in ``_schedalerts.py``) runs a job that
|
|
24
|
+
always fails and follows its alert: written down first, routed to a
|
|
25
|
+
``log`` notifier, and delivered.
|
|
26
|
+
|
|
27
|
+
Shell command ``schedweb`` (in ``_schedweb.py``) stocks a demo folder with
|
|
28
|
+
a dozen jobs and three days of runs and serves PyScheduler's web UI over
|
|
29
|
+
it until Ctrl-C (or ``--seconds N``).
|
|
30
|
+
|
|
31
|
+
This plugin has no Pebble module.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
import tempfile
|
|
35
|
+
import textwrap
|
|
36
|
+
import time
|
|
37
|
+
from collections.abc import Callable
|
|
38
|
+
from pathlib import Path
|
|
39
|
+
|
|
40
|
+
from pynet.loop import Event, run, run_in_thread, sleep, spawn, timeout
|
|
41
|
+
from pyscheduler.client import ApiClient
|
|
42
|
+
from pyscheduler.service import serve
|
|
43
|
+
|
|
44
|
+
from pystack.plugins.base import Plugin, PluginInfo, ShellCommand
|
|
45
|
+
|
|
46
|
+
RUN_DATE = "2026-10-19"
|
|
47
|
+
CHAIN = ("extract", "transform", "load")
|
|
48
|
+
CLEANUP = "cleanup"
|
|
49
|
+
READY_SECONDS = 5.0
|
|
50
|
+
DONE_SECONDS = 5.0
|
|
51
|
+
POLL = 0.02
|
|
52
|
+
FINAL_STATES = frozenset({"succeeded", "failed", "skipped", "cancelled"})
|
|
53
|
+
|
|
54
|
+
JOBS = """
|
|
55
|
+
jobs:
|
|
56
|
+
extract:
|
|
57
|
+
command: sleep 0.1
|
|
58
|
+
schedule: manual
|
|
59
|
+
transform:
|
|
60
|
+
command: sh -c 'test "$PYSCHED_ATTEMPT" -gt 1'
|
|
61
|
+
depends_on: [extract]
|
|
62
|
+
retries: {count: 1, delay: 1s}
|
|
63
|
+
load:
|
|
64
|
+
command: sleep 0.1
|
|
65
|
+
depends_on: [transform]
|
|
66
|
+
cleanup:
|
|
67
|
+
command: echo tidying up after a failed load
|
|
68
|
+
depends_on:
|
|
69
|
+
- {job: load, on: failure}
|
|
70
|
+
"""
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def write_config(folder: Path) -> Path:
|
|
74
|
+
"""Write the demo's ``pysched.yaml`` into ``folder`` and return its path."""
|
|
75
|
+
header = (
|
|
76
|
+
"scheduler:\n"
|
|
77
|
+
" name: pystack-demo\n"
|
|
78
|
+
f" state_dir: {folder / 'state'}\n"
|
|
79
|
+
f" log_dir: {folder / 'logs'}\n"
|
|
80
|
+
" listen: 127.0.0.1:0\n"
|
|
81
|
+
)
|
|
82
|
+
path = folder / "pysched.yaml"
|
|
83
|
+
path.write_text(header + textwrap.dedent(JOBS).lstrip("\n"), encoding="utf-8")
|
|
84
|
+
return path
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def with_scheduler[T](config: Path, body: Callable[[ApiClient], T]) -> T:
|
|
88
|
+
"""Run the scheduler for ``config`` on the loop, ``body(client)`` on a thread, then stop it."""
|
|
89
|
+
|
|
90
|
+
async def main() -> T:
|
|
91
|
+
"""Start the scheduler, wait until it listens, run the body, then stop."""
|
|
92
|
+
stop = Event()
|
|
93
|
+
ports: list[int] = []
|
|
94
|
+
task = spawn(serve(config, ready=ports.append, stop=stop), name="sched-demo")
|
|
95
|
+
async with timeout(READY_SECONDS):
|
|
96
|
+
while not ports and not task.done():
|
|
97
|
+
await sleep(POLL)
|
|
98
|
+
if task.done():
|
|
99
|
+
task.result() # raises whatever stopped the scheduler
|
|
100
|
+
msg = "the scheduler stopped before it was ready"
|
|
101
|
+
raise RuntimeError(msg)
|
|
102
|
+
client = ApiClient(f"http://127.0.0.1:{ports[0]}", None)
|
|
103
|
+
try:
|
|
104
|
+
return await run_in_thread(lambda: body(client))
|
|
105
|
+
finally:
|
|
106
|
+
stop.set()
|
|
107
|
+
await task
|
|
108
|
+
|
|
109
|
+
return run(main())
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def wait_for_chain(client: ApiClient) -> dict[str, dict[str, object]]:
|
|
113
|
+
"""Wait until every job's run for ``RUN_DATE`` has finished; return them by job.
|
|
114
|
+
|
|
115
|
+
Raises:
|
|
116
|
+
TimeoutError: If they have not all finished within ``DONE_SECONDS``.
|
|
117
|
+
|
|
118
|
+
"""
|
|
119
|
+
deadline = time.monotonic() + DONE_SECONDS
|
|
120
|
+
jobs = (*CHAIN, CLEANUP)
|
|
121
|
+
while True:
|
|
122
|
+
runs = {run["job"]: run for run in client.runs(run_date=RUN_DATE)["runs"]}
|
|
123
|
+
if all(runs.get(job, {}).get("state") in FINAL_STATES for job in jobs):
|
|
124
|
+
return runs
|
|
125
|
+
if time.monotonic() > deadline:
|
|
126
|
+
msg = f"the chain did not finish within {DONE_SECONDS:g} s"
|
|
127
|
+
raise TimeoutError(msg)
|
|
128
|
+
time.sleep(POLL)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def board_lines(runs: dict[str, dict[str, object]]) -> list[str]:
|
|
132
|
+
"""Return the board: one line per job with its state, attempts and duration."""
|
|
133
|
+
lines = [f" {'JOB':<10} {'STATE':<10} {'ATTEMPTS':<9} DURATION"]
|
|
134
|
+
for job in (*CHAIN, CLEANUP):
|
|
135
|
+
run = runs[job]
|
|
136
|
+
seconds = run.get("duration_seconds")
|
|
137
|
+
duration = "-" if not isinstance(seconds, float | int) else f"{seconds:.2f}s"
|
|
138
|
+
lines.append(f" {job:<10} {run['state']!s:<10} {run['attempt']!s:<9} {duration}")
|
|
139
|
+
return lines
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def first_start(client: ApiClient) -> list[str]:
|
|
143
|
+
"""Trigger the chain, wait for it and describe what happened."""
|
|
144
|
+
run = client.trigger(CHAIN[0], run_date=RUN_DATE)["run"]
|
|
145
|
+
lines = [f"Triggered {run['run_id']}; the rest of the chain follows on its own."]
|
|
146
|
+
runs = wait_for_chain(client)
|
|
147
|
+
lines.append("")
|
|
148
|
+
lines.append(f"The board for {RUN_DATE}:")
|
|
149
|
+
lines.extend(board_lines(runs))
|
|
150
|
+
if runs[CLEANUP]["reason"]:
|
|
151
|
+
lines.append(f"{CLEANUP} {runs[CLEANUP]['reason']}")
|
|
152
|
+
return lines
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def second_start(client: ApiClient) -> list[str]:
|
|
156
|
+
"""Look at the runs a brand-new scheduler finds in the old state folder."""
|
|
157
|
+
runs = client.runs(run_date=RUN_DATE)["runs"]
|
|
158
|
+
found = sorted(f"{run['job']} {run['state']}" for run in runs)
|
|
159
|
+
survived = {run["job"] for run in runs} == {*CHAIN, CLEANUP}
|
|
160
|
+
return [
|
|
161
|
+
f"The new scheduler found {len(runs)} runs: {', '.join(found)}",
|
|
162
|
+
"history survived the restart"
|
|
163
|
+
if survived
|
|
164
|
+
else "history was lost -- that should never happen!",
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _sched_cmd(_args: list[str]) -> str:
|
|
169
|
+
"""Run the demo chain, print its board, restart and show the history survived."""
|
|
170
|
+
lines = ["Starting a scheduler on PyNet's event loop..."]
|
|
171
|
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp:
|
|
172
|
+
config = write_config(Path(tmp))
|
|
173
|
+
lines.extend(with_scheduler(config, first_start))
|
|
174
|
+
lines.append("")
|
|
175
|
+
lines.append("Stopping the scheduler and starting a new one on the same state folder...")
|
|
176
|
+
lines.extend(with_scheduler(config, second_start))
|
|
177
|
+
return "\n".join(lines)
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def _schedagents_cmd(args: list[str]) -> str:
|
|
181
|
+
"""Run the remote-agents demo (imported lazily, like ``schedalerts``)."""
|
|
182
|
+
from pystack.plugins._schedagents import schedagents_cmd # noqa: PLC0415
|
|
183
|
+
|
|
184
|
+
return schedagents_cmd(args)
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def _schedalerts_cmd(args: list[str]) -> str:
|
|
188
|
+
"""Run the alert demo (imported lazily: it reuses this module's helpers)."""
|
|
189
|
+
from pystack.plugins._schedalerts import schedalerts_cmd # noqa: PLC0415
|
|
190
|
+
|
|
191
|
+
return schedalerts_cmd(args)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _schedweb_cmd(args: list[str]) -> str:
|
|
195
|
+
"""Serve PyScheduler's web UI over seeded demo runs (imported lazily, like ``schedalerts``)."""
|
|
196
|
+
from pystack.plugins._schedweb import schedweb_cmd # noqa: PLC0415
|
|
197
|
+
|
|
198
|
+
return schedweb_cmd(args)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
class PySchedulerPlugin(Plugin):
|
|
202
|
+
"""Add PyScheduler's shell demos to PyStack (``sched``, ``schedagents``, ``schedalerts``, ``schedweb``)."""
|
|
203
|
+
|
|
204
|
+
def info(self) -> PluginInfo:
|
|
205
|
+
"""Return plugin metadata."""
|
|
206
|
+
return PluginInfo(
|
|
207
|
+
name="PyScheduler",
|
|
208
|
+
description="Run a job chain with a retry and watch its history survive a restart",
|
|
209
|
+
version="0.1.0",
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
def shell_commands(self) -> list[ShellCommand]:
|
|
213
|
+
"""Return the scheduler shell commands."""
|
|
214
|
+
return [
|
|
215
|
+
ShellCommand(
|
|
216
|
+
name="sched",
|
|
217
|
+
handler=_sched_cmd,
|
|
218
|
+
help_text="Run a small job chain on PyScheduler and restart it",
|
|
219
|
+
),
|
|
220
|
+
ShellCommand(
|
|
221
|
+
name="schedagents",
|
|
222
|
+
handler=_schedagents_cmd,
|
|
223
|
+
help_text="Run PyScheduler jobs on remote agents and see which agent ran each",
|
|
224
|
+
),
|
|
225
|
+
ShellCommand(
|
|
226
|
+
name="schedalerts",
|
|
227
|
+
handler=_schedalerts_cmd,
|
|
228
|
+
help_text="Fail a PyScheduler job and follow its alert to a log notifier",
|
|
229
|
+
),
|
|
230
|
+
ShellCommand(
|
|
231
|
+
name="schedweb",
|
|
232
|
+
handler=_schedweb_cmd,
|
|
233
|
+
help_text="Serve PyScheduler's web UI over a few days of demo runs",
|
|
234
|
+
),
|
|
235
|
+
]
|
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""PySearch integration plugin for PyStack.
|
|
2
|
+
|
|
3
|
+
Bridge PySearch's full-text search engine into Pebble so kids can
|
|
4
|
+
create search indices, add documents, and query them with TF-IDF
|
|
5
|
+
ranking from their Pebble programs.
|
|
6
|
+
|
|
7
|
+
A search engine is like the index at the back of a book -- you type a
|
|
8
|
+
word and it instantly tells you which pages mention it, best matches
|
|
9
|
+
first.
|
|
10
|
+
|
|
11
|
+
Pebble module name: ``search``
|
|
12
|
+
|
|
13
|
+
Example Pebble usage::
|
|
14
|
+
|
|
15
|
+
import "search"
|
|
16
|
+
let engine = search_create()
|
|
17
|
+
search_add(engine, "doc1", "the cat sat on the mat")
|
|
18
|
+
search_add(engine, "doc2", "the dog chased the cat")
|
|
19
|
+
let results = search_query(engine, "cat")
|
|
20
|
+
print(results)
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import logging
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from pebble import StdlibModule
|
|
27
|
+
from pebble import Value as PebbleValue
|
|
28
|
+
from pysearch.engine import SearchEngine
|
|
29
|
+
from pysearch.persistence import load_engine, save_engine
|
|
30
|
+
|
|
31
|
+
from pystack.plugins.base import Plugin, PluginInfo, ShellCommand, pebble_method
|
|
32
|
+
|
|
33
|
+
_log = logging.getLogger(__name__)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _engine_number(engine_id: str) -> int:
|
|
37
|
+
"""Return the number in an engine id: ``engine_7`` -> 7."""
|
|
38
|
+
return int(engine_id.removeprefix("engine_"))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _is_engine_id(name: str) -> bool:
|
|
42
|
+
"""Return True for ids this plugin makes itself: ``engine_0``, ``engine_1``, ..."""
|
|
43
|
+
number = name.removeprefix("engine_")
|
|
44
|
+
return name.startswith("engine_") and number.isascii() and number.isdigit()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class SearchPlugin(Plugin):
|
|
48
|
+
"""Integrate PySearch full-text search into PyStack.
|
|
49
|
+
|
|
50
|
+
Register search_create, search_add, and search_query functions in
|
|
51
|
+
Pebble's ``search`` stdlib module. No shell commands -- search is
|
|
52
|
+
more naturally used from Pebble programs.
|
|
53
|
+
"""
|
|
54
|
+
|
|
55
|
+
def __init__(self) -> None:
|
|
56
|
+
"""Start with no data; it is created on first use or loaded at start-up."""
|
|
57
|
+
self._engines: dict[str, SearchEngine] = {}
|
|
58
|
+
self._next_id: list[int] = [0]
|
|
59
|
+
|
|
60
|
+
@pebble_method
|
|
61
|
+
def search_create(self, args: list[PebbleValue]) -> PebbleValue: # noqa: ARG002
|
|
62
|
+
"""Create a new search engine and return its ID string."""
|
|
63
|
+
engine_id = f"engine_{self._next_id[0]}"
|
|
64
|
+
self._next_id[0] += 1
|
|
65
|
+
self._engines[engine_id] = SearchEngine()
|
|
66
|
+
return engine_id
|
|
67
|
+
|
|
68
|
+
@pebble_method
|
|
69
|
+
def search_add(self, args: list[PebbleValue]) -> PebbleValue:
|
|
70
|
+
"""Add a document to a search engine by engine ID."""
|
|
71
|
+
engine_id = str(args[0])
|
|
72
|
+
doc_id = str(args[1])
|
|
73
|
+
text = str(args[2])
|
|
74
|
+
if engine_id not in self._engines:
|
|
75
|
+
return f"error: unknown engine {engine_id}"
|
|
76
|
+
self._engines[engine_id].add(doc_id, text)
|
|
77
|
+
return True
|
|
78
|
+
|
|
79
|
+
@pebble_method
|
|
80
|
+
def search_query(self, args: list[PebbleValue]) -> PebbleValue:
|
|
81
|
+
"""Query a search engine and return a list of [doc_id, score] results."""
|
|
82
|
+
engine_id = str(args[0])
|
|
83
|
+
query = str(args[1])
|
|
84
|
+
if engine_id not in self._engines:
|
|
85
|
+
return f"error: unknown engine {engine_id}"
|
|
86
|
+
results = self._engines[engine_id].search(query)
|
|
87
|
+
pebble_results: list[PebbleValue] = []
|
|
88
|
+
for doc_id, score in results:
|
|
89
|
+
pair: list[PebbleValue] = [doc_id, score]
|
|
90
|
+
pebble_results.append(pair)
|
|
91
|
+
return pebble_results
|
|
92
|
+
|
|
93
|
+
@pebble_method
|
|
94
|
+
def search_list(self, args: list[PebbleValue]) -> PebbleValue: # noqa: ARG002 -- Pebble passes args
|
|
95
|
+
"""Return the ids of every engine, oldest first (including saved ones)."""
|
|
96
|
+
ordered = sorted(self._engines, key=_engine_number)
|
|
97
|
+
ids: list[PebbleValue] = list(ordered)
|
|
98
|
+
return ids
|
|
99
|
+
|
|
100
|
+
def load_state(self, folder: Path) -> None:
|
|
101
|
+
"""Load every saved engine; new engines get ids after the saved ones.
|
|
102
|
+
|
|
103
|
+
Only files named like the ids this plugin makes (``engine_7.json``)
|
|
104
|
+
are engines. Anything else in the folder, even ``engine_.json`` or
|
|
105
|
+
``engine_two.json``, is left alone, with a warning naming it.
|
|
106
|
+
"""
|
|
107
|
+
if not folder.is_dir():
|
|
108
|
+
return
|
|
109
|
+
for path in sorted(folder.iterdir()):
|
|
110
|
+
if path.suffix == ".json" and _is_engine_id(path.stem):
|
|
111
|
+
self._engines[path.stem] = load_engine(path)
|
|
112
|
+
else:
|
|
113
|
+
_log.warning("search: skipping %s, which isn't a saved engine", path.name)
|
|
114
|
+
numbers = [_engine_number(engine_id) for engine_id in self._engines]
|
|
115
|
+
self._next_id[0] = max(numbers, default=-1) + 1
|
|
116
|
+
|
|
117
|
+
def save_state(self, folder: Path) -> None:
|
|
118
|
+
"""Save every engine, one file each."""
|
|
119
|
+
if not self._engines:
|
|
120
|
+
return
|
|
121
|
+
folder.mkdir(parents=True, exist_ok=True)
|
|
122
|
+
for engine_id, engine in self._engines.items():
|
|
123
|
+
save_engine(engine, folder / f"{engine_id}.json")
|
|
124
|
+
|
|
125
|
+
def info(self) -> PluginInfo:
|
|
126
|
+
"""Return plugin metadata."""
|
|
127
|
+
return PluginInfo(
|
|
128
|
+
name="PySearch",
|
|
129
|
+
description="Full-text search with TF-IDF ranking for Pebble programs",
|
|
130
|
+
version="0.1.0",
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def pebble_module_name(self) -> str:
|
|
134
|
+
"""Return the Pebble import name."""
|
|
135
|
+
return "search"
|
|
136
|
+
|
|
137
|
+
def pebble_stdlib(self) -> StdlibModule:
|
|
138
|
+
"""Return the search stdlib module with create, add, and query functions."""
|
|
139
|
+
return StdlibModule(
|
|
140
|
+
functions={
|
|
141
|
+
"search_create": (0, self.search_create),
|
|
142
|
+
"search_add": (3, self.search_add),
|
|
143
|
+
"search_query": (2, self.search_query),
|
|
144
|
+
"search_list": (0, self.search_list),
|
|
145
|
+
},
|
|
146
|
+
constants={},
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
def shell_commands(self) -> list[ShellCommand]:
|
|
150
|
+
"""Return no shell commands (search is used from Pebble)."""
|
|
151
|
+
return []
|