Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
134 changes: 134 additions & 0 deletions .github/script/ci/aie_image_hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
#!/usr/bin/env python3
# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved.
# Portions of this file consist of AI-generated content.
"""The toolchain hash: the tag of the dev kit's kernel build image.

aie_image_hash.py [<toolchain.lock> <Dockerfile>]

Prints the first 16 hex digits of the sha256 of the two files' normalised
text, flm-dev-kit/FLM_Xclbin/toolchain.lock and docker/aie-build.Dockerfile
by default (paths relative to the current directory, the repository root in
CI). Each file is hashed on its own and the hash is that of the two
digests, so a line moved from one file to the other is a new hash.
devkit-aie-image.yml tags ghcr.io/rocm/fastflowlm/aie-build
:<toolchain hash> with it, and devkit-xclbins.yml looks that tag up, so both
must compute it here.

Normalised: line endings made "\\n", trailing whitespace stripped, and blank
lines and comment lines (first non-blank character "#") dropped, so an edit
to the comments of either file keeps the tag; devkit-aie-image.yml then
finds the tag published and neither rebuilds nor republishes the image (it
still runs the kernel check in it). Docker ignores those lines, and every
toolchain.lock line that is not KEY=VALUE is one of them. The exception is a
Dockerfile's parser directives (# syntax=, # escape=, # check=) at the top of
the file: they are comment-shaped but change the build, so they are kept.
Any other change, a value, an instruction, a directive, changes the hash.

Two limits keep that true. A Dockerfile with a heredoc (RUN <<EOF, COPY
<<EOF /path) is hashed with only its line endings normalised: in a heredoc
body a "#" line, a blank line or trailing whitespace is content, not a
comment. And toolchain.lock must hold only "#" comments at column 0, blank
lines and KEY=VALUE lines with no whitespace in the value (the script exits
1 otherwise), so every byte it ignores there is one no build arg reads.
"""

from __future__ import annotations

import argparse
import hashlib
import re
import sys
from pathlib import Path

LOCK = "flm-dev-kit/FLM_Xclbin/toolchain.lock"
DOCKERFILE = "docker/aie-build.Dockerfile"
HASH_LEN = 16

# BuildKit reads a directive only before the first comment, blank line or
# instruction; the names are case-insensitive, spaces around "=" allowed.
# Blank lines among them are skipped here, not treated as the end: keeping a
# line Docker reads as a comment costs at most one extra rebuild.
DIRECTIVE = re.compile(r"^#\s*(syntax|escape|check)\s*=", re.IGNORECASE)
# A heredoc marker, <<EOF, <<-EOF, <<"EOF", outside a comment line. It also
# matches a shell here-string (<<<word): a false hit only costs a rebuild.
HEREDOC = re.compile(r"<<-?\s*[\"']?[A-Za-z_]")
# What toolchain.lock may hold (devkit-aie-image.yml's check, before this).
LOCK_LINE = re.compile(r"#.*|\s*|[A-Z0-9_]+=\S+")


def lines_of(text: str) -> list[str]:
return text.replace("\r\n", "\n").replace("\r", "\n").split("\n")


def has_heredoc(text: str) -> bool:
return any(HEREDOC.search(line) for line in lines_of(text)
if not line.lstrip().startswith("#"))


def check_lock(text: str) -> None:
"""Raises ValueError naming the first line of <text> that is not a "#"
comment at column 0, blank, or KEY=VALUE with no whitespace."""
for n, line in enumerate(lines_of(text), 1):
if not LOCK_LINE.fullmatch(line):
raise ValueError(f"line {n} is not KEY=VALUE, a comment at column 0 or blank: {line!r}")


def normalise(text: str, directives: bool = False) -> str:
"""<text> without blank and comment lines, each kept line stripped at its
end and ended by "\\n". With <directives>, the parser directives at the top
are kept."""
out = []
in_header = directives
for line in lines_of(text):
line = line.rstrip()
stripped = line.lstrip()
if not stripped:
continue
if stripped.startswith("#"):
if in_header and DIRECTIVE.match(stripped):
out.append(stripped)
continue
in_header = False
continue
in_header = False
out.append(line)
return "".join(f"{line}\n" for line in out)


def sha256(text: str) -> bytes:
return hashlib.sha256(text.encode("utf-8")).digest()


