s-ttp commited on
Commit
a2cc695
·
verified ·
1 Parent(s): d6a28c7

Upload folder using huggingface_hub

Browse files
Files changed (3) hide show
  1. README.md +5 -0
  2. app.py +13 -0
  3. services/watchdog.py +145 -0
README.md CHANGED
@@ -63,6 +63,11 @@ standing margin balance. Sells are placed first and **waited for** before buys g
63
  a discussion on this Space, which HF notifies you about. It doubles as the keep-alive: free Spaces
64
  sleep after 48 h idle, and the weekday-only rebalance ping left it asleep every weekend.
65
  All schedules (refresh, rebalance, supervisor, shadow book) are HF Jobs. See the Refinery README.
 
 
 
 
 
66
  - **Restarts are safe.** All fund state lives in Alpaca. The `data/` risk-screen cache is
67
  ephemeral inside the container — a restart just recomputes it (one LLM call).
68
  - **Public by design.** The dashboard, holdings and dry-run plan are world-readable (it's a paper
 
63
  a discussion on this Space, which HF notifies you about. It doubles as the keep-alive: free Spaces
64
  sleep after 48 h idle, and the weekday-only rebalance ping left it asleep every weekend.
65
  All schedules (refresh, rebalance, supervisor, shadow book) are HF Jobs. See the Refinery README.
66
+ - **Jobs watchdog**: `services/watchdog.py` runs inside this Space (all the schedules are HF Jobs, so they can't
67
+ watch themselves). Every 6 h it resumes any of the fund's suspended schedules (`task` = supervisor, rebalance,
68
+ refresh-weekly, refresh-monthly), flags missing ones and a bundle older than 10 days, and opens a discussion for each.
69
+ Status: `GET /api/watchdog`. Needs the Space secret `HF_TOKEN` (write). **To pause the Jobs on purpose, set the
70
+ Space variable `JOBS_WATCHDOG=off` first**, or they'll be resumed within 6 h.
71
  - **Restarts are safe.** All fund state lives in Alpaca. The `data/` risk-screen cache is
72
  ephemeral inside the container — a restart just recomputes it (one LLM call).
