diff --git a/.github/fixtures/pelican-question-e2e/Dockerfile b/.github/fixtures/pelican-question-e2e/Dockerfile index fb0f90bb0c01..0a26d5f0fb14 100644 --- a/.github/fixtures/pelican-question-e2e/Dockerfile +++ b/.github/fixtures/pelican-question-e2e/Dockerfile @@ -12,6 +12,8 @@ RUN mkdir -p /opt/fixture/tls && \ chmod 644 /opt/fixture/tls/key.pem COPY scripts/pelican-question-e2e.mjs /opt/fixture/pelican-question-e2e.mjs COPY scripts/pelican-detail-identity.mjs /opt/fixture/pelican-detail-identity.mjs +COPY scripts/pelican-nominal-round.mjs /opt/fixture/pelican-nominal-round.mjs +COPY scripts/pelican-complete-rounds.mjs /opt/fixture/pelican-complete-rounds.mjs ENV NODE_EXTRA_CA_CERTS=/opt/fixture/tls/cert.pem ENTRYPOINT ["node", "/opt/fixture/pelican-question-e2e.mjs"] diff --git a/.github/fixtures/pelican-question-e2e/README.md b/.github/fixtures/pelican-question-e2e/README.md index d281440a9c4b..9accacf9dca6 100644 --- a/.github/fixtures/pelican-question-e2e/README.md +++ b/.github/fixtures/pelican-question-e2e/README.md @@ -2,8 +2,9 @@ Refs #795。本目录只提供 CI fixture,不修改应用业务代码,不表示完整验收、真实模型兼容性或经验难度校准完成。逐场景状态由 `acceptance.json` 声明;脚本即使成功,也固定输出 `full_acceptance_complete: false`。 -PR #832 独审 P2 仍为 **BLOCKED**,直到修正后候选的远程证据取得。`pelican-detail-identity.mjs` 按请求 URL 选 PG 行,逐条校验 URL result/plan、响应体 id/plan、PG id/plan 和 marker;账号窗口在所有详情响应通过后才以该请求绑定选卡与命名截图,产物保留 `request_binding`。分组 URL 只有 result ID,因此明确校验 URL result=body id=PG id,以及 body plan=PG plan,不虚构 URL plan。远程工作流先运行无网络/API替换的 `node:test` 合成门禁,要求同计划 R1/R2 整包交换两个方向均被拒绝,另验正常乱序和错误 plan/样本内容;保存 `detail-identity-synthetic.tap`。合成门禁不替代真实应用 E2E,未在本机执行。 +PR #832 的六个真实成功结果和请求身份门禁已由父级接受,仅代表该增量。当前 successor 从 `dfc0219a9e66a19642eb73875e4914e540b49575` 开始,保留原有场景,再增加同账号/分组计划的第二 nominal round;待当前 head 的远程运行证据,不能用旧 SHA 的成功代替。`pelican-detail-identity.mjs` 按真实请求 URL 将响应绑定到 PG result/plan,拒绝整包交换。独立合成门禁与真实应用结果分开记录。 +第二轮只根据源码 `pelican_questions.go` 的 bank version、SHA256 前八字节 big-endian 与 modulo 公式选择已到期且题目不同的微秒时间,写入 fixture 计划的 `next_run_at`。不注入题目、不修改抽题算法,不保证普通随机轮次必不重复。远程 oracle 回归另以 #832 两份真实 PG 问题身份校验公式。真实 RunDue/Claim 的持有租约、Finish 释放、last_run_at 和已推进 next_run_at 均读取限定投影;旧/新结果按各自冻结快照关联 provider marker、API 请求 URL 和真实 DOM。 ## 本增量的运行链 GitHub `pull_request`(base 为 `production`,包含 fixture/script/workflow 变动)即可触发本分支新工作流,Draft 不跳过。`workflow_dispatch` 只是工作流进入默认分支后的备用入口,不能假定新分支已经可 dispatch。父协调者负责 publication 和精确 head/check 回读。 @@ -20,7 +21,7 @@ GitHub `pull_request`(base 为 `production`,包含 fixture/script/workflow 分组定时阶段复用先前真实创建的禁用计划:经真实编辑表单设置年周期 Cron,等计划行显示新 Cron 后点击 Enable。以实际 PUT 响应、启用后的 DOM 和限定 PG 规则投影对账,然后仅对这个 fixture plan/group 更新一次 `next_run_at`。仍等待真实分钟 tick/RunDue/Claim,并复用 provider 最多30秒的回复等待来观察有效运行租约、推进后的到期时间及两份真实请求;释放回复后要求两份真实 PG 结果和成功轮次的 lease 完成。每份结果按实际 `account_id` 与 capture alias 对账,允许两份都选中 A 或 B,不断言路由均匀。 -页面保持在真实 `PelicanTestsView`,等待其15秒轮询取得本轮 list,随后点击按 result ID 标记的行,监听实际 detail 响应,核对组名、模型、实际账号、成功状态、展开的 question/actual_prompt 和 iframe marker。按 group plan/result ID 保存截图与受限投影。不写结果、调用 `/run` 或注入 auth/store;这个分组的首次 nominal T 不是同一计划的第二轮 T2。CI 浏览器总等待上限为660秒,job仍为45分钟;本轮新代码未远程验证。 +页面保持在真实 `PelicanTestsView`,等待其15秒轮询取得本轮 list,随后点击按 result ID 标记的行,监听实际 detail 响应,核对组名、模型、实际账号、成功状态、展开的 question/actual_prompt 和 iframe marker。按 group plan/result ID 保存截图与受限投影。不写结果、调用 `/run` 或注入 auth/store;这个分组的首次 nominal T 不是同一计划的第二轮 T2。CI 浏览器总等待上限为1080秒,job仍为45分钟;本轮新代码未远程验证。 ## HTTPS fixture 与原 HTTP 建议的差异 @@ -28,17 +29,20 @@ GitHub `pull_request`(base 为 `production`,包含 fixture/script/workflow 假上游只接受模型发现和 messages SSE,额外的健康、去认证 capture 读取及单次 refusal 控制端点仅供 fixture。可选 pricing 刷新明确返回 503,真实应用使用打包的 fallback 文件;未知路径/输入记录为拒绝并使浏览器验收失败。网页本身仅允许 app origin;provider 只能由应用调用,Node fixture 控制读取不伪装成浏览器请求。主防外呼边界是所有运行容器的 Docker internal 网络,虚构 key 不是防外呼措施。 -## 未完成的完整验收范围 - -- [ ] 远程验收上述已实现的 A/B 随机定时 UI 创建、同一 T、真实 Claim 和四份 PG/provider/API/DOM 对账;静态实现不等于通过。 -- [ ] 远程验收已实现的分组 UI 启用、真实 RunDue/Claim、成功轮次 lease 完成、PG/provider/list/detail/真实 DOM 对账;不假设分组均匀路由 A/B。 -- [ ] 经真实浏览器编辑计划后,旧 PG/API/UI 快照保持不变。 -- [ ] 第二 nominal time T2 按现有哈希公式选到另一题,等待真实 tick,新旧记录共存;不能修改生产抽题算法。 -- [ ] arm 单次 refusal 后真正产生 failed 持久化结果、失败历史及 lease 释放;现有 refusal server 能力尚未被此增量测试。 -- [ ] 失败场景的结果/租约/到期字段限定投影及关联。账号与分组成功轮次已编写限定投影,但尚待各自实际候选的远程证据。 -- #809 已合并;本 successor 的远程 Actions、失败记录及当前 head 检查结论由父级发布后补录,以当前候选 artifact 为准。没有运行本地动态检查。 -- [ ] 隔离链路真实截图上传 PR 原生附件并回读;现有组件 job 截图仍只是组件证据,不能混同此 job。无 PNG 提交到源码。 -- [ ] 父协调者独审、完整技术验收与产品/经验难度证据。fixture 的简单 SVG 不代表题目作答合格或难度相当。 +## Successor 的编辑、失败和恢复门禁(待本 head 远程运行) + +同计划 T2 后,通过实际账号 Scheduled tests 编辑表单与分组编辑表单,将随机规则改为不同的 custom prompt、样本数改为1。核对 PUT、PG,刷新页面后读取真实 list API,再打开编辑器核对保存值。原计划的 last_run_at 不应被 UI 编辑改写,账号 B 的计划应保持不变。再次打开旧历史,逐条按原 PG result/plan、请求 URL、provider marker 校验旧题目、版本、actual_prompt、样本数和 DOM;不使用当前计划覆盖旧结果。随后经同一真实表单恢复 random 模式,保留新样本数。 + +账号和分组各运行一次确定 refusal,再各运行一个有效 nominal round。refusal 是实际假提供商 SSE 的 stop_reason=refusal/category,附带唯一 partial-output marker;它是真实 service 的模型输出失败,不是编译 RED、网络拦截或预先写入的 failed 行。账号 A/B 并发时只拒绝一个实际到达的请求,不预设到达顺序或拒绝账号;按 marker/alias 精确绑定实际失败样本。分组拒绝应保留失败答案而不 failover。每轮都观察 Claim、原 last_run_at 保持、Finish 释放、last_run_at 前进及 next_run_at 已推进,检查旧结果不变。 + +账号失败卡片通过真实 history/detail 展开,核对冻结快照与失败文本。分组原 UI 失败行没有 preview 按钮,仅从实际 list 请求核对 snapshot/身份,并核对 DOM failed/error;不伪造该 UI 不提供的 detail 请求或失败快照 DOM。下一有效轮次要求相同计划再次实际执行成功并保留之前失败历史。 + +## 剩余验收 + +- [ ] 当前 successor exact-head 的远程原始日志、每个 attempt、真实 PG/provider/API/DOM 产物;静态实现不是通过,#832 六份结果也不替代本轮。 +- [ ] 下载并检查当前真实渲染截图,原生附件上传/字节回读(可用时);无 PNG 入源码。 +- [ ] 父级独立冻结 diff 复审及全部检查验收。 +- [ ] 原始产品/完整题库判据和专家或经验难度可比性。没有实际模型调用,fixture SVG 只证明工程链路,`full_acceptance_complete:false` 保留。 ## 证据与清理 diff --git a/.github/fixtures/pelican-question-e2e/acceptance.json b/.github/fixtures/pelican-question-e2e/acceptance.json index 2f141aa741f8..4f277727405f 100644 --- a/.github/fixtures/pelican-question-e2e/acceptance.json +++ b/.github/fixtures/pelican-question-e2e/acceptance.json @@ -1,17 +1,13 @@ { - "scope": "manual-account-and-group-scheduled-increment", + "scope": "issue795-successor-complete-engineering-rounds", "full_acceptance_complete": false, - "review_P2_identity_gate": "BLOCKED pending remote synthetic whole-response swap rejection evidence and real account/group E2E at the corrected head; static diff is not acceptance", - "unimplemented": [ - "plan UI edit followed by proof old stored/API/DOM snapshot is unchanged", - "second nominal time mapped to a different question, new and old scheduled records coexist", - "deterministic upstream refusal yields failed persisted history and released lease", - "failed-result/lease SQL projections linked to captures and API IDs" - ], + "review_P2_identity_gate": "Prior PR832 exact cb54990 accepted by parent; successor requires its own exact-head remote artifacts. Pure identity tests are not business proof.", + "unimplemented": [], "pending_external_gates": [ - "remote execution and exact PR head checks for account and group scheduled scenarios; prior SHA or component-only success is not their validation", - "screenshots from successful isolated chain uploaded as PR native attachments and read back", - "product policy and empirical difficulty calibration; fixture output cannot prove either" + "current successor exact-head remote execution and raw attempt logs for all added engineering gates; earlier SHA success is insufficient", + "current CI captures downloaded and inspected, PR native attachments with byte readback if upload is available", + "parent independent frozen-diff review and all-check acceptance", + "original product policy, complete question-bank criteria and expert/empirical difficulty acceptance; no actual model calls or quality equivalence inferred" ], "fixture_transport_difference": "Uses fixture-only HTTPS and an ephemeral fixture CA, because the enabled real account-test URL allowlist calls ValidateHTTPSURL. The audit's proposed HTTP URL is not accepted with that allowlist enabled. No application validation is disabled or modified.", "implemented_scenarios": [ @@ -29,7 +25,11 @@ "restricted account plan/result/due/active-lease projections; no result writes and no manual /run substitutes", "existing disabled group plan configured and enabled through actual PelicanTestsView UI; only its fixture next_run_at aligned via SQL", "actual group RunDue/Claim observed with two held provider replies, two persisted results and successful-run lease completion", - "group plan/result IDs and actual selected accounts correlated across restricted PG projection, provider captures, real page list/detail API responses, DOM rows, expanded snapshots and iframe markers; no equal account routing assumption" + "group plan/result IDs and actual selected accounts correlated across restricted PG projection, provider captures, real page list/detail API responses, DOM rows, expanded snapshots and iframe markers; no equal account routing assumption", + "same account A/B plans second nominal RunDue with a deterministically different question; original and second PG/provider/API/request-bound DOM histories coexist", + "same group plan second nominal RunDue with a deterministically different question; original and second PG/provider/API/request-bound DOM histories coexist", + "real account and group UI edits random to distinct custom prompts and one sample, update response/PG/reloaded list/reopened editor persistence; all previously saved PG/API/DOM snapshots unchanged", + "random mode restored through real UI; deterministic single provider refusal persists failed result with unique partial-output marker and exact frozen snapshot, UI failure history, released leases; same account/group plans execute next valid nominal RunDue" ], "verification_evidence": "Read scenario-results.json and the current PR head checks; this declaration does not assert runtime success." } diff --git a/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs b/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs index 7db1424286ad..cb4c24004668 100644 --- a/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs +++ b/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs @@ -38,3 +38,19 @@ test('account: wrong request plan is rejected even when the body matches a PG ro assert.throws(() => bindDetailResponse(url('account', '101', '8'), bodies[0], rows), /request plan ID must equal PG plan ID/) }) + +for (const kind of ['account', 'group']) { + test(`${kind}: old result IDs and marker cannot relabel the saved snapshot with the current rule or next round`, () => { + const changed = { ...bodies[0], pelican_config: { parallel_count: 1, prompt_mode: 'custom', + actual_prompt: 'edited current rule', pelican_question: { round_id: 'scheduled:next', id: 'different-question' } } } + assert.throws(() => bindDetailResponse(url(kind, '101'), changed, rows, kind), assert.AssertionError) + }) + test(`${kind}: refusal keeps its own failed identity and partial-output marker`, () => { + const failed = { ...rows[0], status: 'failed' } + const body = { ...bodies[0], status: 'failed', response_text: `${failed.marker}: fixture refusal` } + assert.equal(bindDetailResponse(url(kind, '101'), body, [failed], kind).marker, failed.marker) + assert.throws(() => bindDetailResponse(url(kind, '101'), { ...body, status: 'success' }, [failed], kind), assert.AssertionError) + assert.throws(() => bindDetailResponse(url(kind, '101'), { ...body, response_text: bodies[1].response_text }, [failed], kind), + /request-bound response marker/) + }) +} diff --git a/.github/fixtures/pelican-question-e2e/nominal-round.test.mjs b/.github/fixtures/pelican-question-e2e/nominal-round.test.mjs new file mode 100644 index 000000000000..c99a9b27acd4 --- /dev/null +++ b/.github/fixtures/pelican-question-e2e/nominal-round.test.mjs @@ -0,0 +1,18 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { nextDifferentNominal, questionAt } from '../../scripts/pelican-nominal-round.mjs' + +test('selection oracle agrees with two prior real Go scheduler result artifacts', () => { + // PR832 run43405643066 attempt1, PG result projections; no model-quality claim. + assert.equal(questionAt('2026-11-13T10:06:24.123456Z'), 'penguin-bicycle') + assert.equal(questionAt('2026-11-13T10:07:16.654321Z'), 'rabbit-scooter') +}) + +test('later nominal time changes the question without changing the source algorithm', () => { + const previous = [{ nominal_time: '2026-11-13T10:06:24.123456Z', question_id: 'penguin-bicycle' }] + const next = nextDifferentNominal('2026-11-13T10:08:00Z', previous) + assert.match(next, /^2026-11-13T10:08:00\.\d{5}[1-9]Z$/) + assert.notEqual(questionAt(next), previous[0].question_id) + assert.ok(Date.parse(next) > Date.parse(previous[0].nominal_time)) + assert.throws(() => nextDifferentNominal('2026-11-13T10:00:00Z', previous), /No later/) +}) diff --git a/.github/scripts/pelican-complete-rounds.mjs b/.github/scripts/pelican-complete-rounds.mjs new file mode 100644 index 000000000000..e880b0205a60 --- /dev/null +++ b/.github/scripts/pelican-complete-rounds.mjs @@ -0,0 +1,396 @@ +import assert from 'node:assert/strict' +import { join } from 'node:path' +import { bindDetailResponse } from './pelican-detail-identity.mjs' +import { nextDifferentNominal, questionAt, bankVersion } from './pelican-nominal-round.mjs' + +const unwrap = value => value?.data ?? value +const pause = () => new Promise(resolve => setTimeout(resolve, 250)) + +// Called only after the original real application scenarios have succeeded. +// All writes except next_run_at go through existing authenticated UI controls. +export async function completeScheduledRounds(c) { + const { db, page, origin, accounts, groups, plans, groupPlanId, groupId, model, + dialog, openAccount, checkSnapshot, readPlans, readResults, readGroupPlan, readGroupResults, + fixtureControl, capturesNow, save, evidence, state } = c + const initial = { account: await readResults(), group: await readGroupResults() } + const readers = { account: readResults, group: readGroupResults } + const planReaders = { account: readPlans, group: async () => [await readGroupPlan()] } + const ids = { account: plans.map(p => p.id), group: [groupPlanId] } + const tables = { account: 'scheduled_test_plans', group: 'pelican_group_test_plans' } + + async function accountHistory(label, expected) { + await page.goto(`${origin}/admin/accounts`) + const projections = [] + for (const account of accounts) { + await openAccount(account) + const rows = expected.filter(row => row.account_id === account.id) + const details = new Map() + const pending = [] + const errors = [] + const observe = response => { + const path = new URL(response.url()).pathname + if (!/^\/api\/v1\/admin\/scheduled-test-plans\/\d+\/results\/\d+$/.test(path)) return + pending.push((async () => { + assert.equal(response.status(), 200) + const body = unwrap(await response.json()) + const binding = bindDetailResponse(response.request().url(), body, rows) + const row = rows.find(row => row.id === binding.request_result_id) + assert.equal(body.error_message, row.error_message) + details.set(row.id, { binding, body }) + })().catch(error => errors.push({ name: error.name, message: error.message }))) + } + page.on('response', observe) + try { + const historyResponse = page.waitForResponse(response => { + const url = new URL(response.url()) + return url.pathname === '/api/v1/admin/pelican-test-results' && url.searchParams.get('account_id') === account.id + }) + await dialog().getByTestId('open-records').click() + const response = await historyResponse + assert.equal(response.status(), 200) + const history = unwrap(await response.json()) + assert.equal(history.next_cursor, 0) + assert.equal(history.items.length, rows.length) + for (const row of rows) { + const item = history.items.find(item => String(item.id) === row.id) + assert.ok(item) + assert.equal(String(item.plan_id), row.plan_id) + assert.equal(String(item.account_id), account.id) + assert.equal(item.status, row.status) + assert.equal(item.error_message, row.error_message) + assert.deepEqual(item.pelican_config, row.pelican_config) + } + const deadline = Date.now() + 20_000 + while (details.size < rows.length && !errors.length && Date.now() < deadline) await pause() + assert.deepEqual(errors, []) + assert.equal(details.size, rows.length, 'every old and new PG identity needs a real detail request') + const panel = page.getByTestId('records-panel') + for (const row of rows) { + const { binding } = details.get(row.id) + const card = panel.getByTestId('pelican-record-card').filter({ has: row.status === 'success' + ? page.locator(`iframe[srcdoc*="${binding.marker}"]`) + : page.locator('pre').filter({ hasText: binding.marker }) }) + await card.waitFor({ state: 'visible' }) + assert.equal(await card.count(), 1) + assert.equal(await card.getByTestId('record-status').innerText(), row.status === 'success' ? 'Complete' : 'Failed') + await card.getByRole('button').click() + const detail = page.getByTestId('record-detail') + await checkSnapshot(detail, row.pelican_config) + if (row.status === 'success') assert.equal(await detail.frameLocator('iframe').locator('p').innerText(), row.marker) + else assert.ok((await detail.innerText()).includes(row.error_message)) + await page.screenshot({ path: join(evidence, `${label}-account-${account.id}-${row.id}.png`), fullPage: true }) + projections.push({ result_id: row.id, status: row.status, snapshot: row.pelican_config, request_binding: binding }) + await detail.getByRole('button', { name: 'Close', exact: true }).click() + } + await panel.getByRole('button', { name: 'Close', exact: true }).click() + await Promise.all(pending) + assert.deepEqual(errors, [], 'duplicate detail responses also retain URL identity') + } finally { page.off('response', observe) } + await dialog().getByRole('button', { name: 'Close modal', exact: true }).click() + } + save(`${label}-account-api-dom.json`, projections) + } + + async function groupHistory(label, expected) { + const listed = page.waitForResponse(response => new URL(response.url()).pathname === '/api/v1/admin/pelican-group-test-results' + && response.request().method() === 'GET' && response.status() === 200) + await page.goto(`${origin}/admin/pelican-tests`) + const response = await listed + const list = unwrap(await response.json()) + assert.equal(list.total, expected.length) + assert.equal(list.items.length, expected.length) + const projections = [] + for (const row of expected) { + const item = list.items.find(item => String(item.id) === row.id) + assert.ok(item) + assert.equal(String(item.plan_id), row.plan_id) + assert.equal(String(item.group_id), groupId) + assert.equal(String(item.account_id), row.account_id) + assert.equal(item.account_name, row.account_name) + assert.equal(item.status, row.status) + assert.equal(item.error_message, row.error_message) + assert.deepEqual(item.pelican_config, row.pelican_config) + assert.equal(item.attempts.length, row.attempt_count) + const domRow = page.getByTestId(`pelican-result-${row.id}`) + await domRow.waitFor({ state: 'visible' }) + assert.equal(await domRow.locator('td').nth(1).innerText(), groups[0].name) + assert.equal(await domRow.locator('td').nth(2).innerText(), model) + assert.equal(await domRow.locator('td').nth(3).innerText(), row.account_name) + assert.equal(await domRow.locator('.result-badge').innerText(), row.status === 'success' ? 'Success' : 'Failed') + if (row.status === 'failed') { + assert.equal(await domRow.locator('.error-text').innerText(), row.error_message) + assert.equal(await page.getByTestId(`pelican-result-view-${row.id}`).count(), 0) + // Existing failed rows expose list/error only, no preview action. Do + // not invent a browser detail request or a failed snapshot DOM claim. + projections.push({ result_id: row.id, list_request_path: new URL(response.request().url()).pathname, + status: row.status, error_message: row.error_message, api_snapshot: item.pelican_config, preview: 'not offered by existing UI' }) + await page.screenshot({ path: join(evidence, `${label}-group-failed-${row.id}.png`), fullPage: true }) + continue + } + const detailResponse = page.waitForResponse(response => new URL(response.url()).pathname === `/api/v1/admin/pelican-group-test-results/${row.id}`) + await page.getByTestId(`pelican-result-view-${row.id}`).click() + const detail = await detailResponse + assert.equal(detail.status(), 200) + const body = unwrap(await detail.json()) + const binding = bindDetailResponse(detail.request().url(), body, expected, 'group') + assert.equal(body.error_message, row.error_message) + const preview = page.getByTestId('pelican-result-preview') + await checkSnapshot(preview, row.pelican_config) + assert.equal(await preview.frameLocator('iframe').locator('p').innerText(), row.marker) + await page.screenshot({ path: join(evidence, `${label}-group-${row.id}.png`), fullPage: true }) + projections.push({ result_id: row.id, snapshot: row.pelican_config, request_binding: binding }) + await page.getByRole('dialog').filter({ has: preview }).getByRole('button', { name: 'Close', exact: true }).click() + await preview.waitFor({ state: 'hidden' }) + } + save(`${label}-group-api-dom.json`, projections) + } + + async function round(kind, label, refuse = false) { + state.active_gate = `${label}-${kind}` + const before = await readers[kind]() + const beforePlans = await planReaders[kind]() + assert.ok(beforePlans.every(p => p.running_until === null && p.last_run_at !== null)) + const previous = before.map(row => ({ nominal_time: row.pelican_config.pelican_question.round_id.slice('scheduled:'.length), + question_id: row.pelican_config.pelican_question.id })) + const { rows: clock } = await db.query(`SELECT to_char(date_trunc('second', now()) - interval '1 second', 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS t`) + const nominal = nextDifferentNominal(clock[0].t, previous.slice(-2)) + const captureStart = (await capturesNow()).captures.length + const sampleCount = beforePlans.reduce((sum, p) => sum + p.pelican_config.parallel_count, 0) + await fixtureControl('hold-scheduled') + let released = false + try { + if (refuse) await fixtureControl('refuse-next') + // Table names come only from the closed map above. Bind exact UI-created + // IDs and fictional owners; CAS the previously read scheduling state. + for (const plan of beforePlans) { + const owner = kind === 'account' ? 'account_id' : 'group_id' + const entity = kind === 'account' ? 'accounts' : 'groups' + const name = kind === 'account' ? accounts.find(a => a.id === plan.account_id).name : groups[0].name + const due = await db.query(`UPDATE ${tables[kind]} p SET next_run_at = $1::timestamptz + FROM ${entity} e WHERE p.id = $2::bigint AND p.${owner} = $3::bigint + AND e.id = p.${owner} AND e.name = $4 AND e.deleted_at IS NULL + AND p.enabled AND p.model_id = $5 AND p.cron_expression = '0 0 1 1 *' + AND p.running_until IS NULL AND p.last_run_at = $6::timestamptz + AND p.next_run_at = $7::timestamptz AND p.next_run_at > now() + AND p.pelican_config = $8::jsonb AND $1::timestamptz < now() + RETURNING p.id::text`, [nominal, plan.id, plan[owner], name, model, plan.last_run_at, plan.next_run_at, JSON.stringify(plan.pelican_config)]) + assert.equal(due.rowCount, 1) + } + save(`${label}-${kind}-due.json`, { nominal_time: nominal, question_id_oracle: questionAt(nominal), previous_plans: beforePlans }) + const deadline = Date.now() + 90_000 + let claimed + while (Date.now() < deadline) { + const current = await planReaders[kind]() + const sent = (await capturesNow()).captures.slice(captureStart) + assert.ok(sent.length <= sampleCount) + if (sent.length === sampleCount && current.every(p => p.lease_active)) { + assert.deepEqual(await readers[kind](), before, 'held replies cannot change saved results') + for (const p of current) { + assert.ok(Date.parse(p.next_run_at) > Date.parse(nominal)) + assert.equal(p.last_run_at, beforePlans.find(old => old.id === p.id).last_run_at, 'Claim preserves last_run_at until Finish') + } + claimed = current + break + } + await pause() + } + assert.ok(claimed, `${label}/${kind}: real RunDue and leases required`) + save(`${label}-${kind}-claimed.json`, claimed) + assert.equal((await fixtureControl('release-scheduled')).released, sampleCount) + released = true + let results, completed + const finishDeadline = Date.now() + 30_000 + while (Date.now() < finishDeadline) { + const rows = await readers[kind]() + const current = await planReaders[kind]() + assert.ok(rows.length <= before.length + sampleCount) + if (rows.length === before.length + sampleCount && current.every(p => p.running_until === null)) { + results = rows; completed = current; break + } + await pause() + } + assert.ok(results, 'new persisted results AND released leases required') + for (const p of completed) { + const old = beforePlans.find(old => old.id === p.id) + assert.ok(Date.parse(p.last_run_at) > Date.parse(old.last_run_at)) + assert.ok(Date.parse(p.next_run_at) > Date.parse(nominal)) + const rule = ({ next_run_at, running_until, last_run_at, lease_active, ...fields }) => fields + assert.deepEqual(rule(p), rule(old), 'execution preserves the saved plan rule and ownership') + } + assert.deepEqual(results.filter(row => before.some(old => old.id === row.id)), before, 'all previously saved JSON values remain unchanged') + const fresh = results.filter(row => !before.some(old => old.id === row.id)) + const provider = await capturesNow() + assert.deepEqual(provider.rejected, []) + const sent = provider.captures.slice(captureStart) + assert.equal(sent.length, sampleCount) + assert.equal(new Set(fresh.map(row => row.marker)).size, sampleCount) + assert.equal(fresh.filter(row => row.status === 'failed').length, refuse ? 1 : 0) + for (const row of fresh) { + assert.ok(ids[kind].includes(row.plan_id)) + const cfg = row.pelican_config + assert.equal(cfg.pelican_question.round_id, `scheduled:${nominal}`) + assert.equal(cfg.pelican_question.id, questionAt(nominal)) + assert.equal(cfg.pelican_question.version, bankVersion) + assert.equal(cfg.pelican_question.source, 'builtin:svg-motion') + assert.deepEqual(cfg.pelican_question, fresh[0].pelican_config.pelican_question, 'all samples in the same nominal round share the exact question') + assert.equal(cfg.actual_prompt, fresh[0].pelican_config.actual_prompt) + assert.equal(cfg.prompt_mode, 'random') + assert.equal(cfg.parallel_count, beforePlans.find(p => p.id === row.plan_id).pelican_config.parallel_count) + assert.notEqual(cfg.pelican_question.id, previous.at(-1).question_id) + const capture = sent.find(item => item.marker === row.marker) + assert.ok(capture, 'persisted marker binds one actual provider request') + const accountIndex = accounts.findIndex(account => account.id === row.account_id) + assert.ok(accountIndex >= 0, 'actual route must identify a fixture account') + assert.equal(capture.alias, accountIndex === 0 ? 'a' : 'b') + if (kind === 'account') { + assert.equal(row.account_id, plans.find(p => p.id === row.plan_id).account_id) + assert.equal(cfg.trigger_source, 'scheduled') + } else { + assert.equal(row.group_id, groupId) + assert.equal(row.account_name, accounts[accountIndex].name) + } + assert.equal(capture.model, model) + assert.equal(capture.prompt, cfg.actual_prompt.trim()) + assert.equal(capture.refused, row.status === 'failed') + assert.equal(row.error_message, row.status === 'failed' ? 'Model refused the request (category: fixture-deterministic)' : '') + if (kind === 'group') assert.equal(row.attempt_count, 0, 'model refusal must not fail over') + } + save(`${label}-${kind}-results.json`, { nominal_time: nominal, pg: results, provider: sent, completed_plans: completed }) + if (kind === 'account') await accountHistory(label, results) + else await groupHistory(label, results) + assert.deepEqual(await readers[kind](), results) + state.scenarios.push({ name: `${label}-${kind}-pg-provider-api-dom`, status: 'passed', nominal_time: nominal, + result_ids: fresh.map(row => row.id), coexisting_result_ids: results.map(row => row.id), failed: refuse ? 1 : 0 }) + } finally { + if (!released) await fixtureControl('release-scheduled') + } + } + + await round('account', 'second-nominal') + await round('group', 'second-nominal') + + async function editAccount(mode) { + state.active_gate = `ui-edit-account-${mode}` + await page.goto(`${origin}/admin/accounts`) + await openAccount(accounts[0]) + await dialog().getByRole('button', { name: 'Scheduled tests', exact: true }).click() + await dialog().getByRole('button', { name: 'Edit Plan', exact: true }).click() + const form = dialog().locator('div.border-t.border-blue-100').filter({ has: page.getByPlaceholder('*/30 * * * *', { exact: true }) }) + assert.equal(await form.count(), 1) + await form.getByTestId('pelican-mode-select').selectOption(mode) + const prompt = 'fixture795 edited account rule: draw a standalone SVG with a violet square.' + if (mode === 'custom') await form.locator('textarea').fill(prompt) + await form.locator('input[type=number]').last().fill('1') + const saved = page.waitForResponse(response => new URL(response.url()).pathname === `/api/v1/admin/scheduled-test-plans/${plans[0].id}` + && response.request().method() === 'PUT') + await form.getByRole('button', { name: 'Save', exact: true }).click() + const response = await saved + assert.equal(response.status(), 200) + const body = unwrap(await response.json()) + assert.equal(String(body.id), plans[0].id) + assert.equal(String(body.account_id), accounts[0].id) + assert.equal(body.pelican_config.prompt_mode, mode) + assert.equal(body.pelican_config.parallel_count, 1) + if (mode === 'custom') assert.equal(body.pelican_config.prompt, prompt) + assert.ok(!body.pelican_config.pelican_question) + const stored = (await readPlans()).find(p => p.id === plans[0].id) + assert.deepEqual(stored.pelican_config, body.pelican_config) + await form.waitFor({ state: 'hidden' }) + await dialog().getByRole('button', { name: 'Close modal', exact: true }).click() + await page.reload() + await openAccount(accounts[0]) + const listRead = page.waitForResponse(response => new URL(response.url()).pathname === `/api/v1/admin/accounts/${accounts[0].id}/scheduled-test-plans` + && response.request().method() === 'GET') + await dialog().getByRole('button', { name: 'Scheduled tests', exact: true }).click() + const listResponse = await listRead + assert.equal(listResponse.status(), 200) + const list = unwrap(await listResponse.json()) + const persisted = list.find(p => String(p.id) === plans[0].id) + assert.ok(persisted) + assert.deepEqual(persisted.pelican_config, body.pelican_config) + await dialog().getByRole('button', { name: 'Edit Plan', exact: true }).click() + assert.equal(await form.getByTestId('pelican-mode-select').inputValue(), mode) + assert.equal(await form.locator('input[type=number]').last().inputValue(), '1') + if (mode === 'custom') assert.equal(await form.locator('textarea').inputValue(), prompt) + await page.screenshot({ path: join(evidence, `edited-account-${mode}-persisted.png`), fullPage: true }) + save(`edited-account-${mode}.json`, { update_request_path: new URL(response.request().url()).pathname, + list_request_path: new URL(listResponse.request().url()).pathname, + api_config: body.pelican_config, pg_plan: stored, reloaded_editor: { prompt_mode: mode, parallel_count: 1 } }) + await form.getByRole('button', { name: 'Cancel', exact: true }).click() + await dialog().getByRole('button', { name: 'Close modal', exact: true }).click() + } + + async function editGroup(mode) { + state.active_gate = `ui-edit-group-${mode}` + await page.goto(`${origin}/admin/pelican-tests`) + await page.getByTestId(`pelican-plan-edit-${groupPlanId}`).click() + const form = page.getByTestId('pelican-test-editor') + await form.getByTestId('pelican-mode-select').selectOption(mode) + const prompt = 'fixture795 edited group rule: draw a standalone SVG with a violet triangle.' + if (mode === 'custom') await form.getByTestId('pelican-test-prompt').fill(prompt) + await form.locator('#pelican-test-parallel').fill('1') + const saved = page.waitForResponse(response => new URL(response.url()).pathname === `/api/v1/admin/pelican-group-tests/${groupPlanId}` + && response.request().method() === 'PUT') + await page.getByTestId('pelican-test-save').click() + const response = await saved + assert.equal(response.status(), 200) + const body = unwrap(await response.json()) + assert.equal(String(body.id), groupPlanId) + assert.equal(String(body.group_id), groupId) + assert.equal(body.pelican_config.prompt_mode, mode) + assert.equal(body.pelican_config.parallel_count, 1) + if (mode === 'custom') assert.equal(body.pelican_config.prompt, prompt) + assert.ok(!body.pelican_config.pelican_question) + const stored = await readGroupPlan() + assert.deepEqual(stored.pelican_config, body.pelican_config) + await form.waitFor({ state: 'hidden' }) + await page.waitForLoadState('networkidle') + const listRead = page.waitForResponse(response => new URL(response.url()).pathname === '/api/v1/admin/pelican-group-tests' + && response.request().method() === 'GET') + await page.reload() + const listResponse = await listRead + assert.equal(listResponse.status(), 200) + const list = unwrap(await listResponse.json()) + const persisted = list.find(p => String(p.id) === groupPlanId) + assert.ok(persisted) + assert.deepEqual(persisted.pelican_config, body.pelican_config) + await page.getByTestId(`pelican-plan-edit-${groupPlanId}`).click() + assert.equal(await form.getByTestId('pelican-mode-select').inputValue(), mode) + assert.equal(await form.locator('#pelican-test-parallel').inputValue(), '1') + if (mode === 'custom') assert.equal(await form.getByTestId('pelican-test-prompt').inputValue(), prompt) + await page.screenshot({ path: join(evidence, `edited-group-${mode}-persisted.png`), fullPage: true }) + save(`edited-group-${mode}.json`, { update_request_path: new URL(response.request().url()).pathname, + list_request_path: new URL(listResponse.request().url()).pathname, + api_config: body.pelican_config, pg_plan: stored, reloaded_editor: { prompt_mode: mode, parallel_count: 1 } }) + await page.getByRole('dialog').filter({ has: form }).getByRole('button', { name: 'Cancel', exact: true }).click() + } + + const savedBeforeEdit = { account: await readResults(), group: await readGroupResults() } + const plansBeforeEdit = { account: await readPlans(), group: await readGroupPlan() } + await editAccount('custom') + await editGroup('custom') + state.active_gate = 'edited-old-snapshots' + assert.deepEqual(await readResults(), savedBeforeEdit.account) + assert.deepEqual(await readGroupResults(), savedBeforeEdit.group) + assert.deepEqual((await readPlans()).find(p => p.id === plans[1].id), plansBeforeEdit.account.find(p => p.id === plans[1].id), + 'editing A must preserve B plan and ownership') + for (const p of await readPlans()) assert.equal(p.last_run_at, plansBeforeEdit.account.find(old => old.id === p.id).last_run_at) + assert.equal((await readGroupPlan()).last_run_at, plansBeforeEdit.group.last_run_at) + await accountHistory('edited-old-snapshots', savedBeforeEdit.account) + await groupHistory('edited-old-snapshots', savedBeforeEdit.group) + save('edited-old-pg-snapshots.json', savedBeforeEdit) + state.scenarios.push({ name: 'ui-edited-account-group-rules-old-pg-api-dom-snapshots-immutable', status: 'passed' }) + + // Restore random mode through the real forms, retaining the changed sample + // count. The failed and recovery records must freeze this new rule, while + // all earlier results continue to describe the old two-sample rule. + await editAccount('random') + await editGroup('random') + await round('account', 'deterministic-refusal', true) + await round('account', 'after-refusal-valid-round') + await round('group', 'deterministic-refusal', true) + await round('group', 'after-refusal-valid-round') + assert.deepEqual((await readResults()).filter(row => initial.account.some(old => old.id === row.id)), initial.account) + assert.deepEqual((await readGroupResults()).filter(row => initial.group.some(old => old.id === row.id)), initial.group) + state.active_gate = null +} diff --git a/.github/scripts/pelican-nominal-round.mjs b/.github/scripts/pelican-nominal-round.mjs new file mode 100644 index 000000000000..e9b555b7515d --- /dev/null +++ b/.github/scripts/pelican-nominal-round.mjs @@ -0,0 +1,25 @@ +import assert from 'node:assert/strict' +import { createHash } from 'node:crypto' + +// Mirror only the selection oracle from service/pelican_questions.go. Never +// inject a selected question or change the application's selection algorithm. +export const bankVersion = 'svg-motion-v1' +export const questionIDs = ['pelican-bicycle', 'penguin-bicycle', 'rabbit-scooter', 'otter-scooter'] +export function questionAt(nominal) { + const hash = createHash('sha256').update(`${bankVersion}:scheduled:${nominal}`).digest() + return questionIDs[Number(hash.readBigUInt64BE(0) % BigInt(questionIDs.length))] +} + +export function nextDifferentNominal(clockSecond, previous) { + assert.match(clockSecond, /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/) + assert.ok(previous.length > 0) + for (let microsecond = 234001; microsecond < 235000; microsecond++) { + // Go RFC3339Nano trims zeroes. Keep six significant fractional digits so + // PG's US projection and the exact source round string are identical. + if (microsecond % 10 === 0) continue + const candidate = clockSecond.replace('Z', `.${microsecond}Z`) + if (previous.every(row => Date.parse(candidate) > Date.parse(row.nominal_time) + && questionAt(candidate) !== row.question_id)) return candidate + } + throw new Error('No later, different deterministic nominal time in fixture bound') +} diff --git a/.github/scripts/pelican-question-e2e.mjs b/.github/scripts/pelican-question-e2e.mjs index b3ae12a84c0d..c75fa3f0ccda 100644 --- a/.github/scripts/pelican-question-e2e.mjs +++ b/.github/scripts/pelican-question-e2e.mjs @@ -7,6 +7,7 @@ import { readFileSync, writeFileSync, appendFileSync, mkdirSync } from 'node:fs' import { join } from 'node:path' import { createRequire } from 'node:module' import { bindDetailResponse } from './pelican-detail-identity.mjs' +import { completeScheduledRounds } from './pelican-complete-rounds.mjs' const evidence = process.env.EVIDENCE_DIR || '/evidence' const upstreamOrigin = 'https://fake-upstream:4199' @@ -140,10 +141,13 @@ function upstream() { id: `msg_fixture_${sequence}`, type: 'message', role: 'assistant', model, content: [], stop_reason: null, usage: { input_tokens: 40, output_tokens: 0 }, } }) - if (!refused) { + { const html = `${marker}

