diff --git a/CHANGELOG.md b/CHANGELOG.md index 8228831..00cc4e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Changelog +## 开发快照 0.1.420(需求单候选排队) + +- 需求单预检通过后自动排队等待验收环境,构建链接回填原单。已发布批次释放其测试容器,接续下一张需求。 + ## 开发快照 0.1.419(候选预检识别落地 merge) - 预检支持从含多个版本号的提交链中识别 `落地 merge`,并分别提示缺少和存在多个落地版本。 diff --git a/deploy/systemd/kg-demand-queue.service b/deploy/systemd/kg-demand-queue.service new file mode 100644 index 0000000..393f81c --- /dev/null +++ b/deploy/systemd/kg-demand-queue.service @@ -0,0 +1,7 @@ +[Unit] +Description=Advance original-task candidate queue + +[Service] +Type=oneshot +ExecStart=%h/.local/lib/kg-candidate-release/python3 %h/.local/lib/kg-candidate-release/scripts/candidate_queue.py +TimeoutStartSec=180 diff --git a/deploy/systemd/kg-demand-queue.timer b/deploy/systemd/kg-demand-queue.timer new file mode 100644 index 0000000..2a24997 --- /dev/null +++ b/deploy/systemd/kg-demand-queue.timer @@ -0,0 +1,10 @@ +[Unit] +Description=Check reviewed demand tasks waiting for QA + +[Timer] +OnStartupSec=30s +OnUnitInactiveSec=45s +AccuracySec=5s + +[Install] +WantedBy=timers.target diff --git a/docs/CANDIDATE_RELEASE_RUNBOOK.md b/docs/CANDIDATE_RELEASE_RUNBOOK.md index 42624e5..7058b31 100644 --- a/docs/CANDIDATE_RELEASE_RUNBOOK.md +++ b/docs/CANDIDATE_RELEASE_RUNBOOK.md @@ -1,5 +1,9 @@ # 知识治理候选和批次验收 +## 需求单的六个状态 + +新需求默认「规划中」。负责人确认方案后进入「进行中」。开发提测后进入「待测试」,白盒预检通过时按原评论登记队列,环境占用时在原单等候。执行器构建候选后转「测试中」,QA 的同包报告通过后系统在需求单登记验收。负责人将原单转「待发布」授权 CD,部署核验通过后回写「已发布」。队列执行器定时运行 `candidate_queue.py`,按已发布回执及容器身份释放旧候选并接续等待项。 + ## 在原需求单发布 白小浅预检通过后,执行器从原单核对合入版本与 CI,在同一张单列出线上基线和随批提交,自动准备隔离候选。候选就绪后进入「测试中」。QA 在原单对同一归档执行需求用例和批次回归,结构化报告的 `cases.business` 与 `cases.regression` 分别列出唯一的已通过用例编号,总数与 `required` 一致。系统登记后,在原单显示「批次验收通过」。发布负责人将原单切到「待发布」即触发 CD。负责人可从原单查看归档、证据和发布记录。 diff --git a/scripts/candidate_queue.py b/scripts/candidate_queue.py new file mode 100644 index 0000000..b477c79 --- /dev/null +++ b/scripts/candidate_queue.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python3 +"""Drain reviewed demand tasks through the shared candidate environment.""" +import json + +import release_handoff as h + +cd = h.cd +coordinator = h.coordinator + + +def release_published_slot(compose): + directory = compose.parent + ready = cd.read_json(cd.immutable_file(directory / 'ready.json')) + task = h.assistant.task_record(ready['task']) + published = cd.metadata(task, 'cd_release') or {} + if task['status']['id'] != cd.PUBLISHED or not all(published.get(k) == ready[k] for k in ('sha', 'bundle')): + return False + project = 'kg-batch-' + ready['bundle'][:20] + cd.require(ready['mode'] == 'acceptance' and cd.hash_file(directory / 'bundle/release.json') == ready['bundle'], + 'published QA archive changed') + cd.require(set(ready['containers']) == {'api', 'web', 'worker'}, 'unexpected candidate service set') + ids = [] + for role, name in ready['containers'].items(): + cd.require(name == project + '-' + role, 'candidate name mismatch') + info = json.loads(cd.run(['docker', 'inspect', name], 'inspect QA container'))[0] + labels = info['Config']['Labels'] + cd.require(labels.get('com.docker.compose.project') == project and info['Image'] == ready['images'][role], + 'candidate container identity changed') + ids.append(info['Id']) + cd.run(['docker', 'stop', *ids], 'retire published QA environment', timeout=90) + info = json.loads(cd.run(['docker', 'inspect', *ids], 'verify stopped QA containers')) + cd.require(len(info) == len(ids) and not any(row['State']['Running'] for row in info), 'QA slot still running') + compose.rename(directory / 'compose.released.json') + return True + + +def in_flight(state): + for path in state.glob('*.dispatch.json'): + claim = cd.read_json(cd.immutable_file(path)) + key = path.name.split('.')[0] + if (state / key / 'ready.json').is_file(): + continue + if claim['state'] != 'queued': + return True + run = h.candidate.read_forge(h.candidate.API + '/actions/runs/' + str(claim['run'])) + if run['status'] != 'completed' or run.get('conclusion') == 'success': + return True + return False + + +def drain(): + state = coordinator.STATE + waiting = state / 'waiting' + waiting.mkdir(mode=0o700, parents=True, exist_ok=True) + with cd.deploy_lock(waiting / 'queue.lock'): + entries = sorted(waiting.glob('*.json'), key=lambda p: (p.stat().st_mtime_ns, p.name)) + entries = [(p, cd.read_json(cd.immutable_file(p))) for p in entries] + entries = [(p, e) for p, e in entries if e['state'] == 'waiting_for_slot'] + if not entries: + return 'idle' + with cd.deploy_lock(state / 'runtime.lock'): + for compose in state.glob('*/compose.json'): + if not release_published_slot(compose): + return 'occupied' + if in_flight(state): + return 'building' + path, entry = entries[0] + task = h.assistant.task_record(entry['task']) + try: + sha, _ = h.resolve(task, entry['event']) + cd.require(sha == entry['sha'], 'review changed before building') + live = h.assistant.worker.main_site_sha() + if h.candidate.git('merge-base', live, sha, cwd=h.assistant.SOURCE, allowed=(0, 1)) == sha: + notice = f'主站当前版本 `{live}` 已包含候选提交 `{sha}`。请核对该需求的发布与验收记录。' + entry.update(state='included_in_live') + else: + result = h.prepare_from_review(task, entry['event']) + entry.update(state='dispatched', result=result) + notice = '候选构建已排队。' + result['url'] + except cd.CDError as exc: + entry.update(state='blocked', reason=str(exc)) + notice = '候选准备已停止。' + str(exc) + cd.record(path, entry) + coordinator.add_comment(task['id'], 'queue-result ' + entry['event'], notice) + return entry['state'] + + +if __name__ == '__main__': + print(drain()) diff --git a/scripts/release_handoff.py b/scripts/release_handoff.py index ffff666..063376d 100644 --- a/scripts/release_handoff.py +++ b/scripts/release_handoff.py @@ -90,6 +90,26 @@ def frozen_approval(task_id, comment_id=None): def preflight(task, event=None): + """Persist the task's verified review before trying the shared QA environment.""" + sha, _ = resolve(task, event) + if event is None: + reviews = [r for r in comments(task['id']) if author(r) == WHITE and r['content'].startswith('🚦')] + event = max(reviews, key=lambda r: r['createdAt'])['id'] + review_identity(task, reviews, event) + waiting = coordinator.STATE / 'waiting' + waiting.mkdir(mode=0o700, exist_ok=True, parents=True) + path = waiting / (event + '.json') + with cd.deploy_lock(waiting / 'queue.lock'): + if not path.exists(): + cd.record(path, {'task': task['id'], 'event': event, 'sha': sha, 'state': 'waiting_for_slot'}) + entry = cd.read_json(cd.immutable_file(path)) + cd.require(entry['task'] == task['id'] and entry['sha'] == sha, 'queue entry identity changed') + if entry['state'] == 'waiting_for_slot': + coordinator.add_comment(task['id'], 'waiting ' + event, f'候选已排队,目标提交 `{sha}`。环境可用后自动准备,候选就绪后进入测试中。') + return entry + + +def prepare_from_review(task, event): """Freeze a test candidate on the originating task. Production still requires its owner event.""" sha, ref = resolve(task, event) DIRECTORY.mkdir(mode=0o700, parents=True, exist_ok=True) diff --git a/scripts/test_release_handoff.py b/scripts/test_release_handoff.py index f2a7378..57a6cc2 100644 --- a/scripts/test_release_handoff.py +++ b/scripts/test_release_handoff.py @@ -3,6 +3,7 @@ import unittest from pathlib import Path from unittest.mock import patch +import candidate_queue as queue import release_handoff as h @@ -33,6 +34,48 @@ class ReleaseHandoffTest(unittest.TestCase): with self.assertRaisesRegex(h.cd.CDError, error): h.review_identity(self.task, [row], 'comment') + def test_busy_candidate_waits_on_original_task_without_dispatch(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \ + patch.object(h, 'resolve', return_value=('a' * 40, '30')), \ + patch.object(h.coordinator, 'add_comment'), patch.object(h.coordinator, 'queue') as dispatch: + task_id = '00000001-1111-2222-3333-444444444444' + event = '00000002-1111-2222-3333-444444444444' + slot = Path(tmp) / 'another' / 'compose.json' + slot.parent.mkdir() + slot.touch() + first = h.preflight({'id': task_id}, event) + second = h.preflight({'id': task_id}, event) + self.assertEqual(first, second) + self.assertEqual(first['state'], 'waiting_for_slot') + self.assertEqual(len(list((Path(tmp) / 'waiting').glob('*.json'))), 1) + dispatch.assert_not_called() + + def test_waiter_dispatches_once_when_slot_is_free(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \ + patch.object(h, 'resolve', return_value=('a' * 40, '30')), \ + patch.object(h.assistant, 'task_record', return_value={'id': 'task'}), \ + patch.object(h.assistant.worker, 'main_site_sha', return_value='b' * 40), \ + patch.object(h.candidate, 'git', return_value='b' * 40), \ + patch.object(h.coordinator, 'add_comment'), \ + patch.object(h, 'prepare_from_review', return_value={'url': 'https://example.test/run/1'}) as build: + h.preflight({'id': 'task'}, 'event') + self.assertEqual(queue.drain(), 'dispatched') + self.assertEqual(queue.drain(), 'idle') + build.assert_called_once_with({'id': 'task'}, 'event') + + def test_active_qa_slot_is_preserved(self): + with tempfile.TemporaryDirectory() as tmp, patch.object(h.coordinator, 'STATE', Path(tmp)), \ + patch.object(h.assistant, 'task_record', return_value={'status': {'id': 'testing'}}), \ + patch.object(h.cd, 'run') as docker: + root = Path(tmp) + (root / 'waiting').mkdir() + h.cd.record(root / 'waiting/event.json', {'state': 'waiting_for_slot'}) + (root / 'slot').mkdir() + (root / 'slot/compose.json').touch() + h.cd.record(root / 'slot/ready.json', {'task': 'task'}) + self.assertEqual(queue.drain(), 'occupied') + docker.assert_not_called() + def test_owner_approval_is_bound_to_exact_preview_and_parent(self): with tempfile.TemporaryDirectory() as tmp, patch.object(h, 'DIRECTORY', Path(tmp)): saved = {'content': 'reviewed scope', 'comment': 'preview', 'plan': {'frozen': True}}