mlsweep 3.1.2__tar.gz → 3.2.0__tar.gz

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.
Files changed (84) hide show
  1. {mlsweep-3.1.2 → mlsweep-3.2.0}/PKG-INFO +5 -4
  2. {mlsweep-3.1.2/mlsweep/docs → mlsweep-3.2.0}/README.md +3 -3
  3. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_manager_db.py +290 -29
  4. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_manager_http.py +62 -16
  5. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_manager_state.py +15 -2
  6. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_manager_workers.py +206 -78
  7. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_shared.py +30 -2
  8. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_topology.py +92 -51
  9. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/cli.py +15 -0
  10. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/ctl.py +327 -40
  11. {mlsweep-3.1.2 → mlsweep-3.2.0/mlsweep/docs}/README.md +3 -3
  12. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/docs/SKILL.md +8 -3
  13. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/docs/mlsweep.md +14 -3
  14. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/docs/sweep_configuration.md +30 -19
  15. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/manager.py +29 -7
  16. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/run_sweep.py +78 -31
  17. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/system.html +54 -3
  18. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/worker.py +233 -84
  19. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep.egg-info/PKG-INFO +5 -4
  20. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep.egg-info/SOURCES.txt +3 -0
  21. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep.egg-info/requires.txt +1 -0
  22. {mlsweep-3.1.2 → mlsweep-3.2.0}/pyproject.toml +7 -3
  23. mlsweep-3.2.0/tests/test_bootstrap.py +122 -0
  24. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_campaigns.py +2 -2
  25. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_campaigns_cli.py +16 -9
  26. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_ctl.py +151 -2
  27. mlsweep-3.2.0/tests/test_device_probe.py +118 -0
  28. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_generate_variations.py +15 -0
  29. mlsweep-3.2.0/tests/test_hello_first.py +76 -0
  30. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_integration.py +41 -0
  31. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_logging_scale.py +4 -0
  32. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_manager_api.py +14 -1
  33. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_manager_db.py +256 -3
  34. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_metrics_cmd.py +9 -1
  35. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_metrics_flow.py +2 -2
  36. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_parsync.py +1 -8
  37. mlsweep-3.2.0/tests/test_placement.py +110 -0
  38. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_pool.py +40 -8
  39. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_race_invariants.py +24 -2
  40. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_races.py +2 -1
  41. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_reconnect.py +98 -12
  42. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_remote_worker.py +60 -0
  43. mlsweep-3.2.0/tests/test_worker_cleanup.py +187 -0
  44. mlsweep-3.1.2/tests/test_bootstrap.py +0 -91
  45. mlsweep-3.1.2/tests/test_worker_cleanup.py +0 -80
  46. {mlsweep-3.1.2 → mlsweep-3.2.0}/LICENSE +0 -0
  47. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/__init__.py +0 -0
  48. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/__main__.py +0 -0
  49. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_bayes.py +0 -0
  50. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_bin/.gitkeep +0 -0
  51. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_colors.py +0 -0
  52. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_env.py +0 -0
  53. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_parsync.py +0 -0
  54. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_sweep.py +0 -0
  55. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_writer_tensorboard.py +0 -0
  56. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_writer_wandb.py +0 -0
  57. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/_writers.py +0 -0
  58. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/docs/examples.md +0 -0
  59. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/logger.py +0 -0
  60. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/py.typed +0 -0
  61. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/ansi_up.js +0 -0
  62. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/campaign.js +0 -0
  63. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/dialog.js +0 -0
  64. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/experiments.html +0 -0
  65. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/favicon.ico +0 -0
  66. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/files.html +0 -0
  67. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/index.html +0 -0
  68. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/logs.html +0 -0
  69. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep/webui/results.html +0 -0
  70. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep.egg-info/dependency_links.txt +0 -0
  71. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep.egg-info/entry_points.txt +0 -0
  72. {mlsweep-3.1.2 → mlsweep-3.2.0}/mlsweep.egg-info/top_level.txt +0 -0
  73. {mlsweep-3.1.2 → mlsweep-3.2.0}/setup.cfg +0 -0
  74. {mlsweep-3.1.2 → mlsweep-3.2.0}/setup.py +0 -0
  75. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_campaigns_webui.py +0 -0
  76. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_cli.py +0 -0
  77. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_docs_sync.py +0 -0
  78. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_env.py +0 -0
  79. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_experiments_webui.py +0 -0
  80. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_monotonic.py +0 -0
  81. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_multinode.py +0 -0
  82. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_multinode_cleanup.py +0 -0
  83. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_rename_webui.py +0 -0
  84. {mlsweep-3.1.2 → mlsweep-3.2.0}/tests/test_validate_options.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: mlsweep
3
- Version: 3.1.2
3
+ Version: 3.2.0
4
4
  Summary: A flexible hyperparameter sweep scheduler for distributed ML training
