servicesToptal commited on
Commit
0c2eb5e
·
verified ·
1 Parent(s): 666125b

Update dataset (part 2)

Browse files
README.md CHANGED
@@ -297,7 +297,7 @@ empty change scores 0, and the reference fix scores 1.0 with every criterion
297
  equal to the task's original grading. The folder contains the reference fixes
298
  and the hidden graders, as the rows of this dataset do.
299
 
300
- 7 more (badger, geode, kratos, open-xml-sdk, openfire, umya, zettlr) are packaged and are being re-checked; they are added
301
  as each one passes.
302
 
303
  Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
 
297
  equal to the task's original grading. The folder contains the reference fixes
298
  and the hidden graders, as the rows of this dataset do.
299
 
300
+ 6 more (geode, kratos, open-xml-sdk, openfire, umya, zettlr) are packaged and are being re-checked; they are added
301
  as each one passes.
302
 
303
  Nine tasks have no Harbor package yet: click, sequelize, druid and hooks (one criterion each
harbor/tasks/journal_recovery_after_unclean_stop/environment/Dockerfile ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-badger:source-v2 AS sanitized
2
+ USER root
3
+ COPY sanitize.py capture.py capture_submission.py /opt/task-tools/
4
+ RUN HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 /opt/hudvenv/bin/python /opt/task-tools/sanitize.py
5
+ FROM scratch
6
+ COPY --from=sanitized / /
7
+ ENV PATH="/usr/local/go/bin:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games"
8
+ ENV LANG="C.UTF-8"
9
+ ENV GOTOOLCHAIN="local"
10
+ ENV CGO_ENABLED="1"
11
+ ENV GOWORK="off"
12
+ ENV GOFLAGS="-mod=mod"
13
+ ENV GOPATH="/go"
14
+ ENV GOMODCACHE="/go/pkg/mod"
15
+ ENV GOMEMLIMIT="1GiB"
16
+ ENV GOPROXY="off"
17
+ ENV GOMAXPROCS="2"
18
+ ENV HOME="/tmp/agent-home"
19
+ ENV GOCACHE="/tmp/agent-home/.cache/go-build"
20
+ ENV HUD_TELEMETRY_ENABLED="false"
21
+ ENV HUD_CLI_ANALYTICS_ENABLED="0"
22
+ WORKDIR /workspace/repo
23
+ USER 1000:1000
24
+ CMD ["sleep", "infinity"]
harbor/tasks/journal_recovery_after_unclean_stop/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/journal_recovery_after_unclean_stop/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/journal_recovery_after_unclean_stop/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/journal_recovery_after_unclean_stop/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/journal_recovery_after_unclean_stop/instruction.md ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Please make your changes directly in /workspace/repo.
2
+
3
+ # What the journal gives back
4
+
5
+ After an unclean stop — a killed process, a torn tail on a log — the build reopens and
6
+ serves whole transactions only: every commit it had acknowledged, none in part, and never
7
+ a later one without every earlier one. A read never answers with a value nobody wrote.
8
+ Opened read-only after such a stop, the build serves that same history when it can serve
9
+ it whole, and otherwise says why it cannot; either way it alters no byte. This holds
10
+ however the transaction was committed and whatever the value's size. Work offline; the
11
+ existing tests stay as green as you found them — add tests, don't change them.
12
+
13
+ Finish with a final response when your changes are ready.
harbor/tasks/journal_recovery_after_unclean_stop/solution/reference.patch ADDED
@@ -0,0 +1,1036 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/db.go b/db.go
2
+ index 9572203..cf8e0f4 100644
3
+ --- a/db.go
4
+ +++ b/db.go
5
+ @@ -341,6 +341,14 @@ func Open(opt Options) (*DB, error) {
6
+ db.closers.updateSize = z.NewCloser(1)
7
+ go db.updateSize(db.closers.updateSize)
8
+
9
+ + // The value log files must be known before the memtables are replayed:
10
+ + // an entry in the WAL may point at a value the value log lost in an
11
+ + // unclean stop, and such a transaction must not come back.
12
+ + db.vlog.init(db)
13
+ + if err := db.vlog.openFiles(); err != nil {
14
+ + return db, y.Wrapf(err, "During db.vlog.openFiles")
15
+ + }
16
+ +
17
+ if err := db.openMemTables(db.opt); err != nil {
18
+ return nil, y.Wrapf(err, "while opening memtables")
19
+ }
20
+ @@ -356,9 +364,6 @@ func Open(opt Options) (*DB, error) {
21
+ return db, err
22
+ }
23
+
24
+ - // Initialize vlog struct.
25
+ - db.vlog.init(db)
26
+ -
27
+ if !opt.ReadOnly {
28
+ db.closers.compactors = z.NewCloser(1)
29
+ db.lc.startCompact(db.closers.compactors)
30
+ diff --git a/journal_recovery_test.go b/journal_recovery_test.go
31
+ new file mode 100644
32
+ index 0000000..0ad986f
33
+ --- /dev/null
34
+ +++ b/journal_recovery_test.go
35
+ @@ -0,0 +1,634 @@
36
+ +/*
37
+ + * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
38
+ + * SPDX-License-Identifier: Apache-2.0
39
+ + */
40
+ +
41
+ +package badger
42
+ +
43
+ +import (
44
+ + "bufio"
45
+ + "crypto/sha256"
46
+ + "encoding/hex"
47
+ + "fmt"
48
+ + "io"
49
+ + "math"
50
+ + "os"
51
+ + "os/exec"
52
+ + "path/filepath"
53
+ + "strings"
54
+ + "sync"
55
+ + "testing"
56
+ +
57
+ + "github.com/stretchr/testify/require"
58
+ +
59
+ + "github.com/dgraph-io/badger/v4/y"
60
+ +)
61
+ +
62
+ +// The tests in this file drive a child process that writes to a DB and never
63
+ +// closes it. The parent tells the child when to take a step, the child answers
64
+ +// "ok <step> <vlog fid> <vlog offset> <wal fid> <wal offset>" once the step's
65
+ +// commit has been acknowledged, and the parent kills the child with SIGKILL
66
+ +// after the step it is interested in. No timers are involved: every kill
67
+ +// happens at a point the child has reported.
68
+ +
69
+ +const (
70
+ + journalChildEnv = "BADGER_JOURNAL_CHILD"
71
+ + journalDirEnv = "BADGER_JOURNAL_DIR"
72
+ + journalBigSize = 4096 // goes to the value log
73
+ + journalSmallLen = 1024 // stays in the WAL
74
+ + journalGCSize = 8000 // fills a value log file quickly
75
+ + journalWriters = 8
76
+ +)
77
+ +
78
+ +func journalOptions(dir string) Options {
79
+ + return DefaultOptions(dir).
80
+ + WithSyncWrites(true).
81
+ + WithValueThreshold(2048).
82
+ + WithMemTableSize(256 << 10).
83
+ + WithValueLogFileSize(1 << 20).
84
+ + WithLoggingLevel(ERROR)
85
+ +}
86
+ +
87
+ +func journalBlob(tag string, size int) []byte {
88
+ + return []byte(strings.Repeat(tag+"|", size/(len(tag)+1)+1)[:size])
89
+ +}
90
+ +
91
+ +func journalBig(tag string) []byte {
92
+ + return journalBlob(tag, journalBigSize)
93
+ +}
94
+ +
95
+ +func journalSmall(tag string) []byte {
96
+ + return []byte(fmt.Sprintf("%-*s", journalSmallLen, tag)[:journalSmallLen])
97
+ +}
98
+ +
99
+ +// journalStep performs step n of the given scenario on db.
100
+ +func journalStep(db *DB, scenario string, n int) error {
101
+ + switch scenario {
102
+ + case "vlog":
103
+ + switch n {
104
+ + case 1:
105
+ + return db.Update(func(txn *Txn) error {
106
+ + if err := txn.Set([]byte("k1"), journalBig("k1v1")); err != nil {
107
+ + return err
108
+ + }
109
+ + return txn.Set([]byte("k2"), journalSmall("k2v1"))
110
+ + })
111
+ + case 2:
112
+ + return db.Update(func(txn *Txn) error {
113
+ + if err := txn.Set([]byte("k3"), journalBig("k3v1")); err != nil {
114
+ + return err
115
+ + }
116
+ + if err := txn.Set([]byte("k4"), journalSmall("k4v1")); err != nil {
117
+ + return err
118
+ + }
119
+ + return txn.Set([]byte("k1"), journalBig("k1v2"))
120
+ + })
121
+ + case 3:
122
+ + return db.Update(func(txn *Txn) error { return txn.Delete([]byte("k2")) })
123
+ + case 4:
124
+ + return db.Update(func(txn *Txn) error { return txn.Set([]byte("k5"), journalSmall("k5v1")) })
125
+ + }
126
+ + case "mixed":
127
+ + switch n {
128
+ + case 1:
129
+ + wb := db.NewManagedWriteBatch()
130
+ + for i, ts := range []uint64{10, 11, 12} {
131
+ + k := []byte(fmt.Sprintf("m%d", i+1))
132
+ + if err := wb.SetEntryAt(NewEntry(k, journalSmall(string(k))), ts); err != nil {
133
+ + return err
134
+ + }
135
+ + }
136
+ + return wb.Flush()
137
+ + case 2:
138
+ + txn := db.NewTransactionAt(20, true)
139
+ + if err := txn.Set([]byte("m4"), journalBig("m4")); err != nil {
140
+ + return err
141
+ + }
142
+ + return txn.CommitAt(20, nil)
143
+ + case 3:
144
+ + wb := db.NewWriteBatchAt(30)
145
+ + if err := wb.SetEntryAt(NewEntry([]byte("m5"), journalSmall("m5")), 31); err != nil {
146
+ + return err
147
+ + }
148
+ + if err := wb.DeleteAt([]byte("m2"), 32); err != nil {
149
+ + return err
150
+ + }
151
+ + return wb.Flush()
152
+ + }
153
+ + case "gc":
154
+ + // x twice (each version flushed to a table, so that the tables carry
155
+ + // the discard statistics), then y and z until the value log rotates;
156
+ + // compaction, then garbage collection until nothing is left to move.
157
+ + // Every live value of the first file is copied to the last one and
158
+ + // re-logged in the WAL, and the first file is deleted.
159
+ + if n != 1 {
160
+ + break
161
+ + }
162
+ + put := func(prefix string, count int, tag string) error {
163
+ + for i := 0; i < count; i++ {
164
+ + k := fmt.Sprintf("%s-%03d", prefix, i)
165
+ + if err := db.Update(func(txn *Txn) error {
166
+ + return txn.Set([]byte(k), journalBlob(k+tag, journalGCSize))
167
+ + }); err != nil {
168
+ + return err
169
+ + }
170
+ + }
171
+ + return nil
172
+ + }
173
+ + flush := func() error {
174
+ + if err := db.Update(func(txn *Txn) error {
175
+ + return txn.Set([]byte("drop-me"), []byte("x"))
176
+ + }); err != nil {
177
+ + return err
178
+ + }
179
+ + return db.DropPrefix([]byte("drop-"))
180
+ + }
181
+ + if err := put("x", 40, "/1"); err != nil {
182
+ + return err
183
+ + }
184
+ + if err := flush(); err != nil {
185
+ + return err
186
+ + }
187
+ + if err := put("x", 40, "/2"); err != nil {
188
+ + return err
189
+ + }
190
+ + if err := flush(); err != nil {
191
+ + return err
192
+ + }
193
+ + if err := put("y", 20, ""); err != nil {
194
+ + return err
195
+ + }
196
+ + if err := put("z", 60, ""); err != nil {
197
+ + return err
198
+ + }
199
+ + if err := db.Flatten(1); err != nil {
200
+ + return err
201
+ + }
202
+ + for {
203
+ + err := db.RunValueLogGC(0.05)
204
+ + if err == ErrNoRewrite {
205
+ + break
206
+ + }
207
+ + if err != nil {
208
+ + return err
209
+ + }
210
+ + }
211
+ + db.vlog.filesLock.RLock()
212
+ + _, kept := db.vlog.filesMap[1]
213
+ + db.vlog.filesLock.RUnlock()
214
+ + if kept {
215
+ + return fmt.Errorf("garbage collection did not retire value log file 1")
216
+ + }
217
+ + return nil
218
+ + case "load":
219
+ + var wg sync.WaitGroup
220
+ + errs := make([]error, journalWriters)
221
+ + for g := 0; g < journalWriters; g++ {
222
+ + wg.Add(1)
223
+ + go func(g int) {
224
+ + defer wg.Done()
225
+ + errs[g] = db.Update(func(txn *Txn) error {
226
+ + big := fmt.Sprintf("g%d-b%d", g, n)
227
+ + small := fmt.Sprintf("g%d-s%d", g, n)
228
+ + if err := txn.Set([]byte(big), journalBig(big)); err != nil {
229
+ + return err
230
+ + }
231
+ + return txn.Set([]byte(small), journalSmall(small))
232
+ + })
233
+ + }(g)
234
+ + }
235
+ + wg.Wait()
236
+ + for _, err := range errs {
237
+ + if err != nil {
238
+ + return err
239
+ + }
240
+ + }
241
+ + return nil
242
+ + }
243
+ + return fmt.Errorf("no step %d in scenario %q", n, scenario)
244
+ +}
245
+ +
246
+ +// TestJournalChild is the child process. It only runs when spawned by the
247
+ +// tests below.
248
+ +func TestJournalChild(t *testing.T) {
249
+ + scenario := os.Getenv(journalChildEnv)
250
+ + if scenario == "" {
251
+ + t.Skip("child process of the journal recovery tests")
252
+ + }
253
+ + opt := journalOptions(os.Getenv(journalDirEnv))
254
+ + var db *DB
255
+ + var err error
256
+ + if scenario == "mixed" {
257
+ + db, err = OpenManaged(opt)
258
+ + } else {
259
+ + db, err = Open(opt)
260
+ + }
261
+ + if err != nil {
262
+ + fmt.Printf("error %v\n", err)
263
+ + os.Exit(2)
264
+ + }
265
+ + in := bufio.NewScanner(os.Stdin)
266
+ + for step := 1; in.Scan(); step++ {
267
+ + if err := journalStep(db, scenario, step); err != nil {
268
+ + fmt.Printf("error %v\n", err)
269
+ + os.Exit(2)
270
+ + }
271
+ + fmt.Printf("ok %d %d %d %d %d\n", step,
272
+ + db.vlog.maxFid, db.vlog.woffset(), db.mt.wal.fid, db.mt.wal.writeAt)
273
+ + }
274
+ + // The parent went away without killing us. Leave without closing, as a
275
+ + // crash would.
276
+ + os.Exit(0)
277
+ +}
278
+ +
279
+ +type journalMark struct {
280
+ + vlogFid, vlogOff, walFid, walOff uint32
281
+ +}
282
+ +
283
+ +type journalChild struct {
284
+ + t *testing.T
285
+ + cmd *exec.Cmd
286
+ + in io.WriteCloser
287
+ + out *bufio.Scanner
288
+ +}
289
+ +
290
+ +func startJournalChild(t *testing.T, scenario, dir string) *journalChild {
291
+ + t.Helper()
292
+ + cmd := exec.Command(os.Args[0], "-test.run=^TestJournalChild$")
293
+ + cmd.Env = append(os.Environ(), journalChildEnv+"="+scenario, journalDirEnv+"="+dir)
294
+ + cmd.Stderr = os.Stderr
295
+ + in, err := cmd.StdinPipe()
296
+ + require.NoError(t, err)
297
+ + out, err := cmd.StdoutPipe()
298
+ + require.NoError(t, err)
299
+ + require.NoError(t, cmd.Start())
300
+ + c := &journalChild{t: t, cmd: cmd, in: in, out: bufio.NewScanner(out)}
301
+ + t.Cleanup(func() { c.kill() })
302
+ + return c
303
+ +}
304
+ +
305
+ +// step asks the child for one more step and returns where its logs ended
306
+ +// once the step was acknowledged.
307
+ +func (c *journalChild) step() journalMark {
308
+ + c.t.Helper()
309
+ + _, err := io.WriteString(c.in, "next\n")
310
+ + require.NoError(c.t, err)
311
+ + require.True(c.t, c.out.Scan(), "child stopped answering")
312
+ + var m journalMark
313
+ + var n int
314
+ + _, err = fmt.Sscanf(c.out.Text(), "ok %d %d %d %d %d",
315
+ + &n, &m.vlogFid, &m.vlogOff, &m.walFid, &m.walOff)
316
+ + require.NoError(c.t, err, "child said %q", c.out.Text())
317
+ + return m
318
+ +}
319
+ +
320
+ +// kill stops the child the way a crash would.
321
+ +func (c *journalChild) kill() {
322
+ + if c.cmd.ProcessState != nil {
323
+ + return
324
+ + }
325
+ + _ = c.cmd.Process.Kill()
326
+ + _ = c.cmd.Wait()
327
+ +}
328
+ +
329
+ +// runJournalChild runs the scenario for the given number of steps in a fresh
330
+ +// directory, kills the child and returns the directory and the marks.
331
+ +func runJournalChild(t *testing.T, scenario string, steps int) (string, []journalMark) {
332
+ + t.Helper()
333
+ + dir, err := os.MkdirTemp("", "badger-journal")
334
+ + require.NoError(t, err)
335
+ + t.Cleanup(func() { removeDir(dir) })
336
+ + c := startJournalChild(t, scenario, dir)
337
+ + marks := make([]journalMark, 0, steps)
338
+ + for i := 0; i < steps; i++ {
339
+ + marks = append(marks, c.step())
340
+ + }
341
+ + c.kill()
342
+ + return dir, marks
343
+ +}
344
+ +
345
+ +func journalFileHashes(t *testing.T, dir string) map[string]string {
346
+ + t.Helper()
347
+ + entries, err := os.ReadDir(dir)
348
+ + require.NoError(t, err)
349
+ + hashes := make(map[string]string)
350
+ + for _, e := range entries {
351
+ + // Tables are outside the journal: a flush that was under way when the
352
+ + // process died leaves one the manifest does not know about, and that
353
+ + // one is removed on open, read-only or not, as it always was.
354
+ + if e.IsDir() || strings.HasSuffix(e.Name(), ".sst") {
355
+ + continue
356
+ + }
357
+ + data, err := os.ReadFile(filepath.Join(dir, e.Name()))
358
+ + require.NoError(t, err)
359
+ + sum := sha256.Sum256(data)
360
+ + hashes[e.Name()] = fmt.Sprintf("%d:%s", len(data), hex.EncodeToString(sum[:]))
361
+ + }
362
+ + return hashes
363
+ +}
364
+ +
365
+ +// zeroTail overwrites path from off to its end with zeros, as if the pages
366
+ +// after off had never reached the disk.
367
+ +func zeroTail(t *testing.T, path string, off uint32) {
368
+ + t.Helper()
369
+ + fi, err := os.Stat(path)
370
+ + require.NoError(t, err)
371
+ + f, err := os.OpenFile(path, os.O_WRONLY, 0)
372
+ + require.NoError(t, err)
373
+ + defer f.Close()
374
+ + _, err = f.WriteAt(make([]byte, fi.Size()-int64(off)), int64(off))
375
+ + require.NoError(t, err)
376
+ +}
377
+ +
378
+ +func openJournal(t *testing.T, dir string, readOnly, managed bool) (*DB, error) {
379
+ + t.Helper()
380
+ + opt := journalOptions(dir)
381
+ + opt.ReadOnly = readOnly
382
+ + if managed {
383
+ + return OpenManaged(opt)
384
+ + }
385
+ + return Open(opt)
386
+ +}
387
+ +
388
+ +// journalGet returns the value of key, or "" and false when it is absent.
389
+ +func journalGet(t *testing.T, db *DB, key string) (string, bool) {
390
+ + t.Helper()
391
+ + var txn *Txn
392
+ + if db.opt.managedTxns {
393
+ + txn = db.NewTransactionAt(math.MaxUint64, false)
394
+ + } else {
395
+ + txn = db.NewTransaction(false)
396
+ + }
397
+ + defer txn.Discard()
398
+ + item, err := txn.Get([]byte(key))
399
+ + if err == ErrKeyNotFound {
400
+ + return "", false
401
+ + }
402
+ + require.NoError(t, err)
403
+ + val, err := item.ValueCopy(nil)
404
+ + require.NoError(t, err)
405
+ + return string(val), true
406
+ +}
407
+ +
408
+ +func requireJournalValue(t *testing.T, db *DB, key string, want []byte) {
409
+ + t.Helper()
410
+ + got, ok := journalGet(t, db, key)
411
+ + require.True(t, ok, "key %s is missing", key)
412
+ + require.Equal(t, string(want), got, "key %s", key)
413
+ +}
414
+ +
415
+ +func requireJournalAbsent(t *testing.T, db *DB, key string) {
416
+ + t.Helper()
417
+ + got, ok := journalGet(t, db, key)
418
+ + require.False(t, ok, "key %s should be absent, has %q", key, got)
419
+ +}
420
+ +
421
+ +// requireReadOnlyRefuses opens the DB read-only, expects an error and
422
+ +// expects every file to be exactly as it was.
423
+ +func requireReadOnlyRefuses(t *testing.T, dir string, managed bool) {
424
+ + t.Helper()
425
+ + before := journalFileHashes(t, dir)
426
+ + db, err := openJournal(t, dir, true, managed)
427
+ + if err == nil {
428
+ + require.NoError(t, db.Close())
429
+ + }
430
+ + require.Error(t, err, "read-only open must refuse a torn history")
431
+ + require.Equal(t, before, journalFileHashes(t, dir), "read-only open changed a file")
432
+ +}
433
+ +
434
+ +func TestJournalTornValueLogTailKeepsTransactionsWhole(t *testing.T) {
435
+ + // A tear in the middle of the second transaction's values, emulating
436
+ + // pages that never reached the disk: the file keeps its length.
437
+ + t.Run("zeroed", func(t *testing.T) {
438
+ + dir, marks := runJournalChild(t, "vlog", 4)
439
+ + vlogPath := vlogFilePath(dir, marks[1].vlogFid)
440
+ + require.Equal(t, marks[0].vlogFid, marks[1].vlogFid)
441
+ + zeroTail(t, vlogPath, marks[0].vlogOff+(marks[1].vlogOff-marks[0].vlogOff)/2)
442
+ +
443
+ + requireReadOnlyRefuses(t, dir, false)
444
+ +
445
+ + db, err := openJournal(t, dir, false, false)
446
+ + require.NoError(t, err)
447
+ + // The first transaction is whole, the torn one is gone entirely —
448
+ + // including the part of it that lived in the WAL — and so is
449
+ + // everything committed after it.
450
+ + requireJournalValue(t, db, "k1", journalBig("k1v1"))
451
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
452
+ + requireJournalAbsent(t, db, "k3")
453
+ + requireJournalAbsent(t, db, "k4")
454
+ + requireJournalAbsent(t, db, "k5")
455
+ +
456
+ + // Writes after recovery win, and stay won.
457
+ + require.NoError(t, db.Update(func(txn *Txn) error {
458
+ + return txn.Set([]byte("k1"), journalBig("k1v3"))
459
+ + }))
460
+ + requireJournalValue(t, db, "k1", journalBig("k1v3"))
461
+ + require.NoError(t, db.Close())
462
+ + db, err = openJournal(t, dir, false, false)
463
+ + require.NoError(t, err)
464
+ + requireJournalValue(t, db, "k1", journalBig("k1v3"))
465
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
466
+ + requireJournalAbsent(t, db, "k3")
467
+ + require.NoError(t, db.Close())
468
+ + })
469
+ +
470
+ + // The file cut exactly where the first transaction's values end: that
471
+ + // transaction is whole, the next one is not.
472
+ + t.Run("truncated at a record boundary", func(t *testing.T) {
473
+ + dir, marks := runJournalChild(t, "vlog", 4)
474
+ + require.NoError(t, os.Truncate(vlogFilePath(dir, marks[0].vlogFid), int64(marks[0].vlogOff)))
475
+ +
476
+ + requireReadOnlyRefuses(t, dir, false)
477
+ +
478
+ + db, err := openJournal(t, dir, false, false)
479
+ + require.NoError(t, err)
480
+ + requireJournalValue(t, db, "k1", journalBig("k1v1"))
481
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
482
+ + requireJournalAbsent(t, db, "k3")
483
+ + requireJournalAbsent(t, db, "k4")
484
+ + requireJournalAbsent(t, db, "k5")
485
+ + require.NoError(t, db.Close())
486
+ + })
487
+ +
488
+ + // A tear in the WAL itself, with the value log whole.
489
+ + t.Run("torn wal", func(t *testing.T) {
490
+ + dir, marks := runJournalChild(t, "vlog", 4)
491
+ + require.Equal(t, marks[0].walFid, marks[1].walFid)
492
+ + zeroTail(t, filepath.Join(dir, fmt.Sprintf("%05d%s", marks[1].walFid, memFileExt)), marks[1].walOff-5)
493
+ +
494
+ + requireReadOnlyRefuses(t, dir, false)
495
+ +
496
+ + db, err := openJournal(t, dir, false, false)
497
+ + require.NoError(t, err)
498
+ + requireJournalValue(t, db, "k1", journalBig("k1v1"))
499
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
500
+ + requireJournalAbsent(t, db, "k3")
501
+ + requireJournalAbsent(t, db, "k4")
502
+ + requireJournalAbsent(t, db, "k5")
503
+ + require.NoError(t, db.Close())
504
+ + })
505
+ +}
506
+ +
507
+ +func TestJournalMixedVersionTransactionWholeAfterTear(t *testing.T) {
508
+ + checkWhole := func(t *testing.T, db *DB) {
509
+ + t.Helper()
510
+ + requireJournalValue(t, db, "m1", journalSmall("m1"))
511
+ + requireJournalAbsent(t, db, "m2") // deleted at 32
512
+ + requireJournalValue(t, db, "m3", journalSmall("m3"))
513
+ + requireJournalValue(t, db, "m4", journalBig("m4"))
514
+ + requireJournalValue(t, db, "m5", journalSmall("m5"))
515
+ + }
516
+ +
517
+ + t.Run("killed without a tear", func(t *testing.T) {
518
+ + dir, _ := runJournalChild(t, "mixed", 3)
519
+ + before := journalFileHashes(t, dir)
520
+ + db, err := openJournal(t, dir, true, true)
521
+ + require.NoError(t, err)
522
+ + checkWhole(t, db)
523
+ + require.NoError(t, db.Close())
524
+ + require.Equal(t, before, journalFileHashes(t, dir))
525
+ +
526
+ + db, err = openJournal(t, dir, false, true)
527
+ + require.NoError(t, err)
528
+ + checkWhole(t, db)
529
+ + require.NoError(t, db.Close())
530
+ + })
531
+ +
532
+ + t.Run("torn inside the mixed transaction", func(t *testing.T) {
533
+ + dir, marks := runJournalChild(t, "mixed", 3)
534
+ + zeroTail(t, filepath.Join(dir, fmt.Sprintf("%05d%s", marks[0].walFid, memFileExt)), marks[0].walOff-5)
535
+ +
536
+ + requireReadOnlyRefuses(t, dir, true)
537
+ +
538
+ + db, err := openJournal(t, dir, false, true)
539
+ + require.NoError(t, err)
540
+ + for _, k := range []string{"m1", "m2", "m3", "m4", "m5"} {
541
+ + requireJournalAbsent(t, db, k)
542
+ + }
543
+ + require.NoError(t, db.Close())
544
+ + })
545
+ +
546
+ + t.Run("torn after the mixed transaction", func(t *testing.T) {
547
+ + dir, marks := runJournalChild(t, "mixed", 3)
548
+ + zeroTail(t, filepath.Join(dir, fmt.Sprintf("%05d%s", marks[2].walFid, memFileExt)), marks[2].walOff-5)
549
+ +
550
+ + requireReadOnlyRefuses(t, dir, true)
551
+ +
552
+ + db, err := openJournal(t, dir, false, true)
553
+ + require.NoError(t, err)
554
+ + requireJournalValue(t, db, "m1", journalSmall("m1"))
555
+ + requireJournalValue(t, db, "m2", journalSmall("m2"))
556
+ + requireJournalValue(t, db, "m3", journalSmall("m3"))
557
+ + requireJournalValue(t, db, "m4", journalBig("m4"))
558
+ + requireJournalAbsent(t, db, "m5")
559
+ + require.NoError(t, db.Close())
560
+ + })
561
+ +}
562
+ +
563
+ +func TestJournalReadOnlyOpenAfterKillServesAcknowledgedCommits(t *testing.T) {
564
+ + const steps = 40
565
+ + dir, marks := runJournalChild(t, "load", steps)
566
+ + last := marks[len(marks)-1]
567
+ + require.Greater(t, last.vlogFid, uint32(1), "the value log should have rotated")
568
+ + require.Greater(t, last.walFid, uint32(1), "the memtable should have rotated")
569
+ +
570
+ + check := func(t *testing.T, db *DB) {
571
+ + t.Helper()
572
+ + for g := 0; g < journalWriters; g++ {
573
+ + for n := 1; n <= steps; n++ {
574
+ + big := fmt.Sprintf("g%d-b%d", g, n)
575
+ + small := fmt.Sprintf("g%d-s%d", g, n)
576
+ + requireJournalValue(t, db, big, journalBig(big))
577
+ + requireJournalValue(t, db, small, journalSmall(small))
578
+ + }
579
+ + }
580
+ + }
581
+ +
582
+ + before := journalFileHashes(t, dir)
583
+ + db, err := openJournal(t, dir, true, false)
584
+ + require.NoError(t, err)
585
+ + check(t, db)
586
+ + require.NoError(t, db.Close())
587
+ + require.Equal(t, before, journalFileHashes(t, dir), "read-only open changed a file")
588
+ +
589
+ + db, err = openJournal(t, dir, false, false)
590
+ + require.NoError(t, err)
591
+ + check(t, db)
592
+ + require.NoError(t, db.Update(func(txn *Txn) error {
593
+ + return txn.Set([]byte("after"), journalBig("after"))
594
+ + }))
595
+ + requireJournalValue(t, db, "after", journalBig("after"))
596
+ + require.NoError(t, db.Close())
597
+ +}
598
+ +
599
+ +// Garbage collection deletes a value log file once every live value in it
600
+ +// has been copied to the last file and re-logged in the WAL. A crash before
601
+ +// the next flush leaves the WAL still pointing at the deleted file for those
602
+ +// values' first records. That is not a tear: nothing acknowledged was lost,
603
+ +// and recovery, read-only or not, serves the whole history.
604
+ +func TestJournalRetiredValueLogFileIsNotATear(t *testing.T) {
605
+ + dir, marks := runJournalChild(t, "gc", 1)
606
+ + require.Greater(t, marks[0].vlogFid, uint32(1), "the value log should have rotated")
607
+ + require.NoFileExists(t, filepath.Join(dir, "000001.vlog"), "file 1 should have been retired")
608
+ +
609
+ + check := func(t *testing.T, db *DB) {
610
+ + t.Helper()
611
+ + for i := 0; i < 40; i++ {
612
+ + k := fmt.Sprintf("x-%03d", i)
613
+ + requireJournalValue(t, db, k, journalBlob(k+"/2", journalGCSize))
614
+ + }
615
+ + for i := 0; i < 20; i++ {
616
+ + k := fmt.Sprintf("y-%03d", i)
617
+ + requireJournalValue(t, db, k, journalBlob(k, journalGCSize))
618
+ + }
619
+ + for i := 0; i < 60; i++ {
620
+ + k := fmt.Sprintf("z-%03d", i)
621
+ + requireJournalValue(t, db, k, journalBlob(k, journalGCSize))
622
+ + }
623
+ + }
624
+ +
625
+ + before := journalFileHashes(t, dir)
626
+ + db, err := openJournal(t, dir, true, false)
627
+ + require.NoError(t, err)
628
+ + check(t, db)
629
+ + require.NoError(t, db.Close())
630
+ + require.Equal(t, before, journalFileHashes(t, dir), "read-only open changed a file")
631
+ +
632
+ + db, err = openJournal(t, dir, false, false)
633
+ + require.NoError(t, err)
634
+ + check(t, db)
635
+ + require.NoError(t, db.Close())
636
+ +}
637
+ +
638
+ +// A WAL written by an earlier build holds transactions with entries of
639
+ +// different versions and no markers around them. They still come back whole.
640
+ +func TestJournalOldTransactionWithoutMarkersReplaysWhole(t *testing.T) {
641
+ + dir, err := os.MkdirTemp("", "badger-journal")
642
+ + require.NoError(t, err)
643
+ + defer removeDir(dir)
644
+ +
645
+ + opt := journalOptions(dir)
646
+ + db0, err := OpenManaged(opt)
647
+ + require.NoError(t, err)
648
+ + defer func() { require.NoError(t, db0.Close()) }()
649
+ + for i, ts := range []uint64{10, 11, 12} {
650
+ + k := fmt.Sprintf("o%d", i+1)
651
+ + require.NoError(t, db0.mt.Put(y.KeyWithTs([]byte(k), ts), y.ValueStruct{Value: journalSmall(k)}))
652
+ + }
653
+ + require.NoError(t, db0.mt.SyncWAL())
654
+ + // Simulate a crash by not closing db0, but releasing the locks.
655
+ + require.NoError(t, db0.dirLockGuard.release())
656
+ + db0.dirLockGuard = nil
657
+ + if db0.valueDirGuard != nil {
658
+ + require.NoError(t, db0.valueDirGuard.release())
659
+ + db0.valueDirGuard = nil
660
+ + }
661
+ +
662
+ + db1, err := openJournal(t, dir, true, true)
663
+ + require.NoError(t, err)
664
+ + for i := 1; i <= 3; i++ {
665
+ + k := fmt.Sprintf("o%d", i)
666
+ + requireJournalValue(t, db1, k, journalSmall(k))
667
+ + }
668
+ + require.NoError(t, db1.Close())
669
+ +}
670
+ diff --git a/memtable.go b/memtable.go
671
+ index 161a463..f107477 100644
672
+ --- a/memtable.go
673
+ +++ b/memtable.go
674
+ @@ -38,6 +38,9 @@ type memTable struct {
675
+ maxVersion uint64
676
+ opt Options
677
+ buf *bytes.Buffer
678
+ + // vptrOK tells replay whether a value pointer found in the WAL still
679
+ + // addresses a record the value log holds.
680
+ + vptrOK func(valuePointer) bool
681
+ }
682
+
683
+ func (db *DB) openMemTables(opt Options) error {
684
+ @@ -98,9 +101,10 @@ func (db *DB) openMemTable(fid, flags int) (*memTable, error) {
685
+ filepath := db.mtFilePath(fid)
686
+ s := skl.NewSkiplist(arenaSize(db.opt))
687
+ mt := &memTable{
688
+ - sl: s,
689
+ - opt: db.opt,
690
+ - buf: &bytes.Buffer{},
691
+ + sl: s,
692
+ + opt: db.opt,
693
+ + buf: &bytes.Buffer{},
694
+ + vptrOK: db.vlog.contains,
695
+ }
696
+ // We don't need to create the wal for the skiplist in in-memory mode so return the mt.
697
+ if db.opt.InMemory {
698
+ @@ -202,12 +206,19 @@ func (mt *memTable) UpdateSkipList() error {
699
+ if mt.wal == nil || mt.sl == nil {
700
+ return nil
701
+ }
702
+ - endOff, err := mt.wal.iterate(true, 0, mt.replayFunction(mt.opt))
703
+ + endOff, stopAt, err := mt.wal.replay(0, mt.replayFunction(mt.opt), mt.vptrOK)
704
+ if err != nil {
705
+ return y.Wrapf(err, "while iterating wal: %s", mt.wal.Fd.Name())
706
+ }
707
+ - if endOff < mt.wal.size.Load() && mt.opt.ReadOnly {
708
+ - return y.Wrapf(ErrTruncateNeeded, "end offset: %d < size: %d", endOff, mt.wal.size.Load())
709
+ + if mt.opt.ReadOnly {
710
+ + // The file is pre-allocated, so a tail of zeros after the last record
711
+ + // is the normal state after an unclean stop and needs no repair. Any
712
+ + // other bytes there are a damaged record, and a read-only DB must
713
+ + // not repair it.
714
+ + if !mt.wal.zeroFrom(stopAt) {
715
+ + return y.Wrapf(ErrTruncateNeeded, "end offset: %d < size: %d", endOff, mt.wal.size.Load())
716
+ + }
717
+ + return nil
718
+ }
719
+ return mt.wal.Truncate(int64(endOff))
720
+ }
721
+ @@ -431,6 +442,41 @@ func (lf *logFile) doneWriting(offset uint32) error {
722
+ // iterate iterates over log file. It doesn't not allocate new memory for every kv pair.
723
+ // Therefore, the kv pair is only valid for the duration of fn call.
724
+ func (lf *logFile) iterate(readOnly bool, offset uint32, fn logEntry) (uint32, error) {
725
+ + end, _, err := lf.replay(offset, fn, nil)
726
+ + return end, err
727
+ +}
728
+ +
729
+ +// lostValue reports whether e's value lives in the value log at a place the
730
+ +// value log no longer holds, according to vptrOK.
731
+ +func lostValue(e *Entry, vptrOK func(valuePointer) bool) bool {
732
+ + if vptrOK == nil || e.meta&bitValuePointer == 0 {
733
+ + return false
734
+ + }
735
+ + if uintptr(len(e.Value)) < vptrSize {
736
+ + return true
737
+ + }
738
+ + var vp valuePointer
739
+ + vp.Decode(e.Value)
740
+ + return !vptrOK(vp)
741
+ +}
742
+ +
743
+ +// zeroFrom reports whether nothing but zeros follows off in the file.
744
+ +func (lf *logFile) zeroFrom(off uint32) bool {
745
+ + if int64(off) >= int64(len(lf.Data)) {
746
+ + return true
747
+ + }
748
+ + return len(bytes.TrimLeft(lf.Data[off:], "\x00")) == 0
749
+ +}
750
+ +
751
+ +// replay is iterate with two additions. When vptrOK is given, an entry whose
752
+ +// value lives in the value log is checked against it before anything of its
753
+ +// transaction is applied, so a pointer to a lost value stops the replay in
754
+ +// front of that transaction. Besides the offset up to which the log was
755
+ +// applied, replay returns the offset of the record it stopped at: the one it
756
+ +// could not read, or the one it could not accept — a transaction with a
757
+ +// missing or mismatching end marker, an entry pointing at a lost value.
758
+ +func (lf *logFile) replay(offset uint32, fn logEntry, vptrOK func(valuePointer) bool) (
759
+ + uint32, uint32, error) {
760
+ if offset == 0 {
761
+ // If offset is set to zero, let's advance past the encryption key header.
762
+ offset = vlogHeaderSize
763
+ @@ -445,14 +491,19 @@ func (lf *logFile) iterate(readOnly bool, offset uint32, fn logEntry) (uint32, e
764
+ lf: lf,
765
+ }
766
+
767
+ - var lastCommit uint64
768
+ + // lastCommit is the version of the entry that opened the transaction
769
+ + // being read, or zero outside a transaction; txnMax is the largest
770
+ + // version seen in it, which its end marker must repeat.
771
+ + var lastCommit, txnMax uint64
772
+ var validEndOffset uint32 = offset
773
+
774
+ var entries []*Entry
775
+ var vptrs []valuePointer
776
+
777
+ + var stopAt uint32
778
+ loop:
779
+ for {
780
+ + stopAt = read.recordOffset
781
+ e, err := read.Entry(reader)
782
+ switch {
783
+ // We have not reached the end of the file but the entry we read is
784
+ @@ -463,7 +514,7 @@ loop:
785
+ case err == io.ErrUnexpectedEOF || err == errTruncate:
786
+ break loop
787
+ case err != nil:
788
+ - return 0, err
789
+ + return 0, 0, err
790
+ case e == nil:
791
+ continue
792
+ case e.isZero():
793
+ @@ -483,19 +534,24 @@ loop:
794
+ if lastCommit == 0 {
795
+ lastCommit = txnTs
796
+ }
797
+ - if lastCommit != txnTs {
798
+ - break loop
799
+ + if txnTs > txnMax {
800
+ + txnMax = txnTs
801
+ }
802
+ entries = append(entries, e)
803
+ vptrs = append(vptrs, vp)
804
+
805
+ case e.meta&bitFinTxn > 0:
806
+ txnTs, err := strconv.ParseUint(string(e.Value), 10, 64)
807
+ - if err != nil || lastCommit != txnTs {
808
+ + if err != nil || lastCommit == 0 || txnTs != txnMax {
809
+ break loop
810
+ }
811
+ + for _, e := range entries {
812
+ + if lostValue(e, vptrOK) {
813
+ + break loop
814
+ + }
815
+ + }
816
+ // Got the end of txn. Now we can store them.
817
+ - lastCommit = 0
818
+ + lastCommit, txnMax = 0, 0
819
+ validEndOffset = read.recordOffset
820
+
821
+ for i, e := range entries {
822
+ @@ -504,7 +560,7 @@ loop:
823
+ if err == errStop {
824
+ break
825
+ }
826
+ - return 0, errFile(err, lf.path, "Iteration function")
827
+ + return 0, 0, errFile(err, lf.path, "Iteration function")
828
+ }
829
+ }
830
+ entries = entries[:0]
831
+ @@ -516,17 +572,20 @@ loop:
832
+ // We shouldn't get this entry in the middle of a transaction.
833
+ break loop
834
+ }
835
+ + if lostValue(e, vptrOK) {
836
+ + break loop
837
+ + }
838
+ validEndOffset = read.recordOffset
839
+
840
+ if err := fn(*e, vp); err != nil {
841
+ if err == errStop {
842
+ break
843
+ }
844
+ - return 0, errFile(err, lf.path, "Iteration function")
845
+ + return 0, 0, errFile(err, lf.path, "Iteration function")
846
+ }
847
+ }
848
+ }
849
+ - return validEndOffset, nil
850
+ + return validEndOffset, stopAt, nil
851
+ }
852
+
853
+ // Zero out the next entry to deal with any crashes.
854
+ diff --git a/txn.go b/txn.go
855
+ index 9c916d1..5e852af 100644
856
+ --- a/txn.go
857
+ +++ b/txn.go
858
+ @@ -532,12 +532,17 @@ func (txn *Txn) commitAndSend() (func() error, error) {
859
+ return nil, ErrConflict
860
+ }
861
+
862
+ - keepTogether := true
863
+ + // Every transaction is bracketed by markers in the log so that replay can
864
+ + // apply it whole or not at all. Entries may carry their own versions
865
+ + // (SetEntryAt in managed mode), and commitTs may then even be zero, so the
866
+ + // end marker carries the largest version in the transaction.
867
+ + var maxVersion uint64
868
+ setVersion := func(e *Entry) {
869
+ if e.version == 0 {
870
+ e.version = commitTs
871
+ - } else {
872
+ - keepTogether = false
873
+ + }
874
+ + if e.version > maxVersion {
875
+ + maxVersion = e.version
876
+ }
877
+ }
878
+ for _, e := range txn.pendingWrites {
879
+ @@ -555,14 +560,7 @@ func (txn *Txn) commitAndSend() (func() error, error) {
880
+ // Suffix the keys with commit ts, so the key versions are sorted in
881
+ // descending order of commit timestamp.
882
+ e.Key = y.KeyWithTs(e.Key, e.version)
883
+ - // Add bitTxn only if these entries are part of a transaction. We
884
+ - // support SetEntryAt(..) in managed mode which means a single
885
+ - // transaction can have entries with different timestamps. If entries
886
+ - // in a single transaction have different timestamps, we don't add the
887
+ - // transaction markers.
888
+ - if keepTogether {
889
+ - e.meta |= bitTxn
890
+ - }
891
+ + e.meta |= bitTxn
892
+ entries = append(entries, e)
893
+ }
894
+
895
+ @@ -579,16 +577,14 @@ func (txn *Txn) commitAndSend() (func() error, error) {
896
+ processEntry(e)
897
+ }
898
+
899
+ - if keepTogether {
900
+ - // CommitTs should not be zero if we're inserting transaction markers.
901
+ - y.AssertTrue(commitTs != 0)
902
+ - e := &Entry{
903
+ - Key: y.KeyWithTs(txnKey, commitTs),
904
+ - Value: []byte(strconv.FormatUint(commitTs, 10)),
905
+ - meta: bitFinTxn,
906
+ - }
907
+ - entries = append(entries, e)
908
+ - }
909
+ + // commitPrecheck guarantees a non-zero commitTs whenever no entry has a
910
+ + // version of its own.
911
+ + y.AssertTrue(maxVersion != 0)
912
+ + entries = append(entries, &Entry{
913
+ + Key: y.KeyWithTs(txnKey, maxVersion),
914
+ + Value: []byte(strconv.FormatUint(maxVersion, 10)),
915
+ + meta: bitFinTxn,
916
+ + })
917
+
918
+ req, err := txn.db.sendToWriteCh(entries)
919
+ if err != nil {
920
+ diff --git a/value.go b/value.go
921
+ index e042651..c343473 100644
922
+ --- a/value.go
923
+ +++ b/value.go
924
+ @@ -580,26 +580,24 @@ func (vlog *valueLog) init(db *DB) {
925
+ db.logToSyncChan(endVLogInitMsg)
926
+ }
927
+
928
+ -func (vlog *valueLog) open(db *DB) error {
929
+ - // We don't need to open any vlog files or collect stats for GC if DB is opened
930
+ - // in InMemory mode. InMemory mode doesn't create any files/directories on disk.
931
+ - if db.opt.InMemory {
932
+ +// openFiles opens the value log files found on disk and establishes how much
933
+ +// of each one holds records. Files that were rotated out were cut down to
934
+ +// their records when they were retired; the last file is pre-allocated and
935
+ +// may end in whatever an unclean stop left behind, so its size is what can be
936
+ +// parsed from it. Nothing is written: this runs before the memtables are
937
+ +// replayed, in read-only mode too, so that replay can tell a pointer into a
938
+ +// lost value from a good one.
939
+ +func (vlog *valueLog) openFiles() error {
940
+ + if vlog.opt.InMemory {
941
+ return nil
942
+ }
943
+ -
944
+ if err := vlog.populateFilesMap(); err != nil {
945
+ return err
946
+ }
947
+ - // If no files are found, then create a new file.
948
+ if len(vlog.filesMap) == 0 {
949
+ - if vlog.opt.ReadOnly {
950
+ - return nil
951
+ - }
952
+ - _, err := vlog.createVlogFile()
953
+ - return y.Wrapf(err, "Error while creating log file in valueLog.open")
954
+ + return nil
955
+ }
956
+ - fids := vlog.sortedFids()
957
+ - for _, fid := range fids {
958
+ + for _, fid := range vlog.sortedFids() {
959
+ lf, ok := vlog.filesMap[fid]
960
+ y.AssertTrue(ok)
961
+
962
+ @@ -612,20 +610,8 @@ func (vlog *valueLog) open(db *DB) error {
963
+ 2*vlog.opt.ValueLogFileSize); err != nil {
964
+ return y.Wrapf(err, "Open existing file: %q", lf.path)
965
+ }
966
+ - // We shouldn't delete the maxFid file.
967
+ - if lf.size.Load() == vlogHeaderSize && fid != vlog.maxFid && !vlog.opt.ReadOnly {
968
+ - vlog.opt.Infof("Deleting empty file: %s", lf.path)
969
+ - if err := lf.Delete(); err != nil {
970
+ - return y.Wrapf(err, "while trying to delete empty file: %s", lf.path)
971
+ - }
972
+ - delete(vlog.filesMap, fid)
973
+ - }
974
+ }
975
+ -
976
+ - if vlog.opt.ReadOnly {
977
+ - return nil
978
+ - }
979
+ - // Now we can read the latest value log file, and see if it needs truncation. We could
980
+ + // Read the latest value log file to see where its records end. We could
981
+ // technically do this over all the value log files, but that would mean slowing down the value
982
+ // log open.
983
+ last, ok := vlog.filesMap[vlog.maxFid]
984
+ @@ -637,7 +623,51 @@ func (vlog *valueLog) open(db *DB) error {
985
+ if err != nil {
986
+ return y.Wrapf(err, "while iterating over: %s", last.path)
987
+ }
988
+ - if err := last.Truncate(int64(lastOff)); err != nil {
989
+ + last.size.Store(lastOff)
990
+ + return nil
991
+ +}
992
+ +
993
+ +// contains reports whether vp addresses a record the value log holds, as
994
+ +// established by openFiles. For use while no writes are in flight.
995
+ +func (vlog *valueLog) contains(vp valuePointer) bool {
996
+ + lf, ok := vlog.filesMap[vp.Fid]
997
+ + if !ok {
998
+ + // A file that is gone was retired by garbage collection, which had
999
+ + // moved every live value out of it first; an unclean stop never
1000
+ + // removes a file. The entry is stale, not torn.
1001
+ + return true
1002
+ + }
1003
+ + return uint64(vp.Offset)+uint64(vp.Len) <= uint64(lf.size.Load())
1004
+ +}
1005
+ +
1006
+ +// open makes the value log writable after openFiles: empty retired files are
1007
+ +// deleted, the last file is cut down to its records, and a fresh file is
1008
+ +// created to write into. A read-only DB leaves the files as they are.
1009
+ +func (vlog *valueLog) open(db *DB) error {
1010
+ + // We don't need to open any vlog files or collect stats for GC if DB is opened
1011
+ + // in InMemory mode. InMemory mode doesn't create any files/directories on disk.
1012
+ + if db.opt.InMemory || vlog.opt.ReadOnly {
1013
+ + return nil
1014
+ + }
1015
+ + // If no files are found, then create a new file.
1016
+ + if len(vlog.filesMap) == 0 {
1017
+ + _, err := vlog.createVlogFile()
1018
+ + return y.Wrapf(err, "Error while creating log file in valueLog.open")
1019
+ + }
1020
+ + for _, fid := range vlog.sortedFids() {
1021
+ + lf := vlog.filesMap[fid]
1022
+ + // We shouldn't delete the maxFid file.
1023
+ + if lf.size.Load() == vlogHeaderSize && fid != vlog.maxFid {
1024
+ + vlog.opt.Infof("Deleting empty file: %s", lf.path)
1025
+ + if err := lf.Delete(); err != nil {
1026
+ + return y.Wrapf(err, "while trying to delete empty file: %s", lf.path)
1027
+ + }
1028
+ + delete(vlog.filesMap, fid)
1029
+ + }
1030
+ + }
1031
+ + last, ok := vlog.filesMap[vlog.maxFid]
1032
+ + y.AssertTrue(ok)
1033
+ + if err := last.Truncate(int64(last.size.Load())); err != nil {
1034
+ return y.Wrapf(err, "while truncating last value log file: %s", last.path)
1035
+ }
1036
+
harbor/tasks/journal_recovery_after_unclean_stop/solution/solve.sh ADDED
@@ -0,0 +1,1042 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -eu
3
+ cd /workspace/repo
4
+ git apply <<'REFERENCE_PATCH'
5
+ diff --git a/db.go b/db.go
6
+ index 9572203..cf8e0f4 100644
7
+ --- a/db.go
8
+ +++ b/db.go
9
+ @@ -341,6 +341,14 @@ func Open(opt Options) (*DB, error) {
10
+ db.closers.updateSize = z.NewCloser(1)
11
+ go db.updateSize(db.closers.updateSize)
12
+
13
+ + // The value log files must be known before the memtables are replayed:
14
+ + // an entry in the WAL may point at a value the value log lost in an
15
+ + // unclean stop, and such a transaction must not come back.
16
+ + db.vlog.init(db)
17
+ + if err := db.vlog.openFiles(); err != nil {
18
+ + return db, y.Wrapf(err, "During db.vlog.openFiles")
19
+ + }
20
+ +
21
+ if err := db.openMemTables(db.opt); err != nil {
22
+ return nil, y.Wrapf(err, "while opening memtables")
23
+ }
24
+ @@ -356,9 +364,6 @@ func Open(opt Options) (*DB, error) {
25
+ return db, err
26
+ }
27
+
28
+ - // Initialize vlog struct.
29
+ - db.vlog.init(db)
30
+ -
31
+ if !opt.ReadOnly {
32
+ db.closers.compactors = z.NewCloser(1)
33
+ db.lc.startCompact(db.closers.compactors)
34
+ diff --git a/journal_recovery_test.go b/journal_recovery_test.go
35
+ new file mode 100644
36
+ index 0000000..0ad986f
37
+ --- /dev/null
38
+ +++ b/journal_recovery_test.go
39
+ @@ -0,0 +1,634 @@
40
+ +/*
41
+ + * SPDX-FileCopyrightText: © Hypermode Inc. <hello@hypermode.com>
42
+ + * SPDX-License-Identifier: Apache-2.0
43
+ + */
44
+ +
45
+ +package badger
46
+ +
47
+ +import (
48
+ + "bufio"
49
+ + "crypto/sha256"
50
+ + "encoding/hex"
51
+ + "fmt"
52
+ + "io"
53
+ + "math"
54
+ + "os"
55
+ + "os/exec"
56
+ + "path/filepath"
57
+ + "strings"
58
+ + "sync"
59
+ + "testing"
60
+ +
61
+ + "github.com/stretchr/testify/require"
62
+ +
63
+ + "github.com/dgraph-io/badger/v4/y"
64
+ +)
65
+ +
66
+ +// The tests in this file drive a child process that writes to a DB and never
67
+ +// closes it. The parent tells the child when to take a step, the child answers
68
+ +// "ok <step> <vlog fid> <vlog offset> <wal fid> <wal offset>" once the step's
69
+ +// commit has been acknowledged, and the parent kills the child with SIGKILL
70
+ +// after the step it is interested in. No timers are involved: every kill
71
+ +// happens at a point the child has reported.
72
+ +
73
+ +const (
74
+ + journalChildEnv = "BADGER_JOURNAL_CHILD"
75
+ + journalDirEnv = "BADGER_JOURNAL_DIR"
76
+ + journalBigSize = 4096 // goes to the value log
77
+ + journalSmallLen = 1024 // stays in the WAL
78
+ + journalGCSize = 8000 // fills a value log file quickly
79
+ + journalWriters = 8
80
+ +)
81
+ +
82
+ +func journalOptions(dir string) Options {
83
+ + return DefaultOptions(dir).
84
+ + WithSyncWrites(true).
85
+ + WithValueThreshold(2048).
86
+ + WithMemTableSize(256 << 10).
87
+ + WithValueLogFileSize(1 << 20).
88
+ + WithLoggingLevel(ERROR)
89
+ +}
90
+ +
91
+ +func journalBlob(tag string, size int) []byte {
92
+ + return []byte(strings.Repeat(tag+"|", size/(len(tag)+1)+1)[:size])
93
+ +}
94
+ +
95
+ +func journalBig(tag string) []byte {
96
+ + return journalBlob(tag, journalBigSize)
97
+ +}
98
+ +
99
+ +func journalSmall(tag string) []byte {
100
+ + return []byte(fmt.Sprintf("%-*s", journalSmallLen, tag)[:journalSmallLen])
101
+ +}
102
+ +
103
+ +// journalStep performs step n of the given scenario on db.
104
+ +func journalStep(db *DB, scenario string, n int) error {
105
+ + switch scenario {
106
+ + case "vlog":
107
+ + switch n {
108
+ + case 1:
109
+ + return db.Update(func(txn *Txn) error {
110
+ + if err := txn.Set([]byte("k1"), journalBig("k1v1")); err != nil {
111
+ + return err
112
+ + }
113
+ + return txn.Set([]byte("k2"), journalSmall("k2v1"))
114
+ + })
115
+ + case 2:
116
+ + return db.Update(func(txn *Txn) error {
117
+ + if err := txn.Set([]byte("k3"), journalBig("k3v1")); err != nil {
118
+ + return err
119
+ + }
120
+ + if err := txn.Set([]byte("k4"), journalSmall("k4v1")); err != nil {
121
+ + return err
122
+ + }
123
+ + return txn.Set([]byte("k1"), journalBig("k1v2"))
124
+ + })
125
+ + case 3:
126
+ + return db.Update(func(txn *Txn) error { return txn.Delete([]byte("k2")) })
127
+ + case 4:
128
+ + return db.Update(func(txn *Txn) error { return txn.Set([]byte("k5"), journalSmall("k5v1")) })
129
+ + }
130
+ + case "mixed":
131
+ + switch n {
132
+ + case 1:
133
+ + wb := db.NewManagedWriteBatch()
134
+ + for i, ts := range []uint64{10, 11, 12} {
135
+ + k := []byte(fmt.Sprintf("m%d", i+1))
136
+ + if err := wb.SetEntryAt(NewEntry(k, journalSmall(string(k))), ts); err != nil {
137
+ + return err
138
+ + }
139
+ + }
140
+ + return wb.Flush()
141
+ + case 2:
142
+ + txn := db.NewTransactionAt(20, true)
143
+ + if err := txn.Set([]byte("m4"), journalBig("m4")); err != nil {
144
+ + return err
145
+ + }
146
+ + return txn.CommitAt(20, nil)
147
+ + case 3:
148
+ + wb := db.NewWriteBatchAt(30)
149
+ + if err := wb.SetEntryAt(NewEntry([]byte("m5"), journalSmall("m5")), 31); err != nil {
150
+ + return err
151
+ + }
152
+ + if err := wb.DeleteAt([]byte("m2"), 32); err != nil {
153
+ + return err
154
+ + }
155
+ + return wb.Flush()
156
+ + }
157
+ + case "gc":
158
+ + // x twice (each version flushed to a table, so that the tables carry
159
+ + // the discard statistics), then y and z until the value log rotates;
160
+ + // compaction, then garbage collection until nothing is left to move.
161
+ + // Every live value of the first file is copied to the last one and
162
+ + // re-logged in the WAL, and the first file is deleted.
163
+ + if n != 1 {
164
+ + break
165
+ + }
166
+ + put := func(prefix string, count int, tag string) error {
167
+ + for i := 0; i < count; i++ {
168
+ + k := fmt.Sprintf("%s-%03d", prefix, i)
169
+ + if err := db.Update(func(txn *Txn) error {
170
+ + return txn.Set([]byte(k), journalBlob(k+tag, journalGCSize))
171
+ + }); err != nil {
172
+ + return err
173
+ + }
174
+ + }
175
+ + return nil
176
+ + }
177
+ + flush := func() error {
178
+ + if err := db.Update(func(txn *Txn) error {
179
+ + return txn.Set([]byte("drop-me"), []byte("x"))
180
+ + }); err != nil {
181
+ + return err
182
+ + }
183
+ + return db.DropPrefix([]byte("drop-"))
184
+ + }
185
+ + if err := put("x", 40, "/1"); err != nil {
186
+ + return err
187
+ + }
188
+ + if err := flush(); err != nil {
189
+ + return err
190
+ + }
191
+ + if err := put("x", 40, "/2"); err != nil {
192
+ + return err
193
+ + }
194
+ + if err := flush(); err != nil {
195
+ + return err
196
+ + }
197
+ + if err := put("y", 20, ""); err != nil {
198
+ + return err
199
+ + }
200
+ + if err := put("z", 60, ""); err != nil {
201
+ + return err
202
+ + }
203
+ + if err := db.Flatten(1); err != nil {
204
+ + return err
205
+ + }
206
+ + for {
207
+ + err := db.RunValueLogGC(0.05)
208
+ + if err == ErrNoRewrite {
209
+ + break
210
+ + }
211
+ + if err != nil {
212
+ + return err
213
+ + }
214
+ + }
215
+ + db.vlog.filesLock.RLock()
216
+ + _, kept := db.vlog.filesMap[1]
217
+ + db.vlog.filesLock.RUnlock()
218
+ + if kept {
219
+ + return fmt.Errorf("garbage collection did not retire value log file 1")
220
+ + }
221
+ + return nil
222
+ + case "load":
223
+ + var wg sync.WaitGroup
224
+ + errs := make([]error, journalWriters)
225
+ + for g := 0; g < journalWriters; g++ {
226
+ + wg.Add(1)
227
+ + go func(g int) {
228
+ + defer wg.Done()
229
+ + errs[g] = db.Update(func(txn *Txn) error {
230
+ + big := fmt.Sprintf("g%d-b%d", g, n)
231
+ + small := fmt.Sprintf("g%d-s%d", g, n)
232
+ + if err := txn.Set([]byte(big), journalBig(big)); err != nil {
233
+ + return err
234
+ + }
235
+ + return txn.Set([]byte(small), journalSmall(small))
236
+ + })
237
+ + }(g)
238
+ + }
239
+ + wg.Wait()
240
+ + for _, err := range errs {
241
+ + if err != nil {
242
+ + return err
243
+ + }
244
+ + }
245
+ + return nil
246
+ + }
247
+ + return fmt.Errorf("no step %d in scenario %q", n, scenario)
248
+ +}
249
+ +
250
+ +// TestJournalChild is the child process. It only runs when spawned by the
251
+ +// tests below.
252
+ +func TestJournalChild(t *testing.T) {
253
+ + scenario := os.Getenv(journalChildEnv)
254
+ + if scenario == "" {
255
+ + t.Skip("child process of the journal recovery tests")
256
+ + }
257
+ + opt := journalOptions(os.Getenv(journalDirEnv))
258
+ + var db *DB
259
+ + var err error
260
+ + if scenario == "mixed" {
261
+ + db, err = OpenManaged(opt)
262
+ + } else {
263
+ + db, err = Open(opt)
264
+ + }
265
+ + if err != nil {
266
+ + fmt.Printf("error %v\n", err)
267
+ + os.Exit(2)
268
+ + }
269
+ + in := bufio.NewScanner(os.Stdin)
270
+ + for step := 1; in.Scan(); step++ {
271
+ + if err := journalStep(db, scenario, step); err != nil {
272
+ + fmt.Printf("error %v\n", err)
273
+ + os.Exit(2)
274
+ + }
275
+ + fmt.Printf("ok %d %d %d %d %d\n", step,
276
+ + db.vlog.maxFid, db.vlog.woffset(), db.mt.wal.fid, db.mt.wal.writeAt)
277
+ + }
278
+ + // The parent went away without killing us. Leave without closing, as a
279
+ + // crash would.
280
+ + os.Exit(0)
281
+ +}
282
+ +
283
+ +type journalMark struct {
284
+ + vlogFid, vlogOff, walFid, walOff uint32
285
+ +}
286
+ +
287
+ +type journalChild struct {
288
+ + t *testing.T
289
+ + cmd *exec.Cmd
290
+ + in io.WriteCloser
291
+ + out *bufio.Scanner
292
+ +}
293
+ +
294
+ +func startJournalChild(t *testing.T, scenario, dir string) *journalChild {
295
+ + t.Helper()
296
+ + cmd := exec.Command(os.Args[0], "-test.run=^TestJournalChild$")
297
+ + cmd.Env = append(os.Environ(), journalChildEnv+"="+scenario, journalDirEnv+"="+dir)
298
+ + cmd.Stderr = os.Stderr
299
+ + in, err := cmd.StdinPipe()
300
+ + require.NoError(t, err)
301
+ + out, err := cmd.StdoutPipe()
302
+ + require.NoError(t, err)
303
+ + require.NoError(t, cmd.Start())
304
+ + c := &journalChild{t: t, cmd: cmd, in: in, out: bufio.NewScanner(out)}
305
+ + t.Cleanup(func() { c.kill() })
306
+ + return c
307
+ +}
308
+ +
309
+ +// step asks the child for one more step and returns where its logs ended
310
+ +// once the step was acknowledged.
311
+ +func (c *journalChild) step() journalMark {
312
+ + c.t.Helper()
313
+ + _, err := io.WriteString(c.in, "next\n")
314
+ + require.NoError(c.t, err)
315
+ + require.True(c.t, c.out.Scan(), "child stopped answering")
316
+ + var m journalMark
317
+ + var n int
318
+ + _, err = fmt.Sscanf(c.out.Text(), "ok %d %d %d %d %d",
319
+ + &n, &m.vlogFid, &m.vlogOff, &m.walFid, &m.walOff)
320
+ + require.NoError(c.t, err, "child said %q", c.out.Text())
321
+ + return m
322
+ +}
323
+ +
324
+ +// kill stops the child the way a crash would.
325
+ +func (c *journalChild) kill() {
326
+ + if c.cmd.ProcessState != nil {
327
+ + return
328
+ + }
329
+ + _ = c.cmd.Process.Kill()
330
+ + _ = c.cmd.Wait()
331
+ +}
332
+ +
333
+ +// runJournalChild runs the scenario for the given number of steps in a fresh
334
+ +// directory, kills the child and returns the directory and the marks.
335
+ +func runJournalChild(t *testing.T, scenario string, steps int) (string, []journalMark) {
336
+ + t.Helper()
337
+ + dir, err := os.MkdirTemp("", "badger-journal")
338
+ + require.NoError(t, err)
339
+ + t.Cleanup(func() { removeDir(dir) })
340
+ + c := startJournalChild(t, scenario, dir)
341
+ + marks := make([]journalMark, 0, steps)
342
+ + for i := 0; i < steps; i++ {
343
+ + marks = append(marks, c.step())
344
+ + }
345
+ + c.kill()
346
+ + return dir, marks
347
+ +}
348
+ +
349
+ +func journalFileHashes(t *testing.T, dir string) map[string]string {
350
+ + t.Helper()
351
+ + entries, err := os.ReadDir(dir)
352
+ + require.NoError(t, err)
353
+ + hashes := make(map[string]string)
354
+ + for _, e := range entries {
355
+ + // Tables are outside the journal: a flush that was under way when the
356
+ + // process died leaves one the manifest does not know about, and that
357
+ + // one is removed on open, read-only or not, as it always was.
358
+ + if e.IsDir() || strings.HasSuffix(e.Name(), ".sst") {
359
+ + continue
360
+ + }
361
+ + data, err := os.ReadFile(filepath.Join(dir, e.Name()))
362
+ + require.NoError(t, err)
363
+ + sum := sha256.Sum256(data)
364
+ + hashes[e.Name()] = fmt.Sprintf("%d:%s", len(data), hex.EncodeToString(sum[:]))
365
+ + }
366
+ + return hashes
367
+ +}
368
+ +
369
+ +// zeroTail overwrites path from off to its end with zeros, as if the pages
370
+ +// after off had never reached the disk.
371
+ +func zeroTail(t *testing.T, path string, off uint32) {
372
+ + t.Helper()
373
+ + fi, err := os.Stat(path)
374
+ + require.NoError(t, err)
375
+ + f, err := os.OpenFile(path, os.O_WRONLY, 0)
376
+ + require.NoError(t, err)
377
+ + defer f.Close()
378
+ + _, err = f.WriteAt(make([]byte, fi.Size()-int64(off)), int64(off))
379
+ + require.NoError(t, err)
380
+ +}
381
+ +
382
+ +func openJournal(t *testing.T, dir string, readOnly, managed bool) (*DB, error) {
383
+ + t.Helper()
384
+ + opt := journalOptions(dir)
385
+ + opt.ReadOnly = readOnly
386
+ + if managed {
387
+ + return OpenManaged(opt)
388
+ + }
389
+ + return Open(opt)
390
+ +}
391
+ +
392
+ +// journalGet returns the value of key, or "" and false when it is absent.
393
+ +func journalGet(t *testing.T, db *DB, key string) (string, bool) {
394
+ + t.Helper()
395
+ + var txn *Txn
396
+ + if db.opt.managedTxns {
397
+ + txn = db.NewTransactionAt(math.MaxUint64, false)
398
+ + } else {
399
+ + txn = db.NewTransaction(false)
400
+ + }
401
+ + defer txn.Discard()
402
+ + item, err := txn.Get([]byte(key))
403
+ + if err == ErrKeyNotFound {
404
+ + return "", false
405
+ + }
406
+ + require.NoError(t, err)
407
+ + val, err := item.ValueCopy(nil)
408
+ + require.NoError(t, err)
409
+ + return string(val), true
410
+ +}
411
+ +
412
+ +func requireJournalValue(t *testing.T, db *DB, key string, want []byte) {
413
+ + t.Helper()
414
+ + got, ok := journalGet(t, db, key)
415
+ + require.True(t, ok, "key %s is missing", key)
416
+ + require.Equal(t, string(want), got, "key %s", key)
417
+ +}
418
+ +
419
+ +func requireJournalAbsent(t *testing.T, db *DB, key string) {
420
+ + t.Helper()
421
+ + got, ok := journalGet(t, db, key)
422
+ + require.False(t, ok, "key %s should be absent, has %q", key, got)
423
+ +}
424
+ +
425
+ +// requireReadOnlyRefuses opens the DB read-only, expects an error and
426
+ +// expects every file to be exactly as it was.
427
+ +func requireReadOnlyRefuses(t *testing.T, dir string, managed bool) {
428
+ + t.Helper()
429
+ + before := journalFileHashes(t, dir)
430
+ + db, err := openJournal(t, dir, true, managed)
431
+ + if err == nil {
432
+ + require.NoError(t, db.Close())
433
+ + }
434
+ + require.Error(t, err, "read-only open must refuse a torn history")
435
+ + require.Equal(t, before, journalFileHashes(t, dir), "read-only open changed a file")
436
+ +}
437
+ +
438
+ +func TestJournalTornValueLogTailKeepsTransactionsWhole(t *testing.T) {
439
+ + // A tear in the middle of the second transaction's values, emulating
440
+ + // pages that never reached the disk: the file keeps its length.
441
+ + t.Run("zeroed", func(t *testing.T) {
442
+ + dir, marks := runJournalChild(t, "vlog", 4)
443
+ + vlogPath := vlogFilePath(dir, marks[1].vlogFid)
444
+ + require.Equal(t, marks[0].vlogFid, marks[1].vlogFid)
445
+ + zeroTail(t, vlogPath, marks[0].vlogOff+(marks[1].vlogOff-marks[0].vlogOff)/2)
446
+ +
447
+ + requireReadOnlyRefuses(t, dir, false)
448
+ +
449
+ + db, err := openJournal(t, dir, false, false)
450
+ + require.NoError(t, err)
451
+ + // The first transaction is whole, the torn one is gone entirely —
452
+ + // including the part of it that lived in the WAL — and so is
453
+ + // everything committed after it.
454
+ + requireJournalValue(t, db, "k1", journalBig("k1v1"))
455
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
456
+ + requireJournalAbsent(t, db, "k3")
457
+ + requireJournalAbsent(t, db, "k4")
458
+ + requireJournalAbsent(t, db, "k5")
459
+ +
460
+ + // Writes after recovery win, and stay won.
461
+ + require.NoError(t, db.Update(func(txn *Txn) error {
462
+ + return txn.Set([]byte("k1"), journalBig("k1v3"))
463
+ + }))
464
+ + requireJournalValue(t, db, "k1", journalBig("k1v3"))
465
+ + require.NoError(t, db.Close())
466
+ + db, err = openJournal(t, dir, false, false)
467
+ + require.NoError(t, err)
468
+ + requireJournalValue(t, db, "k1", journalBig("k1v3"))
469
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
470
+ + requireJournalAbsent(t, db, "k3")
471
+ + require.NoError(t, db.Close())
472
+ + })
473
+ +
474
+ + // The file cut exactly where the first transaction's values end: that
475
+ + // transaction is whole, the next one is not.
476
+ + t.Run("truncated at a record boundary", func(t *testing.T) {
477
+ + dir, marks := runJournalChild(t, "vlog", 4)
478
+ + require.NoError(t, os.Truncate(vlogFilePath(dir, marks[0].vlogFid), int64(marks[0].vlogOff)))
479
+ +
480
+ + requireReadOnlyRefuses(t, dir, false)
481
+ +
482
+ + db, err := openJournal(t, dir, false, false)
483
+ + require.NoError(t, err)
484
+ + requireJournalValue(t, db, "k1", journalBig("k1v1"))
485
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
486
+ + requireJournalAbsent(t, db, "k3")
487
+ + requireJournalAbsent(t, db, "k4")
488
+ + requireJournalAbsent(t, db, "k5")
489
+ + require.NoError(t, db.Close())
490
+ + })
491
+ +
492
+ + // A tear in the WAL itself, with the value log whole.
493
+ + t.Run("torn wal", func(t *testing.T) {
494
+ + dir, marks := runJournalChild(t, "vlog", 4)
495
+ + require.Equal(t, marks[0].walFid, marks[1].walFid)
496
+ + zeroTail(t, filepath.Join(dir, fmt.Sprintf("%05d%s", marks[1].walFid, memFileExt)), marks[1].walOff-5)
497
+ +
498
+ + requireReadOnlyRefuses(t, dir, false)
499
+ +
500
+ + db, err := openJournal(t, dir, false, false)
501
+ + require.NoError(t, err)
502
+ + requireJournalValue(t, db, "k1", journalBig("k1v1"))
503
+ + requireJournalValue(t, db, "k2", journalSmall("k2v1"))
504
+ + requireJournalAbsent(t, db, "k3")
505
+ + requireJournalAbsent(t, db, "k4")
506
+ + requireJournalAbsent(t, db, "k5")
507
+ + require.NoError(t, db.Close())
508
+ + })
509
+ +}
510
+ +
511
+ +func TestJournalMixedVersionTransactionWholeAfterTear(t *testing.T) {
512
+ + checkWhole := func(t *testing.T, db *DB) {
513
+ + t.Helper()
514
+ + requireJournalValue(t, db, "m1", journalSmall("m1"))
515
+ + requireJournalAbsent(t, db, "m2") // deleted at 32
516
+ + requireJournalValue(t, db, "m3", journalSmall("m3"))
517
+ + requireJournalValue(t, db, "m4", journalBig("m4"))
518
+ + requireJournalValue(t, db, "m5", journalSmall("m5"))
519
+ + }
520
+ +
521
+ + t.Run("killed without a tear", func(t *testing.T) {
522
+ + dir, _ := runJournalChild(t, "mixed", 3)
523
+ + before := journalFileHashes(t, dir)
524
+ + db, err := openJournal(t, dir, true, true)
525
+ + require.NoError(t, err)
526
+ + checkWhole(t, db)
527
+ + require.NoError(t, db.Close())
528
+ + require.Equal(t, before, journalFileHashes(t, dir))
529
+ +
530
+ + db, err = openJournal(t, dir, false, true)
531
+ + require.NoError(t, err)
532
+ + checkWhole(t, db)
533
+ + require.NoError(t, db.Close())
534
+ + })
535
+ +
536
+ + t.Run("torn inside the mixed transaction", func(t *testing.T) {
537
+ + dir, marks := runJournalChild(t, "mixed", 3)
538
+ + zeroTail(t, filepath.Join(dir, fmt.Sprintf("%05d%s", marks[0].walFid, memFileExt)), marks[0].walOff-5)
539
+ +
540
+ + requireReadOnlyRefuses(t, dir, true)
541
+ +
542
+ + db, err := openJournal(t, dir, false, true)
543
+ + require.NoError(t, err)
544
+ + for _, k := range []string{"m1", "m2", "m3", "m4", "m5"} {
545
+ + requireJournalAbsent(t, db, k)
546
+ + }
547
+ + require.NoError(t, db.Close())
548
+ + })
549
+ +
550
+ + t.Run("torn after the mixed transaction", func(t *testing.T) {
551
+ + dir, marks := runJournalChild(t, "mixed", 3)
552
+ + zeroTail(t, filepath.Join(dir, fmt.Sprintf("%05d%s", marks[2].walFid, memFileExt)), marks[2].walOff-5)
553
+ +
554
+ + requireReadOnlyRefuses(t, dir, true)
555
+ +
556
+ + db, err := openJournal(t, dir, false, true)
557
+ + require.NoError(t, err)
558
+ + requireJournalValue(t, db, "m1", journalSmall("m1"))
559
+ + requireJournalValue(t, db, "m2", journalSmall("m2"))
560
+ + requireJournalValue(t, db, "m3", journalSmall("m3"))
561
+ + requireJournalValue(t, db, "m4", journalBig("m4"))
562
+ + requireJournalAbsent(t, db, "m5")
563
+ + require.NoError(t, db.Close())
564
+ + })
565
+ +}
566
+ +
567
+ +func TestJournalReadOnlyOpenAfterKillServesAcknowledgedCommits(t *testing.T) {
568
+ + const steps = 40
569
+ + dir, marks := runJournalChild(t, "load", steps)
570
+ + last := marks[len(marks)-1]
571
+ + require.Greater(t, last.vlogFid, uint32(1), "the value log should have rotated")
572
+ + require.Greater(t, last.walFid, uint32(1), "the memtable should have rotated")
573
+ +
574
+ + check := func(t *testing.T, db *DB) {
575
+ + t.Helper()
576
+ + for g := 0; g < journalWriters; g++ {
577
+ + for n := 1; n <= steps; n++ {
578
+ + big := fmt.Sprintf("g%d-b%d", g, n)
579
+ + small := fmt.Sprintf("g%d-s%d", g, n)
580
+ + requireJournalValue(t, db, big, journalBig(big))
581
+ + requireJournalValue(t, db, small, journalSmall(small))
582
+ + }
583
+ + }
584
+ + }
585
+ +
586
+ + before := journalFileHashes(t, dir)
587
+ + db, err := openJournal(t, dir, true, false)
588
+ + require.NoError(t, err)
589
+ + check(t, db)
590
+ + require.NoError(t, db.Close())
591
+ + require.Equal(t, before, journalFileHashes(t, dir), "read-only open changed a file")
592
+ +
593
+ + db, err = openJournal(t, dir, false, false)
594
+ + require.NoError(t, err)
595
+ + check(t, db)
596
+ + require.NoError(t, db.Update(func(txn *Txn) error {
597
+ + return txn.Set([]byte("after"), journalBig("after"))
598
+ + }))
599
+ + requireJournalValue(t, db, "after", journalBig("after"))
600
+ + require.NoError(t, db.Close())
601
+ +}
602
+ +
603
+ +// Garbage collection deletes a value log file once every live value in it
604
+ +// has been copied to the last file and re-logged in the WAL. A crash before
605
+ +// the next flush leaves the WAL still pointing at the deleted file for those
606
+ +// values' first records. That is not a tear: nothing acknowledged was lost,
607
+ +// and recovery, read-only or not, serves the whole history.
608
+ +func TestJournalRetiredValueLogFileIsNotATear(t *testing.T) {
609
+ + dir, marks := runJournalChild(t, "gc", 1)
610
+ + require.Greater(t, marks[0].vlogFid, uint32(1), "the value log should have rotated")
611
+ + require.NoFileExists(t, filepath.Join(dir, "000001.vlog"), "file 1 should have been retired")
612
+ +
613
+ + check := func(t *testing.T, db *DB) {
614
+ + t.Helper()
615
+ + for i := 0; i < 40; i++ {
616
+ + k := fmt.Sprintf("x-%03d", i)
617
+ + requireJournalValue(t, db, k, journalBlob(k+"/2", journalGCSize))
618
+ + }
619
+ + for i := 0; i < 20; i++ {
620
+ + k := fmt.Sprintf("y-%03d", i)
621
+ + requireJournalValue(t, db, k, journalBlob(k, journalGCSize))
622
+ + }
623
+ + for i := 0; i < 60; i++ {
624
+ + k := fmt.Sprintf("z-%03d", i)
625
+ + requireJournalValue(t, db, k, journalBlob(k, journalGCSize))
626
+ + }
627
+ + }
628
+ +
629
+ + before := journalFileHashes(t, dir)
630
+ + db, err := openJournal(t, dir, true, false)
631
+ + require.NoError(t, err)
632
+ + check(t, db)
633
+ + require.NoError(t, db.Close())
634
+ + require.Equal(t, before, journalFileHashes(t, dir), "read-only open changed a file")
635
+ +
636
+ + db, err = openJournal(t, dir, false, false)
637
+ + require.NoError(t, err)
638
+ + check(t, db)
639
+ + require.NoError(t, db.Close())
640
+ +}
641
+ +
642
+ +// A WAL written by an earlier build holds transactions with entries of
643
+ +// different versions and no markers around them. They still come back whole.
644
+ +func TestJournalOldTransactionWithoutMarkersReplaysWhole(t *testing.T) {
645
+ + dir, err := os.MkdirTemp("", "badger-journal")
646
+ + require.NoError(t, err)
647
+ + defer removeDir(dir)
648
+ +
649
+ + opt := journalOptions(dir)
650
+ + db0, err := OpenManaged(opt)
651
+ + require.NoError(t, err)
652
+ + defer func() { require.NoError(t, db0.Close()) }()
653
+ + for i, ts := range []uint64{10, 11, 12} {
654
+ + k := fmt.Sprintf("o%d", i+1)
655
+ + require.NoError(t, db0.mt.Put(y.KeyWithTs([]byte(k), ts), y.ValueStruct{Value: journalSmall(k)}))
656
+ + }
657
+ + require.NoError(t, db0.mt.SyncWAL())
658
+ + // Simulate a crash by not closing db0, but releasing the locks.
659
+ + require.NoError(t, db0.dirLockGuard.release())
660
+ + db0.dirLockGuard = nil
661
+ + if db0.valueDirGuard != nil {
662
+ + require.NoError(t, db0.valueDirGuard.release())
663
+ + db0.valueDirGuard = nil
664
+ + }
665
+ +
666
+ + db1, err := openJournal(t, dir, true, true)
667
+ + require.NoError(t, err)
668
+ + for i := 1; i <= 3; i++ {
669
+ + k := fmt.Sprintf("o%d", i)
670
+ + requireJournalValue(t, db1, k, journalSmall(k))
671
+ + }
672
+ + require.NoError(t, db1.Close())
673
+ +}
674
+ diff --git a/memtable.go b/memtable.go
675
+ index 161a463..f107477 100644
676
+ --- a/memtable.go
677
+ +++ b/memtable.go
678
+ @@ -38,6 +38,9 @@ type memTable struct {
679
+ maxVersion uint64
680
+ opt Options
681
+ buf *bytes.Buffer
682
+ + // vptrOK tells replay whether a value pointer found in the WAL still
683
+ + // addresses a record the value log holds.
684
+ + vptrOK func(valuePointer) bool
685
+ }
686
+
687
+ func (db *DB) openMemTables(opt Options) error {
688
+ @@ -98,9 +101,10 @@ func (db *DB) openMemTable(fid, flags int) (*memTable, error) {
689
+ filepath := db.mtFilePath(fid)
690
+ s := skl.NewSkiplist(arenaSize(db.opt))
691
+ mt := &memTable{
692
+ - sl: s,
693
+ - opt: db.opt,
694
+ - buf: &bytes.Buffer{},
695
+ + sl: s,
696
+ + opt: db.opt,
697
+ + buf: &bytes.Buffer{},
698
+ + vptrOK: db.vlog.contains,
699
+ }
700
+ // We don't need to create the wal for the skiplist in in-memory mode so return the mt.
701
+ if db.opt.InMemory {
702
+ @@ -202,12 +206,19 @@ func (mt *memTable) UpdateSkipList() error {
703
+ if mt.wal == nil || mt.sl == nil {
704
+ return nil
705
+ }
706
+ - endOff, err := mt.wal.iterate(true, 0, mt.replayFunction(mt.opt))
707
+ + endOff, stopAt, err := mt.wal.replay(0, mt.replayFunction(mt.opt), mt.vptrOK)
708
+ if err != nil {
709
+ return y.Wrapf(err, "while iterating wal: %s", mt.wal.Fd.Name())
710
+ }
711
+ - if endOff < mt.wal.size.Load() && mt.opt.ReadOnly {
712
+ - return y.Wrapf(ErrTruncateNeeded, "end offset: %d < size: %d", endOff, mt.wal.size.Load())
713
+ + if mt.opt.ReadOnly {
714
+ + // The file is pre-allocated, so a tail of zeros after the last record
715
+ + // is the normal state after an unclean stop and needs no repair. Any
716
+ + // other bytes there are a damaged record, and a read-only DB must
717
+ + // not repair it.
718
+ + if !mt.wal.zeroFrom(stopAt) {
719
+ + return y.Wrapf(ErrTruncateNeeded, "end offset: %d < size: %d", endOff, mt.wal.size.Load())
720
+ + }
721
+ + return nil
722
+ }
723
+ return mt.wal.Truncate(int64(endOff))
724
+ }
725
+ @@ -431,6 +442,41 @@ func (lf *logFile) doneWriting(offset uint32) error {
726
+ // iterate iterates over log file. It doesn't not allocate new memory for every kv pair.
727
+ // Therefore, the kv pair is only valid for the duration of fn call.
728
+ func (lf *logFile) iterate(readOnly bool, offset uint32, fn logEntry) (uint32, error) {
729
+ + end, _, err := lf.replay(offset, fn, nil)
730
+ + return end, err
731
+ +}
732
+ +
733
+ +// lostValue reports whether e's value lives in the value log at a place the
734
+ +// value log no longer holds, according to vptrOK.
735
+ +func lostValue(e *Entry, vptrOK func(valuePointer) bool) bool {
736
+ + if vptrOK == nil || e.meta&bitValuePointer == 0 {
737
+ + return false
738
+ + }
739
+ + if uintptr(len(e.Value)) < vptrSize {
740
+ + return true
741
+ + }
742
+ + var vp valuePointer
743
+ + vp.Decode(e.Value)
744
+ + return !vptrOK(vp)
745
+ +}
746
+ +
747
+ +// zeroFrom reports whether nothing but zeros follows off in the file.
748
+ +func (lf *logFile) zeroFrom(off uint32) bool {
749
+ + if int64(off) >= int64(len(lf.Data)) {
750
+ + return true
751
+ + }
752
+ + return len(bytes.TrimLeft(lf.Data[off:], "\x00")) == 0
753
+ +}
754
+ +
755
+ +// replay is iterate with two additions. When vptrOK is given, an entry whose
756
+ +// value lives in the value log is checked against it before anything of its
757
+ +// transaction is applied, so a pointer to a lost value stops the replay in
758
+ +// front of that transaction. Besides the offset up to which the log was
759
+ +// applied, replay returns the offset of the record it stopped at: the one it
760
+ +// could not read, or the one it could not accept — a transaction with a
761
+ +// missing or mismatching end marker, an entry pointing at a lost value.
762
+ +func (lf *logFile) replay(offset uint32, fn logEntry, vptrOK func(valuePointer) bool) (
763
+ + uint32, uint32, error) {
764
+ if offset == 0 {
765
+ // If offset is set to zero, let's advance past the encryption key header.
766
+ offset = vlogHeaderSize
767
+ @@ -445,14 +491,19 @@ func (lf *logFile) iterate(readOnly bool, offset uint32, fn logEntry) (uint32, e
768
+ lf: lf,
769
+ }
770
+
771
+ - var lastCommit uint64
772
+ + // lastCommit is the version of the entry that opened the transaction
773
+ + // being read, or zero outside a transaction; txnMax is the largest
774
+ + // version seen in it, which its end marker must repeat.
775
+ + var lastCommit, txnMax uint64
776
+ var validEndOffset uint32 = offset
777
+
778
+ var entries []*Entry
779
+ var vptrs []valuePointer
780
+
781
+ + var stopAt uint32
782
+ loop:
783
+ for {
784
+ + stopAt = read.recordOffset
785
+ e, err := read.Entry(reader)
786
+ switch {
787
+ // We have not reached the end of the file but the entry we read is
788
+ @@ -463,7 +514,7 @@ loop:
789
+ case err == io.ErrUnexpectedEOF || err == errTruncate:
790
+ break loop
791
+ case err != nil:
792
+ - return 0, err
793
+ + return 0, 0, err
794
+ case e == nil:
795
+ continue
796
+ case e.isZero():
797
+ @@ -483,19 +534,24 @@ loop:
798
+ if lastCommit == 0 {
799
+ lastCommit = txnTs
800
+ }
801
+ - if lastCommit != txnTs {
802
+ - break loop
803
+ + if txnTs > txnMax {
804
+ + txnMax = txnTs
805
+ }
806
+ entries = append(entries, e)
807
+ vptrs = append(vptrs, vp)
808
+
809
+ case e.meta&bitFinTxn > 0:
810
+ txnTs, err := strconv.ParseUint(string(e.Value), 10, 64)
811
+ - if err != nil || lastCommit != txnTs {
812
+ + if err != nil || lastCommit == 0 || txnTs != txnMax {
813
+ break loop
814
+ }
815
+ + for _, e := range entries {
816
+ + if lostValue(e, vptrOK) {
817
+ + break loop
818
+ + }
819
+ + }
820
+ // Got the end of txn. Now we can store them.
821
+ - lastCommit = 0
822
+ + lastCommit, txnMax = 0, 0
823
+ validEndOffset = read.recordOffset
824
+
825
+ for i, e := range entries {
826
+ @@ -504,7 +560,7 @@ loop:
827
+ if err == errStop {
828
+ break
829
+ }
830
+ - return 0, errFile(err, lf.path, "Iteration function")
831
+ + return 0, 0, errFile(err, lf.path, "Iteration function")
832
+ }
833
+ }
834
+ entries = entries[:0]
835
+ @@ -516,17 +572,20 @@ loop:
836
+ // We shouldn't get this entry in the middle of a transaction.
837
+ break loop
838
+ }
839
+ + if lostValue(e, vptrOK) {
840
+ + break loop
841
+ + }
842
+ validEndOffset = read.recordOffset
843
+
844
+ if err := fn(*e, vp); err != nil {
845
+ if err == errStop {
846
+ break
847
+ }
848
+ - return 0, errFile(err, lf.path, "Iteration function")
849
+ + return 0, 0, errFile(err, lf.path, "Iteration function")
850
+ }
851
+ }
852
+ }
853
+ - return validEndOffset, nil
854
+ + return validEndOffset, stopAt, nil
855
+ }
856
+
857
+ // Zero out the next entry to deal with any crashes.
858
+ diff --git a/txn.go b/txn.go
859
+ index 9c916d1..5e852af 100644
860
+ --- a/txn.go
861
+ +++ b/txn.go
862
+ @@ -532,12 +532,17 @@ func (txn *Txn) commitAndSend() (func() error, error) {
863
+ return nil, ErrConflict
864
+ }
865
+
866
+ - keepTogether := true
867
+ + // Every transaction is bracketed by markers in the log so that replay can
868
+ + // apply it whole or not at all. Entries may carry their own versions
869
+ + // (SetEntryAt in managed mode), and commitTs may then even be zero, so the
870
+ + // end marker carries the largest version in the transaction.
871
+ + var maxVersion uint64
872
+ setVersion := func(e *Entry) {
873
+ if e.version == 0 {
874
+ e.version = commitTs
875
+ - } else {
876
+ - keepTogether = false
877
+ + }
878
+ + if e.version > maxVersion {
879
+ + maxVersion = e.version
880
+ }
881
+ }
882
+ for _, e := range txn.pendingWrites {
883
+ @@ -555,14 +560,7 @@ func (txn *Txn) commitAndSend() (func() error, error) {
884
+ // Suffix the keys with commit ts, so the key versions are sorted in
885
+ // descending order of commit timestamp.
886
+ e.Key = y.KeyWithTs(e.Key, e.version)
887
+ - // Add bitTxn only if these entries are part of a transaction. We
888
+ - // support SetEntryAt(..) in managed mode which means a single
889
+ - // transaction can have entries with different timestamps. If entries
890
+ - // in a single transaction have different timestamps, we don't add the
891
+ - // transaction markers.
892
+ - if keepTogether {
893
+ - e.meta |= bitTxn
894
+ - }
895
+ + e.meta |= bitTxn
896
+ entries = append(entries, e)
897
+ }
898
+
899
+ @@ -579,16 +577,14 @@ func (txn *Txn) commitAndSend() (func() error, error) {
900
+ processEntry(e)
901
+ }
902
+
903
+ - if keepTogether {
904
+ - // CommitTs should not be zero if we're inserting transaction markers.
905
+ - y.AssertTrue(commitTs != 0)
906
+ - e := &Entry{
907
+ - Key: y.KeyWithTs(txnKey, commitTs),
908
+ - Value: []byte(strconv.FormatUint(commitTs, 10)),
909
+ - meta: bitFinTxn,
910
+ - }
911
+ - entries = append(entries, e)
912
+ - }
913
+ + // commitPrecheck guarantees a non-zero commitTs whenever no entry has a
914
+ + // version of its own.
915
+ + y.AssertTrue(maxVersion != 0)
916
+ + entries = append(entries, &Entry{
917
+ + Key: y.KeyWithTs(txnKey, maxVersion),
918
+ + Value: []byte(strconv.FormatUint(maxVersion, 10)),
919
+ + meta: bitFinTxn,
920
+ + })
921
+
922
+ req, err := txn.db.sendToWriteCh(entries)
923
+ if err != nil {
924
+ diff --git a/value.go b/value.go
925
+ index e042651..c343473 100644
926
+ --- a/value.go
927
+ +++ b/value.go
928
+ @@ -580,26 +580,24 @@ func (vlog *valueLog) init(db *DB) {
929
+ db.logToSyncChan(endVLogInitMsg)
930
+ }
931
+
932
+ -func (vlog *valueLog) open(db *DB) error {
933
+ - // We don't need to open any vlog files or collect stats for GC if DB is opened
934
+ - // in InMemory mode. InMemory mode doesn't create any files/directories on disk.
935
+ - if db.opt.InMemory {
936
+ +// openFiles opens the value log files found on disk and establishes how much
937
+ +// of each one holds records. Files that were rotated out were cut down to
938
+ +// their records when they were retired; the last file is pre-allocated and
939
+ +// may end in whatever an unclean stop left behind, so its size is what can be
940
+ +// parsed from it. Nothing is written: this runs before the memtables are
941
+ +// replayed, in read-only mode too, so that replay can tell a pointer into a
942
+ +// lost value from a good one.
943
+ +func (vlog *valueLog) openFiles() error {
944
+ + if vlog.opt.InMemory {
945
+ return nil
946
+ }
947
+ -
948
+ if err := vlog.populateFilesMap(); err != nil {
949
+ return err
950
+ }
951
+ - // If no files are found, then create a new file.
952
+ if len(vlog.filesMap) == 0 {
953
+ - if vlog.opt.ReadOnly {
954
+ - return nil
955
+ - }
956
+ - _, err := vlog.createVlogFile()
957
+ - return y.Wrapf(err, "Error while creating log file in valueLog.open")
958
+ + return nil
959
+ }
960
+ - fids := vlog.sortedFids()
961
+ - for _, fid := range fids {
962
+ + for _, fid := range vlog.sortedFids() {
963
+ lf, ok := vlog.filesMap[fid]
964
+ y.AssertTrue(ok)
965
+
966
+ @@ -612,20 +610,8 @@ func (vlog *valueLog) open(db *DB) error {
967
+ 2*vlog.opt.ValueLogFileSize); err != nil {
968
+ return y.Wrapf(err, "Open existing file: %q", lf.path)
969
+ }
970
+ - // We shouldn't delete the maxFid file.
971
+ - if lf.size.Load() == vlogHeaderSize && fid != vlog.maxFid && !vlog.opt.ReadOnly {
972
+ - vlog.opt.Infof("Deleting empty file: %s", lf.path)
973
+ - if err := lf.Delete(); err != nil {
974
+ - return y.Wrapf(err, "while trying to delete empty file: %s", lf.path)
975
+ - }
976
+ - delete(vlog.filesMap, fid)
977
+ - }
978
+ }
979
+ -
980
+ - if vlog.opt.ReadOnly {
981
+ - return nil
982
+ - }
983
+ - // Now we can read the latest value log file, and see if it needs truncation. We could
984
+ + // Read the latest value log file to see where its records end. We could
985
+ // technically do this over all the value log files, but that would mean slowing down the value
986
+ // log open.
987
+ last, ok := vlog.filesMap[vlog.maxFid]
988
+ @@ -637,7 +623,51 @@ func (vlog *valueLog) open(db *DB) error {
989
+ if err != nil {
990
+ return y.Wrapf(err, "while iterating over: %s", last.path)
991
+ }
992
+ - if err := last.Truncate(int64(lastOff)); err != nil {
993
+ + last.size.Store(lastOff)
994
+ + return nil
995
+ +}
996
+ +
997
+ +// contains reports whether vp addresses a record the value log holds, as
998
+ +// established by openFiles. For use while no writes are in flight.
999
+ +func (vlog *valueLog) contains(vp valuePointer) bool {
1000
+ + lf, ok := vlog.filesMap[vp.Fid]
1001
+ + if !ok {
1002
+ + // A file that is gone was retired by garbage collection, which had
1003
+ + // moved every live value out of it first; an unclean stop never
1004
+ + // removes a file. The entry is stale, not torn.
1005
+ + return true
1006
+ + }
1007
+ + return uint64(vp.Offset)+uint64(vp.Len) <= uint64(lf.size.Load())
1008
+ +}
1009
+ +
1010
+ +// open makes the value log writable after openFiles: empty retired files are
1011
+ +// deleted, the last file is cut down to its records, and a fresh file is
1012
+ +// created to write into. A read-only DB leaves the files as they are.
1013
+ +func (vlog *valueLog) open(db *DB) error {
1014
+ + // We don't need to open any vlog files or collect stats for GC if DB is opened
1015
+ + // in InMemory mode. InMemory mode doesn't create any files/directories on disk.
1016
+ + if db.opt.InMemory || vlog.opt.ReadOnly {
1017
+ + return nil
1018
+ + }
1019
+ + // If no files are found, then create a new file.
1020
+ + if len(vlog.filesMap) == 0 {
1021
+ + _, err := vlog.createVlogFile()
1022
+ + return y.Wrapf(err, "Error while creating log file in valueLog.open")
1023
+ + }
1024
+ + for _, fid := range vlog.sortedFids() {
1025
+ + lf := vlog.filesMap[fid]
1026
+ + // We shouldn't delete the maxFid file.
1027
+ + if lf.size.Load() == vlogHeaderSize && fid != vlog.maxFid {
1028
+ + vlog.opt.Infof("Deleting empty file: %s", lf.path)
1029
+ + if err := lf.Delete(); err != nil {
1030
+ + return y.Wrapf(err, "while trying to delete empty file: %s", lf.path)
1031
+ + }
1032
+ + delete(vlog.filesMap, fid)
1033
+ + }
1034
+ + }
1035
+ + last, ok := vlog.filesMap[vlog.maxFid]
1036
+ + y.AssertTrue(ok)
1037
+ + if err := last.Truncate(int64(last.size.Load())); err != nil {
1038
+ return y.Wrapf(err, "while truncating last value log file: %s", last.path)
1039
+ }
1040
+
1041
+
1042
+ REFERENCE_PATCH
harbor/tasks/journal_recovery_after_unclean_stop/task.toml ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+ artifacts = ["/workspace/submissions/submitted.patch"]
3
+ [metadata]
4
+ task = "journal_recovery_after_unclean_stop"
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/journal_recovery_after_unclean_stop/tests/Dockerfile ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ FROM ec-swe-badger:source-v2
2
+ USER root
3
+ RUN grep -q '^[^:]*:[^:]*:1000:' /etc/passwd || echo 'grader:x:1000:1000::/tmp/agent-home:/bin/sh' >> /etc/passwd; grep -q '^[^:]*:[^:]*:1000:' /etc/group || echo 'grader:x:1000:' >> /etc/group
4
+ ENV HUD_TELEMETRY_ENABLED=false HUD_CLI_ANALYTICS_ENABLED=0 HUD_FILE_TRACKING_ENABLED=false
5
+ RUN rm -f /hud/gold.diff
6
+ COPY verify.py evidence.py config.json test.sh /tests/
7
+ RUN chmod 755 /tests/test.sh
8
+ WORKDIR /app
9
+ CMD ["sleep", "infinity"]
harbor/tasks/journal_recovery_after_unclean_stop/tests/config.json ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "revision": "coding-rubric-v2",
3
+ "task_id": "journal_recovery_after_unclean_stop",
4
+ "arguments": {},
5
+ "grader_version": "0.6.15",
6
+ "source_image": "ec-swe-badger:source-v2",
7
+ "source_image_id": "sha256:07828139bd6f6ce1204b51a18fc72537c75e861e64d27e3aac0e12d9e1cc451a",
8
+ "provenance": {
9
+ "repository": "dgraph-io/badger",
10
+ "environment_id": "5c04bdfd-7abc-40a6-8c86-cfe9e13930b5",
11
+ "build": 2,
12
+ "build_id": "f683e58c-4463-4e44-bfc1-c87834bfe006",
13
+ "hosted_task": "journal_recovery_after_unclean_stop",
14
+ "task_version": 1,
15
+ "source_archive_sha256": "3745442faf694143dd96944f41986e939cdfa02edac2676bbe5533dd0b0c5a34",
16
+ "hosted_revision_argument": "not recorded; the scenario does not read it"
17
+ },
18
+ "criteria": [
19
+ [
20
+ "torn_value_log_tail_keeps_transactions_whole",
21
+ 0.25,
22
+ true,
23
+ "bash",
24
+ 600
25
+ ],
26
+ [
27
+ "mixed_version_transaction_whole_after_tear",
28
+ 0.19,
29
+ true,
30
+ "bash",
31
+ 600
32
+ ],
33
+ [
34
+ "history_comes_back_as_a_prefix",
35
+ 0.16,
36
+ false,
37
+ "bash",
38
+ 600
39
+ ],
40
+ [
41
+ "writes_after_recovery_win",
42
+ 0.12,
43
+ false,
44
+ "bash",
45
+ 600
46
+ ],
47
+ [
48
+ "read_only_open_after_kill_serves_acknowledged_commits",
49
+ 0.1,
50
+ false,
51
+ "bash",
52
+ 600
53
+ ],
54
+ [
55
+ "read_only_open_refuses_a_torn_history",
56
+ 0.06,
57
+ false,
58
+ "bash",
59
+ 600
60
+ ],
61
+ [
62
+ "history_from_released_build_replays_whole",
63
+ 0.06,
64
+ false,
65
+ "bash",
66
+ 600
67
+ ],
68
+ [
69
+ "build_vet_and_targeted_tests_green",
70
+ 0.06,
71
+ false,
72
+ "bash",
73
+ 900
74
+ ]
75
+ ],
76
+ "gates": [],
77
+ "reward_rule": "weighted_cap",
78
+ "local_hostname": false,
79
+ "fault_exit": 3,
80
+ "grader_readable": [],
81
+ "grader_writable": [],
82
+ "blocker_cap": 0.6,
83
+ "empty_sha256": "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
84
+ "verifier_files": {
85
+ "/app/env.py": "87a7c5c754cb9669455e2fac0406278b4bf4679b8deeeebae8fa96e0e047ec2d",
86
+ "/app/tasks.py": "bbf54c844b7da9fd1349ce772688c1122e00b4423873eea5feef6f3843983690",
87
+ "/app/coding/github.py": "dfb450735dd44af94d51088ccd37df0470a4bf7c1339f5277aea2419bd64c694",
88
+ "/app/coding/repo.py": "b1366540d1ea28ccb7cc578a311662ef4a2b9e7e5a4c27543dcbd594cc6d86da",
89
+ "/app/coding/swe_bench_pro.py": "9b1131236eb514c62ba3a3bfb7aba61bad29df18a0293afc1bcb8a277c4ff929",
90
+ "/app/coding/__init__.py": "9ba11441d392f54835f33527d4a098f48528824a8f8c3c255cf4c140f89523bf",
91
+ "/app/task/prompt.md": "e235e9cfb731a8d638fe30c29652eb17c5e2241a76c3b1a674fca88f0f792110",
92
+ "/hud/grader/run_grading.sh": "5f527d179db7944b29d59613561bd3dcfacff3b488b8028a4f3896263c3e51f9",
93
+ "/hud/grader/driver/build_driver.sh": "441f9f33f5c46dfe5e37c50f80bd38c085d534fc23997fe1ce4fb31e02ff32d2",
94
+ "/hud/grader/driver/child.go": "5364e132b51e3f777326f9eca47f5774f1cb19e9906dc9e8019cc1b6b7a8faa6",
95
+ "/hud/grader/driver/fixtures.go": "dd98bbe8d6677a2d5444b0f40fee8d9ce18ea66e0d5a56c6e1b1a252047d6148",
96
+ "/hud/grader/driver/go.mod.tmpl": "37a9e476e0340c8761ee1acec40b52ecb51e83add3e4af67c1882af3cda3bd32",
97
+ "/hud/grader/driver/go.sum": "1b55494a77d5610e01a7f7bd4973e66b0f913d8c275195d80fa438e520399cf7",
98
+ "/hud/grader/driver/main.go": "86325fba79d5f649ae2230436729c867e45bd61c46146a07d7fac11e1b27bf18",
99
+ "/hud/grader/driver/observe.go": "d6c392bb9326c51af06ddd0775a1989e62a6b9ffb9927e08c5f024f800ab13a0",
100
+ "/hud/grader/driver/program.go": "66b27109098e62f14f4ebe7fe5ab9c391445a6b79b85ec247024ebb4963dd4ac",
101
+ "/hud/grader/driver/surgery.go": "591ebfbfab53d861121e07ab860dd0d9abf0bd069fd0f36ef72e008d3a1b9756",
102
+ "/hud/grader/driver/verify.go": "5253733c38e8d6d4662e7e4ed0391e0f77f1092947bd4226d5d81f4a08125ce5",
103
+ "/hud/grader/fixtures/killed_and_whole.tar.gz": "1493ffe05f758ea41e59b8a42b8e5e307e2534ff84d26c4fd7fa018dfd91d252",
104
+ "/hud/grader/fixtures/torn_log_with_older_ones_behind_it.tar.gz": "084f0ca0babf200047b55f2702addac5c0203bf063cde3c9f3a76cc1664e6e7c",
105
+ "/hud/grader/fixtures/torn_value_log.tar.gz": "8da672d8a0f83f69f83936eb94ce36578b81fd325c260b20d2a2745785a1f6be",
106
+ "/hud/grader/tests/check_journal.py": "8945d49e75a4f2f94f14f1cfb704274a88fe3a457f57e3c3dddc8fc99346cab1",
107
+ "/hud/grader/tests/new_vet_diagnostics.py": "219421ebc76649bf399c54128f2bfb53b5d7b7868c6e342d144fc570ed20e5cc"
108
+ },
109
+ "preflight": [
110
+ [
111
+ "/bin/bash",
112
+ "--version"
113
+ ],
114
+ [
115
+ "setpriv",
116
+ "--version"
117
+ ],
118
+ [
119
+ "git",
120
+ "--version"
121
+ ],
122
+ [
123
+ "bash",
124
+ "-c",
125
+ "bash -lc 'go version' || go version"
126
+ ],
127
+ [
128
+ "/usr/local/bin/python3",
129
+ "--version"
130
+ ]
131
+ ]
132
+ }
harbor/tasks/journal_recovery_after_unclean_stop/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/journal_recovery_after_unclean_stop/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/journal_recovery_after_unclean_stop/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/journal_recovery_after_unclean_stop/tests/verify.py ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the original trusted coding rubric in a fresh, offline verifier container."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import hashlib
7
+ import importlib
8
+ import importlib.metadata
9
+ import json
10
+ import os
11
+ import shlex
12
+ import shutil
13
+ import signal
14
+ import subprocess
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any
18
+
19
+ from evidence import REVISION, validate_report
20
+
21
+ OUT = Path("/logs/verifier")
22
+ PRIVATE = Path("/var/lib/task-evidence")
23
+ CONFIG = Path("/tests/config.json")
24
+ PATCH = Path("/workspace/submissions/submitted.patch")
25
+ GRADER_HOME = "/tmp/agent-home"
26
+
27
+
28
+ def _run(command: list[str], **kwargs: Any) -> subprocess.CompletedProcess[str]:
29
+ return subprocess.run(command, text=True, capture_output=True, timeout=300, **kwargs)
30
+
31
+
32
+ def _preflight(config: dict[str, Any]) -> None:
33
+ if importlib.metadata.version("hud") != config["grader_version"]:
34
+ raise RuntimeError("Grader library version does not match the task")
35
+ for filename, expected in config["verifier_files"].items():
36
+ if hashlib.sha256(Path(filename).read_bytes()).hexdigest() != expected:
37
+ raise RuntimeError(f"Verifier source changed: {filename}")
38
+ for command in config["preflight"]:
39
+ completed = _run(command, cwd="/workspace/repo")
40
+ if completed.returncode:
41
+ raise RuntimeError(f"Prerequisite failed: {command}: {completed.stderr[-2000:]}")
42
+
43
+
44
+ def _readable_mode(path: Path) -> int:
45
+ # World-readable, keeping what is executable so: a grader may ship tools.
46
+ return 0o755 if path.is_dir() or path.stat().st_mode & 0o111 else 0o644
47
+
48
+
49
+ def _permissions() -> None:
50
+ # The orchestrator owns reports and rubric definitions. Grader commands,
51
+ # and so the candidate's code, run as uid 1000: the user the task installed
52
+ # its toolchain and caches for. They cannot read gold/vault or overwrite
53
+ # the rubric or the result files, which stay root's.
54
+ Path("/hud").chmod(0o711)
55
+ for root in (Path("/hud/grader"), Path("/hud/base"), Path("/hud/base-src")):
56
+ if root.exists():
57
+ root.chmod(0o755)
58
+ for path in root.rglob("*"):
59
+ if not path.is_symlink():
60
+ path.chmod(_readable_mode(path))
61
+ home = Path(GRADER_HOME)
62
+ home.mkdir(parents=True, exist_ok=True)
63
+ os.chown(home, 1000, 1000)
64
+ for directory in ("/hud/logs", "/hud/gocache", "/hud/grader/runner"):
65
+ path = Path(directory)
66
+ path.mkdir(parents=True, exist_ok=True)
67
+ for item in (path, *path.rglob("*")):
68
+ if not item.is_symlink():
69
+ os.chown(item, 1000, 1000)
70
+ item.chmod(_readable_mode(item))
71
+
72
+
73
+ def _hand_over_checkout() -> None:
74
+ # The original grader runs as root and may run the candidate's own suite in
75
+ # place, which writes into the tree. The rubric resets and re-applies the
76
+ # candidate as root, so give what root touched back to the grading user.
77
+ # Installed dependency trees are large and already that user's.
78
+ subprocess.run(
79
+ [
80
+ "find",
81
+ "/workspace/repo",
82
+ "-path",
83
+ "*/node_modules",
84
+ "-prune",
85
+ "-o",
86
+ "!",
87
+ "-user",
88
+ "1000",
89
+ "-exec",
90
+ "chown",
91
+ "-h",
92
+ "1000:1000",
93
+ "{}",
94
+ "+",
95
+ ],
96
+ check=True,
97
+ capture_output=True,
98
+ timeout=3600,
99
+ )
100
+
101
+
102
+ async def _grade(config: dict[str, Any], record: dict[str, Any]) -> None:
103
+ _preflight(config)
104
+ sys.path.insert(0, "/app")
105
+ task: Any = importlib.import_module("tasks")
106
+ await task._setup()
107
+ _permissions()
108
+ patch = PATCH.read_bytes()
109
+ if patch:
110
+ checked = _run(["git", "apply", "--check", str(PATCH)], cwd="/workspace/repo")
111
+ if checked.returncode:
112
+ record.update(
113
+ status="rejected_patch",
114
+ patch_error=checked.stderr[-4000:],
115
+ result={"reward": 0.0, "subscores": None},
116
+ )
117
+ return
118
+ _run(["git", "apply", str(PATCH)], cwd="/workspace/repo", check=True)
119
+ original = task.BashGrader
120
+ fault_exit = config.get("fault_exit")
121
+ faulted: list[tuple[tuple[Any, ...], dict[str, Any], str]] = []
122
+
123
+ class ObservedGrader:
124
+ @classmethod
125
+ async def grade(cls, *args: Any, **kwargs: Any) -> Any:
126
+ command = kwargs["command"]
127
+ _hand_over_checkout()
128
+ kwargs["command"] = (
129
+ "setpriv --reuid 1000 --regid 1000 --clear-groups --no-new-privs "
130
+ f"env HOME={GRADER_HOME} bash -lc " + shlex.quote(command)
131
+ )
132
+ score = await original.grade(*args, **kwargs)
133
+ snapshot = score.model_dump(mode="json")
134
+ record["commands"].append(snapshot)
135
+ (PRIVATE / "commands.json").write_text(json.dumps(record["commands"], indent=2))
136
+ info = snapshot.get("info") or {}
137
+ if info.get("timed_out") or type(info.get("exit_code")) is not int:
138
+ raise RuntimeError(f"Grader infrastructure failure: {snapshot['name']}")
139
+ if fault_exit is not None and info["exit_code"] == fault_exit:
140
+ # The grader says it could not judge. Whether the submission or
141
+ # the environment is the reason is settled after grading.
142
+ faulted.append((args, dict(kwargs), snapshot["name"]))
143
+ elif info["exit_code"] not in (0, 1):
144
+ raise RuntimeError(f"Grader command exit {info['exit_code']}: {snapshot['name']}")
145
+ return score
146
+
147
+ task.BashGrader = ObservedGrader
148
+ result = await task._grade(None)
149
+ if faulted:
150
+ # Ask the same commands about the untouched repository. A verdict there
151
+ # means the grader works here and the submission is what it could not
152
+ # judge, so the criterion stays unmet. No verdict there means the
153
+ # environment is at fault, and the attempt is invalid.
154
+ await task.repo_lib.git(task.REPO_DIR, "reset", "--hard", "HEAD")
155
+ await task.repo_lib.git(task.REPO_DIR, "clean", "-fd")
156
+ # Graders keep state between criteria, some of them a copy of the tree
157
+ # they judged. It describes the submission, so it goes too.
158
+ for leftover in Path(getattr(task, "LOGS_DIR", "/hud/logs")).iterdir():
159
+ if leftover.is_dir() and not leftover.is_symlink():
160
+ shutil.rmtree(leftover)
161
+ else:
162
+ leftover.unlink()
163
+ record["fault_probes"] = []
164
+ for args, kwargs, name in faulted:
165
+ _hand_over_checkout()
166
+ probe = (await original.grade(*args, **kwargs)).model_dump(mode="json")
167
+ info = probe.get("info") or {}
168
+ record["fault_probes"].append(
169
+ {
170
+ "name": name,
171
+ "exit_code": info.get("exit_code"),
172
+ "timed_out": info.get("timed_out"),
173
+ "stdout": (info.get("stdout") or "")[-2000:],
174
+ }
175
+ )
176
+ (PRIVATE / "fault_probes.json").write_text(json.dumps(record["fault_probes"], indent=2))
177
+ if info.get("timed_out") or info.get("exit_code") not in (0, 1):
178
+ raise RuntimeError(f"Grader cannot judge the untouched repository: {name}")
179
+ record["result"] = result.model_dump(mode="json")
180
+ # A rubric may answer an empty change without running any criterion.
181
+ record["status"] = "empty_patch" if not patch and not record["commands"] else "graded"
182
+
183
+
184
+ def _stop_candidate_processes() -> None:
185
+ # A candidate may fork. End its UID's processes before publishing evidence
186
+ # to a host bind mount, whose permissions may differ on Docker Desktop.
187
+ for directory in Path("/proc").iterdir():
188
+ if not directory.name.isdecimal():
189
+ continue
190
+ try:
191
+ status = (directory / "status").read_text()
192
+ uid = next(line.split()[1] for line in status.splitlines() if line.startswith("Uid:"))
193
+ if uid == "1000":
194
+ os.kill(int(directory.name), signal.SIGKILL)
195
+ except (FileNotFoundError, ProcessLookupError):
196
+ pass
197
+
198
+
199
+ def main() -> None:
200
+ """Persist structured evidence and publish reward only after validation."""
201
+ OUT.mkdir(parents=True, exist_ok=True)
202
+ PRIVATE.mkdir(parents=True, exist_ok=True, mode=0o700)
203
+ PRIVATE.chmod(0o700)
204
+ reward_path = OUT / "reward.txt"
205
+ reward_path.unlink(missing_ok=True)
206
+ config = json.loads(CONFIG.read_text())
207
+ shutil.copy2(CONFIG, OUT / "config.json")
208
+ record: dict[str, Any] = {
209
+ "revision": REVISION,
210
+ "task_id": config["task_id"],
211
+ "grader_version": importlib.metadata.version("hud"),
212
+ "commands": [],
213
+ "status": "error",
214
+ }
215
+ try:
216
+ if PATCH.is_symlink() or not PATCH.is_file() or PATCH.stat().st_size > 32 * 1024 * 1024:
217
+ raise ValueError("Missing, oversized or symlink submission")
218
+ record["patch_sha256"] = hashlib.sha256(PATCH.read_bytes()).hexdigest()
219
+ try:
220
+ asyncio.run(_grade(config, record))
221
+ finally:
222
+ _stop_candidate_processes()
223
+ reward_path.unlink(missing_ok=True)
224
+ validate_report(record, config, record["patch_sha256"])
225
+ (OUT / "report.json").write_text(json.dumps(record, indent=2))
226
+ reward_path.write_text(str(record["result"]["reward"]) + "\n")
227
+ except BaseException as error:
228
+ reward_path.unlink(missing_ok=True)
229
+ record.update(status="error", error={"type": type(error).__name__, "message": str(error)})
230
+ (OUT / "report.json").write_text(json.dumps(record, indent=2))
231
+ raise
232
+
233
+
234
+ if __name__ == "__main__":
235
+ main()
harbor/tasks/manifest.json CHANGED
@@ -1,6 +1,7 @@
1
  {
2
  "revision": "coding-rubric-v2",
3
  "tasks": [
 
4
  "bazel_remote_disk_eviction_accounting_contract",
5
  "celery_retry_expires_countdown_contract",
6
  "coredns_rewrite_svcb_opt",
 
1
  {
2
  "revision": "coding-rubric-v2",
3
  "tasks": [
4
+ "journal_recovery_after_unclean_stop",
5
  "bazel_remote_disk_eviction_accounting_contract",
6
  "celery_retry_expires_countdown_contract",
7
  "coredns_rewrite_svcb_opt",