Lara Monteagudo Tubau commited on
Commit Β·
7070b94
1
Parent(s): e612a97
fix: circuit breaker resilience, Drive save on every persist, remove local upload
Browse filesFiles changed (2)
- app.py+21-25
- llm_client.py+32-8
48 unmodified lines495051525354551026 unmodified lines10821083108410851086108710881089109010911092109310941095109610971098511 unmodified lines161016111612161316141615232 unmodified lines1848184918501851185218531500 unmodified lines33543355335633573358335933603361336233633364336533663367336833693370337133723373592 unmodified lines39663967396839693970397139723973397439753976397748 unmodified linesrender_pipeline_stats_html,PipelineStats,)from llm_client import circuit_state, compute_timeoutfrom sequential_analysis import (load_and_analyse,render_transition_matrix_html,1026 unmodified linesdef _persist(state: dict) -> None:try:d = _session_dir(state)d.mkdir(parents=True, exist_ok=True)skip = {"turns", "kappa_report"}(d / "app_state.json").write_text(json.dumps({k: v for k, v in state.items() if k not in skip},indent=2, ensure_ascii=False),encoding="utf-8",)except Exception:passdef _seconds_to_hms(s: float) -> str:511 unmodified linesTriggered by 'Continue to Sections' button on screener page.Outputs: state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES"""turns = state.get("turns", [])if not turns:raise gr.Error("No transcript loaded β process a file first.")232 unmodified lines# ββ Agent 1a β parallel boundary detection βββββββββββββββββββββββββββββββββββdef fn_run_all_boundaries(state: dict):sections = state.get("sections", [])if not sections:raise gr.Error("Confirm sections first.")1500 unmodified linesprocess_status = gr.HTML()process_log = gr.HTML()# ββ Option B: Local file ββββββββββββββββββββββββββββββββββββββββββgr.HTML('<div style="border-top:1px solid var(--cc-border);margin:20px 0 12px"></div>''<div style="font-weight:700;color:var(--cc-ink);margin-bottom:4px">Option B β Local file</div>''<div style="font-size:0.82em;color:var(--cc-muted);margin-bottom:10px">''Upload a .txt, .vtt or .csv transcript from your computer.</div>')local_file_upload = gr.File(label="Transcript file",file_types=[".txt", ".vtt", ".csv"],)process_local_btn = gr.Button("Load Local File β", variant="primary")local_process_status = gr.HTML()back_setup_btn = gr.Button("β Back to Home", size="sm")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ592 unmodified linesoutputs=PARSE_OUTPUTS,).then(fn=lambda: gr.update(visible=True), outputs=[pipeline_bar_html])# Setup: Local file β Phase 1 (parse + screen)process_local_btn.click(fn=fn_process_local,inputs=[local_file_upload, researcher_id_box, state],outputs=PARSE_OUTPUTS,).then(fn=lambda: gr.update(visible=True), outputs=[pipeline_bar_html])# Screener: manual re-run (only shown when auto-run failed)run_screener_btn.click(48 unmodified lines495051525354551026 unmodified lines1082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112511 unmodified lines1624162516261627162816291630232 unmodified lines18631864186518661867186818691500 unmodified lines337033713372337333743375592 unmodified lines39683969397039713972397348 unmodified linesrender_pipeline_stats_html,PipelineStats,)from llm_client import circuit_state, compute_timeout, reset_circuitfrom sequential_analysis import (load_and_analyse,render_transition_matrix_html,1026 unmodified linesdef _persist(state: dict) -> None:"""Save state to local disk AND Drive (if Drive is configured)."""skip = {"turns", "kappa_report"}slim = {k: v for k, v in state.items() if k not in skip}# Local save (fast, always)try:d = _session_dir(state)d.mkdir(parents=True, exist_ok=True)(d / "app_state.json").write_text(json.dumps(slim, indent=2, ensure_ascii=False), encoding="utf-8")except Exception:pass# Drive save (async-ish β run in background thread so UI isn't blocked)rid = state.get("researcher_id", "")sid = state.get("session_id", "")if rid and sid:def _drive_save():try:svc = get_drive_service(rid)if svc:write_session_to_drive(svc, rid, sid, slim)except Exception as e:print(f"[Drive] Background save failed: {e}", file=_sys.stderr)import threading as _threading_threading.Thread(target=_drive_save, daemon=True).start()def _seconds_to_hms(s: float) -> str:511 unmodified linesTriggered by 'Continue to Sections' button on screener page.Outputs: state, pipeline_bar_html, sections_display_html, sections_labels_box, *ALL_PAGES"""reset_circuit() # fresh start β don't carry over failures from a previous runturns = state.get("turns", [])if not turns:raise gr.Error("No transcript loaded β process a file first.")232 unmodified lines# ββ Agent 1a β parallel boundary detection βββββββββββββββββββββββββββββββββββdef fn_run_all_boundaries(state: dict):reset_circuit() # fresh start for this pipeline stepsections = state.get("sections", [])if not sections:raise gr.Error("Confirm sections first.")1500 unmodified linesprocess_status = gr.HTML()process_log = gr.HTML()back_setup_btn = gr.Button("β Back to Home", size="sm")# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ592 unmodified linesoutputs=PARSE_OUTPUTS,).then(fn=lambda: gr.update(visible=True), outputs=[pipeline_bar_html])# Screener: manual re-run (only shown when auto-run failed)run_screener_btn.click(
48 unmodified lines495051525354555657585960616258 unmodified lines1211221231241251261271281 unmodified line130131132133134135121 unmodified lines25725825926026126226317 unmodified lines28128228348 unmodified lines_CHARS_PER_SEC = 800 # empirical chars-per-second at Qwen 72B on HF inference# Circuit breaker_CB_FAILURE_THRESHOLD = 4 # consecutive failures before opening_CB_RESET_SECS = 120 # seconds before trying again# Retry policy_MAX_RETRIES = 3_RETRY_BASE_SECS = 4 # first backoff; doubles each attempt + jitter_TRANSIENT_CODES = ("504", "503", "502", "429", "timeout", "Timeout")# ---------------------------------------------------------------------------58 unmodified linesprint(f"[LLM] Circuit closed β service recovered.")self._state = "CLOSED"def record_failure(self):with self._lock:self._failures += 1if self._failures >= _CB_FAILURE_THRESHOLD and self._state != "OPEN":self._state = "OPEN"1 unmodified lineprint(f"[LLM] Circuit OPENED after {self._failures} consecutive failures. "f"Will retry in {_CB_RESET_SECS}s.")@propertydef state(self) -> str:return self._state121 unmodified linestime.sleep(wait)continue_circuit_breaker.record_failure()wall = round(time.perf_counter() - t0, 2)stats = LLMCallStats(model=MODEL, temperature=TEMPERATURE,17 unmodified linesdef circuit_state() -> str:"""Expose circuit breaker state for the UI transparency panel."""return _circuit_breaker.state48 unmodified lines495051525354555657585960616263646566676858 unmodified lines1271281291301311321331341351361371381 unmodified line140141142143144145146147148149150151152153121 unmodified lines27527627727827928028128217 unmodified lines30030130230330430530630748 unmodified lines_CHARS_PER_SEC = 800 # empirical chars-per-second at Qwen 72B on HF inference# Circuit breaker# Threshold raised to 8 so parallel section runs (up to 6 sections Γ 1 retry)# don't trip the breaker due to a single burst of transient rate-limit errors._CB_FAILURE_THRESHOLD = 8_CB_RESET_SECS = 90 # seconds before trying again# Retry policy β more retries with longer first backoff to survive HF rate limits_MAX_RETRIES = 4_RETRY_BASE_SECS = 8 # first backoff 8s β 16s β 32s (+ jitter)# Transient codes that trigger backoff (not circuit failure)# 429 = rate limit β always retry with backoff, never count as circuit failure_TRANSIENT_CODES = ("504", "503", "502", "429", "timeout", "Timeout","rate limit", "Rate limit", "overloaded")_RATE_LIMIT_CODES = ("429", "rate limit", "Rate limit")# ---------------------------------------------------------------------------58 unmodified linesprint(f"[LLM] Circuit closed β service recovered.")self._state = "CLOSED"def record_failure(self, is_rate_limit: bool = False):with self._lock:# Rate-limit errors are expected under load β don't count toward circuit openingif is_rate_limit:print(f"[LLM] Rate-limit hit β not counting toward circuit breaker.")returnself._failures += 1if self._failures >= _CB_FAILURE_THRESHOLD and self._state != "OPEN":self._state = "OPEN"1 unmodified lineprint(f"[LLM] Circuit OPENED after {self._failures} consecutive failures. "f"Will retry in {_CB_RESET_SECS}s.")def reset(self):"""Reset the circuit breaker β call at the start of each user-initiated pipeline run."""with self._lock:self._failures = 0self._state = "CLOSED"self._opened_at = Noneprint("[LLM] Circuit breaker reset for new run.")@propertydef state(self) -> str:return self._state121 unmodified linestime.sleep(wait)continueis_rate_limit = any(c in last_error for c in _RATE_LIMIT_CODES)_circuit_breaker.record_failure(is_rate_limit=is_rate_limit)wall = round(time.perf_counter() - t0, 2)stats = LLMCallStats(model=MODEL, temperature=TEMPERATURE,17 unmodified linesdef circuit_state() -> str:"""Expose circuit breaker state for the UI transparency panel."""return _circuit_breaker.statedef reset_circuit() -> None:"""Reset circuit breaker before a new user-initiated pipeline run."""_circuit_breaker.reset()
app.py+21-25
llm_client.py+32-8