"""Record local stock runs and compute metrics by run identity."""
import argparse
from collections import Counter, defaultdict
from contextlib import contextmanager
import csv
from datetime import datetime, timezone
import json
from pathlib import Path
import sys
from time import perf_counter_ns
from uuid import uuid4
EVENTS={"run_start","step_start","step_finish","run_finish"}
class Trace:
def __init__(self, directory):
self.run=uuid4().hex
self.directory=directory
self.started=perf_counter_ns()
self.sequence=0
self.channel=directory/(self.run+".jsonl")
def event(self, name, level="info", **details):
self.sequence+=1
row={"run":self.run,"event":name,"level":level,"sequence":self.sequence,
"ts":datetime.now(timezone.utc).isoformat(),**details}
serialized=json.dumps(row,ensure_ascii=False,separators=(",",":"))
with self.channel.open("a",encoding="utf-8",newline="\n") as log:
log.write(serialized+"\n")
print(serialized,file=sys.stderr)
@contextmanager
def step(self,name):
self.event("step_start",step=name)
started=perf_counter_ns()
try:
yield
except (OSError,ValueError,csv.Error):
self.event("step_finish","error",step=name,status="failed",elapsed_ns=perf_counter_ns()-started)
raise
else:
self.event("step_finish",step=name,status="ok",elapsed_ns=perf_counter_ns()-started)
def run_stock(source,directory):
directory.mkdir(parents=True,exist_ok=True)
trace=Trace(directory)
trace.event("run_start")
try:
with trace.step("read"):
with source.open(encoding="utf-8",newline="") as file:
reader=csv.DictReader(file,strict=True)
if reader.fieldnames!=["zone","units"]:
raise ValueError("columns")
rows=list(reader)
with trace.step("normalize"):
values=[int(row["units"]) for row in rows if row["units"]]
with trace.step("total"):
total=sum(values)
except (OSError,ValueError,csv.Error) as error:
trace.event("run_finish","error",status="failed",code=type(error).__name__,
elapsed_ns=perf_counter_ns()-trace.started)
return 2,{"ok":False,"run":trace.run,"code":type(error).__name__}
trace.event("run_finish",status="ok",elapsed_ns=perf_counter_ns()-trace.started)
return 0,{"ok":True,"run":trace.run,"rows":len(rows),"units":total}
def parse_event(line):
event=json.loads(line)
if (not isinstance(event,dict) or not isinstance(event.get("run"),str) or
type(event.get("sequence")) is not int or event["sequence"]<1 or
event.get("event") not in EVENTS or event.get("level") not in ("info","warning","error") or
datetime.fromisoformat(event["ts"]).utcoffset() is None):
raise ValueError("event schema")
if event["event"].startswith("step") and not isinstance(event.get("step"),str):
raise ValueError("step")
if event["event"].endswith("finish") and (
type(event.get("elapsed_ns")) is not int or event["elapsed_ns"]<0 or event.get("status") not in ("ok","failed")):
raise ValueError("finish schema")
return event
def aggregate(directory):
by_run=defaultdict(dict)
invalid=set()
counts=Counter()
for log in directory.glob("*.jsonl"):
for line in log.read_bytes().splitlines():
if not line.strip():
continue
try:
event=parse_event(line)
except (ValueError,KeyError,TypeError):
counts["malformed"]+=1
continue
run=event["run"]
seq=event["sequence"]
original=by_run[run].setdefault(seq,event)
if original!=event:
invalid.add(run)
recent=[]
times=[]
traces={}
for run,group in by_run.items():
events=[group[key] for key in sorted(group)]
counts["error_events"]+=sum(item["level"]=="error" for item in events)
if run in invalid:
counts["conflict"]+=1
continue
starts=[e for e in events if e["event"]=="run_start"]
finishes=[e for e in events if e["event"]=="run_finish"]
if not starts:
counts["orphan"]+=1
continue
counts["started"]+=1
if len(starts)!=1 or len(finishes)>1 or events[0]!=starts[0] or (finishes and events[-1]!=finishes[0]):
counts["conflict"]+=1
continue
traces[run]=[{"step":e["step"],"status":e["status"],"elapsed_ns":e["elapsed_ns"]} for e in events if e["event"]=="step_finish"]
if not finishes:
counts["incomplete"]+=1
elif finishes[0]["status"]=="ok":
counts["success"]+=1
times.append(finishes[0]["elapsed_ns"])
else:
counts["failure"]+=1
recent.append({k:finishes[0].get(k) for k in ("ts","run","code")})
completed=counts["success"]+counts["failure"]
return {"metrics":{k:counts[k] for k in ("started","success","failure","incomplete","orphan","conflict",
"malformed","error_events")},"success_rate_among_completed":counts["success"]/completed if completed else None,
"average_success_ns":sum(times)/len(times) if times else None,
"recent_errors":sorted(recent,key=lambda item:datetime.fromisoformat(item["ts"]))[-5:],"traces":traces}
def main():
parser=argparse.ArgumentParser(description=__doc__)
commands=parser.add_subparsers(dest="command",required=True)
run=commands.add_parser("run")
run.add_argument("source",type=Path)
run.add_argument("log_dir",type=Path)
report=commands.add_parser("metrics")
report.add_argument("log_dir",type=Path)
args=parser.parse_args()
if args.command=="run":
code,result=run_stock(args.source,args.log_dir)
elif not args.log_dir.is_dir():
code,result=2,{"ok":False,"code":"MISSING_LOG_DIRECTORY"}
else:
code,result=0,aggregate(args.log_dir)
print(json.dumps(result,ensure_ascii=False))
return code
if __name__=="__main__":
raise SystemExit(main())
本例需在 Windows、Python 3.12。各实验所需工具和版本见下载包 README。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:Windows、Python 3.12。各实验所需工具和版本见下载包 README。
入口文件:projects/skills-monitor/observe_stock.py
本地运行步骤快速上手
- 点击上方“保存源码”保存为
observe_stock.py,或下载右侧课程工程包。 - 确认本地已准备 Windows、Python 3.12。各实验所需工具和版本见下载包 README。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联39章) · 含当前章节或实例 · mbskycom202612a331.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a343.zip