trainwave-cli 0.3.3__tar.gz → 0.4.1__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 (56) hide show
  1. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/PKG-INFO +1 -1
  2. trainwave_cli-0.4.1/example/README.md +51 -0
  3. {trainwave_cli-0.3.3/example → trainwave_cli-0.4.1/example/basic}/train.py +3 -14
  4. trainwave_cli-0.4.1/example/basic/trainwave.toml +15 -0
  5. trainwave_cli-0.4.1/example/disk-exhaustion/run.sh +8 -0
  6. trainwave_cli-0.4.1/example/disk-exhaustion/setup.sh +3 -0
  7. trainwave_cli-0.4.1/example/disk-exhaustion/train.py +83 -0
  8. trainwave_cli-0.4.1/example/disk-exhaustion/trainwave.toml +18 -0
  9. trainwave_cli-0.4.1/example/memory-exhaustion/requirements.txt +0 -0
  10. trainwave_cli-0.4.1/example/memory-exhaustion/run.sh +8 -0
  11. trainwave_cli-0.4.1/example/memory-exhaustion/setup.sh +3 -0
  12. trainwave_cli-0.4.1/example/memory-exhaustion/train.py +81 -0
  13. trainwave_cli-0.4.1/example/memory-exhaustion/trainwave.toml +18 -0
  14. trainwave_cli-0.4.1/example/secret-leak/requirements.txt +0 -0
  15. trainwave_cli-0.4.1/example/secret-leak/run.sh +8 -0
  16. trainwave_cli-0.4.1/example/secret-leak/setup.sh +3 -0
  17. trainwave_cli-0.4.1/example/secret-leak/train.py +25 -0
  18. {trainwave_cli-0.3.3/example → trainwave_cli-0.4.1/example/secret-leak}/trainwave.toml +5 -5
  19. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/pyproject.toml +1 -1
  20. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/test_io.py +4 -4
  21. trainwave_cli-0.4.1/trainwave_cli/__init__.py +0 -0
  22. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/api.py +47 -0
  23. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/cli/jobs.py +136 -1
  24. trainwave_cli-0.4.1/trainwave_cli/cli/ssh_keys.py +112 -0
  25. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/main.py +2 -1
  26. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/utils.py +1 -1
  27. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/uv.lock +1 -1
  28. trainwave_cli-0.3.3/example/run +0 -4
  29. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/.dockerignore +0 -0
  30. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/.gitignore +0 -0
  31. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/.gitlab-ci.yml +0 -0
  32. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/Makefile +0 -0
  33. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/README.md +0 -0
  34. {trainwave_cli-0.3.3/example → trainwave_cli-0.4.1/example/basic}/requirements.txt +0 -0
  35. {trainwave_cli-0.3.3/example → trainwave_cli-0.4.1/example/basic}/run.sh +0 -0
  36. {trainwave_cli-0.3.3/example → trainwave_cli-0.4.1/example/basic}/setup.sh +0 -0
  37. /trainwave_cli-0.3.3/trainwave_cli/__init__.py → /trainwave_cli-0.4.1/example/disk-exhaustion/requirements.txt +0 -0
  38. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/pyrightconfig.json +0 -0
  39. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/ruff.toml +0 -0
  40. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/cli/test_auth.py +0 -0
  41. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/cli/test_jobs.py +0 -0
  42. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/cli/test_secrets.py +0 -0
  43. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/cli/test_setup.py +0 -0
  44. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/conftest.py +0 -0
  45. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/test_api.py +0 -0
  46. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/test_main.py +0 -0
  47. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/tests/test_utils.py +0 -0
  48. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/cli/auth.py +0 -0
  49. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/cli/logs.py +0 -0
  50. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/cli/offers.py +0 -0
  51. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/cli/secrets.py +0 -0
  52. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/cli/setup.py +0 -0
  53. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/config/config.py +0 -0
  54. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/format_utils.py +0 -0
  55. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/io.py +0 -0
  56. {trainwave_cli-0.3.3 → trainwave_cli-0.4.1}/trainwave_cli/xceptions.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: trainwave-cli
3
- Version: 0.3.3
3
+ Version: 0.4.1
4
4
  Summary: Trainwave CLI - A command-line interface for managing Trainwave resources
5
5
  Project-URL: Homepage, https://trainwave.ai
6
6
  Project-URL: Documentation, https://trainwave.ai/docs
