Compare commits

..
Author SHA1 Message Date
Chris LuandClaude Opus 5.5 f400a0c696 release notes: test that a changed-file path keeps its spaces
pr_files moves to module level so the test can stub gh; main keeps the
failure tracking around it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 22:14:03 -08:00
Chris LuandClaude Opus 5.5 a957802c6d release notes: keep indentation when comparing the grouped lines
An indented "    ### Filer" (a Markdown code block) compared equal to
the script's heading once stripped, so the rewrite turned it into a
heading. Only trailing whitespace is ignored now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:51:58 -08:00
Chris LuandClaude Opus 5.5 19b51cec32 release notes: refuse headings that are not the script's own grouping
A hand-written heading that matches a section name, such as "### Security"
over a filer PR, passed as scaffolding and was replaced by the component
heading. Headings in What's Changed are now accepted only when regrouping
gives the same lines back; otherwise the notes are left unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:49:22 -08:00
Chris LuandClaude Opus 5.5 916bba2609 release notes: accept only the script's own headings between the PRs
A hand-written "### " heading in What's Changed was taken for a component
heading and dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:08:33 -08:00
Chris LuandClaude Opus 5.5 8b783a3933 release notes: split a PR's changed files by line, not by space
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 20:00:39 -08:00
Chris LuandClaude Opus 5.5 fb3a41f224 release notes: skip the release edit when the notes are already grouped
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:42:39 -08:00
Chris LuandClaude Opus 5.5 f1eac773cc release notes: read the author from the PR line's own by-clause
A title that itself contains "by @someone in" gave the wrong author, and a
dependabot mention there sent the PR to Dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:42:33 -08:00
Chris LuandClaude Opus 5.5 15e7aecdaa ci: run the release notes grouping tests
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:42:10 -08:00
Chris LuandClaude Opus 5.5 bf02a57bf2 release notes: leave the notes alone when What's Changed has non-PR lines
A hand-added bullet or a line in a shape the parser does not know was
dropped from the rewritten section. Stop instead, so the flat notes stay.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:41:55 -08:00
Chris LuandClaude Opus 5.5 f697808439 release notes: do not publish when a PR's files could not be read
A failed lookup filed the PR under Other and the notes were still written.
Print them, but leave the release alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:41:47 -08:00
Chris LuandClaude Opus 5.5 8ce51ce629 release notes: let files under test/ decide only test-only PRs
A PR with no title prefix that changes one S3 file and two Python tests
under test/s3 was filed under Tests and CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:41:15 -08:00
Chris LuandClaude Opus 5.5 7144c3c5cf release notes: keep the Full Changelog link when no one is new
Without a New Contributors section the changelog line follows the PR list
directly, so it was read as part of What's Changed and dropped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 19:41:08 -08:00
Chris LuandClaude Opus 5.5 1fb0d8d53f release: group the release notes by component
GitHub's generated notes are one flat list of PRs in merge order. After the
release is created, a new step sorts them under component headings (S3 API,
S3 Tables and Iceberg, Vectors, Filer, Mount, Volume Server, Rust Volume
Server, Erasure Coding, Master and Topology, Admin UI and Workers, Shell,
Security, Kubernetes/Helm, Core and CLI, Documentation, Tests and CI), with
dependency bumps folded into a collapsed block at the end.

The section comes from the PR title prefix ("s3api:", "fix(mount):",
"filer.sync:", "rust volume:"); a PR without a recognised prefix is placed by
the files it changes. Each line stays as GitHub wrote it, the New
Contributors and Full Changelog parts are kept, and rerunning on grouped
notes changes nothing. The step runs with continue-on-error, so a failure
only leaves the flat list; the script can be rerun by hand with --write.

On the 4.54 notes it places all 138 PRs, none in "Other".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011UpvaiJJGR5PzmkzuMU1mT
2026-11-17 19:17:24 -08:00
717 changed files with 6534 additions and 65407 deletions

No files matched your search

+1 -3
View File
@@ -28,9 +28,7 @@ runs:
# Cosign 3 also defaults to --use-signing-config, which insists on a
# bundle for its output; turning it off falls back to the default
# Fulcio and Rekor URLs, which is all the .sig layout ever used.
# --recursive signs every platform manifest in every registry, which
# outlasts the 3m default timeout when Fulcio or Rekor is slow.
cosign sign --yes --recursive --timeout 15m \
cosign sign --yes --recursive \
--new-bundle-format=false --use-signing-config=false \
$IMAGES
+21 -92
View File
@@ -22,16 +22,6 @@ CHART = ROOT / "k8s/charts/seaweedfs"
SECTIONS = ("jwt.signing", "jwt.signing.read", "jwt.filer_signing", "jwt.filer_signing.read")
KEYS = {section: f"active-{index}" for index, section in enumerate(SECTIONS)}
ESCAPED_HEADER = '["jw\\u0074".signing]\nkey = "existing"'
# No workload is needed to exercise Helm's real lookup and update.
RELEASE_SETTINGS = (
"master.enabled=false", "volume.enabled=false", "filer.enabled=false",
"global.seaweedfs.createClusterRole=false",
"global.seaweedfs.securityConfig.jwtSigning.volumeWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.volumeRead=true",
"global.seaweedfs.securityConfig.jwtSigning.filerWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.filerRead=true",
)
CONFIGMAP_CHART = ("seaweedfs", "--repo", "https://seaweedfs.github.io/seaweedfs/helm", "--version", "4.54.0")
def run(*args):
@@ -87,7 +77,8 @@ def fixtures():
def check_generated(value):
assert len(value) == 64 and value.isascii() and value.isalnum(), "invalid generated JWT key"
decoded = base64.b64decode(value, validate=True).decode("ascii")
assert len(decoded) == 10 and decoded.isascii() and decoded.isalnum(), "invalid generated JWT key"
def check_helpers(helm, reference_helm):
@@ -156,11 +147,20 @@ def check_upgrades(helm, context):
legacy = "seaweedfs-security-config"
kubectl = ["kubectl", "--context", context, "-n", namespace]
release_args = ["jk", str(CHART), "--kube-context", context, "-n", namespace]
for setting in RELEASE_SETTINGS:
# No workload is needed to exercise Helm's real ConfigMap lookup and update.
for setting in (
"master.enabled=false", "volume.enabled=false", "filer.enabled=false",
"global.seaweedfs.createClusterRole=false",
"global.seaweedfs.securityConfig.jwtSigning.volumeWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.volumeRead=true",
"global.seaweedfs.securityConfig.jwtSigning.filerWrite=true",
"global.seaweedfs.securityConfig.jwtSigning.filerRead=true",
):
release_args += ["--set", setting]
def stored():
return secret_keys(kubectl, current)
cm = json.loads(run(*kubectl, "get", "configmap", current, "-o", "json"))
return keys(cm["data"]["security.toml"])
def upgrade():
run(helm, "upgrade", *release_args)
@@ -168,8 +168,8 @@ def check_upgrades(helm, context):
def patch(raw):
# Seed previous-release content without taking Helm 4's SSA ownership.
run(*kubectl, "patch", "secret", current, "--type=merge", "--field-manager=helm", "-p",
json.dumps({"stringData": {"security.toml": raw}}))
run(*kubectl, "patch", "configmap", current, "--type=merge", "--field-manager=helm", "-p",
json.dumps({"data": {"security.toml": raw}}))
run(*kubectl, "create", "namespace", namespace)
try:
@@ -194,24 +194,17 @@ def check_upgrades(helm, context):
assert upgrade() == actual, f"{name}: subsequent upgrade changed a key"
print(f"PASS upgrade: {name}")
# Migration from the ConfigMaps of earlier chart versions, then precedence of the Secret.
configmap_raw = "\n".join(f'[{section}]\nkey = "configmap-{index}"'
for index, section in enumerate(SECTIONS))
run(*kubectl, "create", "configmap", current, "--from-literal=security.toml=" + configmap_raw)
run(*kubectl, "delete", "secret", current)
assert upgrade() == keys(configmap_raw), "ConfigMap keys were not preserved"
print("PASS upgrade: ConfigMap migration")
# Migration from the old chart name, followed by precedence of the current name.
legacy_raw = "\n".join(f'[{section}]\nkey = "legacy-{index}"'
for index, section in enumerate(SECTIONS))
run(*kubectl, "delete", "configmap", current)
run(*kubectl, "create", "configmap", legacy, "--from-literal=security.toml=" + legacy_raw)
run(*kubectl, "delete", "secret", current)
run(*kubectl, "delete", "configmap", current)
assert upgrade() == keys(legacy_raw), "legacy ConfigMap keys were not preserved"
print("PASS upgrade: legacy ConfigMap migration")
current_raw = next(fixtures())[1]
patch(current_raw)
assert upgrade() == keys(current_raw), "legacy ConfigMap overrode the Secret"
print("PASS upgrade: Secret takes precedence")
assert upgrade() == keys(current_raw), "legacy ConfigMap overrode current ConfigMap"
print("PASS upgrade: current ConfigMap takes precedence")
patch(ESCAPED_HEADER)
try:
@@ -220,76 +213,13 @@ def check_upgrades(helm, context):
assert "unsupported quoted section header" in error.stderr, error.stderr
else:
raise AssertionError("unsupported quoted header silently rotated its key")
assert stored()["jwt.signing"] == "existing"
assert keys(run(*kubectl, "get", "configmap", current, "-o",
"jsonpath={.data.security\\.toml}"))["jwt.signing"] == "existing"
print("PASS upgrade: unsupported quoted header leaves stored key untouched")
finally:
run(*kubectl, "delete", "namespace", namespace, "--wait=false")
def secret_keys(kubectl, name):
secret = json.loads(run(*kubectl, "get", "secret", name, "-o", "json"))
return keys(base64.b64decode(secret["data"]["security.toml"]).decode())
def check_configmap_release_upgrade(helm, context):
namespace = "jwt-key-migrate-" + uuid.uuid4().hex[:8]
name = "jk-seaweedfs-security-config"
kubectl = ["kubectl", "--context", context, "-n", namespace]
common = ["--kube-context", context, "-n", namespace]
for setting in RELEASE_SETTINGS:
common += ["--set", setting]
upgrade = ["upgrade", "jk", str(CHART), *common, "--set", "master.enabled=true"]
def refuse_partitioned(stage):
try:
run(helm, *upgrade, "--set", "master.updatePartition=1")
except subprocess.CalledProcessError as error:
assert "updatePartition=0" in error.stderr, error.stderr
else:
raise AssertionError(f"partitioned upgrade removed the ConfigMap ({stage})")
def exists(kind):
return run(*kubectl, "get", kind, name, "--ignore-not-found", "-o", "name").strip()
run(*kubectl, "create", "namespace", namespace)
try:
run(helm, "install", "jk", *CONFIGMAP_CHART, *common)
before = keys(run(*kubectl, "get", "configmap", name, "-o", "jsonpath={.data.security\\.toml}"))
assert set(before) == set(SECTIONS), "ConfigMap chart omitted a JWT section"
refuse_partitioned("ConfigMap release")
print("PASS upgrade: partitioned upgrade from the ConfigMap chart is refused")
# Fail an upgrade after Helm created the Secret, so it never removes the ConfigMap.
run(*kubectl, "create", "quota", "no-statefulsets", "--hard=count/statefulsets.apps=0")
try:
run(helm, *upgrade)
except subprocess.CalledProcessError as error:
assert "quota" in error.stderr, error.stderr
else:
raise AssertionError("upgrade was not blocked by the quota")
run(*kubectl, "delete", "quota", "no-statefulsets")
assert exists("secret") and exists("configmap"), "failed upgrade did not leave both objects"
refuse_partitioned("retry after a failed upgrade")
print("PASS upgrade: partitioned retry after a failed migration is refused")
run(helm, "upgrade", "jk", str(CHART), *common)
assert secret_keys(kubectl, name) == before, "upgrade from the ConfigMap chart changed a key"
assert not exists("configmap"), "upgrade left the ConfigMap behind"
print("PASS upgrade: ConfigMap chart release moves its keys to the Secret")
# The unprefixed legacy name can belong to another release in the namespace.
other = "seaweedfs-security-config"
run(*kubectl, "create", "configmap", other, '--from-literal=security.toml=[jwt.signing]\nkey = "other"')
run(*kubectl, "annotate", "configmap", other, "meta.helm.sh/release-name=other",
"meta.helm.sh/release-namespace=" + namespace)
run(helm, *upgrade, "--set", "master.updatePartition=1")
assert secret_keys(kubectl, name) == before, "another release's ConfigMap changed a key"
assert run(*kubectl, "get", "configmap", other, "-o", "name").strip(), "removed another release's ConfigMap"
print("PASS upgrade: another release's legacy ConfigMap does not block a partitioned upgrade")
finally:
run(*kubectl, "delete", "namespace", namespace, "--wait=false")
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--helm", default="helm")
@@ -300,7 +230,6 @@ def main():
check_helpers(args.helm, args.reference_helm)
if args.context:
check_upgrades(args.helm, args.context)
check_configmap_release_upgrade(args.helm, args.context)
if __name__ == "__main__":
@@ -0,0 +1,307 @@
#!/usr/bin/env python3
"""Regroup a GitHub release's generated notes by component.
GitHub's generated notes are one flat list of PRs in merge order. This keeps every
line as GitHub wrote it, but sorts the PRs under component headings (S3 API, Filer,
Mount, Volume Server, ...), with dependency bumps folded at the end.
The component comes from the PR title prefix, which nearly every PR has
("s3api: ...", "fix(mount): ...", "filer.sync: ...", "rust volume: ..."). A PR with
no recognised prefix is placed by the files it changes.
Usage:
release_notes_by_component.py --tag 4.54 # print the regrouped notes
release_notes_by_component.py --tag 4.54 --write # also update the release
Running it again on notes it already regrouped gives the same result.
"""
import argparse
import json
import re
import subprocess
import sys
# Display order. Each PR lands in exactly one section.
SECTIONS = [
"S3 API",
"S3 Tables and Iceberg",
"Vectors",
"Filer",
"Mount",
"Volume Server",
"Rust Volume Server",
"Erasure Coding",
"Master and Topology",
"Admin UI and Workers",
"Shell",
"Security",
"Message Queue",
"Kubernetes, Helm and Deployment",
"Core and CLI",
"Documentation",
"Tests and CI",
"Other",
"Dependencies",
]
# Title scope -> section, first match wins. Matched against each lower-cased scope
# token, e.g. "filer.sync", "s3 lifecycle", "weed/s3api" (a "weed/" prefix is
# dropped first). Order matters: specific scopes come before the general ones
# they start with (s3tables before s3, volume.fsck before volume).
SCOPE_RULES = [
(r"(build\(deps\)|deps|dependabot)\b", "Dependencies"),
(r"(test|tests|e2e|integration)\b|.*\btests?$|test/", "Tests and CI"),
(r"(rust[ -]?volume|seaweed-volume|volume\(rust\)|rust)\b", "Rust Volume Server"),
(r"(s3 ?vectors?|vectors?|seaweed-vector|weed-vector|lance)\b", "Vectors"),
(r"(s3 ?tables|iceberg)\b", "S3 Tables and Iceberg"),
(r"(s3 sink|remote|remote_storage|filer|webdav|sftp|ftp|notification|replication|"
r"redis\d*|leveldb\d*|backup)\b", "Filer"),
(r"(s3|s3api|iam|oidc|sts|credential|sse|cors|policy|object ?lock)\b", "S3 API"),
(r"(mount|fuse)\b", "Mount"),
(r"(ec|ec_\w+|ec\.\w+|erasure[ _-]?coding|worker/ec)\b", "Erasure Coding"),
(r"(master|topology|wdclient|cluster|raft|placement)\b", "Master and Topology"),
(r"(admin|worker|weed-worker|plugin|plugin worker|maintenance)\b",
"Admin UI and Workers"),
(r"(shell|fsck|volume\.\w+|fs\.\w+|collection\.\w+|bucket\.\w+)", "Shell"),
(r"(volume|volume_\w+|storage|vacuum|operation|compression|needle)\b", "Volume Server"),
(r"(security|tls|mtls|jwt|grpc|kms)\b", "Security"),
(r"(mq|kafka|messaging)\b", "Message Queue"),
(r"(helm|k8s|kubernetes|operator|csi|docker|grafana|install\.sh|chart|snap|terraform)\b",
"Kubernetes, Helm and Deployment"),
(r"(docs?|readme|wiki)\b", "Documentation"),
(r"(ci|release|build|github|workflow|actions)\b", "Tests and CI"),
(r"(server|command|mini|weed-db|weed|util|pb|cmd|glog|stats|telemetry|query|config)\b",
"Core and CLI"),
]
# Changed path prefix -> section, for PRs whose title has no usable prefix.
# Longest prefix wins.
PATH_RULES = {
"weed/s3api/s3tables/": "S3 Tables and Iceberg",
"weed/s3api/iceberg/": "S3 Tables and Iceberg",
"weed/s3api/s3vectors/": "Vectors",
"weed/s3api/lance/": "Vectors",
"seaweed-vector/": "Vectors",
"weed/s3api/": "S3 API",
"weed/iam/": "S3 API",
"weed/iamapi/": "S3 API",
"weed/credential/": "S3 API",
"weed/filer/": "Filer",
"weed/filer_client/": "Filer",
"weed/server/filer": "Filer",
"weed/server/webdav": "Filer",
"weed/sftpd/": "Filer",
"weed/replication/": "Filer",
"weed/notification/": "Filer",
"weed/remote_storage/": "Filer",
"weed/mount/": "Mount",
"weed/storage/erasure_coding/": "Erasure Coding",
"weed/ec/": "Erasure Coding",
"weed/worker/tasks/erasure_coding/": "Erasure Coding",
"weed/storage/": "Volume Server",
"weed/server/volume": "Volume Server",
"weed/operation/": "Volume Server",
"seaweed-volume/": "Rust Volume Server",
"weed/topology/": "Master and Topology",
"weed/server/master": "Master and Topology",
"weed/wdclient/": "Master and Topology",
"weed/cluster/": "Master and Topology",
"weed/placement/": "Master and Topology",
"weed/admin/": "Admin UI and Workers",
"weed/worker/": "Admin UI and Workers",
"weed/plugin/": "Admin UI and Workers",
"seaweed-worker/": "Admin UI and Workers",
"weed/shell/": "Shell",
"weed/security/": "Security",
"weed/kms/": "Security",
"weed/mq/": "Message Queue",
"k8s/": "Kubernetes, Helm and Deployment",
"docker/": "Kubernetes, Helm and Deployment",
"snap/": "Kubernetes, Helm and Deployment",
"terraform/": "Kubernetes, Helm and Deployment",
"weed/": "Core and CLI",
"test/": "Tests and CI",
".github/": "Tests and CI",
}
PR_LINE = re.compile(r"^\* (?P<title>.+?) by @(?P<author>\S+) in https://github\.com/\S+/pull/(?P<num>\d+)\s*$")
# Lines regroup() writes between the PRs, so a second run accepts them.
SCAFFOLD = re.compile(r"^$|^### (%s)$|^<details><summary>Dependencies \(\d+ updates?\)</summary>$|^</details>$"
% "|".join(re.escape(s) for s in SECTIONS))
# "fix(s3tables,s3vectors): ...", "s3 lifecycle: ...", "[Volume] ...", "Fix/admin ..."
CONVENTIONAL = re.compile(r"^(?P<type>[a-z]+)\((?P<scope>[^)]*)\)!?$")
TYPE_ONLY = {"fix", "feat", "feature", "perf", "refactor", "chore", "style", "revert", "improvement"}
def scope_of(title):
"""Return the raw scope text of a PR title, or ""."""
t = title.strip()
m = re.match(r"^\[([^\]]{1,40})\]", t)
if m:
return m.group(1)
m = re.match(r"^(?:fix|feat|feature)/(\S+)", t, re.I)
if m:
return m.group(1)
head, sep, _ = t.partition(":")
if not sep or len(head) > 50:
return ""
head = head.strip()
m = CONVENTIONAL.match(head.lower())
if m:
kind, scope = m.group("type"), m.group("scope")
if kind in ("test", "tests", "ci"):
return "test"
if kind == "docs":
return "docs"
if kind == "build" and scope == "deps":
return "build(deps)"
return scope
if head.lower() in TYPE_ONLY:
return ""
return head
def section_by_scope(scope):
if scope.strip().lower() == "build(deps)":
return "Dependencies"
for token in re.split(r"\s*[,+&]\s*|\s+and\s+", scope.lower()):
token = token.strip()
token = re.sub(r"^weed[/ ]", "", token)
if not token:
continue
for pattern, section in SCOPE_RULES:
if re.match(pattern, token):
return section
return ""
def section_by_paths(paths):
votes = {}
code = [p for p in paths if not p.endswith(("_test.go", "_test.rs")) and not p.startswith("test/")]
for p in code or paths:
if p.endswith(".md"):
section = "Documentation"
else:
best = max((pre for pre in PATH_RULES if p.startswith(pre)), key=len, default="")
section = PATH_RULES.get(best, "Other")
votes[section] = votes.get(section, 0) + 1
if not votes:
return "Other"
# Most files wins; ties go to the earlier section in display order.
return max(votes, key=lambda s: (votes[s], -SECTIONS.index(s)))
def classify(title, author, pr_files):
if author.startswith("dependabot") or title.lower().startswith("build(deps)"):
return "Dependencies"
section = section_by_scope(scope_of(title))
if section:
return section
return section_by_paths(pr_files())
def split_notes(body):
"""Split generated notes into (PR lines, the text before them, the text after,
the non-blank lines of What's Changed)."""
lines = body.replace("\r\n", "\n").split("\n")
start = next((i for i, l in enumerate(lines) if l.strip() == "## What's Changed"), None)
if start is None:
return [], body, "", []
end = next((i for i in range(start + 1, len(lines))
if lines[i].startswith(("## ", "**Full Changelog**"))), len(lines))
prs, stray = [], []
block = [l.rstrip() for l in lines[start + 1:end] if l.strip()]
for line in lines[start + 1:end]:
if PR_LINE.match(line):
prs.append(line)
elif not SCAFFOLD.match(line.strip()):
stray.append(line)
if prs and stray:
raise ValueError("What's Changed has lines that are not PRs: %r" % stray[:3])
before = "\n".join(lines[:start]).rstrip()
after = "\n".join(lines[end:]).strip()
return prs, before, after, block
def regroup(body, pr_files):
prs, before, after, block = split_notes(body)
if not prs:
return body
groups = {s: [] for s in SECTIONS}
for line in prs:
m = PR_LINE.match(line)
num = int(m.group("num"))
groups[classify(m.group("title"), m.group("author"), lambda: pr_files(num))].append(line)
out = [before, ""] if before else []
out.append("## What's Changed")
for section in SECTIONS:
items = groups[section]
if not items:
continue
out.append("")
if section == "Dependencies":
out.append("<details><summary>Dependencies (%d update%s)</summary>" % (len(items), "" if len(items) == 1 else "s"))
out.append("")
out.extend(items)
out.append("")
out.append("</details>")
else:
out.append("### " + section)
out.extend(items)
if after:
out.extend(["", after])
notes = "\n".join(out).strip() + "\n"
# Headings are accepted only as this script's own grouping: a hand-written
# "### Security" over PRs of other components would otherwise be dropped.
if len(block) != len(prs) and split_notes(notes)[3] != block:
raise ValueError("What's Changed has headings that do not match the component grouping")
return notes
def gh(*args, stdin=None):
return subprocess.run(["gh", *args], input=stdin, capture_output=True, text=True, check=True).stdout
def pr_files(repo, num):
return gh("pr", "view", str(num), "-R", repo, "--json", "files", "--jq", ".files[].path").splitlines()
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--repo", default="seaweedfs/seaweedfs")
ap.add_argument("--tag", required=True)
ap.add_argument("--write", action="store_true", help="update the release notes on GitHub")
args = ap.parse_args()
body = json.loads(gh("release", "view", args.tag, "-R", args.repo, "--json", "body"))["body"]
failed = []
def files_of(num):
try:
return pr_files(args.repo, num)
except subprocess.CalledProcessError as e:
print("warning: files of #%d: %s" % (num, e.stderr.strip()), file=sys.stderr)
failed.append(num)
return []
try:
notes = regroup(body, files_of)
except ValueError as e:
sys.exit("release %s: %s" % (args.tag, e))
sys.stdout.write(notes)
if notes.strip() == body.replace("\r\n", "\n").strip():
print("release %s: notes already grouped, nothing to change" % args.tag, file=sys.stderr)
return
if failed and args.write:
sys.exit("release %s: not writing, could not read the files of %s"
% (args.tag, ", ".join("#%d" % n for n in failed)))
if args.write:
gh("release", "edit", args.tag, "-R", args.repo, "--notes-file", "-", stdin=notes)
print("release %s: notes updated" % args.tag, file=sys.stderr)
if __name__ == "__main__":
main()
@@ -0,0 +1,190 @@
import importlib.util
from pathlib import Path
import unittest
from unittest import mock
def load():
path = Path(__file__).with_name("release_notes_by_component.py")
spec = importlib.util.spec_from_file_location("release_notes_by_component", path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
rn = load()
def no_files(num):
raise AssertionError("files of #%d should not be needed" % num)
class ClassifyTest(unittest.TestCase):
def check(self, title, section, author="someone", files=None):
got = rn.classify(title, author, (lambda: files) if files is not None else (lambda: no_files(0)))
self.assertEqual(got, section, title)
def test_title_prefixes(self):
cases = {
"s3: keep serving for -preStopSeconds after SIGTERM": "S3 API",
"s3api: keep a multipart upload's state on the object's owner filer": "S3 API",
"fix(s3api): reject an invalid storage class before uploading the body": "S3 API",
"s3 lifecycle: count filer entries a walk reads but skips as progress": "S3 API",
"iam/oidc: accept a list audience": "S3 API",
"fix(s3tables,s3vectors): bind DeleteNamespace to the authorized records": "S3 Tables and Iceberg",
"iceberg maintenance: expire snapshots": "S3 Tables and Iceberg",
"s3vectors: support TagResource": "Vectors",
"s3 vectors: page ListVectors": "Vectors",
"vector: compact segments": "Vectors",
"filer: fail health check when absent from lock ring": "Filer",
"filer.sync: skip a rewritten source version": "Filer",
"filer.remote.sync: retry": "Filer",
"webdav: honor locks": "Filer",
"remote.uncache, remote.meta.sync, remote.cache: keep local writes": "Filer",
"mount: cache dir": "Mount",
"fix(mount): flush on close": "Mount",
"volume: keep reads over the download limit local": "Volume Server",
"[Volume] Preserve request semantics in replica proxy reads": "Volume Server",
"operation: pad the marginal gzip test": "Volume Server",
"fix(storage): update deletion metrics": "Volume Server",
"rust volume: bulk-load needle maps": "Rust Volume Server",
"seaweed-volume: pin the status": "Rust Volume Server",
"volume(rust): fix": "Rust Volume Server",
"ec: mount shards through the encode's .vif": "Erasure Coding",
"ec.rebuild: pick the right disk": "Erasure Coding",
"ec_balance: spread shards": "Erasure Coding",
"master: unregister a volume server whose heartbeats stop": "Master and Topology",
"topology: never report negative free volume slots": "Master and Topology",
"wdclient: let master-pushed adds replace locations": "Master and Topology",
"admin: manage filer webhook targets": "Admin UI and Workers",
"Fix/admin cluster submenu": "Admin UI and Workers",
"weed-worker: retry": "Admin UI and Workers",
"shell: fix s3.circuitBreaker help examples": "Shell",
"volume.fsck: skip deleted": "Shell",
"fix(fsck): inspect references to deleted volumes": "Shell",
"security: optional dialed-host check": "Security",
"helm: drop the 4.53 vector metrics render guard": "Kubernetes, Helm and Deployment",
"install.sh: add --enterprise": "Kubernetes, Helm and Deployment",
"mq/kafka: commit offsets": "Message Queue",
"server: add -grpc.localSocketDir": "Core and CLI",
"pb: recover when a local gRPC socket file is deleted": "Core and CLI",
"docs: explain the 3-filer recommendation": "Documentation",
"test(fuse): two mounts staging the same files": "Tests and CI",
"test/s3vectors: a hardened cluster": "Tests and CI",
"s3vectors test: cover tags": "Tests and CI",
"ci: run the Python 3.9 jobs on 3.10": "Tests and CI",
"build(deps): bump actions/setup-go from 6 to 7": "Dependencies",
}
for title, section in cases.items():
self.check(title, section)
def test_dependabot_author(self):
self.check("Bump x from 1 to 2", "Dependencies", author="dependabot[bot]")
def test_no_prefix_uses_files(self):
self.check("Fix s3 cancelled read relookup", "S3 API",
files=["weed/s3api/s3api_object_handlers.go", "weed/s3api/s3api_object_handlers_test.go"])
self.check("Retry transient failures in star history generation", "Tests and CI",
files=[".github/scripts/star_history.py"])
self.check("fix: handle empty chunk list", "Filer",
files=["weed/filer/filechunks.go", "weed/storage/needle/needle.go", "weed/filer/reader_at.go"])
self.check("Improve everything", "Other", files=[])
def test_test_files_count_only_when_alone(self):
self.check("Make it faster", "Mount",
files=["weed/mount/weedfs.go", "test/fuse/a_test.go", "test/fuse/b_test.go"])
self.check("Make it right", "S3 API",
files=["weed/s3api/auth.go", "test/s3/iam/test_a.py", "test/s3/iam/test_b.py"])
self.check("Cover more", "Tests and CI", files=["test/s3/iam/test_a.py"])
def test_path_with_space(self):
with mock.patch.object(rn, "gh", return_value="test/s3/iam/policy cases.json\n"):
files = rn.pr_files("seaweedfs/seaweedfs", 1)
self.assertEqual(files, ["test/s3/iam/policy cases.json"])
self.check("Cover more", "Tests and CI", files=files)
NOTES = """## What's Changed
* filer: fail health check when absent from lock ring by @a in https://github.com/seaweedfs/seaweedfs/pull/12709
* s3: answer ClientDisconnected by @b in https://github.com/seaweedfs/seaweedfs/pull/12707
* build(deps): bump actions/setup-go from 6 to 7 by @dependabot[bot] in https://github.com/seaweedfs/seaweedfs/pull/12685
* filer.sync: skip a rewritten source version by @a in https://github.com/seaweedfs/seaweedfs/pull/12366
* Fix s3 cancelled read relookup by @c in https://github.com/seaweedfs/seaweedfs/pull/12600
## New Contributors
* @c made their first contribution in https://github.com/seaweedfs/seaweedfs/pull/12600
**Full Changelog**: https://github.com/seaweedfs/seaweedfs/compare/4.53...4.54
"""
class RegroupTest(unittest.TestCase):
def files(self, num):
self.assertEqual(num, 12600)
return ["weed/s3api/s3api_object_handlers.go"]
def test_regroup(self):
out = rn.regroup(NOTES, self.files)
self.assertEqual(out, """## What's Changed
### S3 API
* s3: answer ClientDisconnected by @b in https://github.com/seaweedfs/seaweedfs/pull/12707
* Fix s3 cancelled read relookup by @c in https://github.com/seaweedfs/seaweedfs/pull/12600
### Filer
* filer: fail health check when absent from lock ring by @a in https://github.com/seaweedfs/seaweedfs/pull/12709
* filer.sync: skip a rewritten source version by @a in https://github.com/seaweedfs/seaweedfs/pull/12366
<details><summary>Dependencies (1 update)</summary>
* build(deps): bump actions/setup-go from 6 to 7 by @dependabot[bot] in https://github.com/seaweedfs/seaweedfs/pull/12685
</details>
## New Contributors
* @c made their first contribution in https://github.com/seaweedfs/seaweedfs/pull/12600
**Full Changelog**: https://github.com/seaweedfs/seaweedfs/compare/4.53...4.54
""")
def test_idempotent(self):
once = rn.regroup(NOTES, self.files)
self.assertEqual(rn.regroup(once, self.files), once)
def test_every_pr_kept(self):
out = rn.regroup(NOTES, self.files)
for n in (12709, 12707, 12685, 12366, 12600):
self.assertEqual(out.count("/pull/%d\n" % n), 2 if n == 12600 else 1)
def test_changelog_kept_without_new_contributors(self):
body = NOTES.replace(
"## New Contributors\n* @c made their first contribution in https://github.com/seaweedfs/seaweedfs/pull/12600\n\n", "")
out = rn.regroup(body, self.files)
self.assertTrue(out.endswith("</details>\n\n**Full Changelog**: https://github.com/seaweedfs/seaweedfs/compare/4.53...4.54\n"), out)
self.assertEqual(rn.regroup(out, self.files), out)
def test_unknown_line_refused(self):
body = NOTES.replace("## New Contributors", "* a hand-written note\n\n## New Contributors")
with self.assertRaises(ValueError):
rn.regroup(body, self.files)
with self.assertRaises(ValueError):
rn.regroup(NOTES.replace("## What's Changed\n", "## What's Changed\n### Known issue\n"), self.files)
def test_hand_written_component_heading_refused(self):
with self.assertRaises(ValueError):
rn.regroup(NOTES.replace("## What's Changed\n", "## What's Changed\n### Security\n"), self.files)
once = rn.regroup(NOTES, self.files)
with self.assertRaises(ValueError):
rn.regroup(once.replace("\n### Filer\n", "\n ### Filer\n"), self.files)
def test_author_from_the_by_clause(self):
body = "## What's Changed\n* Bump a by @dependabot[bot] in docs by @alice in https://github.com/seaweedfs/seaweedfs/pull/7\n"
self.assertIn("### Documentation", rn.regroup(body, lambda n: ["README.md"]))
def test_notes_without_prs_unchanged(self):
body = "Hand-written notes\n\n**Full Changelog**: x"
self.assertEqual(rn.regroup(body, no_files), body)
if __name__ == "__main__":
unittest.main()
+11
View File
@@ -5,11 +5,13 @@ on:
branches: [ master ]
paths:
- '.github/actions/**'
- '.github/scripts/*release_notes_by_component.py'
- '.github/workflows/action-tests.yml'
pull_request:
branches: [ master ]
paths:
- '.github/actions/**'
- '.github/scripts/*release_notes_by_component.py'
- '.github/workflows/action-tests.yml'
concurrency:
@@ -28,3 +30,12 @@ jobs:
- name: Run cleanup action unit tests
run: python3 .github/actions/cleanup-stale-fuse-mounts/test_cleanup.py
release-notes-by-component:
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Run release notes grouping unit tests
run: python3 .github/scripts/test_release_notes_by_component.py
+3 -3
View File
@@ -33,7 +33,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4.39.4
uses: github/codeql-action/init@v4.39.3
# Override language selection by uncommenting this and choosing your languages
with:
languages: go
@@ -41,7 +41,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
# If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild
uses: github/codeql-action/autobuild@v4.39.4
uses: github/codeql-action/autobuild@v4.39.3
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -55,4 +55,4 @@ jobs:
# make release
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4.39.4
uses: github/codeql-action/analyze@v4.39.3
+1 -1
View File
@@ -434,7 +434,7 @@ jobs:
output: trivy-results.sarif
exit-code: '0'
- name: Upload Trivy scan results to GitHub Security
uses: github/codeql-action/upload-sarif@v4.39.4
uses: github/codeql-action/upload-sarif@v4.39.3
if: always()
with:
sarif_file: trivy-results.sarif
@@ -515,7 +515,7 @@ jobs:
- name: Upload Trivy scan results to GitHub Security
if: always()
uses: github/codeql-action/upload-sarif@v4.39.4
uses: github/codeql-action/upload-sarif@v4.39.3
with:
sarif_file: trivy-results.sarif
category: trivy-${{ matrix.variant }}
+20 -54
View File
@@ -259,40 +259,6 @@ jobs:
grep -q "security-config" /tmp/security.yaml
echo "Security configuration renders correctly"
echo "=== Testing volume server HTTPS ==="
awk '/^ *\[https.client\]$/{f=1;next} /^ *\[/{f=0} f' /tmp/security.yaml | grep -q 'enabled = false'
helm template test $CHART_DIR \
--set global.seaweedfs.enableSecurity=true \
--set global.seaweedfs.volumeHttps.enabled=true \
--set volumes.hot.replicas=1 \
> /tmp/volume-https.yaml
awk '/^ *\[https.client\]$/{f=1;next} /^ *\[/{f=0} f' /tmp/volume-https.yaml > /tmp/volume-https-client.txt
grep -q 'enabled = true' /tmp/volume-https-client.txt
grep -q 'cert = "/usr/local/share/ca-certificates/client/tls.crt"' /tmp/volume-https-client.txt
grep -q 'ca = "/usr/local/share/ca-certificates/ca/tls.crt"' /tmp/volume-https-client.txt
awk '/^ *\[https.volume\]$/{f=1;next} /^ *\[/{f=0} f' /tmp/volume-https.yaml \
| grep -q 'cert = "/usr/local/share/ca-certificates/volume/tls.crt"'
grep -q "'\*.test-seaweedfs-volume.default'" /tmp/volume-https.yaml
grep -q "'\*.test-seaweedfs-volume-hot.default'" /tmp/volume-https.yaml
test "$(grep -c 'scheme: HTTPS' /tmp/volume-https.yaml)" -eq 4
test "$(grep -c 'checksum/volume-https:' /tmp/volume-https.yaml)" -eq 4
if grep -q 'checksum/volume-https' /tmp/security.yaml; then
echo "FAIL: the volume HTTPS rollout annotation should only render while the option is on"
exit 1
fi
if helm template test $CHART_DIR --set global.seaweedfs.volumeHttps.enabled=true > /dev/null 2>/tmp/volume-https-nosec.err; then
echo "FAIL: volumeHttps without enableSecurity should fail to render"
exit 1
fi
grep -q "requires global.seaweedfs.enableSecurity" /tmp/volume-https-nosec.err
if helm template test $CHART_DIR --set global.seaweedfs.enableSecurity=true \
--set global.seaweedfs.volumeHttps.enabled=true --set allInOne.enabled=true > /dev/null 2>/tmp/volume-https-aio.err; then
echo "FAIL: volumeHttps with allInOne should fail to render"
exit 1
fi
grep -q "not supported with allInOne" /tmp/volume-https-aio.err
echo "Volume server HTTPS renders [https.volume], [https.client], certificate names, HTTPS probes and rollout annotations"
echo "=== Testing secure bucket-creation hook certificate mounts ==="
helm template test $CHART_DIR \
--show-only templates/shared/post-install-bucket-hook.yaml \
@@ -394,9 +360,9 @@ jobs:
def docs(manifest):
return [d for d in yaml.safe_load_all(manifest) if d]
def security_config(manifest, name):
def configmap(manifest, name):
for d in docs(manifest):
if d.get("kind") == "Secret" and d["metadata"]["name"] == name:
if d.get("kind") == "ConfigMap" and d["metadata"]["name"] == name:
return d
return None
@@ -421,13 +387,13 @@ jobs:
# security-related; preserve that so this PR is non-breaking on
# existing installs.
out = render({})
if security_config(out, "test-seaweedfs-security-config") is not None:
failed.append("defaults: security Secret should not render")
if configmap(out, "test-seaweedfs-security-config") is not None:
failed.append("defaults: security ConfigMap should not render")
else:
print("defaults: no security-config Secret (unchanged)")
print("defaults: no security-config ConfigMap (unchanged)")
# Case 2: filerWrite=true alone is the documented opt-in for
# the Admin UI Users tab. The Secret must render with
# the Admin UI Users tab. Configmap must render with
# [jwt.filer_signing] and NO [grpc.*] sections (cert paths
# only exist with mTLS).
out = render({
@@ -437,11 +403,11 @@ jobs:
# refuses to bind without authentication.
"admin.secret.adminPassword": "ci-admin-password",
})
cm = security_config(out, "test-seaweedfs-security-config")
cm = configmap(out, "test-seaweedfs-security-config")
if cm is None:
failed.append("filerWrite=true: security Secret missing")
failed.append("filerWrite=true: security ConfigMap missing")
else:
toml = cm["stringData"]["security.toml"]
toml = cm["data"]["security.toml"]
if "[jwt.filer_signing]" not in toml:
failed.append("filerWrite=true: security.toml missing [jwt.filer_signing]")
if "[grpc" in toml:
@@ -449,7 +415,7 @@ jobs:
if "[jwt.filer_signing]" in toml and "[grpc" not in toml:
print("filerWrite=true: security.toml has [jwt.filer_signing], no [grpc.*]")
# Case 3: filer + admin pods must MOUNT the security Secret
# Case 3: filer + admin pods must MOUNT the security ConfigMap
# under filerWrite=true so the JWT key reaches both processes.
# Cert volumes must NOT be present (no mTLS).
for wl in ("test-seaweedfs-filer", "test-seaweedfs-admin"):
@@ -469,11 +435,11 @@ jobs:
# with both [jwt.signing] and [grpc.*]. Guards against the
# decoupling change accidentally regressing the mTLS path.
out = render({"global.seaweedfs.enableSecurity": "true"})
cm = security_config(out, "test-seaweedfs-security-config")
cm = configmap(out, "test-seaweedfs-security-config")
if cm is None:
failed.append("enableSecurity=true: security Secret missing")
failed.append("enableSecurity=true: security ConfigMap missing")
else:
toml = cm["stringData"]["security.toml"]
toml = cm["data"]["security.toml"]
missing = [s for s in ("[jwt.signing]", "[grpc.master]") if s not in toml]
if missing:
failed.append(f"enableSecurity=true: security.toml missing {missing}")
@@ -490,8 +456,8 @@ jobs:
except subprocess.CalledProcessError as e:
failed.append(f"{null_path}=null: render failed: {e.output[:200] if e.output else e}")
continue
if security_config(out, "test-seaweedfs-security-config") is not None:
failed.append(f"{null_path}=null: should not render the security Secret")
if configmap(out, "test-seaweedfs-security-config") is not None:
failed.append(f"{null_path}=null: should not render configmap")
else:
print(f"{null_path}=null: render tolerates explicit null")
@@ -595,16 +561,16 @@ jobs:
mount = next((m for m in pod["containers"][0].get("volumeMounts", []) if m["name"] == "security-config"), None)
# The file has to land on one of weed's config search paths, so
# the target matters as much as the volume itself - and a volume
# of that name backed by anything but the chart's Secret
# of that name backed by anything but the chart's ConfigMap
# leaves `weed shell` without the signing key just the same.
target = ("/etc/seaweedfs/security.toml", "security.toml")
secret = "test-seaweedfs-security-config"
configmap = "test-seaweedfs-security-config"
if vol is None or mount is None:
failed.append("filerWrite=true: bucket hook does not mount security-config (s3.configure would fail)")
elif (mount.get("mountPath"), mount.get("subPath")) != target:
failed.append(f"filerWrite=true: bucket hook mounts security-config as {mount}")
elif vol.get("secret", {}).get("secretName") != secret:
failed.append(f"filerWrite=true: security-config is not backed by the {secret} Secret: {vol}")
elif vol.get("configMap", {}).get("name") != configmap:
failed.append(f"filerWrite=true: security-config is not backed by the {configmap} ConfigMap: {vol}")
else:
print("filerWrite=true: bucket hook mounts security-config at /etc/seaweedfs/security.toml")
@@ -2110,7 +2076,7 @@ jobs:
"--set", "admin.enabled=true", "--set", "admin.secret.adminPassword=ci",
"--set", "cosi.enabled=true", "--set", "networkPolicy.enabled=true",
"--set", "volumes.dc2.replicas=1",
# render the security Secret without its generated jwt key
# render the security ConfigMap without its generated jwt key
"--set", "global.seaweedfs.enableSecurity=true",
"--set", "global.seaweedfs.securityConfig.jwtSigning.volumeWrite=false",
]
+17 -1
View File
@@ -4,7 +4,9 @@ name: "release: bump version and cut the release"
# 1. bump MAJOR/MINOR in constants.go and the Helm Chart.yaml, commit to master
# 2. push the <appVersion> tag, which fans out to the workflows that trigger on
# `push: tags` (binaries_release*, container_release_unified, helm_manual_release)
# 3. create the GitHub release, with GitHub's generated notes
# 3. create the GitHub release, with GitHub's generated notes, then regroup those
# notes by component (S3 API, Filer, Mount, ...) with
# .github/scripts/release_notes_by_component.py
# 4. dispatch "Prepare release" in seaweedfs-csi-driver and seaweedfs-operator,
# which pick up the new master through `go get -u`, and wait for both
#
@@ -41,6 +43,7 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: read # the notes step reads a PR's files when its title has no component prefix
outputs:
app_version: ${{ steps.compute.outputs.app_version }}
sha: ${{ steps.tag.outputs.sha }}
@@ -174,6 +177,19 @@ jobs:
TAG: ${{ steps.compute.outputs.app_version }}
run: gh release create "$TAG" --title "$TAG" --generate-notes --verify-tag
# GitHub's generated notes are one flat list of PRs. Sort them under
# component headings by title prefix (or changed files). The release is
# already published, so a failure here only leaves the flat list; rerun
# the script by hand to fix it:
# python3 .github/scripts/release_notes_by_component.py --tag <tag> --write
- name: Group the release notes by component
if: ${{ !inputs.dry_run }}
continue-on-error: true
env:
GH_TOKEN: ${{ secrets.RELEASE_PAT || secrets.GITHUB_TOKEN }}
TAG: ${{ steps.compute.outputs.app_version }}
run: python3 .github/scripts/release_notes_by_component.py --repo "$GITHUB_REPOSITORY" --tag "$TAG" --write > /dev/null
downstream:
needs: release
if: ${{ inputs.downstream && !inputs.dry_run }}
@@ -1,74 +0,0 @@
name: "S3 listing study tests"
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/listing_study/**'
- '.github/workflows/s3-listing-study-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/filer/**'
- 'weed/server/**'
- 'test/s3/listing_study/**'
- '.github/workflows/s3-listing-study-tests.yml'
concurrency:
group: ${{ github.event.pull_request.number || github.ref }}/s3-listing-study-tests
cancel-in-progress: true
permissions:
contents: read
jobs:
listing-study:
name: s3-listing-study tools and strategies
runs-on: ubuntu-24.04
timeout-minutes: 40
defaults:
run:
working-directory: test/s3/listing_study
steps:
- name: Check out code
uses: actions/checkout@v7
with:
persist-credentials: false
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Cache pinned listing tools
uses: actions/cache@v6
with:
path: test/s3/listing_study/.work/tools
key: listing-study-tools-${{ runner.os }}-${{ hashFiles('test/s3/listing_study/Makefile', 'test/s3/listing_study/install_tools.py') }}
- name: Build weed and install the study's pinned tools
run: make build-weed tools
- name: Run the listing study against SeaweedFS
timeout-minutes: 15
run: make test
- name: Show logs on failure
if: failure()
run: |
tail -200 .work/weed.log || true
- name: Upload results
if: always()
uses: actions/upload-artifact@v7
with:
name: s3-listing-study-results
path: |
test/s3/listing_study/.work/run/results.json
test/s3/listing_study/.work/weed.log
retention-days: 14
+1 -11
View File
@@ -68,15 +68,7 @@ jobs:
with:
java-version: '17'
distribution: 'temurin'
- name: Cache suite Maven dependencies
if: runner.environment == 'github-hosted'
uses: actions/cache@v6
with:
path: ~/.m2/repository
key: snowflake-s3compat-m2-${{ hashFiles('test/s3/snowflake/run.sh') }}
restore-keys: |
snowflake-s3compat-m2-
cache: ${{ runner.environment == 'github-hosted' && 'maven' || '' }}
- name: Install SeaweedFS
run: |
@@ -86,8 +78,6 @@ jobs:
- name: Run Snowflake S3Compat API tests
timeout-minutes: 20
env:
MAVEN_ARGS: -ntp -s ${{ github.workspace }}/test/s3/snowflake/maven-settings.xml
run: |
# Starts weed server, creates the buckets/objects the suite needs,
# clones the upstream suite, and runs mvn -Dtest=S3CompatApiTest.
-6
View File
@@ -684,12 +684,6 @@ jobs:
pull() { for i in 1 2 3; do docker pull "$1" && return 0; sleep 15; done; return 1; }
pull apache/spark:3.5.1
- name: Cache Iceberg jars
uses: actions/cache@v6
with:
path: ~/.cache/seaweedfs-test-jars
key: iceberg-jars-${{ hashFiles('test/s3tables/catalog_spark/setup_test.go') }}
- name: Run go mod tidy
run: go mod tidy
@@ -1,57 +0,0 @@
name: "S3 Tigris Compatibility Tests"
on:
push:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/server/filer_server_handlers_*.go'
- 'test/s3/tigris_compat/**'
- '.github/workflows/s3-tigris-compat-tests.yml'
pull_request:
branches: [ master ]
paths:
- 'weed/s3api/**'
- 'weed/server/filer_server_handlers_*.go'
- 'test/s3/tigris_compat/**'
- '.github/workflows/s3-tigris-compat-tests.yml'
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.ref) || github.run_id }}
cancel-in-progress: ${{ github.event_name == 'pull_request' || (github.event_name == 'push' && !startsWith(github.ref, 'refs/tags/')) }}
permissions:
contents: read
jobs:
s3-tigris-compat-tests:
name: s3-api-compat-tests (Tigris)
runs-on: ubuntu-24.04
timeout-minutes: 20
steps:
- name: Check out code
uses: actions/checkout@v7
- name: Set up Go
uses: actions/setup-go@v7
with:
go-version-file: 'go.mod'
cache: ${{ runner.environment == 'github-hosted' }}
- name: Run s3-api-compat-tests
working-directory: test/s3/tigris_compat
run: make test
- name: Show server log on failure
if: failure()
working-directory: test/s3/tigris_compat
run: tail -200 weed-test.log || true
- name: Upload report
if: always()
uses: actions/upload-artifact@v7
with:
name: s3-tigris-compat-results
path: test/s3/tigris_compat/results.json
if-no-files-found: ignore
retention-days: 7
@@ -6,16 +6,12 @@ on:
paths:
- 'telemetry/**'
- 'weed/telemetry/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/telemetry-integration.yml'
pull_request:
branches: [ master ]
paths:
- 'telemetry/**'
- 'weed/telemetry/**'
- 'go.mod'
- 'go.sum'
- '.github/workflows/telemetry-integration.yml'
concurrency:
@@ -56,12 +56,8 @@ jobs:
- name: Setup Caddy
run: |
CADDY_VERSION=2.11.9
base="https://github.com/caddyserver/caddy/releases/download/v${CADDY_VERSION}"
curl -fsSLO "${base}/caddy_${CADDY_VERSION}_linux_amd64.tar.gz"
curl -fsSLO "${base}/caddy_${CADDY_VERSION}_checksums.txt"
grep " caddy_${CADDY_VERSION}_linux_amd64.tar.gz$" "caddy_${CADDY_VERSION}_checksums.txt" | sha512sum -c -
tar -xzf "caddy_${CADDY_VERSION}_linux_amd64.tar.gz" caddy
curl -fsSL "https://caddyserver.com/api/download?os=linux&arch=amd64" -o caddy
chmod +x caddy
./caddy version
echo "{
auto_https disable_redirects
+2 -2
View File
@@ -1,6 +1,6 @@
apiVersion: v1
description: SeaweedFS
name: seaweedfs
appVersion: "4.55"
appVersion: "4.54"
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
version: 4.55.0
version: 4.54.0
+5 -20
View File
@@ -30,12 +30,10 @@ so your deployment will be spread/HA.
The chart's templates render with Helm 3.16.3 and newer versions tested in CI.
Earlier Helm versions are not covered by this chart's compatibility checks.
When JWT signing is enabled, `security.toml` is kept in the
`<fullname>-security-config` Secret. A live upgrade reuses keys from that
Secret, or from the security ConfigMap of earlier chart versions (including
the legacy ConfigMap name); a key absent from them is generated. Plain
`helm template` does not read cluster state; use an install and upgrade
against a cluster to check key persistence.
When JWT signing is enabled, a live upgrade reuses keys from the existing
security ConfigMap (including the legacy ConfigMap name); a key absent from
that ConfigMap is generated. Plain `helm template` does not read cluster state;
use an install and upgrade against a cluster to check key persistence.
The key reader supports single-line quoted TOML strings in JWT sections,
including indented assignments, quoted key names, and bare or simply quoted
@@ -571,8 +569,6 @@ s3:
With `rules` left empty the route sends all traffic to the component's own Service and port. A rule may set `matches`, `filters`, `timeouts` and `backendRefs`, and a rule without `backendRefs` still routes to that Service. In all-in-one mode the master, volume, filer and s3 routes target the all-in-one Service. When S3 runs only on the filer (`filer.s3.enabled` without `s3.enabled`), the s3 route uses `filer.s3.port`.
Outside all-in-one mode, the volume Ingress and the default volume route target the `client-volume` Service, which lists only Ready volume pods. The `volume` Service also publishes pods that are not Ready yet, so their DNS records can exist before readiness. An explicit `backendRefs` entry that names the `volume` Service can therefore reach a volume server before it is Ready. Name the `client-volume` Service instead, with `volume.port`, and copy its `metadata.name` from `helm template` because long release names are truncated.
## Network Policies
In a namespace with a default-deny policy the install hangs: the components cannot resolve each other, and the post-install bucket hook waits on the master and filer until it gives up. `networkPolicy.enabled` renders one `NetworkPolicy` per component, selecting its pods by the standard `app.kubernetes.io/{name,instance,component}` labels and admitting traffic from the other pods of the release on the ports that component listens on.
@@ -614,17 +610,6 @@ Two things worth knowing before you turn this on:
The DNS selectors default to CoreDNS as kubeadm, kind and the managed offerings from AWS, Google and Azure install it. On OpenShift, override `egress.dnsNamespaceSelector` and `egress.dnsPodSelector` to match `openshift-dns`; see the comment in `values.yaml`.
## Volume server HTTPS
With `global.seaweedfs.enableSecurity`, gRPC between components uses mutual TLS, but the volume servers' HTTP port, which carries the file data, stays plaintext. Set `global.seaweedfs.volumeHttps.enabled: true` to serve it over TLS:
- `[https.volume]` points at the volume certificate, which then also names every volume group's service (`*.<fullname>-volume.<namespace>`), since volume servers register as `<pod>.<fullname>-volume.<namespace>`. With `certificates.externalCertificates`, the provided `<fullname>-volume-cert` needs those names.
- `[https.client]` is enabled with the client certificate and the chart CA, so every chart pod that talks to the volume servers does it over HTTPS.
- The volume probes use HTTPS.
- Every pod that reads `security.toml` gets a `checksum/volume-https` annotation, so switching the option on or off restarts them together.
The volume servers do not require client certificates, because kubelet probes cannot present one; enable JWT signing (`securityConfig.jwtSigning`) to authorize volume reads and writes. `[https.client]` also sends the admin UI's HTTP lookups on masters and S3 over HTTPS, which their plain listeners refuse, so the UI can miss volume public URLs and refuse SSE-S3 vector buckets. A volume Ingress or HTTPRoute needs its controller's HTTPS-backend setting. `weed mount`, the CSI driver and other clients outside the chart need their own `[https.client]` with the chart CA. The option is not supported with `allInOne`, whose volume server registers by pod IP.
## Common labels
`commonLabels` adds labels to the metadata of every object the chart creates. It may be a map or a template string rendering to one. The chart's own labels cannot be overridden, and pods (see `podLabels`) and `volumeClaimTemplates` are left unchanged.
@@ -729,7 +714,7 @@ global:
The engine registers its pod address with the masters and stores indexes through the filers and volume servers. Both Go and Rust volume servers use the same setup. The maintenance worker builds and updates ANN indexes; queries can scan data before indexing completes. Enabling filer write signing also requires clients writing directly to the filer HTTP API to supply a signed JWT.
The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The engine sizes its caches to a quarter of its memory limit.
The bundled engine images support Linux amd64 and arm64. Use `vector.imageOverride` to select a compatible engine build, `vector.masters` for an external cluster, and `vector.resources` to set memory and CPU limits. The cache defaults to 512 MiB and is configured with `vector.readCacheMB`.
`global.seaweedfs.enableSecurity` provisions and mounts the vector certificate and shared security configuration. With external certificates, provide the `<fullname>-vector-cert` secret (`my-seaweedfs-vector-cert` for release `my`). `fullname` follows `seaweedfs.fullname`, including `fullnameOverride`, `nameOverride`, and DNS-name truncation. Provide this secret alongside the existing CA and client secrets.
@@ -56,7 +56,6 @@ spec:
{{- with .Values.admin.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.admin.restartPolicy }}
{{- if .Values.admin.affinity }}
@@ -189,10 +188,6 @@ spec:
{{- else }}
-masters={{ range $index := until (.Values.master.replicas | int) }}${SEAWEEDFS_FULLNAME}-master-{{ $index }}.${SEAWEEDFS_FULLNAME}-master.{{ include "seaweedfs.namespace" $ }}:{{ $.Values.master.port }}{{ if lt $index (sub ($.Values.master.replicas | int) 1) }},{{ end }}{{ end }} \
{{- end }}
{{- /* admin lists the filers and S3 gateways the workers use from this group */}}
{{- if .Values.filer.filerGroup }}
-filerGroup={{ .Values.filer.filerGroup }} \
{{- end }}
{{- if $urlPrefix }}
-urlPrefix={{ $urlPrefix }} \
{{- end }}
@@ -318,8 +313,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -1,8 +1,5 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.allInOne.enabled }}
{{- if include "seaweedfs.volumeHttps" . }}
{{- fail "global.seaweedfs.volumeHttps is not supported with allInOne: its volume server registers by pod IP, which the volume certificate cannot name" }}
{{- end }}
{{- $s3PreStopSeconds := 0 }}
{{- if .Values.allInOne.s3.enabled }}
{{- $s3PreStopSeconds = .Values.allInOne.s3.preStopSeconds }}
@@ -507,8 +504,8 @@ spec:
name: {{ include "seaweedfs.fullname" . }}-master-config
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -38,14 +38,6 @@ spec:
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ include "seaweedfs.namespace" . }}'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ include "seaweedfs.namespace" . }}.svc'
- '*.{{ include "seaweedfs.fullname" . }}-master.{{ include "seaweedfs.namespace" . }}.svc.cluster.local'
{{- if include "seaweedfs.volumeHttps" . }}
{{- range $vname, $_ := deepCopy .Values.volumes | mergeOverwrite (dict "" .Values.volume) }}
{{- $volumeService := printf "%s.%s" (include "seaweedfs.componentName" (list $ (trimSuffix "-" (printf "volume-%s" $vname)))) (include "seaweedfs.namespace" $) }}
- '*.{{ $volumeService }}'
- '*.{{ $volumeService }}.svc'
- '*.{{ $volumeService }}.svc.cluster.local'
{{- end }}
{{- end }}
{{- if .Values.certificates.ipAddresses }}
ipAddresses:
{{- range .Values.certificates.ipAddresses }}
@@ -39,7 +39,6 @@ spec:
{{- with .Values.cosi.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.cosi.restartPolicy }}
{{- if .Values.cosi.affinity }}
@@ -196,8 +195,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -57,7 +57,6 @@ spec:
{{- end }}
annotations:
{{- toYaml $podAnnotations | nindent 8 }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.filer.restartPolicy }}
{{- if .Values.filer.affinity }}
@@ -453,8 +452,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -48,7 +48,6 @@ spec:
{{- $_ := set $podAnnotations "checksum/master-config" (include "seaweedfs.master.configChecksum" .) }}
annotations:
{{- toYaml $podAnnotations | nindent 8 }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.master.restartPolicy }}
{{- if .Values.master.affinity }}
@@ -300,8 +299,8 @@ spec:
name: {{ include "seaweedfs.fullname" . }}-master-config
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -54,7 +54,6 @@ spec:
{{- end }}
annotations:
{{- toYaml $podAnnotations | nindent 8 }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.s3.restartPolicy }}
{{- if .Values.s3.affinity }}
@@ -289,8 +288,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -43,7 +43,6 @@ spec:
{{- with .Values.sftp.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.sftp.restartPolicy }}
{{- if .Values.sftp.affinity }}
@@ -298,8 +297,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -269,20 +269,15 @@ true
{{- end -}}
{{- end -}}
{{/* The S3 service's Lance namespace URL, for a worker pinned before 4.56; empty when it serves none */}}
{{/* Lance namespace URL the worker's Lance container maintains; empty when unreachable */}}
{{- define "seaweedfs.worker.lanceNamespaceUrl" -}}
{{- if and .Values.s3.enabled .Values.s3.lancePort -}}
{{- if .Values.worker.namespaceUrl -}}
{{- .Values.worker.namespaceUrl -}}
{{- else if and .Values.s3.enabled .Values.s3.lancePort -}}
{{- printf "http://%s.%s:%d" (include "seaweedfs.componentName" (list . "s3")) (include "seaweedfs.namespace" .) (int .Values.s3.lancePort) -}}
{{- end -}}
{{- end -}}
{{/* "true" when the worker runs its Lance container: an S3 gateway of this release serves a Lance namespace, or the worker serves an external admin, which names its cluster's */}}
{{- define "seaweedfs.worker.lanceEnabled" -}}
{{- if or (include "seaweedfs.worker.lanceNamespaceUrl" .) .Values.filer.s3.enabled .Values.worker.adminServer -}}
true
{{- end -}}
{{- end -}}
{{/* Return the proper volume image */}}
{{- define "seaweedfs.volume.image" -}}
{{- if .Values.volume.imageOverride -}}
@@ -496,25 +491,6 @@ true
{{- end -}}
{{- end -}}
{{/* True when the volume servers serve HTTPS. Their certificates come from
enableSecurity, so the option fails without it. */}}
{{- define "seaweedfs.volumeHttps" -}}
{{- if ((.Values.global.seaweedfs).volumeHttps).enabled -}}
{{- if not .Values.global.seaweedfs.enableSecurity -}}
{{- fail "global.seaweedfs.volumeHttps.enabled requires global.seaweedfs.enableSecurity, which provides the certificates" -}}
{{- end -}}
true
{{- end -}}
{{- end -}}
{{/* Pod annotation that restarts the readers of security.toml when volume
HTTPS is switched on or off. */}}
{{- define "seaweedfs.volumeHttpsAnnotation" -}}
{{- with include "seaweedfs.volumeHttps" . -}}
checksum/volume-https: {{ sha256sum . | quote }}
{{- end -}}
{{- end -}}
{{/* Read a JWT key from the chart's existing security.toml without fromToml
(which requires Helm >=3.17). Args: (list "<section>" $raw).
Return the single-line TOML string token, including its quotes, so escapes
@@ -104,7 +104,7 @@
{{- if .Values.worker.metricsPort }}
{{- $ports = append $ports .Values.worker.metricsPort }}
{{- end }}
{{- if and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- if and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- $ports = append $ports .Values.worker.lanceMetricsPort }}
{{- end }}
{{- $targets = append $targets (dict "component" "worker" "ports" $ports) }}
@@ -286,8 +286,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -1,7 +1,7 @@
{{- include "seaweedfs.compat" . -}}
{{- if include "seaweedfs.securityConfigEnabled" . }}
apiVersion: v1
kind: Secret
kind: ConfigMap
metadata:
name: {{ include "seaweedfs.fullname" . }}-security-config
namespace: {{ include "seaweedfs.namespace" . | quote }}
@@ -11,8 +11,7 @@ metadata:
app.kubernetes.io/managed-by: {{ .Release.Service }}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
type: Opaque
stringData:
data:
{{- $fullname := include "seaweedfs.fullname" . }}
{{- $securityConfigName := printf "%s-security-config" $fullname }}
{{- $existing := lookup "v1" "ConfigMap" (include "seaweedfs.namespace" .) $securityConfigName }}
@@ -20,11 +19,7 @@ stringData:
{{- $legacyName := printf "%s-%s" (include "seaweedfs.name" .) "security-config" }}
{{- $existing = lookup "v1" "ConfigMap" (include "seaweedfs.namespace" .) $legacyName }}
{{- end }}
{{- $ownConfigMap := eq (dig "metadata" "annotations" "meta.helm.sh/release-name" "" $existing) .Release.Name }}
{{- if and $ownConfigMap (or (and .Values.master.enabled (gt (int .Values.master.updatePartition) 0)) (and .Values.filer.enabled (gt (int .Values.filer.updatePartition) 0))) }}
{{- fail "this upgrade moves security.toml from a ConfigMap to a Secret and removes the ConfigMap; run it with master.updatePartition=0 and filer.updatePartition=0 so no pod is left on the old template" }}
{{- end }}
{{- $existingToml := dig "data" "security.toml" "" (lookup "v1" "Secret" (include "seaweedfs.namespace" .) $securityConfigName) | b64dec | default (dig "data" "security.toml" "" $existing) }}
{{- $existingToml := dig "data" "security.toml" "" $existing }}
{{- $securityConfigValues := .Values.global.seaweedfs.securityConfig | default dict }}
{{- $jwtSigning := $securityConfigValues.jwtSigning | default dict }}
{{- $expiresAfterSeconds := $jwtSigning.expiresAfterSeconds | default dict }}
@@ -35,7 +30,7 @@ stringData:
# the jwt signing key is read by master and volume server
# the jwt defaults to expire after 10 seconds
[jwt.signing]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing" $existingToml) | default (randAlphaNum 64 | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
{{- if gt (int $expiresAfterSeconds.volumeWrite) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.volumeWrite }}
{{- end }}
@@ -47,7 +42,7 @@ stringData:
# - the Volume server validates the JWT on reading
# the jwt defaults to expire after 60 seconds
[jwt.signing.read]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing.read" $existingToml) | default (randAlphaNum 64 | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.signing.read" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
{{- if gt (int $expiresAfterSeconds.volumeRead) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.volumeRead }}
{{- end }}
@@ -59,7 +54,7 @@ stringData:
# - the Filer server validates the JWT on writing
# the jwt defaults to expire after 10 seconds
[jwt.filer_signing]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing" $existingToml) | default (randAlphaNum 64 | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
{{- if gt (int $expiresAfterSeconds.filerWrite) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.filerWrite }}
{{- end }}
@@ -71,7 +66,7 @@ stringData:
# - the Filer server validates the JWT on reading
# the jwt defaults to expire after 60 seconds
[jwt.filer_signing.read]
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing.read" $existingToml) | default (randAlphaNum 64 | quote) }}
key = {{ include "seaweedfs.existingTomlKey" (list "jwt.filer_signing.read" $existingToml) | default (randAlphaNum 10 | b64enc | quote) }}
{{- if gt (int $expiresAfterSeconds.filerRead) 0 }}
expires_after_seconds = {{ int $expiresAfterSeconds.filerRead }}
{{- end }}
@@ -126,25 +121,13 @@ stringData:
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
{{- if include "seaweedfs.volumeHttps" . }}
[https.client]
enabled = true
cert = "/usr/local/share/ca-certificates/client/tls.crt"
key = "/usr/local/share/ca-certificates/client/tls.key"
ca = "/usr/local/share/ca-certificates/ca/tls.crt"
[https.volume]
cert = "/usr/local/share/ca-certificates/volume/tls.crt"
key = "/usr/local/share/ca-certificates/volume/tls.key"
{{- else }}
# volume server https: set global.seaweedfs.volumeHttps.enabled
# volume server https options
# Note: work in progress!
# this does not work with other clients, e.g., "weed filer|mount" etc, yet.
[https.client]
enabled = false
[https.volume]
cert = ""
key = ""
{{- end }}
{{- end }}
{{- end }}
@@ -25,7 +25,6 @@ spec:
annotations:
{{- with .Values.podAnnotations }}{{ toYaml . | nindent 8 }}{{ end }}
{{- with .Values.vector.podAnnotations }}{{ toYaml . | nindent 8 }}{{ end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
{{- include "seaweedfs.imagePullSecrets" . | nindent 6 }}
automountServiceAccountToken: {{ .Values.global.seaweedfs.automountServiceAccountToken }}
@@ -56,9 +55,13 @@ spec:
- 'case "$POD_IP" in *:*) POD_IP="[$POD_IP]";; esac; exec /usr/bin/weed-vector --listen="$POD_IP:{{ .Values.vector.port }}" "$@"'
- vector
- {{ printf "--masters=%s" (.Values.vector.masters | default $masters) | quote }}
- {{ printf "--read-cache-mb=%d" (int .Values.vector.readCacheMB) | quote }}
{{- if .Values.filer.filerGroup }}
- {{ printf "--filer-group=%s" .Values.filer.filerGroup | quote }}
{{- end }}
{{- if .Values.vector.nprobes }}
- {{ printf "--nprobes=%d" (int .Values.vector.nprobes) | quote }}
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- --security-toml=/etc/seaweedfs/security.toml
{{- end }}
@@ -147,8 +150,8 @@ spec:
emptyDir: {}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
{{- range list "ca" "client" "vector" }}
@@ -1,6 +1,6 @@
{{- $volumeEnabled := or .Values.volume.enabled .Values.allInOne.enabled }}
{{- if and $volumeEnabled .Values.volume.httpRoute.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "client-volume")) .Values.allInOne.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "volume")) .Values.allInOne.enabled }}
apiVersion: gateway.networking.k8s.io/v1
kind: HTTPRoute
metadata:
@@ -2,7 +2,7 @@
{{- $volumeEnabled := or .Values.volume.enabled .Values.allInOne.enabled }}
{{- if and $volumeEnabled .Values.volume.ingress.enabled }}
{{- /* Determine service name based on deployment mode */}}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "client-volume")) .Values.allInOne.enabled }}
{{- $serviceName := ternary (include "seaweedfs.componentName" (list . "all-in-one")) (include "seaweedfs.componentName" (list . "volume")) .Values.allInOne.enabled }}
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion }}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion }}
@@ -1,42 +0,0 @@
{{- /* Ready-only backend for the volume ingress and HTTPRoute; the volume Service publishes not-ready pods for DNS.
Not named volume-client: every volume-<key> name belongs to a group under .Values.volumes. */}}
{{- if and .Values.volume.enabled (not .Values.allInOne.enabled) (or .Values.volume.ingress.enabled .Values.volume.httpRoute.enabled) }}
{{- $name := include "seaweedfs.componentName" (list . "client-volume") }}
{{- $volumes := deepCopy .Values.volumes | mergeOverwrite (dict "" .Values.volume) }}
{{- range $vname, $volume := $volumes }}
{{- $volumeName := trimSuffix "-" (printf "volume-%s" $vname) }}
{{- $volume := mergeOverwrite (deepCopy $.Values.volume) (dict "enabled" true) $volume }}
{{- if and $volume.enabled (eq (include "seaweedfs.componentName" (list $ $volumeName)) $name) }}
{{- fail (printf "The volume Ingress/HTTPRoute Service %q has the same name as the %s Service after truncation. Shorten fullnameOverride or the release name." $name $volumeName) }}
{{- end }}
{{- end }}
apiVersion: v1
kind: Service
metadata:
name: {{ $name }}
namespace: {{ include "seaweedfs.namespace" . | quote }}
labels:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: volume
helm.sh/chart: {{ .Chart.Name }}-{{ .Chart.Version | replace "+" "_" }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
{{- if .Values.volume.annotations }}
annotations:
{{- toYaml .Values.volume.annotations | nindent 4 }}
{{- end }}
spec:
clusterIP: None
internalTrafficPolicy: {{ .Values.volume.internalTrafficPolicy | default "Cluster" }}
{{- /* No metrics port, so the volume ServiceMonitor does not scrape each pod twice */}}
ports:
- name: "swfs-volume"
port: {{ .Values.volume.port }}
targetPort: {{ .Values.volume.port }}
protocol: TCP
selector:
app.kubernetes.io/name: {{ template "seaweedfs.name" . }}
app.kubernetes.io/instance: {{ .Release.Name }}
app.kubernetes.io/component: volume
{{- end }}
@@ -23,9 +23,6 @@ metadata:
{{- end }}
spec:
clusterIP: None
{{- /* The master hands out ${POD_NAME}.<this service> as soon as a volume server heartbeats, before it is Ready.
Ingress and HTTPRoute use the client-volume Service instead, which publishes only Ready pods. */}}
publishNotReadyAddresses: true
internalTrafficPolicy: {{ $volume.internalTrafficPolicy | default "Cluster" }}
ports:
- name: "swfs-volume"
@@ -55,7 +55,6 @@ spec:
{{- with $volume.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
{{- if $volume.affinity }}
affinity:
@@ -282,7 +281,7 @@ spec:
httpGet:
path: {{ $volume.readinessProbe.httpGet.path }}
port: {{ $volume.port }}
scheme: {{ if include "seaweedfs.volumeHttps" $ }}HTTPS{{ else }}{{ $volume.readinessProbe.httpGet.scheme }}{{ end }}
scheme: {{ $volume.readinessProbe.httpGet.scheme }}
initialDelaySeconds: {{ $volume.readinessProbe.initialDelaySeconds }}
periodSeconds: {{ $volume.readinessProbe.periodSeconds }}
successThreshold: {{ $volume.readinessProbe.successThreshold }}
@@ -294,7 +293,7 @@ spec:
httpGet:
path: {{ $volume.livenessProbe.httpGet.path }}
port: {{ $volume.port }}
scheme: {{ if include "seaweedfs.volumeHttps" $ }}HTTPS{{ else }}{{ $volume.livenessProbe.httpGet.scheme }}{{ end }}
scheme: {{ $volume.livenessProbe.httpGet.scheme }}
initialDelaySeconds: {{ $volume.livenessProbe.initialDelaySeconds }}
periodSeconds: {{ $volume.livenessProbe.periodSeconds }}
successThreshold: {{ $volume.livenessProbe.successThreshold }}
@@ -371,8 +370,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" $ }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" $ }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" $ }}-security-config
{{- end }}
{{- if $.Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -46,7 +46,6 @@ spec:
{{- with .Values.worker.podAnnotations }}
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with include "seaweedfs.volumeHttpsAnnotation" $ }}{{ . | nindent 8 }}{{ end }}
spec:
restartPolicy: {{ default .Values.global.seaweedfs.restartPolicy .Values.worker.restartPolicy }}
{{- if .Values.worker.affinity }}
@@ -228,7 +227,7 @@ spec:
{{- if .Values.worker.containerSecurityContext.enabled }}
securityContext: {{- omit .Values.worker.containerSecurityContext "enabled" | toYaml | nindent 12 }}
{{- end }}
{{- if include "seaweedfs.worker.lanceEnabled" . }}
{{- if include "seaweedfs.worker.lanceNamespaceUrl" . }}
- name: worker-lance
image: {{ template "seaweedfs.worker.image" . }}
imagePullPolicy: {{ default "IfNotPresent" .Values.global.seaweedfs.imagePullPolicy }}
@@ -237,21 +236,13 @@ spec:
valueFrom:
fieldRef:
fieldPath: metadata.name
{{- /* only a worker pinned before 4.56 reads these; later ones learn the cluster from admin */}}
{{- with include "seaweedfs.worker.lanceNamespaceUrl" . }}
- name: WEED_LANCE_NAMESPACE
value: {{ . | quote }}
{{- end }}
- name: WEED_MASTERS
value: {{ include "seaweedfs.masterServerArg" . | quote }}
{{- if .Values.filer.filerGroup }}
- name: WEED_FILER_GROUP
value: {{ .Values.filer.filerGroup | quote }}
{{- end }}
{{- /* the URL crosses a shell line; metacharacters must arrive as data, not syntax */}}
- name: LANCE_NAMESPACE_URL
value: {{ include "seaweedfs.worker.lanceNamespaceUrl" . | quote }}
{{- $mergedExtraEnvironmentVars := dict }}
{{- include "seaweedfs.mergeExtraEnvironmentVars" (dict "global" .Values.global.seaweedfs "component" .Values.worker "target" $mergedExtraEnvironmentVars) }}
{{- /* a duplicate would win over the chart's value and change --id or the cluster */}}
{{- $mergedExtraEnvironmentVars = omit $mergedExtraEnvironmentVars "POD_NAME" "WEED_LANCE_NAMESPACE" "WEED_MASTERS" "WEED_FILER_GROUP" }}
{{- /* a duplicate would win over the chart's value and change --id or --namespace */}}
{{- $mergedExtraEnvironmentVars = omit $mergedExtraEnvironmentVars "POD_NAME" "LANCE_NAMESPACE_URL" }}
{{- range $key := keys $mergedExtraEnvironmentVars | sortAlpha }}
{{- $value := index $mergedExtraEnvironmentVars $key }}
- name: {{ $key }}
@@ -280,6 +271,11 @@ spec:
{{- else }}
--admin={{ template "seaweedfs.fullname" . }}-admin.{{ include "seaweedfs.namespace" . }}:{{ .Values.admin.port }}{{ if .Values.admin.grpcPort }}.{{ .Values.admin.grpcPort }}{{ end }} \
{{- end }}
--namespace="$LANCE_NAMESPACE_URL" \
--masters={{ include "seaweedfs.masterServerArg" . }} \
{{- if .Values.filer.filerGroup }}
--filer-group={{ .Values.filer.filerGroup }} \
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
--tls-ca=/usr/local/share/ca-certificates/ca/tls.crt \
--tls-cert=/usr/local/share/ca-certificates/worker/tls.crt \
@@ -302,7 +298,7 @@ spec:
- name: ca-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/ca/
{{- /* grpc.client, which the worker dials the filers with */}}
{{- /* grpc.client, which the worker dials the masters and filers with */}}
- name: client-cert
readOnly: true
mountPath: /usr/local/share/ca-certificates/client/
@@ -345,7 +341,7 @@ spec:
{{- include "seaweedfs.tplvalues.render" (dict "value" .Values.worker.sidecars "context" $) | nindent 8 }}
{{- end }}
volumes:
{{- include "seaweedfs.tmpDirVolume" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .) (ne (include "seaweedfs.worker.lanceEnabled" .) "")) | nindent 8 }}
{{- include "seaweedfs.tmpDirVolume" (list . .Values.worker.containerSecurityContext (tpl (.Values.worker.extraVolumeMounts | default "") .) (tpl (.Values.worker.extraVolumes | default "") .) (ne (include "seaweedfs.worker.lanceNamespaceUrl" .) "")) | nindent 8 }}
{{- if eq .Values.worker.data.type "hostPath" }}
- name: worker-data
hostPath:
@@ -378,8 +374,8 @@ spec:
{{- end }}
{{- if include "seaweedfs.securityConfigEnabled" . }}
- name: security-config
secret:
secretName: {{ include "seaweedfs.fullname" . }}-security-config
configMap:
name: {{ include "seaweedfs.fullname" . }}-security-config
{{- end }}
{{- if .Values.global.seaweedfs.enableSecurity }}
- name: ca-cert
@@ -13,7 +13,7 @@ metadata:
{{- with include "seaweedfs.commonLabels" $ }}{{ . | nindent 4 }}{{ end }}
spec:
clusterIP: None # Headless service
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- if or .Values.worker.metricsPort $lanceMetrics }}
ports:
{{- if .Values.worker.metricsPort }}
@@ -1,6 +1,6 @@
{{- include "seaweedfs.compat" . -}}
{{- if .Values.worker.enabled }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceEnabled" .) }}
{{- $lanceMetrics := and .Values.worker.lanceMetricsPort (include "seaweedfs.worker.lanceNamespaceUrl" .) }}
{{- if or .Values.worker.metricsPort $lanceMetrics }}
{{- if .Values.global.seaweedfs.monitoring.enabled }}
apiVersion: monitoring.coreos.com/v1
@@ -1,107 +0,0 @@
package tests
import (
"fmt"
"os/exec"
"strings"
"testing"
)
func findDocument(documents []map[string]interface{}, kind, name string) map[string]interface{} {
for _, document := range documents {
if document["kind"] == kind && document["metadata"].(map[string]interface{})["name"] == name {
return document
}
}
return nil
}
func TestVolumeServicePublishesNotReadyPods(t *testing.T) {
_, documents := render(t)
service := findDocument(documents, "Service", "vector-test-seaweedfs-volume")
if service == nil {
t.Fatal("no volume service")
}
if service["spec"].(map[string]interface{})["publishNotReadyAddresses"] != true {
t.Fatal("volume pod DNS names must resolve before the pods are Ready")
}
if findDocument(documents, "Service", "vector-test-seaweedfs-client-volume") != nil {
t.Fatal("client-volume service rendered without ingress or httpRoute")
}
}
func TestVolumeIngressUsesReadyOnlyService(t *testing.T) {
_, documents := render(t, "volume.ingress.enabled=true", "volume.httpRoute.enabled=true", "volume.metricsPort=9327")
client := findDocument(documents, "Service", "vector-test-seaweedfs-client-volume")
if client == nil {
t.Fatal("no client-volume service")
}
spec := client["spec"].(map[string]interface{})
if _, found := spec["publishNotReadyAddresses"]; found {
t.Fatal("client-volume must publish only Ready pods")
}
for _, port := range spec["ports"].([]interface{}) {
if port.(map[string]interface{})["name"] == "metrics" {
t.Fatal("client-volume must not expose metrics, or the ServiceMonitor scrapes each pod twice")
}
}
ingress := findDocument(documents, "Ingress", "ingress-vector-test-seaweedfs-volume")
if ingress == nil {
t.Fatal("no volume ingress")
}
path := ingress["spec"].(map[string]interface{})["rules"].([]interface{})[0].(map[string]interface{})["http"].(map[string]interface{})["paths"].([]interface{})[0].(map[string]interface{})
if backend := path["backend"].(map[string]interface{})["service"].(map[string]interface{})["name"]; backend != "vector-test-seaweedfs-client-volume" {
t.Fatalf("volume ingress backend is %v", backend)
}
route := findDocument(documents, "HTTPRoute", "vector-test-seaweedfs-volume")
if route == nil {
t.Fatal("no volume httpRoute")
}
rule := route["spec"].(map[string]interface{})["rules"].([]interface{})[0].(map[string]interface{})
if backend := rule["backendRefs"].([]interface{})[0].(map[string]interface{})["name"]; backend != "vector-test-seaweedfs-client-volume" {
t.Fatalf("volume httpRoute backend is %v", backend)
}
}
func TestVolumeRoutingServiceDoesNotCollideWithVolumeGroups(t *testing.T) {
_, documents := render(t, "volume.ingress.enabled=true", "volume.httpRoute.enabled=true", "volumes.client.replicas=1")
seen := map[string]bool{}
for _, document := range documents {
key := fmt.Sprint(document["kind"], "/", document["metadata"].(map[string]interface{})["name"])
if seen[key] {
t.Fatalf("%s rendered twice", key)
}
seen[key] = true
}
if !seen["Service/vector-test-seaweedfs-volume-client"] || !seen["Service/vector-test-seaweedfs-client-volume"] {
t.Fatal("volumes.client group Service and the routing Service must both render")
}
}
func TestVolumeRoutingServiceRejectsTruncatedCollision(t *testing.T) {
if _, err := exec.LookPath("helm"); err != nil {
t.Skip("helm is not installed")
}
fullname := strings.Repeat("a", 49) + "-client"
output, err := exec.Command("helm", "template", "test", "..", "--set", "fullnameOverride="+fullname, "--set", "volume.ingress.enabled=true").CombinedOutput()
if err == nil || !strings.Contains(string(output), "same name as the volume Service") {
t.Fatalf("colliding routing Service accepted: %v %s", err, output)
}
}
func TestVolumeIngressAllInOne(t *testing.T) {
_, documents := render(t, "allInOne.enabled=true", "volume.ingress.enabled=true")
if findDocument(documents, "Service", "vector-test-seaweedfs-client-volume") != nil {
t.Fatal("client-volume service rendered in all-in-one mode")
}
ingress := findDocument(documents, "Ingress", "ingress-vector-test-seaweedfs-volume")
if ingress == nil {
t.Fatal("no volume ingress")
}
path := ingress["spec"].(map[string]interface{})["rules"].([]interface{})[0].(map[string]interface{})["http"].(map[string]interface{})["paths"].([]interface{})[0].(map[string]interface{})
if backend := path["backend"].(map[string]interface{})["service"].(map[string]interface{})["name"]; backend != "vector-test-seaweedfs-all-in-one" {
t.Fatalf("all-in-one volume ingress backend is %v", backend)
}
}
+7 -14
View File
@@ -45,18 +45,6 @@ global:
volumeRead: 0
filerWrite: 0
filerRead: 0
# Serve the volume servers' HTTP port over TLS with the chart's volume
# certificate, and make every chart component reach them over HTTPS
# ([https.volume] and [https.client] in security.toml). Requires
# enableSecurity and is not supported with allInOne. Clients outside the
# chart (weed mount, the CSI driver) need their own [https.client].
# The volume servers do not ask for client certificates, because kubelet
# probes cannot present one; JWT signing keeps authorizing volume access.
# [https.client] also sends the admin UI's HTTP lookups on masters and
# S3 over HTTPS, which their plain listeners refuse, so the UI can miss
# volume public URLs and refuse SSE-S3 vector buckets.
volumeHttps:
enabled: false
# we will use this serviceAccountName for all ClusterRoles/ClusterRoleBindings
serviceAccountName: "seaweedfs"
serviceAccountAnnotations: {}
@@ -1161,7 +1149,7 @@ s3:
# Set to a port number to enable, or 0/null to disable
icebergPort: null
# Lance Namespace port; weed serves 9101 by default, 0 disables it
# (and the worker's Lance container)
# (and, unless worker.namespaceUrl points elsewhere, the worker's Lance container)
lancePort: 9101
loggingOverrideLevel: null
# enable user & permission to s3 (need to inject to all services)
@@ -1774,6 +1762,8 @@ vector:
port: 8090
metricsPort: 0
masters: ""
readCacheMB: 512
nprobes: null
extraArgs: []
extraEnvironmentVars: {}
podLabels: {}
@@ -1830,7 +1820,7 @@ worker:
# The lance_* jobs run in their own container, /usr/bin/weed-worker.
# amd64/arm64 only; pin mixed clusters with worker.affinity/nodeSelector.
# Admin tells it the filers and the S3 gateways' Lance namespaces; it reads
# It keeps tables through the filers the masters list and reads
# security.toml. The Lance namespace knows it by a token derived from
# jwt.filer_signing.key, which the chart renders only with
# global.seaweedfs.securityConfig.jwtSigning.filerWrite: true. When S3 has
@@ -1839,6 +1829,9 @@ worker:
# HTTP writes, so clients writing to the filer's HTTP API directly need a JWT
# signed with that key.
# Lance namespace URL override; empty derives it from s3.lancePort.
namespaceUrl: ""
# Metrics port for the Lance worker container; the Go worker keeps metricsPort
lanceMetricsPort: 9328
+1067 -1019
View File
File diff suppressed because it is too large. Load diff

Before

Width:  |  Height:  |  Size: 53 KiB

After

Width:  |  Height:  |  Size: 54 KiB

@@ -156,14 +156,11 @@ public class SeaweedWrite {
entry.clearChunks();
entry.addAllChunks(chunks);
FilerProto.CreateEntryResponse response = filerClient.getBlockingStub().createEntry(
filerClient.getBlockingStub().createEntry(
FilerProto.CreateEntryRequest.newBuilder()
.setDirectory(parentDirectory)
.setEntry(entry)
.build());
if (!Strings.isNullOrEmpty(response.getError())) {
throw new IOException(response.getError());
}
}
}
@@ -262,8 +262,6 @@ message CreateEntryRequest {
// Set on a create a filer forwarded to the entry's ring owner, so the owner
// applies it locally instead of forwarding again. Clients leave it unset.
bool is_moved = 8;
// The store write must be durable before the reply, as for ?fsync=true.
bool fsync = 9;
}
// WriteCondition is the precondition the filer evaluates against the existing
+4 -720
View File
@@ -2302,113 +2302,6 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Writable Volumes per Disk",
"description": "Disks holding more than one writable volume of a collection, and the most writable volumes of a collection on one disk.",
"type": "timeseries",
"id": 262,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 69
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "count by (collection) (sum by (cluster, collection, data_center, rack, node, disk_id) (SeaweedFS_master_writable_volumes_per_disk{cluster=~\"$cluster\", state=\"writable\"}) > 1)",
"range": true,
"refId": "A",
"legendFormat": "{{collection}} disks with 2+"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "max by (collection) (sum by (cluster, collection, data_center, rack, node, disk_id) (SeaweedFS_master_writable_volumes_per_disk{cluster=~\"$cluster\", state=\"writable\"}))",
"range": true,
"refId": "B",
"legendFormat": "{{collection}} max on one disk"
}
],
"pluginVersion": "10.3.1"
}
]
},
@@ -3442,102 +3335,6 @@
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Vacuum Dropped Needles",
"description": "Live needles vacuum dropped because their data could not be read back intact (CRC mismatch, malformed or short record), counted since the volume server started. Any non-zero value means a lost replica copy; the volume server log has each dropped key.",
"type": "timeseries",
"id": 267,
"gridPos": {
"h": 8,
"w": 8,
"x": 16,
"y": 54
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "short",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance, collection) (SeaweedFS_volumeServer_vacuuming_dropped_needles{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "{{instance}} {{collection}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
@@ -6832,423 +6629,6 @@
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Subscribe Delivery Lag",
"description": "Seconds from a metadata event's mutation until the filer sends it to a subscriber, by stream scope",
"type": "timeseries",
"id": 263,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 71
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_delivery_lag_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "A",
"legendFormat": "p99 {{scope}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.5, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_delivery_lag_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "B",
"legendFormat": "p50 {{scope}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Watermark Hold Duration",
"description": "How long an aggregated read stayed held at one entry until the peers' watermark released it (memory: delivery watermark, disk: flush watermark)",
"type": "timeseries",
"id": 264,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 71
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_hold_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "A",
"legendFormat": "p99 {{scope}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.5, sum by (le, scope) (rate(SeaweedFS_filer_subscribe_hold_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])))",
"range": true,
"refId": "B",
"legendFormat": "p50 {{scope}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Delivery Claim / Peer Low-Watermark Age",
"description": "Seconds the filer's delivery claim and the peers' delivery and flush low-watermarks trail the clock; -1 while a tracked peer has not signalled",
"type": "timeseries",
"id": 265,
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 79
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "max by (instance) (SeaweedFS_filer_meta_delivery_claim_age_seconds{cluster=~\"$cluster\"})",
"range": true,
"refId": "A",
"legendFormat": "claim {{instance}}"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "max by (instance, kind) (SeaweedFS_filer_meta_peer_low_watermark_age_seconds{cluster=~\"$cluster\"})",
"range": true,
"refId": "B",
"legendFormat": "peer low {{kind}} {{instance}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "Metadata Subscribers Resumed from Disk",
"description": "Times a metadata subscriber fell off the in-memory ring and resumed from the persisted log",
"type": "timeseries",
"id": 266,
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 79
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "ops",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "sum by (instance, scope) (rate(SeaweedFS_filer_subscribe_resume_from_disk{cluster=~\"$cluster\"}[$__rate_interval]))",
"range": true,
"refId": "A",
"legendFormat": "{{scope}} {{instance}}"
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
@@ -7262,7 +6642,7 @@
"h": 8,
"w": 12,
"x": 0,
"y": 87
"y": 71
},
"fieldConfig": {
"defaults": {
@@ -7358,7 +6738,7 @@
"h": 8,
"w": 12,
"x": 12,
"y": 87
"y": 71
},
"fieldConfig": {
"defaults": {
@@ -7454,7 +6834,7 @@
"h": 8,
"w": 12,
"x": 0,
"y": 95
"y": 79
},
"fieldConfig": {
"defaults": {
@@ -7550,7 +6930,7 @@
"h": 8,
"w": 12,
"x": 12,
"y": 95
"y": 79
},
"fieldConfig": {
"defaults": {
@@ -9157,102 +8537,6 @@
}
],
"pluginVersion": "10.3.1"
},
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"title": "S3 PUT Stage Duration p99",
"description": "Time an object write (PutObject, UploadPart) spends waiting on the request body, volume assigns, chunk uploads apart from body reads, and the metadata commit after the upload.",
"type": "timeseries",
"id": 268,
"gridPos": {
"h": 8,
"w": 24,
"x": 0,
"y": 49
},
"fieldConfig": {
"defaults": {
"color": {
"mode": "palette-classic"
},
"custom": {
"axisBorderShow": false,
"axisCenteredZero": false,
"axisColorMode": "text",
"axisLabel": "",
"axisPlacement": "auto",
"barAlignment": 0,
"drawStyle": "line",
"fillOpacity": 10,
"gradientMode": "none",
"hideFrom": {
"legend": false,
"tooltip": false,
"viz": false
},
"insertNulls": false,
"lineInterpolation": "linear",
"lineWidth": 1,
"pointSize": 4,
"scaleDistribution": {
"type": "linear"
},
"showPoints": "never",
"spanNulls": false,
"stacking": {
"group": "A",
"mode": "none"
},
"thresholdsStyle": {
"mode": "off"
}
},
"mappings": [],
"unit": "s",
"thresholds": {
"mode": "absolute",
"steps": [
{
"color": "green",
"value": null
}
]
}
},
"overrides": []
},
"options": {
"legend": {
"calcs": [
"lastNotNull",
"max"
],
"displayMode": "table",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${DS_PROMETHEUS}"
},
"editorMode": "code",
"expr": "histogram_quantile(0.99, sum(rate(SeaweedFS_s3_put_stage_seconds_bucket{cluster=~\"$cluster\"}[$__rate_interval])) by (le, operation, stage))",
"range": true,
"refId": "A",
"legendFormat": "{{operation}} {{stage}}"
}
],
"pluginVersion": "10.3.1"
}
]
},
-6
View File
@@ -7143,10 +7143,8 @@ dependencies = [
"aes",
"aes-gcm",
"anyhow",
"arrow-array",
"arrow-cast",
"arrow-schema",
"arrow-select",
"async-trait",
"base64 0.22.1",
"bytes",
@@ -7160,7 +7158,6 @@ dependencies = [
"hmac 0.12.1",
"http",
"hyper-util",
"jsonb",
"jsonwebtoken",
"lance",
"lance-datafusion",
@@ -7193,7 +7190,6 @@ dependencies = [
"tower",
"tracing",
"tracing-subscriber",
"uuid",
"x509-parser",
"zstd",
]
@@ -7212,7 +7208,6 @@ dependencies = [
"lance",
"lance-index",
"lance-linalg",
"lance-select",
"lance-table",
"object_store",
"roaring",
@@ -7241,7 +7236,6 @@ dependencies = [
"futures",
"lance",
"lance-arrow",
"lance-index",
"lance-linalg",
"moka",
"object_store",
+3 -3
View File
@@ -15,12 +15,12 @@ Point an AWS S3 Vectors client at the S3 endpoint, normally `http://localhost:83
| `--masters` | Required | Comma-separated master addresses |
| `--listen` | `127.0.0.1:8090` | gRPC listener and registered address |
| `--filer-group` | Empty | Filer group used for table storage |
| `--read-cache-mb` | `512` | Immutable data/index read cache; zero disables it |
| `--nprobes` | Automatic | ANN partitions searched per query |
| `--metrics-port` | `0` | HTTP metrics and health listener; zero disables it |
| `--metrics-ip` | `127.0.0.1` | HTTP listener address |
| `--security-toml` | Discovered | Cluster certificates, signing keys and encryption keys |
The engine caches a quarter of the memory it may use (its cgroup limit, else the machine's), split 2:4:1 between file reads, loaded indexes and table metadata, and logs the sizes at startup. Each query probes a tenth of the index's partitions, at least 8, and more under a filter.
The HTTP listener provides `/health`, `/ready`, and `/metrics`. Readiness requires an active registration with the master. The gRPC listener also implements the standard health service for `vector_pb.VectorService` and the whole server. These health statuses follow master registration.
Metrics use the `SeaweedFS_vector_` prefix:
@@ -35,6 +35,6 @@ The S3 gateway separately publishes `SeaweedFS_s3_` request metrics with `type="
For mutual TLS, configure `[grpc.vector]` for the engine's server certificate, `[grpc.client]` for its master/filer connections, and the cluster CA. HTTPS volume reads also use `[https.client]`. The engine follows the same signing and encryption configuration as the other cluster clients.
Run the Lance maintenance worker against the cluster's admin to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
Run the Lance maintenance worker against the same masters and Lance namespace to build and update ANN indexes. Queries can scan data that has not been indexed yet. See the [maintenance worker documentation](../seaweed-worker/README.md) and [Helm chart](../k8s/charts/seaweedfs/README.md) for deployment settings.
The integration suite at `test/s3vectors` runs the same API and observability checks against both Go and Rust volume servers, including mutual TLS, signed volume reads, and encrypted volume data.
-1
View File
@@ -22,7 +22,6 @@ object_store = "0.13"
lance-index = "10"
lance-linalg = "10"
lance-table = "10"
lance-select = "10"
arrow-array = "58"
arrow-cast = "58"
arrow-schema = "58"
@@ -139,7 +139,6 @@ mod tests {
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
@@ -168,7 +167,6 @@ mod tests {
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let filtered = ann(&dataset, &table, &query).await.unwrap();
let exact = flat(&dataset, &table, &query).await.unwrap();
@@ -206,7 +204,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
+7 -17
View File
@@ -4,7 +4,6 @@
//! compares the elements as typed JSON values: Lance's compares their text, so
//! 1 would match "1".
use std::collections::HashMap;
use std::sync::Arc;
use arrow_array::builder::{BooleanBuilder, StringBuilder};
@@ -20,21 +19,13 @@ use lance::deps::datafusion::logical_expr::{
ColumnarValue, Expr, ScalarFunctionArgs, ScalarUDF, ScalarUDFImpl, Signature, Volatility,
};
/// Set `filter` on the scanner with the JSONPath functions swapped and the
/// conjuncts on `ready` indexed keys answered by their columns, which it
/// returns.
pub(crate) fn apply(
scanner: &mut Scanner,
filter: &str,
ready: &HashMap<String, String>,
) -> anyhow::Result<Vec<crate::indexed_filter::Indexed>> {
/// Set `filter` on the scanner with the JSONPath functions swapped.
pub(crate) fn apply(scanner: &mut Scanner, filter: &str) -> anyhow::Result<()> {
scanner.filter(filter)?;
let Some(expr) = scanner.get_expr_filter()? else {
return Ok(Vec::new());
};
let (expr, indexed) = crate::indexed_filter::rewrite(expr, ready);
scanner.filter_expr(swap(expr)?);
Ok(indexed)
if let Some(expr) = scanner.get_expr_filter()? {
scanner.filter_expr(swap(expr)?);
}
Ok(())
}
fn swap(expr: Expr) -> Result<Expr> {
@@ -277,7 +268,7 @@ mod tests {
async fn keys(dataset: &Dataset, filter: &str, swapped: bool) -> anyhow::Result<Vec<String>> {
let mut scanner = dataset.scan();
if swapped {
apply(&mut scanner, filter, &HashMap::new())?;
apply(&mut scanner, filter)?;
} else {
scanner.filter(filter)?;
}
@@ -404,7 +395,6 @@ mod tests {
apply(
&mut scanner,
r#"json_extract(`metadata`, '$["k"]') = '"v"' AND json_exists(`metadata`, '$["k"]') AND json_get_string(`metadata`, 'k') = 'v' AND json_array_contains(`metadata`, '$["k"]', '"v"') AND NOT json_array_contains(`metadata`, '$["k"]', key)"#,
&HashMap::new(),
)
.unwrap();
let mut swapped = Vec::new();
-78
View File
@@ -104,7 +104,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
}
}
@@ -199,83 +198,6 @@ mod tests {
assert_eq!(filtered.len(), 10);
}
/// A filtered query through the index returns every eligible row when
/// fewer than k match, though the probed partitions cannot hold them all:
/// 400 of 4000 rows match, the index has 63 partitions and probes at most
/// 32 of them.
#[tokio::test]
async fn filtered_ann_returns_every_match_below_k() {
let dir = TempDir::new().unwrap();
let rows = scattered(4000, 8, 0x9E3779B97F4A7C15);
let tags: Vec<&str> = (0..4000)
.map(|i| if i % 10 == 0 { "rare" } else { "common" })
.collect();
let mut dataset = testing::write_dataset(&dir, &rows, &tags).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(
&mut dataset,
&table.vector_column,
INDEX_NAME,
partitions_for(4000),
false,
)
.await
.unwrap();
assert_eq!(partitions_for(4000), 63);
for vector in &scattered(3, 8, 0xD1B54A32D192ED03) {
let q = Query {
filter: Some("tag = 'rare'".to_string()),
..exact(vector, 500)
};
let flat = query::flat(&dataset, &table, &q).await.unwrap();
assert_eq!(flat.len(), 400);
let ann = query::ann(&dataset, &table, &q).await.unwrap();
assert_eq!(ann.len(), 400, "the index path dropped eligible rows");
for (f, a) in flat.iter().zip(ann.iter()) {
assert!((f.distance - a.distance).abs() < 1e-5);
}
}
}
/// When no more than k rows match, every match comes back with its own
/// distance, nearest first — not the rows the probes missed with an
/// infinite distance. Ten fragments of 400 rows, 5 of them matching.
#[tokio::test]
async fn filtered_ann_scores_every_match_at_or_below_k() {
let dir = TempDir::new().unwrap();
let rows = scattered(4000, 8, 0x9E3779B97F4A7C15);
let tags: Vec<&str> = (0..4000)
.map(|i| if i % 800 == 0 { "rare" } else { "common" })
.collect();
let mut dataset = testing::write_dataset(&dir, &rows[..400], &tags[..400]).await;
for chunk in 1..10 {
let r = chunk * 400..(chunk + 1) * 400;
testing::append_dataset(&mut dataset, &rows[r.clone()], &tags[r]).await;
}
let table = VectorTable::resolve(&dataset, None, None).unwrap();
build(&mut dataset, &table.vector_column, INDEX_NAME, 63, false)
.await
.unwrap();
for vector in &scattered(3, 8, 0xD1B54A32D192ED03) {
for k in [5, 10] {
let q = Query {
filter: Some("tag = 'rare'".to_string()),
..exact(vector, k)
};
let flat = query::flat(&dataset, &table, &q).await.unwrap();
assert_eq!(flat.len(), 5);
let ann = query::ann(&dataset, &table, &q).await.unwrap();
assert_eq!(ann.len(), 5);
for (f, a) in flat.iter().zip(ann.iter()) {
assert!(
(f.distance - a.distance).abs() < 1e-5,
"k={k}: {flat:?} vs {ann:?}"
);
}
}
}
}
#[tokio::test]
async fn default_probes_take_the_largest_index() {
use lance::index::DatasetIndexExt;
@@ -1,739 +0,0 @@
//! Filters on indexed metadata keys (see `weed_lance_worker::metadata_index`).
//!
//! The gateway renders a string `$eq` or `$in` on a key as an OR of
//! `json_extract(metadata, P) = '"v"'` (or `IN`) and
//! `json_array_contains(metadata, P, '"v"')` over the same values. In the
//! parsed filter, such a top-level conjunct on a ready key is replaced by
//! `array_has` / `array_has_any` on the key's column, which its LABEL_LIST
//! index answers. Everything else, including `$ne` and `$nin`, stays on the
//! JSON path.
use std::collections::{BTreeMap, BTreeSet, HashMap};
use anyhow::Result;
use jsonb::OwnedJsonb;
use lance::Dataset;
use lance::deps::datafusion::common::{Column, ScalarValue};
use lance::deps::datafusion::functions_nested::expr_fn::{array_has, array_has_any};
use lance::deps::datafusion::logical_expr::utils::split_conjunction_owned;
use lance::deps::datafusion::logical_expr::{BinaryExpr, Expr, Operator};
use lance::deps::datafusion::prelude::lit;
use weed_lance_worker::metadata_index::{self, State};
const METADATA_COLUMN: &str = "metadata";
/// The column of each ready indexed key of `dataset`, by metadata key.
pub(crate) fn ready_columns(dataset: &Dataset) -> HashMap<String, String> {
let schema: arrow_schema::Schema = dataset.schema().into();
metadata_index::indexed_keys(&schema)
.into_iter()
.filter(|k| k.state == Some(State::Ready))
.map(|k| (k.key, k.column))
.collect()
}
/// A conjunct a key's column answers: rows whose `column` holds one of
/// `values`.
#[derive(Debug, Clone)]
pub(crate) struct Indexed {
pub column: String,
pub values: Vec<String>,
pub expr: Expr,
}
/// `filter` with each top-level conjunct that is a string `$eq` or `$in` on
/// a key in `ready` answered by the key's column instead, and those
/// replacements.
pub(crate) fn rewrite(filter: Expr, ready: &HashMap<String, String>) -> (Expr, Vec<Indexed>) {
if ready.is_empty() {
return (filter, Vec::new());
}
let mut indexed: Vec<Indexed> = Vec::new();
let mut rewritten: Option<Expr> = None;
for conjunct in split_conjunction_owned(filter) {
let replacement = string_membership(&conjunct).and_then(|(key, values)| {
let name = ready.get(&key)?;
let column = Expr::Column(Column::from_name(name));
let expr = match values.as_slice() {
[one] => array_has(column, lit(one.as_str())),
_ => {
let values: Vec<ScalarValue> = values
.iter()
.map(|v| ScalarValue::Utf8(Some(v.clone())))
.collect();
let list = ScalarValue::new_list(&values, &arrow_schema::DataType::Utf8, true);
array_has_any(column, Expr::Literal(ScalarValue::List(list), None))
}
};
Some(Indexed {
column: name.clone(),
values,
expr,
})
});
let part = match replacement {
Some(found) => {
let expr = found.expr.clone();
indexed.push(found);
expr
}
None => conjunct,
};
rewritten = Some(and(rewritten, part));
}
(rewritten.unwrap_or(lit(true)), indexed)
}
fn and(left: Option<Expr>, right: Expr) -> Expr {
match left {
Some(left) => Expr::BinaryExpr(BinaryExpr::new(
Box::new(left),
Operator::And,
Box::new(right),
)),
None => right,
}
}
/// The key and string values of a conjunct meaning "the key holds one of
/// these strings, or an array with one of them": the OR of scalar matches
/// and array-member matches over the same values and key.
fn string_membership(expr: &Expr) -> Option<(String, Vec<String>)> {
let mut disjuncts = Vec::new();
split_or(expr, &mut disjuncts);
let mut path: Option<&str> = None;
let mut scalars = BTreeSet::new();
let mut elements = BTreeSet::new();
for disjunct in disjuncts {
let (p, kind) = match unwrap_false_coalesce(disjunct) {
Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::Eq,
right,
}) => (
json_function(left, "json_extract")?,
Member::Scalar(vec![utf8(right)?]),
),
Expr::InList(list) if !list.negated => (
json_function(&list.expr, "json_extract")?,
Member::Scalar(list.list.iter().map(utf8).collect::<Option<_>>()?),
),
Expr::ScalarFunction(f) if f.func.name() == "json_array_contains" => {
let [data, p, value] = f.args.as_slice() else {
return None;
};
if !is_metadata(data) {
return None;
}
let element: serde_json::Value = serde_json::from_str(utf8(value)?).ok()?;
(utf8(p)?, Member::Element(element.as_str()?.to_string()))
}
_ => return None,
};
if path.is_some_and(|q| q != p) {
return None;
}
path = Some(p);
match kind {
Member::Scalar(values) => scalars.extend(values.into_iter().map(str::to_string)),
Member::Element(value) => {
elements.insert(value);
}
}
}
let key = json_path_key(path?)?;
let rendered: BTreeSet<String> = elements
.iter()
.map(|s| jsonb_text(s))
.collect::<Option<_>>()?;
(!elements.is_empty() && rendered == scalars).then(|| (key, elements.into_iter().collect()))
}
enum Member<'a> {
Scalar(Vec<&'a str>),
Element(String),
}
fn split_or<'a>(expr: &'a Expr, out: &mut Vec<&'a Expr>) {
match expr {
Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::Or,
right,
}) => {
split_or(left, out);
split_or(right, out);
}
Expr::Alias(alias) => split_or(&alias.expr, out),
other => out.push(other),
}
}
/// `x` for `COALESCE(x, false)` or its simplified `x IS NOT NULL AND x`;
/// either is false where `x` is null, which a top-level conjunct treats alike.
fn unwrap_false_coalesce(expr: &Expr) -> &Expr {
match expr {
Expr::ScalarFunction(f) if f.func.name() == "coalesce" => match f.args.as_slice() {
[x, Expr::Literal(ScalarValue::Boolean(Some(false)), _)] => x,
_ => expr,
},
Expr::BinaryExpr(BinaryExpr {
left,
op: Operator::And,
right,
}) => match left.as_ref() {
Expr::IsNotNull(x) if x == right => right,
_ => expr,
},
_ => expr,
}
}
fn utf8(expr: &Expr) -> Option<&str> {
match expr {
Expr::Literal(ScalarValue::Utf8(Some(s)) | ScalarValue::LargeUtf8(Some(s)), _) => {
Some(s.as_str())
}
_ => None,
}
}
fn is_metadata(expr: &Expr) -> bool {
matches!(expr, Expr::Column(c) if c.name == METADATA_COLUMN)
}
/// The JSONPath literal of `name(metadata, path)`.
fn json_function<'a>(expr: &'a Expr, name: &str) -> Option<&'a str> {
match expr {
Expr::ScalarFunction(f) if f.func.name() == name => match f.args.as_slice() {
[data, path] if is_metadata(data) => utf8(path),
_ => None,
},
_ => None,
}
}
/// The key of a `$["key"]` path, with `\\` and `\"` unescaped.
fn json_path_key(path: &str) -> Option<String> {
let inner = path.strip_prefix("$[\"")?.strip_suffix("\"]")?;
let mut key = String::with_capacity(inner.len());
let mut chars = inner.chars();
while let Some(c) = chars.next() {
match c {
'\\' => match chars.next()? {
c @ ('\\' | '"') => key.push(c),
_ => return None,
},
'"' => return None,
c => key.push(c),
}
}
Some(key)
}
/// What json_extract returns for a stored string `s`.
fn jsonb_text(s: &str) -> Option<String> {
let value: OwnedJsonb = serde_json::to_string(s).ok()?.parse().ok()?;
Some(value.to_string())
}
/// Segments searched at once when counting.
const PARALLEL_SEGMENTS: usize = 8;
/// The rows of `scope` (every fragment when None) whose column matches
/// `indexed`, or None once there are more than `limit`. Segments are
/// searched newest first, several at once, and counting stops as soon as
/// the total passes the limit. Rows the index has not reached are counted
/// by a read of the column. Deleted rows an index segment still lists
/// count too: the total is an upper bound, which only ever sends a query
/// to the vector index instead of an exact scan.
pub(crate) async fn count_indexed(
dataset: &Dataset,
indexed: &Indexed,
scope: Option<&[u64]>,
limit: u64,
) -> Result<Option<u64>> {
use futures::{StreamExt, TryStreamExt};
use lance::index::DatasetIndexInternalExt;
use lance_index::metrics::NoOpMetricsCollector;
use lance_index::scalar::{LabelListQuery, SearchResult};
use lance_select::RowSetOps;
let scope: Option<roaring::RoaringBitmap> =
scope.map(|ids| ids.iter().map(|id| *id as u32).collect());
let segments = metadata_index::segments(dataset, &indexed.column).await?;
let query = LabelListQuery::HasAnyLabel(
indexed
.values
.iter()
.map(|v| ScalarValue::Utf8(Some(v.clone())))
.collect(),
);
let mut searches: Vec<futures::future::BoxFuture<'_, Result<u64>>> = Vec::new();
for segment in segments.iter().rev() {
let fragments = match &scope {
Some(scope) => &segment.fragments & scope,
None => segment.fragments.clone(),
};
if fragments.is_empty() {
continue;
}
let uuid = segment.uuid;
let query = &query;
searches.push(Box::pin(async move {
let index = dataset
.open_scalar_index(&indexed.column, &uuid, &NoOpMetricsCollector)
.await?;
let mut found = match index.search(query, &NoOpMetricsCollector).await? {
SearchResult::Exact(rows) | SearchResult::AtMost(rows) => rows.true_rows(),
SearchResult::AtLeast(_) => anyhow::bail!("a LABEL_LIST index answered AtLeast"),
};
found.retain_fragments(fragments.iter());
Ok(found.len().unwrap_or(u64::MAX))
}));
}
let mut counts = futures::stream::iter(searches).buffered(PARALLEL_SEGMENTS);
let mut total = 0u64;
while let Some(count) = counts.try_next().await? {
total = total.saturating_add(count);
if total > limit {
return Ok(None);
}
}
let unindexed: Vec<lance_table::format::Fragment> = dataset
.fragments()
.iter()
.filter(|f| !segments.iter().any(|s| s.fragments.contains(f.id as u32)))
.filter(|f| scope.as_ref().is_none_or(|s| s.contains(f.id as u32)))
.cloned()
.collect();
if !unindexed.is_empty() {
let mut scanner = dataset.scan();
scanner
.filter_expr(indexed.expr.clone())
.with_fragments(unindexed);
total = total.saturating_add(scanner.count_rows().await?);
}
Ok((total <= limit).then_some(total))
}
/// How a filter compares a key.
pub mod operand {
pub const STRING: u8 = 1;
pub const NUMBER: u8 = 2;
pub const BOOL: u8 = 4;
pub const EXISTS: u8 = 8;
}
/// The metadata keys `filter` reads, each with the [`operand`] kinds it is
/// compared with.
pub fn filter_keys(dataset: &Dataset, filter: &str) -> Result<BTreeMap<String, u8>> {
let mut scanner = dataset.scan();
scanner.filter(filter)?;
let mut keys = BTreeMap::new();
if let Some(expr) = scanner.get_expr_filter()? {
collect_keys(&expr, &mut keys);
}
Ok(keys)
}
fn literal_kind(text: &str) -> u8 {
match serde_json::from_str::<serde_json::Value>(text) {
Ok(serde_json::Value::String(_)) => operand::STRING,
Ok(serde_json::Value::Number(_)) => operand::NUMBER,
Ok(serde_json::Value::Bool(_)) => operand::BOOL,
// json_extract's text of a string with control characters is not
// JSON, but it is quoted.
_ if text.starts_with('"') => operand::STRING,
_ => 0,
}
}
fn collect_keys(expr: &Expr, keys: &mut BTreeMap<String, u8>) {
let mut note = |path: &str, kind: u8| {
if let Some(key) = json_path_key(path) {
*keys.entry(key).or_default() |= kind;
}
};
match expr {
Expr::TryCast(cast) if extract(&cast.expr).is_some() => {
note(extract(&cast.expr).unwrap_or_default(), operand::NUMBER);
return;
}
Expr::BinaryExpr(BinaryExpr { left, right, .. }) => {
if let (Some(path), Some(value)) = (extract(left), utf8(right)) {
note(path, literal_kind(value));
return;
}
}
Expr::InList(list) => {
if let Some(path) = extract(&list.expr) {
let kind = list
.list
.iter()
.filter_map(utf8)
.fold(0, |k, v| k | literal_kind(v));
note(path, kind);
return;
}
}
Expr::ScalarFunction(f) if is_json_function(f.func.name()) => {
if let [data, path, rest @ ..] = f.args.as_slice()
&& is_metadata(data)
&& let Some(path) = utf8(path)
{
let kind = match (f.func.name(), rest) {
("json_exists", _) => operand::EXISTS,
(_, [value]) => utf8(value).map_or(0, literal_kind),
_ => 0,
};
note(path, kind);
return;
}
}
_ => {}
}
for child in children(expr) {
collect_keys(child, keys);
}
}
fn extract(expr: &Expr) -> Option<&str> {
json_function(expr, "json_extract")
}
fn is_json_function(name: &str) -> bool {
matches!(name, "json_extract" | "json_exists" | "json_array_contains")
}
fn children(expr: &Expr) -> Vec<&Expr> {
use lance::deps::datafusion::common::tree_node::TreeNode;
let mut out = Vec::new();
let _ = expr.apply_children(|child| {
out.push(child);
Ok(lance::deps::datafusion::common::tree_node::TreeNodeRecursion::Continue)
});
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::query::{self, Query};
use crate::table::VectorTable;
use arrow_array::{FixedSizeListArray, RecordBatch, RecordBatchIterator, StringArray};
use arrow_schema::{DataType, Field, Schema};
use lance::index::DatasetIndexExt;
use lance_index::IndexType;
use lance_index::scalar::{BuiltinIndexType, ScalarIndexParams};
use lance_linalg::distance::DistanceType;
use std::sync::Arc;
use tempfile::TempDir;
const DIM: usize = 4;
/// The gateway's text for `{"author": "<v>"}`.
fn eq(field: &str, json: &str) -> String {
let json = json.replace('\'', "''");
format!(
"(COALESCE(json_extract(`metadata`, '$[\"{field}\"]') = '{json}', false) OR COALESCE(json_array_contains(`metadata`, '$[\"{field}\"]', '{json}'), false))"
)
}
/// The gateway's text for `{"author": {"$in": [<strings>]}}`.
fn among(values: &[&str]) -> String {
let scalars: Vec<String> = values.iter().map(|v| format!("'\"{v}\"'")).collect();
let mut groups = vec![format!(
"COALESCE(json_extract(`metadata`, '$[\"author\"]') in ({}), false)",
scalars.join(", ")
)];
for v in values {
groups.push(format!(
"COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"{v}\"'), false)"
));
}
format!("({})", groups.join(" OR "))
}
/// Rows `u0..u<n>` by author, plus a few others, in fragments of 100,
/// with the author column ready and indexed and a vector index.
async fn dataset(dir: &TempDir, rows: usize) -> Dataset {
let metadata = Field::new("metadata", DataType::Utf8, true)
.with_metadata([("ARROW:extension:name".to_string(), "arrow.json".to_string())].into());
let schema = Arc::new(Schema::new(vec![
Field::new("key", DataType::Utf8, false),
Field::new(
"vector",
DataType::FixedSizeList(
Arc::new(Field::new("item", DataType::Float32, true)),
DIM as i32,
),
false,
),
metadata,
metadata_index::field("_mk_0", "author", State::Ready),
]));
let metas: Vec<serde_json::Value> = (0..rows)
.map(|i| match i % 10 {
0 => serde_json::json!({"author": "rare"}),
1 => serde_json::json!({"author": ["many", "rare2"]}),
_ => serde_json::json!({"author": "many", "n": i}),
})
.collect();
let batches: Vec<RecordBatch> = (0..rows)
.step_by(100)
.map(|start| {
let range = start..(start + 100).min(rows);
RecordBatch::try_new(
schema.clone(),
vec![
Arc::new(StringArray::from(
range.clone().map(|i| format!("k{i}")).collect::<Vec<_>>(),
)),
Arc::new(FixedSizeListArray::from_iter_primitive::<
arrow_array::types::Float32Type,
_,
_,
>(
range.clone().map(|i| {
Some((0..DIM).map(move |j| Some(((i * 31 + j * 17) % 97) as f32)))
}),
DIM as i32,
)),
Arc::new(StringArray::from(
range
.clone()
.map(|i| Some(metas[i].to_string()))
.collect::<Vec<_>>(),
)),
metadata_index::column_from_json(range.map(|i| Some(&metas[i])), "author"),
],
)
.unwrap()
})
.collect();
let uri = dir.path().to_str().unwrap();
let mut dataset = None::<Dataset>;
for batch in batches {
let reader = RecordBatchIterator::new(vec![Ok(batch)], schema.clone());
dataset = Some(match dataset {
None => Dataset::write(reader, uri, None).await.unwrap(),
Some(mut d) => {
d.append(reader, None).await.unwrap();
d
}
});
}
let mut dataset = dataset.unwrap();
dataset
.create_index(
&["_mk_0"],
IndexType::LabelList,
None,
&ScalarIndexParams::for_builtin(BuiltinIndexType::LabelList),
true,
)
.await
.unwrap();
crate::index::build(&mut dataset, "vector", crate::index::INDEX_NAME, 4, false)
.await
.unwrap();
dataset
}
fn rewritten(dataset: &Dataset, filter: &str) -> (String, Option<String>) {
let mut scanner = dataset.scan();
let indexed = crate::filter::apply(&mut scanner, filter, &ready_columns(dataset)).unwrap();
(
scanner.get_expr_filter().unwrap().unwrap().to_string(),
indexed.first().map(|i| i.expr.to_string()),
)
}
#[tokio::test]
async fn string_eq_and_in_on_a_ready_key_use_its_column() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 200).await;
assert_eq!(
ready_columns(&dataset),
HashMap::from([("author".to_string(), "_mk_0".to_string())])
);
for (filter, want) in [
(eq("author", "\"rare\""), Some("array_has(_mk_0, Utf8(\"rare\"))")),
(
among(&["rare", "many"]),
Some("array_has_any(_mk_0, List([many, rare]))"),
),
(
format!("{} AND TRY_CAST(json_extract(`metadata`, '$[\"n\"]') AS DOUBLE) > 3", eq("author", "\"rare\"")),
Some("array_has(_mk_0, Utf8(\"rare\"))"),
),
(eq("author", "\"o'neil \\\"q\\\"\""), Some("array_has(_mk_0, Utf8(\"o'neil \"q\"\"))")),
(
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"c\\u0001d\\n\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"c\\u0001d\\n\"'), false))".to_string(),
Some("array_has(_mk_0, Utf8(\"c\u{1}d\n\"))"),
),
// The scalar half's text is not what json_extract returns for
// the array half's string, so the two do not agree.
(
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"c\\u{1}d\\n\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"c\\u0001d\\n\"'), false))".to_string(),
None,
),
// Not a string, not this key, or not every value on both sides.
(eq("author", "true"), None),
(eq("other", "\"rare\""), None),
(format!("NOT {}", eq("author", "\"rare\"")), None),
(format!("NOT {}", among(&["rare", "many"])), None),
(
"COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"rare\"', false)".to_string(),
None,
),
(
among(&["rare", "many"]).replace("'\"many\"'), false))", "'\"other\"'), false))"),
None,
),
("json_exists(`metadata`, '$[\"author\"]')".to_string(), None),
(format!("({} OR json_exists(`metadata`, '$[\"n\"]'))", eq("author", "\"rare\"")), None),
] {
let (expr, indexed) = rewritten(&dataset, &filter);
assert_eq!(indexed.as_deref(), want, "{filter}");
assert_eq!(expr.contains("json_"), want.is_none() || filter.contains(" AND "), "{filter}: {expr}");
}
}
/// The planner scores few matches exactly and leaves many to the vector
/// index, per scope.
#[tokio::test]
async fn few_indexed_matches_are_scored_exactly() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 1000).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = |filter: &str, fragments: Option<Vec<u64>>| Query {
vector: vec![1.0, 2.0, 3.0, 4.0],
k: 10,
filter: Some(filter.to_string()),
postfilter: false,
distance: DistanceType::L2,
nprobes: None,
index_segments: None,
fragments,
exact_match_limit: None,
};
let rare = eq("author", "\"rare\"");
let many = eq("author", "\"many\"");
let few = |q: Query| {
let (dataset, table) = (&dataset, &table);
async move {
query::few_indexed_matches(dataset, table, &q)
.await
.unwrap()
}
};
// 100 and 900 matches, and 90 in the first two fragments.
assert!(few(query(&rare, None)).await);
assert!(!few(query(&many, None)).await);
let first = Some(vec![0, 1]);
assert!(few(query(&many, first.clone())).await);
assert!(
!few(Query {
exact_match_limit: Some(0),
..query(&rare, None)
})
.await
);
// A JSON-only filter is not counted.
assert!(!few(query("json_exists(`metadata`, '$[\"n\"]')", None)).await);
for (filter, fragments) in [(&rare, None), (&many, first)] {
let q = query(filter, fragments);
let exact = query::flat(&dataset, &table, &q).await.unwrap();
let got = query::ann(&dataset, &table, &q).await.unwrap();
assert_eq!(got.len(), 10);
for (g, e) in got.iter().zip(&exact) {
assert!(
(g.distance - e.distance).abs() < 1e-4,
"{got:?} vs {exact:?}"
);
}
}
}
#[tokio::test]
async fn the_plan_reads_the_scalar_index() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 300).await;
let mut scanner = dataset.scan();
crate::filter::apply(
&mut scanner,
&eq("author", "\"rare\""),
&ready_columns(&dataset),
)
.unwrap();
let plan = scanner.explain_plan(true).await.unwrap();
assert!(plan.contains("LabelList"), "{plan}");
assert!(!plan.contains("json_"), "{plan}");
}
#[tokio::test]
async fn filter_keys_note_how_each_key_is_compared() {
let dir = TempDir::new().unwrap();
let dataset = dataset(&dir, 100).await;
let filter = format!(
"{} AND TRY_CAST(json_extract(`metadata`, '$[\"n\"]') AS DOUBLE) > 3 AND NOT json_exists(`metadata`, '$[\"a.b\\\"c\"]') AND COALESCE(json_extract(`metadata`, '$[\"f\"]') = 'true', false)",
eq("author", "\"rare\"")
);
let keys = filter_keys(&dataset, &filter).unwrap();
assert_eq!(
keys,
BTreeMap::from([
("a.b\"c".to_string(), operand::EXISTS),
("author".to_string(), operand::STRING),
("f".to_string(), operand::BOOL),
("n".to_string(), operand::NUMBER),
])
);
}
/// Counting walks the segments, keeps to the scope and stops once over
/// the limit.
#[tokio::test]
async fn counts_follow_segments_and_scope() {
let dir = TempDir::new().unwrap();
let mut dataset = dataset(&dir, 1000).await;
dataset.drop_index("_mk_0_idx").await.unwrap();
// Ten fragments of 100 rows: four segments of up to 300 rows.
let ids: Vec<u64> = dataset.fragments().iter().map(|f| f.id).collect();
metadata_index::index_fragments(&mut dataset, "_mk_0", 300, 0)
.await
.unwrap();
let segments = metadata_index::segments(&dataset, "_mk_0").await.unwrap();
assert_eq!(segments.len(), 4);
let ready = ready_columns(&dataset);
let indexed =
crate::filter::apply(&mut dataset.scan(), &eq("author", "\"rare\""), &ready).unwrap();
let rare = &indexed[0];
// "rare" in rows i % 10 == 0, "rare2" never matches it.
assert_eq!(
count_indexed(&dataset, rare, None, 1_000).await.unwrap(),
Some(100)
);
assert_eq!(count_indexed(&dataset, rare, None, 99).await.unwrap(), None);
assert_eq!(
count_indexed(&dataset, rare, Some(&ids[..2]), 1_000)
.await
.unwrap(),
Some(20)
);
assert_eq!(
count_indexed(&dataset, rare, Some(&ids[9..]), 1_000)
.await
.unwrap(),
Some(10)
);
assert_eq!(
count_indexed(&dataset, rare, Some(&[]), 1_000)
.await
.unwrap(),
Some(0)
);
}
}
-1
View File
@@ -8,7 +8,6 @@
pub mod coverage;
mod filter;
pub mod index;
pub mod indexed_filter;
pub mod maintenance;
pub mod query;
pub mod segments;
+55 -75
View File
@@ -2,27 +2,35 @@ use anyhow::{Context, Result, bail};
use clap::{Parser, Subcommand};
use weed_lance_worker::catalog::{NamespaceClient, SigningKey, TableDescription, parse_id};
use weed_lance_worker::cluster::Cluster;
use weed_lance_worker::dataset::{self, Storage};
use weed_vector_core::coverage;
use weed_vector_core::index;
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
/// Finds everything through the masters: the S3 gateway whose Lance Namespace
/// says where a table is, and the filers that hold it.
/// Mirrors `weed-worker`'s flags where the two touch the same thing: the
/// namespace that says where a table is, and the masters whose filers hold
/// it.
#[derive(Parser, Debug)]
#[command(
name = "weed-vector",
about = "Describe, query and index S3 Vectors tables"
)]
struct Args {
/// Comma-separated master addresses. A table named by a local path needs
/// none.
/// Lance namespace the tables live in.
#[arg(
long,
default_value = "http://localhost:9101",
env = "WEED_LANCE_NAMESPACE"
)]
namespace: String,
/// Comma-separated master addresses, whose filers the tables are kept
/// through. A table named by a local URI needs none.
#[arg(long, alias = "master", env = "WEED_MASTERS")]
masters: Option<String>,
/// The filer group whose gateways and filers hold the tables.
/// The filer group whose filers hold the tables.
#[arg(
long,
alias = "filer.group",
@@ -37,7 +45,7 @@ struct Args {
filer_signing_key: Option<String>,
/// The cluster's security.toml; by default the file weed processes find
/// in ., ~/.seaweedfs and /etc/seaweedfs.
/// in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<std::path::PathBuf>,
@@ -138,44 +146,34 @@ enum IndexAction {
},
}
/// Where tables are found: through the cluster the masters name, or, for a
/// local path, nowhere in particular.
struct Tables {
cluster: Option<Cluster>,
storage: Storage,
signing_key: Option<SigningKey>,
}
impl Tables {
/// `id` is a delimiter-joined table id, looked up in the namespace of a
/// gateway the masters name; when it looks like a URI the dataset is
/// opened directly: an `s3://` URI on the cluster's storage, a local path
/// (`/path/...`, `file://...`) as it is.
async fn open(&self, id: &str) -> Result<lance::Dataset> {
let on_cluster = id.starts_with("s3://");
if !on_cluster && (id.contains("://") || id.starts_with('/')) {
return lance::dataset::builder::DatasetBuilder::from_uri(id)
.load()
.await
.with_context(|| format!("open {id}"));
}
let Some(cluster) = &self.cluster else {
bail!("{id} is kept on the cluster and needs --masters");
};
if on_cluster {
let description = TableDescription {
location: id.to_string(),
storage_options: Default::default(),
managed_versioning: false,
};
return dataset::open_at(&description, self.storage.wrapper(id).await?, None).await;
}
let client = NamespaceClient::new(cluster.lance_namespace().await?)
.with_signing_key(self.signing_key.as_ref());
Ok(dataset::open(&client, &parse_id(id), &self.storage)
.await?
.dataset)
/// `id` is a delimiter-joined table id; when it looks like a URI the dataset
/// is opened directly, skipping the namespace: an `s3://` URI on the
/// cluster's storage, a local path (`/path/...`, `file://...`) as it is.
async fn open_dataset(
client: &NamespaceClient,
id: &str,
storage: &Storage,
) -> Result<lance::Dataset> {
let on_cluster = id.starts_with("s3://");
if !on_cluster && (id.contains("://") || id.starts_with('/')) {
return lance::dataset::builder::DatasetBuilder::from_uri(id)
.load()
.await
.with_context(|| format!("open {id}"));
}
if storage.0.is_none() {
bail!("{id} is kept on the cluster and needs --masters");
}
if on_cluster {
let description = TableDescription {
location: id.to_string(),
storage_options: Default::default(),
managed_versioning: false,
};
return dataset::open_at(&description, storage.wrapper(id).await?, None).await;
}
let table = dataset::open(client, &parse_id(id), storage).await?;
Ok(table.dataset)
}
#[tokio::main]
@@ -190,26 +188,20 @@ async fn main() -> Result<()> {
.init();
let args = Args::parse();
let security = weed_lance_worker::security::Security::load(args.security_toml.as_deref())?;
let security =
weed_lance_worker::security::Security::load(args.security_toml.as_deref(), None)?;
let signing_key = SigningKey::new(
args.filer_signing_key
.or_else(|| security.get("jwt.filer_signing.key")),
);
let tables = match &args.masters {
let client = NamespaceClient::new(args.namespace).with_signing_key(signing_key.as_ref());
let storage = match &args.masters {
Some(masters) => {
let cluster = Cluster::new(masters, &args.filer_group, &security)?;
let storage = Storage(Some(cluster.storage(&security).await?));
Tables {
cluster: Some(cluster),
storage,
signing_key,
}
let cluster =
weed_lance_worker::cluster::Cluster::new(masters, &args.filer_group, &security)?;
Storage(Some(cluster.storage(&security).await?))
}
None => Tables {
cluster: None,
storage: Storage::default(),
signing_key,
},
None => Storage::default(),
};
match args.command {
@@ -218,7 +210,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = tables.open(&id).await?;
let dataset = open_dataset(&client, &id, &storage).await?;
let schema: arrow_schema::Schema = dataset.schema().into();
let resolved =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref());
@@ -258,7 +250,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = tables.open(&id).await?;
let dataset = open_dataset(&client, &id, &storage).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
let coverages = coverage::coverage(&dataset, &vector.vector_column).await?;
@@ -270,7 +262,7 @@ async fn main() -> Result<()> {
vector_column,
key_column,
} => {
let dataset = tables.open(&id).await?;
let dataset = open_dataset(&client, &id, &storage).await?;
let vector =
VectorTable::resolve(&dataset, vector_column.as_deref(), key_column.as_deref())?;
for batch in query::get(&dataset, &vector, &keys, None).await? {
@@ -290,7 +282,7 @@ async fn main() -> Result<()> {
key_column,
nprobes,
} => {
let opened = tables.open(&id).await?;
let opened = open_dataset(&client, &id, &storage).await?;
let dataset = match version {
Some(v) => opened.checkout_version(v).await?,
None => opened,
@@ -317,7 +309,6 @@ async fn main() -> Result<()> {
nprobes,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let hits = if flat {
query::flat(&dataset, &vector_table, &query).await?
@@ -335,7 +326,7 @@ async fn main() -> Result<()> {
id, vector_column, ..
} => (id.clone(), vector_column.clone()),
};
let mut dataset = tables.open(&id).await?;
let mut dataset = open_dataset(&client, &id, &storage).await?;
let table = VectorTable::resolve(&dataset, vector_column.as_deref(), None)?;
let started = std::time::Instant::now();
match action {
@@ -412,17 +403,6 @@ mod tests {
.unwrap();
assert_eq!(args.masters.as_deref(), Some("m:9333"));
assert_eq!(args.filer_group, "eu");
assert!(
Args::try_parse_from([
"weed-vector",
"--namespace",
"http://s3:9101",
"describe",
"t"
])
.is_err(),
"the namespace comes from the masters"
);
assert!(
Args::try_parse_from(["weed-vector", "--encryptVolumeData", "describe", "t"]).is_err(),
"volume encryption follows the filer"
@@ -312,7 +312,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let mut ids: Vec<u64> = query::flat(&pinned, &resolved, &q)
.await
@@ -735,7 +734,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
assert!(query::flat(&dataset, &resolved, &q).await.is_err());
}
+6 -143
View File
@@ -39,15 +39,8 @@ pub struct Query {
/// a worker the unindexed-fragment sweep. Listed ids that no longer exist
/// scan nothing.
pub fragments: Option<Vec<u64>>,
/// Score the matches exactly instead of searching the vector index when
/// the filter's indexed metadata keys match at most this many rows of the
/// scope; 0 never does. None takes [`DEFAULT_EXACT_MATCH_LIMIT`].
pub exact_match_limit: Option<usize>,
}
/// Up to this many matches of an indexed metadata key are scored exactly.
pub const DEFAULT_EXACT_MATCH_LIMIT: usize = 256;
/// One row of a top-K answer.
#[derive(Debug, Clone, serde::Serialize)]
pub struct Hit {
@@ -60,101 +53,14 @@ pub struct Hit {
/// Exact top-K over every fragment, ignoring any index.
pub async fn flat(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
run(scanner(dataset, table, query, false).await?.0, table).await
run(scanner(dataset, table, query, false).await?, table).await
}
/// Top-K with the ANN index where it covers the fragment and a flat pass over
/// the rest. Whether the index is used is Lance's decision per fragment, so
/// rows written after the last index build are always candidates.
///
/// A prefiltered search sees only the probed partitions: it can come back
/// short of k, or with unscored rows (infinite distance) when at most k rows
/// match. Either way it is answered again by an exact scan of the same scope.
///
/// When the filter's indexed metadata keys match few rows of that scope,
/// they are scored exactly to begin with. The decision is per scope, so
/// exact answers of several scopes merge into the exact answer.
pub async fn ann(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
if few_indexed_matches(dataset, table, query).await? {
return exact_in_scope(dataset, table, query).await;
}
let (scanner, indexed) = scanner(dataset, table, query, true).await?;
let hits = run(scanner, table).await?;
if indexed
&& query.filter.is_some()
&& !query.postfilter
&& (hits.len() < query.k || hits.iter().any(|h| !h.distance.is_finite()))
{
return exact_in_scope(dataset, table, query).await;
}
Ok(hits)
}
/// [`flat`] over what [`ann`] searches for `query`: the listed fragments plus
/// the live coverage of the listed index segments, or the whole table.
async fn exact_in_scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Vec<Hit>> {
let exact = Query {
index_segments: None,
fragments: scope(dataset, table, query).await?,
..query.clone()
};
run(scanner(dataset, table, &exact, false).await?.0, table).await
}
/// The fragments [`ann`] searches for `query`, or None for the whole table.
async fn scope(dataset: &Dataset, table: &VectorTable, query: &Query) -> Result<Option<Vec<u64>>> {
Ok(match &query.index_segments {
Some(segments) if !segments.is_empty() => {
let mut ids = query.fragments.clone().unwrap_or_default();
ids.extend(
crate::segments::covered_fragments(dataset, &table.vector_column, segments).await?,
);
Some(ids)
}
_ => query.fragments.clone(),
})
}
/// Whether the rows of [`ann`]'s scope matching the filter's indexed
/// metadata keys, counted through their scalar indexes, are at most the
/// query's limit. Only a search through the vector index asks.
pub(crate) async fn few_indexed_matches(
dataset: &Dataset,
table: &VectorTable,
query: &Query,
) -> Result<bool> {
let limit = query.exact_match_limit.unwrap_or(DEFAULT_EXACT_MATCH_LIMIT);
let Some(filter) = &query.filter else {
return Ok(false);
};
if limit == 0 || query.postfilter || query.index_segments.as_ref().is_some_and(|s| s.is_empty())
{
return Ok(false);
}
let ready = crate::indexed_filter::ready_columns(dataset);
if ready.is_empty()
|| crate::index::index_names(dataset, &table.vector_column)
.await?
.is_empty()
{
return Ok(false);
}
let indexed = crate::filter::apply(&mut dataset.scan(), filter, &ready)?;
if indexed.is_empty() {
return Ok(false);
}
let scope = scope(dataset, table, query).await?;
// An AND matches at most what its most selective indexed conjunct does.
for conjunct in &indexed {
let count =
crate::indexed_filter::count_indexed(dataset, conjunct, scope.as_deref(), limit as u64)
.await?;
tracing::debug!(column = %conjunct.column, ?count, limit, "indexed metadata filter");
if count.is_some() {
return Ok(true);
}
}
Ok(false)
run(scanner(dataset, table, query, true).await?, table).await
}
/// Fetch rows by key, projected to `columns` (all of them when None).
@@ -195,7 +101,7 @@ async fn scanner(
table: &VectorTable,
query: &Query,
use_index: bool,
) -> Result<(Scanner, bool)> {
) -> Result<Scanner> {
if query.vector.len() != table.dimension {
bail!(
"query dim({}) does not match the table's dim({})",
@@ -211,24 +117,18 @@ async fn scanner(
.use_index(use_index)
.with_row_id();
if let Some(filter) = &query.filter {
let ready = crate::indexed_filter::ready_columns(dataset);
crate::filter::apply(&mut scanner, filter, &ready)?;
crate::filter::apply(&mut scanner, filter)?;
scanner.prefilter(!query.postfilter);
}
// An explicitly empty segment list searches no index, so there is
// nothing to size probes for.
let no_segments = query.index_segments.as_ref().is_some_and(|s| s.is_empty());
let mut indexed = false;
if use_index && !no_segments {
let probes = match query.nprobes {
Some(n) => crate::index::index_names(dataset, &table.vector_column)
.await?
.first()
.map(|_| crate::index::Probes { min: n, max: n }),
Some(n) => Some(crate::index::Probes { min: n, max: n }),
None => crate::index::default_probes(dataset, &table.vector_column).await?,
};
if let Some(probes) = probes {
indexed = true;
// Lance searches `min` partitions, and under a prefilter keeps
// going up to `max` until it has k rows. An open bound would
// make it prepare every partition for that, which costs as much
@@ -278,7 +178,7 @@ async fn scanner(
columns.push(DISTANCE_COLUMN.to_string());
columns.push(ROW_ID_COLUMN.to_string());
scanner.project(&columns)?;
Ok((scanner, indexed))
Ok(scanner)
}
async fn run(scanner: Scanner, table: &VectorTable) -> Result<Vec<Hit>> {
@@ -361,7 +261,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let hits = flat(&dataset, &table, &query).await.unwrap();
assert_eq!(hits.len(), 2);
@@ -403,7 +302,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
@@ -483,7 +381,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
@@ -587,7 +484,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
assert!(flat(&dataset, &table, &query).await.is_err());
}
@@ -611,7 +507,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let indexed = ann(&dataset, &table, &query).await.unwrap();
let exact = flat(&dataset, &table, &query).await.unwrap();
@@ -620,36 +515,4 @@ mod tests {
exact.iter().map(|h| &h.key).collect::<Vec<_>>()
);
}
/// An explicit probe count does not make an unindexed table's scan count
/// as indexed, so a short filtered answer is not scanned a second time.
#[tokio::test]
async fn explicit_probes_need_an_index() {
let dir = TempDir::new().unwrap();
let rows = crate::testing::vectors(300, DIM);
let mut dataset = write_dataset(&dir, &rows, &["a"; 300]).await;
let table = VectorTable::resolve(&dataset, None, None).unwrap();
let query = Query {
vector: rows[0].clone(),
k: 10,
filter: Some("tag = 'a'".to_string()),
postfilter: false,
distance: DistanceType::L2,
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
};
assert!(!scanner(&dataset, &table, &query, true).await.unwrap().1);
crate::index::build(
&mut dataset,
&table.vector_column,
crate::index::INDEX_NAME,
4,
false,
)
.await
.unwrap();
assert!(scanner(&dataset, &table, &query, true).await.unwrap().1);
}
}
@@ -139,7 +139,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
};
let want: Vec<(u64, u32)> = query::ann(&dataset, &resolved, &base)
.await
@@ -240,7 +239,6 @@ mod tests {
nprobes: None,
index_segments: None,
fragments: Some(vec![u64::MAX]),
exact_match_limit: None,
};
assert!(
query::ann(&dataset, &resolved, &q)
-1
View File
@@ -44,7 +44,6 @@ fn query_for(vector: Vec<f32>, k: usize) -> Query {
nprobes: Some(4),
index_segments: None,
fragments: None,
exact_match_limit: None,
}
}
-1
View File
@@ -46,7 +46,6 @@ tracing.workspace = true
tracing-subscriber.workspace = true
[dev-dependencies]
lance-index = "10"
tempfile = "3"
[build-dependencies]
@@ -1,392 +0,0 @@
//! How often, and how slowly, each index's queries filter on each metadata
//! key over the last hour. Keys come from the parsed filter; the number of
//! indexes and of keys per index is bounded, so arbitrary keys cannot grow
//! memory without limit. Not exported as metrics: a key is no label.
use std::collections::{BTreeMap, HashMap};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use weed_vector_core::indexed_filter::operand;
use crate::pb::vector as pb;
const BUCKETS: usize = 12;
const BUCKET: Duration = Duration::from_secs(300);
pub const WINDOW: Duration = Duration::from_secs(BUCKET.as_secs() * BUCKETS as u64);
pub const MAX_INDEXES: usize = 512;
pub const MAX_KEYS_PER_INDEX: usize = 32;
const MAX_RETIRED_TABLES: usize = 4;
#[derive(Default, Clone, Copy)]
struct Bucket {
/// The bucket's number since the stats started.
at: u64,
queries: u64,
seconds: f64,
/// The operand kinds the bucket's queries compared the key with.
kinds: u8,
}
#[derive(Default)]
struct KeyStats {
buckets: [Bucket; BUCKETS],
}
#[derive(Default)]
struct IndexStats {
/// The table the stats were counted on: an index dropped and created
/// again under its name is another table.
table: String,
/// Tables the name held before, whose late queries are not counted.
retired: Vec<String>,
keys: HashMap<String, KeyStats>,
/// The last bucket a key was left uncounted in.
truncated: Option<u64>,
last: u64,
}
impl IndexStats {
/// Starts counting on `table`, retiring the table counted on before.
fn replace(&mut self, table: &str) {
let mut retired = std::mem::take(&mut self.retired);
if !self.table.is_empty() {
retired.push(std::mem::take(&mut self.table));
if retired.len() > MAX_RETIRED_TABLES {
retired.remove(0);
}
}
*self = IndexStats {
table: table.to_string(),
retired,
last: self.last,
..Default::default()
};
}
}
/// Whether bucket `at` is still in the window of bucket `now`.
fn live(at: u64, now: u64) -> bool {
at + BUCKETS as u64 > now
}
pub struct FilterStats {
start: Instant,
indexes: Mutex<HashMap<String, IndexStats>>,
}
impl Default for FilterStats {
fn default() -> Self {
Self::new()
}
}
impl FilterStats {
pub fn new() -> Self {
Self {
start: Instant::now(),
indexes: Mutex::new(HashMap::new()),
}
}
fn bucket(&self, now: Instant) -> u64 {
(now.duration_since(self.start).as_secs() / BUCKET.as_secs()) + 1
}
/// Drops the stats of `index`, which now holds `table` ("" once
/// dropped): late queries of the table it held before are not counted.
pub fn forget(&self, index: &str, table: &str) {
let mut indexes = self.indexes.lock().unwrap();
if let Some(stats) = indexes.get_mut(index)
&& (table.is_empty() || stats.table != table)
{
stats.replace(table);
}
}
/// One query of `index`, whose table is `table`, that took `elapsed` and
/// filtered on `keys`. Stats counted on another table under the name are
/// dropped; a query of a table the name no longer holds is not counted.
pub fn record(&self, index: &str, table: &str, keys: &BTreeMap<String, u8>, elapsed: Duration) {
self.record_table_at(index, table, keys, elapsed, Instant::now());
}
#[cfg(test)]
fn record_at(&self, index: &str, keys: &BTreeMap<String, u8>, elapsed: Duration, now: Instant) {
self.record_table_at(index, "", keys, elapsed, now);
}
fn record_table_at(
&self,
index: &str,
table: &str,
keys: &BTreeMap<String, u8>,
elapsed: Duration,
now: Instant,
) {
if keys.is_empty() {
return;
}
let at = self.bucket(now);
let mut indexes = self.indexes.lock().unwrap();
if !indexes.contains_key(index) && indexes.len() >= MAX_INDEXES {
let Some(oldest) = indexes
.iter()
.min_by_key(|(_, stats)| stats.last)
.map(|(name, _)| name.clone())
else {
return;
};
indexes.remove(&oldest);
}
let stats = indexes.entry(index.to_string()).or_default();
if !table.is_empty() && stats.table != table {
if stats.retired.iter().any(|t| t == table) {
return;
}
if stats.table.is_empty() {
stats.table = table.to_string();
} else {
stats.replace(table);
}
}
stats.last = stats.last.max(at);
for (key, kinds) in keys {
if !stats.keys.contains_key(key) && stats.keys.len() >= MAX_KEYS_PER_INDEX {
// Make room only by dropping a key no query used in the window.
let idle = stats
.keys
.iter()
.find(|(_, k)| k.buckets.iter().all(|b| !live(b.at, at)))
.map(|(name, _)| name.clone());
match idle {
Some(idle) => {
stats.keys.remove(&idle);
}
None => {
stats.truncated = stats.truncated.max(Some(at));
continue;
}
}
}
let entry = stats.keys.entry(key.clone()).or_default();
let bucket = &mut entry.buckets[(at % BUCKETS as u64) as usize];
if bucket.at != at {
*bucket = Bucket {
at,
..Default::default()
};
}
bucket.queries += 1;
bucket.seconds += elapsed.as_secs_f64();
bucket.kinds |= kinds;
}
}
/// The stats of `index` over the window.
pub fn snapshot(&self, index: &str) -> pb::FilterStatsResponse {
self.snapshot_at(index, Instant::now())
}
fn snapshot_at(&self, index: &str, now: Instant) -> pb::FilterStatsResponse {
let at = self.bucket(now);
let window_seconds = now.duration_since(self.start).min(WINDOW).as_secs() as u32;
let indexes = self.indexes.lock().unwrap();
let Some(stats) = indexes.get(index) else {
return pb::FilterStatsResponse {
window_seconds,
..Default::default()
};
};
let mut keys: Vec<pb::FilterKeyStats> = stats
.keys
.iter()
.filter_map(|(key, s)| {
let (queries, seconds, kinds) = s
.buckets
.iter()
.filter(|b| live(b.at, at))
.fold((0, 0.0, 0), |(q, t, k), b| {
(q + b.queries, t + b.seconds, k | b.kinds)
});
(queries > 0).then(|| pb::FilterKeyStats {
key: key.clone(),
queries,
seconds,
string_operand: kinds & operand::STRING != 0,
number_operand: kinds & operand::NUMBER != 0,
bool_operand: kinds & operand::BOOL != 0,
})
})
.collect();
keys.sort_by(|a, b| b.queries.cmp(&a.queries).then(a.key.cmp(&b.key)));
pb::FilterStatsResponse {
keys,
window_seconds,
truncated: stats.truncated.is_some_and(|t| live(t, at)),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn keys(pairs: &[(&str, u8)]) -> BTreeMap<String, u8> {
pairs.iter().map(|(k, v)| (k.to_string(), *v)).collect()
}
#[test]
fn counts_queries_and_latency_per_key_within_the_window() {
let stats = FilterStats::new();
let t0 = stats.start;
let ms = Duration::from_millis;
stats.record_at("b/i", &keys(&[("author", operand::STRING)]), ms(10), t0);
stats.record_at(
"b/i",
&keys(&[("author", operand::STRING), ("year", operand::NUMBER)]),
ms(30),
t0 + Duration::from_secs(600),
);
stats.record_at("b/j", &keys(&[("x", operand::BOOL)]), ms(5), t0);
let got = stats.snapshot_at("b/i", t0 + Duration::from_secs(900));
assert_eq!(got.window_seconds, 900);
assert_eq!(got.keys.len(), 2);
assert_eq!(got.keys[0].key, "author");
assert_eq!(got.keys[0].queries, 2);
assert!((got.keys[0].seconds - 0.04).abs() < 1e-9);
assert!(got.keys[0].string_operand && !got.keys[0].number_operand);
assert_eq!(got.keys[1].key, "year");
assert!(got.keys[1].number_operand);
// The first query leaves the window an hour after its bucket.
let later = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(1));
assert_eq!(later.window_seconds, WINDOW.as_secs() as u32);
assert_eq!(later.keys[0].queries, 1);
let year = later.keys.iter().find(|k| k.key == "year").unwrap();
assert!(year.number_operand);
// A string query that left the window no longer marks the key.
stats.record_at(
"b/i",
&keys(&[("author", operand::NUMBER)]),
ms(1),
t0 + WINDOW + Duration::from_secs(2),
);
let mixed = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(3));
let author = mixed.keys.iter().find(|k| k.key == "author").unwrap();
assert!(author.string_operand && author.number_operand);
let numeric = stats.snapshot_at("b/i", t0 + WINDOW + Duration::from_secs(700));
let author = numeric.keys.iter().find(|k| k.key == "author").unwrap();
assert!(!author.string_operand && author.number_operand);
let gone = stats.snapshot_at("b/i", t0 + 2 * WINDOW + Duration::from_secs(900));
assert!(gone.keys.is_empty());
assert!(stats.snapshot_at("other", t0).keys.is_empty());
}
#[test]
fn indexes_and_keys_are_bounded() {
let stats = FilterStats::new();
let t0 = stats.start;
for i in 0..MAX_KEYS_PER_INDEX + 5 {
stats.record_at(
"b/i",
&keys(&[(&format!("k{i}"), operand::STRING)]),
Duration::ZERO,
t0,
);
}
let got = stats.snapshot_at("b/i", t0);
assert_eq!(got.keys.len(), MAX_KEYS_PER_INDEX);
assert!(got.truncated);
// A key idle for the whole window makes room for a new one.
let later = t0 + WINDOW + BUCKET;
stats.record_at(
"b/i",
&keys(&[("new", operand::STRING)]),
Duration::ZERO,
later,
);
let got = stats.snapshot_at("b/i", later);
assert!(!got.truncated, "the uncounted keys left the window");
assert_eq!(got.keys.len(), 1);
assert_eq!(got.keys[0].key, "new");
for i in 0..MAX_INDEXES + 3 {
stats.record_at(
&format!("b/{i}"),
&keys(&[("k", operand::STRING)]),
Duration::ZERO,
later,
);
}
assert_eq!(stats.indexes.lock().unwrap().len(), MAX_INDEXES);
}
#[test]
fn a_record_from_an_earlier_bucket_keeps_the_later_truncation() {
let stats = FilterStats::new();
let t0 = stats.start;
for i in 0..=MAX_KEYS_PER_INDEX {
stats.record_at(
"b/i",
&keys(&[(&format!("k{i}"), operand::STRING)]),
Duration::ZERO,
t0 + BUCKET,
);
}
// Took its time before the lock while the later bucket recorded.
stats.record_at(
"b/i",
&keys(&[("late", operand::STRING)]),
Duration::ZERO,
t0,
);
let got = stats.snapshot_at("b/i", t0 + WINDOW);
assert!(
got.truncated,
"the later bucket's uncounted key is in the window"
);
assert_eq!(stats.indexes.lock().unwrap()["b/i"].last, 2);
}
#[test]
fn stats_follow_the_table_behind_an_index_name() {
let stats = FilterStats::new();
let t0 = stats.start;
let author = keys(&[("author", operand::STRING)]);
let count = |stats: &FilterStats| {
stats
.snapshot_at("b/i", t0)
.keys
.first()
.map_or(0, |k| k.queries)
};
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 2);
// The index was created again: its first query starts over.
stats.record_table_at("b/i", "t2", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 1);
// A late query of the old table is not counted on the new one.
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 1);
stats.forget("b/i", "");
assert_eq!(count(&stats), 0);
// A first query records its table: a later table starts over.
stats.record_table_at("b/i", "t3", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t4", &author, Duration::ZERO, t0);
assert_eq!(count(&stats), 1);
}
#[test]
fn a_late_query_after_a_drop_is_not_counted_on_the_new_table() {
let stats = FilterStats::new();
let t0 = stats.start;
let author = keys(&[("author", operand::STRING)]);
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
stats.forget("b/i", "");
stats.record_table_at("b/i", "t2", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t2", &author, Duration::ZERO, t0);
stats.record_table_at("b/i", "t1", &author, Duration::ZERO, t0);
assert_eq!(stats.snapshot_at("b/i", t0).keys[0].queries, 2);
}
}
@@ -1,817 +0,0 @@
//! Indexed metadata keys through the VectorService: PutVectors derives the
//! columns, and a query answers the same with or without them.
use std::sync::Arc;
use arrow_array::RecordBatch;
use arrow_schema::Schema;
use lance::Dataset;
use lance::dataset::{BatchUDF, NewColumnTransform};
use lance::index::DatasetIndexExt;
use lance_index::IndexType;
use lance_index::scalar::{BuiltinIndexType, ScalarIndexParams};
use tonic::Request;
use weed_lance_worker::metadata_index::{self, STATE_FIELD_META, State};
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
use crate::pb::vector::{self as pb, vector_service_server::VectorService};
use crate::service::VectorServer;
const DIM: usize = 8;
const ROWS: usize = 3000;
const COLUMN: &str = "_mk_0";
/// How the engine answers a filter once `author` is indexed.
#[derive(Debug, Clone, Copy, PartialEq)]
enum Path {
/// Through the column, at most the exact-match limit of rows: exact.
Exact,
/// Through the column, more rows: the vector index with the column's
/// prefilter.
Ivf,
/// Not through the column.
Json,
}
/// S3 Vectors filters, the gateway's translation of each, and its path.
const FILTERS: [(&str, &str, Path); 22] = [
(
"{\"author\":\"alice\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"alice\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false))",
Path::Ivf,
),
(
"{\"author\":{\"$eq\":\"bob\"}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"bob\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false))",
Path::Exact,
),
(
"{\"author\":\"carol\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"carol\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"carol\"'), false))",
Path::Exact,
),
(
"{\"author\":\"x\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"x\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"x\"'), false))",
Path::Exact,
),
(
"{\"author\":\"7\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"7\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"7\"'), false))",
Path::Exact,
),
(
"{\"author\":7}",
"(COALESCE(TRY_CAST(json_extract(`metadata`, '$[\"author\"]') AS DOUBLE) = 7, false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '7'), false))",
Path::Json,
),
(
"{\"author\":true}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = 'true', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', 'true'), false))",
Path::Json,
),
(
"{\"author\":{\"$in\":[\"alice\",\"bob\",\"x\"]}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"alice\"', '\"bob\"', '\"x\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"x\"'), false))",
Path::Ivf,
),
(
"{\"author\":{\"$in\":[\"alice\",7]}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"alice\"'), false) OR COALESCE(TRY_CAST(json_extract(`metadata`, '$[\"author\"]') AS DOUBLE) in (7), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '7'), false))",
Path::Json,
),
(
"{\"author\":{\"$ne\":\"alice\"}}",
"NOT (COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"alice\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false))",
Path::Json,
),
(
"{\"author\":{\"$nin\":[\"alice\",\"bob\"]}}",
"NOT (COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"alice\"', '\"bob\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false))",
Path::Json,
),
(
"{\"author\":{\"$exists\":false}}",
"NOT json_exists(`metadata`, '$[\"author\"]')",
Path::Json,
),
(
"{\"$and\":[{\"author\":\"alice\"},{\"genre\":\"g1\"}]}",
"((COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"alice\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"alice\"'), false)) AND (COALESCE(json_extract(`metadata`, '$[\"genre\"]') = '\"g1\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"genre\"]', '\"g1\"'), false)))",
Path::Ivf,
),
(
"{\"$and\":[{\"author\":\"bob\"},{\"year\":{\"$gt\":2005}}]}",
"((COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"bob\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false)) AND TRY_CAST(json_extract(`metadata`, '$[\"year\"]') AS DOUBLE) > 2005)",
Path::Exact,
),
(
"{\"$or\":[{\"author\":\"bob\"},{\"genre\":\"g2\"}]}",
"((COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"bob\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"bob\"'), false)) OR (COALESCE(json_extract(`metadata`, '$[\"genre\"]') = '\"g2\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"genre\"]', '\"g2\"'), false)))",
Path::Json,
),
(
"{\"author\":\"o'neil \\\"q\\\" \\\\ \\n\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"o''neil \\\"q\\\" \\\\ \\n\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"o''neil \\\"q\\\" \\\\ \\n\"'), false))",
Path::Exact,
),
(
"{\"author\":\"nobody\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"nobody\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"nobody\"'), false))",
Path::Exact,
),
("{\"author\":{\"$in\":[]}}", "false", Path::Json),
(
"{\"genre\":\"g1\"}",
"(COALESCE(json_extract(`metadata`, '$[\"genre\"]') = '\"g1\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"genre\"]', '\"g1\"'), false))",
Path::Json,
),
(
"{\"author\":\"u5\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"u5\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"u5\"'), false))",
Path::Exact,
),
(
"{\"author\":\"ctl\\u0001x\"}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') = '\"ctl\\u{1}x\"', false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"ctl\\u0001x\"'), false))",
Path::Json,
),
(
"{\"author\":{\"$in\":[\"u5\",\"u6\"]}}",
"(COALESCE(json_extract(`metadata`, '$[\"author\"]') in ('\"u5\"', '\"u6\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"u5\"'), false) OR COALESCE(json_array_contains(`metadata`, '$[\"author\"]', '\"u6\"'), false))",
Path::Exact,
),
];
fn rng(seed: &mut u64) -> f32 {
*seed = seed
.wrapping_mul(6364136223846793005)
.wrapping_add(1442695040888963407);
((*seed >> 33) as f32 / (1u64 << 31) as f32) - 0.5
}
fn vector_of(i: usize) -> Vec<f32> {
let mut centre = (i % 16) as u64 + 1;
let mut noise = i as u64 * 7919 + 13;
(0..DIM)
.map(|_| rng(&mut centre) * 4.0 + rng(&mut noise))
.collect()
}
fn author(i: usize) -> Option<serde_json::Value> {
use serde_json::json;
Some(match i % 100 {
0..=9 => json!("alice"),
10 => json!("bob"),
11 => json!(["carol", "x"]),
12 => json!(7),
13 => json!("7"),
14 => serde_json::Value::Null,
15 => return None,
16 => json!(true),
17 => json!("o'neil \"q\" \\ \n"),
18 => json!("ctl\u{1}x"),
19 => json!(["alice", 3]),
_ => json!(format!("u{}", i % 37)),
})
}
fn row(i: usize, author: Option<serde_json::Value>) -> pb::Vector {
let mut meta = serde_json::json!({"genre": format!("g{}", i % 3), "year": 2000 + i % 10});
if let Some(author) = author {
meta["author"] = author;
}
let serde_json::Value::Object(meta) = meta else {
unreachable!()
};
pb::Vector {
key: format!("k{i}"),
data: vector_of(i),
metadata: Some(crate::service::json_to_struct(meta)),
}
}
struct Fixture {
server: VectorServer,
exact_off: VectorServer,
table: pb::Table,
}
impl Fixture {
async fn new() -> Self {
let bucket = format!(
"mk-{:x}",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
);
let table = pb::Table {
id: vec![bucket.clone(), "vector".into(), "x".into()],
location: format!("shared-memory://{bucket}/vector/x"),
..Default::default()
};
let fixture = Self {
server: VectorServer::new().with_schemes(&["shared-memory"]),
exact_off: VectorServer::new()
.with_schemes(&["shared-memory"])
.with_exact_match_limit(Some(0)),
table,
};
fixture
.server
.create_index(Request::new(pb::CreateIndexRequest {
table: Some(fixture.table.clone()),
dimension: DIM as u32,
distance_metric: pb::DistanceMetric::L2 as i32,
..Default::default()
}))
.await
.unwrap();
fixture
}
async fn put(&self, vectors: Vec<pb::Vector>) {
self.server
.put_vectors(Request::new(pb::PutVectorsRequest {
table: Some(self.table.clone()),
vectors,
}))
.await
.unwrap();
}
async fn dataset(&self, version: u64) -> Dataset {
let dataset = Dataset::open(&self.table.location).await.unwrap();
if version == 0 {
dataset
} else {
dataset.checkout_version(version).await.unwrap()
}
}
/// Adds `author`'s column, indexes it and marks it ready, returning the
/// version before it was ready.
async fn index_author(&self) -> u64 {
let mut dataset = self.dataset(0).await;
let output = Arc::new(Schema::new(vec![metadata_index::field(
COLUMN,
"author",
State::Building,
)]));
let schema = output.clone();
dataset
.add_columns(
NewColumnTransform::BatchUDF(BatchUDF {
mapper: Box::new(move |batch: &RecordBatch| {
let column = metadata_index::column_from_metadata(
batch.column_by_name("metadata").unwrap().as_ref(),
"author",
)
.map_err(|e| lance::Error::invalid_input(e.to_string()))?;
Ok(RecordBatch::try_new(schema.clone(), vec![column])?)
}),
output_schema: output,
result_checkpoint: None,
}),
Some(vec!["metadata".to_string()]),
None,
)
.await
.unwrap();
dataset
.create_index(
&[COLUMN],
IndexType::LabelList,
Some(format!("{COLUMN}_idx")),
&ScalarIndexParams::for_builtin(BuiltinIndexType::LabelList),
true,
)
.await
.unwrap();
let building = dataset.version().version;
self.set_state(State::Ready).await;
building
}
async fn set_state(&self, state: State) -> u64 {
let mut dataset = self.dataset(0).await;
dataset
.update_field_metadata()
.update(COLUMN, [(STATE_FIELD_META, state.as_str())])
.unwrap()
.await
.unwrap();
dataset.version().version
}
async fn query(
&self,
server: &VectorServer,
version: u64,
filter: &str,
k: u32,
v: &[f32],
) -> Vec<(String, f32)> {
let mut table = self.table.clone();
table.version = version;
server
.query_vectors(Request::new(pb::QueryVectorsRequest {
table: Some(table),
query_vector: v.to_vec(),
top_k: k,
filter: filter.to_string(),
return_distance: true,
..Default::default()
}))
.await
.unwrap()
.into_inner()
.vectors
.into_iter()
.map(|r| (r.key, r.distance))
.collect()
}
/// Exact filtered top-k at `version`.
async fn flat(&self, version: u64, filter: &str, k: u32, v: &[f32]) -> Vec<(String, f32)> {
let dataset = self.dataset(version).await;
let table = VectorTable::resolve(&dataset, None, Some("key")).unwrap();
query::flat(
&dataset,
&table,
&Query {
vector: v.to_vec(),
k: k as usize,
filter: Some(filter.to_string()),
postfilter: false,
distance: lance_linalg::distance::DistanceType::L2,
nprobes: None,
index_segments: None,
fragments: None,
exact_match_limit: None,
},
)
.await
.unwrap()
.into_iter()
.map(|h| (h.key, h.distance))
.collect()
}
/// Every filter answers through the column as through the JSON at
/// `json` (the same rows and indexes, the column not ready), and an
/// exact answer as the exact filtered top-k.
async fn compare(&self, json: u64, ready: u64) {
for q in [7, 1234] {
let v = vector_of(q);
for (s3, filter, path) in FILTERS {
for k in [10, 400] {
let what = format!("{s3} k={k} q={q}");
let exact = self.flat(json, filter, k, &v).await;
assert_same(&self.flat(ready, filter, k, &v).await, &exact, &what);
let json_ann = self.query(&self.server, json, filter, k, &v).await;
let off = self.query(&self.exact_off, ready, filter, k, &v).await;
assert_same(&off, &json_ann, &format!("{what}: indexed prefilter"));
let got = self.query(&self.server, ready, filter, k, &v).await;
let want = if path == Path::Exact {
&exact
} else {
&json_ann
};
assert_same(&got, want, &format!("{what}: {path:?}"));
}
}
}
}
}
fn assert_same(got: &[(String, f32)], want: &[(String, f32)], what: &str) {
assert_eq!(got.len(), want.len(), "{what}: {got:?} vs {want:?}");
// Ties may come back in either order: the same keys, and the same
// distance at each rank.
fn keys(hits: &[(String, f32)]) -> Vec<&str> {
let mut keys: Vec<&str> = hits.iter().map(|(k, _)| k.as_str()).collect();
keys.sort();
keys
}
assert_eq!(keys(got), keys(want), "{what}: {got:?} vs {want:?}");
for (g, w) in got.iter().zip(want) {
let same = (g.1 - w.1).abs() < 1e-4 || (g.1.is_infinite() && w.1.is_infinite());
assert!(same, "{what}: {got:?} vs {want:?}");
if g.0 != w.0 {
let tie = want
.iter()
.any(|(k, d)| k == &g.0 && (d - w.1).abs() < 1e-4);
assert!(
tie,
"{what}: {} at {} is no tie: {got:?} vs {want:?}",
g.0, g.1
);
}
}
}
/// Indexed and JSON answers agree on mixed types, missing keys, arrays,
/// null, untouched operators, and after updates, deletes and rows no
/// scalar or vector index covers yet.
#[tokio::test]
async fn indexed_answers_match_the_json_path() {
let fixture = Fixture::new().await;
for start in (0..ROWS).step_by(300) {
fixture
.put((start..start + 300).map(|i| row(i, author(i))).collect())
.await;
}
let mut dataset = fixture.dataset(0).await;
weed_lance_worker::vector_index::build(&mut dataset, "vector", "vector_idx", 16, false)
.await
.unwrap();
let json = fixture.index_author().await;
let schema: Schema = fixture.dataset(0).await.schema().into();
assert_eq!(
metadata_index::indexed_keys(&schema)[0].state,
Some(State::Ready)
);
fixture.compare(json, 0).await;
// Updates move rows between values, deletes drop some, and new rows land
// in fragments neither index covers; PutVectors fills the column.
fixture
.put(
(0..60)
.map(|i| row(i, Some(serde_json::json!(["moved", "bob"]))))
.chain((ROWS..ROWS + 200).map(|i| row(i, author(i))))
.collect(),
)
.await;
fixture
.server
.delete_vectors(Request::new(pb::DeleteVectorsRequest {
table: Some(fixture.table.clone()),
keys: (100..130).map(|i| format!("k{i}")).collect(),
}))
.await
.unwrap();
let json = fixture.set_state(State::Building).await;
let ready = fixture.set_state(State::Ready).await;
fixture.compare(json, ready).await;
let moved = r#"(COALESCE(json_extract(`metadata`, '$["author"]') = '"moved"', false) OR COALESCE(json_array_contains(`metadata`, '$["author"]', '"moved"'), false))"#;
let hits = fixture
.query(&fixture.server, ready, moved, 100, &vector_of(0))
.await;
assert_eq!(hits.len(), 60);
}
/// The planner counts and scores per scope: an exact answer over a fragment
/// subset is that subset's exact top-k.
#[tokio::test]
async fn a_scoped_query_is_exact_within_its_fragments() {
let fixture = Fixture::new().await;
for start in (0..ROWS).step_by(300) {
fixture
.put((start..start + 300).map(|i| row(i, author(i))).collect())
.await;
}
let mut dataset = fixture.dataset(0).await;
weed_lance_worker::vector_index::build(&mut dataset, "vector", "vector_idx", 16, false)
.await
.unwrap();
let json = fixture.index_author().await;
let ready = fixture.dataset(0).await;
let table = VectorTable::resolve(&ready, None, Some("key")).unwrap();
let ids: Vec<u64> = ready.fragments().iter().map(|f| f.id).take(4).collect();
let filter = FILTERS[1].1;
let scoped = || Query {
vector: vector_of(5),
k: 10,
filter: Some(filter.to_string()),
postfilter: false,
distance: lance_linalg::distance::DistanceType::L2,
nprobes: None,
index_segments: None,
fragments: Some(ids.clone()),
exact_match_limit: None,
};
let got = query::ann(&ready, &table, &scoped()).await.unwrap();
let old = fixture.dataset(json).await;
let want = query::flat(&old, &table, &scoped()).await.unwrap();
assert_eq!(want.len(), 10);
let pairs = |hits: Vec<weed_vector_core::Hit>| {
hits.into_iter()
.map(|h| (h.key, h.distance))
.collect::<Vec<_>>()
};
assert_same(&pairs(got), &pairs(want), "scoped bob");
}
/// The engine counts each index's filtered queries by key.
#[tokio::test]
async fn queries_are_counted_by_filter_key() {
let fixture = Fixture::new().await;
fixture
.put((0..50).map(|i| row(i, author(i))).collect())
.await;
for (_, filter, _) in &FILTERS[..3] {
fixture
.query(&fixture.server, 0, filter, 5, &vector_of(1))
.await;
}
let year = FILTERS[13].1;
fixture
.query(&fixture.server, 0, year, 5, &vector_of(1))
.await;
let stats = fixture
.server
.filter_stats(Request::new(pb::FilterStatsRequest {
table: Some(fixture.table.clone()),
}))
.await
.unwrap()
.into_inner();
let author = stats.keys.iter().find(|k| k.key == "author").unwrap();
assert_eq!(author.queries, 4);
assert!(author.string_operand && !author.number_operand);
let year = stats.keys.iter().find(|k| k.key == "year").unwrap();
assert_eq!(year.queries, 1);
assert!(year.number_operand && !year.string_operand);
}
/// A PutVectors that opened the table before its key column was added and
/// commits after: Lance rebases the write and its rows hold NULL in the new
/// column, which the write then fills from the rows' metadata.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_write_that_raced_the_column_add_fills_the_column() {
let fixture = Fixture::new().await;
fixture
.put((0..300).map(|i| row(i, author(i))).collect())
.await;
let unhealed = fixture.dataset(0).await;
let healed = fixture.dataset(0).await;
fixture.index_author().await;
let nulls = |dataset: Dataset| async move {
dataset
.count_rows(Some(format!("{COLUMN} IS NULL")))
.await
.unwrap()
};
let rows: Vec<pb::Vector> = (250..400).map(|i| row(i, author(i))).collect();
let written = crate::service::merge_vectors(unhealed, &rows)
.await
.unwrap();
assert!(written.schema().field(COLUMN).is_some());
assert!(nulls(written).await >= 100, "the race is reproduced");
let written = crate::service::write_vectors(healed, &rows).await.unwrap();
assert_eq!(nulls(written.clone()).await, 0);
let filter = FILTERS[1].1;
let latest = written.version().version;
let v = vector_of(5);
assert_same(
&fixture
.query(&fixture.server, latest, filter, 400, &v)
.await,
&fixture.flat(latest, filter, 400, &v).await,
"bob after the race",
);
assert_eq!(fixture.flat(latest, filter, 400, &v).await.len(), 4);
}
/// A write names no version: one at a version from before a key's column
/// add would commit rows without the column.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_write_at_an_older_version_is_refused() {
let fixture = Fixture::new().await;
fixture
.put((0..10).map(|i| row(i, author(i))).collect())
.await;
let before = fixture.dataset(0).await.version().version;
fixture.index_author().await;
let mut table = fixture.table.clone();
table.version = before;
let refused = fixture
.server
.put_vectors(Request::new(pb::PutVectorsRequest {
table: Some(table),
vectors: (10..20).map(|i| row(i, author(i))).collect(),
}))
.await
.unwrap_err();
assert_eq!(refused.code(), tonic::Code::InvalidArgument);
}
/// Two writes updating the same keys raced the column add, and the first
/// one's fill commits last: each write's rows get the values of its own
/// metadata, not the ones derived before it or from the other write.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_write_that_raced_the_column_add_derives_its_updated_rows() {
let fixture = Fixture::new().await;
fixture
.put((0..300).map(|i| row(i, author(i))).collect())
.await;
let first = fixture.dataset(0).await;
let second = fixture.dataset(0).await;
let written: Schema = first.schema().into();
fixture.index_author().await;
let rows = |name: &str| -> Vec<pb::Vector> {
(250..300)
.map(|i| row(i, Some(serde_json::json!(name))))
.collect()
};
let keys: Vec<String> = (250..300).map(|i| format!("k{i}")).collect();
let first = crate::service::merge_vectors(first, &rows("alice"))
.await
.unwrap();
let second = crate::service::merge_vectors(second, &rows("bob"))
.await
.unwrap();
crate::service::heal_columns(second, &written, &keys)
.await
.unwrap();
crate::service::heal_columns(first, &written, &keys)
.await
.unwrap();
let latest = fixture.dataset(0).await;
let count = |filter: String| {
let latest = latest.clone();
async move { latest.count_rows(Some(filter)).await.unwrap() }
};
assert_eq!(count(format!("{COLUMN} IS NULL")).await, 0);
for (name, filter) in [("alice", FILTERS[0].1), ("bob", FILTERS[1].1)] {
assert_eq!(
count(format!("array_has({COLUMN}, '{name}')")).await,
count(filter.to_string()).await,
"{name}"
);
}
let mut got = fixture
.server
.get_vectors(Request::new(pb::GetVectorsRequest {
table: Some(fixture.table.clone()),
keys: keys.clone(),
return_data: true,
return_metadata: true,
}))
.await
.unwrap()
.into_inner()
.vectors;
got.sort_by_key(|v| v.key[1..].parse::<usize>().unwrap());
assert_eq!(got, rows("bob"));
}
/// Operators ask through the engine; the table records the request and,
/// once the worker has done its part, the key's state, coverage and size.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn keys_are_requested_and_listed_through_the_engine() {
let fixture = Fixture::new().await;
fixture
.put((0..600).map(|i| row(i, author(i))).collect())
.await;
let update = |key: &str, remove: bool| {
fixture
.server
.update_metadata_key(Request::new(pb::UpdateMetadataKeyRequest {
table: Some(fixture.table.clone()),
key: key.to_string(),
remove,
}))
};
let listed = update("author", false).await.unwrap().into_inner();
assert_eq!(listed.keys.len(), 1);
assert_eq!(listed.keys[0].state, "requested");
assert_eq!(listed.keys[0].rows, 600);
// A retry of a committed request answers as the first one did.
let again = update("author", false).await.unwrap().into_inner();
assert_eq!(again.keys.len(), 1);
assert_eq!(again.keys[0].state, "requested");
let mut dataset = fixture.dataset(0).await;
let key = metadata_index::add_column(&mut dataset, "author")
.await
.unwrap();
metadata_index::finish_after(&mut dataset, &key, 1_000_000, std::time::Duration::ZERO)
.await
.unwrap();
let listed = fixture
.server
.metadata_keys(Request::new(pb::MetadataKeysRequest {
table: Some(fixture.table.clone()),
}))
.await
.unwrap()
.into_inner();
assert_eq!((listed.rows, listed.vector_index.as_str()), (600, ""));
let author = &listed.keys[0];
assert_eq!(
(
author.key.as_str(),
author.state.as_str(),
author.column.as_str()
),
("author", "ready", "_mk_0")
);
assert_eq!(
(author.indexed_rows, author.rows, author.segments),
(600, 600, 1)
);
assert!(author.index_bytes > 0);
// Off at once: the next query reads the JSON again.
let listed = update("author", true).await.unwrap().into_inner();
assert_eq!(listed.keys[0].state, "off");
let dataset = fixture.dataset(0).await;
assert_eq!(metadata_index::keys_of(&dataset)[0].state, Some(State::Off));
// Removing a key that is not indexed needs nothing.
let nobody = update("nobody", true).await.unwrap().into_inner();
assert_eq!(nobody.keys.len(), 1);
assert_eq!(
update("author", false).await.unwrap_err().code(),
tonic::Code::FailedPrecondition,
"being removed"
);
}
/// DeleteIndex purges the table's directory and an index created again
/// under the same name reuses it: the same running engine serves nothing of
/// the old table, neither rows, nor its indexed key, nor its filter stats.
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn a_dropped_and_recreated_index_serves_nothing_old() {
let fixture = Fixture::new().await;
fixture
.put((0..600).map(|i| row(i, author(i))).collect())
.await;
let mut dataset = fixture.dataset(0).await;
weed_lance_worker::vector_index::build(&mut dataset, "vector", "vector_idx", 4, false)
.await
.unwrap();
fixture.index_author().await;
let bob = FILTERS[1].1;
let old = fixture
.query(&fixture.server, 0, bob, 50, &vector_of(10))
.await;
assert_eq!(old.len(), 6);
let server = &fixture.server;
let stats = || {
server.filter_stats(Request::new(pb::FilterStatsRequest {
table: Some(fixture.table.clone()),
}))
};
assert_eq!(stats().await.unwrap().into_inner().keys[0].queries, 1);
// What the catalog's DeleteTable does, then CreateIndex again.
let (store, path) = lance::io::ObjectStore::from_uri(&fixture.table.location)
.await
.unwrap();
store.remove_dir_all(path).await.unwrap();
fixture
.server
.create_index(Request::new(pb::CreateIndexRequest {
table: Some(fixture.table.clone()),
dimension: DIM as u32,
distance_metric: pb::DistanceMetric::L2 as i32,
..Default::default()
}))
.await
.unwrap();
let keys = fixture
.server
.metadata_keys(Request::new(pb::MetadataKeysRequest {
table: Some(fixture.table.clone()),
}))
.await
.unwrap()
.into_inner();
assert!(keys.keys.is_empty());
assert!(
stats().await.unwrap().into_inner().keys.is_empty(),
"the old table's filter stats"
);
fixture
.put((1000..1100).map(|i| row(i, author(i))).collect())
.await;
let new = |hits: &[(String, f32)]| {
hits.iter().all(|(k, _)| {
k[1..]
.parse::<usize>()
.is_ok_and(|i| (1000..1100).contains(&i))
})
};
let unfiltered = fixture
.query(&fixture.server, 0, "", 200, &vector_of(10))
.await;
assert_eq!(unfiltered.len(), 100);
assert!(new(&unfiltered), "{unfiltered:?}");
let bob_now = fixture
.query(&fixture.server, 0, bob, 50, &vector_of(10))
.await;
assert_eq!(bob_now.len(), 1);
assert!(new(&bob_now), "{bob_now:?}");
let author = stats().await.unwrap().into_inner().keys;
assert_eq!((author.len(), author[0].queries), (1, 1));
}
-8
View File
@@ -1,12 +1,5 @@
//! The VectorService gRPC server the S3 gateway talks to.
// PutVectors awaits two Lance merge_insert futures; proving the handler
// future Send takes deeper trait recursion than the default.
#![recursion_limit = "256"]
pub mod filter_stats;
#[cfg(test)]
mod indexed_keys_tests;
pub mod metrics;
pub mod observed;
pub mod read_cache;
@@ -22,7 +15,6 @@ pub mod master_pb {
tonic::include_proto!("master_pb");
}
pub mod master_client;
pub mod memory;
pub mod security {
pub use weed_lance_worker::security::*;
}
+41 -16
View File
@@ -5,7 +5,6 @@ use clap::Parser;
use tokio_stream::wrappers::TcpListenerStream;
use tonic::transport::Server;
use weed_lance_worker::cluster::Cluster;
use weed_vector_server::memory::CacheSizes;
use weed_vector_server::pb::vector::vector_service_server::VectorServiceServer;
use weed_vector_server::read_cache::ReadCache;
use weed_vector_server::security::Security;
@@ -39,11 +38,25 @@ struct Args {
default_value = ""
)]
filer_group: String,
/// Memory for caching reads of write-once table files, in MiB; 0 disables.
#[arg(long, env = "WEED_VECTOR_READ_CACHE_MB", default_value_t = 512)]
read_cache_mb: u64,
/// Memory for indexes loaded by queries, kept for the next query, in MiB.
#[arg(long, env = "WEED_VECTOR_INDEX_CACHE_MB", default_value_t = 1024)]
index_cache_mb: usize,
/// Memory for table metadata (manifests, file footers) kept across
/// queries, in MiB.
#[arg(long, env = "WEED_VECTOR_METADATA_CACHE_MB", default_value_t = 256)]
metadata_cache_mb: usize,
/// Partitions each query probes in a table's vector index. Default: a
/// tenth of the index's partitions, at least 8; more under a filter.
#[arg(long, env = "WEED_VECTOR_NPROBES")]
nprobes: Option<std::num::NonZeroUsize>,
/// The cluster's security.toml: [grpc.vector] for this server,
/// [grpc.client] for the masters and filers, https.client for volume
/// servers under HTTPS, jwt.signing.read.key for signed volume reads,
/// s3.sse.kek or s3.sse.key for SSE-S3 buckets. By default the file weed
/// processes find in ., ~/.seaweedfs and /etc/seaweedfs.
/// processes find in -config_dir, ., ~/.seaweedfs and /etc/seaweedfs.
#[arg(long, env = "WEED_VECTOR_SECURITY_TOML")]
security_toml: Option<PathBuf>,
#[arg(
@@ -60,6 +73,11 @@ struct Args {
default_value = "127.0.0.1"
)]
metrics_ip: String,
/// The directory weed's -config_dir names, searched for security.toml
/// first.
#[arg(long, alias = "config_dir", env = "WEED_VECTOR_CONFIG_DIR")]
config_dir: Option<PathBuf>,
}
// weed tools take Go-style single-dash long flags; normalize_args converts
@@ -130,7 +148,7 @@ async fn main() -> Result<()> {
tracing_subscriber::fmt::init();
let args = Args::parse_from(normalize_args(std::env::args().collect()));
weed_lance_worker::tls::install_default_crypto_provider();
let security = Security::load(args.security_toml.as_deref())?;
let security = Security::load(args.security_toml.as_deref(), args.config_dir.as_deref())?;
if let Some(path) = security.path() {
tracing::info!("security settings from {}", path.display());
}
@@ -148,18 +166,15 @@ async fn main() -> Result<()> {
let (health, health_service) = tonic_health::server::health_reporter();
let metrics = Metrics::new()?.with_health(health);
metrics.set_connected(false).await;
let sizes = CacheSizes::detect();
tracing::info!(
"caching {} MiB of file reads, {} MiB of indexes, {} MiB of table metadata",
sizes.read >> 20,
sizes.index >> 20,
sizes.metadata >> 20
);
let cache = ReadCache::new(sizes.read).with_metrics(metrics.clone());
let service = VectorServer::new()
.with_lance_caches(sizes.index as usize, sizes.metadata as usize)
.with_storage(reads)
.with_read_cache(cache.clone());
let cache = (args.read_cache_mb > 0)
.then(|| ReadCache::new(args.read_cache_mb << 20).with_metrics(metrics.clone()));
let mut service = VectorServer::new()
.with_nprobes(args.nprobes.map(std::num::NonZeroUsize::get))
.with_lance_caches(args.index_cache_mb << 20, args.metadata_cache_mb << 20)
.with_storage(reads);
if let Some(cache) = &cache {
service = service.with_read_cache(cache.clone());
}
if args.metrics_port > 0 {
let ip = args
.metrics_ip
@@ -170,7 +185,7 @@ async fn main() -> Result<()> {
tokio::net::TcpListener::bind(std::net::SocketAddr::new(ip, args.metrics_port)).await?;
let metrics = metrics.clone();
tokio::spawn(async move {
if let Err(error) = metrics::serve_listener(metrics, listener, Some(cache)).await {
if let Err(error) = metrics::serve_listener(metrics, listener, cache).await {
tracing::error!(%error, "vector metrics server stopped");
}
});
@@ -242,6 +257,16 @@ mod tests {
);
}
#[test]
fn nprobes_must_be_positive() {
let parse = |nprobes: &str| {
Args::try_parse_from(["weed-vector", "--masters", "m:9333", "--nprobes", nprobes])
};
assert!(parse("0").is_err());
let args = parse("12").unwrap();
assert_eq!(args.nprobes.map(std::num::NonZeroUsize::get), Some(12));
}
#[test]
fn the_catalog_flags_are_gone() {
let parse = |extra: &[&str]| {
@@ -24,7 +24,6 @@ fn registration(client_addr: &str, filer_group: &str, metrics_port: u16) -> Keep
rack: String::new(),
leave_lock_ring: false,
metrics_port: metrics_port.into(),
lance_port: 0,
}
}
-155
View File
@@ -1,155 +0,0 @@
//! How much the engine caches: a share of the memory this process may use,
//! so a small pod is not overcommitted and a large host is not left idle.
use std::path::{Path, PathBuf};
/// The read, index and metadata caches, in bytes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CacheSizes {
pub read: u64,
pub index: u64,
pub metadata: u64,
}
/// Where no limit can be read, the sizes the flags used to default to.
const UNKNOWN_LIMIT_BUDGET: u64 = 1792 << 20;
impl CacheSizes {
/// A quarter of the memory limit, split 2:4:1 between file reads, loaded
/// indexes and table metadata.
pub fn for_limit(limit: Option<u64>) -> Self {
let budget = limit.map_or(UNKNOWN_LIMIT_BUDGET, |limit| limit / 4);
let seventh = budget / 7;
Self {
read: seventh * 2,
index: seventh * 4,
metadata: seventh,
}
}
pub fn detect() -> Self {
Self::for_limit(memory_limit())
}
}
/// The smallest of the machine's memory and the limits of this process's
/// memory cgroup and its ancestors: a systemd service is limited in its own
/// group, a container usually at the root it sees.
fn memory_limit() -> Option<u64> {
let read = |path: &Path| std::fs::read_to_string(path).ok();
let total = read(Path::new("/proc/meminfo")).and_then(|info| mem_total(&info));
let groups = read(Path::new("/proc/self/cgroup"))
.map(|groups| limit_files(&groups))
.unwrap_or_default();
groups
.iter()
.filter_map(|file| read(file).and_then(|limit| cgroup_limit(&limit)))
.chain(total)
.min()
}
/// The limit files of the memory cgroup `/proc/self/cgroup` names and of its
/// ancestors: v1's memory controller where it has one, else v2's unified group.
fn limit_files(self_cgroup: &str) -> Vec<PathBuf> {
let entries: Vec<(&str, &str)> = self_cgroup
.lines()
.filter_map(|line| {
let mut fields = line.splitn(3, ':');
fields.next()?;
Some((fields.next()?, fields.next()?))
})
.collect();
let v1 = entries
.iter()
.find(|(controllers, _)| controllers.split(',').any(|c| c == "memory"))
.map(|(_, group)| ("/sys/fs/cgroup/memory", *group, "memory.limit_in_bytes"));
let v2 = entries
.iter()
.find(|(controllers, _)| controllers.is_empty())
.map(|(_, group)| ("/sys/fs/cgroup", *group, "memory.max"));
let Some((root, group, file)) = v1.or(v2) else {
return Vec::new();
};
Path::new(group)
.ancestors()
.map(|dir| {
Path::new(root)
.join(dir.strip_prefix("/").unwrap_or(dir))
.join(file)
})
.collect()
}
fn mem_total(meminfo: &str) -> Option<u64> {
let line = meminfo.lines().find(|line| line.starts_with("MemTotal:"))?;
let kib: u64 = line.split_whitespace().nth(1)?.parse().ok()?;
Some(kib << 10)
}
/// cgroup v2 writes "max" for no limit; v1 writes a number near u64::MAX.
fn cgroup_limit(limit: &str) -> Option<u64> {
let bytes: u64 = limit.trim().parse().ok()?;
(bytes < 1 << 60).then_some(bytes)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_quarter_of_the_limit_split_two_four_one() {
let sizes = CacheSizes::for_limit(Some(28 << 30));
assert_eq!(sizes.read, 2 << 30);
assert_eq!(sizes.index, 4 << 30);
assert_eq!(sizes.metadata, 1 << 30);
}
#[test]
fn no_limit_keeps_the_former_defaults() {
let sizes = CacheSizes::for_limit(None);
assert_eq!(
(sizes.read, sizes.index, sizes.metadata),
(512 << 20, 1024 << 20, 256 << 20)
);
}
#[test]
fn looks_up_the_process_group_and_its_ancestors() {
let paths = |groups: &str| -> Vec<String> {
limit_files(groups)
.iter()
.map(|p| p.display().to_string().replace('\\', "/"))
.collect()
};
assert_eq!(
paths("0::/system.slice/weed-vector.service\n"),
[
"/sys/fs/cgroup/system.slice/weed-vector.service/memory.max",
"/sys/fs/cgroup/system.slice/memory.max",
"/sys/fs/cgroup/memory.max",
]
);
// A container's namespace shows its own group as the root.
assert_eq!(paths("0::/\n"), ["/sys/fs/cgroup/memory.max"]);
// On a hybrid host the memory controller is v1's.
assert_eq!(
paths("12:cpu,cpuacct:/a\n4:memory:/user.slice\n0::/user.slice\n"),
[
"/sys/fs/cgroup/memory/user.slice/memory.limit_in_bytes",
"/sys/fs/cgroup/memory/memory.limit_in_bytes",
]
);
assert!(paths("").is_empty());
}
#[test]
fn reads_the_limits_the_kernel_writes() {
assert_eq!(
mem_total("MemTotal: 16384000 kB\nMemFree: 1 kB\n"),
Some(16_384_000 << 10)
);
assert_eq!(cgroup_limit("4294967296\n"), Some(4 << 30));
assert_eq!(cgroup_limit("max\n"), None);
assert_eq!(cgroup_limit("9223372036854771712\n"), None);
}
}
@@ -10,10 +10,6 @@ use tonic_health::{ServingStatus, server::HealthReporter};
use crate::read_cache::ReadCache;
/// The gRPC health service an engine reports serving when its writes derive
/// the indexed metadata key columns.
pub const METADATA_COLUMNS_CAPABILITY: &str = "weed.vector.capability.metadata_columns";
#[derive(Clone)]
pub struct Metrics {
pub registry: Registry,
@@ -124,11 +120,6 @@ impl Metrics {
health
.set_service_status("vector_pb.VectorService", status)
.await;
// A capability, not readiness: the admin refuses to index a
// metadata key while an engine without it could write the table.
health
.set_service_status(METADATA_COLUMNS_CAPABILITY, ServingStatus::Serving)
.await;
}
}
@@ -78,33 +78,6 @@ impl VectorService for ObservedService {
}
result
}
async fn metadata_keys(
&self,
request: Request<pb::MetadataKeysRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
let mut in_flight = self.metrics.start("MetadataKeys");
let result = self.inner.metadata_keys(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn update_metadata_key(
&self,
request: Request<pb::UpdateMetadataKeyRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
let mut in_flight = self.metrics.start("UpdateMetadataKey");
let result = self.inner.update_metadata_key(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
async fn filter_stats(
&self,
request: Request<pb::FilterStatsRequest>,
) -> Result<Response<pb::FilterStatsResponse>, Status> {
let mut in_flight = self.metrics.start("FilterStats");
let result = self.inner.filter_stats(request).await;
in_flight.complete(result.as_ref().err().map(|e| e.code()));
result
}
}
#[cfg(test)]
+54 -296
View File
@@ -19,9 +19,7 @@ use weed_lance_worker::catalog::TableDescription;
use weed_lance_worker::dataset;
use weed_lance_worker::direct_read::{DirectReads, Wrappers};
use weed_lance_worker::jobs::vector_index::is_vector_table;
use weed_lance_worker::metadata_index;
use weed_vector_core::index;
use weed_vector_core::indexed_filter;
use weed_vector_core::maintenance::SharedLeases;
use weed_vector_core::query::{self, Query};
use weed_vector_core::table::VectorTable;
@@ -169,13 +167,14 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
};
let vectors_array =
FixedSizeListArray::try_new(item_field.clone(), dimension as i32, values, None)?;
let json: Vec<Option<serde_json::Value>> = vectors
let metas = vectors
.iter()
.map(|v| v.metadata.as_ref().map(struct_to_json))
.collect();
let metas = json
.iter()
.map(|m| m.as_ref().map(serde_json::to_string).transpose())
.map(|v| {
v.metadata
.as_ref()
.map(|m| serde_json::to_string(&struct_to_json(m)))
.transpose()
})
.collect::<Result<Vec<_>, _>>()?;
// The stored column is lance's jsonb (LargeBinary) once the field carries
// the arrow.json extension; encode the strings, else keep the Utf8 batch.
@@ -188,188 +187,11 @@ fn batch_of(vectors: &[pb::Vector], dimension: usize, schema: Arc<Schema>) -> Re
}
_ => Arc::new(StringArray::from(metas)),
};
let (keys, vectors_array): (ArrayRef, ArrayRef) = (Arc::new(keys), Arc::new(vectors_array));
// An indexed metadata key's column is derived from the row's metadata,
// whatever the key's state.
let columns = schema
.fields()
.iter()
.map(|field| match field.name().as_str() {
KEY_COLUMN => Ok(keys.clone()),
VECTOR_COLUMN => Ok(vectors_array.clone()),
METADATA_COLUMN => Ok(metadata_array.clone()),
name => match metadata_index::indexed_key(field) {
Some(indexed) => Ok(metadata_index::column_from_json(
json.iter().map(Option::as_ref),
&indexed.key,
)),
None => bail!("the table has a column {name} that PutVectors cannot fill"),
},
})
.collect::<Result<Vec<_>>>()?;
RecordBatch::try_new(schema, columns).map_err(Into::into)
}
/// Upserts `vectors` by key into `dataset`, the version the request opened,
/// then fills the indexed-key columns a concurrent column add left empty.
pub(crate) async fn write_vectors(
dataset: Dataset,
vectors: &[pb::Vector],
) -> Result<Dataset, Status> {
let written = Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema()));
let dataset = merge_vectors(dataset, vectors).await?;
let keys: Vec<String> = vectors.iter().map(|v| v.key.clone()).collect();
heal_columns(dataset, &written, &keys)
.await
.map_err(internal)
}
/// The upsert itself, in the schema of the version `dataset` is at.
pub(crate) async fn merge_vectors(
dataset: Dataset,
vectors: &[pb::Vector],
) -> Result<Dataset, Status> {
let dimension = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN))
.map_err(invalid)?
.dimension;
let batch = batch_of(
vectors,
dimension,
Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema())),
RecordBatch::try_new(
schema,
vec![Arc::new(keys), Arc::new(vectors_array), metadata_array],
)
.map_err(invalid)?;
// Upsert by key in one merge commit: no window where the old rows are
// already deleted, and a losing writer fails the request instead of
// leaving duplicate keys.
let mut builder = MergeInsertBuilder::try_new(Arc::new(dataset), vec![KEY_COLUMN.to_string()])
.map_err(internal)?;
builder.when_matched(WhenMatched::UpdateAll);
builder.when_not_matched(WhenNotMatched::InsertAll);
let (dataset, _stats) = builder
.try_build()
.map_err(internal)?
.execute_batches(vec![batch])
.await
.map_err(internal)?;
Ok(Arc::unwrap_or_clone(dataset))
}
/// Attempts [`heal_columns`] makes against writes committing meanwhile.
const HEAL_ATTEMPTS: usize = 10;
/// Lance rebases a write onto a column add committed after the write opened
/// its version: the rows it inserted hold NULL in the new column and the
/// rows it updated keep the value derived from their old metadata. Derive
/// such columns again for the rows of `keys` from their stored metadata.
pub(crate) async fn heal_columns(
mut dataset: Dataset,
written: &Schema,
keys: &[String],
) -> Result<Dataset> {
for _ in 0..HEAL_ATTEMPTS {
let schema: Schema = dataset.schema().into();
let missing: Vec<metadata_index::IndexedKey> = metadata_index::indexed_keys(&schema)
.into_iter()
.filter(|k| written.field_with_name(&k.column).is_err())
.collect();
if missing.is_empty() || keys.is_empty() {
return Ok(dataset);
}
let mut scanner = dataset.scan();
scanner
.filter(&key_list(keys))?
.project(&[KEY_COLUMN, METADATA_COLUMN])?;
let rows: Vec<RecordBatch> = scanner.try_into_stream().await?.try_collect().await?;
let mut fields = vec![schema.field_with_name(KEY_COLUMN)?.clone()];
for k in &missing {
fields.push(schema.field_with_name(&k.column)?.clone());
}
let patch_schema = Arc::new(Schema::new(fields));
let mut patches = Vec::new();
for batch in rows.iter().filter(|b| b.num_rows() > 0) {
let (Some(keys), Some(metadata)) = (
batch.column_by_name(KEY_COLUMN),
batch.column_by_name(METADATA_COLUMN),
) else {
bail!("the scan did not return keys and metadata");
};
let mut columns = vec![keys.clone()];
for k in &missing {
columns.push(metadata_index::column_from_metadata(
metadata.as_ref(),
&k.key,
)?);
}
patches.push(RecordBatch::try_new(patch_schema.clone(), columns)?);
}
if patches.is_empty() {
return Ok(dataset);
}
// Lance's own retry would join these values onto rows a later write
// replaced; derive them again from the version that write left.
let mut builder =
MergeInsertBuilder::try_new(Arc::new(dataset.clone()), vec![KEY_COLUMN.to_string()])?;
builder
.when_matched(WhenMatched::UpdateAll)
.when_not_matched(WhenNotMatched::DoNothing)
.conflict_retries(0);
match builder.try_build()?.execute_batches(patches).await {
Ok((healed, _stats)) => {
tracing::info!(
rows = rows.iter().map(|b| b.num_rows()).sum::<usize>(),
"derived indexed metadata key columns a concurrent column add left stale"
);
return Ok(Arc::unwrap_or_clone(healed));
}
Err(lance::Error::TooMuchWriteContention { .. }) => dataset.checkout_latest().await?,
Err(e) => return Err(e.into()),
}
}
bail!("writes kept replacing the rows while their indexed key columns were derived")
}
/// The indexed metadata keys `dataset` records, requested ones first.
async fn metadata_keys(dataset: &Dataset) -> Result<pb::MetadataKeysResponse> {
let rows: u64 = dataset
.fragments()
.iter()
.map(|f| f.num_rows().unwrap_or(0) as u64)
.sum();
let mut keys: Vec<pb::MetadataKey> = metadata_index::requests(dataset)
.into_iter()
.map(|key| pb::MetadataKey {
key,
state: "requested".to_string(),
rows,
..Default::default()
})
.collect();
for key in metadata_index::keys_of(dataset) {
let segments = metadata_index::segments(dataset, &key.column).await?;
keys.push(pb::MetadataKey {
state: key.state.map_or("unknown", |s| s.as_str()).to_string(),
indexed_rows: segments.iter().map(|s| s.rows).sum(),
index_bytes: segments.iter().map(|s| s.bytes).sum(),
segments: segments.len() as u32,
rows,
key: key.key,
column: key.column,
});
}
let vector_index = match index::index_names(dataset, VECTOR_COLUMN).await?.first() {
Some(name) => {
weed_lance_worker::vector_index::index_settings(dataset, name)
.await?
.index_type
}
None => String::new(),
};
Ok(pb::MetadataKeysResponse {
keys,
version: dataset.version().version,
rows,
vector_index,
})
.map_err(Into::into)
}
fn struct_to_json(s: &Struct) -> serde_json::Value {
@@ -408,7 +230,7 @@ fn json_to_value(v: serde_json::Value) -> Value {
Value { kind: Some(kind) }
}
pub(crate) fn json_to_struct(map: serde_json::Map<String, serde_json::Value>) -> Struct {
fn json_to_struct(map: serde_json::Map<String, serde_json::Value>) -> Struct {
Struct {
fields: map
.into_iter()
@@ -705,8 +527,7 @@ pub struct VectorServer {
pub(crate) handles: moka::sync::Cache<(String, bool), (u64, Dataset)>,
lance_cache_bytes: (usize, usize),
leases: SharedLeases,
exact_match_limit: Option<usize>,
filter_stats: crate::filter_stats::FilterStats,
nprobes: Option<usize>,
/// URI schemes a table's location may have.
schemes: &'static [&'static str],
}
@@ -729,8 +550,7 @@ impl VectorServer {
lance_cache_bytes: (DEFAULT_INDEX_CACHE_BYTES, DEFAULT_METADATA_CACHE_BYTES),
handles: moka::sync::Cache::new(MAX_HANDLES),
leases: SharedLeases::default(),
exact_match_limit: None,
filter_stats: Default::default(),
nprobes: None,
schemes: &["s3"],
}
}
@@ -742,11 +562,9 @@ impl VectorServer {
self
}
/// Matches of a filter's indexed metadata keys scored exactly instead of
/// searched through the vector index, at most; None keeps the default.
#[cfg(test)]
pub(crate) fn with_exact_match_limit(mut self, limit: Option<usize>) -> Self {
self.exact_match_limit = limit;
/// Partitions every query probes, instead of the index's own default.
pub fn with_nprobes(mut self, nprobes: Option<usize>) -> Self {
self.nprobes = nprobes;
self
}
@@ -922,11 +740,7 @@ impl VectorService for VectorServer {
)
.await;
let dataset = match dataset {
Ok(dataset) => {
self.filter_stats
.forget(&table.id.join("/"), table_id(&dataset));
dataset
}
Ok(dataset) => dataset,
Err(error) => match self.open(&table).await {
Ok(existing)
if matches_index_schema(
@@ -977,7 +791,6 @@ impl VectorService for VectorServer {
store.remove_dir_all(path).await.map_err(internal)?;
}
}
self.filter_stats.forget(&table.id.join("/"), "");
Ok(Response::new(pb::DropIndexResponse {}))
}
@@ -989,37 +802,35 @@ impl VectorService for VectorServer {
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
if table.version != 0 {
return Err(Status::invalid_argument("a write takes no table version"));
let dataset = self.open(&table).await?;
if req.vectors.is_empty() {
return Ok(Response::new(pb::PutVectorsResponse {
version: dataset.version().version,
}));
}
// A write commits within its deadline of opening the table or not
// at all: a key's column add waits longer than that before the key
// is ready, so a write that opened before the add has committed,
// and been derived again, before any query uses the key.
let merged = tokio::time::timeout(metadata_index::WRITE_DEADLINE, async {
let dataset = self.open(&table).await?;
if req.vectors.is_empty() {
return Ok::<_, Status>((dataset, None));
}
let written = Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema()));
Ok((merge_vectors(dataset, &req.vectors).await?, Some(written)))
})
.await
.map_err(|_| {
Status::deadline_exceeded(format!(
"PutVectors took longer than {:?} to commit",
metadata_index::WRITE_DEADLINE
))
})??;
let dataset = match merged {
(dataset, Some(written)) => {
let keys: Vec<String> = req.vectors.iter().map(|v| v.key.clone()).collect();
heal_columns(dataset, &written, &keys)
.await
.map_err(internal)?
}
(dataset, None) => dataset,
};
let dimension = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN))
.map_err(invalid)?
.dimension;
let batch = batch_of(
&req.vectors,
dimension,
Arc::new(Into::<arrow_schema::Schema>::into(dataset.schema())),
)
.map_err(invalid)?;
// Upsert by key in one merge commit: no window where the old rows are
// already deleted, and a losing writer fails the request instead of
// leaving duplicate keys.
let mut builder =
MergeInsertBuilder::try_new(Arc::new(dataset), vec![KEY_COLUMN.to_string()])
.map_err(internal)?;
builder.when_matched(WhenMatched::UpdateAll);
builder.when_not_matched(WhenNotMatched::InsertAll);
let (dataset, _stats) = builder
.try_build()
.map_err(internal)?
.execute_batches(vec![batch])
.await
.map_err(internal)?;
Ok(Response::new(pb::PutVectorsResponse {
version: dataset.version().version,
}))
@@ -1097,9 +908,14 @@ impl VectorService for VectorServer {
0 => DEFAULT_PAGE,
n => n.min(MAX_PAGE),
};
// A purge keeps only the latest version, so lease the one this page reads.
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
if segments > 1 {
// Data and metadata come from a second read of this version, so
// lease it as get_vectors does.
let _lease = if columns.len() > 1 {
self.leases.try_pin(&dataset).await.map_err(internal)?
} else {
None
};
let (vectors, next) = list_segment(
&dataset,
&columns,
@@ -1137,7 +953,6 @@ impl VectorService for VectorServer {
&self,
request: Request<pb::QueryVectorsRequest>,
) -> Result<Response<pb::QueryVectorsResponse>, Status> {
let started = std::time::Instant::now();
let req = request.into_inner();
let table = req
.table
@@ -1147,11 +962,6 @@ impl VectorService for VectorServer {
// while this query runs against it.
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
let resolved = VectorTable::resolve(&dataset, None, Some(KEY_COLUMN)).map_err(invalid)?;
let filter_keys = if req.filter.is_empty() {
Default::default()
} else {
indexed_filter::filter_keys(&dataset, &req.filter).unwrap_or_default()
};
if req.query_vector.len() != resolved.dimension {
return Err(Status::invalid_argument(format!(
"query vector carries {} floats, the index dimension is {}",
@@ -1173,10 +983,9 @@ impl VectorService for VectorServer {
},
postfilter: req.postfilter,
distance,
nprobes: None,
nprobes: self.nprobes,
index_segments: None,
fragments: None,
exact_match_limit: self.exact_match_limit,
};
let hits = query::ann(&dataset, &resolved, &query)
.await
@@ -1252,59 +1061,8 @@ impl VectorService for VectorServer {
data: data_map.remove(&hit.key).unwrap_or_default(),
});
}
let index = table.id.join("/");
self.filter_stats
.record(&index, table_id(&dataset), &filter_keys, started.elapsed());
Ok(Response::new(pb::QueryVectorsResponse { vectors }))
}
async fn metadata_keys(
&self,
request: Request<pb::MetadataKeysRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
let table = request
.into_inner()
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let dataset = self.open_to_read(&table).await?;
let _lease = self.leases.try_pin(&dataset).await.map_err(internal)?;
Ok(Response::new(
metadata_keys(&dataset).await.map_err(internal)?,
))
}
async fn update_metadata_key(
&self,
request: Request<pb::UpdateMetadataKeyRequest>,
) -> Result<Response<pb::MetadataKeysResponse>, Status> {
let req = request.into_inner();
let table = req
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
let mut dataset = self.open(&table).await?;
let updated = if req.remove {
metadata_index::request_removal(&mut dataset, &req.key).await
} else {
metadata_index::request(&mut dataset, &req.key).await
};
updated.map_err(|e| Status::failed_precondition(format!("{e:#}")))?;
Ok(Response::new(
metadata_keys(&dataset).await.map_err(internal)?,
))
}
async fn filter_stats(
&self,
request: Request<pb::FilterStatsRequest>,
) -> Result<Response<pb::FilterStatsResponse>, Status> {
let table = request
.into_inner()
.table
.ok_or_else(|| Status::invalid_argument("missing table"))?;
Ok(Response::new(
self.filter_stats.snapshot(&table.id.join("/")),
))
}
}
#[cfg(test)]
-3
View File
@@ -234,8 +234,6 @@ message KeepConnectedRequest {
// it is not enabled. Advertised so the admin server can scrape it without
// exposing metrics on the client-facing service port.
uint32 metrics_port = 9;
// Port an S3 gateway serves its Lance Namespace on, or 0 when it serves none.
uint32 lance_port = 10;
}
message VolumeLocation {
@@ -561,7 +559,6 @@ message ListClusterNodesResponse {
string address = 1;
string version = 2;
int64 created_at_ns = 4;
uint32 lance_port = 7;
string data_center = 5;
string rack = 6;
}
-2
View File
@@ -147,7 +147,6 @@ service VolumeServer {
message BatchDeleteRequest {
repeated string file_ids = 1;
bool skip_cookie_check = 2;
bool fsync = 3;
}
message BatchDeleteResponse {
@@ -482,7 +481,6 @@ message VolumeEcShardsCopyRequest {
bool copy_vif_file = 7;
uint32 disk_id = 8; // Target disk ID for storing EC shards
bool copy_ecsum_file = 9; // copy the bitrot checksum sidecar (.ecsum) when present; tolerant of a missing source (no-op), since this non-2PC path has no Prepare backstop
string disk_type = 11; // with disk_id 0, pick only among disks of this type; empty means any
}
message VolumeEcShardsCopyResponse {
}
-61
View File
@@ -306,8 +306,6 @@ pub struct VolumeServerConfig {
pub ui_enabled: bool,
pub jwt_signing_key: Vec<u8>,
pub jwt_signing_expires_seconds: i64,
pub jwt_previous_signing_key: Vec<u8>,
pub jwt_previous_read_signing_key: Vec<u8>,
pub jwt_read_signing_key: Vec<u8>,
pub jwt_read_signing_expires_seconds: i64,
pub https_cert_file: String,
@@ -1001,8 +999,6 @@ fn resolve_config_with_env(cli: Cli, env: EnvLookup<'_>) -> VolumeServerConfig {
ui_enabled: sec.jwt_signing_key.is_empty() || sec.access_ui,
jwt_signing_key: sec.jwt_signing_key,
jwt_signing_expires_seconds: sec.jwt_signing_expires,
jwt_previous_signing_key: sec.jwt_previous_signing_key,
jwt_previous_read_signing_key: sec.jwt_previous_read_signing_key,
jwt_read_signing_key: sec.jwt_read_signing_key,
jwt_read_signing_expires_seconds: sec.jwt_read_signing_expires,
https_cert_file: sec.https_cert_file,
@@ -1034,8 +1030,6 @@ fn default_volume_dir() -> String {
pub struct SecurityConfig {
pub jwt_signing_key: Vec<u8>,
pub jwt_signing_expires: i64,
pub jwt_previous_signing_key: Vec<u8>,
pub jwt_previous_read_signing_key: Vec<u8>,
pub jwt_read_signing_key: Vec<u8>,
pub jwt_read_signing_expires: i64,
pub https_cert_file: String,
@@ -1054,8 +1048,6 @@ pub struct SecurityConfig {
pub grpc_volume_allowed_common_names: Vec<String>,
pub tls_policy: TlsPolicy,
pub access_ui: bool,
/// The file was read; otherwise only defaults and WEED_ overrides are set.
pub file_read: bool,
/// IPs from [guard] white_list in security.toml
pub guard_white_list: Vec<String>,
}
@@ -1188,7 +1180,6 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
match section {
Section::JwtSigningRead => match key {
"key" => cfg.jwt_read_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_read_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_read_signing_expires = value.parse().unwrap_or(60)
}
@@ -1196,7 +1187,6 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
},
Section::JwtSigning => match key {
"key" => cfg.jwt_signing_key = value.as_bytes().to_vec(),
"previous_key" => cfg.jwt_previous_signing_key = value.as_bytes().to_vec(),
"expires_after_seconds" => {
cfg.jwt_signing_expires = value.parse().unwrap_or(10)
}
@@ -1272,7 +1262,6 @@ fn parse_security_config_with_env(path: &str, env: EnvLookup<'_>) -> SecurityCon
// prefix WEED_, uppercase, replace . with _).
// e.g. WEED_JWT_SIGNING_KEY overrides [jwt.signing] key
apply_env_overrides(&mut cfg, env);
cfg.file_read = true;
cfg
}
@@ -1311,12 +1300,6 @@ fn apply_env_overrides(cfg: &mut SecurityConfig, env: EnvLookup<'_>) {
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_EXPIRES_AFTER_SECONDS") {
cfg.jwt_signing_expires = v.parse().unwrap_or(cfg.jwt_signing_expires);
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_PREVIOUS_KEY") {
cfg.jwt_previous_signing_key = v.into_bytes();
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_READ_PREVIOUS_KEY") {
cfg.jwt_previous_read_signing_key = v.into_bytes();
}
if let Some(v) = env_string(env, "WEED_JWT_SIGNING_READ_KEY") {
cfg.jwt_read_signing_key = v.into_bytes();
}
@@ -2194,50 +2177,6 @@ cipher_suites = "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_previous_signing_keys_from_file_and_env() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(
tmp.path(),
r#"
[jwt.signing]
key = "write-new"
previous_key = "write-old"
[jwt.signing.read]
key = "read-new"
previous_key = "read-old"
"#,
)
.unwrap();
let path = tmp.path().to_str().unwrap();
let cfg = parse_security_config_with_env(path, &fake_env(&[]));
assert_eq!(cfg.jwt_previous_signing_key, b"write-old");
assert_eq!(cfg.jwt_previous_read_signing_key, b"read-old");
let env = fake_env(&[
("WEED_JWT_SIGNING_PREVIOUS_KEY", "env-write-old"),
("WEED_JWT_SIGNING_READ_PREVIOUS_KEY", "env-read-old"),
]);
let cfg = parse_security_config_with_env(path, &env);
assert_eq!(cfg.jwt_previous_signing_key, b"env-write-old");
assert_eq!(cfg.jwt_previous_read_signing_key, b"env-read-old");
}
#[test]
fn test_security_config_file_read() {
let tmp = tempfile::NamedTempFile::new().unwrap();
std::fs::write(tmp.path(), "[jwt.signing]\nkey = \"secret\"\n").unwrap();
let path = tmp.path().to_str().unwrap().to_string();
assert!(parse_security_config_with_env(&path, &fake_env(&[])).file_read);
drop(tmp);
let env = fake_env(&[("WEED_JWT_SIGNING_KEY", "env-secret")]);
let cfg = parse_security_config_with_env(&path, &env);
assert!(!cfg.file_read);
assert_eq!(cfg.jwt_signing_key, b"env-secret");
}
#[test]
fn test_env_override_takes_precedence_over_file() {
let tmp = tempfile::NamedTempFile::new().unwrap();
+2 -11
View File
@@ -340,7 +340,7 @@ async fn run(
store.set_volume_load_guard(volume_copies_in_flight.clone());
// Build shared state
let mut guard = Guard::new(
let guard = Guard::new(
&config.white_list,
SigningKey(config.jwt_signing_key.clone()),
config.jwt_signing_expires_seconds,
@@ -358,8 +358,6 @@ async fn run(
let security_file = config.security_file.clone();
let cli_white_list = config.white_list.clone();
guard.previous_signing_key = SigningKey(config.jwt_previous_signing_key.clone());
guard.previous_read_signing_key = SigningKey(config.jwt_previous_read_signing_key.clone());
let state = Arc::new(VolumeServerState {
store: RwLock::new(store),
@@ -418,7 +416,6 @@ async fn run(
.to_string_lossy()
.into_owned()
},
ec_lifecycle_locks: std::sync::Mutex::new(std::collections::HashMap::new()),
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
volume_copies_in_flight,
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
@@ -621,13 +618,9 @@ async fn run(
}
// 2. Reload security config (Go's Reload)
'security: {
{
info!("Reloading security config...");
let sec = config::parse_security_config(&state_reload.security_file);
if !sec.file_read {
warn!("SIGHUP: security config cannot be read, keeping the keys in effect");
break 'security;
}
let mut whitelist = state_reload.cli_white_list.clone();
whitelist.extend(sec.guard_white_list.iter().cloned());
let mut guard = state_reload.guard.write().unwrap();
@@ -637,8 +630,6 @@ async fn run(
sec.jwt_signing_expires,
SigningKey(sec.jwt_read_signing_key),
sec.jwt_read_signing_expires,
SigningKey(sec.jwt_previous_signing_key),
SigningKey(sec.jwt_previous_read_signing_key),
);
}
-14
View File
@@ -85,19 +85,6 @@ pub static VACUUMING_COMMIT_COUNTER: LazyLock<IntCounterVec> = LazyLock::new(||
.expect("metric can be created")
});
/// Live needles vacuum dropped because their data could not be read back
/// intact, with label `collection`.
pub static VACUUMING_DROPPED_NEEDLES_COUNTER: LazyLock<IntCounterVec> = LazyLock::new(|| {
IntCounterVec::new(
Opts::new(
"SeaweedFS_volumeServer_vacuuming_dropped_needles",
"Counter of live needles dropped by vacuum because their data could not be read back intact.",
),
&["collection"],
)
.expect("metric can be created")
});
/// Vacuuming duration histogram with label `type` (compact/commit).
pub static VACUUMING_HISTOGRAM: LazyLock<HistogramVec> = LazyLock::new(|| {
HistogramVec::new(
@@ -415,7 +402,6 @@ pub fn register_metrics() {
Box::new(VACUUMING_COMPACT_COUNTER.clone()),
Box::new(VACUUMING_COMMIT_COUNTER.clone()),
Box::new(VACUUMING_HISTOGRAM.clone()),
Box::new(VACUUMING_DROPPED_NEEDLES_COUNTER.clone()),
Box::new(VOLUME_GAUGE.clone()),
Box::new(READ_ONLY_VOLUME_GAUGE.clone()),
Box::new(MAX_VOLUMES.clone()),
+23 -207
View File
@@ -83,13 +83,7 @@ pub fn gen_jwt(
}
/// Decode and validate a JWT token.
/// A token whose signature does not match `signing_key` is checked against
/// each non-empty `previous_keys` entry, like Go's `security.DecodeJwt`.
pub fn decode_jwt(
signing_key: &SigningKey,
token: &str,
previous_keys: &[&SigningKey],
) -> Result<FileIdClaims, JwtError> {
pub fn decode_jwt(signing_key: &SigningKey, token: &str) -> Result<FileIdClaims, JwtError> {
if signing_key.is_empty() {
return Err(JwtError::NoSigningKey);
}
@@ -103,64 +97,13 @@ pub fn decode_jwt(
validation.validate_nbf = true;
validation.leeway = 0;
let mut result = decode::<FileIdClaims>(
let data = decode::<FileIdClaims>(
token,
&DecodingKey::from_secret(&signing_key.0),
&validation,
);
for previous in previous_keys {
let bad_signature = matches!(&result, Err(e)
if matches!(e.kind(), jsonwebtoken::errors::ErrorKind::InvalidSignature));
if !bad_signature {
break;
}
if previous.is_empty() || previous.0 == signing_key.0 {
continue;
}
result = decode::<FileIdClaims>(token, &DecodingKey::from_secret(&previous.0), &validation);
}
)?;
Ok(result?.claims)
}
/// Reports a signed, fid-bound write token whose only failure is expiry. It
/// never authorizes a request. Mirrors Go's `security.IsExpiredVolumeJwt`.
pub fn is_expired_volume_jwt(
signing_key: &SigningKey,
token: &str,
expected_fid: &str,
previous_keys: &[&SigningKey],
) -> bool {
match decode_jwt(signing_key, token, previous_keys) {
Err(JwtError::Jwt(e))
if matches!(e.kind(), jsonwebtoken::errors::ErrorKind::ExpiredSignature) => {}
_ => return false,
}
#[derive(Deserialize)]
struct ExpiredClaims {
fid: Option<String>,
iat: Option<u64>,
}
let mut validation = Validation::new(Algorithm::HS256);
validation.required_spec_claims.clear();
validation.validate_exp = false;
validation.validate_nbf = true;
validation.leeway = 0;
let Some(data) = std::iter::once(signing_key)
.chain(previous_keys.iter().copied())
.filter(|key| !key.is_empty())
.find_map(|key| {
decode::<ExpiredClaims>(token, &DecodingKey::from_secret(&key.0), &validation).ok()
})
else {
return false;
};
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
data.claims.fid.as_deref() == Some(expected_fid) && data.claims.iat.is_none_or(|iat| iat <= now)
Ok(data.claims)
}
// ============================================================================
@@ -175,9 +118,6 @@ pub struct Guard {
pub expires_after_sec: i64,
pub read_signing_key: SigningKey,
pub read_expires_after_sec: i64,
/// Accepted when verifying, never used to sign.
pub previous_signing_key: SigningKey,
pub previous_read_signing_key: SigningKey,
/// Combined flag: true when whitelist is non-empty OR signing key is present.
/// Matches Go's `isWriteActive = !isEmptyWhiteList || len(SigningKey) != 0`.
is_write_active: bool,
@@ -198,8 +138,6 @@ impl Guard {
expires_after_sec,
read_signing_key,
read_expires_after_sec,
previous_signing_key: SigningKey(vec![]),
previous_read_signing_key: SigningKey(vec![]),
is_write_active: false,
};
guard.update_whitelist(whitelist);
@@ -244,15 +182,11 @@ impl Guard {
expires_after_sec: i64,
read_signing_key: SigningKey,
read_expires_after_sec: i64,
previous_signing_key: SigningKey,
previous_read_signing_key: SigningKey,
) {
self.signing_key = signing_key;
self.expires_after_sec = expires_after_sec;
self.read_signing_key = read_signing_key;
self.read_expires_after_sec = read_expires_after_sec;
self.previous_signing_key = previous_signing_key;
self.previous_read_signing_key = previous_read_signing_key;
let is_empty_whitelist = self.whitelist_ips.is_empty() && self.whitelist_cidrs.is_empty();
self.is_write_active = !is_empty_whitelist || !self.signing_key.is_empty();
@@ -295,16 +229,6 @@ impl Guard {
false
}
/// The write (or read) signing key and the previous key still accepted for
/// it. Mirrors Go's `Guard.VerificationKeys`.
pub fn verification_keys(&self, is_write: bool) -> (&SigningKey, &SigningKey) {
if is_write {
(&self.signing_key, &self.previous_signing_key)
} else {
(&self.read_signing_key, &self.previous_read_signing_key)
}
}
/// Check if a read signing key is configured.
pub fn has_read_signing_key(&self) -> bool {
!self.read_signing_key.is_empty()
@@ -314,14 +238,18 @@ impl Guard {
/// `is_write` determines which signing key to use.
/// Returns Ok(()) if valid, or if security is disabled.
pub fn check_jwt(&self, token: Option<&str>, is_write: bool) -> Result<(), JwtError> {
let (key, previous) = self.verification_keys(is_write);
let key = if is_write {
&self.signing_key
} else {
&self.read_signing_key
};
if key.is_empty() {
return Ok(()); // Security disabled for this operation type
}
let token = token.ok_or(JwtError::MissingToken)?;
decode_jwt(key, token, &[previous])?;
decode_jwt(key, token)?;
Ok(())
}
@@ -332,14 +260,18 @@ impl Guard {
expected_fid: &str,
is_write: bool,
) -> Result<(), JwtError> {
let (key, previous) = self.verification_keys(is_write);
let key = if is_write {
&self.signing_key
} else {
&self.read_signing_key
};
if key.is_empty() {
return Ok(());
}
let token = token.ok_or(JwtError::MissingToken)?;
let claims = decode_jwt(key, token, &[previous])?;
let claims = decode_jwt(key, token)?;
match claims.fid {
None => {
@@ -453,7 +385,7 @@ mod tests {
fn test_jwt_round_trip() {
let key = SigningKey::from_string("test-secret-key");
let token = gen_jwt(&key, 3600, "3,01637037d6").unwrap();
let claims = decode_jwt(&key, &token, &[]).unwrap();
let claims = decode_jwt(&key, &token).unwrap();
assert_eq!(claims.fid, Some("3,01637037d6".to_string()));
}
@@ -466,7 +398,7 @@ mod tests {
#[test]
fn test_jwt_invalid_token() {
let key = SigningKey::from_string("secret");
let result = decode_jwt(&key, "invalid.token.here", &[]);
let result = decode_jwt(&key, "invalid.token.here");
assert!(result.is_err());
}
@@ -475,60 +407,7 @@ mod tests {
let key1 = SigningKey::from_string("secret1");
let key2 = SigningKey::from_string("secret2");
let token = gen_jwt(&key1, 3600, "1,abc").unwrap();
assert!(decode_jwt(&key2, &token, &[]).is_err());
}
#[test]
fn test_is_expired_volume_jwt_classifies_expiry_only() {
let key = SigningKey::from_string("write-key");
let fid = "3,01637037d6";
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs();
let sign = |claims: serde_json::Value, key: &SigningKey| {
encode(
&Header::new(Algorithm::HS256),
&claims,
&EncodingKey::from_secret(&key.0),
)
.unwrap()
};
let expired = sign(serde_json::json!({"fid": fid, "exp": now - 10}), &key);
assert!(is_expired_volume_jwt(&key, &expired, fid, &[]));
assert!(!is_expired_volume_jwt(&key, &expired, "3,01637037d7", &[]));
assert!(!is_expired_volume_jwt(
&SigningKey::from_string("other-key"),
&expired,
fid,
&[]
));
assert!(!is_expired_volume_jwt(
&SigningKey(vec![]),
&expired,
fid,
&[]
));
let immature = sign(
serde_json::json!({"fid": fid, "exp": now - 10, "nbf": now + 60}),
&key,
);
assert!(!is_expired_volume_jwt(&key, &immature, fid, &[]));
let future_issued = sign(
serde_json::json!({"fid": fid, "exp": now - 10, "iat": now + 60}),
&key,
);
assert!(!is_expired_volume_jwt(&key, &future_issued, fid, &[]));
let live = sign(serde_json::json!({"fid": fid, "exp": now + 60}), &key);
assert!(!is_expired_volume_jwt(&key, &live, fid, &[]));
let unsigned = format!(
"eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0.{}.",
base64::Engine::encode(
&base64::engine::general_purpose::URL_SAFE_NO_PAD,
serde_json::json!({"fid": fid, "exp": now - 10}).to_string()
)
);
assert!(!is_expired_volume_jwt(&key, &unsigned, fid, &[]));
assert!(decode_jwt(&key2, &token).is_err());
}
#[test]
@@ -628,88 +507,25 @@ mod tests {
11,
SigningKey::from_string("new-read"),
61,
SigningKey(vec![]),
SigningKey(vec![]),
);
let token = gen_jwt(&guard.signing_key, 60, "3,01637037d6").unwrap();
// Validates with the rotated key, not the old one.
assert!(decode_jwt(&guard.signing_key, &token, &[]).is_ok());
assert!(decode_jwt(&SigningKey::from_string("old-write"), &token, &[]).is_err());
assert!(decode_jwt(&guard.signing_key, &token).is_ok());
assert!(decode_jwt(&SigningKey::from_string("old-write"), &token).is_err());
assert_eq!(guard.expires_after_sec, 11);
assert_eq!(guard.read_expires_after_sec, 61);
}
#[test]
fn test_previous_signing_key_is_accepted() {
let fid = "3,01637037d6";
let accepts = |guard: &Guard, key: &str, is_write: bool| {
let token = gen_jwt(&SigningKey::from_string(key), 60, fid).unwrap();
guard
.check_jwt_for_file(Some(&token), fid, is_write)
.is_ok()
};
let mut guard = Guard::new(
&[],
SigningKey::from_string("write-new"),
10,
SigningKey::from_string("read-new"),
60,
);
guard.previous_signing_key = SigningKey::from_string("write-old");
guard.previous_read_signing_key = SigningKey::from_string("read-old");
assert!(accepts(&guard, "write-new", true));
assert!(accepts(&guard, "write-old", true));
assert!(accepts(&guard, "read-old", false));
assert!(!accepts(&guard, "other", true));
assert!(!accepts(&guard, "read-old", true));
let expired = encode(
&Header::new(Algorithm::HS256),
&serde_json::json!({"fid": fid, "exp": 1}),
&EncodingKey::from_secret(b"write-old"),
)
.unwrap();
let (key, previous) = guard.verification_keys(true);
assert!(is_expired_volume_jwt(key, &expired, fid, &[previous]));
assert!(!is_expired_volume_jwt(key, &expired, fid, &[]));
guard.update_signing_keys(
SigningKey::from_string("write-new"),
10,
SigningKey::from_string("read-new"),
60,
SigningKey(vec![]),
SigningKey(vec![]),
);
assert!(!accepts(&guard, "write-old", true));
assert!(!accepts(&guard, "read-old", false));
}
#[test]
fn test_update_signing_keys_toggles_write_active() {
let mut guard = Guard::new(&[], SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(guard.check_jwt(None, true).is_ok());
guard.update_signing_keys(
SigningKey::from_string("write"),
10,
SigningKey(vec![]),
0,
SigningKey(vec![]),
SigningKey(vec![]),
);
guard.update_signing_keys(SigningKey::from_string("write"), 10, SigningKey(vec![]), 0);
assert!(guard.is_write_active);
guard.update_signing_keys(
SigningKey(vec![]),
0,
SigningKey(vec![]),
0,
SigningKey(vec![]),
SigningKey(vec![]),
);
guard.update_signing_keys(SigningKey(vec![]), 0, SigningKey(vec![]), 0);
assert!(!guard.is_write_active);
}
+2 -15
View File
@@ -110,17 +110,6 @@ pub fn load_outgoing_grpc_tls(
}))
}
#[cfg(test)]
impl OutgoingGrpcTlsConfig {
pub(crate) fn self_signed_for_test() -> Self {
Self {
cert_pem: tests::TEST_CERT_PEM.to_string(),
key_pem: tests::TEST_KEY_PEM.to_string(),
ca_pem: tests::TEST_CERT_PEM.to_string(),
}
}
}
pub fn grpc_endpoint_uri(grpc_host_port: &str, tls: Option<&OutgoingGrpcTlsConfig>) -> String {
let scheme = if tls.is_some() { "https" } else { "http" };
format!("{}://{}", scheme, grpc_host_port)
@@ -371,8 +360,8 @@ mod tests {
use std::sync::{Arc, Mutex};
use std::time::Duration;
pub(super) const TEST_CERT_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBPDCB76ADAgECAhRuRPQgeAu43BT/M7EfAWSdapVdYDAFBgMrZXAwFDESMBAG\nA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNTE2MTUyOVoXDTM2MDcwMjE2MTUyOVow\nFDESMBAGA1UEAwwJbG9jYWxob3N0MCowBQYDK2VwAyEAr/3bNIFI+8V32oCiY6y+\nXRFmZpdNQ2g//VtRkT+nQg+jUzBRMB0GA1UdDgQWBBTsy9tLf1zPiXCQfgci6zNi\ndEzRSjAfBgNVHSMEGDAWgBTsy9tLf1zPiXCQfgci6zNidEzRSjAPBgNVHRMBAf8E\nBTADAQH/MAUGAytlcANBAIvsdw0IbvOBBkb9cd7BfMJfIP9pQQrAL03pCRWJFnFh\nSysaLVgFXI4T078IiaM874oO+iB+5vNbWEpc7CkGow4=\n-----END CERTIFICATE-----\n";
pub(super) const TEST_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIHbyn71Kk+Y7KT3sBctit7uZpErpoH6qDbFj6P8qGaZH\n-----END PRIVATE KEY-----\n";
const TEST_CERT_PEM: &str = "-----BEGIN CERTIFICATE-----\nMIIBPDCB76ADAgECAhRuRPQgeAu43BT/M7EfAWSdapVdYDAFBgMrZXAwFDESMBAG\nA1UEAwwJbG9jYWxob3N0MB4XDTI2MDcwNTE2MTUyOVoXDTM2MDcwMjE2MTUyOVow\nFDESMBAGA1UEAwwJbG9jYWxob3N0MCowBQYDK2VwAyEAr/3bNIFI+8V32oCiY6y+\nXRFmZpdNQ2g//VtRkT+nQg+jUzBRMB0GA1UdDgQWBBTsy9tLf1zPiXCQfgci6zNi\ndEzRSjAfBgNVHSMEGDAWgBTsy9tLf1zPiXCQfgci6zNidEzRSjAPBgNVHRMBAf8E\nBTADAQH/MAUGAytlcANBAIvsdw0IbvOBBkb9cd7BfMJfIP9pQQrAL03pCRWJFnFh\nSysaLVgFXI4T078IiaM874oO+iB+5vNbWEpc7CkGow4=\n-----END CERTIFICATE-----\n";
const TEST_KEY_PEM: &str = "-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIHbyn71Kk+Y7KT3sBctit7uZpErpoH6qDbFj6P8qGaZH\n-----END PRIVATE KEY-----\n";
#[test]
fn test_build_grpc_endpoint_with_tls_resolves_crypto_provider() {
@@ -436,8 +425,6 @@ mod tests {
ui_enabled: false,
jwt_signing_key: vec![],
jwt_signing_expires_seconds: 0,
jwt_previous_signing_key: vec![],
jwt_previous_read_signing_key: vec![],
jwt_read_signing_key: vec![],
jwt_read_signing_expires_seconds: 0,
https_cert_file: String::new(),
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
-1
View File
@@ -1698,7 +1698,6 @@ mod tests {
security_file: String::new(),
cli_white_list: vec![],
state_file_path: String::new(),
ec_lifecycle_locks: std::sync::Mutex::new(std::collections::HashMap::new()),
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
volume_copies_in_flight: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
-2
View File
@@ -156,8 +156,6 @@ mod tests {
ui_enabled: false,
jwt_signing_key: vec![],
jwt_signing_expires_seconds: 0,
jwt_previous_signing_key: vec![],
jwt_previous_read_signing_key: vec![],
jwt_read_signing_key: vec![],
jwt_read_signing_expires_seconds: 0,
https_cert_file: String::new(),
+108 -347
View File
@@ -158,7 +158,7 @@ pub async fn read_ec_shard_needle_or_miss(
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => {
// A complete reply merges into the cache; an incomplete one
// (< data_shards) only puts the holders it names first.
// (< data_shards) is left unwritten — keep the prior cache.
match write_back_shard_locations(
state,
vid,
@@ -167,6 +167,8 @@ pub async fn read_ec_shard_needle_or_miss(
snapshot.encode_ts_ns,
) {
Some(merged) => shard_locations = merged,
// An incomplete reply leaves the cache unwritten and its refresh
// time unadvanced, so the mark this refresh consumed goes back.
None => mark_shard_locations_stale(state, vid),
}
}
@@ -441,95 +443,6 @@ pub async fn delete_ec_shard_needle_distributed(
)))
}
/// A delete whose read found the needle deleted, best effort. A holder's read
/// checks one disk's deletion set, and a delete that failed part way can leave
/// its other disks live, so the delete goes to the primary shard holders whose
/// read answers deleted, which skip the disks already recording it. Normal
/// routing could stop at another copy instead; it is used only when no holder
/// answers deleted. `forwardEcDeleteOfDeletedNeedle` in Go.
pub async fn forward_ec_delete_of_deleted_needle(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) {
if let Err(e) = forward_ec_delete_to_holders_reading_deleted(state, vid, needle_id).await {
tracing::debug!(
"re-forward delete of deleted ec needle {}.{}: {}",
vid.0,
needle_id,
e
);
}
}
async fn forward_ec_delete_to_holders_reading_deleted(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) -> io::Result<()> {
let (probe, holders, collection, version) = {
let store = state.store.read().unwrap();
let ecv = store.find_ec_volume(vid).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("ec volume {} not mounted", vid.0),
)
})?;
let (_, _, intervals) = ecv.locate_needle(needle_id)?.ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("needle {} not in ec volume {}", needle_id, vid.0),
)
})?;
let (shard_id, shard_offset) = intervals
.first()
.map(|i| ecv.interval_to_shard_id_and_offset(i))
.ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "no intervals for needle"))?;
let (locations, _) = ecv.shard_locations_snapshot();
(
EcInterval {
vid,
needle_id,
shard_id,
shard_offset,
size: 1,
expected_encode_ts_ns: ecv.encode_ts_ns,
},
locations.get(&shard_id).cloned().unwrap_or_default(),
ecv.collection.clone(),
ecv.version,
)
};
let target = EcDeleteTarget {
vid,
collection: &collection,
version,
needle_id,
};
let mut reported = false;
let mut last_err = None;
for addr in &holders {
if !matches!(
tokio::time::timeout(
EC_READ_HINT_TIMEOUT,
do_read_remote_ec_shard_interval(state, addr, probe),
)
.await,
Ok(Ok((_, true)))
) {
continue;
}
reported = true;
if let Err(e) = delete_on_remote_ec_shard(state, addr, &target).await {
last_err = Some(e);
}
}
if !reported {
return delete_ec_shard_needle_distributed(state, vid, needle_id).await;
}
last_err.map_or(Ok(()), Err)
}
/// `doDeleteNeedleFromRemoteEcShardServers` in Go. `Ok(false)` is the
/// shard-missing signal — no live holder anywhere — that triggers the
/// caller's fallback walk over the remaining shards.
@@ -548,12 +461,12 @@ async fn delete_on_ec_shard_holders(
let mut last_err = None;
if local_shards.contains(&shard_id) {
// A decode in its publishing tail must not miss this delete. The
// tail membership is verified again under the journal lock inside
// journal_delete_local — WouldBlock means the decode claimed it in
// the gap after this wait — so wait and retry.
// tail membership is verified again under the store write lock
// inside journal_delete_local — WouldBlock means the decode claimed
// it in the gap after this wait — so wait and retry.
loop {
crate::server::grpc_server::wait_ec_decode_tail(state, target.vid).await;
match journal_delete_local(state, target.vid, target.needle_id).await {
match journal_delete_local(state, target.vid, target.needle_id) {
Ok(()) => return Ok(true),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => continue,
// Nothing was committed — the volume unmounted or remounted
@@ -620,52 +533,38 @@ async fn delete_on_remote_ec_shard(
/// no-op: `journal_delete` would accept it silently, but here it means the
/// volume remounted as a different generation mid-delete and the tombstone
/// should go to a replica that still has the needle.
pub(crate) async fn journal_delete_local(
fn journal_delete_local(
state: &Arc<VolumeServerState>,
vid: VolumeId,
needle_id: NeedleId,
) -> io::Result<()> {
// Every local runtime records the delete, the first last, as in the
// VolumeEcBlobDelete handler.
let appenders = {
let store = state.store.read().unwrap();
let ec_vols = store.find_all_ec_volumes(vid);
if ec_vols.is_empty() {
let mut store = state.store.write().unwrap();
// Membership is read under the write lock: a decode can claim the
// publishing tail while this call waited for the decoder's read lock,
// so a check taken earlier would be stale by commit time.
if crate::server::grpc_server::ec_decode_tail_contains(state, vid) {
return Err(io::Error::new(
io::ErrorKind::WouldBlock,
format!("ec volume {} is in decode publishing tail", vid.0),
));
}
let ecv = store.find_ec_volume_mut(vid).ok_or_else(|| {
io::Error::new(
io::ErrorKind::NotFound,
format!("ec volume {} unmounted", vid.0),
)
})?;
match ecv.find_needle_from_ecx(needle_id)? {
None => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("ec volume {} unmounted", vid.0),
format!("needle {} not in local ecx", needle_id),
));
}
let mut appenders = Vec::new();
for (i, ecv) in ec_vols.into_iter().enumerate() {
match ecv.find_needle_from_ecx(needle_id)? {
None if i > 0 => continue,
None => {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("needle {} not in local ecx", needle_id),
));
}
Some((_, size)) if size.is_deleted() => continue,
Some(_) => {}
}
appenders.push(ecv.journal_appender());
}
appenders
};
// Membership is read under the journal lock: a decode claims the
// publishing tail before it takes that lock for its catch-up, so a check
// taken earlier would be stale by commit time.
let state = state.clone();
tokio::task::spawn_blocking(move || {
appenders.iter().rev().try_for_each(|appender| {
appender.journal_delete(needle_id, || {
crate::server::grpc_server::ec_decode_tail_contains(&state, vid)
})
})
})
.await
.map_err(io::Error::other)?
Some((_, size)) if size.is_deleted() => return Ok(()),
Some(_) => {}
}
ecv.journal_delete(needle_id)
}
fn local_shard_ids(ecv: &crate::storage::erasure_coding::EcVolume) -> HashSet<ShardId> {
@@ -811,10 +710,8 @@ pub async fn scrub_ec_volume_distributed(
) {
match cached_lookup_ec_shard_locations(state, vid).await {
Ok(fresh) => {
let partial = located_shard_count(&fresh) < data_shards;
if write_back_shard_locations(state, vid, fresh, data_shards, expected_encode_ts_ns)
.is_none()
|| partial
{
mark_shard_locations_stale(state, vid);
return (
@@ -1331,44 +1228,35 @@ async fn cached_lookup_ec_shard_locations(
.lookup_ec_volume(Request::new(LookupEcVolumeRequest { volume_id: vid.0 }))
.await
.map_err(|e| io::Error::other(format!("lookup_ec_volume: {}", e)))?;
Ok(shard_locations_from_reply(resp.into_inner()))
}
let resp = resp.into_inner();
/// The shard slots of a `LookupEcVolume` reply. The master answers every slot
/// it tracks, so a shard whose holders are all down comes back with no
/// addresses: it does not count toward the reply's completeness, and a complete
/// reply drops it from the cache, as Go's `cachedLookupEcShardLocations` does.
fn shard_locations_from_reply(
resp: master_pb::LookupEcVolumeResponse,
) -> HashMap<ShardId, Vec<String>> {
let mut out = HashMap::new();
for entry in resp.shard_id_locations {
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
continue;
};
let addrs: Vec<String> = entry
.locations
.iter()
.map(format_location_as_server_address)
.collect();
// Defensive: skip out-of-range shard ids from the master instead of
// truncating (256 would alias 0). Valid replies are unaffected.
let Ok(sid) = shard_id_try_from(entry.shard_id) else {
continue;
};
out.insert(sid, addrs);
}
out
}
fn located_shard_count(locations: &HashMap<ShardId, Vec<String>>) -> usize {
locations.values().filter(|addrs| !addrs.is_empty()).count()
Ok(out)
}
/// Merge a fresh `LookupEcVolume` reply into the per-EcVolume shard-location
/// cache. Returns the resulting map, or `None` when the volume is gone.
/// cache. Returns the merged map on success, or `None` when the reply is
/// incomplete (and was therefore NOT written) or the volume is gone.
///
/// Completeness guard (mirrors Go's `cachedLookupEcShardLocations`): a reply
/// carrying fewer than `data_shards` shard locations is a master-mid-recovery
/// partial, not ground truth. It only puts the holders it names ahead of the
/// cached ones, and leaves the refresh time unadvanced with the map marked
/// stale, so a previously-complete cache is never clobbered with a partial map.
/// On a complete reply the write is a per-shard MERGE (see
/// partial, not ground truth — Go aborts the lookup with a retryable error and
/// leaves the cache + refresh time untouched. Returning `None` without writing
/// does the same, so a previously-complete cache is never clobbered with a
/// partial map. On a complete reply the write is a per-shard MERGE (see
/// `merge_shard_locations`), not a full replace.
fn write_back_shard_locations(
state: &Arc<VolumeServerState>,
@@ -1377,11 +1265,11 @@ fn write_back_shard_locations(
data_shards: usize,
expected_encode_ts_ns: i64,
) -> Option<HashMap<ShardId, Vec<String>>> {
if locations.len() < data_shards {
return None;
}
let store = state.store.read().unwrap();
let ecv = find_ec_volume_for_scrub(&store, vid, expected_encode_ts_ns)?;
if located_shard_count(&locations) < data_shards {
return Some(ecv.merge_partial_shard_locations(locations));
}
Some(ecv.merge_shard_locations(locations))
}
@@ -1444,11 +1332,6 @@ struct EcShardMap<'a> {
parity_shards: usize,
}
/// Bounds a one-byte probe of a holder that may have stopped answering: a
/// delisted holder before the read reconstructs the shard, or a holder a
/// delete retry asks (Go's `ecReadHintTimeout`).
const EC_READ_HINT_TIMEOUT: Duration = Duration::from_secs(5);
/// Try direct peer read; on failure, reconstruct via Reed-Solomon
/// from the other shards. Mirrors `readOneEcShardInterval`'s tail.
async fn fetch_one_interval(
@@ -1457,12 +1340,6 @@ async fn fetch_one_interval(
map: EcShardMap<'_>,
) -> io::Result<(Vec<u8>, bool)> {
let EcInterval { vid, shard_id, .. } = iv;
if map.locations.get(&shard_id).is_none_or(Vec::is_empty)
&& let Some((hints, revision)) = shard_read_hints(state, vid, shard_id)
&& ask_ec_shard_read_hints(state, iv, &hints, revision).await
{
return Ok((Vec::new(), true));
}
// Direct peer read against the cached locations for this shard.
if let Some(sources) = map.locations.get(&shard_id)
&& !sources.is_empty()
@@ -1640,8 +1517,7 @@ async fn do_read_remote_ec_shard_interval(
}
/// Reads one `VolumeEcShardRead` reply into the interval's bytes, or the
/// holder's deleted answer, taken as soon as it arrives so a stream that fails
/// or stalls after it cannot lose it.
/// holder's deleted answer, which stands even if the stream fails after it.
async fn collect_ec_shard_read(
mut stream: tonic::Streaming<VolumeEcShardReadResponse>,
source: &str,
@@ -1655,11 +1531,12 @@ async fn collect_ec_shard_read(
..
} = iv;
let mut out = Vec::with_capacity(size);
while let Some(msg) = stream
.message()
.await
.map_err(|e| io::Error::other(format!("recv: {}", e)))?
{
let mut is_deleted = false;
// A deleted answer stands even if the stream fails after it.
while let Some(msg) = match stream.message().await {
Err(_) if is_deleted => None,
msg => msg.map_err(|e| io::Error::other(format!("recv: {}", e)))?,
} {
// Validate the served shard's identity client-side, so the guard holds even
// against a pre-upgrade server that ignored the request field (returns 0).
// A mismatch fails the read; the caller recovers from parity.
@@ -1669,20 +1546,23 @@ async fn collect_ec_shard_read(
vid.0, shard_id, source, expected_encode_ts_ns, msg.encode_ts_ns
)));
}
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
// at read time and answers is_deleted with no payload. Signal the deletion to
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
// into Reed-Solomon. Exempt from the short-read guard below.
if msg.is_deleted {
return Ok((Vec::new(), true));
is_deleted = true;
}
if !msg.data.is_empty() {
out.extend_from_slice(&msg.data);
}
}
// A runtime EC delete keeps the .ecx size positive; the holder masks the delete
// at read time and answers is_deleted with no payload. Signal the deletion to
// the caller (Go's `(bytes, is_deleted)` contract) instead of synthesizing bytes
// here: the scrub zero-fills the interval (so the assembled needle hits read_bytes
// -> SizeMismatch{found:0} -> suppression), the serving direct read short-circuits
// to "deleted", and reconstruction EXCLUDES the shard rather than feeding zeros
// into Reed-Solomon. Exempt from the short-read guard below.
if is_deleted {
return Ok((Vec::new(), true));
}
if out.len() < size {
return Err(io::Error::new(
io::ErrorKind::UnexpectedEof,
@@ -1944,62 +1824,6 @@ async fn recover_one_remote_ec_shard_interval(
}
}
/// Reports whether a delisted holder of the shard journaled the needle's
/// delete (Go's `askEcShardReadHints`). Each holder is asked, since any one of
/// them may hold the delete; only a deleted answer is taken, so one byte is
/// enough. Holders that failed are forgotten, even when a later one answers
/// deleted, unless a lookup changed the hints meanwhile.
async fn ask_ec_shard_read_hints(
state: &Arc<VolumeServerState>,
iv: EcInterval,
hints: &[String],
revision: u64,
) -> bool {
let probe = EcInterval { size: 1, ..iv };
let mut failed = Vec::new();
let mut deleted = false;
for hint in hints {
let err = match tokio::time::timeout(
EC_READ_HINT_TIMEOUT,
do_read_remote_ec_shard_interval(state, hint, probe),
)
.await
{
Ok(Ok((_, true))) => {
deleted = true;
break;
}
Ok(Ok(_)) => continue,
Ok(Err(e)) => e.to_string(),
Err(_) => "timed out".to_string(),
};
tracing::debug!(
"read ec shard {}.{} from delisted holder {} failed: {}",
iv.vid.0,
iv.shard_id,
hint,
err
);
failed.push(hint.clone());
}
if !failed.is_empty() {
let store = state.store.read().unwrap();
if let Some(ecv) = store.find_ec_volume(iv.vid) {
ecv.forget_shard_read_hints(iv.shard_id, revision, &failed);
}
}
deleted
}
fn shard_read_hints(
state: &Arc<VolumeServerState>,
vid: VolumeId,
shard_id: ShardId,
) -> Option<(Vec<String>, u64)> {
let store = state.store.read().unwrap();
store.find_ec_volume(vid)?.shard_read_hints(shard_id)
}
/// Drop a confirmed-corrupt shard's cached location so later reads go straight
/// to reconstruction — Go's `forgetShardId` reached through the volume.
fn forget_shard_location(state: &Arc<VolumeServerState>, vid: VolumeId, shard_id: ShardId) {
@@ -2560,45 +2384,23 @@ pub(crate) async fn recover_missing_ec_indexes(
"cannot look up peers to recover missing .ecx: {}",
e
);
Vec::new()
continue;
}
};
// Under the volume's lifecycle lock, so an in-flight VolumeEcShardsCopy
// of it, which may unlink the shards it renamed in, never has them
// mounted from under it.
let _lifecycle = state.ec_lifecycle_lock(m.vid).lock_owned().await;
let current = state
.store
.read()
.unwrap()
.collect_ec_volumes_missing_index_only(Some(m.vid))
.into_iter()
.find(|x| x.vid == m.vid && x.collection == m.collection);
// A copy holding the lock may have installed the index meanwhile: skip
// the fetch, but its shards still need the mount.
if let Some(current) = &current {
if peers.is_empty() {
tracing::warn!(
volume_id = m.vid.0,
"shards present locally but .ecx missing and no peer holds it; leaving shards unloaded"
);
continue;
}
if !fetch_ec_index_from_peers(state, current, &peers).await {
continue;
}
if peers.is_empty() {
tracing::warn!(
volume_id = m.vid.0,
"shards present locally but .ecx missing and no peer holds it; leaving shards unloaded"
);
continue;
}
state
.store
.write()
.unwrap()
.mount_recovered_ec_shards_only(Some(m.vid));
if current.is_some() {
if fetch_ec_index_from_peers(state, m, &peers).await {
recovered += 1;
}
}
if recovered > 0 {
state.store.write().unwrap().mount_recovered_ec_shards();
tracing::info!(
"recovered missing EC index for {} volume(s) from peers and mounted their shards",
recovered
@@ -2954,38 +2756,6 @@ mod tests {
assert!(search(&shards, &metas, &n, dat_offset).is_none());
}
// The master answers all 32 shard slots, located or not. While 7 of a 10+4
// volume's shards have a holder up, the reply must count as 7 shards, short
// of the data shards.
#[test]
fn a_lookup_reply_counts_only_located_shards() {
use master_pb::lookup_ec_volume_response::EcShardIdLocation;
let located = [0u32, 3, 4, 6, 7, 9, 12];
let reply = master_pb::LookupEcVolumeResponse {
volume_id: 136,
shard_id_locations: (0..32u32)
.map(|sid| EcShardIdLocation {
shard_id: sid,
locations: if located.contains(&sid) {
vec![master_pb::Location {
url: "10.0.0.5:8180".to_string(),
grpc_port: 18180,
..Default::default()
}]
} else {
Vec::new()
},
..Default::default()
})
.collect(),
};
let got = shard_locations_from_reply(reply);
assert_eq!(got.len(), 32);
assert_eq!(located_shard_count(&got), 7);
assert!(got[&1].is_empty());
assert_eq!(got[&3], vec!["10.0.0.5:8180.18180".to_string()]);
}
fn locations(count: usize) -> HashMap<ShardId, Vec<String>> {
(0..count)
.map(|sid| (sid as ShardId, vec!["127.0.0.1:8080".to_string()]))
@@ -3012,10 +2782,9 @@ mod tests {
assert!(needs_refresh(&locations(0), None, false, 10, 14));
}
/// Serves one frame, then fails the stream or, with `stall`, never ends it.
struct AfterFrame(Option<bytes::Bytes>, bool);
struct FailAfterFrame(Option<bytes::Bytes>);
impl http_body::Body for AfterFrame {
impl http_body::Body for FailAfterFrame {
type Data = bytes::Bytes;
type Error = tonic::Status;
@@ -3024,54 +2793,46 @@ mod tests {
_cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Option<Result<http_body::Frame<bytes::Bytes>, tonic::Status>>>
{
match self.0.take() {
Some(frame) => std::task::Poll::Ready(Some(Ok(http_body::Frame::data(frame)))),
None if self.1 => std::task::Poll::Pending,
None => std::task::Poll::Ready(Some(Err(tonic::Status::unavailable(
std::task::Poll::Ready(Some(match self.0.take() {
Some(frame) => Ok(http_body::Frame::data(frame)),
None => Err(tonic::Status::unavailable(
"stream failed after the deleted answer",
)))),
}
)),
}))
}
}
/// A holder's deleted answer stands even when its stream fails or stalls
/// afterwards, so a later source or the quarantined shard cannot answer for
/// the needle.
/// A holder's deleted answer stands even when its stream fails afterwards,
/// so a later source or the quarantined shard cannot answer for the needle.
#[tokio::test]
async fn test_collect_ec_shard_read_keeps_deletion_when_the_stream_fails() {
for stall in [false, true] {
let message = prost::Message::encode_to_vec(&VolumeEcShardReadResponse {
is_deleted: true,
..Default::default()
});
let mut frame = vec![0u8];
frame.extend_from_slice(&(message.len() as u32).to_be_bytes());
frame.extend_from_slice(&message);
let stream = tonic::Streaming::new_response(
tonic_prost::ProstDecoder::<VolumeEcShardReadResponse>::default(),
AfterFrame(Some(frame.into()), stall),
tonic::codegen::http::StatusCode::OK,
None,
None,
);
let iv = EcInterval {
vid: VolumeId(7),
needle_id: NeedleId(42),
shard_id: 0,
shard_offset: 0,
size: 64,
expected_encode_ts_ns: 0,
};
let message = prost::Message::encode_to_vec(&VolumeEcShardReadResponse {
is_deleted: true,
..Default::default()
});
let mut frame = vec![0u8];
frame.extend_from_slice(&(message.len() as u32).to_be_bytes());
frame.extend_from_slice(&message);
let stream = tonic::Streaming::new_response(
tonic_prost::ProstDecoder::<VolumeEcShardReadResponse>::default(),
FailAfterFrame(Some(frame.into())),
tonic::codegen::http::StatusCode::OK,
None,
None,
);
let iv = EcInterval {
vid: VolumeId(7),
needle_id: NeedleId(42),
shard_id: 0,
shard_offset: 0,
size: 64,
expected_encode_ts_ns: 0,
};
let (buf, is_deleted) = tokio::time::timeout(
Duration::from_secs(5),
collect_ec_shard_read(stream, "peer:18080", iv),
)
let (buf, is_deleted) = collect_ec_shard_read(stream, "peer:18080", iv)
.await
.expect("the deleted answer waited for the stream to end")
.unwrap();
assert!(is_deleted, "stall={stall}");
assert!(buf.is_empty());
}
assert!(is_deleted);
assert!(buf.is_empty());
}
}
@@ -125,11 +125,6 @@ pub struct VolumeServerState {
pub cli_white_list: Vec<String>,
/// Path to state.pb file for persisting VolumeServerState across restarts.
pub state_file_path: String,
/// Per-vid EC lifecycle lock, serializing EC ops that install or remove a
/// vid's files. A tokio Mutex so the guard survives the copy's `.await` IO.
pub ec_lifecycle_locks: std::sync::Mutex<
std::collections::HashMap<crate::storage::types::VolumeId, Arc<tokio::sync::Mutex<()>>>,
>,
/// Volumes with an EC decode in flight. A dropped request leaves the
/// blocking job running; this keeps a retry from racing it on the
/// same volume files.
@@ -156,20 +151,6 @@ pub struct VolumeServerState {
}
impl VolumeServerState {
/// Return the per-vid EC lifecycle lock, creating it on first use. Entries
/// are never reaped.
pub fn ec_lifecycle_lock(
&self,
vid: crate::storage::types::VolumeId,
) -> Arc<tokio::sync::Mutex<()>> {
self.ec_lifecycle_locks
.lock()
.unwrap()
.entry(vid)
.or_insert_with(|| Arc::new(tokio::sync::Mutex::new(())))
.clone()
}
/// The master lookups should go to: the leader the heartbeat confirmed,
/// or empty while none is known, in its announced `host:port[.grpcPort]`
/// form. Mirrors Go's `vs.getCurrentMaster()`.
-1
View File
@@ -467,7 +467,6 @@ mod tests {
security_file: String::new(),
cli_white_list: vec![],
state_file_path: String::new(),
ec_lifecycle_locks: std::sync::Mutex::new(std::collections::HashMap::new()),
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
volume_copies_in_flight: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
@@ -829,24 +829,6 @@ impl DiskLocation {
self.volumes.len()
}
/// Number of local volumes of `collection` that still take writes: not
/// read-only and, when `volume_size_limit` is known (non zero), with a .dat
/// below it. The .dat size is what the master compares with the limit to
/// stop writes. Mirrors Go's WritableCollectionVolumesLen.
pub fn writable_collection_volumes_len(
&self,
collection: &str,
volume_size_limit: u64,
) -> usize {
self.volumes
.values()
.filter(|v| v.collection == collection && !v.has_remote_file() && !v.is_read_only())
.filter(|v| {
volume_size_limit == 0 || v.dat_file_size().unwrap_or(0) < volume_size_limit
})
.count()
}
/// Get all volume IDs, sorted.
pub fn volume_ids(&self) -> Vec<VolumeId> {
let mut ids: Vec<VolumeId> = self.volumes.keys().copied().collect();
@@ -6,7 +6,7 @@
use std::collections::{HashMap, HashSet};
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufWriter, Write};
use std::sync::{Arc, Mutex, MutexGuard, RwLock};
use std::sync::RwLock;
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::pb::master_pb;
@@ -31,17 +31,6 @@ pub(crate) struct ShardLocationCache {
/// Maps shard ID -> list of server addresses where that shard exists.
/// Used for distributed EC reads across the cluster.
locations: HashMap<ShardId, Vec<String>>,
/// Holders a complete lookup stopped placing a shard on (Go's
/// `ShardReadHints`). Reads ask them before reconstructing, for a delete only
/// such a holder journaled, but take nothing else from them: a delete made
/// since went to a listed holder, which reconstruction asks. Deletes never
/// use them.
read_hints: HashMap<ShardId, Vec<String>>,
/// Changes with every change to `read_hints` (Go's `ShardReadHintsRevision`),
/// so a read only forgets the hint holders it asked if no lookup changed them.
/// Drawn from `READ_HINTS_REVISION`, so a revision read before a remount
/// never matches the new `EcVolume`'s cache.
read_hints_revision: u64,
/// Wall-clock timestamp of the most recent successful `LookupEcVolume`
/// refresh of `locations`. `None` until the first refresh. Drives the
/// staleness heuristic in `cached_lookup_ec_shard_locations` (mirrors Go's
@@ -60,12 +49,6 @@ pub(crate) struct ShardLocationCache {
/// A multiple of `NEEDLE_ID_SIZE`; 1 MiB is 131072 entries per syscall.
const ECJ_LOAD_CHUNK_BYTES: usize = 1 << 20;
static READ_HINTS_REVISION: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
fn next_read_hints_revision() -> u64 {
READ_HINTS_REVISION.fetch_add(1, std::sync::atomic::Ordering::Relaxed) + 1
}
/// Process-wide epoch bumped whenever a failed .ecj append truncates its
/// uncommitted tail. A decode that read the journal without the store lock
/// compares a sample taken before the read with one taken under the
@@ -197,146 +180,6 @@ fn read_ecj_ids_with(
Ok(())
}
/// A volume's `.ecj` append handle and on-disk size, under the volume's own
/// journal lock (Go's `EcVolume.ecjFileAccessLock`). The size is what
/// mount-time compaction compares against the id set; the runtime delete count
/// comes from `deleted_needles`.
#[derive(Default)]
pub(crate) struct EcJournal {
file: Option<File>,
size: i64,
/// Set once the volume is closed or dropped: an appender that resolved the
/// volume before that must re-resolve rather than write a detached file.
closed: bool,
}
impl EcJournal {
/// Append whole records and sync them. On any failure the file is
/// truncated back to the pre-append length so the on-disk journal and
/// `deleted_needles` cannot drift.
fn append(&mut self, records: &[u8], volume_id: VolumeId, ecj_path: &str) -> io::Result<()> {
let ecj_file = self
.file
.as_mut()
.ok_or_else(|| io::Error::other("ecj file not open"))?;
// The file's own length, not this handle's cached size: another disk
// holding the same journal may have appended since.
let prev_ecj_size = ecj_file.metadata()?.len() as i64;
let append_result = ecj_file
.write_all(records)
.and_then(|_| ecj_file.sync_all());
match append_result {
Ok(()) => {
self.size = prev_ecj_size + records.len() as i64;
Ok(())
}
Err(e) => {
// write_all may have extended the file on disk before
// sync_all failed; truncate back to the known-good size so
// the on-disk journal never drifts past `deleted_needles`.
// Uses its own write handle: on Windows the append handle
// lacks FILE_WRITE_DATA, so set_len through it fails with
// ERROR_ACCESS_DENIED and the rollback would silently not
// happen.
let rollback = open_volume_file(OpenOptions::new().write(true), ecj_path)
.and_then(|f| f.set_len(prev_ecj_size as u64).and_then(|_| f.sync_all()));
// Bumped on attempt, not success: a failed rollback leaves the
// bytes in place and a decode re-reading for the epoch change
// simply sees them — harmless — while a successful one must
// never go unnoticed by an unlocked journal read.
ECJ_ROLLBACK_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if let Err(trunc_err) = rollback {
tracing::error!(
volume_id = volume_id.0,
truncate_error = %trunc_err,
"failed to truncate ecj after append failure"
);
}
Err(e)
}
}
}
}
/// Takes a `.ecj` path's append lock, ahead of any holder's journal lock.
pub(crate) fn lock_path(lock: &Option<Arc<Mutex<()>>>) -> Option<MutexGuard<'_, ()>> {
lock.as_ref()
.map(|l| l.lock().unwrap_or_else(|e| e.into_inner()))
}
/// A mounted volume's deletion journal, usable after the store lock that found
/// the volume is released, so the append's fsync stalls only this volume.
pub struct EcJournalAppender {
volume_id: VolumeId,
ecj_path: String,
path_lock: Option<Arc<Mutex<()>>>,
ecj: Arc<Mutex<EcJournal>>,
deleted_needles: Arc<RwLock<HashSet<NeedleId>>>,
}
impl EcJournalAppender {
/// Journal a delete of a needle the caller found live in `.ecx`.
/// `must_wait` runs under the journal lock, which a decode takes for its
/// catch-up, so a `true` answer (the decode publishing tail) is current
/// when the append would commit; it gives `WouldBlock`. A volume closed
/// since it was resolved gives `NotFound` with nothing written.
pub fn journal_delete(
&self,
needle_id: NeedleId,
must_wait: impl FnOnce() -> bool,
) -> io::Result<()> {
let _path = lock_path(&self.path_lock);
let mut journal = self.ecj.lock().unwrap_or_else(|e| e.into_inner());
if journal.closed {
return Err(io::Error::new(
io::ErrorKind::NotFound,
format!("ec volume {} closed", self.volume_id.0),
));
}
if self
.deleted_needles
.read()
.map(|s| s.contains(&needle_id))
.unwrap_or(false)
{
return Ok(());
}
if must_wait() {
return Err(io::Error::new(
io::ErrorKind::WouldBlock,
format!(
"ec volume {} is in decode publishing tail",
self.volume_id.0
),
));
}
let mut buf = [0u8; NEEDLE_ID_SIZE];
needle_id.to_bytes(&mut buf);
journal.append(&buf, self.volume_id, &self.ecj_path)?;
if let Ok(mut set) = self.deleted_needles.write() {
set.insert(needle_id);
}
Ok(())
}
/// Holds the journal lock, standing in for an append stuck in its fsync.
#[cfg(test)]
pub(crate) fn lock_journal(&self) -> MutexGuard<'_, EcJournal> {
self.ecj.lock().unwrap()
}
/// Drops the journal file, so every later append fails.
#[cfg(test)]
pub(crate) fn drop_journal_file(&self) {
self.ecj.lock().unwrap().file = None;
}
}
/// The encode run a holder reports when its disks serve shards of more than
/// one encode run for the volume (Go `erasure_coding.MixedEncodeRuns`).
pub const MIXED_ENCODE_RUNS: i64 = -1;
/// An erasure-coded volume managing its local shards and index.
pub struct EcVolume {
pub volume_id: VolumeId,
@@ -353,17 +196,22 @@ pub struct EcVolume {
pub block_size: i64,
ecx_file: Option<File>,
ecx_file_size: i64,
ecj: Arc<Mutex<EcJournal>>,
ecj_file: Option<File>,
/// This volume's registration as a holder of its `.ecj` path. Held for as
/// long as the journal handle may be open; see `ecj_registry`.
/// long as `ecj_file` may be open; see `ecj_registry`.
ecj_hold: Option<EcjHold>,
/// On-disk size of the .ecj deletion journal: the rollback point for a
/// failed append, and the size mount-time compaction compares against the
/// id set and re-checks on disk before replacing the file. The runtime
/// delete count comes from `deleted_needles.len()`, not from this.
ecj_file_size: i64,
/// In-memory set of needle ids that have been deleted since the volume
/// was encoded. .ecx is immutable at runtime — it only stores the
/// sorted (id, offset, size) index written at encode time — and runtime
/// deletes are journaled to .ecj + tracked here. Reads consult this
/// set to mask out deleted needles on top of the sealed .ecx lookup.
/// Seeded from .ecj in `new()` and updated by `journal_delete`.
deleted_needles: Arc<RwLock<HashSet<NeedleId>>>,
deleted_needles: RwLock<HashSet<NeedleId>>,
pub disk_type: DiskType,
/// Directory where .ecx/.ecj were actually found (may differ from dir_idx after fallback).
ecx_actual_dir: String,
@@ -907,9 +755,10 @@ impl EcVolume {
block_size,
ecx_file: None,
ecx_file_size: 0,
ecj: Arc::default(),
ecj_file: None,
ecj_hold: None,
deleted_needles: Arc::default(),
ecj_file_size: 0,
deleted_needles: RwLock::new(HashSet::new()),
disk_type: DiskType::default(),
ecx_actual_dir: dir_idx.to_string(),
shard_locations: RwLock::new(ShardLocationCache::default()),
@@ -997,10 +846,6 @@ impl EcVolume {
// the tail repair and the handle below see the final inode, and it
// stops any compaction from replacing the file under this handle.
vol.ecj_hold = Some(EcjHold::acquire(&ecj_path));
// Another disk's runtime may be appending to this file: repair and
// load only settled records.
let path_lock = vol.journal_path_lock();
let path_guard = lock_path(&path_lock);
// Repair a torn tail BEFORE the append handle exists.
//
@@ -1041,15 +886,11 @@ impl EcVolume {
}
let ecj_file = open_ecj_append(&ecj_path)?;
{
let mut journal = vol.journal();
journal.size = ecj_file.metadata()?.len() as i64;
journal.file = Some(ecj_file);
}
vol.ecj_file_size = ecj_file.metadata()?.len() as i64;
vol.ecj_file = Some(ecj_file);
// Seed the in-memory deleted set from the journal.
vol.load_deleted_needles_from_ecj(ecj_ops.read_at)?;
drop(path_guard);
// Load the generation-0 EC bitrot checksum sidecar. Optional, except
// when it contradicts the volume's own geometry — see
@@ -1288,12 +1129,11 @@ impl EcVolume {
&mut self,
read_at: fn(&File, &mut [u8], u64) -> io::Result<()>,
) -> io::Result<()> {
let journal = self.journal();
let ecj_file = match journal.file.as_ref() {
let ecj_file = match self.ecj_file.as_ref() {
Some(f) => f,
None => return Ok(()),
};
if journal.size < NEEDLE_ID_SIZE as i64 {
if self.ecj_file_size < NEEDLE_ID_SIZE as i64 {
return Ok(());
}
@@ -1301,8 +1141,7 @@ impl EcVolume {
// held the `deleted_needles` write lock for the whole scan, which on a
// bloated journal is the entire (unbounded) startup.
let mut loaded: HashSet<NeedleId> = HashSet::new();
read_ecj_ids_with(read_at, ecj_file, 0, journal.size as u64, &mut loaded)?;
drop(journal);
read_ecj_ids_with(read_at, ecj_file, 0, self.ecj_file_size as u64, &mut loaded)?;
let mut set = self
.deleted_needles
@@ -1392,7 +1231,7 @@ impl EcVolume {
tracing::warn!(
volume_id = self.volume_id.0,
collection = %self.collection,
on_disk_bytes = self.journal().size,
on_disk_bytes = self.ecj_file_size,
unique_ids = ids.len(),
compacted_bytes = ids.len() * NEEDLE_ID_SIZE,
"compacting bloated .ecj deletion journal",
@@ -1426,11 +1265,8 @@ impl EcVolume {
.map_err(|_| io::Error::other("deleted_needles lock poisoned"))?
.len();
let compacted_len = (distinct as i64).saturating_mul(NEEDLE_ID_SIZE as i64);
let size = self.journal().size;
Ok(
size >= ECJ_COMPACT_MIN_BYTES
&& size >= compacted_len.saturating_mul(ECJ_COMPACT_RATIO),
)
Ok(self.ecj_file_size >= ECJ_COMPACT_MIN_BYTES
&& self.ecj_file_size >= compacted_len.saturating_mul(ECJ_COMPACT_RATIO))
}
/// The deleted set, sorted so the rewritten file is deterministic: two
@@ -1453,8 +1289,7 @@ impl EcVolume {
/// A copy that appended, or replaced the file, after the load fails this,
/// and compacting then would drop what it wrote.
fn ecj_unchanged_since_load(&self, ecj_path: &str) -> io::Result<bool> {
let journal = self.journal();
let Some(held) = journal.file.as_ref() else {
let Some(held) = self.ecj_file.as_ref() else {
return Ok(false);
};
let held = held.metadata()?;
@@ -1466,7 +1301,7 @@ impl EcVolume {
return Ok(false);
}
}
Ok(held.len() == on_path.len() && on_path.len() as i64 == journal.size)
Ok(held.len() == on_path.len() && on_path.len() as i64 == self.ecj_file_size)
}
/// Publish a compacted tmp file over the live journal: drop the handle
@@ -1488,13 +1323,12 @@ impl EcVolume {
// rename over a file that is still open fails outright, which would
// make compaction a permanent no-op there; on Unix the handle would
// survive as an unlinked inode, which is worse than useless.
let mut journal = self.journal();
journal.file = None;
self.ecj_file = None;
if let Err(rename_err) = (ops.rename)(tmp_path, ecj_path) {
let _ = fs::remove_file(tmp_path);
return match (ops.reopen)(ecj_path) {
Ok(f) => {
journal.file = Some(f);
self.ecj_file = Some(f);
Err(EcjPublishError::Abandoned(rename_err))
}
Err(reopen_err) => Err(EcjPublishError::HandleLost(io::Error::new(
@@ -1521,8 +1355,8 @@ impl EcVolume {
// Reopen so later journal_delete appends land in the file just written.
let reopened = (ops.reopen)(ecj_path).map_err(|e| lost("reopen it", e))?;
let size = reopened.metadata().map_err(|e| lost("stat it", e))?.len();
journal.size = size as i64;
journal.file = Some(reopened);
self.ecj_file_size = size as i64;
self.ecj_file = Some(reopened);
Ok(())
}
@@ -1585,12 +1419,8 @@ impl EcVolume {
/// Sync the EC volume's journal and index files to disk (matching Go's ecv.Sync()).
/// Go flushes both .ecj and .ecx to ensure in-place deletion marks are persisted.
pub fn sync_to_disk(&self) -> io::Result<()> {
// Every append syncs its own record, so one in flight is not waited
// for: callers such as CopyFile hold the store lock here.
if let Ok(journal) = self.ecj.try_lock() {
if let Some(ref ecj_file) = journal.file {
ecj_file.sync_all()?;
}
if let Some(ref ecj_file) = self.ecj_file {
ecj_file.sync_all()?;
}
if let Some(ref ecx_file) = self.ecx_file {
ecx_file.sync_all()?;
@@ -1749,11 +1579,10 @@ impl EcVolume {
/// stamp the refresh time, returning a clone of the resulting map.
///
/// Per-shard upsert (mirrors Go's `cachedLookupEcShardLocations`): each shard
/// id present in the reply overwrites its cached entry, and one the reply
/// places nowhere is dropped, while shard ids absent from the reply keep
/// their previously-cached locations — so a reply that passes the data-shard
/// completeness guard but omits a shard already in cache does not drop that
/// shard's known location (unlike a full replace).
/// id present in the reply overwrites its cached entry, while shard ids absent
/// from the reply keep their previously-cached locations — so a reply that
/// passes the data-shard completeness guard but omits a shard already in cache
/// does not drop that shard's known location (unlike a full replace).
///
/// Map and refresh time advance in one write section, so no reader can pair
/// the merged map with the previous lookup's timestamp.
@@ -1763,48 +1592,9 @@ impl EcVolume {
) -> HashMap<ShardId, Vec<String>> {
let mut cache = self.shard_locations.write().unwrap();
for (shard_id, addrs) in locations {
if addrs.is_empty() {
if let Some(known) = cache.locations.remove(&shard_id)
&& !known.is_empty()
{
cache.read_hints.insert(shard_id, known);
cache.read_hints_revision = next_read_hints_revision();
}
} else {
if cache.read_hints.remove(&shard_id).is_some() {
cache.read_hints_revision = next_read_hints_revision();
}
cache.locations.insert(shard_id, addrs);
}
}
cache.refreshed_at = Some(Instant::now());
cache.locations.clone()
}
/// Put a partial reply's holders ahead of the cached ones for each shard it
/// places, keeping the cached addresses as fallback and every other shard
/// and the refresh time alone. A partial is not the volume's map, but a read
/// can still go straight to a shard it names; the map stays marked so the
/// next read looks it up again.
pub(crate) fn merge_partial_shard_locations(
&self,
locations: HashMap<ShardId, Vec<String>>,
) -> HashMap<ShardId, Vec<String>> {
let mut cache = self.shard_locations.write().unwrap();
for (shard_id, mut addrs) in locations {
if addrs.is_empty() {
continue;
}
if let Some(known) = cache.locations.get(&shard_id) {
for addr in known {
if !addrs.contains(addr) {
addrs.push(addr.clone());
}
}
}
cache.locations.insert(shard_id, addrs);
}
cache.stale = true;
cache.refreshed_at = Some(Instant::now());
cache.locations.clone()
}
@@ -1818,37 +1608,6 @@ impl EcVolume {
(cache.locations.clone(), cache.refreshed_at)
}
/// The shard's hint with the revision to pass back to
/// `forget_shard_read_hints`.
pub(crate) fn shard_read_hints(&self, shard_id: ShardId) -> Option<(Vec<String>, u64)> {
let cache = self.shard_locations.read().unwrap();
let hints = cache.read_hints.get(&shard_id)?.clone();
Some((hints, cache.read_hints_revision))
}
/// Drops the `failed` holders from the shard's hint only if no lookup
/// changed the hints since `revision`, as one may have while the reads were
/// in flight.
pub(crate) fn forget_shard_read_hints(
&self,
shard_id: ShardId,
revision: u64,
failed: &[String],
) {
let mut cache = self.shard_locations.write().unwrap();
if cache.read_hints_revision != revision {
return;
}
let Some(hints) = cache.read_hints.get_mut(&shard_id) else {
return;
};
hints.retain(|h| !failed.contains(h));
if hints.is_empty() {
cache.read_hints.remove(&shard_id);
}
cache.read_hints_revision = next_read_hints_revision();
}
/// Mark the cached map for a prompt re-check after a read failed against one
/// of its locations.
pub(crate) fn mark_shard_locations_stale(&self) {
@@ -2324,7 +2083,6 @@ impl EcVolume {
/// in place and the error is propagated so tombstones are not lost.
pub(crate) fn rebuild_ecx_from_journal(&mut self) -> io::Result<()> {
let ecj_path = self.ecj_file_name();
let mut journal = self.journal();
if !std::path::Path::new(&ecj_path).exists() {
return Ok(());
}
@@ -2360,9 +2118,9 @@ impl EcVolume {
// if the recreate fails, deletes must error rather than keep
// appending to the removed inode.
fs::remove_file(&ecj_path)?;
journal.file = None;
journal.file = Some(open_ecj_append(&ecj_path)?);
journal.size = 0;
self.ecj_file = None;
self.ecj_file = Some(open_ecj_append(&ecj_path)?);
self.ecj_file_size = 0;
if let Ok(mut set) = self.deleted_needles.write() {
set.clear();
}
@@ -2380,11 +2138,10 @@ impl EcVolume {
// The old handle points at the replaced file: drop it before the
// reopen so a failure leaves deletes erroring, not appending to a
// detached inode. Mirrors Go's ReopenDeletionJournal.
let mut journal = self.journal();
journal.file = None;
self.ecj_file = None;
let reopened = open_ecj_append(&ecj_path)?;
journal.size = reopened.metadata()?.len() as i64;
journal.file = Some(reopened);
self.ecj_file_size = reopened.metadata()?.len() as i64;
self.ecj_file = Some(reopened);
if let Ok(mut set) = self.deleted_needles.write() {
set.clear();
}
@@ -2427,36 +2184,61 @@ impl EcVolume {
return Ok(());
}
self.journal_appender().journal_delete(needle_id, || false)
}
/// This volume's journal, detached from the borrow of the volume.
pub fn journal_appender(&self) -> EcJournalAppender {
EcJournalAppender {
volume_id: self.volume_id,
ecj_path: self.ecj_file_name(),
path_lock: self.journal_path_lock(),
ecj: self.ecj.clone(),
deleted_needles: self.deleted_needles.clone(),
let mut buf = [0u8; NEEDLE_ID_SIZE];
needle_id.to_bytes(&mut buf);
self.append_journal(&buf)?;
if let Ok(mut set) = self.deleted_needles.write() {
set.insert(needle_id);
}
Ok(())
}
/// The append lock of this volume's `.ecj` path, shared with every other
/// disk's runtime journaling into the same file.
pub(crate) fn journal_path_lock(&self) -> Option<Arc<Mutex<()>>> {
self.ecj_hold.as_ref().map(EcjHold::append_lock)
}
/// Takes this volume's journal lock, waiting out an append in flight.
pub(crate) fn journal(&self) -> MutexGuard<'_, EcJournal> {
self.ecj.lock().unwrap_or_else(|e| e.into_inner())
}
/// Append whole records to `.ecj` and sync them. On any failure the file is
/// truncated back to the pre-append length so the on-disk journal and
/// `deleted_needles` cannot drift.
fn append_journal(&mut self, records: &[u8]) -> io::Result<()> {
let ecj_path = self.ecj_file_name();
let path_lock = self.journal_path_lock();
let _path = lock_path(&path_lock);
self.journal().append(records, self.volume_id, &ecj_path)
let prev_ecj_size = self.ecj_file_size;
let append_result: io::Result<()> = {
let ecj_file = self
.ecj_file
.as_mut()
.ok_or_else(|| io::Error::other("ecj file not open"))?;
ecj_file
.write_all(records)
.and_then(|_| ecj_file.sync_all())
};
match append_result {
Ok(()) => {
self.ecj_file_size += records.len() as i64;
Ok(())
}
Err(e) => {
// write_all may have extended the file on disk before
// sync_all failed; truncate back to the known-good size so
// the on-disk journal never drifts past `deleted_needles`.
// Uses its own write handle: on Windows the append handle
// lacks FILE_WRITE_DATA, so set_len through it fails with
// ERROR_ACCESS_DENIED and the rollback would silently not
// happen.
let ecj_path = self.ecj_file_name();
let rollback = open_volume_file(OpenOptions::new().write(true), &ecj_path)
.and_then(|f| f.set_len(prev_ecj_size as u64).and_then(|_| f.sync_all()));
// Bumped on attempt, not success: a failed rollback leaves the
// bytes in place and a decode re-reading for the epoch change
// simply sees them — harmless — while a successful one must
// never go unnoticed by an unlocked journal read.
ECJ_ROLLBACK_EPOCH.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
if let Err(trunc_err) = rollback {
tracing::error!(
volume_id = self.volume_id.0,
truncate_error = %trunc_err,
"failed to truncate ecj after append failure"
);
}
Err(e)
}
}
}
/// Internal: binary search .ecx without masking by `deleted_needles`.
@@ -2598,9 +2380,9 @@ impl EcVolume {
/// Fold a peer's deletion journal into this mounted volume: append only
/// the ids not already deleted here, in one write and one fsync, then
/// publish them into the in-memory set — the same commit order as
/// `journal_delete`. The journal lock serializes it with deletes, and the
/// live handle is appended to in place, so no delete can land in an
/// orphaned file. Returns how many ids were added.
/// `journal_delete`. `&mut self` serializes it with deletes under the store
/// lock, and the live handle is appended to in place, so no delete can land
/// in an orphaned file. Returns how many ids were added.
pub fn merge_journal(&mut self, ids: &HashSet<NeedleId>) -> io::Result<usize> {
let delta = super::ecj_merge::ecj_delta(ids, |id| self.is_needle_deleted(*id));
if delta.is_empty() {
@@ -2623,13 +2405,6 @@ impl EcVolume {
// ---- Lifecycle ----
/// Closes the journal handle under its lock, after any append in flight.
fn close_journal(&self) {
let mut journal = self.journal();
journal.file = None;
journal.closed = true;
}
pub fn close(&mut self) {
for shard in &mut self.shards {
if let Some(s) = shard {
@@ -2642,7 +2417,7 @@ impl EcVolume {
let _ = ecx_file.sync_all();
}
self.ecx_file = None;
self.close_journal();
self.ecj_file = None;
self.ecj_hold = None;
}
@@ -2704,17 +2479,11 @@ impl EcVolume {
let _ = crate::storage::erasure_coding::ec_bitrot::remove_bitrot_sidecars(&idx_base);
}
self.ecx_file = None;
self.close_journal();
self.ecj_file = None;
self.ecj_hold = None;
}
}
impl Drop for EcVolume {
fn drop(&mut self) {
self.close_journal();
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -3735,44 +3504,6 @@ mod tests {
assert!(deleted.contains(&NeedleId(7)));
}
/// Disks sharing one `.ecj` share its append lock: a delete through one
/// disk's handle waits while another disk's runtime reads or replaces the
/// file, so a fold or a mount never sees an append half done.
#[test]
fn test_sibling_holders_share_the_append_lock() {
let tmp = TempDir::new().unwrap();
let a_dir = tmp.path().join("a");
let b_dir = tmp.path().join("b");
std::fs::create_dir_all(&a_dir).unwrap();
std::fs::create_dir_all(&b_dir).unwrap();
let (a, b) = (a_dir.to_str().unwrap(), b_dir.to_str().unwrap());
let vid = VolumeId(49);
write_ecx_file(
a,
"",
vid,
&[(NeedleId(7), Offset::from_actual_offset(8), Size(10))],
);
let on_a = EcVolume::new(a, a, "", vid).unwrap();
let on_b = EcVolume::new(b, a, "", vid).unwrap();
assert_eq!(on_b.ecj_file_name(), on_a.ecj_file_name());
let path_lock = on_a.journal_path_lock();
let held = lock_path(&path_lock);
let appender = on_b.journal_appender();
let delete = std::thread::spawn(move || appender.journal_delete(NeedleId(7), || false));
std::thread::sleep(std::time::Duration::from_millis(100));
assert!(
!delete.is_finished(),
"a sibling's append must wait for the path lock"
);
drop(held);
delete.join().unwrap().unwrap();
assert!(on_b.is_needle_deleted(NeedleId(7)));
assert_eq!(on_a.read_deleted_needles().unwrap(), vec![NeedleId(7)]);
}
/// A copy appending to the journal by path must not have its bytes
/// dropped by a compaction renaming over the file.
#[test]
@@ -3803,33 +3534,6 @@ mod tests {
assert_eq!(vol.read_deleted_needles().unwrap(), ids);
}
/// A read hint revision taken from one instance of a volume must not let
/// a read forget the hint a later instance holds after a remount.
#[test]
fn test_read_hint_revision_is_not_shared_across_instances() {
let tmp = TempDir::new().unwrap();
let dir = tmp.path().to_str().unwrap();
let vid = VolumeId(50);
write_ecx_file(dir, "", vid, &[]);
let holder = "127.0.0.1:8080".to_string();
let delist = |vol: &EcVolume| {
vol.merge_shard_locations(HashMap::from([(0, vec![holder.clone()])]));
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
vol.shard_read_hints(0).unwrap().1
};
let old = EcVolume::new(dir, dir, "", vid).unwrap();
let revision = delist(&old);
drop(old);
let vol = EcVolume::new(dir, dir, "", vid).unwrap();
delist(&vol);
vol.forget_shard_read_hints(0, revision, std::slice::from_ref(&holder));
assert_eq!(
vol.shard_read_hints(0).map(|(hints, _)| hints),
Some(vec![holder])
);
}
/// A journal that grew, or was replaced, after it was loaded must not be
/// compacted from the stale set.
#[test]
@@ -3951,10 +3655,7 @@ mod tests {
write_bloated_ecj(dir, "", VolumeId(43), &ids, 4096);
let mut vol = EcVolume::new(dir, dir, "", VolumeId(43)).unwrap();
assert!(
vol.journal().file.is_some(),
"mount must leave a journal handle"
);
assert!(vol.ecj_file.is_some(), "mount must leave a journal handle");
let ecj_path = format!(
"{}.ecj",
@@ -5569,78 +5270,6 @@ mod tests {
later.unwrap() >= before,
"the second merge re-stamped the refresh time"
);
// A shard the master places nowhere is dropped, not kept at an address
// a delete would trust; its holder stays a place a read can ask first.
let merged = vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
assert_eq!(merged, HashMap::from([(1, vec!["c:3".to_string()])]));
let hint = || vol.shard_read_hints(0).map(|(hint, _)| hint);
let a = vec!["a:1".to_string()];
assert_eq!(hint(), Some(a.clone()));
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
assert_eq!(
hint(),
Some(a.clone()),
"a later reply placing the shard nowhere keeps the hint"
);
let (_, revision) = vol.shard_read_hints(0).unwrap();
vol.merge_shard_locations(HashMap::from([(0, a.clone())]));
assert_eq!(hint(), None);
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
vol.forget_shard_read_hints(0, revision, &a);
assert_eq!(
hint(),
Some(a.clone()),
"a failed read keeps a hint a lookup reinstalled meanwhile, even for the same holder"
);
let (_, revision) = vol.shard_read_hints(0).unwrap();
vol.forget_shard_read_hints(0, revision, &a);
assert_eq!(hint(), None);
vol.merge_shard_locations(HashMap::from([(0, vec!["e:5".into(), "f:6".into()])]));
vol.merge_shard_locations(HashMap::from([(0, Vec::new())]));
let (_, revision) = vol.shard_read_hints(0).unwrap();
vol.forget_shard_read_hints(0, revision, &["e:5".into()]);
assert_eq!(
hint(),
Some(vec!["f:6".to_string()]),
"only the holders that failed are forgotten"
);
}
#[test]
fn merge_partial_shard_locations_keeps_known_holders_and_refresh_time() {
let tmp = TempDir::new().unwrap();
let vol = mount_bare_ec_volume(tmp.path().to_str().unwrap());
let filled =
vol.merge_partial_shard_locations(HashMap::from([(0, vec!["a:1".to_string()])]));
assert_eq!(filled.get(&0), Some(&vec!["a:1".to_string()]));
assert!(
vol.shard_locations_snapshot().1.is_none(),
"a partial reply is not a refresh"
);
vol.merge_shard_locations(HashMap::from([(1, vec!["b:2".to_string()])]));
let stamped = vol.shard_locations_snapshot().1;
vol.claim_shard_locations_refresh(|_| true);
let filled = vol.merge_partial_shard_locations(HashMap::from([
(1, vec!["c:3".to_string()]),
(2, vec!["d:4".to_string()]),
(3, Vec::new()),
]));
assert_eq!(
filled.get(&1),
Some(&vec!["c:3".to_string(), "b:2".to_string()]),
"a holder the partial names goes first, the cached one stays as fallback"
);
assert_eq!(filled.get(&0), Some(&vec!["a:1".to_string()]));
assert_eq!(filled.get(&2), Some(&vec!["d:4".to_string()]));
assert!(!filled.contains_key(&3), "a partial reply's empty slot adds nothing");
assert_eq!(vol.shard_locations_snapshot().1, stamped);
assert!(
vol.claim_shard_locations_refresh(|stale| stale),
"the partial leaves the map marked for the next lookup"
);
}
/// The stale mark is consumed by the refresh that acts on it, exactly once:
@@ -32,7 +32,7 @@
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, LazyLock, Mutex, MutexGuard};
use std::sync::{Condvar, LazyLock, Mutex, MutexGuard};
#[derive(Default)]
struct PathState {
@@ -42,10 +42,6 @@ struct PathState {
/// Writers that have started on the path. Lives as long as the entry,
/// which a registered holder keeps.
write_gen: u64,
/// Serializes appends through every holder's handle with anything that
/// reads or replaces the file under a holder, as one disk's journal lock
/// covers only its own handle.
append_lock: Arc<Mutex<()>>,
}
impl PathState {
@@ -73,7 +69,7 @@ fn lock() -> MutexGuard<'static, HashMap<PathBuf, PathState>> {
/// Canonical key for `path`: its resolved parent directory joined with the
/// file name. The file itself may not exist yet (a copy creates it), so only
/// the directory is resolved.
pub(crate) fn key_for(path: &str) -> PathBuf {
fn key_for(path: &str) -> PathBuf {
let p = Path::new(path);
let (Some(parent), Some(name)) = (p.parent(), p.file_name()) else {
return std::path::absolute(p).unwrap_or_else(|_| p.to_path_buf());
@@ -122,7 +118,6 @@ pub(crate) struct EcjHold {
/// so they cover every write the load might have missed.
write_gen: u64,
writer_at_start: bool,
append_lock: Arc<Mutex<()>>,
}
impl EcjHold {
@@ -130,23 +125,17 @@ impl EcjHold {
/// progress so the handle opened afterwards is on the final inode.
pub(crate) fn acquire(ecj_path: &str) -> Self {
let key = key_for(ecj_path);
let (write_gen, writer_at_start, append_lock) = update_when_not_compacting(&key, |s| {
let (write_gen, writer_at_start) = update_when_not_compacting(&key, |s| {
s.holders += 1;
(s.write_gen, s.writers > 0, s.append_lock.clone())
(s.write_gen, s.writers > 0)
});
EcjHold {
key,
write_gen,
writer_at_start,
append_lock,
}
}
/// The path's append lock, shared by every holder of the path.
pub(crate) fn append_lock(&self) -> Arc<Mutex<()>> {
self.append_lock.clone()
}
/// Reserve the path for a compaction, or `None` when another holder or an
/// active writer could still reach the current inode, or when a writer
/// has run on the path since the hold was taken, so the journal may no
+28 -209
View File
@@ -292,20 +292,12 @@ impl Store {
// ---- Volume lifecycle ----
/// Find the location with the fewest writable volumes of `collection`, so
/// they do not share one disk's write bandwidth, then the most free slots
/// (load-balance) of the given disk type. Matches Go's FindFreeLocation:
/// accounts for EC shards when computing free slots.
fn find_free_location(
&self,
disk_type: &DiskType,
collection: &str,
preallocate: u64,
) -> Option<usize> {
/// Find the location with fewest volumes (load-balance) of the given disk type.
/// Matches Go's FindFreeLocation: accounts for EC shards when computing free slots.
fn find_free_location(&self, disk_type: &DiskType, preallocate: u64) -> Option<usize> {
use crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT;
let volume_size_limit = self.volume_size_limit.load(Ordering::Relaxed);
let mut best: Option<(usize, usize, i64)> = None; // (index, writable, effective_free)
let mut best: Option<(usize, i64)> = None; // (index, effective_free)
for (i, loc) in self.locations.iter().enumerate() {
if &loc.disk_type != disk_type {
continue;
@@ -335,14 +327,11 @@ impl Store {
) {
continue;
}
let writable = loc.writable_collection_volumes_len(collection, volume_size_limit);
if best.is_none_or(|(_, min_writable, max_free)| {
writable < min_writable || (writable == min_writable && effective_free > max_free)
}) {
best = Some((i, writable, effective_free));
if best.is_none() || effective_free > best.unwrap().1 {
best = Some((i, effective_free));
}
}
best.map(|(i, _, _)| i)
best.map(|(i, _)| i)
}
/// Find a free location matching a predicate.
@@ -478,10 +467,6 @@ impl Store {
/// their index files across disks of the same node and lose them at
/// startup. See seaweedfs/seaweedfs#9212.
///
/// A non-empty `required_disk_type` limits every step to disks of that
/// type, so a copy meant for one medium never lands beside the volume's
/// copy on another.
///
/// `data_shard_count` is taken as a parameter rather than read from
/// `DATA_SHARDS_COUNT` so custom-ratio builds can swap the default
/// without touching this helper.
@@ -495,7 +480,6 @@ impl Store {
collection: &str,
vid: VolumeId,
data_shard_count: u32,
required_disk_type: &str,
shard_ids: &[ShardId],
) -> Option<usize> {
const TIER_ANY_DISK: u8 = 1;
@@ -504,21 +488,14 @@ impl Store {
const TIER_MOUNTED: u8 = 4;
const TIER_OWNS_SHARD: u8 = 5;
let required =
(!required_disk_type.is_empty()).then(|| DiskType::from_string(required_disk_type));
// (index, tier, owned shard count, free shard slots)
let mut best: Option<(usize, u8, usize, i64)> = None;
for (i, loc) in self.locations.iter().enumerate() {
let owned = owned_ec_shard_count(loc, vid, shard_ids);
if loc.read_only_mount || required.as_ref().is_some_and(|t| loc.disk_type != *t) {
// An owner that cannot take the copy still owns the shard:
// placing another copy on a sibling would register it on two disks.
// A typed copy also yields to an unmounted file of the shard there,
// which a later mount would pick ahead of the copy.
if owned > 0
|| (required.is_some()
&& has_ec_shard_file_on_disk(loc, collection, vid, shard_ids))
{
if loc.read_only_mount {
// A read-only owner still owns the shard: placing another
// copy on a writable sibling would register it on two disks.
if owned > 0 {
return None;
}
continue;
@@ -624,7 +601,7 @@ impl Store {
return Err(VolumeError::AlreadyExists);
}
let loc_idx = self
.find_free_location(&disk_type, spec.collection, spec.preallocate)
.find_free_location(&disk_type, spec.preallocate)
.ok_or_else(|| {
VolumeError::Io(io::Error::other(format!(
"no free location for disk type {:?}",
@@ -1065,18 +1042,13 @@ impl Store {
}
/// Delete a needle from a volume.
pub fn delete_volume_needle(
&self,
vid: VolumeId,
n: &mut Needle,
fsync: bool,
) -> Result<Size, VolumeError> {
pub fn delete_volume_needle(&self, vid: VolumeId, n: &mut Needle) -> Result<Size, VolumeError> {
// Match Go's DeleteVolumeNeedle: check noWriteOrDelete before proceeding.
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
if vol.is_no_write_or_delete() {
return Err(VolumeError::ReadOnly(vid));
}
vol.delete_needle(n, fsync)
vol.delete_needle(n)
}
// ---- Collection operations ----
@@ -1375,19 +1347,6 @@ impl Store {
None
}
/// Takes the journal lock of every runtime of `vid`, in disk order, so no
/// delete append is in flight while the caller reads the journals.
pub(crate) fn lock_ec_journals(
&self,
vid: VolumeId,
) -> Vec<std::sync::MutexGuard<'_, crate::storage::erasure_coding::ec_volume::EcJournal>> {
self.locations
.iter()
.filter_map(|loc| loc.find_ec_volume(vid))
.map(|ecv| ecv.journal())
.collect()
}
/// Find an EC volume across all locations (mutable).
/// Every per-disk `EcVolume` this store maps for `vid`. A vid can mount on
/// N disks as N distinct runtimes, and the first-match `find_ec_volume_mut`
@@ -2112,19 +2071,6 @@ fn ec_free_shard_count(loc: &DiskLocation, data_shard_count: u32) -> i64 {
free
}
/// Whether `loc` holds a file for one of `shard_ids` of `vid`, mounted or not.
fn has_ec_shard_file_on_disk(
loc: &DiskLocation,
collection: &str,
vid: VolumeId,
shard_ids: &[ShardId],
) -> bool {
let base = crate::storage::volume::volume_file_name(&loc.directory, collection, vid);
shard_ids
.iter()
.any(|shard_id| std::path::Path::new(&format!("{}.ec{:02}", base, shard_id)).exists())
}
/// Reports how many of `shard_ids` this disk already claims for `vid`, per
/// the in-memory registration the read path and heartbeats use.
///
@@ -2977,9 +2923,7 @@ mod tests {
cookie: Cookie(0xaa),
..Needle::default()
};
let deleted = store
.delete_volume_needle(VolumeId(1), &mut del_n, false)
.unwrap();
let deleted = store.delete_volume_needle(VolumeId(1), &mut del_n).unwrap();
assert!(deleted.0 > 0);
}
@@ -3088,87 +3032,6 @@ mod tests {
assert_eq!(store.locations[1].volumes_len(), 1);
}
fn add_spread_test_volume(store: &mut Store, vid: u32, collection: &str) {
let spec = VolumeSpec {
collection,
..VolumeSpec::default()
};
store
.add_volume(VolumeId(vid), DiskType::HardDrive, &spec)
.unwrap();
}
fn location_of(store: &Store, vid: u32) -> Option<usize> {
store
.locations
.iter()
.position(|loc| loc.find_volume(VolumeId(vid)).is_some())
}
// Mirrors Go's TestAddVolumeSpreadsCollectionOverDisks.
#[test]
fn test_add_volume_spreads_collection_over_disks() {
let tmp1 = TempDir::new().unwrap();
let tmp2 = TempDir::new().unwrap();
let mut store =
make_test_store(&[tmp1.path().to_str().unwrap(), tmp2.path().to_str().unwrap()]);
add_spread_test_volume(&mut store, 1, "other");
add_spread_test_volume(&mut store, 2, "other");
add_spread_test_volume(&mut store, 3, "spread");
let first = location_of(&store, 3);
// Leave the disk with the "spread" volume holding fewer volumes overall.
let other_on_first = if first == Some(1) { 2 } else { 1 };
store
.delete_volume(VolumeId(other_on_first), false, false, false)
.unwrap();
add_spread_test_volume(&mut store, 4, "spread");
assert_ne!(location_of(&store, 4), first);
}
// Mirrors Go's TestAddVolumeIgnoresFullVolumesOfCollection.
#[test]
fn test_add_volume_ignores_full_volumes_of_collection() {
let tmp1 = TempDir::new().unwrap();
let tmp2 = TempDir::new().unwrap();
let mut store =
make_test_store(&[tmp1.path().to_str().unwrap(), tmp2.path().to_str().unwrap()]);
// Every .dat holds at least its superblock, so all volumes are full.
store.volume_size_limit.store(1, Ordering::Relaxed);
add_spread_test_volume(&mut store, 1, "spread");
let full_disk = location_of(&store, 1);
add_spread_test_volume(&mut store, 2, "other");
add_spread_test_volume(&mut store, 3, "spread");
assert_eq!(location_of(&store, 3), full_disk);
}
// Mirrors Go's TestAddVolumeIgnoresReadOnlyVolumesOfCollection.
#[test]
fn test_add_volume_ignores_read_only_volumes_of_collection() {
let tmp1 = TempDir::new().unwrap();
let tmp2 = TempDir::new().unwrap();
let mut store =
make_test_store(&[tmp1.path().to_str().unwrap(), tmp2.path().to_str().unwrap()]);
add_spread_test_volume(&mut store, 1, "spread");
let writable_disk = location_of(&store, 1);
add_spread_test_volume(&mut store, 2, "other");
add_spread_test_volume(&mut store, 3, "spread");
assert_ne!(location_of(&store, 3), writable_disk);
store
.find_volume(VolumeId(3))
.unwrap()
.1
.set_read_only()
.unwrap();
// The other disk holds more volumes, but its "spread" volume is read-only.
add_spread_test_volume(&mut store, 4, "spread");
assert_ne!(location_of(&store, 4), writable_disk);
}
#[test]
fn test_store_delete_collection() {
let tmp = TempDir::new().unwrap();
@@ -3537,7 +3400,7 @@ mod tests {
cookie: Cookie(2),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del, false).unwrap();
store.delete_volume_needle(vid, &mut del).unwrap();
let size_before = store.find_volume(vid).unwrap().1.dat_file_size().unwrap();
@@ -3861,7 +3724,7 @@ mod tests {
cookie: Cookie(2),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del, false).unwrap();
store.delete_volume_needle(vid, &mut del).unwrap();
let revision = {
let (_, v) = store.find_volume(vid).unwrap();
v.super_block().compaction_revision
@@ -3886,7 +3749,7 @@ mod tests {
cookie: Cookie(4),
..Needle::default()
};
store.delete_volume_needle(vid, &mut del, false).unwrap();
store.delete_volume_needle(vid, &mut del).unwrap();
drop(release_tx);
copy.join().unwrap().unwrap();
@@ -3959,7 +3822,7 @@ mod tests {
let base = volume_file_name(&store.locations[2].idx_directory, collection, vid);
std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap();
let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]);
let got = store.find_ec_shard_target_location(collection, vid, 10, &[]);
assert_eq!(
got,
Some(2),
@@ -4169,7 +4032,7 @@ mod tests {
let base = volume_file_name(&store.locations[2].idx_directory, collection, vid);
std::fs::write(format!("{}.ecx", base), vec![0u8; 20]).unwrap();
let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]);
let got = store.find_ec_shard_target_location(collection, vid, 10, &[]);
assert_eq!(
got,
Some(1),
@@ -4183,7 +4046,7 @@ mod tests {
#[test]
fn test_find_ec_shard_target_location_falls_through_to_hdd_when_nothing_matches() {
let (store, _tmp) = make_ec_target_test_store(2);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(3333), 10, "", &[]);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(3333), 10, &[]);
assert!(got.is_some(), "expected an HDD fallback");
assert_eq!(store.locations[got.unwrap()].disk_type, DiskType::HardDrive);
}
@@ -4199,7 +4062,7 @@ mod tests {
.max_volume_count
.store(0, Ordering::Relaxed);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(4444), 10, "", &[]);
let got = store.find_ec_shard_target_location("grafana-loki", VolumeId(4444), 10, &[]);
assert_eq!(
got,
Some(0),
@@ -4248,7 +4111,7 @@ mod tests {
.mount_ec_shards(vid, collection, &[0], "")
.unwrap();
let got = store.find_ec_shard_target_location(collection, vid, 10, "", &[]);
let got = store.find_ec_shard_target_location(collection, vid, 10, &[]);
assert_eq!(
got,
Some(1),
@@ -4290,68 +4153,24 @@ mod tests {
.unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "", &[0]),
store.find_ec_shard_target_location(collection, vid, 10, &[0]),
Some(0),
"a copy of shard 0 left its owning disk",
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "", &[2]),
store.find_ec_shard_target_location(collection, vid, 10, &[2]),
Some(1),
"a copy of shard 2 left its owning disk",
);
// A shard no disk owns yet is placed by the unchanged waterfall: both
// disks have it mounted, so the emptier one wins.
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "", &[7]),
store.find_ec_shard_target_location(collection, vid, 10, &[7]),
Some(1),
"placement of an unclaimed shard changed",
);
}
/// A copy that names a disk type skips the other medium even when that
/// disk has the EC volume mounted, and refuses rather than split a shard
/// another medium already owns.
#[test]
fn test_find_ec_shard_target_location_required_disk_type() {
let (mut store, _tmp) = make_ec_target_test_store(2);
store.locations[0].disk_type = DiskType::Ssd;
store.locations[1].disk_type = DiskType::from_string("hdd_ht");
let collection = "grafana-loki";
let vid = VolumeId(5555);
let base0 = volume_file_name(&store.locations[0].directory, collection, vid);
std::fs::write(format!("{}.ec00", base0), b"x").unwrap();
std::fs::write(format!("{}.ec01", base0), b"x").unwrap();
std::fs::write(format!("{}.ecx", base0), vec![0u8; 20]).unwrap();
store.locations[0]
.mount_ec_shards(vid, collection, &[0, 1], "")
.unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "", &[2]),
Some(0)
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[2]),
Some(1),
"a hdd_ht copy landed off the hdd_ht disk",
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[1]),
None,
"a shard the ssd disk owns must not get a second claim on hdd_ht",
);
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd", &[2]),
None
);
std::fs::write(format!("{}.ec03", base0), b"x").unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "hdd_ht", &[3]),
None,
"an unmounted shard file on ssd would be mounted ahead of a hdd_ht copy",
);
}
/// The second half of the invariant: a disk with no free shard slots
/// still wins for a shard it already owns. Re-copying that shard
/// overwrites bytes the disk is already accounted for, while routing to a
@@ -4386,13 +4205,13 @@ mod tests {
.unwrap();
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "", &[0]),
store.find_ec_shard_target_location(collection, vid, 10, &[0]),
Some(0),
"a copy of shard 0 left its owning disk when the disk was full",
);
// A shard it does not own still respects the space filter.
assert_eq!(
store.find_ec_shard_target_location(collection, vid, 10, "", &[7]),
store.find_ec_shard_target_location(collection, vid, 10, &[7]),
Some(1),
"an unclaimed shard should go to the disk with free slots",
);
+11 -24
View File
@@ -36,14 +36,10 @@ impl Store {
/// `reconcile_ec_shards_across_disks` so the orphan pass can
/// prefer the local idx_directory.
pub fn mirror_ec_metadata_to_shard_disks(&mut self) {
self.mirror_ec_metadata_to_shard_disks_only(None)
}
pub(crate) fn mirror_ec_metadata_to_shard_disks_only(&mut self, only: Option<VolumeId>) {
if self.locations.len() < 2 {
return;
}
let owners = self.index_ecx_owners_for_mirror(only);
let owners = self.index_ecx_owners_for_mirror();
if owners.is_empty() {
return;
}
@@ -58,7 +54,7 @@ impl Store {
}
let mut mirrors: Vec<Mirror> = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let orphans = collect_shard_disk_volumes(loc, only);
let orphans = collect_shard_disk_volumes(loc);
for (key, _shards) in orphans {
let Some(owner) = owners.get(&key) else {
continue;
@@ -117,7 +113,7 @@ impl Store {
// Records both idx_dir (where .ecx was found) and data_dir, so
// the mirror can resolve .vif from data_dir even when .ecx lives
// in idx_directory.
fn index_ecx_owners_for_mirror(&self, only: Option<VolumeId>) -> HashMap<EcKey, EcxOwner> {
fn index_ecx_owners_for_mirror(&self) -> HashMap<EcKey, EcxOwner> {
let mut owners: HashMap<EcKey, EcxOwner> = HashMap::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let mut seen: Vec<&str> = Vec::with_capacity(2);
@@ -137,18 +133,15 @@ impl Store {
let Some(base) = name.strip_suffix(".ecx") else {
continue;
};
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
// A 0-byte .ecx is a corrupt stub from a failed copy, not a
// credible owner — skip it so the scan keeps looking for a
// real index on a sibling disk (Go's indexEcxOwners).
if !ent.metadata().is_ok_and(|m| m.len() > 0) {
continue;
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
owners
.entry(EcKey { collection, vid })
.or_insert_with(|| EcxOwner {
@@ -304,10 +297,7 @@ fn copy_sidecar_atomic(src: &Path, dst: &Path) -> io::Result<()> {
Ok(())
}
fn collect_shard_disk_volumes(
loc: &DiskLocation,
only: Option<VolumeId>,
) -> HashMap<EcKey, Vec<String>> {
fn collect_shard_disk_volumes(loc: &DiskLocation) -> HashMap<EcKey, Vec<String>> {
let mut out: HashMap<EcKey, Vec<String>> = HashMap::new();
let Ok(read) = fs::read_dir(&loc.directory) else {
return out;
@@ -324,16 +314,13 @@ fn collect_shard_disk_volumes(
if crate::storage::disk_location::is_ec_shard_extension(ext).is_none() {
continue;
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
match ent.metadata() {
Ok(meta) if meta.len() > 0 => {}
_ => continue,
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
out.entry(EcKey { collection, vid }).or_default().push(name);
}
out
@@ -701,7 +688,7 @@ mod tests {
add_loc(&mut store, &dir0);
add_loc(&mut store, &dir1);
let owners = store.index_ecx_owners_for_mirror(None);
let owners = store.index_ecx_owners_for_mirror();
let owner = owners
.get(&EcKey {
collection: collection.to_string(),
+18 -115
View File
@@ -92,15 +92,11 @@ impl Store {
///
/// Mirrors `Store.reconcileEcShardsAcrossDisks` in Go.
pub fn reconcile_ec_shards_across_disks(&mut self) {
self.reconcile_ec_shards_across_disks_only(None)
}
pub(crate) fn reconcile_ec_shards_across_disks_only(&mut self, only: Option<VolumeId>) {
if self.locations.len() < 2 {
return;
}
let owners = self.index_ecx_owners(only);
let owners = self.index_ecx_owners();
if owners.is_empty() {
return;
}
@@ -110,7 +106,7 @@ impl Store {
// loc.idx_directory instead of the owner disk.
let mut to_load: Vec<OrphanShardLoad> = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let orphans = collect_orphan_ec_shards(loc, loc_idx, only);
let orphans = collect_orphan_ec_shards(loc, loc_idx);
for (key, shards) in orphans {
let Some(owner) = owners.get(&key) else {
warn!(
@@ -406,7 +402,7 @@ impl Store {
/// matched so downstream loaders point `EcVolume::new` at the
/// directory that really has the file. The first owner found wins;
/// duplicates across disks are unusual but tolerated.
fn index_ecx_owners(&self, only: Option<VolumeId>) -> HashMap<EcKey, EcxOwnerInfo> {
fn index_ecx_owners(&self) -> HashMap<EcKey, EcxOwnerInfo> {
let mut owners: HashMap<EcKey, EcxOwnerInfo> = HashMap::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
let mut seen: Vec<&str> = Vec::with_capacity(2);
@@ -426,18 +422,15 @@ impl Store {
let Some(base) = name.strip_suffix(".ecx") else {
continue;
};
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
// A 0-byte .ecx is a corrupt stub from a failed copy, not a
// credible owner — skip it so the scan keeps looking for a
// real index on a sibling disk (Go's indexEcxOwners).
if !ent.metadata().is_ok_and(|m| m.len() > 0) {
continue;
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
let key = EcKey { collection, vid };
owners.entry(key).or_insert(EcxOwnerInfo {
location: loc_idx,
@@ -457,18 +450,11 @@ impl Store {
///
/// Mirrors `Store.CollectEcVolumesMissingIndex` in Go.
pub(crate) fn collect_ec_volumes_missing_index(&self) -> Vec<EcVolumeMissingIndex> {
self.collect_ec_volumes_missing_index_only(None)
}
pub(crate) fn collect_ec_volumes_missing_index_only(
&self,
only: Option<VolumeId>,
) -> Vec<EcVolumeMissingIndex> {
let owners = self.index_ecx_owners(only);
let owners = self.index_ecx_owners();
let mut seen: HashSet<EcKey> = HashSet::new();
let mut missing = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
for (key, _shards) in collect_orphan_ec_shards(loc, loc_idx, only) {
for (key, _shards) in collect_orphan_ec_shards(loc, loc_idx) {
if owners.contains_key(&key) || !seen.insert(key.clone()) {
continue;
}
@@ -488,24 +474,18 @@ impl Store {
/// the disks that now have a local index, then fall back to the cross-disk
/// virtual mount. Mirrors `Store.MountRecoveredEcShards` in Go.
pub(crate) fn mount_recovered_ec_shards(&mut self) {
self.mount_recovered_ec_shards_only(None)
}
/// `mount_recovered_ec_shards` restricted to one volume's shards when
/// `only` names it.
pub(crate) fn mount_recovered_ec_shards_only(&mut self, only: Option<VolumeId>) {
self.mirror_ec_metadata_to_shard_disks_only(only);
self.load_orphan_ec_shards_with_local_index(only);
self.reconcile_ec_shards_across_disks_only(only);
self.mirror_ec_metadata_to_shard_disks();
self.load_orphan_ec_shards_with_local_index();
self.reconcile_ec_shards_across_disks();
}
/// Mount on-disk EC shards whose `.ecx` index is now present on the same disk.
/// Unlike `reconcile_ec_shards_across_disks` it needs no sibling disk, so a
/// single-disk store recovers once its index has been fetched from a peer.
fn load_orphan_ec_shards_with_local_index(&mut self, only: Option<VolumeId>) {
fn load_orphan_ec_shards_with_local_index(&mut self) {
let mut work: Vec<(usize, EcKey, Vec<ShardId>)> = Vec::new();
for (loc_idx, loc) in self.locations.iter().enumerate() {
for (key, shards) in collect_orphan_ec_shards(loc, loc_idx, only) {
for (key, shards) in collect_orphan_ec_shards(loc, loc_idx) {
if !loc.has_ecx_file_on_disk(&key.collection, key.vid) {
continue;
}
@@ -536,7 +516,6 @@ impl Store {
fn collect_orphan_ec_shards(
loc: &crate::storage::disk_location::DiskLocation,
_loc_idx: usize,
only: Option<VolumeId>,
) -> HashMap<EcKey, Vec<(String, ShardId)>> {
let mut orphans: HashMap<EcKey, Vec<(String, ShardId)>> = HashMap::new();
let Ok(read) = fs::read_dir(&loc.directory) else {
@@ -554,12 +533,6 @@ fn collect_orphan_ec_shards(
let Some(shard_id) = is_ec_shard_extension(ext) else {
continue;
};
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
if only.is_some_and(|o| o != vid) {
continue;
}
// Ignore zero-byte shards. Use the DirEntry's metadata so we
// don't pay a second stat syscall per file beyond what
// read_dir already returned.
@@ -567,6 +540,9 @@ fn collect_orphan_ec_shards(
Ok(meta) if meta.len() > 0 => {}
_ => continue,
}
let Some((collection, vid)) = parse_collection_volume_id_pub(base) else {
continue;
};
// Skip shards that are already registered to an EcVolume.
if let Some(ecv) = loc.find_ec_volume(vid)
&& ecv.has_shard(shard_id)
@@ -679,7 +655,7 @@ mod tests {
std::fs::write(ec_local_ecx_path(&d0, "pics", VolumeId(7)), b"").unwrap();
write_index_files(&d1, "pics", 7, 10, 4);
let owners = store.index_ecx_owners(None);
let owners = store.index_ecx_owners();
let owner = owners
.get(&EcKey {
collection: "pics".to_string(),
@@ -691,7 +667,7 @@ mod tests {
// A stub with no real index anywhere owns nothing.
std::fs::write(ec_local_ecx_path(&d0, "pics", VolumeId(8)), b"").unwrap();
assert!(!store.index_ecx_owners(None).contains_key(&EcKey {
assert!(!store.index_ecx_owners().contains_key(&EcKey {
collection: "pics".to_string(),
vid: VolumeId(8),
}));
@@ -1264,79 +1240,6 @@ mod tests {
);
}
#[test]
fn test_mount_recovered_ec_shards_only_named_volume() {
// Recovering one volume mounts only its shards. Another volume's orphan
// shards, such as ones an in-flight copy just renamed in, stay unmounted
// even when an index for them is already on disk. Mirrors Go
// TestMountRecoveredEcShards_OnlyNamedVolume.
let tmp = TempDir::new().unwrap();
let dir0 = tmp.path().join("data0");
let dir1 = tmp.path().join("data1");
std::fs::create_dir_all(&dir0).unwrap();
std::fs::create_dir_all(&dir1).unwrap();
let collection = "col";
let (recovered_vid, other_vid) = (71u32, 72u32);
let mut store = Store::new(NeedleMapKind::InMemory);
for d in [&dir0, &dir1] {
store
.add_location(
d.to_str().unwrap(),
d.to_str().unwrap(),
100,
DiskType::HardDrive,
MinFreeSpace::Percent(0.0),
Vec::new(),
)
.unwrap();
}
for vid in [recovered_vid, other_vid] {
write_shard(dir0.to_str().unwrap(), collection, vid, 0);
write_shard(dir1.to_str().unwrap(), collection, vid, 1);
}
write_index_files(dir0.to_str().unwrap(), collection, other_vid, 10, 4);
let missing = store.collect_ec_volumes_missing_index();
let m = missing
.iter()
.find(|m| m.vid == VolumeId(recovered_vid))
.expect("recovered volume not reported as missing its index");
write_index_files(&m.idx_dir, collection, recovered_vid, 10, 4);
store.mount_recovered_ec_shards_only(Some(VolumeId(recovered_vid)));
for (i, loc) in store.locations.iter().enumerate() {
let ev = loc
.find_ec_volume(VolumeId(recovered_vid))
.unwrap_or_else(|| panic!("volume {} not mounted on disk{}", recovered_vid, i));
assert!(
ev.has_shard(i as u8),
"shard {}.{} not mounted",
recovered_vid,
i
);
assert!(
loc.find_ec_volume(VolumeId(other_vid)).is_none(),
"volume {} mounted on disk{} by the recovery of volume {}",
other_vid,
i,
recovered_vid,
);
}
let mirrored = format!(
"{}/{}_{}.ecx",
dir1.to_str().unwrap(),
collection,
other_vid
);
assert!(
!std::path::Path::new(&mirrored).exists(),
"volume {} index mirrored to disk1 by the recovery of volume {}",
other_vid,
recovered_vid,
);
}
#[test]
fn test_collect_missing_index_excludes_cross_disk_orphan() {
// A .ecx merely on a sibling disk is the same-server case the reconcile
File diff suppressed because it is too large. Load diff
@@ -188,7 +188,7 @@ mod tests {
for id in 1..=3 {
v.write_needle(&mut needle(id), true, false).unwrap();
}
v.delete_needle(&mut needle(2), false).unwrap();
v.delete_needle(&mut needle(2)).unwrap();
v.sync_to_disk().unwrap();
let (want_count, want_deleted) = (v.file_count(), v.deleted_count());
drop(v);
@@ -382,13 +382,10 @@ pub(crate) mod tests {
write_test_volume(dir, 6);
let v = open_volume(dir);
v.delete_needle(
&mut Needle {
id: NeedleId(3),
..Needle::default()
},
false,
)
v.delete_needle(&mut Needle {
id: NeedleId(3),
..Needle::default()
})
.unwrap();
drop(v);
@@ -420,13 +417,10 @@ pub(crate) mod tests {
write_test_volume(dir, 8);
let v = open_volume(dir);
v.delete_needle(
&mut Needle {
id: NeedleId(2),
..Needle::default()
},
false,
)
v.delete_needle(&mut Needle {
id: NeedleId(2),
..Needle::default()
})
.unwrap();
drop(v);
@@ -505,13 +505,10 @@ mod tests {
f.written.insert(*id, n.data.clone());
}
Op::Del(id) => {
v.delete_needle(
&mut Needle {
id: NeedleId(*id),
..Needle::default()
},
false,
)
v.delete_needle(&mut Needle {
id: NeedleId(*id),
..Needle::default()
})
.unwrap();
}
Op::Empty(id) => {
-118
View File
@@ -110,7 +110,6 @@ fn build_test_state(
vacuum_commit_slots: None,
vacuum_commits_waiting: std::sync::atomic::AtomicU32::new(0),
is_heartbeating: std::sync::atomic::AtomicBool::new(true),
ec_lifecycle_locks: std::sync::Mutex::new(std::collections::HashMap::new()),
ec_decodes_in_flight: std::sync::Mutex::new(std::collections::HashSet::new()),
volume_copies_in_flight: std::sync::Arc::new(std::sync::Mutex::new(std::collections::HashSet::new())),
ec_decode_tail: std::sync::Mutex::new(std::collections::HashSet::new()),
@@ -1436,120 +1435,3 @@ async fn write_queue_upload_returns_same_etag_as_direct_write() {
}
assert_eq!(etags[1], etags[0], "unchanged upload ETag differs");
}
// ============================================================================
// A Range over a compressed needle is answered from the decoded bytes
// ============================================================================
#[tokio::test]
async fn range_with_accept_gzip_on_compressed_needle_serves_decoded_bytes() {
let (state, _tmp) = test_state();
let uri = "/1/03637037d6/notes.txt";
let plain: Vec<u8> = (0..400)
.flat_map(|i| format!("line {i:06}: the quick brown fox\n").into_bytes())
.collect();
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri(uri)
.body(Body::from(plain.clone()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
let read = |range: Option<&str>| {
let mut request = Request::builder()
.uri(uri)
.header("Accept-Encoding", "gzip");
if let Some(range) = range {
request = request.header("Range", range);
}
build_admin_router(state.clone()).oneshot(request.body(Body::empty()).unwrap())
};
// The whole read passes the stored gzip through, so its length is the compressed size.
let response = read(None).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(response.headers()["Content-Encoding"], "gzip");
let compressed_len = body_bytes(response).await.len();
assert!(compressed_len < plain.len() / 4);
for (start, end) in [(10, 69), (compressed_len + 10, compressed_len + 69)] {
let response = read(Some(&format!("bytes={start}-{end}"))).await.unwrap();
assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT);
assert!(response.headers().get("Content-Encoding").is_none());
assert_eq!(
response.headers()["Content-Range"],
format!("bytes {start}-{end}/{}", plain.len()).as_str()
);
assert_eq!(body_bytes(response).await, &plain[start..=end]);
}
}
// ============================================================================
// HEAD of a compressed needle reports the length the matching GET would send
// ============================================================================
#[tokio::test]
async fn head_on_compressed_needle_reports_served_length() {
let (state, _tmp) = test_state();
let uri = "/1/04637037d6/notes.txt";
let plain: Vec<u8> = (0..400)
.flat_map(|i| format!("line {i:06}: the quick brown fox\n").into_bytes())
.collect();
let app = build_admin_router(state.clone());
let response = app
.oneshot(
Request::builder()
.method("POST")
.uri(uri)
.body(Body::from(plain.clone()))
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::CREATED);
let send = |method: &str, accept_gzip: bool, range: Option<&str>| {
let mut request = Request::builder().method(method).uri(uri);
if accept_gzip {
request = request.header("Accept-Encoding", "gzip");
}
if let Some(range) = range {
request = request.header("Range", range);
}
build_admin_router(state.clone()).oneshot(request.body(Body::empty()).unwrap())
};
let response = send("GET", true, None).await.unwrap();
let compressed_len = body_bytes(response).await.len();
assert!(compressed_len < plain.len() / 4);
for (accept_gzip, range, encoding, length) in [
(false, None, None, plain.len()),
(true, None, Some("gzip"), compressed_len),
(true, Some("bytes=0-9"), None, plain.len()),
] {
let response = send("HEAD", accept_gzip, range).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(
response
.headers()
.get("Content-Encoding")
.map(|v| v.to_str().unwrap()),
encoding,
"accept_gzip={accept_gzip} range={range:?}"
);
assert_eq!(
response.headers()["Content-Length"],
length.to_string().as_str(),
"accept_gzip={accept_gzip} range={range:?}"
);
}
}
-4
View File
@@ -7157,7 +7157,6 @@ dependencies = [
"arrow-array",
"arrow-cast",
"arrow-schema",
"arrow-select",
"async-trait",
"base64 0.22.1",
"bytes",
@@ -7171,10 +7170,8 @@ dependencies = [
"hmac 0.12.1",
"http 1.5.0",
"hyper-util",
"jsonb",
"jsonwebtoken",
"lance",
"lance-arrow",
"lance-datafusion",
"lance-index",
"lance-linalg",
@@ -7206,7 +7203,6 @@ dependencies = [
"tower",
"tracing",
"tracing-subscriber",
"uuid",
"x509-parser",
"zstd",
]
+8 -10
View File
@@ -35,10 +35,7 @@ binary for the runner's platform, resolved from the version in `Cargo.lock`.
## Running
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535
Admin is all it needs, as with `weed worker`: every request admin sends names
the filers, and the Lance Namespaces the S3 gateways serve.
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333
The admin's *HTTP* address is what an operator has; the gRPC port is derived
from it the way the Go side does. Dialling the HTTP port fails as "frame with
@@ -52,7 +49,7 @@ Released builds do not need a toolchain. The worker ships inside the SeaweedFS
image, beside the Rust volume server, under the verb that mirrors
`volume-rust`:
docker run chrislusf/seaweedfs worker-rust --admin admin:12535
docker run chrislusf/seaweedfs worker-rust --admin admin:12535 --masters master:9333
and as `weed-worker_linux_{amd64,arm64}.tar.gz` on each GitHub release. Both are
linux amd64/arm64 only — lance, arrow and datafusion make every extra target an
@@ -62,7 +59,7 @@ entrypoint says so rather than failing as "not found".
## Metrics
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --metrics-port 9328
cargo run -p weed-lance-worker -- --admin 127.0.0.1:12535 --masters 127.0.0.1:9333 --metrics-port 9328
Serves `/health`, `/ready` and `/metrics` on that port, the same three the Go
worker serves under `weed worker -metricsPort`, so one scrape config covers
@@ -93,8 +90,9 @@ running but is not going to do anything.
## Credentials
The worker holds no S3 credentials. The namespace tells it where a table is;
its files are read and written on the cluster's filers, which admin names, and
volume servers. What that takes comes from the same security.toml the weed processes use:
its files are read and written on the cluster's filers and volume servers,
which `--masters` names the masters of (`--filer-group` picks the filers). What
that takes comes from the same security.toml the weed processes use:
`grpc.client` for the filers, `https.client` for volume servers under HTTPS,
`jwt.signing.read.key` where volume reads are signed, and `s3.sse.kek` or
`s3.sse.key` where a bucket encrypts with SSE-S3. Chunks are encrypted for the
@@ -118,8 +116,8 @@ All three jobs are implemented and tested end to end against a live gateway:
`cargo test -p weed-lance-worker` runs them when `WEED_LANCE_NAMESPACE` names a
live namespace and skips otherwise, the way the Go integration tests skip
without Docker. A live namespace needs `WEED_FILER` naming its cluster's
filer as the master lists it (`host:port.grpc`), and `WEED_JWT_FILER_SIGNING_KEY` (or security.toml) where the
without Docker. A live namespace needs `WEED_MASTERS` naming its cluster's
masters, and `WEED_JWT_FILER_SIGNING_KEY` (or security.toml) where the
namespace authenticates cluster processes; the tests fail without the first
and are refused without the second. Each test seeds the table it needs, including building a vector
index and then appending rows outside it, so a run does not depend on what the
+1 -1
View File
@@ -26,6 +26,6 @@ pub mod pb {
pub use config::{TlsOptions, WorkerOptions};
pub use metrics::Metrics;
pub use registry::{ClusterObserver, JobHandler, Preview, PreviewProvider, Registry};
pub use registry::{JobHandler, Preview, PreviewProvider, Registry};
pub use senders::{DetectionSender, ExecutionSender};
pub use stream::run;
+1 -60
View File
@@ -4,9 +4,7 @@ use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use crate::pb::{
ClusterContext, ExecuteJobRequest, JobTypeCapability, JobTypeDescriptor, RunDetectionRequest,
};
use crate::pb::{ExecuteJobRequest, JobTypeCapability, JobTypeDescriptor, RunDetectionRequest};
use crate::senders::{DetectionSender, ExecutionSender};
/// One job type, worker side. Mirrors the Go JobHandler interface in
@@ -49,20 +47,12 @@ pub trait PreviewProvider: Send + Sync {
async fn preview(&self, object_id: &[String], row_limit: usize) -> Result<Preview>;
}
/// Learns the cluster from admin, which describes it on every request, as the
/// Go worker reads request.ClusterContext. Runs before the request's handler.
#[async_trait]
pub trait ClusterObserver: Send + Sync {
async fn observe(&self, cluster: &ClusterContext);
}
/// The handlers one worker process serves. A process may serve several job
/// types, which is why WorkerHello carries a list of capabilities.
#[derive(Default, Clone)]
pub struct Registry {
handlers: HashMap<String, Arc<dyn JobHandler>>,
previews: HashMap<String, Arc<dyn PreviewProvider>>,
observer: Option<Arc<dyn ClusterObserver>>,
}
impl Registry {
@@ -81,18 +71,6 @@ impl Registry {
self
}
pub fn with_cluster_observer(mut self, observer: Arc<dyn ClusterObserver>) -> Self {
self.observer = Some(observer);
self
}
/// Hands a request's cluster context to the observer, if both exist.
pub async fn observe(&self, cluster: Option<&ClusterContext>) {
if let (Some(observer), Some(cluster)) = (&self.observer, cluster) {
observer.observe(cluster).await;
}
}
pub fn get(&self, job_type: &str) -> Option<Arc<dyn JobHandler>> {
self.handlers.get(job_type).cloned()
}
@@ -109,40 +87,3 @@ impl Registry {
self.handlers.is_empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Mutex;
#[derive(Default)]
struct Seen(Mutex<Vec<Vec<String>>>);
#[async_trait]
impl ClusterObserver for Seen {
async fn observe(&self, cluster: &ClusterContext) {
self.0.lock().unwrap().push(cluster.filer_addresses.clone());
}
}
#[tokio::test]
async fn observe_hands_the_context_to_the_observer() {
let seen = Arc::new(Seen::default());
let registry = Registry::new().with_cluster_observer(seen.clone());
registry
.observe(Some(&ClusterContext {
filer_addresses: vec!["f1:8888.18888".into()],
..Default::default()
}))
.await;
// An older admin, or a request without one, has nothing to say.
registry.observe(None).await;
Registry::new()
.observe(Some(&ClusterContext::default()))
.await;
assert_eq!(
*seen.0.lock().unwrap(),
vec![vec!["f1:8888.18888".to_string()]]
);
}
}
+2 -39
View File
@@ -3,7 +3,7 @@ use tokio::sync::mpsc;
use crate::pb::{
ActivityEvent, DetectionComplete, DetectionProposals, JobCompleted, JobProgressUpdate,
JobState, WorkerObservations, WorkerToAdminMessage, worker_to_admin_message::Body,
WorkerObservations, WorkerToAdminMessage, worker_to_admin_message::Body,
};
/// Replies to one detection request.
@@ -65,12 +65,7 @@ impl DetectionSender for StreamSender {
}
impl ExecutionSender for StreamSender {
fn send_progress(&self, mut progress: JobProgressUpdate) -> Result<()> {
// the Go handlers always report a state; older admins read a missing
// one as an ended job and drop its completion
if progress.state == JobState::Unspecified as i32 {
progress.state = JobState::Running as i32;
}
fn send_progress(&self, progress: JobProgressUpdate) -> Result<()> {
self.send(Body::JobProgressUpdate(progress))
}
@@ -205,36 +200,4 @@ mod tests {
.expect("send");
assert!(metered.reported_failure());
}
#[test]
fn progress_without_a_state_is_sent_as_running() {
let (tx, mut rx) = mpsc::unbounded_channel();
let stream = StreamSender::new("worker-1".to_string(), tx);
let metered = MeteredSender::new(&stream);
metered
.send_progress(JobProgressUpdate {
progress_percent: 10.0,
..Default::default()
})
.expect("send");
metered
.send_progress(JobProgressUpdate {
state: JobState::Failed as i32,
..Default::default()
})
.expect("send");
let mut states = Vec::new();
while let Ok(message) = rx.try_recv() {
let Some(Body::JobProgressUpdate(progress)) = message.body else {
panic!("expected a progress update");
};
states.push(progress.state);
}
assert_eq!(
states,
vec![JobState::Running as i32, JobState::Failed as i32]
);
}
}
-3
View File
@@ -288,7 +288,6 @@ fn spawn_preview(
) {
tokio::spawn(async move {
let limit = request.row_limit.max(1) as usize;
registry.observe(request.cluster_context.as_ref()).await;
let response = match registry.preview_provider(&request.format) {
None => ObjectPreviewResponse {
request_id,
@@ -377,7 +376,6 @@ fn spawn_detection(
// Held until the sweep finishes, so the worker keeps to the capacity it
// advertised and the heartbeat reports the truth while it works.
let _permit = slots.detection.acquire().await;
registry.observe(request.cluster_context.as_ref()).await;
let metered = MeteredSender::new(&sender);
let started = Instant::now();
let outcome = handler.detect(&request, &metered).await;
@@ -431,7 +429,6 @@ fn spawn_execution(
let Some(handler) = registry.get(&job_type) else {
return;
};
registry.observe(request.cluster_context.as_ref()).await;
let metered = MeteredSender::new(&sender);
let started = Instant::now();
let outcome = handler.execute(&request, &metered).await;
+1 -8
View File
@@ -35,16 +35,10 @@ lance-table = "10"
# For the execution options the sort needs; the scanner's own stream helper
# takes the default, which has spilling off.
lance-datafusion = "10"
arrow-array = "58"
arrow-schema = "58"
arrow-cast = "58"
arrow-select = "58"
# Lance's stored form of the metadata JSON, read when deriving the
# indexed-key columns.
jsonb = { version = "0.5", default-features = false }
chrono = "0.4"
futures = "0.3"
uuid = "1"
anyhow.workspace = true
async-trait.workspace = true
clap = { version = "4", features = ["derive", "env"] }
@@ -94,10 +88,9 @@ protoc-bin-vendored = "3"
[dev-dependencies]
tokio = { workspace = true, features = ["test-util"] }
tonic.workspace = true
lance-arrow = "10"
arrow-array = "58"
arrow-schema = "58"
arrow-cast = "58"
arrow-select = "58"
lance-linalg = "10"
tempfile = "3"
Loaded 100 of 717 files, more files were not shown because too many files have changed in this diff. Show more