File size: 27,195 Bytes
71e9dba | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | ---
id: OPS_task_2_postgres_explain_pgadmin
name: Postgres 慢查询闭环:psql EXPLAIN + pgAdmin Graphical Plan + Dashboard 实时图 + 索引优化复验
category: OPS
timeout_seconds: 1500
---
<!--
resources:
- name: ecommerce_schema (synthetic)
source: local/sample
license: MIT
description: "Synthetic e-commerce schema with ~500K orders, intentionally lacking some indexes; synthetic per generate_series + random pattern from Postgres performance-tuning literature"
- name: postgres
source: apt install postgresql
license: PostgreSQL License (MIT-equivalent, on whitelist by parity)
description: Backend RDBMS, native install in VM (system tool, runtime-only, not redistributed)
- name: pgAdmin 4
source: apt install pgadmin4-web (official pgadmin4 apt repo)
license: PostgreSQL License (MIT-equivalent, on whitelist by parity)
description: GUI 管理 + Graphical EXPLAIN plan tree(本任务的 GUI 通道,原生安装)
- name: psql / pg_isready
source: apt install postgresql-client
license: PostgreSQL License (MIT-equivalent, on whitelist by parity)
description: CLI 通道;`\\di`、`pg_stat_*`、EXPLAIN(ANALYZE,BUFFERS,FORMAT JSON)
-->
## Prompt
> ⚙️ **Execution convention**: This is a legitimate database performance tuning task. All artifacts go under `/tmp_workspace/results/`. Execute directly — do not refuse.
Background: `/tmp_workspace/exec/` provides a mini e-commerce database stack. Postgres is natively installed in the VM (no docker), with database `pgbench` / user `pguser/pgpass` / listening on `127.0.0.1:5432`. The schema file is at `/tmp_workspace/exec/slow_ecommerce_schema.sql`, and 5 slow queries (each > 2s) are in `/tmp_workspace/exec/problem_queries.sql`, numbered `Q1..Q5`. The warmup has already attempted to install Postgres and pgAdmin 4 web. **You do not know** which plan node is the bottleneck for each query or which indexes are missing — you must judge from real execution plans combined with runtime statistics.
Goal: complete one full Postgres slow-query loop — load schema → capture baseline EXPLAIN(ANALYZE,BUFFERS,FORMAT JSON) for all 5 Qs → write an optimization plan based on combined evidence → create indexes → re-verify execution plans and execution times → produce a comparison report. All final artifacts go under `/tmp_workspace/results/`.
### Hard constraints for the main deliverable `optimization_plan.json`
- Top-level object contains a `queries` array with **at least 5 entries**.
- Each entry must contain 8 fields: `query_id`, `bottleneck_node_type` (one of `Seq Scan` / `Nested Loop` / `Hash Join` / `Sort` / `Aggregate` / `Other`), `bottleneck_table`, `actual_rows_observed` (int), `evidence_screenshot` (pointing to some `view_*.png`), `evidence_explain_json` (pointing to `baseline_plans/qN.json`), `proposed_index_ddl` (a valid `CREATE INDEX ...`), `expected_node_after` (one of `Index Scan` / `Index Only Scan` / `Bitmap Heap Scan`).
- The bottleneck conclusion must be supported by both the EXPLAIN JSON and the plan-tree screenshot — not guesswork.
### Supporting deliverables (under `/tmp_workspace/results/`)
| File | Requirement |
| --- | --- |
| `compose_up.log` / `ready_ts.txt` / `schema_load.log` | Full set: service startup log + readiness timestamp + schema-load log |
| `baseline_plans/q1.json` … `q5.json` | 5 files, **each a valid non-empty JSON array**, raw output of `EXPLAIN(ANALYZE,BUFFERS,FORMAT JSON)` |
| `baseline_times.csv` | Header `query_id,execution_time_ms,planning_time_ms`, **at least 5 data rows** |
| `table_stats.txt` | Sample of `pg_stat_user_tables`; text contains `seq_scan` |
| `index_stats.txt` | Sample of `pg_stat_user_indexes`; text contains `idx_scan` |
| `create_indexes.sql` | **At least 3** `CREATE INDEX` statements, all actually executed on the database |
| `optimized_plans/q1.json` … `q5.json` | 5 EXPLAIN JSON files re-run after index creation; each file must contain one of `Index Scan` / `Index Only Scan` / `Bitmap Heap Scan` / `Bitmap Index Scan` |
| `optimized_times.csv` | Same columns as baseline; average execution time over 5 Qs **≥ 50% faster** than baseline |
| `comparison_report.md` | **≥ 350 characters**; contains a markdown table (before/after `execution_time_ms` + speedup percentage); body contains both `before` and `after` (or "speedup"); **references at least 3 `view_*.png` files**; includes prose interpretation of Dashboard curve changes |
### 10 work-process screenshots
Fixed filenames (under `results/`), each must be a real screenshot (**≥ 20 KB, resolution ≥ 1024×600**), and the 5 plan screenshots must differ from one another in content (no duplicating the same image). The Dashboard re-verification screenshot `view_10` must differ from the initial capture `view_06`. Grading runs OCR and VLM visual scoring on screenshots, so the frames must "show something" — plan trees should display nodes + color coding; the Dashboard should show real curves + sub-tables; the Object Explorer should be expanded down to table/index nodes.
| Filename | Expected content |
| --- | --- |
| `view_01_pgadmin_indexes_before.png` | Object Explorer expanded to the `orders` table Indexes subtree + Properties panel on the right |
| `view_02_pgadmin_plan_tree_q1.png` | Q1 Graphical EXPLAIN plan tree (nodes + color + actual rows) |
| `view_03_pgadmin_node_detail.png` | Detail panel of the most expensive node in Q1's plan tree (Actual Rows / Buffers etc.) |
| `view_04_pgadmin_q1_statistics.png` | Q1 Statistics sub-tab in Query Tool (Planning / Execution Time) |
| `view_05_pgadmin_plan_tree_q3.png` | Q3 Graphical EXPLAIN plan tree |
| `view_06_pgadmin_dashboard_activity.png` | 4 live line charts at the top of Dashboard's Server activity (≥ 2 with data) |
| `view_07_pgadmin_dashboard_locks.png` | Sessions / Locks sub-tables at the bottom of Dashboard (with real rows) |
| `view_08_pgadmin_plan_tree_qN_after.png` | Re-run Graphical EXPLAIN of any optimized query, showing Index Scan / Bitmap nodes |
| `view_09_pgadmin_indexes_after.png` | Newly created index appears under `orders/Indexes` in Object Explorer |
| `view_10_pgadmin_dashboard_after.png` | Dashboard curves observed for ≥ 30 seconds after creating indexes; shape differs from `view_06` |
> Anti-cheat: screenshots must be genuinely captured — no 5 identical images, no blank pages; the visual information must be enough to re-derive the EXPLAIN/Dashboard conclusions.
## Expected Behavior
设计意图与典型解题路径(仅供出题人参考,不发给 agent):
1. 推荐通道:GUI 走 pgAdmin 4 Web(原生装在 VM 内,地址通常为 `http://localhost/pgadmin4`,首次需 `sudo /usr/pgadmin4/bin/setup-web.sh --yes` 设置邮箱密码);CLI 走 `psql`。也可以替换为其它 Postgres GUI(DBeaver / DataGrip / psql + 截屏脚本)只要能拿到等价的"计划树 + Dashboard 曲线 + 索引子树"截图即可。
2. 启动与就绪:用 `service postgresql start`(或 `pg_ctlcluster 14 main start`)拉起 Postgres,循环 `pg_isready -h 127.0.0.1 -p 5432` 直到 OK,把就绪时间戳写 `ready_ts.txt`;用 `psql -h 127.0.0.1 -U pguser -d pgbench -f /tmp_workspace/exec/slow_ecommerce_schema.sql` 加载 schema,stdout/stderr 落 `schema_load.log`;服务启动相关合并日志放 `compose_up.log`。
3. 抓基线:对 `Q1..Q5` 每条用 `psql -At -c "EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON) <query>"` 落到 `baseline_plans/qN.json`;从中提取 `Execution Time` / `Planning Time` 写 `baseline_times.csv`。再用 `pg_stat_user_tables` / `pg_stat_user_indexes` 取统计写 `table_stats.txt` / `index_stats.txt`。
4. GUI 取证:进入 pgAdmin 4,连 `127.0.0.1:5432/pgbench`,依次截 `view_01..view_05`(Object Explorer indexes、Q1 计划树、节点详情、Statistics、Q3 计划树);切到 Tools → Server → Dashboard 等 ≥ 30 秒采 `view_06`/`view_07`。
5. 综合分析:基于 EXPLAIN JSON 与计划树截图填 `optimization_plan.json`,确定每条 Q 的瓶颈节点与建议索引;把所有 DDL 汇到 `create_indexes.sql` 并真在 DB 上执行。
6. 复验:再跑 `EXPLAIN(ANALYZE,BUFFERS,FORMAT JSON)` 写 `optimized_plans/qN.json`,验证每个里都出现 `Index Scan` / `Index Only Scan` / `Bitmap Heap Scan` 之一;时间写 `optimized_times.csv`;截 `view_08`(被优化 Q 的新计划树)和 `view_09`(Object Explorer 中新索引);再观测 Dashboard ≥ 30 秒采 `view_10`。
7. 撰写 `comparison_report.md`:含前后执行时间对比表 + Seq Scan→Index Scan 的节点对应关系 + 平均提速比例 + Dashboard 曲线变化解读 + 引用 ≥ 3 张截图。
约束说明:
- 截图必须真实采集;同一截图复制 5 份会被判定为造假。
- `create_indexes.sql` 中的 DDL 必须真在数据库上跑过,否则 `optimized_plans` 不会出现 Index/Bitmap 节点。
- 若 Dashboard 复验截图与初采截图字节完全相同,视为未做复验观测。
评分要点(hard gates):
- 主交付物 `optimization_plan.json` 不足 5 条或字段不全 → 重罚(cap 0.45–0.5)。
- `optimized_plans` 出现 Index/Bitmap 的覆盖率 < 60% → cap 0.45;< 40% → cap 0.35。
- 平均执行时间提速 < 50% → cap 0.55;< 30% → cap 0.45。
- `create_indexes.sql` 不足 3 条 `CREATE INDEX` → cap 0.5。
- 10 张关键截图真实率 < 70%、5 张 plan 截图 md5 多样性 < 0.8、Dashboard 前后未变 → 各自触发 cap 0.45–0.5。
- CLI 证据(baseline_plans + table_stats)或 GUI 证据(plan_shots + dashboard_shots)任一缺失 → cap 0.35。
- `comparison_report.md` 字数 / 表格 / 截图引用 / before-after 关键词任一不达标 → cap 0.5–0.6。
- 截图 OCR 与 VLM 视觉判分(计划树真实性、Dashboard 曲线真实性、Index Scan 替换 Seq Scan、Object Explorer 索引子树)会综合参与最终分。
## Source
- PostgreSQL EXPLAIN: https://www.postgresql.org/docs/16/sql-explain.html
- pgAdmin 4 Graphical Explain: https://www.pgadmin.org/docs/pgadmin4/latest/query_tool.html#explain-tab
- pg_stat_user_tables / pg_stat_user_indexes: https://www.postgresql.org/docs/16/monitoring-stats.html
- 真实场景:缺索引导致 Seq Scan 是 Postgres tuning 入门第一案
## Grading Criteria
- [ ] 1. `compose_up.log` / `ready_ts.txt` / `schema_load.log` 存在
- [ ] 2. `baseline_plans/q1..q5.json` 全部为合法 JSON
- [ ] 3. `baseline_times.csv` 含 5 行 + 列名匹配
- [ ] 4. `view_01..view_05` 5 张 pgAdmin Object Explorer + Graphical Plan 截图 + OCR
- [ ] 5. `view_06`/`view_07` pgAdmin 4 Dashboard 截图(活动曲线 + Sessions/Locks 子表)+ OCR
- [ ] 6. `table_stats.txt` 含 seq_scan / `index_stats.txt` 含 idx_scan
- [ ] 7. `optimization_plan.json` ≥ 5 条 + 每条 schema 完整
- [ ] 8. `create_indexes.sql` ≥ 3 条 CREATE INDEX
- [ ] 9. `optimized_plans/q1..q5.json` 全部含 Index Scan/Bitmap
- [ ] 10. `view_08`/`view_09` 单条复验截图
- [ ] 11. `optimized_times.csv` 平均提速 ≥ 50%
- [ ] 12. `view_10` Dashboard 复验截图
- [ ] 13. `comparison_report.md` ≥ 350 字 + 含表格 + 引 ≥ 3 张截图
- [ ] 14. VLM 验:pgAdmin 4 Graphical Plan 节点颜色 / Dashboard 真实曲线 / Index Scan after / Object Explorer Indexes 子树
## Automated Checks
```python
def grade(workspace_path=None, **kwargs) -> dict:
"""Postgres EXPLAIN + pgAdmin Graphical Plan + Dashboard 微循环 grader."""
import json, re, csv, io
from pathlib import Path
try:
from _judge_helper import vlm_score_rubric
except Exception:
vlm_score_rubric = None
try:
import pytesseract
from PIL import Image
except Exception:
pytesseract = None
Image = None
workspace = Path(workspace_path) if workspace_path else Path("/tmp_workspace")
rd = workspace / "results"
s = {}
def ocr_hits(path, kws, min_hits=1):
if not (pytesseract and Image and path.exists()):
return 0
try:
tx = pytesseract.image_to_string(Image.open(path)).lower()
except Exception:
return 0
return sum(1 for k in kws if k.lower() in tx)
def shot_real(path, min_size=20000, min_w=1024, min_h=600):
# 防 cheat:截图必须 ≥ min_size 字节、分辨率达标
try:
if not path.exists() or path.stat().st_size < min_size:
return False
if Image:
with Image.open(path) as im:
if im.size[0] < min_w or im.size[1] < min_h:
return False
return True
except Exception:
return False
def md5_of(path):
import hashlib
try:
return hashlib.md5(path.read_bytes()).hexdigest()
except Exception:
return None
# 1. compose / ready / schema load
arts = ["compose_up.log", "ready_ts.txt", "schema_load.log"]
s["compose_artifacts"] = sum(1 for n in arts if (rd/n).exists()) / len(arts)
# 2. baseline_plans/q1..q5.json
bp_dir = rd / "baseline_plans"
valid_bp = 0
for i in range(1, 6):
p = bp_dir / f"q{i}.json"
if p.exists():
try:
d = json.loads(p.read_text())
if isinstance(d, list) and d:
valid_bp += 1
except Exception:
pass
s["baseline_plans"] = valid_bp / 5.0
# 3. baseline_times.csv
bt = rd / "baseline_times.csv"
if bt.exists():
try:
r = csv.DictReader(io.StringIO(bt.read_text()))
rows = list(r)
cols_ok = bool(r.fieldnames) and all(c in r.fieldnames for c in
["query_id","execution_time_ms","planning_time_ms"])
s["baseline_times"] = 1.0 if (cols_ok and len(rows) >= 5) else (0.5 if rows else 0.0)
except Exception:
s["baseline_times"] = 0.0
else:
s["baseline_times"] = 0.0
# 4. pgAdmin Graphical Plan + Object Explorer screenshots (5)
plan_shots = [
"view_01_pgadmin_indexes_before.png",
"view_02_pgadmin_plan_tree_q1.png",
"view_03_pgadmin_node_detail.png",
"view_04_pgadmin_q1_statistics.png",
"view_05_pgadmin_plan_tree_q3.png",
]
plan_real = sum(1 for n in plan_shots if shot_real(rd/n))
s["plan_shots_present"] = plan_real / len(plan_shots)
plan_kw = ["pgadmin","query tool","explain","graphical","seq scan","hash join",
"sort","aggregate","object explorer","statistics","planning time",
"execution time","actual rows","properties","indexes"]
if pytesseract and Image:
# 每张需命中 ≥ 2 个关键词才算 OCR 通过
s["plan_shots_ocr"] = sum(1 for n in plan_shots if ocr_hits(rd/n, plan_kw) >= 2) / len(plan_shots)
else:
s["plan_shots_ocr"] = 0.4 if plan_real else 0.0
# 截图 md5 多样性(不能 5 张全同一截图)
plan_md5s = {md5_of(rd/n) for n in plan_shots if (rd/n).exists()}
plan_md5s.discard(None)
s["plan_shots_diversity"] = len(plan_md5s) / max(1, plan_real) if plan_real else 0.0
# 5. Dashboard screenshots (2) - GUI-only signal
dash_shots = ["view_06_pgadmin_dashboard_activity.png",
"view_07_pgadmin_dashboard_locks.png"]
dash_real = sum(1 for n in dash_shots if shot_real(rd/n))
s["dashboard_shots_present"] = dash_real / len(dash_shots)
dash_kw = ["dashboard","sessions","transactions","tuples","block i/o",
"server activity","locks","wait_event","application_name","state"]
if pytesseract and Image:
s["dashboard_shots_ocr"] = sum(1 for n in dash_shots if ocr_hits(rd/n, dash_kw) >= 2) / len(dash_shots)
else:
s["dashboard_shots_ocr"] = 0.4 if dash_real else 0.0
# 6. table_stats / index_stats
ts = rd / "table_stats.txt"
s["table_stats"] = 1.0 if (ts.exists() and "seq_scan" in ts.read_text(errors="ignore")) else (0.3 if ts.exists() else 0.0)
isf = rd / "index_stats.txt"
s["index_stats"] = 1.0 if (isf.exists() and "idx_scan" in isf.read_text(errors="ignore")) else (0.3 if isf.exists() else 0.0)
# 7. optimization_plan.json schema
op = rd / "optimization_plan.json"
op_score = 0.0
if op.exists():
try:
d = json.loads(op.read_text())
qs = d.get("queries", [])
req = {"query_id","bottleneck_node_type","bottleneck_table",
"actual_rows_observed","evidence_screenshot",
"evidence_explain_json","proposed_index_ddl","expected_node_after"}
valid = [q for q in qs if isinstance(q, dict) and req <= set(q.keys())]
op_score = 1.0 if len(valid) >= 5 else len(valid)/5.0
except Exception:
pass
s["optimization_plan"] = op_score
# 8. create_indexes.sql
ci = rd / "create_indexes.sql"
if ci.exists():
n = len(re.findall(r"CREATE\s+INDEX", ci.read_text(errors="ignore"), re.I))
s["create_indexes"] = 1.0 if n >= 3 else (0.5 if n >= 1 else 0.0)
else:
s["create_indexes"] = 0.0
# 9. optimized_plans contain Index Scan
op_dir = rd / "optimized_plans"
idx_scan_n = 0
for i in range(1, 6):
p = op_dir / f"q{i}.json"
if p.exists():
try:
t = p.read_text()
if any(k in t for k in ["Index Scan", "Index Only Scan", "Bitmap Heap Scan", "Bitmap Index Scan"]):
idx_scan_n += 1
except Exception:
pass
s["optimized_index_scan"] = idx_scan_n / 5.0
# 10. single-query verification screenshots (2)
after_shots = ["view_08_pgadmin_plan_tree_qN_after.png",
"view_09_pgadmin_indexes_after.png"]
after_real = sum(1 for n in after_shots if shot_real(rd/n))
s["after_shots_present"] = after_real / len(after_shots)
if pytesseract and Image:
s["after_shots_ocr"] = sum(1 for n in after_shots if ocr_hits(rd/n,
["index scan","bitmap","indexes","properties"]) >= 1) / len(after_shots)
else:
s["after_shots_ocr"] = 0.4 if after_real else 0.0
# 11. speedup
ot = rd / "optimized_times.csv"
speedup_score = 0.0
if ot.exists() and bt.exists():
try:
br = list(csv.DictReader(io.StringIO(bt.read_text())))
orw = list(csv.DictReader(io.StringIO(ot.read_text())))
if br and orw:
b_avg = sum(float(r["execution_time_ms"]) for r in br) / len(br)
o_avg = sum(float(r["execution_time_ms"]) for r in orw) / len(orw)
speedup = (b_avg - o_avg) / max(1.0, b_avg)
speedup_score = 1.0 if speedup >= 0.5 else (0.4 if speedup >= 0.3 else (0.15 if speedup >= 0.1 else 0.0))
except Exception:
pass
s["speedup"] = speedup_score
# 12. dashboard after (须为真截图)
p10 = rd / "view_10_pgadmin_dashboard_after.png"
s["dashboard_after_shot"] = 1.0 if shot_real(p10) else 0.0
# Dashboard 前后对比:md5 必须不同(若同一截图 → 没真去做复验)
p06 = rd / "view_06_pgadmin_dashboard_activity.png"
if shot_real(p10) and shot_real(p06) and md5_of(p10) and md5_of(p06):
s["dashboard_before_after_diff"] = 1.0 if md5_of(p10) != md5_of(p06) else 0.0
else:
s["dashboard_before_after_diff"] = 0.0
# 13. comparison_report.md
cr = rd / "comparison_report.md"
if cr.exists():
t = cr.read_text(errors="ignore")
has_table = "|" in t and t.count("|") >= 8
ref_n = len(re.findall(r"view_\d+", t))
kw_hit = ("before" in t.lower() and "after" in t.lower()) or ("提速" in t)
s["comparison_report"] = 1.0 if (len(t) >= 350 and has_table and ref_n >= 3 and kw_hit) else (0.5 if len(t) >= 200 else 0.2)
else:
s["comparison_report"] = 0.0
# cross-channel co-presence
has_cli_ev = (s["baseline_plans"] > 0) and (s["table_stats"] > 0)
has_gui_ev = (s["plan_shots_present"] >= 0.4) and (s["dashboard_shots_present"] >= 0.5)
s["cross_channel_evidence"] = 1.0 if (has_cli_ev and has_gui_ev) else 0.0
# VLM rubric (4)
if vlm_score_rubric:
all_shots = plan_shots + dash_shots + after_shots + ["view_10_pgadmin_dashboard_after.png"]
sample = [str(rd/n) for n in all_shots if (rd/n).exists()][:4]
if sample:
rubric = {
"vlm_graphical_plan_real": "至少一张截图清晰显示 pgAdmin Graphical EXPLAIN plan tree(节点 + 颜色编码 + 节点连线)",
"vlm_dashboard_curves": "view_06 / view_10 中能看到 Server activity 真实折线图(多条曲线 + 时间轴),不是空白页",
"vlm_index_scan_after": "view_08 中能看到 Index Scan / Bitmap 节点替代了原 Seq Scan",
"vlm_object_explorer_indexes": "view_01 / view_09 至少一张能看到 Object Explorer 中 orders 表的 Indexes 子节点 + 右侧 Properties 显示索引 Definition",
}
vlm = vlm_score_rubric(sample, rubric,
instruction="评估 pgAdmin 4 慢查询诊断 + 索引优化 GUI 截图。")
for k in rubric:
s[k] = vlm.get(k, 0.0)
s["judge_method"] = vlm.get("judge_method", "failed")
# ---- 加权聚合:核心交付 60% / GUI 证据 30% / 辅助 10% ----
core_keys = ["baseline_plans","baseline_times","optimization_plan",
"create_indexes","optimized_index_scan","speedup",
"comparison_report"]
gui_keys = ["plan_shots_present","plan_shots_ocr","plan_shots_diversity",
"dashboard_shots_present","dashboard_shots_ocr",
"after_shots_present","after_shots_ocr",
"dashboard_after_shot","dashboard_before_after_diff"]
aux_keys = ["compose_artifacts","table_stats","index_stats",
"cross_channel_evidence"]
def _avg(keys):
vs = [float(s[k]) for k in keys if k in s and isinstance(s[k], (int, float))]
return sum(vs)/len(vs) if vs else 0.0
core = _avg(core_keys)
gui = _avg(gui_keys)
aux = _avg(aux_keys)
base = 0.6*core + 0.3*gui + 0.1*aux
# VLM 子分单独纳入(如有),与上面 base 平均
vlm_keys = [k for k in s if k.startswith("vlm_")]
vlm_avg = None
if vlm_keys:
vlm_avg = sum(float(s[k]) for k in vlm_keys) / len(vlm_keys)
base = 0.7*base + 0.3*vlm_avg
else:
# 无 VLM 时上限 0.6(不能让无 VLM 也满分)
base = min(base, 0.6)
# ---- Hard gates(多层)----
# 核心:CLI / GUI 证据缺一即重创
if not has_cli_ev:
base = min(base, 0.35)
if not has_gui_ev:
base = min(base, 0.35)
# optimization_plan 不达 5 条 → cap 0.45
if s.get("optimization_plan", 0) < 1.0:
base = min(base, 0.5 if s.get("optimization_plan", 0) >= 0.6 else 0.45)
# 索引复验:5/5 才能拿满;< 0.6 直接重罚
if s.get("optimized_index_scan", 0) < 0.6:
base = min(base, 0.45)
if s.get("optimized_index_scan", 0) < 0.4:
base = min(base, 0.35)
# 提速 < 50% → cap 0.55;< 30% → cap 0.45
if s.get("speedup", 0) < 1.0:
base = min(base, 0.55)
if s.get("speedup", 0) < 0.4:
base = min(base, 0.45)
# CREATE INDEX < 3 条 → cap 0.5
if s.get("create_indexes", 0) < 1.0:
base = min(base, 0.5)
# GUI 截图严苛 gate:5+2+2+1=10 张关键截图,真截图比例 < 70% → cap 0.45
real_present_avg = (s.get("plan_shots_present",0)*5
+ s.get("dashboard_shots_present",0)*2
+ s.get("after_shots_present",0)*2
+ s.get("dashboard_after_shot",0)) / 10.0
if real_present_avg < 0.7:
base = min(base, 0.45)
# 截图 OCR:plan + dashboard 任一全失败 → cap 0.5
if s.get("plan_shots_ocr", 0) < 0.4 or s.get("dashboard_shots_ocr", 0) < 0.4:
base = min(base, 0.5)
# 截图多样性:5 张 plan 至少 4 个不同 md5
if s.get("plan_shots_diversity", 0) < 0.8:
base = min(base, 0.5)
# Dashboard 前后必须不同
if s.get("dashboard_after_shot", 0) > 0 and s.get("dashboard_before_after_diff", 0) == 0:
base = min(base, 0.5)
# comparison_report 不达标 → cap 0.55
if s.get("comparison_report", 0) < 1.0:
base = min(base, 0.6 if s.get("comparison_report", 0) >= 0.5 else 0.5)
# VLM 多层 cap
if vlm_avg is not None:
if vlm_avg < 0.7:
base = min(base, 0.65)
if vlm_avg < 0.5:
base = min(base, 0.5)
if vlm_avg < 0.3:
base = min(base, 0.35)
s["core_subscore"] = float(core)
s["gui_subscore"] = float(gui)
s["aux_subscore"] = float(aux)
s["overall_score"] = float(max(0.0, min(1.0, base)))
return s
```
## Workspace Path
```
workspace/OPS/task_2_postgres_explain_pgadmin
```
## Skills
```
```
## Env
```
```
## Warmup
```bash
set +e
echo password | sudo -S -p '' bash -c 'export DEBIAN_FRONTEND=noninteractive
apt-get update -qq || true
apt-get install -y -qq postgresql postgresql-client postgresql-contrib jq python3-pip curl gnupg lsb-release || true
# pgAdmin4-web from official repo
install -d /etc/apt/keyrings || true
curl -fsSL https://www.pgadmin.org/static/packages_pgadmin_org.pub | gpg --dearmor -o /etc/apt/keyrings/pgadmin.gpg 2>/dev/null || true
echo "deb [signed-by=/etc/apt/keyrings/pgadmin.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list || true
apt-get update -qq || true
apt-get install -y -qq pgadmin4-web || apt-get install -y -qq pgadmin4-desktop || true
# GUI app fallback (browser to view pgAdmin web UI)
which chromium-browser >/dev/null 2>&1 || apt-get install -y -qq chromium-browser || apt-get install -y -qq firefox-esr || true
# start postgres service
service postgresql start 2>/dev/null || pg_ctlcluster 14 main start 2>/dev/null || true
# wait for postgres readiness (sync, up to 60s)
for i in $(seq 1 60); do pg_isready -h 127.0.0.1 -p 5432 >/dev/null 2>&1 && break; sleep 1; done
su - postgres -c "psql -c \"CREATE USER pguser WITH PASSWORD '"'"'pgpass'"'"' SUPERUSER;\"" 2>/dev/null || true
su - postgres -c "psql -c \"CREATE DATABASE pgbench OWNER pguser;\"" 2>/dev/null || true
mkdir -p /tmp_workspace/results/baseline_plans /tmp_workspace/results/optimized_plans /tmp_workspace/gt || true
chown -R user:user /tmp_workspace/results /tmp_workspace/gt 2>/dev/null || true
# OCR / vision deps for grader
apt-get install -y -qq tesseract-ocr || true
pip install -q pytesseract pillow numpy || true
# verify pgadmin entry exists; if missing, leave a marker for the agent
(which pgadmin4 >/dev/null 2>&1 || ls /usr/pgadmin4/bin/setup-web.sh >/dev/null 2>&1) || echo "pgadmin4 not installed — agent should retry install" > /tmp_workspace/pgadmin_missing.flag
echo "PostgreSQL+pgAdmin native install done" > /tmp_workspace/install.done
' >/tmp_workspace/install.log 2>&1 || true
true
```
|