servicesToptal commited on
Commit
66b737d
·
verified ·
1 Parent(s): bdbf8e2

Update dataset (part 2)

Browse files
README.md CHANGED
@@ -298,7 +298,7 @@ empty change scores 0, and the reference fix scores 1.0 with every criterion
298
  equal to the task's original grading. The folder contains the reference fixes
299
  and the hidden graders, as the rows of this dataset do.
300
 
301
- 11 more (badger, bazel-remote, celery, geode, kratos, microblogpub, open-xml-sdk, openfire, terser, umya, zettlr) are packaged and are being re-checked; they are added
302
  as each one passes.
303
 
304
  Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
 
298
  equal to the task's original grading. The folder contains the reference fixes
299
  and the hidden graders, as the rows of this dataset do.
300
 
301
+ 10 more (badger, bazel-remote, geode, kratos, microblogpub, open-xml-sdk, openfire, terser, umya, zettlr) are packaged and are being re-checked; they are added
302
  as each one passes.
303
 
304
  Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
harbor/tasks/celery_retry_expires_countdown_contract/environment/Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-celery:source-v12 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="/opt/agentvenv/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
8
+ ENV LANG="C.UTF-8"
9
+ ENV PYTHONUNBUFFERED="1"
10
+ ENV PYTHONNOUSERSITE="1"
11
+ ENV PYTHONPATH="/workspace/repo"
12
+ ENV PYTHONDONTWRITEBYTECODE="1"
13
+ ENV HOME="/tmp/agent-home"
14
+ ENV GOCACHE="/tmp/agent-home/.cache/go-build"
15
+ ENV HUD_TELEMETRY_ENABLED="false"
16
+ ENV HUD_CLI_ANALYTICS_ENABLED="0"
17
+ WORKDIR /workspace/repo
18
+ USER 1000:1000
19
+ CMD ["sleep", "infinity"]
harbor/tasks/celery_retry_expires_countdown_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/celery_retry_expires_countdown_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/celery_retry_expires_countdown_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/celery_retry_expires_countdown_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/celery_retry_expires_countdown_contract/instruction.md ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ # Ticket
4
+
5
+ We set an expiry on calls and rely on it as a fixed deadline, whether the task runs in a worker or in the caller's own process. Workers already drop deliveries that arrive after it. Where it showed up for us was retries: a task retrying with a countdown that runs past its expiry still publishes the retry, which is only thrown away later.
6
+
7
+ The deadline should hold everywhere: no retry moves or clears it, and anything due at or after it ends at once, a retry unsent, failing the task as out of retries, a delivery discarded as expired on receipt, that discard reported to the caller and to monitors as a revocation that expired. Discarding a delivery ends that delivery, not the call.
8
+
9
+ Some things are fine today and should stay that way: calls without an expiry behave as before, an expiry given in seconds or as a date is the same deadline, and max_retries still caps retries. Existing test files stay green and unedited.
10
+
11
+ Finish with a final response when your changes are ready.
harbor/tasks/celery_retry_expires_countdown_contract/solution/reference.patch ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/celery/app/task.py b/celery/app/task.py
2
+ index ada306e..619d0fb 100644
3
+ --- a/celery/app/task.py
4
+ +++ b/celery/app/task.py
5
+ @@ -1,6 +1,8 @@
6
+ """Task implementation: request context and the task base class."""
7
+ +import numbers
8
+ import sys
9
+ import types
10
+ +from datetime import datetime, timedelta
11
+
12
+ from billiard.einfo import ExceptionInfo, ExceptionWithTraceback
13
+ from kombu import serialization
14
+ @@ -18,6 +20,7 @@ from celery.utils.functional import mattrgetter, maybe_list
15
+ from celery.utils.imports import instantiate
16
+ from celery.utils.nodenames import gethostname
17
+ from celery.utils.serialization import raise_with_context
18
+ +from celery.utils.time import maybe_iso8601, maybe_make_aware
19
+
20
+ from .annotations import resolve_all as resolve_all_annotations
21
+ from .registry import _unpickle_task_v2
22
+ @@ -843,6 +846,11 @@ class Task:
23
+ countdown = self.default_retry_delay
24
+
25
+ is_eager = request.is_eager
26
+ + # The expiry given by the original call is a fixed deadline: a retry
27
+ + # can neither move it nor clear it.
28
+ + deadline = request.expires
29
+ + if deadline:
30
+ + options['expires'] = deadline
31
+ S = self.signature_from_request(
32
+ request, args, kwargs,
33
+ countdown=countdown, eta=eta, retries=retries,
34
+ @@ -860,6 +868,17 @@ class Task:
35
+ ), task_args=S.args, task_kwargs=S.kwargs
36
+ )
37
+
38
+ + if deadline and self._retry_runs_past(eta, countdown, deadline):
39
+ + # A retry that would only run at or after the deadline could never
40
+ + # run: the task is out of retries.
41
+ + if exc:
42
+ + raise_with_context(exc)
43
+ + raise self.MaxRetriesExceededError(
44
+ + "Can't retry {}[{}] past its expiry {} args:{} kwargs:{}".format(
45
+ + self.name, request.id, deadline, S.args, S.kwargs
46
+ + ), task_args=S.args, task_kwargs=S.kwargs
47
+ + )
48
+ +
49
+ ret = Retry(exc=exc, when=eta or countdown, is_eager=is_eager, sig=S)
50
+
51
+ if is_eager:
52
+ @@ -877,6 +896,32 @@ class Task:
53
+ raise ret
54
+ return ret
55
+
56
+ + def _retry_runs_past(self, eta, countdown, deadline):
57
+ + """Whether a retry at ``eta``/``countdown`` starts at or after ``deadline``."""
58
+ + if isinstance(deadline, numbers.Real):
59
+ + return False
60
+ + app = self._get_app()
61
+ + tz = app.timezone
62
+ + deadline = maybe_make_aware(maybe_iso8601(deadline), tz)
63
+ + # The message is built with countdown taking precedence over eta
64
+ + # (celery.app.amqp.AMQP.as_task_v2), so that is when the retry is due.
65
+ + if countdown:
66
+ + run_at = maybe_make_aware(
67
+ + app.now() + timedelta(seconds=countdown), tz)
68
+ + elif eta:
69
+ + run_at = maybe_make_aware(maybe_iso8601(eta), tz)
70
+ + else:
71
+ + run_at = maybe_make_aware(app.now(), tz)
72
+ + return run_at >= deadline
73
+ +
74
+ + def _absolute_expires(self, expires):
75
+ + """The expiry of a call as an absolute ISO 8601 deadline (or None)."""
76
+ + if expires is None or isinstance(expires, str):
77
+ + return expires
78
+ + if isinstance(expires, datetime):
79
+ + return expires.isoformat()
80
+ + return (self._get_app().now() + timedelta(seconds=expires)).isoformat()
81
+ +
82
+ def apply(self, args=None, kwargs=None,
83
+ link=None, link_error=None,
84
+ task_id=None, retries=None, throw=None,
85
+ @@ -932,6 +977,7 @@ class Task:
86
+ else [self.time_limit, self.soft_time_limit]
87
+ ),
88
+ 'ignore_result': options.get('ignore_result', False),
89
+ + 'expires': self._absolute_expires(options.get('expires')),
90
+ 'delivery_info': {
91
+ 'is_eager': True,
92
+ 'exchange': options.get('exchange'),
93
+ diff --git a/celery/worker/strategy.py b/celery/worker/strategy.py
94
+ index 6a1c622..8cea85f 100644
95
+ --- a/celery/worker/strategy.py
96
+ +++ b/celery/worker/strategy.py
97
+ @@ -187,6 +187,14 @@ def default(task, app, consumer,
98
+ error("Couldn't convert ETA %r to timestamp: %r. Task: %r",
99
+ req.eta, exc, req.info(safe=True), exc_info=True)
100
+ req.reject(requeue=False)
101
+ + if eta and req.expires and req.eta >= req.expires:
102
+ + # Scheduled to start at or after its expiry, it can never run:
103
+ + # discard it as expired now instead of holding it until then.
104
+ + info('Discarding task scheduled past its expiry: %s[%s]',
105
+ + req.name, req.id)
106
+ + req._announce_revoked('expired', False, None, True)
107
+ + return
108
+ +
109
+ if rate_limits_enabled:
110
+ bucket = get_bucket(task.name)
111
+
112
+ diff --git a/t/unit/tasks/test_retry_expiry_deadline.py b/t/unit/tasks/test_retry_expiry_deadline.py
113
+ new file mode 100644
114
+ index 0000000..8a0c8b3
115
+ --- /dev/null
116
+ +++ b/t/unit/tasks/test_retry_expiry_deadline.py
117
+ @@ -0,0 +1,104 @@
118
+ +"""The expiry given by the original call is a fixed deadline for its retries."""
119
+ +from datetime import datetime, timedelta, timezone
120
+ +from unittest.mock import ANY, patch
121
+ +
122
+ +import pytest
123
+ +
124
+ +from celery.exceptions import MaxRetriesExceededError
125
+ +from celery.utils.time import maybe_iso8601
126
+ +
127
+ +
128
+ +class test_retry_expiry_deadline:
129
+ +
130
+ + def setup_method(self):
131
+ + runs = self.runs = []
132
+ +
133
+ + @self.app.task(bind=True, shared=False, max_retries=5)
134
+ + def flaky(self, countdown=None, eta=None, exc=None, **retry_options):
135
+ + runs.append(self.request.retries)
136
+ + if self.request.retries >= 1:
137
+ + return 'done'
138
+ + raise self.retry(countdown=countdown, eta=eta, exc=exc,
139
+ + **retry_options)
140
+ +
141
+ + self.flaky = flaky
142
+ + self.deadline = datetime.now(timezone.utc) + timedelta(seconds=300)
143
+ +
144
+ + def _retry(self, **kwargs):
145
+ + self.flaky.push_request(
146
+ + id='task-id', args=(), kwargs={}, retries=0, is_eager=False,
147
+ + called_directly=False, expires=self.deadline.isoformat(),
148
+ + )
149
+ + try:
150
+ + with patch.object(self.app, 'send_task') as send_task:
151
+ + try:
152
+ + self.flaky.retry(**kwargs)
153
+ + except MaxRetriesExceededError as exc:
154
+ + return send_task, exc
155
+ + except ValueError as exc:
156
+ + return send_task, exc
157
+ + except Exception as exc: # Retry
158
+ + return send_task, exc
159
+ + finally:
160
+ + self.flaky.pop_request()
161
+ +
162
+ + def _sent_deadline(self, send_task):
163
+ + send_task.assert_called_once_with(ANY, ANY, ANY, **{
164
+ + k: ANY for k in send_task.call_args.kwargs})
165
+ + return maybe_iso8601(send_task.call_args.kwargs['expires'])
166
+ +
167
+ + def test_retry_after_deadline_is_not_sent(self):
168
+ + send_task, raised = self._retry(countdown=600)
169
+ + send_task.assert_not_called()
170
+ + assert isinstance(raised, MaxRetriesExceededError)
171
+ +
172
+ + def test_retry_after_deadline_reraises_given_exception(self):
173
+ + send_task, raised = self._retry(countdown=600, exc=ValueError('boom'))
174
+ + send_task.assert_not_called()
175
+ + assert isinstance(raised, ValueError)
176
+ +
177
+ + def test_retry_exactly_at_deadline_is_not_sent(self):
178
+ + send_task, raised = self._retry(eta=self.deadline)
179
+ + send_task.assert_not_called()
180
+ + assert isinstance(raised, MaxRetriesExceededError)
181
+ +
182
+ + def test_retry_with_countdown_past_deadline_is_not_sent_even_with_earlier_eta(self):
183
+ + # The message is built with the countdown taking precedence over the
184
+ + # eta (celery.app.amqp.AMQP.as_task_v2), so this retry would start at
185
+ + # now + 600s, past the deadline, however early the eta beside it is.
186
+ + send_task, raised = self._retry(
187
+ + eta=self.deadline - timedelta(seconds=60), countdown=600)
188
+ + send_task.assert_not_called()
189
+ + assert isinstance(raised, MaxRetriesExceededError)
190
+ +
191
+ + def test_retry_before_deadline_keeps_deadline(self):
192
+ + send_task, _ = self._retry(eta=self.deadline - timedelta(seconds=1))
193
+ + assert self._sent_deadline(send_task) == self.deadline
194
+ +
195
+ + @pytest.mark.parametrize('retry_expires', [3600, None, 'later'])
196
+ + def test_retry_cannot_move_or_clear_deadline(self, retry_expires):
197
+ + if retry_expires == 'later':
198
+ + retry_expires = (self.deadline + timedelta(days=1)).isoformat()
199
+ + send_task, _ = self._retry(countdown=10, expires=retry_expires)
200
+ + assert self._sent_deadline(send_task) == self.deadline
201
+ +
202
+ + def test_eager_retry_after_deadline_is_not_run(self):
203
+ + res = self.flaky.apply(kwargs={'countdown': 600}, expires=120)
204
+ + assert self.runs == [0]
205
+ + assert res.state == 'FAILURE'
206
+ + assert isinstance(res.result, MaxRetriesExceededError)
207
+ +
208
+ + def test_always_eager_retry_after_deadline_is_not_run(self):
209
+ + self.app.conf.task_always_eager = True
210
+ + try:
211
+ + res = self.flaky.apply_async(kwargs={'countdown': 600},
212
+ + expires=self.deadline)
213
+ + finally:
214
+ + self.app.conf.task_always_eager = False
215
+ + assert self.runs == [0]
216
+ + assert res.state == 'FAILURE'
217
+ +
218
+ + def test_eager_retry_inside_deadline_runs(self):
219
+ + res = self.flaky.apply(kwargs={'countdown': 5}, expires=300)
220
+ + assert self.runs == [0, 1]
221
+ + assert res.get() == 'done'
222
+ diff --git a/t/unit/worker/test_strategy_expiry_deadline.py b/t/unit/worker/test_strategy_expiry_deadline.py
223
+ new file mode 100644
224
+ index 0000000..dc9eb67
225
+ --- /dev/null
226
+ +++ b/t/unit/worker/test_strategy_expiry_deadline.py
227
+ @@ -0,0 +1,57 @@
228
+ +"""A delivery scheduled to start at or after its expiry is dropped on receipt."""
229
+ +from datetime import datetime, timedelta, timezone
230
+ +from unittest.mock import Mock
231
+ +
232
+ +import pytest
233
+ +
234
+ +from celery import signals
235
+ +from celery.contrib.testing.mocks import task_message_from_sig
236
+ +
237
+ +
238
+ +class test_strategy_expiry_deadline:
239
+ +
240
+ + def setup_method(self):
241
+ + @self.app.task(shared=False)
242
+ + def add(x, y):
243
+ + return x + y
244
+ +
245
+ + self.add = add
246
+ + self.deadline = datetime.now(timezone.utc) + timedelta(seconds=300)
247
+ +
248
+ + def _receive(self, eta, rate_limits=False):
249
+ + reserved = Mock()
250
+ + consumer = Mock()
251
+ + consumer.task_buckets = {self.add.name: None}
252
+ + consumer.controller.state.revoked = set()
253
+ + consumer.disable_rate_limits = not rate_limits
254
+ + consumer.event_dispatcher.enabled = False
255
+ + handler = self.add.start_strategy(self.app, consumer,
256
+ + task_reserved=reserved)
257
+ + sig = self.add.s(2, 2).set(eta=eta, expires=self.deadline)
258
+ + message = task_message_from_sig(self.app, sig)
259
+ + revoked = []
260
+ +
261
+ + def on_revoked(request=None, expired=None, **kwargs):
262
+ + revoked.append(expired)
263
+ +
264
+ + signals.task_revoked.connect(on_revoked, weak=False)
265
+ + try:
266
+ + handler(message, None, message.ack, message.reject, [])
267
+ + finally:
268
+ + signals.task_revoked.disconnect(on_revoked)
269
+ + return consumer, reserved, revoked
270
+ +
271
+ + @pytest.mark.parametrize('rate_limits', [False, True])
272
+ + @pytest.mark.parametrize('offset', [0, 60])
273
+ + def test_eta_at_or_after_deadline_is_dropped(self, offset, rate_limits):
274
+ + consumer, reserved, revoked = self._receive(
275
+ + self.deadline + timedelta(seconds=offset), rate_limits)
276
+ + assert not consumer.timer.call_at.called
277
+ + assert not reserved.called
278
+ + assert revoked == [True]
279
+ +
280
+ + def test_eta_before_deadline_is_scheduled(self):
281
+ + consumer, reserved, revoked = self._receive(
282
+ + self.deadline - timedelta(seconds=60))
283
+ + assert consumer.timer.call_at.called
284
+ + assert revoked == []
harbor/tasks/celery_retry_expires_countdown_contract/solution/solve.sh ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/celery/app/task.py b/celery/app/task.py
6
+ index ada306e..619d0fb 100644
7
+ --- a/celery/app/task.py
8
+ +++ b/celery/app/task.py
9
+ @@ -1,6 +1,8 @@
10
+ """Task implementation: request context and the task base class."""
11
+ +import numbers
12
+ import sys
13
+ import types
14
+ +from datetime import datetime, timedelta
15
+
16
+ from billiard.einfo import ExceptionInfo, ExceptionWithTraceback
17
+ from kombu import serialization
18
+ @@ -18,6 +20,7 @@ from celery.utils.functional import mattrgetter, maybe_list
19
+ from celery.utils.imports import instantiate
20
+ from celery.utils.nodenames import gethostname
21
+ from celery.utils.serialization import raise_with_context
22
+ +from celery.utils.time import maybe_iso8601, maybe_make_aware
23
+
24
+ from .annotations import resolve_all as resolve_all_annotations
25
+ from .registry import _unpickle_task_v2
26
+ @@ -843,6 +846,11 @@ class Task:
27
+ countdown = self.default_retry_delay
28
+
29
+ is_eager = request.is_eager
30
+ + # The expiry given by the original call is a fixed deadline: a retry
31
+ + # can neither move it nor clear it.
32
+ + deadline = request.expires
33
+ + if deadline:
34
+ + options['expires'] = deadline
35
+ S = self.signature_from_request(
36
+ request, args, kwargs,
37
+ countdown=countdown, eta=eta, retries=retries,
38
+ @@ -860,6 +868,17 @@ class Task:
39
+ ), task_args=S.args, task_kwargs=S.kwargs
40
+ )
41
+
42
+ + if deadline and self._retry_runs_past(eta, countdown, deadline):
43
+ + # A retry that would only run at or after the deadline could never
44
+ + # run: the task is out of retries.
45
+ + if exc:
46
+ + raise_with_context(exc)
47
+ + raise self.MaxRetriesExceededError(
48
+ + "Can't retry {}[{}] past its expiry {} args:{} kwargs:{}".format(
49
+ + self.name, request.id, deadline, S.args, S.kwargs
50
+ + ), task_args=S.args, task_kwargs=S.kwargs
51
+ + )
52
+ +
53
+ ret = Retry(exc=exc, when=eta or countdown, is_eager=is_eager, sig=S)
54
+
55
+ if is_eager:
56
+ @@ -877,6 +896,32 @@ class Task:
57
+ raise ret
58
+ return ret
59
+
60
+ + def _retry_runs_past(self, eta, countdown, deadline):
61
+ + """Whether a retry at ``eta``/``countdown`` starts at or after ``deadline``."""
62
+ + if isinstance(deadline, numbers.Real):
63
+ + return False
64
+ + app = self._get_app()
65
+ + tz = app.timezone
66
+ + deadline = maybe_make_aware(maybe_iso8601(deadline), tz)
67
+ + # The message is built with countdown taking precedence over eta
68
+ + # (celery.app.amqp.AMQP.as_task_v2), so that is when the retry is due.
69
+ + if countdown:
70
+ + run_at = maybe_make_aware(
71
+ + app.now() + timedelta(seconds=countdown), tz)
72
+ + elif eta:
73
+ + run_at = maybe_make_aware(maybe_iso8601(eta), tz)
74
+ + else:
75
+ + run_at = maybe_make_aware(app.now(), tz)
76
+ + return run_at >= deadline
77
+ +
78
+ + def _absolute_expires(self, expires):
79
+ + """The expiry of a call as an absolute ISO 8601 deadline (or None)."""
80
+ + if expires is None or isinstance(expires, str):
81
+ + return expires
82
+ + if isinstance(expires, datetime):
83
+ + return expires.isoformat()
84
+ + return (self._get_app().now() + timedelta(seconds=expires)).isoformat()
85
+ +
86
+ def apply(self, args=None, kwargs=None,
87
+ link=None, link_error=None,
88
+ task_id=None, retries=None, throw=None,
89
+ @@ -932,6 +977,7 @@ class Task:
90
+ else [self.time_limit, self.soft_time_limit]
91
+ ),
92
+ 'ignore_result': options.get('ignore_result', False),
93
+ + 'expires': self._absolute_expires(options.get('expires')),
94
+ 'delivery_info': {
95
+ 'is_eager': True,
96
+ 'exchange': options.get('exchange'),
97
+ diff --git a/celery/worker/strategy.py b/celery/worker/strategy.py
98
+ index 6a1c622..8cea85f 100644
99
+ --- a/celery/worker/strategy.py
100
+ +++ b/celery/worker/strategy.py
101
+ @@ -187,6 +187,14 @@ def default(task, app, consumer,
102
+ error("Couldn't convert ETA %r to timestamp: %r. Task: %r",
103
+ req.eta, exc, req.info(safe=True), exc_info=True)
104
+ req.reject(requeue=False)
105
+ + if eta and req.expires and req.eta >= req.expires:
106
+ + # Scheduled to start at or after its expiry, it can never run:
107
+ + # discard it as expired now instead of holding it until then.
108
+ + info('Discarding task scheduled past its expiry: %s[%s]',
109
+ + req.name, req.id)
110
+ + req._announce_revoked('expired', False, None, True)
111
+ + return
112
+ +
113
+ if rate_limits_enabled:
114
+ bucket = get_bucket(task.name)
115
+
116
+ diff --git a/t/unit/tasks/test_retry_expiry_deadline.py b/t/unit/tasks/test_retry_expiry_deadline.py
117
+ new file mode 100644
118
+ index 0000000..8a0c8b3
119
+ --- /dev/null
120
+ +++ b/t/unit/tasks/test_retry_expiry_deadline.py
121
+ @@ -0,0 +1,104 @@
122
+ +"""The expiry given by the original call is a fixed deadline for its retries."""
123
+ +from datetime import datetime, timedelta, timezone
124
+ +from unittest.mock import ANY, patch
125
+ +
126
+ +import pytest
127
+ +
128
+ +from celery.exceptions import MaxRetriesExceededError
129
+ +from celery.utils.time import maybe_iso8601
130
+ +
131
+ +
132
+ +class test_retry_expiry_deadline:
133
+ +
134
+ + def setup_method(self):
135
+ + runs = self.runs = []
136
+ +
137
+ + @self.app.task(bind=True, shared=False, max_retries=5)
138
+ + def flaky(self, countdown=None, eta=None, exc=None, **retry_options):
139
+ + runs.append(self.request.retries)
140
+ + if self.request.retries >= 1:
141
+ + return 'done'
142
+ + raise self.retry(countdown=countdown, eta=eta, exc=exc,
143
+ + **retry_options)
144
+ +
145
+ + self.flaky = flaky
146
+ + self.deadline = datetime.now(timezone.utc) + timedelta(seconds=300)
147
+ +
148
+ + def _retry(self, **kwargs):
149
+ + self.flaky.push_request(
150
+ + id='task-id', args=(), kwargs={}, retries=0, is_eager=False,
151
+ + called_directly=False, expires=self.deadline.isoformat(),
152
+ + )
153
+ + try:
154
+ + with patch.object(self.app, 'send_task') as send_task:
155
+ + try:
156
+ + self.flaky.retry(**kwargs)
157
+ + except MaxRetriesExceededError as exc:
158
+ + return send_task, exc
159
+ + except ValueError as exc:
160
+ + return send_task, exc
161
+ + except Exception as exc: # Retry
162
+ + return send_task, exc
163
+ + finally:
164
+ + self.flaky.pop_request()
165
+ +
166
+ + def _sent_deadline(self, send_task):
167
+ + send_task.assert_called_once_with(ANY, ANY, ANY, **{
168
+ + k: ANY for k in send_task.call_args.kwargs})
169
+ + return maybe_iso8601(send_task.call_args.kwargs['expires'])
170
+ +
171
+ + def test_retry_after_deadline_is_not_sent(self):
172
+ + send_task, raised = self._retry(countdown=600)
173
+ + send_task.assert_not_called()
174
+ + assert isinstance(raised, MaxRetriesExceededError)
175
+ +
176
+ + def test_retry_after_deadline_reraises_given_exception(self):
177
+ + send_task, raised = self._retry(countdown=600, exc=ValueError('boom'))
178
+ + send_task.assert_not_called()
179
+ + assert isinstance(raised, ValueError)
180
+ +
181
+ + def test_retry_exactly_at_deadline_is_not_sent(self):
182
+ + send_task, raised = self._retry(eta=self.deadline)
183
+ + send_task.assert_not_called()
184
+ + assert isinstance(raised, MaxRetriesExceededError)
185
+ +
186
+ + def test_retry_with_countdown_past_deadline_is_not_sent_even_with_earlier_eta(self):
187
+ + # The message is built with the countdown taking precedence over the
188
+ + # eta (celery.app.amqp.AMQP.as_task_v2), so this retry would start at
189
+ + # now + 600s, past the deadline, however early the eta beside it is.
190
+ + send_task, raised = self._retry(
191
+ + eta=self.deadline - timedelta(seconds=60), countdown=600)
192
+ + send_task.assert_not_called()
193
+ + assert isinstance(raised, MaxRetriesExceededError)
194
+ +
195
+ + def test_retry_before_deadline_keeps_deadline(self):
196
+ + send_task, _ = self._retry(eta=self.deadline - timedelta(seconds=1))
197
+ + assert self._sent_deadline(send_task) == self.deadline
198
+ +
199
+ + @pytest.mark.parametrize('retry_expires', [3600, None, 'later'])
200
+ + def test_retry_cannot_move_or_clear_deadline(self, retry_expires):
201
+ + if retry_expires == 'later':
202
+ + retry_expires = (self.deadline + timedelta(days=1)).isoformat()
203
+ + send_task, _ = self._retry(countdown=10, expires=retry_expires)
204
+ + assert self._sent_deadline(send_task) == self.deadline
205
+ +
206
+ + def test_eager_retry_after_deadline_is_not_run(self):
207
+ + res = self.flaky.apply(kwargs={'countdown': 600}, expires=120)
208
+ + assert self.runs == [0]
209
+ + assert res.state == 'FAILURE'
210
+ + assert isinstance(res.result, MaxRetriesExceededError)
211
+ +
212
+ + def test_always_eager_retry_after_deadline_is_not_run(self):
213
+ + self.app.conf.task_always_eager = True
214
+ + try:
215
+ + res = self.flaky.apply_async(kwargs={'countdown': 600},
216
+ + expires=self.deadline)
217
+ + finally:
218
+ + self.app.conf.task_always_eager = False
219
+ + assert self.runs == [0]
220
+ + assert res.state == 'FAILURE'
221
+ +
222
+ + def test_eager_retry_inside_deadline_runs(self):
223
+ + res = self.flaky.apply(kwargs={'countdown': 5}, expires=300)
224
+ + assert self.runs == [0, 1]
225
+ + assert res.get() == 'done'
226
+ diff --git a/t/unit/worker/test_strategy_expiry_deadline.py b/t/unit/worker/test_strategy_expiry_deadline.py
227
+ new file mode 100644
228
+ index 0000000..dc9eb67
229
+ --- /dev/null
230
+ +++ b/t/unit/worker/test_strategy_expiry_deadline.py
231
+ @@ -0,0 +1,57 @@
232
+ +"""A delivery scheduled to start at or after its expiry is dropped on receipt."""
233
+ +from datetime import datetime, timedelta, timezone
234
+ +from unittest.mock import Mock
235
+ +
236
+ +import pytest
237
+ +
238
+ +from celery import signals
239
+ +from celery.contrib.testing.mocks import task_message_from_sig
240
+ +
241
+ +
242
+ +class test_strategy_expiry_deadline:
243
+ +
244
+ + def setup_method(self):
245
+ + @self.app.task(shared=False)
246
+ + def add(x, y):
247
+ + return x + y
248
+ +
249
+ + self.add = add
250
+ + self.deadline = datetime.now(timezone.utc) + timedelta(seconds=300)
251
+ +
252
+ + def _receive(self, eta, rate_limits=False):
253
+ + reserved = Mock()
254
+ + consumer = Mock()
255
+ + consumer.task_buckets = {self.add.name: None}
256
+ + consumer.controller.state.revoked = set()
257
+ + consumer.disable_rate_limits = not rate_limits
258
+ + consumer.event_dispatcher.enabled = False
259
+ + handler = self.add.start_strategy(self.app, consumer,
260
+ + task_reserved=reserved)
261
+ + sig = self.add.s(2, 2).set(eta=eta, expires=self.deadline)
262
+ + message = task_message_from_sig(self.app, sig)
263
+ + revoked = []
264
+ +
265
+ + def on_revoked(request=None, expired=None, **kwargs):
266
+ + revoked.append(expired)
267
+ +
268
+ + signals.task_revoked.connect(on_revoked, weak=False)
269
+ + try:
270
+ + handler(message, None, message.ack, message.reject, [])
271
+ + finally:
272
+ + signals.task_revoked.disconnect(on_revoked)
273
+ + return consumer, reserved, revoked
274
+ +
275
+ + @pytest.mark.parametrize('rate_limits', [False, True])
276
+ + @pytest.mark.parametrize('offset', [0, 60])
277
+ + def test_eta_at_or_after_deadline_is_dropped(self, offset, rate_limits):
278
+ + consumer, reserved, revoked = self._receive(
279
+ + self.deadline + timedelta(seconds=offset), rate_limits)
280
+ + assert not consumer.timer.call_at.called
281
+ + assert not reserved.called
282
+ + assert revoked == [True]
283
+ +
284
+ + def test_eta_before_deadline_is_scheduled(self):
285
+ + consumer, reserved, revoked = self._receive(
286
+ + self.deadline - timedelta(seconds=60))
287
+ + assert consumer.timer.call_at.called
288
+ + assert revoked == []
289
+
290
+ REFERENCE_PATCH
harbor/tasks/celery_retry_expires_countdown_contract/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "celery_retry_expires_countdown_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/celery_retry_expires_countdown_contract/tests/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-celery:source-v12
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/celery_retry_expires_countdown_contract/tests/config.json ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "celery_retry_expires_countdown_contract",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-celery:source-v12",
7
+ "source_image_id": "sha256:b59d3e620f4a1b1e16fbf8a1465daea4b1d37c12108eb8bd4d8f6975ee6136cd",
8
+ "provenance": {
9
+ "repository": "celery/celery",
10
+ "environment_id": "120273dd-1c9c-41d8-a1a1-45689ed9db14",
11
+ "build": 12,
12
+ "build_id": "3bc62c1d-033f-4d17-8458-d3f18a5353d8",
13
+ "hosted_task": "celery_retry_expires_countdown_contract",
14
+ "task_version": 8,
15
+ "source_archive_sha256": "8a80cd86fa99b775f44c94525e49b0a2dcac0da1a676003cc615d42367e1e950",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "retry_past_deadline_is_not_sent",
21
+ 0.09,
22
+ true,
23
+ "bash",
24
+ 600
25
+ ],
26
+ [
27
+ "retry_cannot_move_or_clear_deadline",
28
+ 0.07,
29
+ false,
30
+ "bash",
31
+ 600
32
+ ],
33
+ [
34
+ "eager_run_honours_deadline",
35
+ 0.07,
36
+ false,
37
+ "bash",
38
+ 600
39
+ ],
40
+ [
41
+ "retry_due_by_countdown_past_deadline_is_not_sent",
42
+ 0.07,
43
+ false,
44
+ "bash",
45
+ 600
46
+ ],
47
+ [
48
+ "delivery_scheduled_past_deadline_dropped_on_receipt",
49
+ 0.12,
50
+ false,
51
+ "bash",
52
+ 600
53
+ ],
54
+ [
55
+ "expired_delivery_outcome_is_revoked",
56
+ 0.19,
57
+ false,
58
+ "bash",
59
+ 600
60
+ ],
61
+ [
62
+ "expired_delivery_announced_to_monitors",
63
+ 0.19,
64
+ false,
65
+ "bash",
66
+ 600
67
+ ],
68
+ [
69
+ "discarded_delivery_does_not_revoke_the_call",
70
+ 0.19,
71
+ false,
72
+ "bash",
73
+ 600
74
+ ],
75
+ [
76
+ "gate_repo_suite_green_and_tests_untouched",
77
+ 0.01,
78
+ true,
79
+ "bash",
80
+ 1800
81
+ ]
82
+ ],
83
+ "gates": [],
84
+ "reward_rule": "weighted_cap",
85
+ "local_hostname": false,
86
+ "fault_exit": 3,
87
+ "grader_readable": [],
88
+ "grader_writable": [],
89
+ "blocker_cap": 0.6,
90
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
91
+ "verifier_files": {
92
+ "/app/env.py": "6a239c604eaf5e839018fa69cf3ba85e98e2bb0fe902cde4b82653c8be542e8e",
93
+ "/app/tasks.py": "fd2d22dc91aff67df560189eada02c53d0184b38f652968da3c6740efb652e18",
94
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
95
+ "/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
96
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
97
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
98
+ "/app/task/prompt.md": "c030c10f98599a520ea0ad07ebcf6bf95c42b43c7fbcd1438a67d870643fc965",
99
+ "/hud/grader/run_grading.sh": "07ca34d1dbc78a055cae51867c5da26615df6c7217686ce754ef5f9cc72748b9",
100
+ "/hud/grader/suite_deselect.txt": "a5d6a8df2b8d703402f3582aad58457725ff273e34c67989c6054d71f4f03d7b",
101
+ "/hud/grader/cells/spec_cells.py": "47c7f8ca6e284806077729f2bb4b00e81a40bad14805e87c56f359569a8ed2f4"
102
+ },
103
+ "preflight": [
104
+ [
105
+ "/bin/bash",
106
+ "--version"
107
+ ],
108
+ [
109
+ "setpriv",
110
+ "--version"
111
+ ],
112
+ [
113
+ "git",
114
+ "--version"
115
+ ],
116
+ [
117
+ "bash",
118
+ "-c",
119
+ "bash -lc 'python --version' || python --version"
120
+ ],
121
+ [
122
+ "/opt/agentvenv/bin/python",
123
+ "--version"
124
+ ]
125
+ ]
126
+ }
harbor/tasks/celery_retry_expires_countdown_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/celery_retry_expires_countdown_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/celery_retry_expires_countdown_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/celery_retry_expires_countdown_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/manifest.json CHANGED
@@ -1,6 +1,7 @@
1
  {
2
  "revision": "coding-rubric-v2",
3
  "tasks": [
 
4
  "coredns_rewrite_svcb_opt",
5
  "epicyon_deleted_post_announce_cache_contract",
6
  "rope_rename_all_reexport_owners_contract",
 
1
  {
2
  "revision": "coding-rubric-v2",
3
  "tasks": [
4
+ "celery_retry_expires_countdown_contract",
5
  "coredns_rewrite_svcb_opt",
6
  "epicyon_deleted_post_announce_cache_contract",
7
  "rope_rename_all_reexport_owners_contract",