Compare commits

...
Author SHA1 Message Date
Ping Qiu a547256ab2 Merge pull request #885 from seaweedfs/docs/v1.0.2-bundle-fixed
docs: v1.0.2 note: support bundles never hold an unproven artifact
2026-12-01 11:34:16 -08:00
pingqiuandClaude Opus 5.5 52b4345dc8 docs: v1.0.2 note: support bundles never hold an unproven artifact
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 10:05:26 -08:00
Ping Qiu 7d03fdf68a Merge pull request #877 from seaweedfs/fix/release-1.0-log-collect-redaction
[HOLD: Ping's yes/no] log.collect: no artifact is written whose redaction is not proven (release-1.0 backport)
2026-12-01 10:04:08 -08:00
Ping Qiu 1978dbb648 Merge pull request #873 from seaweedfs/docs/v1.0.2-note
docs: v1.0.2 release note
2026-12-01 09:34:27 -08:00
pingqiuandClaude Opus 5.5 d4eb07fade docs: v1.0.2 note: the open gate's result and verify's measured time
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:17:08 -08:00
pingqiuandClaude Opus 5.5 7f25b2c451 log.collect: only a unit command's own failure is unproven; colliding JSON keys withhold
A unit journal read whole with no records in the window (or a command
the host does not have) is only unavailable; only the command's own
failure (cut, nonzero exit, truncated) makes the bundle unproven. Two JSON
keys that collide once sanitized are no longer told apart by a suffix,
which could itself be a known credential and cost quadratic probes: that
artifact is withheld as not proven, checked after its redaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:50:37 -08:00
pingqiuandClaude Opus 5.5 4712a47407 log.collect: any declared source not read whole makes redaction unproven
A declared log file refused before discovery (not a regular file, changed,
over 4 MiB, not text, unreadable), a process whose arguments could not be
read, and a failed or truncated unit command each make the bundle
manifest-only, not only a unit cut by the time budget. A missing file or a
gone process holds nothing to discover and stays only unavailable. In an
unproven bundle every artifact error is replaced by a fixed one, and the
skipped names are printed sanitized. A known credential used as a JSON
object key is redacted too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:40:42 -08:00
pingqiuandClaude Opus 5.5 30780decdd docs: ledger row for the bundle's unproven-redaction rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:24:03 -08:00
pingqiuandClaude Opus 5.5 f009b9269a log.collect: no artifact is written whose redaction is not proven
Credential discovery read the declared log files only while the
collection's time budget lasted: a slow run (as under the race detector)
skipped the later files, and an earlier file was written with a
credential only a skipped one named. The declared log files are now read
whole for discovery whatever time is left (each is bounded at 4 MiB, at
most 32), after the declared commands and before the status reads. A
declared source the budget still cuts (a -unit's commands) makes the
bundle hold only its manifest, which says the redaction is not proven
and names the cut sources; the command reports it and exits 3. Each log
file is discovered once, not twice.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 04:23:52 -08:00
pingqiuandClaude Opus 5.5 d8b2e7d225 docs: v1.0.2 release note
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 03:07:46 -08:00
Ping Qiu 2340d9a523 Merge pull request #870 from seaweedfs/fix/release-1.0-verify-bindings-head
fix: backport body-less bindings verification to release-1.0
2026-12-01 02:54:22 -08:00
Ping Qiu 0667c62cc4 Merge pull request #868 from seaweedfs/fix/verify-bindings-stat
fix: verify chunk bindings without reading their bodies
2026-12-01 02:27:30 -08:00
Ping Qiu b7a4275975 Merge pull request #869 from seaweedfs/fix/r10-head-newer-version
layout: a HEAD with a version field is refused as written by a newer version
2026-12-01 02:02:53 -08:00
pingqiuandClaude Opus 5.5 0d281fc5fc master: the HEAD probe test counts writes; the newer HEAD fixture is top level
Every row of the master's HEAD probe table now asserts that the reader
attempted no filer create, update or delete and no blob upload, whatever
it answered (a write injected into the HEAD read fails every row). The
decoder test builds its newer-version HEAD with the new fields at the
top level and checks them there.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 01:33:11 -08:00
pingqiuandClaude Opus 5.5 afae4dfa0b layout: a HEAD with a version field is refused as written by a newer version
A v1.0.x reader meeting a HEAD that carries a version field (a newer
format writes it first) answers "HEAD written by a newer version: use a
newer binary" (ErrHeadNewerVersion, wrapping ErrMalformed) instead of a
plain malformed HEAD, so every final refusal stays final. Read side only:
nothing here writes a version or ext.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 00:32:20 -08:00
Ping Qiu f52c0960ce Merge pull request #854 from seaweedfs/docs/v101-drop-pending
docs: v1.0.1 note drops the pending release-gate limits line
2026-11-30 14:03:13 -08:00
pingqiuandClaude Opus 5.5 a1219cd304 docs: v1.0.1 note drops the pending release-gate limits line
Each limit the release gates found now has its own line in the note:
the 200-volume density, the verify time, and the refetch of a
read-only restored volume. The placeholder adds nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 13:43:00 -08:00
Ping Qiu 98c8e3938d Merge pull request #846 from seaweedfs/docs/v101-verify-time
docs: v1.0.1 note says how verify's time grows and what to set
2026-11-30 13:39:37 -08:00
pingqiuandClaude Opus 5.5 63ca9b2883 docs: v1.0.1 note says how verify's time grows and what to set
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 12:07:36 -08:00
Ping Qiu 559f69e955 Merge pull request #840 from seaweedfs/ci/pub-rc-own-tag-release-1.0
ci: a release candidate publishes only its own version tag
2026-11-30 11:16:17 -08:00
pingqiuandClaude Opus 5.5 15129d39c0 ci: move :alpha only for the highest stable version; refuse odd tags
A stable tag moves :alpha only when it is the highest vX.Y.Z tag, so a
later patch on an older line never moves :alpha back. A tag that is not
vX.Y.Z or vX.Y.Z-pre fails the run instead of publishing. The checkout
fetches tags so the comparison sees them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:51:47 -08:00
Ping Qiu 489f6d2696 Merge pull request #841 from seaweedfs/docs/v101-engines-notice
docs: v1.0.1 note gives advance notice that two experimental engines go in v1.1
2026-11-30 10:50:39 -08:00
pingqiuandClaude Opus 5.5 6ccd3bfd2e docs: v1.0.1 note gives advance notice that two experimental engines go in v1.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:49:27 -08:00
pingqiuandClaude Opus 5.5 8e3c2b81a6 ci: a release candidate publishes only its own version tag
Only a stable-line release tag (vX.Y.Z, no pre-release suffix) moves the
public :alpha and sha-* image tags; a release candidate (vX.Y.Z-rc.N)
publishes its version tag alone. The workflow also runs only on version
tags and on a manual run from a version tag, never on a branch push.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:49:21 -08:00
Ping Qiu 5e224c4057 Merge pull request #837 from seaweedfs/docs/v101-density
docs: v1.0.1 note states the 200-volume density tested
2026-11-30 10:29:56 -08:00
pingqiuandClaude Opus 5.5 58df877faa docs: v1.0.1 note states the 200-volume density tested
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 10:28:14 -08:00
Ping Qiu aa16ffa7a5 Merge pull request #830 from seaweedfs/fix/delete-head-conflict
v1.0.1 gate fix: a raced snapshot delete answers head_conflict
2026-11-30 08:04:56 -08:00
pingqiuandClaude Opus 5.5 77fa10070e docs(invariants): INV-CATALOG-HEAD-CONFLICT-001 registers the delete-race tests
A companion of INV-CUT-ERROR-PRECEDENCE-001 (whose statement is at its
length limit): a catalog transition that lost its conditional HEAD write
reports head_conflict, never internal, and decides last. Its tests are the
two delete-race regressions and the typed table.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:18:09 -08:00
pingqiuandClaude Opus 5.5 64eddb3484 fix(volume): the layout precondition decides last
The layout.ErrPrecondition case moves to the last position before default,
so every other cause an error carries decides first, the non-retryable
ones (closed, detached, frozen detach unsupported, an invalid freeze
budget, not a chunk volume) included. Controls: each joined with the
precondition reports its own code; with the case moved back to its
earlier place the closed, detached and frozen-detach rows fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:12:21 -08:00
pingqiuandClaude Opus 5.5 3a5de69079 fix(volume): a snapshot delete that loses its HEAD write is head_conflict
chunkErrorCode maps layout.ErrPrecondition (a catalog transition lost its
conditional HEAD write to another writer, such as a cleaning's begin) to
head_conflict, 409, retryable, as it maps the engine's HEAD precondition.
It answered internal before. The case sits with the HEAD-precondition one,
after every terminal and uncertain cause, so a joined error keeps its
precedence. The operator guide and the v1.0.1 notes say to retry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:07:55 -08:00
pingqiuandClaude Opus 5.5 031312357b test(volume): a snapshot delete raced by a HEAD write is a head conflict
The holder's cleaning begins between a snapshot delete's HEAD read and its
conditional write: the delete fails on the HEAD precondition, nothing of it
applies, and a retry completes. Red: the refusal maps to 500 internal, not
retryable; under a persistent conflict every attempt is internal.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 07:06:49 -08:00
Ping Qiu 9790c07bfd Merge pull request #828 from seaweedfs/docs/restored-refetch
docs: a read-only restored volume fetches every chunk again after any restart
2026-11-30 06:45:52 -08:00
pingqiuandClaude Opus 5.5 3759fae784 docs: a read-only restored volume fetches every chunk again after any restart
The v1.0.1 known limit and the standalone restore steps said fetched chunks
are fetched again after a crash; a restored volume that has only been read
takes no checkpoint, so it fetches all of them again after any restart,
clean included, until a write or its next checkpoint records them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 06:43:29 -08:00
Ping Qiu ebf6b8010a Merge pull request #820 from seaweedfs/test/start-wal-replay-interruption
test: kill and restart startup WAL replay at record boundaries
2026-11-30 05:46:06 -08:00
Ping Qiu 50d5cdcf18 Merge pull request #823 from seaweedfs/docs/remote-unavailable-bound
docs: remote_unavailable also follows a request that ran out of its 5-minute bound
2026-11-30 05:21:09 -08:00
pingqiuandClaude Opus 5.5 efb91181e0 docs: remote_unavailable also follows a request that ran out of its 5-minute bound
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 05:19:13 -08:00
Ping Qiu dcfc41445a Merge pull request #822 from seaweedfs/ci/pr-tp04-release-1.0
ci: run Test for same-repo pull requests on the self-hosted runner
2026-11-30 04:42:04 -08:00
pingqiuandClaude Opus 5.5 aec98979c7 ci: run Test for same-repo pull requests on the self-hosted runner
The hosted queue held every same-repo pull request's Test job for more than
an hour today, which blocked gate fixes and reviewed work alike. Same-repo
pull requests now run Test on the tp04-seaweed-block label, as main pushes
and train branches already do. Pull requests from forks keep the hosted
runner, so no fork code runs on our machines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 04:38:35 -08:00
pingqiu ac18390a51 test: verify replay kill status and release failed seeds 2026-11-30 04:09:43 -08:00
pingqiu e4e9e57e9b test: kill startup WAL replay at record and batch boundaries 2026-11-30 04:02:01 -08:00
Ping Qiu 55294a9835 Merge pull request #813 from seaweedfs/docs/v101-note
docs: v1.0.1 release note; drop the stale "coming in v1.0.1" lines
2026-11-30 03:41:31 -08:00
pingqiuandClaude Opus 5.5 8719e9cace docs: operator guide states the 5-minute request bound, not measured figures
The restore-target delete and the snapshot timeout paragraphs keep the
contract that follows from the server's 5-minute bound for one request and
drop the figures measured before the performance round.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 02:46:05 -08:00
Ping Qiu 330797ba8b Merge pull request #811 from seaweedfs/test/powerloss-verify-master-rc1
test: observe applied cut objects before power-loss replay
2026-11-30 02:45:38 -08:00
pingqiuandClaude Opus 5.5 5c1c1c75b4 docs: v1.0.1 note adds the start checks and later fixes; no unmeasured figures
Adds the start-up checks operators meet (workspace lease required, the
conditional HEAD probe, the stricter single-filer check, exit 79), the
snapshot position, schedule, upload and fsync fixes, and the forced-move
JSON. Limits are stated without performance figures measured before the
performance round; the gate line stays until the release gates end.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 02:42:14 -08:00
pingqiuandClaude Opus 5.5 e883ade9be docs: v1.0.1 release note; drop the stale "coming in v1.0.1" lines
The note lists what v1.0.1 adds and fixes, its upgrade, limits and known
limits, checked against this branch. README, troubleshooting, the cleaning
page and the operator guide no longer call those changes unreleased; the
operator guide describes the CLI's own repeat of 5-minute requests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 02:38:36 -08:00
pingqiu 5c679df1cf Make power-loss replay verification use a causal cut boundary 2026-11-30 02:20:11 -08:00
39 changed files with 2493 additions and 150 deletions

No files matched your search

+32 -27
View File
@@ -3,8 +3,6 @@ name: Publish alpha images
on:
workflow_dispatch:
push:
branches:
- main
tags:
- "v*"
@@ -19,10 +17,14 @@ env:
jobs:
publish:
# Publish only from a version tag; a manual run from a branch must not move :alpha.
if: startsWith(github.ref, 'refs/tags/v')
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # the tag list decides whether :alpha moves
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
@@ -39,33 +41,36 @@ jobs:
shell: bash
run: |
set -euo pipefail
# vX.Y.Z-pre (a release candidate) publishes only its own version tag. A stable vX.Y.Z also
# publishes sha-*, and moves :alpha only when it is the highest stable version tag, so a later
# patch on an older line never moves :alpha back.
short_sha="${GITHUB_SHA::12}"
if [[ "${GITHUB_REF_TYPE}" == "tag" ]]; then
version="${GITHUB_REF_NAME}"
{
echo "block_tags<<EOF"
echo "${BLOCK_IMAGE}:${version}"
echo "${BLOCK_IMAGE}:alpha"
echo "${BLOCK_IMAGE}:sha-${short_sha}"
echo "EOF"
echo "csi_tags<<EOF"
echo "${CSI_IMAGE}:${version}"
echo "${CSI_IMAGE}:alpha"
echo "${CSI_IMAGE}:sha-${short_sha}"
echo "EOF"
} >> "$GITHUB_OUTPUT"
else
{
echo "block_tags<<EOF"
echo "${BLOCK_IMAGE}:alpha"
echo "${BLOCK_IMAGE}:sha-${short_sha}"
echo "EOF"
echo "csi_tags<<EOF"
echo "${CSI_IMAGE}:alpha"
echo "${CSI_IMAGE}:sha-${short_sha}"
echo "EOF"
} >> "$GITHUB_OUTPUT"
version="${GITHUB_REF_NAME}"
if [[ ! "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]]; then
echo "refusing to publish: tag ${version} is not vX.Y.Z or vX.Y.Z-pre" >&2
exit 1
fi
stable=false
move_alpha=false
if [[ "${version}" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
stable=true
highest="$(git tag -l 'v*' | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$' | sort -V | tail -n 1)"
if [[ "${version}" == "${highest}" ]]; then
move_alpha=true
fi
fi
{
echo "block_tags<<EOF"
echo "${BLOCK_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${BLOCK_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${BLOCK_IMAGE}:alpha"; fi
echo "EOF"
echo "csi_tags<<EOF"
echo "${CSI_IMAGE}:${version}"
if [[ "${stable}" == true ]]; then echo "${CSI_IMAGE}:sha-${short_sha}"; fi
if [[ "${move_alpha}" == true ]]; then echo "${CSI_IMAGE}:alpha"; fi
echo "EOF"
} >> "$GITHUB_OUTPUT"
- name: Build and push block image
uses: docker/build-push-action@v6
+1 -1
View File
@@ -39,7 +39,7 @@ jobs:
# train/* of this repository, a few a day) also runs on the team's runners:
# it is the merge gate, and the organization's shared GitHub-hosted queue held
# it 30-55 minutes before it started. A PR from a fork never runs there.
runs-on: ${{ (github.event_name == 'push' || (github.event.pull_request.head.repo.full_name == github.repository && startsWith(github.head_ref, 'train/'))) && 'tp04-seaweed-block' || 'ubuntu-latest' }}
runs-on: ${{ (github.event_name == 'push' || (github.event.pull_request.head.repo.full_name == github.repository)) && 'tp04-seaweed-block' || 'ubuntu-latest' }}
# process: 44 tests in 4 parallel shards of about 13 min each (55 min in sequence).
timeout-minutes: ${{ matrix.suite == 'unit' && 40 || 90 }}
env:
+8 -16
View File
@@ -46,12 +46,12 @@ not format or write the attached device; it only creates local backing files
and logs. It needs Linux, bash, `nvme-cli`, `sudo` and the binaries
above. To format and write, use the [write test](docs/standalone-deployment.md#write-test-scratch-host-only) (scratch host only).
### On main, coming in v1.0.1: `sw-block mini`
### `sw-block mini`
`main` is unreleased: use it for a trial on a scratch host, not for data you keep. One command starts a single-host
A trial on a scratch host, not for data you keep. One command starts a single-host
trial on loopback, with SeaweedFS's `weed mini` as the chunk store (run against SeaweedFS 4.53). Build all three
binaries from `main` and run the one you built, so that `mini` finds its matching `blockmaster` and `blockvolume`
next to it:
binaries from the same checkout and run the one you built, so that `mini` finds its matching `blockmaster` and
`blockvolume` next to it:
```bash
git clone https://github.com/seaweedfs/seaweed-block && cd seaweed-block
@@ -144,21 +144,13 @@ measured.
Seaweed Block is block storage for AI agent workspaces: one local-speed disk per sandbox or microVM, with its history
(snapshots, restores, moves) in your own SeaweedFS. The same core serves Kubernetes block volumes (alpha).
- **Works today (v1.0.0):** single-replica volumes up to 256 GiB over NVMe/TCP or iSCSI; scheduled and manual
- **Works today (v1.0.1):** single-replica volumes up to 256 GiB over NVMe/TCP or iSCSI; scheduled and manual
snapshots; restore into a new volume; a planned hand-over to another machine (run across two machines on the
release candidate); a forced move after a host is lost, from the volume's last cut (tested with two server
identities on one machine); volume delete. Each is a documented sequence of `sw-block ops` commands and systemd
units.
- **Next, planned for v1.0.1** (still single replica):
- `sw-block mini`: one command that starts a single-host trial;
- whole-job volume commands, each one command: `sw-block volume start`, `stop` (it publishes the volume's changes
first), `backup` and `restore`;
- `sw-block shell` for inspection: status, lists, and `cluster.check`, a fixed list of checks whose troubleshooting
page says what to do for each;
- a log bundle without secrets, for bug reports;
- a working `ops chunk verify`.
The recovery point above does not change in v1.0.1.
units. v1.0.1 adds `sw-block mini`, a single-host trial; whole-job volume commands (`sw-block volume start`,
`stop`, `backup`, `restore`); `sw-block shell` for inspection, with `cluster.check` and a troubleshooting page; a
log bundle without secrets; and a working `ops chunk verify` (see the [v1.0.1 note](docs/releases/v1.0.1.md)).
- **After that, planned:** volumes up to 1 TiB (v1.1); replicated volumes beyond the preview; export of a snapshot to another object store, and
import from it; `volume fork` and `volume move` commands.
@@ -4,12 +4,16 @@ package main_test
import (
"bytes"
"context"
"fmt"
"os"
"path"
"path/filepath"
"syscall"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// Power loss on a chunk volume (INV-FE-FLUSH-SYNC-001),
@@ -27,7 +31,7 @@ import (
// 2. image B over the same LBAs, flushed, one more write without a flush,
// then a power cut (image A in HEAD must not show through);
// 3. a new image flushed, a cut started, a power cut while it uploads (the
// delay adapts until chunk objects reached the filer but HEAD did not move).
// first applied object-create reply is held until the holder is killed).
//
// Environment: SWBLOCK_REPLAY_ROOT and SWBLOCK_REPLAY_CUT as for
// TestPowerLossReplayAckedWritesSurvive; CHUNKSTORE_WEED; optional
@@ -40,7 +44,19 @@ func TestPowerLossReplayChunkVolume(t *testing.T) {
if root == "" || cutTool == "" {
t.Fatalf("SWBLOCK_REPLAY_ROOT=%q and SWBLOCK_REPLAY_CUT=%q must be set together", root, cutTool)
}
env := startHandoffEnvWith(t, 1, []string{"v2"})
if testListenHost() != "127.0.0.1" {
t.Fatal("causal filer fixture requires loopback")
}
var boundary *snapshotFilerBoundary
cluster := startWorkspaceWeedWith(t, t.TempDir(), w4WeedOpts{VolumeSizeLimitMB: 256, VolumeMax: 32,
FilerBind: "127.0.0.2", FilerFront: func(c *w4WeedCluster) { boundary = newSnapshotFilerBoundary(t, c) }})
env := startHandoffEnvOnCluster(t, 1, []string{"v2"}, procedureTLSConfig(), false, cluster)
id, err := layout.ParseVolumeID(env.layoutID("v1"))
if err != nil {
t.Fatal(err)
}
boundary.id = id
boundary.dir = path.Join(env.chunkPath, layout.VolumeDir("v1", id))
if d := os.Getenv("SWBLOCK_REPLAY_LOGS"); d != "" {
t.Cleanup(func() { copyLogs(t, env.h.dir, d) })
}
@@ -49,7 +65,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) {
env.hosts["s1"] = h
env.volExtra = []string{"--chunk-capture-interval", "0", "--chunk-snapshot-schedule", "off"}
cut := []string{"ops", "chunk", "cut", "--volume", "v1", "--status-addr", env.hosts["s1"].status}
verify := []string{"ops", "chunk", "verify", "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"}
verify := []string{"ops", "chunk", "verify", "--master", env.h.masterAddr, "--volume", "v1", "--chunk-filer", env.cluster.filerGRPC, "--chunk-path", env.chunkPath, "--depth", "data", "--timeout", "5m"}
headGen := func() uint64 {
out, _ := env.h.command(t, env.chunkShow()...)
hd, err := parseLayoutHead(out)
@@ -67,13 +83,16 @@ func TestPowerLossReplayChunkVolume(t *testing.T) {
// a new generation (a cut that uploads nothing would leave it). frozenGen,
// when not 0, is the HEAD generation seen while frozen: it must still hold
// after the kill, so no HEAD write from before the freeze landed later.
powerCut := func(phase string, img byte, frozenGen uint64, advance bool) {
powerCut := func(phase string, img byte, frozenGen uint64, advance bool, afterKill func()) {
t.Helper()
if err := holder.proc.Signal(syscall.SIGSTOP); err != nil {
t.Fatalf("%s: freeze the holder: %v", phase, err)
}
runReplayCut(t, cutTool, "mark")
holder.kill(t)
if afterKill != nil {
afterKill()
}
if frozenGen != 0 {
if g := headGen(); g != frozenGen {
t.Fatalf("%s: HEAD moved from gen %d to %d after the freeze: the cut was not in progress at the mark", phase, frozenGen, g)
@@ -99,10 +118,8 @@ func TestPowerLossReplayChunkVolume(t *testing.T) {
// Phase 1: a committed cut before the power cut.
env.writeCutCrashImage(t, 'A')
cutStart := time.Now()
env.h.command(t, cut...)
cutTook := time.Since(cutStart)
powerCut("phase 1 (after a committed cut)", 'A', 0, false)
powerCut("phase 1 (after a committed cut)", 'A', 0, false, nil)
// Phase 2: overwrite with B; then a write the guest never flushed.
env.writeCutCrashImage(t, 'B')
@@ -117,7 +134,7 @@ func TestPowerLossReplayChunkVolume(t *testing.T) {
defer c.close()
c.write(t, extra, cutCrashBlock('x', extra))
}()
powerCut("phase 2 (between a write and its flush)", 'B', 0, true)
powerCut("phase 2 (between a write and its flush)", 'B', 0, true, nil)
func() {
c := dialNVMe(t, env.hosts["s1"].nvme, plannedHandoffNQN)
defer c.close()
@@ -127,50 +144,37 @@ func TestPowerLossReplayChunkVolume(t *testing.T) {
}
}()
// Phase 3: a power cut while a cut uploads.
delay := cutTook / 2
img, landed := byte('B'), false
for attempt := 1; attempt <= cutCrashAttempts && !landed; attempt++ {
img++
env.writeCutCrashImage(t, img)
gen, entries := headGen(), f1FilerEntries(t, env)
done := make(chan int, 1)
go func() {
_, _, code := env.h.run(t, cut...)
done <- code
}()
time.Sleep(delay)
if err := holder.proc.Signal(syscall.SIGSTOP); err != nil {
t.Fatalf("phase 3: freeze the holder: %v", err)
}
time.Sleep(time.Second) // a HEAD write already on the wire lands before the reading
uploaded, after := f1FilerEntries(t, env)-entries, headGen()
switch {
case after != gen:
t.Logf("phase 3 attempt %d: the cut committed before %s (HEAD gen %d -> %d); shorter", attempt, delay, gen, after)
delay /= 2
case uploaded <= 0:
t.Logf("phase 3 attempt %d: nothing uploaded by %s; longer", attempt, delay)
delay *= 2
default:
landed = true
t.Logf("phase 3 attempt %d: frozen at %s mid-upload: %d new filer entries, HEAD still gen %d", attempt, delay, uploaded, gen)
}
if landed {
// Still frozen mid-upload: the power cut starts from here (its
// SIGSTOP is a no-op on a stopped process).
powerCut(fmt.Sprintf("phase 3 attempt %d (cut in progress)", attempt), img, gen, true)
<-done
break
}
if err := holder.proc.Signal(syscall.SIGCONT); err != nil {
t.Fatalf("phase 3: resume: %v", err)
}
// Phase 3: hold the stock filer's first applied object-create answer.
// Begin itself advances HEAD; generation movement is not proof of Commit.
// Observe an open session and unchanged Current at the actual object boundary.
img := byte('C')
env.writeCutCrashImage(t, img)
beforeHead := boundary.head(t)
reached := boundary.arm("OBJECT", "")
ctx, cancel := context.WithTimeout(context.Background(), 150*time.Second)
defer cancel()
done := make(chan struct{})
go func() { defer close(done); _, _, _, _ = runCLI(ctx, env.h, cut...) }()
t.Cleanup(func() { cancel(); boundary.unblock(); <-done })
select {
case <-reached:
case <-time.After(30 * time.Second):
cancel()
boundary.unblock()
<-done
t.Fatal("inconclusive: cut never reached applied object boundary")
}
if !landed {
t.Fatalf("no power cut landed while a cut uploaded, in %d attempts", cutCrashAttempts)
if err := holder.proc.Signal(syscall.SIGSTOP); err != nil {
t.Fatal(err)
}
frozen := boundary.head(t)
if frozen.Activity.Kind != layout.ActSnap || frozen.Activity.Session == "" || frozen.Current == nil || beforeHead.Current == nil || *frozen.Current != *beforeHead.Current {
t.Fatalf("object boundary is not an open unpublished cut: before=%+v frozen=%+v", beforeHead, frozen)
}
t.Logf("phase 3: applied object held, HEAD gen=%d open session=%s Current unchanged", frozen.Gen, frozen.Activity.Session)
// Mark and kill while the holder is stopped, then release the old RPC before
// checking the exact frozen HEAD and restarting from the replayed device.
powerCut("phase 3 (cut in progress)", img, frozen.Gen, true, func() { boundary.unblock(); <-done })
// What the filer holds is the image: a snapshot restored into a new volume.
env.snapshot(t, "s1", "v1", "after-power-cuts")
env.restoreInto(t, "v1", "after-power-cuts", "v2")
@@ -0,0 +1,111 @@
package main
import (
"bytes"
"context"
"path"
"strings"
"sync/atomic"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// countingChunkStore counts every mutating filer call and blob put.
type countingChunkStore struct {
*memChunkStore
writes atomic.Int64
}
func (c *countingChunkStore) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
c.writes.Add(1)
return c.memChunkStore.CreateEntry(ctx, dir, e, oExcl)
}
func (c *countingChunkStore) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
c.writes.Add(1)
return c.memChunkStore.UpdateEntry(ctx, dir, e, expected)
}
func (c *countingChunkStore) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
c.writes.Add(1)
return c.memChunkStore.DeleteEntry(ctx, dir, name, expected)
}
func (c *countingChunkStore) Put(ctx context.Context, data []byte) (string, error) {
c.writes.Add(1)
return c.memChunkStore.Put(ctx, data)
}
// plantNewerHead rewrites v's HEAD as a newer format writes it (a version
// field first, a size and an ext object), in place.
func plantNewerHead(t *testing.T, store *memChunkStore, v chunkstore.VolumeRef) {
t.Helper()
ctx := context.Background()
dir := path.Join(defaultChunkPathCLI, v.Dir())
e, err := store.LookupEntry(ctx, dir, layout.HeadName)
if err != nil {
t.Fatal(err)
}
b := e.Content
if _, err := layout.DecodeHead(b, 1, v.ID); err != nil {
t.Fatalf("setup: %v", err)
}
newer := append([]byte(`{"version":1,`), b[1:len(b)-1]...)
e.Content = append(newer, []byte(`,"current_bytes":10,"ext":{"later":1}}`)...)
if err := store.MemFiler.UpdateEntry(ctx, dir, e, nil); err != nil {
t.Fatal(err)
}
}
// A v1.0.x CLI meeting a HEAD written by a newer format: every chunk verb
// that reads HEAD from the filer refuses with the newer-version text (use a
// newer binary; never corruption, restore or recreate), and writes nothing:
// no entry is created, updated or deleted and no blob is put. cut, snapshot
// and detach are requests to the holder, whose Start refuses the HEAD
// (TestFinalLayoutStartRefusalTable).
func TestOpsChunkEveryVerbRefusesANewerHeadAndWritesNothing(t *testing.T) {
mem := newMemChunkStore()
store := &countingChunkStore{memChunkStore: mem}
useMemChunkStore(t, mem)
dialChunkFiler = func(string) (chunkstore.Filer, func() error, error) { return store, func() error { return nil }, nil }
src := cliVolume(t, mem, "src", "daily")
plantNewerHead(t, mem, src)
tid, _ := layout.NewVolumeID()
tgt := chunkstore.VolumeRef{Name: "t", ID: tid}
lc := &fakeLifecycle{}
addr := startFakeLifecycle(t, lc)
verbs := map[string][]string{
"snapshots": cliArgs("snapshots", volArgs("volume", src)),
"show": cliArgs("show", volArgs("volume", src)),
"usage": cliArgs("usage", volArgs("volume", src)),
"snapshot-delete": cliArgs("snapshot-delete", volArgs("volume", src), []string{"--name", "daily"}),
"retain": cliArgs("retain", volArgs("volume", src)),
"retain --dry-run": cliArgs("retain", volArgs("volume", src), []string{"--dry-run"}),
"release": cliArgs("release", volArgs("source", src), volArgs("target", tgt)),
"verify": cliArgs("verify", volArgs("volume", src)),
"restore": cliArgs("restore", volArgs("source", src), volArgs("target", tgt), []string{"--snapshot", "daily"}),
"volume-delete": cliArgs("volume-delete", volArgs("volume", src), []string{"--master", addr, "--request-id", "r1"}),
}
for name, args := range verbs {
t.Run(name, func(t *testing.T) {
before := store.writes.Load()
var out, errb bytes.Buffer
code := run(append([]string{"ops", "chunk"}, args...), &out, &errb)
all := out.String() + errb.String()
if code == 0 || !strings.Contains(all, "written by a newer version: use a newer binary") {
t.Fatalf("exit %d, out %q err %q; want the newer-version refusal", code, out.String(), errb.String())
}
for _, bad := range []string{"corrupt", "recreate", "restore or"} {
if strings.Contains(strings.ToLower(all), bad) {
t.Fatalf("the refusal says %q: %s", bad, all)
}
}
if n := store.writes.Load() - before; n != 0 {
t.Fatalf("%d filer writes; want none", n)
}
})
}
}
+1 -1
View File
@@ -37,7 +37,7 @@ func chunkVerify(args []string, stdout, stderr io.Writer) int {
fs.StringVar(&base, "chunk-path", defaultChunkPathCLI, "filer directory holding one directory per volume")
fs.StringVar(&snapshot, "snapshot", "", "unsupported: every snapshot HEAD names is always checked")
fs.BoolVar(&allSnapshots, "all-snapshots", false, "unsupported: every snapshot HEAD names is always checked")
fs.StringVar(&depth, "depth", "bindings", "meta or bindings: every named object exists; data: and every chunk's bytes hash to its name")
fs.StringVar(&depth, "depth", "bindings", "meta or bindings: named filer entries, sizes and needle HEAD; data: and every chunk's bytes hash to its name")
fs.BoolVar(&orphans, "orphans", false, "also report the volume's own names no reachable root names (report only)")
fs.IntVar(&concurrency, "concurrency", 1, "unsupported: chunks are read one at a time")
fs.Int64Var(&bytesPerSec, "bytes-per-sec", 0, "unsupported: chunk reads are not paced")
@@ -43,7 +43,7 @@ func verifyCLIFixture(t *testing.T) (*manifestFixtureFiler, string) {
oldResolve := resolveVolumeID
resolveVolumeID = func(context.Context, string, string) (layout.VolumeID, error) { return id, nil }
t.Cleanup(func() { resolveVolumeID = oldResolve })
vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}, Format: layout.VolumeFormat}.Encode()
vb, err := layout.Volume{ID: id, Name: "v1", Geometry: layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4096}, Format: layout.VolumeFormat}.Encode()
if err != nil {
t.Fatal(err)
}
+95 -12
View File
@@ -9,6 +9,7 @@ import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
@@ -34,8 +35,16 @@ type logBundle struct {
Since time.Time `json:"since"`
Until time.Time `json:"until"`
Artifacts []bundleArtifact `json:"artifacts"`
// Redaction is "not_proven" when a declared source (-log-file, -unit,
// -pid) was not read whole for credential discovery (cut by the time
// budget, unreadable, over its bound, truncated); the bundle then holds
// no artifact but this manifest, with fixed diagnostics only. Skipped
// names those sources.
Redaction string `json:"redaction,omitempty"`
Skipped []string `json:"skipped,omitempty"`
bytes int
redactor *bundleRedactor
ctx context.Context // the collection's time budget
}
func (b *logBundle) discover(data []byte) {
@@ -48,10 +57,38 @@ func (b *logBundle) discover(data []byte) {
}
b.redactor.discover(data)
}
// add adds a source the bundle collects on its own (the master's and the
// holders' status): one the time budget cut adds no bytes, and none of its
// own reach the bundle.
func (b *logBundle) add(name string, data []byte, err error) {
b.addSource(name, data, err, true)
}
// addCommand adds a declared -unit's command output. The command's own
// failure (cut by the time budget, a nonzero exit, output truncated at its
// bound) left it not read whole, so its credentials are not all discovered;
// a command this host does not have read nothing, and is only unavailable.
// err is the artifact's error (the command's, or the time filter's after a
// whole read).
func (b *logBundle) addCommand(name string, data []byte, cmdErr, err error) {
if cmdErr != nil && !errors.Is(cmdErr, exec.ErrNotFound) {
b.unproven(name)
}
b.addSource(name, data, err, true)
}
// unproven records a declared source whose discovery did not complete.
func (b *logBundle) unproven(name string) { b.Skipped = append(b.Skipped, name) }
// addSource adds a source; discover says its bytes are still to be
// discovered (a log file's were, whole, as it was read).
func (b *logBundle) addSource(name string, data []byte, err error, discover bool) {
// Even a source omitted by the aggregate artifact budget can identify a
// credential repeated in a retained artifact. Keep only its bounded secrets.
b.discover(data)
if discover {
b.discover(data)
}
if err != nil {
b.discover([]byte(err.Error()))
}
@@ -81,13 +118,30 @@ func (b *logBundle) write(dir string) error {
if r.overflow {
return errors.New("redaction discovery bound exceeded")
}
// A source cut by the time budget may hold a credential repeated in
// another artifact: no artifact is written whose redaction is not proven.
// Every free-form error goes too: only fixed diagnostics remain.
if len(b.Skipped) > 0 {
b.Redaction = "not_proven"
for i := range b.Artifacts {
a := &b.Artifacts[i]
if a.data != nil {
a.State = "withheld"
}
a.data, a.Error = nil, "withheld: redaction not proven"
}
}
outputBytes := 0
for i := range b.Artifacts {
a := &b.Artifacts[i]
if a.data == nil {
continue
}
clean := r.redact(a.data)
clean, proven := r.redactChecked(a.data)
if !proven {
a.data, a.State, a.Error = nil, "withheld", "withheld: redaction not proven"
continue
}
if len(clean) > bundleSourceLimit || outputBytes+len(clean) > bundleTotalLimit {
a.data = nil
a.State = "unavailable"
@@ -101,8 +155,8 @@ func (b *logBundle) write(dir string) error {
if err != nil {
return err
}
meta = r.redact(meta)
if len(meta) > bundleSourceLimit {
meta, proven := r.redactChecked(meta)
if !proven || len(meta) > bundleSourceLimit {
return errors.New("manifest exceeds collection bound")
}
if err = os.Mkdir(dir, 0700); err != nil {
@@ -142,25 +196,46 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in
b := logBundle{Version: 1, Since: now.Add(-*since), Until: now}
ctx, cancel := context.WithTimeout(context.Background(), s.timeout)
defer cancel()
b.ctx = ctx
if len(files) == 0 && len(units) == 0 {
discovered, err := defaultBundleUnits(ctx)
units = discovered
b.addJSON("unit-discovery.json", map[string]any{"units": discovered}, err)
}
for i, p := range files {
if ctx.Err() != nil {
b.add(fmt.Sprintf("file-%03d.log", i+1), nil, ctx.Err())
continue
}
data, err := readBundleLog(p, b.Since, b.Until, b.discover)
b.add(fmt.Sprintf("file-%03d.log", i+1), data, err)
}
// The declared sources first: the commands the time budget bounds (-unit,
// -pid), then the log files, each read whole for discovery whatever time
// is left (each is bounded at 4 MiB, at most 32 sources), so the budget
// never cuts their discovery. The status reads, not declared, come last.
b.collectLocal(ctx, units, pids)
for i, p := range files {
name, discovered := fmt.Sprintf("file-%03d.log", i+1), false
data, err := readBundleLog(p, b.Since, b.Until, func(raw []byte) { b.discover(raw); discovered = true })
if !discovered && !errors.Is(err, errBundleLogMissing) {
b.unproven(name) // refused before discovery: not a regular file, changed, over 4 MiB, not text, unreadable
}
b.addSource(name, data, err, false)
}
b.collectStatus(ctx, s)
if err := b.write(dir); err != nil {
fmt.Fprintln(stderr, "cannot write bundle")
return 1
}
if b.Redaction == "not_proven" {
skipped := make([]string, len(b.Skipped)) // printed as sanitized as the manifest
for i, name := range b.Skipped {
skipped[i] = b.redactor.redactText(name)
}
if *format == "json" {
_ = json.NewEncoder(stdout).Encode(map[string]any{"bundle_written": true, "complete": false, "redaction": "not_proven", "skipped": skipped, "manifest": "manifest.json"})
} else {
named := skipped
if len(named) > 8 {
named = append(append([]string(nil), named[:8]...), fmt.Sprintf("and %d more", len(skipped)-8))
}
fmt.Fprintf(stdout, "bundle written; incomplete: redaction not proven (not read in time: %s); only manifest.json was written\n", strings.Join(named, ", "))
}
return 3
}
complete := true
for _, a := range b.Artifacts {
if a.State != "collected" {
@@ -179,8 +254,16 @@ func (s inspectionShell) collectLogs(args []string, stdout, stderr io.Writer) in
}
return 0
}
// errBundleLogMissing: a declared log file that does not exist holds
// nothing to discover; it is unavailable, not unproven.
var errBundleLogMissing = errors.New("log file is unavailable")
func readBundleLog(path string, since, until time.Time, discover ...func([]byte)) ([]byte, error) {
before, err := os.Lstat(path)
if errors.Is(err, os.ErrNotExist) {
return nil, errBundleLogMissing
}
if err != nil {
return nil, errors.New("log file is unavailable")
}
@@ -185,8 +185,10 @@ func TestLogCollectJournalDeadlineAndLinkedFileAreUnavailable(t *testing.T) {
if code != 3 {
t.Fatalf("link certified: exit%d", code)
}
// The refused link was never read whole: redaction is not proven, so the
// manifest names it and carries only fixed diagnostics.
raw, _ := os.ReadFile(filepath.Join(bundle, "manifest.json"))
if !strings.Contains(string(raw), "regular file") {
if !strings.Contains(string(raw), `"redaction": "not_proven"`) || !strings.Contains(string(raw), `"file-001.log"`) || strings.Contains(string(raw), "do-not-copy") {
t.Fatalf("link refusal missing: %s", raw)
}
if _, err := os.Stat(filepath.Join(bundle, "file-001.log")); !os.IsNotExist(err) {
@@ -288,3 +290,112 @@ func TestLogCollectChangedSourceCannotBlockAcquisition(t *testing.T) {
default:
}
}
// A declared unit whose journal output is truncated at its bound, with the
// collection's time budget still live: the credential named past the bound
// is never discovered, so no artifact repeating it is written.
func TestLogCollectTruncatedUnitWithholdsEveryArtifact(t *testing.T) {
const secret = "truncated-planted-60617"
dir := t.TempDir()
stamp := time.Now().UTC().Format(time.RFC3339Nano)
scripts := map[string]string{
"systemctl": "#!/bin/sh\nprintf '%s\n' 'ExecStart=/bin/blockvolume --volume-id=v1'\n",
"journalctl": "#!/bin/sh\nhead -c 5000000 /dev/zero | tr '\\0' 'x'\nprintf '\\n%s --password=%s\\n' '" + stamp + "' '" + secret + "'\n",
}
for name, script := range scripts {
if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil {
t.Fatal(err)
}
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
file := filepath.Join(dir, "daemon.log")
if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil {
t.Fatal(err)
}
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
bundle := filepath.Join(dir, "bundle")
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", "log.collect -out '" + bundle + "' -unit 'sw-blockvolume@v1.service' -log-file '" + file + "'"}, &out, &errout)
if code != 3 || !strings.Contains(out.String(), "redaction not proven") {
t.Fatalf("exit %d %q %s", code, &out, &errout)
}
if n := bundleOccurrences(t, bundle, secret); n != 0 {
t.Fatalf("%d unredacted occurrences of the credential in the bundle", n)
}
}
// fakeUnitCommands puts systemctl and journalctl scripts on PATH; journal
// is what journalctl prints.
func fakeUnitCommands(t *testing.T, journal string) {
t.Helper()
dir := t.TempDir()
scripts := map[string]string{
"systemctl": "#!/bin/sh\nprintf '%s\\n' 'ExecStart=/bin/blockvolume --volume-id=v1'\n",
"journalctl": "#!/bin/sh\nprintf '%s\\n' '" + journal + "'\n",
}
for name, script := range scripts {
if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil {
t.Fatal(err)
}
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
}
// A declared source the time budget cut (a -unit's commands) may hold a
// credential another artifact repeats: the bundle then holds only its
// manifest, says the redaction is not proven, names the cut sources, and
// no byte of the bundle carries the credential.
func TestLogCollectCutDeclaredSourceWithholdsEveryArtifact(t *testing.T) {
fakeUnitCommands(t, "-- No entries --")
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
dir := t.TempDir()
bundle := filepath.Join(dir, "bundle")
const secret = "cut-source-planted-77031"
file := filepath.Join(dir, "daemon.log")
if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil {
t.Fatal(err)
}
command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", bundle, file)
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout)
if code != 3 || !strings.Contains(out.String(), "incomplete: redaction not proven") || !strings.Contains(out.String(), "unit-001.log") {
t.Fatalf("exit %d %q %s", code, &out, &errout)
}
entries, err := os.ReadDir(bundle)
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if e.Name() != "manifest.json" {
t.Errorf("artifact %s written although redaction is not proven", e.Name())
}
}
if n := bundleOccurrences(t, bundle, secret); n != 0 {
t.Fatalf("%d unredacted occurrences of the credential in the bundle", n)
}
}
// A quiet unit (its journal read whole: no records in the window, exit 0)
// is only unavailable: it does not withhold the bundle.
func TestLogCollectQuietUnitIsOnlyUnavailable(t *testing.T) {
fakeUnitCommands(t, "-- No entries --")
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
dir := t.TempDir()
bundle := filepath.Join(dir, "bundle")
file := filepath.Join(dir, "daemon.log")
if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" local diagnostic\n"), 0600); err != nil {
t.Fatal(err)
}
command := fmt.Sprintf("log.collect -out '%s' -unit 'sw-blockvolume@v1.service' -log-file '%s'", bundle, file)
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout)
if code != 3 || strings.Contains(out.String(), "redaction not proven") {
t.Fatalf("exit %d %q %s", code, &out, &errout)
}
if raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")); err != nil || !bytes.Contains(raw, []byte("local diagnostic")) {
t.Fatalf("a quiet unit withheld the bundle: %v %q", err, raw)
}
}
@@ -77,26 +77,31 @@ func defaultBundleUnits(ctx context.Context) (bundleStrings, error) {
func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) {
if len(units) == 0 && len(pids) == 0 {
b.add("startup-flags.json", nil, errors.New("no service unit or local process selected"))
b.addSource("startup-flags.json", nil, errors.New("no service unit or local process selected"), true)
}
for i, u := range units {
flags, err := bundleCommand(ctx, "systemctl", "show", "--property=ExecStart", "--value", "--", u)
b.add(fmt.Sprintf("unit-%03d-flags.txt", i+1), flags, err)
raw, err := bundleCommand(ctx, "journalctl", "--no-pager", "--utc", "--output=short-iso-precise", "--since="+b.Since.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--until="+b.Until.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--unit="+u)
b.addCommand(fmt.Sprintf("unit-%03d-flags.txt", i+1), flags, err, err)
raw, cmdErr := bundleCommand(ctx, "journalctl", "--no-pager", "--utc", "--output=short-iso-precise", "--since="+b.Since.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--until="+b.Until.UTC().Format("2006-01-02 15:04:05.000000 UTC"), "--unit="+u)
b.discover(raw)
err = cmdErr
if err == nil {
// The whole output was discovered: a window with no records is
// only unavailable, not unproven.
raw, err = recentBundleLog(raw, b.Since, b.Until)
}
b.add(fmt.Sprintf("unit-%03d.log", i+1), raw, err)
b.addCommand(fmt.Sprintf("unit-%03d.log", i+1), raw, cmdErr, err)
}
for i, pid := range pids {
var raw []byte
var err error
gone := false // the process does not exist: nothing to discover
if runtime.GOOS != "linux" {
err = errors.New("process startup arguments require this Linux host")
} else {
f, e := os.Open("/proc/" + pid + "/cmdline")
err = e
gone = errors.Is(e, os.ErrNotExist)
if err == nil {
raw, err = io.ReadAll(io.LimitReader(f, bundleSourceLimit+1))
f.Close()
@@ -113,9 +118,16 @@ func (b *logBundle) collectLocal(ctx context.Context, units, pids []string) {
if err == nil {
data, err = json.Marshal(strings.Split(strings.TrimRight(string(raw), "\x00"), "\x00"))
}
name := fmt.Sprintf("process-%03d-flags.json", i+1)
// A process that is gone, or an empty command line (a kernel thread),
// holds nothing to discover; any other failure left the arguments
// unread (over the bound, unreadable, not this Linux host).
if err != nil && !gone && !(len(raw) == 0 && err.Error() == "process has no startup arguments") {
b.unproven(name)
}
if err != nil {
err = errors.New("process startup arguments unavailable")
}
b.add(fmt.Sprintf("process-%03d-flags.json", i+1), data, err)
b.addSource(name, data, err, true)
}
}
@@ -24,6 +24,9 @@ type bundleRedactor struct {
secrets map[string]bool
overflow bool
replacer *strings.Replacer
// collided: two keys of one JSON object sanitized to the same key in
// the value being redacted; that value's redaction is not proven.
collided bool
}
func bundleSensitiveKey(k string) bool {
@@ -61,13 +64,23 @@ func (r *bundleRedactor) remember(s string) {
func (r *bundleRedactor) jsonValue(v any) any {
switch x := v.(type) {
case map[string]any:
// A key can carry a known credential too: keys are redacted like
// text. Two keys that then collide are not told apart (a suffix
// could itself be a credential): the value is refused.
out := make(map[string]any, len(x))
for k, value := range x {
if bundleSensitiveKey(k) {
x[k] = bundleRedacted
value = bundleRedacted
} else {
x[k] = r.jsonValue(value)
value = r.jsonValue(value)
}
key := r.redactText(k)
if _, taken := out[key]; taken {
r.collided = true
}
out[key] = value
}
return out
case []any:
for i, value := range x {
if s, ok := value.(string); ok && strings.HasPrefix(s, "-") {
@@ -215,6 +228,15 @@ func (r *bundleRedactor) rememberValue(v any) {
}
}
}
// redactChecked is redact, and false when the redaction is not proven (two
// JSON keys collided once sanitized): the caller then writes nothing of it.
func (r *bundleRedactor) redactChecked(raw []byte) ([]byte, bool) {
r.collided = false
clean := r.redact(raw)
return clean, !r.collided
}
func (r *bundleRedactor) redact(raw []byte) []byte {
var v any
if bundleDecodeJSON(raw, &v) == nil {
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"github.com/seaweedfs/seaweed-block/core/rpc/control"
"google.golang.org/grpc"
@@ -12,6 +13,7 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"runtime"
"strings"
"sync"
"sync/atomic"
@@ -531,3 +533,253 @@ func TestLogCollectUsesOneInventoryForChecksAndVolumeArtifacts(t *testing.T) {
}
}
}
// A time budget spent before the declared log files are read never cuts
// their credential discovery: a credential one file names (a flag) is
// redacted where another file repeats it.
func TestLogCollectSpentBudgetStillDiscoversEveryLogFile(t *testing.T) {
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
dir := t.TempDir()
bundle := filepath.Join(dir, "bundle")
stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000")
const secret = "spent-budget-planted-55120"
opaque := filepath.Join(dir, "opaque.log")
flags := filepath.Join(dir, "flags.log")
if err := os.WriteFile(opaque, []byte(stamp+" opaque "+secret+"\n"), 0600); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(flags, []byte(stamp+" --password="+secret+"\n"), 0600); err != nil {
t.Fatal(err)
}
command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(opaque), filepath.ToSlash(flags))
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-timeout", "1ns", "-c", command}, &out, &errout)
if code != 3 {
t.Fatalf("exit %d %s %s", code, &out, &errout)
}
raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log"))
if err != nil || !bytes.Contains(raw, []byte("opaque")) {
t.Fatalf("the first log file was not collected: %v %q", err, raw)
}
if n := bundleOccurrences(t, bundle, secret); n != 0 {
t.Fatalf("%d unredacted occurrences of the credential in the bundle", n)
}
}
// bundleOccurrences counts secret over every byte of every file in the bundle.
func bundleOccurrences(t *testing.T, bundle, secret string) int {
t.Helper()
n := 0
err := filepath.WalkDir(bundle, func(p string, d os.DirEntry, err error) error {
if err != nil || d.IsDir() {
return err
}
raw, err := os.ReadFile(p)
n += bytes.Count(raw, []byte(secret))
return err
})
if err != nil {
t.Fatal(err)
}
return n
}
// collectUnproven runs log.collect over a small opaque log that repeats
// secret and the given extra arguments, and checks the bundle holds only its
// manifest, marked not proven, and no byte carrying secret.
func collectUnproven(t *testing.T, secret string, extra string) (stdout string) {
t.Helper()
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
dir := t.TempDir()
bundle := filepath.Join(dir, "bundle")
opaque := filepath.Join(dir, "opaque.log")
if err := os.WriteFile(opaque, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" opaque "+secret+"\n"), 0600); err != nil {
t.Fatal(err)
}
extra = strings.ReplaceAll(extra, "DIR", filepath.ToSlash(dir))
command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' %s", filepath.ToSlash(bundle), filepath.ToSlash(opaque), extra)
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout)
if code != 3 || !strings.Contains(out.String(), "redaction not proven") {
t.Fatalf("exit %d %q %s", code, &out, &errout)
}
entries, err := os.ReadDir(bundle)
if err != nil {
t.Fatal(err)
}
for _, e := range entries {
if e.Name() != "manifest.json" {
t.Errorf("artifact %s written although redaction is not proven", e.Name())
}
}
if n := bundleOccurrences(t, bundle, secret); n != 0 {
t.Fatalf("%d unredacted occurrences of the credential in the bundle", n)
}
return out.String()
}
// A declared log file over its 4 MiB bound is the only source naming a
// credential another file repeats: it is never read whole, so nothing is written.
func TestLogCollectOversizedDeclaredFileWithholdsEveryArtifact(t *testing.T) {
const secret = "oversized-planted-31744"
dir := t.TempDir()
big := filepath.Join(dir, "flags.log")
stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000")
if err := os.WriteFile(big, []byte(stamp+" --password="+secret+"\n"+strings.Repeat("x", 5<<20)+"\n"), 0600); err != nil {
t.Fatal(err)
}
collectUnproven(t, secret, fmt.Sprintf("-log-file '%s'", filepath.ToSlash(big)))
}
// A declared log file that is not text is refused before discovery: its
// discovery did not complete.
func TestLogCollectRefusedDeclaredFileWithholdsEveryArtifact(t *testing.T) {
dir := t.TempDir()
bad := filepath.Join(dir, "binary.log")
if err := os.WriteFile(bad, []byte{0xff, 0xfe, 0x00, '\n'}, 0600); err != nil {
t.Fatal(err)
}
collectUnproven(t, "refused-planted-90215", fmt.Sprintf("-log-file '%s'", filepath.ToSlash(bad)))
}
// A declared log file that does not exist holds nothing to discover: it is
// unavailable, and the others are still written, redacted.
func TestLogCollectMissingDeclaredFileIsOnlyUnavailable(t *testing.T) {
addr, closeMaster := startInspectionMaster(t)
defer closeMaster()
dir := t.TempDir()
bundle := filepath.Join(dir, "bundle")
file := filepath.Join(dir, "daemon.log")
if err := os.WriteFile(file, []byte(time.Now().UTC().Format("2006/01/02 15:04:05.000000")+" local diagnostic\n"), 0600); err != nil {
t.Fatal(err)
}
command := fmt.Sprintf("log.collect -out '%s' -log-file '%s' -log-file '%s'", filepath.ToSlash(bundle), filepath.ToSlash(file), filepath.ToSlash(filepath.Join(dir, "no-such.log")))
var out, errout bytes.Buffer
code := run([]string{"shell", "-master", addr, "-timeout", "1m", "-c", command}, &out, &errout)
if code != 3 || strings.Contains(out.String(), "redaction not proven") {
t.Fatalf("exit %d %q %s", code, &out, &errout)
}
if raw, err := os.ReadFile(filepath.Join(bundle, "file-001.log")); err != nil || !bytes.Contains(raw, []byte("local diagnostic")) {
t.Fatalf("the readable log was not written: %v %q", err, raw)
}
}
// A declared process whose arguments cannot be read leaves its discovery
// incomplete (off Linux they cannot be read at all); a process that is gone
// holds nothing to discover and is only unavailable.
func TestLogCollectUnreadablePIDWithholdsEveryArtifact(t *testing.T) {
if runtime.GOOS == "linux" {
t.Skip("off Linux a process's arguments cannot be read; on Linux a gone process is only unavailable")
}
collectUnproven(t, "pid-planted-41102", "-pid 1")
}
// The names printed for skipped sources are sanitized like the manifest: a
// credential equal to a generated name is not printed.
func TestLogCollectSkippedNamesArePrintedSanitized(t *testing.T) {
dir := t.TempDir()
flags := filepath.Join(dir, "flags.log")
stamp := time.Now().UTC().Format("2006/01/02 15:04:05.000000")
if err := os.WriteFile(flags, []byte(stamp+" --password=file-003.log\n"), 0600); err != nil {
t.Fatal(err)
}
bad := filepath.Join(dir, "binary.log") // refused before discovery: file-003.log is skipped
if err := os.WriteFile(bad, []byte{0xff, 0xfe, 0x00, '\n'}, 0600); err != nil {
t.Fatal(err)
}
out := collectUnproven(t, "label-planted-27719", fmt.Sprintf("-log-file '%s' -log-file '%s'", filepath.ToSlash(flags), filepath.ToSlash(bad)))
if strings.Contains(out, "file-003.log") {
t.Fatalf("a known credential was printed as a skipped name: %q", out)
}
}
// Unproven redaction replaces every free-form error in the manifest, also
// on entries that hold no data.
func TestLogCollectUnprovenManifestKeepsOnlyFixedErrors(t *testing.T) {
const secret = "error-planted-58810"
b := logBundle{Version: 1}
b.add("cluster.json", nil, errors.New("request failed: "+secret))
b.unproven("file-001.log")
bundle := filepath.Join(t.TempDir(), "bundle")
if err := b.write(bundle); err != nil {
t.Fatal(err)
}
if n := bundleOccurrences(t, bundle, secret); n != 0 {
t.Fatalf("%d occurrences of a free-form error in the unproven manifest", n)
}
}
// A known credential used as a JSON object key is redacted too, and the
// output stays valid JSON.
func TestLogCollectRedactsKnownCredentialsInJSONKeys(t *testing.T) {
const secret = "key-planted-77031"
r := &bundleRedactor{secrets: map[string]bool{}}
r.discover([]byte("--password=" + secret))
out := r.redact([]byte(`{"` + secret + `":"opaque","other":{"` + secret + `":1}}`))
if bytes.Contains(out, []byte(secret)) || !json.Valid(out) {
t.Fatalf("redacted JSON: %s", out)
}
}
// Two JSON keys that collide once sanitized are not told apart by a suffix
// (the suffix could itself be a credential): that artifact is withheld, and
// no byte of the bundle carries any of the known credentials.
func TestLogCollectCollidingJSONKeysAreWithheld(t *testing.T) {
creds := []string{"alphaAAA", "betaBBBB", "#2"}
b := logBundle{Version: 1}
for _, c := range creds {
b.discover([]byte("--password=" + c))
}
b.add("cluster.json", []byte(`{"alphaAAA":1,"betaBBBB":2,"plain":3}`), nil)
bundle := filepath.Join(t.TempDir(), "bundle")
if err := b.write(bundle); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(bundle, "cluster.json")); !os.IsNotExist(err) {
t.Fatal("an artifact whose keys collided once sanitized was written")
}
for _, c := range creds {
if n := bundleOccurrences(t, bundle, c); n != 0 {
t.Fatalf("%d occurrences of the known credential %q in the bundle", n, c)
}
}
}
// Many keys that all sanitize to one (65,536 keys of a and b, both known)
// stop at the first collision: bounded work, and the artifact is withheld.
func TestLogCollectManyCollidingJSONKeysStopAtTheFirst(t *testing.T) {
b := logBundle{Version: 1}
b.discover([]byte("--password=a"))
b.discover([]byte("--password=b"))
var obj strings.Builder
obj.WriteByte('{')
for i := 0; i < 1<<16; i++ {
if i > 0 {
obj.WriteByte(',')
}
obj.WriteByte('"')
for bit := 15; bit >= 0; bit-- {
if i>>bit&1 == 1 {
obj.WriteByte('b')
} else {
obj.WriteByte('a')
}
}
obj.WriteString(`":1`)
}
obj.WriteByte('}')
b.add("cluster.json", []byte(obj.String()), nil)
bundle := filepath.Join(t.TempDir(), "bundle")
started := time.Now()
if err := b.write(bundle); err != nil {
t.Fatal(err)
}
if d := time.Since(started); d > 30*time.Second {
t.Fatalf("sanitizing colliding keys took %s", d)
}
if _, err := os.Stat(filepath.Join(bundle, "cluster.json")); !os.IsNotExist(err) {
t.Fatal("an artifact whose keys collided once sanitized was written")
}
}
@@ -264,6 +264,16 @@ type fakeBlobs struct {
func newFakeBlobs() *fakeBlobs { return &fakeBlobs{data: map[string][]byte{}} }
func (b *fakeBlobs) HeadBlob(_ context.Context, fid string) (uint64, error) {
b.mu.Lock()
defer b.mu.Unlock()
d, ok := b.data[fid]
if !ok {
return 0, ErrBlobNotFound
}
return uint64(len(d)), nil
}
func (b *fakeBlobs) Put(_ context.Context, d []byte) (string, error) {
b.mu.Lock()
defer b.mu.Unlock()
@@ -318,6 +318,12 @@ func (h Head) Encode() ([]byte, error) {
return b, err
}
// ErrHeadNewerVersion refuses a HEAD written by a newer format version: a
// binary too old to read it, not damage. It wraps ErrMalformed, so every
// caller that refuses a malformed HEAD for good (Start among them) refuses
// this one the same way; its text names the cure.
var ErrHeadNewerVersion = fmt.Errorf("%w: HEAD written by a newer version: use a newer binary", ErrMalformed)
// DecodeHead parses canonical HEAD bytes for the volume whose VOLUME
// record carries volume; unknown fields and non-canonical bytes are
// refused, and so is a HEAD of another volume id (ErrIdentity): one left
@@ -327,6 +333,21 @@ func DecodeHead(b []byte, gen uint64, volume VolumeID) (Head, error) {
if volume.IsZero() {
return Head{}, errors.New("layout: DecodeHead needs the volume's id from its VOLUME")
}
// A version field is a later format's (v1.1 writes version 1 first):
// read it leniently and refuse the HEAD as newer, never as damaged.
var probe struct {
Version json.RawMessage `json:"version"`
}
if err := json.Unmarshal(b, &probe); err != nil {
return Head{}, fmt.Errorf("%w: HEAD: %v", ErrMalformed, err)
}
if probe.Version != nil {
var v uint64
if err := json.Unmarshal(probe.Version, &v); err != nil || v == 0 {
return Head{}, fmt.Errorf("%w: HEAD version %s", ErrMalformed, probe.Version)
}
return Head{}, fmt.Errorf("%w (version %d; this binary reads only the v1.0 format)", ErrHeadNewerVersion, v)
}
var d headDoc
dec := json.NewDecoder(bytes.NewReader(b))
dec.DisallowUnknownFields()
@@ -0,0 +1,50 @@
package layout
import (
"bytes"
"encoding/json"
"errors"
"strings"
"testing"
)
// A HEAD carrying a version field was written by a newer format (v1.1
// writes version 1 and its own fields). This reader answers that it is
// newer (ErrHeadNewerVersion, which wraps ErrMalformed so every final
// refusal stays final, and whose text names a newer binary, never
// corruption); a HEAD without the field decodes as before, and a version
// field that is not a positive number is malformed (not newer).
func TestHeadWithAVersionIsRefusedAsNewer(t *testing.T) {
h := idleHead()
b, err := h.Encode()
if err != nil {
t.Fatal(err)
}
if !bytes.HasPrefix(b, []byte(`{"volume_id"`)) {
t.Fatalf("setup: HEAD bytes %s", b)
}
// A newer HEAD at the top level: the version first, its own fields
// after the v1.0 ones.
newer := append([]byte(`{"version":1,`), b[1:len(b)-1]...)
newer = append(newer, []byte(`,"current_bytes":10,"ext":{"later":1}}`)...)
var top map[string]json.RawMessage
if err := json.Unmarshal(newer, &top); err != nil || top["current_bytes"] == nil || top["ext"] == nil || top["version"] == nil {
t.Fatalf("setup: the newer HEAD's top-level fields: %v %v", top, err)
}
_, err = DecodeHead(newer, 1, h.VolumeID)
if !errors.Is(err, ErrHeadNewerVersion) || !errors.Is(err, ErrMalformed) {
t.Fatalf("a HEAD of a newer version: %v; want ErrHeadNewerVersion, wrapping ErrMalformed", err)
}
if msg := err.Error(); !strings.Contains(msg, "written by a newer version: use a newer binary") || strings.Contains(msg, "corrupt") {
t.Fatalf("the refusal's text: %q", msg)
}
if _, err := DecodeHead(b, 1, h.VolumeID); err != nil {
t.Fatalf("a v1.0 HEAD: %v", err)
}
for _, v := range []string{`0`, `-1`, `"1"`, `1.5`} {
bad := append([]byte(`{"version":`+v+`,`), b[1:]...)
if _, err := DecodeHead(bad, 1, h.VolumeID); !errors.Is(err, ErrMalformed) || errors.Is(err, ErrHeadNewerVersion) {
t.Fatalf("version %s: %v; want ErrMalformed", v, err)
}
}
}
@@ -40,6 +40,9 @@ type VerifyOptions struct {
Depth string // DepthNames (default) or DepthFull
Orphans bool // also report unreachable own names (needs List)
List List
// Stat checks a chunk's presence and size without reading its body.
// In-memory callers may omit it and supply those bytes through Fetch.
Stat func(ctx context.Context, p string, expectedSize uint64) (found bool, err error)
}
// Finding is one problem found at Path (relative to <base>).
@@ -66,7 +69,9 @@ type verifier struct {
res VerifyResult
ownPool map[string]bool // reachable own names, by path relative to the volume
ownMeta map[string]bool
owners map[string]ownerID // VOLUME id per chunk owner, read once
owners map[string]ownerID // VOLUME id per chunk owner, read once
checked map[verifyChunkKey]bool // exact immutable chunk identities across all roots
geometry map[string]Geometry
ownID VolumeID
}
@@ -75,6 +80,12 @@ type ownerID struct {
ok bool
}
type verifyChunkKey struct {
owner VolumeID
index uint64
hash Hash
}
// Verify checks the canonical store directory vol under base; callers resolve
// logical names through the master before choosing VolumeDir(name, id).
func Verify(ctx context.Context, base, vol string, fetch Fetch, opts VerifyOptions) (VerifyResult, error) {
@@ -93,7 +104,7 @@ func Verify(ctx context.Context, base, vol string, fetch Fetch, opts VerifyOptio
if opts.Orphans && opts.List == nil {
return VerifyResult{}, errors.New("layout: verify orphans needs a list")
}
v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}}
v := &verifier{base: base, vol: vol, fetch: fetch, opts: opts, ownPool: map[string]bool{}, ownMeta: map[string]bool{}, owners: map[string]ownerID{}, checked: map[verifyChunkKey]bool{}, geometry: map[string]Geometry{}}
v.res.Complete = true
head, ok, err := v.head(ctx, vol)
if err != nil {
@@ -196,6 +207,7 @@ func (v *verifier) volumeID(ctx context.Context, vol string, report bool) (Volum
v.incomplete("VOLUME identity mismatch")
return VolumeID{}, false, nil
}
v.geometry[vol] = rec.Geometry
return rec.ID, true, nil
}
@@ -321,6 +333,11 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo
v.find(FindIdentity, p, fmt.Sprintf("names owner %s id %s; its VOLUME has %s", ref.Owner, ref.OwnerID, map[bool]string{true: o.id.String(), false: "none"}[o.ok]))
continue
}
key := verifyChunkKey{owner: ref.OwnerID, index: ref.Chunk.Index, hash: ref.Chunk.Hash}
if v.checked[key] {
continue
}
v.checked[key] = true
if v.opts.Depth == DepthFull {
if _, err := r.get(ctx, dir, ref.Chunk.Path(), ref.Chunk.Hash); err != nil {
if err := v.classify(p, err); err != nil {
@@ -329,8 +346,27 @@ func (v *verifier) chunks(ctx context.Context, r *Reader, seg Segment, count boo
}
continue
}
_, ok, err := v.fetch(ctx, path.Join(v.base, p))
var expectedSize uint64
if v.opts.Stat != nil {
g := v.geometry[dir]
if ref.Chunk.Index > (g.SizeBytes-1)/g.ChunkBytes {
v.find(FindCorrupt, p, "chunk index is outside its owner's VOLUME geometry")
continue
}
expectedSize = min(g.ChunkBytes, g.SizeBytes-ref.Chunk.Index*g.ChunkBytes)
}
var ok bool
var err error
if v.opts.Stat != nil {
ok, err = v.opts.Stat(ctx, path.Join(v.base, p), expectedSize)
} else {
_, ok, err = v.fetch(ctx, path.Join(v.base, p))
}
if err != nil {
if errors.Is(err, ErrCorrupt) {
v.find(FindCorrupt, p, err.Error())
continue
}
return fmt.Errorf("layout: read %s: %w", p, err)
}
if !ok {
@@ -87,6 +87,9 @@ func TestVolumeWriterRepositorySites(t *testing.T) {
"core/frontend/chunkstore/layout/verify.go volumeID VolumeName": 1,
"core/frontend/chunkstore/layout_create.go ReadVolumeRecord VolumeName": 1,
"core/frontend/chunkstore/layout_create.go CreateVolumeRecord VolumeName": 1,
// Read-only cache discriminator; the distinct-object verifier control
// proves VOLUME is observed once while HEAD is confirmed separately.
"core/frontend/chunkstore/layout_verify.go VerifyLayout VolumeName": 1,
}
got := map[string]int{}
root := filepath.Clean("../../../..")
@@ -51,13 +51,30 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve
}
s := &LayoutStore{f: f, b: b, root: path.Join(base, vol)}
opts.List = s.List
opts.Stat = s.verifyStat
// Keep the generation from the same lookup as the HEAD bytes walked by
// Verify. A later lookup must confirm every observed HEAD, including live
// dependent targets, before publishing absence/reachability findings.
heads := map[string]layout.Head{}
// Immutable metadata may be shared by several roots. Keep it for this
// pass, but never retain chunk bodies or cache mutable HEAD observations.
type metadataObject struct {
data []byte
found bool
}
metadata := map[string]metadataObject{}
fetch := func(ctx context.Context, p string) ([]byte, bool, error) {
if path.Base(p) != layout.HeadName {
return s.Fetch(ctx, p)
parts := strings.Split(strings.TrimPrefix(p, base+"/"), "/")
cacheable := len(parts) == 2 && parts[1] == layout.VolumeName || len(parts) == 3 && (parts[1] == layout.RootDir || parts[1] == layout.SegDir)
if cached, ok := metadata[p]; ok && cacheable {
return cached.data, cached.found, nil
}
data, found, err := s.Fetch(ctx, p)
if cacheable && err == nil {
metadata[p] = metadataObject{data, found}
}
return data, found, err
}
b, head, found, err := s.verifyHead(ctx, p)
heads[p] = head
@@ -103,6 +120,51 @@ func VerifyLayout(ctx context.Context, f Filer, base, vol string, opts layout.Ve
return res, nil
}
// verifyStat checks the filer binding and the needle's existence and size by
// HEAD. Reading and hashing the response body belongs to data depth.
func (s *LayoutStore) verifyStat(ctx context.Context, p string, expectedSize uint64) (bool, error) {
if !path.IsAbs(p) || path.Clean(p) != p || !strings.HasPrefix(p, path.Dir(s.root)+"/") {
return false, errors.New("chunkstore: object path outside the store base")
}
e, err := s.f.LookupEntry(ctx, path.Dir(p), path.Base(p))
if errors.Is(err, ErrNotFound) {
return false, nil
}
if err != nil {
return false, err
}
if e == nil || e.IsDirectory {
return false, fmt.Errorf("%w: %s is not a file", layout.ErrCorrupt, p)
}
if len(e.Chunks) == 0 {
if uint64(len(e.Content)) != expectedSize {
return false, fmt.Errorf("%w: inline size differs from VOLUME geometry for %s", layout.ErrCorrupt, p)
}
if e.Attributes != nil && e.Attributes.FileSize != uint64(len(e.Content)) {
return false, fmt.Errorf("%w: inline size mismatch for %s", layout.ErrCorrupt, p)
}
return true, nil
}
if len(e.Content) != 0 || len(e.Chunks) != 1 || e.Chunks[0] == nil || e.Chunks[0].Offset != 0 || e.Chunks[0].FileId == "" || e.Attributes == nil || e.Attributes.FileSize != e.Chunks[0].Size || e.Attributes.FileSize != expectedSize {
return false, fmt.Errorf("%w: invalid file binding or size for %s", layout.ErrCorrupt, p)
}
head, ok := s.b.(BlobHeaders)
if !ok {
return false, errors.New("chunkstore: verify needs needle HEAD support")
}
size, err := head.HeadBlob(ctx, e.Chunks[0].FileId)
if errors.Is(err, ErrBlobNotFound) {
return false, nil
}
if err != nil {
return false, err
}
if size != expectedSize {
return false, fmt.Errorf("%w: needle size differs from VOLUME geometry for %s", layout.ErrCorrupt, p)
}
return true, nil
}
// verifyHead preserves inline bytes for the kernel's malformed/identity
// diagnostics; an invalid envelope has no usable generation for confirmation.
func (s *LayoutStore) verifyHead(ctx context.Context, p string) ([]byte, layout.Head, bool, error) {
@@ -48,7 +48,7 @@ func verifyFixtureVolume(t *testing.T) (filerBlobs, layout.VolumeID) {
manifest := map[uint64]layout.Ref{}
putDir(t, f, path.Join("/blocks", layout.VolumeDir("v", id), "pool/0"))
for _, i := range []uint64{0, 5} {
d := []byte(strings.Repeat(string(rune('a'+i)), 64))
d := []byte(strings.Repeat(string(rune('a'+i)), 4*4096))
c := layout.NameChunk(i, d)
putFile(t, f, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), c.Path()), d)
manifest[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: c}
@@ -87,7 +87,7 @@ func TestVerifyLayoutThroughTheAdapter(t *testing.T) {
}
extra := layout.NameChunk(9, []byte("zz"))
putFile(t, fb.fakeFiler, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), extra.Path()), []byte("zz"))
c0 := layout.NameChunk(0, []byte(strings.Repeat("a", 64)))
c0 := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))
delete(fb.fakeFiler.entries, path.Join(path.Join("/blocks", layout.VolumeDir("v", id)), c0.Path()))
before = snapshotStore(fb)
r, err = VerifyLayout(ctx, fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Orphans: true})
@@ -190,7 +190,7 @@ func TestVerifyLayoutRequiresStableHeadForMissingAndOrphans(t *testing.T) {
fb, id := verifyFixtureVolume(t)
hp := path.Join("/blocks", layout.VolumeDir("v", id), layout.HeadName)
fb.fakeFiler.entries[hp].Extended = map[string][]byte{layoutKind: []byte("head"), layoutVolume: []byte(id.String()), layoutGen: []byte("1")}
c := layout.NameChunk(0, []byte(strings.Repeat("a", 64)))
c := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))
delete(fb.fakeFiler.entries, path.Join("/blocks", layout.VolumeDir("v", id), c.Path()))
extra := layout.NameChunk(9, []byte("orphan"))
putFile(t, fb.fakeFiler, path.Join("/blocks", layout.VolumeDir("v", id), extra.Path()), []byte("orphan"))
@@ -0,0 +1,85 @@
package chunkstore
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
)
// BlobHeaders checks needle existence and logical size without transferring its
// body to the client. The volume server may read small needles internally.
type BlobHeaders interface {
HeadBlob(context.Context, string) (uint64, error)
}
// HeadBlob resolves every replica with the same fresh-location absence rule as
// Get. A reachable copy is sufficient; only all fresh 404s prove absence.
func (c *SWFS) HeadBlob(ctx context.Context, fid string) (uint64, error) {
vid, needle, ok := strings.Cut(fid, ",")
if !ok || vid == "" || needle == "" || strings.ContainsAny(fid, "/\\?#% \r\n") {
return 0, fmt.Errorf("chunkstore: bad fid %q", fid)
}
urls, cached, err := c.lookupVolume(ctx, vid)
if err != nil {
return 0, err
}
for attempt := 0; ; attempt++ {
size, absent, readErr := c.headFromAll(ctx, urls, fid)
if readErr == nil {
return size, nil
}
c.mu.Lock()
delete(c.vidCache, vid)
c.mu.Unlock()
if absent && cached && attempt == 0 {
urls, _, err = c.lookupVolume(ctx, vid)
if err != nil {
return 0, err
}
continue
}
if absent {
readErr = &blobNotFoundError{readErr}
}
return 0, fmt.Errorf("chunkstore: HEAD %s: %w", fid, readErr)
}
}
func (c *SWFS) headFromAll(ctx context.Context, urls []string, fid string) (uint64, bool, error) {
absent := true
var last error
for _, host := range urls {
req, err := http.NewRequestWithContext(ctx, http.MethodHead, "http://"+host+"/"+fid, nil)
if err != nil {
return 0, false, err
}
resp, err := c.http.Do(req)
if err == nil {
closeErr := resp.Body.Close()
switch {
case closeErr != nil:
err = closeErr
case resp.StatusCode != http.StatusOK:
err = &blobStatusError{code: resp.StatusCode, host: host}
case resp.ContentLength < 0:
err = errors.New("chunkstore: needle HEAD has no size")
default:
return uint64(resp.ContentLength), false, nil
}
}
last = err
var se *blobStatusError
if !errors.As(err, &se) || se.code != http.StatusNotFound {
absent = false
}
}
if last == nil {
last = errors.New("chunkstore: needle HEAD has no locations")
absent = false
}
return 0, absent, last
}
var _ BlobHeaders = (*SWFS)(nil)
@@ -0,0 +1,80 @@
package chunkstore
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
)
func TestSWFSHeadBlobUsesOnlyHEADAndClassifiesAbsence(t *testing.T) {
for _, tc := range []struct {
name, length string
status int
missing bool
wantError bool
}{
{"exists", "4194304", 200, false, false},
{"missing", "0", 404, true, true},
{"unavailable", "0", 503, false, true},
{"size-unavailable", "", 200, false, true},
} {
t.Run(tc.name, func(t *testing.T) {
methods := make(chan string, 4)
vol := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
methods <- r.Method
if tc.length != "" {
w.Header().Set("Content-Length", tc.length)
}
w.WriteHeader(tc.status)
}))
defer vol.Close()
host := strings.TrimPrefix(vol.URL, "http://")
f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: host}}}}}}
c := startFakeFiler(t, f)
size, err := c.HeadBlob(context.Background(), "7,01abcdef")
if (err != nil) != tc.wantError || errors.Is(err, ErrBlobNotFound) != tc.missing || !tc.wantError && size != 4194304 {
t.Fatalf("size=%d err=%v", size, err)
}
if method := <-methods; method != http.MethodHead {
t.Fatalf("body request %s", method)
}
})
}
}
func TestSWFSHeadBlobRefreshesCachedMissingLocation(t *testing.T) {
stale := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }))
defer stale.Close()
live := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodHead {
t.Errorf("body request %s", r.Method)
}
w.Header().Set("Content-Length", "4096")
}))
defer live.Close()
f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: strings.TrimPrefix(live.URL, "http://")}}}}}}
c := startFakeFiler(t, f)
c.vidCache["7"] = []string{strings.TrimPrefix(stale.URL, "http://")}
size, err := c.HeadBlob(context.Background(), "7,01abcdef")
if err != nil || size != 4096 || f.volLookups != 1 {
t.Fatalf("size=%d err=%v fresh lookups=%d", size, err, f.volLookups)
}
}
func TestSWFSHeadBlobMixedReplicaFailureDoesNotProveAbsence(t *testing.T) {
missing := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) }))
defer missing.Close()
failed := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(503) }))
defer failed.Close()
f := &fakeFilerGRPC{lookupVol: &filerpb.LookupVolumeResponse{LocationsMap: map[string]*filerpb.Locations{"7": {Locations: []*filerpb.Location{{Url: strings.TrimPrefix(failed.URL, "http://")}, {Url: strings.TrimPrefix(missing.URL, "http://")}}}}}}
c := startFakeFiler(t, f)
_, err := c.HeadBlob(context.Background(), "7,01abcdef")
if err == nil || errors.Is(err, ErrBlobNotFound) {
t.Fatalf("mixed operational/404 answer: %v", err)
}
}
@@ -0,0 +1,429 @@
package chunkstore
import (
"context"
"errors"
"path"
"strings"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
func verifyBlobFixture(t *testing.T) (filerBlobs, layout.VolumeID) {
t.Helper()
fb, id := verifyFixtureVolume(t)
for p, e := range fb.fakeFiler.entries {
if !strings.Contains(p, "/pool/") || e.IsDirectory {
continue
}
fid, err := fb.fakeBlobs.Put(context.Background(), e.Content)
if err != nil {
t.Fatal(err)
}
e.Attributes = &filerpb.FuseAttributes{FileSize: uint64(len(e.Content))}
e.Chunks = []*filerpb.FileChunk{{FileId: fid, Size: uint64(len(e.Content))}}
e.Content = nil
}
return fb, id
}
func TestVerifyBindingsNeverReadsChunkBodies(t *testing.T) {
fb, id := verifyBlobFixture(t)
_, before, _ := fb.fakeBlobs.counts()
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
if err != nil || !res.Complete || len(res.Findings) != 0 || res.Chunks != 2 {
t.Fatalf("bindings: %+v, %v", res, err)
}
_, after, _ := fb.fakeBlobs.counts()
if after != before {
t.Fatalf("bindings read %d chunk bodies; want zero", after-before)
}
// Data depth must continue to fetch the two bodies and verify their hashes.
res, err = VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthFull})
_, full, _ := fb.fakeBlobs.counts()
if err != nil || !res.Complete || len(res.Findings) != 0 || full-after != 2 {
t.Fatalf("data: %+v, %v, body reads=%d", res, err, full-after)
}
// Same-size damage is invisible to bindings, but must be caught by data depth.
e := fb.fakeFiler.entries[path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path())]
fb.fakeBlobs.data[e.Chunks[0].FileId] = []byte(strings.Repeat("z", 4*4096))
res, err = VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthFull})
if err != nil || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt {
t.Fatalf("damaged data: %+v, %v", res, err)
}
}
func TestVerifyBindingsReportsMissingNeedleBehindPresentEntry(t *testing.T) {
fb, id := verifyBlobFixture(t)
dir := layout.VolumeDir("v", id)
n := layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))
e := fb.fakeFiler.entries[path.Join("/blocks", dir, n.Path())]
delete(fb.fakeBlobs.data, e.Chunks[0].FileId)
_, before, _ := fb.fakeBlobs.counts()
res, err := VerifyLayout(context.Background(), fb, "/blocks", dir, layout.VerifyOptions{Depth: layout.DepthNames})
_, after, _ := fb.fakeBlobs.counts()
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindMissing || after != before {
t.Fatalf("missing needle without body reads: %+v, %v, gets=%d", res, err, after-before)
}
}
type verifyNeedleFailure struct {
filerBlobs
err error
size uint64
}
func (f verifyNeedleFailure) HeadBlob(context.Context, string) (uint64, error) {
return f.size, f.err
}
func TestVerifyBindingsNeedleFailureAndSize(t *testing.T) {
fb, id := verifyBlobFixture(t)
injected := errors.New("needle service unavailable")
res, err := VerifyLayout(context.Background(), verifyNeedleFailure{filerBlobs: fb, err: injected}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
if !errors.Is(err, injected) || res.Complete || len(res.Findings) != 0 {
t.Fatalf("unavailable needle: %+v, %v", res, err)
}
res, err = VerifyLayout(context.Background(), verifyNeedleFailure{filerBlobs: fb, size: 32}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
if err != nil || !res.Complete || len(res.Findings) != 2 {
t.Fatalf("wrong needle sizes: %+v, %v", res, err)
}
for _, f := range res.Findings {
if f.Class != layout.FindCorrupt {
t.Fatalf("wrong-size class: %+v", f)
}
}
}
func TestVerifyDistinctChunksRetainHashAcrossSnapshots(t *testing.T) {
for _, depth := range []string{layout.DepthNames, layout.DepthFull} {
t.Run(depth, func(t *testing.T) {
fb, id := verifyBlobFixture(t)
dir := path.Join("/blocks", layout.VolumeDir("v", id))
missing := layout.NameChunk(0, []byte(strings.Repeat("z", 4*4096)))
root, segs, err := layout.Build(map[uint64]layout.Ref{0: {Owner: "v", OwnerID: id, Chunk: missing}})
if err != nil {
t.Fatal(err)
}
for n, b := range segs {
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b)
}
rn, raw, err := layout.NameRoot(root)
if err != nil {
t.Fatal(err)
}
putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw)
e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)]
h, err := layout.DecodeHead(e.Content, 0, id)
if err != nil {
t.Fatal(err)
}
h.Snapshots = map[string]layout.Snapshot{"older": {Root: rn}}
e.Content, err = h.Encode()
if err != nil {
t.Fatal(err)
}
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: depth})
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindMissing || res.Findings[0].Path != path.Join(layout.VolumeDir("v", id), missing.Path()) {
t.Fatalf("different content at the same owner/index: %+v, %v", res, err)
}
})
}
}
type verifyLookupCounter struct {
filerBlobs
reads map[string]int
}
func (f *verifyLookupCounter) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
f.reads[path.Join(dir, name)]++
return f.filerBlobs.LookupEntry(ctx, dir, name)
}
func TestVerifyBindingsChecksEachDistinctObjectOnce(t *testing.T) {
fb, id := verifyBlobFixture(t)
dir := path.Join("/blocks", layout.VolumeDir("v", id))
refs := map[uint64]layout.Ref{}
for _, i := range []uint64{0, 5} {
refs[i] = layout.Ref{Owner: "v", OwnerID: id, Chunk: layout.NameChunk(i, []byte(strings.Repeat(string(rune('a'+i)), 4*4096)))}
}
// This snapshot deliberately reaches the next shard; its volume covers it.
vp := path.Join(dir, layout.VolumeName)
volume, err := layout.DecodeVolume(fb.fakeFiler.entries[vp].Content)
if err != nil {
t.Fatal(err)
}
volume.SizeBytes = uint64(layout.ShardSize+2) * volume.ChunkBytes
fb.fakeFiler.entries[vp].Content, err = volume.Encode()
if err != nil {
t.Fatal(err)
}
index := uint64(layout.ShardSize + 1)
n := layout.NameChunk(index, []byte(strings.Repeat("s", 4*4096)))
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), []byte(strings.Repeat("s", 4*4096)))
refs[index] = layout.Ref{Owner: "v", OwnerID: id, Chunk: n}
root, segs, err := layout.Build(refs)
if err != nil {
t.Fatal(err)
}
for n, b := range segs {
if fb.fakeFiler.entries[path.Join(dir, n.Path())] == nil {
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b)
}
}
rn, raw, err := layout.NameRoot(root)
if err != nil {
t.Fatal(err)
}
putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw)
e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)]
h, err := layout.DecodeHead(e.Content, 0, id)
if err != nil {
t.Fatal(err)
}
h.Snapshots = map[string]layout.Snapshot{"s": {Root: rn}}
e.Content, err = h.Encode()
if err != nil {
t.Fatal(err)
}
f := &verifyLookupCounter{filerBlobs: fb, reads: map[string]int{}}
res, err := VerifyLayout(context.Background(), f, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
if err != nil || !res.Complete || len(res.Findings) != 0 || res.Roots != 2 {
t.Fatalf("shared snapshot objects: %+v, %v", res, err)
}
for p, count := range f.reads {
want := 1
if path.Base(p) == layout.HeadName {
want = 2
}
if count != want {
t.Errorf("%s: %d lookups; want %d", p, count, want)
}
}
for _, ref := range refs {
p := path.Join(dir, ref.Chunk.Path())
if f.reads[p] != 1 {
t.Errorf("reachable chunk %s: %d lookups", p, f.reads[p])
}
}
}
func TestVerifyBindingsChecksDeclaredSizesAndRefusals(t *testing.T) {
for _, mode := range []string{"size", "no-attributes", "offset", "empty-fid", "nil-chunk", "multiple-chunks", "directory", "mixed-content", "inline-size", "missing"} {
t.Run(mode, func(t *testing.T) {
fb, id := verifyBlobFixture(t)
p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path())
e := fb.fakeFiler.entries[p]
switch mode {
case "size":
e.Attributes.FileSize++
case "no-attributes":
e.Attributes = nil
case "offset":
e.Chunks[0].Offset = 1
case "empty-fid":
e.Chunks[0].FileId = ""
case "nil-chunk":
e.Chunks[0] = nil
case "multiple-chunks":
e.Chunks = append(e.Chunks, e.Chunks[0])
case "directory":
e.IsDirectory = true
case "mixed-content":
e.Content = []byte("mixed")
case "inline-size":
e.Chunks = nil
e.Content = []byte("short")
case "missing":
delete(fb.fakeFiler.entries, p)
}
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
want := layout.FindCorrupt
if mode == "missing" {
want = layout.FindMissing
}
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != want || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") {
t.Fatalf("%s: %+v, %v; want %s at %s", mode, res, err, want, p)
}
_, gets, _ := fb.fakeBlobs.counts()
if gets != 0 {
t.Fatalf("bindings read %d bodies", gets)
}
})
}
}
type verifyLookupFailure struct {
filerBlobs
err error
}
func (f verifyLookupFailure) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
if strings.Contains(dir, "/pool/") {
return nil, f.err
}
return f.filerBlobs.LookupEntry(ctx, dir, name)
}
func TestVerifyBindingsLookupFailureIsNotAMissingObject(t *testing.T) {
fb, id := verifyBlobFixture(t)
injected := errors.New("injected filer unavailable")
res, err := VerifyLayout(context.Background(), verifyLookupFailure{fb, injected}, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
if !errors.Is(err, injected) || res.Complete || len(res.Findings) != 0 {
t.Fatalf("lookup failure: %+v, %v", res, err)
}
}
type verifyPayloadCounter struct {
Filer
Blobs
payloads map[string]bool
payloadReads, metadataReads int
}
func (f *verifyPayloadCounter) HeadBlob(ctx context.Context, fid string) (uint64, error) {
return f.Blobs.(BlobHeaders).HeadBlob(ctx, fid)
}
func (f *verifyPayloadCounter) Get(ctx context.Context, fid string) ([]byte, error) {
if f.payloads[fid] {
f.payloadReads++
} else {
f.metadataReads++
}
return f.Blobs.Get(ctx, fid)
}
func TestVerifyBindingsProductionMetadataStillDecodes(t *testing.T) {
ctx := context.Background()
c, source := verifyProductionFixture(t)
target := newRef(t, "restored")
if _, err := c.Restore(ctx, source, "s", target); err != nil {
t.Fatal(err)
}
entries, err := c.f.ListEntries(ctx, path.Join(c.base, source.Dir(), layout.PoolDir, "0"), "", "", 0)
if err != nil {
t.Fatal(err)
}
f := &verifyPayloadCounter{Filer: c.f, Blobs: c.b, payloads: map[string]bool{}}
for _, e := range entries {
for _, chunk := range e.Chunks {
f.payloads[chunk.FileId] = true
}
}
if len(f.payloads) == 0 {
t.Fatal("production fixture has no blob-backed chunks")
}
for _, v := range []VolumeRef{source, target} {
res, err := VerifyLayout(ctx, f, c.base, v.Dir(), layout.VerifyOptions{Depth: layout.DepthNames})
if err != nil || !res.Complete || len(res.Findings) != 0 || res.Chunks != 1 {
t.Fatalf("%s bindings: %+v, %v", v.Name, res, err)
}
}
if f.payloadReads != 0 || f.metadataReads == 0 {
t.Fatalf("body reads: payload=%d metadata=%d; only manifests need body decoding", f.payloadReads, f.metadataReads)
}
res, err := VerifyLayout(ctx, f, c.base, target.Dir(), layout.VerifyOptions{Depth: layout.DepthFull})
if err != nil || !res.Complete || len(res.Findings) != 0 || f.payloadReads != 1 {
t.Fatalf("restore data: %+v, %v, payload reads=%d", res, err, f.payloadReads)
}
}
func TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry(t *testing.T) {
fb, id := verifyBlobFixture(t)
p := path.Join("/blocks", layout.VolumeDir("v", id), layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096))).Path())
e := fb.fakeFiler.entries[p]
e.Attributes.FileSize = 32
e.Chunks[0].Size = 32
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") {
t.Fatalf("self-consistent truncation: %+v, %v", res, err)
}
}
func TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume(t *testing.T) {
for _, mode := range []string{"tail", "short-tail", "outside"} {
t.Run(mode, func(t *testing.T) {
fb, id := verifyBlobFixture(t)
dir := path.Join("/blocks", layout.VolumeDir("v", id))
vp := path.Join(dir, layout.VolumeName)
volume, err := layout.DecodeVolume(fb.fakeFiler.entries[vp].Content)
if err != nil {
t.Fatal(err)
}
volume.SizeBytes = 5*volume.ChunkBytes + 4096
if mode == "outside" {
volume.SizeBytes = 5 * volume.ChunkBytes
}
fb.fakeFiler.entries[vp].Content, err = volume.Encode()
if err != nil {
t.Fatal(err)
}
p := path.Join(dir, layout.NameChunk(5, []byte(strings.Repeat("f", 4*4096))).Path())
// A valid tail has both a shortened needle and matching metadata.
e := fb.fakeFiler.entries[p]
fb.fakeBlobs.data[e.Chunks[0].FileId] = fb.fakeBlobs.data[e.Chunks[0].FileId][:4096]
e.Attributes.FileSize, e.Chunks[0].Size = 4096, 4096
if mode == "short-tail" {
e.Attributes.FileSize, e.Chunks[0].Size = 2048, 2048
}
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: layout.DepthNames})
if err != nil || !res.Complete {
t.Fatalf("%s: %+v, %v", mode, res, err)
}
if mode == "tail" {
if len(res.Findings) != 0 {
t.Fatalf("valid tail: %+v", res.Findings)
}
} else if len(res.Findings) != 1 || res.Findings[0].Class != layout.FindCorrupt || res.Findings[0].Path != strings.TrimPrefix(p, "/blocks/") {
t.Fatalf("%s: %+v", mode, res.Findings)
}
_, gets, _ := fb.fakeBlobs.counts()
if gets != 0 {
t.Fatalf("bindings read %d bodies", gets)
}
})
}
}
func TestVerifyDeduplicationNeverSkipsFullOwnerIdentity(t *testing.T) {
for _, depth := range []string{layout.DepthNames, layout.DepthFull} {
t.Run(depth, func(t *testing.T) {
fb, id := verifyBlobFixture(t)
wrong := id
wrong[15] ^= 1
if layout.VolumeDir("v", wrong) != layout.VolumeDir("v", id) {
t.Fatal("fixture needs an id8 collision")
}
ref := layout.Ref{Owner: "v", OwnerID: wrong, Chunk: layout.NameChunk(0, []byte(strings.Repeat("a", 4*4096)))}
root, segs, err := layout.Build(map[uint64]layout.Ref{0: ref})
if err != nil {
t.Fatal(err)
}
dir := path.Join("/blocks", layout.VolumeDir("v", id))
for n, b := range segs {
putFile(t, fb.fakeFiler, path.Join(dir, n.Path()), b)
}
rn, raw, err := layout.NameRoot(root)
if err != nil {
t.Fatal(err)
}
putFile(t, fb.fakeFiler, path.Join(dir, rn.Path()), raw)
e := fb.fakeFiler.entries[path.Join(dir, layout.HeadName)]
h, err := layout.DecodeHead(e.Content, 0, id)
if err != nil {
t.Fatal(err)
}
h.Snapshots = map[string]layout.Snapshot{"different-owner": {Root: rn}}
e.Content, err = h.Encode()
if err != nil {
t.Fatal(err)
}
res, err := VerifyLayout(context.Background(), fb, "/blocks", layout.VolumeDir("v", id), layout.VerifyOptions{Depth: depth})
if err != nil || !res.Complete || len(res.Findings) != 1 || res.Findings[0].Class != layout.FindIdentity {
t.Fatalf("id8 collision after a valid reference: %+v, %v", res, err)
}
})
}
}
@@ -1,6 +1,7 @@
package chunkstore
import (
"bytes"
"context"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"google.golang.org/protobuf/proto"
@@ -15,11 +16,15 @@ type verifyProductionStore struct {
Blobs
}
func (f verifyProductionStore) HeadBlob(ctx context.Context, fid string) (uint64, error) {
return f.Blobs.(BlobHeaders).HeadBlob(ctx, fid)
}
// Use the production creators, not a hand-written name-only directory: a
// restored image borrows the source's chunks while owning copied metadata.
func TestVerifyProductionLayoutCurrentAndRestored(t *testing.T) {
ctx := context.Background()
c, source, _, _ := cleanFixture(t)
c, source := verifyProductionFixture(t)
target := newRef(t, "restored")
if _, err := c.Restore(ctx, source, "s", target); err != nil {
t.Fatal(err)
@@ -58,7 +63,7 @@ func (f *verifyMovingDependent) LookupEntry(ctx context.Context, dir, name strin
}
func TestVerifyConfirmsDependentHeadBeforeReportingOrphans(t *testing.T) {
ctx := context.Background()
c, source, _, _ := cleanFixture(t)
c, source := verifyProductionFixture(t)
target := newRef(t, "restored")
if _, err := c.Restore(ctx, source, "s", target); err != nil {
t.Fatal(err)
@@ -80,3 +85,21 @@ func TestVerifyConfirmsDependentHeadBeforeReportingOrphans(t *testing.T) {
t.Fatalf("moving dependent: %+v %v reads=%d", r, err, f.reads)
}
}
// Unlike catalog-only fixtures, a verifier fixture stores full geometry-sized chunks.
func verifyProductionFixture(t *testing.T) (*BCatalog, VolumeRef) {
t.Helper()
c, err := NewBCatalog(NewMemFiler(), newFakeBlobs(), "/blocks")
if err != nil {
t.Fatal(err)
}
source := newRef(t, "source")
if _, err := c.CreateVolume(context.Background(), source, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
commitSnapshot(t, c, source, bytes.Repeat([]byte{7}, 4*4096), "s")
if err := c.f.CreateEntry(context.Background(), path.Join(c.base, source.Dir(), layout.PoolDir), &filerpb.Entry{Name: "0", IsDirectory: true}, false); err != nil {
t.Fatal(err)
}
return c, source
}
@@ -0,0 +1,113 @@
package durable_test
import (
"context"
"path"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/seaweedfs/seaweed-block/core/frontend"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
// writeCountingFiler counts every mutating filer call.
type writeCountingFiler struct {
*chunkstore.MemFiler
writes atomic.Int64
}
func (f *writeCountingFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
f.writes.Add(1)
return f.MemFiler.CreateEntry(ctx, dir, e, oExcl)
}
func (f *writeCountingFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
f.writes.Add(1)
return f.MemFiler.UpdateEntry(ctx, dir, e, expected)
}
func (f *writeCountingFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
f.writes.Add(1)
return f.MemFiler.DeleteEntry(ctx, dir, name, expected)
}
// countingStartStore counts the HEAD reads a holder's Start makes.
type countingStartStore struct {
layout.StartStore
reads *atomic.Int64
}
func (s countingStartStore) ReadHead(ctx context.Context) (layout.Head, bool, error) {
s.reads.Add(1)
return s.StartStore.ReadHead(ctx)
}
// A v1.0.x holder meeting a HEAD written by a newer format refuses it once
// and finally: its recovery answers the newer-version refusal (use a newer
// binary), the volume is not served, no Start is retried (the HEAD reads
// stay at one across a wait), and nothing is written to the filer.
func TestLayoutProviderRefusesANewerHeadOnceAndWritesNothing(t *testing.T) {
ctx := context.Background()
f := &writeCountingFiler{MemFiler: chunkstore.NewMemFiler()}
cat, err := chunkstore.NewBCatalog(f, &layoutProviderBlobs{blobs: map[string][]byte{}}, "/layout-test")
if err != nil {
t.Fatal(err)
}
id, err := layout.NewVolumeID()
if err != nil {
t.Fatal(err)
}
v := chunkstore.VolumeRef{Name: "v1", ID: id}
if _, err = cat.CreateVolume(ctx, v, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
dir := path.Join("/layout-test", v.Dir())
e, err := f.LookupEntry(ctx, dir, layout.HeadName)
if err != nil {
t.Fatal(err)
}
b := e.Content
e.Content = append(append([]byte(`{"version":1,`), b[1:len(b)-1]...), []byte(`,"current_bytes":10,"ext":{"later":1}}`)...)
if err := f.MemFiler.UpdateEntry(ctx, dir, e, nil); err != nil {
t.Fatal(err)
}
writes := f.writes.Load()
var reads atomic.Int64
view := newStubView(healthyProj(frontend.Identity{VolumeID: "v1", ReplicaID: "r1", Epoch: 1, EndpointVersion: 1}))
p, err := durable.NewDurableProvider(durable.ProviderConfig{Impl: durable.ImplWALStoreChunk, StorageRoot: t.TempDir(), NumBlocks: 64, BlockSize: 4096, ChunkBlocks: 4, ChunkHolder: "s/r1",
ChunkLayoutHeadFor: func(string) (layout.StartStore, error) {
st, err := cat.Store(v)
if err != nil {
return nil, err
}
return countingStartStore{StartStore: st, reads: &reads}, nil
},
ChunkLayoutRemoteFor: func(_ string, me layout.HolderID) (storage.ChunkRemote, error) {
return chunkstore.NewLayoutRemote(cat, v, me)
},
}, view)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = p.Close() })
if _, err := p.EnsureStorage("v1"); err != nil {
t.Fatal(err)
}
_, err = p.RecoverVolume(ctx, "v1")
if err == nil || !strings.Contains(err.Error(), "written by a newer version: use a newer binary") {
t.Fatalf("recovery over a newer HEAD: %v; want the newer-version refusal", err)
}
time.Sleep(500 * time.Millisecond) // a retry loop would read HEAD again
if n := reads.Load(); n != 1 {
t.Fatalf("%d HEAD reads; want one Start attempt, no retry", n)
}
if n := f.writes.Load() - writes; n != 0 {
t.Fatalf("%d filer writes; want none", n)
}
}
@@ -28,6 +28,7 @@ func TestFinalLayoutStartRefusalTable(t *testing.T) {
{"foreign volume", layout.ErrIdentity, true},
{"corrupt store", layout.ErrCorrupt, true},
{"malformed store", layout.ErrMalformed, true},
{"HEAD of a newer version", layout.ErrHeadNewerVersion, true},
{"missing VOLUME", layout.ErrMissing, true},
{"oversized HEAD", layout.ErrHeadTooLarge, true},
{"legacy store", chunkstore.ErrLegacyStore, true},
@@ -15,20 +15,41 @@ import (
type workspaceHeadBlobs struct{}
// workspaceHeadPuts counts blob uploads the HEAD reader attempts.
var workspaceHeadPuts atomic.Int32
func (workspaceHeadBlobs) Put(context.Context, []byte) (string, error) {
workspaceHeadPuts.Add(1)
return "", errors.New("HEAD reader must not upload")
}
func (workspaceHeadBlobs) Get(context.Context, string) ([]byte, error) {
return nil, errors.New("HEAD reader must not hydrate")
}
// headFiler counts HEAD lookups and can fail them (a filer that is down).
// headFiler counts HEAD lookups and can fail them (a filer that is down),
// and counts every create, update and delete attempted through it.
type headFiler struct {
*chunkstore.MemFiler
lookups atomic.Int32
writes atomic.Int32
fail error
}
func (f *headFiler) CreateEntry(ctx context.Context, dir string, e *filerpb.Entry, oExcl bool) error {
f.writes.Add(1)
return f.MemFiler.CreateEntry(ctx, dir, e, oExcl)
}
func (f *headFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
f.writes.Add(1)
return f.MemFiler.UpdateEntry(ctx, dir, e, expected)
}
func (f *headFiler) DeleteEntry(ctx context.Context, dir, name string, expected map[string][]byte) error {
f.writes.Add(1)
return f.MemFiler.DeleteEntry(ctx, dir, name, expected)
}
func (f *headFiler) LookupEntry(ctx context.Context, dir, name string) (*filerpb.Entry, error) {
f.lookups.Add(1)
if f.fail != nil {
@@ -143,6 +164,9 @@ func TestWorkspaceLayoutHEADRefusalsAndStates(t *testing.T) {
{name: "legacy content", alter: func(e *filerpb.Entry) {
e.Content = []byte(`{"format":1,"gen":9,"epoch":3,"holder":"node/r","remote_lsn":42}`)
}},
{name: "HEAD of a newer version", alter: func(e *filerpb.Entry) {
e.Content = append(append([]byte(`{"version":1,`), e.Content[1:len(e.Content)-1]...), []byte(`,"current_bytes":10,"ext":{"later":1}}`)...)
}, sentinel: layout.ErrHeadNewerVersion},
{name: "oversized inline HEAD", alter: func(e *filerpb.Entry) { e.Content = bytes.Repeat([]byte("x"), layout.MaxHeadBytes+1) }, sentinel: layout.ErrHeadTooLarge},
{name: "not found", absent: true, sentinel: layout.ErrHeadAbsent},
{name: "unavailable", down: true},
@@ -181,7 +205,13 @@ func TestWorkspaceLayoutHEADRefusalsAndStates(t *testing.T) {
if err != nil {
t.Fatal(err)
}
puts := workspaceHeadPuts.Load()
got, err := read(ctx, "v")
// The reader writes nothing, whatever it answers: no filer
// create, update or delete and no blob upload is attempted.
if n, p := f.writes.Load(), workspaceHeadPuts.Load()-puts; n != 0 || p != 0 {
t.Fatalf("the HEAD reader attempted %d filer writes and %d uploads; want none", n, p)
}
wantTime := int64(100e9)
if tc.name == "unknown mtime" || tc.name == "out-of-range mtime" {
wantTime = 0
@@ -361,6 +361,13 @@ func chunkErrorCode(err error) (int, string, bool) {
return http.StatusServiceUnavailable, codeHostSlotBusy, true
case errors.Is(err, storage.ErrChunkCaptureRefused):
return http.StatusServiceUnavailable, "capture_refused", true
case errors.Is(err, layout.ErrPrecondition):
// Last before default: a catalog transition (a snapshot delete) lost
// its conditional HEAD write to another writer (a cleaning's begin);
// nothing of it applied, and a retry reads HEAD again. Every other
// cause an error also carries (terminal, uncertain or retryable)
// decides first.
return http.StatusConflict, codeHeadConflict, true
default:
return http.StatusInternalServerError, codeInternal, false
}
@@ -15,6 +15,7 @@ import (
"github.com/seaweedfs/seaweed-block/core/engine"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
"github.com/seaweedfs/seaweed-block/core/frontend/durable"
"github.com/seaweedfs/seaweed-block/core/storage"
)
@@ -218,6 +219,14 @@ func TestStatusServer_ChunkErrorBodyIsTyped(t *testing.T) {
{fmt.Errorf("%w: %w", storage.ErrChunkReconciling, context.DeadlineExceeded), "reconciling", 409, true},
{fmt.Errorf("x: %w", storage.ErrChunkCASOutcomeUnknown), "outcome_unknown", 503, true},
{fmt.Errorf("x: %w", storage.ErrChunkHeadPrecondition), "head_conflict", 409, true},
{fmt.Errorf("x: %w", layout.ErrPrecondition), "head_conflict", 409, true}, // a raced catalog transition (snapshot delete)
// The precondition is the last cause to decide: joined with any
// terminal one, that one is reported.
{errors.Join(storage.ErrChunkLayerClosed, layout.ErrPrecondition), "closing", 503, false},
{errors.Join(storage.ErrChunkLayerDetached, layout.ErrPrecondition), "closing", 409, false},
{errors.Join(errFrozenDetachUnsupported, layout.ErrPrecondition), "frozen_detach_unsupported", 409, false},
{errors.Join(storage.ErrInvalidFreezeBudget, layout.ErrPrecondition), "invalid_freeze_budget", 400, false},
{errors.Join(durable.ErrNotChunkVolume, layout.ErrPrecondition), "not_chunk_volume", 409, false},
{fmt.Errorf("save: %w", storage.ErrCutCOWAborted), "cut_aborted", 503, true},
// Local capacity abort cancels the in-flight remote PUT.
{errors.Join(storage.ErrCutCOWAborted, storage.ErrChunkRemoteUnavailable, context.Canceled, errors.New("storage: saver capacity")), "cut_aborted", 503, true},
@@ -0,0 +1,138 @@
package volume
import (
"context"
"errors"
"net/http"
"sync"
"testing"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/filerpb"
"github.com/seaweedfs/seaweed-block/core/frontend/chunkstore/layout"
)
// racingHeadFiler runs between, before each HEAD update it forwards, while
// armed: another writer's HEAD update landing between a transition's HEAD
// read and its conditional write. times bounds how many updates it races
// (-1: every one).
type racingHeadFiler struct {
*adapterManifestFiler
mu sync.Mutex
times int
between func()
busy bool
}
func (f *racingHeadFiler) UpdateEntry(ctx context.Context, dir string, e *filerpb.Entry, expected map[string][]byte) error {
f.mu.Lock()
run := !f.busy && f.times != 0 && e.GetName() == layout.HeadName && f.between != nil
if run {
f.busy = true
if f.times > 0 {
f.times--
}
}
f.mu.Unlock()
if run {
f.between() // its own HEAD update is forwarded unraced (busy)
f.mu.Lock()
f.busy = false
f.mu.Unlock()
}
return f.adapterManifestFiler.UpdateEntry(ctx, dir, e, expected)
}
// deleteRaceFixture is a live volume, held by me, with snapshot "a", and a
// filer that can race its HEAD updates.
func deleteRaceFixture(t *testing.T) (context.Context, *racingHeadFiler, *chunkstore.BCatalog, chunkstore.VolumeRef, layout.HolderID) {
t.Helper()
ctx := context.Background()
f := &racingHeadFiler{adapterManifestFiler: &adapterManifestFiler{Filer: chunkstore.NewMemFiler(), blobs: map[string][]byte{}}}
cat, err := chunkstore.NewBCatalog(f, f, "/chunks")
if err != nil {
t.Fatal(err)
}
id, _ := layout.ParseVolumeID("00112233445566778899aabbccddeeff")
ref := chunkstore.VolumeRef{Name: "v1", ID: id}
if _, err := cat.CreateVolume(ctx, ref, layout.Geometry{SizeBytes: 64 * 4096, BlockSize: 4096, ChunkBytes: 4 * 4096}); err != nil {
t.Fatal(err)
}
h, _, err := cat.ReadHead(ctx, ref)
if err != nil {
t.Fatal(err)
}
me := layout.HolderID{Epoch: 1, Holder: "a", ClaimID: "k"}
h.Epoch, h.Holder, h.ClaimID, h.State = me.Epoch, me.Holder, me.ClaimID, layout.StateLive
h.Snapshots = map[string]layout.Snapshot{"a": {Root: layout.RootName{Hash: layout.Sum([]byte("root"))}}}
s, _ := cat.Store(ref)
if err := s.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
t.Fatal(err)
}
return ctx, f, cat, ref, me
}
// The holder's cleaning begins (a HEAD update) between a snapshot delete's
// HEAD read and its conditional write. The delete is refused as
// head_conflict (409, retryable), never internal; HEAD keeps the snapshot
// (nothing of the delete applied); a retry completes the delete.
func TestSnapshotDeleteRacedByACleanBeginIsAHeadConflict(t *testing.T) {
ctx, f, cat, ref, me := deleteRaceFixture(t)
s, _ := cat.Store(ref)
f.mu.Lock()
f.times, f.between = 1, func() {
if _, err := layout.RunBeginClean(ctx, s, me, "clean-1"); err != nil {
t.Errorf("the racing clean-begin: %v", err)
}
}
f.mu.Unlock()
p := &fakeChunkProvider{}
ctl := NewChunkControl(p, cat, ref)
_, err := ctl.DeleteSnapshot(ctx, "v1", "a")
if !errors.Is(err, layout.ErrPrecondition) {
t.Fatalf("setup: the raced delete: %v; want the HEAD precondition", err)
}
if status, code, retryable := chunkErrorCode(err); status != http.StatusConflict || code != codeHeadConflict || !retryable {
t.Fatalf("a raced delete maps to %d %q retryable=%v; want 409 head_conflict retryable", status, code, retryable)
}
h, _, err := cat.ReadHead(ctx, ref)
if err != nil {
t.Fatal(err)
}
if _, ok := h.Snapshots["a"]; !ok || h.Activity.Kind != layout.ActClean || len(p.kicks) != 0 {
t.Fatalf("after the refused delete: snapshots %v, activity %v, kicks %v; want the snapshot kept, the cleaning's activity, no kick", h.Snapshots, h.Activity, p.kicks)
}
if _, err := ctl.DeleteSnapshot(ctx, "v1", "a"); err != nil {
t.Fatalf("the retry: %v", err)
}
h, _, err = cat.ReadHead(ctx, ref)
if _, still := h.Snapshots["a"]; err != nil || still {
t.Fatalf("after the retry: %v %v; want the snapshot gone", h.Snapshots, err)
}
}
// A conflict that persists (every attempt raced) stays head_conflict: the
// operator sees a retryable conflict, never an internal error.
func TestSnapshotDeleteUnderAPersistentConflictIsNeverInternal(t *testing.T) {
ctx, f, cat, ref, _ := deleteRaceFixture(t)
s, _ := cat.Store(ref)
f.mu.Lock()
f.times, f.between = -1, func() {
h, _, err := s.ReadHead(ctx)
if err != nil {
t.Errorf("racing read: %v", err)
return
}
if err := s.UpdateHead(ctx, h.Gen, h, layout.CauseCommit); err != nil {
t.Errorf("racing write: %v", err)
}
}
f.mu.Unlock()
ctl := NewChunkControl(&fakeChunkProvider{}, cat, ref)
for attempt := 0; attempt < 3; attempt++ {
_, err := ctl.DeleteSnapshot(ctx, "v1", "a")
if status, code, retryable := chunkErrorCode(err); err == nil || status != http.StatusConflict || code != codeHeadConflict || !retryable {
t.Fatalf("attempt %d under a persistent conflict: %v -> %d %q retryable=%v; want 409 head_conflict retryable", attempt, err, status, code, retryable)
}
}
}
@@ -0,0 +1,411 @@
package storage
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"syscall"
"testing"
"time"
)
const k3ReplayPath = "SWBLOCK_TEST_START_REPLAY_PATH"
const k3ReplayPoint = "SWBLOCK_TEST_START_REPLAY_POINT"
const k3ReplayBlocks = 128
type k3ReplayRecord struct {
lba uint32
blocks int
first, last uint64
}
type k3ReplayCut struct {
Record int
Block int
} // Block 0 = completed record; >0 = inside batch
// A private typed IPC witness, not a product log line or a timed guess.
type k3ReplayWitness struct {
Record, Block int
AppliedLSN, BlockedLSN uint64
}
func k3ReplayRecords() []k3ReplayRecord {
var out []k3ReplayRecord
var lsn uint64
for i := 0; i < 10; i++ {
r := k3ReplayRecord{lba: 7, blocks: 1, first: lsn + 1}
if i%2 != 0 {
r.lba, r.blocks = uint32((i/2)%3)*16, 8
}
lsn += uint64(r.blocks)
r.last = lsn
out = append(out, r)
}
return out
}
func k3ReplayData(record int, lba uint32) []byte {
b := make([]byte, 4096)
for i := range b {
b[i] = byte((record+1)*37 + int(lba)*11 + i*13 + i/251)
}
return b
}
func k3ReplaySeed(t *testing.T, path string, mode WMode) ([][]byte, uint64) {
t.Helper()
s, err := createMappedWALStoreV3ForTest(path, k3ReplayBlocks, 4096, 1<<20, mode, 8)
if err != nil {
t.Fatal(err)
}
owned := true
t.Cleanup(func() {
if !owned {
return
}
checkpoint := s.CheckpointLSN()
crashRecoveryHardeningStore(t, s)
owned = false
if os.Getenv("SWBLOCK_TEST_REPLAY_SEED_FAILURE") == "1" {
_, err := s.fd.WriteAt([]byte{0}, 0)
if !errors.Is(err, os.ErrClosed) || s.v3.ownedMap != nil || checkpoint != 0 {
t.Errorf("failed seed still owns resources or checkpointed: %v cp=%d", err, checkpoint)
return
}
fmt.Println("seed failure resources released; checkpoint=0")
}
})
// Stopping the flusher does not remove a production replay interleaving:
// RecoverContext holds s.mu for writing throughout replay; a flusher must
// acquire its read lock before taking the dirty-map snapshot. Chunk startup
// also keeps draining held until the chunk layer attaches.
s.DisableAutoFlushForRecoveryTest() // stop before any write; the image must need replay
expected := make([][]byte, k3ReplayBlocks)
for i := range expected {
expected[i] = make([]byte, 4096)
}
var ack uint64
for i, r := range k3ReplayRecords() {
blocks := make([][]byte, r.blocks)
for j := range blocks {
blocks[j] = k3ReplayData(i, r.lba+uint32(j))
}
if r.blocks == 1 {
_, err = s.Write(r.lba, blocks[0])
} else {
_, err = s.WriteBatch(r.lba, blocks)
}
if err != nil {
t.Fatal(err)
}
if ack, err = s.Sync(); err != nil || ack != r.last {
t.Fatalf("ack=%d want=%d: %v", ack, r.last, err)
}
if os.Getenv("SWBLOCK_TEST_REPLAY_SEED_FAILURE") == "1" {
t.Fatal("forced seed failure after acknowledged write")
}
for j, b := range blocks {
expected[int(r.lba)+j] = b
}
}
if s.CheckpointLSN() != 0 {
t.Fatal("seed checkpointed: the test would not prove WAL replay")
}
crashRecoveryHardeningStore(t, s) // no clean stop, no extent drain
owned = false
return expected, ack
}
func k3ReplayCopy(t *testing.T, source, target string) {
t.Helper()
for _, suffix := range []string{"", ".chunkmap"} {
in, err := os.Open(source + suffix)
if err != nil {
t.Fatal(err)
}
out, err := os.OpenFile(target+suffix, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
if err != nil {
in.Close()
t.Fatal(err)
}
_, err = io.Copy(out, in)
if err == nil {
err = out.Sync()
}
err = errors.Join(err, in.Close(), out.Close())
if err != nil {
t.Fatal(err)
}
}
}
func k3ReplayChild(t *testing.T, path string, cut k3ReplayCut) {
t.Helper()
s, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
if s.CheckpointLSN() != 0 {
t.Fatal("child has no WAL-only image")
}
records := k3ReplayRecords()
target := records[cut.Record]
if cut.Block < 0 || cut.Block >= target.blocks {
t.Fatal("invalid replay cut", cut)
}
emit := func(w k3ReplayWitness) {
if err := json.NewEncoder(os.Stdout).Encode(w); err != nil {
panic(err)
}
}
now := time.Unix(0, 0)
ctx := context.WithValue(context.Background(), recoveryClockKey{}, func(RecoveryPhase) time.Time {
now = now.Add(2 * time.Second) // expose every completed record, without sleeping
return now
})
ctx = WithRecoveryProgress(ctx, func(phase RecoveryPhase, done uint64) {
if phase != RecoveryReplay || os.Getenv("SWBLOCK_TEST_START_REPLAY_SKIP_POINT") == "1" {
return
}
if cut.Block == 0 && done == uint64(cut.Record+1) {
var applied uint64
for _, e := range s.dm.snapshot() {
applied = max(applied, e.LSN)
}
if applied != target.last {
panic("record progress does not match the applied WAL prefix")
}
emit(k3ReplayWitness{Record: cut.Record, AppliedLSN: applied})
select {} // parent kills this process before recovery can publish/serve
}
if cut.Block == 0 || done != uint64(cut.Record) {
return
}
blocked := target.lba + uint32(cut.Block)
prior := blocked - 1
// The preceding record's progress callback runs AFTER dirty-map clear.
// Hold only the shard the target block will enter; the earlier blocks of
// this multi-block record can still be replayed by the real product loop.
shard := s.dm.shard(uint64(blocked))
if shard == s.dm.shard(uint64(prior)) {
panic("mid-record witness shares blocked shard")
}
shard.mu.Lock()
old := shard.m[uint64(blocked)].lsn
if old >= target.first {
panic("batch interruption armed after its target block was applied")
}
go func() {
watchdog := time.NewTimer(5 * time.Second)
defer watchdog.Stop()
for {
_, _, lsn, _, ok := s.dm.get(uint64(prior))
if ok && lsn == target.first+uint64(cut.Block)-1 {
emit(k3ReplayWitness{Record: cut.Record, Block: cut.Block, AppliedLSN: lsn, BlockedLSN: old})
return // shard remains held until the parent kills the child
}
select {
case <-watchdog.C:
panic("replay never reached the batch prefix")
default:
runtime.Gosched()
}
}
}()
})
if _, err := s.RecoverContext(ctx); err != nil {
t.Fatal(err)
}
t.Fatal("replay completed without reaching the requested interruption")
}
func k3ReplayKill(t *testing.T, path string, cut k3ReplayCut) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestStartWALReplayInterruptionsConverge$", "-test.timeout=12s")
raw, err := json.Marshal(cut)
if err != nil {
t.Fatal(err)
}
cmd.Env = append(os.Environ(), k3ReplayPath+"="+path, k3ReplayPoint+"="+string(raw))
var stderr bytes.Buffer
cmd.Stderr = &stderr
stdout, err := cmd.StdoutPipe()
if err != nil {
t.Fatal(err)
}
if err = cmd.Start(); err != nil {
t.Fatal(err)
}
waited := false
defer func() {
if !waited {
_ = cmd.Process.Kill()
_ = cmd.Wait()
}
}()
var witness k3ReplayWitness
if err := json.NewDecoder(stdout).Decode(&witness); err != nil {
_ = cmd.Process.Kill()
_ = cmd.Wait()
waited = true
t.Fatalf("interruption not reached: %v (deadline=%v): %s", err, ctx.Err(), stderr.String())
}
wantLSN := k3ReplayRecords()[cut.Record].last
if cut.Block != 0 {
wantLSN = k3ReplayRecords()[cut.Record].first + uint64(cut.Block) - 1
}
if witness.Record != cut.Record || witness.Block != cut.Block || witness.AppliedLSN != wantLSN || (cut.Block != 0 && witness.BlockedLSN >= wantLSN) {
t.Fatalf("wrong typed replay witness: %+v for %+v", witness, cut)
}
if err = cmd.Process.Kill(); err != nil {
t.Fatal(err)
} // SIGKILL on Linux
err = cmd.Wait()
waited = true
var exited *exec.ExitError
if ctx.Err() != nil || !errors.As(err, &exited) || !k3ReplayKilled(exited.ProcessState) {
t.Fatalf("child not killed at replay witness: %v deadline=%v: %s", err, ctx.Err(), stderr.String())
}
}
func k3ReplayVerify(t *testing.T, s *WALStore, expected [][]byte, ack uint64) {
t.Helper()
if s.NextLSN() != ack+1 || s.CheckpointLSN() != 0 {
t.Fatalf("frontier next=%d cp=%d ack=%d", s.NextLSN(), s.CheckpointLSN(), ack)
}
for lba, want := range expected {
got, err := s.Read(uint32(lba))
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("acknowledged image differs at LBA %d: %v", lba, err)
}
}
}
// Kill the actual startup store replay, not a clean stop or a torn WAL write.
// The mid-record points interrupt application of a validated multi-block WAL
// record after a proved prefix, while its next block is causally blocked.
func TestStartWALReplayInterruptionsConverge(t *testing.T) {
if path := os.Getenv(k3ReplayPath); path != "" {
var cut k3ReplayCut
if err := json.Unmarshal([]byte(os.Getenv(k3ReplayPoint)), &cut); err != nil {
t.Fatal(err)
}
k3ReplayChild(t, path, cut)
return
}
for _, mode := range []struct {
name string
mode WMode
}{{"lagged", WModeLagged}, {"strict", WModeStrict}} {
t.Run(mode.name, func(t *testing.T) {
seed := filepath.Join(t.TempDir(), "seed")
expected, ack := k3ReplaySeed(t, seed, mode.mode)
var cuts []k3ReplayCut
for i, r := range k3ReplayRecords() {
cuts = append(cuts, k3ReplayCut{Record: i})
if r.blocks > 1 {
for _, block := range []int{1, 4, 7} {
cuts = append(cuts, k3ReplayCut{Record: i, Block: block})
}
}
}
for _, cut := range cuts {
name := "record-" + fmt.Sprintf("%02d", cut.Record)
if cut.Block != 0 {
name = "batch-" + fmt.Sprintf("%02d", cut.Record) + "-block-" + strconv.Itoa(cut.Block)
}
t.Run(name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "volume")
k3ReplayCopy(t, seed, path)
k3ReplayKill(t, path, cut)
s, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
s.DisableAutoFlushForRecoveryTest()
defer func() { _ = s.Close() }()
// The first attempt was killed; the restarted replay must finish with
// exactly the last acknowledged image, including every untouched zero.
if frontier, err := s.Recover(); err != nil || frontier != ack {
t.Fatalf("restart frontier=%d want=%d: %v", frontier, ack, err)
}
k3ReplayVerify(t, s, expected, ack)
beforeR, beforeS, beforeH := s.Boundaries()
if frontier, err := s.Recover(); err != nil || frontier != ack {
t.Fatalf("second replay frontier=%d: %v", frontier, err)
}
k3ReplayVerify(t, s, expected, ack)
if r, tail, h := s.Boundaries(); r != beforeR || tail != beforeS || h != beforeH {
t.Fatalf("replay did not converge: %d/%d/%d -> %d/%d/%d", beforeR, beforeS, beforeH, r, tail, h)
}
if err := s.Close(); err != nil {
t.Fatal(err)
}
next, err := OpenWALStore(path)
if err != nil {
t.Fatal(err)
}
next.DisableAutoFlushForRecoveryTest()
defer next.Close()
if frontier, err := next.Recover(); err != nil || frontier != ack {
t.Fatalf("physical reopen frontier=%d: %v", frontier, err)
}
k3ReplayVerify(t, next, expected, ack)
})
}
})
}
}
// Keep an unrelated child failure distinct from a proved replay interruption.
func k3ReplayKilled(state *os.ProcessState) bool {
if runtime.GOOS == "linux" {
status, ok := state.Sys().(syscall.WaitStatus)
return ok && status.Signaled() && status.Signal() == syscall.Signal(9)
}
// Go's Windows Process.Kill uses TerminateProcess with exit code 1.
// Ordinary test failures/timeouts use 2; this is not a SIGKILL claim.
return runtime.GOOS == "windows" && state.ExitCode() == 1
}
func TestStartWALReplayRejectsUnrelatedExit(t *testing.T) {
if os.Getenv("SWBLOCK_TEST_REPLAY_ORDINARY_EXIT") == "1" {
fmt.Println("witness reached")
os.Exit(2)
}
cmd := exec.Command(os.Args[0], "-test.run=^TestStartWALReplayRejectsUnrelatedExit$")
cmd.Env = append(os.Environ(), "SWBLOCK_TEST_REPLAY_ORDINARY_EXIT=1")
output, err := cmd.Output()
var exited *exec.ExitError
if !errors.As(err, &exited) || !bytes.Contains(output, []byte("witness reached")) {
t.Fatalf("ordinary-exit control failed: %s %v", output, err)
}
if k3ReplayKilled(exited.ProcessState) {
t.Fatal("ordinary exit after a witness counted as a kill")
}
}
func TestStartWALReplaySeedFailureCleansUp(t *testing.T) {
if os.Getenv("SWBLOCK_TEST_REPLAY_SEED_FAILURE") == "1" {
k3ReplaySeed(t, filepath.Join(t.TempDir(), "seed"), WModeLagged)
return
}
cmd := exec.Command(os.Args[0], "-test.run=^TestStartWALReplaySeedFailureCleansUp$")
cmd.Env = append(os.Environ(), "SWBLOCK_TEST_REPLAY_SEED_FAILURE=1")
output, err := cmd.CombinedOutput()
var exited *exec.ExitError
if !errors.As(err, &exited) || !bytes.Contains(output, []byte("seed failure resources released; checkpoint=0")) {
t.Fatalf("seed failure did not release its resources: %s %v", output, err)
}
}
+10 -4
View File
@@ -950,6 +950,7 @@ Notes:
| `INV-CUT-PAYLOAD-SPILL-SOURCE-001` | Only a COW save made before a store mutation (`WriteContext`, `WriteBatchContext` or `applyEntryV3`) consumes side-file bytes; copy and upload workers never write the side file. | M5 Copy (COW save) | `core/storage/chunk_cut_cow.go` `beforeCOWMutation`, `copyCOWEntry`; `core/storage/walstore.go` `WriteContext`, `WriteBatchContext`; `core/storage/base_install_v3.go` `applyEntryV3` | `TestCutCOWV3_SpillWithinCapIsAccounted` (`core/storage/chunk_cut_cow_spillcap_test.go`) | — | ACTIVE |
| `INV-CUT-PAYLOAD-JOIN-001` | Every upload worker of a cut or staging round has returned before that round's intents are cleaned up or its outcome is settled, also after an upload failure or cancellation. | M5 Upload → Closed, Aborted | `core/storage/chunk_upload.go` `uploadBatch`; `core/storage/chunk_layer.go` `captureLocked` | `TestChunkUploads_FailureJoinsBeforeIntentCleanup` (`core/storage/chunk_upload_parallel_test.go`) | — | ACTIVE |
| `INV-CUT-ERROR-PRECEDENCE-001` | A chunk-control error body reports `cut_aborted` for a local cut abort even when the abort cancelled a remote upload, but an unknown CAS outcome, a fence or a closed or detached layer joined to it keeps its own code (`outcome_unknown`, `fenced`, `closing`). | M5 Copy, Upload → Aborted (HTTP error body) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestStatusServer_ChunkErrorBodyIsTyped` (`core/host/volume/chunk_control_test.go`) | — | ACTIVE |
| `INV-CATALOG-HEAD-CONFLICT-001` | A catalog transition that lost its conditional HEAD write (`layout.ErrPrecondition`, such as a snapshot delete raced by a cleaning's begin) reports `head_conflict` (409, retryable), never `internal`; it decides last, so any other cause joined to it keeps its own code. | M6 snapshot delete (HTTP error body) | `core/host/volume/chunk_control.go` `chunkErrorCode` | `TestSnapshotDeleteRacedByACleanBeginIsAHeadConflict`, `TestSnapshotDeleteUnderAPersistentConflictIsNeverInternal` (`core/host/volume/chunk_delete_head_conflict_test.go`); `TestStatusServer_ChunkErrorBodyIsTyped` (`core/host/volume/chunk_control_test.go`) | — | ACTIVE |
| `INV-HOST-CUT-BUDGET-001` | A cooperating cut process holds a host OS slot from its admission, before staging or the capture barrier: see M7 free → admitted. | M7 free → admitted | `core/hostlimit/limiter.go` `Admit`; `core/storage/chunk_cut_budget.go`; blockvolume host-limit flags | `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`); `TestHostCutLimitDoesNotGateGuestIO` (`core/frontend/durable/host_limit_test.go`) | `HostBudget` HeldUntilJoined/PayloadBound/SpillBound (bounded OS-lock abstraction; fallback excluded) | ACTIVE |
| `INV-HOST-CUT-BUDGET-RESERVE-001` | Each admitted slot, urgent included, carries at most PayloadBytes of cut payload and at most COWBytes of COW side bytes; a reservation beyond COWBytes revokes the slot and aborts its cut. | M7 admitted | `core/hostlimit/limiter.go` `Admit`, `ReserveCOW`; `core/storage/chunk_cut_budget.go` | `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`); `TestSlotsUrgentAndJoinedRelease` (`core/hostlimit/limiter_test.go`) | `HostBudget` PayloadBound/SpillBound | ACTIVE |
| `INV-HOST-CUT-BUDGET-SETTLE-001` | A slot's OS lock is released only after its cut's workers settle and Release is called; cancellation, hold expiry and limiter Close abort the cut but keep the slot until then. | M7 draining → joined → released | `core/hostlimit/limiter.go` `Release`, `releaseLoop`, `revoke`, `Close`; `core/storage/chunk_layer.go` `captureLocked` | `TestCOWAbortHoldsSlotUntilWorkerSettlement`, `TestHoldExpiryAndCloseDoNotSteal`, `TestKilledProcessReleasesButLiveHolderDoesNot` (`core/hostlimit/limiter_test.go`); `TestHostCOWCapAbortsCutAndRetainsPermitUntilJoin` (`core/storage/chunk_host_budget_test.go`) | `HostBudget` HeldUntilJoined | ACTIVE |
@@ -1003,8 +1004,10 @@ Notes:
| ID | Statement | Machine / transition | Enforced in | Test | TLA+ property | Status |
|---|---|---|---|---|---|---|
| `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `cmd/sw-block/log_collect.go` `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle` | - (pure client sanitization) | ACTIVE |
| `INV-CLI-BUNDLE-DISCOVERY-001` | Credential discovery precedes time filtering and aggregate-budget omission; exhausting the match bound refuses all output. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `discover`, `add`, `readBundleLog`; `cmd/sw-block/log_collect_redact.go` `discoverText` | `TestLogCollectRefusesExhaustedCredentialDiscovery`, `TestLogCollectDiscoversCredentialsBeforeTheTimeWindow`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (bounded discovery) | ACTIVE |
| `INV-CLI-BUNDLE-REDACTION-001` | Recognized credentials are discovered across bounded sources before any artifact is written, and their opaque repeats are masked. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go`; `cmd/sw-block/log_collect.go` `logBundle.write` | `TestLogCollectPlantedSecretsNeverLeaveTheBundle`, `TestLogCollectRecognizedCredentialFormsNeverLeaveTheBundle`, `TestLogCollectRedactsKnownCredentialsInJSONKeys` | - (pure client sanitization) | ACTIVE |
| `INV-CLI-BUNDLE-DISCOVERY-001` | Credential discovery precedes time filtering and aggregate-budget omission; exhausting the match bound refuses all output. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `discover`, `addSource`, `readBundleLog`; `cmd/sw-block/log_collect_redact.go` `discoverText` | `TestLogCollectRefusesExhaustedCredentialDiscovery`, `TestLogCollectDiscoversCredentialsBeforeTheTimeWindow`, `TestLogCollectDiscoversCredentialsInSourcesBeyondTheArtifactBudget` | - (bounded discovery) | ACTIVE |
| `INV-CLI-BUNDLE-UNPROVEN-001` | A declared source (-log-file, -unit, -pid) whose discovery did not complete (cut by the time budget, refused or over its bound, a failed or truncated command; a missing file, process or command, or an empty window, is only unavailable) leaves only the manifest, `redaction: not_proven`; exit 3. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs`, `addCommand`, `unproven`, `logBundle.write`; `cmd/sw-block/log_collect_local.go` `collectLocal` | `TestLogCollectCutDeclaredSourceWithholdsEveryArtifact`, `TestLogCollectOversizedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectRefusedDeclaredFileWithholdsEveryArtifact`, `TestLogCollectMissingDeclaredFileIsOnlyUnavailable`, `TestLogCollectUnreadablePIDWithholdsEveryArtifact`, `TestLogCollectTruncatedUnitWithholdsEveryArtifact`, `TestLogCollectQuietUnitIsOnlyUnavailable` (Linux) | - (pure client sanitization) | ACTIVE |
| `INV-CLI-BUNDLE-UNPROVEN-002` | In an unproven bundle every artifact error is replaced by a fixed one, and the cut sources are named in the manifest and printed sanitized like it; a JSON artifact whose keys collide once sanitized is withheld. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `logBundle.write`, `collectLogs` | `TestLogCollectUnprovenManifestKeepsOnlyFixedErrors`, `TestLogCollectSkippedNamesArePrintedSanitized`, `TestLogCollectCollidingJSONKeysAreWithheld` | - (pure client sanitization) | ACTIVE |
| `INV-CLI-BUNDLE-DIAGNOSTICS-001` | Bare prose does not seed global replacement; ordinary values are excluded so diagnostic words, dates and generations remain readable. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `remember`, `discoverText` | `TestLogCollectKeepsOrdinaryWordsAndGenerationsWhileRedactingTokens` | - (pure client sanitization) | ACTIVE |
| `INV-CLI-BUNDLE-NUMBERS-001` | Sanitizing structured JSON preserves exact integer evidence, including uint64 counters and positions above 2^53. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect_redact.go` `bundleDecodeJSON` | `TestLogCollectPreservesExactLargeJSONNumbers` | - (pure client sanitization) | ACTIVE |
| `INV-CLI-BUNDLE-LOCAL-RETENTION-001` | Selected local logs are collected before remote observations; an unresponsive master produces an incomplete bundle without discarding those logs. | M9 read-only inspection; no state transition | `cmd/sw-block/log_collect.go` `collectLogs` | `TestLogCollectKeepsLocalLogsWhenTheMasterDoesNotAnswer` | - (client ordering; no service-availability claim) | ACTIVE |
@@ -1024,13 +1027,16 @@ Notes:
| `INV-SNAP-SEAL-DURABLE-001` | A named snapshot is reported done only after the commit naming it is confirmed (every object its root reaches written by the session first); an unknown outcome reports failure, settled by reading HEAD. | M5 CAS → Settled; M6 snapshot: name held → published | `core/host/volume/chunk_control.go` `chunkControl.Snapshot`; `core/storage/chunk_layer.go` `captureLocked`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.CASHead`; `core/frontend/chunkstore/layout/commit.go` `RunCommit` | `TestLayoutRemote_CutCommitsThroughTheKernel` (`core/frontend/chunkstore/layout_remote_test.go`); `TestNamedSnapshotWindowAbortNeverSubstitutesPoint` (`core/host/volume/chunk_review271_test.go`) | — | ACTIVE |
| `INV-SNAP-SCHEDULE-RESTART-001` | A new snapshot worker seeds its last success from HEAD's newest scheduled creation time (future clamped to now), then the next stable per-volume grid slot; absent history is due now. Restarts preserve overdue age; manual snapshots do not seed it. | M8 scheduled worker Armed → Due | `core/frontend/durable/chunk_snapshot_schedule.go` `snapshotScheduleFromHead`; `provider_chunk.go` `newChunkLayer` | `TestScheduledSnapshotRestartsStillTakeTheDueSnapshot`, `TestScheduledSnapshotRestartPreservesOverdueFromHEAD`, `TestScheduledSnapshotWithoutHistoryIsImmediatelyDue`, `TestScheduledSnapshotProvidersSpreadAfterImmediateFirstAttempt`, `TestSnapshotScheduleHeadSeedKeepsPerVolumeGrid`, `TestSnapshotScheduleHeadSeedClampsFutureCreationTime` | — (read-only timer initialization from existing HEAD metadata) | ACTIVE |
| `INV-SNAP-SCHEDULED-KEEP-001` | Retention keeps the newest K scheduled snapshots, K being the newest one's swb.schedule.keep (default 7); scheduled snapshots never count against KeepNewest or get age keeps, so other snapshots are planned as if they were absent. | M6 snapshot: Published → Deleting (retention, class `scheduled`) | `core/frontend/chunkstore/retain/retain.go` `Plan`, `scheduleKeepOf` | `TestPlanRetention_ScheduledClassKeepsItsOwnNewest`, `TestPlanRetention_PinnedScheduledStaysInItsClass` (`core/frontend/chunkstore/retain/retain_test.go`) | — | ACTIVE |
| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-READONLY-001` | Verify writes nothing at any depth: it reaches the store only through Fetch, Stat and List, and a full pass with orphans leaves every filer entry and blob unchanged. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyLayoutThroughTheAdapter` (`core/frontend/chunkstore/layout_verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-BINDINGS-001` | Bindings checks each chunk's filer binding, declared size and needle HEAD size against its owner's VOLUME geometry (tail excepted), without transferring the blob body. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `verifyStat`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsNeverReadsChunkBodies`, `TestVerifyBindingsChecksDeclaredSizesAndRefusals`, `TestVerifyBindingsLookupFailureIsNotAMissingObject`, `TestVerifyBindingsRejectsSelfConsistentTruncationAgainstGeometry`, `TestVerifyBindingsUsesTailGeometryAndRejectsOutsideVolume` | — (read-only inspection) | ACTIVE |
| `INV-VERIFY-NEEDLE-001` | Bindings reports a missing needle only after every freshly resolved location answers 404; operational failures remain incomplete. A needle HEAD never falls back to a client GET. | M6 reader (no transition) | `core/frontend/chunkstore/swfs_head.go` `HeadBlob`; `core/frontend/chunkstore/layout_verify.go` `verifyStat` | `TestVerifyBindingsReportsMissingNeedleBehindPresentEntry`, `TestSWFSHeadBlobUsesOnlyHEADAndClassifiesAbsence`, `TestSWFSHeadBlobRefreshesCachedMissingLocation` | — (read-only inspection) | ACTIVE |
| `INV-VERIFY-DISTINCT-001` | A verify pass looks up each immutable metadata object and chunk binding once across roots; HEAD remains independently confirmed, and chunk bodies are never retained in the metadata cache. | M6 reader (no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `core/frontend/chunkstore/layout/verify.go` `chunks` | `TestVerifyBindingsChecksEachDistinctObjectOnce` | — (pass-local reuse) | ACTIVE |
| `INV-VERIFY-STABLE-HEAD-001` | Filer verify publishes MISSING or ORPHAN only after two HEAD observations agree on a nonzero generation and volume identity. An unavailable or changed own/dependent HEAD makes the pass incomplete and suppresses those findings. Unsupported verify options refuse before dialing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout_verify.go` `VerifyLayout`; `cmd/sw-block/chunk_verify.go` `chunkVerify` | `TestVerifyLayoutRequiresStableHeadForMissingAndOrphans`; `TestVerifyConfirmsDependentHeadBeforeReportingOrphans`; `TestOpsChunkVerifyRefusesUnsupportedFlagsBeforeDial` | — | ACTIVE |
| `INV-VERIFY-NOTFOUND-001` | Verify reports `MISSING` only when the store answers that the object does not exist; any other read failure ends the pass as incomplete with that error, and is never a finding. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyReadErrorIsReturned`, `TestVerifyFindsMissingAndCorrupt` (`core/frontend/chunkstore/layout/verify_test.go`); `TestOpsChunk_VerifyReadErrorIsIncomplete` (`cmd/sw-block/chunk_verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-REACH-001` | A complete pass checks every object the current root and every snapshot root name (roots, segments, chunks): an absent one is `MISSING`; one whose bytes do not hash to its name, at depth full, is `CORRUPT`. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyCleanVolume`, `TestVerifyFindsMissingAndCorrupt`, `TestVerifyWalksSnapshotRoots` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-INCOMPLETE-001` | A volume whose VOLUME or HEAD is absent or does not decode is never reported clean: the pass is incomplete and says which object. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyHeadMissingOrMalformedIsIncomplete` (`core/frontend/chunkstore/layout/verify_test.go`) | — | ACTIVE |
| `INV-VERIFY-ORPHAN-001` | With orphans on, only this volume's own full-id names that no root or live restore target names are ORPHAN. Owner/target paths use VolumeDir(name,id); an unreadable live target suppresses orphan findings. Verify deletes nothing. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyOrphans`, `TestVerifyDependentReachIsNotOrphanAndUnreadableDependentSuppresses` (`core/frontend/chunkstore/layout/verify_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`) | — | ACTIVE |
| `INV-VERIFY-IDENTITY-001` | Verify reads canonical VolumeDir(name,id) directories. VOLUME must match its directory, HEAD must match VOLUME, and a master-resolved id must match in full. A mismatched chunk-owner VOLUME is IDENTITY, never clean. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyVolumeRecordAndHeadID`, `TestVerifyChunkOwnerIdentity` (`core/frontend/chunkstore/layout/verify_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`); `TestOpsChunk_VerifyProductionLayoutNameAndDirectory`, `TestOpsChunk_VerifyBindsMasterFullIDDespiteDirectoryPrefixCollision` (`cmd/sw-block/chunk_verify_production_test.go`) | — | ACTIVE |
| `INV-VERIFY-IDENTITY-001` | Verify reads canonical VolumeDir(name,id) directories. VOLUME must match its directory, HEAD must match VOLUME, and a master-resolved id must match in full. A mismatched chunk-owner VOLUME is IDENTITY, never clean. | M6 (reader; no transition) | `core/frontend/chunkstore/layout/verify.go` `Verify`; `core/frontend/chunkstore/layout_verify.go` `VerifyLayout` | `TestVerifyVolumeRecordAndHeadID`, `TestVerifyChunkOwnerIdentity` (`core/frontend/chunkstore/layout/verify_test.go`), `TestVerifyDeduplicationNeverSkipsFullOwnerIdentity` (`core/frontend/chunkstore/verify_bindings_stat_test.go`) ; `TestVerifyProductionLayoutCurrentAndRestored` (`core/frontend/chunkstore/verify_production_layout_test.go`); `TestOpsChunk_VerifyProductionLayoutNameAndDirectory`, `TestOpsChunk_VerifyBindsMasterFullIDDespiteDirectoryPrefixCollision` (`cmd/sw-block/chunk_verify_production_test.go`) | — | ACTIVE |
| `INV-RESTORE-HYDRATE-001` | The background hydrate walker fetches a chunk only through that chunk's shared fill flight: at most one fetch per chunk absence, and a fetched block is never installed over a block written locally. | M4 Holder (background hydrate) | `core/storage/chunk_hydrate_all.go` `HydrateAll`, `HydrateAllAt`, `startWalkerFill`, `nextHydrateTarget`, `admitFill`; `core/storage/chunk_hydration.go` `hydrationFlightLocked`; `core/storage/chunk_layer.go` `fillOnce` | `TestHydrateAll_FillsEveryChunkOnceAndReadsTheHeadImage`, `TestHydrateAll_YieldsToGuestReadsAndNeverFetchesTwice`, `TestHydrateAll_NeverOverwritesALocalWrite`, `TestHydrateAll_AdmitsEachFillThroughTheLimiterWithTheCallersClass`, `TestHydrateAll_RealBackgroundFillLimiterAdmitsEveryFill`, `TestHydrateAll_PermitIsHeldUntilTheOwnedFetchSettles`, `TestHydrateAll_RevocationStopsTheWalker`, `TestHydrateAll_CancelReturnsWhileTheFetchIsHeld`, `TestHydrateAll_PacedByByteRate` (`core/storage/chunk_hydrate_all_test.go`) | — | DORMANT |
| `INV-RESTORE-OWN-BATCH-001` | A batch cut re-uploads at most N local chunks whose HEAD keys name another volume under new own keys, even when their bytes equal HEAD's, in one ordinary cut (one intent, one HEAD CAS); it never fetches an absent chunk. | M6.Restore.Owning>Owning | `core/storage/chunk_own.go` `OwnBatch`; `core/storage/chunk_cut_payload.go` `streamCutPayloads` | `TestOwnBatch_BoundedBatchesReplaceEveryForeignKey`, `TestOwnBatch_SkipsChunksNotLocal`, `TestOwnBatch_CarriesGuestWrites` (`core/storage/chunk_own_test.go`) | `RestoreIndependence` `NoGap` | DORMANT |
| `INV-RESTORE-READ-REF-001` | A restore target reads each chunk its HEAD names from the pool of the reference's owner, by the reference alone (no other copy, no name-built path); a chunk missing there is an error on a fresh host, never zeros. | M6 restore target read (no transition) | `core/frontend/chunkstore/layout/read.go` `Reader.ReadRef`; `core/frontend/chunkstore/layout_remote.go` `LayoutRemote.Get` | `TestLayoutRemote_RestoreTargetReadsItsSource` (`core/frontend/chunkstore/layout_restore_read_test.go`) | — | ACTIVE |
+7
View File
@@ -87,6 +87,8 @@ Local file acquisition is supported on Linux and Windows; other platforms mark
selected files unavailable. Structured JSON keeps exact integer values.
The shell timeout bounds status and journal collection; the reused store command's
name resolution and reads share the same deadline. No unbounded subprocess output is buffered.
Each `-log-file` is read whole for credential discovery whatever the timeout has left
(each is bounded at 4 MiB, at most 32 sources); a missing file is only unavailable.
## Credential handling
@@ -94,6 +96,11 @@ All retained source data stays in bounded memory until credential discovery
finishes. Bounded log inputs are scanned before the time filter; credentials in
sources omitted by the aggregate artifact budget still teach redaction of their
repeats. A discovery scan that exhausts its match bound refuses all output.
**Redaction not proven:** when a declared source (`-log-file`, `-unit`, `-pid`) was not
read whole for discovery (cut by the timeout, over its bound, not text, a link or pipe,
unreadable, a failed or truncated command), the bundle holds only `manifest.json`
(`"redaction": "not_proven"`, the sources named in `skipped`, fixed diagnostics only),
and the command prints `incomplete: redaction not proven` and exits 3.
Only sanitized artifacts are written; raw sources are never staged in the bundle.
The same boundary sanitizes structured status, startup arguments, logs and
manifest errors. Sensitive key/value and flag names include password, token,
+14 -11
View File
@@ -352,12 +352,11 @@ that never served (step 4 of
delete means this case; retrying the delete alone does not help. Until the release, the source's delete answers
`snapshot_has_dependents` ("has 1").
Deleting a restore target: its first cut compares every restored chunk locally (about 1.4 GiB/s measured). The
default `--timeout` of 120 s covers up to about 84 GiB; above that, pass `--timeout 5m` (the server's limit for one
request). At the 256 GiB maximum the first cut takes about 3 min. An `outcome_unknown` answer there means the volume
Deleting a restore target: its first cut compares every restored chunk locally, so it reads the target's whole filled
size. The server bounds one request at 5 minutes: pass `--timeout 5m` for a large target. An `outcome_unknown` answer there means the volume
has stopped I/O while its holder settles the outcome in the background; it resumes serving when that settles (the
holder logs it), and nothing acknowledged is lost. Then retry the delete with `--timeout 5m`. A restore target's
filled size must be at most about 4 min x your disk's read rate for its first cut to finish. On disks slower than NVMe the 256 GiB figure does not hold; see the v1.0.0 Known limits.
holder logs it), and nothing acknowledged is lost. Then retry the delete with `--timeout 5m`. The first cut must read the filled size within one
5-minute request, so the filled size divided by your disk's read rate must fit in it; see the v1.0.1 Known limits.
[Standalone deployment: snapshots, restore and space](standalone-deployment.md#snapshots-restore-and-space-walstore-chunk):
@@ -387,8 +386,11 @@ the snapshot name exists only after a request for it succeeds (check with `sw-bl
(`TestKnownDefectSnapshotRetryAfterAGenuineConflictCommitsTheDataUnnamed`). A retry that names the snapshot at once is
planned for a later release.
A snapshot's time grows with the data changed since the volume's last cut: 64 GiB changed took 122 s (about 2 s
per GiB). `sw-block ops chunk snapshot` waits 60 s by default, so pass `--timeout` above the expected time; the
A snapshot delete can answer `head_conflict` (HTTP 409, retryable) too: another write to the volume's HEAD, such as the
holder's cleaning beginning, landed between the delete's read of HEAD and its write. Nothing of the delete applied;
retry it (`TestSnapshotDeleteRacedByACleanBeginIsAHeadConflict`).
A snapshot's time grows with the data changed since the volume's last cut. `sw-block ops chunk snapshot` waits 60 s by default, so pass `--timeout` above the expected time; the
server bounds one request at 5 minutes whatever `--timeout` says. A request that runs
out of time answers a retryable code: `remote_unavailable` or `deadline_exceeded` when it ran out before its commit,
`outcome_unknown` when it ran out during the commit. Before the commit, the name is withdrawn and no later cut
@@ -396,10 +398,11 @@ publishes it; the volume's data is unchanged and stays queued for the next cut.
After `outcome_unknown`, the commit may have landed with the name.
Rerun the snapshot with the same name and a larger `--timeout`: a name already in HEAD is answered with the
snapshot it names, so a rerun never takes a second one. A rerun keeps what a timed-out request already
uploaded: it finds those chunks and sends only the rest. More than about 150 GiB changed needs more than one 5-minute
request: at the 256 GiB maximum a snapshot published on its second request, after about 9 minutes in all, so rerun
until it answers. A scheduled snapshot retries by itself (after 1 minute, doubling to 1 hour). A longer or derived
default is planned for a later release.
uploaded: it finds those chunks and sends only the rest. A large change can need more than one 5-minute
request. With a
`--timeout` above 5 minutes (for example `--timeout 15m`), `sw-block ops chunk snapshot`, `cut` and `detach` repeat
the 5-minute request with the same body until it answers or the timeout ends; with a shorter one, rerun until it
answers. A scheduled snapshot retries by itself (after 1 minute, doubling to 1 hour).
With `--host-limit-dir` set (it is off by default), uploads are paced at `--host-limit-upload-bytes-sec` (64 MiB/s by
default) shared by the host's 4 slots, about 16 MiB/s per volume. Only the bytes a cut sends are paced: a chunk
+3 -1
View File
@@ -4,8 +4,10 @@ Seaweed Block release notes use narrow product claims. Each alpha version names
what a user or reviewer can actually run, what QA evidence backs it, and what
is still outside the supported boundary.
- [v1.0.2](v1.0.2.md)
- [v1.0.1](v1.0.1.md)
- [v1.0.0](v1.0.0.md)
- [Planned cleaning convergence after v1.0.0](cleaning-convergence.md)
- [Cleaning changes in v1.0.1](cleaning-convergence.md)
- [Diagnostic log format](log-format.md)
- [Typed refusal codes of the chunk CLI](cli-refusal-codes.md)
- [Holder identity and pre-release upgrades](holder-identity.md)
@@ -1,8 +1,7 @@
# Planned cleaning changes after v1.0.0
# Cleaning changes in v1.0.1
These changes are proposed for v1.0.1. They are not a claim about v1.0.0 or
qualification of a published binary. The v1.0.0 release note's cleaning limits
describe that release; this change replaces those limits when it is released.
These changes are in v1.0.1. They replace the v1.0.0 release note's cleaning
limits.
- Cleaning removes unreferenced roots, then segments, then chunks. It no longer
waits for volume deletion to reclaim abandoned roots and segments.
@@ -19,8 +18,7 @@ describe that release; this change replaces those limits when it is released.
through the existing worker. Queued is not completed; an ended worker refuses.
See [cleaning and the schedule command](../standalone-deployment.md#resuming-cleaning-passes).
Linux/race qualification and the production-layout CLI verifier evidence remain
separate gates. A live graph/count check is not a `verify`-clean result.
A live graph/count check is not a `verify`-clean result.
### Last holder maintenance pass
+157
View File
@@ -0,0 +1,157 @@
# v1.0.1
A maintenance release of v1.0.0. The supported configuration is still the **single-replica volume**
(`--durable-impl walstore-chunk`), new volumes are still at most 256 GiB, and the recovery point does not change:
the loss of a whole host loses what was acknowledged since the volume's last successful snapshot or cut. Replicated
volumes remain a preview: see [replicated volumes in v1.0: a preview](replicated-volumes-preview.md).
v1.0.1 adds whole-job volume commands, a single-host trial (`sw-block mini`), an inspection shell with
`cluster.check` and a troubleshooting page, a support bundle, and a working `ops chunk verify`; it fixes the cleaning
limits and the rare holder crash listed in v1.0.0's Known limits.
## Upgrade
- In place, with no format change in any store (see [persisted state](../persisted-state.md)) and no flag to set:
blockmaster first, then each volume host one at a time, the `sw-block` CLI last. Follow
[upgrade from v1.0.0 to v1.0.1](../upgrade-v1.0.1.md).
- While some hosts still run v1.0.0: create no volume above 256 GiB (as in v1.0.0); a restore's target must be in the
cluster spec before the restore, unless blockmaster's product loop is on (`--lifecycle-product-loop-interval`);
`cluster.check` against a v1.0.0 holder reports its version as unavailable, never `ok`. A v1.0.0 blockmaster with
a v1.0.1 volume host is not supported.
- Downgrade is not supported.
## New
- **Volume commands** (run as root): `sw-block volume start <volume>` writes the volume's settings to
`/etc/sw-block/volumes/<volume>.env` and starts the unit `sw-blockvolume@<volume>.service`;
`sw-block volume stop <volume>` cuts and stops it, and refuses while a guest is connected (`--force` to stop anyway,
`--no-cut` to skip the cut); `sw-block volume backup <volume> --name S` takes a snapshot;
`sw-block volume restore <volume> --snapshot S --as <new> ...` creates and starts a restored volume (`--abort` undoes
a restore that did not finish). See [standalone deployment](../standalone-deployment.md) and
[volume backup and restore](volume-backup-restore.md).
- **`sw-block mini`**: a single-host trial on loopback with SeaweedFS's `weed mini` as the chunk store. Snapshots work
at once; a restore into a new volume is refused inside the trial (blockmaster's product loop is off).
- **`sw-block shell`**: inspection commands (`cluster.status`, `volume.list`, `volume.status`, `volume.explain`,
`snapshot.list`, `store.show`, `store.usage`, `volume.verify`), each with `-o json`, and `cluster.check [volume]`:
fourteen checks in the order a start-up fails, one line each (`ok`, `FAIL`, `not checked here`, `not applicable`).
A `FAIL` prints its cure and names its section of the [troubleshooting page](../troubleshooting.md). The checks of a
volume's holder run only on its host (`-server-id`); elsewhere they say `not checked here`.
- **Support bundle**: `log.collect -out DIR` in `sw-block shell` gathers versions, the cluster and `cluster.check`
results, the holder's status pages, a HEAD summary, the start-up arguments and the last `-since` (default 15 min) of
logs into a new directory. Credentials in what it collects are redacted; it reads no environment, configuration tree
or key file. Exit 0 means every source was collected, not that the cluster is healthy.
- **`ops chunk verify` works on production volumes**: `--master MASTER --volume NAME` resolves the volume's directory
through blockmaster (or give the `<name>-<id8>` directory). It checks every named snapshot in turn; `--orphans` lists
unreferenced objects. See [verify on the production layout](verify-production-layout.md).
- **Status and logs**: `/status/durable` shows the phase of the running cut, the volume's HEAD writes and unknown
outcomes by cause, and the cleaning passes (see [status schema](../status-schema.md)); each HEAD write is logged with
its cause; `--log-level info|debug` and UTC timestamps (see [log format](log-format.md)).
- **Forced move answers in JSON**: `sw-block ops workspace force-move --json` (with or without `--dry-run`) reports
whether the move is admitted, the barrier time, a typed refusal code, and for an issued move the new epoch, host and
replica and the kept HEAD position. `--dry-run` exits 0 whenever the check ran, admitted or not: read `admitted`.
- **Long requests repeat**: `ops chunk snapshot`, `cut` and `detach` with a `--timeout` above 5 minutes repeat the
server's 5-minute request with the same body until it answers or the timeout ends. The defaults (60 s, 60 s, 120 s)
send one request.
## Changed at start
- **`--workspace-lease` is required** for every `--durable-impl walstore-chunk` volume: `blockvolume` refuses to start
without it (without a lease, two holders could both acknowledge writes). Plain `walstore` volumes are unchanged.
- **The filer must refuse a stale conditional HEAD update**: `blockmaster` and `blockvolume` check at start, in a
disposable `.startup-head-probe-<id>` directory under the chunk path, that the filer refuses an update with the
wrong generation and leaves the object unchanged; a filer that does not, or an unknown outcome, refuses the start.
- **The single-filer check is stricter**: it passes only when every master answered, and the leader's list decides.
`sw-block ops chunk` commands that write metadata refuse a filer client that cannot run the check (one that is not
SeaweedFS).
- **A revoked holder stays stopped**: a holder started again after its revocation was already recorded exits once
with status 79, which the shipped units do not restart (as for 78). Update the units before the binary (see the
upgrade page). A revocation acknowledgement retried after its deadline is answered from the record.
## Fixed
- **Holder crash on first reads**: v1.0.0's rare `fatal error: concurrent map writes` during the first reads of a
volume opened from the object store (after a move, a takeover, or as a restore target).
- **Cleaning reaches the whole store**: a pass continues where the previous pass of the same process stopped, instead
of starting at the first shard, so its space is reclaimed whatever the store's size (after a restart the first pass
starts again from the beginning). Cleaning now also removes roots and segments that no snapshot names, so a cut no
longer keeps metadata until the volume is deleted. This replaces two v1.0.0 Known limits.
- **Commit of a large volume**: the check of the chunks a cut names runs before the HEAD update, within the cut's own
time, and the HEAD update does constant work. The v1.0.0 limit tying the 256 GiB size to the filer's round-trip
time is gone (the 256 GiB maximum stays).
- **A refused restore leaves no target**: a restore refused for good (for example from a snapshot of a restored
volume) no longer leaves the target name bound, and answers `restore_source_not_own` without the misleading
`layout store not ready:` prefix. An unknown volume now answers `volume_not_found` (exit 1) instead of
`bad_request` (exit 2). See [CLI refusal codes](cli-refusal-codes.md).
- **Cuts keep their progress**: a cut that fails or runs out of time keeps the chunks it already compared and the
uploads it already made; the next cut compares and sends only the rest. A chunk filled from the source snapshot is not
sent again while unchanged. With `--host-limit-dir`, only the bytes a cut sends are paced, so a rerun converges.
- **A snapshot holds every write acknowledged before its request**: its name is recorded only by a cut at or after
the request's log position, never by a cut that was already past its barrier when the request arrived.
- **Scheduled snapshots survive restarts**: a restarted holder takes the next due time from the volume's newest
scheduled snapshot in HEAD, instead of placing the next daily attempt again (up to a day away); a missed time stays
due.
- **Uploads do not block HEAD reads**: a cut's uploads run concurrently, and reads of the volume's HEAD proceed while
they do.
- **A failed fsync stays failed**: the save of a volume's chunk presence follows the store's rule that a failed fsync
is never retried as if it had succeeded.
- **Plain detach** keeps time inside the caller's `--timeout` to settle: it answers aborted or unknown within the
timeout instead of after it.
- **Connections to SeaweedFS volume servers are reused**, instead of leaving a burst of closed sockets per cut.
- **A status server closed right after its start** no longer panics.
## Replicated volumes (preview)
- No support claim changes: replicated volumes remain a preview (see
[replicated volumes in v1.0: a preview](replicated-volumes-preview.md)).
- Preview fix: a primary's session exchanges with a replica now go through one queue per replica, in order, and are
refused cleanly when that replica's worker stops.
## Limits
- New volumes are at most 256 GiB, as in v1.0.0.
- Tested with up to 200 volumes on one 8-vCPU host; at that density the host CPU is saturated and per-volume latency
is not qualified.
- Restoring needs room: the target's full size plus its WAL (64 MiB) free on the restoring host; the create is refused
with a message that names both numbers.
- Up to 10 snapshots per volume; up to 4 restore targets per snapshot and 16 per volume; snapshot names up to 64
bytes; up to 4 labels. A volume's geometry is fixed at creation.
- A snapshot's time grows with the data changed since the last cut; see the operator guide for `--timeout`.
- `ops chunk verify` checks the current image and each named snapshot one after another, and the chunks of each
snapshot one at a time, so its time grows with the volume's size times the number of snapshots. The default
`--timeout` (10 min) is not enough for a 256 GiB volume with the default snapshot schedule: raise `--timeout`.
`--depth data` reads every chunk's bytes and needs an explicit `--timeout`. There is no option to verify only some
snapshots.
## Advance notice: removed in v1.1
- The experimental engines `--durable-impl smartwal` and `--durable-impl parallel-walstore` are removed in v1.1, and
their volumes will not open there. Before upgrading such a volume to v1.1, copy its data to a `walstore` volume with
v1.0.x.
## Known limits
- On a freshly restored volume each cut pauses guest writes while it looks up the block entries of every chunk not
yet local; the pause falls as the volume's chunks become local.
- A restored volume never becomes independent: its source snapshot stays pinned and counts toward the source's 10
while the target exists, and the source cannot be deleted before it. Independence is planned for a later release.
- While a large restore is being created, do not move or detach other volumes; a move that fails then is retried after
the restore completes.
- A restored volume takes no scheduled snapshots while any of its chunks is still only in the source snapshot.
- A snapshot of a restored volume cannot itself be a restore source (`restore_source_not_own`).
- Node Ready/Schedulable in the observation report and the Kubernetes operator status are always true in v1.0.1; use
cluster.check for node state.
- sw-block does not authenticate to SeaweedFS; run SeaweedFS on a trusted network.
- An upload whose outcome is unknown may leave an unreferenced object that cleaning does not reclaim;
`weed shell volume.fsck -collection <block collection> -v` lists such objects; do not use its delete option on
block data.
- blockmaster reads its cluster spec only at start.
- One SeaweedFS filer per chunk store.
- A restore target's first cut reads every filled byte, so its time grows with the target's filled size and the
disk's read rate; on a slow disk or a large target its detach and delete may not finish within the server's
5-minute bound for one request. See the operator guide.
- A volume created at run time and not in the cluster spec is served only with `--lifecycle-product-loop-interval` set.
- A volume-delete refused with `snapshot_has_dependents` has already reserved the volume; delete or release the
restored volume first, then run the same delete again.
- A snapshot that meets a concurrent HEAD change answers `head_conflict`: retry it (and once more if the retry answers
`snapshot "NAME" of VOL is not in HEAD after its commit`). A snapshot delete that meets one (for example the
holder's cleaning beginning) answers `head_conflict` too, where it answered `internal` before: nothing applied, retry it.
- A restored volume that has only been read fetches all of its chunks again after any restart; writing to it, or its
next checkpoint, records what it has fetched (no data is lost).
- A guest's NVMe/TCP connection waits about 181 s (holder stopped, host up) or about 464 s (holder's host powered off)
for a stopped target; see [host connect settings](../operator-guide.md#host-connect-settings).
- Every deleted volume leaves one small record in blockmaster's deletion store; the name cannot be reused.
- replicated (preview): a replica whose rebuild was refused is not reported unhealthy; fixed in a later release.
- replicated volumes are a preview: a primary cut off from the block master is not stopped by a lease and may serve
stale reads to a guest still connected to it; do not use replicated volumes for data you cannot lose.
+56
View File
@@ -0,0 +1,56 @@
# v1.0.2
A maintenance release of v1.0.1 with three fixes. The supported configuration is unchanged: the **single-replica
volume** (`--durable-impl walstore-chunk`), new volumes at most 256 GiB, and the same recovery point (the loss of a
whole host loses what was acknowledged since the volume's last successful snapshot or cut). Replicated volumes remain
a preview: see [replicated volumes in v1.0: a preview](replicated-volumes-preview.md).
## Upgrade
- In place from v1.0.1, with no format change in any store (see [persisted state](../persisted-state.md)) and no flag
to set: blockmaster first, then each volume host one at a time, the `sw-block` CLI last, as in
[upgrade from v1.0.0 to v1.0.1](../upgrade-v1.0.1.md).
- v1.0.2 writes the same HEAD format as v1.0.1, so going back to v1.0.1 works: on a 256 GiB volume with seven
snapshots made by v1.0.1, v1.0.2 opened it, read it, verified it at `--depth data` and cut; v1.0.1 then opened the
HEAD v1.0.2 wrote, read the same blocks back and verified it at `--depth data`, with the image and every snapshot
unchanged.
## Fixed
- **`ops chunk verify --depth bindings` no longer reads chunk bodies.** The default depth (also named `meta`) checks,
for each distinct chunk, its filer entry and its declared size against the volume's geometry, then the backing
needle's existence and size with an HTTP HEAD request, without downloading the body. A present entry whose needle is
missing is reported `MISSING`. Roots and segments are still read and decoded, and an object shared by several
snapshots is checked once per pass. See [standalone deployment](../standalone-deployment.md).
- **A HEAD written by a newer version is refused as such, not as damage.** A v1.0.x binary that meets a HEAD carrying
a format version field answers `HEAD written by a newer version: use a newer binary` and writes nothing:
- the holder refuses the volume once and finally (it does not retry, and the volume is not served);
- every `sw-block ops chunk` verb that reads HEAD refuses with the same text;
- blockmaster refuses that HEAD the same way.
Earlier v1.0.x binaries reported such a HEAD as malformed. Use a binary of the version that wrote it.
- **A support bundle never holds an artifact whose redaction was not proven.** When `log.collect` cannot read a
declared source (`-log-file`, `-unit`, `-pid`) whole, because it was cut by the time budget, refused or over its
bound, or its command failed or was truncated, the bundle keeps only its manifest, which says
`redaction: not_proven` and names the cut sources; the command prints `incomplete: redaction not proven` and exits
with status 3. A JSON artifact whose keys collide once credentials are removed is withheld. A missing file, process
or command, or an empty log window, is only reported unavailable. See [support bundle](v1.0.1.md#new).
## What verify proves at each depth
- **`--depth bindings`** (the default, also named `meta`): every object the current image and each named snapshot
name exists, each chunk with its expected size, and its needle exists with that size. It does not detect damage that
keeps a chunk's size.
- **`--depth data`**: also reads every chunk's bytes and checks that they hash to its name. It needs an explicit
`--timeout`.
- With SeaweedFS 4.53, an HTTP HEAD of an ordinary uncompressed 4 MiB needle reads only its metadata; SeaweedFS may
still read a small needle internally. A chunk stored inline in its filer entry is checked from that entry (it has no
needle). When no replica of a needle answers, the pass is incomplete; it does not report the needle missing.
## Limits
As in [v1.0.1](v1.0.1.md#limits), except for verify's time:
- `ops chunk verify` checks the current image and each named snapshot one after another. On a 256 GiB volume with
seven snapshots, `--depth bindings` (the default) took 29 s, within the default `--timeout` (10 min), and read no
chunk body; a removed needle was reported `MISSING` (exit 3) at that depth. `--depth data` reads each chunk's bytes
once per pass, even when several snapshots share it (v1.0.1 read it again for each): 12 min 29 s on that volume,
where v1.0.1 took 97 min 25 s. It needs an explicit `--timeout`. There is no option to verify only some snapshots.
## Known limits
As in [v1.0.1](v1.0.1.md#known-limits).
+14 -1
View File
@@ -870,6 +870,19 @@ must also match VOLUME; the eight-character directory suffix is not an identity
check. Source and restore-target chunks are checked in their owners' canonical
directories using each reference's full owner id.
The default `--depth bindings` (also named `meta`) checks each distinct chunk's
filer entry and its declared size against its owner's VOLUME geometry (including
the final partial chunk), then checks the backing needle's existence and size
using HTTP HEAD without downloading its body. A missing needle behind a present
entry is MISSING. A successful replica is sufficient; when none succeeds,
an operational failure makes the pass incomplete rather than proving absence. This does
not detect same-size content damage; use `--depth data` for the hash check.
SeaweedFS 4.53 reads only metadata for ordinary uncompressed 4 MiB needles on
HEAD, but may read small needles internally. Roots and segments are still
read and decoded, and shared immutable objects are checked once per pass.
Inline filer entries are checked directly from the content returned by the
lookup; they have no backing needle and require no needle HEAD.
Verify is read-only: exit 0 means complete with no findings, 3 means complete
with findings, 1 means incomplete, and 2 means invalid arguments. `--depth data`
checks chunk hashes and requires an explicit timeout. `--orphans` only reports;
@@ -947,7 +960,7 @@ A restore makes a new volume from a snapshot. The new volume reads every chunk i
3. **Start v2's blockvolume** with the normal standalone command, its own volume id, endpoints and local root, the source's geometry (`--durable-blocks` and `--durable-blocksize`, for example `65536` and `4096`), and the same chunk settings as the source (`--chunk-filer`, `--chunk-path`, `--chunk-control-endpoint`). v2 serves at once. A start with other geometry flags is refused with `geometry_mismatch` and exits 78, creating no local store; the refusal names the record's values.
4. **Reads fill v2.** A block in a chunk that v2 does not hold yet is read from the source's snapshot; the read waits for that chunk, which is then kept locally. There is no background copy: a chunk that is never read stays in the source's snapshot.
- Progress is the volume's count of chunks still absent: `Chunk.Stats.AbsentChunks` in `GET http://STATUS_OF_V2/status/durable?volume=v2` (0 means every chunk is local).
- That progress is written to v2's local store at its next checkpoint. If v2's blockvolume is killed before then, the chunks it made local since are absent again after the restart and are fetched again from the source's snapshot on their next read. No data is lost: the source's snapshot still holds them.
- That progress is written to v2's local store when v2 is written to, or at its next checkpoint; a volume that has only been read takes none. After any restart of v2's blockvolume before then, clean or not, the chunks it made local are absent again and are fetched again from the source's snapshot on their next read. No data is lost: the source's snapshot still holds them.
- To make every chunk local, read the whole device once (for example with `dd` to `/dev/null`).
- **A restored volume takes no scheduled snapshot until its whole device has been read once**: while any chunk is absent, each scheduled snapshot is skipped and counted as `restoring`.
- A manual snapshot (`ops chunk snapshot`) is taken in that state too. It names the source's chunks for every chunk v2 has not made local, so, like any snapshot of v2, it cannot be restored (below).
+3 -2
View File
@@ -1,6 +1,6 @@
# Troubleshooting
**Coming in v1.0.1 (on `main`, not in v1.0.0).** `cluster.check` in `sw-block shell` runs the checks below in the order a start-up fails and prints
`cluster.check` in `sw-block shell` runs the checks below in the order a start-up fails and prints
one line per check: `ok`, `FAIL`, `not checked here` or `not applicable`. A `FAIL` line names its section on this page. Each section
begins with the same one-sentence cure the command prints, then says what you see and how to fix it.
@@ -131,7 +131,8 @@ prove a new failure, so read the holder's log. Off the host: `not checked here:
local-engine volume: `not applicable: no chunk store`.
**Fix:** a retryable code (`remote_unavailable`) clears when SeaweedFS answers again; keep free capacity in
SeaweedFS. See [recovery point and sync policy](operator-guide.md#recovery-point-and-sync-policy).
SeaweedFS. `remote_unavailable` also follows a request that ran out of its own 5-minute bound while SeaweedFS was
still answering (a long first cut); rerun it: the work already done is kept. See [recovery point and sync policy](operator-guide.md#recovery-point-and-sync-policy).
## volume.cleaning