def toolchain_hash(lock_text: str, dockerfile_text: str) -> str:
"""The first HASH_LEN hex digits of sha256(sha256(normalised lock) +
sha256(normalised Dockerfile)). Raises ValueError for a bad lock."""
check_lock(lock_text)
if has_heredoc(dockerfile_text):
dockerfile = "\n".join(lines_of(dockerfile_text))
else:
dockerfile = normalise(dockerfile_text, directives=True)
return hashlib.sha256(sha256(normalise(lock_text)) + sha256(dockerfile)).hexdigest()[:HASH_LEN]


def read(path: str) -> str:
return Path(path).read_bytes().decode("utf-8-sig")


def main(argv: list[str] | None = None) -> int:
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("lock", nargs="?", default=LOCK, help=f"default {LOCK}")
ap.add_argument("dockerfile", nargs="?", default=DOCKERFILE, help=f"default {DOCKERFILE}")
args = ap.parse_args(argv)
try:
print(toolchain_hash(read(args.lock), read(args.dockerfile)))
except (OSError, UnicodeDecodeError) as e:
print(f"aie_image_hash.py: {e}", file=sys.stderr)
return 1
except ValueError as e:
print(f"::error file={args.lock}::{e}", file=sys.stderr)
return 1
return 0


if __name__ == "__main__":
sys.exit(main())
262 changes: 262 additions & 0 deletions .github/script/ci/test_aie_image_hash.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,262 @@
# Copyright © Advanced Micro Devices, Inc., or its affiliates. All rights reserved.
# Portions of this file consist of AI-generated content.
"""Tests for aie_image_hash.py: python3 -m unittest discover -s ci -p 'test_*.py' -t ci"""

from __future__ import annotations

import io
import re
import sys
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import aie_image_hash as ah # noqa: E402

REPO = HERE.parents[2]

LOCK = """\
# Copyright header
#
# The toolchain, pinned.

# Base image.
UBUNTU_IMAGE=ubuntu:24.04@sha256:00
PEANO_VERSION=1.2.3
"""

DOCKERFILE = """\
# syntax=docker/dockerfile:1
# Copyright header
#
# What the image is.
ARG UBUNTU_IMAGE
FROM ${UBUNTU_IMAGE} AS build
ARG PEANO_VERSION
# Peano, by version.
RUN pip install llvm-aie==${PEANO_VERSION} \\
&& echo done
"""


def h(lock: str = LOCK, dockerfile: str = DOCKERFILE) -> str:
return ah.toolchain_hash(lock, dockerfile)


class HashFormat(unittest.TestCase):
def test_sixteen_hex(self):
self.assertRegex(h(), r"^[0-9a-f]{16}$")

def test_current_files(self):
lock, dockerfile = REPO / ah.LOCK, REPO / ah.DOCKERFILE
if not (lock.is_file() and dockerfile.is_file()):
self.skipTest("not in a FastFlowLM checkout")
out = io.StringIO()
with redirect_stdout(out):
self.assertEqual(ah.main([str(lock), str(dockerfile)]), 0)
self.assertRegex(out.getvalue(), r"^[0-9a-f]{16}\n$")


class SameHash(unittest.TestCase):
def test_comment_edit(self):
self.assertEqual(h(LOCK.replace("pinned.", "pinned, with care."),
DOCKERFILE.replace("# Peano, by version.", "# Peano, the AIE compiler.")), h())

def test_comment_added_and_removed(self):
self.assertEqual(h(LOCK + "# A trailing note.\n",
DOCKERFILE.replace("# Peano, by version.\n", "")), h())

def test_indented_comment(self):
self.assertEqual(h(dockerfile=DOCKERFILE.replace("ARG PEANO_VERSION\n",
"ARG PEANO_VERSION\n # note\n")), h())

def test_blank_lines(self):
self.assertEqual(h(LOCK.replace("\n", "\n\n"), "\n" + DOCKERFILE + "\n \n"), h())

def test_trailing_whitespace(self):
self.assertEqual(h(LOCK.replace("pinned.\n", "pinned. \t\n"),
DOCKERFILE.replace("AS build\n", "AS build \n")), h())

