forked from linkong/planet
609 lines
21 KiB
Python
609 lines
21 KiB
Python
"""Proactive snapshot -> semantic delta -> ResultRevision -> StagePresentation -> TopicWatch pipeline (Gate 0 & Gate 2)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime
|
|
from typing import Any
|
|
|
|
from sqlalchemy import desc, func, select
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
from app.core.logging import get_logger
|
|
from app.models.bgp_incident import BGPIncident
|
|
from app.models.compute_configuration_revision import ComputeConfigurationRevision
|
|
from app.models.situational_assessment import (
|
|
SituationalAssessment,
|
|
StagePresentation,
|
|
TopicWatch,
|
|
WorkflowRun,
|
|
)
|
|
from app.services.ai.incident_agent import DRILL_INCIDENT_KEY, investigate_infrastructure_incident
|
|
from app.services.ai.posture_agent import generate_or_get_compute_posture
|
|
from app.services.ai.presentation_compiler import (
|
|
compile_compute_revision_presentation,
|
|
compile_incident_five_act_presentation,
|
|
publish_stage_contract,
|
|
)
|
|
from app.services.ai.semantic_delta import classify_snapshot_delta, snapshot_fingerprint
|
|
from app.services.ai.tool_registry import query_compute_posture_tool
|
|
|
|
logger = get_logger(__name__, service="ai_proactive")
|
|
|
|
_BGP_STATE_KEY = "situational_bgp_snapshot_state"
|
|
|
|
|
|
async def _load_state_setting(db: AsyncSession, key: str) -> tuple[SituationalAssessment | None, dict[str, Any] | None]:
|
|
if not hasattr(db, "execute"):
|
|
return None, None
|
|
try:
|
|
row = (
|
|
await db.execute(
|
|
select(SituationalAssessment)
|
|
.where(
|
|
SituationalAssessment.subject_type == "snapshot_checkpoint",
|
|
SituationalAssessment.subject_key == key,
|
|
)
|
|
.order_by(desc(SituationalAssessment.id))
|
|
.limit(1)
|
|
)
|
|
).scalar_one_or_none()
|
|
if isinstance(row, SituationalAssessment) and isinstance(row.payload, dict):
|
|
return row, dict(row.payload)
|
|
return None, None
|
|
except Exception:
|
|
return None, None
|
|
|
|
|
|
async def _save_state_setting(
|
|
db: AsyncSession,
|
|
existing_row: SituationalAssessment | None,
|
|
key: str,
|
|
state: dict[str, Any],
|
|
) -> None:
|
|
if not hasattr(db, "add") or not hasattr(db, "flush"):
|
|
return
|
|
try:
|
|
fp = str((state.get("snapshot") or {}).get("fingerprint") or "checkpoint")[:64]
|
|
if existing_row is not None:
|
|
existing_row.input_fingerprint = fp
|
|
existing_row.payload = state
|
|
existing_row.revision = int(existing_row.revision or 1) + 1
|
|
else:
|
|
db.add(
|
|
SituationalAssessment(
|
|
subject_type="snapshot_checkpoint",
|
|
subject_key=key,
|
|
input_fingerprint=fp,
|
|
revision=1,
|
|
generation_mode="semantic_delta_checkpoint",
|
|
payload=state,
|
|
evidence_ids=[],
|
|
audit_meta={},
|
|
)
|
|
)
|
|
await db.flush()
|
|
except Exception as exc:
|
|
logger.warning_event(
|
|
"Proactive state checkpoint skipped",
|
|
event="ai_proactive.checkpoint.skipped",
|
|
context={"key": key, "error": str(exc)},
|
|
)
|
|
|
|
|
|
async def _evaluate_topic_watches(
|
|
db: AsyncSession,
|
|
*,
|
|
domain: str,
|
|
target_keys: list[str],
|
|
revision: int,
|
|
) -> list[dict[str, Any]]:
|
|
if not hasattr(db, "execute"):
|
|
return []
|
|
triggered: list[dict[str, Any]] = []
|
|
try:
|
|
watches = (
|
|
(
|
|
await db.execute(
|
|
select(TopicWatch)
|
|
.where(
|
|
TopicWatch.domain == domain,
|
|
TopicWatch.status == "active",
|
|
)
|
|
.limit(50)
|
|
)
|
|
)
|
|
.scalars()
|
|
.all()
|
|
)
|
|
now = datetime.now(UTC)
|
|
for w in watches:
|
|
scope = w.target_scope or {}
|
|
scope_inc = scope.get("incident_key")
|
|
if scope_inc and scope_inc not in target_keys:
|
|
continue
|
|
w.last_triggered_revision = revision
|
|
w.last_triggered_at = now
|
|
triggered.append(w.to_dict())
|
|
if triggered and hasattr(db, "flush"):
|
|
await db.flush()
|
|
except Exception as exc:
|
|
logger.warning_event(
|
|
"TopicWatch evaluation skipped",
|
|
event="ai_proactive.watches.skipped",
|
|
context={"domain": domain, "error": str(exc)},
|
|
)
|
|
return triggered
|
|
|
|
|
|
async def process_bgp_snapshot_proactive_delta(
|
|
db: AsyncSession,
|
|
*,
|
|
source: str,
|
|
record_count: int,
|
|
status: str = "success",
|
|
completed_at: str | datetime | None = None,
|
|
error: str | None = None,
|
|
ignore_coverage_drop: bool = False,
|
|
) -> dict[str, Any]:
|
|
"""Evaluate a BGP collection/incident snapshot through `classify_snapshot_delta` and publish stage deltas."""
|
|
setting_row, prev_state = await _load_state_setting(db, _BGP_STATE_KEY)
|
|
prev_snapshot = prev_state.get("snapshot") if prev_state else None
|
|
seen_fps: set[str] = set(prev_state.get("seen_fingerprints") or []) if prev_state else set()
|
|
|
|
active_keys: list[str] = []
|
|
incident_digests: dict[str, dict[str, Any]] = {}
|
|
if status == "success" and hasattr(db, "execute"):
|
|
try:
|
|
active_rows = (
|
|
(
|
|
await db.execute(
|
|
select(BGPIncident)
|
|
.where(BGPIncident.status == "active")
|
|
.order_by(desc(BGPIncident.started_at))
|
|
.limit(20)
|
|
)
|
|
)
|
|
.scalars()
|
|
.all()
|
|
)
|
|
for inc in active_rows:
|
|
if isinstance(inc, str):
|
|
active_keys.append(inc)
|
|
continue
|
|
key = str(getattr(inc, "incident_key", "") or "")
|
|
if not key:
|
|
continue
|
|
active_keys.append(key)
|
|
incident_digests[key] = {
|
|
"severity": str(getattr(inc, "severity", None) or "medium"),
|
|
"incident_type": str(getattr(inc, "incident_type", None) or ""),
|
|
"prefixes": sorted(str(p) for p in (getattr(inc, "affected_prefixes", None) or [])),
|
|
"asns": sorted(getattr(inc, "affected_asns", None) or []),
|
|
"collectors": sorted(str(c) for c in (getattr(inc, "affected_collectors", None) or [])),
|
|
"cables_count": len(getattr(inc, "related_cables", None) or []),
|
|
}
|
|
except Exception:
|
|
active_keys = []
|
|
incident_digests = {}
|
|
|
|
effective_record_count = (
|
|
max(record_count, int((prev_snapshot or {}).get("record_count") or 0))
|
|
if ignore_coverage_drop
|
|
else record_count
|
|
)
|
|
curr_snapshot: dict[str, Any] = {
|
|
"source": source,
|
|
"status": status,
|
|
"record_count": effective_record_count,
|
|
"completed_at": (
|
|
completed_at.isoformat()
|
|
if isinstance(completed_at, datetime)
|
|
else completed_at or datetime.now(UTC).isoformat()
|
|
),
|
|
"active_keys": active_keys,
|
|
"error": error,
|
|
}
|
|
if incident_digests:
|
|
curr_snapshot["incident_digests"] = incident_digests
|
|
if status == "success":
|
|
curr_snapshot["fingerprint"] = snapshot_fingerprint(curr_snapshot)
|
|
|
|
delta = classify_snapshot_delta(
|
|
prev_snapshot,
|
|
curr_snapshot,
|
|
ignore_coverage_drop=ignore_coverage_drop,
|
|
seen_fingerprints=seen_fps,
|
|
)
|
|
|
|
if delta["preserve_previous_snapshot"]:
|
|
return {
|
|
"domain": "bgp",
|
|
"delta": delta,
|
|
"emitted_presentations": [],
|
|
"triggered_watches": [],
|
|
}
|
|
|
|
emitted: list[dict[str, Any]] = []
|
|
triggered_watches: list[dict[str, Any]] = []
|
|
|
|
if delta["emit_event"]:
|
|
focus_keys = (
|
|
delta["added_keys"]
|
|
or delta.get("updated_keys")
|
|
or delta["resolved_keys"]
|
|
or active_keys
|
|
)[:2]
|
|
for inc_key in focus_keys:
|
|
inc_eval = await investigate_infrastructure_incident(
|
|
db,
|
|
incident_key=inc_key,
|
|
time_basis="live",
|
|
allow_drill=False,
|
|
persist=True,
|
|
)
|
|
if not inc_eval.get("found") or not inc_eval.get("incident"):
|
|
continue
|
|
for tb in ("live", "retrospective"):
|
|
contract = compile_incident_five_act_presentation(
|
|
inc_eval["incident"],
|
|
inc_eval["payload"],
|
|
inc_eval["evidence"],
|
|
time_basis=tb,
|
|
)
|
|
published = await publish_stage_contract(db, contract)
|
|
if published is not None and tb == "retrospective":
|
|
emitted.append(published.to_dict())
|
|
triggered_watches.extend(
|
|
await _evaluate_topic_watches(
|
|
db,
|
|
domain="bgp",
|
|
target_keys=[inc_key],
|
|
revision=int(inc_eval.get("revision") or 1),
|
|
)
|
|
)
|
|
|
|
await _save_state_setting(
|
|
db,
|
|
setting_row,
|
|
_BGP_STATE_KEY,
|
|
{
|
|
"snapshot": curr_snapshot,
|
|
"seen_fingerprints": sorted(seen_fps)[-32:],
|
|
"last_verdict": delta["verdict"],
|
|
},
|
|
)
|
|
return {
|
|
"domain": "bgp",
|
|
"delta": delta,
|
|
"emitted_presentations": emitted,
|
|
"triggered_watches": triggered_watches,
|
|
}
|
|
|
|
|
|
async def process_compute_revision_presentation(
|
|
db: AsyncSession,
|
|
revision_id: int,
|
|
*,
|
|
countries: list[str] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Emit an idempotent StagePresentation driven directly by one `ComputeConfigurationRevision`."""
|
|
row = (
|
|
await db.execute(
|
|
select(ComputeConfigurationRevision).where(
|
|
ComputeConfigurationRevision.id == revision_id
|
|
)
|
|
)
|
|
).scalar_one_or_none()
|
|
if not isinstance(row, ComputeConfigurationRevision):
|
|
return {
|
|
"domain": "compute",
|
|
"status": "not_found",
|
|
"revision_id": revision_id,
|
|
"emitted_presentations": [],
|
|
"triggered_watches": [],
|
|
}
|
|
|
|
if row.presentation_status in {"delivered", "skipped"}:
|
|
return {
|
|
"domain": "compute",
|
|
"status": row.presentation_status,
|
|
"publish_id": row.publish_id,
|
|
"revision_id": row.id,
|
|
"idempotent": True,
|
|
"emitted_presentations": [],
|
|
"triggered_watches": [],
|
|
}
|
|
|
|
value_diffs = [
|
|
item
|
|
for item in (row.diff_summary or [])
|
|
if item.get("kind") == "observation_value"
|
|
and item.get("delta") is not None
|
|
and float(item["delta"]) != 0.0
|
|
]
|
|
if not value_diffs:
|
|
row.presentation_status = "skipped"
|
|
row.presentation_error = ""
|
|
await db.flush()
|
|
return {
|
|
"domain": "compute",
|
|
"status": "skipped",
|
|
"publish_id": row.publish_id,
|
|
"revision_id": row.id,
|
|
"emitted_presentations": [],
|
|
"triggered_watches": [],
|
|
}
|
|
|
|
historical = [d for d in value_diffs if d.get("change_kind") == "historical_revision"]
|
|
primary = historical[0] if historical else value_diffs[0]
|
|
primary_mode = str(primary.get("metric") or "global_share")
|
|
changed_codes = [str(d["code"]) for d in value_diffs if d.get("code")]
|
|
codes = list(dict.fromkeys([*(countries or ["CN", "US"]), *changed_codes]))
|
|
|
|
series = await query_compute_posture_tool(
|
|
db, codes, mode=primary_mode, publish_id=row.publish_id
|
|
)
|
|
posture = await generate_or_get_compute_posture(
|
|
db,
|
|
countries=codes,
|
|
mode=primary_mode,
|
|
series_payload=series,
|
|
persist=True,
|
|
)
|
|
|
|
existing_stage_rows = (
|
|
(
|
|
await db.execute(
|
|
select(StagePresentation)
|
|
.where(
|
|
StagePresentation.presentation_key == "compute-revision-notice",
|
|
StagePresentation.time_basis == "retrospective",
|
|
)
|
|
.order_by(desc(StagePresentation.id))
|
|
.limit(50)
|
|
)
|
|
)
|
|
.scalars()
|
|
.all()
|
|
)
|
|
existing_for_publish = next(
|
|
(
|
|
st
|
|
for st in existing_stage_rows
|
|
if isinstance(st.contract, dict) and st.contract.get("publish_id") == row.publish_id
|
|
),
|
|
None,
|
|
)
|
|
|
|
if existing_for_publish is not None:
|
|
published = existing_for_publish
|
|
else:
|
|
contract = compile_compute_revision_presentation(
|
|
publish_id=row.publish_id,
|
|
action=row.action,
|
|
series=series,
|
|
value_diffs=value_diffs,
|
|
time_basis="retrospective",
|
|
)
|
|
published = await publish_stage_contract(db, contract, explicit_revision=int(row.id))
|
|
|
|
row.presentation_status = "delivered"
|
|
row.presentation_attempts = int(row.presentation_attempts or 0) + 1
|
|
row.presentation_error = ""
|
|
row.presentation_delivered_at = datetime.now(UTC)
|
|
await db.flush()
|
|
|
|
triggered_watches = await _evaluate_topic_watches(
|
|
db,
|
|
domain="compute",
|
|
target_keys=[posture["subject_key"]],
|
|
revision=int(row.id),
|
|
)
|
|
return {
|
|
"domain": "compute",
|
|
"status": "delivered",
|
|
"publish_id": row.publish_id,
|
|
"revision_id": row.id,
|
|
"emitted_presentations": [published.to_dict()] if published is not None else [],
|
|
"triggered_watches": triggered_watches,
|
|
}
|
|
|
|
|
|
async def retry_pending_compute_presentations(
|
|
db: AsyncSession,
|
|
*,
|
|
max_attempts: int = 3,
|
|
) -> dict[str, Any]:
|
|
"""Retry pending or failed compute revision presentations in ascending revision order."""
|
|
if not hasattr(db, "execute"):
|
|
return {"domain": "compute", "processed": 0, "delivered": 0, "skipped": 0, "failed": 0, "results": []}
|
|
|
|
rows = (
|
|
(
|
|
await db.execute(
|
|
select(ComputeConfigurationRevision)
|
|
.where(
|
|
ComputeConfigurationRevision.presentation_status.in_(["pending", "failed"]),
|
|
ComputeConfigurationRevision.presentation_attempts < max_attempts,
|
|
)
|
|
.order_by(ComputeConfigurationRevision.id.asc())
|
|
.limit(20)
|
|
)
|
|
)
|
|
.scalars()
|
|
.all()
|
|
)
|
|
delivered = 0
|
|
skipped = 0
|
|
failed = 0
|
|
results: list[dict[str, Any]] = []
|
|
for row in rows:
|
|
try:
|
|
res = await process_compute_revision_presentation(db, row.id)
|
|
results.append(res)
|
|
if res.get("status") == "delivered":
|
|
delivered += 1
|
|
elif res.get("status") == "skipped":
|
|
skipped += 1
|
|
except Exception as exc:
|
|
failed += 1
|
|
row.presentation_status = "failed"
|
|
row.presentation_attempts = int(row.presentation_attempts or 0) + 1
|
|
row.presentation_error = str(exc)[:1000]
|
|
await db.flush()
|
|
logger.warning_event(
|
|
"Compute revision presentation retry failed",
|
|
event="compute.revision.presentation_failed",
|
|
context={
|
|
"revision_id": row.id,
|
|
"publish_id": row.publish_id,
|
|
"attempts": row.presentation_attempts,
|
|
"error": str(exc),
|
|
},
|
|
)
|
|
results.append(
|
|
{
|
|
"domain": "compute",
|
|
"status": "failed",
|
|
"publish_id": row.publish_id,
|
|
"revision_id": row.id,
|
|
"error": str(exc),
|
|
}
|
|
)
|
|
return {
|
|
"domain": "compute",
|
|
"processed": len(rows),
|
|
"delivered": delivered,
|
|
"skipped": skipped,
|
|
"failed": failed,
|
|
"results": results,
|
|
}
|
|
|
|
|
|
async def process_compute_config_proactive_delta(
|
|
db: AsyncSession,
|
|
*,
|
|
countries: list[str] | None = None,
|
|
publish_id: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Compatibility wrapper delegating to `process_compute_revision_presentation` for the target/latest revision."""
|
|
stmt = select(ComputeConfigurationRevision)
|
|
if publish_id:
|
|
stmt = stmt.where(ComputeConfigurationRevision.publish_id == publish_id)
|
|
else:
|
|
stmt = stmt.order_by(desc(ComputeConfigurationRevision.id))
|
|
row = (await db.execute(stmt.limit(1))).scalar_one_or_none()
|
|
if not isinstance(row, ComputeConfigurationRevision):
|
|
return {
|
|
"domain": "compute",
|
|
"status": "skipped",
|
|
"emitted_presentations": [],
|
|
"triggered_watches": [],
|
|
}
|
|
return await process_compute_revision_presentation(db, row.id, countries=countries)
|
|
|
|
|
|
async def audit_situational_hygiene(db: AsyncSession) -> dict[str, Any]:
|
|
"""Gate 0 · R1: Pure read-only SQL aggregate audit of `situational_assessments` and `stage_presentations`."""
|
|
total_rows = int(
|
|
(await db.execute(select(func.count(SituationalAssessment.id)))).scalar_one_or_none() or 0
|
|
)
|
|
grouped = (
|
|
(
|
|
await db.execute(
|
|
select(
|
|
SituationalAssessment.subject_type,
|
|
SituationalAssessment.subject_key,
|
|
func.count(SituationalAssessment.id).label("row_count"),
|
|
func.count(func.distinct(SituationalAssessment.input_fingerprint)).label("distinct_fingerprints"),
|
|
func.min(SituationalAssessment.revision).label("min_rev"),
|
|
func.max(SituationalAssessment.revision).label("max_rev"),
|
|
)
|
|
.group_by(SituationalAssessment.subject_type, SituationalAssessment.subject_key)
|
|
.order_by(desc("row_count"))
|
|
.limit(50)
|
|
)
|
|
)
|
|
.mappings()
|
|
.all()
|
|
)
|
|
|
|
redundant_rows = 0
|
|
drill_rows = 0
|
|
subject_summaries: list[dict[str, Any]] = []
|
|
for row in grouped:
|
|
r_count = int(row["row_count"] or 0)
|
|
d_fps = int(row["distinct_fingerprints"] or 0)
|
|
dup = max(0, r_count - d_fps)
|
|
redundant_rows += dup
|
|
is_drill_subj = DRILL_INCIDENT_KEY in str(row["subject_key"])
|
|
if is_drill_subj:
|
|
drill_rows += r_count
|
|
subject_summaries.append(
|
|
{
|
|
"subject_type": row["subject_type"],
|
|
"subject_key": row["subject_key"],
|
|
"row_count": r_count,
|
|
"canonical_distinct_fingerprints": d_fps,
|
|
"redundant_duplicate_rows": dup,
|
|
"is_drill_archive": is_drill_subj,
|
|
"revision_span": [row["min_rev"], row["max_rev"]],
|
|
}
|
|
)
|
|
|
|
stage_count = int(
|
|
(await db.execute(select(func.count(StagePresentation.id)))).scalar_one_or_none() or 0
|
|
)
|
|
run_rows = (
|
|
(
|
|
await db.execute(
|
|
select(WorkflowRun.status, WorkflowRun.budget_used)
|
|
.order_by(desc(WorkflowRun.started_at))
|
|
.limit(500)
|
|
)
|
|
)
|
|
.all()
|
|
)
|
|
model_cost_summary = {
|
|
"sampled_runs": len(run_rows),
|
|
"completed_runs": 0,
|
|
"cancelled_runs": 0,
|
|
"failed_runs": 0,
|
|
"zero_token_runs": 0,
|
|
"llm_runs": 0,
|
|
"total_llm_calls": 0,
|
|
"total_input_tokens": 0,
|
|
"total_output_tokens": 0,
|
|
"total_thinking_tokens": 0,
|
|
"total_tokens": 0,
|
|
}
|
|
for r_status, r_budget in run_rows:
|
|
st_key = f"{r_status}_runs"
|
|
if st_key in model_cost_summary:
|
|
model_cost_summary[st_key] += 1
|
|
b = r_budget if isinstance(r_budget, dict) else {}
|
|
calls = int(b.get("llm_calls") or 0)
|
|
if calls > 0:
|
|
model_cost_summary["llm_runs"] += 1
|
|
elif b.get("zero_token", True):
|
|
model_cost_summary["zero_token_runs"] += 1
|
|
model_cost_summary["total_llm_calls"] += calls
|
|
model_cost_summary["total_input_tokens"] += int(b.get("input_tokens") or 0)
|
|
model_cost_summary["total_output_tokens"] += int(b.get("output_tokens") or 0)
|
|
model_cost_summary["total_thinking_tokens"] += int(b.get("thinking_tokens") or 0)
|
|
model_cost_summary["total_tokens"] += int(b.get("total_tokens") or 0)
|
|
|
|
return {
|
|
"read_only_audit": True,
|
|
"destructive_cleanup_executed": False,
|
|
"total_assessment_rows": total_rows,
|
|
"redundant_r1_loop_duplicate_rows": redundant_rows,
|
|
"drill_archive_rows": drill_rows,
|
|
"stage_presentation_rows": stage_count,
|
|
"model_cost_summary": model_cost_summary,
|
|
"subjects": subject_summaries,
|
|
"remediation_status": (
|
|
"R1 write-on-GET feedback loop severed; SituationalAssessment & StagePresentation writes are now strictly content-fingerprint idempotent."
|
|
),
|
|
}
|