diff --git a/.github/fixtures/pelican-question-e2e/Dockerfile b/.github/fixtures/pelican-question-e2e/Dockerfile index c15b508a4585..fb0f90bb0c01 100644 --- a/.github/fixtures/pelican-question-e2e/Dockerfile +++ b/.github/fixtures/pelican-question-e2e/Dockerfile @@ -11,6 +11,7 @@ RUN mkdir -p /opt/fixture/tls && \ -keyout /opt/fixture/tls/key.pem -out /opt/fixture/tls/cert.pem && \ 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 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 c9c70d5adf58..d281440a9c4b 100644 --- a/.github/fixtures/pelican-question-e2e/README.md +++ b/.github/fixtures/pelican-question-e2e/README.md @@ -1,14 +1,26 @@ -# Issue #795 隔离应用 E2E:手动链路与禁用分组计划 +# Issue #795 隔离应用 E2E:手动、账号定时与分组定时 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,未在本机执行。 + ## 本增量的运行链 GitHub `pull_request`(base 为 `production`,包含 fixture/script/workflow 变动)即可触发本分支新工作流,Draft 不跳过。`workflow_dispatch` 只是工作流进入默认分支后的备用入口,不能假定新分支已经可 dispatch。父协调者负责 publication 和精确 head/check 回读。 `APP_SHA` 与 `HARNESS_SHA` 均显式取 PR head(dispatch 时取该事件 SHA),分别 checkout,记录 SHA/tree。`PARENT_BASE_SHA` 记录本轮父协调者提供的整合基线,绝不作为永久固定的被测旧应用 SHA。正常根 Dockerfile 构建嵌入前端的真实应用;浏览器/pg 依赖、镜像和 fixture CA 也全部在运行隔离前准备。运行期间 Compose 一次性内部网络上的应用、PostgreSQL、Redis、假上游和浏览器均无第二网络、host networking、宿主 Docker socket 或发布端口。宿主 CI 的 Docker inspect 只投影网络/端口/挂载/特权配置,不输出容器环境变量。 -真实 AUTO_SETUP、迁移及虚构管理员正常登录后,SQL 只初始化两个 `anthropic/apikey` 账号和测试分组/关联,不插入题目、计划或结果。手动测试通过真实页面按钮、prepare API、handler/service 和上游 HTTP 请求执行,A/B 各两样本;输出唯一标记与上游去认证后的题面记录关联,再核真实 DOM 和 localStorage 刷新恢复。分组页面通过真实创建表单保存**禁用**计划并核对 API/PG,尚不执行调度。没有调用任何 `/run` 来代替 RunDue。 +真实 AUTO_SETUP、迁移及虚构管理员正常登录后,SQL 只初始化两个 `anthropic/apikey` 账号和测试分组/关联,不插入题目、计划或结果。手动测试通过真实页面按钮、prepare API、handler/service 和上游 HTTP 请求执行,A/B 各两样本;输出唯一标记与上游去认证后的题面记录关联,再核真实 DOM 和 localStorage 刷新恢复。分组页面通过真实创建表单保存**禁用**计划并核对 API/PG,这一步不执行调度,后续分组定时场景再经真实 UI 启用。没有调用任何 `/run` 来代替 RunDue。 + +账号定时增量从真实账号页的 Scheduled tests → Add Plan 创建 A/B 随机计划,各两个样本。年周期 Cron 避免创建期间自动到期;该阶段唯一 SQL 写入是绑定两份计划 ID、账号 ID/fixture 名称和未执行条件,原子地将两者 `next_run_at` 对齐到同一个已到期 UTC 微秒 T,其他计划字段与结果不写入。 + +脚本等待真实每分钟 runner。唯一外部替身 fake-upstream 暂停这四份回复(每份最多 30 秒),使脚本可以读到两份有效 `running_until`、已推进的到期时间及四份真实 provider capture,同时确认 PG 尚无结果。90 秒内必须观察到两份 Claim,否则失败;释放 provider 回复后最多等 30 秒,要求真正落库四份成功结果、唯一 marker、同一 `scheduled:T` / question / actual_prompt。此能力只延迟外部提供商回复,不调用或替换应用执行器。 + +真实历史窗口发起账号过滤的 history 和 result detail API;脚本只监听这些响应,对照限定 PG 字段与 provider marker,逐一点击对应卡片、展开题目快照并核对 iframe,截图文件名包含 account/result ID。不读取登录 token 或直接发起待验 API 请求。新场景的代码已实现,仍须在 successor PR 的实际候选 SHA 上远程执行;#809 的历史结果不能证明本增量通过。 + +分组定时阶段复用先前真实创建的禁用计划:经真实编辑表单设置年周期 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分钟;本轮新代码未远程验证。 ## HTTPS fixture 与原 HTTP 建议的差异 @@ -18,20 +30,21 @@ GitHub `pull_request`(base 为 `production`,包含 fixture/script/workflow ## 未完成的完整验收范围 -- [ ] A/B 账号随机定时计划由真实 UI 创建,各两个样本;只用限定 SQL 对齐同一 UTC 微秒 nominal time T,等待真正 runner/Claim。 -- [ ] 四个账号结果的 PG 投影、去认证 payload、history list/detail API 和真实展开 DOM/iframe 按同一 plan/result ID 对账。 -- [ ] 分组计划真实 RunDue/Claim、结果 PG → list/detail API → `PelicanTestsView` 同 ID 对账;不假设分组均匀路由 A/B。 +- [ ] 远程验收上述已实现的 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 能力尚未被此增量测试。 -- [ ] 对结果/租约/到期字段进行限定 SQL 投影,与 API、capture 和场景 ID 关联。目前只有初始化实体与禁用分组计划投影,没有定时结果 SQL 证据。 -- 远程 Actions、失败记录及当前 head 检查结论见 PR #809;场景结果以当次 artifact 为准。没有运行本地动态检查。 +- [ ] 失败场景的结果/租约/到期字段限定投影及关联。账号与分组成功轮次已编写限定投影,但尚待各自实际候选的远程证据。 +- #809 已合并;本 successor 的远程 Actions、失败记录及当前 head 检查结论由父级发布后补录,以当前候选 artifact 为准。没有运行本地动态检查。 - [ ] 隔离链路真实截图上传 PR 原生附件并回读;现有组件 job 截图仍只是组件证据,不能混同此 job。无 PNG 提交到源码。 - [ ] 父协调者独审、完整技术验收与产品/经验难度证据。fixture 的简单 SVG 不代表题目作答合格或难度相当。 ## 证据与清理 -CI artifact 预期包含应用/harness SHA/tree、显式未完成清单、命名场景结果、网络结构投影、仅限 fixture 题面的 provider captures(无认证头/全量 body)、真实手动请求/题面投影、本轮 localStorage 结果投影、必要的实体/计划 PG 投影、浏览器错误/拒绝清单和截图。比较 `actual_prompt` 的边界是本 fixture 的 UTF-8 文本经过真实 service TrimSpace 后的发送值,不能外推任意输入。 +CI artifact 预期包含应用/harness SHA/tree、显式未完成清单、命名场景结果、网络结构投影、仅限 fixture 题面的 provider captures(无认证头/全量 body)、真实手动请求/题面投影、本轮 localStorage 结果投影、必要的实体/计划 PG 投影、浏览器错误/拒绝清单和截图。账号定时新增 `account-scheduled-created/due/wait/claimed/results.json`、按账号的 history/detail/DOM 投影与按结果命名的截图;SQL 不导出响应全文,只取 fixture marker、ID、status、pelican_config、到期与租约字段。比较 `actual_prompt` 的边界是本 fixture 的 UTF-8 文本经过真实 service TrimSpace 后的发送值,不能外推任意输入。 + +分组定时新增 `group-scheduled-enabled/due/wait/claimed/results/api-dom.json` 与 `group-scheduled--.png`;实际选中账号按 fixture ID/name 和 provider alias 关联,SQL 只读 attempts 数量,不导出完整尝试错误。尚未执行编辑后旧快照、第二轮、确定失败历史或失败 lease 验收,成功轮次 lease 完成不能代替它们。 不导出 auth token、Cookie、完整 HAR、数据库全表、凭据列、原始应用日志或真实用户数据。不把整个运行目录当附件。fixture 密码/key/CA 都是本轮自建假值,不能用到任何其他环境。失败时也留存上述受限产物,`always()` 销毁容器、网络和一次性卷,artifact 保留七天。父协调者首次远程运行前需审查此增量,发布后仍须按原 brief 继续同一 PR 的未完成范围。 diff --git a/.github/fixtures/pelican-question-e2e/acceptance.json b/.github/fixtures/pelican-question-e2e/acceptance.json index d16059c25d3f..2f141aa741f8 100644 --- a/.github/fixtures/pelican-question-e2e/acceptance.json +++ b/.github/fixtures/pelican-question-e2e/acceptance.json @@ -1,17 +1,15 @@ { - "scope": "initial-reviewable-increment", + "scope": "manual-account-and-group-scheduled-increment", "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": [ - "account scheduled plans created via UI, two samples per A and B", - "same nominal UTC time, actual account runner Claim and four PG results", - "account PG result IDs and payloads reconciled with history/detail APIs and expanded real DOM", - "group due time alignment, real RunDue/Claim and PG/list/detail/DOM reconciliation", "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", - "restricted result/lease/due SQL projections linked to captures and API IDs" + "failed-result/lease SQL projections linked to captures and API IDs" ], "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" ], @@ -23,7 +21,15 @@ "provider payload compared with API question and real DOM snapshot", "manual localStorage recovery, history expansion and fixture iframe after reload", "next manual round identity changes; repeated question selection is permitted", - "disabled group plan created through real browser form, create API and PG" + "disabled group plan created through real browser form, create API and PG", + "account A/B random scheduled plans created through actual UI, two samples each", + "only fixture next_run_at aligned to one UTC microsecond nominal time; actual minute runner and live Claim leases observed while provider replies wait", + "four actual scheduled PG results correlated to unique provider captures, same frozen question and actual_prompt", + "account-scoped real history and detail API responses triggered by UI, expanded DOM snapshots and iframe markers matched to PG result IDs", + "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" ], "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 new file mode 100644 index 000000000000..7db1424286ad --- /dev/null +++ b/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs @@ -0,0 +1,40 @@ +import assert from 'node:assert/strict' +import test from 'node:test' +import { bindDetailResponse } from '../../scripts/pelican-detail-identity.mjs' + +// Same plan, status and question; only the sample identities/markers differ. +// These synthetic checks do not replace the real application E2E or its APIs. +const rows = ['101', '102'].map((id, index) => ({ id, plan_id: '7', status: 'success', + pelican_config: { pelican_question: { round_id: 'scheduled:fixture', id: 'same-question' } }, + marker: `fixture795-${index + 1}` })) +const bodies = rows.map(row => ({ id: Number(row.id), plan_id: Number(row.plan_id), + status: row.status, pelican_config: row.pelican_config, response_text: `