5
5
  Author-email: Aaron Pazdera <aarpazdera@gmail.com>
6
6
  License-Expression: Apache-2.0
@@ -21,6 +21,7 @@ Requires-Dist: tensorboard; extra == "all"
21
21
  Provides-Extra: test
22
22
  Requires-Dist: torch; extra == "test"
23
23
  Requires-Dist: pytest; extra == "test"
24
+ Requires-Dist: pytest-xdist; extra == "test"
24
25
  Requires-Dist: paramiko; extra == "test"
25
26
  Dynamic: license-file
26
27
 
@@ -182,7 +183,7 @@ Every client command resolves the token the same way, in order: `--token`, then
182
183
  ```sh
183
184
  mlsweep status # manager / token / GPUs / result paths
184
185
  mlsweep watch EXP_ID # live terminal status
185
- mlsweep ls # list experiments (`mlsweep ls EXP_ID` lists runs)
186
+ mlsweep ls # experiments grouped by status (`mlsweep ls EXP_ID` lists runs, --all lifts the cap of 20 settled)
186
187
  mlsweep logs RUN_ID --experiment EXP_ID # tail a run's training.log
187
188
  mlsweep metrics --experiment EXP_ID --keys REGEX # runs' logged metrics (--last, --with-dims, --pivot, --json, --csv)
188
189
  mlsweep best --experiment EXP_ID # top runs by metric (--group-by DIM, --table D1,D2)
@@ -249,9 +250,9 @@ jobs = 2
249
250
  | `pass` | no | SSH password (needs `sshpass`); or set `MLSWEEP_SSH_PASS` env var |
250
251
  | `venv` | no | Existing venv to prefer over the auto-bootstrapped one. Accepts a project root, venv root, `bin/` dir, activate script, or python binary. |
251
252
  | `devices` | no | Specific GPU IDs to use (worker CLI: `-g`). Default: all visible. |
252
- | `gpus` | no | Total GPU count (default: all visible) |
253
253
  | `jobs` | no | Max concurrent jobs per GPU on this worker (worker CLI: `-j`). Default 1; set to 0 for unlimited. |
254
254
  | `port` | no | Worker TCP port (default: 7890; `0` = ephemeral). |
255
+ | `scratch_dir` | no | Where the worker keeps each run's working files while it runs (default: the manager's `--scratch-dir`, `/tmp/mlsweep`). A second worker given a directory that a live worker already uses takes a `.worker-<port>` subdirectory of it. |
255
256
 
256
257
  #### 2. Start the manager with the workers file
257
258
 
@@ -279,7 +280,7 @@ All flags below assume `--manager http://localhost:7891`:
279
280
  | `--tensorboard-dir D` | Write TensorBoard logs |
280
281
  | `--color` | Enable ANSI color in human-readable output (default: off) |
281
282
 
282
- Colored output is **off by default** so piping and logging stay clean. Pass
283
+ Colored output is off by default so piping and logging stay clean. Pass
283
284
  `--color` to any entry point (`mlsweep`, `mlsweep run`, `mlsweep manager`,
284
285
  `mlsweep worker`) to turn it on. Machine-readable output (`--json`, `--csv`) and
285
286
  raw `logs`/`metrics` text are never colorized.
@@ -156,7 +156,7 @@ Every client command resolves the token the same way, in order: `--token`, then
156
156
  ```sh
157
157
  mlsweep status # manager / token / GPUs / result paths
158
158
  mlsweep watch EXP_ID # live terminal status
159
- mlsweep ls # list experiments (`mlsweep ls EXP_ID` lists runs)
159
+ mlsweep ls # experiments grouped by status (`mlsweep ls EXP_ID` lists runs, --all lifts the cap of 20 settled)
160
160
  mlsweep logs RUN_ID --experiment EXP_ID # tail a run's training.log
161
161
  mlsweep metrics --experiment EXP_ID --keys REGEX # runs' logged metrics (--last, --with-dims, --pivot, --json, --csv)
162
162
  mlsweep best --experiment EXP_ID # top runs by metric (--group-by DIM, --table D1,D2)
@@ -223,9 +223,9 @@ jobs = 2
223
223
  | `pass` | no | SSH password (needs `sshpass`); or set `MLSWEEP_SSH_PASS` env var |
224
224
  | `venv` | no | Existing venv to prefer over the auto-bootstrapped one. Accepts a project root, venv root, `bin/` dir, activate script, or python binary. |
225
225
  | `devices` | no | Specific GPU IDs to use (worker CLI: `-g`). Default: all visible. |
226
- | `gpus` | no | Total GPU count (default: all visible) |
227
226
  | `jobs` | no | Max concurrent jobs per GPU on this worker (worker CLI: `-j`). Default 1; set to 0 for unlimited. |
228
227
  | `port` | no | Worker TCP port (default: 7890; `0` = ephemeral). |
228
+ | `scratch_dir` | no | Where the worker keeps each run's working files while it runs (default: the manager's `--scratch-dir`, `/tmp/mlsweep`). A second worker given a directory that a live worker already uses takes a `.worker-<port>` subdirectory of it. |
229
229
 
230
230
  #### 2. Start the manager with the workers file
231
231
 
@@ -253,7 +253,7 @@ All flags below assume `--manager http://localhost:7891`:
253
253
  | `--tensorboard-dir D` | Write TensorBoard logs |
