src.dackar.RCA.synthesis.rca_synthesizer_v31¶
Attributes¶
Classes¶
Minimal structured-generation interface expected by the synthesizer. |
|
Tunable configuration for |
|
Synthesizer aligned to richer TSKR-aware causality candidate structure. |
Functions¶
Module Contents¶
- class src.dackar.RCA.synthesis.rca_synthesizer_v31.LLMClient[source]¶
Bases:
ProtocolMinimal structured-generation interface expected by the synthesizer.
- generate_json(model, prompt, temperature=0.1)[source]¶
Generate a JSON object from a prompt.
- Parameters:
model (str) – Model identifier to invoke.
prompt (str) – Fully-rendered prompt string.
temperature (float) – Sampling temperature; the synthesizer passes a low default for determinism.
- Returns:
The parsed JSON object emitted by the model. Implementations must return a
dict(already JSON-decoded), not a raw string. A generation or decode failure should raise; the synthesizer catches the exception and falls back to deterministic template synthesis.- Return type:
- class src.dackar.RCA.synthesis.rca_synthesizer_v31.RCASynthesizerConfig[source]¶
Tunable configuration for
RuleValidatedRCASynthesizerV31.- max_synthesis_extra_review_candidates[source]¶
Additional lower-ranked candidates retained for review context beyond the prompt cap.
- min_evidence_per_candidate_in_prompt[source]¶
Minimum evidence snippets guaranteed per candidate when available.
- allow_fallback_template_fill[source]¶
When True, a failed or invalid LLM generation falls back to deterministic template synthesis instead of raising.
- class src.dackar.RCA.synthesis.rca_synthesizer_v31.RuleValidatedRCASynthesizerV31(llm_client, config=None)[source]¶
Synthesizer aligned to richer TSKR-aware causality candidate structure.
- Responsibilities:
select top candidates and evidence
build a constrained prompt
call LLM for structured JSON generation
normalize output into rca_card schema
validate minimum semantic requirements
fallback to deterministic template synthesis if needed
- Parameters:
llm_client (LLMClient)
config (Optional[RCASynthesizerConfig])
- synthesize(event, telemetry_summary, kg_context, tskr_patterns, causality_candidates, evidence_bundle, operational_context, pm_compliance, ishikawa_matrix, run_context, cmms_context=None, similar_event_list=None)[source]¶
Synthesize a validated RCA card from structured reasoning artifacts.
- Parameters:
event (JsonDict) – Target abnormal event. Must carry
event_id(orid); an optionalseverity(1–5) raises the minimum-evidence gate floor.telemetry_summary (JsonDict) – Telemetry anomaly summary for the event window.
kg_context (JsonDict) – Knowledge-graph neighbourhood (components, failure modes, barriers).
tskr_patterns (Optional[JsonDict]) – TSKR chain-position patterns, or None when unavailable.
causality_candidates (JsonDict) – Ranked candidate hypotheses under
candidates(each with scores, evidence posture, and optional epistemics digest).evidence_bundle (JsonDict) – Retrieved evidence snippets keyed for citation.
operational_context (Optional[JsonDict]) – Optional supporting artifacts folded into the card when present.
pm_compliance (Optional[JsonDict]) – Optional supporting artifacts folded into the card when present.
ishikawa_matrix (Optional[JsonDict]) – Optional supporting artifacts folded into the card when present.
cmms_context (Optional[JsonDict]) – Optional supporting artifacts folded into the card when present.
similar_event_list (Optional[JsonDict]) – Optional supporting artifacts folded into the card when present.
run_context (JsonDict) – Orchestrator run context (
run_id, optionalevent_id/asset_id).
- Returns:
An RCA card conforming to
schemas/rca_card.json. On LLM failure or invalid output a deterministic fallback card is returned instead (validation_status.fallback_used = True) rather than raising.validation_statusrecords schema/citation/evidence-gate outcomes andsynthesis_quality(deterministic | partial_llm | full_llm).- Return type:
- static _eliminating_gates_for(candidate)[source]¶
Gate(s)/posture(s) that removed a candidate from primary standing.
- Parameters:
candidate (JsonDict)
- Return type:
List[str]
- _build_gate_disposition(*, card, causality_candidates)[source]¶
F-4 — make the elimination-first semantics explicit and auditable.
Hard gates already run (after scoring) and set
primary_eligibility="blocked",ruleout, andprimary_block_reasonson candidates — the raw audit exists but is scattered, and an eliminated candidate keeps its (possibly high) composite_score. This consolidates the verdicts into one card block stating that a failed gate is dispositive regardless of score, and surfaces any high-scoring candidate that a gate eliminated so it cannot be silently outranked-then-ignored. Purely additive; no pipeline reordering, no ranking change.
- _build_causal_graph(*, card, event, causality_candidates)[source]¶
N-6 — assemble one inspectable, directed per-run causal graph.
Causal reasoning is otherwise spread across TSKR chain-position, the telemetry signal-DAG, common-cause/explain-away links, near-tie competition, and hard gates, so depth/direction/mechanism are each approximated separately and never fall out of a single model the analyst can contest. This consolidates those already-computed signals into one graph: nodes are the target event and the assessed candidates; directed edges commit a cause->effect ordering where the signals support it (chain_position vs the event, shared-cause explain-away), and undirected edges mark near-tie competition. Purely additive and ranking-neutral — it reflects the existing scores, making N-1/N-2/N-3 checkable by construction.
- static _build_score_interpretation()[source]¶
N-4 — honest semantics for
composite_score.The composite is a weighted blend of heuristic sub-scores with hand-set weights and relation priors; it is not calibrated against outcome frequencies, and any score confidence interval encodes data availability, not statistical uncertainty. Emitting this block prevents
composite_score = 0.72from being read as ‘72% likely the cause’. Constant, additive, and ranking-neutral.- Return type:
- _select_candidates(causality_candidates)[source]¶
Top-N by score plus any
review_requiredrows (SE review §6.7 H1 / NH11).
- _promote_initiator_over_consequence(ranked)[source]¶
Promote a near-tie initiating candidate ahead of a top consequence.
Conservative: only fires when the #1 candidate is a consequence and some initiating candidate scores within
_CHAIN_POSITION_PRIMARY_TIE_MARGINof it. A clearly-stronger consequence is left in place (and later flagged for analyst review by_apply_chain_position_review_flag).
- _apply_chain_position_review_flag(card, causality_candidates)[source]¶
WS2 Part A: flag when the primary hypothesis is a downstream consequence.
A consequence is a derivative effect, not the initiating cause. When the primary chain_position is consequence, surface an analyst attention flag and an uncertainty note pointing to the strongest upstream initiating candidate, so the analyst reviews whether the true primary cause is upstream. Depth labelling is intentionally left category-based (WS2 scope = Part A only).
- _apply_temporal_support_flag(card, causality_candidates)[source]¶
N-2: flag when the primary hypothesis’s temporal support is unestablished.
When no TSKR pattern matched the primary failure mode, its temporal sub-score is a co-occurrence proxy (anomalies merely co-present in the event window) — not established temporal precedence and not a propagation path. Surface this so an engineer does not read a proxy-derived temporal score as confirmed temporal causation (post-hoc/cum-hoc guard).
- _apply_signal_dag_position_flag(card, causality_candidates)[source]¶
P-5: surface the telemetry signal-DAG causal position of the primary hypothesis.
The signal-evidence builder classifies each candidate’s anomaly within the telemetry-propagation DAG (root / common-cause root / intermediate / convergence confluence) and records whether a root’s onset lead over its successor was actually established. That view was previously consumed only to zero convergence evidence. Here it is surfaced to the analyst in two honest, additive ways (no ranking or confidence change):
the primary sits at a convergence confluence — a downstream node where multiple propagation chains meet, i.e. a likely symptom rather than the initiator; or
the primary is a signal-DAG initiator whose onset lead was not established (co-temporal / OVERLAPS), so telemetry does not demonstrate it precedes the sequence it is claimed to initiate.
- _apply_common_cause_explain_away_flag(card, causality_candidates)[source]¶
N-3: flag when the primary hypothesis is a co-symptom of a suspected common cause.
The engine’s common-cause analysis identifies when several candidates converge on a shared dependency (common_cause_summary.suspected_common_cause), names the strongest shared-cause candidate (top_common_cause_candidate_id) and lists the remaining co-symptoms (explained_away_candidate_ids). A downstream symptom of a common cause is not itself the initiating root — if such a co-symptom is selected primary, surface an analyst flag pointing at the shared cause / shared dependency so the true common cause is reviewed. Additive (flag + uncertainty note); ranking is unchanged.
- _apply_data_limited_confidence_cap(card, causality_candidates)[source]¶
P-7: cap card confidence when the primary hypothesis is data-limited.
The engine already reduces a data-limited candidate’s quality multiplier and flags
data_limited_conclusionwithcritical_streams_below_floor, but that was previously only annotated (uncertainties/evidence-gaps) — the confidence label could still read high. §3.5/§7 require conservative bias under sparse data, so a data-limited primary must not carry a high confidence claim. Cap the primary and executive confidence at medium (downward-only; never raises) and add an analyst attention flag. Ranking is untouched.
- static _evidence_linked_candidate_id(row)[source]¶
- Parameters:
row (JsonDict)
- Return type:
Optional[str]
- static _authority_level_rank(authority_level)[source]¶
- Parameters:
authority_level (Any)
- Return type:
int
- _build_prompt(event, telemetry_summary, kg_context, tskr_patterns, causality_candidates, evidence_bundle, operational_context, pm_compliance, ishikawa_matrix, run_context, cmms_context=None)[source]¶
- Parameters:
event (JsonDict)
telemetry_summary (JsonDict)
kg_context (JsonDict)
tskr_patterns (Optional[JsonDict])
causality_candidates (List[JsonDict])
evidence_bundle (List[JsonDict])
operational_context (Optional[JsonDict])
pm_compliance (Optional[JsonDict])
ishikawa_matrix (Optional[JsonDict])
run_context (JsonDict)
cmms_context (Optional[JsonDict])
- Return type:
str
- _compact_cmms_context(cmms_context)[source]¶
Return a token-efficient summary of cmms_context for the prompt.
Only the most recent CR/WO records (up to 5 each) are included, with long_text stripped (long_text is already in Chroma for semantic retrieval — duplicating it in the prompt wastes tokens). The recurrence_summary and lookback window are always included.
- _normalize_llm_output(raw_output, rca_id, event, evidence_bundle, run_context, causality_candidates)[source]¶
- _inject_review_required_questions(analyst_review, *, causality_candidates, max_candidates=3)[source]¶
Ensure Stage F review_required candidates are visible to analysts in analyst_review.questions_to_resolve.
- static _build_evidence_excerpt_index(evidence_rows)[source]¶
Build a lookup index so card evidence rows can recover raw snippet excerpts.
- _resolve_evidence_excerpt(*, row, excerpt_index)[source]¶
Ensure evidence excerpt is source text when available.
- static minimum_score_for_severity(severity)[source]¶
Return the minimum composite score a primary must clear for a severity.
- Parameters:
severity – Event severity 1 (minor) … 5 (critical). Accepts int or numeric string; None or an unparseable value defaults to severity 3.
- Returns:
The severity floor from
_SEVERITY_SCORE_FLOORS(0.35 for any severity outside 1–5). Callers combine this withconfig.minimum_primary_scoreviamaxso the floor only ever tightens the gate.- Return type:
float
- _CRITICAL_SAFETY_KEYWORDS = ('reactor protection', 'reactor trip', 'trip logic', 'reactor shutdown', 'containment...[source]¶
- _HIGH_SAFETY_KEYWORDS = ('core cooling', 'emergency core cooling', 'emergency cooling', 'residual heat removal', 'decay...[source]¶
- classmethod _bump_priority(base, steps=1)[source]¶
- Parameters:
base (str)
steps (int)
- Return type:
str
- classmethod _contains_any_keyword(values, keywords)[source]¶
- Parameters:
values (List[str])
keywords (tuple)
- Return type:
bool
- classmethod _apply_safety_priority(current_priority, safety_ctx)[source]¶
- Parameters:
current_priority (str)
safety_ctx (JsonDict)
- Return type:
str
- classmethod _apply_barrier_priority(current_priority, barrier_ctx)[source]¶
- Parameters:
current_priority (str)
barrier_ctx (JsonDict)
- Return type:
str
- classmethod _apply_risk_priority(current_priority, risk_ctx)[source]¶
- Parameters:
current_priority (str)
risk_ctx (JsonDict)
- Return type:
str
- _fallback_decision_status_from_posture(*, evidence_summary, pattern_posture, passed_minimum_evidence_gate)[source]¶
- _fallback_attention_flags_from_posture(*, evidence_summary, pattern_posture, passed_minimum_evidence_gate)[source]¶
- _primary_recurrence_why_primary(candidate)[source]¶
- Parameters:
candidate (Optional[JsonDict])
- Return type:
List[str]
- _primary_recurrence_uncertainties(candidate)[source]¶
- Parameters:
candidate (Optional[JsonDict])
- Return type:
List[str]
- _recurrence_review_questions(candidate)[source]¶
- Parameters:
candidate (Optional[JsonDict])
- Return type:
List[str]
- _candidate_temporal_posture(candidate)[source]¶
- Parameters:
candidate (Optional[JsonDict])
- Return type:
str
- _candidate_evidence_posture(candidate)[source]¶
- Parameters:
candidate (Optional[JsonDict])
- Return type:
str
- _build_unresolved_gaps(*, primary_candidate, evidence_summary, pattern_posture, analyst_attention_flags, causal_depth_summary=None, sensitivity_any_change=False, novel_pattern_flag=False, similar_event_list=None)[source]¶
Deeper gap list — links depth layers, sensitivity table, novel patterns, and OE coverage.
- Parameters:
- Return type:
List[str]
- static _build_effectiveness_monitoring_plan(*, primary_candidate, recommended_actions)[source]¶
Depth-stratified monitoring plan.
Proximate → equipment-health indicator (recurrence / precursor anomaly) Contributing → process/procedure adherence indicator (PM compliance, WO closure) Root → programmatic/systemic indicator (fleet OE recurrence, AMP review)
- _build_prevention_analysis(*, card, causality_candidates, pm_compliance, telemetry_summary, event=None)[source]¶
F-3 — deterministic ‘why was it not prevented?’ defense-in-depth assessment.
The metamodel requires the RCA card to state which barriers failed, which held, and why (a first-class output). The existing structural
barrier_analysisonly maps which safety functions a scored candidate impacts; it does not explain why the failure was not prevented. This assesses three defense-in-depth layers for the primary cause from data already on hand — no new inputs, no speculation:preventive_maintenance — from
pm_compliancesurveillance/PM checks (a failed check is a prevention gap);condition_monitoring — from telemetry detection (anomaly precursors present ⇒ monitoring held; telemetry present but no precursor ⇒ a detection gap; no telemetry ⇒ not evaluated);
protection_logic — from the primary candidate’s
barrier_logichard gate (a retained primary passed the gate, so protection did not preclude the cause ⇒ gap; degraded/absent inputs ⇒ not evaluated).
Honest by construction: any layer without inputs is
not_evaluatedrather than being asserted as a failure. Additive card block; ranking untouched.
- static _build_human_performance_assessment(*, selected_candidates, recommended_actions)[source]¶
Step 6 — Human and Organisational Performance Assessment.
Scans retained candidates for H/I/J/K categories and produces a structured block for the RCA card. When no such candidates are present, returns an
applicable=Falserecord so the field is always populated.
- _cap_confidence_label(label, maximum)[source]¶
- Parameters:
label (Optional[str])
maximum (str)
- Return type:
str
- _score_gap_to_runner_up(selected_candidates)[source]¶
- Parameters:
selected_candidates (List[JsonDict])
- Return type:
float
- _summarize_primary_pattern_posture(primary_candidate, evidence_summary, selected_candidates, causality_candidates, *, passed_minimum_evidence_gate, fallback_used)[source]¶
- _compute_conclusion_type(top, selected_candidates, calibrated_confidence_label, actuation_type)[source]¶
Derives the epistemic standing of the RCA conclusion.
Mirrors Stage D A/B-series tiering thresholds (composite ≥ 0.45 AND evidence ≥ 0.35 = A-series) without requiring an explicit series label on the candidate object.
design_signal actuation: the pipeline is verifying a design-basis response, not diagnosing a failure. All anomaly-based FM candidates are speculative by definition, so the minimum output is hypothesis_speculative regardless of scoring.
- _build_ccf_summary(selected_candidates, causality_candidates)[source]¶
Builds the rca_card ccf_summary block from the causality engine’s common_cause_summary. Returns None when no common-cause signal was detected (candidate_count_with_common_cause == 0).
affected_trains is assembled from per-candidate common_cause.train_id_in_oos so that all OOS trains in the clustered set are surfaced — the engine’s common_cause_summary does not aggregate this.
- _apply_epistemics_postprocessing(card, causality_candidates)[source]¶
Enforce epistemics digest rules on the card in-place.
Cap confidence_label at digest.confidence_cap when set.
Set causal_grounding_absent on primary_hypothesis.
Add gap-typed attention flags per §7.4 when ungrounded or absent analyzes support.
- _fallback_card(rca_id, event, selected_candidates, selected_evidence, causality_candidates, evidence_bundle, run_context, prior_errors, tskr_patterns=None, similar_event_list=None)[source]¶
- Parameters:
- Return type:
- _enforce_balanced_card_evidence(*, card, selected_candidates, evidence_pool, max_rows)[source]¶
Tighten LLM-path evidence balance by ensuring in-card alternatives are represented.
- static _validate_and_repair_llm_sections(card, all_input_candidate_ids)[source]¶
Remove LLM-hallucinated candidate IDs from secondary card sections.
Filters contributing_causes[] and alternatives[] by removing entries whose candidate_id is not in all_input_candidate_ids. Nullifies linked_candidate_id on recommended_actions[] and evidence[] items that reference an invented ID. Does NOT touch primary_hypothesis (handled by the hard-reject gate in synthesize()).
Returns the count of repaired (removed/nullified) items so the caller can set synthesis_quality accordingly.
- Parameters:
card (JsonDict)
all_input_candidate_ids (set)
- Return type:
int