perf(monitors): a monitor's latest results by a LATERAL probe, not row_number over its history (#5208)
_last_n_results (Status, the monitors list, host monitors), host_status (hosts overview, list_hosts) and the report's down-monitor list each ranked every result a monitor ever recorded to keep the newest few. Each monitor now gets ORDER BY checked_at DESC LIMIT n in a LATERAL subquery, which walks ix_monitor_results_monitor_checked backwards and stops. Also fixes the latest-table test, which read between two begin() blocks and so autobegan a transaction the second block then refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -93,21 +93,12 @@ async def host_status(db, host_ids: list[str]) -> dict[str, dict]:
|
||||
"""
|
||||
if not host_ids:
|
||||
return {}
|
||||
rn = func.row_number().over(
|
||||
partition_by=MonitorResult.monitor_id, order_by=MonitorResult.checked_at.desc()
|
||||
).label("rn")
|
||||
subq = (
|
||||
select(MonitorResult.id, rn)
|
||||
.join(Monitor, Monitor.id == MonitorResult.monitor_id)
|
||||
monitors = (await db.execute(
|
||||
select(Monitor.id, Monitor.host_id)
|
||||
.where(Monitor.host_id.in_(host_ids), Monitor.enabled.is_(True))
|
||||
.subquery()
|
||||
)
|
||||
rows = (await db.execute(
|
||||
select(MonitorResult, Monitor.host_id)
|
||||
.join(subq, MonitorResult.id == subq.c.id)
|
||||
.join(Monitor, Monitor.id == MonitorResult.monitor_id)
|
||||
.where(subq.c.rn == 1)
|
||||
)).all()
|
||||
latest = await _last_n_results(db, [m.id for m in monitors], n=1)
|
||||
rows = [(latest[mid][-1], host_id) for mid, host_id in monitors if latest.get(mid)]
|
||||
out: dict[str, dict] = {}
|
||||
for res, host_id in rows:
|
||||
d = out.setdefault(host_id, {"state": "pending", "latency_ms": None, "count": 0})
|
||||
|
||||
Reference in New Issue
Block a user