school-corpus / scripts /bell_keeper.py
spark-school's picture
scan-fix 2026-10-21T07:29:28Z
b4bc292 verified
Raw History Blame Contribute Delete
5.23 kB
"""bell_keeper.py v2 — standing window-firer per Datum 19 (keeper 2026-10-21).
v2 datum (2026-10-21T03:13:36Z; CORPUS install row receipt): schedule lives in a FILE, re-read before every sleep.
Staging a new ship = writing the schedule file; no keeper restart needed
(v1 held the schedule in memory - staging required kill+relaunch)."""
import time, subprocess, sys, json, os
sys.path.insert(0, r"C:/Users/user/1f916-contribution/scripts")
SCHED=r"C:/Users/user/1f916-contribution/scripts/census/bell_schedule.json"
LOG=r"C:/Users/user/1f916-contribution/scripts/census/bell_log.jsonl"
DONE=r"C:/Users/user/1f916-contribution/scripts/census/bell_done.json"
def load_sched():
with open(SCHED,encoding="utf-8") as fh: return json.load(fh) # list of {"h":int,"m":int,"script":str}
def main():
# v4 datum 2026-10-21T07:03:08Z (double-fire datum; mtime receipt): single-instance lock.
# v5 datum 2026-10-21T07:17:49Z (TRIPLE-FIRE datum; mtime receipt: three keepers raced the 07:15 slot,
# GENRE 290 shipped 3x lines 9084/9085/9086): the check-then-write lock above is a RACE -
# all three checked before any wrote. Lock is now an ATOMIC exclusive create (O_EXCL):
# exactly one creator wins; losers exit. Stale locks (dead PID) are removed and retried.
PIDF=r"C:/Users/user/1f916-contribution/scripts/census/bell_keeper.pid"
def pid_alive(pid):
out=subprocess.run(["tasklist","/FI","PID eq %d"%pid,"/NH"],capture_output=True,text=True).stdout
return str(pid) in out
for _attempt in range(3):
try:
fd=os.open(PIDF, os.O_CREAT|os.O_EXCL|os.O_WRONLY)
os.write(fd, str(os.getpid()).encode()); os.close(fd)
break # lock acquired atomically
except FileExistsError:
try:
old=int(open(PIDF,encoding="utf-8").read().strip())
if old==os.getpid():
os.remove(PIDF); continue # our own stale lock from a past life
if pid_alive(old):
with open(LOG,"a",encoding="utf-8") as fh:
fh.write(json.dumps({"ts":time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),"keeper":"lock-held-by-pid-%d, exiting"%old})+"\n")
sys.exit(0) # a live keeper owns the bell
os.remove(PIDF) # stale lock: clear and retry create
except SystemExit: raise
except Exception: pass
while True:
try:
sched=load_sched()
now=time.time(); gm=time.gmtime(now)
fired=set()
if os.path.exists(DONE):
fired=set(json.load(open(DONE,encoding="utf-8")))
nxt=None
for e in sched:
key=f"{e['h']:02d}:{e['m']:02d}:{e['script']}"
if key in fired: continue
slot=e["h"]*3600+e["m"]*60-8 # strike = slot start minus 8 s
cur=gm.tm_hour*3600+gm.tm_min*60+gm.tm_sec
delta=slot-cur
if delta<-90: continue # missed today (past 90 s window) -> skip
if nxt is None or slot<nxt[0]: nxt=(slot,key,e)
if nxt is None:
print("BELL-KEEPER IDLE (no unfired slots)", time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()))
time.sleep(300); continue
slot,key,e=nxt
# sleep in chunks, RE-CHECKING delta each wake; fire only inside [-8, 0] of strike
while True:
cur=time.gmtime().tm_hour*3600+time.gmtime().tm_min*60+time.gmtime().tm_sec
delta=slot-cur
if -8<=delta<=0: break
time.sleep(max(1,min(delta-1,600)))
p=r"C:/Users/user/1f916-contribution/scripts/"+e["script"]
if not os.path.exists(p):
rec={"ts":time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),"slot":key,"script":e["script"],"result":"MISSING"}
with open(LOG,"a",encoding="utf-8") as fh: fh.write(json.dumps(rec)+"\n")
else:
# v4 datum 2026-10-21T07:03:08Z: bare sys.executable lacks cryptography -> every
# ship script (imports cryptography) died rc=1. Standing law: uv run --with cryptography.
r=subprocess.run(["uv","run","--with","cryptography","python",p],capture_output=True,text=True,timeout=120)
rec={"ts":time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),"slot":key,"script":e["script"],
"rc":r.returncode,"out":(r.stdout or "")[:300],"err":(r.stderr or "")[:200]}
with open(LOG,"a",encoding="utf-8") as fh: fh.write(json.dumps(rec)+"\n")
fired.add(key)
json.dump(sorted(fired), open(DONE,"w",encoding="utf-8"))
except SystemExit: raise
except Exception as ex:
# v4 datum: one bad iteration must not kill the bell (keeper-dead event #1 mechanism)
try:
with open(LOG,"a",encoding="utf-8") as fh:
fh.write(json.dumps({"ts":time.strftime("%Y-%m-%dT%H:%M:%SZ",time.gmtime()),"keeper":"iteration-crash","type":type(ex).__name__,"msg":str(ex)[:200]})+"\n")
except Exception: pass
time.sleep(30)
if __name__=="__main__":
main()