Datasets:
Tasks:
Text Generation
Formats:
parquet
Sub-tasks:
language-modeling
Languages:
English
Size:
< 1K
License:
Update dataset (part 2)
Browse files- README.md +1 -1
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/Dockerfile +24 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/capture.py +28 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/capture_submission.py +157 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/docker-compose.yaml +11 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/sanitize.py +25 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/instruction.md +7 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/solution/reference.patch +445 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/solution/solve.sh +451 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/task.toml +26 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/Dockerfile +9 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/config.json +122 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/docker-compose.yaml +6 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/evidence.py +123 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/test.sh +3 -0
- harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/verify.py +235 -0
- harbor/tasks/manifest.json +1 -0
README.md
CHANGED
|
@@ -297,7 +297,7 @@ empty change scores 0, and the reference fix scores 1.0 with every criterion
|
|
| 297 |
equal to the task's original grading. The folder contains the reference fixes
|
| 298 |
and the hidden graders, as the rows of this dataset do.
|
| 299 |
|
| 300 |
-
|
| 301 |
as each one passes.
|
| 302 |
|
| 303 |
Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
|
|
|
|
| 297 |
equal to the task's original grading. The folder contains the reference fixes
|
| 298 |
and the hidden graders, as the rows of this dataset do.
|
| 299 |
|
| 300 |
+
8 more (badger, geode, kratos, open-xml-sdk, openfire, terser, umya, zettlr) are packaged and are being re-checked; they are added
|
| 301 |
as each one passes.
|
| 302 |
|
| 303 |
Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/Dockerfile
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-bazel-remote:source-v2 AS sanitized
|
| 2 |
+
USER root
|
| 3 |
+
COPY sanitize.py capture.py capture_submission.py /opt/task-tools/
|
| 4 |
+
RUN HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 /opt/hudvenv/bin/python /opt/task-tools/sanitize.py
|
| 5 |
+
FROM scratch
|
| 6 |
+
COPY --from=sanitized / /
|
| 7 |
+
ENV PATH="/usr/local/go/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
|
| 8 |
+
ENV LANG="C.UTF-8"
|
| 9 |
+
ENV GOTOOLCHAIN="local"
|
| 10 |
+
ENV CGO_ENABLED="1"
|
| 11 |
+
ENV GOWORK="off"
|
| 12 |
+
ENV GOFLAGS="-mod=mod"
|
| 13 |
+
ENV GOPATH="/go"
|
| 14 |
+
ENV GOMODCACHE="/go/pkg/mod"
|
| 15 |
+
ENV GOMEMLIMIT="1GiB"
|
| 16 |
+
ENV GOPROXY="off"
|
| 17 |
+
ENV GOMAXPROCS="2"
|
| 18 |
+
ENV HOME="/tmp/agent-home"
|
| 19 |
+
ENV GOCACHE="/tmp/agent-home/.cache/go-build"
|
| 20 |
+
ENV HUD_TELEMETRY_ENABLED="false"
|
| 21 |
+
ENV HUD_CLI_ANALYTICS_ENABLED="0"
|
| 22 |
+
WORKDIR /workspace/repo
|
| 23 |
+
USER 1000:1000
|
| 24 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/capture.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Capture a patch against protected baseline history inside the agent sandbox."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
import tempfile
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
sys.path.insert(0, "/opt/task-tools")
|
| 11 |
+
from capture_submission import capture_submission # noqa: E402
|
| 12 |
+
|
| 13 |
+
with tempfile.TemporaryDirectory(prefix="capture-") as directory:
|
| 14 |
+
git_dir = Path(directory) / "git"
|
| 15 |
+
shutil.copytree("/opt/task-tools/baseline.git", git_dir)
|
| 16 |
+
os.environ.update(
|
| 17 |
+
GIT_DIR=str(git_dir),
|
| 18 |
+
GIT_WORK_TREE="/workspace/repo",
|
| 19 |
+
GIT_CONFIG_NOSYSTEM="1",
|
| 20 |
+
GIT_CONFIG_GLOBAL="/dev/null",
|
| 21 |
+
)
|
| 22 |
+
print(
|
| 23 |
+
json.dumps(
|
| 24 |
+
capture_submission(
|
| 25 |
+
Path("/workspace/repo"), Path("/workspace/submissions/submitted.patch")
|
| 26 |
+
)
|
| 27 |
+
)
|
| 28 |
+
)
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/capture_submission.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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7 |
+
import shlex
|
| 8 |
+
import subprocess
|
| 9 |
+
import tempfile
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
MAX_SUBMISSION_BYTES = 32 * 1024 * 1024
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def capture_submission(
|
| 16 |
+
repository: Path, output: Path, *, max_bytes: int = MAX_SUBMISSION_BYTES
|
| 17 |
+
) -> dict[str, object]:
|
| 18 |
+
"""Write a bounded binary patch including nonignored new files.
|
| 19 |
+
|
| 20 |
+
Parameters
|
| 21 |
+
----------
|
| 22 |
+
repository : Path
|
| 23 |
+
Git checkout root. HEAD must remain the task's initial commit.
|
| 24 |
+
output : Path
|
| 25 |
+
Submission path outside the checkout. Replaces any prior submission.
|
| 26 |
+
max_bytes : int, default: 33554432
|
| 27 |
+
Maximum emitted patch size. Oversized submissions fail without a patch.
|
| 28 |
+
|
| 29 |
+
Returns
|
| 30 |
+
-------
|
| 31 |
+
dict
|
| 32 |
+
Patch size, SHA-256, base commit and capture format for trial evidence.
|
| 33 |
+
|
| 34 |
+
Raises
|
| 35 |
+
------
|
| 36 |
+
ValueError
|
| 37 |
+
If paths or the limit are invalid, or the patch exceeds the limit.
|
| 38 |
+
OSError, subprocess.CalledProcessError, RuntimeError
|
| 39 |
+
If capture fails. No partial patch is published.
|
| 40 |
+
|
| 41 |
+
Notes
|
| 42 |
+
-----
|
| 43 |
+
Uses a temporary index to combine staged, unstaged and untracked changes.
|
| 44 |
+
Ignored untracked files are excluded. This is a capture bound, not a total
|
| 45 |
+
sandbox disk quota or a security boundary against a malicious Git runtime.
|
| 46 |
+
"""
|
| 47 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 48 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 49 |
+
repository = repository.resolve(strict=True)
|
| 50 |
+
if output.is_symlink():
|
| 51 |
+
raise ValueError("Submission output must not be a symlink")
|
| 52 |
+
output = output.resolve()
|
| 53 |
+
if output.is_relative_to(repository):
|
| 54 |
+
raise ValueError("Submission output must be outside the repository")
|
| 55 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 56 |
+
output.unlink(missing_ok=True)
|
| 57 |
+
root = subprocess.check_output(
|
| 58 |
+
["git", "rev-parse", "--show-toplevel"], cwd=repository, text=True
|
| 59 |
+
).strip()
|
| 60 |
+
if Path(root).resolve() != repository:
|
| 61 |
+
raise ValueError("repository must be the Git checkout root")
|
| 62 |
+
base = subprocess.check_output(
|
| 63 |
+
["git", "rev-parse", "--verify", "HEAD^{commit}"], cwd=repository, text=True
|
| 64 |
+
).strip()
|
| 65 |
+
with tempfile.TemporaryDirectory(prefix="submission-", dir=output.parent) as directory:
|
| 66 |
+
temporary = Path(directory)
|
| 67 |
+
env = {**os.environ, "GIT_INDEX_FILE": str(temporary / "index")}
|
| 68 |
+
for arguments in (["read-tree", base], ["add", "--all", "--", "."]):
|
| 69 |
+
subprocess.run(["git", *arguments], cwd=repository, env=env, check=True)
|
| 70 |
+
patch = temporary / "patch"
|
| 71 |
+
size = 0
|
| 72 |
+
digest = hashlib.sha256()
|
| 73 |
+
with (
|
| 74 |
+
patch.open("wb") as stream,
|
| 75 |
+
tempfile.TemporaryFile() as errors,
|
| 76 |
+
subprocess.Popen(
|
| 77 |
+
[
|
| 78 |
+
"git",
|
| 79 |
+
"diff",
|
| 80 |
+
"--cached",
|
| 81 |
+
"--binary",
|
| 82 |
+
"--full-index",
|
| 83 |
+
"--no-renames",
|
| 84 |
+
"--no-ext-diff",
|
| 85 |
+
"--no-textconv",
|
| 86 |
+
"--no-color",
|
| 87 |
+
"--src-prefix=a/",
|
| 88 |
+
"--dst-prefix=b/",
|
| 89 |
+
base,
|
| 90 |
+
],
|
| 91 |
+
cwd=repository,
|
| 92 |
+
env=env,
|
| 93 |
+
stdout=subprocess.PIPE,
|
| 94 |
+
stderr=errors,
|
| 95 |
+
) as process,
|
| 96 |
+
):
|
| 97 |
+
assert process.stdout is not None
|
| 98 |
+
try:
|
| 99 |
+
while chunk := process.stdout.read(65536):
|
| 100 |
+
size += len(chunk)
|
| 101 |
+
if size > max_bytes:
|
| 102 |
+
raise ValueError(f"Submission exceeds {max_bytes} bytes")
|
| 103 |
+
stream.write(chunk)
|
| 104 |
+
digest.update(chunk)
|
| 105 |
+
except BaseException:
|
| 106 |
+
process.kill()
|
| 107 |
+
process.wait()
|
| 108 |
+
raise
|
| 109 |
+
if process.wait():
|
| 110 |
+
errors.seek(0)
|
| 111 |
+
raise RuntimeError(
|
| 112 |
+
"Git patch capture failed: " + errors.read(4096).decode(errors="replace")
|
| 113 |
+
)
|
| 114 |
+
patch.replace(output)
|
| 115 |
+
return {
|
| 116 |
+
"bytes": size,
|
| 117 |
+
"sha256": digest.hexdigest(),
|
| 118 |
+
"base_commit": base,
|
| 119 |
+
"format": "git-binary-v1",
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def submission_command(*, max_bytes: int = MAX_SUBMISSION_BYTES) -> str:
|
| 124 |
+
"""Build the trusted command recorded before Harbor collects artifacts.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
----------
|
| 128 |
+
max_bytes : int, default: 33554432
|
| 129 |
+
Maximum emitted patch bytes.
|
| 130 |
+
|
| 131 |
+
Returns
|
| 132 |
+
-------
|
| 133 |
+
str
|
| 134 |
+
Shell command carrying this exact helper into the solver runtime.
|
| 135 |
+
|
| 136 |
+
Raises
|
| 137 |
+
------
|
| 138 |
+
ValueError
|
| 139 |
+
If the size limit is invalid.
|
| 140 |
+
"""
|
| 141 |
+
if isinstance(max_bytes, bool) or not isinstance(max_bytes, int) or max_bytes < 1:
|
| 142 |
+
raise ValueError("max_bytes must be a positive integer")
|
| 143 |
+
return "python -c " + shlex.quote(Path(__file__).read_text()) + f" --max-bytes {max_bytes}"
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def main() -> None:
|
| 147 |
+
"""Capture the submission and print its identity as trial evidence."""
|
| 148 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 149 |
+
parser.add_argument("--repository", type=Path, default=Path("/testbed"))
|
| 150 |
+
parser.add_argument("--output", type=Path, default=Path("/workspace/submitted.patch"))
|
| 151 |
+
parser.add_argument("--max-bytes", type=int, default=MAX_SUBMISSION_BYTES)
|
| 152 |
+
args = parser.parse_args()
|
| 153 |
+
print(json.dumps(capture_submission(args.repository, args.output, max_bytes=args.max_bytes)))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
main()
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/docker-compose.yaml
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
pids_limit: 512
|
| 4 |
+
security_opt:
|
| 5 |
+
- no-new-privileges:true
|
| 6 |
+
volumes:
|
| 7 |
+
- type: tmpfs
|
| 8 |
+
target: /logs/verifier
|
| 9 |
+
tmpfs:
|
| 10 |
+
mode: 448
|
| 11 |
+
size: 1048576
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/environment/sanitize.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Remove private task assets and history when building the agent-only image."""
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import os
|
| 5 |
+
import shutil
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
sys.path.insert(0, "/app")
|
| 10 |
+
from env import _setup # noqa: E402
|
| 11 |
+
|
| 12 |
+
asyncio.run(_setup())
|
| 13 |
+
# The new history contains only the public baseline. Preserve a root-owned
|
| 14 |
+
# copy so capture can ignore agent-controlled refs, hooks and Git configuration.
|
| 15 |
+
shutil.copytree("/workspace/repo/.git", "/opt/task-tools/baseline.git")
|
| 16 |
+
for path in Path("/opt/task-tools/baseline.git").rglob("*"):
|
| 17 |
+
os.chown(path, 0, 0)
|
| 18 |
+
path.chmod(0o755 if path.is_dir() else 0o644)
|
| 19 |
+
for name in ("/hud", "/app", "/root/.cache", "/root/.hud"):
|
| 20 |
+
if Path(name).exists():
|
| 21 |
+
shutil.rmtree(name)
|
| 22 |
+
# Capture runs on the base interpreter under one name, whatever the image calls it.
|
| 23 |
+
os.symlink(os.path.realpath(sys.executable), "/opt/task-tools/python")
|
| 24 |
+
Path("/workspace/submissions").mkdir()
|
| 25 |
+
os.chown("/workspace/submissions", 1000, 1000)
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/instruction.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please make your changes directly in /workspace/repo.
|
| 2 |
+
|
| 3 |
+
# Ticket
|
| 4 |
+
|
| 5 |
+
Every reported number covers the bytes or events it names, logical sizes in plain bytes, each entry observed at its own size; an admitted write never loses its space to a concurrent write, a reopening under the same limits, or the stored form's overhead; a directory always opens, dropping what no longer fits. Existing tests stay unchanged and green.
|
| 6 |
+
|
| 7 |
+
Finish with a final response when your changes are ready.
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/solution/reference.patch
ADDED
|
@@ -0,0 +1,445 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/cache/disk/accounting_test.go b/cache/disk/accounting_test.go
|
| 2 |
+
new file mode 100644
|
| 3 |
+
index 0000000..e2b40cd
|
| 4 |
+
--- /dev/null
|
| 5 |
+
+++ b/cache/disk/accounting_test.go
|
| 6 |
+
@@ -0,0 +1,229 @@
|
| 7 |
+
+package disk
|
| 8 |
+
+
|
| 9 |
+
+import (
|
| 10 |
+
+ "bytes"
|
| 11 |
+
+ "context"
|
| 12 |
+
+ "crypto/sha256"
|
| 13 |
+
+ "encoding/hex"
|
| 14 |
+
+ "io"
|
| 15 |
+
+ "math/rand"
|
| 16 |
+
+ "os"
|
| 17 |
+
+ "testing"
|
| 18 |
+
+ "time"
|
| 19 |
+
+
|
| 20 |
+
+ "github.com/buchgr/bazel-remote/v2/cache"
|
| 21 |
+
+ testutils "github.com/buchgr/bazel-remote/v2/utils"
|
| 22 |
+
+ dto "github.com/prometheus/client_model/go"
|
| 23 |
+
+)
|
| 24 |
+
+
|
| 25 |
+
+func accountingBlob(n int, seed int64) ([]byte, string) {
|
| 26 |
+
+ r := rand.New(rand.NewSource(seed))
|
| 27 |
+
+ b := make([]byte, n)
|
| 28 |
+
+ _, _ = r.Read(b)
|
| 29 |
+
+ sum := sha256.Sum256(b)
|
| 30 |
+
+ return b, hex.EncodeToString(sum[:])
|
| 31 |
+
+}
|
| 32 |
+
+
|
| 33 |
+
+func openAccountingCache(t *testing.T, dir string, maxSize int64, mode string) *diskCache {
|
| 34 |
+
+ t.Helper()
|
| 35 |
+
+ c, err := New(dir, maxSize, WithStorageMode(mode), WithAccessLogger(testutils.NewSilentLogger()))
|
| 36 |
+
+ if err != nil {
|
| 37 |
+
+ t.Fatal(err)
|
| 38 |
+
+ }
|
| 39 |
+
+ return c.(*diskCache)
|
| 40 |
+
+}
|
| 41 |
+
+
|
| 42 |
+
+func TestAdmittedBlobKeptDespiteStoredFormOverhead(t *testing.T) {
|
| 43 |
+
+ ctx := context.Background()
|
| 44 |
+
+ dir := testutils.TempDir(t)
|
| 45 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 46 |
+
+
|
| 47 |
+
+ maxSize := int64(8 * BlockSize)
|
| 48 |
+
+ c := openAccountingCache(t, dir, maxSize, "zstd")
|
| 49 |
+
+
|
| 50 |
+
+ data, hash := accountingBlob(int(maxSize), 1)
|
| 51 |
+
+ if err := c.Put(ctx, cache.CAS, hash, int64(len(data)), bytes.NewReader(data)); err != nil {
|
| 52 |
+
+ t.Fatalf("admitted blob was refused at commit: %v", err)
|
| 53 |
+
+ }
|
| 54 |
+
+ if ok, _ := c.Contains(ctx, cache.CAS, hash, int64(len(data))); !ok {
|
| 55 |
+
+ t.Fatal("admitted blob is not in the cache")
|
| 56 |
+
+ }
|
| 57 |
+
+
|
| 58 |
+
+ // A restart with the same limit keeps it.
|
| 59 |
+
+ c2 := openAccountingCache(t, dir, maxSize, "zstd")
|
| 60 |
+
+ rc, _, err := c2.Get(ctx, cache.CAS, hash, int64(len(data)), 0)
|
| 61 |
+
+ if err != nil || rc == nil {
|
| 62 |
+
+ t.Fatalf("admitted blob lost on restart: rc=%v err=%v", rc, err)
|
| 63 |
+
+ }
|
| 64 |
+
+ got, err := io.ReadAll(rc)
|
| 65 |
+
+ _ = rc.Close()
|
| 66 |
+
+ if err != nil || !bytes.Equal(got, data) {
|
| 67 |
+
+ t.Fatalf("admitted blob not served back after restart: %v", err)
|
| 68 |
+
+ }
|
| 69 |
+
+}
|
| 70 |
+
+
|
| 71 |
+
+type heldReader struct {
|
| 72 |
+
+ data []byte
|
| 73 |
+
+ pos int
|
| 74 |
+
+ started, release chan struct{}
|
| 75 |
+
+ once bool
|
| 76 |
+
+}
|
| 77 |
+
+
|
| 78 |
+
+func (h *heldReader) Read(p []byte) (int, error) {
|
| 79 |
+
+ if !h.once {
|
| 80 |
+
+ h.once = true
|
| 81 |
+
+ close(h.started)
|
| 82 |
+
+ }
|
| 83 |
+
+ if h.pos < len(h.data) {
|
| 84 |
+
+ n := copy(p, h.data[h.pos:])
|
| 85 |
+
+ h.pos += n
|
| 86 |
+
+ return n, nil
|
| 87 |
+
+ }
|
| 88 |
+
+ <-h.release
|
| 89 |
+
+ return 0, io.EOF
|
| 90 |
+
+}
|
| 91 |
+
+
|
| 92 |
+
+func TestAdmittedBlobKeptDespiteBlockRounding(t *testing.T) {
|
| 93 |
+
+ ctx := context.Background()
|
| 94 |
+
+ dir := testutils.TempDir(t)
|
| 95 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 96 |
+
+
|
| 97 |
+
+ maxSize := int64(16 * BlockSize)
|
| 98 |
+
+ c := openAccountingCache(t, dir, maxSize, "uncompressed")
|
| 99 |
+
+
|
| 100 |
+
+ aData, aHash := accountingBlob(int(maxSize)-4097, 2)
|
| 101 |
+
+ hold := &heldReader{data: aData, started: make(chan struct{}), release: make(chan struct{})}
|
| 102 |
+
+ aDone := make(chan error, 1)
|
| 103 |
+
+ go func() { aDone <- c.Put(ctx, cache.CAS, aHash, int64(len(aData)), hold) }()
|
| 104 |
+
+ <-hold.started
|
| 105 |
+
+ for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(time.Millisecond) {
|
| 106 |
+
+ if _, reserved, _, _ := c.Stats(); reserved == int64(len(aData)) {
|
| 107 |
+
+ break
|
| 108 |
+
+ }
|
| 109 |
+
+ if time.Now().After(deadline) {
|
| 110 |
+
+ t.Fatal("reservation not visible")
|
| 111 |
+
+ }
|
| 112 |
+
+ }
|
| 113 |
+
+
|
| 114 |
+
+ bData, bHash := accountingBlob(4097, 3)
|
| 115 |
+
+ errB := c.Put(ctx, cache.CAS, bHash, int64(len(bData)), bytes.NewReader(bData))
|
| 116 |
+
+ close(hold.release)
|
| 117 |
+
+ if err := <-aDone; err != nil {
|
| 118 |
+
+ t.Fatal(err)
|
| 119 |
+
+ }
|
| 120 |
+
+ if errB != nil {
|
| 121 |
+
+ t.Fatalf("admitted blob was refused at commit: %v", errB)
|
| 122 |
+
+ }
|
| 123 |
+
+}
|
| 124 |
+
+
|
| 125 |
+
+func TestLoadDiscardsBlobsThatNoLongerFit(t *testing.T) {
|
| 126 |
+
+ ctx := context.Background()
|
| 127 |
+
+ dir := testutils.TempDir(t)
|
| 128 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 129 |
+
+
|
| 130 |
+
+ c := openAccountingCache(t, dir, 64*BlockSize, "uncompressed")
|
| 131 |
+
+ big, bigHash := accountingBlob(20000, 4)
|
| 132 |
+
+ if err := c.Put(ctx, cache.CAS, bigHash, int64(len(big)), bytes.NewReader(big)); err != nil {
|
| 133 |
+
+ t.Fatal(err)
|
| 134 |
+
+ }
|
| 135 |
+
+ small, smallHash := accountingBlob(1000, 5)
|
| 136 |
+
+ if err := c.Put(ctx, cache.RAW, smallHash, int64(len(small)), bytes.NewReader(small)); err != nil {
|
| 137 |
+
+ t.Fatal(err)
|
| 138 |
+
+ }
|
| 139 |
+
+
|
| 140 |
+
+ c2 := openAccountingCache(t, dir, 2*BlockSize, "uncompressed")
|
| 141 |
+
+ if ok, _ := c2.Contains(ctx, cache.CAS, bigHash, int64(len(big))); ok {
|
| 142 |
+
+ t.Fatal("oversized blob was not discarded")
|
| 143 |
+
+ }
|
| 144 |
+
+ if ok, _ := c2.Contains(ctx, cache.RAW, smallHash, int64(len(small))); !ok {
|
| 145 |
+
+ t.Fatal("blob that fits was not kept")
|
| 146 |
+
+ }
|
| 147 |
+
+ if _, _, n, _ := c2.Stats(); n != 1 {
|
| 148 |
+
+ t.Fatalf("expected 1 item, found %d", n)
|
| 149 |
+
+ }
|
| 150 |
+
+}
|
| 151 |
+
+
|
| 152 |
+
+func TestLogicalSizeInPlainBytes(t *testing.T) {
|
| 153 |
+
+ ctx := context.Background()
|
| 154 |
+
+ dir := testutils.TempDir(t)
|
| 155 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 156 |
+
+
|
| 157 |
+
+ c := openAccountingCache(t, dir, 64*BlockSize, "zstd")
|
| 158 |
+
+ acHash := hashStr("accounting-ac")
|
| 159 |
+
+ if err := c.Put(ctx, cache.AC, acHash, 100, bytes.NewReader(bytes.Repeat([]byte("a"), 100))); err != nil {
|
| 160 |
+
+ t.Fatal(err)
|
| 161 |
+
+ }
|
| 162 |
+
+ raw, rawHash := accountingBlob(1000, 6)
|
| 163 |
+
+ if err := c.Put(ctx, cache.RAW, rawHash, int64(len(raw)), bytes.NewReader(raw)); err != nil {
|
| 164 |
+
+ t.Fatal(err)
|
| 165 |
+
+ }
|
| 166 |
+
+ if err := c.Put(ctx, cache.AC, acHash, 50, bytes.NewReader(bytes.Repeat([]byte("b"), 50))); err != nil {
|
| 167 |
+
+ t.Fatal(err)
|
| 168 |
+
+ }
|
| 169 |
+
+ if _, _, _, logical := c.Stats(); logical != 1050 {
|
| 170 |
+
+ t.Fatalf("logical size %d, want 1050", logical)
|
| 171 |
+
+ }
|
| 172 |
+
+}
|
| 173 |
+
+
|
| 174 |
+
+func TestEvictedBytesCountOnlyEvictions(t *testing.T) {
|
| 175 |
+
+ ctx := context.Background()
|
| 176 |
+
+ dir := testutils.TempDir(t)
|
| 177 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 178 |
+
+
|
| 179 |
+
+ c := openAccountingCache(t, dir, 3*BlockSize, "uncompressed")
|
| 180 |
+
+ evicted := func() float64 {
|
| 181 |
+
+ var m dto.Metric
|
| 182 |
+
+ if err := c.lru.counterEvictedBytes.Write(&m); err != nil {
|
| 183 |
+
+ t.Fatal(err)
|
| 184 |
+
+ }
|
| 185 |
+
+ return m.GetCounter().GetValue()
|
| 186 |
+
+ }
|
| 187 |
+
+
|
| 188 |
+
+ data, hash := accountingBlob(BlockSize, 7)
|
| 189 |
+
+ if err := c.Put(ctx, cache.RAW, hash, int64(len(data)), bytes.NewReader(data)); err != nil {
|
| 190 |
+
+ t.Fatal(err)
|
| 191 |
+
+ }
|
| 192 |
+
+ key := cache.LookupKey(cache.RAW, hash)
|
| 193 |
+
+ item, _ := c.lru.Get(key)
|
| 194 |
+
+ if err := os.Remove(c.getElementPath(key, item)); err != nil {
|
| 195 |
+
+ t.Fatal(err)
|
| 196 |
+
+ }
|
| 197 |
+
+ if rc, _, _ := c.Get(ctx, cache.RAW, hash, int64(len(data)), 0); rc != nil {
|
| 198 |
+
+ t.Fatal("lost blob was served")
|
| 199 |
+
+ }
|
| 200 |
+
+ if got := evicted(); got != 0 {
|
| 201 |
+
+ t.Fatalf("evicted bytes %v after dropping a lost file", got)
|
| 202 |
+
+ }
|
| 203 |
+
+
|
| 204 |
+
+ for i := 0; i < 4; i++ {
|
| 205 |
+
+ d, h := accountingBlob(BlockSize, int64(10+i))
|
| 206 |
+
+ if err := c.Put(ctx, cache.RAW, h, int64(len(d)), bytes.NewReader(d)); err != nil {
|
| 207 |
+
+ t.Fatal(err)
|
| 208 |
+
+ }
|
| 209 |
+
+ }
|
| 210 |
+
+ if got := evicted(); got != BlockSize {
|
| 211 |
+
+ t.Fatalf("evicted bytes %v after one eviction, want %d", got, BlockSize)
|
| 212 |
+
+ }
|
| 213 |
+
+}
|
| 214 |
+
+
|
| 215 |
+
+func TestEntryBytesSummaryObservesEntrySize(t *testing.T) {
|
| 216 |
+
+ ctx := context.Background()
|
| 217 |
+
+ dir := testutils.TempDir(t)
|
| 218 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 219 |
+
+
|
| 220 |
+
+ c := openAccountingCache(t, dir, 64*BlockSize, "zstd")
|
| 221 |
+
+ hash := hashStr("accounting-summary")
|
| 222 |
+
+ body := bytes.Repeat([]byte("y"), 100)
|
| 223 |
+
+ for i := 0; i < 2; i++ {
|
| 224 |
+
+ if err := c.Put(ctx, cache.AC, hash, int64(len(body)), bytes.NewReader(body)); err != nil {
|
| 225 |
+
+ t.Fatal(err)
|
| 226 |
+
+ }
|
| 227 |
+
+ }
|
| 228 |
+
+ var m dto.Metric
|
| 229 |
+
+ if err := c.lru.summaryCacheItemBytes.Write(&m); err != nil {
|
| 230 |
+
+ t.Fatal(err)
|
| 231 |
+
+ }
|
| 232 |
+
+ if n, sum := m.GetSummary().GetSampleCount(), m.GetSummary().GetSampleSum(); n != 2 || sum != 200 {
|
| 233 |
+
+ t.Fatalf("entry bytes summary: %d observations summing to %v, want 2 of 100", n, sum)
|
| 234 |
+
+ }
|
| 235 |
+
+}
|
| 236 |
+
diff --git a/cache/disk/disk.go b/cache/disk/disk.go
|
| 237 |
+
index 4db928c..cb54739 100644
|
| 238 |
+
--- a/cache/disk/disk.go
|
| 239 |
+
+++ b/cache/disk/disk.go
|
| 240 |
+
@@ -429,7 +429,11 @@ func (c *diskCache) commit(key string, legacy bool, tempfile string, reservedSiz
|
| 241 |
+
random: random,
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
- if !c.lru.Add(key, newItem) {
|
| 245 |
+
+ if reservedSize > 0 {
|
| 246 |
+
+ // Space for this blob was granted when it was reserved. That
|
| 247 |
+
+ // grant is not withdrawn now, whatever the stored form adds.
|
| 248 |
+
+ c.lru.AddAdmitted(key, newItem)
|
| 249 |
+
+ } else if !c.lru.Add(key, newItem) {
|
| 250 |
+
err = fmt.Errorf("INTERNAL ERROR: failed to add: %s, size %d (on disk: %d)",
|
| 251 |
+
key, logicalSize, sizeOnDisk)
|
| 252 |
+
log.Println(err.Error())
|
| 253 |
+
diff --git a/cache/disk/load.go b/cache/disk/load.go
|
| 254 |
+
index cab7f4e..b09d646 100644
|
| 255 |
+
--- a/cache/disk/load.go
|
| 256 |
+
+++ b/cache/disk/load.go
|
| 257 |
+
@@ -616,12 +616,25 @@ func (c *diskCache) loadExistingFiles(maxSizeBytes int64, cc CacheConfig) error
|
| 258 |
+
go c.lru.performQueuedEvictionsContinuously()
|
| 259 |
+
|
| 260 |
+
for i := 0; i < len(result.item); i++ {
|
| 261 |
+
- ok := c.lru.Add(result.metadata[i].lookupKey, *result.item[i])
|
| 262 |
+
- if !ok {
|
| 263 |
+
- err = os.Remove(filepath.Join(c.dir, result.metadata[i].lookupKey))
|
| 264 |
+
- if err != nil {
|
| 265 |
+
- return err
|
| 266 |
+
- }
|
| 267 |
+
+ key := result.metadata[i].lookupKey
|
| 268 |
+
+ item := *result.item[i]
|
| 269 |
+
+
|
| 270 |
+
+ // An existing file is kept if a request of its size would be
|
| 271 |
+
+ // granted space by this cache, i.e. by the same rule that
|
| 272 |
+
+ // admitted it in the first place.
|
| 273 |
+
+ if c.lru.Fits(item.size) {
|
| 274 |
+
+ c.lru.AddAdmitted(key, item)
|
| 275 |
+
+ continue
|
| 276 |
+
+ }
|
| 277 |
+
+
|
| 278 |
+
+ // It no longer fits (e.g. the cache was restarted with a lower
|
| 279 |
+
+ // max size): discard it and carry on loading.
|
| 280 |
+
+ f := c.getElementPath(key, item)
|
| 281 |
+
+ log.Printf("Removing %s (%d bytes), it does not fit in the cache (max size %d bytes).",
|
| 282 |
+
+ f, item.size, maxSizeBytes)
|
| 283 |
+
+ err = os.Remove(f)
|
| 284 |
+
+ if err != nil && !os.IsNotExist(err) {
|
| 285 |
+
+ return err
|
| 286 |
+
}
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
diff --git a/cache/disk/lru.go b/cache/disk/lru.go
|
| 290 |
+
index 7bc4997..faf058c 100644
|
| 291 |
+
--- a/cache/disk/lru.go
|
| 292 |
+
+++ b/cache/disk/lru.go
|
| 293 |
+
@@ -26,8 +26,8 @@ type SizedLRU struct {
|
| 294 |
+
// Total cache size including reserved bytes and estimated filesystem overhead.
|
| 295 |
+
currentSize int64
|
| 296 |
+
|
| 297 |
+
- // Total size of all blobs in uncompressed form.
|
| 298 |
+
- // This does not include reserved space.
|
| 299 |
+
+ // Total size of all blobs in uncompressed form, in plain bytes (not
|
| 300 |
+
+ // rounded up to BlockSize). This does not include reserved space.
|
| 301 |
+
uncompressedSize int64
|
| 302 |
+
|
| 303 |
+
// Number of bytes reserved for incoming blobs.
|
| 304 |
+
@@ -188,47 +188,77 @@ func (c *SizedLRU) Add(key string, value lruItem) (ok bool) {
|
| 305 |
+
// time (unless Reserve method was used and evicted them).
|
| 306 |
+
c.calcTotalDiskSizeAndUpdatePeak(roundedUpSizeOnDisk)
|
| 307 |
+
|
| 308 |
+
- var sizeDelta, uncompressedSizeDelta int64
|
| 309 |
+
+ sizeDelta := roundedUpSizeOnDisk
|
| 310 |
+
if ee, ok := c.cache[key]; ok {
|
| 311 |
+
- sizeDelta = roundedUpSizeOnDisk - roundUp4k(ee.Value.(*entry).value.sizeOnDisk)
|
| 312 |
+
- if c.reservedSize+sizeDelta > c.maxSize {
|
| 313 |
+
- return false
|
| 314 |
+
- }
|
| 315 |
+
- uncompressedSizeDelta = roundUp4k(value.size) - roundUp4k(ee.Value.(*entry).value.size)
|
| 316 |
+
+ sizeDelta -= roundUp4k(ee.Value.(*entry).value.sizeOnDisk)
|
| 317 |
+
+ }
|
| 318 |
+
+ if c.reservedSize+sizeDelta > c.maxSize {
|
| 319 |
+
+ return false
|
| 320 |
+
+ }
|
| 321 |
+
+
|
| 322 |
+
+ c.insert(key, value)
|
| 323 |
+
+
|
| 324 |
+
+ return true
|
| 325 |
+
+}
|
| 326 |
+
+
|
| 327 |
+
+// AddAdmitted adds a (key, value) whose admission was already decided,
|
| 328 |
+
+// either because space for it was granted by Reserve (which the caller
|
| 329 |
+
+// must have released with Unreserve first), or because it is an existing
|
| 330 |
+
+// file that fits the cache by its logical size. It never rejects the item,
|
| 331 |
+
+// whatever its stored form adds on top of the logical size (block rounding,
|
| 332 |
+
+// compression headers): other items are evicted to make room, but never the
|
| 333 |
+
+// item itself, so the cache can temporarily exceed maxSize by that overhead.
|
| 334 |
+
+func (c *SizedLRU) AddAdmitted(key string, value lruItem) {
|
| 335 |
+
+ c.calcTotalDiskSizeAndUpdatePeak(roundUp4k(value.sizeOnDisk))
|
| 336 |
+
+ c.insert(key, value)
|
| 337 |
+
+}
|
| 338 |
+
+
|
| 339 |
+
+// Fits reports whether an item of the given logical size can be admitted,
|
| 340 |
+
+// using the same rule as Reserve.
|
| 341 |
+
+func (c *SizedLRU) Fits(logicalSize int64) bool {
|
| 342 |
+
+ return logicalSize >= 0 && logicalSize <= c.maxSize
|
| 343 |
+
+}
|
| 344 |
+
+
|
| 345 |
+
+// insert stores (key, value), replacing any existing value for key, and
|
| 346 |
+
+// then evicts least recently used items (never the inserted one) until the
|
| 347 |
+
+// cache is within maxSize again.
|
| 348 |
+
+func (c *SizedLRU) insert(key string, value lruItem) {
|
| 349 |
+
+ sizeDelta := roundUp4k(value.sizeOnDisk)
|
| 350 |
+
+ uncompressedSizeDelta := value.size
|
| 351 |
+
+
|
| 352 |
+
+ var ele *list.Element
|
| 353 |
+
+ if ee, ok := c.cache[key]; ok {
|
| 354 |
+
+ old := ee.Value.(*entry)
|
| 355 |
+
+ sizeDelta -= roundUp4k(old.value.sizeOnDisk)
|
| 356 |
+
+ uncompressedSizeDelta -= old.value.size
|
| 357 |
+
c.ll.MoveToFront(ee)
|
| 358 |
+
- c.counterOverwrittenBytes.Add(float64(ee.Value.(*entry).value.sizeOnDisk))
|
| 359 |
+
+ c.counterOverwrittenBytes.Add(float64(old.value.sizeOnDisk))
|
| 360 |
+
|
| 361 |
+
- kv := ee.Value.(*entry)
|
| 362 |
+
- kvCopy := &entry{kv.key, kv.value}
|
| 363 |
+
- c.appendEvictionToQueue(kvCopy)
|
| 364 |
+
+ // The replaced file still has to be removed from disk.
|
| 365 |
+
+ c.appendEvictionToQueue(&entry{old.key, old.value})
|
| 366 |
+
|
| 367 |
+
- ee.Value.(*entry).value = value
|
| 368 |
+
+ old.value = value
|
| 369 |
+
+ ele = ee
|
| 370 |
+
} else {
|
| 371 |
+
- sizeDelta = roundedUpSizeOnDisk
|
| 372 |
+
- if c.reservedSize+sizeDelta > c.maxSize {
|
| 373 |
+
- return false
|
| 374 |
+
- }
|
| 375 |
+
- uncompressedSizeDelta = roundUp4k(value.size)
|
| 376 |
+
- ele := c.ll.PushFront(&entry{key, value})
|
| 377 |
+
+ ele = c.ll.PushFront(&entry{key, value})
|
| 378 |
+
c.cache[key] = ele
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
+ c.currentSize += sizeDelta
|
| 382 |
+
+ c.uncompressedSize += uncompressedSizeDelta
|
| 383 |
+
+
|
| 384 |
+
// Eviction. This is needed even if the key was already present, since the size of the
|
| 385 |
+
// value might have changed, pushing the total size over maxSize.
|
| 386 |
+
- for c.currentSize+sizeDelta > c.maxSize {
|
| 387 |
+
- ele := c.ll.Back()
|
| 388 |
+
- if ele != nil {
|
| 389 |
+
- c.removeElement(ele)
|
| 390 |
+
+ for c.currentSize > c.maxSize {
|
| 391 |
+
+ back := c.ll.Back()
|
| 392 |
+
+ if back == nil || back == ele {
|
| 393 |
+
+ break
|
| 394 |
+
}
|
| 395 |
+
+ c.evictElement(back)
|
| 396 |
+
}
|
| 397 |
+
|
| 398 |
+
- c.currentSize += sizeDelta
|
| 399 |
+
- c.uncompressedSize += uncompressedSizeDelta
|
| 400 |
+
-
|
| 401 |
+
c.gaugeCacheLogicalBytes.Set(float64(c.uncompressedSize))
|
| 402 |
+
- c.summaryCacheItemBytes.Observe(float64(sizeDelta))
|
| 403 |
+
-
|
| 404 |
+
- return true
|
| 405 |
+
+ c.summaryCacheItemBytes.Observe(float64(value.sizeOnDisk))
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
// Get looks up a key in the cache. The lruItem is only valid if *list.Element is not nil.
|
| 409 |
+
@@ -361,7 +391,7 @@ func (c *SizedLRU) Reserve(size int64) error {
|
| 410 |
+
for sumLargerThan(size, c.currentSize, c.maxSize) {
|
| 411 |
+
ele := c.ll.Back()
|
| 412 |
+
if ele != nil {
|
| 413 |
+
- c.removeElement(ele)
|
| 414 |
+
+ c.evictElement(ele)
|
| 415 |
+
} else {
|
| 416 |
+
return internalErr(errReservation) // This should have been caught at the start.
|
| 417 |
+
}
|
| 418 |
+
@@ -394,16 +424,25 @@ func (c *SizedLRU) Unreserve(size int64) error {
|
| 419 |
+
return nil
|
| 420 |
+
}
|
| 421 |
+
|
| 422 |
+
+// removeElement drops an element from the index and queues its file for
|
| 423 |
+
+// removal. It is used both for evictions and for entries whose file was
|
| 424 |
+
+// lost or found to be corrupt; only evictElement counts as an eviction.
|
| 425 |
+
func (c *SizedLRU) removeElement(e *list.Element) {
|
| 426 |
+
c.ll.Remove(e)
|
| 427 |
+
kv := e.Value.(*entry)
|
| 428 |
+
delete(c.cache, kv.key)
|
| 429 |
+
c.currentSize -= roundUp4k(kv.value.sizeOnDisk)
|
| 430 |
+
- c.uncompressedSize -= roundUp4k(kv.value.size)
|
| 431 |
+
- c.counterEvictedBytes.Add(float64(kv.value.sizeOnDisk))
|
| 432 |
+
+ c.uncompressedSize -= kv.value.size
|
| 433 |
+
+ c.gaugeCacheLogicalBytes.Set(float64(c.uncompressedSize))
|
| 434 |
+
c.appendEvictionToQueue(kv)
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
+// evictElement removes an element to make room in a full cache.
|
| 438 |
+
+func (c *SizedLRU) evictElement(e *list.Element) {
|
| 439 |
+
+ c.counterEvictedBytes.Add(float64(e.Value.(*entry).value.sizeOnDisk))
|
| 440 |
+
+ c.removeElement(e)
|
| 441 |
+
+}
|
| 442 |
+
+
|
| 443 |
+
// Round n up to the nearest multiple of BlockSize (4096).
|
| 444 |
+
func roundUp4k(n int64) int64 {
|
| 445 |
+
return (n + BlockSize - 1) & -BlockSize
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/solution/solve.sh
ADDED
|
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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accounting_test.go
|
| 10 |
+
@@ -0,0 +1,229 @@
|
| 11 |
+
+package disk
|
| 12 |
+
+
|
| 13 |
+
+import (
|
| 14 |
+
+ "bytes"
|
| 15 |
+
+ "context"
|
| 16 |
+
+ "crypto/sha256"
|
| 17 |
+
+ "encoding/hex"
|
| 18 |
+
+ "io"
|
| 19 |
+
+ "math/rand"
|
| 20 |
+
+ "os"
|
| 21 |
+
+ "testing"
|
| 22 |
+
+ "time"
|
| 23 |
+
+
|
| 24 |
+
+ "github.com/buchgr/bazel-remote/v2/cache"
|
| 25 |
+
+ testutils "github.com/buchgr/bazel-remote/v2/utils"
|
| 26 |
+
+ dto "github.com/prometheus/client_model/go"
|
| 27 |
+
+)
|
| 28 |
+
+
|
| 29 |
+
+func accountingBlob(n int, seed int64) ([]byte, string) {
|
| 30 |
+
+ r := rand.New(rand.NewSource(seed))
|
| 31 |
+
+ b := make([]byte, n)
|
| 32 |
+
+ _, _ = r.Read(b)
|
| 33 |
+
+ sum := sha256.Sum256(b)
|
| 34 |
+
+ return b, hex.EncodeToString(sum[:])
|
| 35 |
+
+}
|
| 36 |
+
+
|
| 37 |
+
+func openAccountingCache(t *testing.T, dir string, maxSize int64, mode string) *diskCache {
|
| 38 |
+
+ t.Helper()
|
| 39 |
+
+ c, err := New(dir, maxSize, WithStorageMode(mode), WithAccessLogger(testutils.NewSilentLogger()))
|
| 40 |
+
+ if err != nil {
|
| 41 |
+
+ t.Fatal(err)
|
| 42 |
+
+ }
|
| 43 |
+
+ return c.(*diskCache)
|
| 44 |
+
+}
|
| 45 |
+
+
|
| 46 |
+
+func TestAdmittedBlobKeptDespiteStoredFormOverhead(t *testing.T) {
|
| 47 |
+
+ ctx := context.Background()
|
| 48 |
+
+ dir := testutils.TempDir(t)
|
| 49 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 50 |
+
+
|
| 51 |
+
+ maxSize := int64(8 * BlockSize)
|
| 52 |
+
+ c := openAccountingCache(t, dir, maxSize, "zstd")
|
| 53 |
+
+
|
| 54 |
+
+ data, hash := accountingBlob(int(maxSize), 1)
|
| 55 |
+
+ if err := c.Put(ctx, cache.CAS, hash, int64(len(data)), bytes.NewReader(data)); err != nil {
|
| 56 |
+
+ t.Fatalf("admitted blob was refused at commit: %v", err)
|
| 57 |
+
+ }
|
| 58 |
+
+ if ok, _ := c.Contains(ctx, cache.CAS, hash, int64(len(data))); !ok {
|
| 59 |
+
+ t.Fatal("admitted blob is not in the cache")
|
| 60 |
+
+ }
|
| 61 |
+
+
|
| 62 |
+
+ // A restart with the same limit keeps it.
|
| 63 |
+
+ c2 := openAccountingCache(t, dir, maxSize, "zstd")
|
| 64 |
+
+ rc, _, err := c2.Get(ctx, cache.CAS, hash, int64(len(data)), 0)
|
| 65 |
+
+ if err != nil || rc == nil {
|
| 66 |
+
+ t.Fatalf("admitted blob lost on restart: rc=%v err=%v", rc, err)
|
| 67 |
+
+ }
|
| 68 |
+
+ got, err := io.ReadAll(rc)
|
| 69 |
+
+ _ = rc.Close()
|
| 70 |
+
+ if err != nil || !bytes.Equal(got, data) {
|
| 71 |
+
+ t.Fatalf("admitted blob not served back after restart: %v", err)
|
| 72 |
+
+ }
|
| 73 |
+
+}
|
| 74 |
+
+
|
| 75 |
+
+type heldReader struct {
|
| 76 |
+
+ data []byte
|
| 77 |
+
+ pos int
|
| 78 |
+
+ started, release chan struct{}
|
| 79 |
+
+ once bool
|
| 80 |
+
+}
|
| 81 |
+
+
|
| 82 |
+
+func (h *heldReader) Read(p []byte) (int, error) {
|
| 83 |
+
+ if !h.once {
|
| 84 |
+
+ h.once = true
|
| 85 |
+
+ close(h.started)
|
| 86 |
+
+ }
|
| 87 |
+
+ if h.pos < len(h.data) {
|
| 88 |
+
+ n := copy(p, h.data[h.pos:])
|
| 89 |
+
+ h.pos += n
|
| 90 |
+
+ return n, nil
|
| 91 |
+
+ }
|
| 92 |
+
+ <-h.release
|
| 93 |
+
+ return 0, io.EOF
|
| 94 |
+
+}
|
| 95 |
+
+
|
| 96 |
+
+func TestAdmittedBlobKeptDespiteBlockRounding(t *testing.T) {
|
| 97 |
+
+ ctx := context.Background()
|
| 98 |
+
+ dir := testutils.TempDir(t)
|
| 99 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 100 |
+
+
|
| 101 |
+
+ maxSize := int64(16 * BlockSize)
|
| 102 |
+
+ c := openAccountingCache(t, dir, maxSize, "uncompressed")
|
| 103 |
+
+
|
| 104 |
+
+ aData, aHash := accountingBlob(int(maxSize)-4097, 2)
|
| 105 |
+
+ hold := &heldReader{data: aData, started: make(chan struct{}), release: make(chan struct{})}
|
| 106 |
+
+ aDone := make(chan error, 1)
|
| 107 |
+
+ go func() { aDone <- c.Put(ctx, cache.CAS, aHash, int64(len(aData)), hold) }()
|
| 108 |
+
+ <-hold.started
|
| 109 |
+
+ for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(time.Millisecond) {
|
| 110 |
+
+ if _, reserved, _, _ := c.Stats(); reserved == int64(len(aData)) {
|
| 111 |
+
+ break
|
| 112 |
+
+ }
|
| 113 |
+
+ if time.Now().After(deadline) {
|
| 114 |
+
+ t.Fatal("reservation not visible")
|
| 115 |
+
+ }
|
| 116 |
+
+ }
|
| 117 |
+
+
|
| 118 |
+
+ bData, bHash := accountingBlob(4097, 3)
|
| 119 |
+
+ errB := c.Put(ctx, cache.CAS, bHash, int64(len(bData)), bytes.NewReader(bData))
|
| 120 |
+
+ close(hold.release)
|
| 121 |
+
+ if err := <-aDone; err != nil {
|
| 122 |
+
+ t.Fatal(err)
|
| 123 |
+
+ }
|
| 124 |
+
+ if errB != nil {
|
| 125 |
+
+ t.Fatalf("admitted blob was refused at commit: %v", errB)
|
| 126 |
+
+ }
|
| 127 |
+
+}
|
| 128 |
+
+
|
| 129 |
+
+func TestLoadDiscardsBlobsThatNoLongerFit(t *testing.T) {
|
| 130 |
+
+ ctx := context.Background()
|
| 131 |
+
+ dir := testutils.TempDir(t)
|
| 132 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 133 |
+
+
|
| 134 |
+
+ c := openAccountingCache(t, dir, 64*BlockSize, "uncompressed")
|
| 135 |
+
+ big, bigHash := accountingBlob(20000, 4)
|
| 136 |
+
+ if err := c.Put(ctx, cache.CAS, bigHash, int64(len(big)), bytes.NewReader(big)); err != nil {
|
| 137 |
+
+ t.Fatal(err)
|
| 138 |
+
+ }
|
| 139 |
+
+ small, smallHash := accountingBlob(1000, 5)
|
| 140 |
+
+ if err := c.Put(ctx, cache.RAW, smallHash, int64(len(small)), bytes.NewReader(small)); err != nil {
|
| 141 |
+
+ t.Fatal(err)
|
| 142 |
+
+ }
|
| 143 |
+
+
|
| 144 |
+
+ c2 := openAccountingCache(t, dir, 2*BlockSize, "uncompressed")
|
| 145 |
+
+ if ok, _ := c2.Contains(ctx, cache.CAS, bigHash, int64(len(big))); ok {
|
| 146 |
+
+ t.Fatal("oversized blob was not discarded")
|
| 147 |
+
+ }
|
| 148 |
+
+ if ok, _ := c2.Contains(ctx, cache.RAW, smallHash, int64(len(small))); !ok {
|
| 149 |
+
+ t.Fatal("blob that fits was not kept")
|
| 150 |
+
+ }
|
| 151 |
+
+ if _, _, n, _ := c2.Stats(); n != 1 {
|
| 152 |
+
+ t.Fatalf("expected 1 item, found %d", n)
|
| 153 |
+
+ }
|
| 154 |
+
+}
|
| 155 |
+
+
|
| 156 |
+
+func TestLogicalSizeInPlainBytes(t *testing.T) {
|
| 157 |
+
+ ctx := context.Background()
|
| 158 |
+
+ dir := testutils.TempDir(t)
|
| 159 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 160 |
+
+
|
| 161 |
+
+ c := openAccountingCache(t, dir, 64*BlockSize, "zstd")
|
| 162 |
+
+ acHash := hashStr("accounting-ac")
|
| 163 |
+
+ if err := c.Put(ctx, cache.AC, acHash, 100, bytes.NewReader(bytes.Repeat([]byte("a"), 100))); err != nil {
|
| 164 |
+
+ t.Fatal(err)
|
| 165 |
+
+ }
|
| 166 |
+
+ raw, rawHash := accountingBlob(1000, 6)
|
| 167 |
+
+ if err := c.Put(ctx, cache.RAW, rawHash, int64(len(raw)), bytes.NewReader(raw)); err != nil {
|
| 168 |
+
+ t.Fatal(err)
|
| 169 |
+
+ }
|
| 170 |
+
+ if err := c.Put(ctx, cache.AC, acHash, 50, bytes.NewReader(bytes.Repeat([]byte("b"), 50))); err != nil {
|
| 171 |
+
+ t.Fatal(err)
|
| 172 |
+
+ }
|
| 173 |
+
+ if _, _, _, logical := c.Stats(); logical != 1050 {
|
| 174 |
+
+ t.Fatalf("logical size %d, want 1050", logical)
|
| 175 |
+
+ }
|
| 176 |
+
+}
|
| 177 |
+
+
|
| 178 |
+
+func TestEvictedBytesCountOnlyEvictions(t *testing.T) {
|
| 179 |
+
+ ctx := context.Background()
|
| 180 |
+
+ dir := testutils.TempDir(t)
|
| 181 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 182 |
+
+
|
| 183 |
+
+ c := openAccountingCache(t, dir, 3*BlockSize, "uncompressed")
|
| 184 |
+
+ evicted := func() float64 {
|
| 185 |
+
+ var m dto.Metric
|
| 186 |
+
+ if err := c.lru.counterEvictedBytes.Write(&m); err != nil {
|
| 187 |
+
+ t.Fatal(err)
|
| 188 |
+
+ }
|
| 189 |
+
+ return m.GetCounter().GetValue()
|
| 190 |
+
+ }
|
| 191 |
+
+
|
| 192 |
+
+ data, hash := accountingBlob(BlockSize, 7)
|
| 193 |
+
+ if err := c.Put(ctx, cache.RAW, hash, int64(len(data)), bytes.NewReader(data)); err != nil {
|
| 194 |
+
+ t.Fatal(err)
|
| 195 |
+
+ }
|
| 196 |
+
+ key := cache.LookupKey(cache.RAW, hash)
|
| 197 |
+
+ item, _ := c.lru.Get(key)
|
| 198 |
+
+ if err := os.Remove(c.getElementPath(key, item)); err != nil {
|
| 199 |
+
+ t.Fatal(err)
|
| 200 |
+
+ }
|
| 201 |
+
+ if rc, _, _ := c.Get(ctx, cache.RAW, hash, int64(len(data)), 0); rc != nil {
|
| 202 |
+
+ t.Fatal("lost blob was served")
|
| 203 |
+
+ }
|
| 204 |
+
+ if got := evicted(); got != 0 {
|
| 205 |
+
+ t.Fatalf("evicted bytes %v after dropping a lost file", got)
|
| 206 |
+
+ }
|
| 207 |
+
+
|
| 208 |
+
+ for i := 0; i < 4; i++ {
|
| 209 |
+
+ d, h := accountingBlob(BlockSize, int64(10+i))
|
| 210 |
+
+ if err := c.Put(ctx, cache.RAW, h, int64(len(d)), bytes.NewReader(d)); err != nil {
|
| 211 |
+
+ t.Fatal(err)
|
| 212 |
+
+ }
|
| 213 |
+
+ }
|
| 214 |
+
+ if got := evicted(); got != BlockSize {
|
| 215 |
+
+ t.Fatalf("evicted bytes %v after one eviction, want %d", got, BlockSize)
|
| 216 |
+
+ }
|
| 217 |
+
+}
|
| 218 |
+
+
|
| 219 |
+
+func TestEntryBytesSummaryObservesEntrySize(t *testing.T) {
|
| 220 |
+
+ ctx := context.Background()
|
| 221 |
+
+ dir := testutils.TempDir(t)
|
| 222 |
+
+ defer func() { _ = os.RemoveAll(dir) }()
|
| 223 |
+
+
|
| 224 |
+
+ c := openAccountingCache(t, dir, 64*BlockSize, "zstd")
|
| 225 |
+
+ hash := hashStr("accounting-summary")
|
| 226 |
+
+ body := bytes.Repeat([]byte("y"), 100)
|
| 227 |
+
+ for i := 0; i < 2; i++ {
|
| 228 |
+
+ if err := c.Put(ctx, cache.AC, hash, int64(len(body)), bytes.NewReader(body)); err != nil {
|
| 229 |
+
+ t.Fatal(err)
|
| 230 |
+
+ }
|
| 231 |
+
+ }
|
| 232 |
+
+ var m dto.Metric
|
| 233 |
+
+ if err := c.lru.summaryCacheItemBytes.Write(&m); err != nil {
|
| 234 |
+
+ t.Fatal(err)
|
| 235 |
+
+ }
|
| 236 |
+
+ if n, sum := m.GetSummary().GetSampleCount(), m.GetSummary().GetSampleSum(); n != 2 || sum != 200 {
|
| 237 |
+
+ t.Fatalf("entry bytes summary: %d observations summing to %v, want 2 of 100", n, sum)
|
| 238 |
+
+ }
|
| 239 |
+
+}
|
| 240 |
+
diff --git a/cache/disk/disk.go b/cache/disk/disk.go
|
| 241 |
+
index 4db928c..cb54739 100644
|
| 242 |
+
--- a/cache/disk/disk.go
|
| 243 |
+
+++ b/cache/disk/disk.go
|
| 244 |
+
@@ -429,7 +429,11 @@ func (c *diskCache) commit(key string, legacy bool, tempfile string, reservedSiz
|
| 245 |
+
random: random,
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
- if !c.lru.Add(key, newItem) {
|
| 249 |
+
+ if reservedSize > 0 {
|
| 250 |
+
+ // Space for this blob was granted when it was reserved. That
|
| 251 |
+
+ // grant is not withdrawn now, whatever the stored form adds.
|
| 252 |
+
+ c.lru.AddAdmitted(key, newItem)
|
| 253 |
+
+ } else if !c.lru.Add(key, newItem) {
|
| 254 |
+
err = fmt.Errorf("INTERNAL ERROR: failed to add: %s, size %d (on disk: %d)",
|
| 255 |
+
key, logicalSize, sizeOnDisk)
|
| 256 |
+
log.Println(err.Error())
|
| 257 |
+
diff --git a/cache/disk/load.go b/cache/disk/load.go
|
| 258 |
+
index cab7f4e..b09d646 100644
|
| 259 |
+
--- a/cache/disk/load.go
|
| 260 |
+
+++ b/cache/disk/load.go
|
| 261 |
+
@@ -616,12 +616,25 @@ func (c *diskCache) loadExistingFiles(maxSizeBytes int64, cc CacheConfig) error
|
| 262 |
+
go c.lru.performQueuedEvictionsContinuously()
|
| 263 |
+
|
| 264 |
+
for i := 0; i < len(result.item); i++ {
|
| 265 |
+
- ok := c.lru.Add(result.metadata[i].lookupKey, *result.item[i])
|
| 266 |
+
- if !ok {
|
| 267 |
+
- err = os.Remove(filepath.Join(c.dir, result.metadata[i].lookupKey))
|
| 268 |
+
- if err != nil {
|
| 269 |
+
- return err
|
| 270 |
+
- }
|
| 271 |
+
+ key := result.metadata[i].lookupKey
|
| 272 |
+
+ item := *result.item[i]
|
| 273 |
+
+
|
| 274 |
+
+ // An existing file is kept if a request of its size would be
|
| 275 |
+
+ // granted space by this cache, i.e. by the same rule that
|
| 276 |
+
+ // admitted it in the first place.
|
| 277 |
+
+ if c.lru.Fits(item.size) {
|
| 278 |
+
+ c.lru.AddAdmitted(key, item)
|
| 279 |
+
+ continue
|
| 280 |
+
+ }
|
| 281 |
+
+
|
| 282 |
+
+ // It no longer fits (e.g. the cache was restarted with a lower
|
| 283 |
+
+ // max size): discard it and carry on loading.
|
| 284 |
+
+ f := c.getElementPath(key, item)
|
| 285 |
+
+ log.Printf("Removing %s (%d bytes), it does not fit in the cache (max size %d bytes).",
|
| 286 |
+
+ f, item.size, maxSizeBytes)
|
| 287 |
+
+ err = os.Remove(f)
|
| 288 |
+
+ if err != nil && !os.IsNotExist(err) {
|
| 289 |
+
+ return err
|
| 290 |
+
}
|
| 291 |
+
}
|
| 292 |
+
|
| 293 |
+
diff --git a/cache/disk/lru.go b/cache/disk/lru.go
|
| 294 |
+
index 7bc4997..faf058c 100644
|
| 295 |
+
--- a/cache/disk/lru.go
|
| 296 |
+
+++ b/cache/disk/lru.go
|
| 297 |
+
@@ -26,8 +26,8 @@ type SizedLRU struct {
|
| 298 |
+
// Total cache size including reserved bytes and estimated filesystem overhead.
|
| 299 |
+
currentSize int64
|
| 300 |
+
|
| 301 |
+
- // Total size of all blobs in uncompressed form.
|
| 302 |
+
- // This does not include reserved space.
|
| 303 |
+
+ // Total size of all blobs in uncompressed form, in plain bytes (not
|
| 304 |
+
+ // rounded up to BlockSize). This does not include reserved space.
|
| 305 |
+
uncompressedSize int64
|
| 306 |
+
|
| 307 |
+
// Number of bytes reserved for incoming blobs.
|
| 308 |
+
@@ -188,47 +188,77 @@ func (c *SizedLRU) Add(key string, value lruItem) (ok bool) {
|
| 309 |
+
// time (unless Reserve method was used and evicted them).
|
| 310 |
+
c.calcTotalDiskSizeAndUpdatePeak(roundedUpSizeOnDisk)
|
| 311 |
+
|
| 312 |
+
- var sizeDelta, uncompressedSizeDelta int64
|
| 313 |
+
+ sizeDelta := roundedUpSizeOnDisk
|
| 314 |
+
if ee, ok := c.cache[key]; ok {
|
| 315 |
+
- sizeDelta = roundedUpSizeOnDisk - roundUp4k(ee.Value.(*entry).value.sizeOnDisk)
|
| 316 |
+
- if c.reservedSize+sizeDelta > c.maxSize {
|
| 317 |
+
- return false
|
| 318 |
+
- }
|
| 319 |
+
- uncompressedSizeDelta = roundUp4k(value.size) - roundUp4k(ee.Value.(*entry).value.size)
|
| 320 |
+
+ sizeDelta -= roundUp4k(ee.Value.(*entry).value.sizeOnDisk)
|
| 321 |
+
+ }
|
| 322 |
+
+ if c.reservedSize+sizeDelta > c.maxSize {
|
| 323 |
+
+ return false
|
| 324 |
+
+ }
|
| 325 |
+
+
|
| 326 |
+
+ c.insert(key, value)
|
| 327 |
+
+
|
| 328 |
+
+ return true
|
| 329 |
+
+}
|
| 330 |
+
+
|
| 331 |
+
+// AddAdmitted adds a (key, value) whose admission was already decided,
|
| 332 |
+
+// either because space for it was granted by Reserve (which the caller
|
| 333 |
+
+// must have released with Unreserve first), or because it is an existing
|
| 334 |
+
+// file that fits the cache by its logical size. It never rejects the item,
|
| 335 |
+
+// whatever its stored form adds on top of the logical size (block rounding,
|
| 336 |
+
+// compression headers): other items are evicted to make room, but never the
|
| 337 |
+
+// item itself, so the cache can temporarily exceed maxSize by that overhead.
|
| 338 |
+
+func (c *SizedLRU) AddAdmitted(key string, value lruItem) {
|
| 339 |
+
+ c.calcTotalDiskSizeAndUpdatePeak(roundUp4k(value.sizeOnDisk))
|
| 340 |
+
+ c.insert(key, value)
|
| 341 |
+
+}
|
| 342 |
+
+
|
| 343 |
+
+// Fits reports whether an item of the given logical size can be admitted,
|
| 344 |
+
+// using the same rule as Reserve.
|
| 345 |
+
+func (c *SizedLRU) Fits(logicalSize int64) bool {
|
| 346 |
+
+ return logicalSize >= 0 && logicalSize <= c.maxSize
|
| 347 |
+
+}
|
| 348 |
+
+
|
| 349 |
+
+// insert stores (key, value), replacing any existing value for key, and
|
| 350 |
+
+// then evicts least recently used items (never the inserted one) until the
|
| 351 |
+
+// cache is within maxSize again.
|
| 352 |
+
+func (c *SizedLRU) insert(key string, value lruItem) {
|
| 353 |
+
+ sizeDelta := roundUp4k(value.sizeOnDisk)
|
| 354 |
+
+ uncompressedSizeDelta := value.size
|
| 355 |
+
+
|
| 356 |
+
+ var ele *list.Element
|
| 357 |
+
+ if ee, ok := c.cache[key]; ok {
|
| 358 |
+
+ old := ee.Value.(*entry)
|
| 359 |
+
+ sizeDelta -= roundUp4k(old.value.sizeOnDisk)
|
| 360 |
+
+ uncompressedSizeDelta -= old.value.size
|
| 361 |
+
c.ll.MoveToFront(ee)
|
| 362 |
+
- c.counterOverwrittenBytes.Add(float64(ee.Value.(*entry).value.sizeOnDisk))
|
| 363 |
+
+ c.counterOverwrittenBytes.Add(float64(old.value.sizeOnDisk))
|
| 364 |
+
|
| 365 |
+
- kv := ee.Value.(*entry)
|
| 366 |
+
- kvCopy := &entry{kv.key, kv.value}
|
| 367 |
+
- c.appendEvictionToQueue(kvCopy)
|
| 368 |
+
+ // The replaced file still has to be removed from disk.
|
| 369 |
+
+ c.appendEvictionToQueue(&entry{old.key, old.value})
|
| 370 |
+
|
| 371 |
+
- ee.Value.(*entry).value = value
|
| 372 |
+
+ old.value = value
|
| 373 |
+
+ ele = ee
|
| 374 |
+
} else {
|
| 375 |
+
- sizeDelta = roundedUpSizeOnDisk
|
| 376 |
+
- if c.reservedSize+sizeDelta > c.maxSize {
|
| 377 |
+
- return false
|
| 378 |
+
- }
|
| 379 |
+
- uncompressedSizeDelta = roundUp4k(value.size)
|
| 380 |
+
- ele := c.ll.PushFront(&entry{key, value})
|
| 381 |
+
+ ele = c.ll.PushFront(&entry{key, value})
|
| 382 |
+
c.cache[key] = ele
|
| 383 |
+
}
|
| 384 |
+
|
| 385 |
+
+ c.currentSize += sizeDelta
|
| 386 |
+
+ c.uncompressedSize += uncompressedSizeDelta
|
| 387 |
+
+
|
| 388 |
+
// Eviction. This is needed even if the key was already present, since the size of the
|
| 389 |
+
// value might have changed, pushing the total size over maxSize.
|
| 390 |
+
- for c.currentSize+sizeDelta > c.maxSize {
|
| 391 |
+
- ele := c.ll.Back()
|
| 392 |
+
- if ele != nil {
|
| 393 |
+
- c.removeElement(ele)
|
| 394 |
+
+ for c.currentSize > c.maxSize {
|
| 395 |
+
+ back := c.ll.Back()
|
| 396 |
+
+ if back == nil || back == ele {
|
| 397 |
+
+ break
|
| 398 |
+
}
|
| 399 |
+
+ c.evictElement(back)
|
| 400 |
+
}
|
| 401 |
+
|
| 402 |
+
- c.currentSize += sizeDelta
|
| 403 |
+
- c.uncompressedSize += uncompressedSizeDelta
|
| 404 |
+
-
|
| 405 |
+
c.gaugeCacheLogicalBytes.Set(float64(c.uncompressedSize))
|
| 406 |
+
- c.summaryCacheItemBytes.Observe(float64(sizeDelta))
|
| 407 |
+
-
|
| 408 |
+
- return true
|
| 409 |
+
+ c.summaryCacheItemBytes.Observe(float64(value.sizeOnDisk))
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
// Get looks up a key in the cache. The lruItem is only valid if *list.Element is not nil.
|
| 413 |
+
@@ -361,7 +391,7 @@ func (c *SizedLRU) Reserve(size int64) error {
|
| 414 |
+
for sumLargerThan(size, c.currentSize, c.maxSize) {
|
| 415 |
+
ele := c.ll.Back()
|
| 416 |
+
if ele != nil {
|
| 417 |
+
- c.removeElement(ele)
|
| 418 |
+
+ c.evictElement(ele)
|
| 419 |
+
} else {
|
| 420 |
+
return internalErr(errReservation) // This should have been caught at the start.
|
| 421 |
+
}
|
| 422 |
+
@@ -394,16 +424,25 @@ func (c *SizedLRU) Unreserve(size int64) error {
|
| 423 |
+
return nil
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
+// removeElement drops an element from the index and queues its file for
|
| 427 |
+
+// removal. It is used both for evictions and for entries whose file was
|
| 428 |
+
+// lost or found to be corrupt; only evictElement counts as an eviction.
|
| 429 |
+
func (c *SizedLRU) removeElement(e *list.Element) {
|
| 430 |
+
c.ll.Remove(e)
|
| 431 |
+
kv := e.Value.(*entry)
|
| 432 |
+
delete(c.cache, kv.key)
|
| 433 |
+
c.currentSize -= roundUp4k(kv.value.sizeOnDisk)
|
| 434 |
+
- c.uncompressedSize -= roundUp4k(kv.value.size)
|
| 435 |
+
- c.counterEvictedBytes.Add(float64(kv.value.sizeOnDisk))
|
| 436 |
+
+ c.uncompressedSize -= kv.value.size
|
| 437 |
+
+ c.gaugeCacheLogicalBytes.Set(float64(c.uncompressedSize))
|
| 438 |
+
c.appendEvictionToQueue(kv)
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
+// evictElement removes an element to make room in a full cache.
|
| 442 |
+
+func (c *SizedLRU) evictElement(e *list.Element) {
|
| 443 |
+
+ c.counterEvictedBytes.Add(float64(e.Value.(*entry).value.sizeOnDisk))
|
| 444 |
+
+ c.removeElement(e)
|
| 445 |
+
+}
|
| 446 |
+
+
|
| 447 |
+
// Round n up to the nearest multiple of BlockSize (4096).
|
| 448 |
+
func roundUp4k(n int64) int64 {
|
| 449 |
+
return (n + BlockSize - 1) & -BlockSize
|
| 450 |
+
|
| 451 |
+
REFERENCE_PATCH
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/task.toml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
artifacts = ["/workspace/submissions/submitted.patch"]
|
| 3 |
+
[metadata]
|
| 4 |
+
task = "bazel_remote_disk_eviction_accounting_contract"
|
| 5 |
+
validation_revision = "coding-rubric-v2"
|
| 6 |
+
[agent]
|
| 7 |
+
timeout_sec = 1800
|
| 8 |
+
user = "1000:1000"
|
| 9 |
+
[environment]
|
| 10 |
+
build_timeout_sec = 1800
|
| 11 |
+
cpus = 2
|
| 12 |
+
memory_mb = 8192
|
| 13 |
+
network_mode = "no-network"
|
| 14 |
+
[verifier]
|
| 15 |
+
timeout_sec = 7200
|
| 16 |
+
user = "0"
|
| 17 |
+
environment_mode = "separate"
|
| 18 |
+
[verifier.environment]
|
| 19 |
+
build_timeout_sec = 1800
|
| 20 |
+
cpus = 2
|
| 21 |
+
memory_mb = 8192
|
| 22 |
+
network_mode = "no-network"
|
| 23 |
+
[[verifier.collect]]
|
| 24 |
+
command = "/opt/task-tools/python -I /opt/task-tools/capture.py"
|
| 25 |
+
user = "0"
|
| 26 |
+
timeout_sec = 900
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-bazel-remote:source-v2
|
| 2 |
+
USER root
|
| 3 |
+
RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
|
| 4 |
+
ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
|
| 5 |
+
RUN rm -f /hud/gold.diff
|
| 6 |
+
COPY verify.py evidence.py config.json test.sh /tests/
|
| 7 |
+
RUN chmod 755 /tests/test.sh
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
CMD ["sleep", "infinity"]
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/config.json
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"revision": "coding-rubric-v2",
|
| 3 |
+
"task_id": "bazel_remote_disk_eviction_accounting_contract",
|
| 4 |
+
"arguments": {},
|
| 5 |
+
"grader_version": "0.6.15",
|
| 6 |
+
"source_image": "ec-swe-bazel-remote:source-v2",
|
| 7 |
+
"source_image_id": "sha256:c1f0073e7b8a86bda5151303cf107f15fc5fda5b5469543413ab37887baf10cf",
|
| 8 |
+
"provenance": {
|
| 9 |
+
"repository": "buchgr/bazel-remote",
|
| 10 |
+
"environment_id": "66517a55-2b44-4cd7-9ff1-3a059e8ccc03",
|
| 11 |
+
"build": 2,
|
| 12 |
+
"build_id": "0e4083f4-d1f1-4e8f-9343-56cdb78655af",
|
| 13 |
+
"hosted_task": "bazel_remote_disk_eviction_accounting_contract-afe5ea56",
|
| 14 |
+
"task_version": 1,
|
| 15 |
+
"source_archive_sha256": "4c42b091fdd5702a54d9a306f14f0e8b774b8daa6e7f81e9021ac8619cf60772",
|
| 16 |
+
"hosted_revision_argument": "not recorded; the scenario does not read it"
|
| 17 |
+
},
|
| 18 |
+
"criteria": [
|
| 19 |
+
[
|
| 20 |
+
"admitted_blob_survives_restart_with_the_same_limits",
|
| 21 |
+
0.27,
|
| 22 |
+
true,
|
| 23 |
+
"bash",
|
| 24 |
+
600
|
| 25 |
+
],
|
| 26 |
+
[
|
| 27 |
+
"admitted_blob_is_kept_despite_stored_form_overhead",
|
| 28 |
+
0.27,
|
| 29 |
+
false,
|
| 30 |
+
"bash",
|
| 31 |
+
600
|
| 32 |
+
],
|
| 33 |
+
[
|
| 34 |
+
"admitted_blob_is_kept_despite_block_rounding_under_concurrent_reservation",
|
| 35 |
+
0.09,
|
| 36 |
+
false,
|
| 37 |
+
"bash",
|
| 38 |
+
600
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
"cache_dir_with_oversized_blob_still_loads_and_discards_it",
|
| 42 |
+
0.09,
|
| 43 |
+
false,
|
| 44 |
+
"bash",
|
| 45 |
+
600
|
| 46 |
+
],
|
| 47 |
+
[
|
| 48 |
+
"logical_size_is_reported_in_plain_bytes",
|
| 49 |
+
0.09,
|
| 50 |
+
false,
|
| 51 |
+
"bash",
|
| 52 |
+
600
|
| 53 |
+
],
|
| 54 |
+
[
|
| 55 |
+
"evicted_bytes_counter_ignores_lost_files",
|
| 56 |
+
0.09,
|
| 57 |
+
false,
|
| 58 |
+
"bash",
|
| 59 |
+
600
|
| 60 |
+
],
|
| 61 |
+
[
|
| 62 |
+
"entry_size_summary_observes_each_entry_size",
|
| 63 |
+
0.09,
|
| 64 |
+
false,
|
| 65 |
+
"bash",
|
| 66 |
+
600
|
| 67 |
+
],
|
| 68 |
+
[
|
| 69 |
+
"gate_repo_suite_green_and_tests_untouched",
|
| 70 |
+
0.01,
|
| 71 |
+
true,
|
| 72 |
+
"bash",
|
| 73 |
+
900
|
| 74 |
+
]
|
| 75 |
+
],
|
| 76 |
+
"gates": [],
|
| 77 |
+
"reward_rule": "weighted_cap",
|
| 78 |
+
"local_hostname": false,
|
| 79 |
+
"fault_exit": 3,
|
| 80 |
+
"grader_readable": [],
|
| 81 |
+
"grader_writable": [],
|
| 82 |
+
"blocker_cap": 0.6,
|
| 83 |
+
"empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
|
| 84 |
+
"verifier_files": {
|
| 85 |
+
"/app/env.py": "2ba1517a839fd7b38b3f9e701ef4741351e3b3c3f577eb4a56a65946ffc956c5",
|
| 86 |
+
"/app/tasks.py": "d7e4325c619978a106a8a61e30b8db95e9aa25ce10e234c0479ee317916bbe47",
|
| 87 |
+
"/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
|
| 88 |
+
"/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
|
| 89 |
+
"/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
|
| 90 |
+
"/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
|
| 91 |
+
"/app/task/prompt.md": "9518d37eeeed2f588b5dc636f6588283863f56f975aa9af9df3281316065b8dd",
|
| 92 |
+
"/hud/grader/run_grading.sh": "344e3b6df0af414c9a49287a333e2d79ed25da263dccc76718bc6dc15c0d1448",
|
| 93 |
+
"/hud/grader/controls/alt.diff": "43162609826d241f9faf52830f446f4bc6d78b67b0ff8d6bcb9c4a22855ad2d0",
|
| 94 |
+
"/hud/grader/controls/cheat.diff": "9dbe991b917ff847efea11cb31dff05ad9a6df9f1f0c9c1cfaffb60535312722",
|
| 95 |
+
"/hud/grader/controls/lazy.diff": "2a15431225ec43bf4b70ea490ee83669886f455da71a3ab6ed01f47c7a4d915f",
|
| 96 |
+
"/hud/grader/harness/suite_gate.py": "c2fe01b49f83cf4d28ee0ab36b42285f2e6c205ca45003d82a9d3d29c5b36b8d",
|
| 97 |
+
"/hud/grader/harness/spec/cells_test.go": "de51528d91ed7b44452861c036e782a66df838bfbc6748abccaed1ab704cf195"
|
| 98 |
+
},
|
| 99 |
+
"preflight": [
|
| 100 |
+
[
|
| 101 |
+
"/bin/bash",
|
| 102 |
+
"--version"
|
| 103 |
+
],
|
| 104 |
+
[
|
| 105 |
+
"setpriv",
|
| 106 |
+
"--version"
|
| 107 |
+
],
|
| 108 |
+
[
|
| 109 |
+
"git",
|
| 110 |
+
"--version"
|
| 111 |
+
],
|
| 112 |
+
[
|
| 113 |
+
"bash",
|
| 114 |
+
"-c",
|
| 115 |
+
"bash -lc 'go version' || go version"
|
| 116 |
+
],
|
| 117 |
+
[
|
| 118 |
+
"/usr/local/bin/python3",
|
| 119 |
+
"--version"
|
| 120 |
+
]
|
| 121 |
+
]
|
| 122 |
+
}
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/docker-compose.yaml
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
services:
|
| 2 |
+
main:
|
| 3 |
+
network_mode: none
|
| 4 |
+
pids_limit: 512
|
| 5 |
+
security_opt:
|
| 6 |
+
- no-new-privileges:true
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/evidence.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Validate complete coding-rubric evidence without importing the grader library or Harbor."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import math
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
REVISION = "coding-rubric-v2"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _number(value: Any) -> float:
|
| 12 |
+
if isinstance(value, bool) or not isinstance(value, (float, int)):
|
| 13 |
+
raise ValueError("Expected numeric rubric evidence")
|
| 14 |
+
if not math.isfinite(value) or not 0 <= value <= 1:
|
| 15 |
+
raise ValueError("Rubric values must be finite and within [0, 1]")
|
| 16 |
+
return float(value)
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def validate_report(report: dict[str, Any], config: dict[str, Any], digest: str) -> None:
|
| 20 |
+
"""Check provenance, criterion coverage, weights, caps and command outcomes.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
report, config : dict
|
| 25 |
+
Fresh verifier evidence and the trusted prepared task configuration.
|
| 26 |
+
digest : str
|
| 27 |
+
SHA-256 of the submission collected by Harbor.
|
| 28 |
+
|
| 29 |
+
Raises
|
| 30 |
+
------
|
| 31 |
+
ValueError
|
| 32 |
+
If evidence is missing, inconsistent or reports infrastructure failure.
|
| 33 |
+
"""
|
| 34 |
+
if (
|
| 35 |
+
report.get("revision") != REVISION
|
| 36 |
+
or report.get("task_id") != config["task_id"]
|
| 37 |
+
or report.get("patch_sha256") != digest
|
| 38 |
+
or report.get("grader_version") != config["grader_version"]
|
| 39 |
+
):
|
| 40 |
+
raise ValueError("Verifier evidence provenance mismatch")
|
| 41 |
+
result = report.get("result", {})
|
| 42 |
+
reward = _number(result.get("reward"))
|
| 43 |
+
# A rubric may flag its own result when a grader could not judge. That is
|
| 44 |
+
# admitted only together with proof, checked below, that the same grader
|
| 45 |
+
# reaches a verdict on the untouched repository.
|
| 46 |
+
fault_exit = config.get("fault_exit")
|
| 47 |
+
faults = {
|
| 48 |
+
row["name"]
|
| 49 |
+
for row in report.get("commands", [])
|
| 50 |
+
if fault_exit is not None and (row.get("info") or {}).get("exit_code") == fault_exit
|
| 51 |
+
}
|
| 52 |
+
flagged = result.get("isError", False)
|
| 53 |
+
if (flagged and not faults) or result.get("done", True) is not True:
|
| 54 |
+
raise ValueError("Grader returned an incomplete or failed evaluation")
|
| 55 |
+
status = report.get("status")
|
| 56 |
+
if status == "rejected_patch":
|
| 57 |
+
if reward != 0 or not report.get("patch_error") or result.get("subscores"):
|
| 58 |
+
raise ValueError("Invalid rejected-patch evidence")
|
| 59 |
+
return
|
| 60 |
+
if status == "empty_patch":
|
| 61 |
+
credited = any(_number(row["value"]) for row in result.get("subscores") or [])
|
| 62 |
+
if reward != 0 or digest != config["empty_sha256"] or report.get("commands") or credited:
|
| 63 |
+
raise ValueError("Invalid empty-patch evidence")
|
| 64 |
+
return
|
| 65 |
+
if status != "graded":
|
| 66 |
+
raise ValueError("Verifier did not complete")
|
| 67 |
+
scores = result.get("subscores")
|
| 68 |
+
expected = {row[0]: row for row in config["criteria"]}
|
| 69 |
+
if not isinstance(scores, list) or len(scores) != len(expected):
|
| 70 |
+
raise ValueError("Missing rubric criteria")
|
| 71 |
+
names = [row["name"] for row in scores]
|
| 72 |
+
if len(set(names)) != len(names) or set(names) != set(expected):
|
| 73 |
+
raise ValueError("Duplicate or unexpected rubric criteria")
|
| 74 |
+
raw = 0.0
|
| 75 |
+
values = {}
|
| 76 |
+
for score in scores:
|
| 77 |
+
name = score["name"]
|
| 78 |
+
value, weight = _number(score["value"]), _number(score["weight"])
|
| 79 |
+
if not math.isclose(weight, expected[name][1], abs_tol=1e-12):
|
| 80 |
+
raise ValueError("Criterion weights changed")
|
| 81 |
+
raw += value * weight
|
| 82 |
+
values[name] = value
|
| 83 |
+
commands = report.get("commands", [])
|
| 84 |
+
command_names = [row["name"] for row in commands]
|
| 85 |
+
expected_commands = set(expected) | set(config["gates"])
|
| 86 |
+
if len(command_names) != len(set(command_names)) or set(command_names) != expected_commands:
|
| 87 |
+
raise ValueError("Missing or duplicate grader command evidence")
|
| 88 |
+
for command in commands:
|
| 89 |
+
info = command.get("info") or {}
|
| 90 |
+
code = info.get("exit_code")
|
| 91 |
+
verdict = type(code) is int and (code in (0, 1) or command["name"] in faults)
|
| 92 |
+
if not verdict or info.get("timed_out"):
|
| 93 |
+
raise ValueError("Grader command failed outside its verdict contract")
|
| 94 |
+
if _number(command["value"]) != float(code == 0):
|
| 95 |
+
raise ValueError("Command exit code disagrees with score")
|
| 96 |
+
probes = {row["name"]: row for row in report.get("fault_probes") or []}
|
| 97 |
+
if set(probes) != faults or any(
|
| 98 |
+
row.get("timed_out") or row.get("exit_code") not in (0, 1) for row in probes.values()
|
| 99 |
+
):
|
| 100 |
+
raise ValueError(
|
| 101 |
+
"A grader could not judge and the untouched repository does not explain it"
|
| 102 |
+
)
|
| 103 |
+
if any(values.get(name, 0) for name in faults):
|
| 104 |
+
raise ValueError("A criterion its grader could not judge is credited")
|
| 105 |
+
info = result.get("info") or {}
|
| 106 |
+
if info.get("aggregate_mismatch") or info.get("git_apply"):
|
| 107 |
+
raise ValueError("Grader reported inconsistent grading")
|
| 108 |
+
if config.get("reward_rule") == "authored":
|
| 109 |
+
# The task's own function decides the reward. It may take credit away
|
| 110 |
+
# (a cap, a criterion that pays only with progress) but never add any.
|
| 111 |
+
passed = {row["name"]: row["value"] for row in commands}
|
| 112 |
+
if any(values[name] > passed[name] for name in expected):
|
| 113 |
+
raise ValueError("A criterion is credited although its command failed")
|
| 114 |
+
if reward > raw + 1e-9:
|
| 115 |
+
raise ValueError("Grader reward exceeds its weighted criteria")
|
| 116 |
+
return
|
| 117 |
+
failed = {name for name, row in expected.items() if row[2] and values[name] < 1}
|
| 118 |
+
gate_failed = {
|
| 119 |
+
row["name"] for row in commands if row["name"] in config["gates"] and row["value"] < 1
|
| 120 |
+
}
|
| 121 |
+
expected_reward = min(raw, config["blocker_cap"]) if failed or gate_failed else raw
|
| 122 |
+
if not math.isclose(reward, expected_reward, abs_tol=1e-9):
|
| 123 |
+
raise ValueError("Grader reward disagrees with original weights and blocker cap")
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/test.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -euo pipefail
|
| 3 |
+
/opt/hudvenv/bin/python /tests/verify.py
|
harbor/tasks/bazel_remote_disk_eviction_accounting_contract/tests/verify.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the original trusted coding rubric in a fresh, offline verifier container."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import hashlib
|
| 7 |
+
import importlib
|
| 8 |
+
import importlib.metadata
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import shlex
|
| 12 |
+
import shutil
|
| 13 |
+
import signal
|
| 14 |
+
import subprocess
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
from typing import Any
|
| 18 |
+
|
| 19 |
+
from evidence import REVISION, validate_report
|
| 20 |
+
|
| 21 |
+
OUT = Path("/logs/verifier")
|
| 22 |
+
PRIVATE = Path("/var/lib/task-evidence")
|
| 23 |
+
CONFIG = Path("/tests/config.json")
|
| 24 |
+
PATCH = Path("/workspace/submissions/submitted.patch")
|
| 25 |
+
GRADER_HOME = "/tmp/agent-home"
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
|
| 29 |
+
return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _preflight(config: dict[str, Any]) -> None:
|
| 33 |
+
if importlib.metadata.version("hud") != config["grader_version"]:
|
| 34 |
+
raise RuntimeError("Grader library version does not match the task")
|
| 35 |
+
for filename, expected in config["verifier_files"].items():
|
| 36 |
+
if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
|
| 37 |
+
raise RuntimeError(f"Verifier source changed: {filename}")
|
| 38 |
+
for command in config["preflight"]:
|
| 39 |
+
completed = _run(command, cwd="/workspace/repo")
|
| 40 |
+
if completed.returncode:
|
| 41 |
+
raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _readable_mode(path: Path) -> int:
|
| 45 |
+
# World-readable, keeping what is executable so: a grader may ship tools.
|
| 46 |
+
return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _permissions() -> None:
|
| 50 |
+
# The orchestrator owns reports and rubric definitions. Grader commands,
|
| 51 |
+
# and so the candidate's code, run as uid 1000: the user the task installed
|
| 52 |
+
# its toolchain and caches for. They cannot read gold/vault or overwrite
|
| 53 |
+
# the rubric or the result files, which stay root's.
|
| 54 |
+
Path("/hud").chmod(0o711)
|
| 55 |
+
for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
|
| 56 |
+
if root.exists():
|
| 57 |
+
root.chmod(0o755)
|
| 58 |
+
for path in root.rglob("*"):
|
| 59 |
+
if not path.is_symlink():
|
| 60 |
+
path.chmod(_readable_mode(path))
|
| 61 |
+
home = Path(GRADER_HOME)
|
| 62 |
+
home.mkdir(parents=True, exist_ok=True)
|
| 63 |
+
os.chown(home, 1000, 1000)
|
| 64 |
+
for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
|
| 65 |
+
path = Path(directory)
|
| 66 |
+
path.mkdir(parents=True, exist_ok=True)
|
| 67 |
+
for item in (path, *path.rglob("*")):
|
| 68 |
+
if not item.is_symlink():
|
| 69 |
+
os.chown(item, 1000, 1000)
|
| 70 |
+
item.chmod(_readable_mode(item))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _hand_over_checkout() -> None:
|
| 74 |
+
# The original grader runs as root and may run the candidate's own suite in
|
| 75 |
+
# place, which writes into the tree. The rubric resets and re-applies the
|
| 76 |
+
# candidate as root, so give what root touched back to the grading user.
|
| 77 |
+
# Installed dependency trees are large and already that user's.
|
| 78 |
+
subprocess.run(
|
| 79 |
+
[
|
| 80 |
+
"find",
|
| 81 |
+
"/workspace/repo",
|
| 82 |
+
"-path",
|
| 83 |
+
"*/node_modules",
|
| 84 |
+
"-prune",
|
| 85 |
+
"-o",
|
| 86 |
+
"!",
|
| 87 |
+
"-user",
|
| 88 |
+
"1000",
|
| 89 |
+
"-exec",
|
| 90 |
+
"chown",
|
| 91 |
+
"-h",
|
| 92 |
+
"1000:1000",
|
| 93 |
+
"{}",
|
| 94 |
+
"+",
|
| 95 |
+
],
|
| 96 |
+
check=True,
|
| 97 |
+
capture_output=True,
|
| 98 |
+
timeout=3600,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
|
| 103 |
+
_preflight(config)
|
| 104 |
+
sys.path.insert(0, "/app")
|
| 105 |
+
task: Any = importlib.import_module("tasks")
|
| 106 |
+
await task._setup()
|
| 107 |
+
_permissions()
|
| 108 |
+
patch = PATCH.read_bytes()
|
| 109 |
+
if patch:
|
| 110 |
+
checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
|
| 111 |
+
if checked.returncode:
|
| 112 |
+
record.update(
|
| 113 |
+
status="rejected_patch",
|
| 114 |
+
patch_error=checked.stderr[-4000:],
|
| 115 |
+
result={"reward": 0.0, "subscores": None},
|
| 116 |
+
)
|
| 117 |
+
return
|
| 118 |
+
_run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
|
| 119 |
+
original = task.BashGrader
|
| 120 |
+
fault_exit = config.get("fault_exit")
|
| 121 |
+
faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []
|
| 122 |
+
|
| 123 |
+
class ObservedGrader:
|
| 124 |
+
@classmethod
|
| 125 |
+
async def grade(cls, *args: Any, **kwargs: Any) -> Any:
|
| 126 |
+
command = kwargs["command"]
|
| 127 |
+
_hand_over_checkout()
|
| 128 |
+
kwargs["command"] = (
|
| 129 |
+
"setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
|
| 130 |
+
f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
|
| 131 |
+
)
|
| 132 |
+
score = await original.grade(*args, **kwargs)
|
| 133 |
+
snapshot = score.model_dump(mode="json")
|
| 134 |
+
record["commands"].append(snapshot)
|
| 135 |
+
(PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
|
| 136 |
+
info = snapshot.get("info") or {}
|
| 137 |
+
if info.get("timed_out") or type(info.get("exit_code")) is not int:
|
| 138 |
+
raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
|
| 139 |
+
if fault_exit is not None and info["exit_code"] == fault_exit:
|
| 140 |
+
# The grader says it could not judge. Whether the submission or
|
| 141 |
+
# the environment is the reason is settled after grading.
|
| 142 |
+
faulted.append((args, dict(kwargs), snapshot["name"]))
|
| 143 |
+
elif info["exit_code"] not in (0, 1):
|
| 144 |
+
raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
|
| 145 |
+
return score
|
| 146 |
+
|
| 147 |
+
task.BashGrader = ObservedGrader
|
| 148 |
+
result = await task._grade(None)
|
| 149 |
+
if faulted:
|
| 150 |
+
# Ask the same commands about the untouched repository. A verdict there
|
| 151 |
+
# means the grader works here and the submission is what it could not
|
| 152 |
+
# judge, so the criterion stays unmet. No verdict there means the
|
| 153 |
+
# environment is at fault, and the attempt is invalid.
|
| 154 |
+
await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
|
| 155 |
+
await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
|
| 156 |
+
# Graders keep state between criteria, some of them a copy of the tree
|
| 157 |
+
# they judged. It describes the submission, so it goes too.
|
| 158 |
+
for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
|
| 159 |
+
if leftover.is_dir() and not leftover.is_symlink():
|
| 160 |
+
shutil.rmtree(leftover)
|
| 161 |
+
else:
|
| 162 |
+
leftover.unlink()
|
| 163 |
+
record["fault_probes"] = []
|
| 164 |
+
for args, kwargs, name in faulted:
|
| 165 |
+
_hand_over_checkout()
|
| 166 |
+
probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
|
| 167 |
+
info = probe.get("info") or {}
|
| 168 |
+
record["fault_probes"].append(
|
| 169 |
+
{
|
| 170 |
+
"name": name,
|
| 171 |
+
"exit_code": info.get("exit_code"),
|
| 172 |
+
"timed_out": info.get("timed_out"),
|
| 173 |
+
"stdout": (info.get("stdout") or "")[-2000:],
|
| 174 |
+
}
|
| 175 |
+
)
|
| 176 |
+
(PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
|
| 177 |
+
if info.get("timed_out") or info.get("exit_code") not in (0, 1):
|
| 178 |
+
raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
|
| 179 |
+
record["result"] = result.model_dump(mode="json")
|
| 180 |
+
# A rubric may answer an empty change without running any criterion.
|
| 181 |
+
record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _stop_candidate_processes() -> None:
|
| 185 |
+
# A candidate may fork. End its UID's processes before publishing evidence
|
| 186 |
+
# to a host bind mount, whose permissions may differ on Docker Desktop.
|
| 187 |
+
for directory in Path("/proc").iterdir():
|
| 188 |
+
if not directory.name.isdecimal():
|
| 189 |
+
continue
|
| 190 |
+
try:
|
| 191 |
+
status = (directory / "status").read_text()
|
| 192 |
+
uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
|
| 193 |
+
if uid == "1000":
|
| 194 |
+
os.kill(int(directory.name), signal.SIGKILL)
|
| 195 |
+
except (FileNotFoundError, ProcessLookupError):
|
| 196 |
+
pass
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def main() -> None:
|
| 200 |
+
"""Persist structured evidence and publish reward only after validation."""
|
| 201 |
+
OUT.mkdir(parents=True, exist_ok=True)
|
| 202 |
+
PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
|
| 203 |
+
PRIVATE.chmod(0o700)
|
| 204 |
+
reward_path = OUT / "reward.txt"
|
| 205 |
+
reward_path.unlink(missing_ok=True)
|
| 206 |
+
config = json.loads(CONFIG.read_text())
|
| 207 |
+
shutil.copy2(CONFIG, OUT / "config.json")
|
| 208 |
+
record: dict[str, Any] = {
|
| 209 |
+
"revision": REVISION,
|
| 210 |
+
"task_id": config["task_id"],
|
| 211 |
+
"grader_version": importlib.metadata.version("hud"),
|
| 212 |
+
"commands": [],
|
| 213 |
+
"status": "error",
|
| 214 |
+
}
|
| 215 |
+
try:
|
| 216 |
+
if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
|
| 217 |
+
raise ValueError("Missing, oversized or symlink submission")
|
| 218 |
+
record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
|
| 219 |
+
try:
|
| 220 |
+
asyncio.run(_grade(config, record))
|
| 221 |
+
finally:
|
| 222 |
+
_stop_candidate_processes()
|
| 223 |
+
reward_path.unlink(missing_ok=True)
|
| 224 |
+
validate_report(record, config, record["patch_sha256"])
|
| 225 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 226 |
+
reward_path.write_text(str(record["result"]["reward"]) + "\n")
|
| 227 |
+
except BaseException as error:
|
| 228 |
+
reward_path.unlink(missing_ok=True)
|
| 229 |
+
record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
|
| 230 |
+
(OUT / "report.json").write_text(json.dumps(record, indent=2))
|
| 231 |
+
raise
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
if __name__ == "__main__":
|
| 235 |
+
main()
|
harbor/tasks/manifest.json
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
{
|
| 2 |
"revision": "coding-rubric-v2",
|
| 3 |
"tasks": [
|
|
|
|
| 4 |
"celery_retry_expires_countdown_contract",
|
| 5 |
"coredns_rewrite_svcb_opt",
|
| 6 |
"epicyon_deleted_post_announce_cache_contract",
|
|
|
|
| 1 |
{
|
| 2 |
"revision": "coding-rubric-v2",
|
| 3 |
"tasks": [
|
| 4 |
+
"bazel_remote_disk_eviction_accounting_contract",
|
| 5 |
"celery_retry_expires_countdown_contract",
|
| 6 |
"coredns_rewrite_svcb_opt",
|
| 7 |
"epicyon_deleted_post_announce_cache_contract",
|