254
254
  | `--color` | Enable ANSI color in human-readable output (default: off) |
255
255
 
256
- Colored output is **off by default** so piping and logging stay clean. Pass
256
+ Colored output is off by default so piping and logging stay clean. Pass
257
257
  `--color` to any entry point (`mlsweep`, `mlsweep run`, `mlsweep manager`,
258
258
  `mlsweep worker`) to turn it on. Machine-readable output (`--json`, `--csv`) and
259
259
  raw `logs`/`metrics` text are never colorized.
@@ -21,6 +21,8 @@ import asyncio
21
21
  import json
22
22
  import sqlite3
23
23
  import dataclasses
24
+ import itertools
25
+ import shlex
24
26
  import zlib
25
27
  from dataclasses import dataclass
26
28
  from datetime import datetime, timezone
@@ -28,7 +30,7 @@ from typing import Any, Callable, Coroutine, Literal, NamedTuple, Sequence, Type
28
30
 
29
31
  import aiosqlite
30
32
 
31
- from mlsweep._shared import DEFAULT_CAMPAIGN
33
+ from mlsweep._shared import DEFAULT_CAMPAIGN, NON_SCHEDULABLE_EXPERIMENT_STATUSES
32
34
  from mlsweep._sweep import SkipIndex
33
35
 
34
36
  _T = TypeVar("_T")
@@ -38,11 +40,6 @@ ExperimentStatus = Literal["running", "paused", "completed", "aborted"]
38
40
 
39
41
  ACTIVE_JOB_STATUSES: tuple[JobStatus, ...] = ("dispatched", "running")
40
42
  FINISHED_JOB_STATUSES: tuple[JobStatus, ...] = ("done", "failed", "xfailed", "cancelled")
41
- # Experiment statuses whose pending jobs the scheduler must NOT dispatch.
42
- # 'paused' is a temporary hold (resumable); 'aborted' is a permanent stop.
43
- # 'running' and 'completed' remain schedulable so that retrying a job in a
44
- # finished experiment works without a separate status flip.
45
- NON_SCHEDULABLE_EXPERIMENT_STATUSES: tuple[str, ...] = ("paused", "aborted")
46
43
 
47
44
 
48
45
  def _sql_in(statuses: Sequence[str]) -> str:
@@ -97,6 +94,7 @@ class WorkerRecord:
97
94
  ssh_key: str | None = None
98
95
  venv: str | None = None
99
96
  devices: str | None = None # JSON list of ints
97
+ unhealthy_devices: str | None = None # JSON list of ints excluded by the CUDA probe
100
98
  last_error: str | None = None # human-readable reason for the last failure
101
99
 
102
100
 
@@ -239,6 +237,7 @@ def _row_to_worker(row: sqlite3.Row) -> WorkerRecord:
239
237
  ssh_key=row["ssh_key"],
240
238
  venv=row["venv"],
241
239
  devices=row["devices"],
240
+ unhealthy_devices=row["unhealthy_devices"],
242
241
  last_error=row["last_error"],
243
242
  )
244
243
 
@@ -374,24 +373,27 @@ _METRICS_TABLE = """
374
373
  ) WITHOUT ROWID
375
374
  """
376
375
 
377
- # A log row is a chunk of whole lines; seq is the byte offset in the run's
378
- # training.log just past the chunk. data is TEXT, or zlib-compressed UTF-8
379
- # as a BLOB when that is smaller.
376
+ # A log row is a span of the run's training.log; seq is the byte offset just
377
+ # past it. data is TEXT, or zlib-compressed UTF-8 as a BLOB when that is
378
+ # smaller. Live rows are chunks of whole lines. Once an attempt is finished,
379
+ # compact_log_attempt replaces its rows with one row of the same form.
380
+ # A rowid table, because WITHOUT ROWID wastes about a third of each page on
381
+ # rows this large.
380
382
  _LOGS_TABLE = """
381
383
  CREATE TABLE IF NOT EXISTS logs (
382
384
  job_key INTEGER NOT NULL,
383
385
  attempt INTEGER NOT NULL,
384
386
  seq INTEGER NOT NULL,
385
387
  data NOT NULL,
386
- PRIMARY KEY (job_key, attempt, seq)
387
- ) WITHOUT ROWID
388
+ UNIQUE (job_key, attempt, seq)
389
+ )
388
390
  """
