test(packer): qualify asset contracts and improve Jenkins reporting

This commit is contained in:
2026-10-16 11:47:58 +01:00
parent 13c0ababbb
commit 91eb86f317
8 changed files with 506 additions and 51 deletions
@@ -0,0 +1,219 @@
package p.packer.services;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import p.packer.messages.*;
import p.packer.repositories.*;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HexFormat;
import java.util.List;
import java.util.Objects;
import static org.junit.jupiter.api.Assertions.*;
/** Producer contract checks only: no runtime executable or runtime decoder. */
final class PackerAssetContractTest {
private static final ObjectMapper JSON = new ObjectMapper();
private static final int[] COLORS = {0x123456ff, 0xabcdef80, 0x34567800, 0x876543ff};
@TempDir Path projectRoot;
@ParameterizedTest
@CsvSource({"8,1", "16,3", "32,64"})
void glyphPayloadMatchesIndependentNibblesAndRgba(int tileSize, int paletteCount) throws Exception {
glyph(7, tileSize, paletteCount, true);
registry(7);
final Envelope packed = pack();
final JsonNode entry = packed.header().path("asset_table").get(0);
assertEquals("GLYPH", entry.path("bank_type").asText());
assertEquals("NONE", entry.path("codec").asText());
assertEquals(tileSize, entry.path("metadata").path("tile_size").asInt());
assertEquals(256, entry.path("metadata").path("width").asInt());
assertEquals(256, entry.path("metadata").path("height").asInt());
assertEquals(paletteCount, entry.path("metadata").path("palette_count").asInt());
assertEquals(32768 + paletteCount * 64, entry.path("size").asInt());
assertEquals(65536 + paletteCount * 64, entry.path("decoded_size").asInt());
assertArrayEquals(expectedGlyph(tileSize, paletteCount), packed.slice(entry));
}
@Test
void embeddedHeaderAddressesMultipleAssetsAndPreloadsByBankIdentity() throws Exception {
glyph(7, 8, 1, true);
glyph(33, 8, 1, false);
glyph(16909060, 8, 1, true);
scene(99);
// Deliberately unsorted registry; asset identity must not become list index or slot.
registry(16909060, 99, 33, 7);
final Envelope packed = pack();
final JsonNode entries = packed.header().path("asset_table");
assertEquals(List.of(7, 33, 99, 16909060),
java.util.stream.StreamSupport.stream(entries.spliterator(), false)
.map(e -> e.path("asset_id").asInt()).toList());
assertEquals(JSON.readTree("""
[{"asset_id":7,"slot":0},{"asset_id":99,"slot":0},{"asset_id":16909060,"slot":1}]
"""), packed.header().path("preload"));
int end = 0;
for (JsonNode entry : entries) {
assertEquals(end, entry.path("offset").asInt(), "offset is payload-relative and contiguous");
assertEquals("NONE", entry.path("codec").asText());
if (entry.path("asset_id").asInt() == 99) {
assertEquals("SCENE", entry.path("bank_type").asText());
assertEquals(1, entry.path("metadata").path("version").asInt());
assertEquals(4, entry.path("metadata").path("layer_count").asInt());
assertEquals(96, entry.path("decoded_size").asInt()); // 4 * (16 overhead + 8 tile)
assertArrayEquals(hex("scene-v1.hex"), packed.slice(entry));
} else {
assertArrayEquals(expectedGlyph(8, 1), packed.slice(entry));
}
end += entry.path("size").asInt();
}
assertEquals(packed.bytes().length, packed.payloadOffset() + end, "no unaddressed/trailing payload");
}
@Test
void invalidPaletteCannotPublishAnAssetArtifact() throws Exception {
glyph(7, 8, 1, true);
registry(7);
Path manifestPath = asset(7).resolve("asset.json");
ObjectNode manifest = (ObjectNode) JSON.readTree(manifestPath.toFile());
((ObjectNode) manifest.path("output").path("pipeline").path("palettes").get(0)).put("index", 64);
JSON.writeValue(manifestPath.toFile(), manifest);
final var result = service().packWorkspace(new PackWorkspaceRequest(project()));
assertEquals(PackerOperationStatus.PARTIAL, result.status());
assertTrue(result.result().emittedArtifacts().isEmpty());
assertFalse(Files.exists(projectRoot.resolve("build/assets.pa")));
}
private Envelope pack() throws Exception {
final var result = service().packWorkspace(new PackWorkspaceRequest(project()));
assertEquals(PackerOperationStatus.SUCCESS, result.status(), result.toString());
final byte[] bytes = Files.readAllBytes(projectRoot.resolve("build/assets.pa"));
final ByteBuffer prelude = ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN);
assertArrayEquals(new byte[]{'A', 'S', 'P', 'A'}, Arrays.copyOf(bytes, 4));
assertEquals(1, prelude.getInt(4));
int headerLength = prelude.getInt(8);
assertTrue(headerLength > 0);
assertEquals(32L + headerLength, prelude.getLong(12));
assertArrayEquals(new byte[12], Arrays.copyOfRange(bytes, 20, 32));
int payloadOffset = Math.toIntExact(prelude.getLong(12));
JsonNode header = JSON.readTree(Arrays.copyOfRange(bytes, 32, payloadOffset));
assertEquals(JSON.readTree(projectRoot.resolve("build/asset_table.json").toFile()), header.path("asset_table"));
assertEquals(JSON.readTree(projectRoot.resolve("build/preload.json").toFile()), header.path("preload"));
return new Envelope(bytes, header, payloadOffset);
}
private record Envelope(byte[] bytes, JsonNode header, int payloadOffset) {
byte[] slice(JsonNode entry) {
int start = payloadOffset + entry.path("offset").asInt();
int end = start + entry.path("size").asInt();
assertTrue(start >= payloadOffset && end <= bytes.length);
return Arrays.copyOfRange(bytes, start, end);
}
}
private byte[] expectedGlyph(int tileSize, int palettes) throws Exception {
byte[] expected = new byte[32768 + palettes * 64];
// Fixed 256-pixel sheet: repeat the independently authored 8-pixel row in the first tile.
byte[] row = hex("glyph-row.hex");
for (int y = 0; y < tileSize; y++) {
for (int x = 0; x < tileSize / 8; x++) {
System.arraycopy(row, 0, expected, y * 128 + x * 4, row.length);
}
}
byte[] colors = hex("glyph-colors.hex");
for (int palette = 0; palette < palettes; palette++) {
System.arraycopy(colors, 0, expected, 32768 + palette * 64, colors.length);
}
return expected;
}
private void glyph(int id, int tileSize, int palettes, boolean preload) throws Exception {
ObjectNode manifest = manifest(id, "glyph_bank", "GLYPH/indexed_v1", preload);
ObjectNode output = (ObjectNode) manifest.path("output");
output.putObject("metadata").put("tile_size", tileSize + "x" + tileSize);
ArrayNode table = output.putObject("pipeline").putArray("palettes");
for (int p = 0; p < palettes; p++) {
ObjectNode palette = table.addObject().put("index", p);
ArrayNode colors = palette.putObject("palette").putArray("rgba8888");
for (int color : COLORS) colors.add(color);
}
manifest.putArray("artifacts").addObject().put("file", "tile.png").put("index", 0);
JSON.writeValue(asset(id).resolve("asset.json").toFile(), manifest);
BufferedImage image = new BufferedImage(tileSize, tileSize, BufferedImage.TYPE_INT_ARGB);
for (int y = 0; y < tileSize; y++) {
for (int x = 0; x < tileSize; x++) {
int rgba = COLORS[x % 4];
image.setRGB(x, y, (rgba >>> 8) | (rgba << 24));
}
}
assertTrue(ImageIO.write(image, "png", asset(id).resolve("tile.png").toFile()));
}
private void scene(int id) throws Exception {
JSON.writeValue(asset(id).resolve("asset.json").toFile(), manifest(id, "scene_bank", "SCENE/tilemap_v1", true));
ObjectNode request = JSON.createObjectNode().put("schema_version", 1).put("format", "SCENE/tilemap_v1").put("version", 1);
ArrayNode layers = request.putArray("layers");
for (int i = 0; i < 4; i++) {
ObjectNode layer = layers.addObject().put("active", true).put("glyph_asset_id", 16909060)
.put("tile_size", 8).put("parallax_factor_x", 1.0).put("parallax_factor_y", 0.5)
.put("width", 1).put("height", 1);
layer.putArray("tiles").addObject().put("active", true).put("glyph_id", i)
.put("palette_id", 0).put("flip_x", (i & 1) != 0).put("flip_y", (i & 2) != 0);
}
JSON.writeValue(asset(id).resolve("scene-bank.pack-request.json").toFile(), request);
}
private ObjectNode manifest(int id, String type, String format, boolean preload) throws Exception {
Files.createDirectories(asset(id));
ObjectNode manifest = JSON.createObjectNode().put("schema_version", 1).put("asset_uuid", "contract-" + id)
.put("name", "asset_" + id).put("type", type);
manifest.putObject("output").put("format", format).put("codec", "NONE");
manifest.putObject("preload").put("enabled", preload);
return manifest;
}
private void registry(int... ids) throws Exception {
Path path = projectRoot.resolve("assets/.prometeu/index.json");
Files.createDirectories(path.getParent());
ObjectNode registry = JSON.createObjectNode().put("schema_version", 1).put("next_asset_id", 16909061);
ArrayNode assets = registry.putArray("assets");
for (int id : ids) assets.addObject().put("asset_id", id).put("asset_uuid", "contract-" + id)
.put("root", "asset-" + id).put("included_in_build", true);
JSON.writeValue(path.toFile(), registry);
}
private Path asset(int id) { return projectRoot.resolve("assets/asset-" + id); }
private PackerProjectContext project() { return new PackerProjectContext("contract", projectRoot); }
private byte[] hex(String name) throws Exception {
try (var input = Objects.requireNonNull(getClass().getResourceAsStream("/fixtures/contracts/" + name))) {
return HexFormat.of().parseHex(new String(input.readAllBytes(), StandardCharsets.UTF_8).replaceAll("\\s", ""));
}
}
private FileSystemPackerWorkspaceService service() {
var foundation = new PackerWorkspaceFoundation(JSON);
var parser = new PackerAssetDeclarationParser(JSON);
var cache = new FileSystemPackerCacheRepository(JSON);
var materializer = new PackerRuntimeAssetMaterializer(new PackerAssetWalker(JSON));
var registry = new PackerRuntimeRegistry(new PackerRuntimeLoader(foundation, parser, cache, materializer));
var resolver = new PackerAssetReferenceResolver(foundation.lookup());
return new FileSystemPackerWorkspaceService(JSON, foundation,
new PackerAssetDetailsService(registry, resolver),
new PackerAssetActionReadService(registry, resolver, foundation.lookup()),
new PackerRuntimePatchService(parser, materializer), registry, cache,
new PackerProjectWriteCoordinator(), event -> {});
}
}
@@ -0,0 +1,59 @@
# Packer binary contract fixtures
These expectations are authored from the published wire contract, independently
of the Java writer. They are not captured from packer output. Tests call the real
`packWorkspace` service and read the embedded header and payload of `assets.pa`;
JSON sidecars alone are not the oracle.
Reference snapshot: runtime `f7d7c167531bb662a1af9d73fc326bb476bf8aa7`:
- `docs/specs/runtime/15-asset-management.md`, sections 3–4 and 9;
- `crates/console/prometeu-hal/src/asset.rs`, scene layout constants;
- `crates/console/prometeu-drivers/src/asset/decode.rs`, nibble and channel order.
The Studio producer's fixed 256×256 sheet and asset envelope are documented in
`docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md`.
No runtime checkout, executable or decoder is needed to execute these tests.
## Fixture interpretation
- `glyph-row.hex`: eight indexed pixels `0,1,2,3,0,1,2,3`, high nibble first.
The test repeats this row within the first 8/16/32-pixel tile and leaves the
rest of the 256×256 sheet at index zero.
- `glyph-colors.hex`: four independent RGBA colors, including opaque index zero,
partial alpha at index one, transparent index two and distinct channel values.
Each palette has these four colors followed by twelve zero entries. Tests
exercise 1, 3 and 64 palettes and compare the entire serialized bank.
- `scene-v1.hex`: a 12-byte SCNE/version-1/four-layer header followed by four
32-byte layer headers and one four-byte tile per layer. All layers are active,
use glyph AssetId `0x01020304` (16909060, not its preload slot 1), tile size 8,
parallax (1.0, 0.5), width/height/count 1 and zero reserved fields. Tile flags
are 1/3/5/7, exercising both flip bits; palette is zero and glyph IDs are
0/1/2/3. Serialized size is 156; decoded size is 4 × (16 + 8) = 96.
The mixed-asset test includes an asset with preload disabled and two GLYPH
preloads in slots 0/1 plus a SCENE preload in slot 0. It checks payload-relative
nonzero offsets, stable IDs, no payload gaps/trailing bytes, and equality between
the embedded header and exported sidecars. The invalid-palette case verifies
that palette index 64 cannot publish a new `assets.pa`.
Existing `FileSystemPackerWorkspaceServiceTest` coverage remains responsible for
basic emission, sparse palettes, material remapping, frozen snapshots and
selected SCENE fields. These fixtures complement those tests at the complete
artifact boundary rather than porting the runtime's decoder corpus.
## Execution and limits
```sh
./gradlew :prometeu-packer:prometeu-packer-v1:test --tests '*PackerAssetContractTest'
```
The suite also runs under ordinary `./gradlew test`. ImageIO uses in-memory
images and temporary files; no display is needed. Fixtures never launch a
runtime, skip for missing runtime, or fall back to a simulated runtime.
Passing these tests demonstrates producer contract coverage, not runtime
loading/rendering. Integrated verification is manual using existing games.
Record the game, Studio/runtime revisions, actions and observed result when
that verification is actually performed; do not infer a gameplay pass from
these byte comparisons.
@@ -0,0 +1 @@
123456ff abcdef80 34567800 876543ff
@@ -0,0 +1,9 @@
53434e45 0100 0400 00000000
01 04030201 08 0000 0000803f 0000003f 01000000 01000000 01000000 00000000
01 00 0000
01 04030201 08 0000 0000803f 0000003f 01000000 01000000 01000000 00000000
03 00 0100
01 04030201 08 0000 0000803f 0000003f 01000000 01000000 01000000 00000000
05 00 0200
01 04030201 08 0000 0000803f 0000003f 01000000 01000000 01000000 00000000
07 00 0300