servicesToptal commited on
Commit
117149d
·
verified ·
1 Parent(s): dd83844

Update dataset (part 5)

Browse files
Files changed (46) hide show
  1. README.md +7 -17
  2. harbor/tasks/mongoose_syncindexes_contract/environment/Dockerfile +20 -0
  3. harbor/tasks/mongoose_syncindexes_contract/environment/capture.py +28 -0
  4. harbor/tasks/mongoose_syncindexes_contract/environment/capture_submission.py +157 -0
  5. harbor/tasks/mongoose_syncindexes_contract/environment/docker-compose.yaml +15 -0
  6. harbor/tasks/mongoose_syncindexes_contract/environment/sanitize.py +25 -0
  7. harbor/tasks/mongoose_syncindexes_contract/instruction.md +18 -0
  8. harbor/tasks/mongoose_syncindexes_contract/solution/reference.patch +564 -0
  9. harbor/tasks/mongoose_syncindexes_contract/solution/solve.sh +570 -0
  10. harbor/tasks/mongoose_syncindexes_contract/task.toml +26 -0
  11. harbor/tasks/mongoose_syncindexes_contract/tests/Dockerfile +11 -0
  12. harbor/tasks/mongoose_syncindexes_contract/tests/config.json +229 -0
  13. harbor/tasks/mongoose_syncindexes_contract/tests/docker-compose.yaml +10 -0
  14. harbor/tasks/mongoose_syncindexes_contract/tests/evidence.py +123 -0
  15. harbor/tasks/mongoose_syncindexes_contract/tests/test.sh +3 -0
  16. harbor/tasks/mongoose_syncindexes_contract/tests/verify.py +235 -0
  17. harbor/tasks/open_xml_sdk_deletepart_refs_contract/environment/Dockerfile +21 -0
  18. harbor/tasks/open_xml_sdk_deletepart_refs_contract/environment/capture.py +28 -0
  19. harbor/tasks/open_xml_sdk_deletepart_refs_contract/environment/capture_submission.py +157 -0
  20. harbor/tasks/open_xml_sdk_deletepart_refs_contract/environment/docker-compose.yaml +11 -0
  21. harbor/tasks/open_xml_sdk_deletepart_refs_contract/environment/sanitize.py +25 -0
  22. harbor/tasks/open_xml_sdk_deletepart_refs_contract/instruction.md +7 -0
  23. harbor/tasks/open_xml_sdk_deletepart_refs_contract/solution/reference.patch +313 -0
  24. harbor/tasks/open_xml_sdk_deletepart_refs_contract/solution/solve.sh +319 -0
  25. harbor/tasks/open_xml_sdk_deletepart_refs_contract/task.toml +26 -0
  26. harbor/tasks/open_xml_sdk_deletepart_refs_contract/tests/Dockerfile +15 -0
  27. harbor/tasks/open_xml_sdk_deletepart_refs_contract/tests/config.json +135 -0
  28. harbor/tasks/open_xml_sdk_deletepart_refs_contract/tests/docker-compose.yaml +6 -0
  29. harbor/tasks/open_xml_sdk_deletepart_refs_contract/tests/evidence.py +123 -0
  30. harbor/tasks/open_xml_sdk_deletepart_refs_contract/tests/test.sh +3 -0
  31. harbor/tasks/open_xml_sdk_deletepart_refs_contract/tests/verify.py +235 -0
  32. harbor/tasks/proxy_cookie_accounting/environment/Dockerfile +24 -0
  33. harbor/tasks/proxy_cookie_accounting/environment/capture.py +28 -0
  34. harbor/tasks/proxy_cookie_accounting/environment/capture_submission.py +157 -0
  35. harbor/tasks/proxy_cookie_accounting/environment/docker-compose.yaml +11 -0
  36. harbor/tasks/proxy_cookie_accounting/environment/sanitize.py +25 -0
  37. harbor/tasks/proxy_cookie_accounting/instruction.md +11 -0
  38. harbor/tasks/proxy_cookie_accounting/solution/reference.patch +196 -0
  39. harbor/tasks/proxy_cookie_accounting/solution/solve.sh +202 -0
  40. harbor/tasks/proxy_cookie_accounting/task.toml +26 -0
  41. harbor/tasks/proxy_cookie_accounting/tests/Dockerfile +9 -0
  42. harbor/tasks/proxy_cookie_accounting/tests/config.json +164 -0
  43. harbor/tasks/proxy_cookie_accounting/tests/docker-compose.yaml +6 -0
  44. harbor/tasks/proxy_cookie_accounting/tests/evidence.py +123 -0
  45. harbor/tasks/proxy_cookie_accounting/tests/test.sh +3 -0
  46. harbor/tasks/proxy_cookie_accounting/tests/verify.py +235 -0
README.md CHANGED
@@ -245,8 +245,7 @@ Harbor on your own machine.
245
 
246
  ### On HUD
247
 