389
391
 
390
- def _pack_log(text: str) -> str | bytes:
392
+ def _pack_log(text: str, level: int = 6) -> str | bytes:
391
393
  """Compress a log chunk if that saves at least 10%."""
392
394
  raw = text.encode("utf-8")
393
395
  if len(raw) >= 256:
394
- packed = zlib.compress(raw, 6)
396
+ packed = zlib.compress(raw, level)
395
397
  if len(packed) < len(raw) * 0.9:
396
398
  return packed
397
399
  return text
@@ -504,16 +506,53 @@ async def _add_missing_columns(
504
506
  await db.execute(f"ALTER TABLE {table} ADD COLUMN {name} {decl}")
505
507
 
506
508
 
509
+ async def _migrate_logs_to_rowid(db: aiosqlite.Connection) -> bool:
510
+ """Rebuild a WITHOUT ROWID ``logs`` table as a rowid table, in one transaction.
511
+
512
+ Returns True if the table was rebuilt. An interrupted rebuild rolls back
513
+ and leaves the old table as it was.
514
+ """
515
+ row = await _exec_one(db, "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'logs'")
516
+ if row is None or "WITHOUT ROWID" not in row[0].upper():
517
+ return False
518
+ await db.execute("BEGIN")
519
+ try:
520
+ await db.execute("ALTER TABLE logs RENAME TO logs_old")
521
+ await db.execute(_LOGS_TABLE)
522
+ await db.execute(
523
+ "INSERT INTO logs (job_key, attempt, seq, data) "
524
+ "SELECT job_key, attempt, seq, data FROM logs_old ORDER BY job_key, attempt, seq"
525
+ )
526
+ await db.execute("DROP TABLE logs_old")
527
+ await db.commit()
528
+ except BaseException:
529
+ await db.rollback()
530
+ raise
531
+ return True
532
+
533
+
534
+ # Bytes the WAL file is cut back to after a checkpoint.
535
+ _WAL_SIZE_LIMIT = 16 * 1024 * 1024
536
+
537
+
507
538
  async def init_db(db: aiosqlite.Connection) -> None:
508
539
  """Create tables and indexes if they do not exist (idempotent).
509
540
 
510
541
  Enables WAL mode and foreign key enforcement on the connection.
511
542
  synchronous=NORMAL is safe under WAL and avoids an fsync on every
512
543
  commit, which matters because every log line and metric is a commit.
544
+
545
+ Incremental auto-vacuum lets the log compactor give freed pages back to
546
+ the filesystem. It applies to a new database, and to an existing one at
547
+ its next VACUUM.
513
548
  """
514
549
  db.row_factory = sqlite3.Row
550
+ await db.execute("PRAGMA auto_vacuum=INCREMENTAL")
515
551
  await db.execute("PRAGMA journal_mode=WAL")
516
552
  await db.execute("PRAGMA synchronous=NORMAL")
553
+ # SQLite reuses the WAL file without shrinking it, so a burst such as a
554
+ # VACUUM would otherwise leave it at that size for good.
555
+ await db.execute(f"PRAGMA journal_size_limit={_WAL_SIZE_LIMIT}")
517
556
  await db.execute("PRAGMA foreign_keys=ON")
518
557
 
519
558
  # ── experiments ─────────────────────────────────────────────────
@@ -553,9 +592,14 @@ async def init_db(db: aiosqlite.Connection) -> None:
553
592
  ssh_key TEXT,
554
593
  venv TEXT,
555
594
  devices TEXT,
595
+ unhealthy_devices TEXT,
556
596
  last_error TEXT
557
597
  );
558
598
  """)
599
+ # Idempotent migration for databases created before the device-health probe.
600
+ await _add_missing_columns(db, "workers", {
601
+ "unhealthy_devices": "TEXT",
602
+ })
559
603
 
560
604
  # ── artifacts ───────────────────────────────────────────────────
561
605
  await db.execute("""
@@ -570,6 +614,10 @@ async def init_db(db: aiosqlite.Connection) -> None:
570
614
 
571
615
  await db.execute(_JOBS_TABLE)
572
616
  await db.execute(_METRICS_TABLE)
617
+ await db.commit()
618
+ # The rebuild leaves the old table's pages free; VACUUM returns them.
619
+ if await _migrate_logs_to_rowid(db):
620
+ await db.execute("VACUUM")
573
621
  await db.execute(_LOGS_TABLE)
574
622
 
575
623
  # ── job_nodes ────────────────────────────────────────────────────
@@ -592,6 +640,16 @@ async def init_db(db: aiosqlite.Connection) -> None:
592
640
  );
