diff --git a/harbor/sources/go-mysql-v9/Dockerfile.hud b/harbor/sources/go-mysql-v9/Dockerfile.hud new file mode 100644 index 0000000000000000000000000000000000000000..817d4a2a8c2e2743c6bb260be4ed18036a6e3c24 --- /dev/null +++ b/harbor/sources/go-mysql-v9/Dockerfile.hud @@ -0,0 +1,379 @@ +# go_mysql_mariadb_compressed_columns on the coding-template. +# +# Substrate: go-mysql-org/go-mysql at the pinned base SHA (history vaulted at +# task setup by coding/repo.py), Go toolchain, hud serve. Everything answer-key- +# shaped lives under /hud (root, mode 700): the vault, the hidden grader, the +# frozen corpus, the pristine base checkout and gold.diff. Agent shells drop to +# uid 1000 (setpriv), so /hud is unreadable from the agent side. +# +# The network exists only while this image builds. After that grading is +# hermetic: no network, no clock, no RNG, no LLM, and -- the point of this task +# -- no database server. The corpus is NOT captured here: tools/build_corpus.py +# needs real MariaDB and MySQL servers, so it ran on the workstation and its +# output (task/grader/data/{corpus,expected,repro,corpus_manifest.json}) is +# baked into the build context. The oracle is therefore bytes real servers +# wrote, frozen here and unreachable from /workspace, plus -- for the control +# logs -- the untouched base build's own parse, recorded in step 7. + +FROM python:3.12-slim-bookworm + +ARG REPO_URL=https://github.com/go-mysql-org/go-mysql +ARG BASE_SHA=8c39e2d302695a4f17769fc009797cd1476056d9 +# go.mod says `go 1.25.0`; 1.27.0 is the toolchain the grader was calibrated +# against on the workstation, so the image pins the same one. GOTOOLCHAIN=local +# below keeps go from fetching a different one at build or grading time. +ARG GO_VERSION=1.27.0 + +# util-linux: setpriv, the privilege wall for agent shells. +# build-essential: go-mysql itself is pure Go, but CGO_ENABLED=1 is the default +# an agent's shell inherits and a missing gcc would turn an unrelated `go build` +# flag into a task-killing error. +# bubblewrap: the workspace's sandbox, and the whole point of v4. env.py serves +# the agent's shell with network=False, and hud only gets a network namespace of +# its own where bwrap can sandbox — without this package the "no egress" +# statement would be silently untrue (v2/v3 shipped no bwrap: the agents had a +# live route out, see FREEZE «v4 — офлайн-среда»). +# procps: `ps`/`pkill` are absent from python:slim; an agent that cannot list +# processes spends steps discovering that. +RUN apt-get update && apt-get install -y --no-install-recommends \ + git curl ca-certificates util-linux patch build-essential \ + bubblewrap procps \ + && rm -rf /var/lib/apt/lists/* \ + && command -v bwrap && command -v ps && command -v pkill + +# hud pin: 0.6.15 (E-3). In 0.6.13 `hud/environment/namespace.py::_spawn` hands +# the asyncssh channel the transports of an asyncio subprocess; when a client +# drops a channel while its command still runs — which the agent harness does on +# its own tool timeout — the env process' connection to the namespace host is +# torn down for good and every later command answers "SSH command ended without +# an exit status" (measured on piscina v4, job 4f30cc06). 0.6.15 spawns through +# raw os.pipe() and survives the same abort. The version and the API this file +# and env.py depend on are asserted in the same layer. +RUN python -m venv /opt/hudvenv \ + && /opt/hudvenv/bin/pip install --no-cache-dir "hud==0.6.15" \ + && /opt/hudvenv/bin/python -c "import importlib.metadata as m, sys; \ +v = m.version('hud'); print('hud', v); sys.exit(0 if v == '0.6.15' else 1)" \ + && /opt/hudvenv/bin/python -c "from hud.environment import DEFAULT_SYSTEM_MOUNTS, Environment, Mount, Workspace; \ +from hud.environment.workspace import usable_bwrap; print('hud API ok; bwrap usable:', usable_bwrap() is not None)" +ENV PATH="/opt/hudvenv/bin:${PATH}" + +# ── Go toolchain ──────────────────────────────────────────────────────────── +RUN set -eux; \ + arch="$(dpkg --print-architecture)"; \ + curl -fsSL "https://go.dev/dl/go${GO_VERSION}.linux-${arch}.tar.gz" -o /tmp/go.tgz; \ + tar -C /usr/local -xzf /tmp/go.tgz; \ + rm /tmp/go.tgz + +# GOPATH is shared and root-owned; the agent gets read-only access to the +# module cache in step 5 and writes only to its own GOCACHE (see env.py, +# AGENT_GO_ENV). GOCACHE lives inside /hud so the warm build cache the grader +# uses cannot be touched from /workspace. +# +# GOPROXY is deliberately NOT set: the build needs the network, and every +# grading path forces GOPROXY=off itself (run_grading.sh). Setting it here +# would either break the build or, worse, survive as a live proxy setting into +# a rollout that has no network. +# +# GOWORK=off: nothing in the image ships a go.work, but the factory tree does, +# and an inherited workspace would make every `go` command fail with +# "directory not contained in workspace". +ENV PATH=/usr/local/go/bin:$PATH \ + GOTOOLCHAIN=local \ + CGO_ENABLED=1 \ + GOWORK=off \ + GOFLAGS=-mod=mod \ + GOPATH=/go \ + GOMODCACHE=/go/pkg/mod \ + GOCACHE=/hud/gocache + +# ENV PATH is not enough, and this is measured, not assumed. Both shells that +# matter here are LOGIN shells -- hud's BashGrader runs `/bin/bash -lc`, and an +# agent session is `env -i ... bash -l` -- and Debian's /etc/profile assigns +# PATH unconditionally, so the image's PATH is thrown away the moment either +# one starts: +# +# $ docker run --rm IMG bash -c 'echo $PATH' -> /usr/local/go/bin:... go found +# $ docker run --rm IMG bash -lc 'echo $PATH' -> /usr/local/sbin:... NO GO +# +# The grader survives it because run_grading.sh re-exports PATH itself. The +# agent would not: a rollout that cannot run `go` cannot do the task at all, +# every run would sit on the floor, and nothing in the grader would say why. +# So the toolchain goes on PATH where a login shell cannot lose it. The Go +# variables below are defaults for the dropped uid only -- env.py declares the +# same set on the workspace (AGENT_GO_ENV) and those come through `env -i` +# ahead of this file; this is the second lock on the same door, not the first. +# Nothing here is answer-key-shaped: the file is world-readable by design. +RUN set -eux; \ + printf '%s\n' \ + 'case ":$PATH:" in' \ + ' *:/usr/local/go/bin:*) ;;' \ + ' *) PATH="/usr/local/go/bin:$PATH" ;;' \ + 'esac' \ + 'export PATH' \ + 'if [ "$(id -u)" != "0" ]; then' \ + ' : "${GOPATH:=/go}"' \ + ' : "${GOMODCACHE:=/go/pkg/mod}"' \ + ' : "${GOCACHE:=$HOME/.cache/go-build}"' \ + ' : "${GOFLAGS:=-mod=mod}"' \ + ' : "${GOPROXY:=off}"' \ + ' : "${GOTOOLCHAIN:=local}"' \ + ' : "${GOWORK:=off}"' \ + ' : "${CGO_ENABLED:=1}"' \ + ' export GOPATH GOMODCACHE GOCACHE GOFLAGS GOPROXY GOTOOLCHAIN GOWORK CGO_ENABLED' \ + 'fi' \ + > /etc/profile.d/10-go-toolchain.sh; \ + chmod 0644 /etc/profile.d/10-go-toolchain.sh; \ + bash -lc 'command -v go' | grep -q '^/usr/local/go/bin/go$' + +# ── 1. substrate repo at the pinned base commit ──────────────────────────── +# History is truncated here and additionally vaulted at task setup +# (coding/repo.py). +RUN mkdir -p /workspace /hud/gocache \ + && git init -q /workspace/repo \ + && cd /workspace/repo \ + && git remote add origin ${REPO_URL} \ + && git fetch --depth 1 origin ${BASE_SHA} \ + && git checkout -q FETCH_HEAD \ + && git checkout -q -b main \ + && test "$(git rev-parse HEAD)" = "${BASE_SHA}" \ + && git config --system user.email "dev@localhost" \ + && git config --system user.name "dev" \ + && git config --system --add safe.directory /workspace/repo \ + && git remote remove origin \ + && test -z "$(git remote)" + +# ── 1b. the RH-1 door: provenance on the workspace is not a back channel ─── +# The module path in go.mod is the library's identity — every import in the +# tree reads it, so it stays. What does NOT have to stay is a pointer at the +# upstream checkout the agent is meant to reason without: the `origin` remote +# is removed above (and its absence asserted), and the CHANGELOG is stubbed to +# the base tag only, so the release notes cannot be mined for "what landed +# after this commit". Nothing in the repo, the grader or the ticket reads +# either. Egress itself is cut at the workspace (env.py: network=False), not +# with a flag an agent can unset. Verified on the base tree: no markdown file +# mentions compressed columns at all. +RUN set -eux; \ + cd /workspace/repo; \ + ! grep -riE "compressed column|column compress" --include="*.md" . ; \ + head -1 CHANGELOG.md > /tmp/changelog.head; \ + { cat /tmp/changelog.head; \ + printf '\n(Release notes for later versions are not part of this checkout.)\n'; \ + } > CHANGELOG.md; \ + rm -f /tmp/changelog.head; \ + test "$(grep -c '' CHANGELOG.md)" -le 3; \ + grep -q '^### Tag ' CHANGELOG.md; \ + git add -A; \ + git commit -q --amend --no-edit; \ + test -z "$(git status --porcelain)"; \ + test -z "$(git remote)" + +# ── 2. warm the module cache and the build cache ─────────────────────────── +# `go mod download all` covers the test dependencies too, so the offline +# rollout never reaches for the network. The -run XXXNONE pass compiles every +# test binary criterion 1 will run into GOCACHE, which is what keeps that +# criterion inside its timeout at grading time. +RUN set -eux; \ + cd /workspace/repo; \ + go mod download all; \ + go build ./...; \ + go test -count=1 -run XXXNONE \ + ./replication/... ./mysql/... ./serialization/... \ + ./compress/... ./packet/... ./utils/... >/dev/null; \ + # `go mod download all` writes the test dependencies' hashes into go.sum, so + # the worktree the agent inherits would start DIRTY (v2/v3 shipped it that + # way: `M go.sum` before the first command). Folded into the base commit + # here, so `git diff` means the agent's own work and nothing else. /hud/base + # and /hud/base_sha are taken from this state, one step below. + git add -A; \ + git commit -q --amend --no-edit; \ + test -z "$(git status --porcelain)" + +# ── 3. the pristine base checkout, kept out of the workspace ─────────────── +# /hud/base is the task's base commit; /workspace/repo is the agent's copy. +# Everything frozen below is computed from /hud/base, never from the agent's. +RUN set -eux; \ + cp -a /workspace/repo /hud/base; \ + rm -rf /hud/base/.git; \ + git -C /workspace/repo rev-parse HEAD > /hud/base_sha + +# ── 4. the capture the ticket points the agent at ────────────────────────── +# Outside /workspace/repo on purpose: it is evidence, not a file the agent is +# meant to edit, and nothing about it can land in the captured diff. It is the +# ONLY corpus file the agent can see; the other 17 stay under /hud. +# +# SOURCE OF TRUTH: task/shared/. This one fixture is the only file BOTH sides +# need -- the agent reads it at /workspace/repro, the grader keeps it beside its +# own oracles at /hud/grader/data/repro -- so it is not stored inside either +# side's tree. It lives in task/shared/repro/ and is copied OUT to both (here, +# and once more after step 6's `COPY task/grader/`). Nothing is copied out of +# the hidden grader tree into the workspace, and there is exactly one copy of +# these bytes in the build context. +COPY task/shared/repro/mariadb-11.8-minimal.binlog /workspace/repro/mariadb-11.8-minimal.binlog +RUN chmod 0755 /workspace/repro && chmod 0444 /workspace/repro/mariadb-11.8-minimal.binlog + +# ── 5. hand the workspace to the agent, and prove the agent can build ────── +# The module cache is readable but not writable from uid 1000: the grader +# compiles its own dumper against the agent's tree with GOPROXY=off, and a +# module cache the agent could rewrite would be a way to change what that +# dumper compiles. cache/lock is the one file Go opens read-write on every +# module operation, so it -- and only it -- is world-writable. +# +# The setpriv run is not a nicety, and it is not an idealised environment. hud +# does not pass the serving process's environment to a uid-dropped shell +# (Workspace._session_env builds a minimal one from scratch: PATH, HOME, TERM, +# plus the workspace env), and the shell it starts is a LOGIN shell, which +# re-assigns PATH from /etc/profile. So this step reproduces that exactly -- +# `env -i` with the same variables env.py declares, a PATH that deliberately +# does NOT contain the toolchain, uid 1000, `bash -lc`, GOPROXY=off -- and +# builds the repo, vets it and compiles the offline tests. If an agent could +# not do that offline, the image does not exist. It also warms the agent's own +# GOCACHE, the only Go directory it needs to write, and proves the published +# capture is readable from the agent side. +# +# What v4 adds to the same step, all of it inside the bwrap sandbox env.py now +# really creates (E-2/E-3, measured on piscina v4 and tarn v5): +# * HOME moves to /home/agent. DEFAULT_SYSTEM_MOUNTS lay a fresh tmpfs over +# /tmp inside the sandbox, so a HOME staged at /tmp/agent-home comes up +# EMPTY — including the pre-warmed GOCACHE. The old path is still created +# below (nothing is taken away), but the agent's HOME is a real directory. +# * /workspace and /home are 0755: env.py mounts both PARENTS, and uid 1000 +# needs `x` on the parent of its repo and of its HOME. Where a parent is +# missing bwrap invents it as `drwx------ root root` and every command dies +# with "Permission denied". +# * uid 1000 has a passwd entry, so `whoami` answers `agent`. +# * /agent-tmp (mode 1777) is what env.py binds over /tmp: under bwrap the +# tmpfs /tmp arrives 0755 owned by the sandbox root, and `go build` needs a +# writable TMPDIR. +RUN set -eux; \ + chmod -R a+rX /go; \ + [ -f /go/pkg/mod/cache/lock ] && chmod 0666 /go/pkg/mod/cache/lock || true; \ + # The one other place `go build` writes inside a read-only module cache: the + # stat cache for the MAIN module's own pseudo-version (the workspace is a + # git repo). It holds a single .info file and no dependency source, so + # opening it costs nothing and spares every rollout the line + # "go: writing stat cache: ... permission denied" on its first build + # (measured on the v4 gate, probe_v4 [build]). + mkdir -p /go/pkg/mod/cache/download/github.com/go-mysql-org; \ + chmod -R a+rwX /go/pkg/mod/cache/download/github.com/go-mysql-org; \ + groupadd -g 1000 agent; \ + useradd -u 1000 -g 1000 -M -d /home/agent -s /bin/bash agent; \ + mkdir -p /home/agent/.cache/go-build /tmp/agent-home/.cache/go-build; \ + mkdir -m 1777 -p /agent-tmp; \ + chmod 755 /workspace /home; \ + chown -R 1000:1000 /workspace/repo /home/agent /tmp/agent-home; \ + setpriv --reuid 1000 --regid 1000 --clear-groups \ + env -i PATH=/usr/local/bin:/usr/bin:/bin \ + HOME=/home/agent TERM=xterm \ + GOPATH=/go GOMODCACHE=/go/pkg/mod \ + GOCACHE=/home/agent/.cache/go-build \ + GOFLAGS=-mod=mod GOPROXY=off GOTOOLCHAIN=local GOWORK=off CGO_ENABLED=1 \ + bash -lc 'set -eux; cd /workspace/repo; go version; id -un; go build ./...; \ + go vet ./replication/... ./mysql/...; \ + go test -count=1 -run XXXNONE ./replication/... ./mysql/... >/dev/null; \ + head -c 4 /workspace/repro/mariadb-11.8-minimal.binlog >/dev/null'; \ + chown -R 1000:1000 /home/agent /tmp/agent-home; \ + test "$(stat -c %a /workspace)" = 755; \ + test "$(stat -c %a /home)" = 755; \ + test "$(stat -c %a /agent-tmp)" = 1777; \ + test "$(stat -c %U /home/agent)" = agent + +# ── 6. /hud: everything the agent must never read ────────────────────────── +COPY task/grader/ /hud/grader/ +# The shared fixture, second and last copy out of task/shared (see step 4). +# task/grader/data/repro/ ships only the oracles (*.json) and the unpublished +# wrapon capture; the published binlog arrives here from the shared source, so +# the two copies inside the image cannot drift. Mode is irrelevant on this side +# -- step 9 puts all of /hud at 700 root:root, exactly as before. +COPY task/shared/repro/mariadb-11.8-minimal.binlog /hud/grader/data/repro/mariadb-11.8-minimal.binlog +COPY task/gold.diff /hud/gold.diff +# calibrate.py reads GRADERS / FRACTIONAL / BLOCKER_CAP / PRISTINE_GREEN out of +# tasks.py by AST -- that file is the one and only place the scoreboard is +# written down -- so it has to sit in the grader tree as well as at the project +# root. This COPY is what keeps the copy hud serves and the copy calibrate.py +# reads byte-identical. +COPY tasks.py /hud/grader/tasks.py + +# Two interpreters (CLAUDE.md §12.2): PATH puts the hudvenv python first for +# build steps, while run_grading.sh re-front-loads /usr/local/bin and grades +# with the python it finds THERE. The grader's only dependency is the standard +# library, so what has to be proved is that both of them can load the harness. +# A mismatch here is invisible until it is a wrong reward, so the image refuses +# to exist. Everything below therefore runs the GRADING interpreter explicitly, +# so the calibration in step 8 is the run the platform will perform. +RUN set -eux; \ + for py in /usr/local/bin/python3 /opt/hudvenv/bin/python3; do \ + GRADER_DIR=/hud/grader PYTHONPATH=/hud/grader/lib "$py" -c \ + "import harness, json, hashlib, subprocess; print('ok', harness.GRADER)"; \ + done + +# ── 7. record what the untouched build makes of the control logs ─────────── +# The reference side of criterion 2 is the BASE build's own parse, not the +# gold's: no run is ever charged for a difference the base already had. This +# also freezes the MariaDB compressed-rows-event type names the base reports, +# the literal criterion 5 holds a candidate to. +RUN set -eux; \ + cd /hud/grader; \ + /usr/local/bin/python3 tools/record_baseline.py --base /hud/base + +# ── 8. prove the grader on the gold before anyone runs it ────────────────── +# Apply the vaulted gold diff to a scratch copy and run every criterion over +# the gold, the untouched tree, and a cosmetic no-op patch. calibrate.py +# asserts the invariants itself -- gold 1.00 with every criterion green; base +# and noop 0.00 with the two pristine-green gates green and every other +# criterion flat red, weighted or not (a zero-weight blocker still has to +# measure something); blockers no more than 0.60 of the weight and the cap no +# lower than 0.60 -- and exits non-zero if any of them breaks, so `set -e` +# fails the build. +# +# The base is graded criterion by criterion here, not short-circuited as an +# empty diff: a zero that rests on the short circuit proves nothing about the +# grader. The noop tree is the same point made with a non-empty diff -- it +# takes the FULL grading path, cosmetic change and all, and still has to score +# 0.00. An unbuildable image is better than an uncalibrated one. +# +# gold.diff carries GIT binary patch hunks (three binlog fixtures), so `git +# apply` is the only applier that can take it; `patch -p1` would silently drop +# them. git apply works outside a repository, which /hud/base is. +RUN set -eux; \ + cp -a /hud/base /tmp/goldtree; \ + cd /tmp/goldtree && git apply --verbose /hud/gold.diff; \ + cp -a /hud/base /tmp/nooptree; \ + printf '\n// (cosmetic no-op change; calibration control)\n' \ + >> /tmp/nooptree/replication/row_event.go; \ + cd /hud/grader; \ + # no `| tee`: the default shell is dash, which has no pipefail, and the + # exit code of calibrate.py is the whole point of this step + { /usr/local/bin/python3 tools/calibrate.py --base /hud/base \ + gold=/tmp/goldtree base=/hud/base noop=/tmp/nooptree \ + > /hud/grader/data/calibration.txt 2>&1 \ + || { cat /hud/grader/data/calibration.txt; exit 1; }; }; \ + cat /hud/grader/data/calibration.txt; \ + grep -q '^CALIBRATION OK' /hud/grader/data/calibration.txt; \ + grep -q '\*\*1.00\*\* | \*\*0.00\*\* | \*\*0.00\*\*' /hud/grader/data/calibration.txt; \ + rm -rf /tmp/goldtree /tmp/nooptree /hud/grader/.calib /hud/grader/__pycache__ + +# ── 9. lock it down ──────────────────────────────────────────────────────── +RUN mkdir -p /hud/vault /hud/logs \ + && chown -R root:root /hud \ + && chmod -R 700 /hud + +# Template runtime layout +ENV REPO_DIR=/workspace/repo \ + AGENT_HOME=/home/agent \ + AGENT_TMP=/agent-tmp \ + VAULT_DIR=/hud/vault \ + GRADING_LOGS_DIR=/hud/logs \ + GOLD_DIFF=/hud/gold.diff \ + GRADER_DIR=/hud/grader \ + BASE_REPO=/hud/base + +WORKDIR /app +COPY coding/ /app/coding/ +COPY env.py tasks.py /app/ +COPY task/prompt.md /app/task/prompt.md +RUN chmod 600 /app/tasks.py + +# CMD is NOT inherited: without this the container starts a bare python and +# DockerRuntime hangs on `docker port` with an unhelpful timeout. Symptom -> +# check `docker inspect --format '{{json .Config.Cmd}}'`. +CMD ["hud", "serve", "tasks.py", "--host", "0.0.0.0"] diff --git a/harbor/sources/go-mysql-v9/coding/__init__.py b/harbor/sources/go-mysql-v9/coding/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..88280a271d88bae2eb437ca5e8c172120a66f336 --- /dev/null +++ b/harbor/sources/go-mysql-v9/coding/__init__.py @@ -0,0 +1,5 @@ +"""The coding environment's core: repo-lifecycle primitives and task flavors.""" + +from . import repo, swe_bench_pro + +__all__ = ["repo", "swe_bench_pro"] diff --git a/harbor/sources/go-mysql-v9/coding/github.py b/harbor/sources/go-mysql-v9/coding/github.py new file mode 100644 index 0000000000000000000000000000000000000000..d07288e5f438181af931b88982147e86ebd1c16f --- /dev/null +++ b/harbor/sources/go-mysql-v9/coding/github.py @@ -0,0 +1,158 @@ +"""A minimal mock GitHub for SDLC tasks. + +One in-process store holds issues (seeded per task) and the pull requests and +comments the agent creates; :func:`serve` publishes it as ``github_*`` MCP +tools over an ``mcp`` capability. The remote itself is a bare git repo on +disk (see :func:`coding.repo.create_remote`) — the agent pushes branches with +plain git and references them from pull requests here. +""" + +from __future__ import annotations + +import asyncio +import json +import socket +from dataclasses import asdict, dataclass, field +from typing import Any + +from fastmcp import FastMCP +from hud.capabilities import Capability + + +@dataclass +class Issue: + number: int + title: str + body: str + labels: list[str] = field(default_factory=list) + state: str = "open" + comments: list[str] = field(default_factory=list) + + +@dataclass +class PullRequest: + number: int + title: str + body: str + head: str + base: str + state: str = "open" + comments: list[str] = field(default_factory=list) + + +class MockGitHub: + """Issue/PR store with an action log (for rubric grading).""" + + def __init__(self) -> None: + self.issues: dict[int, Issue] = {} + self.pull_requests: dict[int, PullRequest] = {} + self.actions: list[dict[str, Any]] = [] + + def seed(self, issues: list[dict[str, Any]]) -> None: + """Reset the store to the task's fixtures.""" + self.issues = { + int(entry["number"]): Issue( + number=int(entry["number"]), + title=str(entry["title"]), + body=str(entry.get("body", "")), + labels=[str(label) for label in entry.get("labels", [])], + ) + for entry in issues + } + self.pull_requests = {} + self.actions = [] + + def _record(self, action: str, **details: Any) -> None: + self.actions.append({"action": action, **details}) + + # ─── operations (the tool surface) ──────────────────────────────── + + def list_issues(self) -> list[dict[str, Any]]: + return [asdict(issue) for issue in self.issues.values()] + + def get_issue(self, number: int) -> dict[str, Any]: + return asdict(self._issue(number)) + + def close_issue(self, number: int) -> dict[str, Any]: + issue = self._issue(number) + issue.state = "closed" + self._record("close_issue", number=number) + return asdict(issue) + + def comment_on_issue(self, number: int, body: str) -> dict[str, Any]: + issue = self._issue(number) + issue.comments.append(body) + self._record("comment_on_issue", number=number, body=body) + return asdict(issue) + + def create_pull_request(self, title: str, body: str, head: str, base: str) -> dict[str, Any]: + number = len(self.pull_requests) + 1 + pr = PullRequest(number=number, title=title, body=body, head=head, base=base) + self.pull_requests[number] = pr + self._record("create_pull_request", number=number, title=title, head=head) + return asdict(pr) + + def list_pull_requests(self) -> list[dict[str, Any]]: + return [asdict(pr) for pr in self.pull_requests.values()] + + def _issue(self, number: int) -> Issue: + if number not in self.issues: + raise ValueError(f"no such issue: #{number}") + return self.issues[number] + + # ─── grading views ──────────────────────────────────────────────── + + def latest_pull_request(self) -> PullRequest | None: + return next(reversed(self.pull_requests.values()), None) + + def transcript(self) -> str: + """Everything the agent did here, for rubric judging.""" + return json.dumps( + { + "issues": [asdict(issue) for issue in self.issues.values()], + "pull_requests": [asdict(pr) for pr in self.pull_requests.values()], + "actions": self.actions, + }, + indent=2, + ) + + +def serve(github: MockGitHub) -> tuple[asyncio.Task[None], Capability]: + """Serve *github* as ``github_*`` MCP tools; returns the server task + capability.""" + server: FastMCP = FastMCP(name="github") + + @server.tool + def github_list_issues() -> list[dict[str, Any]]: + """List all issues in the repository.""" + return github.list_issues() + + @server.tool + def github_get_issue(number: int) -> dict[str, Any]: + """Get one issue by number.""" + return github.get_issue(number) + + @server.tool + def github_close_issue(number: int) -> dict[str, Any]: + """Close an issue.""" + return github.close_issue(number) + + @server.tool + def github_comment_on_issue(number: int, body: str) -> dict[str, Any]: + """Add a comment to an issue.""" + return github.comment_on_issue(number, body) + + @server.tool + def github_create_pull_request(title: str, body: str, head: str, base: str = "main") -> dict[str, Any]: + """Open a pull request from branch *head* (already pushed to the remote) into *base*.""" + return github.create_pull_request(title, body, head, base) + + @server.tool + def github_list_pull_requests() -> list[dict[str, Any]]: + """List all pull requests.""" + return github.list_pull_requests() + + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock: + sock.bind(("127.0.0.1", 0)) + port = int(sock.getsockname()[1]) + task = asyncio.create_task(server.run_async(transport="http", host="127.0.0.1", port=port, show_banner=False)) + return task, Capability.mcp(name="github", url=f"http://127.0.0.1:{port}/mcp") diff --git a/harbor/sources/go-mysql-v9/coding/repo.py b/harbor/sources/go-mysql-v9/coding/repo.py new file mode 100644 index 0000000000000000000000000000000000000000..bb675cf6f58da32de51e10bc71bdb1bc4b5057d9 --- /dev/null +++ b/harbor/sources/go-mysql-v9/coding/repo.py @@ -0,0 +1,172 @@ +"""Git-history vaulting and diff-based grading primitives. + +The repo's real ``.git`` may contain the answer key — solution branches, the +fix commit, the hidden tests. Every task flavor shares this lifecycle: + +- setup (:func:`vault_history`): snapshot the pre-agent worktree into the + real history, move ``.git`` into a vault outside the workspace, and leave a + fresh single-commit repo — git works normally for the agent, but there is + no history, no refs, and no remotes. +- grading (:func:`restore_history` → :func:`capture_agent_diff` → + :func:`reset_worktree` → :func:`apply_diff`): discard the agent's ``.git`` + (hooks and history included), restore the vaulted history, capture the + agent's changes as a diff against the setup snapshot, reset the worktree to + that snapshot, and re-apply the diff. Hidden tests come from vaulted refs + and land after the agent's diff. + +The snapshot covers the whole worktree, so installed dependencies and build +artifacts survive into grading. +""" + +from __future__ import annotations + +import asyncio +import os +import shutil +from pathlib import Path + +_GIT_ID = ("-c", "user.name=hud-grader", "-c", "user.email=grader@hud.ai") +_SETUP_COMMIT = "setup_commit" + + +async def run( + *argv: str, + cwd: Path, + timeout: float = 600.0, + check: bool = True, +) -> tuple[int, str, str]: + """Run a command, returning ``(returncode, stdout, stderr)``. Kills on timeout.""" + proc = await asyncio.create_subprocess_exec( + *argv, + cwd=str(cwd), + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + ) + try: + out_bytes, err_bytes = await asyncio.wait_for(proc.communicate(), timeout=timeout) + except TimeoutError: + proc.kill() + await proc.wait() + raise TimeoutError(f"{' '.join(argv[:4])} timed out after {timeout:.0f}s") from None + out = out_bytes.decode("utf-8", "replace") + err = err_bytes.decode("utf-8", "replace") + if check and proc.returncode != 0: + detail = (err.strip() or out.strip())[:2000] + raise RuntimeError(f"{' '.join(argv)} failed ({proc.returncode}): {detail}") + return proc.returncode if proc.returncode is not None else 1, out, err + + +async def git(repo: Path, *args: str, timeout: float = 600.0, check: bool = True) -> tuple[int, str, str]: + return await run("git", *_GIT_ID, *args, cwd=repo, timeout=timeout, check=check) + + +def _append_git_exclude(git_dir: Path) -> None: + """Keep the workspace's SSH credential dir out of snapshots and diffs.""" + exclude = git_dir / "info" / "exclude" + exclude.parent.mkdir(parents=True, exist_ok=True) + with exclude.open("a", encoding="utf-8") as fh: + fh.write("\n.hud/\n") + + +async def vault_history(repo: Path, vault: Path) -> None: + """Snapshot the pre-agent state, then hide the repo's history in *vault*.""" + if (vault / "git").exists(): + raise RuntimeError(f"vault {vault} already holds a history: one task per substrate") + + if hasattr(os, "geteuid") and os.geteuid() == 0: + # Grade-time git runs as root on the (chowned) agent-owned repo; git + # honors safe.directory only from system/global config, never from -c. + await run("git", "config", "--global", "--add", "safe.directory", str(repo), cwd=Path("/")) + + _append_git_exclude(repo / ".git") + await git(repo, "add", "-A") + await git(repo, "commit", "-q", "--allow-empty", "-m", "hud: pre-agent snapshot") + _, sha, _ = await git(repo, "rev-parse", "HEAD") + + vault.mkdir(parents=True, exist_ok=True) + (vault / _SETUP_COMMIT).write_text(sha.strip(), "utf-8") + shutil.move(str(repo / ".git"), str(vault / "git")) + + await git(repo, "init", "-q", ".") + _append_git_exclude(repo / ".git") + await git(repo, "add", "-A") + await git(repo, "commit", "-q", "--allow-empty", "-m", "baseline") + + +async def create_remote(repo: Path, remote: Path, ref: str, *, branch: str = "main") -> None: + """A bare "GitHub" remote holding *ref*'s history as *branch*. + + Pushing a single ref publishes only its ancestry — sibling answer-key + branches (hidden tests, golden fix) stay unreachable, while the agent + still gets realistic past history to work with. + """ + remote.parent.mkdir(parents=True, exist_ok=True) + await git(remote.parent, "init", "-q", "--bare", "-b", branch, str(remote)) + await git(repo, "push", "-q", str(remote), f"{ref}:refs/heads/{branch}") + + +async def attach_to_remote(repo: Path, remote: Path, *, branch: str = "main") -> None: + """Point the agent's fresh repo at the remote, sharing its (sanitized) history. + + Called after :func:`vault_history`: the throwaway single-commit repo is + replaced by the remote's clone state — same worktree, but with ``origin`` + configured and history the agent can branch from and push back to. + """ + shutil.rmtree(repo / ".git") + await git(repo, "init", "-q", "-b", branch, ".") + _append_git_exclude(repo / ".git") + await git(repo, "remote", "add", "origin", str(remote)) + await git(repo, "fetch", "-q", "origin") + # Adopt the remote's history without a checkout: the worktree already + # matches (plus untracked build artifacts a checkout would refuse to + # cross), so point the branch at origin and sync only the index. + await git(repo, "update-ref", f"refs/heads/{branch}", f"refs/remotes/origin/{branch}") + await git(repo, "reset", "-q") + await git(repo, "branch", "-q", f"--set-upstream-to=origin/{branch}", branch) + + +async def restore_history(repo: Path, vault: Path) -> str: + """Swap the agent's throwaway ``.git`` for the vaulted real history. + + Returns the setup-snapshot commit sha recorded by :func:`vault_history`. + """ + agent_git = repo / ".git" + if agent_git.exists(): + shutil.rmtree(agent_git) + shutil.move(str(vault / "git"), str(agent_git)) + return (vault / _SETUP_COMMIT).read_text("utf-8").strip() + + +async def capture_agent_diff(repo: Path, setup_commit: str) -> str: + """The agent's changes: setup snapshot -> final worktree state. + + Runs on the restored real history: the final worktree (including files the + agent added) is committed and diffed against the snapshot. + """ + await git(repo, "add", "-A") + await git(repo, "commit", "-q", "--allow-empty", "-m", "hud: final snapshot") + _, final, _ = await git(repo, "rev-parse", "HEAD") + # --binary is mandatory: without it git emits "Binary files ... differ" for + # any binary file the agent added, and `git apply` then rejects the ENTIRE + # patch — scoring a real solution 0.0. Verified end to end. + _, diff, _ = await git( + repo, "diff", "--binary", setup_commit, final.strip(), timeout=1200.0 + ) + return diff + + +async def reset_worktree(repo: Path, setup_commit: str) -> None: + await git(repo, "reset", "--hard", setup_commit) + await git(repo, "clean", "-fd") + + +async def apply_diff(repo: Path, diff: str, patch_path: Path) -> str | None: + """Apply *diff* to the worktree; returns git's error output on failure.""" + if not diff.strip(): + return None + patch_path.parent.mkdir(parents=True, exist_ok=True) + patch_path.write_text(diff, "utf-8") + code, out, err = await git(repo, "apply", "-v", str(patch_path), check=False) + if code != 0: + return (err.strip() or out.strip())[-4000:] + return None diff --git a/harbor/sources/go-mysql-v9/coding/swe_bench_pro.py b/harbor/sources/go-mysql-v9/coding/swe_bench_pro.py new file mode 100644 index 0000000000000000000000000000000000000000..da655cfc4cfaf8596fa6e18c3a47c8aad21d42d5 --- /dev/null +++ b/harbor/sources/go-mysql-v9/coding/swe_bench_pro.py @@ -0,0 +1,149 @@ +"""The SWE-bench Pro task flavor: dataset-row parsing and the official grading pipeline. + +An instance directory (baked into the instance image by ``swe_tasks.py``) +holds the dataset row (``instance.json``) plus the official per-instance +``run_script.sh`` and ``parser.py`` from scaleapi/SWE-bench_Pro-os. Grading +replays the official evaluator's entryscript on the repo-lifecycle primitives +in :mod:`coding.repo`: reset to the pre-agent snapshot, apply the (agent or +golden) patch, check out the hidden test files, run the script, parse, and +resolve iff every ``fail_to_pass`` and ``pass_to_pass`` test passes. +""" + +from __future__ import annotations + +import ast +import json +import re +import sys +from pathlib import Path +from typing import Any + +from hud.graders import EvaluationResult, SubScore + +from . import repo as repo_lib + + +def load_instance(instance_dir: Path) -> dict[str, Any]: + return json.loads((instance_dir / "instance.json").read_text("utf-8")) + + +def str_list(field: str) -> list[str]: + """Parse the dataset's list-shaped string fields. + + The rows store lists as Python reprs (single quotes; the official + evaluator uses ``eval``), so ``ast.literal_eval`` is the safe equivalent. + """ + value = ast.literal_eval(field) + if not isinstance(value, list): + raise ValueError(f"expected a list, got {type(value).__name__}") + return [str(item) for item in value] + + +def strip_binary_hunks(patch: str) -> str: + """Drop binary diff sections, exactly like the official evaluator.""" + if not patch: + return patch + sections = re.split(r"(?=^diff --git )", patch, flags=re.MULTILINE) + kept = [ + section + for section in sections + if section.strip() + and not re.search(r"^Binary files .* differ$", section, re.MULTILINE) + and not re.search(r"^GIT binary patch$", section, re.MULTILINE) + ] + return "".join(kept) + + +def score(instance: dict[str, Any], tests: list[dict[str, Any]]) -> EvaluationResult: + """The official resolution criterion: every required test passes.""" + passed = {t["name"] for t in tests if t.get("status") == "PASSED"} + fail_to_pass = set(str_list(instance["fail_to_pass"])) + pass_to_pass = set(str_list(instance["pass_to_pass"])) + required = fail_to_pass | pass_to_pass + resolved = required <= passed + + def fraction(subset: set[str]) -> float: + return len(subset & passed) / len(subset) if subset else 1.0 + + missing = sorted(required - passed) + return EvaluationResult( + reward=1.0 if resolved else 0.0, + content="resolved" if resolved else f"unresolved: {len(missing)} required test(s) not passing", + subscores=[ + SubScore(name="resolved", value=1.0 if resolved else 0.0, weight=1.0), + SubScore(name="fail_to_pass", value=fraction(fail_to_pass), weight=0.0), + SubScore(name="pass_to_pass", value=fraction(pass_to_pass), weight=0.0), + ], + info={"tests_reported": len(tests), "missing": missing[:20]}, + ) + + +def build_prompt(instance: dict[str, Any], repo_dir: Path) -> str: + sections = [ + f"You are working in {repo_dir}, a checkout of the {instance['repo']} repository. " + "Resolve the issue described below by modifying the code. Hidden tests grade your " + "work when you finish; do not modify existing tests.", + instance["problem_statement"], + ] + if instance.get("requirements"): + sections.append("## Requirements\n\n" + instance["requirements"]) + if instance.get("interface"): + sections.append("## Interface\n\n" + instance["interface"]) + return "\n\n".join(section.strip() for section in sections if section and section.strip()) + + +async def grade( + instance: dict[str, Any], + instance_dir: Path, + repo_dir: Path, + vault_dir: Path, + logs_dir: Path, + *, + validate_mode: str | None = None, + tests_timeout: float = 3600.0, +) -> EvaluationResult: + """Replay the official evaluator's entryscript in place. + + ``validate_mode="golden"`` grades the dataset's golden patch instead of + the agent's diff (the official gold-patch sanity check). The hidden test + files (the last line of ``before_repo_set_cmd``) are checked out *after* + the patch, so patch edits to them never survive. + """ + logs_dir.mkdir(parents=True, exist_ok=True) + setup_commit = await repo_lib.restore_history(repo_dir, vault_dir) + + if validate_mode == "golden": + diff = instance["patch"] + else: + diff = await repo_lib.capture_agent_diff(repo_dir, setup_commit) + diff = strip_binary_hunks(diff) + + await repo_lib.reset_worktree(repo_dir, setup_commit) + apply_error = await repo_lib.apply_diff(repo_dir, diff, logs_dir / "patch.diff") + if apply_error is not None: + return EvaluationResult(reward=0.0, content="patch failed to apply", info={"git_apply": apply_error}) + + test_checkout = instance["before_repo_set_cmd"].strip().splitlines()[-1] + await repo_lib.run("bash", "-c", test_checkout, cwd=repo_dir) + + files_csv = ",".join(str_list(instance["selected_test_files_to_run"])) + _, out, err = await repo_lib.run( + "bash", + str(instance_dir / "run_script.sh"), + files_csv, + cwd=repo_dir, + timeout=tests_timeout, + check=False, + ) + (logs_dir / "stdout.log").write_text(out, "utf-8") + (logs_dir / "stderr.log").write_text(err, "utf-8") + await repo_lib.run( + sys.executable, + str(instance_dir / "parser.py"), + "stdout.log", + "stderr.log", + "output.json", + cwd=logs_dir, + ) + tests = json.loads((logs_dir / "output.json").read_text("utf-8"))["tests"] + return score(instance, tests) diff --git a/harbor/sources/go-mysql-v9/env.py b/harbor/sources/go-mysql-v9/env.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd0b2b591516d965da190bcec367caaa502d488 --- /dev/null +++ b/harbor/sources/go-mysql-v9/env.py @@ -0,0 +1,468 @@ +"""Coding environment (HUD v6): a repo workspace with diff-based grading. + +The env publishes one ``ssh`` workspace over a git repo; the agent's harness +brings its own bash/file tools. Task setup vaults the repo's real history +(:mod:`coding.repo`) so the agent gets a fresh single-commit repo with working +git but no answer-key refs; grading captures the agent's changes as a diff, +resets to the pre-agent snapshot, re-applies, brings in the hidden tests, and +runs them. + +Three task templates: + +- ``coding-task`` — hidden tests live as refs in the repo's vaulted history + (the ``{task}_baseline`` / ``{task}_test`` / ``{task}_golden`` branch + convention) and a shell command scores by exit code. Runs locally (clones + ``REPO_URL`` per process) or from an image that bakes the repo. +- ``sdlc-task`` — adds workflow: a bare mock-GitHub remote the agent pushes + to, ``github_*`` issue/PR tools (:mod:`coding.github`), and grading over + the pushed pull-request branch instead of the worktree. +- one SWE-bench Pro instance template, registered only when an instance dir + is baked in (see ``swe_tasks.py``): grading replays the official evaluator + (:mod:`coding.swe_bench_pro`). + +Images set ``REPO_DIR``; locally everything lives in per-process temp dirs. +The image substrate here is go-mysql (Go, ~30 modules), so the agent's Go +environment is declared explicitly on the workspace — see ``AGENT_GO_ENV``. +The vault and instance assets sit outside the workspace — under ``/hud`` +(root, mode 700) in images — and agent shells drop to a non-root uid, so only +the env process can read them. +""" + +from __future__ import annotations + +import asyncio +import logging +import os +import shutil +import tempfile +from pathlib import Path +from typing import Any + +from hud.environment import DEFAULT_SYSTEM_MOUNTS, Environment, Mount, Workspace +from hud.graders import BashGrader, EvaluationResult, LLMJudgeGrader, SubScore, combine +from hud.settings import settings + +from coding import repo as repo_lib +from coding import swe_bench_pro as swe +from coding.github import MockGitHub +from coding.github import serve as serve_github + +logger = logging.getLogger(__name__) + +# ─── substrate layout ──────────────────────────────────────────────────── +# Images set REPO_DIR (and ship the repo); locally everything lives in +# per-process temp dirs and the repo is cloned from REPO_URL at startup. + +_explicit_repo = os.environ.get("REPO_DIR") +if _explicit_repo: + REPO_DIR = Path(_explicit_repo) + VAULT_DIR = Path(os.environ.get("VAULT_DIR", "/hud/vault")) + LOGS_DIR = Path(os.environ.get("GRADING_LOGS_DIR", "/hud/logs")) + _LOCAL_SUBSTRATE = False +else: + _LOCAL_ROOT = Path(tempfile.gettempdir()) / "hud-coding" + REPO_DIR = _LOCAL_ROOT / f"repo-{os.getpid()}" + VAULT_DIR = _LOCAL_ROOT / f"vault-{os.getpid()}" + LOGS_DIR = _LOCAL_ROOT / f"logs-{os.getpid()}" + _LOCAL_SUBSTRATE = True + +# The SDLC flavor's mock-GitHub remote: a bare repo the agent pushes to. It +# must be writable by the agent, so it lives outside /hud. +REMOTE_DIR = ( + Path(os.environ.get("REMOTE_DIR", "/srv/git/project.git")) + if _explicit_repo + else _LOCAL_ROOT / f"remote-{os.getpid()}" / "project.git" +) + +REPO_URL = os.environ.get("REPO_URL", "https://github.com/go-mysql-org/go-mysql") +TESTS_TIMEOUT = float(os.environ.get("GRADING_TIMEOUT", "3600")) + +INSTANCE_DIR = Path(os.environ.get("INSTANCE_DIR", "/hud/instance")) + +AGENT_UID = 1000 +# HOME must NOT live under /tmp. DEFAULT_SYSTEM_MOUNTS lay a fresh tmpfs over +# /tmp inside the bwrap sandbox, so the /tmp/agent-home the image stages (with +# its pre-warmed GOCACHE) is masked and the agent's HOME comes up empty. In +# images HOME is a real directory the image creates and owns (uid 1000); +# locally it stays a per-process temp dir. +AGENT_HOME = ( + Path(os.environ.get("AGENT_HOME", "/home/agent")) + if _explicit_repo + else _LOCAL_ROOT / f"home-{os.getpid()}" +) +# The image's writable stand-in for /tmp (mode 1777): bound over the sandbox's +# own tmpfs /tmp, which arrives 0755 owned by the sandbox root. `go build` +# writes to TMPDIR on every invocation. +AGENT_TMP = Path(os.environ.get("AGENT_TMP", "/agent-tmp")) + +env = Environment(name="ec-swe-go-mysql-mariadb-compressed-columns") + + +# The agent's Go environment, and why it is spelled out here rather than left +# to the image's ENV. +# +# When shell_uid drops privileges, hud does NOT hand the session the serving +# process's environment: Workspace._session_env() builds a minimal one from +# scratch (PATH, HOME, TERM) and layers this dict on top, precisely so a +# secret the env process holds cannot leak into the agent's shell. So every +# `ENV GO...` line in the Dockerfile reaches the grader and never the agent. +# +# That is harmless for a repo with no dependencies. go-mysql has ~30 (pingcap +# parser, klauspost/compress, zstd, testify, ...) and the rollout is offline: +# with GOPATH left at its default the agent's +# module cache would be $HOME/go — empty — and `go build ./...` would fail on +# the first import with no network to recover from. The task would be +# impossible for reasons that have nothing to do with the ticket. +# +# GOPATH points at the module cache the image pre-populated. It is root-owned +# and read-only to uid 1000 on purpose: the grader compiles its own harness +# against the agent's tree with GOPROXY=off, and a module cache the agent +# could rewrite would be a way to change what that harness compiles. GOCACHE +# is the one Go directory the agent must be able to write, so it sits in the +# agent's HOME (pre-warmed at image build). +AGENT_GO_ENV = { + "GOPATH": os.environ.get("AGENT_GOPATH", "/go"), + "GOMODCACHE": os.environ.get("AGENT_GOMODCACHE", "/go/pkg/mod"), + "GOCACHE": str(AGENT_HOME / ".cache" / "go-build"), + "TMPDIR": "/tmp", + "GOFLAGS": "-mod=mod", + "GOPROXY": "off", + "GOTOOLCHAIN": "local", + "GOWORK": "off", + "CGO_ENABLED": "1", +} +# PATH is deliberately NOT in that dict. An agent session is a LOGIN shell +# (`env -i ... bash -l`), and Debian's /etc/profile assigns PATH +# unconditionally, so anything set here would be thrown away before the first +# command runs -- measured, not assumed: `docker run IMG bash -lc 'command -v +# go'` finds nothing without the fix. The toolchain therefore goes on PATH from +# inside the image, in /etc/profile.d/10-go-toolchain.sh, where a login shell +# cannot lose it. That file also repeats the variables above as defaults, so +# the two mechanisms cover each other. + + +# shell_uid is the privilege wall: the env process (root, in images) keeps the +# vault and instance assets under /hud at mode 700; the uid-dropped agent can +# edit the repo but never read the answer key. No-op off root (local). +# (Requires hud>=0.6.12.dev0: earlier shell_uid recursively chowned the whole +# workspace on the serving path, missing the deploy readiness probe.) +# +# network=False is the v4 door, and hud's own default. The workspace gets a +# network namespace of its own with no route out, so the agent's shell cannot +# reach deb.debian.org or raw.githubusercontent.com — where the MariaDB server +# sources that spell out the on-the-wire format of a compressed column live. +# Under v2/v3 that route was open and it was the ONE measured separator between +# a 1.0 rollout and a 0.0 one (FREEZE «v4 — офлайн-среда», forensics/v2-five). +# It is cut at the workspace, not with GOPROXY (a variable the agent can unset); +# the Go knobs above stay as a belt so a stray `go get` fails fast instead of +# hanging. Grading never needed the network: the image bakes the module cache +# and run_grading.sh forces GOPROXY=off. +# +# system_mounts, and why the defaults are not enough. network=False only bites +# where bwrap can sandbox, and this image is the first here to ship bubblewrap — +# so this is the first workspace that really runs in a bwrap namespace. In there +# the filesystem is NOT the image's: bwrap starts from a private tmpfs and +# mounts back only DEFAULT_SYSTEM_MOUNTS (/usr, /etc, the lib/bin symlinks, +# /proc, /dev, tmpfs /tmp) plus `--bind `. Any parent that is +# missing bwrap invents itself, as uid 0 in the userns under bwrap's umask -> +# `drwx------ root root`; the session is dropped to uid 1000 AROUND bwrap, so +# it has no `x` there and every command dies with "Permission denied" +# (piscina v3, job fd3f8d82, 4/5 rollouts abandoned at 0.0 — and the harness +# grades outside the sandbox as root, so live gold stayed 1.000 and the gate was +# blind to it). So both PARENTS are mounted, plus HOME itself, plus the image's +# 1777 /agent-tmp over the sandbox's /tmp. System mounts are emitted BEFORE the +# repo bind, so the bind still lands on top and no path the ticket, the prompt +# or the grader names changes. +_SYSTEM_MOUNTS = ( + DEFAULT_SYSTEM_MOUNTS + if _LOCAL_SUBSTRATE + else ( + *DEFAULT_SYSTEM_MOUNTS, + Mount("rw", src=str(REPO_DIR.parent), dst=str(REPO_DIR.parent), optional=True), + Mount("rw", src=str(AGENT_HOME.parent), dst=str(AGENT_HOME.parent), optional=True), + Mount("rw", src=str(AGENT_HOME), dst=str(AGENT_HOME), optional=True), + Mount("rw", src=str(AGENT_TMP), dst="/tmp", optional=True), + # GOPATH/GOMODCACHE. Nothing outside DEFAULT_SYSTEM_MOUNTS exists inside + # the sandbox, so without this bind /go is simply absent and `go build + # ./...` dies on the first import with GOPROXY=off and no way to + # recover — the task would be impossible for reasons that have nothing + # to do with the ticket (measured on the v4 gate, probe_v4 [build]). + # The bind is rw only so Go can take its cache/lock (0666); everything + # else under /go is root-owned and read-only to uid 1000, which is what + # keeps the module cache out of reach of a candidate that would rather + # rewrite a dependency than fix the decoder. + Mount("rw", src=str(Path(AGENT_GO_ENV["GOPATH"])), dst=str(Path(AGENT_GO_ENV["GOPATH"])), optional=True), + ) +) + +_ws = Workspace( + REPO_DIR, + guest_path=str(REPO_DIR), + network=False, + system_mounts=_SYSTEM_MOUNTS, + env={"HOME": str(AGENT_HOME), **({} if _LOCAL_SUBSTRATE else AGENT_GO_ENV)}, + track_files=settings.file_tracking_enabled, + shell_uid=AGENT_UID, +) + +SDLC_TOOLS = os.environ.get("SDLC_TOOLS", "") not in ("", "0", "false") + +# RH-2: the sandbox states its own shape. This is workspace provenance, not +# ticket content — the ticket (task/prompt.md, sha 9f5474138f46) is untouched — +# and it exists so a rollout does not spend a third of its steps discovering the +# door is shut, as three v2 rollouts did with pip/apt probes. +WORKSPACE_NOTE = ( + f"Please make your changes directly in {REPO_DIR}, not in a copy or a " + "separate worktree. This sandbox is offline: no package registry, no module " + "proxy, no upstream sources — solve within the repository. The Go module " + "cache already holds every dependency this repository builds and tests with." +) + +_github = MockGitHub() +_github_server: asyncio.Task[None] | None = None + + +@env.initialize +async def _up() -> None: + global _github_server + if _LOCAL_SUBSTRATE and not (REPO_DIR / ".git").exists(): + REPO_DIR.parent.mkdir(parents=True, exist_ok=True) + logger.info("cloning %s into %s", REPO_URL, REPO_DIR) + await repo_lib.run("git", "clone", "-q", REPO_URL, str(REPO_DIR), cwd=REPO_DIR.parent) + await _ws.start() + env.add_capability(_ws.capability("shell")) + if _ws.tracks_files: + env.add_capability(_ws.file_tracking_capability()) + # The mock-GitHub tools belong to the SDLC flavor, which seeds issues and + # wants a pull request. A plain coding task never uses them, and offering + # them anyway spends agent steps on an empty issue list - every rollout so + # far called github_list_issues and github_list_pull_requests once. + if SDLC_TOOLS: + _github_server, github_capability = serve_github(_github) + env.add_capability(github_capability) + + +@env.shutdown +async def _down() -> None: + if _github_server is not None: + _github_server.cancel() + await _ws.stop() + if _LOCAL_SUBSTRATE: + for path in (REPO_DIR, VAULT_DIR, LOGS_DIR, REMOTE_DIR.parent): + shutil.rmtree(path, ignore_errors=True) + + +# ─── shared task lifecycle ─────────────────────────────────────────────── + + +async def _setup(base_ref: str | None = None, *, remote: bool = False) -> None: + """Check out the task's baseline, vault the history, hand the repo to the agent. + + With ``remote=True`` (the SDLC flavor) a bare "GitHub" remote is created + from the baseline first, and the agent's repo is attached to it as a + normal clone would be — realistic history, pushes, and branches, but no + reachable answer-key refs. + """ + if base_ref: + await repo_lib.git(REPO_DIR, "checkout", "-qf", base_ref) + if remote: + await repo_lib.create_remote(REPO_DIR, REMOTE_DIR, base_ref or "HEAD") + await repo_lib.vault_history(REPO_DIR, VAULT_DIR) + if remote: + await repo_lib.attach_to_remote(REPO_DIR, REMOTE_DIR) + if hasattr(os, "geteuid") and os.geteuid() == 0: + AGENT_HOME.mkdir(parents=True, exist_ok=True) + uid = f"{AGENT_UID}:{AGENT_UID}" + paths = [str(REPO_DIR), str(AGENT_HOME)] + ([str(REMOTE_DIR)] if remote else []) + await repo_lib.run("chown", "-R", uid, *paths, cwd=Path("/")) + if remote: + # The grader (root) pushes to and clones from the agent-owned remote. + await repo_lib.run("git", "config", "--global", "--add", "safe.directory", str(REMOTE_DIR), cwd=Path("/")) + + +# ─── generic flavor ────────────────────────────────────────────────────── + + +async def _grade_generic( + test_command: str, + base_ref: str | None, + test_ref: str | None, + test_files: list[str] | None, + golden_ref: str | None, + validate_mode: str | None, +) -> EvaluationResult: + setup_commit = await repo_lib.restore_history(REPO_DIR, VAULT_DIR) + if validate_mode == "golden": + if not (base_ref and golden_ref): + raise ValueError('validate_mode="golden" needs base_ref and golden_ref') + _, diff, _ = await repo_lib.git(REPO_DIR, "diff", base_ref, golden_ref) + else: + diff = await repo_lib.capture_agent_diff(REPO_DIR, setup_commit) + + await repo_lib.reset_worktree(REPO_DIR, setup_commit) + apply_error = await repo_lib.apply_diff(REPO_DIR, diff, LOGS_DIR / "patch.diff") + if apply_error is not None: + return EvaluationResult(reward=0.0, content="patch failed to apply", info={"git_apply": apply_error}) + if test_ref: + # Hidden tests come from the vaulted history, after the agent's diff — + # so agent edits to them never survive into grading. + await repo_lib.git(REPO_DIR, "checkout", test_ref, "--", *(test_files or ["."])) + + command = test_command.format(test_files=" ".join(test_files or [])) + return await combine( + BashGrader.grade(weight=1.0, command=command, cwd=str(REPO_DIR), timeout_seconds=int(TESTS_TIMEOUT)) + ) + + +@env.template(id="coding-task", description="Fix a bug in the repo; hidden tests grade the diff.") +async def coding_task( + description: str, + test_command: str, + base_ref: str | None = None, + test_ref: str | None = None, + test_files: list[str] | None = None, + golden_ref: str | None = None, + validate_mode: str | None = None, +): + """Generic coding task. + + ``base_ref`` is the agent's starting state; ``test_ref`` holds the hidden + tests (``test_files`` are checked out from it at grade time); + ``test_command`` scores by exit code, with ``{test_files}`` expanded. + ``validate_mode="golden"`` grades ``base_ref..golden_ref`` instead of + agent edits. + """ + if validate_mode not in (None, "golden"): + raise ValueError(f"unknown validate_mode: {validate_mode!r}") + await _setup(base_ref) + _ = yield ( + f"You are working in a coding repository located at {REPO_DIR}. {WORKSPACE_NOTE}\n\n" + "Use the tools provided to complete the following task. Hidden tests grade your " + f"work when you finish; do not modify existing tests.\n\n{description}" + ) + yield await _grade_generic(test_command, base_ref, test_ref, test_files, golden_ref, validate_mode) + + +# ─── SDLC flavor: issue-driven fix, graded on the pushed PR branch ─────── + + +async def _fetch_hidden_ref(dest: Path, ref: str) -> None: + """Fetch an answer-key ref from the vaulted history into *dest*.""" + full = f"refs/remotes/{ref}" if ref.startswith("origin/") else ref + await repo_lib.git(dest, "fetch", "-q", str(VAULT_DIR / "git"), full) + + +async def _grade_sdlc( + test_command: str, + test_ref: str, + test_files: list[str], + golden_ref: str | None, + pr_rubric: str | None, + validate_mode: str | None, +) -> EvaluationResult: + if validate_mode == "golden": + # Simulate the workflow the agent is graded on: push the reference + # fix as a branch and open a pull request for it. + if not golden_ref: + raise ValueError('validate_mode="golden" needs golden_ref') + await repo_lib.git(VAULT_DIR / "git", "push", "-q", str(REMOTE_DIR), f"{golden_ref}:refs/heads/golden-fix") + _github.create_pull_request( + "Fix the reported bug", "Applies the reference fix.", head="golden-fix", base="main" + ) + + pr = _github.latest_pull_request() + if pr is None: + return EvaluationResult(reward=0.0, content="no pull request was opened") + + # Hermetic checkout of the PR head from the remote (never the worktree). + grading_dir = LOGS_DIR / "pr-checkout" + shutil.rmtree(grading_dir, ignore_errors=True) + LOGS_DIR.mkdir(parents=True, exist_ok=True) + await repo_lib.run("git", "clone", "-q", str(REMOTE_DIR), str(grading_dir), cwd=LOGS_DIR) + code, _, err = await repo_lib.git(grading_dir, "checkout", "-q", pr.head, check=False) + if code != 0: + return EvaluationResult( + reward=0.0, + content=f"pull request head branch {pr.head!r} was never pushed", + info={"git_checkout": err.strip()[-2000:]}, + ) + + await _fetch_hidden_ref(grading_dir, test_ref) + await repo_lib.git(grading_dir, "checkout", "FETCH_HEAD", "--", *test_files) + + command = test_command.format(test_files=" ".join(test_files)) + quality: Any + if pr_rubric: + quality = LLMJudgeGrader.grade(weight=0.2, answer=_github.transcript(), criteria=[pr_rubric]) + else: + opened_well = bool(pr.title.strip() and pr.body.strip()) + quality = SubScore(name="pull_request", value=1.0 if opened_well else 0.0, weight=0.2) + return await combine( + BashGrader.grade(weight=0.8, command=command, cwd=str(grading_dir), timeout_seconds=int(TESTS_TIMEOUT)), + quality, + ) + + +@env.template( + id="sdlc-task", + description="Issue-driven bug fix: fix the code, push a branch, open a pull request.", +) +async def sdlc_task( + description: str, + test_command: str, + base_ref: str, + test_ref: str, + test_files: list[str], + issues: list[dict[str, Any]] | None = None, + golden_ref: str | None = None, + pr_rubric: str | None = None, + validate_mode: str | None = None, +): + """The generic flavor plus workflow: the repo has an ``origin`` remote (a + bare mock-GitHub repo) and ``github_*`` tools seeded with *issues*; the + deliverable is a pushed branch with a pull request. Grading checks the PR + head out of the remote, brings in the hidden tests, runs ``test_command`` + (weight 0.8), and scores the PR itself (weight 0.2) — structurally, or + against ``pr_rubric`` with an LLM judge when provided. + """ + if validate_mode not in (None, "golden"): + raise ValueError(f"unknown validate_mode: {validate_mode!r}") + _github.seed(issues or []) + await _setup(base_ref, remote=True) + _ = yield ( + f"You are working in a coding repository located at {REPO_DIR}; its `origin` remote " + "is the team's shared repository, and the `github_*` tools give you the team's " + "issue tracker.\n\n" + "Complete the following task. When you are done, push your work to `origin` as a " + "new branch and open a pull request for it with `github_create_pull_request`. " + "Hidden tests grade your work; do not modify existing tests.\n\n" + f"{description}" + ) + yield await _grade_sdlc(test_command, test_ref, test_files, golden_ref, pr_rubric, validate_mode) + + +# ─── SWE-bench Pro flavor (present only in baked instance images) ──────── + +if (INSTANCE_DIR / "instance.json").is_file(): + INSTANCE = swe.load_instance(INSTANCE_DIR) + + @env.template( + id=INSTANCE["instance_id"], + description=f"SWE-bench Pro instance on {INSTANCE['repo']}", + ) + async def swe_bench_pro_task(validate_mode: str | None = None): + """One SWE-bench Pro rollout. ``validate_mode="golden"`` grades the + dataset's golden patch instead of agent edits (gold-patch validation).""" + if validate_mode not in (None, "golden"): + raise ValueError(f"unknown validate_mode: {validate_mode!r}") + await _setup() + _ = yield swe.build_prompt(INSTANCE, REPO_DIR) + yield await swe.grade( + INSTANCE, + INSTANCE_DIR, + REPO_DIR, + VAULT_DIR, + LOGS_DIR, + validate_mode=validate_mode, + tests_timeout=TESTS_TIMEOUT, + ) diff --git a/harbor/sources/go-mysql-v9/pyproject.toml b/harbor/sources/go-mysql-v9/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..fdc6806c9464ef513d2c3587cb4e65d4fdb88331 --- /dev/null +++ b/harbor/sources/go-mysql-v9/pyproject.toml @@ -0,0 +1,31 @@ +[project] +name = "swe-task-go-mysql-mariadb-compressed-columns" +version = "0.1.0" +description = "go_mysql_mariadb_compressed_columns on the coding-template: per-criterion execution grading" +requires-python = ">=3.11,<3.13" +dependencies = [ "hud>=0.6.13", "httpx>=0.27.0",] + +[build-system] +requires = [ "hatchling",] +build-backend = "hatchling.build" + +[project.optional-dependencies] +dev = [ "pytest>=8.0.0", "ruff==0.11.2",] + +[tool.ruff] +target-version = "py311" +line-length = 120 + +[tool.ruff.lint] +select = [ "E", "F", "B", "I", "C4", "UP",] +ignore = [ "E501",] +fixable = [ "ALL",] +unfixable = [] + +[tool.ruff.format] +quote-style = "double" +indent-style = "space" +line-ending = "auto" + +[tool.hatch.build.targets.wheel] +packages = [ ".",] diff --git a/harbor/sources/go-mysql-v9/task/gold.diff b/harbor/sources/go-mysql-v9/task/gold.diff new file mode 100644 index 0000000000000000000000000000000000000000..12a2da072f688318f4f9ad59630959475d3f4d61 --- /dev/null +++ b/harbor/sources/go-mysql-v9/task/gold.diff @@ -0,0 +1,747 @@ +diff --git a/mysql/const.go b/mysql/const.go +index a602ab3..619626e 100644 +--- a/mysql/const.go ++++ b/mysql/const.go +@@ -199,6 +199,16 @@ const ( + MYSQL_TYPE_GEOMETRY + ) + ++// MariaDB-only column types, emitted in row-based binlog events for columns ++// that use storage-engine-independent column compression (MariaDB 10.3+, ++// e.g. VARCHAR(...) COMPRESSED). See include/mysql_com.h in the MariaDB ++// sources: "Compressed types are only used internally for RBR". Note the ++// BLOB code is the lower one, the reverse of the base enum's order. ++const ( ++ MYSQL_TYPE_BLOB_COMPRESSED byte = 140 ++ MYSQL_TYPE_VARCHAR_COMPRESSED byte = 141 ++) ++ + const ( + NOT_NULL_FLAG = 1 + PRI_KEY_FLAG = 2 +diff --git a/mysql/util.go b/mysql/util.go +index ccbdcce..3fc39c8 100644 +--- a/mysql/util.go ++++ b/mysql/util.go +@@ -3,6 +3,7 @@ package mysql + import ( + "bytes" + "cmp" ++ "compress/flate" + "compress/zlib" + "crypto/rand" + "crypto/rsa" +@@ -299,6 +300,68 @@ func DecompressMariadbData(data []byte) ([]byte, error) { + return uncompressedData, nil + } + ++// DecompressMariadbColumn decodes the binlog value of a column that uses ++// MariaDB storage-engine-independent column compression ++// (MYSQL_TYPE_VARCHAR_COMPRESSED / MYSQL_TYPE_BLOB_COMPRESSED). data is the ++// column value with its VARCHAR/BLOB length prefix already stripped. The ++// layout, from mariadb sql/field_comp.cc, is: ++// ++// byte 0: bits 0-2: how many bytes the original data length takes ++// bit 3: set when the deflate stream carries no zlib ++// wrapper (column_compression_zlib_wrap=OFF, which ++// is the server default) ++// bits 4-7: compression method: 0 = stored uncompressed, ++// 8 = zlib ++// bytes 1..n: original data length, big endian ++// rest: compressed data ++// ++// Values shorter than column_compression_threshold, and values that did not ++// shrink when compressed, are stored uncompressed under method 0 with just ++// the header byte. Empty values are stored with no header at all. ++// ++// This is not interchangeable with DecompressMariadbData: that helper decodes ++// the payload of mariadb *_COMPRESSED_EVENT_V1 events, which the server ++// always writes zlib-wrapped, while column values honor the wrapper bit and ++// on default settings are raw deflate streams. ++func DecompressMariadbColumn(data []byte) ([]byte, error) { ++ if len(data) == 0 { ++ return data, nil ++ } ++ ++ switch method := (data[0] & 0xF0) >> 4; method { ++ case 0: ++ // Stored uncompressed: everything after the header byte is the value. ++ return data[1:], nil ++ case 8: ++ // zlib deflate, handled below. ++ default: ++ return nil, errors.Errorf("unknown MariaDB column compression method %d", method) ++ } ++ ++ lenBytes := int(data[0] & 0x07) ++ if len(data) < 1+lenBytes { ++ return nil, errors.Errorf("MariaDB compressed column value too short: %d bytes, %d length bytes", len(data), lenBytes) ++ } ++ uncompressedDataSize := BFixedLengthInt(data[1 : 1+lenBytes]) ++ ++ var r io.ReadCloser ++ if data[0]&0x08 != 0 { ++ r = flate.NewReader(bytes.NewReader(data[1+lenBytes:])) ++ } else { ++ var err error ++ if r, err = zlib.NewReader(bytes.NewReader(data[1+lenBytes:])); err != nil { ++ return nil, errors.Trace(err) ++ } ++ } ++ defer r.Close() ++ ++ uncompressedData := make([]byte, uncompressedDataSize) ++ if _, err := io.ReadFull(r, uncompressedData); err != nil { ++ return nil, errors.Trace(err) ++ } ++ return uncompressedData, nil ++} ++ + // AppendLengthEncodedInteger: encodes a uint64 value and appends it to the given bytes slice + func AppendLengthEncodedInteger(b []byte, n uint64) []byte { + switch { +diff --git a/mysql/util_test.go b/mysql/util_test.go +index 4ae9b01..756e06d 100644 +--- a/mysql/util_test.go ++++ b/mysql/util_test.go +@@ -1,6 +1,9 @@ + package mysql + + import ( ++ "bytes" ++ "compress/flate" ++ "compress/zlib" + "testing" + "time" + +@@ -132,3 +135,84 @@ func TestToBinaryDateTime(t *testing.T) { + }) + } + } ++ ++func TestDecompressMariadbColumn(t *testing.T) { ++ payload := bytes.Repeat([]byte("compress-me-"), 40) ++ ++ rawDeflate := func(data []byte) []byte { ++ var buf bytes.Buffer ++ w, err := flate.NewWriter(&buf, flate.DefaultCompression) ++ require.NoError(t, err) ++ _, err = w.Write(data) ++ require.NoError(t, err) ++ require.NoError(t, w.Close()) ++ return buf.Bytes() ++ } ++ zlibWrapped := func(data []byte) []byte { ++ var buf bytes.Buffer ++ w := zlib.NewWriter(&buf) ++ _, err := w.Write(data) ++ require.NoError(t, err) ++ require.NoError(t, w.Close()) ++ return buf.Bytes() ++ } ++ ++ tests := []struct { ++ name string ++ data []byte ++ expect []byte ++ err bool ++ }{ ++ { ++ // Empty values are stored with no compression header at all. ++ name: "empty", ++ data: []byte{}, ++ expect: []byte{}, ++ }, ++ { ++ // Values below column_compression_threshold, and values deflate ++ // could not shrink, carry method 0: the value follows the header ++ // byte uncompressed. ++ name: "method 0 stored uncompressed", ++ data: append([]byte{0x00}, []byte("short")...), ++ expect: []byte("short"), ++ }, ++ { ++ // column_compression_zlib_wrap=OFF (the default) sets bit 3: ++ // the payload is a raw deflate stream, original length 480 is ++ // big endian over 2 bytes. ++ name: "zlib without wrapper", ++ data: append([]byte{0x8a, 0x01, 0xe0}, rawDeflate(payload)...), ++ expect: payload, ++ }, ++ { ++ // column_compression_zlib_wrap=ON clears bit 3: the payload ++ // carries the zlib header and trailer. ++ name: "zlib with wrapper", ++ data: append([]byte{0x82, 0x01, 0xe0}, zlibWrapped(payload)...), ++ expect: payload, ++ }, ++ { ++ name: "unknown compression method", ++ data: []byte{0x31, 0x01}, ++ err: true, ++ }, ++ { ++ name: "length bytes beyond value", ++ data: []byte{0x8a, 0x01}, ++ err: true, ++ }, ++ } ++ ++ for _, test := range tests { ++ t.Run(test.name, func(t *testing.T) { ++ got, err := DecompressMariadbColumn(test.data) ++ if test.err { ++ require.Error(t, err) ++ return ++ } ++ require.NoError(t, err) ++ require.Equal(t, test.expect, got) ++ }) ++ } ++} +diff --git a/replication/row_event.go b/replication/row_event.go +index f436af2..6b35980 100644 +--- a/replication/row_event.go ++++ b/replication/row_event.go +@@ -220,7 +220,10 @@ func (e *TableMapEvent) decodeMeta(data []byte) error { + pos += 2 + case mysql.MYSQL_TYPE_VAR_STRING, + mysql.MYSQL_TYPE_VARCHAR, +- mysql.MYSQL_TYPE_BIT: ++ mysql.MYSQL_TYPE_BIT, ++ // mariadb compressed columns log the same metadata as their ++ // plain counterparts: the field length for VARCHAR ... ++ mysql.MYSQL_TYPE_VARCHAR_COMPRESSED: + e.ColumnMeta[i] = binary.LittleEndian.Uint16(data[pos:]) + pos += 2 + case mysql.MYSQL_TYPE_BLOB, +@@ -228,7 +231,9 @@ func (e *TableMapEvent) decodeMeta(data []byte) error { + mysql.MYSQL_TYPE_FLOAT, + mysql.MYSQL_TYPE_GEOMETRY, + mysql.MYSQL_TYPE_VECTOR, +- mysql.MYSQL_TYPE_JSON: ++ mysql.MYSQL_TYPE_JSON, ++ // ... and the packlength for TEXT/BLOB. ++ mysql.MYSQL_TYPE_BLOB_COMPRESSED: + e.ColumnMeta[i] = uint16(data[pos]) + pos++ + case mysql.MYSQL_TYPE_TIME2, +@@ -828,6 +833,15 @@ func (e *TableMapEvent) IsCharacterColumn(i int) bool { + } + return false + ++ case mysql.MYSQL_TYPE_VARCHAR_COMPRESSED, ++ mysql.MYSQL_TYPE_BLOB_COMPRESSED: ++ // mariadb-only compressed columns keep their charset, and mariadb ++ // selects columns for the charset metadata by "the field has a ++ // charset" (is_character_field in sql/log_event_server.cc) rather ++ // than by the type list above - so compressed columns take part in ++ // DefaultCharset/ColumnCharset just like their plain counterparts. ++ return true ++ + default: + return false + } +@@ -898,6 +912,8 @@ const RowsEventStmtEndFlag = 0x01 + // - mysql.MYSQL_TYPE_JSON: []byte / *replication.JsonDiff + // - mysql.MYSQL_TYPE_GEOMETRY: []byte + // - mysql.MYSQL_TYPE_VECTOR: []byte ++// - mysql.MYSQL_TYPE_VARCHAR_COMPRESSED: string (decompressed) ++// - mysql.MYSQL_TYPE_BLOB_COMPRESSED: []byte (decompressed) + type RowsEvent struct { + // 0, 1, 2 + Version int +@@ -1441,6 +1457,22 @@ func (e *RowsEvent) decodeValue(data []byte, tp byte, meta uint16, isPartial boo + v, n = decodeString(data, length) + case mysql.MYSQL_TYPE_STRING: + v, n = decodeString(data, length) ++ case mysql.MYSQL_TYPE_VARCHAR_COMPRESSED: ++ // mariadb column compression: a regular varstring whose payload ++ // starts with a one-byte compression header. meta is the field ++ // length the server recorded - it already counts the header byte ++ // and picks the length prefix width, exactly as for VARCHAR. ++ var raw, decoded []byte ++ raw, n = decodeStringBytes(data, int(meta)) ++ if decoded, err = mysql.DecompressMariadbColumn(raw); err == nil { ++ v = utils.ByteSliceToString(decoded) ++ } ++ case mysql.MYSQL_TYPE_BLOB_COMPRESSED: ++ // Same for TEXT/BLOB ... COMPRESSED; meta is the blob packlength. ++ var raw []byte ++ if raw, n, err = decodeBlob(data, meta); err == nil { ++ v, err = mysql.DecompressMariadbColumn(raw) ++ } + case mysql.MYSQL_TYPE_JSON: + // Refer: https://github.com/shyiko/mysql-binlog-connector-java/blob/master/src/main/java/com/github/shyiko/mysql/binlog/event/deserialization/AbstractRowsEventDataDeserializer.java#L404 + length = int(mysql.FixedLengthInt(data[0:meta])) +@@ -1495,15 +1527,20 @@ func (e *RowsEvent) decodeValue(data []byte, tp byte, meta uint16, isPartial boo + } + + func decodeString(data []byte, length int) (v string, n int) { ++ b, n := decodeStringBytes(data, length) ++ return utils.ByteSliceToString(b), n ++} ++ ++func decodeStringBytes(data []byte, length int) (v []byte, n int) { + if length < 256 { + length = int(data[0]) + + n = length + 1 +- v = utils.ByteSliceToString(data[1:n]) ++ v = data[1:n] + } else { + length = int(binary.LittleEndian.Uint16(data[0:])) + n = length + 2 +- v = utils.ByteSliceToString(data[2:n]) ++ v = data[2:n] + } + + return v, n +diff --git a/replication/row_event_compressed_columns_test.go b/replication/row_event_compressed_columns_test.go +new file mode 100644 +index 0000000..3ac7a22 +--- /dev/null ++++ b/replication/row_event_compressed_columns_test.go +@@ -0,0 +1,341 @@ ++package replication ++ ++import ( ++ "encoding/hex" ++ "path" ++ "strings" ++ "testing" ++ ++ "github.com/stretchr/testify/require" ++ ++ "github.com/go-mysql-org/go-mysql/mysql" ++) ++ ++// The fixtures under testdata/ were captured from real MariaDB servers ++// (docker images mariadb:11.8 and mariadb:10.11) started with ++// --log-bin --binlog-format=ROW --binlog-row-metadata=FULL, running the SQL ++// quoted in each test below. The expected collation ids come from the same ++// server's information_schema (COLLATIONS and ++// COLLATION_CHARACTER_SET_APPLICABILITY), not from parser output. ++ ++// entropyHex is 150 fixed random bytes. deflate cannot shrink them, so even ++// though they are longer than column_compression_threshold the server falls ++// back to storing them uncompressed (compression method 0). ++const entropyHex = "2ff106625aa562c60c4471b7af0ca7883a664c0a3edb17402491586554452ab646ced028b3e6804086e1a7e4b642f8c75225e19df8d5eae9917e143a1ef23f0642944d0671cf325c365324144cd791756894a405f855f334f2dc585c4a6e3d0b9921cb3fd31d09addf213f15795e6ae95b042056429fe0b11c5fc4809c2da1161f94d42de3d71a33f89f4c2c2867bfe06dc2b21b4df7" ++ ++type binlogFixture struct { ++ // last TableMapEvent seen for each table ++ tableMaps map[string]*TableMapEvent ++ // RowsEvents per table, in binlog order ++ rows map[string][]*RowsEvent ++ // raw event types, in binlog order ++ types []EventType ++} ++ ++func parseBinlogFixture(t *testing.T, name string) *binlogFixture { ++ t.Helper() ++ ++ f := &binlogFixture{ ++ tableMaps: map[string]*TableMapEvent{}, ++ rows: map[string][]*RowsEvent{}, ++ } ++ p := NewBinlogParser() ++ p.SetFlavor("mariadb") ++ err := p.ParseFile(path.Join("testdata", name), 0, func(e *BinlogEvent) error { ++ f.types = append(f.types, e.Header.EventType) ++ switch ev := e.Event.(type) { ++ case *TableMapEvent: ++ f.tableMaps[string(ev.Table)] = ev ++ case *RowsEvent: ++ f.rows[string(ev.Table.Table)] = append(f.rows[string(ev.Table.Table)], ev) ++ } ++ return nil ++ }) ++ require.NoError(t, err) ++ return f ++} ++ ++// TestMariadbCompressedColumnsRowValues checks that columns using MariaDB ++// storage-engine-independent column compression decode to exactly the same ++// Go values as plain columns holding the same data. Fixture schema ++// (mariadb:11.8, default column compression settings): ++// ++// CREATE TABLE twin ( ++// id INT PRIMARY KEY, ++// vp VARCHAR(600) CHARACTER SET utf8mb4, ++// vc VARCHAR(600) COMPRESSED CHARACTER SET utf8mb4, ++// tp TEXT CHARACTER SET latin1, ++// tc TEXT COMPRESSED CHARACTER SET latin1, ++// bp VARBINARY(400), ++// bc VARBINARY(400) COMPRESSED ++// ); ++// ++// with every row inserting the same value into each plain/COMPRESSED pair: ++// values long enough to be deflated, values below ++// column_compression_threshold (100) that are stored uncompressed, empty ++// strings, NULLs, values of 99/100 bytes right at the threshold, random ++// bytes that deflate cannot shrink (the server stores them uncompressed ++// despite their length), and multi-byte text; followed by an UPDATE and a ++// DELETE. ++func TestMariadbCompressedColumnsRowValues(t *testing.T) { ++ entropy, err := hex.DecodeString(entropyHex) ++ require.NoError(t, err) ++ ++ longV := strings.Repeat("compress-me-", 40) ++ longT := strings.Repeat("xyz", 300) ++ binLong := strings.Repeat("\xab", 280) ++ x99 := strings.Repeat("x", 99) ++ y100 := strings.Repeat("y", 100) ++ multibyte := strings.Repeat("日本語", 80) ++ ++ f := parseBinlogFixture(t, "mariadb-11.8-compressed-columns.binlog") ++ events := f.rows["twin"] ++ require.Len(t, events, 9) // 7 inserts, 1 update, 1 delete ++ ++ inserts := [][]any{ ++ {int32(1), longV, longV, []byte(longT), []byte(longT), binLong, binLong}, ++ {int32(2), "short", "short", []byte("tiny"), []byte("tiny"), "\x01", "\x01"}, ++ {int32(3), "", "", []byte{}, []byte{}, "", ""}, ++ {int32(4), nil, nil, nil, nil, nil, nil}, ++ {int32(5), x99, x99, []byte(y100), []byte(y100), nil, nil}, ++ {int32(6), nil, nil, nil, nil, string(entropy), string(entropy)}, ++ {int32(7), multibyte, multibyte, nil, nil, nil, nil}, ++ } ++ for i, expect := range inserts { ++ ev := events[i] ++ require.Equal(t, EnumRowsEventTypeInsert, ev.Type()) ++ require.Len(t, ev.Rows, 1) ++ require.Equal(t, expect, ev.Rows[0], "insert row %d", i+1) ++ ++ // twin equivalence: a COMPRESSED column must yield exactly what the ++ // plain column holding the same data yields - same type, same bytes ++ row := ev.Rows[0] ++ require.IsType(t, row[1], row[2], "insert row %d vp/vc", i+1) ++ require.Equal(t, row[1], row[2], "insert row %d vp/vc", i+1) ++ require.IsType(t, row[3], row[4], "insert row %d tp/tc", i+1) ++ require.Equal(t, row[3], row[4], "insert row %d tp/tc", i+1) ++ require.Equal(t, row[5], row[6], "insert row %d bp/bc", i+1) ++ } ++ ++ // UPDATE twin SET vc = CONCAT(vc, '-upd'), vp = CONCAT(vp, '-upd') WHERE id = 2 ++ update := events[7] ++ require.Equal(t, EnumRowsEventTypeUpdate, update.Type()) ++ require.Len(t, update.Rows, 2) ++ require.Equal(t, inserts[1], update.Rows[0]) ++ require.Equal(t, ++ []any{int32(2), "short-upd", "short-upd", []byte("tiny"), []byte("tiny"), "\x01", "\x01"}, ++ update.Rows[1]) ++ ++ // DELETE FROM twin WHERE id = 3 ++ del := events[8] ++ require.Equal(t, EnumRowsEventTypeDelete, del.Type()) ++ require.Len(t, del.Rows, 1) ++ require.Equal(t, inserts[2], del.Rows[0]) ++} ++ ++// TestMariadbCompressedColumnsTableMapMetadata checks that a table map ++// carrying MYSQL_TYPE_VARCHAR_COMPRESSED/MYSQL_TYPE_BLOB_COMPRESSED columns ++// reports correct metadata for every column of the table: the compressed ++// columns must not desynchronize the per-column metadata stream, and they ++// take part in the charset optional metadata just like their plain ++// counterparts, so none of the optional-metadata accessors may shift. ++// Fixture schema (mariadb:11.8) on top of twin from the previous test: ++// ++// CREATE TABLE mixed ( ++// id INT UNSIGNED PRIMARY KEY, ++// a VARCHAR(50) CHARACTER SET latin1 COLLATE latin1_bin, ++// b VARCHAR(100) COMPRESSED CHARACTER SET utf8mb4 COLLATE utf8mb4_bin, ++// c TEXT COMPRESSED CHARACTER SET latin2, ++// d VARCHAR(60) CHARACTER SET ascii, ++// e ENUM('on','off') CHARACTER SET utf8mb3, ++// f SET('p','q') CHARACTER SET utf8mb3, ++// g TEXT CHARACTER SET utf8mb3 COLLATE utf8mb3_bin, ++// h YEAR, ++// i BIGINT, ++// j VARCHAR(20) COMPRESSED CHARACTER SET cp1251 ++// ); ++// CREATE TABLE widths ( ++// id INT PRIMARY KEY, ++// v254 VARCHAR(254) COMPRESSED CHARACTER SET latin1, ++// v255 VARCHAR(255) COMPRESSED CHARACTER SET latin1, ++// tt TINYTEXT COMPRESSED CHARACTER SET latin1, ++// mt MEDIUMTEXT COMPRESSED CHARACTER SET latin1, ++// lt LONGTEXT COMPRESSED CHARACTER SET latin1, ++// bb BLOB COMPRESSED ++// ); ++func TestMariadbCompressedColumnsTableMapMetadata(t *testing.T) { ++ f := parseBinlogFixture(t, "mariadb-11.8-compressed-columns.binlog") ++ ++ twin := f.tableMaps["twin"] ++ require.NotNil(t, twin) ++ require.Equal(t, []byte{ ++ mysql.MYSQL_TYPE_LONG, ++ mysql.MYSQL_TYPE_VARCHAR, ++ mysql.MYSQL_TYPE_VARCHAR_COMPRESSED, ++ mysql.MYSQL_TYPE_BLOB, ++ mysql.MYSQL_TYPE_BLOB_COMPRESSED, ++ mysql.MYSQL_TYPE_VARCHAR, // VARBINARY ++ mysql.MYSQL_TYPE_VARCHAR_COMPRESSED, // VARBINARY COMPRESSED ++ }, twin.ColumnType) ++ // A compressed VARCHAR logs the internal field length, one byte larger ++ // than its plain twin (the byte reserved for the compression header); ++ // a compressed TEXT/BLOB logs the same packlength as its twin. ++ require.Equal(t, []uint16{0, 2400, 2401, 2, 2, 400, 401}, twin.ColumnMeta) ++ // 2304 = utf8mb4_uca1400_ai_ci, 8 = latin1_swedish_ci, 63 = binary ++ require.Equal(t, map[int]uint64{1: 2304, 2: 2304, 3: 8, 4: 8, 5: 63, 6: 63}, ++ twin.CollationMap()) ++ ++ mixed := f.tableMaps["mixed"] ++ require.NotNil(t, mixed) ++ require.Equal(t, []byte{ ++ mysql.MYSQL_TYPE_LONG, ++ mysql.MYSQL_TYPE_VARCHAR, ++ mysql.MYSQL_TYPE_VARCHAR_COMPRESSED, ++ mysql.MYSQL_TYPE_BLOB_COMPRESSED, ++ mysql.MYSQL_TYPE_VARCHAR, ++ mysql.MYSQL_TYPE_STRING, // ENUM ++ mysql.MYSQL_TYPE_STRING, // SET ++ mysql.MYSQL_TYPE_BLOB, ++ mysql.MYSQL_TYPE_YEAR, ++ mysql.MYSQL_TYPE_LONGLONG, ++ mysql.MYSQL_TYPE_VARCHAR_COMPRESSED, ++ }, mixed.ColumnType) ++ require.Equal(t, []uint16{0, 50, 401, 2, 60, 0xf701, 0xf801, 2, 0, 0, 21}, ++ mixed.ColumnMeta) ++ // Collation ids from the server's information_schema: ++ // 47 latin1_bin, 46 utf8mb4_bin, 9 latin2_general_ci, ++ // 11 ascii_general_ci, 83 utf8mb3_bin, 51 cp1251_general_ci, ++ // 2048 utf8mb3_uca1400_ai_ci ++ require.Equal(t, map[int]uint64{1: 47, 2: 46, 3: 9, 4: 11, 7: 83, 10: 51}, ++ mixed.CollationMap()) ++ require.Equal(t, map[int]uint64{5: 2048, 6: 2048}, mixed.EnumSetCollationMap()) ++ require.Equal(t, map[int][]string{5: {"on", "off"}}, mixed.EnumStrValueMap()) ++ require.Equal(t, map[int][]string{6: {"p", "q"}}, mixed.SetStrValueMap()) ++ require.Equal(t, map[int]bool{0: true, 8: true, 9: false}, mixed.UnsignedMap()) ++ ++ widths := f.tableMaps["widths"] ++ require.NotNil(t, widths) ++ // v254 logs field length 255 (one length-prefix byte on the wire), ++ // v255 logs 256 (two bytes); TINYTEXT/TEXT-as-BLOB/MEDIUMTEXT/LONGTEXT ++ // log their packlength 1/2/3/4. ++ require.Equal(t, []uint16{0, 255, 256, 1, 3, 4, 2}, widths.ColumnMeta) ++ // All columns of this table share one collation except the last, so the ++ // server wrote the DEFAULT_CHARSET form of the optional metadata; the ++ // (column, collation) override pair must land on the last column, which ++ // it can only do if the compressed columns are counted as character ++ // columns. ++ require.NotEmpty(t, widths.DefaultCharset) ++ require.Equal(t, map[int]uint64{1: 8, 2: 8, 3: 8, 4: 8, 5: 8, 6: 63}, ++ widths.CollationMap()) ++} ++ ++// TestMariadbCompressedColumnsLengthWidths decodes the rows of the widths ++// table (schema in the previous test): compressed values whose original ++// lengths need one, two and three big-endian header length bytes, plus the ++// VARCHAR(254)/VARCHAR(255) boundary where the internal field length (+1 for ++// the compression header) pushes the wire length prefix from one byte to two. ++func TestMariadbCompressedColumnsLengthWidths(t *testing.T) { ++ f := parseBinlogFixture(t, "mariadb-11.8-compressed-columns.binlog") ++ events := f.rows["widths"] ++ require.Len(t, events, 1) ++ require.Equal(t, []any{ ++ int32(1), ++ strings.Repeat("a", 254), ++ strings.Repeat("b", 255), ++ []byte(strings.Repeat("c", 200)), ++ []byte(strings.Repeat("d", 70000)), ++ []byte(strings.Repeat("e", 70000)), ++ []byte(strings.Repeat("f", 600)), ++ }, events[0].Rows[0]) ++} ++ ++// TestMariadbCompressedColumnsZlibWrap decodes rows written by a session ++// running with column_compression_zlib_wrap=ON: the deflate stream then ++// carries the zlib header and trailer, flagged in the value's compression ++// header byte. The twin/widths tables in the same fixture cover the OFF ++// (default) form, so both wrappings must decode. Fixture schema ++// (mariadb:11.8): ++// ++// CREATE TABLE wrapt ( ++// id INT PRIMARY KEY, ++// vc VARCHAR(600) COMPRESSED CHARACTER SET utf8mb4, ++// tc TEXT COMPRESSED CHARACTER SET latin1 ++// ); ++// SET SESSION column_compression_zlib_wrap=ON; ++// INSERT INTO wrapt VALUES (1, REPEAT('compress-me-',40), REPEAT('xyz',300)); ++// INSERT INTO wrapt VALUES (2, 'short', 'tiny'); ++func TestMariadbCompressedColumnsZlibWrap(t *testing.T) { ++ f := parseBinlogFixture(t, "mariadb-11.8-compressed-columns.binlog") ++ events := f.rows["wrapt"] ++ require.Len(t, events, 2) ++ require.Equal(t, ++ []any{int32(1), strings.Repeat("compress-me-", 40), []byte(strings.Repeat("xyz", 300))}, ++ events[0].Rows[0]) ++ require.Equal(t, []any{int32(2), "short", []byte("tiny")}, events[1].Rows[0]) ++} ++ ++// TestMariadbCompressedColumnsInsideCompressedEvents parses a binlog written ++// with log_bin_compress=ON: the rows events themselves arrive as mariadb ++// *_COMPRESSED_EVENT_V1 (zlib-wrapped whole-event payload), and the columns ++// inside them use column compression on top. Both layers must decode, and ++// the existing event-level decompression must not be disturbed. Fixture ++// schema (mariadb:11.8): ++// ++// CREATE TABLE nested ( ++// id INT PRIMARY KEY, ++// vc VARCHAR(600) COMPRESSED CHARACTER SET utf8mb4, ++// tc TEXT COMPRESSED CHARACTER SET latin1 ++// ); ++// SET GLOBAL log_bin_compress=ON; ++// SET GLOBAL log_bin_compress_min_len=10; ++// INSERT INTO nested VALUES (1, REPEAT('compress-me-',40), REPEAT('xyz',300)); ++// INSERT INTO nested VALUES (2, 'short', 'tiny'); ++func TestMariadbCompressedColumnsInsideCompressedEvents(t *testing.T) { ++ f := parseBinlogFixture(t, "mariadb-11.8-compressed-columns-log-bin-compress.binlog") ++ ++ require.Contains(t, f.types, MARIADB_WRITE_ROWS_COMPRESSED_EVENT_V1) ++ ++ events := f.rows["nested"] ++ require.Len(t, events, 2) ++ require.Equal(t, ++ []any{int32(1), strings.Repeat("compress-me-", 40), []byte(strings.Repeat("xyz", 300))}, ++ events[0].Rows[0]) ++ require.Equal(t, []any{int32(2), "short", "tiny"}, []any{ ++ events[1].Rows[0][0], events[1].Rows[0][1], string(events[1].Rows[0][2].([]byte)), ++ }) ++} ++ ++// TestMariadbCompressedColumnsMariadb1011 parses the same kind of capture ++// taken from mariadb:10.11, whose default collations differ from 11.8 ++// (pre-uca1400 ids). Fixture schema: ++// ++// CREATE TABLE mixed ( ++// id INT PRIMARY KEY, ++// a VARCHAR(50) CHARACTER SET latin1 COLLATE latin1_bin, ++// b VARCHAR(100) COMPRESSED CHARACTER SET utf8mb4 COLLATE utf8mb4_bin, ++// c TEXT COMPRESSED CHARACTER SET latin2, ++// d VARCHAR(60) CHARACTER SET ascii, ++// e TEXT CHARACTER SET utf8mb3 COLLATE utf8mb3_bin, ++// f VARCHAR(20) CHARACTER SET cp1251 ++// ); ++// INSERT INTO mixed VALUES (1, 'aaa', REPEAT('payload-',9), REPEAT('xyz',300), 'dddd', 'eeee', 'fff'); ++// INSERT INTO mixed VALUES (2, 'b', 's', 't', 'z', 'w', 'q'); ++func TestMariadbCompressedColumnsMariadb1011(t *testing.T) { ++ f := parseBinlogFixture(t, "mariadb-10.11-compressed-columns.binlog") ++ ++ mixed := f.tableMaps["mixed"] ++ require.NotNil(t, mixed) ++ require.Equal(t, []uint16{0, 50, 401, 2, 60, 2, 20}, mixed.ColumnMeta) ++ require.Equal(t, map[int]uint64{1: 47, 2: 46, 3: 9, 4: 11, 5: 83, 6: 51}, ++ mixed.CollationMap()) ++ ++ events := f.rows["mixed"] ++ require.Len(t, events, 2) ++ require.Equal(t, []any{ ++ int32(1), "aaa", strings.Repeat("payload-", 9), ++ []byte(strings.Repeat("xyz", 300)), "dddd", []byte("eeee"), "fff", ++ }, events[0].Rows[0]) ++ require.Equal(t, []any{ ++ int32(2), "b", "s", []byte("t"), "z", []byte("w"), "q", ++ }, events[1].Rows[0]) ++} +diff --git a/replication/testdata/mariadb-10.11-compressed-columns.binlog b/replication/testdata/mariadb-10.11-compressed-columns.binlog +new file mode 100644 +index 0000000000000000000000000000000000000000..24bf4aa16651aec71e5f66e77cd9c36533871668 +GIT binary patch +literal 1115 +zcmcIjO=uHQ5T3WY+I5?-wFxMqxOi|AyPNK&Vl8-S=^_hSYZ67!%WgN(NNP=!(k6#i +z(Ua)GOTD%Rq^LKq#gl@dcoP(a9{i(-;Gy897H8g?NGzVzfp6ZtH}mGr%(uJY7cbS9 +z?_5+F0IVZ`43NOKQnsD42h8K%WYHTQGN=5hblN&-mL|?q#Acy1vBOc2p&KNWZh-e7 +z?UFH4mSq7KMNz_QEn{<*|9m3FB#2@;SONRGwD6XSZcxj62)y^Og5JjD3ON_)%s{x@ +zxgD+XTBTeHOq^WGBC)@}`S6Zn?^4JCLgpIpE>L70@r7q~N3u>P +zr@14!6WVxjCLd_02ala{vRcA6G~M$&-Ow`5s56*L=$E}(X~GLk-55yzI-RN2b)(O+ +z@JJ6(@PeL4p|wyb=*buH$TfO7Mh~7txWoujMZ$npVGDm5Iz;u>O?6#W(r}vzM?i?f +zEMp*U?M-d#%=SsDPz;#Id^W}cmS+W-!Q#uOhbZ?B$~})*Y0KR)cZD1x_Td6F>;K!e +z3vP(lA1pn*ztd@4h(~t|AW`EIP}?H*{OQ^JW2&l)9^Z@D;8k^^MPj`^x<>96X$g@? +z<1t}GleB%AGn`&d+DY`)FcJs&N7B+bbe|?)Ayp-X>}dKlsj{AYbZ?Heaq)^L{3l$j +z?e7_CanX-uMkFe>nH#yF4w;X-f~c}OgK1VC?T6L2VfFB9KR;XeIJ`VdZi!}TAe5{mE5FI6#sML1H>U>1hR4~iwkp7bb%qKX8;0*ccsNW +zL24I)lxP8QF_6Il2}vLi1b76vLDYh+cE3R?7l2eIfkeQ-(=XUHC`7^2FT`IVFSWQN +zHANxJ(I?b3SV6;3MH;MYRpLBfmGoVTK0>6OIfcZlGa=d_>%%Iq1uA91B%eR#yCn_DgT$e5Gyf;chY* +z!~qGI5C8T~1cly-pF9>H`t9-g^^TW0WbVMWLU?9T=1_R6Yj19>HHrYaVjfBO`WRaMXN#9C|WJqt=J +z=7;BbCJKd~x#3&FrPUL?dP7~bDbn0rR2M1o7D~MDvshUk`*&^a9o|AepW6S*rZ%st +zc?-p0O0Q&-Z}HT(-$AK|qtp>gW&+EM#1JM%+$c54aOJGMuqJ11)@_+;Cd)p=tYhwC +z7~;yhKr-PU$CZ@0^Vk}LZHcliIvb0!F`d<-tfq4exxVAZjX23Doa9dwEgU{ENygos +z$mnKLaTs`y>%%t*hmmA8(_Mb#wW5i$i;CZRwero%agm%U3c1$>YCG_60D%Dn{*MUc +zlGUzz_x*7H6Zzqt%SQ|@U`al+Z-9D5APX#6{^I95M%?Bio*C-}Jl%5f5W5k&rzt^}2XS(+F9&;44?;^YNuM5sSm^OKFK=jyc~f6vHTCV- +zVAXA2UVuMoQrq=29WRFl`$KrrZ66-Cl{)gLi5At3Rh +z6cXg1BFmB_i>jtbiXJg|F{t??N|2ZMpb`<(KtuwLXa@CwEQ)eO2pMM3kRxg&6cPdv +zLGr6Y#1#D|54}Q?WbjHr&`rN6>wZP{i;^Hox)FfBvJwnQs>I7?P?k-Qayo>7tvTl5L)bt7K7DlSWlb*fl$m#t!Mr} +zq%-d=Tr#_U+Mq|r|EA;*V>6$8e|$+^`_dIB7P~zQW^C*JX~D9WJ2w~Y7W=OB&^B1xZGN8yD`20W%T~tBV4Ws;__nYT3Y5xF&Mci74wjaN!iApHK-cH# +znmkieO`@;y;r~SYS4neiuP%AM_8@Yvv&T2>KE8SXU!K@H@G=0xH$W305XioMhjQnM +zr$gUcy8p4WwHt(A=by_a$AA9JdWUs+D<3TbH8D`H=k!tI)b&8X`fKb-DFa +zQ_>v**U_T+x0IDuhvRYhdEshLi|(1`nK`FwCPd*|bhz;qt&AF8aLrqyDU7Ji@Z5TH +zcy8EJV*ppIIK9WyZx$jSPq2=}ccg^Q@9zAZw`tlhGk)8~&xE@)y?Nt%Z@2H<4-YVo +zwa`Z6^m&#HXBzLj+OZaEfXxva`mnlKYjJeauw&ShhBYLMM@U(?A`EMB)7&|g@dZi2 +z)<1ed-sFD6_A10yv;|9A-%i^iTg(Y}%-QF_q-6|pMq2D+1*`lHOtu4?BQ$DZb+Irx +zy!79DY)sZ!JV->PB#Y{5+9F13w#cihDtMcTq)}9DuWe8bNEkWplF5{i*8sv0MngT8 +z(ZWWoB0x}!ya)-XBDj@$P1E%H&I>)jN^{xifge=k0y2of7jb@20GlHam$J!HfENp%G;9ShZEoKR +zfWbb<<3Yp^3mWo+lfXI>2diWA-i_%8X)cxUDS +zWHuIK>tbwejMX&QWs}c(=?rw24YKb=i5aY1EZ23hyrSS&h+@~J^4X(*2X9@!EUy{| +zxG#bTH#0PP`k;WnKD7P7sci>`ZJllpWlR0VUm9F6xO4PpPA&WLM$ZPnV_|vun6#ap +z=LmV}+Sfu3ttuOjB7;vsX<6FTEe@@!2R27&ywK{BolBMUp`+)sY^_o)-ep?Vq()=C +zDOGBI_p;nS