248
- Every task runs on HUD, including the ones that have no Harbor package. The tasks are
249
- published there as the taskset [`ec-swe`](https://www.hud.ai/shared/tasksets/979e6e02-d726-46f6-a066-914afc5c9f44),
250
  which anyone can view; it holds all 24.
251
 
252
  To run a task in a HUD workspace of your own: each folder under `harbor/sources/` is the build
@@ -264,16 +263,15 @@ hud eval my-ec-swe claude --full # runs it on the platform with an agent
264
 
265
  Results appear as jobs and traces on hud.ai (`hud jobs`). On HUD the agent and the grader
266
  share one container, kept apart by file permissions, and the four tasks with a criterion
267
- judged by a model get that judge from HUD's gateway. The commands follow HUD's
268
- documentation. We deployed twenty-two of the folders this way ourselves and synced the task of
269
- every folder into the taskset above; we have not run an agent with `hud eval` from this
270
- folder.
271
 
272
  ### With Harbor
273
 
274
  The `harbor/` folder of this repository makes tasks runnable end
275
  to end with [Harbor](https://github.com/harbor-framework/harbor) 0.23.0 and
276
- Docker, and nothing else. Each task is packaged as two containers: one for the
277
  agent, holding the repository at its base commit and nothing from the grading
278
  side, and a separate one that grades the patch the agent leaves behind with the
279
  task's original grader. Both are offline by default. The folder holds each
@@ -290,18 +288,10 @@ harbor run -p tasks/<task folder> -a nop # no change: reward 0.0
290
  harbor run -p tasks/<task folder> -a <agent> -m <model> --allow-agent-host <model API host>
291
  ```
292
 
293
- `harbor/README.md` has the requirements, a table that maps each task folder to
294
- its `instance_id` here, the scripted checks, and what was recorded for each
295
- task. Every packaged task was run through Harbor on the files in the folder: an
296
- 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
- Five tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
302
- is judged by a model) and Babylon.js. The folder holds the complete build context of each,
303
- and `harbor/README.md` says for each how it is built and graded and what it needs.
304
-
305
  ## Dataset Creation
306
 
307
  ### Curation Rationale
 
245
 
246
  ### On HUD
247
 
248
+ The tasks are published there as the taskset [`ec-swe`](https://www.hud.ai/shared/tasksets/979e6e02-d726-46f6-a066-914afc5c9f44),
 
249
  which anyone can view; it holds all 24.
250
 
251
  To run a task in a HUD workspace of your own: each folder under `harbor/sources/` is the build
 
263
 
264
  Results appear as jobs and traces on hud.ai (`hud jobs`). On HUD the agent and the grader
265
  share one container, kept apart by file permissions, and the four tasks with a criterion
266
+ judged by a model get that judge from HUD's gateway. Outside HUD, that judge can
267
+ run on your own key at any OpenAI-compatible endpoint, such as OpenRouter; `harbor/README.md`
268
+ says how. The commands follow HUD's documentation.
 
269
 
270
  ### With Harbor
271
 
272
  The `harbor/` folder of this repository makes tasks runnable end
273
  to end with [Harbor](https://github.com/harbor-framework/harbor) 0.23.0 and
274
+ Docker, and nothing else. Each task under `harbor/tasks/` is packaged as two containers: one for the
275
  agent, holding the repository at its base commit and nothing from the grading
276
  side, and a separate one that grades the patch the agent leaves behind with the
277
  task's original grader. Both are offline by default. The folder holds each
 
288
  harbor run -p tasks/<task folder> -a <agent> -m <model> --allow-agent-host <model API host>
289
  ```
290
 
291
+ `harbor/README.md` has the requirements and a table that maps each task folder to
292
+ its `instance_id` here. The folder contains the reference fixes
 
 
 
293
  and the hidden graders, as the rows of this dataset do.
294
 
 
 
 
 
 
295
  ## Dataset Creation
296
 
297
  ### Curation Rationale
harbor/tasks/mongoose_syncindexes_contract/environment/Dockerfile ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-mongoose:source-v10 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/node/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
8
+ ENV LANG="C.UTF-8"
9
+ ENV NODE_OPTIONS="--max-old-space-size=4096"
10
+ ENV MONGOMS_VERSION="8.0.30"
11
+ ENV MONGOMS_SYSTEM_BINARY="/usr/local/bin/mongod"
12
+ ENV DO_NOT_TRACK="1"
13
+ ENV MONGOMS_DISABLE_POSTINSTALL="1"
14
+ ENV HOME="/tmp/agent-home"
15
+ ENV GOCACHE="/tmp/agent-home/.cache/go-build"
16
+ ENV HUD_TELEMETRY_ENABLED="false"
17
+ ENV HUD_CLI_ANALYTICS_ENABLED="0"
18
+ WORKDIR /workspace/repo
19
+ USER 1000:1000
20
+ CMD ["sleep", "infinity"]
harbor/tasks/mongoose_syncindexes_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/mongoose_syncindexes_contract/environment/capture_submission.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture tracked and new SWE files without changing the agent's Git index."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import os
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/mongoose_syncindexes_contract/environment/docker-compose.yaml ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ pids_limit: 512
4
+ ulimits:
5
+ nofile:
6
+ soft: 1048576
7
+ hard: 1048576
8
+ security_opt:
9
+ - no-new-privileges:true
10
+ volumes:
11
+ - type: tmpfs
12
+ target: /logs/verifier
13
+ tmpfs:
14
+ mode: 448
15
+ size: 1048576
harbor/tasks/mongoose_syncindexes_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/mongoose_syncindexes_contract/instruction.md ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ # Ticket
4
+
5
+ After a deploy we synced every model and ran a dry run to confirm nothing was left to do.
6
+ The dry run still listed work, and the next sync rebuilt indexes that already matched,
7
+ unique:false ones among them, while leaving the collection's own values in place of
8
+ options a schema spells out and of the defaults it sets for the collection; options no
9
+ schema declares had survived the sync too, parts an option leaves unstated had settled on
10
+ something other than the server's pick, and here and there an index a schema asks for, not
11
+ always one of the same kind, had not been built at all. On a collection two models share
12
+ it went further: whichever of them had synced, an index the schemas ask for was not there
13
+ afterwards. An option a schema states, even as false, is not one it leaves out, and an
14
+ index the collection already shares between models stays shared. The test files the
15
+ repository ships stay byte-for-byte as they are and green; tests of your own go in new
16
+ files.
17
+
18
+ Finish with a final response when your changes are ready.
harbor/tasks/mongoose_syncindexes_contract/solution/reference.patch ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/lib/helpers/indexes/applySchemaCollation.js b/lib/helpers/indexes/applySchemaCollation.js
2
+ index 464210e..f58d0ea 100644
3
+ --- a/lib/helpers/indexes/applySchemaCollation.js
4
+ +++ b/lib/helpers/indexes/applySchemaCollation.js
5
+ @@ -3,11 +3,17 @@
6
+ const isTextIndex = require('./isTextIndex');
7
+
8
+ module.exports = function applySchemaCollation(indexKeys, indexOptions, schemaOptions) {
9
+ - if (isTextIndex(indexKeys)) {
10
+ + if (!Object.hasOwn(schemaOptions, 'collation') || Object.hasOwn(indexOptions, 'collation')) {
11
+ return;
12
+ }
13
+
14
+ - if (Object.hasOwn(schemaOptions, 'collation') && !Object.hasOwn(indexOptions, 'collation')) {
15
+ - indexOptions.collation = schemaOptions.collation;
16
+ + if (isTextIndex(indexKeys) || Object.values(indexKeys).includes('2d')) {
17
+ + // Text and 2d indexes only support simple binary comparison. The
18
+ + // schema-level collation becomes the collection's default collation, which
19
+ + // such an index would otherwise inherit and fail to build with.
20
+ + indexOptions.collation = { locale: 'simple' };
21
+ + return;
22
+ }
23
+ +
24
+ + indexOptions.collation = schemaOptions.collation;
25
+ };
26
+ diff --git a/lib/helpers/indexes/getRelatedIndexes.js b/lib/helpers/indexes/getRelatedIndexes.js
27
+ index e68cb8d..66efcc0 100644
28
+ --- a/lib/helpers/indexes/getRelatedIndexes.js
29
+ +++ b/lib/helpers/indexes/getRelatedIndexes.js
30
+ @@ -1,23 +1,54 @@
31
+ 'use strict';
32
+
33
+ const hasDollarKeys = require('../query/hasDollarKeys');
34
+ +const isIndexEqual = require('./isIndexEqual');
35
+ +const utils = require('../../utils');
36
+
37
+ function getRelatedSchemaIndexes(model, schemaIndexes) {
38
+ - return getRelatedIndexes({
39
+ + const related = getRelatedIndexes({
40
+ baseModelName: model.baseModelName,
41
+ discriminatorMapping: model.schema.discriminatorMapping,
42
+ indexes: schemaIndexes,
43
+ indexesType: 'schema'
44
+ });
45
+ + const owned = unfilterableIndexesOf(model, schemaIndexes);
46
+ + if (owned.length === 0) {
47
+ + return related;
48
+ + }
49
+ + return schemaIndexes.filter(index => related.includes(index) || owned.includes(index));
50
+ }
51
+
52
+ function getRelatedDBIndexes(model, dbIndexes) {
53
+ - return getRelatedIndexes({
54
+ + const related = getRelatedIndexes({
55
+ baseModelName: model.baseModelName,
56
+ discriminatorMapping: model.schema.discriminatorMapping,
57
+ indexes: dbIndexes,
58
+ indexesType: 'db'
59
+ });
60
+ + if (!model.schema.discriminatorMapping?.key) {
61
+ + return related;
62
+ + }
63
+ +
64
+ + // MongoDB rejects `sparse` together with `partialFilterExpression`, so an
65
+ + // index a discriminator declares sparse carries no discriminator filter and
66
+ + // cannot be recognized by one. It belongs to the discriminator whose schema
67
+ + // declares it: to that discriminator's own sync, and to nobody else's.
68
+ + if (isChildDiscriminator(model)) {
69
+ + const owned = unfilterableIndexesOf(model, model.schema.indexes());
70
+ + if (owned.length === 0) {
71
+ + return related;
72
+ + }
73
+ + return dbIndexes.filter(dbIndex => related.includes(dbIndex) || matchesAny(owned, dbIndex));
74
+ + }
75
+ +
76
+ + const ownedByDiscriminators = [];
77
+ + for (const discriminator of Object.values(model.discriminators || {})) {
78
+ + ownedByDiscriminators.push(...unfilterableIndexesOf(discriminator, discriminator.schema.indexes()));
79
+ + }
80
+ + if (ownedByDiscriminators.length === 0) {
81
+ + return related;
82
+ + }
83
+ + return related.filter(dbIndex => !matchesAny(ownedByDiscriminators, dbIndex));
84
+ }
85
+
86
+ module.exports = {
87
+ @@ -25,6 +56,37 @@ module.exports = {
88
+ getRelatedDBIndexes
89
+ };
90
+
91
+ +function isChildDiscriminator(model) {
92
+ + return Boolean(model.baseModelName) && Boolean(model.schema.discriminatorMapping?.key);
93
+ +}
94
+ +
95
+ +function matchesAny(schemaIndexes, dbIndex) {
96
+ + return schemaIndexes.some(([keys, options]) => isIndexEqual(keys, options, dbIndex));
97
+ +}
98
+ +
99
+ +/*!
100
+ + * The indexes `model` declares that no discriminator filter can be attached to,
101
+ + * so `getRelatedIndexes()` cannot see whose they are: the sparse ones this
102
+ + * discriminator's schema adds to the schema it inherits from.
103
+ + */
104
+ +
105
+ +function unfilterableIndexesOf(model, schemaIndexes) {
106
+ + if (!isChildDiscriminator(model)) {
107
+ + return [];
108
+ + }
109
+ + const discriminatorKey = model.schema.discriminatorMapping.key;
110
+ + const baseSchema = model.schema._baseSchema;
111
+ + const baseIndexes = baseSchema != null ? baseSchema.indexes() : [];
112
+ + return schemaIndexes.filter(index => {
113
+ + const options = index[1] || {};
114
+ + if (!options.sparse || options.partialFilterExpression?.[discriminatorKey] != null) {
115
+ + return false;
116
+ + }
117
+ + return !baseIndexes.some(baseIndex => utils.deepEqual(baseIndex[0], index[0]) &&
118
+ + utils.deepEqual(baseIndex[1], options));
119
+ + });
120
+ +}
121
+ +
122
+ function getRelatedIndexes({
123
+ baseModelName,
124
+ discriminatorMapping,
125
+ diff --git a/lib/helpers/indexes/isIndexEqual.js b/lib/helpers/indexes/isIndexEqual.js
126
+ index 22d4212..a0c627e 100644
127
+ --- a/lib/helpers/indexes/isIndexEqual.js
128
+ +++ b/lib/helpers/indexes/isIndexEqual.js
129
+ @@ -2,6 +2,35 @@
130
+
131
+ const get = require('../get');
132
+ const utils = require('../../utils');
133
+ +
134
+ +/*!
135
+ + * Boolean index options. MongoDB does not store some of them when they are
136
+ + * `false` (for example `unique: false`), so `false` and "not set" are the same.
137
+ + */
138
+ +
139
+ +const booleanOptionKeys = ['unique', 'sparse', 'hidden'];
140
+ +
141
+ +/*!
142
+ + * Options compared as-is: set on one side only means the indexes differ.
143
+ + */
144
+ +
145
+ +const exactOptionKeys = ['partialFilterExpression', 'expireAfterSeconds', 'wildcardProjection'];
146
+ +
147
+ +/*!
148
+ + * Collation options whose default never depends on the locale. When the
149
+ + * Mongoose index doesn't set one of these, the MongoDB index must hold the
150
+ + * default. The remaining collation options (`caseFirst`, `alternate`,
151
+ + * `normalization`, `backwards`) have locale-specific defaults, so they are
152
+ + * only compared when the Mongoose index sets them.
153
+ + */
154
+ +
155
+ +const localeIndependentCollationDefaults = {
156
+ + strength: 3,
157
+ + caseLevel: false,
158
+ + numericOrdering: false,
159
+ + maxVariable: 'punct'
160
+ +};
161
+ +
162
+ /**
163
+ * Given a Mongoose index definition (key + options objects) and a MongoDB server
164
+ * index definition, determine if the two indexes are equal.
165
+ @@ -13,6 +42,8 @@ const utils = require('../../utils');
166
+ */
167
+
168
+ module.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex) {
169
+ + options = options || {};
170
+ +
171
+ // Special case: text indexes have a special format in the db. For example,
172
+ // `{ name: 'text' }` becomes:
173
+ // {
174
+ @@ -26,59 +57,43 @@ module.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex)
175
+ // textIndexVersion: 3
176
+ // }
177
+ if (dbIndex.textIndexVersion != null) {
178
+ - delete dbIndex.key._fts;
179
+ - delete dbIndex.key._ftsx;
180
+ - const weights = { ...dbIndex.weights, ...dbIndex.key };
181
+ - if (Object.keys(weights).length !== Object.keys(schemaIndexKeysObject).length) {
182
+ + if (!isTextIndexEqual(schemaIndexKeysObject, options, dbIndex)) {
183
+ return false;
184
+ }
185
+ - for (const prop of Object.keys(weights)) {
186
+ - if (!(prop in schemaIndexKeysObject)) {
187
+ - return false;
188
+ - }
189
+ - const weight = weights[prop];
190
+ - if (weight !== get(options, 'weights.' + prop) && !(weight === 1 && get(options, 'weights.' + prop) == null)) {
191
+ - return false;
192
+ - }
193
+ - }
194
+ + } else if (!isKeyEqual(schemaIndexKeysObject, dbIndex.key)) {
195
+ + return false;
196
+ + }
197
+
198
+ - if (options['default_language'] !== dbIndex['default_language']) {
199
+ - return dbIndex['default_language'] === 'english' && options['default_language'] == null;
200
+ - }
201
+ + if (options.name != null && options.name !== dbIndex.name) {
202
+ + return false;
203
+ + }
204
+
205
+ - return true;
206
+ + for (const key of booleanOptionKeys) {
207
+ + if (Boolean(options[key]) !== Boolean(dbIndex[key])) {
208
+ + return false;
209
+ + }
210
+ }
211
+
212
+ - const optionKeys = [
213
+ - 'unique',
214
+ - 'partialFilterExpression',
215
+ - 'sparse',
216
+ - 'expireAfterSeconds',
217
+ - 'collation'
218
+ - ];
219
+ - for (const key of optionKeys) {
220
+ - if (!(key in options) && !(key in dbIndex)) {
221
+ + for (const key of exactOptionKeys) {
222
+ + if (options[key] == null && dbIndex[key] == null) {
223
+ continue;
224
+ }
225
+ - if (key === 'collation') {
226
+ - if (options[key] == null || dbIndex[key] == null) {
227
+ - return options[key] == null && dbIndex[key] == null;
228
+ - }
229
+ - const definedKeys = Object.keys(options.collation);
230
+ - const schemaCollation = options.collation;
231
+ - const dbCollation = dbIndex.collation;
232
+ - for (const opt of definedKeys) {
233
+ - if (get(schemaCollation, opt) !== get(dbCollation, opt)) {
234
+ - return false;
235
+ - }
236
+ - }
237
+ - } else if (!utils.deepEqual(options[key], dbIndex[key])) {
238
+ + if (!utils.deepEqual(options[key], dbIndex[key])) {
239
+ return false;
240
+ }
241
+ }
242
+
243
+ + if (options['2dsphereIndexVersion'] != null &&
244
+ + options['2dsphereIndexVersion'] !== dbIndex['2dsphereIndexVersion']) {
245
+ + return false;
246
+ + }
247
+ +
248
+ + return isCollationEqual(options.collation, dbIndex.collation);
249
+ +};
250
+ +
251
+ +function isKeyEqual(schemaIndexKeysObject, dbIndexKey) {
252
+ const schemaIndexKeys = Object.keys(schemaIndexKeysObject);
253
+ - const dbIndexKeys = Object.keys(dbIndex.key);
254
+ + const dbIndexKeys = Object.keys(dbIndexKey || {});
255
+ if (schemaIndexKeys.length !== dbIndexKeys.length) {
256
+ return false;
257
+ }
258
+ @@ -86,10 +101,99 @@ module.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex)
259
+ if (schemaIndexKeys[i] !== dbIndexKeys[i]) {
260
+ return false;
261
+ }
262
+ - if (!utils.deepEqual(schemaIndexKeysObject[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) {
263
+ + if (!utils.deepEqual(schemaIndexKeysObject[schemaIndexKeys[i]], dbIndexKey[dbIndexKeys[i]])) {
264
+ return false;
265
+ }
266
+ }
267
+ + return true;
268
+ +}
269
+ +
270
+ +function isTextIndexEqual(schemaIndexKeysObject, options, dbIndex) {
271
+ + // Non-text keys (compound text indexes) keep their direction in `key`, the
272
+ + // text fields collapse into `_fts`/`_ftsx` and are listed in `weights`.
273
+ + const schemaShape = [];
274
+ + const textFields = new Set();
275
+ + for (const key of Object.keys(schemaIndexKeysObject)) {
276
+ + if (schemaIndexKeysObject[key] === 'text') {
277
+ + if (textFields.size === 0) {
278
+ + schemaShape.push(['_fts', 'text']);
279
+ + }
280
+ + textFields.add(key);
281
+ + } else {
282
+ + schemaShape.push([key, schemaIndexKeysObject[key]]);
283
+ + }
284
+ + }
285
+ + const dbShape = Object.keys(dbIndex.key || {}).
286
+ + filter(key => key !== '_ftsx').
287
+ + map(key => [key, dbIndex.key[key]]);
288
+ + if (schemaShape.length !== dbShape.length) {
289
+ + return false;
290
+ + }
291
+ + for (let i = 0; i < schemaShape.length; ++i) {
292
+ + if (schemaShape[i][0] !== dbShape[i][0] || !utils.deepEqual(schemaShape[i][1], dbShape[i][1])) {
293
+ + return false;
294
+ + }
295
+ + }
296
+ +
297
+ + const schemaWeights = options.weights || {};
298
+ + for (const key of Object.keys(schemaWeights)) {
299
+ + textFields.add(key);
300
+ + }
301
+ + const dbWeights = dbIndex.weights || {};
302
+ + if (Object.keys(dbWeights).length !== textFields.size) {
303
+ + return false;
304
+ + }
305
+ + for (const prop of Object.keys(dbWeights)) {
306
+ + if (!textFields.has(prop)) {
307
+ + return false;
308
+ + }
309
+ + let weight = Object.hasOwn(schemaWeights, prop) ? schemaWeights[prop] : get(options, 'weights.' + prop);
310
+ + if (weight == null) {
311
+ + weight = 1;
312
+ + }
313
+ + if (dbWeights[prop] !== weight) {
314
+ + return false;
315
+ + }
316
+ + }
317
+ +
318
+ + if ((options.default_language ?? 'english') !== (dbIndex.default_language ?? 'english')) {
319
+ + return false;
320
+ + }
321
+ + if ((options.language_override ?? 'language') !== (dbIndex.language_override ?? 'language')) {
322
+ + return false;
323
+ + }
324
+ + if (options.textIndexVersion != null && options.textIndexVersion !== dbIndex.textIndexVersion) {
325
+ + return false;
326
+ + }
327
+
328
+ return true;
329
+ -};
330
+ +}
331
+ +
332
+ +function isSimpleCollation(collation) {
333
+ + return collation == null || collation.locale === 'simple';
334
+ +}
335
+ +
336
+ +function isCollationEqual(schemaCollation, dbCollation) {
337
+ + if (isSimpleCollation(schemaCollation) || isSimpleCollation(dbCollation)) {
338
+ + return isSimpleCollation(schemaCollation) && isSimpleCollation(dbCollation);
339
+ + }
340
+ +
341
+ + for (const opt of Object.keys(schemaCollation)) {
342
+ + if (schemaCollation[opt] === undefined) {
343
+ + continue;
344
+ + }
345
+ + if (get(schemaCollation, opt) !== get(dbCollation, opt)) {
346
+ + return false;
347
+ + }
348
+ + }
349
+ + for (const opt of Object.keys(localeIndependentCollationDefaults)) {
350
+ + if (schemaCollation[opt] !== undefined || dbCollation[opt] === undefined) {
351
+ + continue;
352
+ + }
353
+ + if (dbCollation[opt] !== localeIndependentCollationDefaults[opt]) {
354
+ + return false;
355
+ + }
356
+ + }
357
+ +
358
+ + return true;
359
+ +}
360
+ diff --git a/lib/model.js b/lib/model.js
361
+ index 28f76f1..4fee356 100644
362
+ --- a/lib/model.js
363
+ +++ b/lib/model.js
364
+ @@ -1495,6 +1495,7 @@ function getIndexesToCreate(schema, schemaIndexes, dbIndexes, toDrop, options) {
365
+ let found = false;
366
+
367
+ const options = decorateDiscriminatorIndexOptions(schema, clone(schemaIndexOptions));
368
+ + applySchemaCollation(schemaIndexKeysObject, options, schema.options);
369
+
370
+ for (const index of dbIndexes) {
371
+ if (isDefaultIdIndex(index)) {
372
+ diff --git a/test/model.syncIndexes.options.test.js b/test/model.syncIndexes.options.test.js
373
+ new file mode 100644
374
+ index 0000000..0b24e8d
375
+ --- /dev/null
376
+ +++ b/test/model.syncIndexes.options.test.js
377
+ @@ -0,0 +1,187 @@
378
+ +'use strict';
379
+ +
380
+ +const start = require('./common');
381
+ +
382
+ +const assert = require('assert');
383
+ +
384
+ +const mongoose = start.mongoose;
385
+ +const Schema = mongoose.Schema;
386
+ +
387
+ +describe('model syncIndexes() keeps the collection in line with the schema', function() {
388
+ + let db;
389
+ +
390
+ + before(function() {
391
+ + db = start();
392
+ + });
393
+ +
394
+ + after(async function() {
395
+ + await db.close();
396
+ + });
397
+ +
398
+ + beforeEach(() => db.deleteModel(/.*/));
399
+ + afterEach(() => require('./util').clearTestData(db));
400
+ + afterEach(() => require('./util').stopRemainingOps(db));
401
+ +
402
+ + async function freshCollection(name) {
403
+ + await db.dropCollection(name).catch(() => {});
404
+ + return name;
405
+ + }
406
+ +
407
+ + async function assertSettled(Model) {
408
+ + const diff = await Model.diffIndexes();
409
+ + assert.deepStrictEqual(diff, { toDrop: [], toCreate: [] });
410
+ + assert.deepStrictEqual(await Model.syncIndexes(), []);
411
+ + }
412
+ +
413
+ + async function findIndex(Model, predicate) {
414
+ + return (await Model.listIndexes()).find(predicate);
415
+ + }
416
+ +
417
+ + it('unhides an index the schema does not hide, and hides one it does', async function() {
418
+ + const coll = await freshCollection('sync_hidden');
419
+ + const Visible = db.model('SyncHiddenA', new Schema({ a: Number }, { autoIndex: false }).index({ a: 1 }), coll);
420
+ + await Visible.createCollection();
421
+ + await Visible.collection.createIndex({ a: 1 }, { hidden: true });
422
+ + assert.deepStrictEqual((await Visible.diffIndexes()).toDrop, ['a_1']);
423
+ + await Visible.syncIndexes();
424
+ + assert.ok(!(await findIndex(Visible, ix => ix.key.a === 1)).hidden);
425
+ + await assertSettled(Visible);
426
+ +
427
+ + db.deleteModel(/.*/);
428
+ + const Hidden = db.model('SyncHiddenB', new Schema({ a: Number }, { autoIndex: false }).index({ a: 1 }, { hidden: true }), coll);
429
+ + await Hidden.syncIndexes();
430
+ + assert.strictEqual((await findIndex(Hidden, ix => ix.key.a === 1)).hidden, true);
431
+ + await assertSettled(Hidden);
432
+ + });
433
+ +
434
+ + it('applies wildcardProjection, 2dsphereIndexVersion and name', async function() {
435
+ + const coll = await freshCollection('sync_options');
436
+ + const schema = new Schema({ meta: Schema.Types.Mixed, loc: [Number], a: Number }, { autoIndex: false });
437
+ + schema.index({ '$**': 1 }, { wildcardProjection: { 'meta.a': 1 } });
438
+ + schema.index({ loc: '2dsphere' }, { '2dsphereIndexVersion': 2 });
439
+ + schema.index({ a: 1 }, { name: 'byA' });
440
+ + const Model = db.model('SyncOptions', schema, coll);
441
+ + await Model.createCollection();
442
+ + await Model.collection.createIndex({ '$**': 1 }, { wildcardProjection: { 'meta.b': 1 } });
443
+ + await Model.collection.createIndex({ loc: '2dsphere' });
444
+ + await Model.collection.createIndex({ a: 1 });
445
+ +
446
+ + await Model.syncIndexes();
447
+ + const indexes = await Model.listIndexes();
448
+ + assert.deepStrictEqual(indexes.find(ix => ix.key['$**'] === 1).wildcardProjection, { 'meta.a': 1 });
449
+ + assert.strictEqual(indexes.find(ix => ix.key.loc === '2dsphere')['2dsphereIndexVersion'], 2);
450
+ + assert.deepStrictEqual(indexes.map(ix => ix.name).filter(name => name.startsWith('a_') || name === 'byA'), ['byA']);
451
+ + await assertSettled(Model);
452
+ + });
453
+ +
454
+ + it('does not rebuild indexes declared with false boolean options', async function() {
455
+ + const coll = await freshCollection('sync_false');
456
+ + const schema = new Schema({ a: Number, b: Number, c: Number }, { autoIndex: false });
457
+ + schema.index({ a: 1 }, { unique: false });
458
+ + schema.index({ b: 1 }, { sparse: false });
459
+ + schema.index({ c: 1 }, { hidden: false });
460
+ + const Model = db.model('SyncFalse', schema, coll);
461
+ + await Model.syncIndexes();
462
+ + await assertSettled(Model);
463
+ + });
464
+ +
465
+ + it('does not rebuild compound text indexes with descending keys', async function() {
466
+ + for (const [name, keys] of [['Prefix', { a: -1, t: 'text' }], ['Suffix', { t: 'text', a: -1 }]]) {
467
+ + const coll = await freshCollection('sync_text_desc_' + name.toLowerCase());
468
+ + const schema = new Schema({ a: Number, t: String }, { autoIndex: false });
469
+ + schema.index(keys);
470
+ + const Model = db.model('SyncTextDesc' + name, schema, coll);
471
+ + await Model.syncIndexes();
472
+ + await assertSettled(Model);
473
+ + }
474
+ + });
475
+ +
476
+ + it('applies language_override on text indexes', async function() {
477
+ + const coll = await freshCollection('sync_text_lang');
478
+ + const schema = new Schema({ t: String }, { autoIndex: false });
479
+ + schema.index({ t: 'text' }, { language_override: 'lang' });
480
+ + const Model = db.model('SyncTextLang', schema, coll);
481
+ + await Model.createCollection();
482
+ + await Model.collection.createIndex({ t: 'text' });
483
+ + await Model.syncIndexes();
484
+ + assert.strictEqual((await findIndex(Model, ix => ix.key._fts)).language_override, 'lang');
485
+ + await assertSettled(Model);
486
+ + });
487
+ +
488
+ + it('dry-run agrees with syncIndexes() for schema-level collation', async function() {
489
+ + const coll = await freshCollection('sync_schema_collation');
490
+ + const schema = new Schema({ a: String }, { autoIndex: false, collation: { locale: 'en', strength: 2 } });
491
+ + schema.index({ a: 1 });
492
+ + const Model = db.model('SyncSchemaCollation', schema, coll);
493
+ + await Model.syncIndexes();
494
+ + await assertSettled(Model);
495
+ + });
496
+ +
497
+ + it('enforces collation options left at their defaults', async function() {
498
+ + const coll = await freshCollection('sync_collation_defaults');
499
+ + const schema = new Schema({ a: String }, { autoIndex: false });
500
+ + schema.index({ a: 1 }, { collation: { locale: 'en' } });
501
+ + const Model = db.model('SyncCollationDefaults', schema, coll);
502
+ + await Model.createCollection();
503
+ + await Model.collection.createIndex({ a: 1 }, { collation: { locale: 'en', strength: 2 } });
504
+ + await Model.syncIndexes();
505
+ + assert.strictEqual((await findIndex(Model, ix => ix.key.a === 1)).collation.strength, 3);
506
+ + await assertSettled(Model);
507
+ + });
508
+ +
509
+ + it('does not rebuild indexes with simple collation', async function() {
510
+ + const coll = await freshCollection('sync_simple_collation');
511
+ + const schema = new Schema({ a: String }, { autoIndex: false });
512
+ + schema.index({ a: 1 }, { collation: { locale: 'simple' } });
513
+ + const Model = db.model('SyncSimpleCollation', schema, coll);
514
+ + await Model.syncIndexes();
515
+ + await assertSettled(Model);
516
+ + });
517
+ +
518
+ + it('creates text indexes on a schema with a collation', async function() {
519
+ + const coll = await freshCollection('sync_text_collation');
520
+ + const schema = new Schema({ t: String, a: String }, { autoIndex: false, collation: { locale: 'en', strength: 2 } });
521
+ + schema.index({ t: 'text' });
522
+ + schema.index({ a: 1 });
523
+ + const Model = db.model('SyncTextCollation', schema, coll);
524
+ + await Model.syncIndexes();
525
+ + const indexes = await Model.listIndexes();
526
+ + assert.ok(indexes.find(ix => ix.key._fts));
527
+ + assert.strictEqual(indexes.find(ix => ix.key.a === 1).collation.strength, 2);
528
+ + await assertSettled(Model);
529
+ + });
530
+ +
531
+ + it('creates 2d indexes on a schema with a collation', async function() {
532
+ + const coll = await freshCollection('sync_geo2d_collation');
533
+ + const schema = new Schema({ loc: [Number], a: String, h: String }, { autoIndex: false, collation: { locale: 'en', strength: 2 } });
534
+ + schema.index({ loc: '2d' });
535
+ + schema.index({ a: 1 });
536
+ + schema.index({ h: 'hashed' });
537
+ + const Model = db.model('SyncGeo2dCollation', schema, coll);
538
+ + await Model.syncIndexes();
539
+ + const indexes = await Model.listIndexes();
540
+ + assert.ok(indexes.find(ix => ix.key.loc === '2d'), 'the 2d index was never built');
541
+ + assert.strictEqual(indexes.find(ix => ix.key.a === 1).collation.strength, 2);
542
+ + assert.strictEqual(indexes.find(ix => ix.key.h === 'hashed').collation.strength, 2);
543
+ + await assertSettled(Model);
544
+ + });
545
+ +
546
+ + it('keeps sparse indexes of discriminators', async function() {
547
+ + const coll = await freshCollection('sync_discriminator_sparse');
548
+ + const baseSchema = new Schema({ kind: String }, { autoIndex: false, discriminatorKey: 'kind' });
549
+ + const Base = db.model('SyncDiscBase', baseSchema, coll);
550
+ + const childSchema = new Schema({ email: String });
551
+ + childSchema.index({ email: 1 }, { sparse: true, unique: true });
552
+ + const Child = Base.discriminator('SyncDiscChild', childSchema);
553
+ +
554
+ + await Child.syncIndexes();
555
+ + assert.ok(await findIndex(Child, ix => ix.key.email === 1));
556
+ + await assertSettled(Child);
557
+ + assert.deepStrictEqual(await Base.syncIndexes(), []);
558
+ + assert.ok(await findIndex(Child, ix => ix.key.email === 1));
559
+ +
560
+ + await Child.create([{}, {}]);
561
+ + await Child.create({ email: 'a@b.c' });
562
+ + await assert.rejects(Child.create({ email: 'a@b.c' }), /E11000/);
563
+ + });
564
+ +});
harbor/tasks/mongoose_syncindexes_contract/solution/solve.sh ADDED
@@ -0,0 +1,570 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/lib/helpers/indexes/applySchemaCollation.js b/lib/helpers/indexes/applySchemaCollation.js
6
+ index 464210e..f58d0ea 100644
7
+ --- a/lib/helpers/indexes/applySchemaCollation.js
8
+ +++ b/lib/helpers/indexes/applySchemaCollation.js
9
+ @@ -3,11 +3,17 @@
10
+ const isTextIndex = require('./isTextIndex');
11
+
12
+ module.exports = function applySchemaCollation(indexKeys, indexOptions, schemaOptions) {
13
+ - if (isTextIndex(indexKeys)) {
14
+ + if (!Object.hasOwn(schemaOptions, 'collation') || Object.hasOwn(indexOptions, 'collation')) {
15
+ return;
16
+ }
17
+
18
+ - if (Object.hasOwn(schemaOptions, 'collation') && !Object.hasOwn(indexOptions, 'collation')) {
19
+ - indexOptions.collation = schemaOptions.collation;
20
+ + if (isTextIndex(indexKeys) || Object.values(indexKeys).includes('2d')) {
21
+ + // Text and 2d indexes only support simple binary comparison. The
22
+ + // schema-level collation becomes the collection's default collation, which
23
+ + // such an index would otherwise inherit and fail to build with.
24
+ + indexOptions.collation = { locale: 'simple' };
25
+ + return;
26
+ }
27
+ +
28
+ + indexOptions.collation = schemaOptions.collation;
29
+ };
30
+ diff --git a/lib/helpers/indexes/getRelatedIndexes.js b/lib/helpers/indexes/getRelatedIndexes.js
31
+ index e68cb8d..66efcc0 100644
32
+ --- a/lib/helpers/indexes/getRelatedIndexes.js
33
+ +++ b/lib/helpers/indexes/getRelatedIndexes.js
34
+ @@ -1,23 +1,54 @@
35
+ 'use strict';
36
+
37
+ const hasDollarKeys = require('../query/hasDollarKeys');
38
+ +const isIndexEqual = require('./isIndexEqual');
39
+ +const utils = require('../../utils');
40
+
41
+ function getRelatedSchemaIndexes(model, schemaIndexes) {
42
+ - return getRelatedIndexes({
43
+ + const related = getRelatedIndexes({
44
+ baseModelName: model.baseModelName,
45
+ discriminatorMapping: model.schema.discriminatorMapping,
46
+ indexes: schemaIndexes,
47
+ indexesType: 'schema'
48
+ });
49
+ + const owned = unfilterableIndexesOf(model, schemaIndexes);
50
+ + if (owned.length === 0) {
51
+ + return related;
52
+ + }
53
+ + return schemaIndexes.filter(index => related.includes(index) || owned.includes(index));
54
+ }
55
+
56
+ function getRelatedDBIndexes(model, dbIndexes) {
57
+ - return getRelatedIndexes({
58
+ + const related = getRelatedIndexes({
59
+ baseModelName: model.baseModelName,
60
+ discriminatorMapping: model.schema.discriminatorMapping,
61
+ indexes: dbIndexes,
62
+ indexesType: 'db'
63
+ });
64
+ + if (!model.schema.discriminatorMapping?.key) {
65
+ + return related;
66
+ + }
67
+ +
68
+ + // MongoDB rejects `sparse` together with `partialFilterExpression`, so an
69
+ + // index a discriminator declares sparse carries no discriminator filter and
70
+ + // cannot be recognized by one. It belongs to the discriminator whose schema
71
+ + // declares it: to that discriminator's own sync, and to nobody else's.
72
+ + if (isChildDiscriminator(model)) {
73
+ + const owned = unfilterableIndexesOf(model, model.schema.indexes());
74
+ + if (owned.length === 0) {
75
+ + return related;
76
+ + }
77
+ + return dbIndexes.filter(dbIndex => related.includes(dbIndex) || matchesAny(owned, dbIndex));
78
+ + }
79
+ +
80
+ + const ownedByDiscriminators = [];
81
+ + for (const discriminator of Object.values(model.discriminators || {})) {
82
+ + ownedByDiscriminators.push(...unfilterableIndexesOf(discriminator, discriminator.schema.indexes()));
83
+ + }
84
+ + if (ownedByDiscriminators.length === 0) {
85
+ + return related;
86
+ + }
87
+ + return related.filter(dbIndex => !matchesAny(ownedByDiscriminators, dbIndex));
88
+ }
89
+
90
+ module.exports = {
91
+ @@ -25,6 +56,37 @@ module.exports = {
92
+ getRelatedDBIndexes
93
+ };
94
+
95
+ +function isChildDiscriminator(model) {
96
+ + return Boolean(model.baseModelName) && Boolean(model.schema.discriminatorMapping?.key);
97
+ +}
98
+ +
99
+ +function matchesAny(schemaIndexes, dbIndex) {
100
+ + return schemaIndexes.some(([keys, options]) => isIndexEqual(keys, options, dbIndex));
101
+ +}
102
+ +
103
+ +/*!
104
+ + * The indexes `model` declares that no discriminator filter can be attached to,
105
+ + * so `getRelatedIndexes()` cannot see whose they are: the sparse ones this
106
+ + * discriminator's schema adds to the schema it inherits from.
107
+ + */
108
+ +
109
+ +function unfilterableIndexesOf(model, schemaIndexes) {
110
+ + if (!isChildDiscriminator(model)) {
111
+ + return [];
112
+ + }
113
+ + const discriminatorKey = model.schema.discriminatorMapping.key;
114
+ + const baseSchema = model.schema._baseSchema;
115
+ + const baseIndexes = baseSchema != null ? baseSchema.indexes() : [];
116
+ + return schemaIndexes.filter(index => {
117
+ + const options = index[1] || {};
118
+ + if (!options.sparse || options.partialFilterExpression?.[discriminatorKey] != null) {
119
+ + return false;
120
+ + }
121
+ + return !baseIndexes.some(baseIndex => utils.deepEqual(baseIndex[0], index[0]) &&
122
+ + utils.deepEqual(baseIndex[1], options));
123
+ + });
124
+ +}
125
+ +
126
+ function getRelatedIndexes({
127
+ baseModelName,
128
+ discriminatorMapping,
129
+ diff --git a/lib/helpers/indexes/isIndexEqual.js b/lib/helpers/indexes/isIndexEqual.js
130
+ index 22d4212..a0c627e 100644
131
+ --- a/lib/helpers/indexes/isIndexEqual.js
132
+ +++ b/lib/helpers/indexes/isIndexEqual.js
133
+ @@ -2,6 +2,35 @@
134
+
135
+ const get = require('../get');
136
+ const utils = require('../../utils');
137
+ +
138
+ +/*!
139
+ + * Boolean index options. MongoDB does not store some of them when they are
140
+ + * `false` (for example `unique: false`), so `false` and "not set" are the same.
141
+ + */
142
+ +
143
+ +const booleanOptionKeys = ['unique', 'sparse', 'hidden'];
144
+ +
145
+ +/*!
146
+ + * Options compared as-is: set on one side only means the indexes differ.
147
+ + */
148
+ +
149
+ +const exactOptionKeys = ['partialFilterExpression', 'expireAfterSeconds', 'wildcardProjection'];
150
+ +
151
+ +/*!
152
+ + * Collation options whose default never depends on the locale. When the
153
+ + * Mongoose index doesn't set one of these, the MongoDB index must hold the
154
+ + * default. The remaining collation options (`caseFirst`, `alternate`,
155
+ + * `normalization`, `backwards`) have locale-specific defaults, so they are
156
+ + * only compared when the Mongoose index sets them.
157
+ + */
158
+ +
159
+ +const localeIndependentCollationDefaults = {
160
+ + strength: 3,
161
+ + caseLevel: false,
162
+ + numericOrdering: false,
163
+ + maxVariable: 'punct'
164
+ +};
165
+ +
166
+ /**
167
+ * Given a Mongoose index definition (key + options objects) and a MongoDB server
168
+ * index definition, determine if the two indexes are equal.
169
+ @@ -13,6 +42,8 @@ const utils = require('../../utils');
170
+ */
171
+
172
+ module.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex) {
173
+ + options = options || {};
174
+ +
175
+ // Special case: text indexes have a special format in the db. For example,
176
+ // `{ name: 'text' }` becomes:
177
+ // {
178
+ @@ -26,59 +57,43 @@ module.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex)
179
+ // textIndexVersion: 3
180
+ // }
181
+ if (dbIndex.textIndexVersion != null) {
182
+ - delete dbIndex.key._fts;
183
+ - delete dbIndex.key._ftsx;
184
+ - const weights = { ...dbIndex.weights, ...dbIndex.key };
185
+ - if (Object.keys(weights).length !== Object.keys(schemaIndexKeysObject).length) {
186
+ + if (!isTextIndexEqual(schemaIndexKeysObject, options, dbIndex)) {
187
+ return false;
188
+ }
189
+ - for (const prop of Object.keys(weights)) {
190
+ - if (!(prop in schemaIndexKeysObject)) {
191
+ - return false;
192
+ - }
193
+ - const weight = weights[prop];
194
+ - if (weight !== get(options, 'weights.' + prop) && !(weight === 1 && get(options, 'weights.' + prop) == null)) {
195
+ - return false;
196
+ - }
197
+ - }
198
+ + } else if (!isKeyEqual(schemaIndexKeysObject, dbIndex.key)) {
199
+ + return false;
200
+ + }
201
+
202
+ - if (options['default_language'] !== dbIndex['default_language']) {
203
+ - return dbIndex['default_language'] === 'english' && options['default_language'] == null;
204
+ - }
205
+ + if (options.name != null && options.name !== dbIndex.name) {
206
+ + return false;
207
+ + }
208
+
209
+ - return true;
210
+ + for (const key of booleanOptionKeys) {
211
+ + if (Boolean(options[key]) !== Boolean(dbIndex[key])) {
212
+ + return false;
213
+ + }
214
+ }
215
+
216
+ - const optionKeys = [
217
+ - 'unique',
218
+ - 'partialFilterExpression',
219
+ - 'sparse',
220
+ - 'expireAfterSeconds',
221
+ - 'collation'
222
+ - ];
223
+ - for (const key of optionKeys) {
224
+ - if (!(key in options) && !(key in dbIndex)) {
225
+ + for (const key of exactOptionKeys) {
226
+ + if (options[key] == null && dbIndex[key] == null) {
227
+ continue;
228
+ }
229
+ - if (key === 'collation') {
230
+ - if (options[key] == null || dbIndex[key] == null) {
231
+ - return options[key] == null && dbIndex[key] == null;
232
+ - }
233
+ - const definedKeys = Object.keys(options.collation);
234
+ - const schemaCollation = options.collation;
235
+ - const dbCollation = dbIndex.collation;
236
+ - for (const opt of definedKeys) {
237
+ - if (get(schemaCollation, opt) !== get(dbCollation, opt)) {
238
+ - return false;
239
+ - }
240
+ - }
241
+ - } else if (!utils.deepEqual(options[key], dbIndex[key])) {
242
+ + if (!utils.deepEqual(options[key], dbIndex[key])) {
243
+ return false;
244
+ }
245
+ }
246
+
247
+ + if (options['2dsphereIndexVersion'] != null &&
248
+ + options['2dsphereIndexVersion'] !== dbIndex['2dsphereIndexVersion']) {
249
+ + return false;
250
+ + }
251
+ +
252
+ + return isCollationEqual(options.collation, dbIndex.collation);
253
+ +};
254
+ +
255
+ +function isKeyEqual(schemaIndexKeysObject, dbIndexKey) {
256
+ const schemaIndexKeys = Object.keys(schemaIndexKeysObject);
257
+ - const dbIndexKeys = Object.keys(dbIndex.key);
258
+ + const dbIndexKeys = Object.keys(dbIndexKey || {});
259
+ if (schemaIndexKeys.length !== dbIndexKeys.length) {
260
+ return false;
261
+ }
262
+ @@ -86,10 +101,99 @@ module.exports = function isIndexEqual(schemaIndexKeysObject, options, dbIndex)
263
+ if (schemaIndexKeys[i] !== dbIndexKeys[i]) {
264
+ return false;
265
+ }
266
+ - if (!utils.deepEqual(schemaIndexKeysObject[schemaIndexKeys[i]], dbIndex.key[dbIndexKeys[i]])) {
267
+ + if (!utils.deepEqual(schemaIndexKeysObject[schemaIndexKeys[i]], dbIndexKey[dbIndexKeys[i]])) {
268
+ return false;
269
+ }
270
+ }
271
+ + return true;
272
+ +}
273
+ +
274
+ +function isTextIndexEqual(schemaIndexKeysObject, options, dbIndex) {
275
+ + // Non-text keys (compound text indexes) keep their direction in `key`, the
276
+ + // text fields collapse into `_fts`/`_ftsx` and are listed in `weights`.
277
+ + const schemaShape = [];
278
+ + const textFields = new Set();
279
+ + for (const key of Object.keys(schemaIndexKeysObject)) {
280
+ + if (schemaIndexKeysObject[key] === 'text') {
281
+ + if (textFields.size === 0) {
282
+ + schemaShape.push(['_fts', 'text']);
283
+ + }
284
+ + textFields.add(key);
285
+ + } else {
286
+ + schemaShape.push([key, schemaIndexKeysObject[key]]);
287
+ + }
288
+ + }
289
+ + const dbShape = Object.keys(dbIndex.key || {}).
290
+ + filter(key => key !== '_ftsx').
291
+ + map(key => [key, dbIndex.key[key]]);
292
+ + if (schemaShape.length !== dbShape.length) {
293
+ + return false;
294
+ + }
295
+ + for (let i = 0; i < schemaShape.length; ++i) {
296
+ + if (schemaShape[i][0] !== dbShape[i][0] || !utils.deepEqual(schemaShape[i][1], dbShape[i][1])) {
297
+ + return false;
298
+ + }
299
+ + }
300
+ +
301
+ + const schemaWeights = options.weights || {};
302
+ + for (const key of Object.keys(schemaWeights)) {
303
+ + textFields.add(key);
304
+ + }
305
+ + const dbWeights = dbIndex.weights || {};
306
+ + if (Object.keys(dbWeights).length !== textFields.size) {
307
+ + return false;
308
+ + }
309
+ + for (const prop of Object.keys(dbWeights)) {
310
+ + if (!textFields.has(prop)) {
311
+ + return false;
312
+ + }
313
+ + let weight = Object.hasOwn(schemaWeights, prop) ? schemaWeights[prop] : get(options, 'weights.' + prop);
314
+ + if (weight == null) {
315
+ + weight = 1;
316
+ + }
317
+ + if (dbWeights[prop] !== weight) {
318
+ + return false;
319
+ + }
320
+ + }
321
+ +
322
+ + if ((options.default_language ?? 'english') !== (dbIndex.default_language ?? 'english')) {
323
+ + return false;
324
+ + }
325
+ + if ((options.language_override ?? 'language') !== (dbIndex.language_override ?? 'language')) {
326
+ + return false;
327
+ + }
328
+ + if (options.textIndexVersion != null && options.textIndexVersion !== dbIndex.textIndexVersion) {
329
+ + return false;
330
+ + }
331
+
332
+ return true;
333
+ -};
334
+ +}
335
+ +
336
+ +function isSimpleCollation(collation) {
337
+ + return collation == null || collation.locale === 'simple';
338
+ +}
339
+ +
340
+ +function isCollationEqual(schemaCollation, dbCollation) {
341
+ + if (isSimpleCollation(schemaCollation) || isSimpleCollation(dbCollation)) {
342
+ + return isSimpleCollation(schemaCollation) && isSimpleCollation(dbCollation);
343
+ + }
344
+ +
345
+ + for (const opt of Object.keys(schemaCollation)) {
346
+ + if (schemaCollation[opt] === undefined) {
347
+ + continue;
348
+ + }
349
+ + if (get(schemaCollation, opt) !== get(dbCollation, opt)) {
350
+ + return false;
351
+ + }
352
+ + }
353
+ + for (const opt of Object.keys(localeIndependentCollationDefaults)) {
354
+ + if (schemaCollation[opt] !== undefined || dbCollation[opt] === undefined) {
355
+ + continue;
356
+ + }
357
+ + if (dbCollation[opt] !== localeIndependentCollationDefaults[opt]) {
358
+ + return false;
359
+ + }
360
+ + }
361
+ +
362
+ + return true;
363
+ +}
364
+ diff --git a/lib/model.js b/lib/model.js
365
+ index 28f76f1..4fee356 100644
366
+ --- a/lib/model.js
367
+ +++ b/lib/model.js
368
+ @@ -1495,6 +1495,7 @@ function getIndexesToCreate(schema, schemaIndexes, dbIndexes, toDrop, options) {
369
+ let found = false;
370
+
371
+ const options = decorateDiscriminatorIndexOptions(schema, clone(schemaIndexOptions));
372
+ + applySchemaCollation(schemaIndexKeysObject, options, schema.options);
373
+
374
+ for (const index of dbIndexes) {
375
+ if (isDefaultIdIndex(index)) {
376
+ diff --git a/test/model.syncIndexes.options.test.js b/test/model.syncIndexes.options.test.js
377
+ new file mode 100644
378
+ index 0000000..0b24e8d
379
+ --- /dev/null
380
+ +++ b/test/model.syncIndexes.options.test.js
381
+ @@ -0,0 +1,187 @@
382
+ +'use strict';
383
+ +
384
+ +const start = require('./common');
385
+ +
386
+ +const assert = require('assert');
387
+ +
388
+ +const mongoose = start.mongoose;
389
+ +const Schema = mongoose.Schema;
390
+ +
391
+ +describe('model syncIndexes() keeps the collection in line with the schema', function() {
392
+ + let db;
393
+ +
394
+ + before(function() {
395
+ + db = start();
396
+ + });
397
+ +
398
+ + after(async function() {
399
+ + await db.close();
400
+ + });
401
+ +
402
+ + beforeEach(() => db.deleteModel(/.*/));
403
+ + afterEach(() => require('./util').clearTestData(db));
404
+ + afterEach(() => require('./util').stopRemainingOps(db));
405
+ +
406
+ + async function freshCollection(name) {
407
+ + await db.dropCollection(name).catch(() => {});
408
+ + return name;
409
+ + }
410
+ +
411
+ + async function assertSettled(Model) {
412
+ + const diff = await Model.diffIndexes();
413
+ + assert.deepStrictEqual(diff, { toDrop: [], toCreate: [] });
414
+ + assert.deepStrictEqual(await Model.syncIndexes(), []);
415
+ + }
416
+ +
417
+ + async function findIndex(Model, predicate) {
418
+ + return (await Model.listIndexes()).find(predicate);
419
+ + }
420
+ +
421
+ + it('unhides an index the schema does not hide, and hides one it does', async function() {
422
+ + const coll = await freshCollection('sync_hidden');
423
+ + const Visible = db.model('SyncHiddenA', new Schema({ a: Number }, { autoIndex: false }).index({ a: 1 }), coll);
424
+ + await Visible.createCollection();
425
+ + await Visible.collection.createIndex({ a: 1 }, { hidden: true });
426
+ + assert.deepStrictEqual((await Visible.diffIndexes()).toDrop, ['a_1']);
427
+ + await Visible.syncIndexes();
428
+ + assert.ok(!(await findIndex(Visible, ix => ix.key.a === 1)).hidden);
429
+ + await assertSettled(Visible);
430
+ +
431
+ + db.deleteModel(/.*/);
432
+ + const Hidden = db.model('SyncHiddenB', new Schema({ a: Number }, { autoIndex: false }).index({ a: 1 }, { hidden: true }), coll);
433
+ + await Hidden.syncIndexes();
434
+ + assert.strictEqual((await findIndex(Hidden, ix => ix.key.a === 1)).hidden, true);
435
+ + await assertSettled(Hidden);
436
+ + });
437
+ +
438
+ + it('applies wildcardProjection, 2dsphereIndexVersion and name', async function() {
439
+ + const coll = await freshCollection('sync_options');
440
+ + const schema = new Schema({ meta: Schema.Types.Mixed, loc: [Number], a: Number }, { autoIndex: false });
441
+ + schema.index({ '$**': 1 }, { wildcardProjection: { 'meta.a': 1 } });
442
+ + schema.index({ loc: '2dsphere' }, { '2dsphereIndexVersion': 2 });
443
+ + schema.index({ a: 1 }, { name: 'byA' });
444
+ + const Model = db.model('SyncOptions', schema, coll);
445
+ + await Model.createCollection();
446
+ + await Model.collection.createIndex({ '$**': 1 }, { wildcardProjection: { 'meta.b': 1 } });
447
+ + await Model.collection.createIndex({ loc: '2dsphere' });
448
+ + await Model.collection.createIndex({ a: 1 });
449
+ +
450
+ + await Model.syncIndexes();
451
+ + const indexes = await Model.listIndexes();
452
+ + assert.deepStrictEqual(indexes.find(ix => ix.key['$**'] === 1).wildcardProjection, { 'meta.a': 1 });
453
+ + assert.strictEqual(indexes.find(ix => ix.key.loc === '2dsphere')['2dsphereIndexVersion'], 2);
454
+ + assert.deepStrictEqual(indexes.map(ix => ix.name).filter(name => name.startsWith('a_') || name === 'byA'), ['byA']);
455
+ + await assertSettled(Model);
456
+ + });
457
+ +
458
+ + it('does not rebuild indexes declared with false boolean options', async function() {
459
+ + const coll = await freshCollection('sync_false');
460
+ + const schema = new Schema({ a: Number, b: Number, c: Number }, { autoIndex: false });
461
+ + schema.index({ a: 1 }, { unique: false });
462
+ + schema.index({ b: 1 }, { sparse: false });
463
+ + schema.index({ c: 1 }, { hidden: false });
464
+ + const Model = db.model('SyncFalse', schema, coll);
465
+ + await Model.syncIndexes();
466
+ + await assertSettled(Model);
467
+ + });
468
+ +
469
+ + it('does not rebuild compound text indexes with descending keys', async function() {
470
+ + for (const [name, keys] of [['Prefix', { a: -1, t: 'text' }], ['Suffix', { t: 'text', a: -1 }]]) {
471
+ + const coll = await freshCollection('sync_text_desc_' + name.toLowerCase());
472
+ + const schema = new Schema({ a: Number, t: String }, { autoIndex: false });
473
+ + schema.index(keys);
474
+ + const Model = db.model('SyncTextDesc' + name, schema, coll);
475
+ + await Model.syncIndexes();
476
+ + await assertSettled(Model);
477
+ + }
478
+ + });
479
+ +
480
+ + it('applies language_override on text indexes', async function() {
481
+ + const coll = await freshCollection('sync_text_lang');
482
+ + const schema = new Schema({ t: String }, { autoIndex: false });
483
+ + schema.index({ t: 'text' }, { language_override: 'lang' });
484
+ + const Model = db.model('SyncTextLang', schema, coll);
485
+ + await Model.createCollection();
486
+ + await Model.collection.createIndex({ t: 'text' });
487
+ + await Model.syncIndexes();
488
+ + assert.strictEqual((await findIndex(Model, ix => ix.key._fts)).language_override, 'lang');
489
+ + await assertSettled(Model);
490
+ + });
491
+ +
492
+ + it('dry-run agrees with syncIndexes() for schema-level collation', async function() {
493
+ + const coll = await freshCollection('sync_schema_collation');
494
+ + const schema = new Schema({ a: String }, { autoIndex: false, collation: { locale: 'en', strength: 2 } });
495
+ + schema.index({ a: 1 });
496
+ + const Model = db.model('SyncSchemaCollation', schema, coll);
497
+ + await Model.syncIndexes();
498
+ + await assertSettled(Model);
499
+ + });
500
+ +
501
+ + it('enforces collation options left at their defaults', async function() {
502
+ + const coll = await freshCollection('sync_collation_defaults');
503
+ + const schema = new Schema({ a: String }, { autoIndex: false });
504
+ + schema.index({ a: 1 }, { collation: { locale: 'en' } });
505
+ + const Model = db.model('SyncCollationDefaults', schema, coll);
506
+ + await Model.createCollection();
507
+ + await Model.collection.createIndex({ a: 1 }, { collation: { locale: 'en', strength: 2 } });
508
+ + await Model.syncIndexes();
509
+ + assert.strictEqual((await findIndex(Model, ix => ix.key.a === 1)).collation.strength, 3);
510
+ + await assertSettled(Model);
511
+ + });
512
+ +
513
+ + it('does not rebuild indexes with simple collation', async function() {
514
+ + const coll = await freshCollection('sync_simple_collation');
515
+ + const schema = new Schema({ a: String }, { autoIndex: false });
516
+ + schema.index({ a: 1 }, { collation: { locale: 'simple' } });
517
+ + const Model = db.model('SyncSimpleCollation', schema, coll);
518
+ + await Model.syncIndexes();
519
+ + await assertSettled(Model);
520
+ + });
521
+ +
522
+ + it('creates text indexes on a schema with a collation', async function() {
523
+ + const coll = await freshCollection('sync_text_collation');
524
+ + const schema = new Schema({ t: String, a: String }, { autoIndex: false, collation: { locale: 'en', strength: 2 } });
525
+ + schema.index({ t: 'text' });
526
+ + schema.index({ a: 1 });
527
+ + const Model = db.model('SyncTextCollation', schema, coll);
528
+ + await Model.syncIndexes();
529
+ + const indexes = await Model.listIndexes();
530
+ + assert.ok(indexes.find(ix => ix.key._fts));
531
+ + assert.strictEqual(indexes.find(ix => ix.key.a === 1).collation.strength, 2);
532
+ + await assertSettled(Model);
533
+ + });
534
+ +
535
+ + it('creates 2d indexes on a schema with a collation', async function() {
536
+ + const coll = await freshCollection('sync_geo2d_collation');
537
+ + const schema = new Schema({ loc: [Number], a: String, h: String }, { autoIndex: false, collation: { locale: 'en', strength: 2 } });
538
+ + schema.index({ loc: '2d' });
539
+ + schema.index({ a: 1 });
540
+ + schema.index({ h: 'hashed' });
541
+ + const Model = db.model('SyncGeo2dCollation', schema, coll);
542
+ + await Model.syncIndexes();
543
+ + const indexes = await Model.listIndexes();
544
+ + assert.ok(indexes.find(ix => ix.key.loc === '2d'), 'the 2d index was never built');
545
+ + assert.strictEqual(indexes.find(ix => ix.key.a === 1).collation.strength, 2);
546
+ + assert.strictEqual(indexes.find(ix => ix.key.h === 'hashed').collation.strength, 2);
547
+ + await assertSettled(Model);
548
+ + });
549
+ +
550
+ + it('keeps sparse indexes of discriminators', async function() {
551
+ + const coll = await freshCollection('sync_discriminator_sparse');
552
+ + const baseSchema = new Schema({ kind: String }, { autoIndex: false, discriminatorKey: 'kind' });
553
+ + const Base = db.model('SyncDiscBase', baseSchema, coll);
554
+ + const childSchema = new Schema({ email: String });
555
+ + childSchema.index({ email: 1 }, { sparse: true, unique: true });
556
+ + const Child = Base.discriminator('SyncDiscChild', childSchema);
557
+ +
558
+ + await Child.syncIndexes();
559
+ + assert.ok(await findIndex(Child, ix => ix.key.email === 1));
560
+ + await assertSettled(Child);
561
+ + assert.deepStrictEqual(await Base.syncIndexes(), []);
562
+ + assert.ok(await findIndex(Child, ix => ix.key.email === 1));
563
+ +
564
+ + await Child.create([{}, {}]);
565
+ + await Child.create({ email: 'a@b.c' });
566
+ + await assert.rejects(Child.create({ email: 'a@b.c' }), /E11000/);
567
+ + });
568
+ +});
569
+
570
+ REFERENCE_PATCH
harbor/tasks/mongoose_syncindexes_contract/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "mongoose_syncindexes_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/mongoose_syncindexes_contract/tests/Dockerfile ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-mongoose:source-v10
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
+ RUN chmod -R a+rX /hud/mongodb
5
+ RUN chown -R 1000:1000 /hud/grader-home
6
+ ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
7
+ RUN rm -f /hud/gold.diff
8
+ COPY verify.py evidence.py config.json test.sh /tests/
9
+ RUN chmod 755 /tests/test.sh
10
+ WORKDIR /app
11
+ CMD ["sleep", "infinity"]
harbor/tasks/mongoose_syncindexes_contract/tests/config.json ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "mongoose_syncindexes_contract",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-mongoose:source-v10",
7
+ "source_image_id": "sha256:3ae9e43927001d4ac27b6687f9630817af3f9cac7990357468e860a1d9aa615a",
8
+ "provenance": {
9
+ "repository": "Automattic/mongoose",
10
+ "environment_id": "8adfe164-788a-4744-952d-d16cfe95387a",
11
+ "build": 10,
12
+ "build_id": "4edb9f8d-9433-42f0-944b-a9d7bd4f1100",
13
+ "hosted_task": "mongoose_syncindexes_contract-97c2a76f",
14
+ "task_version": "04b44ad4-10b6-4ae0-9ac3-6bebbba3ac3b",
15
+ "source_archive_sha256": "13f212b2fb88bbbf521716bc7056fa0b3f5a7dfef323b14aa10aab85b19ff31e",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "text_index_on_collated_schema_syncs",
21
+ 0.065,
22
+ false,
23
+ "bash",
24
+ 600
25
+ ],
26
+ [
27
+ "geo2d_index_on_collated_schema_syncs",
28
+ 0.065,
29
+ false,
30
+ "bash",
31
+ 600
32
+ ],
33
+ [
34
+ "text_index_added_to_collated_collection_syncs",
35
+ 0.065,
36
+ false,
37
+ "bash",
38
+ 600
39
+ ],
40
+ [
41
+ "text_index_weights_on_collated_schema_enforced",
42
+ 0.065,
43
+ false,
44
+ "bash",
45
+ 600
46
+ ],
47
+ [
48
+ "compound_text_index_on_collated_schema_syncs",
49
+ 0.065,
50
+ false,
51
+ "bash",
52
+ 600
53
+ ],
54
+ [
55
+ "collation_locale_defaults_drift_repaired",
56
+ 0.065,
57
+ false,
58
+ "bash",
59
+ 600
60
+ ],
61
+ [
62
+ "collation_backwards_locale_drift_repaired",
63
+ 0.065,
64
+ false,
65
+ "bash",
66
+ 600
67
+ ],
68
+ [
69
+ "schema_locale_collation_no_churn",
70
+ 0.065,
71
+ false,
72
+ "bash",
73
+ 600
74
+ ],
75
+ [
76
+ "discriminator_index_not_dropped_by_base_sync",
77
+ 0.08,
78
+ true,
79
+ "bash",
80
+ 600
81
+ ],
82
+ [
83
+ "discriminator_sparse_index_created",
84
+ 0.03,
85
+ false,
86
+ "bash",
87
+ 600
88
+ ],
89
+ [
90
+ "geo_index_version_enforced",
91
+ 0.03,
92
+ false,
93
+ "bash",
94
+ 600
95
+ ],
96
+ [
97
+ "text_index_extra_weights_enforced",
98
+ 0.03,
99
+ false,
100
+ "bash",
101
+ 600
102
+ ],
103
+ [
104
+ "index_collation_defaults_enforced",
105
+ 0.03,
106
+ false,
107
+ "bash",
108
+ 600
109
+ ],
110
+ [
111
+ "simple_collation_no_churn",
112
+ 0.03,
113
+ false,
114
+ "bash",
115
+ 600
116
+ ],
117
+ [
118
+ "hidden_option_enforced",
119
+ 0.03,
120
+ false,
121
+ "bash",
122
+ 600
123
+ ],
124
+ [
125
+ "compound_text_descending_no_churn",
126
+ 0.03,
127
+ false,
128
+ "bash",
129
+ 600
130
+ ],
131
+ [
132
+ "text_language_override_enforced",
133
+ 0.03,
134
+ false,
135
+ "bash",
136
+ 600
137
+ ],
138
+ [
139
+ "explicit_false_options_no_churn",
140
+ 0.03,
141
+ false,
142
+ "bash",
143
+ 600
144
+ ],
145
+ [
146
+ "dry_run_honours_schema_collation",
147
+ 0.03,
148
+ false,
149
+ "bash",
150
+ 600
151
+ ],
152
+ [
153
+ "wildcard_projection_enforced",
154
+ 0.03,
155
+ false,
156
+ "bash",
157
+ 600
158
+ ],
159
+ [
160
+ "index_name_enforced",
161
+ 0.03,
162
+ false,
163
+ "bash",
164
+ 600
165
+ ],
166
+ [
167
+ "discriminator_stated_sparse_false_stays_shared",
168
+ 0.03,
169
+ true,
170
+ "bash",
171
+ 600
172
+ ],
173
+ [
174
+ "gate_repo_suite_green_and_tests_untouched",
175
+ 0.01,
176
+ true,
177
+ "bash",
178
+ 2400
179
+ ]
180
+ ],
181
+ "gates": [],
182
+ "reward_rule": "weighted_cap",
183
+ "local_hostname": false,
184
+ "fault_exit": 3,
185
+ "grader_readable": [
186
+ "/hud/mongodb"
187
+ ],
188
+ "grader_writable": [
189
+ "/hud/grader-home"
190
+ ],
191
+ "blocker_cap": 0.6,
192
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
193
+ "verifier_files": {
194
+ "/app/env.py": "a151c69dbf1e135db7428c4d772cc7f8949046aa4d6138bda582337c26344d46",
195
+ "/app/tasks.py": "ff2e8f4cf38633350e356bd58273dcba10db3e9b842fc236db406273b7da4e81",
196
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
197
+ "/app/coding/repo.py": "7bacfab572412c8d878ecd9c6cd53a05a17cde829be7921bfaeb903d1973d4fb",
198
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
199
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
200
+ "/app/task/prompt.md": "58389104047c0e886de9622b728aab26f5ddc93e0817312d1847e1fe16674c5f",
201
+ "/hud/grader/run_grading.sh": "4532a4da403df85cb4b48a6d81392f144b03a17f0b167cc7d8cb6557b4f76f87",
202
+ "/hud/grader/harness/contract_cells.cjs": "b3248f785e062404a876e64d5c5fd59169128a3fa51ccc4020e7238d595b569a",
203
+ "/hud/grader/controls/lazy.diff": "5c2387a08d6ad00d9035e76650f0c50e52cede2ac818ce6a61ef3d839a3e97a4",
204
+ "/hud/grader/controls/cheat.diff": "90fc23b96230c532963e3022e4d429cce289616e7a474d69125819bc9005c9aa",
205
+ "/hud/grader/controls/cheat2.diff": "10a1ceea174749ebbb68e4ba2f5fc5ec0239d724f196534dd6f397e5031cf0c7",
206
+ "/hud/grader/controls/alt.diff": "132ec68936d64b9051fc743199dbe54bc6c5da8eef09b2d9d4523c0a64cb06cd",
207
+ "/hud/grader/tools/record_protected.py": "7c1fc52858c6a1be80e6b2a3be37a0e7e89b34f399fb272f073bf1ce2c8916b9",
208
+ "/hud/grader/tools/check_protected.py": "9a1fe691953cdac54715c2154db7828fd8ddf7dd78cb03d74fc263c00e239190"
209
+ },
210
+ "preflight": [
211
+ [
212
+ "/bin/bash",
213
+ "--version"
214
+ ],
215
+ [
216
+ "setpriv",
217
+ "--version"
218
+ ],
219
+ [
220
+ "git",
221
+ "--version"
222
+ ],
223
+ [
224
+ "bash",
225
+ "-c",
226
+ "bash -lc 'node --version' || node --version"
227
+ ]
228
+ ]
229
+ }
harbor/tasks/mongoose_syncindexes_contract/tests/docker-compose.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ services:
2
+ main:
3
+ network_mode: none
4
+ pids_limit: 512
5
+ ulimits:
6
+ nofile:
7
+ soft: 1048576
8
+ hard: 1048576
9
+ security_opt:
10
+ - no-new-privileges:true
harbor/tasks/mongoose_syncindexes_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/mongoose_syncindexes_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/mongoose_syncindexes_contract/tests/verify.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/open_xml_sdk_deletepart_refs_contract/environment/Dockerfile ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-open-xml-sdk:source-v5 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/share/dotnet:/usr/bin:/bin"
8
+ ENV DOTNET_ROOT="/usr/share/dotnet"
9
+ ENV DOTNET_CLI_TELEMETRY_OPTOUT="1"
10
+ ENV DOTNET_SKIP_FIRST_TIME_EXPERIENCE="1"
11
+ ENV DOTNET_CLI_HOME="/tmp/agent-home"
12
+ ENV DOTNET_NOLOGO="1"
13
+ ENV NUGET_PACKAGES="/tmp/agent-home/.nuget/packages"
14
+ ENV NUGET_FALLBACK_PACKAGES="/opt/nuget/packages"
15
+ ENV HOME="/tmp/agent-home"
16
+ ENV GOCACHE="/tmp/agent-home/.cache/go-build"
17
+ ENV HUD_TELEMETRY_ENABLED="false"
18
+ ENV HUD_CLI_ANALYTICS_ENABLED="0"
19
+ WORKDIR /workspace/repo
20
+ USER 1000:1000
21
+ CMD ["sleep", "infinity"]
harbor/tasks/open_xml_sdk_deletepart_refs_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/open_xml_sdk_deletepart_refs_contract/environment/capture_submission.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture tracked and new SWE files without changing the agent's Git index."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import os
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/open_xml_sdk_deletepart_refs_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/open_xml_sdk_deletepart_refs_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/open_xml_sdk_deletepart_refs_contract/instruction.md ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ # Ticket
4
+
5
+ A document whose parts were deleted or re-identified can reopen with references leading nowhere: owners relating to one part, however its name is cased, share it, the saved package keeps it exactly while any owner relates to it, and giving a part an id its owner holds for any relationship throws, changing nothing, with existing tests green and untouched.
6
+
7
+ Finish with a final response when your changes are ready.
harbor/tasks/open_xml_sdk_deletepart_refs_contract/solution/reference.patch ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs b/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs
2
+ index 69e37bc..ff549f5 100644
3
+ --- a/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs
4
+ +++ b/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs
5
+ @@ -53,12 +53,7 @@ internal static void UseTransitionalRelationshipNamespaces(this OpenXmlPackage p
6
+ {
7
+ if (alteredRelationships.TryGetValue(OpenXmlPackage.Uri, out var list))
8
+ {
9
+ - foreach (var toReplace in list)
10
+ - {
11
+ - package.Relationships.Remove(toReplace.Id);
12
+ - package.Relationships.Create(toReplace.TargetUri, toReplace.TargetMode, toReplace.RelationshipType, toReplace.Id);
13
+ - }
14
+ -
15
+ + ReplaceRelationships(package.Relationships, list);
16
+ alteredRelationships.Remove(OpenXmlPackage.Uri);
17
+ }
18
+ }
19
+ @@ -66,12 +61,7 @@ internal static void UseTransitionalRelationshipNamespaces(this OpenXmlPackage p
20
+ {
21
+ if (alteredRelationships.TryGetValue(part.Uri, out var list))
22
+ {
23
+ - foreach (var toReplace in list)
24
+ - {
25
+ - part.Relationships.Remove(toReplace.Id);
26
+ - part.Relationships.Create(toReplace.TargetUri, toReplace.TargetMode, toReplace.RelationshipType, toReplace.Id);
27
+ - }
28
+ -
29
+ + ReplaceRelationships(part.Relationships, list);
30
+ alteredRelationships.Remove(part.Uri);
31
+ }
32
+ }
33
+ @@ -79,6 +69,41 @@ internal static void UseTransitionalRelationshipNamespaces(this OpenXmlPackage p
34
+ }
35
+ }
36
+
37
+ + /// <summary>
38
+ + /// Rewrites the relationships whose namespace was translated when the package was loaded so the transitional
39
+ + /// namespace is persisted. Only relationships that still exist exactly as they were loaded are rewritten;
40
+ + /// a relationship that was deleted or re-identified in the meantime must not be resurrected, as that would
41
+ + /// leave the saved package with relationships leading to parts that no longer exist.
42
+ + /// </summary>
43
+ + private static void ReplaceRelationships(IRelationshipCollection relationships, List<PackageRelationshipBuilder> altered)
44
+ + {
45
+ + foreach (var toReplace in altered)
46
+ + {
47
+ + if (!relationships.Contains(toReplace.Id))
48
+ + {
49
+ + // Deleted (or its id was given up) since loading.
50
+ + continue;
51
+ + }
52
+ +
53
+ + var current = relationships[toReplace.Id];
54
+ +
55
+ + if (!ReferenceEquals(current, toReplace) && !IsSameRelationship(current, toReplace))
56
+ + {
57
+ + // The id now identifies a different relationship that was created after loading and is
58
+ + // therefore already persisted with the namespace it was created with.
59
+ + continue;
60
+ + }
61
+ +
62
+ + relationships.Remove(toReplace.Id);
63
+ + relationships.Create(toReplace.TargetUri, toReplace.TargetMode, toReplace.RelationshipType, toReplace.Id);
64
+ + }
65
+ + }
66
+ +
67
+ + private static bool IsSameRelationship(IPackageRelationship current, PackageRelationshipBuilder original)
68
+ + => current.TargetMode == original.TargetMode
69
+ + && string.Equals(current.RelationshipType, original.RelationshipType, StringComparison.Ordinal)
70
+ + && string.Equals(current.TargetUri.OriginalString, original.TargetUri.OriginalString, StringComparison.Ordinal);
71
+ +
72
+ private sealed class StrictNamespaceFeature : IStrictNamespaceFeature
73
+ {
74
+ private OpenXmlPackage? _package;
75
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs b/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs
76
+ index 5ebbd8d..51c456c 100644
77
+ --- a/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs
78
+ +++ b/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs
79
+ @@ -90,6 +90,8 @@ internal override void InitPart(OpenXmlPart newPart, string contentType, string?
80
+ throw new ArgumentException(ExceptionMessages.StringArgumentEmptyException, nameof(contentType));
81
+ }
82
+
83
+ + ThrowIfRelationshipIdInUse(id, nameof(id));
84
+ +
85
+ newPart.CreateInternal(InternalOpenXmlPackage, ThisOpenXmlPart, contentType, targetExt: null);
86
+
87
+ ChildrenRelationshipParts.Add(newPart, id);
88
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs b/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs
89
+ index bd9d8e7..840cf05 100644
90
+ --- a/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs
91
+ +++ b/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs
92
+ @@ -599,6 +599,9 @@ public string ChangeIdOfPart(OpenXmlPart part, string newRelationshipId)
93
+ throw new ArgumentOutOfRangeException(nameof(part));
94
+ }
95
+
96
+ + // the id may also be held by a relationship that is not to a part (hyperlink, external, data part)
97
+ + ThrowIfRelationshipIdInUse(newRelationshipId, nameof(newRelationshipId));
98
+ +
99
+ // Add a new relationship, and then remove the old relationship
100
+ ChildrenRelationshipParts.Add(part, newRelationshipId);
101
+ ChildrenRelationshipParts.Remove(oldId);
102
+ @@ -606,6 +609,18 @@ public string ChangeIdOfPart(OpenXmlPart part, string newRelationshipId)
103
+ return oldId;
104
+ }
105
+
106
+ + /// <summary>
107
+ + /// Throws when <paramref name="id"/> already names a relationship of this container, whether it targets a part
108
+ + /// or not (hyperlink, external or data part reference relationships share the same id space).
109
+ + /// </summary>
110
+ + internal void ThrowIfRelationshipIdInUse(string? id, string paramName)
111
+ + {
112
+ + if (id is not null && (ChildrenRelationshipParts.Contains(id) || Relationships.Contains(id)))
113
+ + {
114
+ + throw new ArgumentException(ExceptionMessages.RelationshipIdConflict, paramName);
115
+ + }
116
+ + }
117
+ +
118
+ /// <summary>
119
+ /// Adds the part to the document.
120
+ /// Must use the returned part to operate on the part added to the document.
121
+ @@ -1100,6 +1115,8 @@ internal virtual void InitPart(OpenXmlPart newPart, string contentType, string?
122
+ throw new ArgumentException(ExceptionMessages.StringArgumentEmptyException);
123
+ }
124
+
125
+ + ThrowIfRelationshipIdInUse(id, nameof(id));
126
+ +
127
+ if (Features.GetRequired<IPartConstraintFeature>().TryGetRule(newPart.RelationshipType, out var partConstraintRule))
128
+ {
129
+ if (!partConstraintRule.MaxOccursGreatThanOne)
130
+ @@ -1165,6 +1182,8 @@ internal virtual OpenXmlPart AddPartFrom(OpenXmlPart subPart, string? rId)
131
+ }
132
+ }
133
+
134
+ + ThrowIfRelationshipIdInUse(rId, nameof(rId));
135
+ +
136
+ if (Features.GetRequired<IPartConstraintFeature>().TryGetRule(subPart.RelationshipType, out var partConstraintRule))
137
+ {
138
+ if (partConstraintRule.ContentType is not null && subPart.ContentType != partConstraintRule.ContentType)
139
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs b/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs
140
+ index d2ca108..1360705 100644
141
+ --- a/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs
142
+ +++ b/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs
143
+ @@ -119,7 +119,22 @@ bool IPartsFeature.TryGetPart(Uri uri, [MaybeNullWhen(false)] out OpenXmlPart pa
144
+ }
145
+
146
+ void IPartsFeature.Add(Uri uri, OpenXmlPart part)
147
+ - => (_parts ??= new()).Add(uri, part);
148
+ + => (_parts ??= new(PartNameComparer.Instance)).Add(uri, part);
149
+ +
150
+ + /// <summary>
151
+ + /// Part names in a package are compared without regard to ASCII letter case, so two
152
+ + /// relationships whose targets differ only in case address the same part.
153
+ + /// </summary>
154
+ + private sealed class PartNameComparer : IEqualityComparer<Uri>
155
+ + {
156
+ + public static readonly PartNameComparer Instance = new();
157
+ +
158
+ + public bool Equals(Uri? x, Uri? y)
159
+ + => ReferenceEquals(x, y) || (x is not null && y is not null && StringComparer.OrdinalIgnoreCase.Equals(x.OriginalString, y.OriginalString));
160
+ +
161
+ + public int GetHashCode(Uri obj)
162
+ + => StringComparer.OrdinalIgnoreCase.GetHashCode(obj.OriginalString);
163
+ + }
164
+
165
+ bool IDataPartsFeature.Remove(DataPart dataPart)
166
+ {
167
+ diff --git a/test/DocumentFormat.OpenXml.Packaging.Tests/PartIdentityAndRelationshipIdTests.cs b/test/DocumentFormat.OpenXml.Packaging.Tests/PartIdentityAndRelationshipIdTests.cs
168
+ new file mode 100644
169
+ index 0000000..067c045
170
+ --- /dev/null
171
+ +++ b/test/DocumentFormat.OpenXml.Packaging.Tests/PartIdentityAndRelationshipIdTests.cs
172
+ @@ -0,0 +1,141 @@
173
+ +// Copyright (c) Microsoft. All rights reserved.
174
+ +// Licensed under the MIT license. See LICENSE file in the project root for full license information.
175
+ +
176
+ +using System;
177
+ +using System.IO;
178
+ +using System.IO.Packaging;
179
+ +using System.Linq;
180
+ +using Xunit;
181
+ +
182
+ +namespace DocumentFormat.OpenXml.Packaging.Tests
183
+ +{
184
+ + public class PartIdentityAndRelationshipIdTests
185
+ + {
186
+ + private const string MainType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
187
+ + private const string HeaderType = "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml";
188
+ + private const string RelImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
189
+ +
190
+ + [Fact]
191
+ + public void ReferencesDifferingOnlyInCaseLoadOnePart()
192
+ + {
193
+ + using var ms = CreateSharedImage("media/IMAGE1.png");
194
+ + using var doc = WordprocessingDocument.Open(ms, false);
195
+ +
196
+ + var main = doc.MainDocumentPart!;
197
+ + var header = main.HeaderParts.Single();
198
+ +
199
+ + Assert.Same(main.GetPartById("rIdImg"), header.GetPartById("rIdImgH"));
200
+ + }
201
+ +
202
+ + [Fact]
203
+ + public void DeletingSharedPartFromOneOwnerKeepsItForTheOther()
204
+ + {
205
+ + using var ms = CreateSharedImage("media/IMAGE1.png");
206
+ +
207
+ + using (var doc = WordprocessingDocument.Open(ms, true))
208
+ + {
209
+ + Assert.True(doc.MainDocumentPart!.DeletePart("rIdImg"));
210
+ + }
211
+ +
212
+ + using var reopened = WordprocessingDocument.Open(ms, false);
213
+ + var header = reopened.MainDocumentPart!.HeaderParts.Single();
214
+ +
215
+ + Assert.True(header.TryGetPartById("rIdImgH", out var image));
216
+ + Assert.IsType<ImagePart>(image);
217
+ + }
218
+ +
219
+ + [Fact]
220
+ + public void DeletingOwnerKeepsPartReferencedByAnotherOwner()
221
+ + {
222
+ + using var ms = CreateSharedImage("media/Image1.PNG");
223
+ +
224
+ + using (var doc = WordprocessingDocument.Open(ms, true))
225
+ + {
226
+ + Assert.True(doc.MainDocumentPart!.DeletePart("rIdHdr"));
227
+ + }
228
+ +
229
+ + using var reopened = WordprocessingDocument.Open(ms, false);
230
+ +
231
+ + Assert.True(reopened.MainDocumentPart!.TryGetPartById("rIdImg", out _));
232
+ + }
233
+ +
234
+ + [Fact]
235
+ + public void ChangeIdOfPartRejectsIdOfHyperlink()
236
+ + {
237
+ + using var ms = new MemoryStream();
238
+ + using var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
239
+ +
240
+ + var main = doc.AddMainDocumentPart();
241
+ + var image = main.AddImagePart(ImagePartType.Png, "rIdPic");
242
+ + main.AddHyperlinkRelationship(new Uri("http://example.com/"), true, "rIdLink");
243
+ +
244
+ + Assert.Throws<ArgumentException>(() => main.ChangeIdOfPart(image, "rIdLink"));
245
+ + Assert.Equal("rIdPic", main.GetIdOfPart(image));
246
+ + Assert.Single(main.HyperlinkRelationships);
247
+ + }
248
+ +
249
+ + [Fact]
250
+ + public void AddNewPartRejectsIdOfExternalRelationship()
251
+ + {
252
+ + using var ms = new MemoryStream();
253
+ + using var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
254
+ +
255
+ + var main = doc.AddMainDocumentPart();
256
+ + main.AddExternalRelationship("http://example.com/rel", new Uri("http://example.com/"), "rIdExt");
257
+ +
258
+ + Assert.Throws<ArgumentException>(() => main.AddImagePart(ImagePartType.Png, "rIdExt"));
259
+ + Assert.Empty(main.ImageParts);
260
+ + }
261
+ +
262
+ + [Fact]
263
+ + public void CreateRelationshipToPartRejectsIdOfHyperlink()
264
+ + {
265
+ + using var ms = new MemoryStream();
266
+ + using var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
267
+ +
268
+ + var main = doc.AddMainDocumentPart();
269
+ + var image = main.AddImagePart(ImagePartType.Png);
270
+ + var header = main.AddNewPart<HeaderPart>();
271
+ + header.AddHyperlinkRelationship(new Uri("http://example.com/"), true, "rIdLink");
272
+ +
273
+ + Assert.Throws<ArgumentException>(() => header.CreateRelationshipToPart(image, "rIdLink"));
274
+ + Assert.Empty(header.Parts);
275
+ + }
276
+ +
277
+ + private static MemoryStream CreateSharedImage(string headerTarget)
278
+ + {
279
+ + var ms = new MemoryStream();
280
+ +
281
+ + using (var package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite))
282
+ + {
283
+ + var documentUri = new Uri("/word/document.xml", UriKind.Relative);
284
+ + var headerUri = new Uri("/word/header1.xml", UriKind.Relative);
285
+ + var document = package.CreatePart(documentUri, MainType);
286
+ + var header = package.CreatePart(headerUri, HeaderType);
287
+ + var image = package.CreatePart(new Uri("/word/media/image1.png", UriKind.Relative), "image/png");
288
+ +
289
+ + WriteText(document, "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:body/></w:document>");
290
+ + WriteText(header, "<w:hdr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"/>");
291
+ +
292
+ + using (var stream = image.GetStream())
293
+ + {
294
+ + stream.Write(new byte[] { 1, 2, 3 }, 0, 3);
295
+ + }
296
+ +
297
+ + package.CreateRelationship(documentUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "rId1");
298
+ + document.CreateRelationship(new Uri("header1.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header", "rIdHdr");
299
+ + document.CreateRelationship(new Uri("media/image1.png", UriKind.Relative), TargetMode.Internal, RelImage, "rIdImg");
300
+ + header.CreateRelationship(new Uri(headerTarget, UriKind.Relative), TargetMode.Internal, RelImage, "rIdImgH");
301
+ + }
302
+ +
303
+ + return ms;
304
+ + }
305
+ +
306
+ + private static void WriteText(PackagePart part, string text)
307
+ + {
308
+ + using var stream = part.GetStream(FileMode.Create);
309
+ + using var writer = new StreamWriter(stream);
310
+ + writer.Write(text);
311
+ + }
312
+ + }
313
+ +}
harbor/tasks/open_xml_sdk_deletepart_refs_contract/solution/solve.sh ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs b/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs
6
+ index 69e37bc..ff549f5 100644
7
+ --- a/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs
8
+ +++ b/src/DocumentFormat.OpenXml.Framework/Features/StrictNamespaceExtensions.cs
9
+ @@ -53,12 +53,7 @@ internal static void UseTransitionalRelationshipNamespaces(this OpenXmlPackage p
10
+ {
11
+ if (alteredRelationships.TryGetValue(OpenXmlPackage.Uri, out var list))
12
+ {
13
+ - foreach (var toReplace in list)
14
+ - {
15
+ - package.Relationships.Remove(toReplace.Id);
16
+ - package.Relationships.Create(toReplace.TargetUri, toReplace.TargetMode, toReplace.RelationshipType, toReplace.Id);
17
+ - }
18
+ -
19
+ + ReplaceRelationships(package.Relationships, list);
20
+ alteredRelationships.Remove(OpenXmlPackage.Uri);
21
+ }
22
+ }
23
+ @@ -66,12 +61,7 @@ internal static void UseTransitionalRelationshipNamespaces(this OpenXmlPackage p
24
+ {
25
+ if (alteredRelationships.TryGetValue(part.Uri, out var list))
26
+ {
27
+ - foreach (var toReplace in list)
28
+ - {
29
+ - part.Relationships.Remove(toReplace.Id);
30
+ - part.Relationships.Create(toReplace.TargetUri, toReplace.TargetMode, toReplace.RelationshipType, toReplace.Id);
31
+ - }
32
+ -
33
+ + ReplaceRelationships(part.Relationships, list);
34
+ alteredRelationships.Remove(part.Uri);
35
+ }
36
+ }
37
+ @@ -79,6 +69,41 @@ internal static void UseTransitionalRelationshipNamespaces(this OpenXmlPackage p
38
+ }
39
+ }
40
+
41
+ + /// <summary>
42
+ + /// Rewrites the relationships whose namespace was translated when the package was loaded so the transitional
43
+ + /// namespace is persisted. Only relationships that still exist exactly as they were loaded are rewritten;
44
+ + /// a relationship that was deleted or re-identified in the meantime must not be resurrected, as that would
45
+ + /// leave the saved package with relationships leading to parts that no longer exist.
46
+ + /// </summary>
47
+ + private static void ReplaceRelationships(IRelationshipCollection relationships, List<PackageRelationshipBuilder> altered)
48
+ + {
49
+ + foreach (var toReplace in altered)
50
+ + {
51
+ + if (!relationships.Contains(toReplace.Id))
52
+ + {
53
+ + // Deleted (or its id was given up) since loading.
54
+ + continue;
55
+ + }
56
+ +
57
+ + var current = relationships[toReplace.Id];
58
+ +
59
+ + if (!ReferenceEquals(current, toReplace) && !IsSameRelationship(current, toReplace))
60
+ + {
61
+ + // The id now identifies a different relationship that was created after loading and is
62
+ + // therefore already persisted with the namespace it was created with.
63
+ + continue;
64
+ + }
65
+ +
66
+ + relationships.Remove(toReplace.Id);
67
+ + relationships.Create(toReplace.TargetUri, toReplace.TargetMode, toReplace.RelationshipType, toReplace.Id);
68
+ + }
69
+ + }
70
+ +
71
+ + private static bool IsSameRelationship(IPackageRelationship current, PackageRelationshipBuilder original)
72
+ + => current.TargetMode == original.TargetMode
73
+ + && string.Equals(current.RelationshipType, original.RelationshipType, StringComparison.Ordinal)
74
+ + && string.Equals(current.TargetUri.OriginalString, original.TargetUri.OriginalString, StringComparison.Ordinal);
75
+ +
76
+ private sealed class StrictNamespaceFeature : IStrictNamespaceFeature
77
+ {
78
+ private OpenXmlPackage? _package;
79
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs b/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs
80
+ index 5ebbd8d..51c456c 100644
81
+ --- a/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs
82
+ +++ b/src/DocumentFormat.OpenXml.Framework/Packaging/ExtendedPart.cs
83
+ @@ -90,6 +90,8 @@ internal override void InitPart(OpenXmlPart newPart, string contentType, string?
84
+ throw new ArgumentException(ExceptionMessages.StringArgumentEmptyException, nameof(contentType));
85
+ }
86
+
87
+ + ThrowIfRelationshipIdInUse(id, nameof(id));
88
+ +
89
+ newPart.CreateInternal(InternalOpenXmlPackage, ThisOpenXmlPart, contentType, targetExt: null);
90
+
91
+ ChildrenRelationshipParts.Add(newPart, id);
92
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs b/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs
93
+ index bd9d8e7..840cf05 100644
94
+ --- a/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs
95
+ +++ b/src/DocumentFormat.OpenXml.Framework/Packaging/OpenXmlPartContainer.cs
96
+ @@ -599,6 +599,9 @@ public string ChangeIdOfPart(OpenXmlPart part, string newRelationshipId)
97
+ throw new ArgumentOutOfRangeException(nameof(part));
98
+ }
99
+
100
+ + // the id may also be held by a relationship that is not to a part (hyperlink, external, data part)
101
+ + ThrowIfRelationshipIdInUse(newRelationshipId, nameof(newRelationshipId));
102
+ +
103
+ // Add a new relationship, and then remove the old relationship
104
+ ChildrenRelationshipParts.Add(part, newRelationshipId);
105
+ ChildrenRelationshipParts.Remove(oldId);
106
+ @@ -606,6 +609,18 @@ public string ChangeIdOfPart(OpenXmlPart part, string newRelationshipId)
107
+ return oldId;
108
+ }
109
+
110
+ + /// <summary>
111
+ + /// Throws when <paramref name="id"/> already names a relationship of this container, whether it targets a part
112
+ + /// or not (hyperlink, external or data part reference relationships share the same id space).
113
+ + /// </summary>
114
+ + internal void ThrowIfRelationshipIdInUse(string? id, string paramName)
115
+ + {
116
+ + if (id is not null && (ChildrenRelationshipParts.Contains(id) || Relationships.Contains(id)))
117
+ + {
118
+ + throw new ArgumentException(ExceptionMessages.RelationshipIdConflict, paramName);
119
+ + }
120
+ + }
121
+ +
122
+ /// <summary>
123
+ /// Adds the part to the document.
124
+ /// Must use the returned part to operate on the part added to the document.
125
+ @@ -1100,6 +1115,8 @@ internal virtual void InitPart(OpenXmlPart newPart, string contentType, string?
126
+ throw new ArgumentException(ExceptionMessages.StringArgumentEmptyException);
127
+ }
128
+
129
+ + ThrowIfRelationshipIdInUse(id, nameof(id));
130
+ +
131
+ if (Features.GetRequired<IPartConstraintFeature>().TryGetRule(newPart.RelationshipType, out var partConstraintRule))
132
+ {
133
+ if (!partConstraintRule.MaxOccursGreatThanOne)
134
+ @@ -1165,6 +1182,8 @@ internal virtual OpenXmlPart AddPartFrom(OpenXmlPart subPart, string? rId)
135
+ }
136
+ }
137
+
138
+ + ThrowIfRelationshipIdInUse(rId, nameof(rId));
139
+ +
140
+ if (Features.GetRequired<IPartConstraintFeature>().TryGetRule(subPart.RelationshipType, out var partConstraintRule))
141
+ {
142
+ if (partConstraintRule.ContentType is not null && subPart.ContentType != partConstraintRule.ContentType)
143
+ diff --git a/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs b/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs
144
+ index d2ca108..1360705 100644
145
+ --- a/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs
146
+ +++ b/src/DocumentFormat.OpenXml.Framework/Packaging/PackageFeatureCollection.cs
147
+ @@ -119,7 +119,22 @@ bool IPartsFeature.TryGetPart(Uri uri, [MaybeNullWhen(false)] out OpenXmlPart pa
148
+ }
149
+
150
+ void IPartsFeature.Add(Uri uri, OpenXmlPart part)
151
+ - => (_parts ??= new()).Add(uri, part);
152
+ + => (_parts ??= new(PartNameComparer.Instance)).Add(uri, part);
153
+ +
154
+ + /// <summary>
155
+ + /// Part names in a package are compared without regard to ASCII letter case, so two
156
+ + /// relationships whose targets differ only in case address the same part.
157
+ + /// </summary>
158
+ + private sealed class PartNameComparer : IEqualityComparer<Uri>
159
+ + {
160
+ + public static readonly PartNameComparer Instance = new();
161
+ +
162
+ + public bool Equals(Uri? x, Uri? y)
163
+ + => ReferenceEquals(x, y) || (x is not null && y is not null && StringComparer.OrdinalIgnoreCase.Equals(x.OriginalString, y.OriginalString));
164
+ +
165
+ + public int GetHashCode(Uri obj)
166
+ + => StringComparer.OrdinalIgnoreCase.GetHashCode(obj.OriginalString);
167
+ + }
168
+
169
+ bool IDataPartsFeature.Remove(DataPart dataPart)
170
+ {
171
+ diff --git a/test/DocumentFormat.OpenXml.Packaging.Tests/PartIdentityAndRelationshipIdTests.cs b/test/DocumentFormat.OpenXml.Packaging.Tests/PartIdentityAndRelationshipIdTests.cs
172
+ new file mode 100644
173
+ index 0000000..067c045
174
+ --- /dev/null
175
+ +++ b/test/DocumentFormat.OpenXml.Packaging.Tests/PartIdentityAndRelationshipIdTests.cs
176
+ @@ -0,0 +1,141 @@
177
+ +// Copyright (c) Microsoft. All rights reserved.
178
+ +// Licensed under the MIT license. See LICENSE file in the project root for full license information.
179
+ +
180
+ +using System;
181
+ +using System.IO;
182
+ +using System.IO.Packaging;
183
+ +using System.Linq;
184
+ +using Xunit;
185
+ +
186
+ +namespace DocumentFormat.OpenXml.Packaging.Tests
187
+ +{
188
+ + public class PartIdentityAndRelationshipIdTests
189
+ + {
190
+ + private const string MainType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml";
191
+ + private const string HeaderType = "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml";
192
+ + private const string RelImage = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
193
+ +
194
+ + [Fact]
195
+ + public void ReferencesDifferingOnlyInCaseLoadOnePart()
196
+ + {
197
+ + using var ms = CreateSharedImage("media/IMAGE1.png");
198
+ + using var doc = WordprocessingDocument.Open(ms, false);
199
+ +
200
+ + var main = doc.MainDocumentPart!;
201
+ + var header = main.HeaderParts.Single();
202
+ +
203
+ + Assert.Same(main.GetPartById("rIdImg"), header.GetPartById("rIdImgH"));
204
+ + }
205
+ +
206
+ + [Fact]
207
+ + public void DeletingSharedPartFromOneOwnerKeepsItForTheOther()
208
+ + {
209
+ + using var ms = CreateSharedImage("media/IMAGE1.png");
210
+ +
211
+ + using (var doc = WordprocessingDocument.Open(ms, true))
212
+ + {
213
+ + Assert.True(doc.MainDocumentPart!.DeletePart("rIdImg"));
214
+ + }
215
+ +
216
+ + using var reopened = WordprocessingDocument.Open(ms, false);
217
+ + var header = reopened.MainDocumentPart!.HeaderParts.Single();
218
+ +
219
+ + Assert.True(header.TryGetPartById("rIdImgH", out var image));
220
+ + Assert.IsType<ImagePart>(image);
221
+ + }
222
+ +
223
+ + [Fact]
224
+ + public void DeletingOwnerKeepsPartReferencedByAnotherOwner()
225
+ + {
226
+ + using var ms = CreateSharedImage("media/Image1.PNG");
227
+ +
228
+ + using (var doc = WordprocessingDocument.Open(ms, true))
229
+ + {
230
+ + Assert.True(doc.MainDocumentPart!.DeletePart("rIdHdr"));
231
+ + }
232
+ +
233
+ + using var reopened = WordprocessingDocument.Open(ms, false);
234
+ +
235
+ + Assert.True(reopened.MainDocumentPart!.TryGetPartById("rIdImg", out _));
236
+ + }
237
+ +
238
+ + [Fact]
239
+ + public void ChangeIdOfPartRejectsIdOfHyperlink()
240
+ + {
241
+ + using var ms = new MemoryStream();
242
+ + using var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
243
+ +
244
+ + var main = doc.AddMainDocumentPart();
245
+ + var image = main.AddImagePart(ImagePartType.Png, "rIdPic");
246
+ + main.AddHyperlinkRelationship(new Uri("http://example.com/"), true, "rIdLink");
247
+ +
248
+ + Assert.Throws<ArgumentException>(() => main.ChangeIdOfPart(image, "rIdLink"));
249
+ + Assert.Equal("rIdPic", main.GetIdOfPart(image));
250
+ + Assert.Single(main.HyperlinkRelationships);
251
+ + }
252
+ +
253
+ + [Fact]
254
+ + public void AddNewPartRejectsIdOfExternalRelationship()
255
+ + {
256
+ + using var ms = new MemoryStream();
257
+ + using var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
258
+ +
259
+ + var main = doc.AddMainDocumentPart();
260
+ + main.AddExternalRelationship("http://example.com/rel", new Uri("http://example.com/"), "rIdExt");
261
+ +
262
+ + Assert.Throws<ArgumentException>(() => main.AddImagePart(ImagePartType.Png, "rIdExt"));
263
+ + Assert.Empty(main.ImageParts);
264
+ + }
265
+ +
266
+ + [Fact]
267
+ + public void CreateRelationshipToPartRejectsIdOfHyperlink()
268
+ + {
269
+ + using var ms = new MemoryStream();
270
+ + using var doc = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
271
+ +
272
+ + var main = doc.AddMainDocumentPart();
273
+ + var image = main.AddImagePart(ImagePartType.Png);
274
+ + var header = main.AddNewPart<HeaderPart>();
275
+ + header.AddHyperlinkRelationship(new Uri("http://example.com/"), true, "rIdLink");
276
+ +
277
+ + Assert.Throws<ArgumentException>(() => header.CreateRelationshipToPart(image, "rIdLink"));
278
+ + Assert.Empty(header.Parts);
279
+ + }
280
+ +
281
+ + private static MemoryStream CreateSharedImage(string headerTarget)
282
+ + {
283
+ + var ms = new MemoryStream();
284
+ +
285
+ + using (var package = Package.Open(ms, FileMode.Create, FileAccess.ReadWrite))
286
+ + {
287
+ + var documentUri = new Uri("/word/document.xml", UriKind.Relative);
288
+ + var headerUri = new Uri("/word/header1.xml", UriKind.Relative);
289
+ + var document = package.CreatePart(documentUri, MainType);
290
+ + var header = package.CreatePart(headerUri, HeaderType);
291
+ + var image = package.CreatePart(new Uri("/word/media/image1.png", UriKind.Relative), "image/png");
292
+ +
293
+ + WriteText(document, "<w:document xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"><w:body/></w:document>");
294
+ + WriteText(header, "<w:hdr xmlns:w=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"/>");
295
+ +
296
+ + using (var stream = image.GetStream())
297
+ + {
298
+ + stream.Write(new byte[] { 1, 2, 3 }, 0, 3);
299
+ + }
300
+ +
301
+ + package.CreateRelationship(documentUri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument", "rId1");
302
+ + document.CreateRelationship(new Uri("header1.xml", UriKind.Relative), TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/header", "rIdHdr");
303
+ + document.CreateRelationship(new Uri("media/image1.png", UriKind.Relative), TargetMode.Internal, RelImage, "rIdImg");
304
+ + header.CreateRelationship(new Uri(headerTarget, UriKind.Relative), TargetMode.Internal, RelImage, "rIdImgH");
305
+ + }
306
+ +
307
+ + return ms;
308
+ + }
309
+ +
310
+ + private static void WriteText(PackagePart part, string text)
311
+ + {
312
+ + using var stream = part.GetStream(FileMode.Create);
313
+ + using var writer = new StreamWriter(stream);
314
+ + writer.Write(text);
315
+ + }
316
+ + }
317
+ +}
318
+
319
+ REFERENCE_PATCH
harbor/tasks/open_xml_sdk_deletepart_refs_contract/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "open_xml_sdk_deletepart_refs_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/open_xml_sdk_deletepart_refs_contract/tests/Dockerfile ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-open-xml-sdk:source-v5
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
+ RUN chmod -R a+rX /hud/base_sha
5
+ RUN chmod -R a+rX /hud/calibrate.py
6
+ RUN chmod -R a+rX /hud/calibration.txt
7
+ RUN chmod -R a+rX /hud/empty-feed
8
+ RUN chmod -R a+rX /hud/tasks.py
9
+ RUN chown -R 1000:1000 /hud/dotnet-home
10
+ ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
11
+ RUN rm -f /hud/gold.diff
12
+ COPY verify.py evidence.py config.json test.sh /tests/
13
+ RUN chmod 755 /tests/test.sh
14
+ WORKDIR /app
15
+ CMD ["sleep", "infinity"]
harbor/tasks/open_xml_sdk_deletepart_refs_contract/tests/config.json ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "open_xml_sdk_deletepart_refs_contract",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-open-xml-sdk:source-v5",
7
+ "source_image_id": "sha256:08241d754d266184c4a57f7dd3bdd9b75a3bb9aa6214a0021123c9053608ff76",
8
+ "provenance": {
9
+ "repository": "dotnet/Open-XML-SDK",
10
+ "environment_id": "4141b6e3-d06d-46bf-b8fb-6ab051a0fce9",
11
+ "build": 5,
12
+ "build_id": "8238997f-bc16-46bc-9e16-d9026b70f326",
13
+ "hosted_task": "open_xml_sdk_deletepart_refs_contract-1c066303",
14
+ "task_version": 1,
15
+ "source_archive_sha256": "abcc9b94e6a5a1ef4f9bc17f885822e56ebc1deaf87504725ed93656a5dbbf23",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "removing_a_shared_part_from_one_owner_keeps_it_for_the_others",
21
+ 0.1,
22
+ true,
23
+ "bash",
24
+ 900
25
+ ],
26
+ [
27
+ "changing_a_part_id_to_a_taken_id_is_refused",
28
+ 0.09,
29
+ false,
30
+ "bash",
31
+ 900
32
+ ],
33
+ [
34
+ "adding_a_part_under_a_taken_id_is_refused",
35
+ 0.09,
36
+ false,
37
+ "bash",
38
+ 900
39
+ ],
40
+ [
41
+ "relating_a_part_under_a_taken_id_is_refused",
42
+ 0.09,
43
+ false,
44
+ "bash",
45
+ 900
46
+ ],
47
+ [
48
+ "copying_a_part_from_another_document_under_a_taken_id_is_refused",
49
+ 0.09,
50
+ false,
51
+ "bash",
52
+ 900
53
+ ],
54
+ [
55
+ "a_deleted_part_leaves_nothing_leading_to_it_after_saving",
56
+ 0.26,
57
+ false,
58
+ "bash",
59
+ 900
60
+ ],
61
+ [
62
+ "an_id_given_back_by_a_delete_leads_to_the_part_that_took_it",
63
+ 0.26,
64
+ false,
65
+ "bash",
66
+ 900
67
+ ],
68
+ [
69
+ "gate_repo_suite_green_and_tests_untouched",
70
+ 0.02,
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
+ "/hud/base_sha",
82
+ "/hud/calibrate.py",
83
+ "/hud/calibration.txt",
84
+ "/hud/empty-feed",
85
+ "/hud/tasks.py"
86
+ ],
87
+ "grader_writable": [
88
+ "/hud/dotnet-home"
89
+ ],
90
+ "blocker_cap": 0.6,
91
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
92
+ "verifier_files": {
93
+ "/app/tasks.py": "f753d247c7673592516e3808091de8ac8555d97994d10f1b5c3eca9d48140d44",
94
+ "/app/env.py": "8c5657ef04817aea9e2daa5fabf91826c2accfc14a71a85be817d360d72da810",
95
+ "/app/task/prompt.md": "34611c2c9f1b517f58ff29e1da24ad77814222e76a15e2fd99d1342517fbdfc6",
96
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
97
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
98
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
99
+ "/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
100
+ "/hud/grader/run_grading.sh": "8a63fca0e3e43ba061afb853d7ba66ca81c9448f68596943fd10b4fb8cf8db42",
101
+ "/hud/grader/controls/lazy-case.diff": "d2339ff85590fcb6c9ffb9e0df904cec035e2f86ed5a1adb05e70ff50113177b",
102
+ "/hud/grader/controls/lazy-both.diff": "d18145badc146f845931521bc65bc49d81a5363bfca6a558c714fbfe71a18d58",
103
+ "/hud/grader/controls/lazy-changeid.diff": "ce3c12527c2160098204d77c06145edada40a0d73cc38bd2efaac363cce9d37e",
104
+ "/hud/grader/controls/lazy-strict1.diff": "e3adb2ebbcb06888315a3dc683a0c1ca814ace35208a45b2f864b5211c09067d",
105
+ "/hud/grader/controls/alt.diff": "d32bf8a8393b002c669d4184451d4e9f0dc495387382327b915e0b6c4f1fa93f",
106
+ "/hud/grader/controls/cheat-keep-bytes.diff": "38d7777c9d1cc9edf8ffd1178dc2b2a0ae5a83a2cf16332ab4e8c2b97d417679",
107
+ "/hud/grader/controls/cheat-tests-edited.diff": "fca5e82cb79f9598a9f740461cc7ad26d53973ea8c436fcf3d7d31abf2cf5398",
108
+ "/hud/grader/controls/noop.diff": "cd547b99021c0a52702bf7c6bd4b3635964d40c025dfda5c87090913af368384",
109
+ "/hud/grader/spec/DeletePartRefsSpec.cs": "8f1cd5f80d73310f378459885d87a6fe72897af71e5e889cb00b40d14eb54bd3",
110
+ "/hud/grader/spec/GraderSpec.csproj": "99fe092a4ab1edbd2e0bbf31f436d9a8fe741909ca35f8a199760b09a1225659"
111
+ },
112
+ "preflight": [
113
+ [
114
+ "/bin/bash",
115
+ "--version"
116
+ ],
117
+ [
118
+ "setpriv",
119
+ "--version"
120
+ ],
121
+ [
122
+ "git",
123
+ "--version"
124
+ ],
125
+ [
126
+ "bash",
127
+ "-c",
128
+ "bash -lc 'dotnet --version' || dotnet --version"
129
+ ],
130
+ [
131
+ "/usr/bin/python3",
132
+ "--version"
133
+ ]
134
+ ]
135
+ }
harbor/tasks/open_xml_sdk_deletepart_refs_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/open_xml_sdk_deletepart_refs_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/open_xml_sdk_deletepart_refs_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/open_xml_sdk_deletepart_refs_contract/tests/verify.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/proxy_cookie_accounting/environment/Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-oauth2-proxy:source-v6 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/proxy_cookie_accounting/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/proxy_cookie_accounting/environment/capture_submission.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Capture tracked and new SWE files without changing the agent's Git index."""
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import os
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/proxy_cookie_accounting/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/proxy_cookie_accounting/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/proxy_cookie_accounting/instruction.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ # Ticket
4
+
5
+ Every oauth2-proxy cookie a request carries must be one the proxy still accounts
6
+ for: written by it, addressed to a configured domain containing that host, and
7
+ kept, replaced, or expired, each once, by the response it triggers, with expiry
8
+ reserved for what a rewrite orphans or a configured count cannot hold, the newest
9
+ kept.
10
+
11
+ Finish with a final response when your changes are ready.
harbor/tasks/proxy_cookie_accounting/solution/reference.patch ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/pkg/cookies/cookies.go b/pkg/cookies/cookies.go
2
+ index be5ee451..5427b20d 100644
3
+ --- a/pkg/cookies/cookies.go
4
+ +++ b/pkg/cookies/cookies.go
5
+ @@ -60,14 +60,30 @@ func MakeCookieFromOptions(req *http.Request, opts *CookieOptions) *http.Cookie
6
+ // by checking the X-Fowarded-Host and host header of an an http request
7
+ func GetCookieDomain(req *http.Request, cookieDomains []string) string {
8
+ host := requestutil.GetRequestHost(req)
9
+ + if h, _, err := net.SplitHostPort(host); err == nil {
10
+ + host = h
11
+ + }
12
+ for _, domain := range cookieDomains {
13
+ - if strings.HasSuffix(host, domain) {
14
+ + if hostInDomain(host, domain) {
15
+ return domain
16
+ }
17
+ }
18
+ return ""
19
+ }
20
+
21
+ +// hostInDomain reports whether host sits inside the cookie domain. Membership
22
+ +// is decided on whole DNS labels: sharing a character suffix with the domain
23
+ +// is not the same as being part of it.
24
+ +func hostInDomain(host, domain string) bool {
25
+ + if host == "" || domain == "" {
26
+ + return false
27
+ + }
28
+ + if strings.HasPrefix(domain, ".") {
29
+ + return strings.HasSuffix(host, domain)
30
+ + }
31
+ + return host == domain || strings.HasSuffix(host, "."+domain)
32
+ +}
33
+ +
34
+ // ParseSameSite a valid http.SameSite value from a user supplied string for use of making cookies.
35
+ func ParseSameSite(v string) http.SameSite {
36
+ switch v {
37
+ diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go
38
+ index 2614f378..ddd09737 100644
39
+ --- a/pkg/cookies/csrf.go
40
+ +++ b/pkg/cookies/csrf.go
41
+ @@ -191,24 +191,52 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht
42
+ }
43
+
44
+ decodedCookies := []*csrf{}
45
+ + undecodableCookies := []*http.Cookie{}
46
+ for _, cookie := range existingCsrfCookies {
47
+ decodedCookie, err := decodeCSRFCookie(cookie, opts)
48
+ if err != nil {
49
+ + undecodableCookies = append(undecodableCookies, cookie)
50
+ continue
51
+ }
52
+ decodedCookies = append(decodedCookies, decodedCookie)
53
+ }
54
+
55
+ - // delete the X oldest cookies
56
+ + // delete the X oldest cookies, counting every CSRF cookie the request
57
+ + // carries. Cookies that no longer decode can never be used again, so they
58
+ + // go first.
59
+ slices.SortStableFunc(decodedCookies, func(a, b *csrf) int {
60
+ return a.clock().Compare(b.clock())
61
+ })
62
+
63
+ - for i := 0; i < len(decodedCookies)-opts.CSRFPerRequestLimit; i++ {
64
+ + excess := len(existingCsrfCookies) - opts.CSRFPerRequestLimit
65
+ + for _, cookie := range undecodableCookies {
66
+ + if excess <= 0 {
67
+ + break
68
+ + }
69
+ + clearCsrfCookieByName(opts, rw, req, cookie.Name)
70
+ + excess--
71
+ + }
72
+ + for i := 0; i < len(decodedCookies) && excess > 0; i++ {
73
+ decodedCookies[i].ClearCookie(rw, req)
74
+ + excess--
75
+ }
76
+ }
77
+
78
+ +// clearCsrfCookieByName removes a CSRF cookie the proxy could not decode, and
79
+ +// so has no csrf value to rebuild the name from.
80
+ +func clearCsrfCookieByName(opts *options.Cookie, rw http.ResponseWriter, req *http.Request, name string) {
81
+ + http.SetCookie(rw, MakeCookieFromOptions(req, &CookieOptions{
82
+ + Name: name,
83
+ + Value: "",
84
+ + Domains: opts.Domains,
85
+ + Expiration: time.Hour * -1,
86
+ + SameSite: getCSRFSameSite(opts),
87
+ + Path: opts.Path,
88
+ + HTTPOnly: opts.HTTPOnly,
89
+ + Secure: opts.Secure,
90
+ + }))
91
+ +}
92
+ +
93
+ // ClearCookie removes the CSRF cookie
94
+ func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) {
95
+ csrfCookieOptions := &CookieOptions{
96
+ diff --git a/pkg/sessions/cookie/session_store.go b/pkg/sessions/cookie/session_store.go
97
+ index a4da3734..3e44a99a 100644
98
+ --- a/pkg/sessions/cookie/session_store.go
99
+ +++ b/pkg/sessions/cookie/session_store.go
100
+ @@ -5,7 +5,8 @@ import (
101
+ "errors"
102
+ "fmt"
103
+ "net/http"
104
+ - "regexp"
105
+ + "strconv"
106
+ + "strings"
107
+ "time"
108
+
109
+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
110
+ @@ -71,30 +72,47 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
111
+ // Clear clears any saved session information by writing a cookie to
112
+ // clear the session
113
+ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
114
+ - // matches CookieName, CookieName_<number>
115
+ - var cookieNameRegex = regexp.MustCompile(fmt.Sprintf("^%s(_\\d+)?$", s.Cookie.Name))
116
+ -
117
+ for _, c := range req.Cookies() {
118
+ - if cookieNameRegex.MatchString(c.Name) {
119
+ - sessionCookieOptions := &pkgcookies.CookieOptions{
120
+ - Name: c.Name,
121
+ - Value: "",
122
+ - Domains: s.Cookie.Domains,
123
+ - Expiration: time.Hour * -1,
124
+ - SameSite: s.Cookie.SameSite,
125
+ - Path: s.Cookie.Path,
126
+ - HTTPOnly: s.Cookie.HTTPOnly,
127
+ - Secure: s.Cookie.Secure,
128
+ - }
129
+ - clearCookie := pkgcookies.MakeCookieFromOptions(req, sessionCookieOptions)
130
+ -
131
+ - http.SetCookie(rw, clearCookie)
132
+ + if s.ownsCookieName(c.Name) {
133
+ + http.SetCookie(rw, s.expireCookie(req, c.Name))
134
+ }
135
+ }
136
+
137
+ return nil
138
+ }
139
+
140
+ +// ownsCookieName reports whether name is one of the names this store writes
141
+ +// the session under: the configured name, or one of the chunk names produced
142
+ +// by splitCookieName for it.
143
+ +func (s *SessionStore) ownsCookieName(name string) bool {
144
+ + if name == s.Cookie.Name {
145
+ + return true
146
+ + }
147
+ + i := strings.LastIndex(name, "_")
148
+ + if i < 0 {
149
+ + return false
150
+ + }
151
+ + count, err := strconv.Atoi(name[i+1:])
152
+ + if err != nil || count < 0 {
153
+ + return false
154
+ + }
155
+ + return splitCookieName(s.Cookie.Name, count) == name
156
+ +}
157
+ +
158
+ +// expireCookie builds a cookie that asks the client to drop name.
159
+ +func (s *SessionStore) expireCookie(req *http.Request, name string) *http.Cookie {
160
+ + return pkgcookies.MakeCookieFromOptions(req, &pkgcookies.CookieOptions{
161
+ + Name: name,
162
+ + Value: "",
163
+ + Domains: s.Cookie.Domains,
164
+ + Expiration: time.Hour * -1,
165
+ + SameSite: s.Cookie.SameSite,
166
+ + Path: s.Cookie.Path,
167
+ + HTTPOnly: s.Cookie.HTTPOnly,
168
+ + Secure: s.Cookie.Secure,
169
+ + })
170
+ +}
171
+ +
172
+ // VerifyConnection always return no-error, as there's no connection
173
+ // in this store
174
+ func (s *SessionStore) VerifyConnection(_ context.Context) error {
175
+ @@ -121,8 +139,21 @@ func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Reques
176
+ if err != nil {
177
+ return err
178
+ }
179
+ + written := make(map[string]struct{}, len(cookies))
180
+ for _, c := range cookies {
181
+ http.SetCookie(rw, c)
182
+ + written[c.Name] = struct{}{}
183
+ + }
184
+ + // A session that needs a different number of cookies than the one already
185
+ + // on the client leaves names behind. Those are still sent back on the next
186
+ + // request and would be joined into the value, so expire them here.
187
+ + for _, c := range req.Cookies() {
188
+ + if _, rewritten := written[c.Name]; rewritten {
189
+ + continue
190
+ + }
191
+ + if s.ownsCookieName(c.Name) {
192
+ + http.SetCookie(rw, s.expireCookie(req, c.Name))
193
+ + }
194
+ }
195
+ return nil
196
+ }
harbor/tasks/proxy_cookie_accounting/solution/solve.sh ADDED
@@ -0,0 +1,202 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/pkg/cookies/cookies.go b/pkg/cookies/cookies.go
6
+ index be5ee451..5427b20d 100644
7
+ --- a/pkg/cookies/cookies.go
8
+ +++ b/pkg/cookies/cookies.go
9
+ @@ -60,14 +60,30 @@ func MakeCookieFromOptions(req *http.Request, opts *CookieOptions) *http.Cookie
10
+ // by checking the X-Fowarded-Host and host header of an an http request
11
+ func GetCookieDomain(req *http.Request, cookieDomains []string) string {
12
+ host := requestutil.GetRequestHost(req)
13
+ + if h, _, err := net.SplitHostPort(host); err == nil {
14
+ + host = h
15
+ + }
16
+ for _, domain := range cookieDomains {
17
+ - if strings.HasSuffix(host, domain) {
18
+ + if hostInDomain(host, domain) {
19
+ return domain
20
+ }
21
+ }
22
+ return ""
23
+ }
24
+
25
+ +// hostInDomain reports whether host sits inside the cookie domain. Membership
26
+ +// is decided on whole DNS labels: sharing a character suffix with the domain
27
+ +// is not the same as being part of it.
28
+ +func hostInDomain(host, domain string) bool {
29
+ + if host == "" || domain == "" {
30
+ + return false
31
+ + }
32
+ + if strings.HasPrefix(domain, ".") {
33
+ + return strings.HasSuffix(host, domain)
34
+ + }
35
+ + return host == domain || strings.HasSuffix(host, "."+domain)
36
+ +}
37
+ +
38
+ // ParseSameSite a valid http.SameSite value from a user supplied string for use of making cookies.
39
+ func ParseSameSite(v string) http.SameSite {
40
+ switch v {
41
+ diff --git a/pkg/cookies/csrf.go b/pkg/cookies/csrf.go
42
+ index 2614f378..ddd09737 100644
43
+ --- a/pkg/cookies/csrf.go
44
+ +++ b/pkg/cookies/csrf.go
45
+ @@ -191,24 +191,52 @@ func ClearExtraCsrfCookies(opts *options.Cookie, rw http.ResponseWriter, req *ht
46
+ }
47
+
48
+ decodedCookies := []*csrf{}
49
+ + undecodableCookies := []*http.Cookie{}
50
+ for _, cookie := range existingCsrfCookies {
51
+ decodedCookie, err := decodeCSRFCookie(cookie, opts)
52
+ if err != nil {
53
+ + undecodableCookies = append(undecodableCookies, cookie)
54
+ continue
55
+ }
56
+ decodedCookies = append(decodedCookies, decodedCookie)
57
+ }
58
+
59
+ - // delete the X oldest cookies
60
+ + // delete the X oldest cookies, counting every CSRF cookie the request
61
+ + // carries. Cookies that no longer decode can never be used again, so they
62
+ + // go first.
63
+ slices.SortStableFunc(decodedCookies, func(a, b *csrf) int {
64
+ return a.clock().Compare(b.clock())
65
+ })
66
+
67
+ - for i := 0; i < len(decodedCookies)-opts.CSRFPerRequestLimit; i++ {
68
+ + excess := len(existingCsrfCookies) - opts.CSRFPerRequestLimit
69
+ + for _, cookie := range undecodableCookies {
70
+ + if excess <= 0 {
71
+ + break
72
+ + }
73
+ + clearCsrfCookieByName(opts, rw, req, cookie.Name)
74
+ + excess--
75
+ + }
76
+ + for i := 0; i < len(decodedCookies) && excess > 0; i++ {
77
+ decodedCookies[i].ClearCookie(rw, req)
78
+ + excess--
79
+ }
80
+ }
81
+
82
+ +// clearCsrfCookieByName removes a CSRF cookie the proxy could not decode, and
83
+ +// so has no csrf value to rebuild the name from.
84
+ +func clearCsrfCookieByName(opts *options.Cookie, rw http.ResponseWriter, req *http.Request, name string) {
85
+ + http.SetCookie(rw, MakeCookieFromOptions(req, &CookieOptions{
86
+ + Name: name,
87
+ + Value: "",
88
+ + Domains: opts.Domains,
89
+ + Expiration: time.Hour * -1,
90
+ + SameSite: getCSRFSameSite(opts),
91
+ + Path: opts.Path,
92
+ + HTTPOnly: opts.HTTPOnly,
93
+ + Secure: opts.Secure,
94
+ + }))
95
+ +}
96
+ +
97
+ // ClearCookie removes the CSRF cookie
98
+ func (c *csrf) ClearCookie(rw http.ResponseWriter, req *http.Request) {
99
+ csrfCookieOptions := &CookieOptions{
100
+ diff --git a/pkg/sessions/cookie/session_store.go b/pkg/sessions/cookie/session_store.go
101
+ index a4da3734..3e44a99a 100644
102
+ --- a/pkg/sessions/cookie/session_store.go
103
+ +++ b/pkg/sessions/cookie/session_store.go
104
+ @@ -5,7 +5,8 @@ import (
105
+ "errors"
106
+ "fmt"
107
+ "net/http"
108
+ - "regexp"
109
+ + "strconv"
110
+ + "strings"
111
+ "time"
112
+
113
+ "github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/options"
114
+ @@ -71,30 +72,47 @@ func (s *SessionStore) Load(req *http.Request) (*sessions.SessionState, error) {
115
+ // Clear clears any saved session information by writing a cookie to
116
+ // clear the session
117
+ func (s *SessionStore) Clear(rw http.ResponseWriter, req *http.Request) error {
118
+ - // matches CookieName, CookieName_<number>
119
+ - var cookieNameRegex = regexp.MustCompile(fmt.Sprintf("^%s(_\\d+)?$", s.Cookie.Name))
120
+ -
121
+ for _, c := range req.Cookies() {
122
+ - if cookieNameRegex.MatchString(c.Name) {
123
+ - sessionCookieOptions := &pkgcookies.CookieOptions{
124
+ - Name: c.Name,
125
+ - Value: "",
126
+ - Domains: s.Cookie.Domains,
127
+ - Expiration: time.Hour * -1,
128
+ - SameSite: s.Cookie.SameSite,
129
+ - Path: s.Cookie.Path,
130
+ - HTTPOnly: s.Cookie.HTTPOnly,
131
+ - Secure: s.Cookie.Secure,
132
+ - }
133
+ - clearCookie := pkgcookies.MakeCookieFromOptions(req, sessionCookieOptions)
134
+ -
135
+ - http.SetCookie(rw, clearCookie)
136
+ + if s.ownsCookieName(c.Name) {
137
+ + http.SetCookie(rw, s.expireCookie(req, c.Name))
138
+ }
139
+ }
140
+
141
+ return nil
142
+ }
143
+
144
+ +// ownsCookieName reports whether name is one of the names this store writes
145
+ +// the session under: the configured name, or one of the chunk names produced
146
+ +// by splitCookieName for it.
147
+ +func (s *SessionStore) ownsCookieName(name string) bool {
148
+ + if name == s.Cookie.Name {
149
+ + return true
150
+ + }
151
+ + i := strings.LastIndex(name, "_")
152
+ + if i < 0 {
153
+ + return false
154
+ + }
155
+ + count, err := strconv.Atoi(name[i+1:])
156
+ + if err != nil || count < 0 {
157
+ + return false
158
+ + }
159
+ + return splitCookieName(s.Cookie.Name, count) == name
160
+ +}
161
+ +
162
+ +// expireCookie builds a cookie that asks the client to drop name.
163
+ +func (s *SessionStore) expireCookie(req *http.Request, name string) *http.Cookie {
164
+ + return pkgcookies.MakeCookieFromOptions(req, &pkgcookies.CookieOptions{
165
+ + Name: name,
166
+ + Value: "",
167
+ + Domains: s.Cookie.Domains,
168
+ + Expiration: time.Hour * -1,
169
+ + SameSite: s.Cookie.SameSite,
170
+ + Path: s.Cookie.Path,
171
+ + HTTPOnly: s.Cookie.HTTPOnly,
172
+ + Secure: s.Cookie.Secure,
173
+ + })
174
+ +}
175
+ +
176
+ // VerifyConnection always return no-error, as there's no connection
177
+ // in this store
178
+ func (s *SessionStore) VerifyConnection(_ context.Context) error {
179
+ @@ -121,8 +139,21 @@ func (s *SessionStore) setSessionCookie(rw http.ResponseWriter, req *http.Reques
180
+ if err != nil {
181
+ return err
182
+ }
183
+ + written := make(map[string]struct{}, len(cookies))
184
+ for _, c := range cookies {
185
+ http.SetCookie(rw, c)
186
+ + written[c.Name] = struct{}{}
187
+ + }
188
+ + // A session that needs a different number of cookies than the one already
189
+ + // on the client leaves names behind. Those are still sent back on the next
190
+ + // request and would be joined into the value, so expire them here.
191
+ + for _, c := range req.Cookies() {
192
+ + if _, rewritten := written[c.Name]; rewritten {
193
+ + continue
194
+ + }
195
+ + if s.ownsCookieName(c.Name) {
196
+ + http.SetCookie(rw, s.expireCookie(req, c.Name))
197
+ + }
198
+ }
199
+ return nil
200
+ }
201
+
202
+ REFERENCE_PATCH
harbor/tasks/proxy_cookie_accounting/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "proxy_cookie_accounting"
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/proxy_cookie_accounting/tests/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-oauth2-proxy:source-v6
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/proxy_cookie_accounting/tests/config.json ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "proxy_cookie_accounting",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-oauth2-proxy:source-v6",
7
+ "source_image_id": "sha256:f458bc6c808c6bf24c501a7a777a485be2bdfa355d80deab706e76b033e42f76",
8
+ "provenance": {
9
+ "repository": "oauth2-proxy/oauth2-proxy",
10
+ "environment_id": "21d03058-9a87-4082-91ac-8a37fa04985e",
11
+ "build": 6,
12
+ "build_id": "bce968e3-7b09-41ef-8b7b-1a5461c4f6ac",
13
+ "hosted_task": "proxy_cookie_accounting",
14
+ "task_version": "12d0d99f-af9a-4044-8663-e10099ec4bb2",
15
+ "source_archive_sha256": "84c89ee639044e27ed5331ba6b3b107a49b4101a44fdbfaaf2ec9e227da4d9a0",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "C7_trim_counts_repeated_names",
21
+ 0.2,
22
+ true,
23
+ "bash",
24
+ 1800
25
+ ],
26
+ [
27
+ "C8_shrink_retires_every_carried_chunk",
28
+ 0.18,
29
+ false,
30
+ "bash",
31
+ 600
32
+ ],
33
+ [
34
+ "C11_repeats_expiry_addressed_like_the_write",
35
+ 0.13,
36
+ false,
37
+ "bash",
38
+ 600
39
+ ],
40
+ [
41
+ "C9_clear_retires_every_carried_chunk",
42
+ 0.12,
43
+ false,
44
+ "bash",
45
+ 600
46
+ ],
47
+ [
48
+ "C10_repeat_trim_keeps_the_newest",
49
+ 0.12,
50
+ false,
51
+ "bash",
52
+ 600
53
+ ],
54
+ [
55
+ "C12_names_the_proxy_never_writes",
56
+ 0.08,
57
+ false,
58
+ "bash",
59
+ 600
60
+ ],
61
+ [
62
+ "C6_trim_counts_every_carried_cookie",
63
+ 0.04,
64
+ false,
65
+ "bash",
66
+ 600
67
+ ],
68
+ [
69
+ "C3_clear_truncated_chunk_names",
70
+ 0.03,
71
+ false,
72
+ "bash",
73
+ 600
74
+ ],
75
+ [
76
+ "C1_expiry_addressed_like_the_write",
77
+ 0.03,
78
+ false,
79
+ "bash",
80
+ 600
81
+ ],
82
+ [
83
+ "C4_domain_longest_match_with_port",
84
+ 0.02,
85
+ false,
86
+ "bash",
87
+ 600
88
+ ],
89
+ [
90
+ "C5_domain_label_boundary",
91
+ 0.02,
92
+ false,
93
+ "bash",
94
+ 600
95
+ ],
96
+ [
97
+ "B1_session_survives_resave",
98
+ 0.01,
99
+ false,
100
+ "bash",
101
+ 600
102
+ ],
103
+ [
104
+ "G1_repo_suite_green",
105
+ 0.01,
106
+ true,
107
+ "gate",
108
+ 600
109
+ ],
110
+ [
111
+ "G2_repo_test_files_untouched",
112
+ 0.01,
113
+ true,
114
+ "gate",
115
+ 600
116
+ ]
117
+ ],
118
+ "gates": [
119
+ "G1_repo_suite_green",
120
+ "G2_repo_test_files_untouched"
121
+ ],
122
+ "reward_rule": "weighted_cap",
123
+ "local_hostname": false,
124
+ "fault_exit": 3,
125
+ "grader_readable": [],
126
+ "grader_writable": [],
127
+ "blocker_cap": 0.6,
128
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
129
+ "verifier_files": {
130
+ "/app/tasks.py": "bfaef0bf2a52eb79310d2e9255b346b085b9408e32f9a271329ba4344792e2b1",
131
+ "/app/env.py": "7d13ca56b594b8259c5d426845646b3cc98d20e7059f1891a4a555e65f59f17d",
132
+ "/app/task/prompt.md": "5ba3add9f83990b60819cd934661e196c847fc25e648c2e27214437fb0029902",
133
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
134
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
135
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
136
+ "/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
137
+ "/hud/grader/board.json": "227ba229409114c271e86887e04a430c80a0172ed13ce5eece4a8ad671dbb300",
138
+ "/hud/grader/run_grading.sh": "02a06368421136ca0b04f3eb1f6e8708d708ec6280c52a76ea3f22ab930ab521",
139
+ "/hud/grader/zzharness/harness_test.go": "dc9561139f6aa5173cf262a2175cc3b52f01d29c988b06d207b5df1abe2647b2"
140
+ },
141
+ "preflight": [
142
+ [
143
+ "/bin/bash",
144
+ "--version"
145
+ ],
146
+ [
147
+ "setpriv",
148
+ "--version"
149
+ ],
150
+ [
151
+ "git",
152
+ "--version"
153
+ ],
154
+ [
155
+ "bash",
156
+ "-c",
157
+ "bash -lc 'go version' || go version"
158
+ ],
159
+ [
160
+ "/usr/local/bin/python3",
161
+ "--version"
162
+ ]
163
+ ]
164
+ }
harbor/tasks/proxy_cookie_accounting/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/proxy_cookie_accounting/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/proxy_cookie_accounting/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/proxy_cookie_accounting/tests/verify.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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()