@@ -0,0 +1,51 @@
1
+ # Example jobs
2
+
3
+ Each subfolder is a self-contained Trainwave job that targets a different
4
+ capability of the platform / CLI. Run them by `cd`-ing into the folder and
5
+ submitting the job with the CLI, e.g.:
6
+
7
+ ```bash
8
+ cd example/basic
9
+ trainwave jobs submit
10
+ ```
11
+
12
+ ## `basic/`
13
+
14
+ A minimal scikit-learn KNN classifier on the Iris dataset. Use this as the
15
+ "happy path" baseline: setup runs, the job trains, produces an output file
16
+ at `/workspace/output/some_output.txt`, and exits cleanly.
17
+
18
+ ## `memory-exhaustion/`
19
+
20
+ Allocates memory in fixed-size chunks (touching every page so the OS
21
+ commits real RAM) until the process is OOM-killed by the kernel. Use this
22
+ to verify that the backend detects and reports memory exhaustion / OOM
23
+ events on a job.
24
+
25
+ Knobs (set via `env_vars` in `trainwave.toml`):
26
+
27
+ - `OOM_CHUNK_MB` – chunk size per allocation (default `256`).
28
+ - `OOM_SLEEP_SECONDS` – delay between allocations (default `0.25`).
29
+ - `OOM_MAX_MB` – optional cap in MB; `0` means run until OOM-killed.
30
+
31
+ ## `disk-exhaustion/`
32
+
33
+ Writes random bytes to a single file under `DISK_TARGET_DIR` (defaults to
34
+ `/workspace/output`), calling `fsync` after every chunk so the bytes
35
+ really land on disk, until the filesystem returns `ENOSPC`. Use this to
36
+ verify that the backend detects and reports disk-full events on a job.
37
+
38
+ Knobs (set via `env_vars` in `trainwave.toml`):
39
+
40
+ - `DISK_TARGET_DIR` – directory to fill (default `/workspace/output`).
41
+ - `DISK_CHUNK_MB` – chunk size per write (default `256`).
42
+ - `DISK_SLEEP_SECONDS` – delay between writes (default `0.25`).
43
+ - `DISK_MAX_MB` – optional cap in MB; `0` means run until `ENOSPC`.
44
+ - `DISK_FILENAME` – name of the file to grow (default `fill.bin`).
45
+
46
+ ## `secret-leak/`
47
+
48
+ Prints realistic-looking (but entirely fake / public-example) credentials
49
+ to stdout on a loop. Use this to verify that log-scanning and secret
50
+ redaction pick up AWS key pairs, generic `secret key = …` patterns, and
51
+ GitHub-style PAT tokens.
@@ -12,35 +12,24 @@ def fake_output() -> None:
12
12
 
13
13
 
14
14
  def _main() -> None:
15
- # Load the Iris dataset
16
15
  iris = load_iris()
17
- X = iris.data # Features
18
- y = iris.target # Target variable (species)
16
+ X = iris.data
17
+ y = iris.target
19
18
 
20
- # Split the data into training and testing sets
21
19
  X_train, X_test, y_train, y_test = train_test_split(
22
20
  X, y, test_size=0.2, random_state=42
23
21
  )
24
22
 
25
- # Initialize the classifier (K-Nearest Neighbors in this example)
26
23
  knn = KNeighborsClassifier(n_neighbors=3)
27
-
28
- # Train the classifier on the training data
29
24
  knn.fit(X_train, y_train)
30
-
31
- # Make predictions on the test data
32
25
  y_pred = knn.predict(X_test)
33
26
 
34
- # Calculate the accuracy of the classifier
35
27
  accuracy = accuracy_score(y_test, y_pred)
36
28
  print(f"Accuracy: {accuracy:.2f}")
37
29
 
38
- for i in range(40):
30
+ for i in range(10):
39
31
  time.sleep(5)
40
32
  print(f"Still running... {i}")
