computeharbor-worker 0.2.4__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 (21) hide show
  1. computeharbor_worker-0.2.4/LICENSE +21 -0
  2. computeharbor_worker-0.2.4/PKG-INFO +213 -0
  3. computeharbor_worker-0.2.4/README.md +185 -0
  4. computeharbor_worker-0.2.4/pyproject.toml +66 -0
  5. computeharbor_worker-0.2.4/setup.cfg +4 -0
  6. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/__init__.py +43 -0
  7. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/batch_inference.py +303 -0
  8. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/checkpoint.py +230 -0
  9. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/client.py +262 -0
  10. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/daemon.py +171 -0
  11. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/models.py +62 -0
  12. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/preemption.py +117 -0
  13. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/storage.py +239 -0
  14. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/supervisor.py +159 -0
  15. computeharbor_worker-0.2.4/worker/src/computeharbor_worker/trainer.py +305 -0
  16. computeharbor_worker-0.2.4/worker/src/computeharbor_worker.egg-info/PKG-INFO +213 -0
  17. computeharbor_worker-0.2.4/worker/src/computeharbor_worker.egg-info/SOURCES.txt +19 -0
  18. computeharbor_worker-0.2.4/worker/src/computeharbor_worker.egg-info/dependency_links.txt +1 -0
  19. computeharbor_worker-0.2.4/worker/src/computeharbor_worker.egg-info/entry_points.txt +4 -0
  20. computeharbor_worker-0.2.4/worker/src/computeharbor_worker.egg-info/requires.txt +8 -0
  21. computeharbor_worker-0.2.4/worker/src/computeharbor_worker.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ComputeHarbor Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,213 @@