def test_line_endings(self):
self.assertEqual(h(LOCK.replace("\n", "\r\n"), DOCKERFILE.replace("\n", "\r\n")), h())
self.assertEqual(h(LOCK.replace("\n", "\r"), DOCKERFILE), h())

def test_no_final_newline(self):
self.assertEqual(h(LOCK.rstrip("\n"), DOCKERFILE.rstrip("\n")), h())

def test_blank_line_between_directives(self):
base = "# syntax=docker/dockerfile:1\n# check=error=true\nFROM x\n"
self.assertEqual(h(dockerfile=base.replace("\n# check", "\n\n# check")), h(dockerfile=base))


class DifferentHash(unittest.TestCase):
def test_value_change(self):
self.assertNotEqual(h(LOCK.replace("1.2.3", "1.2.4")), h())

def test_key_added(self):
self.assertNotEqual(h(LOCK + "XRT_VERSION=2\n"), h())

def test_instruction_change(self):
self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("echo done", "echo ok")), h())

def test_indentation_inside_instruction(self):
self.assertNotEqual(h(dockerfile=DOCKERFILE.replace(" && echo", " && echo")), h())

def test_directive_change(self):
self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("dockerfile:1", "dockerfile:1.7")), h())

def test_directive_added_or_removed(self):
self.assertNotEqual(h(dockerfile="# escape=`\n" + DOCKERFILE), h())
self.assertNotEqual(h(dockerfile="# check=error=true\n" + DOCKERFILE), h())
self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("# syntax=docker/dockerfile:1\n", "")), h())

def test_directive_spelling(self):
self.assertNotEqual(h(dockerfile=DOCKERFILE.replace("# syntax=", "# SYNTAX = ")), h())

def test_lock_and_dockerfile_kept_apart(self):
# The same line moved from one file to the other is a different input.
self.assertNotEqual(h(LOCK + "X=1\n", DOCKERFILE), h(LOCK, "X=1\n" + DOCKERFILE))
self.assertNotEqual(h(LOCK.replace("PEANO_VERSION=1.2.3\n", ""), "PEANO_VERSION=1.2.3\n" + DOCKERFILE),
h())


HEREDOC = """\
# syntax=docker/dockerfile:1
FROM x
COPY <<EOF /etc/tool.conf
# a setting, commented out
key=value

EOF
RUN <<'SCRIPT'
#!/bin/sh
echo hi
SCRIPT
"""


class Heredoc(unittest.TestCase):
def test_detected(self):
self.assertTrue(ah.has_heredoc(HEREDOC))
self.assertTrue(ah.has_heredoc('RUN <<-"EOF" bash\n'))
self.assertFalse(ah.has_heredoc(DOCKERFILE))
self.assertFalse(ah.has_heredoc("FROM x\n# RUN <<EOF\n"))

def test_comment_line_in_body_is_content(self):
self.assertNotEqual(h(dockerfile=HEREDOC.replace("# a setting", "# another setting")),
h(dockerfile=HEREDOC))
self.assertNotEqual(h(dockerfile=HEREDOC.replace("#!/bin/sh", "#!/bin/bash")), h(dockerfile=HEREDOC))

def test_blank_line_and_trailing_whitespace_in_body_are_content(self):
self.assertNotEqual(h(dockerfile=HEREDOC.replace("key=value\n\n", "key=value\n")),
h(dockerfile=HEREDOC))
self.assertNotEqual(h(dockerfile=HEREDOC.replace("key=value", "key=value ")), h(dockerfile=HEREDOC))

def test_line_endings_still_normalised(self):
self.assertEqual(h(dockerfile=HEREDOC.replace("\n", "\r\n")), h(dockerfile=HEREDOC))


class Lock(unittest.TestCase):
def test_accepted(self):
ah.check_lock(LOCK)
ah.check_lock(LOCK.replace("\n", "\r\n") + " \n")

def test_rejected(self):
for bad in ("PEANO_VERSION=1.2.3 \n", # trailing whitespace a build arg would carry
"PEANO_VERSION=1.2 3\n", # whitespace inside the value
" PEANO_VERSION=1.2.3\n", # indented: hashed, but no build arg
" # indented comment\n",
"PEANO_VERSION=\n",
"peano_version=1\n",
"ARG X\n"):
with self.subTest(bad=bad), self.assertRaises(ValueError):
h(LOCK + bad)

