From 3994f6b038acf6cde64ee8e69e5e0acdd94e5e7e Mon Sep 17 00:00:00 2001 From: zhaozhaozz <6450679+zhaozhaozz@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:00:57 +0000 Subject: [PATCH] fix(dashboard): keep execution tables separate by producer group --- docs/test-reports.md | 14 +++++++++ gsb/incremental_project.py | 9 +++++- gsb/public_sections.py | 3 +- gsb/reports.py | 33 ++++++++++++++++++-- gsb/sync.py | 2 +- static/app.js | 23 +++++++++++--- static/style.css | 3 ++ test/journey-summary-table.spec.cjs | 31 +++++++++++++++++++ test/prepare-site.py | 21 +++++++++++++ tests/test_incremental.py | 22 ++++++++++++++ tests/test_reports.py | 47 +++++++++++++++++++++++++++++ 11 files changed, 199 insertions(+), 9 deletions(-) diff --git a/docs/test-reports.md b/docs/test-reports.md index deebd6a24..37015bd69 100644 --- a/docs/test-reports.md +++ b/docs/test-reports.md @@ -42,6 +42,20 @@ Actions 产物名使用 `ut-results`、`st-results`、`e2e-results`、`real-e2e- 5. `run.log`:兼容现有 CI 的 TAP / unittest / pytest 汇总,作为没有结构化报告时的后备来源。 6. Real E2E 评分:从 `benchmark-metrics.json`、`team-metrics.json`、`evolve-metrics.json` 分别读取 DeepResearchBench、BiomniBench、Research Team 和 PUCT Compression 的原生分数、交付状态与耗时。看板不统一不同评分器的量纲,也不设置质量通过门槛;prompt、原始响应、错误详情和凭据不会进入公开快照。 +### 通用执行表与分组 + +任意仓库的 `dashboard-summary.json` 都可以附带 `table`,列顺序由 `columns` 声明,格子由生产者写成最终字符串。看板只转义并显示,不按仓库、产物名、列名解释或重算数字: + +```json +{"tests":2,"passed":1,"failed":1,"skipped":0,"flaky":0,"table":{"title":"Service probes","group":{"key":"smoke","label":"L3 · smoke"},"columns":[{"key":"probe","label":"Probe"}],"rows":[{"probe":"probe-a"},{"probe":"probe-b"}]}} +``` + +`group` 是可选的通用分组身份,`key` 与 `label` 均为非空字符串。生产者可以用它区分测试层级、执行策略等;例如分别声明 L3、L4、L5,看板不会从工作流名或用例数猜层级。没有分组的旧表显示为「未分组(旧报告)」;没有表格的旧 summary 继续只提供计数。 + +E2E 页提供分组筛选,每个分组、每个产物名保留最近有表格的运行,分别标明 run、SHA、attempt、分支和该表计数。各组不累加,后来的同名无表格产物不会遮住已有表格;展示的是最近有表格的运行,不保证它就是整仓最新的一次 CI。增量快照从所属分支线的完整已采集历史选表,不受最近 100 次运行窗口影响。同一 run 只认最新 attempt,最新 attempt 没有表时不会挪用它的旧 attempt。 + +### 评分与计数 + Real E2E 的简化分数与运行耗时随每次 run / attempt 保存在看板历史记录中。E2E 页按分支线、用例 ID 汇总最近 30 次有记录的运行;同一 run 重跑只采用最新 attempt;每个北京日取一次运行,手动或触发式优先,但只在最新 attempt 有可读 `real-e2e-results` 评分的运行中挑选,仍在运行或产物不可读的运行不会挡掉当天已读到的结果;缺失指标或耗时留空,不当作 0。E2E 页在每个用例下直接画出这些点的全部曲线,不需要打开弹窗。历史只从已采集的产物累积,无法用最新结果推造过去的趋势。 同一产物内只取一种报告格式,优先级为 summary、Playwright、标签化 summary、JUnit、log。分片产物必须互不重叠,避免同时上传同一层的合并报告和分片。用例数按报告中的测试实例(包含浏览器项目)计数,不是测试文件数;重试不重复计数。稳定通过率 = passed / tests;skipped 和 flaky 单列,不计稳定通过。零用例不显示 100%。 diff --git a/gsb/incremental_project.py b/gsb/incremental_project.py index 280eecd5e..b991b03f1 100644 --- a/gsb/incremental_project.py +++ b/gsb/incremental_project.py @@ -13,9 +13,10 @@ from .work_trend import daily_trend from .public_sections import public_ops, public_tests, score_history, daily_score_runs, latest_score_report, envelope from .sync import stamp, date +from .reports import summary_tables -SUPPLEMENT_TESTS_VERSION = 7 +SUPPLEMENT_TESTS_VERSION = 8 COVERAGE_TIMEZONE = ZoneInfo("Asia/Shanghai") COVERAGE_GATE_JOBS = ("Gate / UT", "Gate / ST", "Gate / Coverage") @@ -324,6 +325,12 @@ def coverage_owner(artifact): if tests.get("data"): # Refresh test metrics without re-fetching the repository tree/Codecov. tests["data"]["executed"] = _executed(runs) + # Tables are independent observations per producer group, not the + # latest same-name artifact. Read durable history so busy CI cannot + # push a less frequent group out of the 100-run current window. + table_runs = history.select("runs", lambda r, key=key: run_line.get(r["id"]) == key + and r["attempt"] == index[r["id"]]["attempt"]) + tests["data"]["summary_tables"] = summary_tables(table_runs) daily = history.select("runs", lambda r, key=key: r.get("channel") == "daily" and run_line.get(r["id"]) == key, limit=120) # The current CI window is capped at 100 runs and can lose yesterday's diff --git a/gsb/public_sections.py b/gsb/public_sections.py index 12e9ab6d1..bdd277a90 100644 --- a/gsb/public_sections.py +++ b/gsb/public_sections.py @@ -10,6 +10,7 @@ from .github import GitHubError from .testparse import summarize_tree, package_of from .real_e2e_definitions import definition as real_e2e_definition +from .reports import summary_tables def _score_with_definition(score): @@ -262,7 +263,7 @@ def public_tests(ctx, runs, owns=None, coverage_eligible=None): break return {'notes': notes, 'tree_source': source, 'tree': {k: v for k, v in tree.items() if k != 'inventory'} if tree else None, 'inventory': [{**row, 'ci_cases': package_counts.get(row['package'], {}).get('tests'), 'ci_failed': package_counts.get(row['package'], {}).get('failed')} for row in (tree or {}).get('inventory', [])], - 'test_scripts': scripts, 'artifacts_recent': artifacts[:30], 'executed': executed, + 'test_scripts': scripts, 'artifacts_recent': artifacts[:30], 'executed': executed, 'summary_tables': summary_tables(runs), 'score_history': score_history(runs), 'score_report': latest_score_report(runs), 'coverage': coverage} diff --git a/gsb/reports.py b/gsb/reports.py index 2d89759cd..62a68a0db 100644 --- a/gsb/reports.py +++ b/gsb/reports.py @@ -268,8 +268,37 @@ def summary_table(value): if any(not isinstance(row, dict) or any(not isinstance(row.get(key), str) for key in keys) for row in rows): return None # Ignore undeclared cells and metadata, just as we omit raw report payloads. - return {"title": value["title"], "columns": [{"key": c["key"], "label": c["label"]} for c in columns], - "rows": [{key: row[key] for key in keys} for row in rows]} + table = {"title": value["title"], "columns": [{"key": c["key"], "label": c["label"]} for c in columns], + "rows": [{key: row[key] for key in keys} for row in rows]} + group = value.get("group") + if isinstance(group, dict) and all(isinstance(group.get(k), str) and group[k].strip() for k in ("key", "label")): + table["group"] = {k: group[k] for k in ("key", "label")} + return table + + +def summary_tables(runs): + """Latest table per producer group/artifact, independent of counts-only reports.""" + attempts = {} + for run in runs: + attempts[run["id"]] = max(attempts.get(run["id"], 0), run.get("attempt", 1)) + selected = {} + for run in sorted(runs, key=lambda r: (r.get("updated_at") or r.get("created_at") or "", r["id"]), reverse=True): + if run.get("attempt", 1) != attempts[run["id"]]: + continue + for report in run.get("tests", []): + table = report.get("table") + if not table: + continue + identity = ((table.get("group") or {}).get("key", ""), report["name"]) + if identity in selected: + continue + selected[identity] = { + "artifact": report["name"], "table": table, "totals": report.get("counts"), + "run_id": run["id"], "sha": run.get("sha"), "attempt": run.get("attempt", 1), + "branch": run.get("branch"), "created_at": report.get("created_at") or run.get("updated_at"), + "url": report.get("url"), "run_url": run.get("url"), + } + return list(selected.values()) def parse_report_zip(blob): diff --git a/gsb/sync.py b/gsb/sync.py index 7248fcfd9..826482f69 100644 --- a/gsb/sync.py +++ b/gsb/sync.py @@ -16,7 +16,7 @@ # 2: tagged catalogs and harness summaries are read from results artifacts. # 3: Real E2E metrics are reduced to public score summaries. -PARSER_VERSION = 5 +PARSER_VERSION = 6 def stamp(value): diff --git a/static/app.js b/static/app.js index ec421a34f..31565eb61 100644 --- a/static/app.js +++ b/static/app.js @@ -1154,12 +1154,22 @@ })); } - function summaryTables(executed) { - return executed.filter(report => report.table).map(report => { + function summaryTables(reports) { + const available = reports.filter(report => report.table); + if (!available.length) return ''; + const key = report => JSON.stringify(report.table.group?.key ?? null); + const groups = new Map(available.map(report => [key(report), report.table.group?.label || '未分组(旧报告)'])); + const selected = groups.has(STATE.summaryGroup) ? STATE.summaryGroup : ''; + let html = sectionHead('用例执行表', '每组保留最近有表格的运行;各组用例数独立,不累加。'); + if (groups.size > 1) html += `
`; + return html + available.filter(report => !selected || key(report) === selected).map(report => { const {title, columns, rows} = report.table; // Cells already contain the producer's final display values. Keep both // axes in declared order and render every cell as text. - return `