593
641
  """)
594
642
 
643
+ # ── settings ────────────────────────────────────────────────────
644
+ # Manager-wide knobs changed from the web UI, such as the GPU placement
645
+ # policy. One row per key; a missing row means the default.
646
+ await db.execute("""
647
+ CREATE TABLE IF NOT EXISTS settings (
648
+ key TEXT PRIMARY KEY,
649
+ value TEXT NOT NULL
650
+ );
651
+ """)
652
+
595
653
  # ── indexes ─────────────────────────────────────────────────────
596
654
  await db.executescript("""
597
655
  CREATE INDEX IF NOT EXISTS idx_experiments_campaign
@@ -604,6 +662,27 @@ async def init_db(db: aiosqlite.Connection) -> None:
604
662
  await db.commit()
605
663
 
606
664
 
665
+ # ===============================================================================
666
+ # Settings
667
+ # ===============================================================================
668
+
669
+
670
+ async def get_setting(db: aiosqlite.Connection, key: str) -> str | None:
671
+ """Return the stored value of manager setting *key*, or ``None`` if unset."""
672
+ row = await _exec_one(db, "SELECT value FROM settings WHERE key = ?", (key,))
673
+ return row["value"] if row else None
674
+
675
+
676
+ async def set_setting(db: aiosqlite.Connection, key: str, value: str) -> None:
677
+ """Store manager setting *key*."""
678
+ await db.execute(
679
+ "INSERT INTO settings (key, value) VALUES (?, ?) "
680
+ "ON CONFLICT(key) DO UPDATE SET value = excluded.value",
681
+ (key, value),
682
+ )
683
+ await db.commit()
684
+
685
+
607
686
  # ===============================================================================
608
687
  # Experiments
609
688
  # ===============================================================================