def test_cli_error(self):
with tempfile.TemporaryDirectory() as d:
lock, dockerfile = Path(d) / "toolchain.lock", Path(d) / "Dockerfile"
lock.write_text(LOCK + "X=1 \n", encoding="utf-8", newline="\n")
dockerfile.write_text(DOCKERFILE, encoding="utf-8", newline="\n")
err, out = io.StringIO(), io.StringIO()
with redirect_stderr(err), redirect_stdout(out):
self.assertEqual(ah.main([str(lock), str(dockerfile)]), 1)
self.assertEqual(out.getvalue(), "")
self.assertIn("::error file=", err.getvalue())
self.assertIn("line 8", err.getvalue())


class Directives(unittest.TestCase):
def test_only_at_the_top(self):
# After a comment or an instruction, "# syntax=" is a comment.
late = DOCKERFILE.replace("# Peano, by version.", "# syntax=docker/dockerfile:1.7")
self.assertEqual(h(dockerfile=late), h())
after_comment = "# A note\n# syntax=docker/dockerfile:1\nFROM x\n"
self.assertEqual(h(dockerfile=after_comment), h(dockerfile="FROM x\n"))

def test_kept_in_dockerfile_only(self):
# toolchain.lock has no directives: "# syntax=" there is a comment.
self.assertEqual(h("# syntax=docker/dockerfile:1\n" + LOCK), h())

def test_normalise(self):
self.assertEqual(ah.normalise(DOCKERFILE, directives=True).splitlines()[:2],
["# syntax=docker/dockerfile:1", "ARG UBUNTU_IMAGE"])
self.assertNotIn("#", ah.normalise(LOCK))


class Workflows(unittest.TestCase):
"""The publisher and the lookup must both compute the tag with the
script: an inline hash in one of them makes the tags silently differ."""

CALL = 'python3 -I .github/script/ci/aie_image_hash.py "$LOCK" "$DOCKERFILE"'
EXPECTED = {"devkit-aie-image.yml": 2, "devkit-xclbins.yml": 1}

def steps(self, text: str) -> list[str]:
"""The "Read toolchain.lock" steps of a workflow, each up to the next step."""
blocks = re.split(r"(?m)^\s*- name: ", text)
return [b for b in blocks if b.startswith("Read toolchain.lock")]

def test_read_steps_call_the_script(self):
for name, count in self.EXPECTED.items():
path = REPO / ".github" / "workflows" / name
if not path.is_file():
self.skipTest("not in a FastFlowLM checkout")
text = path.read_text(encoding="utf-8")
with self.subTest(workflow=name):
self.assertIn(f"LOCK: {ah.LOCK}\n", text.replace("\r\n", "\n"))
self.assertIn(f"DOCKERFILE: {ah.DOCKERFILE}\n", text.replace("\r\n", "\n"))
steps = self.steps(text)
self.assertEqual(len(steps), count)
for step in steps:
self.assertIn(self.CALL, step)
self.assertNotIn("sha256sum", step)

def test_steps_split(self):
text = (" steps:\n - name: Read toolchain.lock\n run: a\n"
" - name: Other\n run: sha256sum\n")
self.assertEqual(self.steps(text), ["Read toolchain.lock\n run: a\n"])


class Cli(unittest.TestCase):
def test_files(self):
with tempfile.TemporaryDirectory() as d:
lock, dockerfile = Path(d) / "toolchain.lock", Path(d) / "Dockerfile"
lock.write_bytes(("\ufeff" + LOCK.replace("\n", "\r\n")).encode("utf-8"))
dockerfile.write_text(DOCKERFILE, encoding="utf-8", newline="\n")
out = io.StringIO()
with redirect_stdout(out):
self.assertEqual(ah.main([str(lock), str(dockerfile)]), 0)
self.assertEqual(out.getvalue(), h() + "\n")

def test_missing_file(self):
with tempfile.TemporaryDirectory() as d:
err = io.StringIO()
with redirect_stderr(err):
self.assertEqual(ah.main([str(Path(d) / "nope"), str(Path(d) / "nope2")]), 1)
self.assertTrue(re.search(r"nope", err.getvalue()))


if __name__ == "__main__":
unittest.main()
Loading
Loading