73
  - **Public by design.** The dashboard, holdings and dry-run plan are world-readable (it's a paper
app.py CHANGED
@@ -21,6 +21,19 @@ import book
21
  app = FastAPI(title="Slipstream")
22
 
23
 
 
 
 
 
 
 
 
 
 
 
 
 
 
24
  @app.get("/api/health")
25
  def health():
26
  return {"fund": "Slipstream",
 
21
  app = FastAPI(title="Slipstream")
22
 
23
 
24
+ @app.on_event("startup")
25
+ def _start_watchdog():
26
+ from services import watchdog
27
+ watchdog.start()
28
+
29
+
30
+ @app.get("/api/watchdog")
31
+ def api_watchdog():
32
+ """Jobs watchdog status: last check, anything resumed, bundle age (see services/watchdog.py)."""
33
+ from services import watchdog
34
+ return watchdog.STATE
35
+
36
+
37
  @app.get("/api/health")
38
  def health():
39
  return {"fund": "Slipstream",
services/watchdog.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Jobs watchdog — keeps the fund's Hugging Face scheduled Jobs running.
2
+
3
+ Every scheduled task (refresh, rebalance, supervisor, shadow book) is an HF Job, so when the
4
+ account's Jobs get suspended (2026-11-09: all of them, silently, for 16 days) the supervisor that
5
+ would raise the alarm is suspended too. This thread runs inside the always-on Slipstream Space
6
+ instead. Every WATCHDOG_INTERVAL_H hours it:
7
+ 1. lists the account's scheduled Jobs and RESUMES any of the fund's that are suspended,
8
+ 2. checks that each expected schedule exists,
9
+ 3. checks the data bundle is fresh (≤ BUNDLE_MAX_AGE_D days),
10
+ and opens a discussion on this Space for anything it did or found (HF notifies the owner).
11
+
12
+ The Space stays awake: the daily supervisor Job pings it, and the check interval (6 h) is far
13
+ shorter than HF's 48 h idle sleep, so a suspension is caught within hours, before the Space can sleep.
14
+
15
+ Needs the Space secret HF_TOKEN (write; fine-grained: Jobs + discussions on this Space).
16
+ To pause the fund's Jobs ON PURPOSE, set the Space variable JOBS_WATCHDOG=off first, or the
17
+ watchdog will resume them.
18
+ """
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import threading
24
+ import time
25
+ from datetime import datetime, timezone
26
+
27
+ import requests
28
+
29
+ import config
30
+
31
+ HF = "https://huggingface.co"
32
+ TOKEN = os.getenv("HF_TOKEN", "")
33
+ NAMESPACE = os.getenv("JOBS_NAMESPACE", "s-ttp")
34
+ SPACE = os.getenv("SPACE_ID", "s-ttp/slipstream")
35
+ ENABLED = os.getenv("JOBS_WATCHDOG", "on").lower() not in ("off", "0", "false")
36
+ INTERVAL_H = float(os.getenv("WATCHDOG_INTERVAL_H", "6"))
37
+ BUNDLE_MAX_AGE_D = int(os.getenv("WATCHDOG_BUNDLE_MAX_AGE_D", "10"))
38
+ WATCHED = ("supervisor", "rebalance", "refresh-weekly", "refresh-monthly") # the `task` labels
39
+ REALERT_H = 72 # repeat an unchanged finding at most every 3 days
40
+
41
+ STATE: dict = {"enabled": ENABLED and bool(TOKEN), "last_check": None, "last_result": None, "resumed": []}
42
+ _alerted: dict[str, float] = {}
43
+
44
+
45
+ def _h() -> dict:
46
+ return {"Authorization": f"Bearer {TOKEN}"}
47
+
48
+
49
+ def _alert(key: str, title: str, body: str) -> None:
50
+ now = time.time()
51
+ if now - _alerted.get(key, 0) < REALERT_H * 3600:
52
+ return
53
+ try:
54
+ r = requests.post(f"{HF}/api/spaces/{SPACE}/discussions", headers=_h(), timeout=30,
55
+ json={"title": title[:200], "description": body, "pullRequest": False})
56
+ r.raise_for_status()
57
+ _alerted[key] = now
58
+ except Exception as e: # noqa: BLE001 — alerting must never crash the app
59
+ print(f"[watchdog] could not open discussion: {type(e).__name__}", flush=True)
60
+
61
+
62
+ def _bundle_age_days() -> int | None:
63
+ try:
64
+ meta = json.loads((config.DATA_DIR / "meta.json").read_text())
65
+ gen = datetime.strptime(meta["generated_at"], "%Y-%m-%d %H:%M UTC").replace(tzinfo=timezone.utc)
66
+ return (datetime.now(timezone.utc) - gen).days
67
+ except Exception: # noqa: BLE001
68
+ return None
69
+
70
+
71
+ def check() -> dict:
72
+ out = {"at": datetime.now(timezone.utc).isoformat(timespec="seconds"), "resumed": [], "missing": [],
73
+ "failed": [], "bundle_age_days": None}
74
+ r = requests.get(f"{HF}/api/scheduled-jobs/{NAMESPACE}", headers=_h(), timeout=30)
75
+ r.raise_for_status()
76
+ jobs = {}
77
+ for sj in r.json():
78
+ task = ((sj.get("jobSpec") or {}).get("labels") or {}).get("task")
79
+ if task in WATCHED:
80
+ jobs[task] = sj
81
+ out["missing"] = [t for t in WATCHED if t not in jobs]
82
+ for task, sj in jobs.items():
83
+ if sj.get("suspend"):
84
+ try:
85
+ requests.post(f"{HF}/api/scheduled-jobs/{NAMESPACE}/{sj['id']}/resume",
86
+ headers=_h(), timeout=30).raise_for_status()
87
+ out["resumed"].append(task)
88
+ except Exception as e: # noqa: BLE001
89
+ out["failed"].append(f"{task}: {type(e).__name__}")
90
+ out["bundle_age_days"] = _bundle_age_days()
91
+
92
+ if out["resumed"]:
93
+ _alert("resumed:" + ",".join(sorted(out["resumed"])) + out["at"][:10],
94
+ f"Watchdog resumed suspended Jobs: {', '.join(out['resumed'])}",
95
+ "The Slipstream watchdog found these scheduled Jobs **suspended** and resumed them. "
96
+ "HF runs each one's missed job immediately; the rebalance is guarded (once a month, "
97
+ "market hours only), so a catch-up run cannot double-trade.\n\n"
98
+ "If the whole account's Jobs were suspended, check the credit balance at "
99
+ "https://huggingface.co/settings/billing. To pause the Jobs on purpose, set the Space "
100
+ "variable `JOBS_WATCHDOG=off` first.")
101
+ if out["failed"]:
102
+ _alert("failed", "Watchdog could not resume Jobs", "Resume failed for: " + "; ".join(out["failed"])
103
+ + "\n\nCheck https://huggingface.co/settings/billing and `hf jobs scheduled ls`.")
104
+ if out["missing"]:
105
+ _alert("missing", "Watchdog: fund schedules missing",
106
+ f"No scheduled Job labelled task={', '.join(out['missing'])}. See the Refinery README for the commands.")
107
+ age = out["bundle_age_days"]
108
+ if age is not None and age > BUNDLE_MAX_AGE_D:
109
+ _alert("stale", f"Watchdog: data bundle is {age} days old",
110
+ f"The signals bundle was last refreshed {age} days ago (limit {BUNDLE_MAX_AGE_D}). "
111
+ "Check the latest refresh Job's logs: `hf jobs ls -a`.")
112
+ return out
113
+
114
+
115
+ def _token_role() -> str:
116
+ """The token's permission level (never the token): 'write', 'read' or 'fineGrained'."""
117
+ try:
118
+ r = requests.get(f"{HF}/api/whoami-v2", headers=_h(), timeout=30)
119
+ r.raise_for_status()
120
+ return ((r.json().get("auth") or {}).get("accessToken") or {}).get("role", "?")
121
+ except Exception as e: # noqa: BLE001
122
+ return f"unknown ({type(e).__name__})"
123
+
124
+
125
+ def _loop() -> None:
126
+ time.sleep(300) # let the app finish starting
127
+ STATE["token_role"] = _token_role()
128
+ if STATE["token_role"] == "read":
129
+ print("[watchdog] HF_TOKEN is read-only — it can detect but not resume Jobs or open alerts", flush=True)
130
+ while True:
131
+ try:
132
+ STATE["last_result"] = check()
133
+ STATE["resumed"] = (STATE["resumed"] + STATE["last_result"]["resumed"])[-20:]
134
+ except Exception as e: # noqa: BLE001
135
+ STATE["last_result"] = {"error": f"{type(e).__name__}: {str(e)[:200]}"}
136
+ STATE["last_check"] = datetime.now(timezone.utc).isoformat(timespec="seconds")
137
+ print(f"[watchdog] {STATE['last_result']}", flush=True)
138
+ time.sleep(INTERVAL_H * 3600)
139
+
140
+
141
+ def start() -> None:
142
+ if not STATE["enabled"]:
143
+ print(f"[watchdog] disabled (JOBS_WATCHDOG={'on' if ENABLED else 'off'}, HF_TOKEN {'set' if TOKEN else 'missing'})", flush=True)
144
+ return
145
+ threading.Thread(target=_loop, name="jobs-watchdog", daemon=True).start()