id: OPS_task_2_postgres_explain_pgadmin
name: Postgres 慢查询闭环:psql EXPLAIN + pgAdmin Graphical Plan + Dashboard 实时图 + 索引优化复验
category: OPS
timeout_seconds: 1500
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
queriesarray with at least 5 entries. - Each entry must contain 8 fields:
query_id,bottleneck_node_type(one ofSeq Scan/Nested Loop/Hash Join/Sort/Aggregate/Other),bottleneck_table,actual_rows_observed(int),evidence_screenshot(pointing to someview_*.png),evidence_explain_json(pointing tobaseline_plans/qN.json),proposed_index_ddl(a validCREATE INDEX ...),expected_node_after(one ofIndex 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):
- 推荐通道:GUI 走 pgAdmin 4 Web(原生装在 VM 内,地址通常为
http://localhost/pgadmin4,首次需sudo /usr/pgadmin4/bin/setup-web.sh --yes设置邮箱密码);CLI 走psql。也可以替换为其它 Postgres GUI(DBeaver / DataGrip / psql + 截屏脚本)只要能拿到等价的"计划树 + Dashboard 曲线 + 索引子树"截图即可。 - 启动与就绪:用
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。 - 抓基线:对
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。 - 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。 - 综合分析:基于 EXPLAIN JSON 与计划树截图填
optimization_plan.json,确定每条 Q 的瓶颈节点与建议索引;把所有 DDL 汇到create_indexes.sql并真在 DB 上执行。 - 复验:再跑
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。 - 撰写
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
-
compose_up.log/ready_ts.txt/schema_load.log存在
-
baseline_plans/q1..q5.json全部为合法 JSON
-
baseline_times.csv含 5 行 + 列名匹配
-
view_01..view_055 张 pgAdmin Object Explorer + Graphical Plan 截图 + OCR
-
view_06/view_07pgAdmin 4 Dashboard 截图(活动曲线 + Sessions/Locks 子表)+ OCR
-
table_stats.txt含 seq_scan /index_stats.txt含 idx_scan
-
optimization_plan.json≥ 5 条 + 每条 schema 完整
-
create_indexes.sql≥ 3 条 CREATE INDEX
-
optimized_plans/q1..q5.json全部含 Index Scan/Bitmap
-
view_08/view_09单条复验截图
-
optimized_times.csv平均提速 ≥ 50%
-
view_10Dashboard 复验截图
-
comparison_report.md≥ 350 字 + 含表格 + 引 ≥ 3 张截图
-
- VLM 验:pgAdmin 4 Graphical Plan 节点颜色 / Dashboard 真实曲线 / Index Scan after / Object Explorer Indexes 子树
Automated Checks
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
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