1
+ Metadata-Version: 2.4
2
+ Name: computeharbor-worker
3
+ Version: 0.2.4
4
+ Summary: ComputeHarbor Spot-GPU & Edge LLM LoRA Checkpoint Worker
5
+ Author: Creova
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/creova-gif/computeharbor
8
+ Project-URL: Repository, https://github.com/creova-gif/computeharbor
9
+ Project-URL: Documentation, https://github.com/creova-gif/computeharbor/tree/main/docs
10
+ Keywords: llm,fine-tuning,lora,spot-gpu,checkpointing,preemption
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Classifier: Topic :: System :: Distributed Computing
17
+ Requires-Python: >=3.12
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: numpy>=2.0
21
+ Requires-Dist: pydantic>=2.9
22
+ Requires-Dist: safetensors>=0.4
23
+ Provides-Extra: dev
24
+ Requires-Dist: mypy>=1.10; extra == "dev"
25
+ Requires-Dist: pytest>=8.0; extra == "dev"
26
+ Requires-Dist: ruff>=0.6; extra == "dev"
27
+ Dynamic: license-file
28
+
29
+ # ComputeHarbor
30
+
31
+ <div align="center">
32
+ <picture>
33
+ <source media="(prefers-color-scheme: dark)" srcset="docs/brand/computeharbor-lockup-light.svg">
34
+ <img src="docs/brand/computeharbor-lockup-dark.svg" alt="ComputeHarbor" width="520">
35
+ </picture>
36
+ <br/><br/>
37
+
38
+ [![CI](https://github.com/creova-gif/computeharbor/actions/workflows/ci.yml/badge.svg)](https://github.com/creova-gif/computeharbor/actions/workflows/ci.yml)
39
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
40
+ [![Go 1.23+](https://img.shields.io/badge/Go-1.23+-00ADD8.svg)](go.mod)
41
+ [![Python 3.12+](https://img.shields.io/badge/Python-3.12+-3776AB.svg)](pyproject.toml)
42
+ [![Release](https://img.shields.io/badge/Release-v0.2.3-green.svg)](CHANGELOG.md)
43
+ </div>
44
+
45
+ ComputeHarbor orchestrates LoRA fine-tuning and batch inference across preemptible spot GPU pools. When a provider sends `SIGTERM` for a 30-second spot eviction, the worker flushes only the mutable LoRA adapter matrices, AdamW moment buffers, and PRNG state in Safetensors format via an atomic write-and-rename commit.
46
+
47
+ ## Installation
48
+
49
+ Requires **Go 1.23+** and **Python 3.12+**.
50
+
51
+ ```bash
52
+ # Build the Go control-plane CLI
53
+ go build -o bin/computeharbor ./control-plane/cmd/computeharbor
54
+
55
+ # Create a virtual environment and install the Python worker package + dev tools
56
+ uv venv .venv && uv pip install --python .venv/bin/python -e ".[dev]"
57
+ # Or with standard venv + pip:
58
+ # python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
59
+ ```
60
+
61
+ Installing the Python package exposes three console scripts: `computeharbor-worker`, `computeharbor-supervisor`, and `computeharbor-batch`.
62
+
63
+ > **macOS troubleshooting:** if console scripts or `import computeharbor_worker` fail with `ModuleNotFoundError` inside `.venv`, macOS may have flagged the venv hidden (`UF_HIDDEN`), which makes Python ≥3.12 skip the editable-install `.pth` file. Fix: `chflags -R nohidden .venv` ([cpython#148121](https://github.com/python/cpython/issues/148121)).
64
+
65
+ ## Quickstart
66
+
67
+ Start the control plane, then run the Python quickstart ([`examples/quickstart.py`](examples/quickstart.py)) or Go client ([`examples/control_plane_client.go`](examples/control_plane_client.go)):
68
+
69
+ ```bash
70
+ ./bin/computeharbor serve -addr :8080 -state-file /tmp/computeharbor-state.json
71
+ .venv/bin/python examples/quickstart.py
72
+ ```
73
+
74
+ ## CLI & Worker Reference
75
+
76
+ ### Control Plane CLI (`computeharbor`)
77
+
78
+ | Command | Purpose | Key Flags |
79
+ | --- | --- | --- |
80
+ | `computeharbor` | Estimate spot vs on-demand cost or rank pools | `-gpu`, `-count`, `-hours`, `-preemptions`, `-recovery-sec`, `-fee`, `-rank-vram` |
81
+ | `computeharbor serve` | Start the HTTP control-plane API & stale-lease reaper | `-addr`, `-reap-interval`, `-lease-ttl`, `-state-file`, `-snapshot-interval`, `-rate-limit-rps`, `-rate-limit-burst`, `-log-json`, `-webhook-url`, `-webhook-secret`, `-api-key` |
82
+ | `computeharbor status` | Query org jobs or a single job lease as JSON | `-url`, `-org` (required), `-job` |
83
+ | `computeharbor savings` | Rank multi-region spot fleet placements | `-url`, `-min-vram`, `-provider`, `-min-availability` |
84
+
85
+ ### Python Worker Entrypoints
86
+
87
+ - **`computeharbor-worker`** (`computeharbor_worker.daemon`): Assigns a worker lease, streams periodic heartbeats, runs LoRA training with `SIGTERM` checkpoint interception, and commits checkpoints back to the control plane.
88
+ ```bash
89
+ .venv/bin/computeharbor-worker \
90
+ --control-plane-url http://127.0.0.1:8080 \
91
+ --org-id org-demo \
92
+ --job-id job-001 \
93
+ --worker-node-id worker-gpu-1 \
94
+ --checkpoint-dir /tmp/computeharbor-ckpt \
95
+ --target-steps 30 \
96
+ --heartbeat-interval-sec 0.5
97
+ ```
98
+ Optional flags: `--remote-store-dir` (object-store mirror), `--max-checkpoints` (retained local checkpoint pairs, default `5`, `0` for unlimited), `--metadata-provider gcp|aws` (poll cloud preemption metadata and trigger `SIGTERM`, with `--metadata-url` and `--metadata-poll-sec`), `--step-delay-sec`, `--ready-file`, and `--summary-out`.
99
+ - **`computeharbor-supervisor`** (`computeharbor_worker.supervisor`): Submits a job and supervises multi-attempt spot failover across preemptions up to `--max-preemptions` (`--control-plane-url`, `--org-id`, `--job-id`, `--gpu`, `--checkpoint-dir`, `--target-steps`, `--worker-prefix`, `--remote-store-dir`, `--summary-out`).
100
+ - **`computeharbor-batch`** (`computeharbor_worker.batch_inference`): Runs deterministic, checkpointed batch inference with atomic `SIGTERM` cursor recovery (`--job-id`, `--checkpoint-dir`, `--prompts-file`, `--num-prompts`, `--seed`, `--batch-size`, `--spot-hourly-usd`, `--record-delay-sec`, `--ready-file`, `--manifest-out`).
101
+
102
+ ## HTTP Control Plane API
103
+
104
+ Full OpenAPI 3.1 specification: [`docs/openapi.yaml`](docs/openapi.yaml). Tenant-scoped job and billing endpoints require the `X-Org-ID` request header (except `POST /v1/jobs`, which reads `org_id` from the JSON body).
105
+
106
+ | Method & Path | Auth / Headers | Request / Query | Response |
107
+ | --- | --- | --- | --- |
108
+ | `GET /healthz` | None | — | `200 OK` `{"status":"ok"}` |
109
+ | `GET /readyz` | None | — | `200 OK` `{"status":"ready"}` or `503 Service Unavailable` `{"status":"draining"}` |
110
+ | `GET /ui` | None | — | `200 OK` HTML status & spot savings web console ([`pkg/server/ui.go`](pkg/server/ui.go)) |
111
+ | `GET /metrics` | None | — | `200 OK` Prometheus `0.0.4` text metrics ([ADR-003](docs/adr/003-prometheus-observability.md)) |
112
+ | `POST /v1/jobs` | `Content-Type: application/json` | `job_id`, `org_id`, `gpu`, `target_steps`, `max_preemptions` | `201 Created` `JobLease` |
113
+ | `GET /v1/jobs` | `X-Org-ID` | — | `200 OK` array of org-scoped `JobLease` objects |
114
+ | `GET /v1/jobs/{id}` | `X-Org-ID` | — | `200 OK` `JobLease` |
115
+ | `POST /v1/jobs/{id}/assign` | `X-Org-ID` | `{"worker_node_id": "..."}` | `200 OK` `JobLease` (`RUNNING`) |
116
+ | `POST /v1/jobs/{id}/heartbeat` | `X-Org-ID` | `{"worker_node_id": "..."}` | `200 OK` `JobLease` with updated `last_heartbeat_at` |
117
+ | `POST /v1/jobs/{id}/sigterm` | `X-Org-ID` | — | `200 OK` `JobLease` (`CHECKPOINTING`, idempotent) |
118
+ | `POST /v1/jobs/{id}/checkpoint` | `X-Org-ID` | `step`, `epoch`, `loss`, `safetensors_uri`, `manifest_uri`, `flush_latency_ms` | `200 OK` `JobLease` (`MIGRATING` or `COMPLETED`) |
119
+ | `POST /v1/jobs/{id}/cancel` | `X-Org-ID` | — | `200 OK` `JobLease` (`FAILED`, idempotent) |
120
+ | `POST /v1/jobs/{id}/barrier` | `X-Org-ID` | `world_size`, `rank`, `step` | `200 OK` `BarrierResponse` (`all_ready`, `committed_step`) |
121
+ | `GET /v1/cost/rank` | None | `min_vram`, `count`, `hours`, `fee` | `200 OK` ranked spot GPU pool quotes |
122
+ | `GET /v1/fleet/rank` | None | `min_vram`, `provider`, `min_availability` | `200 OK` multi-region fleet placements |
123
+ | `POST /v1/schedule` | `Content-Type: application/json` | `min_vram_gb`, `gpu_count`, `active_hours`, `fee_fraction`, `exclude_gpus` | `200 OK` selected pool + fallback alternatives |
124
+ | `GET /v1/billing/summary` | `X-Org-ID` | `fee` | `200 OK` org-scoped job & preemption billing summary |
125
+
126
+ ### Server Configuration Flags (`computeharbor serve`)
127
+
128
+ - `-state-file` / `-snapshot-interval`: Path for atomic coordinator JSON snapshot persistence across restarts, and background snapshot cadence when `-state-file` is set (default `5s`).
129
+ - `-reap-interval` / `-lease-ttl`: Background stale-lease reaper cadence (default `5s`) and heartbeat TTL (default `30s`).
130
+ - `-rate-limit-rps` / `-rate-limit-burst`: Per-org token-bucket rate limiting (`0` disables; default burst `20`).
131
+ - `-log-json`: Emit structured JSON HTTP request logs via `slog` to `stderr` (default `true`).
132
+ - `-webhook-url` / `-webhook-secret`: Async HTTP endpoint and HMAC-SHA256 secret for signed lifecycle webhook delivery.
133
+ - `-api-key`: Optional Bearer API key for HTTP authentication (defaults to `COMPUTEHARBOR_API_KEY`).
134
+ - `-org-api-keys`: Optional comma-separated org-scoped Bearer API keys (`org=token,...`, defaults to `COMPUTEHARBOR_ORG_API_KEYS`) that bind tokens to `X-Org-ID` tenants ([`ADR-007`](docs/adr/007-scoped-org-api-keys.md)).
135
+
136
+ ## Deployment & Observability
137
+
138
+ See [`docs/RUNBOOK.md`](docs/RUNBOOK.md) for production SRE operations, incident response, key rotation, and graceful draining procedures.
139
+
140
+ Run the control plane and Prometheus locally with Docker Compose:
141
+
142
+ ```bash
143
+ docker compose up --build
144
+ ```
145
+
146
+ - [`docker-compose.yml`](docker-compose.yml): Starts `control-plane` on `:8080` (with `/healthz` healthcheck) and `prometheus` (`prom/prometheus:v2.55.1`) on `:9090`.
147
+ - [`Dockerfile`](Dockerfile): Multi-stage `golang:1.23-alpine` -> `gcr.io/distroless/static-debian12:nonroot` build for the `computeharbor` control plane (`serve -addr :8080`).
148
+ - [`Dockerfile.worker`](Dockerfile.worker): `python:3.12-slim` image installing `computeharbor_worker` with entrypoint `python -m computeharbor_worker.daemon`.
149
+ - [`deploy/prometheus.yml`](deploy/prometheus.yml) & [`deploy/grafana-dashboard.json`](deploy/grafana-dashboard.json): Prometheus scrape config (`5s` interval) and pre-built Grafana dashboard.
150
+ - Kubernetes manifests: [`deploy/k8s/control-plane.yaml`](deploy/k8s/control-plane.yaml) and [`deploy/k8s/worker-job.yaml`](deploy/k8s/worker-job.yaml).
151
+
152
+ ## Architecture
153
+
154
+ - [`control-plane/cmd/computeharbor/main.go`](control-plane/cmd/computeharbor/main.go): CLI for cost modeling, `status`/`savings` queries, and the `serve` HTTP control plane.
155
+ - [`pkg/server/server.go`](pkg/server/server.go): Stdlib `net/http` JSON API for job leases, scheduling, billing summaries, Prometheus metrics, per-org rate limiting, and `X-Org-ID` tenant isolation.
156
+ - [`pkg/cost/calculator.go`](pkg/cost/calculator.go): Spot pricing catalog (NVIDIA L4, A10G, A100-40GB, A100-80GB, H100-80GB), multi-region fleet ranking, preemption recovery overhead accounting, and net customer savings after the platform fee.
157
+ - [`pkg/orchestrator/coordinator.go`](pkg/orchestrator/coordinator.go): Thread-safe job lease state machine (`QUEUED` -> `RUNNING` -> `CHECKPOINTING` -> `MIGRATING` -> `COMPLETED` / `FAILED`) with idempotent `SIGTERM` handling, step-regression guards, and `RingBarrier` synchronization.
158
+ - [`worker/src/computeharbor_worker/`](worker/src/computeharbor_worker/): Python 3.12+ worker that intercepts `SIGTERM`, syncs CUDA when available, writes LoRA weights and AdamW state to a temporary Safetensors file, calls `os.fsync`, atomically swaps `latest.json`, optionally replicates to an object-store mirror (`--remote-store-dir`), and verifies SHA-256 integrity on restore.
159
+ - [`tests/chaos/test_sigterm_preemption.py`](tests/chaos/test_sigterm_preemption.py): Subprocess chaos harness that injects three OS `SIGTERM` signals into a live training run and checks bit-for-bit loss and weight parity against an uninterrupted baseline.
160
+ - Architecture Decision Records: [`ADR-001`](docs/adr/001-lora-streaming-checkpoints.md), [`ADR-002`](docs/adr/002-control-plane-http-api.md), [`ADR-003`](docs/adr/003-prometheus-observability.md), [`ADR-004`](docs/adr/004-rate-limiting-and-observability.md), [`ADR-005`](docs/adr/005-event-webhooks-and-fleet-routing.md), and [`ADR-006`](docs/adr/006-readiness-and-request-correlation.md).
161
+
162
+ ## Measured Benchmarks
163
+
164
+ ### Preemption recovery and bit-for-bit loss parity
165
+
166
+ Run on a 10-core Apple Silicon host (`Darwin arm64`, Python 3.12.12, 5 trials, 3 real `SIGTERM` preemptions per trial, 15 preemptions total):
167
+
168
+ | Metric | Value | SLA / Gate |
169
+ | --- | --- | --- |
170
+ | Step-by-step loss curve parity (30 steps, 3 `SIGTERM` kills) | 15 / 15 preemptions (100% bit-for-bit match) | 100% parity |
171
+ | Final `lora_a` and `lora_b` SHA-256 match | 5 / 5 trials exact match | 100% match |
172
+ | Safetensors + manifest `fsync` flush latency (median) | 0.737 ms (range 0.656 ms to 1.286 ms) | < 30,000 ms |
173
+ | End-to-end `SIGTERM` to checkpoint restore latency (median) | 25.147 ms (range 21.643 ms to 67.660 ms) | < 30,000 ms |
174
+
175
+ Limiter: `os.fsync` syscall latency on the local APFS volume for the Safetensors file and two JSON manifests (`step-NNNNNN.manifest.json` and `latest.json`).
176
+
177
+ ### Spot vs on-demand cost savings (4 GPUs, 24 active hours, 12% savings fee)
178
+
179
+ | Pool | Provider | On-demand cost | Raw spot cost | Platform fee (12%) | Net customer cost | Gross savings | Net savings |
180
+ | --- | --- | --- | --- | --- | --- | --- | --- |
181
+ | `nvidia-l4-24gb` | GCP (`us-central1`) | \$81.60 | \$23.05 | \$7.03 | \$30.07 | 71.76% | 63.15% |
182
+ | `nvidia-a10g-24gb` | AWS (`us-east-1`) | \$116.16 | \$34.57 | \$9.79 | \$44.36 | 70.24% | 61.81% |
183
+ | `nvidia-a100-40gb` | GCP (`us-central1`) | \$352.32 | \$105.64 | \$29.60 | \$135.25 | 70.01% | 61.61% |
184
+ | `nvidia-a100-80gb` | AWS (`us-west-2`) | \$470.40 | \$136.40 | \$40.08 | \$176.48 | 71.00% | 62.48% |
185
+ | `nvidia-h100-80gb` | GCP (`us-east4`) | \$825.60 | \$247.82 | \$69.33 | \$317.15 | 69.98% | 61.59% |
186
+
187
+ ### Control Plane Throughput (Go Benchmarks)
188
+
189
+ Measured on Apple M5 (`Darwin arm64`, `make bench`):
190
+
191
+ | Benchmark | Result |
192
+ | --- | --- |
193
+ | `BenchmarkCalculate-10` | `38.35 ns/op` |
194
+ | `BenchmarkRankFleet-10` | `1383 ns/op` |
195
+ | `BenchmarkCoordinatorSubmitAndHeartbeat-10` | `479.3 ns/op` |
196
+ | `BenchmarkCoordinatorReapStaleLeases-10` | `9071 ns/op` |
197
+
198
+ ## Reproduce All Checks
199
+
200
+ ```bash
201
+ # Run all linters, type checks, unit tests, E2E tests, and SIGTERM chaos tests
202
+ make lint
203
+ make test
204
+ make test-e2e
205
+ make chaos
206
+
207
+ # Reproduce the 5-trial SIGTERM benchmark JSON report
208
+ PYTHONPATH=worker/src .venv/bin/python tests/chaos/test_sigterm_preemption.py
209
+ ```
210
+
211
+ ## Contributing
212
+
213
+ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for development setup, test/lint requirements, and PR guidelines. Also see [`SECURITY.md`](SECURITY.md), [`docs/RUNBOOK.md`](docs/RUNBOOK.md), [`AGENTS.md`](AGENTS.md), [`LICENSE`](LICENSE), [`docs/adr/000-template.md`](docs/adr/000-template.md), and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
@@ -0,0 +1,185 @@
1
+ # ComputeHarbor
2
+
3
+ <div align="center">
4
+ <picture>
5
+ <source media="(prefers-color-scheme: dark)" srcset="docs/brand/computeharbor-lockup-light.svg">
6
+ <img src="docs/brand/computeharbor-lockup-dark.svg" alt="ComputeHarbor" width="520">
7
+ </picture>
8
+ <br/><br/>
9
+
10
+ [![CI](https://github.com/creova-gif/computeharbor/actions/workflows/ci.yml/badge.svg)](https://github.com/creova-gif/computeharbor/actions/workflows/ci.yml)
11
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
12
+ [![Go 1.23+](https://img.shields.io/badge/Go-1.23+-00ADD8.svg)](go.mod)
13
+ [![Python 3.12+](https://img.shields.io/badge/Python-3.12+-3776AB.svg)](pyproject.toml)
14
+ [![Release](https://img.shields.io/badge/Release-v0.2.3-green.svg)](CHANGELOG.md)
15
+ </div>
16
+
17
+ ComputeHarbor orchestrates LoRA fine-tuning and batch inference across preemptible spot GPU pools. When a provider sends `SIGTERM` for a 30-second spot eviction, the worker flushes only the mutable LoRA adapter matrices, AdamW moment buffers, and PRNG state in Safetensors format via an atomic write-and-rename commit.
18
+
19
+ ## Installation
20
+
21
+ Requires **Go 1.23+** and **Python 3.12+**.
22
+
23
+ ```bash
24
+ # Build the Go control-plane CLI
25
+ go build -o bin/computeharbor ./control-plane/cmd/computeharbor
26
+
27
+ # Create a virtual environment and install the Python worker package + dev tools
28
+ uv venv .venv && uv pip install --python .venv/bin/python -e ".[dev]"
29
+ # Or with standard venv + pip:
30
+ # python3 -m venv .venv && .venv/bin/pip install -e ".[dev]"
31
+ ```
32
+
33
+ Installing the Python package exposes three console scripts: `computeharbor-worker`, `computeharbor-supervisor`, and `computeharbor-batch`.
34
+
35
+ > **macOS troubleshooting:** if console scripts or `import computeharbor_worker` fail with `ModuleNotFoundError` inside `.venv`, macOS may have flagged the venv hidden (`UF_HIDDEN`), which makes Python ≥3.12 skip the editable-install `.pth` file. Fix: `chflags -R nohidden .venv` ([cpython#148121](https://github.com/python/cpython/issues/148121)).
36
+
37
+ ## Quickstart
38
+
39
+ Start the control plane, then run the Python quickstart ([`examples/quickstart.py`](examples/quickstart.py)) or Go client ([`examples/control_plane_client.go`](examples/control_plane_client.go)):
40
+
41
+ ```bash
42
+ ./bin/computeharbor serve -addr :8080 -state-file /tmp/computeharbor-state.json
43
+ .venv/bin/python examples/quickstart.py
44
+ ```
45
+
46
+ ## CLI & Worker Reference
47
+
48
+ ### Control Plane CLI (`computeharbor`)
49
+
50
+ | Command | Purpose | Key Flags |
51
+ | --- | --- | --- |
52
+ | `computeharbor` | Estimate spot vs on-demand cost or rank pools | `-gpu`, `-count`, `-hours`, `-preemptions`, `-recovery-sec`, `-fee`, `-rank-vram` |
53
+ | `computeharbor serve` | Start the HTTP control-plane API & stale-lease reaper | `-addr`, `-reap-interval`, `-lease-ttl`, `-state-file`, `-snapshot-interval`, `-rate-limit-rps`, `-rate-limit-burst`, `-log-json`, `-webhook-url`, `-webhook-secret`, `-api-key` |
54
+ | `computeharbor status` | Query org jobs or a single job lease as JSON | `-url`, `-org` (required), `-job` |
55
+ | `computeharbor savings` | Rank multi-region spot fleet placements | `-url`, `-min-vram`, `-provider`, `-min-availability` |
56
+
57
+ ### Python Worker Entrypoints
58
+
59
+ - **`computeharbor-worker`** (`computeharbor_worker.daemon`): Assigns a worker lease, streams periodic heartbeats, runs LoRA training with `SIGTERM` checkpoint interception, and commits checkpoints back to the control plane.
60
+ ```bash
61
+ .venv/bin/computeharbor-worker \
62
+ --control-plane-url http://127.0.0.1:8080 \
63
+ --org-id org-demo \
64
+ --job-id job-001 \
65
+ --worker-node-id worker-gpu-1 \
66
+ --checkpoint-dir /tmp/computeharbor-ckpt \
67
+ --target-steps 30 \
68
+ --heartbeat-interval-sec 0.5
69
+ ```
70
+ Optional flags: `--remote-store-dir` (object-store mirror), `--max-checkpoints` (retained local checkpoint pairs, default `5`, `0` for unlimited), `--metadata-provider gcp|aws` (poll cloud preemption metadata and trigger `SIGTERM`, with `--metadata-url` and `--metadata-poll-sec`), `--step-delay-sec`, `--ready-file`, and `--summary-out`.
71
+ - **`computeharbor-supervisor`** (`computeharbor_worker.supervisor`): Submits a job and supervises multi-attempt spot failover across preemptions up to `--max-preemptions` (`--control-plane-url`, `--org-id`, `--job-id`, `--gpu`, `--checkpoint-dir`, `--target-steps`, `--worker-prefix`, `--remote-store-dir`, `--summary-out`).
72
+ - **`computeharbor-batch`** (`computeharbor_worker.batch_inference`): Runs deterministic, checkpointed batch inference with atomic `SIGTERM` cursor recovery (`--job-id`, `--checkpoint-dir`, `--prompts-file`, `--num-prompts`, `--seed`, `--batch-size`, `--spot-hourly-usd`, `--record-delay-sec`, `--ready-file`, `--manifest-out`).
73
+
74
+ ## HTTP Control Plane API
75
+
76
+ Full OpenAPI 3.1 specification: [`docs/openapi.yaml`](docs/openapi.yaml). Tenant-scoped job and billing endpoints require the `X-Org-ID` request header (except `POST /v1/jobs`, which reads `org_id` from the JSON body).
77
+
78
+ | Method & Path | Auth / Headers | Request / Query | Response |
79
+ | --- | --- | --- | --- |
80
+ | `GET /healthz` | None | — | `200 OK` `{"status":"ok"}` |
81
+ | `GET /readyz` | None | — | `200 OK` `{"status":"ready"}` or `503 Service Unavailable` `{"status":"draining"}` |
82
+ | `GET /ui` | None | — | `200 OK` HTML status & spot savings web console ([`pkg/server/ui.go`](pkg/server/ui.go)) |
83
+ | `GET /metrics` | None | — | `200 OK` Prometheus `0.0.4` text metrics ([ADR-003](docs/adr/003-prometheus-observability.md)) |
84
+ | `POST /v1/jobs` | `Content-Type: application/json` | `job_id`, `org_id`, `gpu`, `target_steps`, `max_preemptions` | `201 Created` `JobLease` |
85
+ | `GET /v1/jobs` | `X-Org-ID` | — | `200 OK` array of org-scoped `JobLease` objects |
86
+ | `GET /v1/jobs/{id}` | `X-Org-ID` | — | `200 OK` `JobLease` |
87
+ | `POST /v1/jobs/{id}/assign` | `X-Org-ID` | `{"worker_node_id": "..."}` | `200 OK` `JobLease` (`RUNNING`) |
88
+ | `POST /v1/jobs/{id}/heartbeat` | `X-Org-ID` | `{"worker_node_id": "..."}` | `200 OK` `JobLease` with updated `last_heartbeat_at` |
89
+ | `POST /v1/jobs/{id}/sigterm` | `X-Org-ID` | — | `200 OK` `JobLease` (`CHECKPOINTING`, idempotent) |
90
+ | `POST /v1/jobs/{id}/checkpoint` | `X-Org-ID` | `step`, `epoch`, `loss`, `safetensors_uri`, `manifest_uri`, `flush_latency_ms` | `200 OK` `JobLease` (`MIGRATING` or `COMPLETED`) |
91
+ | `POST /v1/jobs/{id}/cancel` | `X-Org-ID` | — | `200 OK` `JobLease` (`FAILED`, idempotent) |
92
+ | `POST /v1/jobs/{id}/barrier` | `X-Org-ID` | `world_size`, `rank`, `step` | `200 OK` `BarrierResponse` (`all_ready`, `committed_step`) |
93
+ | `GET /v1/cost/rank` | None | `min_vram`, `count`, `hours`, `fee` | `200 OK` ranked spot GPU pool quotes |
94
+ | `GET /v1/fleet/rank` | None | `min_vram`, `provider`, `min_availability` | `200 OK` multi-region fleet placements |
95
+ | `POST /v1/schedule` | `Content-Type: application/json` | `min_vram_gb`, `gpu_count`, `active_hours`, `fee_fraction`, `exclude_gpus` | `200 OK` selected pool + fallback alternatives |
96
+ | `GET /v1/billing/summary` | `X-Org-ID` | `fee` | `200 OK` org-scoped job & preemption billing summary |
97
+
98
+ ### Server Configuration Flags (`computeharbor serve`)
99
+
100
+ - `-state-file` / `-snapshot-interval`: Path for atomic coordinator JSON snapshot persistence across restarts, and background snapshot cadence when `-state-file` is set (default `5s`).
101
+ - `-reap-interval` / `-lease-ttl`: Background stale-lease reaper cadence (default `5s`) and heartbeat TTL (default `30s`).
102
+ - `-rate-limit-rps` / `-rate-limit-burst`: Per-org token-bucket rate limiting (`0` disables; default burst `20`).
103
+ - `-log-json`: Emit structured JSON HTTP request logs via `slog` to `stderr` (default `true`).
104
+ - `-webhook-url` / `-webhook-secret`: Async HTTP endpoint and HMAC-SHA256 secret for signed lifecycle webhook delivery.
105
+ - `-api-key`: Optional Bearer API key for HTTP authentication (defaults to `COMPUTEHARBOR_API_KEY`).
106
+ - `-org-api-keys`: Optional comma-separated org-scoped Bearer API keys (`org=token,...`, defaults to `COMPUTEHARBOR_ORG_API_KEYS`) that bind tokens to `X-Org-ID` tenants ([`ADR-007`](docs/adr/007-scoped-org-api-keys.md)).
107
+
108
+ ## Deployment & Observability
109
+
110
+ See [`docs/RUNBOOK.md`](docs/RUNBOOK.md) for production SRE operations, incident response, key rotation, and graceful draining procedures.
111
+
112
+ Run the control plane and Prometheus locally with Docker Compose:
113
+
114
+ ```bash
115
+ docker compose up --build
116
+ ```
117
+
118
+ - [`docker-compose.yml`](docker-compose.yml): Starts `control-plane` on `:8080` (with `/healthz` healthcheck) and `prometheus` (`prom/prometheus:v2.55.1`) on `:9090`.
119
+ - [`Dockerfile`](Dockerfile): Multi-stage `golang:1.23-alpine` -> `gcr.io/distroless/static-debian12:nonroot` build for the `computeharbor` control plane (`serve -addr :8080`).
120
+ - [`Dockerfile.worker`](Dockerfile.worker): `python:3.12-slim` image installing `computeharbor_worker` with entrypoint `python -m computeharbor_worker.daemon`.
121
+ - [`deploy/prometheus.yml`](deploy/prometheus.yml) & [`deploy/grafana-dashboard.json`](deploy/grafana-dashboard.json): Prometheus scrape config (`5s` interval) and pre-built Grafana dashboard.
122
+ - Kubernetes manifests: [`deploy/k8s/control-plane.yaml`](deploy/k8s/control-plane.yaml) and [`deploy/k8s/worker-job.yaml`](deploy/k8s/worker-job.yaml).
123
+
124
+ ## Architecture
125
+
126
+ - [`control-plane/cmd/computeharbor/main.go`](control-plane/cmd/computeharbor/main.go): CLI for cost modeling, `status`/`savings` queries, and the `serve` HTTP control plane.
127
+ - [`pkg/server/server.go`](pkg/server/server.go): Stdlib `net/http` JSON API for job leases, scheduling, billing summaries, Prometheus metrics, per-org rate limiting, and `X-Org-ID` tenant isolation.
128
+ - [`pkg/cost/calculator.go`](pkg/cost/calculator.go): Spot pricing catalog (NVIDIA L4, A10G, A100-40GB, A100-80GB, H100-80GB), multi-region fleet ranking, preemption recovery overhead accounting, and net customer savings after the platform fee.
129
+ - [`pkg/orchestrator/coordinator.go`](pkg/orchestrator/coordinator.go): Thread-safe job lease state machine (`QUEUED` -> `RUNNING` -> `CHECKPOINTING` -> `MIGRATING` -> `COMPLETED` / `FAILED`) with idempotent `SIGTERM` handling, step-regression guards, and `RingBarrier` synchronization.
130
+ - [`worker/src/computeharbor_worker/`](worker/src/computeharbor_worker/): Python 3.12+ worker that intercepts `SIGTERM`, syncs CUDA when available, writes LoRA weights and AdamW state to a temporary Safetensors file, calls `os.fsync`, atomically swaps `latest.json`, optionally replicates to an object-store mirror (`--remote-store-dir`), and verifies SHA-256 integrity on restore.
131
+ - [`tests/chaos/test_sigterm_preemption.py`](tests/chaos/test_sigterm_preemption.py): Subprocess chaos harness that injects three OS `SIGTERM` signals into a live training run and checks bit-for-bit loss and weight parity against an uninterrupted baseline.
132
+ - Architecture Decision Records: [`ADR-001`](docs/adr/001-lora-streaming-checkpoints.md), [`ADR-002`](docs/adr/002-control-plane-http-api.md), [`ADR-003`](docs/adr/003-prometheus-observability.md), [`ADR-004`](docs/adr/004-rate-limiting-and-observability.md), [`ADR-005`](docs/adr/005-event-webhooks-and-fleet-routing.md), and [`ADR-006`](docs/adr/006-readiness-and-request-correlation.md).
133
+
134
+ ## Measured Benchmarks
135
+
136
+ ### Preemption recovery and bit-for-bit loss parity
137
+
138
+ Run on a 10-core Apple Silicon host (`Darwin arm64`, Python 3.12.12, 5 trials, 3 real `SIGTERM` preemptions per trial, 15 preemptions total):
139
+
140
+ | Metric | Value | SLA / Gate |
141
+ | --- | --- | --- |
142
+ | Step-by-step loss curve parity (30 steps, 3 `SIGTERM` kills) | 15 / 15 preemptions (100% bit-for-bit match) | 100% parity |
143
+ | Final `lora_a` and `lora_b` SHA-256 match | 5 / 5 trials exact match | 100% match |
144
+ | Safetensors + manifest `fsync` flush latency (median) | 0.737 ms (range 0.656 ms to 1.286 ms) | < 30,000 ms |
145
+ | End-to-end `SIGTERM` to checkpoint restore latency (median) | 25.147 ms (range 21.643 ms to 67.660 ms) | < 30,000 ms |
146
+
147
+ Limiter: `os.fsync` syscall latency on the local APFS volume for the Safetensors file and two JSON manifests (`step-NNNNNN.manifest.json` and `latest.json`).
148
+
149
+ ### Spot vs on-demand cost savings (4 GPUs, 24 active hours, 12% savings fee)
150
+
151
+ | Pool | Provider | On-demand cost | Raw spot cost | Platform fee (12%) | Net customer cost | Gross savings | Net savings |
152
+ | --- | --- | --- | --- | --- | --- | --- | --- |
153
+ | `nvidia-l4-24gb` | GCP (`us-central1`) | \$81.60 | \$23.05 | \$7.03 | \$30.07 | 71.76% | 63.15% |
154
+ | `nvidia-a10g-24gb` | AWS (`us-east-1`) | \$116.16 | \$34.57 | \$9.79 | \$44.36 | 70.24% | 61.81% |
155
+ | `nvidia-a100-40gb` | GCP (`us-central1`) | \$352.32 | \$105.64 | \$29.60 | \$135.25 | 70.01% | 61.61% |
156
+ | `nvidia-a100-80gb` | AWS (`us-west-2`) | \$470.40 | \$136.40 | \$40.08 | \$176.48 | 71.00% | 62.48% |
157
+ | `nvidia-h100-80gb` | GCP (`us-east4`) | \$825.60 | \$247.82 | \$69.33 | \$317.15 | 69.98% | 61.59% |
158
+
159
+ ### Control Plane Throughput (Go Benchmarks)
160
+
161
+ Measured on Apple M5 (`Darwin arm64`, `make bench`):
162
+
163
+ | Benchmark | Result |
164
+ | --- | --- |
165
+ | `BenchmarkCalculate-10` | `38.35 ns/op` |
166
+ | `BenchmarkRankFleet-10` | `1383 ns/op` |
167
+ | `BenchmarkCoordinatorSubmitAndHeartbeat-10` | `479.3 ns/op` |
168
+ | `BenchmarkCoordinatorReapStaleLeases-10` | `9071 ns/op` |
169
+
170
+ ## Reproduce All Checks
171
+
172
+ ```bash
173
+ # Run all linters, type checks, unit tests, E2E tests, and SIGTERM chaos tests
174
+ make lint
175
+ make test
176
+ make test-e2e
177
+ make chaos
178
+
179
+ # Reproduce the 5-trial SIGTERM benchmark JSON report
180
+ PYTHONPATH=worker/src .venv/bin/python tests/chaos/test_sigterm_preemption.py
181
+ ```
182
+
183
+ ## Contributing
184
+
185
+ See [`CONTRIBUTING.md`](CONTRIBUTING.md) for development setup, test/lint requirements, and PR guidelines. Also see [`SECURITY.md`](SECURITY.md), [`docs/RUNBOOK.md`](docs/RUNBOOK.md), [`AGENTS.md`](AGENTS.md), [`LICENSE`](LICENSE), [`docs/adr/000-template.md`](docs/adr/000-template.md), and [`docs/THREAT_MODEL.md`](docs/THREAT_MODEL.md).
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "computeharbor-worker"
7
+ version = "0.2.4"
8
+ description = "ComputeHarbor Spot-GPU & Edge LLM LoRA Checkpoint Worker"
9
+ readme = "README.md"
10
+ requires-python = ">=3.12"
11
+ license = "MIT"
12
+ authors = [{ name = "Creova" }]
13
+ keywords = ["llm", "fine-tuning", "lora", "spot-gpu", "checkpointing", "preemption"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3.12",
18
+ "Programming Language :: Python :: 3.13",
19
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
20
+ "Topic :: System :: Distributed Computing",
21
+ ]
22
+ dependencies = [
23
+ "numpy>=2.0",
24
+ "pydantic>=2.9",
25
+ "safetensors>=0.4",
26
+ ]
27
+
28
+ [project.optional-dependencies]
29
+ dev = [
30
+ "mypy>=1.10",
31
+ "pytest>=8.0",
32
+ "ruff>=0.6",
33
+ ]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/creova-gif/computeharbor"
37
+ Repository = "https://github.com/creova-gif/computeharbor"
38
+ Documentation = "https://github.com/creova-gif/computeharbor/tree/main/docs"
39
+
40
+ [project.scripts]
41
+ computeharbor-worker = "computeharbor_worker.daemon:main"
42
+ computeharbor-supervisor = "computeharbor_worker.supervisor:main"
43
+ computeharbor-batch = "computeharbor_worker.batch_inference:main"
44
+
45
+ [tool.setuptools.packages.find]
46
+ where = ["worker/src"]
47
+
48
+ [tool.pytest.ini_options]
49
+ pythonpath = ["worker/src"]
50
+ testpaths = ["worker/tests", "tests/chaos", "tests/e2e"]
51
+
52
+ [tool.mypy]
53
+ strict = true
54
+ mypy_path = "worker/src"
55
+ files = ["worker/src", "worker/tests", "tests/chaos", "tests/e2e"]
56
+
57
+ [[tool.mypy.overrides]]
58
+ module = ["safetensors.*"]
59
+ ignore_missing_imports = true
60
+
61
+ [tool.ruff]
62
+ line-length = 100
63
+ target-version = "py312"
64
+
65
+ [tool.ruff.lint]
66
+ select = ["E", "F", "I", "UP", "B", "SIM"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,43 @@
1
+ from computeharbor_worker.batch_inference import (
2
+ BatchCursorManifest,
3
+ BatchInferenceRunner,
4
+ BatchRunSummary,
5
+ )
6
+ from computeharbor_worker.checkpoint import CheckpointManager
7
+ from computeharbor_worker.client import ControlPlaneClient, ControlPlaneError
8
+ from computeharbor_worker.daemon import run_worker_daemon
9
+ from computeharbor_worker.models import CheckpointManifest, LoRAConfig, RNGStatePayload
10
+ from computeharbor_worker.preemption import MetadataPreemptionWatcher, MetadataProvider
11
+ from computeharbor_worker.storage import (
12
+ CheckpointStore,
13
+ HTTPPresignedStore,
14
+ LocalMirrorObjectStore,
15
+ cuda_synchronize_if_available,
16
+ store_from_uri,
17
+ )
18
+ from computeharbor_worker.supervisor import FailoverResult, run_job_with_failover
19
+ from computeharbor_worker.trainer import LoRATrainer, RunResult
20
+
21
+ __all__ = [
22
+ "BatchCursorManifest",
23
+ "BatchInferenceRunner",
24
+ "BatchRunSummary",
25
+ "CheckpointManager",
26
+ "CheckpointManifest",
27
+ "CheckpointStore",
28
+ "ControlPlaneClient",
29
+ "ControlPlaneError",
30
+ "FailoverResult",
31
+ "HTTPPresignedStore",
32
+ "LoRAConfig",
33
+ "LoRATrainer",
34
+ "LocalMirrorObjectStore",
35
+ "MetadataPreemptionWatcher",
36
+ "MetadataProvider",
37
+ "RNGStatePayload",
38
+ "RunResult",
39
+ "cuda_synchronize_if_available",
40
+ "run_job_with_failover",
41
+ "run_worker_daemon",
42
+ "store_from_uri",
43
+ ]