File size: 21,324 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 | ---
id: WEB_task_15_sourcemap_stack_decode
name: 生产 stack trace × 失效 sourcemap 取证 × 重生成
category: WEB
timeout_seconds: 1800
---
## Prompt
Task background: a small production SPA at `http://127.0.0.1:8200/` throws a `TypeError` when the user clicks the "Crash" button. SRE has already captured the minimized stack trace locations of that crash into `/tmp_workspace/exec/error.log`, one frame per line in the format `BUNDLE LINE COL`, three frames total (`feature.bundle.js`, `app.bundle.js`, `vendor.bundle.js`).
The three `*.bundle.js` + `*.bundle.js.map` pairs under `/tmp_workspace/exec/dist/` are the deployed build. `src/` is the current trunk source. **Only one bundle's map is stale** — its `sourcesContent` embeds an old version that is several lines shorter than the current `src/`, so the source line it decodes to is not the actual line that threw. The two signal channels for detecting this staleness — "a source line in `sourcesContent` that looks unrelated to the crash" and "structural mismatch between `sourcesContent` line count and `src/<name>.js` line count" — must both be exercised: on the script side, decode the three frames and cross-check against `src/`; in the browser source forensics view, hover the failing frame and inspect the source line it actually jumps to.
Materials already prepared on site:
- Target page: `http://127.0.0.1:8200/` (warmup starts it automatically; click "Crash" to trigger the `TypeError`).
- Three-frame stack trace input: `/tmp_workspace/exec/error.log` (`BUNDLE LINE COL`, three lines).
- Deployed artifacts: `/tmp_workspace/exec/dist/{vendor,app,feature}.bundle.js{,.map}` (in **exactly one** of these maps, `sourcesContent[0]` differs in line count from the corresponding `src/<name>.js` by > 4).
- Current trunk source: `/tmp_workspace/exec/src/{vendor,app,feature}.js`.
- Helpers (the agent may reuse them directly or rewrite them):
- `/tmp_workspace/exec/tools/decode.py`: pure-stdlib sourcemap decoder. Takes `error.log` plus a set of `.map` files and outputs a JSON array of `{input, decoded:{source, line, source_line_text, ...}}` per frame.
- `/tmp_workspace/exec/tools/build_map.py`: pure-stdlib sourcemap regenerator. Three arguments `<src.js> <bundle.js> <out.map>`; rewrites `.map.sourcesContent[0]` from the current `src/`.
Goal: identify the bundle name that is actually stale → use `build_map.py` to regenerate its map → verify that after re-decoding, the frame in question now resolves to the real throw site. How to launch the browser, how to cross-check source lines, and how to invoke the helpers are up to you.
The following deliverables must be produced under `/tmp_workspace/results/`:
1. **Pre-fix decode** `decoded_before.json`: array of decode results for `error.log` × the three `.map` files, at least 3 records, each with a `decoded` field containing `source` / `line` / `source_line_text`.
2. **Stale bundle name** `stale_bundle.txt`: a single line containing the basename of the truly stale bundle (e.g. `feature.bundle.js`). The named bundle must actually exist in `dist/`, and its `.map.sourcesContent[0]` line count must differ from the current `src/<name>.js` line count by > 4.
3. **Map integrity comparison** `map_validation.json`:
```json
{
"vendor": {"src_lines": <int>, "map_sourcesContent_lines": <int>, "match": <bool>},
"app": {"src_lines": <int>, "map_sourcesContent_lines": <int>, "match": <bool>},
"feature": {"src_lines": <int>, "map_sourcesContent_lines": <int>, "match": <bool>}
}
```
Exactly one entry must have `match == false` (the same one named in `stale_bundle.txt`).
4. **Diagnosis report** `diagnosis.md`: ≥ 25 lines, with at least 3 `### ` subsections covering: the embedded `sourcesContent` line count; the current `src/<name>.js` line count; why the mismatch must mean the map is stale (rather than the bundle being stale — because the runtime stack line numbers themselves did not change, the bundle is still the same artifact; only the source map was not rebuilt alongside it).
5. **Visual forensic screenshots** (each ≥ 4 KB, from actual rendered state):
- `view_01_console_stack.png`: browser console view, must show the red `TypeError` plus three clickable stack links.
- `view_02_sources_stale_frame.png`: browser source forensics view; the left file tree highlights the `*.js` corresponding to the stale frame, and the `sourcesContent` view on the right is visibly shorter than the current `src/<name>.js`, with the highlighted line's contents not matching the real `src/`.
- `view_03_sources_correct_frame.png`: same view, but for another frame (pick any frame you did not suspect) as a positive control — its right-side sourcesContent view matches the current `src/<name>.js`.
- `view_04_after_fix_stack.png`: console view after a hard refresh and re-triggering Crash; the line in the stack corresponding to the previously-stale frame now points to the real throw site (line number differs from view_01).
6. **Regenerate the map**: use `tools/build_map.py` to rewrite `dist/<stale-bundle-base>.bundle.js.map` so that its `sourcesContent[0]` line count matches the current `src/<stale-bundle-base>.js` line count (tolerance ≤ 2).
7. **Post-fix decode** `decoded_after.json`: run `tools/decode.py` again to produce the decode result array for `error.log` × the three `.map` files (including the regenerated one). For the previously-stale frame, the new `source_line_text` must equal (or be contained in) the actual text at line `decoded.line` of the current `src/<name>.js`.
Hard constraints:
- `stale_bundle.txt` must name the actually stale bundle (determined by `sourcesContent` line-count diff > 4).
- `map_validation.json` must have exactly one entry with `match == false`.
- After regeneration, the stale bundle's `.map.sourcesContent[0]` line count must match the current `src/<name>.js` line count (tolerance ≤ 2).
- You may not directly edit `error.log` or `dist/*.bundle.js` — the decode results must align only via map regeneration.
## Expected Behavior
一个合格的解答会在 `/tmp_workspace/results/` 留下一条互相印证的取证链:
- 一份修复前 `decoded_before.json`,至少包含三帧 decode 结果,且其中一帧的 `source_line_text` 与当前 `src/<name>.js` 在该 `line` 上的真实内容显著对不上。
- 一份 `stale_bundle.txt` 写明失效 bundle 的基名 + 一份 `map_validation.json` 恰有一项 `match == false`,二者指向同一份 bundle。
- `diagnosis.md`(≥ 25 行 + ≥ 3 个 `### ` 子小节)解释:`sourcesContent` 行数与当前源行数对不上为什么意味着 map stale;为何这种问题在外部数字上看不到、必须对照源端字节去发现。
- 4 张截图:控制台 TypeError + 三链;源码取证视图里失效帧 sourcesContent 行数明显偏少且内容对不上;同视图里另一帧作为正向对照(行数 + 内容对得上);硬刷新重 crash 后控制台 stack 中对应那一行已经指向真实抛错处。
- 用 `build_map.py` 重生 map 之后,`decoded_after.json` 中之前的失效帧 `source_line_text` 在 `decoded.line` 行上能与当前 `src/<name>.js` 对得上(grader 会做严格/包含两级匹配)。
整套交付应让一位审阅者无须重跑就能判断:根因是 map 没跟着 bundle 一起 rebuild、定位是通过同时查 sourcesContent 行数差与源码取证视图、修复严格在 sourcemap 层完成、修复后 stack trace 真正指向产生 TypeError 的那一行。
## Source
- Source Maps v3 spec — https://sourcemaps.info/spec.html
- Sentry blog — “Stale source maps cause us to debug the wrong line of code”
- Webpack issue #3603(sourcemap drift after partial rebuild)
## Grading Criteria
- [ ] 1. `decoded_before.json` 含 3 条记录 + 每条有 `decoded.source`。
- [ ] 2. `decoded_before.json` 至少有一帧的 `source_line_text` 与当前同名 `src/*.js` 对应行内容不一致。
- [ ] 3. `stale_bundle.txt` 标识出真正失效的 bundle。
- [ ] 4. `map_validation.json` 字段齐全,且唯一一帧 `match == false`。
- [ ] 5. `diagnosis.md` ≥ 25 行 + ≥ 3 个 `### ` 子小节。
- [ ] 6. 4 张 GUI 截图齐全 + OCR 命中 `Sources|Console|TypeError|\.js|Stack|bundle`。
- [ ] 7. 重生后失效 bundle 的 `.map.sourcesContent[0]` 行数与对应 `src/*.js` 一致(误差 ≤ 2)。
- [ ] 8. `decoded_after.json` 里之前的失效帧 `source_line_text` 含真实抛错处关键 token,且 `decoded.source` 指向同名 `src/*.js`。
- [ ] 9. VLM rubric:DevTools Sources/Console 真打开 + 修复前后能对比。
## Automated Checks
```python
def grade(workspace_path=None, **kwargs) -> dict:
"""Sourcemap stack decode grader (12 sub-scores + 3 hard gates)."""
import json, re
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
rd = Path("/tmp_workspace/results")
exec_root = Path("/tmp_workspace/exec")
s = {}
def _read(p):
try:
return p.read_text(errors="ignore")
except Exception:
return ""
# 1. decoded_before.json structure
db = {}
try:
db = json.loads(_read(rd / "decoded_before.json"))
except Exception:
db = {}
if isinstance(db, list) and len(db) >= 3:
s["decoded_before_count"] = 1.0
elif isinstance(db, list) and db:
s["decoded_before_count"] = 0.5
else:
s["decoded_before_count"] = 0.0
# 2. BEFORE: at least one frame must show a stale signal (decoded
# source line text disagrees with the current src file at decoded
# line — proof the agent identified a real mismatch).
stale_evidence = 0.0
if isinstance(db, list):
for ent in db:
if not isinstance(ent, dict):
continue
d = ent.get("decoded") or {}
src_name = (d.get("source") or "").split("/")[-1]
line = d.get("line")
text = (d.get("source_line_text") or "").strip()
if not src_name or not line or not text:
continue
cur_src = exec_root / "src" / src_name
if not cur_src.exists():
continue
try:
cur_lines = cur_src.read_text().splitlines()
except Exception:
continue
if 1 <= line <= len(cur_lines):
cur_text = cur_lines[line - 1].strip()
if cur_text and text and cur_text != text:
stale_evidence = 1.0
break
s["before_shows_stale"] = stale_evidence
# 3. stale_bundle.txt names a real bundle that exists in dist/
stale_txt = _read(rd / "stale_bundle.txt").strip().lower()
bundle_basenames = []
dist = exec_root / "dist"
if dist.exists():
bundle_basenames = [p.name.lower() for p in dist.glob("*.bundle.js")]
first_tok = (stale_txt.splitlines() or [""])[0].strip().strip('"').strip("'")
named_real = first_tok in {b for b in bundle_basenames} \
or first_tok in {b.split(".")[0] for b in bundle_basenames}
# Cross-check: the named bundle should also be the one whose
# sourcesContent length disagrees with current src.
truly_stale = None
for bj in bundle_basenames:
base = bj.split(".")[0]
mp = dist / f"{base}.bundle.js.map"
sp = exec_root / "src" / f"{base}.js"
if mp.exists() and sp.exists():
try:
mj = json.loads(mp.read_text())
sc = (mj.get("sourcesContent") or [""])[0] or ""
if abs(len(sc.splitlines())
- len(sp.read_text().splitlines())) > 4:
truly_stale = base
break
except Exception:
pass
matches_truth = (truly_stale is not None
and first_tok in (truly_stale, f"{truly_stale}.bundle.js"))
if matches_truth:
s["stale_bundle_named"] = 1.0
elif named_real:
s["stale_bundle_named"] = 0.5
else:
s["stale_bundle_named"] = 0.0
# 4. map_validation.json: any frame must be marked match=false
mv = {}
try:
mv = json.loads(_read(rd / "map_validation.json"))
except Exception:
mv = {}
falsy = [k for k, v in (mv.items() if isinstance(mv, dict) else [])
if isinstance(v, dict) and v.get("match") is False]
exactly_one = (len(falsy) == 1)
points_to_truth = (truly_stale is not None
and exactly_one and falsy[0].lower().startswith(truly_stale))
s["map_validation"] = (1.0 if points_to_truth
else 0.5 if exactly_one
else 0.2 if falsy else 0.0)
# 5. diagnosis.md depth
diag = _read(rd / "diagnosis.md")
diag_lines = len([ln for ln in diag.splitlines() if ln.strip()])
diag_subs = len(re.findall(r"(?m)^###\s+\S", diag))
diag_lower = diag.lower()
needed = ["sourcescontent", "line", "stale", "rebuild", truly_stale or "feature"]
hits = sum(1 for w in needed if w in diag_lower)
s["diagnosis_depth"] = (
1.0 if (diag_lines >= 25 and diag_subs >= 3 and hits >= 4)
else 0.5 if (diag_lines >= 18 and diag_subs >= 2 and hits >= 3)
else 0.0
)
# 6. GUI screenshots
shots = [
"view_01_console_stack.png",
"view_02_sources_stale_frame.png",
"view_03_sources_correct_frame.png",
"view_04_after_fix_stack.png",
]
present = sum(1 for n in shots if (rd / n).exists())
s["gui_screens_present"] = present / len(shots)
ocr_re = re.compile(r"(TypeError|sourcesContent|DevTools|Sources panel|at\s+\w+\s*\()", re.I)
per_shot = {"view_01_console_stack.png": re.compile(r"TypeError", re.I),
"view_02_sources_stale_frame.png": re.compile(r"sourcesContent|Sources", re.I),
"view_04_after_fix_stack.png": re.compile(r"TypeError", re.I)}
ocr_hits = 0
if pytesseract and Image:
for n in shots:
p = rd / n
if p.exists():
try:
tx = pytesseract.image_to_string(Image.open(p))
needed_re = per_shot.get(n)
if needed_re is not None:
if needed_re.search(tx):
ocr_hits += 1
elif ocr_re.search(tx):
ocr_hits += 1
except Exception:
pass
s["gui_screens_ocr"] = ocr_hits / len(shots)
else:
s["gui_screens_ocr"] = 0.0
# 7. After-fix: the bundle the agent named should now have its map's
# sourcesContent[0] line count match the current src file.
diff = None
target_base = None
for bj in bundle_basenames:
base = bj.split(".")[0]
if base in stale_txt:
target_base = base
break
if target_base is None and truly_stale:
target_base = truly_stale
if target_base:
sp = exec_root / "src" / f"{target_base}.js"
mp = exec_root / "dist" / f"{target_base}.bundle.js.map"
if sp.exists() and mp.exists():
try:
cur_lines = len(sp.read_text().splitlines())
mj = json.loads(mp.read_text())
sc = (mj.get("sourcesContent") or [""])[0] or ""
diff = abs(cur_lines - len(sc.splitlines()))
except Exception:
diff = None
if diff is None:
s["map_regenerated"] = 0.0
else:
s["map_regenerated"] = 1.0 if diff <= 2 else 0.4 if diff <= 8 else 0.0
# 8. decoded_after.json: the previously-stale frame now decodes to
# a source line whose text matches the current src/<name>.js at the
# decoded line number.
da = {}
try:
da = json.loads(_read(rd / "decoded_after.json"))
except Exception:
da = {}
after_ok = 0.0
if isinstance(da, list) and target_base:
for ent in da:
if not isinstance(ent, dict):
continue
if target_base not in str(ent.get("input", "")):
continue
d = ent.get("decoded") or {}
src = (d.get("source") or "").split("/")[-1]
line = d.get("line")
text = (d.get("source_line_text") or "").strip()
if src == f"{target_base}.js" and line and text:
cur_src = exec_root / "src" / src
if cur_src.exists():
cur_lines = cur_src.read_text().splitlines()
if 1 <= line <= len(cur_lines):
gt_token = "crashHere"
if cur_lines[line - 1].strip() == text and gt_token in text:
after_ok = max(after_ok, 1.0)
elif gt_token in text and text in cur_lines[line - 1]:
after_ok = max(after_ok, 0.6)
else:
after_ok = max(after_ok, 0.0)
s["after_decodes_correct"] = after_ok
# 9. VLM rubric
sample = [str(rd / n) for n in shots if (rd / n).exists()][:4]
if vlm_score_rubric and sample:
rubric = {
"vlm_devtools_real": "至少一张截图清晰显示 Chrome DevTools 真实 UI(左 Files / 右 Sources 编辑器,或顶部 Console 面板)",
"vlm_stack_visible": "至少一张截图能看到 TypeError 或 stack trace(红色错误链接)",
"vlm_before_after": "view_04 与 view_01 能体现修复前后差异(行号或源文件指向变化)",
}
try:
vlm = vlm_score_rubric(sample, rubric,
instruction="评估 sourcemap mismatch 调试的 DevTools 截图证据。")
except Exception:
vlm = {}
for k in rubric:
s[k] = vlm.get(k, 0.0)
s["judge_method"] = vlm.get("judge_method", "failed")
vlm_avg = sum(vlm.get(k, 0) for k in rubric) / len(rubric) if vlm else 0.0
else:
vlm_avg = 0.3
# base
numerics = [v for k, v in s.items()
if isinstance(v, (int, float)) and k != "judge_method"]
base = sum(numerics) / max(1, len(numerics))
overall = round((base + vlm_avg) / 2.0, 3) if vlm_score_rubric else round(base, 3)
# hard gates
has_cli_evidence = (
(rd / "decoded_before.json").exists()
and (rd / "decoded_after.json").exists()
and (rd / "diagnosis.md").exists()
)
has_gui_screenshot = present >= 2
if not has_cli_evidence:
overall = round(min(overall, 0.4), 3)
# GUI-path scoring axis removed: missing screenshots already cost
# the screenshots / OCR / vlm_* sub-scores.
if vlm_score_rubric and vlm_avg < 0.6:
overall = round(min(overall, 0.45), 3)
s["overall_score"] = overall
return s
```
## Workspace Path
```
workspace/WEB/task_15_sourcemap_stack_decode
```
## Skills
```
```
## Env
```
```
## Warmup
```bash
mkdir -p /tmp_workspace/results /tmp_workspace/state /opt/web15_gt && chmod 777 /tmp_workspace/results /tmp_workspace/state
if [ -f /tmp_workspace/gt/expected.json ]; then
mv /tmp_workspace/gt/expected.json /opt/web15_gt/expected.json 2>/dev/null || cp /tmp_workspace/gt/expected.json /opt/web15_gt/expected.json 2>/dev/null || true
chown -R root:root /opt/web15_gt 2>/dev/null || true
chmod 700 /opt/web15_gt 2>/dev/null || true
chmod 600 /opt/web15_gt/expected.json 2>/dev/null || true
rm -rf /tmp_workspace/gt 2>/dev/null || true
fi
which curl || (for i in 1 2 3 4 5; do apt-get -o Acquire::Retries=10 update -qq && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=10 install -y -qq --fix-missing curl ca-certificates && break; sleep 5; done) || true
which jq || (for i in 1 2 3 4 5; do apt-get -o Acquire::Retries=10 update -qq && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=10 install -y -qq --fix-missing jq && break; sleep 5; done) || true
which python3 || (for i in 1 2 3 4 5; do apt-get -o Acquire::Retries=10 update -qq && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=10 install -y -qq --fix-missing python3 python3-pip && break; sleep 5; done) || true
which tesseract || (for i in 1 2 3 4 5; do apt-get -o Acquire::Retries=10 update -qq && DEBIAN_FRONTEND=noninteractive apt-get -o Acquire::Retries=10 install -y -qq --fix-missing tesseract-ocr fonts-noto-cjk && break; sleep 5; done) || true
pip3 install --break-system-packages --ignore-installed --quiet blinker 2>/dev/null || pip3 install --ignore-installed --quiet blinker || true
pip3 install --break-system-packages --quiet flask pillow pytesseract requests sourcemap 2>/dev/null || pip3 install --quiet flask pillow pytesseract requests sourcemap || true
chmod +x /tmp_workspace/start.sh 2>/dev/null || true; chmod +x /tmp_workspace/tools/*.py 2>/dev/null || true
nohup bash /tmp_workspace/start.sh >/tmp/start.log 2>&1 & sleep 3; for i in $(seq 1 30); do curl -sf http://localhost:8200/ >/dev/null && break; sleep 1; done
```
|