${esc(title)}

${link(report.url, esc(report.artifact))} · ${date(report.created_at)} · ${esc(report.branch)}

${columns.map(column => ``).join('')}${rows.map(row => `${columns.map(column => ``).join('')}`).join('')}
${esc(column.label)}
${esc(row[column.key])}
`; + const counts = report.totals; + const countText = [['用例', 'tests'], ['通过', 'passed'], ['失败', 'failed'], ['跳过', 'skipped'], ['重试通过', 'flaky']] + .map(([label, field]) => `${label} ${n(counts?.[field])}`).join(' · '); + return `

${esc(title)}

${badge(report.table.group?.label || '未分组(旧报告)', 'info')} ${countText}

${link(report.run_url || report.url, `run #${esc(report.run_id)} / attempt ${esc(report.attempt ?? '—')}`)} · ${date(report.created_at)} · ${esc(report.branch)} · ${esc(report.sha?.slice(0, 12))} · ${link(report.url, esc(report.artifact))}

${columns.map(column => ``).join('')}${rows.map(row => `${columns.map(column => ``).join('')}`).join('')}
${esc(column.label)}
${esc(row[column.key])}
`; }).join(''); } @@ -1177,7 +1187,7 @@ { label: 'CI 最近 E2E 用例', value: n(e2e?.totals?.tests), sub: e2e?.totals ? `${e2e.totals.passed} 通过 · ${e2e.totals.failed} 失败/超时 · ${e2e.totals.skipped} 跳过 · ${e2e.totals.flaky} 重试通过` : e2e ? '产物存在但没有解析出用例数' : '无产物', tone: e2e?.totals?.failed ? 'bad' : e2e?.totals ? 'good' : '' }, ]); html += e2eRecordsSection(); - html += summaryTables(d.executed); + html += summaryTables(d.summary_tables ?? d.executed); html += realScoresSection(d.executed, d.score_history, d.score_runs, d.mock_real_e2e, d.local_artifact_preview, d.score_report); html += taggedSection(d.tagged, line); @@ -1491,6 +1501,11 @@ console.error(err); } // ------------------------------------------------------------ events + $('#tab-tests').addEventListener('change', (ev) => { + if (!ev.target.matches('[data-summary-group]')) return; + STATE.summaryGroup = ev.target.value; + renderTabs(); + }); $('#tab-tests').addEventListener('input', (ev) => { const el = ev.target.closest('[data-e2e-filter]'); if (!el) return; diff --git a/static/style.css b/static/style.css index 56741f5f0..6bfbf78f9 100644 --- a/static/style.css +++ b/static/style.css @@ -614,3 +614,6 @@ td.nowrap { white-space: nowrap; } .trend-table .table-wrap { max-height: 280px; overflow: auto; margin-top: 6px; } .trend-table th, .trend-table td { padding: 3px 10px; text-align: left; } .trend-table .num { text-align: right; font-variant-numeric: tabular-nums; } + +.summary-counts { display: inline-flex; flex-wrap: wrap; gap: 0 .3em; } +.summary-counts > span { white-space: nowrap; } diff --git a/test/journey-summary-table.spec.cjs b/test/journey-summary-table.spec.cjs index 2adaaeb1e..a8755f309 100644 --- a/test/journey-summary-table.spec.cjs +++ b/test/journey-summary-table.spec.cjs @@ -46,6 +46,7 @@ test('arbitrary column keys and order remain producer-controlled', async ({ page title: 'Sensor readings', columns: [{ key: 'opaque', label: 'Reading' }, { key: 'id', label: 'Sensor' }], rows: [{ id: 'sensor-z', opaque: '34.2K' }, { id: 'sensor-a', opaque: 'n/a' }], }; + delete doc.sections.tests.data.summary_tables; // Older snapshots use the same renderer. await route.fulfill({ response, json: doc }); }); await page.goto('/generic-summary/#tests'); @@ -58,6 +59,7 @@ test('legacy counts-only summary keeps its existing view', async ({ page }) => { await page.route('**/generic-summary/data/snapshot.json*', async route => { const response = await route.fetch(), doc = await response.json(); delete doc.sections.tests.data.executed[0].table; + delete doc.sections.tests.data.summary_tables; await route.fulfill({ response, json: doc }); }); await page.goto('/generic-summary/#tests'); @@ -65,3 +67,32 @@ test('legacy counts-only summary keeps its existing view', async ({ page }) => { await expect(page.locator('#tab-tests')).toContainText('CI 最近 E2E 用例'); await expect(page.locator('#tab-tests .tile').filter({ hasText: 'CI 最近 E2E 用例' })).toContainText('2'); }); + +for (const width of [1440, 390]) { + test(`producer groups keep separate counts and can be selected at ${width}px`, async ({ page }) => { + await page.setViewportSize({ width, height: 1000 }); + await page.goto('/tiered-summary/#tests'); + await expect(page.locator('#repo-link')).toHaveText('acme/weather-service'); + const sections = page.locator('#tab-tests .summary-table'); + await expect(sections).toHaveCount(3); + const picker = page.getByRole('combobox', { name: '表格分组' }); + for (const [key, label, count, run] of [['smoke', 'L3 · smoke', 2, 101], ['regression', 'L4 · regression', 3, 102], ['full', 'L5 · full', 4, 103]]) { + await picker.selectOption({ label }); + await expect(sections).toHaveCount(1); + await expect(sections.first()).toHaveAttribute('data-summary-group', key); + await expect(sections.locator('tbody tr')).toHaveCount(count); + await expect(sections.getByRole('cell', { name: 'failed', exact: true })).toHaveCount(1); + await expect(sections.getByRole('cell', { name: 'passed', exact: true })).toHaveCount(count - 1); + await expect(sections.locator('.summary-counts')).toHaveText(`用例 ${count} · 通过 ${count - 1} · 失败 1 · 跳过 0 · 重试通过 0`); + await expect(sections).toContainText(`run #${run} / attempt 1`); + await expect(sections.getByRole('link', { name: 'service-test-results', exact: true })).toHaveAttribute('href', + `https://github.com/acme/weather-service/actions/runs/${run}/artifacts/${run}`); + await expect(sections.locator('tbody tr').first()).toContainText(`${key}-probe`); + expect(await page.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth + 1)).toBeTruthy(); + await sections.scrollIntoViewIfNeeded(); + await sections.screenshot({ path: resolve(__dirname, `../.e2e/summary-${key}-${width}.png`) }); + } + await picker.selectOption(''); + await expect(sections).toHaveCount(3); + }); +} diff --git a/test/prepare-site.py b/test/prepare-site.py index cbc40db7a..5ef0c9a38 100644 --- a/test/prepare-site.py +++ b/test/prepare-site.py @@ -245,6 +245,27 @@ def get_text_file(self, *args): return '{}' generic['sections']['tests'] = wrap(summary_tests) export_site(root/'.e2e/site/generic-summary', generic) +# The same artifact name across three producer groups, followed by a newer +# counts-only run, exercises the full collector rather than a UI-only fixture. +tiered_runs = [] +for ident, key, label, count in [(101, 'smoke', 'L3 · smoke', 2), (102, 'regression', 'L4 · regression', 3), (103, 'full', 'L5 · full', 4)]: + grouped = json.loads(json.dumps(summary_table)) + grouped['group'] = dict(key=key, label=label) + grouped['rows'] = [dict(grouped['rows'][i % 2], ordinal=str(i + 1), probe=f'{key}-probe-{i + 1}', + state='failed' if i == 0 else 'passed') for i in range(count)] + tiered_runs.append(dict(summary_run, id=ident, sha=str(ident)[-1]*40, updated_at=f'2026-09-20T{ident-100:02}:00:00Z', + url=summary_cfg.repo_url+f'/actions/runs/{ident}', tests=[dict(summary_run['tests'][0], artifact_id=ident, + table=grouped, url=summary_cfg.repo_url+f'/actions/runs/{ident}/artifacts/{ident}', + counts=dict(tests=count, passed=count-1, failed=1, skipped=0, flaky=0))])) +latest = json.loads(json.dumps(tiered_runs[-1])) +latest.update(id=104, updated_at='2026-09-20T04:00:00Z') +del latest['tests'][0]['table'] +with patch('gsb.public_sections._tree_paths', return_value=([], 'fixture')): + tiered_tests = public_tests(Context(SummaryGH(), summary_cfg, datetime.now(timezone.utc), {'default_branch':'main'}), [latest, *reversed(tiered_runs)]) +tiered = json.loads(json.dumps(generic)) +tiered['sections']['tests'] = wrap(tiered_tests) +export_site(root/'.e2e/site/tiered-summary', tiered) + # E2E run records through the real collector and Pages attachment, offline: yesterday's # collection read histories across multiple runs and branch lines. An expired # artifact disappears; fork and oversized artifacts have no hosted HTML. diff --git a/tests/test_incremental.py b/tests/test_incremental.py index fa74a5cde..8c1e1f5cc 100644 --- a/tests/test_incremental.py +++ b/tests/test_incremental.py @@ -159,6 +159,28 @@ def test_same_day_new_run_refreshes_tests_but_not_daily_ops(self): self.assertEqual(updated['sections']['ops']['data']['marker'],'old-ops') self.assertEqual(updated['sections']['tests']['data']['marker'],'new-tests') + def test_grouped_tables_survive_the_current_run_window_without_reusing_old_attempts(self): + sync = Sync(Source(), self.root, REPO, now=NOW).collect() + for ident in range(1, 107): + raw = run(ident) + raw['updated_at'] = raw['created_at'] + row = slim_run(raw, {}) + if ident in (105, 106): + row['tests'] = [dict(name='service-test-results', artifact_id=ident, layer='e2e', + counts=dict(tests=2, passed=1, failed=1, skipped=0, flaky=0), cases=[], + table=dict(title='Probes', group=dict(key=str(ident), label=f'Group {ident}'), + columns=[dict(key='probe', label='Probe')], rows=[dict(probe='a'), dict(probe='b')]))] + sync.history.put('runs', row) + latest = slim_run(dict(run(106, attempt=2), updated_at=stamp(NOW)), {}) + sync.history.put('runs', latest) + with patch('gsb.incremental_project.public_ops', return_value={}), \ + patch('gsb.incremental_project.public_tests', return_value={'marker':'tests'}): + doc = build_snapshot(sync) + self.assertNotIn(105, [row['id'] for row in doc['quality']['runs']]) + tables = doc['sections']['tests']['data']['summary_tables'] + self.assertEqual([(row['run_id'], row['attempt']) for row in tables], [(105, 1)]) + self.assertEqual(tables[0]['totals']['tests'], 2) + def test_coverage_summaries_persist_on_runs_and_keep_latest_result_per_beijing_day(self): history=History(self.root) for number in (1,2,3,4,5): diff --git a/tests/test_reports.py b/tests/test_reports.py index 641edbe20..997b4b73a 100644 --- a/tests/test_reports.py +++ b/tests/test_reports.py @@ -61,6 +61,53 @@ def test_missing_or_malformed_optional_table_keeps_legacy_summary_counts(self): self.assertNotIn('table', parsed) self.assertEqual(parsed['cases'], []) + def test_summary_table_group_is_optional_public_producer_metadata(self): + table = dict(title='Probes', columns=[dict(key='probe', label='Probe')], rows=[dict(probe='a')], + group=dict(key='smoke', label='L3 · smoke', secret='PRIVATE')) + counts = dict(tests=1, passed=1, failed=0, skipped=0, flaky=0) + parsed = parse_report_zip(archive({'dashboard-summary.json': json.dumps(dict(counts, table=table))})) + self.assertEqual(parsed['table']['group'], dict(key='smoke', label='L3 · smoke')) + self.assertNotIn('PRIVATE', json.dumps(parsed)) + for group in [None, [], {}, dict(key='', label=''), dict(key='x', label={'answer': 'PRIVATE'})]: + with self.subTest(group=group): + table['group'] = group + parsed = parse_report_zip(archive({'dashboard-summary.json': json.dumps(dict(counts, table=table))})) + self.assertEqual(parsed['tests'], 1) + self.assertEqual(parsed['table']['rows'], [dict(probe='a')]) + self.assertNotIn('group', parsed['table']) + + def test_table_groups_survive_newer_same_name_counts_only_reports_and_reruns(self): + from gsb.reports import summary_tables + from gsb.public_sections import public_tests + from gsb.collectors import Context + from datetime import datetime, timezone + from unittest.mock import patch + def run(ident, group=None, count=1, attempt=1): + report = dict(name='service-test-results', artifact_id=ident * 10 + attempt, layer='e2e', status='available', + url=f'https://example.com/runs/{ident}/artifacts/{attempt}', cases=[], + counts=dict(tests=count, passed=count - 1, failed=1, skipped=0, flaky=0)) + if group is not None: + report['table'] = dict(title='Probes', group=dict(key=group, label=group), + columns=[dict(key='probe', label='Probe')], rows=[dict(probe=f'{group}-{i}') for i in range(count)]) + return dict(id=ident, attempt=attempt, sha=str(ident)*20, branch='main', updated_at=f'2026-01-01T00:{ident:02}:00Z', tests=[report]) + runs = [run(6), run(5, 'smoke', 2), run(4, 'full', 4), run(3, 'regression', 3), run(2, 'smoke', 1)] + tables = summary_tables(runs) + self.assertEqual([(r['table']['group']['key'], r['totals']['tests'], r['run_id']) for r in tables], + [('smoke', 2, 5), ('full', 4, 4), ('regression', 3, 3)]) + self.assertEqual(tables[0]['sha'], runs[1]['sha']) + self.assertEqual(tables[0]['attempt'], 1) + # An older attempt of the SAME run must never stand in for its latest attempt. + self.assertEqual(summary_tables([run(7, attempt=2), run(7, 'obsolete', attempt=1)]), []) + # The full collector has the same selection contract as the incremental projection. + class GH: + def paginate(self, *a, **kw): return [] + def get_text_file(self, *a): return '{}' + ctx = Context(GH(), Config(repo='acme/weather-service'), datetime.now(timezone.utc), {'default_branch':'main'}) + with patch('gsb.public_sections._tree_paths', return_value=([], 'test')): + full = public_tests(ctx, runs) + self.assertEqual(full['summary_tables'], tables) + self.assertNotIn('table', full['executed'][0]) + def test_non_science_repository_table_survives_collection_and_both_snapshot_paths(self): from datetime import datetime, timezone from unittest.mock import patch