Documentation
¶
Overview ¶
Package storeguard is the store-agnostic engine for surviving a corrupt BadgerDB directory on a path that must not be allowed to kill the process.
WHY THIS EXISTS ¶
Culvert opens more than one BadgerDB directory on the data volume, and every one of them shares two properties that make the combination dangerous for an in-line gateway:
- badger.Open does not always return an error. A corrupted `.sst` table makes it PANIC from a goroutine badger itself spawns (table.OpenTable ← newLevelsController), so no recover() at any call site can contain it — the process dies. Verified empirically against badger v4.9.6 for BOTH stores' option sets (see `roadmap/CHAOS-ENGINEERING-REVIEW.md` §19.3 and §25.2).
- Every other open failure it DOES return (torn MANIFEST, bad magic, missing table, KEYREGISTRY damage) is unrecoverable by retrying: the directory stays broken across restarts.
Left alone, either one turns "one unclean kill of the container" into a permanent refusal to run. The CHAOS-05/07 contract established the right rule for corrupt state on the boot path — quarantine the evidence, do not overwrite it, and keep going — and this package carries that rule for any store whose failure mode badger will not let us catch.
This code shipped first as `internal/catdb/resilient.go` (CHAOS-50) for the Layer-2 community category store. CHAOS-62 extracted it here unchanged so the request-history store (`internal/logstore`) could reuse it. The alternative — a second copy — would have duplicated the empirically-derived badger message table, which is exactly the artefact that must never drift: it is pinned by a test precisely so that a badger upgrade which rewords a message fails the build instead of silently switching recovery off.
HOW ¶
Every open attempt arms its OWN marker file beside the directory and holds an flock on it for the duration of the attempt. A marker whose flock can be taken belongs to a process that is gone — the kernel releases flocks on death — so it means exactly one thing: that process entered badger.Open on this directory and never came back out. That is the only signal available for the uncatchable-panic case, and it also covers a SIGKILL/OOM landing inside Open. On that signal the directory is quarantined BEFORE badger is allowed near it again, so the second start succeeds where the first one died.
The marker is per-attempt and flock-owned rather than a single shared path because a shared one cannot survive concurrency: a second process starting while the first is still inside Open would clear the first process's breadcrumb, and if the first then hit the panic, nothing would be left for the next start to act on — the crash loop would persist through the very mechanism meant to break it.
Quarantine is deliberately hard to trigger:
- a RETURNED error quarantines only when it is positively identified as corruption. Environmental failures (another process holds the store, no permission, read-only volume, no space, not a directory) degrade instead. Renaming the directory would not fix any of them, and on the lock case it would move a live store out from under its owner.
- the store's own flock is HELD ACROSS THE RENAME, not merely probed before it. Probing and releasing leaves a window in which another process can start its own open and have its live directory renamed underneath it — rename succeeds regardless of who holds an flock.
- anything unclassified degrades. The fail-safe default is to leave the disk alone.
The classifier matches on message text because badger v4 wraps these failures with y.Wrapf, which implements no Unwrap — errors.Is against every exported sentinel (ErrTruncateNeeded, y.ErrChecksumMismatch, ErrEncryptionKeyMismatch) returns false for all of them, verified empirically. String matching is the only mechanism available, so it is used only to WIDEN recovery, never to authorise destruction on its own: the environmental deny-list is consulted first and the directory lock gates the rename.
WHAT IS PER-STORE ¶
Only the Policy. The shared corruption table is derived from what badger says, but what a given MESSAGE means depends on how the store is opened — see Policy for the case that forced this to be a parameter rather than a constant.
Index ¶
- Constants
- Variables
- func AbandonedMarkers(dir string) []string
- func ApplyQuarantine(dir string, rec *Recovery)
- func ContainFault(storeDir string, op func() error) (err error)
- func IsStoreFault(err error) bool
- func QuarantineDir(lock *HeldLock, dir string) (string, error)
- func QuarantinedCopies(dir string) []string
- func RecordFault(dir, cause string) error
- type HeldLock
- type OpenAttempt
- type OpenErrClass
- type Policy
- type Recovery
- type RecoveryTrigger
Constants ¶
const ( FaultMarkerSuffix = ".faulted" FaultMarkerTempSuffix = ".faultedtmp." )
FaultMarkerSuffix names the fault marker beside the store directory. Like the open-attempt markers it is a sibling, not a file inside the store, so moving the store aside never moves the evidence that justified it.
const ( MarkerSuffix = ".opening." MarkerTempSuffix = ".openingtmp." )
MarkerSuffix / MarkerTempSuffix name the per-attempt open markers. The temp form is deliberately NOT a prefix match of the final form (no dot after "opening"), so the sweep cannot pick up a marker still being armed.
const FaultContainmentSupported = true
FaultContainmentSupported reports whether ContainFault can establish that a fault came from the store's mappings on this platform, and so whether it ever contains one. It is true on Linux, the production deployment target (Docker/OVA), where /proc/self/maps is the source of truth.
const MaxQuarantinedCopies = 1
MaxQuarantinedCopies bounds how many damaged copies are kept. A store can be gigabytes, and a host that keeps producing corruption must not fill the volume with evidence — the newest copy is the diagnostically useful one.
const QuarantineSuffix = ".corrupt."
QuarantineSuffix is the prefix of the timestamped name a damaged store directory is moved aside to. It matches the `.corrupt.<unixnano>` convention the CHAOS-05/07 state-file quarantine already uses, so operators learn one naming rule for the whole data directory.
Variables ¶
var ErrStoreFault = errors.New("storeguard: memory fault reading the store's mapped file")
ErrStoreFault reports that a memory fault raised by the store's mapped file was contained. It is deliberately distinct from any error badger returns: a returned error means badger was able to describe what went wrong, while this means the mapping itself could not be read and the store must be treated as unusable from here on.
var ErrStoreLockNotHeld = errors.New("refusing to quarantine without holding the store lock")
ErrStoreLockNotHeld guards the rename against a future refactor that probes the lock and lets go before moving the directory. That ordering looks harmless and is not: rename does not consult flocks, so the window lets another process acquire badger's directory lock and start opening a store that is about to be renamed out from under it.
Functions ¶
func AbandonedMarkers ¶
AbandonedMarkers returns the markers of open attempts whose owning process is gone — the poison signal. A marker whose flock cannot be taken belongs to a LIVE opener and is never returned: clearing or acting on it would destroy the breadcrumb of an attempt still in progress.
It also reaps temp markers left by a death during arming. Those are not a poison signal (the owner never reached badger.Open), just litter.
func ApplyQuarantine ¶
ApplyQuarantine moves dir aside, recording the outcome on rec. It refuses when the directory is absent, when another process holds the store lock, or when the lock state cannot be determined — the fail-safe default is to leave the disk alone.
The store lock is HELD ACROSS THE RENAME. Probing it and letting go first would leave a window in which another process acquires badger's directory lock and starts opening, only to have its live directory renamed underneath it: rename does not consult flocks, so the probe has to remain in force until the move is done.
func ContainFault ¶ added in v1.0.264
ContainFault runs op with memory-fault containment armed on the calling goroutine, converting a fault on the store's mapped file into an error that wraps ErrStoreFault instead of a process-killing `fatal error: fault`.
The previous SetPanicOnFault setting is restored before returning, so nesting this inside a caller that has its own setting does not change that caller's behavior.
Only memory faults are converted. An ordinary panic raised by op — including a genuine nil-pointer dereference, which is a BUG and not disk damage — is NOT swallowed: it is re-panicked so it keeps reaching the existing crashguard machinery instead of being quietly reported as a failing volume.
Telling those two apart takes two checks, because neither one is enough by itself:
- Both arrive carrying the text "invalid memory address or nil pointer dereference", so the message is useless. The runtime attaches an `Addr() uintptr` method only to the error it builds for a fault at a NON-NIL address (`runtime.errorAddressString`). A nil dereference panics with a plain runtime error that has no such method, so it is re-panicked.
- Addr() alone does not prove the fault came from the STORE's mapping. A wild non-nil `unsafe.Pointer` dereference, or any other runtime-corruption bug on the lookup path, also gets Addr(). Swallowing that would disable Layer 2 and keep a process with corrupted state running. So the faulting address must also fall inside a file-backed mapping whose file is under storeDir, checked against `/proc/self/maps` at recover time. This only runs after a fault has already happened, so the read costs nothing on the normal path.
The check fails closed. If the maps can't be read or parsed, or the platform has no `/proc/self/maps`, or the address lies outside the store's mappings, the original panic propagates. For a real mapping fault that is no worse than running without the guard at all. Measured in `faultguard_test.go`: a nil dereference has no Addr(), a fault on a mapping under storeDir is contained, and the same fault checked against another directory (or with unreadable maps) is re-panicked.
func IsStoreFault ¶ added in v1.0.264
IsStoreFault reports whether err came from a contained memory fault.
func QuarantineDir ¶
QuarantineDir renames dir aside and prunes older copies down to MaxQuarantinedCopies. The rename is within the same parent directory, so it is an atomic metadata operation on one filesystem — never a copy, and it needs no free space for the data.
The store lock is a REQUIRED argument and must still be held: see ErrStoreLockNotHeld.
func QuarantinedCopies ¶
QuarantinedCopies returns the `.corrupt.*` siblings of dir, newest last. Exported so the caller can re-surface an unreconciled quarantine from a PRIOR start: the in-memory record is process-local, so without this a self-healed store looks pristine on the next restart while the evidence — and the disk it occupies — is still sitting there.
func RecordFault ¶ added in v1.0.264
RecordFault durably records that the store at dir took a contained memory fault, so the next Open quarantines it instead of handing badger the same damaged tables. The write is atomic (temp file, fsync, rename, directory fsync), so a crash mid-write leaves either no marker or a complete one.
The directory fsync is part of the result. Without it the rename may not survive a power loss, and the next start would reopen the damaged store instead of quarantining it, so a failed fsync is reported, not swallowed.
Only a store whose contents are rebuildable should call this: Open treats the marker as sufficient grounds to move the directory aside (still gated by the store lock, and never a deletion). The error is for the caller's log line: a volume damaged enough to fault may refuse the write, and nothing more can be done about it from inside the faulting process.
Types ¶
type HeldLock ¶
type HeldLock struct {
// contains filtered or unexported fields
}
HeldLock is an flock the caller is responsible for releasing. It is passed to QuarantineDir so the "lock is held across the rename" invariant is carried by the type rather than by a comment: there is no way to reach the rename without producing one, and a released handle is refused.
func LockStore ¶
LockStore takes badger's directory lock. (nil, nil) means a live process holds it; (nil, err) means the lock state could not be determined. Only a non-nil handle authorises a quarantine.
type OpenAttempt ¶
type OpenAttempt struct {
// Path is the marker file armed for this attempt, or "" when arming failed
// (best-effort — a marker that cannot be written must not stop the open).
Path string
// Lock is the flock held for the attempt's duration; nil when arming failed.
Lock *HeldLock
}
OpenAttempt is one in-flight badger.Open, represented on disk by a marker file this process holds an flock on.
Both fields are exported because they are the attempt's observable state, not bookkeeping: Path is the breadcrumb a later start reads, and Lock is what distinguishes a live attempt from a dead one. Releasing Lock while leaving Path in place is precisely what the kernel does when a process dies inside badger.Open, which is the condition this whole package exists to detect.
func BeginAttempt ¶
func BeginAttempt(dir string) *OpenAttempt
BeginAttempt arms a marker for this attempt. Best-effort: the marker is a safety net, and failing to write one must not stop the store from opening — that would be the refuse-to-run posture this package exists to remove. A zero-value attempt is safe to End().
The marker is created under a temporary name, flocked, and only then renamed into place, so it can never be observed existing-but-unlocked. Without that ordering a concurrent start could catch the microsecond gap between create and flock and mistake a live attempt for a dead one.
func (*OpenAttempt) End ¶
func (a *OpenAttempt) End()
End removes this attempt's marker and then releases its lock, in that order. Releasing first would leave a window in which our own still-present marker reads as abandoned to a concurrently starting process. (The store lock would still veto its quarantine, so the window was never destructive — but a primitive that is only safe because a second one catches it is one refactor away from not being safe at all.) It touches no other process's marker.
type OpenErrClass ¶
type OpenErrClass int
OpenErrClass is the verdict on a returned open error.
const ( // ClassUnknown — not recognised. Degrade; never touch the disk. ClassUnknown OpenErrClass = iota // ClassEnvironment — the store may be perfectly intact; the environment is // the problem. Quarantining would fix nothing and could destroy a live store. ClassEnvironment // ClassCorrupt — the on-disk store is damaged and will keep failing. ClassCorrupt )
func ClassifyOpenError ¶
func ClassifyOpenError(err error, policy Policy) OpenErrClass
ClassifyOpenError decides what a returned open error means for this store.
Order is load-bearing: environmental first (a fault renaming cannot fix and where renaming could destroy a live store), then the policy's exemptions, then corruption, then degrade.
type Policy ¶
type Policy struct {
// NeverCorrupt are errors.Is targets this store refuses to classify as
// corruption. Structural and therefore exact — preferred over text.
NeverCorrupt []error
// NeverCorruptText are lowercase message fragments this store refuses to
// classify as corruption. The text-level backstop for a condition whose
// error does not survive as a comparable sentinel.
NeverCorruptText []string
}
Policy is the per-store part of the decision. Everything else in this package is store-agnostic.
It exists because of one empirically-established divergence. badger reports KEYREGISTRY damage as "Encryption key mismatch", and for a store that is NEVER opened with an encryption key that message can only mean corruption — which is why the shared table lists it. For a store that IS opened with a key the same message additionally covers two conditions that are not corruption at all and whose data is perfectly intact: the operator changed the passphrase, or the key-derivation salt sidecar was lost. Measured on badger v4.9.6, all three produce an indistinguishable error (CHAOS-62; see `roadmap/CHAOS-ENGINEERING-REVIEW.md` §25.2). Quarantining on it would move a healthy store aside over an ordinary configuration change.
So the rule a store may override is narrow and one-directional: a Policy can only ever make the guard LESS willing to touch the disk, never more. There is deliberately no field for adding corruption signals — widening destruction from a call site is how a shared safety mechanism becomes an unsafe one.
type Recovery ¶
type Recovery struct {
// Trigger is what prompted the recovery attempt (TriggerNone when the
// store opened cleanly on the first try).
Trigger RecoveryTrigger
// Cause is the human-readable reason behind Trigger.
Cause string
// Quarantined reports whether the damaged directory was moved aside.
Quarantined bool
// QuarantinePath is where it was moved to (empty unless Quarantined).
QuarantinePath string
// Skipped explains why a recovery that was triggered did NOT quarantine —
// a live lock holder, a missing directory, or a rename that failed. Empty
// when nothing was skipped.
Skipped string
// ResidualQuarantines lists `.corrupt.*` siblings present at open time,
// including any created by this call. A non-empty list after the operator
// has reconciled the incident is their signal to clean up.
ResidualQuarantines []string
}
Recovery reports what Open had to do. It is data, not logging: the caller owns the log line, the alert, and the metrics, so this package stays free of policy about how a degradation is surfaced.
func Open ¶
Open opens a store through open, recovering from a directory the previous run could not survive, or one whose previous run contained a memory fault on it and recorded that with RecordFault. It never panics on behalf of badger — the panic case is handled by refusing to hand badger a directory a previous process died inside of — and it never destroys data it has not first moved aside.
Returns (store, recovery, nil) on success. On failure the caller MUST decide how to degrade; this package never exits. For every store wired to it so far the answer has been the same: run without it, because refusing to run an in-line gateway over a damaged local store is a self-inflicted outage.
type RecoveryTrigger ¶
type RecoveryTrigger string
RecoveryTrigger names what caused a recovery attempt.
const ( // TriggerNone means the store opened normally. TriggerNone RecoveryTrigger = "" // TriggerPoisonMarker means a previous process died inside badger.Open on // this directory (uncatchable panic, SIGKILL, OOM, or a fatal exit). TriggerPoisonMarker RecoveryTrigger = "poison_marker" // TriggerOpenError means badger.Open returned an error identified as // corruption of the on-disk store. TriggerOpenError RecoveryTrigger = "open_error" // TriggerRuntimeFault means a previous run contained a memory fault on the // store's mapped tables after a healthy open and recorded it with // RecordFault (CHAOS-74). TriggerRuntimeFault RecoveryTrigger = "runtime_fault" )