${marker}

` event({ type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } }) - event({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: html } }) + // A refusal may contain partial text. Its unique marker binds the real + // failed persisted output to this provider request, without treating it + // as a successful HTML answer or relying on arrival ordering. + event({ type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: refused ? `${marker}: fixture refusal` : html } }) event({ type: 'content_block_stop', index: 0 }) } event({ type: 'message_delta', delta: refused @@ -460,7 +464,7 @@ async function browser() { to_char(next_run_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS next_run_at, running_until::text, last_run_at::text, running_until > now() AS lease_active FROM scheduled_test_plans WHERE id = ANY($1::bigint[]) ORDER BY id` - const resultSQL = `SELECT r.id::text, r.plan_id::text, p.account_id::text, r.status, r.pelican_config, + const resultSQL = `SELECT r.id::text, r.plan_id::text, p.account_id::text, r.status, r.error_message, r.pelican_config, substring(r.response_text from 'fixture795-[0-9]+') AS marker FROM scheduled_test_results r JOIN scheduled_test_plans p ON p.id = r.plan_id WHERE r.plan_id = ANY($1::bigint[]) ORDER BY r.id` @@ -743,7 +747,7 @@ async function browser() { FROM pelican_group_test_plans p JOIN groups g ON g.id = p.group_id WHERE p.id = $1::bigint AND g.id = $2::bigint AND g.name = 'fixture-pelican-group'` const groupResultSQL = `SELECT r.id::text, r.plan_id::text, p.group_id::text, - r.account_id::text, r.account_name, r.status, r.pelican_config, + r.account_id::text, r.account_name, r.status, r.error_message, r.pelican_config, jsonb_array_length(r.attempts) AS attempt_count, substring(r.response_text from 'fixture795-[0-9]+') AS marker FROM pelican_group_test_results r JOIN pelican_group_test_plans p ON p.id = r.plan_id @@ -885,7 +889,7 @@ async function browser() { assert.equal(list.items.length, 2) const groupAPIProjection = item => ({ id: String(item.id), plan_id: String(item.plan_id), group_id: String(item.group_id), account_id: String(item.account_id), account_name: item.account_name, - status: item.status, pelican_config: item.pelican_config, attempt_count: item.attempts.length }) + status: item.status, error_message: item.error_message, pelican_config: item.pelican_config, attempt_count: item.attempts.length }) const expectedAPIProjection = row => { const { marker, ...projection } = row return projection @@ -934,6 +938,13 @@ async function browser() { } } + stage = 'complete-scheduled-rounds' + await completeScheduledRounds({ db, page, origin, accounts, groups, plans, groupPlanId, groupId, model, + dialog, openAccount, checkSnapshot, readPlans, readResults, readGroupPlan, readGroupResults, + fixtureControl, capturesNow, save, evidence, state }) + + assert.deepEqual(forbiddenRuns, [], 'all successor rounds must use real RunDue') + assert.equal(manualRequests.length, 4, 'successor rounds cannot be manual submissions') stage = 'post-bootstrap-browser-and-provider-error-lists' const finalCaptures = await (await fetch(`${upstreamOrigin}/__fixture/captures`)).json() assert.deepEqual(finalCaptures.rejected, []) diff --git a/.github/workflows/pelican-random-questions.yml b/.github/workflows/pelican-random-questions.yml index da7320811013..bd3f282db981 100644 --- a/.github/workflows/pelican-random-questions.yml +++ b/.github/workflows/pelican-random-questions.yml @@ -32,6 +32,8 @@ on: - '.github/fixtures/pelican-question-e2e/**' - '.github/scripts/pelican-question-e2e.mjs' - '.github/scripts/pelican-detail-identity.mjs' + - '.github/scripts/pelican-nominal-round.mjs' + - '.github/scripts/pelican-complete-rounds.mjs' - '.github/scripts/pelican-question-browser.mjs' - '.github/workflows/pelican-random-questions.yml' - 'Dockerfile' @@ -80,7 +82,7 @@ jobs: env: APP_SHA: ${{ github.event.pull_request.head.sha || github.sha }} HARNESS_SHA: ${{ github.event.pull_request.head.sha || github.sha }} - PARENT_BASE_SHA: dbed7697aa56e76c6eb48c4914fa441496b67bdd + PARENT_BASE_SHA: dfc0219a9e66a19642eb73875e4914e540b49575 COMPOSE_PROJECT_NAME: pelican-${{ github.run_id }}-${{ github.run_attempt }} steps: - uses: actions/checkout@v6 @@ -116,7 +118,7 @@ jobs: shell: bash run: | set -euo pipefail - node --test harness/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs \ + node --test harness/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs harness/.github/fixtures/pelican-question-e2e/nominal-round.test.mjs \ | tee "$EVIDENCE_DIR/detail-identity-synthetic.tap" - name: Build and prefetch before runtime isolation (CI only) shell: bash @@ -156,7 +158,7 @@ jobs: run: | set -euo pipefail container_id="$(docker compose ps --all --quiet browser)" - result="$(timeout 660s docker wait "$container_id")" + result="$(timeout 1080s docker wait "$container_id")" # Harness logs contain only scenario names/status, never response bodies or tokens. docker compose logs --no-color browser test "$result" = 0 @@ -170,8 +172,9 @@ jobs: echo 'same nominal time, real Claim leases, four PG results and provider/history/detail/DOM reconciliation.' echo 'Also implemented: UI-enabled group plan, actual RunDue/Claim, two results and PG/provider/list/detail/DOM reconciliation.' echo 'Group routing is checked against the actual chosen accounts, without assuming equal distribution.' - echo 'Historical snapshots after editing, second nominal round,' - echo 'deterministic failed record and failure lease release remain unimplemented.' + echo 'Successor gates: same-plan T2 with a different question and coexisting histories;' + echo 'UI edits persisted and reloaded while old PG/API/DOM snapshots stay unchanged;' + echo 'deterministic provider refusal, failed history, released leases and subsequent valid RunDue.' echo 'Read this candidate artifact and checks; earlier SHA results do not validate new scenarios.' echo 'A green job does not clear all Issue #795 technical or product acceptance gates.' } >> "$GITHUB_STEP_SUMMARY"