@@ -721,7 +800,7 @@ async def update_experiment_campaign(
721
800
 
722
801
 
723
802
  # Statuses broken out in ``job_counts``, plus "total".
724
- _JOB_COUNT_STATUSES = ("done", "failed", "xfailed", "running", "pending", "dispatched")
803
+ _JOB_COUNT_STATUSES = ("done", "failed", "xfailed", "cancelled", "running", "pending", "dispatched")
725
804
  _JOB_COUNT_COLUMNS = ",\n ".join(
726
805
  ["COUNT(j.run_id) AS total_jobs"]
727
806
  + [f"SUM(CASE WHEN j.status = '{st}' THEN 1 ELSE 0 END) AS {st}_jobs" for st in _JOB_COUNT_STATUSES]
@@ -783,6 +862,7 @@ async def upsert_worker(
783
862
  ssh_key: str | None = None,
784
863
  venv: str | None = None,
785
864
  devices: str | None = None,
865
+ unhealthy_devices: str | None = None,
786
866
  status: WorkerStatus = "connected",
787
867
  last_error: str | None = None,
788
868
  ) -> WorkerRecord:
@@ -792,8 +872,9 @@ async def upsert_worker(
792
872
  db,
793
873
  """
794
874
  INSERT INTO workers (worker_id, host, remote_dir, status, last_seen,
795
- scratch_dir, port, ssh_key, venv, devices, last_error)
796
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
875
+ scratch_dir, port, ssh_key, venv, devices,
876
+ unhealthy_devices, last_error)
877
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
797
878
  ON CONFLICT (worker_id) DO UPDATE SET
798
879
  host = EXCLUDED.host,
799
880
  remote_dir = EXCLUDED.remote_dir,
@@ -804,11 +885,12 @@ async def upsert_worker(
804
885
  ssh_key = EXCLUDED.ssh_key,
805
886
  venv = EXCLUDED.venv,
806
887
  devices = EXCLUDED.devices,
888
+ unhealthy_devices = EXCLUDED.unhealthy_devices,
807
889
  last_error = EXCLUDED.last_error
808
890
  RETURNING *;
809
891
  """,
810
892
  (worker_id, host, remote_dir, status, now,
811
- scratch_dir, port, ssh_key, venv, devices, last_error),
893
+ scratch_dir, port, ssh_key, venv, devices, unhealthy_devices, last_error),
812
894
  )
813
895
  await db.commit()
814
896
  assert row is not None
@@ -909,6 +991,16 @@ def _serialize_job_fields(
909
991
  return command_json, combo_json, env_json, return_files_json, files_json
910
992
 
911
993
 
994
+ def _setup_command_text(value: Any) -> str | None:
995
+ """A job's setup command as stored: one shell-style string. An argument
996
+ list is joined so that dispatch's ``shlex.split`` gives it back."""
997
+ if value is None or isinstance(value, str):
998
+ return value
999
+ if isinstance(value, list) and all(isinstance(a, str) for a in value):
1000
+ return shlex.join(value) if value else None
1001
+ raise ValueError("'setup_command' must be a string or a list of strings")
1002
+
1003
+
912
1004
  async def insert_job(
913
1005
  db: aiosqlite.Connection,
914
1006
  *,
@@ -927,7 +1019,7 @@ async def insert_job(
927
1019
  files: dict[str, str] | None = None,
928
1020
  max_retries: int = 2,
929
1021
  artifact_id: str | None = None,
930
- setup_command: str | None = None,
1022
+ setup_command: str | list[str] | None = None,
931
1023
  ) -> JobRecord:
932
1024
  """Insert a new job row. Returns the created JobRecord."""
933
1025
  [job] = await insert_jobs_bulk(db, [dict(
@@ -978,7 +1070,7 @@ async def _insert_jobs_and_reopen(
978
1070
  j.get("gpus_per_run", 1), j.get("nodes_per_run", 1),
979
1071
  int(j.get("set_dist_env", False)), j.get("run_from"),
980
1072
  return_files_json, files_json, j.get("max_retries", 2),
981
- j.get("artifact_id"), j.get("setup_command")),
1073
+ j.get("artifact_id"), _setup_command_text(j.get("setup_command"))),
982
1074
  )
983
1075
  assert row is not None
984
1076
  records.append(_row_to_job(row))
@@ -1513,17 +1605,21 @@ async def retry_job(
1513
1605
  run_id: str,
1514
1606
  experiment_id: str,
1515
1607
  ) -> JobRecord | None:
1516
- """Re-queue a finished job, using one retry.
1608
+ """Re-queue a finished job on request, with a fresh automatic-retry budget.
1609
+
1610
+ ``max_retries`` caps the retries the manager makes on its own when a run is
1611
+ lost. A retry someone asks for is not one of those. It resets
1612
+ ``retry_count``, so the new attempt gets the full budget. Earlier attempts
1613
+ keep their logs and metrics, which are keyed by ``attempt``.
1517
1614
 
1518
- Returns None if the job is not finished or has no retries left.
1615
+ Returns None if the job is not finished.
1519
1616
  """
1520
1617
  row = await _exec_one(
1521
1618
  db,
1522
1619
  f"""
1523
- UPDATE jobs SET status = 'pending', retry_count = retry_count + 1, {_CLEAR_DISPATCH}
1620
+ UPDATE jobs SET status = 'pending', retry_count = 0, {_CLEAR_DISPATCH}
1524
1621
  WHERE run_id = ? AND experiment_id = ?
1525
1622
  AND {_FINISHED_IN}
1526
- AND retry_count < max_retries
1527
1623
  RETURNING *
1528
1624
  """,
1529
1625
  (run_id, experiment_id),
@@ -1989,6 +2085,139 @@ async def get_logs_for_run(
1989
2085
  return "".join(parts)
1990
2086
 
1991
2087
 
2088
+ # A compacted log is one row, so this compression is a level above the live one.
2089
+ _COMPACT_LOG_LEVEL = 9
2090
+
2091
+
2092
+ async def uncompacted_log_attempts(
2093
+ db: aiosqlite.Connection, limit: int = 64, after: tuple[int, int] = (-1, -1),
2094
+ ) -> list[tuple[int, int]]:
2095
+ """``(job_key, attempt)`` of finished attempts whose log is still in several rows.
2096
+
2097
+ An attempt is finished once a later one has been dispatched, or once its
2098
+ job is in a finished status. Only attempts past *after* are returned, in
2099
+ order, so a caller can page through them.
2100
+ """
2101
+ rows = await _exec_all(
2102
+ db,
2103
+ f"""
2104
+ SELECT l.job_key, l.attempt FROM logs l JOIN jobs j ON j.job_key = l.job_key
2105
+ WHERE (l.job_key, l.attempt) > (?, ?)
2106
+ AND (l.attempt < j.attempt OR (l.attempt = j.attempt AND j.{_FINISHED_IN}))
2107
+ GROUP BY l.job_key, l.attempt HAVING COUNT(*) > 1
2108
+ ORDER BY l.job_key, l.attempt
2109
+ LIMIT ?
2110
+ """,
2111
+ (*after, limit),
2112
+ )
2113
+ return [(r[0], r[1]) for r in rows]
2114
+
2115
+
2116
+ def _join_log_rows(datas: Sequence[str | bytes]) -> str | bytes:
2117
+ """One row's data holding the text of *datas*, in the form ``insert_log`` stores."""
2118
+ return _pack_log("".join(_unpack_log(d) for d in datas), _COMPACT_LOG_LEVEL)
2119
+
2120
+
2121
+ async def replace_log_rows(
2122
+ db: aiosqlite.Connection,
2123
+ job_key: int,
2124
+ attempt: int,
2125
+ count: int,
2126
+ last_seq: int,
2127
+ data: str | bytes,
2128
+ ) -> bool:
2129
+ """Replace an attempt's rows up to *last_seq* with one row, in one transaction.
2130
+
2131
+ *count* is how many rows the caller read up to *last_seq*. If that no
2132
+ longer matches (the job was deleted, or the rows changed), nothing is
2133
+ written and this returns False. Rows after *last_seq* are kept.
2134
+ """
2135
+ row = await _exec_one(
2136
+ db,
2137
+ "SELECT COUNT(*), MAX(seq) FROM logs WHERE job_key = ? AND attempt = ? AND seq <= ?",
2138
+ (job_key, attempt, last_seq),
2139
+ )
2140
+ if row is None or (row[0], row[1]) != (count, last_seq):
2141
+ return False
2142
+ await db.execute(
2143
+ "DELETE FROM logs WHERE job_key = ? AND attempt = ? AND seq <= ?",
2144
+ (job_key, attempt, last_seq),
2145
+ )
2146
+ await db.execute(
2147
+ "INSERT INTO logs (job_key, attempt, seq, data) VALUES (?, ?, ?, ?)",
2148
+ (job_key, attempt, last_seq, data),
2149
+ )
2150
+ await db.commit()
2151
+ return True
2152
+
2153
+
2154
+ async def compact_log_attempt(
2155
+ db: aiosqlite.Connection, writer: DbWriter, job_key: int, attempt: int,
2156
+ ) -> bool:
2157
+ """Compress one attempt's log rows into a single row.
2158
+
2159
+ The rows are read on *db* and compressed off the event loop. Only the
2160
+ swap goes through *writer*, as one transaction checked against what was
2161
+ read. Interrupting this at any point leaves the log as it was. Returns
2162
+ True if the rows were replaced.
2163
+ """
2164
+ rows = await _exec_all(
2165
+ db,
2166
+ "SELECT seq, data FROM logs WHERE job_key = ? AND attempt = ? ORDER BY seq",
2167
+ (job_key, attempt),
2168
+ )
2169
+ if len(rows) < 2:
2170
+ return False
2171
+ data = await asyncio.to_thread(_join_log_rows, [r[1] for r in rows])
2172
+ return await writer.replace_log_rows(job_key, attempt, len(rows), rows[-1][0], data)
2173
+
2174
+
2175
+ # Free pages released per write, so other writes are not held up for long.
2176
+ _VACUUM_PAGES = 2000
2177
+
2178
+
2179
+ async def release_free_pages(db: aiosqlite.Connection) -> bool:
2180
+ """Shrink the file by up to ``_VACUUM_PAGES`` free pages (a no-op without
2181
+ incremental auto-vacuum). Returns whether free pages remain."""
2182
+ mode = await _exec_all(db, "PRAGMA auto_vacuum")
2183
+ if not mode or mode[0][0] != 2: # 2 is INCREMENTAL
2184
+ return False
2185
+ await _exec_all(db, f"PRAGMA incremental_vacuum({_VACUUM_PAGES})")
2186
+ await db.commit()
2187
+ rows = await _exec_all(db, "PRAGMA freelist_count")
2188
+ return bool(rows and rows[0][0])
2189
+
2190
+
2191
+ # Seconds between sweeps for finished logs.
2192
+ _COMPACT_INTERVAL = 30.0
2193
+
2194
+
2195
+ async def log_compactor(db: aiosqlite.Connection, writer: DbWriter) -> None:
2196
+ """Compact finished attempts' logs, one at a time, behind other writes.
2197
+
2198
+ Runs for the life of the manager. Whatever it has not reached yet is
2199
+ still readable as it is, and it picks up again after a restart. Each
2200
+ sweep pages through the backlog once, then waits before the next.
2201
+ """
2202
+ while True:
2203
+ after = (-1, -1)
2204
+ try:
2205
+ compacted = False
2206
+ while batch := await uncompacted_log_attempts(db, after=after):
2207
+ for job_key, attempt in batch:
2208
+ # One attempt that cannot be compacted must not hold up the rest.
2209
+ try:
2210
+ compacted |= await compact_log_attempt(db, writer, job_key, attempt)
2211
+ except Exception as e:
2212
+ print(f"log compaction of job {job_key} attempt {attempt} failed: {e!r}")
2213
+ after = batch[-1]
2214
+ if compacted:
2215
+ await writer.release_free_pages()
2216
+ except Exception as e:
2217
+ print(f"log compaction failed: {e!r}")
2218
+ await asyncio.sleep(_COMPACT_INTERVAL)
2219
+
2220
+
1992
2221
  # ===============================================================================
1993
2222
  # DB Writer Actor
1994
2223
  # ===============================================================================
@@ -2011,12 +2240,18 @@ class DbWriter:
2011
2240
 
2012
2241
  def __init__(self, db: aiosqlite.Connection) -> None:
2013
2242
  self._db = db
2014
- self._q: asyncio.Queue[tuple[Callable[[], Coroutine[Any, Any, Any]], asyncio.Future[Any]]] = asyncio.Queue()
2243
+ # (priority, seq, fn, fut): background writes (priority 1) run only
2244
+ # when no normal write (priority 0) is waiting. seq keeps each
2245
+ # priority FIFO and ensures fn/fut are never compared.
2246
+ self._q: asyncio.PriorityQueue[
2247
+ tuple[int, int, Callable[[], Coroutine[Any, Any, Any]], asyncio.Future[Any]]
2248
+ ] = asyncio.PriorityQueue()
2249
+ self._seq = itertools.count()
2015
2250
 
2016
2251
  async def run(self) -> None:
2017
2252
  """Actor loop — run as a long-lived asyncio task."""
2018
2253
  while True:
2019
- fn, fut = await self._q.get()
2254
+ _, _, fn, fut = await self._q.get()
2020
2255
  try:
2021
2256
  fut.set_result(await fn())
2022
2257
  except Exception as exc:
@@ -2026,10 +2261,12 @@ class DbWriter:
2026
2261
  pass
2027
2262
  fut.set_exception(exc)
2028
2263
 
2029
- async def _enqueue(self, fn: Callable[[], Coroutine[Any, Any, _T]]) -> _T:
2264
+ async def _enqueue(
2265
+ self, fn: Callable[[], Coroutine[Any, Any, _T]], *, background: bool = False,
2266
+ ) -> _T:
2030
2267
  loop = asyncio.get_running_loop()
2031
2268
  fut: asyncio.Future[_T] = loop.create_future()
2032
- await self._q.put((fn, fut))
2269
+ await self._q.put((int(background), next(self._seq), fn, fut))
2033
2270
  return await fut
2034
2271
 
2035
2272
  # ── Experiments ───────────────────────────────────────────────────────────
@@ -2106,6 +2343,7 @@ class DbWriter:
2106
2343
  ssh_key: str | None = None,
2107
2344
  venv: str | None = None,
2108
2345
  devices: str | None = None,
2346
+ unhealthy_devices: str | None = None,
2109
2347
  status: WorkerStatus = "connected",
2110
2348
  last_error: str | None = None,
2111
2349
  ) -> WorkerRecord:
@@ -2113,7 +2351,8 @@ class DbWriter:
2113
2351
  return await self._enqueue(lambda: upsert_worker(
2114
2352
  db, worker_id=worker_id, host=host, remote_dir=remote_dir,
2115
2353
  scratch_dir=scratch_dir, port=port, ssh_key=ssh_key,
2116
- venv=venv, devices=devices, status=status, last_error=last_error,
2354
+ venv=venv, devices=devices, unhealthy_devices=unhealthy_devices,
2355
+ status=status, last_error=last_error,
2117
2356
  ))
2118
2357
 
2119
2358
  async def update_worker_status(
@@ -2132,6 +2371,12 @@ class DbWriter:
2132
2371
  db = self._db
2133
2372
  await self._enqueue(lambda: update_worker_devices(db, worker_id, devices))
2134
2373
 
2374
+ # ── Settings ──────────────────────────────────────────────────────────────
2375
+
2376
+ async def set_setting(self, key: str, value: str) -> None:
2377
+ db = self._db
2378
+ await self._enqueue(lambda: set_setting(db, key, value))
2379
+
2135
2380
  # ── Jobs ──────────────────────────────────────────────────────────────────
2136
2381
 
2137
2382
  async def insert_job(
@@ -2152,7 +2397,7 @@ class DbWriter:
2152
2397
  files: dict[str, str] | None = None,
2153
2398
  max_retries: int = 2,
2154
2399
  artifact_id: str | None = None,
2155
- setup_command: str | None = None,
2400
+ setup_command: str | list[str] | None = None,
2156
2401
  ) -> JobRecord:
2157
2402
  db = self._db
2158
2403
  return await self._enqueue(lambda: insert_job(
@@ -2301,3 +2546,19 @@ class DbWriter:
2301
2546
  async def insert_log(self, job_key: int, attempt: int, seq: int, data: str) -> None:
2302
2547
  db = self._db
2303
2548
  await self._enqueue(lambda: insert_log(db, job_key, attempt, seq, data))
2549
+
2550
+ async def release_free_pages(self) -> None:
2551
+ """Background writes, one batch at a time: each runs only when no other
2552
+ write is waiting."""
2553
+ db = self._db
2554
+ while await self._enqueue(lambda: release_free_pages(db), background=True):
2555
+ pass
2556
+
2557
+ async def replace_log_rows(
2558
+ self, job_key: int, attempt: int, count: int, last_seq: int, data: str | bytes,
2559
+ ) -> bool:
2560
+ """Background write: it runs only when no other write is waiting."""
2561
+ db = self._db
2562
+ return await self._enqueue(
2563
+ lambda: replace_log_rows(db, job_key, attempt, count, last_seq, data),
2564
+ background=True)