Datasets:
Tasks:
Text Generation
Formats:
parquet
Sub-tasks:
language-modeling
Languages:
English
Size:
< 1K
License:
Update dataset (part 2)
Browse files- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/environment/Dockerfile +24 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/environment/capture.py +28 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/environment/capture_submission.py +157 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/environment/docker-compose.yaml +11 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/environment/sanitize.py +25 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/instruction.md +17 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/solution/reference.patch +510 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/solution/solve.sh +516 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/task.toml +26 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/tests/Dockerfile +9 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/tests/config.json +127 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/tests/docker-compose.yaml +6 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/tests/evidence.py +123 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/tests/test.sh +3 -0
- harbor/tasks/kratos_cleanup_stale_flows_courier_contract/tests/verify.py +235 -0
- harbor/tasks/manifest.json +1 -0
harbor/tasks/kratos_cleanup_stale_flows_courier_contract/environment/Dockerfile
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-kratos: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/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/kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_contract/instruction.md
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Please make your changes directly in /workspace/repo.
|
| 2 |
+
|
| 3 |
+
# Ticket
|
| 4 |
+
|
| 5 |
+
Two reports about the courier came in after the last deploy.
|
| 6 |
+
|
| 7 |
+
The first one is about the restart. The deploy stopped the workers in the middle of their batches, and the mail they had picked up stayed in processing; the new workers never touched it. Mail a dead or stopped worker claimed over an hour ago is retried as usual, and one a live worker just claimed is never taken by another. No user should see the same email twice.
|
| 8 |
+
|
| 9 |
+
There is a second half to that report. A worker takes several messages at once, and when one of them cannot be handed over, everything else it had taken is put back for anyone to pick up while the worker is still going through the batch; a second worker then starts on that same mail before the first one has finished with it. Only the message that could not be handed over belongs back in the queue. The rest stay with the worker that took them until it has sent them or given up on them, no other worker sends them or is handed them in the meantime, and each of them still arrives exactly once.
|
| 10 |
+
|
| 11 |
+
The second one is about disk. `cleanup sql` purges expired flows as it always has, but sent and abandoned mail past retention, with its delivery attempts, is never removed, while mail that is queued or being sent has to stay. Every other table the command cleans is a single step that follows its batch size and network, and courier history should be no different.
|
| 12 |
+
|
| 13 |
+
We checked: none of this needs a schema change, a new dependency, or a new flag or config key.
|
| 14 |
+
|
| 15 |
+
Existing tests stay green and unedited.
|
| 16 |
+
|
| 17 |
+
Finish with a final response when your changes are ready.
|
harbor/tasks/kratos_cleanup_stale_flows_courier_contract/solution/reference.patch
ADDED
|
@@ -0,0 +1,510 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
diff --git a/courier/courier_dispatcher.go b/courier/courier_dispatcher.go
|
| 2 |
+
index 288d1f30..8e3da6f6 100644
|
| 3 |
+
--- a/courier/courier_dispatcher.go
|
| 4 |
+
+++ b/courier/courier_dispatcher.go
|
| 5 |
+
@@ -113,6 +113,13 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 6 |
+
span.SetAttributes(attribute.Int("messages_count", len(messages)))
|
| 7 |
+
|
| 8 |
+
for k, msg := range messages {
|
| 9 |
+
+ if ctx.Err() != nil {
|
| 10 |
+
+ // The worker is being stopped: hand the messages it has not
|
| 11 |
+
+ // attempted yet back to the queue instead of leaving them claimed.
|
| 12 |
+
+ c.requeue(ctx, messages[k:])
|
| 13 |
+
+ return nil
|
| 14 |
+
+ }
|
| 15 |
+
+
|
| 16 |
+
logger := c.deps.Logger().
|
| 17 |
+
WithField("message_id", msg.ID).
|
| 18 |
+
WithField("message_nid", msg.NID).
|
| 19 |
+
@@ -125,6 +132,9 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 20 |
+
logger.
|
| 21 |
+
WithError(err).
|
| 22 |
+
Error(`Unable to set the retried message's status to "abandoned".`)
|
| 23 |
+
+ if ctx.Err() != nil {
|
| 24 |
+
+ c.requeue(ctx, messages[k:])
|
| 25 |
+
+ }
|
| 26 |
+
return err
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
@@ -138,27 +148,33 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 30 |
+
logger.
|
| 31 |
+
WithError(err).
|
| 32 |
+
Warn(`Unable to dispatch message.`)
|
| 33 |
+
- if err := c.deps.CourierPersister().RecordDispatch(ctx, msg.ID, CourierMessageDispatchStatusFailed, err); err != nil {
|
| 34 |
+
+ // The failure is recorded and only THIS message goes back to the
|
| 35 |
+
+ // queue. The rest of the batch is still claimed by this worker and
|
| 36 |
+
+ // is sent below; putting it back as well would let another worker
|
| 37 |
+
+ // pick it up while this one is sending it.
|
| 38 |
+
+ storeCtx := context.WithoutCancel(ctx)
|
| 39 |
+
+ if err := c.deps.CourierPersister().RecordDispatch(storeCtx, msg.ID, CourierMessageDispatchStatusFailed, err); err != nil {
|
| 40 |
+
logger.
|
| 41 |
+
WithError(err).
|
| 42 |
+
Error(`Unable to record failure log entry.`)
|
| 43 |
+
if c.failOnDispatchError {
|
| 44 |
+
+ c.requeue(ctx, messages[k:])
|
| 45 |
+
return err
|
| 46 |
+
}
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
- for _, replace := range messages[k:] {
|
| 50 |
+
- if err := c.deps.CourierPersister().SetMessageStatus(ctx, replace.ID, MessageStatusQueued); err != nil {
|
| 51 |
+
- logger.
|
| 52 |
+
- WithError(err).
|
| 53 |
+
- Error(`Unable to reset the failed message's status to "queued".`)
|
| 54 |
+
- if c.failOnDispatchError {
|
| 55 |
+
- return err
|
| 56 |
+
- }
|
| 57 |
+
+ if err := c.deps.CourierPersister().SetMessageStatus(storeCtx, msg.ID, MessageStatusQueued); err != nil {
|
| 58 |
+
+ logger.
|
| 59 |
+
+ WithError(err).
|
| 60 |
+
+ Error(`Unable to reset the failed message's status to "queued".`)
|
| 61 |
+
+ if c.failOnDispatchError {
|
| 62 |
+
+ c.requeue(ctx, messages[k+1:])
|
| 63 |
+
+ return err
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
if c.failOnDispatchError {
|
| 68 |
+
+ c.requeue(ctx, messages[k+1:])
|
| 69 |
+
return err
|
| 70 |
+
}
|
| 71 |
+
} else if err := c.deps.CourierPersister().RecordDispatch(ctx, msg.ID, CourierMessageDispatchStatusSuccess, nil); err != nil {
|
| 72 |
+
@@ -171,3 +187,17 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 73 |
+
|
| 74 |
+
return nil
|
| 75 |
+
}
|
| 76 |
+
+
|
| 77 |
+
+// requeue puts claimed messages that this worker will not attempt back into the
|
| 78 |
+
+// queue. It must work while the worker's context is being canceled.
|
| 79 |
+
+func (c *courier) requeue(ctx context.Context, messages []Message) {
|
| 80 |
+
+ storeCtx := context.WithoutCancel(ctx)
|
| 81 |
+
+ for _, m := range messages {
|
| 82 |
+
+ if err := c.deps.CourierPersister().SetMessageStatus(storeCtx, m.ID, MessageStatusQueued); err != nil {
|
| 83 |
+
+ c.deps.Logger().
|
| 84 |
+
+ WithError(err).
|
| 85 |
+
+ WithField("message_id", m.ID).
|
| 86 |
+
+ Error(`Unable to reset the message's status to "queued".`)
|
| 87 |
+
+ }
|
| 88 |
+
+ }
|
| 89 |
+
+}
|
| 90 |
+
diff --git a/courier/courier_dispatcher_claims_test.go b/courier/courier_dispatcher_claims_test.go
|
| 91 |
+
new file mode 100644
|
| 92 |
+
index 00000000..68735f49
|
| 93 |
+
--- /dev/null
|
| 94 |
+
+++ b/courier/courier_dispatcher_claims_test.go
|
| 95 |
+
@@ -0,0 +1,193 @@
|
| 96 |
+
+// Copyright © 2026 Ory Corp
|
| 97 |
+
+// SPDX-License-Identifier: Apache-2.0
|
| 98 |
+
+
|
| 99 |
+
+package courier_test
|
| 100 |
+
+
|
| 101 |
+
+import (
|
| 102 |
+
+ "context"
|
| 103 |
+
+ "encoding/base64"
|
| 104 |
+
+ "encoding/json"
|
| 105 |
+
+ "fmt"
|
| 106 |
+
+ "io"
|
| 107 |
+
+ "net/http"
|
| 108 |
+
+ "net/http/httptest"
|
| 109 |
+
+ "sync"
|
| 110 |
+
+ "testing"
|
| 111 |
+
+ "time"
|
| 112 |
+
+
|
| 113 |
+
+ "github.com/gofrs/uuid"
|
| 114 |
+
+ "github.com/stretchr/testify/assert"
|
| 115 |
+
+ "github.com/stretchr/testify/require"
|
| 116 |
+
+
|
| 117 |
+
+ "github.com/ory/kratos/courier"
|
| 118 |
+
+ templates "github.com/ory/kratos/courier/template/email"
|
| 119 |
+
+ "github.com/ory/kratos/driver"
|
| 120 |
+
+ "github.com/ory/kratos/driver/config"
|
| 121 |
+
+ "github.com/ory/kratos/pkg"
|
| 122 |
+
+ "github.com/ory/x/configx"
|
| 123 |
+
+)
|
| 124 |
+
+
|
| 125 |
+
+type subjectRelay struct {
|
| 126 |
+
+ mu sync.Mutex
|
| 127 |
+
+ sent map[string]int
|
| 128 |
+
+ handle func(subject string) int
|
| 129 |
+
+}
|
| 130 |
+
+
|
| 131 |
+
+func newSubjectRelay(t *testing.T) (*subjectRelay, *httptest.Server) {
|
| 132 |
+
+ r := &subjectRelay{sent: map[string]int{}}
|
| 133 |
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
| 134 |
+
+ raw, _ := io.ReadAll(req.Body)
|
| 135 |
+
+ var body struct {
|
| 136 |
+
+ Subject string `json:"subject"`
|
| 137 |
+
+ }
|
| 138 |
+
+ _ = json.Unmarshal(raw, &body)
|
| 139 |
+
+ code := http.StatusOK
|
| 140 |
+
+ if r.handle != nil {
|
| 141 |
+
+ code = r.handle(body.Subject)
|
| 142 |
+
+ }
|
| 143 |
+
+ if code == http.StatusOK {
|
| 144 |
+
+ r.mu.Lock()
|
| 145 |
+
+ r.sent[body.Subject]++
|
| 146 |
+
+ r.mu.Unlock()
|
| 147 |
+
+ }
|
| 148 |
+
+ w.WriteHeader(code)
|
| 149 |
+
+ }))
|
| 150 |
+
+ t.Cleanup(srv.Close)
|
| 151 |
+
+ return r, srv
|
| 152 |
+
+}
|
| 153 |
+
+
|
| 154 |
+
+func (r *subjectRelay) count(s string) int {
|
| 155 |
+
+ r.mu.Lock()
|
| 156 |
+
+ defer r.mu.Unlock()
|
| 157 |
+
+ return r.sent[s]
|
| 158 |
+
+}
|
| 159 |
+
+
|
| 160 |
+
+func claimsRegistry(t *testing.T, url string) *driver.RegistryDefault {
|
| 161 |
+
+ body := base64.StdEncoding.EncodeToString([]byte(`function(ctx) { subject: ctx.template_data.subject }`))
|
| 162 |
+
+ _, reg := pkg.NewRegistryDefaultWithDSN(t, "", configx.WithValues(map[string]any{
|
| 163 |
+
+ config.ViperKeyCourierDeliveryStrategy: "http",
|
| 164 |
+
+ config.ViperKeyCourierHTTPRequestConfig: fmt.Sprintf(`{"url": "%s", "method": "POST", "body": "base64://%s"}`, url, body),
|
| 165 |
+
+ config.ViperKeyCourierMessageRetries: 5,
|
| 166 |
+
+ config.ViperKeyCourierWorkerPullCount: 10,
|
| 167 |
+
+ }))
|
| 168 |
+
+ return reg
|
| 169 |
+
+}
|
| 170 |
+
+
|
| 171 |
+
+func queueSubject(t *testing.T, c courier.Courier, subject string) uuid.UUID {
|
| 172 |
+
+ id, err := c.QueueEmail(t.Context(), templates.NewTestStub(&templates.TestStubModel{
|
| 173 |
+
+ To: subject + "@example.org", Subject: subject, Body: subject,
|
| 174 |
+
+ }))
|
| 175 |
+
+ require.NoError(t, err)
|
| 176 |
+
+ return id
|
| 177 |
+
+}
|
| 178 |
+
+
|
| 179 |
+
+func moveTimes(t *testing.T, reg *driver.RegistryDefault, id uuid.UUID, created, updated time.Time) {
|
| 180 |
+
+ require.NoError(t, reg.Persister().GetConnection(t.Context()).RawQuery(
|
| 181 |
+
+ "UPDATE courier_messages SET created_at = ?, updated_at = ? WHERE id = ?",
|
| 182 |
+
+ created.UTC(), updated.UTC(), id).Exec())
|
| 183 |
+
+}
|
| 184 |
+
+
|
| 185 |
+
+func TestDispatchQueueReclaimsAbandonedClaims(t *testing.T) {
|
| 186 |
+
+ relay, srv := newSubjectRelay(t)
|
| 187 |
+
+ reg := claimsRegistry(t, srv.URL)
|
| 188 |
+
+ c, err := reg.Courier(t.Context())
|
| 189 |
+
+ require.NoError(t, err)
|
| 190 |
+
+
|
| 191 |
+
+ stale := queueSubject(t, c, "stale")
|
| 192 |
+
+ claimed, err := reg.CourierPersister().NextMessages(t.Context(), 10)
|
| 193 |
+
+ require.NoError(t, err)
|
| 194 |
+
+ require.Len(t, claimed, 1)
|
| 195 |
+
+
|
| 196 |
+
+ live := queueSubject(t, c, "live")
|
| 197 |
+
+ now := time.Now()
|
| 198 |
+
+ moveTimes(t, reg, live, now.Add(-4*time.Hour), now.Add(-4*time.Hour))
|
| 199 |
+
+ claimed, err = reg.CourierPersister().NextMessages(t.Context(), 10)
|
| 200 |
+
+ require.NoError(t, err)
|
| 201 |
+
+ require.Len(t, claimed, 1)
|
| 202 |
+
+ require.Equal(t, live, claimed[0].ID)
|
| 203 |
+
+
|
| 204 |
+
+ moveTimes(t, reg, stale, now.Add(-3*time.Hour), now.Add(-2*time.Hour))
|
| 205 |
+
+
|
| 206 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 207 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 208 |
+
+
|
| 209 |
+
+ assert.Equal(t, 1, relay.count("stale"))
|
| 210 |
+
+ assert.Equal(t, 0, relay.count("live"))
|
| 211 |
+
+ m, err := reg.CourierPersister().FetchMessage(t.Context(), live)
|
| 212 |
+
+ require.NoError(t, err)
|
| 213 |
+
+ assert.Equal(t, courier.MessageStatusProcessing, m.Status)
|
| 214 |
+
+}
|
| 215 |
+
+
|
| 216 |
+
+func TestDispatchQueueKeepsTheRestOfTheBatchClaimedAfterAFailure(t *testing.T) {
|
| 217 |
+
+ relay, srv := newSubjectRelay(t)
|
| 218 |
+
+ reg := claimsRegistry(t, srv.URL)
|
| 219 |
+
+ c, err := reg.Courier(t.Context())
|
| 220 |
+
+ require.NoError(t, err)
|
| 221 |
+
+
|
| 222 |
+
+ now := time.Now()
|
| 223 |
+
+ var ids []uuid.UUID
|
| 224 |
+
+ for i, s := range []string{"first", "second", "third"} {
|
| 225 |
+
+ id := queueSubject(t, c, s)
|
| 226 |
+
+ moveTimes(t, reg, id, now.Add(time.Duration(i-3)*time.Minute), now.Add(time.Duration(i-3)*time.Minute))
|
| 227 |
+
+ ids = append(ids, id)
|
| 228 |
+
+ }
|
| 229 |
+
+
|
| 230 |
+
+ var thirdWhileSecond courier.MessageStatus
|
| 231 |
+
+ relay.handle = func(subject string) int {
|
| 232 |
+
+ switch subject {
|
| 233 |
+
+ case "first":
|
| 234 |
+
+ return http.StatusServiceUnavailable
|
| 235 |
+
+ case "second":
|
| 236 |
+
+ m, err := reg.CourierPersister().FetchMessage(context.Background(), ids[2])
|
| 237 |
+
+ if err == nil {
|
| 238 |
+
+ thirdWhileSecond = m.Status
|
| 239 |
+
+ }
|
| 240 |
+
+ }
|
| 241 |
+
+ return http.StatusOK
|
| 242 |
+
+ }
|
| 243 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 244 |
+
+
|
| 245 |
+
+ assert.Equal(t, courier.MessageStatusProcessing, thirdWhileSecond,
|
| 246 |
+
+ "a message the worker still has to send must stay claimed")
|
| 247 |
+
+ assert.Equal(t, 1, relay.count("second"))
|
| 248 |
+
+ assert.Equal(t, 1, relay.count("third"))
|
| 249 |
+
+
|
| 250 |
+
+ m, err := reg.CourierPersister().FetchMessage(t.Context(), ids[0])
|
| 251 |
+
+ require.NoError(t, err)
|
| 252 |
+
+ assert.Equal(t, courier.MessageStatusQueued, m.Status)
|
| 253 |
+
+}
|
| 254 |
+
+
|
| 255 |
+
+func TestDispatchQueueRequeuesWhenStopped(t *testing.T) {
|
| 256 |
+
+ relay, srv := newSubjectRelay(t)
|
| 257 |
+
+ reg := claimsRegistry(t, srv.URL)
|
| 258 |
+
+ c, err := reg.Courier(t.Context())
|
| 259 |
+
+ require.NoError(t, err)
|
| 260 |
+
+
|
| 261 |
+
+ now := time.Now()
|
| 262 |
+
+ var ids []uuid.UUID
|
| 263 |
+
+ for i, s := range []string{"a", "b", "c"} {
|
| 264 |
+
+ id := queueSubject(t, c, s)
|
| 265 |
+
+ moveTimes(t, reg, id, now.Add(time.Duration(i-3)*time.Minute), now.Add(time.Duration(i-3)*time.Minute))
|
| 266 |
+
+ ids = append(ids, id)
|
| 267 |
+
+ }
|
| 268 |
+
+
|
| 269 |
+
+ ctx, cancel := context.WithCancel(t.Context())
|
| 270 |
+
+ defer cancel()
|
| 271 |
+
+ relay.handle = func(subject string) int {
|
| 272 |
+
+ if subject == "a" {
|
| 273 |
+
+ cancel()
|
| 274 |
+
+ }
|
| 275 |
+
+ return http.StatusOK
|
| 276 |
+
+ }
|
| 277 |
+
+ _ = c.DispatchQueue(ctx)
|
| 278 |
+
+
|
| 279 |
+
+ for _, id := range ids[1:] {
|
| 280 |
+
+ m, err := reg.CourierPersister().FetchMessage(t.Context(), id)
|
| 281 |
+
+ require.NoError(t, err)
|
| 282 |
+
+ assert.Equal(t, courier.MessageStatusQueued, m.Status)
|
| 283 |
+
+ }
|
| 284 |
+
+ relay.handle = nil
|
| 285 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 286 |
+
+ assert.Equal(t, 1, relay.count("b"))
|
| 287 |
+
+ assert.Equal(t, 1, relay.count("c"))
|
| 288 |
+
+}
|
| 289 |
+
diff --git a/persistence/sql/persister.go b/persistence/sql/persister.go
|
| 290 |
+
index 92c3460f..5d72fb8f 100644
|
| 291 |
+
--- a/persistence/sql/persister.go
|
| 292 |
+
+++ b/persistence/sql/persister.go
|
| 293 |
+
@@ -231,6 +231,12 @@ func (p *Persister) CleanupDatabase(ctx context.Context, wait time.Duration, old
|
| 294 |
+
}
|
| 295 |
+
time.Sleep(wait)
|
| 296 |
+
|
| 297 |
+
+ p.r.Logger().Println("Cleaning up old courier messages")
|
| 298 |
+
+ if err := p.DeleteOldCourierMessages(ctx, currentTime, batchSize); err != nil {
|
| 299 |
+
+ return err
|
| 300 |
+
+ }
|
| 301 |
+
+ time.Sleep(wait)
|
| 302 |
+
+
|
| 303 |
+
p.r.Logger().Println("Successfully cleaned up the latest batch of the SQL database! " +
|
| 304 |
+
"This should be re-run periodically, to be sure that all expired data is purged.")
|
| 305 |
+
return nil
|
| 306 |
+
diff --git a/persistence/sql/persister_courier.go b/persistence/sql/persister_courier.go
|
| 307 |
+
index a66218ad..c3e8d2db 100644
|
| 308 |
+
--- a/persistence/sql/persister_courier.go
|
| 309 |
+
+++ b/persistence/sql/persister_courier.go
|
| 310 |
+
@@ -7,6 +7,8 @@ import (
|
| 311 |
+
"context"
|
| 312 |
+
"database/sql"
|
| 313 |
+
"encoding/json"
|
| 314 |
+
+ "fmt"
|
| 315 |
+
+ "strings"
|
| 316 |
+
"time"
|
| 317 |
+
|
| 318 |
+
"github.com/gofrs/uuid"
|
| 319 |
+
@@ -25,6 +27,10 @@ import (
|
| 320 |
+
|
| 321 |
+
var _ courier.Persister = new(Persister)
|
| 322 |
+
|
| 323 |
+
+// courierProcessingLease is how long a claimed message may stay "processing"
|
| 324 |
+
+// before it is considered abandoned by its worker and handed out again.
|
| 325 |
+
+const courierProcessingLease = time.Hour
|
| 326 |
+
+
|
| 327 |
+
func (p *Persister) AddMessage(ctx context.Context, m *courier.Message) (err error) {
|
| 328 |
+
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.AddMessage")
|
| 329 |
+
defer otelx.End(span, &err)
|
| 330 |
+
@@ -71,9 +77,15 @@ func (p *Persister) NextMessages(ctx context.Context, limit uint8) (messages []c
|
| 331 |
+
defer otelx.End(span, &err)
|
| 332 |
+
|
| 333 |
+
if err := p.Transaction(ctx, func(ctx context.Context, tx *pop.Connection) error {
|
| 334 |
+
- q := tx.Where("nid = ? AND status = ?",
|
| 335 |
+
+ now := time.Now().UTC()
|
| 336 |
+
+ // A message stays "processing" only while the worker that claimed it is
|
| 337 |
+
+ // alive. One whose claim is older than the lease was left behind by a
|
| 338 |
+
+ // worker that crashed or was stopped, and is taken up again.
|
| 339 |
+
+ q := tx.Where("nid = ? AND (status = ? OR (status = ? AND updated_at < ?))",
|
| 340 |
+
p.NetworkID(ctx),
|
| 341 |
+
courier.MessageStatusQueued,
|
| 342 |
+
+ courier.MessageStatusProcessing,
|
| 343 |
+
+ now.Add(-courierProcessingLease),
|
| 344 |
+
)
|
| 345 |
+
if tx.Dialect.Name() == dbal.DriverCockroachDB {
|
| 346 |
+
// On CockroachDB, exclude messages enqueued within the last second.
|
| 347 |
+
@@ -102,7 +114,8 @@ func (p *Persister) NextMessages(ctx context.Context, limit uint8) (messages []c
|
| 348 |
+
for i := range m {
|
| 349 |
+
message := &m[i]
|
| 350 |
+
message.Status = courier.MessageStatusProcessing
|
| 351 |
+
- if err := update.Generic(ctx, tx, p.r.Tracer(ctx).Tracer(), message, "status"); err != nil {
|
| 352 |
+
+ message.UpdatedAt = now
|
| 353 |
+
+ if err := update.Generic(ctx, tx, p.r.Tracer(ctx).Tracer(), message, "status", "updated_at"); err != nil {
|
| 354 |
+
return err
|
| 355 |
+
}
|
| 356 |
+
}
|
| 357 |
+
@@ -149,8 +162,9 @@ func (p *Persister) SetMessageStatus(ctx context.Context, id uuid.UUID, ms couri
|
| 358 |
+
defer otelx.End(span, &err)
|
| 359 |
+
|
| 360 |
+
count, err := p.GetConnection(ctx).RawQuery(
|
| 361 |
+
- "UPDATE courier_messages SET status = ? WHERE id = ? AND nid = ?",
|
| 362 |
+
+ "UPDATE courier_messages SET status = ?, updated_at = ? WHERE id = ? AND nid = ?",
|
| 363 |
+
ms,
|
| 364 |
+
+ time.Now().UTC(),
|
| 365 |
+
id,
|
| 366 |
+
p.NetworkID(ctx),
|
| 367 |
+
).ExecWithCount()
|
| 368 |
+
@@ -170,7 +184,8 @@ func (p *Persister) IncrementMessageSendCount(ctx context.Context, id uuid.UUID)
|
| 369 |
+
defer otelx.End(span, &err)
|
| 370 |
+
|
| 371 |
+
count, err := p.GetConnection(ctx).RawQuery(
|
| 372 |
+
- "UPDATE courier_messages SET send_count = send_count + 1 WHERE id = ? AND nid = ?",
|
| 373 |
+
+ "UPDATE courier_messages SET send_count = send_count + 1, updated_at = ? WHERE id = ? AND nid = ?",
|
| 374 |
+
+ time.Now().UTC(),
|
| 375 |
+
id,
|
| 376 |
+
p.NetworkID(ctx),
|
| 377 |
+
).ExecWithCount()
|
| 378 |
+
@@ -227,3 +242,52 @@ func (p *Persister) RecordDispatch(ctx context.Context, msgID uuid.UUID, status
|
| 379 |
+
|
| 380 |
+
return nil
|
| 381 |
+
}
|
| 382 |
+
+
|
| 383 |
+
+// DeleteOldCourierMessages removes up to limit messages that are finished
|
| 384 |
+
+// (sent or abandoned) and were created before olderThan, together with their
|
| 385 |
+
+// dispatch attempts. Queued and processing messages are never removed.
|
| 386 |
+
+func (p *Persister) DeleteOldCourierMessages(ctx context.Context, olderThan time.Time, limit int) (err error) {
|
| 387 |
+
+ ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteOldCourierMessages")
|
| 388 |
+
+ defer otelx.End(span, &err)
|
| 389 |
+
+
|
| 390 |
+
+ return p.Transaction(ctx, func(ctx context.Context, tx *pop.Connection) error {
|
| 391 |
+
+ var finished []courier.Message
|
| 392 |
+
+ if err := tx.
|
| 393 |
+
+ Select("id").
|
| 394 |
+
+ Where("nid = ? AND status IN (?, ?) AND created_at <= ?",
|
| 395 |
+
+ p.NetworkID(ctx),
|
| 396 |
+
+ courier.MessageStatusSent,
|
| 397 |
+
+ courier.MessageStatusAbandoned,
|
| 398 |
+
+ olderThan.UTC(),
|
| 399 |
+
+ ).
|
| 400 |
+
+ Order("created_at ASC, id ASC").
|
| 401 |
+
+ Limit(limit).
|
| 402 |
+
+ All(&finished); err != nil {
|
| 403 |
+
+ return sqlcon.HandleError(err)
|
| 404 |
+
+ }
|
| 405 |
+
+ if len(finished) == 0 {
|
| 406 |
+
+ return nil
|
| 407 |
+
+ }
|
| 408 |
+
+
|
| 409 |
+
+ args := make([]any, 0, len(finished)+1)
|
| 410 |
+
+ args = append(args, p.NetworkID(ctx))
|
| 411 |
+
+ for _, m := range finished {
|
| 412 |
+
+ args = append(args, m.ID)
|
| 413 |
+
+ }
|
| 414 |
+
+ in := strings.TrimSuffix(strings.Repeat("?, ", len(finished)), ", ")
|
| 415 |
+
+
|
| 416 |
+
+ //#nosec G201 -- only placeholders are formatted into the statement
|
| 417 |
+
+ if err := tx.RawQuery(fmt.Sprintf(
|
| 418 |
+
+ "DELETE FROM courier_message_dispatches WHERE nid = ? AND message_id IN (%s)", in,
|
| 419 |
+
+ ), args...).Exec(); err != nil {
|
| 420 |
+
+ return sqlcon.HandleError(err)
|
| 421 |
+
+ }
|
| 422 |
+
+ //#nosec G201 -- only placeholders are formatted into the statement
|
| 423 |
+
+ if err := tx.RawQuery(fmt.Sprintf(
|
| 424 |
+
+ "DELETE FROM courier_messages WHERE nid = ? AND id IN (%s)", in,
|
| 425 |
+
+ ), args...).Exec(); err != nil {
|
| 426 |
+
+ return sqlcon.HandleError(err)
|
| 427 |
+
+ }
|
| 428 |
+
+ return nil
|
| 429 |
+
+ })
|
| 430 |
+
+}
|
| 431 |
+
diff --git a/persistence/sql/persister_courier_cleanup_test.go b/persistence/sql/persister_courier_cleanup_test.go
|
| 432 |
+
new file mode 100644
|
| 433 |
+
index 00000000..e91afcf1
|
| 434 |
+
--- /dev/null
|
| 435 |
+
+++ b/persistence/sql/persister_courier_cleanup_test.go
|
| 436 |
+
@@ -0,0 +1,74 @@
|
| 437 |
+
+// Copyright © 2026 Ory Corp
|
| 438 |
+
+// SPDX-License-Identifier: Apache-2.0
|
| 439 |
+
+
|
| 440 |
+
+package sql_test
|
| 441 |
+
+
|
| 442 |
+
+import (
|
| 443 |
+
+ "context"
|
| 444 |
+
+ "testing"
|
| 445 |
+
+ "time"
|
| 446 |
+
+
|
| 447 |
+
+ "github.com/gofrs/uuid"
|
| 448 |
+
+ "github.com/stretchr/testify/assert"
|
| 449 |
+
+ "github.com/stretchr/testify/require"
|
| 450 |
+
+
|
| 451 |
+
+ "github.com/ory/kratos/courier"
|
| 452 |
+
+ "github.com/ory/kratos/pkg"
|
| 453 |
+
+ "github.com/ory/kratos/pkg/testhelpers"
|
| 454 |
+
+ "github.com/ory/kratos/persistence"
|
| 455 |
+
+)
|
| 456 |
+
+
|
| 457 |
+
+func TestPersister_CourierMessages_Cleanup(t *testing.T) {
|
| 458 |
+
+ t.Parallel()
|
| 459 |
+
+
|
| 460 |
+
+ _, reg := pkg.NewFastRegistryWithMocks(t)
|
| 461 |
+
+ ctx := context.Background()
|
| 462 |
+
+ p := reg.Persister()
|
| 463 |
+
+ now := time.Now()
|
| 464 |
+
+ old := now.Add(-48 * time.Hour)
|
| 465 |
+
+
|
| 466 |
+
+ add := func(p persistence.Persister, st courier.MessageStatus, created time.Time, attempts int) uuid.UUID {
|
| 467 |
+
+ m := courier.Message{Type: courier.MessageTypeEmail, Recipient: "a@example.org", Subject: "s", Body: "b", TemplateType: "stub"}
|
| 468 |
+
+ require.NoError(t, p.AddMessage(ctx, &m))
|
| 469 |
+
+ for range attempts {
|
| 470 |
+
+ require.NoError(t, p.RecordDispatch(ctx, m.ID, courier.CourierMessageDispatchStatusSuccess, nil))
|
| 471 |
+
+ }
|
| 472 |
+
+ require.NoError(t, p.GetConnection(ctx).RawQuery(
|
| 473 |
+
+ "UPDATE courier_messages SET status = ?, created_at = ?, updated_at = ? WHERE id = ?",
|
| 474 |
+
+ st, created.UTC(), created.UTC(), m.ID).Exec())
|
| 475 |
+
+ return m.ID
|
| 476 |
+
+ }
|
| 477 |
+
+ exists := func(id uuid.UUID) bool {
|
| 478 |
+
+ n, err := p.GetConnection(ctx).Where("id = ?", id).Count(&courier.Message{})
|
| 479 |
+
+ require.NoError(t, err)
|
| 480 |
+
+ return n == 1
|
| 481 |
+
+ }
|
| 482 |
+
+ attempts := func(id uuid.UUID) int {
|
| 483 |
+
+ n, err := p.GetConnection(ctx).Where("message_id = ?", id).Count(&courier.MessageDispatch{})
|
| 484 |
+
+ require.NoError(t, err)
|
| 485 |
+
+ return n
|
| 486 |
+
+ }
|
| 487 |
+
+
|
| 488 |
+
+ sent := add(p, courier.MessageStatusSent, old, 1)
|
| 489 |
+
+ abandoned := add(p, courier.MessageStatusAbandoned, old.Add(time.Minute), 2)
|
| 490 |
+
+ queued := add(p, courier.MessageStatusQueued, old, 1)
|
| 491 |
+
+ processing := add(p, courier.MessageStatusProcessing, old, 0)
|
| 492 |
+
+ recent := add(p, courier.MessageStatusSent, now.Add(-time.Hour), 1)
|
| 493 |
+
+
|
| 494 |
+
+ _, other := testhelpers.NewNetwork(t, ctx, p)
|
| 495 |
+
+ foreign := add(other, courier.MessageStatusSent, old, 1)
|
| 496 |
+
+
|
| 497 |
+
+ require.NoError(t, p.CleanupDatabase(ctx, 0, 24*time.Hour, 1))
|
| 498 |
+
+ assert.False(t, exists(sent), "the oldest finished message goes first")
|
| 499 |
+
+ assert.True(t, exists(abandoned), "one batch of size 1")
|
| 500 |
+
+
|
| 501 |
+
+ require.NoError(t, p.CleanupDatabase(ctx, 0, 24*time.Hour, 100))
|
| 502 |
+
+ assert.False(t, exists(abandoned))
|
| 503 |
+
+ assert.Zero(t, attempts(sent))
|
| 504 |
+
+ assert.Zero(t, attempts(abandoned))
|
| 505 |
+
+ assert.True(t, exists(queued))
|
| 506 |
+
+ assert.Equal(t, 1, attempts(queued))
|
| 507 |
+
+ assert.True(t, exists(processing))
|
| 508 |
+
+ assert.True(t, exists(recent))
|
| 509 |
+
+ assert.True(t, exists(foreign))
|
| 510 |
+
+}
|
harbor/tasks/kratos_cleanup_stale_flows_courier_contract/solution/solve.sh
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
set -eu
|
| 3 |
+
cd /workspace/repo
|
| 4 |
+
git apply <<'REFERENCE_PATCH'
|
| 5 |
+
diff --git a/courier/courier_dispatcher.go b/courier/courier_dispatcher.go
|
| 6 |
+
index 288d1f30..8e3da6f6 100644
|
| 7 |
+
--- a/courier/courier_dispatcher.go
|
| 8 |
+
+++ b/courier/courier_dispatcher.go
|
| 9 |
+
@@ -113,6 +113,13 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 10 |
+
span.SetAttributes(attribute.Int("messages_count", len(messages)))
|
| 11 |
+
|
| 12 |
+
for k, msg := range messages {
|
| 13 |
+
+ if ctx.Err() != nil {
|
| 14 |
+
+ // The worker is being stopped: hand the messages it has not
|
| 15 |
+
+ // attempted yet back to the queue instead of leaving them claimed.
|
| 16 |
+
+ c.requeue(ctx, messages[k:])
|
| 17 |
+
+ return nil
|
| 18 |
+
+ }
|
| 19 |
+
+
|
| 20 |
+
logger := c.deps.Logger().
|
| 21 |
+
WithField("message_id", msg.ID).
|
| 22 |
+
WithField("message_nid", msg.NID).
|
| 23 |
+
@@ -125,6 +132,9 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 24 |
+
logger.
|
| 25 |
+
WithError(err).
|
| 26 |
+
Error(`Unable to set the retried message's status to "abandoned".`)
|
| 27 |
+
+ if ctx.Err() != nil {
|
| 28 |
+
+ c.requeue(ctx, messages[k:])
|
| 29 |
+
+ }
|
| 30 |
+
return err
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
@@ -138,27 +148,33 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 34 |
+
logger.
|
| 35 |
+
WithError(err).
|
| 36 |
+
Warn(`Unable to dispatch message.`)
|
| 37 |
+
- if err := c.deps.CourierPersister().RecordDispatch(ctx, msg.ID, CourierMessageDispatchStatusFailed, err); err != nil {
|
| 38 |
+
+ // The failure is recorded and only THIS message goes back to the
|
| 39 |
+
+ // queue. The rest of the batch is still claimed by this worker and
|
| 40 |
+
+ // is sent below; putting it back as well would let another worker
|
| 41 |
+
+ // pick it up while this one is sending it.
|
| 42 |
+
+ storeCtx := context.WithoutCancel(ctx)
|
| 43 |
+
+ if err := c.deps.CourierPersister().RecordDispatch(storeCtx, msg.ID, CourierMessageDispatchStatusFailed, err); err != nil {
|
| 44 |
+
logger.
|
| 45 |
+
WithError(err).
|
| 46 |
+
Error(`Unable to record failure log entry.`)
|
| 47 |
+
if c.failOnDispatchError {
|
| 48 |
+
+ c.requeue(ctx, messages[k:])
|
| 49 |
+
return err
|
| 50 |
+
}
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
- for _, replace := range messages[k:] {
|
| 54 |
+
- if err := c.deps.CourierPersister().SetMessageStatus(ctx, replace.ID, MessageStatusQueued); err != nil {
|
| 55 |
+
- logger.
|
| 56 |
+
- WithError(err).
|
| 57 |
+
- Error(`Unable to reset the failed message's status to "queued".`)
|
| 58 |
+
- if c.failOnDispatchError {
|
| 59 |
+
- return err
|
| 60 |
+
- }
|
| 61 |
+
+ if err := c.deps.CourierPersister().SetMessageStatus(storeCtx, msg.ID, MessageStatusQueued); err != nil {
|
| 62 |
+
+ logger.
|
| 63 |
+
+ WithError(err).
|
| 64 |
+
+ Error(`Unable to reset the failed message's status to "queued".`)
|
| 65 |
+
+ if c.failOnDispatchError {
|
| 66 |
+
+ c.requeue(ctx, messages[k+1:])
|
| 67 |
+
+ return err
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
if c.failOnDispatchError {
|
| 72 |
+
+ c.requeue(ctx, messages[k+1:])
|
| 73 |
+
return err
|
| 74 |
+
}
|
| 75 |
+
} else if err := c.deps.CourierPersister().RecordDispatch(ctx, msg.ID, CourierMessageDispatchStatusSuccess, nil); err != nil {
|
| 76 |
+
@@ -171,3 +187,17 @@ func (c *courier) DispatchQueue(ctx context.Context) (err error) {
|
| 77 |
+
|
| 78 |
+
return nil
|
| 79 |
+
}
|
| 80 |
+
+
|
| 81 |
+
+// requeue puts claimed messages that this worker will not attempt back into the
|
| 82 |
+
+// queue. It must work while the worker's context is being canceled.
|
| 83 |
+
+func (c *courier) requeue(ctx context.Context, messages []Message) {
|
| 84 |
+
+ storeCtx := context.WithoutCancel(ctx)
|
| 85 |
+
+ for _, m := range messages {
|
| 86 |
+
+ if err := c.deps.CourierPersister().SetMessageStatus(storeCtx, m.ID, MessageStatusQueued); err != nil {
|
| 87 |
+
+ c.deps.Logger().
|
| 88 |
+
+ WithError(err).
|
| 89 |
+
+ WithField("message_id", m.ID).
|
| 90 |
+
+ Error(`Unable to reset the message's status to "queued".`)
|
| 91 |
+
+ }
|
| 92 |
+
+ }
|
| 93 |
+
+}
|
| 94 |
+
diff --git a/courier/courier_dispatcher_claims_test.go b/courier/courier_dispatcher_claims_test.go
|
| 95 |
+
new file mode 100644
|
| 96 |
+
index 00000000..68735f49
|
| 97 |
+
--- /dev/null
|
| 98 |
+
+++ b/courier/courier_dispatcher_claims_test.go
|
| 99 |
+
@@ -0,0 +1,193 @@
|
| 100 |
+
+// Copyright © 2026 Ory Corp
|
| 101 |
+
+// SPDX-License-Identifier: Apache-2.0
|
| 102 |
+
+
|
| 103 |
+
+package courier_test
|
| 104 |
+
+
|
| 105 |
+
+import (
|
| 106 |
+
+ "context"
|
| 107 |
+
+ "encoding/base64"
|
| 108 |
+
+ "encoding/json"
|
| 109 |
+
+ "fmt"
|
| 110 |
+
+ "io"
|
| 111 |
+
+ "net/http"
|
| 112 |
+
+ "net/http/httptest"
|
| 113 |
+
+ "sync"
|
| 114 |
+
+ "testing"
|
| 115 |
+
+ "time"
|
| 116 |
+
+
|
| 117 |
+
+ "github.com/gofrs/uuid"
|
| 118 |
+
+ "github.com/stretchr/testify/assert"
|
| 119 |
+
+ "github.com/stretchr/testify/require"
|
| 120 |
+
+
|
| 121 |
+
+ "github.com/ory/kratos/courier"
|
| 122 |
+
+ templates "github.com/ory/kratos/courier/template/email"
|
| 123 |
+
+ "github.com/ory/kratos/driver"
|
| 124 |
+
+ "github.com/ory/kratos/driver/config"
|
| 125 |
+
+ "github.com/ory/kratos/pkg"
|
| 126 |
+
+ "github.com/ory/x/configx"
|
| 127 |
+
+)
|
| 128 |
+
+
|
| 129 |
+
+type subjectRelay struct {
|
| 130 |
+
+ mu sync.Mutex
|
| 131 |
+
+ sent map[string]int
|
| 132 |
+
+ handle func(subject string) int
|
| 133 |
+
+}
|
| 134 |
+
+
|
| 135 |
+
+func newSubjectRelay(t *testing.T) (*subjectRelay, *httptest.Server) {
|
| 136 |
+
+ r := &subjectRelay{sent: map[string]int{}}
|
| 137 |
+
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
| 138 |
+
+ raw, _ := io.ReadAll(req.Body)
|
| 139 |
+
+ var body struct {
|
| 140 |
+
+ Subject string `json:"subject"`
|
| 141 |
+
+ }
|
| 142 |
+
+ _ = json.Unmarshal(raw, &body)
|
| 143 |
+
+ code := http.StatusOK
|
| 144 |
+
+ if r.handle != nil {
|
| 145 |
+
+ code = r.handle(body.Subject)
|
| 146 |
+
+ }
|
| 147 |
+
+ if code == http.StatusOK {
|
| 148 |
+
+ r.mu.Lock()
|
| 149 |
+
+ r.sent[body.Subject]++
|
| 150 |
+
+ r.mu.Unlock()
|
| 151 |
+
+ }
|
| 152 |
+
+ w.WriteHeader(code)
|
| 153 |
+
+ }))
|
| 154 |
+
+ t.Cleanup(srv.Close)
|
| 155 |
+
+ return r, srv
|
| 156 |
+
+}
|
| 157 |
+
+
|
| 158 |
+
+func (r *subjectRelay) count(s string) int {
|
| 159 |
+
+ r.mu.Lock()
|
| 160 |
+
+ defer r.mu.Unlock()
|
| 161 |
+
+ return r.sent[s]
|
| 162 |
+
+}
|
| 163 |
+
+
|
| 164 |
+
+func claimsRegistry(t *testing.T, url string) *driver.RegistryDefault {
|
| 165 |
+
+ body := base64.StdEncoding.EncodeToString([]byte(`function(ctx) { subject: ctx.template_data.subject }`))
|
| 166 |
+
+ _, reg := pkg.NewRegistryDefaultWithDSN(t, "", configx.WithValues(map[string]any{
|
| 167 |
+
+ config.ViperKeyCourierDeliveryStrategy: "http",
|
| 168 |
+
+ config.ViperKeyCourierHTTPRequestConfig: fmt.Sprintf(`{"url": "%s", "method": "POST", "body": "base64://%s"}`, url, body),
|
| 169 |
+
+ config.ViperKeyCourierMessageRetries: 5,
|
| 170 |
+
+ config.ViperKeyCourierWorkerPullCount: 10,
|
| 171 |
+
+ }))
|
| 172 |
+
+ return reg
|
| 173 |
+
+}
|
| 174 |
+
+
|
| 175 |
+
+func queueSubject(t *testing.T, c courier.Courier, subject string) uuid.UUID {
|
| 176 |
+
+ id, err := c.QueueEmail(t.Context(), templates.NewTestStub(&templates.TestStubModel{
|
| 177 |
+
+ To: subject + "@example.org", Subject: subject, Body: subject,
|
| 178 |
+
+ }))
|
| 179 |
+
+ require.NoError(t, err)
|
| 180 |
+
+ return id
|
| 181 |
+
+}
|
| 182 |
+
+
|
| 183 |
+
+func moveTimes(t *testing.T, reg *driver.RegistryDefault, id uuid.UUID, created, updated time.Time) {
|
| 184 |
+
+ require.NoError(t, reg.Persister().GetConnection(t.Context()).RawQuery(
|
| 185 |
+
+ "UPDATE courier_messages SET created_at = ?, updated_at = ? WHERE id = ?",
|
| 186 |
+
+ created.UTC(), updated.UTC(), id).Exec())
|
| 187 |
+
+}
|
| 188 |
+
+
|
| 189 |
+
+func TestDispatchQueueReclaimsAbandonedClaims(t *testing.T) {
|
| 190 |
+
+ relay, srv := newSubjectRelay(t)
|
| 191 |
+
+ reg := claimsRegistry(t, srv.URL)
|
| 192 |
+
+ c, err := reg.Courier(t.Context())
|
| 193 |
+
+ require.NoError(t, err)
|
| 194 |
+
+
|
| 195 |
+
+ stale := queueSubject(t, c, "stale")
|
| 196 |
+
+ claimed, err := reg.CourierPersister().NextMessages(t.Context(), 10)
|
| 197 |
+
+ require.NoError(t, err)
|
| 198 |
+
+ require.Len(t, claimed, 1)
|
| 199 |
+
+
|
| 200 |
+
+ live := queueSubject(t, c, "live")
|
| 201 |
+
+ now := time.Now()
|
| 202 |
+
+ moveTimes(t, reg, live, now.Add(-4*time.Hour), now.Add(-4*time.Hour))
|
| 203 |
+
+ claimed, err = reg.CourierPersister().NextMessages(t.Context(), 10)
|
| 204 |
+
+ require.NoError(t, err)
|
| 205 |
+
+ require.Len(t, claimed, 1)
|
| 206 |
+
+ require.Equal(t, live, claimed[0].ID)
|
| 207 |
+
+
|
| 208 |
+
+ moveTimes(t, reg, stale, now.Add(-3*time.Hour), now.Add(-2*time.Hour))
|
| 209 |
+
+
|
| 210 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 211 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 212 |
+
+
|
| 213 |
+
+ assert.Equal(t, 1, relay.count("stale"))
|
| 214 |
+
+ assert.Equal(t, 0, relay.count("live"))
|
| 215 |
+
+ m, err := reg.CourierPersister().FetchMessage(t.Context(), live)
|
| 216 |
+
+ require.NoError(t, err)
|
| 217 |
+
+ assert.Equal(t, courier.MessageStatusProcessing, m.Status)
|
| 218 |
+
+}
|
| 219 |
+
+
|
| 220 |
+
+func TestDispatchQueueKeepsTheRestOfTheBatchClaimedAfterAFailure(t *testing.T) {
|
| 221 |
+
+ relay, srv := newSubjectRelay(t)
|
| 222 |
+
+ reg := claimsRegistry(t, srv.URL)
|
| 223 |
+
+ c, err := reg.Courier(t.Context())
|
| 224 |
+
+ require.NoError(t, err)
|
| 225 |
+
+
|
| 226 |
+
+ now := time.Now()
|
| 227 |
+
+ var ids []uuid.UUID
|
| 228 |
+
+ for i, s := range []string{"first", "second", "third"} {
|
| 229 |
+
+ id := queueSubject(t, c, s)
|
| 230 |
+
+ moveTimes(t, reg, id, now.Add(time.Duration(i-3)*time.Minute), now.Add(time.Duration(i-3)*time.Minute))
|
| 231 |
+
+ ids = append(ids, id)
|
| 232 |
+
+ }
|
| 233 |
+
+
|
| 234 |
+
+ var thirdWhileSecond courier.MessageStatus
|
| 235 |
+
+ relay.handle = func(subject string) int {
|
| 236 |
+
+ switch subject {
|
| 237 |
+
+ case "first":
|
| 238 |
+
+ return http.StatusServiceUnavailable
|
| 239 |
+
+ case "second":
|
| 240 |
+
+ m, err := reg.CourierPersister().FetchMessage(context.Background(), ids[2])
|
| 241 |
+
+ if err == nil {
|
| 242 |
+
+ thirdWhileSecond = m.Status
|
| 243 |
+
+ }
|
| 244 |
+
+ }
|
| 245 |
+
+ return http.StatusOK
|
| 246 |
+
+ }
|
| 247 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 248 |
+
+
|
| 249 |
+
+ assert.Equal(t, courier.MessageStatusProcessing, thirdWhileSecond,
|
| 250 |
+
+ "a message the worker still has to send must stay claimed")
|
| 251 |
+
+ assert.Equal(t, 1, relay.count("second"))
|
| 252 |
+
+ assert.Equal(t, 1, relay.count("third"))
|
| 253 |
+
+
|
| 254 |
+
+ m, err := reg.CourierPersister().FetchMessage(t.Context(), ids[0])
|
| 255 |
+
+ require.NoError(t, err)
|
| 256 |
+
+ assert.Equal(t, courier.MessageStatusQueued, m.Status)
|
| 257 |
+
+}
|
| 258 |
+
+
|
| 259 |
+
+func TestDispatchQueueRequeuesWhenStopped(t *testing.T) {
|
| 260 |
+
+ relay, srv := newSubjectRelay(t)
|
| 261 |
+
+ reg := claimsRegistry(t, srv.URL)
|
| 262 |
+
+ c, err := reg.Courier(t.Context())
|
| 263 |
+
+ require.NoError(t, err)
|
| 264 |
+
+
|
| 265 |
+
+ now := time.Now()
|
| 266 |
+
+ var ids []uuid.UUID
|
| 267 |
+
+ for i, s := range []string{"a", "b", "c"} {
|
| 268 |
+
+ id := queueSubject(t, c, s)
|
| 269 |
+
+ moveTimes(t, reg, id, now.Add(time.Duration(i-3)*time.Minute), now.Add(time.Duration(i-3)*time.Minute))
|
| 270 |
+
+ ids = append(ids, id)
|
| 271 |
+
+ }
|
| 272 |
+
+
|
| 273 |
+
+ ctx, cancel := context.WithCancel(t.Context())
|
| 274 |
+
+ defer cancel()
|
| 275 |
+
+ relay.handle = func(subject string) int {
|
| 276 |
+
+ if subject == "a" {
|
| 277 |
+
+ cancel()
|
| 278 |
+
+ }
|
| 279 |
+
+ return http.StatusOK
|
| 280 |
+
+ }
|
| 281 |
+
+ _ = c.DispatchQueue(ctx)
|
| 282 |
+
+
|
| 283 |
+
+ for _, id := range ids[1:] {
|
| 284 |
+
+ m, err := reg.CourierPersister().FetchMessage(t.Context(), id)
|
| 285 |
+
+ require.NoError(t, err)
|
| 286 |
+
+ assert.Equal(t, courier.MessageStatusQueued, m.Status)
|
| 287 |
+
+ }
|
| 288 |
+
+ relay.handle = nil
|
| 289 |
+
+ require.NoError(t, c.DispatchQueue(t.Context()))
|
| 290 |
+
+ assert.Equal(t, 1, relay.count("b"))
|
| 291 |
+
+ assert.Equal(t, 1, relay.count("c"))
|
| 292 |
+
+}
|
| 293 |
+
diff --git a/persistence/sql/persister.go b/persistence/sql/persister.go
|
| 294 |
+
index 92c3460f..5d72fb8f 100644
|
| 295 |
+
--- a/persistence/sql/persister.go
|
| 296 |
+
+++ b/persistence/sql/persister.go
|
| 297 |
+
@@ -231,6 +231,12 @@ func (p *Persister) CleanupDatabase(ctx context.Context, wait time.Duration, old
|
| 298 |
+
}
|
| 299 |
+
time.Sleep(wait)
|
| 300 |
+
|
| 301 |
+
+ p.r.Logger().Println("Cleaning up old courier messages")
|
| 302 |
+
+ if err := p.DeleteOldCourierMessages(ctx, currentTime, batchSize); err != nil {
|
| 303 |
+
+ return err
|
| 304 |
+
+ }
|
| 305 |
+
+ time.Sleep(wait)
|
| 306 |
+
+
|
| 307 |
+
p.r.Logger().Println("Successfully cleaned up the latest batch of the SQL database! " +
|
| 308 |
+
"This should be re-run periodically, to be sure that all expired data is purged.")
|
| 309 |
+
return nil
|
| 310 |
+
diff --git a/persistence/sql/persister_courier.go b/persistence/sql/persister_courier.go
|
| 311 |
+
index a66218ad..c3e8d2db 100644
|
| 312 |
+
--- a/persistence/sql/persister_courier.go
|
| 313 |
+
+++ b/persistence/sql/persister_courier.go
|
| 314 |
+
@@ -7,6 +7,8 @@ import (
|
| 315 |
+
"context"
|
| 316 |
+
"database/sql"
|
| 317 |
+
"encoding/json"
|
| 318 |
+
+ "fmt"
|
| 319 |
+
+ "strings"
|
| 320 |
+
"time"
|
| 321 |
+
|
| 322 |
+
"github.com/gofrs/uuid"
|
| 323 |
+
@@ -25,6 +27,10 @@ import (
|
| 324 |
+
|
| 325 |
+
var _ courier.Persister = new(Persister)
|
| 326 |
+
|
| 327 |
+
+// courierProcessingLease is how long a claimed message may stay "processing"
|
| 328 |
+
+// before it is considered abandoned by its worker and handed out again.
|
| 329 |
+
+const courierProcessingLease = time.Hour
|
| 330 |
+
+
|
| 331 |
+
func (p *Persister) AddMessage(ctx context.Context, m *courier.Message) (err error) {
|
| 332 |
+
ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.AddMessage")
|
| 333 |
+
defer otelx.End(span, &err)
|
| 334 |
+
@@ -71,9 +77,15 @@ func (p *Persister) NextMessages(ctx context.Context, limit uint8) (messages []c
|
| 335 |
+
defer otelx.End(span, &err)
|
| 336 |
+
|
| 337 |
+
if err := p.Transaction(ctx, func(ctx context.Context, tx *pop.Connection) error {
|
| 338 |
+
- q := tx.Where("nid = ? AND status = ?",
|
| 339 |
+
+ now := time.Now().UTC()
|
| 340 |
+
+ // A message stays "processing" only while the worker that claimed it is
|
| 341 |
+
+ // alive. One whose claim is older than the lease was left behind by a
|
| 342 |
+
+ // worker that crashed or was stopped, and is taken up again.
|
| 343 |
+
+ q := tx.Where("nid = ? AND (status = ? OR (status = ? AND updated_at < ?))",
|
| 344 |
+
p.NetworkID(ctx),
|
| 345 |
+
courier.MessageStatusQueued,
|
| 346 |
+
+ courier.MessageStatusProcessing,
|
| 347 |
+
+ now.Add(-courierProcessingLease),
|
| 348 |
+
)
|
| 349 |
+
if tx.Dialect.Name() == dbal.DriverCockroachDB {
|
| 350 |
+
// On CockroachDB, exclude messages enqueued within the last second.
|
| 351 |
+
@@ -102,7 +114,8 @@ func (p *Persister) NextMessages(ctx context.Context, limit uint8) (messages []c
|
| 352 |
+
for i := range m {
|
| 353 |
+
message := &m[i]
|
| 354 |
+
message.Status = courier.MessageStatusProcessing
|
| 355 |
+
- if err := update.Generic(ctx, tx, p.r.Tracer(ctx).Tracer(), message, "status"); err != nil {
|
| 356 |
+
+ message.UpdatedAt = now
|
| 357 |
+
+ if err := update.Generic(ctx, tx, p.r.Tracer(ctx).Tracer(), message, "status", "updated_at"); err != nil {
|
| 358 |
+
return err
|
| 359 |
+
}
|
| 360 |
+
}
|
| 361 |
+
@@ -149,8 +162,9 @@ func (p *Persister) SetMessageStatus(ctx context.Context, id uuid.UUID, ms couri
|
| 362 |
+
defer otelx.End(span, &err)
|
| 363 |
+
|
| 364 |
+
count, err := p.GetConnection(ctx).RawQuery(
|
| 365 |
+
- "UPDATE courier_messages SET status = ? WHERE id = ? AND nid = ?",
|
| 366 |
+
+ "UPDATE courier_messages SET status = ?, updated_at = ? WHERE id = ? AND nid = ?",
|
| 367 |
+
ms,
|
| 368 |
+
+ time.Now().UTC(),
|
| 369 |
+
id,
|
| 370 |
+
p.NetworkID(ctx),
|
| 371 |
+
).ExecWithCount()
|
| 372 |
+
@@ -170,7 +184,8 @@ func (p *Persister) IncrementMessageSendCount(ctx context.Context, id uuid.UUID)
|
| 373 |
+
defer otelx.End(span, &err)
|
| 374 |
+
|
| 375 |
+
count, err := p.GetConnection(ctx).RawQuery(
|
| 376 |
+
- "UPDATE courier_messages SET send_count = send_count + 1 WHERE id = ? AND nid = ?",
|
| 377 |
+
+ "UPDATE courier_messages SET send_count = send_count + 1, updated_at = ? WHERE id = ? AND nid = ?",
|
| 378 |
+
+ time.Now().UTC(),
|
| 379 |
+
id,
|
| 380 |
+
p.NetworkID(ctx),
|
| 381 |
+
).ExecWithCount()
|
| 382 |
+
@@ -227,3 +242,52 @@ func (p *Persister) RecordDispatch(ctx context.Context, msgID uuid.UUID, status
|
| 383 |
+
|
| 384 |
+
return nil
|
| 385 |
+
}
|
| 386 |
+
+
|
| 387 |
+
+// DeleteOldCourierMessages removes up to limit messages that are finished
|
| 388 |
+
+// (sent or abandoned) and were created before olderThan, together with their
|
| 389 |
+
+// dispatch attempts. Queued and processing messages are never removed.
|
| 390 |
+
+func (p *Persister) DeleteOldCourierMessages(ctx context.Context, olderThan time.Time, limit int) (err error) {
|
| 391 |
+
+ ctx, span := p.r.Tracer(ctx).Tracer().Start(ctx, "persistence.sql.DeleteOldCourierMessages")
|
| 392 |
+
+ defer otelx.End(span, &err)
|
| 393 |
+
+
|
| 394 |
+
+ return p.Transaction(ctx, func(ctx context.Context, tx *pop.Connection) error {
|
| 395 |
+
+ var finished []courier.Message
|
| 396 |
+
+ if err := tx.
|
| 397 |
+
+ Select("id").
|
| 398 |
+
+ Where("nid = ? AND status IN (?, ?) AND created_at <= ?",
|
| 399 |
+
+ p.NetworkID(ctx),
|
| 400 |
+
+ courier.MessageStatusSent,
|
| 401 |
+
+ courier.MessageStatusAbandoned,
|
| 402 |
+
+ olderThan.UTC(),
|
| 403 |
+
+ ).
|
| 404 |
+
+ Order("created_at ASC, id ASC").
|
| 405 |
+
+ Limit(limit).
|
| 406 |
+
+ All(&finished); err != nil {
|
| 407 |
+
+ return sqlcon.HandleError(err)
|
| 408 |
+
+ }
|
| 409 |
+
+ if len(finished) == 0 {
|
| 410 |
+
+ return nil
|
| 411 |
+
+ }
|
| 412 |
+
+
|
| 413 |
+
+ args := make([]any, 0, len(finished)+1)
|
| 414 |
+
+ args = append(args, p.NetworkID(ctx))
|
| 415 |
+
+ for _, m := range finished {
|
| 416 |
+
+ args = append(args, m.ID)
|
| 417 |
+
+ }
|
| 418 |
+
+ in := strings.TrimSuffix(strings.Repeat("?, ", len(finished)), ", ")
|
| 419 |
+
+
|
| 420 |
+
+ //#nosec G201 -- only placeholders are formatted into the statement
|
| 421 |
+
+ if err := tx.RawQuery(fmt.Sprintf(
|
| 422 |
+
+ "DELETE FROM courier_message_dispatches WHERE nid = ? AND message_id IN (%s)", in,
|
| 423 |
+
+ ), args...).Exec(); err != nil {
|
| 424 |
+
+ return sqlcon.HandleError(err)
|
| 425 |
+
+ }
|
| 426 |
+
+ //#nosec G201 -- only placeholders are formatted into the statement
|
| 427 |
+
+ if err := tx.RawQuery(fmt.Sprintf(
|
| 428 |
+
+ "DELETE FROM courier_messages WHERE nid = ? AND id IN (%s)", in,
|
| 429 |
+
+ ), args...).Exec(); err != nil {
|
| 430 |
+
+ return sqlcon.HandleError(err)
|
| 431 |
+
+ }
|
| 432 |
+
+ return nil
|
| 433 |
+
+ })
|
| 434 |
+
+}
|
| 435 |
+
diff --git a/persistence/sql/persister_courier_cleanup_test.go b/persistence/sql/persister_courier_cleanup_test.go
|
| 436 |
+
new file mode 100644
|
| 437 |
+
index 00000000..e91afcf1
|
| 438 |
+
--- /dev/null
|
| 439 |
+
+++ b/persistence/sql/persister_courier_cleanup_test.go
|
| 440 |
+
@@ -0,0 +1,74 @@
|
| 441 |
+
+// Copyright © 2026 Ory Corp
|
| 442 |
+
+// SPDX-License-Identifier: Apache-2.0
|
| 443 |
+
+
|
| 444 |
+
+package sql_test
|
| 445 |
+
+
|
| 446 |
+
+import (
|
| 447 |
+
+ "context"
|
| 448 |
+
+ "testing"
|
| 449 |
+
+ "time"
|
| 450 |
+
+
|
| 451 |
+
+ "github.com/gofrs/uuid"
|
| 452 |
+
+ "github.com/stretchr/testify/assert"
|
| 453 |
+
+ "github.com/stretchr/testify/require"
|
| 454 |
+
+
|
| 455 |
+
+ "github.com/ory/kratos/courier"
|
| 456 |
+
+ "github.com/ory/kratos/pkg"
|
| 457 |
+
+ "github.com/ory/kratos/pkg/testhelpers"
|
| 458 |
+
+ "github.com/ory/kratos/persistence"
|
| 459 |
+
+)
|
| 460 |
+
+
|
| 461 |
+
+func TestPersister_CourierMessages_Cleanup(t *testing.T) {
|
| 462 |
+
+ t.Parallel()
|
| 463 |
+
+
|
| 464 |
+
+ _, reg := pkg.NewFastRegistryWithMocks(t)
|
| 465 |
+
+ ctx := context.Background()
|
| 466 |
+
+ p := reg.Persister()
|
| 467 |
+
+ now := time.Now()
|
| 468 |
+
+ old := now.Add(-48 * time.Hour)
|
| 469 |
+
+
|
| 470 |
+
+ add := func(p persistence.Persister, st courier.MessageStatus, created time.Time, attempts int) uuid.UUID {
|
| 471 |
+
+ m := courier.Message{Type: courier.MessageTypeEmail, Recipient: "a@example.org", Subject: "s", Body: "b", TemplateType: "stub"}
|
| 472 |
+
+ require.NoError(t, p.AddMessage(ctx, &m))
|
| 473 |
+
+ for range attempts {
|
| 474 |
+
+ require.NoError(t, p.RecordDispatch(ctx, m.ID, courier.CourierMessageDispatchStatusSuccess, nil))
|
| 475 |
+
+ }
|
| 476 |
+
+ require.NoError(t, p.GetConnection(ctx).RawQuery(
|
| 477 |
+
+ "UPDATE courier_messages SET status = ?, created_at = ?, updated_at = ? WHERE id = ?",
|
| 478 |
+
+ st, created.UTC(), created.UTC(), m.ID).Exec())
|
| 479 |
+
+ return m.ID
|
| 480 |
+
+ }
|
| 481 |
+
+ exists := func(id uuid.UUID) bool {
|
| 482 |
+
+ n, err := p.GetConnection(ctx).Where("id = ?", id).Count(&courier.Message{})
|
| 483 |
+
+ require.NoError(t, err)
|
| 484 |
+
+ return n == 1
|
| 485 |
+
+ }
|
| 486 |
+
+ attempts := func(id uuid.UUID) int {
|
| 487 |
+
+ n, err := p.GetConnection(ctx).Where("message_id = ?", id).Count(&courier.MessageDispatch{})
|
| 488 |
+
+ require.NoError(t, err)
|
| 489 |
+
+ return n
|
| 490 |
+
+ }
|
| 491 |
+
+
|
| 492 |
+
+ sent := add(p, courier.MessageStatusSent, old, 1)
|
| 493 |
+
+ abandoned := add(p, courier.MessageStatusAbandoned, old.Add(time.Minute), 2)
|
| 494 |
+
+ queued := add(p, courier.MessageStatusQueued, old, 1)
|
| 495 |
+
+ processing := add(p, courier.MessageStatusProcessing, old, 0)
|
| 496 |
+
+ recent := add(p, courier.MessageStatusSent, now.Add(-time.Hour), 1)
|
| 497 |
+
+
|
| 498 |
+
+ _, other := testhelpers.NewNetwork(t, ctx, p)
|
| 499 |
+
+ foreign := add(other, courier.MessageStatusSent, old, 1)
|
| 500 |
+
+
|
| 501 |
+
+ require.NoError(t, p.CleanupDatabase(ctx, 0, 24*time.Hour, 1))
|
| 502 |
+
+ assert.False(t, exists(sent), "the oldest finished message goes first")
|
| 503 |
+
+ assert.True(t, exists(abandoned), "one batch of size 1")
|
| 504 |
+
+
|
| 505 |
+
+ require.NoError(t, p.CleanupDatabase(ctx, 0, 24*time.Hour, 100))
|
| 506 |
+
+ assert.False(t, exists(abandoned))
|
| 507 |
+
+ assert.Zero(t, attempts(sent))
|
| 508 |
+
+ assert.Zero(t, attempts(abandoned))
|
| 509 |
+
+ assert.True(t, exists(queued))
|
| 510 |
+
+ assert.Equal(t, 1, attempts(queued))
|
| 511 |
+
+ assert.True(t, exists(processing))
|
| 512 |
+
+ assert.True(t, exists(recent))
|
| 513 |
+
+ assert.True(t, exists(foreign))
|
| 514 |
+
+}
|
| 515 |
+
|
| 516 |
+
REFERENCE_PATCH
|
harbor/tasks/kratos_cleanup_stale_flows_courier_contract/task.toml
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version = "1.0"
|
| 2 |
+
artifacts = ["/workspace/submissions/submitted.patch"]
|
| 3 |
+
[metadata]
|
| 4 |
+
task = "kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_contract/tests/Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM ec-swe-kratos: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 |
+
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/kratos_cleanup_stale_flows_courier_contract/tests/config.json
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"revision": "coding-rubric-v2",
|
| 3 |
+
"task_id": "kratos_cleanup_stale_flows_courier_contract",
|
| 4 |
+
"arguments": {},
|
| 5 |
+
"grader_version": "0.6.15",
|
| 6 |
+
"source_image": "ec-swe-kratos:source-v10",
|
| 7 |
+
"source_image_id": "sha256:a3c3f9a393f79d72fff709b01e919ef72e0d7a3fba232533eb107875f006496b",
|
| 8 |
+
"provenance": {
|
| 9 |
+
"repository": "ory/kratos",
|
| 10 |
+
"environment_id": "4e12f395-6431-4c02-b211-fd3707822aba",
|
| 11 |
+
"build": 10,
|
| 12 |
+
"build_id": "36572f42-b5da-4777-8379-34459bff5575",
|
| 13 |
+
"hosted_task": "kratos_cleanup_stale_flows_courier_contract",
|
| 14 |
+
"task_version": 6,
|
| 15 |
+
"source_archive_sha256": "207a452f2c259f7f6474f2bd3ce7c1f1beaac49eafece386a0190498ee211d96",
|
| 16 |
+
"hosted_revision_argument": "not recorded; the scenario does not read it"
|
| 17 |
+
},
|
| 18 |
+
"criteria": [
|
| 19 |
+
[
|
| 20 |
+
"stranded_message_is_delivered_once",
|
| 21 |
+
0.0608,
|
| 22 |
+
true,
|
| 23 |
+
"bash",
|
| 24 |
+
600
|
| 25 |
+
],
|
| 26 |
+
[
|
| 27 |
+
"stranded_message_is_retried_then_abandoned",
|
| 28 |
+
0.0608,
|
| 29 |
+
false,
|
| 30 |
+
"bash",
|
| 31 |
+
600
|
| 32 |
+
],
|
| 33 |
+
[
|
| 34 |
+
"concurrent_poll_never_double_delivers",
|
| 35 |
+
0.1817,
|
| 36 |
+
false,
|
| 37 |
+
"bash",
|
| 38 |
+
600
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
"claimed_mail_is_not_sent_by_another_worker",
|
| 42 |
+
0.1817,
|
| 43 |
+
false,
|
| 44 |
+
"bash",
|
| 45 |
+
600
|
| 46 |
+
],
|
| 47 |
+
[
|
| 48 |
+
"claimed_mail_is_not_handed_to_another_worker",
|
| 49 |
+
0.1817,
|
| 50 |
+
false,
|
| 51 |
+
"bash",
|
| 52 |
+
600
|
| 53 |
+
],
|
| 54 |
+
[
|
| 55 |
+
"batch_is_released_only_when_the_worker_gives_up",
|
| 56 |
+
0.1817,
|
| 57 |
+
false,
|
| 58 |
+
"bash",
|
| 59 |
+
600
|
| 60 |
+
],
|
| 61 |
+
[
|
| 62 |
+
"cleanup_keeps_pending_messages",
|
| 63 |
+
0.0608,
|
| 64 |
+
true,
|
| 65 |
+
"bash",
|
| 66 |
+
600
|
| 67 |
+
],
|
| 68 |
+
[
|
| 69 |
+
"cleanup_removes_old_finished_with_attempts",
|
| 70 |
+
0.0608,
|
| 71 |
+
false,
|
| 72 |
+
"bash",
|
| 73 |
+
600
|
| 74 |
+
],
|
| 75 |
+
[
|
| 76 |
+
"gate_repo_suite_green_and_tests_untouched",
|
| 77 |
+
0.03,
|
| 78 |
+
true,
|
| 79 |
+
"bash",
|
| 80 |
+
900
|
| 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": "f500868545909809d90d32c59d3c484f2f2dfd401c5095a1d62e16604d9c8b77",
|
| 93 |
+
"/app/tasks.py": "e3b3f5fe4fec8e4d3f1c8261ef9ce13fc8058031634162dc72c17d8ee368dc5a",
|
| 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": "239e21d58525fb1d4f03502a02aaf35855cfcdad5b16eb89547947c9b6b2780e",
|
| 99 |
+
"/hud/grader/board.json": "f58568b0e7d41942cd8311ae566e61fd1259291d93b2f4a8afcebee16b5b19e7",
|
| 100 |
+
"/hud/grader/cells_test.go": "cf3052230ff44491db7f191206603fb73cdf24c59de4331f7839bf3026cb7a7c",
|
| 101 |
+
"/hud/grader/run_grading.sh": "82c1ca34535b2da3c93e728229e508319224cd3e9f35f54139d38b8f98f1d913",
|
| 102 |
+
"/hud/grader/suite_gate.py": "de0fc10861f98f87af69bc34b8c49248f386cbb35d47396b1e37576f8962b688"
|
| 103 |
+
},
|
| 104 |
+
"preflight": [
|
| 105 |
+
[
|
| 106 |
+
"/bin/bash",
|
| 107 |
+
"--version"
|
| 108 |
+
],
|
| 109 |
+
[
|
| 110 |
+
"setpriv",
|
| 111 |
+
"--version"
|
| 112 |
+
],
|
| 113 |
+
[
|
| 114 |
+
"git",
|
| 115 |
+
"--version"
|
| 116 |
+
],
|
| 117 |
+
[
|
| 118 |
+
"bash",
|
| 119 |
+
"-c",
|
| 120 |
+
"bash -lc 'go version' || go version"
|
| 121 |
+
],
|
| 122 |
+
[
|
| 123 |
+
"/usr/local/bin/python3",
|
| 124 |
+
"--version"
|
| 125 |
+
]
|
| 126 |
+
]
|
| 127 |
+
}
|
harbor/tasks/kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_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/kratos_cleanup_stale_flows_courier_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
|
@@ -5,6 +5,7 @@
|
|
| 5 |
"bazel_remote_disk_eviction_accounting_contract",
|
| 6 |
"celery_retry_expires_countdown_contract",
|
| 7 |
"epicyon_deleted_post_announce_cache_contract",
|
|
|
|
| 8 |
"microblogpub_deleted_object_resurrect_lookup_contract",
|
| 9 |
"openfire_userdeleting_last_owner_contract",
|
| 10 |
"rope_rename_all_reexport_owners_contract",
|
|
|
|
| 5 |
"bazel_remote_disk_eviction_accounting_contract",
|
| 6 |
"celery_retry_expires_countdown_contract",
|
| 7 |
"epicyon_deleted_post_announce_cache_contract",
|
| 8 |
+
"kratos_cleanup_stale_flows_courier_contract",
|
| 9 |
"microblogpub_deleted_object_resurrect_lookup_contract",
|
| 10 |
"openfire_userdeleting_last_owner_contract",
|
| 11 |
"rope_rename_all_reexport_owners_contract",
|