Compare commits

...
Author SHA1 Message Date
elforeign f1ec653b91 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:06:04 -06:00
elforeign b1ab08c09d agent queue: apply claim checks when /reassign creates a claim
/reassign turned a ready task into a claim without the dependency and
file-overlap checks /claim applies, so a maintainer reassignment could
grant two overlapping claims. Run the same checks for the new holder.

Refs #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:47 -06:00
elforeign 6b479a6617 agent queue: fix review findings in replies, verification and issue forms
From independent review of the queue follow-up:
- Bot replies echoed user text (/blocked reasons, /reassign logins,
  file patterns) verbatim. Markers count when the bot posts them, so a
  reason containing an approval or done marker became a bot marker and
  could approve an acceptance command or hide another user's claim.
  Echoed text now has angle brackets and backticks escaped.
- /verified accepted a 7-character prefix and ignored extra arguments;
  a commit with the same short prefix is cheap to make. Require exactly
  one full 40-character SHA, with one parser shared by decide and the
  check.
- After a verification, the job looked up the check run by the pull
  request head SHA, but pull_request_target runs carry the base branch
  SHA, so it found nothing and || true hid it. The verify job now
  evaluates the same advisory check itself and no longer needs
  actions: write.
- The issue form renders Files inside a ```text fence and the parser
  took "text" as a path, so any two form-created tasks overlapped.
  Fence lines are skipped.
- A command still unanswered after lease_hours now gets a "Not decided"
  reply (window 2 x lease_hours) instead of being dropped silently.

Each fix has a test shown to fail with the fix reverted.

Refs #210, #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:05:28 -06:00
elforeign e70780f30a Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 01:00:40 -06:00
Ranveer Soni 0cac6c4fcf Merge pull request #214 from elforeign/test/metal-bc2-bc3
test(metal): BC2/BC3 upload and sampling conformance (#168)
2026-11-24 12:30:21 +05:30
Ranveer Soni b69d4b97c6 Merge pull request #166 from elforeign/feat/gpu-compatibility-expansion
isa: complete gfx1030 instruction metadata and identification
2026-11-24 12:26:27 +05:30
elforeign 9fda5aab18 agent queue: re-run the check only after an accepted verification
The verify job re-ran the pull request check after any /verified
comment, including refused ones: the author's own, a non-verifier's, a
stale or unknown head or a malformed SHA. decide now marks only an
accepted verification of the current head, and the job re-runs the check
only when should-rerun confirms it. A test checks that what re-runs the
check is exactly what the check counts.

Replay decides a comment listed twice only once. Tests cover duplicate
and out-of-order listings, and every arrival order of a five-claim burst
grants exactly one of two overlapping claims.

Fixes #210, fixes #211

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:56:00 -06:00
elforeign 6d7523f5d1 Merge upstream main into test/metal-bc2-bc3
Resolves the CHANGELOG.md conflict with the claim-rules entry; both
entries are kept.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:55:23 -06:00
elforeign 59ee786a12 metal: upload and read BC2 and BC3 blocks natively
BC2 and BC3 had CPU decoders (#167) but no native Metal path, so nothing
showed that the original 16-byte blocks reach the GPU and decode as the
specifications describe. This adds a pitched BcAlphaUpload with the BC1
upload's validation (shared, now measured in 16-byte blocks) and
NativeCompute::read_bc_alpha_upload, which places the blocks in BC2_RGBA
or BC3_RGBA textures behind the existing BC capability check.

The GPU tests cover explicit 4-bit alpha, six- and eight-value
interpolated alpha (equal endpoints included), descending, ascending and
equal colour endpoints, padded row and slice pitches, two layers and two
mips. Texels are compared with the CPU decoders and hand-derived anchors.
On an Apple M5 Pro interpolated values lie within 1.14 codes of the exact
values, two codes at most from the truncating CPU reference, which sets
the tolerance. Uploading BC3 as BC2, BC2 as BC1, or ignoring the row
pitch each fails the tests.

Refs #168

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:49:17 -06:00
elforeign e37c8566c6 agent queue: start runs only for commands and replay cancelled claims
Every pull request comment started the verify job, which gathered state
and re-ran the pull request check, so ordinary review discussion re-ran
verification. Gate the verify job on comments that start with /verified
and the claim job on comments that start with /.

Claim runs share one concurrency group with cancel-in-progress: false.
GitHub keeps one waiting run per group and cancels it when a newer run
queues, so with the run deciding only its own comment, a /claim posted
while another claim was being decided could be dropped without a reply.
Each run now replays every command of the last lease_hours that has no
bot reply, oldest first, updating labels in memory between commands; the
hourly audit does the same, so a cancelled run's command is answered by
the run that replaced it at the latest within the hour. Replies carry a
done marker that counts only from the Actions bot.

The pull request check is advisory until a live smoke test and the
migration of existing issues: problems are a warning and the job passes.

Tests model the concurrency group (the old event-only design loses the
cancelled claim; replay answers all four commands), in-order overlap
decisions, bot-only markers and the workflow triggers.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:46:21 -06:00
elforeign 98bbe57471 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:58 -06:00
20 changed files with 1100 additions and 105 deletions

No files matched your search

+20 -4
View File
@@ -4,6 +4,13 @@ name: Agent task claims
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
# text is only parsed as data by scripts/agent_queue; it is never executed and
# never interpolated into a shell. Not yet run on GitHub.
#
# Both jobs share one concurrency group, so decisions never race. GitHub keeps
# at most one pending run per group and cancels the older pending run when a
# newer one queues, so a run does not decide only its own comment: `replay`
# decides every command of the last lease_hours that has no bot reply yet,
# oldest first. The surviving run, or at the latest the hourly audit, answers
# the commands of cancelled runs. Comments that do not start with `/` start no run.
on:
issue_comment:
@@ -16,7 +23,7 @@ permissions: {}
jobs:
command:
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request && startsWith(github.event.comment.body, '/')
runs-on: ubuntu-24.04-arm
permissions:
contents: read
@@ -36,9 +43,8 @@ jobs:
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/state.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
audit:
@@ -54,6 +60,16 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide commands whose runs were cancelled
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs --recent-commands > "$RUNNER_TEMP/commands.json"
python3 -m agent_queue replay --state "$RUNNER_TEMP/commands.json" > "$RUNNER_TEMP/replay.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/replay.json"
- name: Lapse stale claims, flag invalid tasks, write summary
env:
GH_TOKEN: ${{ github.token }}
+32 -8
View File
@@ -4,6 +4,11 @@ name: Agent PR checks
# ownership, overlap with other open pull requests, and independent
# verification. Runs on the base branch only: pull request code is never checked
# out or executed; changed files come from the API. Not yet run on GitHub.
#
# Advisory: problems are reported as a warning and in the run summary, but the
# check does not fail until a live smoke test and the migration of existing
# issues are done (docs/coordination/agent-tasks.md). Only a comment starting
# with /verified starts the verify job; ordinary comments start nothing.
on:
pull_request_target:
@@ -43,17 +48,21 @@ jobs:
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
exit "$status"
# 1 means problems were found: advisory for now. Anything else is a failure of the check itself.
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
verify:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
if: github.event_name == 'issue_comment' && github.event.issue.pull_request && startsWith(github.event.comment.body, '/verified')
runs-on: ubuntu-24.04-arm
# issues: write posts the reply; actions: write re-runs the check after a recorded verification.
# issues: write posts the reply.
permissions:
contents: read
issues: write
pull-requests: read
actions: write
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
@@ -61,7 +70,7 @@ jobs:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and re-run the check
- name: Record verification and check again
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
@@ -73,6 +82,21 @@ jobs:
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
sha=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["pr"]["head_sha"])' "$RUNNER_TEMP/state.json")
run=$(gh run list --workflow agent-pr-checks.yml --commit "$sha" --event pull_request_target --limit 1 --json databaseId -q '.[0].databaseId // empty')
if [ -n "$run" ]; then gh run rerun "$run" || true; fi
# Check again only after an accepted verification of the current head: refused, stale,
# malformed or unauthorized /verified comments get a reply and nothing else.
if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi
# pull_request_target runs are recorded against the base branch, not the pull request
# head, so the earlier check run cannot be found by head SHA. Evaluate the same check here.
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check after verification'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
if [ "$status" -eq 1 ]; then
echo "::warning title=Agent PR check (advisory)::problems found; see the run summary"
elif [ "$status" -ne 0 ]; then
exit "$status"
fi
+8
View File
@@ -11,7 +11,15 @@ remains unsupported.
### Added
- Added an agent task queue for the cpu, gpu, runtime, shared and qa areas: an *Agent task* issue form with priority and interface fields, a workflow that decides `/claim`, `/release`, `/reassign`, `/progress`, `/blocked`, `/unblock` and `/approve-acceptance` comments one at a time (dependency, cycle and file-overlap checks, 24-hour leases renewed by progress), a pull request check (linked claimed task, file ownership, overlap with other pull requests, independent `/verified <head sha>`), `scripts/agent-queue.sh` and `scripts/agent-sync.sh` (upstream fetch every 12 minutes, task branches in separate worktrees) and a machine-readable queue summary. The rules are standard-library Python in `scripts/agent_queue/` with unit tests in `tests/agent_queue/`; issue text is never executed and acceptance commands need maintainer approval. Only comments that start with a command start a job, so ordinary pull request comments never re-run verification, and only an accepted `/verified <full head sha>` evaluates the check again; and each claim run decides every unanswered command in order, so commands whose pending runs GitHub cancelled are still answered. See `docs/coordination/agent-tasks.md`. Unit tests pass locally; the workflows have not run on GitHub yet, and the pull request check stays advisory (it never blocks a merge) until a live smoke test and the migration of existing issues are done.
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
- Added native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
1.14 codes of the exact values, so up to two codes from the truncating CPU reference.
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
+66 -21
View File
@@ -16,7 +16,7 @@ use objc2_metal::{
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{Bc1Upload, TiledBc1};
use xenora_texture::{Bc1Upload, BcAlphaFormat, BcAlphaUpload, TiledBc1};
#[path = "render.rs"]
mod render;
@@ -26,12 +26,12 @@ const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const BC1_READBACK: &str = r"
const BC_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
kernel void read_bc(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
@@ -184,11 +184,18 @@ impl NativeCompute {
let (width, height) = tiled
.mip_extent(mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(width, height)?;
let pixels = self.validate_bc_extent(width, height, "BC1")?;
let blocks = tiled
.linearize(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
&blocks,
width.div_ceil(4) * 8,
width,
height,
pixels,
)
}
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
@@ -269,8 +276,9 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(level.width, level.height)?;
self.read_bc1_blocks(
let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?;
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
level.bytes,
level.row_pitch,
level.width,
@@ -279,7 +287,45 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
)
}
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
/// Read a selected subresource from a validated pitched BC2 or BC3 upload.
///
/// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA`
/// texture, and the output has the layout of [`Self::read_bc1_upload`].
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression, or Metal setup or execution failure.
pub fn read_bc_alpha_upload(
&self,
upload: &BcAlphaUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let (format, name) = match upload.format() {
BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"),
BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"),
};
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
self.read_bc_blocks(
format,
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
fn validate_bc_extent(
&self,
width: usize,
height: usize,
name: &str,
) -> Result<usize, MetalError> {
let pixels = width
.checked_mul(height)
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
@@ -287,14 +333,15 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
if !self.device.supportsBCTextureCompression() {
return Err(MetalError::new(
"supportsBCTextureCompression",
"BC1 is unavailable",
format!("{name} is unavailable"),
));
}
Ok(pixels)
}
fn read_bc1_blocks(
fn read_bc_blocks(
&self,
format: MTLPixelFormat,
blocks: &[u8],
row_pitch: usize,
width: usize,
@@ -302,14 +349,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
pixels: usize,
) -> Result<Vec<u32>, MetalError> {
autoreleasepool(|_| {
// SAFETY: The positive bounded dimensions and supported BC1 format
// SAFETY: The positive bounded dimensions and supported BC format
// describe a 2D texture with just its base level.
let descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
MTLPixelFormat::BC1_RGBA,
width,
height,
false,
format, width, height, false,
)
};
descriptor.setStorageMode(MTLStorageMode::Shared);
@@ -318,7 +362,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
.device
.newTextureWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
MetalError::new("newTextureWithDescriptor", "BC allocation failed")
})?;
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
@@ -332,7 +376,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
// SAFETY: The region spans the whole level, including any partial
// edge block. Both callers validate that the input holds all rows
// of complete BC1 blocks at the supplied, block-aligned stride.
// of complete blocks of this format at the supplied, block-aligned
// stride.
unsafe {
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
@@ -342,8 +387,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
);
}
self.run(
BC1_READBACK,
"read_bc1",
BC_READBACK,
"read_bc",
ComputeInput::Texture(&texture, pixels),
)
.map(|profile| profile.output)
@@ -0,0 +1,287 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Metal upload and readback of original BC2 and BC3 blocks.
//!
//! Every block below was written for this test. The full-texel reference is
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
//! the Microsoft Direct3D 11 block-compression documentation (BC2, BC3) and
//! the Khronos Data Format Specification 1.3 (S3TC DXT3/DXT5). Apple's GPU
//! decoder is the value under test, so expected and actual values come from
//! different decoders.
use super::context;
use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3};
/// The specifications define colour and BC3 alpha interpolation in real
/// numbers, and the CPU reference truncates them. On an Apple M5 Pro the
/// native decoder's interpolated values lie within 1.14 codes of the real
/// value (they match 6-bit fixed-point weights), so they can sit two codes
/// above the truncated reference: 124 against 122 for BC3 alpha
/// (4 * 200 + 3 * 20) / 7 = 122.86. Endpoints, BC2 alpha and BC3's fixed
/// 0 and 255 are exact and are pinned by the anchor checks.
const TOLERANCE: u8 = 2;
/// Bound for anchors against the real-number value of an interpolated code.
const REAL_TOLERANCE: f64 = 1.5;
fn assert_near(label: &str, actual: u8, real: f64) {
assert!(
(f64::from(actual) - real).abs() <= REAL_TOLERANCE,
"{label}: got {actual}, real value {real:.2}"
);
}
const WIDTH: usize = 5;
const HEIGHT: usize = 5;
const ROW_PITCH: usize = 48;
const SLICE_PITCH: usize = 112;
/// Colour half: two little-endian RGB565 endpoints, then 2-bit indices.
/// Every row of 0xe4 selects palette entries 0, 1, 2, 3 from left to right.
fn colour((first, second): (u16, u16)) -> [u8; 8] {
let [a, b] = first.to_le_bytes();
let [c, d] = second.to_le_bytes();
[a, b, c, d, 0xe4, 0xe4, 0xe4, 0xe4]
}
/// BC3 alpha half whose texel `t` selects palette entry `(t + 6) % 8`, so
/// every row starts with the indices 6 and 7 and a full block uses all eight.
fn bc3_alpha(first: u8, second: u8) -> [u8; 8] {
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
let i = bits.to_le_bytes();
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
}
fn block(alpha: [u8; 8], colour: [u8; 8]) -> [u8; 16] {
let mut block = [0; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour);
block
}
// First endpoint greater: red over blue.
const DESCENDING: (u16, u16) = (0xf800, 0x001f);
// First endpoint smaller, with odd channel values that exercise rounding.
const ASCENDING: (u16, u16) = (0x52aa, 0xad55);
// Equal endpoints: BC1 would decode index 3 as transparent black.
const EQUAL: (u16, u16) = (0x07e0, 0x07e0);
/// White with zero alpha (BC2 nibbles 0; BC3 endpoints 0 and 0) in every
/// padding slot, so a wrong row or slice pitch reads visibly wrong texels.
const PAD: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0];
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
type Layer = [[u8; 16]; 5];
/// Two layers of a 5×5 texture with two mips. Each subresource has seven
/// physical blocks: rows of two logical blocks plus one padding block, a
/// padding block that closes the slice, and mip 1 uses only its block zero.
fn upload_bytes(layers: [Layer; 2]) -> Vec<u8> {
let mut bytes = Vec::new();
for [b0, b1, b2, b3, small] in layers {
for slot in [b0, b1, PAD, b2, b3, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
for slot in [small, PAD, PAD, PAD, PAD, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
}
assert_eq!(bytes.len(), 2 * 2 * SLICE_PITCH);
bytes
}
/// Crops decoded blocks (a row-major block grid) to a `width`×`height` level
/// of words with red in the lowest byte, as the readback kernel writes them.
fn reference(blocks: &[[[u8; 4]; 16]], blocks_x: usize, width: usize, height: usize) -> Vec<u32> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
let decoded = blocks[(y / 4) * blocks_x + x / 4];
texels.push(u32::from_le_bytes(decoded[(y % 4) * 4 + x % 4]));
}
}
texels
}
fn alpha(word: u32) -> u8 {
word.to_le_bytes()[3]
}
/// Returns the largest per-channel difference, failing on any texel above the
/// tolerance with its index and both values.
fn assert_close(label: &str, actual: &[u32], expected: &[u32]) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &want)) in actual.iter().zip(expected).enumerate() {
let diff = got
.to_le_bytes()
.iter()
.zip(want.to_le_bytes())
.map(|(g, w)| g.abs_diff(w))
.max()
.unwrap();
assert!(
diff <= TOLERANCE,
"{label}: texel {texel} got {got:#010x}, want {want:#010x}"
);
worst = worst.max(diff);
}
worst
}
/// GPU reads of both layers: `[layer][mip]`.
type Reads = [[Vec<u32>; 2]; 2];
/// Uploads both layers, reads all four subresources on the GPU, compares
/// them with the CPU decoder and returns the reads with the worst difference.
fn read_and_compare(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
layers: [Layer; 2],
) -> (Reads, u8) {
let bytes = upload_bytes(layers);
let upload = BcAlphaUpload::new(
&bytes,
BcAlphaUploadDesc {
width: WIDTH,
height: HEIGHT,
mips: 2,
layers: 2,
format,
row_pitch: ROW_PITCH,
slice_pitch: SLICE_PITCH,
},
)
.unwrap();
let gpu = context();
let mut worst = 0;
let reads = std::array::from_fn(|layer| {
let decoded = layers[layer].map(decode);
let base = gpu.read_bc_alpha_upload(&upload, layer, 0).unwrap();
let expected = reference(&decoded[..4], 2, WIDTH, HEIGHT);
let label = format!("{format:?} layer {layer}");
worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected));
let small = gpu.read_bc_alpha_upload(&upload, layer, 1).unwrap();
let expected = reference(&decoded[4..], 1, 2, 2);
worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected));
[base, small]
});
for (layer, mip) in [(2, 0), (0, 2)] {
assert_eq!(
gpu.read_bc_alpha_upload(&upload, layer, mip)
.unwrap_err()
.operation,
"texture subresource"
);
}
(reads, worst)
}
#[test]
fn reads_pitched_bc2_explicit_alpha_across_mips_and_layers() {
// Nibble t in texel t, low nibble first: alpha t * 17.
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let opaque = [0xff; 8];
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc2,
decode_bc2,
[
[
block(ramp, descending),
block(reverse, ascending),
block(opaque, equal),
block(ramp, ascending),
block(reverse, descending),
],
[
block(opaque, ascending),
block(ramp, equal),
block(reverse, descending),
block(opaque, descending),
block(ramp, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
// (0, 0): red endpoint, nibble 0. (1, 0): blue endpoint, nibble 1.
assert_eq!(base[0], 0x0000_00ff);
assert_eq!(base[1], 0x11ff_0000);
// (0, 2) is texel 8 of block 0: red endpoint, nibble 8 -> 0x88.
assert_eq!(base[2 * WIDTH], 0x8800_00ff);
// (3, 3) is texel 15 of block 0: nibble 15 -> opaque.
assert_eq!(alpha(base[3 * WIDTH + 3]), 0xff);
// (4, 0) is texel 0 of block 1: reversed ramp, nibble 15.
assert_eq!(alpha(base[4]), 0xff);
// (3, 4) is index 3 of block 2's equal green endpoints: opaque green,
// not BC1's transparent black.
assert_eq!(base[4 * WIDTH + 3], 0xff00_ff00);
// Layer 1 mip 1: green endpoints, ramp nibbles 0, 1, 4, 5.
assert_eq!(
reads[1][1],
[0x0000_ff00, 0x1100_ff00, 0x4400_ff00, 0x5500_ff00]
);
println!("checked 58 BC2 texels from four subresources, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() {
// First endpoint greater: eight-value palette.
let eight = bc3_alpha(200, 20);
// First endpoint smaller: six-value palette with fixed 0 and 255.
let six = bc3_alpha(20, 200);
// Equal endpoints also select the six-value palette.
let level = bc3_alpha(128, 128);
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc3,
decode_bc3,
[
[
block(eight, descending),
block(six, ascending),
block(level, equal),
block(eight, ascending),
block(six, descending),
],
[
block(six, equal),
block(eight, ascending),
block(level, descending),
block(six, ascending),
block(eight, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
let a = |x: usize, y: usize| alpha(base[y * WIDTH + x]);
// Block 0, eight-value: row 0 holds indices 6, 7, 0, 1, and row 1
// indices 2, 3, 4, 5, each (k = index - 1) ((7 - k) * 200 + k * 20) / 7.
assert_near("index 6", a(0, 0), (2.0 * 200.0 + 5.0 * 20.0) / 7.0);
assert_near("index 7", a(1, 0), (200.0 + 6.0 * 20.0) / 7.0);
for (x, k) in (0..4).zip(1..) {
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
assert_near(&format!("index {}", k + 1), a(x, 1), real);
}
// Then the endpoints themselves, exactly; texel (0, 0) is the red endpoint.
assert_eq!([a(2, 0), a(3, 0)], [200, 20]);
assert_eq!(base[0] & 0x00ff_ffff, 0x0000_00ff);
// Block 1, six-value: column 4 holds indices 6, 2, 6, 2. Index 6 is the
// fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
assert_eq!([a(4, 0), a(4, 2)], [0, 0]);
assert_near("six-value index 2", a(4, 1), 56.0);
assert_near("six-value index 2", a(4, 3), 56.0);
// Block 2, equal endpoints of 128: row 4 holds indices 6, 7, 0, 1, so the
// six-value mode shows as the fixed 0 and 255.
assert_eq!([a(0, 4), a(1, 4), a(2, 4), a(3, 4)], [0, 255, 128, 128]);
// Mip 1, six-value: indices 6, 7, 2, 3 -> 0, 255, 56, (3 * 20 + 2 * 200) / 5 = 92.
let small: Vec<_> = reads[0][1].iter().copied().map(alpha).collect();
assert_eq!(small[..2], [0, 255]);
assert_near("six-value index 2", small[2], 56.0);
assert_near("six-value index 3", small[3], 92.0);
println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}");
}
+2
View File
@@ -6,6 +6,8 @@ mod guest_buffer;
mod offscreen;
#[path = "native/texture.rs"]
mod texture;
#[path = "native/texture_bc_alpha.rs"]
mod texture_bc_alpha;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_render.rs"]
+3 -1
View File
@@ -14,7 +14,9 @@ pub use bc::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
pub use upload::{
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
};
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
+207 -37
View File
@@ -32,56 +32,153 @@ pub struct Bc1Subresource<'a> {
impl<'a> Bc1Upload<'a> {
pub fn new(bytes: &'a [u8], desc: Bc1UploadDesc) -> Result<Self, TextureError> {
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
if desc.format != 1
|| desc.usage != 1
|| desc.width == 0
|| desc.height == 0
|| desc.layers == 0
|| desc.mips == 0
|| desc.mips > max_mips
{
if desc.format != 1 || desc.usage != 1 {
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(desc.width, desc.height, 0);
let tight_row = blocks_x
.checked_mul(BLOCK_BYTES)
.ok_or(TextureError::SizeOverflow)?;
if desc.row_pitch < tight_row || !desc.row_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = desc
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if desc.slice_pitch < minimum_slice || !desc.slice_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let size = desc
.slice_pitch
.checked_mul(desc.mips as usize)
.and_then(|size| size.checked_mul(desc.layers))
.ok_or(TextureError::SizeOverflow)?;
if bytes.len() != size {
return Err(TextureError::InvalidByteLength);
}
Self::layout(desc).validate(bytes.len(), BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.desc.layers || mip >= self.desc.mips {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: Bc1UploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// A block-compressed format whose 16-byte block holds an alpha half followed
/// by a BC1-style colour half.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BcAlphaFormat {
/// Explicit 4-bit alpha per texel.
Bc2,
/// Interpolated alpha from two 8-bit endpoints and 3-bit indices.
Bc3,
}
/// A layer-major BC2 or BC3 upload with the same pitch rules as
/// [`Bc1UploadDesc`], measured in 16-byte blocks.
#[derive(Clone, Copy, Debug)]
pub struct BcAlphaUploadDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub layers: usize,
pub format: BcAlphaFormat,
pub row_pitch: usize,
pub slice_pitch: usize,
}
#[derive(Debug)]
pub struct BcAlphaUpload<'a> {
bytes: &'a [u8],
desc: BcAlphaUploadDesc,
}
impl<'a> BcAlphaUpload<'a> {
/// Size of one BC2 or BC3 block in bytes.
pub const BLOCK_BYTES: usize = 16;
pub fn new(bytes: &'a [u8], desc: BcAlphaUploadDesc) -> Result<Self, TextureError> {
Self::layout(desc).validate(bytes.len(), Self::BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn format(&self) -> BcAlphaFormat {
self.desc.format
}
/// Selects one level; the returned rows hold 16-byte blocks.
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: BcAlphaUploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// Format-independent pitch rules shared by the pitched uploads.
struct PitchedLayout {
width: usize,
height: usize,
mips: u32,
layers: usize,
row_pitch: usize,
slice_pitch: usize,
}
impl PitchedLayout {
fn validate(&self, len: usize, block_bytes: usize) -> Result<(), TextureError> {
let max_mips = usize::BITS - self.width.max(self.height).leading_zeros();
if self.width == 0
|| self.height == 0
|| self.layers == 0
|| self.mips == 0
|| self.mips > max_mips
{
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(self.width, self.height, 0);
let tight_row = blocks_x
.checked_mul(block_bytes)
.ok_or(TextureError::SizeOverflow)?;
if self.row_pitch < tight_row || !self.row_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = self
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if self.slice_pitch < minimum_slice || !self.slice_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let size = self
.slice_pitch
.checked_mul(self.mips as usize)
.and_then(|size| size.checked_mul(self.layers))
.ok_or(TextureError::SizeOverflow)?;
if len != size {
return Err(TextureError::InvalidByteLength);
}
Ok(())
}
fn subresource<'a>(
&self,
bytes: &'a [u8],
layer: usize,
mip: u32,
) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.layers || mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
// Construction proved that the complete array fits in the source span.
let offset = (layer * self.desc.mips as usize + mip as usize) * self.desc.slice_pitch;
let width = (self.desc.width >> mip).max(1);
let height = (self.desc.height >> mip).max(1);
let offset = (layer * self.mips as usize + mip as usize) * self.slice_pitch;
let width = (self.width >> mip).max(1);
let height = (self.height >> mip).max(1);
let rows = height.div_ceil(4);
Ok(Bc1Subresource {
bytes: &self.bytes[offset..offset + rows * self.desc.row_pitch],
bytes: &bytes[offset..offset + rows * self.row_pitch],
width,
height,
row_pitch: self.desc.row_pitch,
row_pitch: self.row_pitch,
})
}
}
@@ -182,4 +279,77 @@ mod tests {
);
}
}
const ALPHA_DESC: BcAlphaUploadDesc = BcAlphaUploadDesc {
width: 5,
height: 5,
mips: 2,
layers: 2,
format: BcAlphaFormat::Bc3,
row_pitch: 48,
slice_pitch: 112,
};
#[test]
fn selects_bc_alpha_subresources_in_sixteen_byte_blocks() {
let mut bytes = [0; 448];
// Layer 1 starts at 224; its base row 1, block 1 is at 224 + 48 + 16.
bytes[288..304].fill(0x5c);
bytes[336] = 0xa7; // Layer 1, mip 1, block 0.
let upload = BcAlphaUpload::new(&bytes, ALPHA_DESC).unwrap();
assert_eq!(upload.format(), BcAlphaFormat::Bc3);
let base = upload.subresource(1, 0).unwrap();
assert_eq!((base.width, base.height, base.row_pitch), (5, 5, 48));
assert_eq!(base.bytes.len(), 96);
assert_eq!(base.bytes[64..80], [0x5c; 16]);
let small = upload.subresource(1, 1).unwrap();
assert_eq!((small.width, small.height, small.bytes.len()), (2, 2, 48));
assert_eq!(small.bytes[0], 0xa7);
assert_eq!(
upload.subresource(2, 0).unwrap_err(),
TextureError::OutOfBounds
);
assert_eq!(
upload.subresource(0, 2).unwrap_err(),
TextureError::OutOfBounds
);
}
#[test]
fn rejects_bc1_pitches_for_sixteen_byte_blocks() {
let bytes = [0; 448];
// Each pitch is a valid BC1 multiple of 8 but not of 16, or is
// shorter than two 16-byte blocks.
for desc in [
BcAlphaUploadDesc {
row_pitch: 24,
..ALPHA_DESC
},
BcAlphaUploadDesc {
row_pitch: 40,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 104,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 80,
..ALPHA_DESC
},
BcAlphaUploadDesc {
mips: 4,
..ALPHA_DESC
},
] {
assert_eq!(
BcAlphaUpload::new(&bytes, desc).unwrap_err(),
TextureError::InvalidLayout
);
}
assert_eq!(
BcAlphaUpload::new(&bytes[..447], ALPHA_DESC).unwrap_err(),
TextureError::InvalidByteLength
);
}
}
+29 -6
View File
@@ -6,7 +6,9 @@ deterministic: the rules live in `scripts/agent_queue/` (standard-library Python
model or external service), and GitHub Actions and the shell helpers only call it.
Status: implemented and unit-tested locally. **Not yet run on GitHub**: the workflows are untested
against the real API until the first live run.
against the real API until the first live run. Until a live smoke test has passed and existing issues
have been migrated into the queue, the pull request check is **advisory**: it reports problems but
never blocks a merge, and it must not be made a required check.
## Areas
@@ -47,6 +49,12 @@ done
prints "claimed".** Refusals name the reason: not `agent:ready`, area not allowed for you, open
or missing dependency, dependency cycle, or file overlap with a claimed task (the issue is named).
Claims are decided one at a time across the whole repository, so two overlapping claims cannot both win.
GitHub keeps at most one waiting run in a concurrency group and cancels it when a newer one
queues, so each run decides every command of the last `lease_hours` that has no bot reply yet,
oldest first; a comment listed twice is decided once. A command whose own run was cancelled is answered by the run that replaced it, or at
the latest by the hourly audit. Each reply carries a marker naming the comment it answers. A
command left unanswered for more than `lease_hours` (the workflow did not run) gets a "Not
decided" reply instead and must be posted again; one older than twice that is no longer read.
4. `scripts/agent-queue.sh start <n>` creates branch `task/<n>-<slug>` from `upstream/main` in a
separate worktree `../xenora-task-<n>` (`--here` uses the current clean checkout instead).
5. Keep the lease alive with `scripts/agent-queue.sh progress <n> "what changed"`. A claim lapses
@@ -54,11 +62,14 @@ done
linked pull request. Other people's comments never renew it. A lapsed task returns to the queue.
6. Open the pull request with `Closes #<n>` and a DCO sign-off (`git commit -s`).
7. A different person (not the author, not the task holder) who is a maintainer or has `qa`
comments `/verified <head sha>` after running the acceptance command. A new push changes the
comments `/verified <full 40-character head sha>` after running the acceptance command. A new push changes the
head and invalidates the verification.
## Commands (issue comments)
A command must start the comment. Comments that do not start with `/` (on an issue) or with
`/verified` (on a pull request) start no job: GitHub records a skipped run and nothing else happens.
| Command | Who | Effect |
| --- | --- | --- |
| `/claim` | allowed for the area | Take a ready task |
@@ -67,7 +78,7 @@ done
| `/progress <text>` | holder | Renew the lease (text required) |
| `/blocked <reason>`, `/unblock` | holder or maintainer | Set or clear `agent:blocked` |
| `/approve-acceptance` | maintainer | Authorise the acceptance command as currently written |
| `/verified <sha>` (on a pull request) | maintainer or `qa`, not author, not holder | Independent verification of the current head |
| `/verified <40-character sha>` (on a pull request) | maintainer or `qa`, not author, not holder | Independent verification of the current head |
Labels: `area:<x>`, `priority:<critical|high|medium|low>`, `agent:ready|claimed|blocked|invalid|conflict`,
`claimed-by:<login>`. An hourly audit lapses stale claims, marks tasks with missing dependencies or
@@ -80,7 +91,16 @@ machine-readable summary (counts and lists per area, priority and state).
`agent-pr-checks` fails a pull request when: it has no `Closes #N` for a claimed task; the task is held
by someone else; it changes files outside the task's patterns; it changes a file that another open
pull request also changes; the claim has lapsed without a push; or no eligible `/verified <current
head sha>` exists. After a `/verified` comment the check is re-run automatically.
head sha>` exists. The SHA must be the full 40 characters and the only argument: a commit with the
same short prefix is cheap to make. After an accepted `/verified` (an eligible verifier, the current
head) the verify job evaluates the same check again and writes it to its run summary; the earlier
check run is not re-run, since `pull_request_target` runs are recorded against the base branch and
cannot be found by the pull request head. Refused, stale, malformed or unauthorized `/verified`
comments get a reply and nothing else, and other pull request comments start no job.
The check is advisory for now: a failure is shown as a warning and in the run summary, and the job
still succeeds. It becomes blocking (fail on problems, then a required check) only after a live smoke
test on GitHub and the migration of existing issues into the queue.
## Forks and upstream sync
@@ -104,7 +124,8 @@ sync report that shows upstream touching your files is the signal to re-read the
- Acceptance commands are never run automatically. `scripts/agent-queue.sh acceptance <n>` prints
one only when a maintainer's `/approve-acceptance` marker (posted by the bot) matches a hash of
the current text; editing the issue body invalidates the approval. Read the command before running it.
- Markers (grant, approval) count only when posted by the Actions bot, so they cannot be forged in a comment.
- Markers (grant, approval, answered command) count only when posted by the Actions bot, so they cannot be forged in a comment.
User text that a bot reply echoes (a `/blocked` reason, a login, a file pattern) has its angle brackets and backticks escaped, so a reply cannot carry a marker the user wrote.
- Workflows declare empty top-level permissions and grant each job only what it needs; actions are
pinned by commit SHA. Pull request checks run on the base branch (`pull_request_target`), never
check out or run pull request code and read changed files through the API.
@@ -118,4 +139,6 @@ sh -n scripts/agent-queue.sh scripts/agent-sync.sh
```
The tests cover command decisions, overlap, cycles, leases, acceptance hashing, pull request checks,
the summary, the CLI and a structural check of the workflow files. They do not exercise GitHub itself.
the summary, the CLI, claim concurrency (a model of a concurrency group in which newer runs cancel
pending ones, and in-order replay of unanswered commands) and a structural check of the workflow
files, including which comments start a run. They do not exercise GitHub itself.
+14 -3
View File
@@ -3,12 +3,12 @@
import argparse
import json
import sys
from datetime import datetime, timezone
from datetime import datetime, timedelta, timezone
from . import config as cfgmod
from . import ghio
from . import lease as L
from . import prcheck, queue
from . import prcheck, queue, replay
from . import tasks as T
from . import decide as decide_mod
from .decide import decide
@@ -35,7 +35,10 @@ def main(argv):
p.add_argument("--now", default="", help="UTC time YYYY-MM-DDTHH:MM:SSZ (tests)")
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("gather"); s.add_argument("--repo", required=True); s.add_argument("--no-prs", action="store_true"); s.add_argument("--pr", type=int, default=0)
s.add_argument("--recent-commands", action="store_true", help="include comments from the last 2 x lease_hours for replay")
s = sub.add_parser("replay"); s.add_argument("--state", required=True)
s = sub.add_parser("decide"); s.add_argument("--event", required=True); s.add_argument("--state", required=True)
s = sub.add_parser("should-rerun"); s.add_argument("--actions", required=True)
s = sub.add_parser("apply"); s.add_argument("--repo", required=True); s.add_argument("--actions", required=True)
s = sub.add_parser("audit"); s.add_argument("--state", required=True)
s = sub.add_parser("summary"); s.add_argument("--state", required=True); s.add_argument("--text", action="store_true")
@@ -65,13 +68,21 @@ def main(argv):
v = cfg[a.key]
print(v if isinstance(v, (str, int, float)) else json.dumps(v))
elif a.cmd == "gather":
st = ghio.gather(a.repo, with_prs=not a.no_prs)
since = ""
if a.recent_commands:
since = (_now(a.now) - timedelta(hours=replay.window_hours(cfg))).strftime("%Y-%m-%dT%H:%M:%SZ")
st = ghio.gather(a.repo, with_prs=not a.no_prs, recent_since=since)
if a.pr:
st["pr"] = ghio.pr_data(a.repo, a.pr)
st["pr_comments"] = ghio.comments(a.repo, a.pr)
_out(st)
elif a.cmd == "decide":
_out(decide(_load(a.event), _load(a.state), cfg))
elif a.cmd == "replay":
_out(replay.replay(_load(a.state), cfg, _now(a.now)))
elif a.cmd == "should-rerun":
# exit 0 only for an accepted /verified of the current head
return 0 if decide_mod.rerun_check(_load(a.actions)) else 1
elif a.cmd == "apply":
ghio.apply_actions(a.repo, _load(a.actions))
elif a.cmd == "audit":
+38 -7
View File
@@ -1,5 +1,7 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Comment command decisions. Returns actions as data; the caller applies them."""
import re
from . import config as cfgmod
from . import lease as L
from . import tasks as T
@@ -8,6 +10,12 @@ COMMANDS = ("/claim", "/release", "/reassign", "/progress", "/blocked", "/unbloc
"/approve-acceptance", "/verified")
def quote(text):
"""User text echoed in a bot reply. Markers count only from the bot, so the reply must not be able
to carry one the user wrote: angle brackets are escaped and code spans are closed."""
return str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;").replace("`", "'")
def parse_command(body):
first = (body or "").strip().split("\n", 1)[0].strip()
parts = first.split(None, 1)
@@ -16,6 +24,19 @@ def parse_command(body):
return parts[0], (parts[1].strip() if len(parts) > 1 else "")
FULL_SHA = re.compile(r"[0-9a-f]{40}")
def verified_sha(body):
"""The SHA of a well-formed `/verified <40-hex sha>` first line, else "". A short prefix is
refused: a pushed commit with the same short prefix is cheap to make."""
cmd, arg = parse_command(body)
parts = arg.split()
if cmd != "/verified" or len(parts) != 1 or not FULL_SHA.fullmatch(parts[0]):
return ""
return parts[0]
def _act(issue, add=(), remove=(), comment=""):
return {"issue": issue, "add_labels": list(add), "remove_labels": list(remove), "comment": comment}
@@ -53,7 +74,7 @@ def claim_problem(task, tasks, cfg, actor):
continue
hit = sets_overlap(task["files"], other["files"])
if hit:
return "file overlap with claimed task #%d (`%s` vs `%s`)." % (other["number"], hit[0], hit[1])
return "file overlap with claimed task #%d (`%s` vs `%s`)." % (other["number"], quote(hit[0]), quote(hit[1]))
return ""
@@ -96,9 +117,13 @@ def decide(event, state, cfg):
if not target:
return _reply(n, "Usage: /reassign <login>")
if not cfgmod.may_work_on(cfg, target, task["area"]):
return _reply(n, "Reassign refused: %s is not allowed to work on area:%s." % (target, task["area"]))
return _reply(n, "Reassign refused: %s is not allowed to work on area:%s." % (quote(target), task["area"]))
if not (set(task["labels"]) & {"agent:claimed", "agent:ready"}):
return _reply(n, "Reassign refused: the task is neither ready nor claimed.")
# A reassignment creates a claim: the same dependency and file-overlap rules apply.
problem = claim_problem(dict(task, labels=task["labels"] + ["agent:ready"]), tasks, cfg, target)
if problem:
return _reply(n, "Reassign refused: %s" % problem)
remove = ["agent:ready"] + (["claimed-by:" + holder] if holder else [])
return [_act(n, ["agent:claimed", "claimed-by:" + target], remove,
"Reassigned to %s by %s. New lease starts now.\n%s" % (target, actor, L.grant_marker(n, target)))]
@@ -115,7 +140,7 @@ def decide(event, state, cfg):
return _reply(n, "Only the holder or a maintainer can mark a task blocked.")
if not arg:
return _reply(n, "Usage: /blocked <reason>")
return [_act(n, ["agent:blocked"], [], "Blocked by %s: %s" % (actor, arg))]
return [_act(n, ["agent:blocked"], [], "Blocked by %s: %s" % (actor, quote(arg)))]
if cmd == "/unblock":
if actor != holder and not maint:
@@ -138,7 +163,7 @@ def _verified(event, state, cfg, arg):
if event.get("kind") != "pr":
return []
pr = state.get("pr") or {}
sha = arg.split()[0] if arg else ""
sha = verified_sha(event.get("body"))
head = pr.get("head_sha", "")
if actor == pr.get("author"):
return _reply(n, "Verification refused: the pull request author cannot verify it.")
@@ -148,6 +173,12 @@ def _verified(event, state, cfg, arg):
return _reply(n, "Verification refused: %s holds the linked task #%d." % (actor, issue))
if not cfgmod.is_verifier(cfg, actor):
return _reply(n, "%s may not verify: only maintainers and qa contributors can." % actor)
if len(sha) < 7 or not head.startswith(sha):
return _reply(n, "Verification refused: `%s` is not the current head %s." % (sha or "(none)", head[:12]))
return _reply(n, "Verification of %s recorded for %s." % (head[:12], actor))
if not sha or sha != head:
return _reply(n, "Verification refused: `%s` is not the full current head %s." % (quote(sha) or "(none)", head))
# Only an accepted verification of the current head re-runs the pull request check.
return [dict(_act(n, comment="Verification of %s recorded for %s." % (head[:12], actor)), rerun_check=True)]
def rerun_check(actions):
"""True when the decided actions record an accepted verification of the current head."""
return any(a.get("rerun_check") for a in actions)
+13 -2
View File
@@ -27,6 +27,14 @@ def comments(repo, n):
return ndjson(gh("api", "repos/%s/issues/%d/comments" % (repo, n), "--paginate", "--jq", jq))
def recent_comments(repo, since):
"""Issue and pull request comments updated since `since` (UTC ISO time), oldest first."""
jq = ('.[] | {id: .id, user: .user.login, body: .body, created_at: .created_at, '
'issue: (.issue_url | split("/") | last | tonumber), pull_request: (.html_url | test("/pull/"))}')
return ndjson(gh("api", "repos/%s/issues/comments?sort=created&direction=asc&per_page=100&since=%s" % (repo, since),
"--paginate", "--jq", jq))
def open_issues(repo):
return json.loads(gh("issue", "list", "-R", repo, "--state", "open", "--limit", "500",
"--json", "number,title,body,state,labels"))
@@ -46,8 +54,9 @@ def open_prs(repo):
return [pr_data(repo, n) for n in nums]
def gather(repo, with_prs=True, with_comments=True):
"""State for decide/audit/summary: open tasks plus any dependency issues they name."""
def gather(repo, with_prs=True, with_comments=True, recent_since=""):
"""State for decide/audit/summary/replay: open tasks plus any dependency issues they name and,
with `recent_since`, every comment since then."""
from .tasks import parse_task
issues = {i["number"]: i for i in open_issues(repo)}
for i in list(issues.values()):
@@ -60,6 +69,8 @@ def gather(repo, with_prs=True, with_comments=True):
if any((l["name"] if isinstance(l, dict) else l) == "agent:claimed" for l in i["labels"])}
if with_prs:
state["prs"] = open_prs(repo)
if recent_since:
state["recent_comments"] = recent_comments(repo, recent_since)
return state
+4 -7
View File
@@ -3,7 +3,7 @@
from . import config as cfgmod
from . import lease as L
from .patterns import path_matches, patterns_overlap
from .decide import task_index
from .decide import task_index, verified_sha
def verified_by(pr, comments, tasks, cfg):
@@ -11,11 +11,8 @@ def verified_by(pr, comments, tasks, cfg):
head, out = pr.get("head_sha", ""), []
holders = {tasks[i]["holder"] for i in L.linked_issues(pr.get("body")) if i in tasks}
for c in comments:
parts = c["body"].strip().split("\n", 1)[0].split()
if len(parts) < 2 or parts[0] != "/verified" or len(parts[1]) < 7:
continue
who = c["user"]
if (head.startswith(parts[1]) and who != pr.get("author") and who not in holders
sha, who = verified_sha(c["body"]), c["user"]
if (sha and sha == head and who != pr.get("author") and who not in holders
and cfgmod.is_verifier(cfg, who) and who not in out):
out.append(who)
return out
@@ -48,5 +45,5 @@ def check_pr(state, cfg, now):
problems.append("overlaps open PR #%d on: %s" % (other["number"], ", ".join(shared[:10])))
ok_by = verified_by(pr, comments, tasks, cfg)
if not ok_by:
problems.append("independent verification missing: an eligible verifier must comment `/verified %s`" % pr.get("head_sha", "")[:12])
problems.append("independent verification missing: an eligible verifier must comment `/verified %s`" % pr.get("head_sha", ""))
return {"pr": pr["number"], "ok": not problems, "problems": problems, "verified_by": ok_by}
+2 -2
View File
@@ -3,7 +3,7 @@
from . import config as cfgmod
from . import lease as L
from . import tasks as T
from .decide import task_index
from .decide import quote, task_index
from .patterns import sets_overlap
@@ -50,7 +50,7 @@ def audit(state, cfg, now):
for x, y in ((a, b), (b, a)):
if "agent:conflict" not in x["labels"] and x["number"] not in lapsed_nums:
actions.append({"issue": x["number"], "add_labels": ["agent:conflict"], "remove_labels": [],
"comment": "File overlap with claimed task #%d (`%s` vs `%s`). A maintainer must resolve it." % (y["number"], hit[0], hit[1])})
"comment": "File overlap with claimed task #%d (`%s` vs `%s`). A maintainer must resolve it." % (y["number"], quote(hit[0]), quote(hit[1]))})
for t in sorted(tasks.values(), key=lambda x: x["number"]):
if t["state"] != "OPEN" or "agent:ready" not in t["labels"]:
continue
+67
View File
@@ -0,0 +1,67 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Decides every unanswered issue command, oldest first.
Claim runs share one concurrency group. GitHub keeps one run in progress and at most one pending in
a group, and a newly queued run cancels the pending one, so the comment that started a cancelled
run would never be decided. Each run therefore decides every recent command that has no bot reply
yet, in comment order, and applies each decision's labels to its in-memory state so later commands
see earlier grants. Every reply carries a marker naming the comment it answers."""
import copy
import re
from datetime import timedelta
from . import lease as L
from .decide import decide, parse_command
from .tasks import label_names, parse_time
DONE = re.compile(r"<!-- agent-queue:done comment=(\d+) -->")
def done_marker(comment_id):
return "<!-- agent-queue:done comment=%d -->" % comment_id
def answered(comments, bots=L.BOT):
"""Ids of comments a bot reply has answered. Markers from anyone else do not count."""
return {int(m) for c in comments if c["user"] in bots for m in DONE.findall(c["body"])}
def _apply(state, action):
for i in state["issues"]:
if int(i["number"]) == action["issue"]:
names = [n for n in label_names(i) if n not in action["remove_labels"]]
names += [n for n in action["add_labels"] if n not in names]
i["labels"] = [{"name": n} for n in names]
def window_hours(cfg):
"""How far back `gather --recent-commands` reads: one lease to decide, one more to expire."""
return 2 * cfg["lease_hours"]
def replay(state, cfg, now, bots=L.BOT):
"""Actions for every unanswered command in state["recent_comments"]: decided if created within
the lease, else answered as expired so that no request goes silently unanswered."""
state = copy.deepcopy(state)
since = now - timedelta(hours=cfg["lease_hours"])
comments = state.get("recent_comments", [])
done = answered(comments, bots)
out = []
for c in sorted(comments, key=lambda c: (parse_time(c["created_at"]), c["id"])):
if c.get("pull_request") or c["id"] in done or c["user"] in bots:
continue
done.add(c["id"]) # a comment listed twice is decided once
if parse_time(c["created_at"]) < since:
if parse_command(c["body"])[0]:
out.append({"issue": c["issue"], "add_labels": [], "remove_labels": [], "comment":
"Not decided: no queue run answered this command within %s hours. Post it again if it still applies.\n%s"
% (cfg["lease_hours"], done_marker(c["id"]))})
continue
actions = decide({"kind": "issue", "number": c["issue"], "actor": c["user"], "body": c["body"]}, state, cfg)
if not actions:
continue
actions[-1]["comment"] += "\n" + done_marker(c["id"])
for a in actions:
_apply(state, a)
out.extend(actions)
return out
+2
View File
@@ -24,6 +24,8 @@ def _lines(text):
res = []
for line in text.splitlines():
line = line.strip()
if line.startswith("```"):
continue # issue forms wrap `render:` fields in a code fence
if line.startswith(("- ", "* ")):
line = line[2:].strip()
line = line.strip("`").strip()
+41 -2
View File
@@ -2,7 +2,7 @@
import unittest
from helpers import CFG, comment, event, issue, state
from agent_queue.decide import decide
from agent_queue.decide import decide, quote
from agent_queue.lease import GRANT
@@ -116,9 +116,48 @@ class Inert(unittest.TestCase):
a = decide(event("gpuer", "/claim " + evil), state(issue(1, files=evil + "\nsrc/gpu/a.rs", acceptance=evil)), CFG)
self.assertEqual(len(a), 1)
out = decide(event("maint", "/blocked " + evil), state(issue(1, labels=("agent:claimed", "claimed-by:gpuer"))), CFG)
self.assertIn(evil, one(out)["comment"])
self.assertIn(quote(evil), one(out)["comment"])
self.assertEqual(one(out)["add_labels"], ["agent:blocked"])
class ReassignChecks(unittest.TestCase):
def test_reassign_cannot_create_an_overlapping_or_blocked_claim(self):
held = issue(1, labels=("agent:claimed", "claimed-by:maint"))
a = one(decide(event("maint", "/reassign gpuer", 2), state(held, issue(2)), CFG))
self.assertIn("file overlap with claimed task #1", a["comment"])
self.assertEqual(a["add_labels"], [])
a = one(decide(event("maint", "/reassign gpuer", 2), state(issue(3), issue(2, deps="#3", files="src/gpu/b.rs")), CFG))
self.assertIn("open dependencies: #3", a["comment"])
a = one(decide(event("maint", "/reassign gpuer", 2), state(held, issue(2, files="src/gpu/b.rs")), CFG))
self.assertIn("claimed-by:gpuer", a["add_labels"])
class IssueForm(unittest.TestCase):
def test_rendered_files_field_is_unfenced(self):
# The issue form renders Files with `render: text`, i.e. inside a ```text fence.
from agent_queue.tasks import parse_task
fenced = issue(2, files="```text\nsrc/gpu/b.rs\n```")
self.assertEqual(parse_task(fenced)["files"], ["src/gpu/b.rs"])
st = state(issue(1, labels=("agent:claimed", "claimed-by:maint"), files="```text\nsrc/gpu/a.rs\n```"), fenced)
self.assertIn("Claimed by gpuer", one(decide(event("gpuer", "/claim", 2), st, CFG))["comment"])
class Forgery(unittest.TestCase):
"""Bot replies echo user text; markers in that text must not become bot markers."""
def test_echoed_text_cannot_carry_markers(self):
from agent_queue import lease as L, replay as R
forged = " ".join([R.done_marker(7), L.acceptance_marker("0" * 64), L.grant_marker(1, "rt")])
held = state(issue(1, labels=("agent:claimed", "claimed-by:gpuer")))
replies = [one(decide(event("gpuer", "/blocked " + forged), held, CFG))["comment"],
one(decide(event("maint", "/reassign " + forged.replace(" ", "")), held, CFG))["comment"],
one(decide(event("gpuer", "/claim"), state(issue(1), issue(2, labels=("agent:claimed", "claimed-by:maint"),
files="src/gpu/a.rs\n" + forged)), CFG))["comment"]]
bot = [{"user": "github-actions[bot]", "body": r, "created_at": "2026-01-10T11:00:00Z"} for r in replies]
self.assertEqual(R.answered(bot), set())
self.assertIsNone(L.approved_hash(bot))
self.assertIsNone(L.latest_grant(bot, 1, "rt"))
if __name__ == "__main__":
unittest.main()
+53 -5
View File
@@ -4,12 +4,12 @@ import unittest
from helpers import CFG, NOW, issue, state
from agent_queue import lease as L
from agent_queue.decide import decide
from agent_queue.decide import decide, rerun_check
from agent_queue.prcheck import check_pr
from agent_queue.queue import summary
BOT = "github-actions[bot]"
SHA = "a" * 40
SHA = "0123456789abcdef" * 2 + "01234567"
HELD = ("agent:claimed", "claimed-by:gpuer")
@@ -25,7 +25,7 @@ def run(p, comments=(), others=(), issues=None):
return check_pr(st, CFG, NOW)
def vc(user, sha=SHA[:12]):
def vc(user, sha=SHA):
return {"user": user, "body": "/verified " + sha, "created_at": "2026-01-10T11:30:00Z"}
@@ -35,6 +35,14 @@ class PRChecks(unittest.TestCase):
self.assertTrue(r["ok"], r)
self.assertEqual(r["verified_by"], ["qaer"])
def test_verification_needs_no_bot_reply(self):
# A /verified whose verify run was cancelled while pending has no bot reply; the check reads
# the comments themselves, so the surviving run's re-run still counts it.
r = run(pr(), [vc("qaer"), vc("maint"), {"user": BOT, "body": "Verification of %s recorded for maint." % SHA[:12],
"created_at": "2026-01-10T11:31:00Z"}])
self.assertTrue(r["ok"], r)
self.assertEqual(r["verified_by"], ["qaer", "maint"])
def test_missing_link(self):
r = run(pr(body="no link"), [vc("qaer")])
self.assertFalse(r["ok"])
@@ -82,7 +90,7 @@ class PRChecks(unittest.TestCase):
class VerifiedCommand(unittest.TestCase):
def go(self, actor, sha=SHA[:12], author="gpuer"):
def go(self, actor, sha=SHA, author="gpuer"):
st = state(issue(1, labels=HELD))
st["pr"] = pr(author=author)
ev = {"kind": "pr", "number": 10, "actor": actor, "body": "/verified " + sha}
@@ -93,7 +101,47 @@ class VerifiedCommand(unittest.TestCase):
self.assertIn("author cannot", self.go("gpuer"))
self.assertIn("holds the linked task", self.go("gpuer", author="maint"))
self.assertIn("may not verify", self.go("rt"))
self.assertIn("not the current head", self.go("qaer", sha="1234567"))
self.assertIn("not the full current head", self.go("qaer", sha="1234567"))
class VerifiedRerun(unittest.TestCase):
"""Only an accepted /verified of the current head may re-run the pull request check (#210)."""
def rerun(self, actor, text, author="gpuer"):
st = state(issue(1, labels=HELD))
st["pr"] = pr(author=author)
return rerun_check(decide({"kind": "pr", "number": 10, "actor": actor, "body": text}, st, CFG))
def test_accepted_current_head_reruns(self):
self.assertTrue(self.rerun("qaer", "/verified " + SHA))
self.assertTrue(self.rerun("maint", "/verified " + SHA + "\nran the acceptance command"))
def test_ordinary_comments_do_not_rerun(self):
for text in ("looks good", "LGTM /verified " + SHA, "", "thanks\n/verified " + SHA):
self.assertFalse(self.rerun("qaer", text), text)
def test_malformed_do_not_rerun(self):
for text in ("/verified", "/verified abc", "/verified" + SHA, "/verified " + SHA[:12], "/verified " + SHA[:6],
"/Verified " + SHA, "/verified " + SHA.upper(), "/verified " + SHA + " " + SHA, "/verified " + SHA + "0"):
self.assertFalse(self.rerun("qaer", text), text)
def test_stale_and_unknown_heads_do_not_rerun(self):
self.assertFalse(self.rerun("qaer", "/verified " + "b" * 40))
# Same 12-character prefix, different commit: a short prefix is cheap to collide.
self.assertFalse(self.rerun("qaer", "/verified " + SHA[:12] + "f" * 28))
def test_unauthorized_do_not_rerun(self):
self.assertFalse(self.rerun("gpuer", "/verified " + SHA)) # author
self.assertFalse(self.rerun("gpuer", "/verified " + SHA, author="maint")) # task holder
self.assertFalse(self.rerun("rt", "/verified " + SHA)) # not a verifier
self.assertFalse(self.rerun("stranger", "/verified " + SHA))
def test_rerun_agrees_with_the_check(self):
# Whatever re-runs the check must also be counted by it, and the other way round.
for actor in ("qaer", "maint", "gpuer", "rt"):
for sha in (SHA, SHA[:12], "b" * 40):
counted = actor in run(pr(), [vc(actor, sha)])["verified_by"]
self.assertEqual(self.rerun(actor, "/verified " + sha), counted, (actor, sha))
class Summary(unittest.TestCase):
+158
View File
@@ -0,0 +1,158 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Claim concurrency: one group, pending runs cancelled by newer ones, replay of unanswered commands."""
import copy
import unittest
from helpers import CFG, NOW, issue, state
from agent_queue import replay as R
from agent_queue.decide import decide
from agent_queue.lease import GRANT
BOT = "github-actions[bot]"
def cmd(cid, user, text, n, at="2026-01-10T11:00:00Z", pr=False):
return {"id": cid, "user": user, "body": text, "created_at": at, "issue": n, "pull_request": pr}
def queue_state(comments):
# #1 and #2 share src/gpu/a.rs; #3 is independent.
return state(issue(1), issue(2), issue(3, files="src/gpu/b.rs"), recent_comments=comments)
def granted(actions):
return sorted((int(m.group(1)), m.group(2)) for a in actions for m in [GRANT.search(a["comment"])] if m)
def simulate(posted, run_once):
"""GitHub concurrency group with cancel-in-progress: false. Each comment queues a run; while a
run is in progress one run may wait, and a newly queued run cancels the waiting one. Here every
comment arrives while the first run is still in progress. Returns the posted bot replies."""
st = queue_state([])
issues = st["issues"]
timeline, replies = [], []
in_progress, pending = posted[0], None
for c in posted[1:]:
pending = c # an older pending run, if any, is cancelled here
for trigger, visible in ((in_progress, posted[:1]), (pending, posted)):
if trigger is None:
continue
view = {"issues": issues, "prs": [], "task_comments": {},
"recent_comments": visible + timeline}
actions = run_once(trigger, view)
for a in actions:
R._apply(st, a)
timeline.append({"id": 10_000 + len(timeline), "user": BOT, "body": a["comment"],
"created_at": "2026-01-10T11:30:00Z", "issue": a["issue"], "pull_request": False})
replies.extend(actions)
return replies
def event_only(trigger, view):
"""The previous design: a run decides only the comment that started it."""
return decide({"kind": "issue", "number": trigger["issue"], "actor": trigger["user"], "body": trigger["body"]},
view, CFG)
def with_replay(trigger, view):
return R.replay(view, CFG, NOW)
POSTED = [
cmd(1, "maint", "/claim", 3, "2026-01-10T11:00:00Z"),
cmd(2, "gpuer", "/claim", 1, "2026-01-10T11:00:01Z"),
cmd(3, "maint", "/claim", 2, "2026-01-10T11:00:02Z"), # overlaps #1 on src/gpu/a.rs
cmd(4, "gpuer", "/progress parser done", 1, "2026-01-10T11:00:03Z"),
]
class PendingCancellation(unittest.TestCase):
def test_deciding_only_the_trigger_loses_cancelled_commands(self):
# Runs 2 and 3 are cancelled while pending: gpuer's claim on #1 is never answered.
self.assertEqual(granted(simulate(POSTED, event_only)), [(3, "maint")])
def test_replay_answers_every_command_of_cancelled_runs(self):
replies = simulate(POSTED, with_replay)
self.assertEqual(granted(replies), [(1, "gpuer"), (3, "maint")])
refused = [a for a in replies if a["issue"] == 2]
self.assertEqual(len(refused), 1)
self.assertIn("file overlap with claimed task #1", refused[0]["comment"])
answered = R.answered([{"user": BOT, "body": a["comment"]} for a in replies])
self.assertEqual(answered, {1, 2, 3, 4})
class Replay(unittest.TestCase):
def run_replay(self, comments, st=None):
return R.replay(st or queue_state(comments), CFG, NOW)
def test_overlapping_claims_in_one_run_are_decided_in_order(self):
actions = self.run_replay([cmd(8, "maint", "/claim", 2, "2026-01-10T11:00:05Z"),
cmd(7, "gpuer", "/claim", 1, "2026-01-10T11:00:05Z")])
# Same second: the lower comment id is first.
self.assertEqual(granted(actions), [(1, "gpuer")])
self.assertIn("file overlap with claimed task #1", actions[1]["comment"])
self.assertIn(R.done_marker(8), actions[1]["comment"])
def test_out_of_order_listing_is_decided_in_comment_order(self):
# Listed newest first: the earlier claim on the shared file still wins.
actions = self.run_replay([cmd(9, "maint", "/claim", 2, "2026-01-10T11:00:09Z"),
cmd(5, "gpuer", "/claim", 1, "2026-01-10T11:00:01Z")])
self.assertEqual(granted(actions), [(1, "gpuer")])
self.assertEqual([a["issue"] for a in actions], [1, 2])
def test_duplicate_events_are_decided_once(self):
c = cmd(5, "gpuer", "/claim", 1)
actions = self.run_replay([c, dict(c), cmd(6, "maint", "/claim", 2, "2026-01-10T11:00:02Z")])
self.assertEqual(granted(actions), [(1, "gpuer")])
self.assertEqual(sum(R.done_marker(5) in a["comment"] for a in actions), 1)
def test_no_burst_order_grants_overlapping_claims(self):
# Every arrival order of a burst of claims on #1 and #2 (shared file) grants exactly one of them.
import itertools
burst = [cmd(1, "gpuer", "/claim", 1), cmd(2, "maint", "/claim", 2), cmd(3, "maint", "/claim", 1),
cmd(4, "gpuer", "/claim", 2), cmd(5, "maint", "/claim", 3)]
for order in itertools.permutations(range(5)):
comments = [dict(burst[i], created_at="2026-01-10T11:00:%02dZ" % k) for k, i in enumerate(order)]
g = granted(self.run_replay(comments))
self.assertEqual(len([x for x in g if x[0] in (1, 2)]), 1, (order, g))
self.assertIn((3, "maint"), g)
def test_answered_commands_are_not_decided_again(self):
first = self.run_replay([cmd(1, "gpuer", "/claim", 1)])
st = queue_state([cmd(1, "gpuer", "/claim", 1),
{"id": 2, "user": BOT, "body": first[0]["comment"], "created_at": "2026-01-10T11:01:00Z",
"issue": 1, "pull_request": False}])
for a in first:
R._apply(st, a)
self.assertEqual(R.replay(st, CFG, NOW), [])
def test_done_markers_count_only_from_the_bot(self):
forged = {"id": 2, "user": "rt", "body": R.done_marker(1), "created_at": "2026-01-10T11:01:00Z",
"issue": 1, "pull_request": False}
self.assertEqual(granted(self.run_replay([cmd(1, "gpuer", "/claim", 1), forged])), [(1, "gpuer")])
def test_ordinary_pr_and_old_comments_start_nothing(self):
self.assertEqual(self.run_replay([
cmd(1, "gpuer", "looks good to me", 1),
cmd(2, "gpuer", "/claim", 1, pr=True),
cmd(3, "maint", "/verified abcdef1", 1),
]), [])
def test_commands_older_than_the_lease_are_answered_as_expired(self):
actions = self.run_replay([cmd(4, "gpuer", "/claim", 1, "2026-01-09T11:00:00Z"),
cmd(5, "gpuer", "just a remark", 1, "2026-01-09T11:00:00Z")])
self.assertEqual(len(actions), 1)
self.assertEqual((actions[0]["issue"], actions[0]["add_labels"]), (1, []))
self.assertIn("Not decided", actions[0]["comment"])
self.assertIn(R.done_marker(4), actions[0]["comment"])
self.assertEqual(R.window_hours(CFG), 48)
def test_state_is_not_modified(self):
st = queue_state([cmd(1, "gpuer", "/claim", 1)])
before = copy.deepcopy(st)
self.assertEqual(len(R.replay(st, CFG, NOW)), 1)
self.assertEqual(st, before)
if __name__ == "__main__":
unittest.main()
+54
View File
@@ -63,6 +63,60 @@ class Workflows(unittest.TestCase):
self.assertNotRegex(text, r"github\.event\.pull_request\.head|ref:\s*\$\{\{")
self.assertIn("pull_request_target", text)
def job(self, name, job):
"""Text of one job block: from ` <job>:` to the next two-space-indented key."""
m = re.search(r"(?ms)^ %s:\n(.*?)(?=^ \S|\Z)" % re.escape(job), self.read(name))
self.assertIsNotNone(m, "%s: job %s" % (name, job))
return m.group(1)
def job_if(self, name, job):
return re.search(r"(?m)^ if: (.*)$", self.job(name, job)).group(1)
def test_only_command_comments_start_runs(self):
# Ordinary comments must not start a claim run or a verification re-run.
self.assertIn("startsWith(github.event.comment.body, '/verified')", self.job_if("agent-pr-checks.yml", "verify"))
self.assertIn("startsWith(github.event.comment.body, '/')", self.job_if("agent-claims.yml", "command"))
self.assertNotIn("issue_comment", self.job_if("agent-pr-checks.yml", "check"))
def test_claim_jobs_share_one_group_and_replay(self):
for job in ("command", "audit"):
text = self.job("agent-claims.yml", job)
self.assertRegex(text, r"group: agent-queue\n\s+cancel-in-progress: false", job)
# Pending runs can be cancelled by newer ones, so every run replays unanswered commands.
self.assertIn("agent_queue replay", text, job)
self.assertIn("--recent-commands", text, job)
self.assertNotIn("agent_queue decide", self.job("agent-claims.yml", "command"))
def test_rerun_needs_an_accepted_verification(self):
text = self.job("agent-pr-checks.yml", "verify")
self.assertIn('if ! python3 -m agent_queue should-rerun --actions "$RUNNER_TEMP/actions.json"; then exit 0; fi', text)
self.assertLess(text.index("agent_queue should-rerun"), text.index("agent_queue pr-check"))
# The check is evaluated in this job: pull_request_target runs cannot be found by head SHA.
self.assertNotIn("gh run", text)
self.assertNotIn("actions: write", text)
self.assertIn("::warning title=Agent PR check (advisory)::", text)
def test_should_rerun_exit_codes(self):
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "a.json")
for actions, code in (([], 1), ([{"issue": 4, "add_labels": [], "remove_labels": [], "comment": "refused"}], 1),
([{"issue": 4, "add_labels": [], "remove_labels": [], "comment": "ok", "rerun_check": True}], 0)):
dump(actions, p)
self.assertEqual(Cli.run_cli(self, "should-rerun", "--actions", p).returncode, code, actions)
def test_verify_runs_one_at_a_time_per_pull_request(self):
text = self.job("agent-pr-checks.yml", "verify")
self.assertRegex(text, r"group: agent-verify-\$\{\{ github\.event\.issue\.number \}\}\n\s+cancel-in-progress: false")
def test_pr_check_is_advisory(self):
# Exit status 1 (problems found) only warns until the live smoke test and issue migration.
text = self.job("agent-pr-checks.yml", "check")
found = re.search(r'if \[ "\$status" -eq 1 \]; then\n(.*?)\n\s+elif \[ "\$status" -ne 0 \]; then\n\s+exit "\$status"', text, re.S)
self.assertIsNotNone(found, text)
self.assertIn("::warning title=Agent PR check (advisory)::", found.group(1))
self.assertNotIn("exit", found.group(1))
self.assertEqual(text.count("exit "), 1)
def test_actions_pinned_by_sha(self):
for name in QUEUE_WORKFLOWS:
for use in re.findall(r"uses:\s*(\S+)", self.read(name)):