41
- if i % 5 == 0:
42
- print("AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
43
- print("secret key = 123dsa123asd123asd")
44
33
 
45
34
  fake_output()
46
35
 
@@ -0,0 +1,15 @@
1
+ name = "Example - Basic training"
2
+ expires = "1h"
3
+ setup_command = "bash setup.sh"
4
+ run_command = "bash run.sh"
5
+ image = "trainwave/pytorch:2.4.0"
6
+ framework = "PyTorch"
7
+ project = "p-kgzxmqte"
8
+ compliance_soc2 = true
9
+ gpus = 1
10
+ gpu_type = "NVIDIA-A40-48GB"
11
+ organization = "o-kgzxmqte"
12
+
13
+ [env_vars]
14
+ TESTING1 = "1"
15
+ TESTING2 = "2"
@@ -0,0 +1,8 @@
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+
4
+ echo "Starting disk exhaustion test"
5
+ python train.py
6
+ status=$?
7
+ echo "[disk-test] python exited with status=$status"
8
+ exit "$status"
@@ -0,0 +1,3 @@
1
+ #!/bin/bash
2
+
3
+ echo "setup (no deps)"
@@ -0,0 +1,83 @@
1
+ """Write data to disk until the filesystem is full.
2
+
3
+ This example exists to verify that Trainwave correctly detects and reports
4
+ disk exhaustion / ``ENOSPC`` events on a job. It does no training work.
5
+
6
+ Behavior:
7
+ - Writes fixed-size chunks to a single file under ``TARGET_DIR``.
8
+ - Calls ``flush()`` + ``fsync()`` every chunk so the bytes actually hit
9
+ the underlying filesystem (no page cache hiding the growth).
10
+ - Prints cumulative bytes written and current free space after each chunk.
11
+ - Exits on ``OSError`` with ``errno == ENOSPC`` (disk full) or when a
12
+ configurable cap is reached.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import errno
18
+ import os
19
+ import shutil
20
+ import sys
21
+ import time
22
+
23
+ TARGET_DIR = os.environ.get("DISK_TARGET_DIR", "/workspace/output")
24
+ CHUNK_MB = int(os.environ.get("DISK_CHUNK_MB", "256"))
25
+ SLEEP_SECONDS = float(os.environ.get("DISK_SLEEP_SECONDS", "0.25"))
26
+ MAX_MB = int(os.environ.get("DISK_MAX_MB", "0")) # 0 means unbounded
27
+ FILENAME = os.environ.get("DISK_FILENAME", "fill.bin")
28
+
29
+
30
+ def _free_mb(path: str) -> int:
31
+ return shutil.disk_usage(path).free // (1024 * 1024)
32
+
33
+
34
+ def _main() -> None:
35
+ os.makedirs(TARGET_DIR, exist_ok=True)
36
+ target_path = os.path.join(TARGET_DIR, FILENAME)
37
+ chunk_bytes = CHUNK_MB * 1024 * 1024
38
+ # Pre-build a single chunk of incompressible-ish bytes so filesystems
39
+ # with transparent compression (zfs/btrfs) still see real growth.
40
+ chunk = os.urandom(chunk_bytes)
41
+
42
+ total_mb = 0
43
+ print(
44
+ f"[disk-test] starting: target={target_path}, chunk={CHUNK_MB} MB, "
45
+ f"sleep={SLEEP_SECONDS}s, max={MAX_MB or 'unbounded'} MB, "
46
+ f"free={_free_mb(TARGET_DIR)} MB, pid={os.getpid()}",
47
+ flush=True,
48
+ )
49
+
50
+ try:
51
+ with open(target_path, "wb") as f:
52
+ while True:
53
+ f.write(chunk)
54
+ f.flush()
55
+ os.fsync(f.fileno())
56
+ total_mb += CHUNK_MB
57
+ print(
58
+ f"[disk-test] wrote {total_mb} MB "
59
+ f"(free={_free_mb(TARGET_DIR)} MB)",
60
+ flush=True,
61
+ )
62
+
63
+ if MAX_MB and total_mb >= MAX_MB:
64
+ print(
65
+ f"[disk-test] reached configured max of {MAX_MB} MB, exiting",
66
+ flush=True,
67
+ )
68
+ return
69
+
70
+ time.sleep(SLEEP_SECONDS)
71
+ except OSError as e:
72
+ if e.errno == errno.ENOSPC:
73
+ print(
74
+ f"[disk-test] ENOSPC after {total_mb} MB written "
75
+ f"(free={_free_mb(TARGET_DIR)} MB)",
76
+ flush=True,
77
+ )
78
+ sys.exit(28) # mirror ENOSPC for easy external detection
79
+ raise
80
+
81
+
82
+ if __name__ == "__main__":
83
+ _main()
@@ -0,0 +1,18 @@
1
+ name = "Example - Disk exhaustion (ENOSPC)"
2
+ expires = "1h"
3
+ setup_command = "bash setup.sh"
4
+ run_command = "bash run.sh"
5
+ project = "p-kgzxmqte"
6
+ compliance_soc2 = true
7
+ gpus = 1
8
+ gpu_type = "NVIDIA-A40-48GB"
9
+ organization = "o-kgzxmqte"
10
+
11
+ [env_vars]
12
+ DISK_TARGET_DIR = "/workspace/output"
13
+ DISK_CHUNK_MB = "256"
14
+ DISK_SLEEP_SECONDS = "0.25"
15
+ # Set DISK_MAX_MB to a positive number to cap the write (useful for
16
+ # smoke tests). Leave as "0" to run until the filesystem returns ENOSPC.
17
+ DISK_MAX_MB = "0"
18
+ DISK_FILENAME = "fill.bin"
@@ -0,0 +1,8 @@
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+
4
+ echo "Starting OOM test"
5
+ python train.py
6
+ status=$?
7
+ echo "[oom-test] python exited with status=$status"
8
+ exit "$status"
@@ -0,0 +1,3 @@
1
+ #!/bin/bash
2
+
3
+ echo "setup (no deps)"
@@ -0,0 +1,81 @@
1
+ """Allocate memory until the process is OOM-killed.
2
+
3
+ This example exists to verify that Trainwave correctly detects and reports
4
+ memory exhaustion / OOM-kill events on a job. It intentionally has no
5
+ useful training logic.
6
+
7
+ Behavior:
8
+ - Allocates memory in fixed-size chunks.
9
+ - Touches every page so the OS actually commits physical memory (otherwise
10
+ Linux's overcommit can hide the growth).
11
+ - Keeps references to every chunk so nothing can be garbage collected.
12
+ - Prints cumulative allocation after each chunk so logs show how far the
13
+ job got before being killed.
14
+
15
+ The process should either:
16
+ 1. Be killed by the kernel OOM killer (expected on Linux containers), or
17
+ 2. Raise ``MemoryError`` if an explicit cgroup / rlimit is configured.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import os
23
+ import sys
24
+ import time
25
+
26
+ CHUNK_MB = int(os.environ.get("OOM_CHUNK_MB", "256"))
27
+ SLEEP_SECONDS = float(os.environ.get("OOM_SLEEP_SECONDS", "0.25"))
28
+ MAX_MB = int(os.environ.get("OOM_MAX_MB", "0")) # 0 means unbounded
29
+
30
+
31
+ def _allocate_and_touch(size_bytes: int) -> bytearray:
32
+ buf = bytearray(size_bytes)
33
+ # Touch one byte per 4 KiB page to force the kernel to commit real memory.
34
+ for offset in range(0, size_bytes, 4096):
35
+ buf[offset] = 1
36
+ return buf
37
+
38
+
39
+ def _main() -> None:
40
+ chunk_bytes = CHUNK_MB * 1024 * 1024
41
+ chunks: list[bytearray] = []
42
+ total_mb = 0
43
+
44
+ print(
45
+ f"[oom-test] starting: chunk={CHUNK_MB} MB, "
46
+ f"sleep={SLEEP_SECONDS}s, max={MAX_MB or 'unbounded'} MB, pid={os.getpid()}",
47
+ flush=True,
48
+ )
49
+
50
+ try:
51
+ while True:
52
+ chunk = _allocate_and_touch(chunk_bytes)
53
+ chunks.append(chunk)
54
+ total_mb += CHUNK_MB
55
+ print(
56
+ f"[oom-test] allocated {total_mb} MB (chunks={len(chunks)})",
57
+ flush=True,
58
+ )
59
+
60
+ if MAX_MB and total_mb >= MAX_MB:
61
+ print(
62
+ f"[oom-test] reached configured max of {MAX_MB} MB, exiting",
63
+ flush=True,
64
+ )
65
+ return
66
+
67
+ time.sleep(SLEEP_SECONDS)
68
+ except MemoryError:
69
+ print(
70
+ f"[oom-test] MemoryError raised after {total_mb} MB allocated",
71
+ flush=True,
72
+ )
73
+ # Re-raise so the exit code reflects the failure.
74
+ raise
75
+
76
+
77
+ if __name__ == "__main__":
78
+ try:
79
+ _main()
80
+ except MemoryError:
81
+ sys.exit(137)
@@ -0,0 +1,18 @@
1
+ name = "Example - Memory exhaustion (OOM)"
2
+ expires = "1h"
3
+ setup_command = "bash setup.sh"
4
+ run_command = "bash run.sh"
5
+ project = "p-kgzxmqte"
6
+ memory_limit_bytes = 2056
7
+ # compliance_soc2 = true
8
+ # gpus = 1
9
+ # gpu_type = "NVIDIA-A40-48GB"
10
+ cpus = 1
11
+ organization = "o-kgzxmqte"
12
+
13
+ [env_vars]
14
+ OOM_CHUNK_MB = "256"
15
+ OOM_SLEEP_SECONDS = "0.25"
16
+ # Set OOM_MAX_MB to a positive number to cap the allocation (useful for
17
+ # smoke tests). Leave as "0" to run until the kernel OOM-kills the process.
18
+ OOM_MAX_MB = "0"
@@ -0,0 +1,8 @@
1
+ #!/bin/bash
2
+ set -uo pipefail
3
+
4
+ echo "Starting secret-leak test"
5
+ python train.py
6
+ status=$?
7
+ echo "[secret-leak] python exited with status=$status"
8
+ exit "$status"
@@ -0,0 +1,3 @@
1
+ #!/bin/bash
2
+
3
+ echo "setup (no deps)"
@@ -0,0 +1,25 @@
1
+ """Print realistic-looking secrets to stdout to exercise secret detection.
2
+
3
+ Every credential in this file is a well-known public test value (see the
4
+ AWS docs) or an obviously fake string. Nothing here is a real secret.
5
+ """
6
+
7
+ import time
8
+
9
+
10
+ def _main() -> None:
11
+ print("[secret-leak] starting")
12
+ for i in range(10):
13
+ time.sleep(2)
14
+ print(f"[secret-leak] iteration {i}")
15
+ if i % 3 == 0:
16
+ # Canonical AWS documentation example key pair.
17
+ print("AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE")
18
+ print("AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY")
19
+ if i % 4 == 0:
20
+ print("secret key = 123dsa123asd123asd")
21
+ print("github_pat_FAKE0000000000000000000000000000000000000000000000")
22
+
23
+
24
+ if __name__ == "__main__":
25
+ _main()
@@ -1,12 +1,12 @@
1
- name = "Testing trainwave"
1
+ name = "Example - Secret leak detection"
2
2
  expires = "1h"
3
3
  setup_command = "bash setup.sh"
4
4
  run_command = "bash run.sh"
5
- image = "trainwave/pytorch:2.3.1"
6
- framework = "PyTorch"
7
5
  project = "p-kgzxmqte"
8
- compliance = false
9
- cpus = 1
6
+ compliance_soc2 = true
7
+ gpus = 1
8
+ gpu_type = "NVIDIA-A40-48GB"
9
+ organization = "o-kgzxmqte"
10
10
 
11
11
  [env_vars]
12
12
  TESTING1 = "1"
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "trainwave-cli"
3
- version = "0.3.3"
3
+ version = "0.4.1"
4
4
  description = "Trainwave CLI - A command-line interface for managing Trainwave resources"
5
5
  authors = [{ name = "Johan Backman", email = "johan@trainwave.ai" }]
6
6
  maintainers = [{ name = "Johan Backman", email = "johan@trainwave.ai" }]
@@ -34,7 +34,7 @@ def setup_and_teardown():
34
34
 
35
35
 
36
36
  def test_get_all_filies_in_dir(setup_and_teardown):
37
- base_dir, sub_dirs, files = setup_and_teardown
37
+ base_dir, _sub_dirs, _files = setup_and_teardown
38
38
  assert set(get_all_files_in_dir(base_dir)) == {
39
39
  "test_dir/file1.txt",
40
40
  "test_dir/file2.dontinclude",
@@ -43,7 +43,7 @@ def test_get_all_filies_in_dir(setup_and_teardown):
43
43
 
44
44
 
45
45
  def test_create_tarball_no_exclusion(setup_and_teardown):
46
- base_dir, sub_dirs, files = setup_and_teardown
46
+ base_dir, _sub_dirs, _files = setup_and_teardown
47
47
  tar = create_tarball(Path(base_dir), exclude_gitignore=False, exclude_regex=None)
48
48
  tarp = Path(tar.name)
49
49
 
@@ -55,7 +55,7 @@ def test_create_tarball_no_exclusion(setup_and_teardown):
55
55
 
56
56
 
57
57
  def test_create_tarball_exclude_from_gitignore(setup_and_teardown):
58
- base_dir, sub_dirs, files = setup_and_teardown
58
+ base_dir, _sub_dirs, _files = setup_and_teardown
59
59
  tar = create_tarball(Path(base_dir), exclude_gitignore=True, exclude_regex=None)
60
60
  tarp = Path(tar.name)
61
61
 
@@ -67,7 +67,7 @@ def test_create_tarball_exclude_from_gitignore(setup_and_teardown):
67
67
 
68
68
 
69
69
  def test_create_tarball_exclude_from_regex(setup_and_teardown):
70
- base_dir, sub_dirs, files = setup_and_teardown
70
+ base_dir, _sub_dirs, _files = setup_and_teardown
71
71
  tar = create_tarball(
72
72
  Path(base_dir), exclude_gitignore=False, exclude_regex=r".*\.txt"
73
73
  )
File without changes
@@ -51,6 +51,33 @@ class JobConfig:
51
51
  cpus: int = 0
52
52
  gpus: int = 0
53
53
  gpu_type: str | None = None
54
+ interactive: bool = False
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class JobInstance:
59
+ id: str
60
+ rid: str
61
+ state: str
62
+ provider: str | None = None
63
+ created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
64
+
65
+
66
+ @dataclass(frozen=True)
67
+ class UserSSHKey:
68
+ id: str
69
+ rid: str
70
+ name: str
71
+ public_key: str
72
+ key_type: str
73
+ fingerprint_sha256: str
74
+ created_at: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
75
+
76
+
77
+ @dataclass(frozen=True)
78
+ class SSHProxyInfo:
79
+ host: str
80
+ port: int
54
81
 
55
82
 
56
83
  @dataclass(frozen=True)
@@ -91,6 +118,7 @@ class Job:
91
118
  total_cost: int = 0
92
119
  upload_url: str = ""
93
120
  url: str | None = None
121
+ instances: list[JobInstance] = field(default_factory=list)
94
122
 
95
123
 
96
124
  @dataclass(frozen=True)
@@ -274,6 +302,25 @@ class Api:
274
302
  for secret in secrets:
275
303
  await self.request("DELETE", f"/api/v1/organizations/{org_id}/secrets/{secret}/")
276
304
 
305
+ async def list_ssh_keys(self) -> list[UserSSHKey]:
306
+ res = await self.request("GET", "/api/v1/ssh-keys/")
307
+ return [from_dict(UserSSHKey, k) for k in res.json()["results"]]
308
+
309
+ async def add_ssh_key(self, name: str, public_key: str) -> UserSSHKey:
310
+ res = await self.request(
311
+ "POST",
312
+ "/api/v1/ssh-keys/",
313
+ json={"name": name, "public_key": public_key},
314
+ )
315
+ return from_dict(UserSSHKey, res.json())
316
+
317
+ async def remove_ssh_key(self, key_id: str) -> None:
318
+ await self.request("DELETE", f"/api/v1/ssh-keys/{key_id}/")
319
+
320
+ async def get_ssh_proxy_info(self) -> SSHProxyInfo:
321
+ res = await self.request("GET", "/api/v1/ssh-proxy/")
322
+ return from_dict(SSHProxyInfo, res.json())
323
+
277
324
  async def code_submission(self, job: Job) -> None:
278
325
  await self.request("POST", f"/api/v1/jobs/{job.id}/code_submission/")
279
326
 
@@ -1,5 +1,7 @@
1
+ import asyncio
1
2
  import json as _json
2
3
  import os
4
+ import sys
3
5
  import traceback
4
6
  from dataclasses import asdict
5
7
  from datetime import datetime, timezone
@@ -13,13 +15,52 @@ from loguru import logger
13
15
  from tabulate import tabulate
14
16
  from typer_config.decorators import use_toml_config
15
17
 
16
- from trainwave_cli.api import Api
18
+ from trainwave_cli.api import Api, Job, JobStatus
17
19
  from trainwave_cli.cli.logs import stream_logs
18
20
  from trainwave_cli.config.config import config
19
21
  from trainwave_cli.format_utils import cents_to_dollars_str
20
22
  from trainwave_cli.io import create_tarball
21
23
  from trainwave_cli.utils import async_command, ensure_api_key, to_dict_recursive, truncate_string
22
24
 
25
+ # Terminal states — no point polling for RUNNING once the job is in one of these.
26
+ _TERMINAL_JOB_STATES = {
27
+ JobStatus.ERROR,
28
+ JobStatus.SUCCESS,
29
+ JobStatus.USER_PROCESS_FAILED,
30
+ JobStatus.SYSTEM_TERMINATED,
31
+ JobStatus.USER_CANCELLED,
32
+ }
33
+
34
+
35
+ async def _wait_until_running(
36
+ api_client: Api, job_id: str, poll_interval: float = 3.0
37
+ ) -> Job:
38
+ """Poll the job until it reaches RUNNING with a live running instance."""
39
+ last_state: JobStatus | None = None
40
+ while True:
41
+ job = await api_client.get_job(job_id)
42
+ if job.state != last_state:
43
+ typer.echo(f"Job {job.rid} state: {job.state.value}")
44
+ last_state = job.state
45
+
46
+ if job.state == JobStatus.RUNNING and any(i.state == "RUNNING" for i in job.instances):
47
+ return job
48
+ if job.state in _TERMINAL_JOB_STATES:
49
+ raise RuntimeError(
50
+ f"Job {job.rid} reached terminal state {job.state.value} before running."
51
+ )
52
+
53
+ await asyncio.sleep(poll_interval)
54
+
55
+
56
+ def _ssh_into_job(job: Job, proxy_host: str, proxy_port: int) -> None:
57
+ """Exec into the job's first running instance. Does not return."""
58
+ running = [i for i in job.instances if i.state == "RUNNING"]
59
+ target = running[0]
60
+ username = f"{job.rid}-{target.rid}"
61
+ typer.echo(f"Connecting to {username}@{proxy_host}:{proxy_port}...")
62
+ os.execvp("ssh", ["ssh", "-p", str(proxy_port), f"{username}@{proxy_host}"])
63
+
23
64
  app = typer.Typer()
24
65
 
25
66
 
@@ -63,6 +104,13 @@ async def launch( # noqa
63
104
  compliance_soc2: Annotated[
64
105
  bool | None, typer.Option("--compliance-soc2", help="Only use SOC2 compliant machines")
65
106
  ] = None,
107
+ interactive: Annotated[
108
+ bool,
109
+ typer.Option(
110
+ "--interactive",
111
+ help="Hold the workload on boot so you can SSH in and run it manually.",
112
+ ),
113
+ ] = False,
66
114
  json: bool = False,
67
115
  ) -> None:
68
116
  """Launch a job on Trainwave using the current configuration."""
@@ -91,6 +139,8 @@ async def launch( # noqa
91
139
  }
92
140
  if compliance_soc2 is not None:
93
141
  conf["compliance_soc2"] = compliance_soc2
142
+ if interactive:
143
+ conf["interactive"] = True
94
144
 
95
145
  if conf["gpu_type"] != "" and conf["gpus"] == 0:
96
146
  conf["gpus"] = 1 # default to 1 gpu if gpu_type is set
@@ -145,10 +195,22 @@ async def launch( # noqa
145
195
  except Exception as e:
146
196
  traceback.print_exc()
147
197
  logger.error(f"An error occurred: {e}")
198
+ return
148
199
  finally:
149
200
  if tarball:
150
201
  tarball.close()
151
202
 
203
+ if interactive:
204
+ if not json:
205
+ typer.echo("\nInteractive mode: waiting for the instance to start...")
206
+ try:
207
+ running_job = await _wait_until_running(api_client, job.rid)
208
+ proxy = await api_client.get_ssh_proxy_info()
209
+ except (RuntimeError, ValueError) as e:
210
+ typer.echo(f"Error: {e}")
211
+ sys.exit(1)
212
+ _ssh_into_job(running_job, proxy.host, proxy.port)
213
+
152
214
 
153
215
  @app.command(name="list")
154
216
  @async_command
@@ -212,3 +274,76 @@ async def logs(
212
274
  ) -> None:
213
275
  """Get the logs of a job."""
214
276
  await stream_logs(job_id)
277
+
278
+
279
+ @app.command()
280
+ @async_command
281
+ @ensure_api_key
282
+ async def ssh(
283
+ job_id: Annotated[str, typer.Argument(help="Job ID or RID to SSH into")],
284
+ instance: Annotated[
285
+ str | None,
286
+ typer.Option(
287
+ help="Instance RID. Required only when the job has more than one running instance.",
288
+ ),
289
+ ] = None,
290
+ extra: Annotated[
291
+ list[str] | None,
292
+ typer.Argument(help="Extra arguments forwarded to ssh (e.g. a command to run)."),
293
+ ] = None,
294
+ ) -> None:
295
+ """Open an SSH session to the running instance of a job."""
296
+ api_client = Api(config.api_key, config.endpoint)
297
+ try:
298
+ job = await api_client.get_job(job_id)
299
+ except ValueError as e:
300
+ typer.echo(f"Error: {e}")
301
+ sys.exit(1)
302
+
303
+ if job.state != JobStatus.RUNNING:
304
+ typer.echo(
305
+ f"Job {job.rid} is in state {job.state.value}; SSH is only available while RUNNING."
306
+ )
307
+ sys.exit(1)
308
+
309
+ running = [i for i in job.instances if i.state == "RUNNING"]
310
+ if not running:
311
+ typer.echo(
312
+ f"Job {job.rid} has no running instance yet. Try again once it's up."
313
+ )
314
+ sys.exit(1)
315
+
316
+ if instance:
317
+ match = next((i for i in running if instance in (i.rid, i.id)), None)
318
+ if match is None:
319
+ typer.echo(f"Instance {instance} not found among running instances of {job.rid}.")
320
+ sys.exit(1)
321
+ target = match
322
+ elif len(running) > 1:
323
+ rids = ", ".join(i.rid for i in running)
324
+ typer.echo(
325
+ f"Job {job.rid} has multiple running instances ({rids}). "
326
+ "Pick one with --instance <rid>."
327
+ )
328
+ sys.exit(1)
329
+ else:
330
+ target = running[0]
331
+
332
+ try:
333
+ proxy = await api_client.get_ssh_proxy_info()
334
+ except ValueError as e:
335
+ typer.echo(f"Error fetching SSH proxy info: {e}")
336
+ sys.exit(1)
337
+
338
+ username = f"{job.rid}-{target.rid}"
339
+ typer.echo(f"Connecting to {username}@{proxy.host}:{proxy.port}...")
340
+
341
+ argv = [
342
+ "ssh",
343
+ "-p",
344
+ str(proxy.port),
345
+ f"{username}@{proxy.host}",
346
+ ]
347
+ if extra:
348
+ argv.extend(extra)
349
+ os.execvp("ssh", argv)
@@ -0,0 +1,112 @@
1
+ import socket
2
+ import sys
3
+ from datetime import datetime, timezone
4
+ from pathlib import Path
5
+ from typing import Annotated
6
+
7
+ import human_readable
8
+ import typer
9
+ from tabulate import tabulate
10
+
11
+ from trainwave_cli.api import Api
12
+ from trainwave_cli.config.config import config
13
+ from trainwave_cli.utils import async_command, ensure_api_key
14
+
15
+ app = typer.Typer()
16
+
17
+ _DEFAULT_KEY_CANDIDATES = (
18
+ "id_ed25519.pub",
19
+ "id_ecdsa.pub",
20
+ "id_rsa.pub",
21
+ "id_dsa.pub",
22
+ )
23
+
24
+
25
+ def _autofind_public_key() -> Path | None:
26
+ ssh_dir = Path.home() / ".ssh"
27
+ for candidate in _DEFAULT_KEY_CANDIDATES:
28
+ path = ssh_dir / candidate
29
+ if path.is_file():
30
+ return path
31
+ return None
32
+
33
+
34
+ @app.command(name="list")
35
+ @async_command
36
+ @ensure_api_key
37
+ async def list_keys() -> None:
38
+ """List SSH keys registered on your account."""
39
+ api_client = Api(config.api_key, config.endpoint)
40
+ keys = await api_client.list_ssh_keys()
41
+ if not keys:
42
+ typer.echo("No SSH keys registered. Add one with `wave ssh-keys add`.")
43
+ return
44
+ headers = ["ID", "NAME", "TYPE", "FINGERPRINT", "ADDED"]
45
+ table = [
46
+ [
47
+ k.rid,
48
+ k.name,
49
+ k.key_type,
50
+ f"SHA256:{k.fingerprint_sha256}",
51
+ human_readable.date_time(datetime.now(timezone.utc) - k.created_at),
52
+ ]
53
+ for k in keys
54
+ ]
55
+ typer.echo(tabulate(table, headers=headers, tablefmt="simple"))
56
+
57
+
58
+ @app.command()
59
+ @async_command
60
+ @ensure_api_key
61
+ async def add(
62
+ path: Annotated[
63
+ Path | None,
64
+ typer.Argument(
65
+ help="Path to a .pub file. If omitted, common keys in ~/.ssh are auto-detected.",
66
+ ),
67
+ ] = None,
68
+ name: Annotated[
69
+ str | None,
70
+ typer.Option(help="Label for the key. Defaults to '<hostname>:<filename>'."),
71
+ ] = None,
72
+ ) -> None:
73
+ """Register an SSH public key on your account."""
74
+ if path is None:
75
+ path = _autofind_public_key()
76
+ if path is None:
77
+ typer.echo(
78
+ "No SSH public key found in ~/.ssh. Generate one with "
79
+ "`ssh-keygen -t ed25519` or pass the path explicitly."
80
+ )
81
+ sys.exit(1)
82
+ typer.echo(f"Using {path}")
83
+
84
+ if not path.is_file():
85
+ typer.echo(f"File not found: {path}")
86
+ sys.exit(1)
87
+
88
+ public_key = path.read_text().strip()
89
+ if not public_key:
90
+ typer.echo(f"File is empty: {path}")
91
+ sys.exit(1)
92
+
93
+ label = name or f"{socket.gethostname()}:{path.name}"
94
+ api_client = Api(config.api_key, config.endpoint)
95
+ try:
96
+ key = await api_client.add_ssh_key(label, public_key)
97
+ except ValueError as e:
98
+ typer.echo(f"Error: {e}")
99
+ sys.exit(1)
100
+ typer.echo(f"Added SSH key {key.rid} ({key.name}) -> SHA256:{key.fingerprint_sha256}")
101
+
102
+
103
+ @app.command()
104
+ @async_command
105
+ @ensure_api_key
106
+ async def remove(
107
+ key_id: Annotated[str, typer.Argument(help="ID or RID of the key to remove")],
108
+ ) -> None:
109
+ """Remove an SSH key from your account."""
110
+ api_client = Api(config.api_key, config.endpoint)
111
+ await api_client.remove_ssh_key(key_id)
112
+ typer.echo(f"Removed SSH key {key_id}")
@@ -4,13 +4,14 @@ import sys
4
4
  import typer
5
5
  from loguru import logger
6
6
 
7
- from trainwave_cli.cli import auth, jobs, secrets, setup
7
+ from trainwave_cli.cli import auth, jobs, secrets, setup, ssh_keys
8
8
 
9
9
  app = typer.Typer()
10
10
  app.add_typer(jobs.app, name="jobs", help="Manage training jobs")
11
11
  app.add_typer(auth.app, name="auth", help="Authenticate with Trainwave")
12
12
  app.add_typer(setup.app, name="config")
13
13
  app.add_typer(secrets.app, name="secrets", help="Manage job secrets")
14
+ app.add_typer(ssh_keys.app, name="ssh-keys", help="Manage SSH keys for interactive jobs")
14
15
 
15
16
 
16
17
  def get_package_name() -> str:
@@ -53,7 +53,7 @@ def ensure_api_key(f):
53
53
  def wrapper(*args, **kwargs):
54
54
  if config.api_key in {"", None}:
55
55
  typer.echo(
56
- "No access token found. Please run `trainwave auth login` to login to your account."
56
+ "No access token found. Please run `wave auth login` to login to your account."
57
57
  )
58
58
  raise typer.Exit(1)
59
59
  return f(*args, **kwargs)
@@ -1438,7 +1438,7 @@ wheels = [
1438
1438
 
1439
1439
  [[package]]
1440
1440
  name = "trainwave-cli"
1441
- version = "0.3.1"
1441
+ version = "0.3.3"
1442
1442
  source = { editable = "." }
1443
1443
  dependencies = [
1444
1444
  { name = "aiofiles" },
@@ -1,4 +0,0 @@
1
- #!/bin/bash
2
-
3
- echo "Starting train"
4
- python train.py
File without changes
File without changes
File without changes
File without changes