${row.marker}

` })) +const url = (kind, id, plan = '7') => kind === 'account' + ? `http://app:8080/api/v1/admin/scheduled-test-plans/${plan}/results/${id}` + : `http://app:8080/api/v1/admin/pelican-group-test-results/${id}` + +for (const kind of ['account', 'group']) { + test(`${kind}: legitimate out-of-order details retain their request identities`, () => { + const bindings = [1, 0].map(index => bindDetailResponse(url(kind, rows[index].id), bodies[index], rows, kind)) + assert.deepEqual(bindings.map(item => item.request_result_id), ['102', '101']) + assert.deepEqual(bindings.map(item => item.marker), ['fixture795-2', 'fixture795-1']) + }) + test(`${kind}: whole R1/R2 response swap is rejected in BOTH directions before card binding`, () => { + for (const index of [0, 1]) { + assert.throws(() => bindDetailResponse(url(kind, rows[index].id), bodies[1 - index], rows, kind), + /response result ID must equal request URL result ID/) + } + }) + test(`${kind}: correct result ID with wrong body plan is rejected`, () => { + assert.throws(() => bindDetailResponse(url(kind, '101'), { ...bodies[0], plan_id: 8 }, rows, kind), + /response plan ID must equal PG plan ID/) + }) + test(`${kind}: correct IDs with the other sample's content is rejected`, () => { + assert.throws(() => bindDetailResponse(url(kind, '101'), { ...bodies[0], response_text: bodies[1].response_text }, rows, kind), + /request-bound response marker must equal its PG marker/) + }) +} +test('account: wrong request plan is rejected even when the body matches a PG row', () => { + assert.throws(() => bindDetailResponse(url('account', '101', '8'), bodies[0], rows), + /request plan ID must equal PG plan ID/) +}) diff --git a/.github/scripts/pelican-detail-identity.mjs b/.github/scripts/pelican-detail-identity.mjs new file mode 100644 index 000000000000..1fd7d01a55f0 --- /dev/null +++ b/.github/scripts/pelican-detail-identity.mjs @@ -0,0 +1,26 @@ +import assert from 'node:assert/strict' + +// Pure evidence validation: never sends, replaces or mutates an application API. +// Select the PG row by the request URL, never by the response body's identity. +export function bindDetailResponse(requestURL, body, expectedRows, kind = 'account') { + assert.ok(kind === 'account' || kind === 'group') + const path = new URL(requestURL).pathname + const match = kind === 'account' + ? path.match(/^\/api\/v1\/admin\/scheduled-test-plans\/(\d+)\/results\/(\d+)$/) + : path.match(/^\/api\/v1\/admin\/pelican-group-test-results\/(\d+)$/) + assert.ok(match, 'expected real detail request path') + const requestResultID = kind === 'account' ? match[2] : match[1] + const matchingRows = expectedRows.filter(row => String(row.id) === requestResultID) + assert.equal(matchingRows.length, 1, 'request result ID must identify exactly one PG row') + const row = matchingRows[0] + const requestPlanID = kind === 'account' ? match[1] : null + if (kind === 'account') assert.equal(requestPlanID, String(row.plan_id), 'request plan ID must equal PG plan ID') + assert.equal(String(body.id), requestResultID, 'response result ID must equal request URL result ID') + assert.equal(String(body.plan_id), String(row.plan_id), 'response plan ID must equal PG plan ID') + assert.equal(body.status, row.status) + assert.deepEqual(body.pelican_config, row.pelican_config) + const marker = body.response_text?.match(/fixture795-\d+/)?.[0] + assert.equal(marker, row.marker, 'request-bound response marker must equal its PG marker') + return { request_path: path, request_plan_id: requestPlanID, request_result_id: requestResultID, + pg_plan_id: String(row.plan_id), pg_result_id: String(row.id), marker } +} diff --git a/.github/scripts/pelican-question-e2e.mjs b/.github/scripts/pelican-question-e2e.mjs index fb8484fbe9e4..b3ae12a84c0d 100644 --- a/.github/scripts/pelican-question-e2e.mjs +++ b/.github/scripts/pelican-question-e2e.mjs @@ -6,6 +6,7 @@ import { createServer } from 'node:https' 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' const evidence = process.env.EVIDENCE_DIR || '/evidence' const upstreamOrigin = 'https://fake-upstream:4199' @@ -47,6 +48,8 @@ function upstream() { const captures = [] const rejected = [] let refuseNext = false + let holdScheduled = false + const heldReplies = new Set() const json = (res, status, value) => { res.writeHead(status, { 'content-type': 'application/json' }) res.end(JSON.stringify(value)) @@ -63,6 +66,19 @@ function upstream() { refuseNext = true return json(res, 200, { armed: true }) } + // Hold only provider replies, never the application's handlers or results. + // This lets CI observe real Claim leases before the fast fixture completes. + if (req.method === 'POST' && path === '/__fixture/hold-scheduled') { + if (holdScheduled || heldReplies.size) return json(res, 409, { error: 'already holding' }) + holdScheduled = true + return json(res, 200, { holding: true }) + } + if (req.method === 'POST' && path === '/__fixture/release-scheduled') { + holdScheduled = false + const released = heldReplies.size + for (const release of heldReplies) release() + return json(res, 200, { released }) + } // Explicitly reject the app's optional pricing refresh; this is not a fake // pricing response. The packaged application fallback remains in use. if (req.method === 'GET' && ['/disabled-pricing', '/disabled-pricing-hash'].includes(path)) { @@ -108,6 +124,16 @@ function upstream() { const capture = { sequence, marker, alias, model: input.model, prompt, refused } captures.push(capture) appendFileSync(join(evidence, 'provider-captures.jsonl'), JSON.stringify(capture) + '\n') + if (holdScheduled) { + await new Promise((resolve, reject) => { + const release = () => { clearTimeout(timer); heldReplies.delete(release); resolve() } + const timer = setTimeout(() => { + heldReplies.delete(release) + reject(new Error('fixture scheduled reply hold expired')) + }, 30_000) + heldReplies.add(release) + }) + } res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-cache' }) const event = data => res.write(`event: ${data.type}\ndata: ${JSON.stringify(data)}\n\n`) event({ type: 'message_start', message: { @@ -183,9 +209,11 @@ async function browser() { page.on('pageerror', error => state.pageErrors.push({ name: error.name })) page.on('console', message => { if (message.type() === 'error') state.consoleErrors.push({ type: 'error' }) }) const manualRequests = [] + const forbiddenRuns = [] let prepareCount = 0 page.on('request', request => { const path = new URL(request.url()).pathname + if (request.method() === 'POST' && /\/(?:scheduled-test-plans|pelican-group-tests)\/\d+\/run$/.test(path)) forbiddenRuns.push(path) if (path === '/api/v1/admin/accounts/pelican-question' && request.method() === 'GET') prepareCount++ const match = path.match(/^\/api\/v1\/admin\/accounts\/(\d+)\/pelican-test$/) if (match && request.method() === 'POST') { @@ -391,6 +419,521 @@ async function browser() { state.scenarios.push({ name: stage, status: 'passed', plan_id: created.id, boundary: 'disabled creation only; no scheduled RunDue, /run or result acceptance claimed' }) + stage = 'account-scheduled-ui-create-a-b' + await page.goto(`${origin}/admin/accounts`) + const plans = [] + const planProjection = plan => ({ id: String(plan.id), account_id: String(plan.account_id), + model_id: plan.model_id, enabled: plan.enabled, cron_expression: plan.cron_expression, + pelican_config: plan.pelican_config }) + for (const account of accounts) { + await openAccount(account) + await dialog().getByRole('button', { name: 'Scheduled tests', exact: true }).click() + await dialog().getByRole('button', { name: 'Add Plan', exact: true }).click() + const form = dialog().locator('div.rounded-xl').filter({ has: page.getByPlaceholder('*/30 * * * *', { exact: true }) }) + assert.equal(await form.count(), 1) + await form.locator('input[type=text]').first().fill(model) + // A far future real schedule prevents an accidental tick between the two + // UI creations; only next_run_at is aligned below, not enabled or config. + await form.getByPlaceholder('*/30 * * * *', { exact: true }).fill('0 0 1 1 *') + await form.getByTestId('pelican-mode-select').selectOption('random') + await form.locator('input[type=number]').last().fill('2') + const creation = page.waitForResponse(response => new URL(response.url()).pathname === '/api/v1/admin/scheduled-test-plans' && response.request().method() === 'POST') + await form.getByRole('button', { name: 'Save', exact: true }).click() + const response = await creation + assert.equal(response.status(), 200) + const plan = planProjection(unwrap(await response.json())) + assert.equal(plan.account_id, account.id) + assert.equal(plan.enabled, true) + assert.equal(plan.model_id, model) + assert.equal(plan.cron_expression, '0 0 1 1 *') + assert.equal(plan.pelican_config.question_kind, 'pelican') + assert.equal(plan.pelican_config.prompt_mode, 'random') + assert.equal(plan.pelican_config.parallel_count, 2) + assert.ok(!plan.pelican_config.pelican_question, 'plan is a rule, not an injected frozen question') + plans.push(plan) + await form.waitFor({ state: 'hidden' }) + await dialog().getByRole('button', { name: 'Close modal', exact: true }).click() + } + const planIds = plans.map(plan => plan.id) + assert.equal(new Set(planIds).size, 2) + const planSQL = `SELECT id::text, account_id::text, model_id, enabled, cron_expression, pelican_config, + 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, + 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` + const readPlans = async () => (await db.query(planSQL, [planIds])).rows + const readResults = async () => (await db.query(resultSQL, [planIds])).rows + const initialPlans = await readPlans() + assert.equal(initialPlans.length, 2) + for (const plan of initialPlans) { + assert.deepEqual(planProjection(plan), plans.find(item => item.id === plan.id)) + assert.equal(plan.running_until, null) + assert.equal(plan.last_run_at, null) + assert.ok(Date.parse(plan.next_run_at) > Date.now(), 'fresh plans must not yet be due') + } + assert.deepEqual(await readResults(), []) + save('account-scheduled-created.json', { api: plans, pg: initialPlans }) + state.scenarios.push({ name: stage, status: 'passed', plans: planIds, samples_per_account: 2 }) + + stage = 'account-scheduled-nominal-time-and-real-claim' + const fixtureControl = async path => { + const response = await fetch(`${upstreamOrigin}/__fixture/${path}`, { method: 'POST', signal: AbortSignal.timeout(5000) }) + assert.equal(response.status, 200) + return response.json() + } + const capturesNow = async () => { + const response = await fetch(`${upstreamOrigin}/__fixture/captures`, { signal: AbortSignal.timeout(5000) }) + assert.equal(response.status, 200) + return response.json() + } + const beforeScheduled = await capturesNow() + assert.equal(beforeScheduled.captures.length, 4, 'only previous manual samples exist') + assert.deepEqual(beforeScheduled.rejected, []) + const captureStart = beforeScheduled.captures.length + await fixtureControl('hold-scheduled') + let repliesReleased = false + try { + // The only SQL mutation after entity seeding. Bind both UI-created plan + // IDs to their exact fictional accounts, require untouched rules, and + // change only their nominal due time in one atomic statement. + const due = await db.query(`WITH nominal AS ( + SELECT date_trunc('second', now()) - interval '1 second' + interval '0.123456 second' AS t + ) UPDATE scheduled_test_plans p SET next_run_at = nominal.t + FROM nominal, accounts a + WHERE p.account_id = a.id AND a.deleted_at IS NULL + AND ((p.id = $1::bigint AND a.id = $2::bigint AND a.name = 'fixture-pelican-a') + OR (p.id = $3::bigint AND a.id = $4::bigint AND a.name = 'fixture-pelican-b')) + AND p.enabled AND p.model_id = $5 AND p.cron_expression = '0 0 1 1 *' + AND p.pelican_config->>'prompt_mode' = 'random' + AND p.pelican_config->>'parallel_count' = '2' + AND p.running_until IS NULL AND p.last_run_at IS NULL AND p.next_run_at > now() + AND NOT EXISTS (SELECT 1 FROM scheduled_test_results r WHERE r.plan_id = p.id) + RETURNING p.id::text, to_char(p.next_run_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS nominal_time`, + [plans[0].id, accounts[0].id, plans[1].id, accounts[1].id, model]) + assert.equal(due.rowCount, 2) + assert.equal(due.rows[0].nominal_time, due.rows[1].nominal_time) + const nominalTime = due.rows[0].nominal_time + save('account-scheduled-due.json', due.rows) + + const deadline = Date.now() + 90_000 // includes one real minute-tick wait + let claimed + while (Date.now() < deadline) { + const currentPlans = await readPlans() + const currentCaptures = await capturesNow() + assert.deepEqual(currentCaptures.rejected, []) + const sent = currentCaptures.captures.slice(captureStart) + assert.ok(sent.length <= 4, 'no duplicate scheduled submissions') + save('account-scheduled-wait.json', { nominal_time: nominalTime, plans: currentPlans, received_samples: sent.length }) + if (sent.length === 4 && currentPlans.length === 2 && currentPlans.every(plan => plan.lease_active)) { + assert.deepEqual(await readResults(), [], 'held upstream replies cannot yet yield result rows') + claimed = currentPlans + break + } + await new Promise(resolve => setTimeout(resolve, 250)) + } + assert.ok(claimed, 'real runner must claim both plans and send four samples within 90 seconds') + for (const plan of claimed) assert.ok(Date.parse(plan.next_run_at) > Date.parse(nominalTime)) + save('account-scheduled-claimed.json', { nominal_time: nominalTime, plans: claimed }) + const release = await fixtureControl('release-scheduled') + repliesReleased = true + assert.equal(release.released, 4) + + stage = 'account-scheduled-pg-provider-reconciliation' + let scheduledResults + const resultDeadline = Date.now() + 30_000 + while (Date.now() < resultDeadline) { + const rows = await readResults() + assert.ok(rows.length <= 4, 'exactly four scheduled results are expected') + if (rows.length === 4) { scheduledResults = rows; break } + await new Promise(resolve => setTimeout(resolve, 250)) + } + assert.ok(scheduledResults, 'real service must persist all four results') + const provider = await capturesNow() + assert.deepEqual(provider.rejected, []) + const sent = provider.captures.slice(captureStart) + assert.equal(sent.length, 4) + assert.equal(new Set(scheduledResults.map(row => row.marker)).size, 4) + const snapshot = scheduledResults[0].pelican_config + assert.equal(snapshot.prompt_mode, 'random') + assert.equal(snapshot.parallel_count, 2) + assert.equal(snapshot.pelican_question.source, 'builtin:svg-motion') + assert.ok(snapshot.pelican_question.id && snapshot.pelican_question.version && snapshot.actual_prompt) + assert.equal(snapshot.pelican_question.round_id, `scheduled:${nominalTime}`) + for (const [index, plan] of plans.entries()) { + const results = scheduledResults.filter(row => row.plan_id === plan.id) + assert.equal(results.length, 2) + for (const result of results) { + assert.equal(result.account_id, plan.account_id) + assert.equal(result.status, 'success') + assert.match(result.marker, /^fixture795-\d+$/) + assert.deepEqual(result.pelican_config, snapshot, 'all four samples freeze the same rule and question') + assert.equal(result.pelican_config.trigger_source, 'scheduled') + const capture = sent.find(item => item.marker === result.marker) + assert.ok(capture, 'PG marker must identify an actual provider request') + assert.equal(capture.alias, index === 0 ? 'a' : 'b') + assert.equal(capture.model, model) + assert.equal(capture.prompt, result.pelican_config.actual_prompt.trim()) + assert.equal(capture.refused, false) + } + } + save('account-scheduled-results.json', { nominal_time: nominalTime, pg: scheduledResults, provider: sent }) + state.scenarios.push({ name: 'account-scheduled-nominal-time-and-real-claim', status: 'passed', nominal_time: nominalTime, plans: planIds }) + state.scenarios.push({ name: stage, status: 'passed', result_ids: scheduledResults.map(row => row.id) }) + + stage = 'account-scheduled-history-detail-dom' + for (const account of accounts) { + await openAccount(account) + const expected = scheduledResults.filter(row => row.account_id === account.id) + // Read responses caused by the actual page. No independent token reads, + // API request substitutes, fabricated store state or fulfilled routes. + const details = new Map() + const pending = [] + const detailErrors = [] + const observeDetail = response => { + const path = new URL(response.url()).pathname + const match = path.match(/^\/api\/v1\/admin\/scheduled-test-plans\/(\d+)\/results\/(\d+)$/) + if (!match || !expected.some(row => row.plan_id === match[1] && row.id === match[2])) return + pending.push((async () => { + assert.equal(response.status(), 200) + const value = unwrap(await response.json()) + const binding = bindDetailResponse(response.request().url(), value, expected) + const record = { status: response.status(), value, binding } + details.set(binding.request_result_id, record) + return record + })().catch(error => { + detailErrors.push({ name: error.name, message: error.message }) + return { read_error: error.name } + })) + } + page.on('response', observeDetail) + 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 history = await historyResponse + assert.equal(history.status(), 200) + const historyBody = unwrap(await history.json()) + assert.equal(historyBody.next_cursor, 0) + assert.equal(historyBody.items.length, 2) + for (const row of expected) { + const item = historyBody.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.deepEqual(item.pelican_config, row.pelican_config) + } + const panel = page.getByTestId('records-panel') + // Validate URL -> body -> PG for every response BEFORE selecting any + // marker-based card. Swapped bodies must fail before a screenshot can + // be mislabeled. The map is keyed only by validated request identity. + const detailDeadline = Date.now() + 20_000 + while (details.size < expected.length && detailErrors.length === 0 && Date.now() < detailDeadline) { + await new Promise(resolve => setTimeout(resolve, 50)) + } + assert.deepEqual(detailErrors, [], 'detail URL/body/PG identity validation must pass before DOM binding') + assert.equal(details.size, expected.length) + for (const row of expected) { + const { binding } = details.get(row.id) + assert.equal(binding.request_plan_id, row.plan_id) + assert.equal(binding.request_result_id, row.id) + assert.equal(binding.marker, row.marker) + const card = panel.getByTestId('pelican-record-card').filter({ has: page.locator(`iframe[srcdoc*="${binding.marker}"]`) }) + await card.waitFor({ state: 'visible' }) + assert.equal(await card.count(), 1) + await card.getByRole('button').click() + const detail = page.getByTestId('record-detail') + await checkSnapshot(detail, row.pelican_config) + assert.equal(await detail.frameLocator('iframe').locator('p').innerText(), row.marker) + await page.screenshot({ path: join(evidence, `account-scheduled-${account.id}-${binding.request_result_id}.png`), fullPage: true }) + await detail.getByRole('button', { name: 'Close', exact: true }).click() + } + await panel.getByRole('button', { name: 'Close', exact: true }).click() + for (const response of await Promise.all(pending)) { + assert.equal(response.read_error, undefined, 'real detail response must be readable') + assert.equal(response.status, 200) + // Includes duplicate/poll responses: each must retain its own URL + // binding, rather than trusting an unordered set of body IDs. + assert.deepEqual(response.binding, bindDetailResponse(`http://app:8080${response.binding.request_path}`, response.value, expected)) + } + assert.deepEqual(detailErrors, [], 'all observed detail responses must keep their URL identity') + assert.equal(details.size, 2) + for (const row of expected) { + const api = details.get(row.id)?.value + assert.ok(api) + assert.equal(String(api.plan_id), row.plan_id) + assert.equal(api.status, row.status) + assert.deepEqual(api.pelican_config, row.pelican_config) + assert.equal(api.response_text.match(/fixture795-\d+/)?.[0], row.marker) + } + save(`account-scheduled-history-${account.id}.json`, { + history: historyBody.items.map(item => ({ id: item.id, plan_id: item.plan_id, account_id: item.account_id, + status: item.status, pelican_config: item.pelican_config })), + detail: [...details.values()].map(({ value: item, binding }) => ({ id: item.id, plan_id: item.plan_id, + status: item.status, pelican_config: item.pelican_config, marker: binding.marker, request_binding: binding })), + expanded_dom: expected.map(row => ({ result_id: row.id, marker: row.marker, snapshot: row.pelican_config, + request_binding: details.get(row.id).binding })), + }) + } finally { + page.off('response', observeDetail) + } + await dialog().getByRole('button', { name: 'Close modal', exact: true }).click() + } + assert.deepEqual(await readResults(), scheduledResults, 'reading history must not change saved results') + assert.deepEqual(forbiddenRuns, [], 'no manual /run may stand in for scheduled execution') + assert.equal(manualRequests.length, 4, 'no new manual submission may stand in for scheduled execution') + state.scenarios.push({ name: stage, status: 'passed', result_ids: scheduledResults.map(row => row.id) }) + } finally { + // On assertion failure unblock the provider, but retain the original error + // and leave all database rows to the application / disposable CI cleanup. + if (!repliesReleased) { + try { await fixtureControl('release-scheduled') } + catch (error) { save('account-scheduled-release-error.json', { name: error.name }) } + } + } + + stage = 'group-scheduled-ui-enable' + await page.goto(`${origin}/admin/pelican-tests`) + const groupPlanId = String(created.id) + const groupId = groups[0].id + const groupPlanPath = `/api/v1/admin/pelican-group-tests/${groupPlanId}` + // Keep the already-tested disabled creation intact. Edit only its schedule + // through the real form before enabling, to avoid an unintended due tick. + await page.getByTestId(`pelican-plan-edit-${groupPlanId}`).click() + const groupEditor = page.getByTestId('pelican-test-editor') + assert.equal(await groupEditor.getByTestId('pelican-test-enabled').getAttribute('aria-checked'), 'false') + await groupEditor.getByTestId('pelican-test-schedule').getByRole('button').click() + await page.getByRole('option', { name: 'Custom', exact: true }).click() + await groupEditor.getByTestId('pelican-test-cron').fill('0 0 1 1 *') + const groupEditResponse = page.waitForResponse(response => new URL(response.url()).pathname === groupPlanPath && response.request().method() === 'PUT') + await page.getByTestId('pelican-test-save').click() + const groupEdited = await groupEditResponse + assert.equal(groupEdited.status(), 200) + const groupEditedBody = unwrap(await groupEdited.json()) + assert.equal(groupEditedBody.enabled, false) + assert.equal(groupEditedBody.cron_expression, '0 0 1 1 *') + await groupEditor.waitFor({ state: 'hidden' }) + // savePlan closes the editor before its list reload completes. Wait until + // the actual row carries the new schedule, so toggle cannot resend stale input. + await page.getByTestId(`pelican-plan-${groupPlanId}`).locator('.plan-meta').getByText('0 0 1 1 *', { exact: true }).waitFor() + const groupEnableResponse = page.waitForResponse(response => new URL(response.url()).pathname === groupPlanPath && response.request().method() === 'PUT') + await page.getByTestId(`pelican-plan-toggle-${groupPlanId}`).click() + const groupEnabled = await groupEnableResponse + assert.equal(groupEnabled.status(), 200) + const groupEnabledBody = unwrap(await groupEnabled.json()) + assert.equal(String(groupEnabledBody.id), groupPlanId) + assert.equal(String(groupEnabledBody.group_id), groupId) + assert.equal(groupEnabledBody.enabled, true) + assert.equal(groupEnabledBody.model_id, model) + assert.equal(groupEnabledBody.cron_expression, '0 0 1 1 *') + assert.deepEqual(groupEnabledBody.pelican_config, groupEditedBody.pelican_config) + assert.equal(groupEnabledBody.pelican_config.prompt_mode, 'random') + assert.equal(groupEnabledBody.pelican_config.parallel_count, 2) + assert.ok(!groupEnabledBody.pelican_config.pelican_question) + await page.getByTestId(`pelican-plan-${groupPlanId}`).getByRole('button', { name: 'Pause', exact: true }).waitFor() + const groupPlanSQL = `SELECT p.id::text, p.group_id::text, p.enabled, p.model_id, + p.cron_expression, p.pelican_config, + to_char(p.next_run_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS next_run_at, + p.running_until::text, p.last_run_at::text, p.running_until > now() AS lease_active + 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, + 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 + WHERE r.plan_id = $1::bigint AND p.group_id = $2::bigint ORDER BY r.id` + const readGroupPlan = async () => { + const { rows } = await db.query(groupPlanSQL, [groupPlanId, groupId]) + assert.equal(rows.length, 1) + return rows[0] + } + const readGroupResults = async () => (await db.query(groupResultSQL, [groupPlanId, groupId])).rows + const enabledGroupPlan = await readGroupPlan() + assert.equal(enabledGroupPlan.enabled, true) + assert.equal(enabledGroupPlan.model_id, model) + assert.equal(enabledGroupPlan.cron_expression, '0 0 1 1 *') + assert.deepEqual(enabledGroupPlan.pelican_config, groupEnabledBody.pelican_config) + assert.equal(enabledGroupPlan.last_run_at, null) + assert.equal(enabledGroupPlan.running_until, null) + assert.ok(Date.parse(enabledGroupPlan.next_run_at) > Date.now()) + assert.deepEqual(await readGroupResults(), []) + save('group-scheduled-enabled.json', { + api: { id: groupEnabledBody.id, group_id: groupEnabledBody.group_id, enabled: groupEnabledBody.enabled, + model_id: groupEnabledBody.model_id, cron_expression: groupEnabledBody.cron_expression, + pelican_config: groupEnabledBody.pelican_config }, pg: enabledGroupPlan, + }) + state.scenarios.push({ name: stage, status: 'passed', plan_id: groupPlanId, group_id: groupId }) + + stage = 'group-scheduled-due-and-real-claim' + const beforeGroup = await capturesNow() + assert.deepEqual(beforeGroup.rejected, []) + assert.equal(beforeGroup.captures.length, 8, 'only manual and account-scheduled samples precede this round') + const groupCaptureStart = beforeGroup.captures.length + await fixtureControl('hold-scheduled') + let groupRepliesReleased = false + try { + // Only this fixture plan's nominal due field is changed. Enabling and + // schedule configuration above went through the actual authenticated UI. + const due = await db.query(`WITH nominal AS ( + SELECT date_trunc('second', now()) - interval '1 second' + interval '0.654321 second' AS t + ) UPDATE pelican_group_test_plans p SET next_run_at = nominal.t + FROM nominal, groups g + WHERE p.id = $1::bigint AND p.group_id = $2::bigint AND g.id = p.group_id + AND g.name = 'fixture-pelican-group' AND g.deleted_at IS NULL AND g.status = 'active' + AND p.enabled AND p.model_id = $3 AND p.cron_expression = '0 0 1 1 *' + AND p.pelican_config->>'prompt_mode' = 'random' + AND p.pelican_config->>'parallel_count' = '2' + AND p.running_until IS NULL AND p.last_run_at IS NULL AND p.next_run_at > now() + AND NOT EXISTS (SELECT 1 FROM pelican_group_test_results r WHERE r.plan_id = p.id) + RETURNING p.id::text, to_char(p.next_run_at AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS nominal_time`, + [groupPlanId, groupId, model]) + assert.equal(due.rowCount, 1) + const groupNominalTime = due.rows[0].nominal_time + save('group-scheduled-due.json', due.rows[0]) + let groupClaim + const claimDeadline = Date.now() + 90_000 + while (Date.now() < claimDeadline) { + const plan = await readGroupPlan() + const provider = await capturesNow() + assert.deepEqual(provider.rejected, []) + const sent = provider.captures.slice(groupCaptureStart) + assert.ok(sent.length <= 2, 'group success fixture must not duplicate or retry submissions') + save('group-scheduled-wait.json', { nominal_time: groupNominalTime, plan, received_samples: sent.length }) + if (sent.length === 2 && plan.lease_active) { + assert.deepEqual(await readGroupResults(), [], 'held provider replies cannot yet yield group results') + assert.ok(Date.parse(plan.next_run_at) > Date.parse(groupNominalTime)) + groupClaim = plan + break + } + await new Promise(resolve => setTimeout(resolve, 250)) + } + assert.ok(groupClaim, 'real group RunDue/Claim must send two samples within 90 seconds') + save('group-scheduled-claimed.json', { nominal_time: groupNominalTime, plan: groupClaim }) + const release = await fixtureControl('release-scheduled') + groupRepliesReleased = true + assert.equal(release.released, 2) + state.scenarios.push({ name: stage, status: 'passed', plan_id: groupPlanId, nominal_time: groupNominalTime }) + + stage = 'group-scheduled-pg-provider-reconciliation' + let groupResults + let completedGroupPlan + const resultsDeadline = Date.now() + 30_000 + while (Date.now() < resultsDeadline) { + const results = await readGroupResults() + const plan = await readGroupPlan() + assert.ok(results.length <= 2) + if (results.length === 2 && plan.running_until === null && plan.last_run_at !== null) { + groupResults = results + completedGroupPlan = plan + break + } + await new Promise(resolve => setTimeout(resolve, 250)) + } + assert.ok(groupResults, 'two real group results and successful-run lease completion are required') + assert.ok(Date.parse(completedGroupPlan.next_run_at) > Date.parse(groupNominalTime)) + const groupProvider = await capturesNow() + assert.deepEqual(groupProvider.rejected, []) + const groupSent = groupProvider.captures.slice(groupCaptureStart) + assert.equal(groupSent.length, 2) + assert.equal(new Set(groupResults.map(row => row.marker)).size, 2) + const groupSnapshot = groupResults[0].pelican_config + assert.equal(groupSnapshot.prompt_mode, 'random') + assert.equal(groupSnapshot.parallel_count, 2) + assert.equal(groupSnapshot.model_id, model) + assert.equal(groupSnapshot.pelican_question.round_id, `scheduled:${groupNominalTime}`) + assert.equal(groupSnapshot.pelican_question.source, 'builtin:svg-motion') + assert.ok(groupSnapshot.pelican_question.id && groupSnapshot.pelican_question.version && groupSnapshot.actual_prompt) + for (const row of groupResults) { + assert.equal(row.plan_id, groupPlanId) + assert.equal(row.group_id, groupId) + assert.equal(row.status, 'success') + assert.equal(row.attempt_count, 0) + assert.match(row.marker, /^fixture795-\d+$/) + assert.deepEqual(row.pelican_config, groupSnapshot) + const accountIndex = accounts.findIndex(account => account.id === row.account_id) + assert.ok(accountIndex >= 0, 'gateway must route to a fixture account') + assert.equal(row.account_name, accounts[accountIndex].name) + const capture = groupSent.find(item => item.marker === row.marker) + assert.ok(capture) + assert.equal(capture.alias, accountIndex === 0 ? 'a' : 'b') + assert.equal(capture.model, model) + assert.equal(capture.prompt, row.pelican_config.actual_prompt.trim()) + assert.equal(capture.refused, false) + // Both samples may legitimately choose the same account. No balance or + // equal-route assertion: record and reconcile the actual chosen account. + } + save('group-scheduled-results.json', { nominal_time: groupNominalTime, plan: completedGroupPlan, pg: groupResults, provider: groupSent }) + state.scenarios.push({ name: stage, status: 'passed', plan_id: groupPlanId, result_ids: groupResults.map(row => row.id) }) + + stage = 'group-scheduled-list-detail-dom' + // PelicanTestsView polls its real list API. Wait for a poll containing this + // run, without injecting a store update or issuing a substitute request. + const listed = await page.waitForResponse(async response => { + if (new URL(response.url()).pathname !== '/api/v1/admin/pelican-group-test-results' + || response.request().method() !== 'GET' || response.status() !== 200) return false + const body = unwrap(await response.json()) + return Array.isArray(body.items) && groupResults.every(row => body.items.some(item => String(item.id) === row.id)) + }, { timeout: 25_000 }) + const list = unwrap(await listed.json()) + assert.equal(list.total, 2) + 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 }) + const expectedAPIProjection = row => { + const { marker, ...projection } = row + return projection + } + const detailProjection = [] + const domProjection = [] + for (const row of groupResults) { + const item = list.items.find(item => String(item.id) === row.id) + assert.deepEqual(groupAPIProjection(item), expectedAPIProjection(row)) + assert.equal(item.group_name, groups[0].name) + 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(), 'Success') + const detailResponse = page.waitForResponse(response => new URL(response.url()).pathname === `/api/v1/admin/pelican-group-test-results/${row.id}` && response.request().method() === 'GET') + await page.getByTestId(`pelican-result-view-${row.id}`).click() + const response = await detailResponse + assert.equal(response.status(), 200) + const full = unwrap(await response.json()) + const requestBinding = bindDetailResponse(response.request().url(), full, [row], 'group') + assert.deepEqual(groupAPIProjection(full), expectedAPIProjection(row)) + assert.equal(full.response_text.match(/fixture795-\d+/)?.[0], row.marker) + const preview = page.getByTestId('pelican-result-preview') + await preview.getByTestId('pelican-artwork-preview').locator('iframe').waitFor({ state: 'visible' }) + await checkSnapshot(preview, row.pelican_config) + assert.equal(await preview.frameLocator('iframe').locator('p').innerText(), row.marker) + await page.screenshot({ path: join(evidence, `group-scheduled-${groupPlanId}-${row.id}.png`), fullPage: true }) + detailProjection.push({ ...groupAPIProjection(full), marker: row.marker, request_binding: requestBinding }) + domProjection.push({ result_id: row.id, plan_id: groupPlanId, group_id: groupId, + account_id: row.account_id, marker: row.marker, snapshot: row.pelican_config, request_binding: requestBinding }) + await page.getByRole('dialog').filter({ has: preview }).getByRole('button', { name: 'Close', exact: true }).click() + await preview.waitFor({ state: 'hidden' }) + } + save('group-scheduled-api-dom.json', { list: list.items.map(groupAPIProjection), detail: detailProjection, expanded_dom: domProjection }) + assert.deepEqual(await readGroupResults(), groupResults, 'viewing group history must not mutate saved results') + assert.deepEqual(forbiddenRuns, [], 'group RunDue cannot be substituted with manual /run') + assert.equal(manualRequests.length, 4, 'group results cannot come from extra manual account tests') + assert.equal((await capturesNow()).captures.length, groupCaptureStart + 2) + state.scenarios.push({ name: stage, status: 'passed', plan_id: groupPlanId, result_ids: groupResults.map(row => row.id) }) + } finally { + if (!groupRepliesReleased) { + try { await fixtureControl('release-scheduled') } + catch (error) { save('group-scheduled-release-error.json', { name: error.name }) } + } + } + stage = 'post-bootstrap-browser-and-provider-error-lists' const finalCaptures = await (await fetch(`${upstreamOrigin}/__fixture/captures`)).json() assert.deepEqual(finalCaptures.rejected, []) @@ -399,7 +942,7 @@ async function browser() { assert.equal(state.consoleErrors.length, 0, 'no browser console errors') assert.equal(state.requestFailures.length, 0, 'no failed browser requests') state.scenarios.push({ name: stage, status: 'passed' }) - console.log('Implemented initial E2E scenarios passed; full acceptance remains incomplete.') + console.log('Implemented manual, account and group scheduled E2E scenarios passed; full acceptance remains incomplete.') } catch (error) { state.scenarios.push({ name: stage, status: 'failed', error: { name: error.name, message: error.message.slice(0, 2000) } }) if (page) { diff --git a/.github/workflows/pelican-random-questions.yml b/.github/workflows/pelican-random-questions.yml index 90d5550b4e27..da7320811013 100644 --- a/.github/workflows/pelican-random-questions.yml +++ b/.github/workflows/pelican-random-questions.yml @@ -31,6 +31,7 @@ on: - 'frontend/src/components/admin/account/IQTestModal.vue' - '.github/fixtures/pelican-question-e2e/**' - '.github/scripts/pelican-question-e2e.mjs' + - '.github/scripts/pelican-detail-identity.mjs' - '.github/scripts/pelican-question-browser.mjs' - '.github/workflows/pelican-random-questions.yml' - 'Dockerfile' @@ -73,13 +74,13 @@ jobs: name: pelican-random-question-ui-${{ github.run_id }} path: evidence/ isolated-e2e: - name: Isolated application E2E (initial scope; full acceptance pending) + name: Isolated application E2E (manual, account and group schedules; full acceptance pending) runs-on: ubuntu-latest timeout-minutes: 45 env: APP_SHA: ${{ github.event.pull_request.head.sha || github.sha }} HARNESS_SHA: ${{ github.event.pull_request.head.sha || github.sha }} - PARENT_BASE_SHA: 3e07fa89096cb58b260c032aa6de2cb2a2aa98b7 + PARENT_BASE_SHA: dbed7697aa56e76c6eb48c4914fa441496b67bdd COMPOSE_PROJECT_NAME: pelican-${{ github.run_id }}-${{ github.run_attempt }} steps: - uses: actions/checkout@v6 @@ -108,6 +109,15 @@ jobs: printf 'PARENT_BASE_SHA=%s\nRUN_ID=%s\nRUN_ATTEMPT=%s\n' "$PARENT_BASE_SHA" "$GITHUB_RUN_ID" "$GITHUB_RUN_ATTEMPT" } > "$EVIDENCE_DIR/identity.txt" cp harness/.github/fixtures/pelican-question-e2e/acceptance.json "$EVIDENCE_DIR/acceptance.json" + - uses: actions/setup-node@v6 + with: + node-version: '22' + - name: Synthetic detail identity gate (does not replace real E2E) + shell: bash + run: | + set -euo pipefail + node --test harness/.github/fixtures/pelican-question-e2e/detail-identity.test.mjs \ + | tee "$EVIDENCE_DIR/detail-identity-synthetic.tap" - name: Build and prefetch before runtime isolation (CI only) shell: bash run: | @@ -146,7 +156,7 @@ jobs: run: | set -euo pipefail container_id="$(docker compose ps --all --quiet browser)" - result="$(timeout 300s docker wait "$container_id")" + result="$(timeout 660s 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 @@ -155,11 +165,15 @@ jobs: shell: bash run: | { - echo '### Isolated E2E initial increment — full acceptance pending' - echo 'This job exercises the implemented manual scenarios and disabled group-plan creation only.' - echo 'Account/group scheduled RunDue, PG/API/DOM result reconciliation, immutable old snapshots,' - echo 'second nominal round, deterministic failed record and lease release remain unimplemented.' - echo 'A green initial job does not clear the Issue #795 technical or product acceptance gates.' + echo '### Isolated E2E manual, account and group schedules — full acceptance pending' + echo 'Implemented: manual scenarios, disabled group-plan creation, UI-created A/B account schedules,' + 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 '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" - name: Destroy all disposable runtime containers and volumes if: always()