WEPPcloud

← Back to help

Role: user

NoDb State Management

File-backed, Redis-cached singleton controllers for WEPPcloud run state management with distributed locking and zero-downtime serialization.

See also: NoDb Persistence and Concurrency Contract, AGENTS.md for coding conventions, and docs/dev-notes/style-guide.md for clarity expectations.

Overview

The NoDb module replaces traditional relational databases with a constellation of file-backed singleton objects for managing WEPPcloud run state. Each NoDb controller:

  • Serializes to JSON - Human-readable .nodb files in the working directory
  • Caches in Redis - 72-hour TTL in DB 13 for instant hydration
  • Distributed locking - Redis-backed locks (DB 0) serialize participating commit sections
  • Singleton per process - getInstance(wd) reuses a per-process cached object for repeated calls in the same worker process
  • Structured telemetry - Per-controller log files (<wd>/<controller>.log) and Redis pub/sub (DB 2)

Instead of SQL queries, developers interact with rich Python objects that expose domain-specific methods and properties. Redis provides coarse-grained locking and caching, while durable-state refresh and stale-write rejection protect whole-object commits across workers and RQ tasks.

Why NoDb?

  • Portability - Zip a run directory and move it anywhere
  • Schema flexibility - Add attributes without migrations
  • Developer ergonomics - Python methods instead of SQL queries
  • Crash safety - Redis caching with disk fallback
  • Distributed coordination - Redis locks, durable refresh, and stale-write rejection coordinate participating writers

Tradeoffs:

  • No relational queries or foreign keys
  • Lock discipline required for all mutations
  • JSON payloads can grow large
  • Learning curve for bespoke patterns

NoDbBase Core Responsibilities

wepppy/nodb/base.py provides the NoDbBase superclass that every controller inherits from. Important behaviors:

  • Singleton lifecycle – NoDbBase.getInstance(wd) maintains one process-local cached controller per working directory for writable paths and refreshes from cache/disk when signatures drift.
  • Distributed locking – with controller.locked(): acquires a Redis-backed lock (DB 0), mirrors legacy hash flags, and raises NoDbAlreadyLockedError when re-entrancy is unsafe.
  • Persistence helpers – dump_and_unlock() fsyncs and atomically replaces the JSON payload, releases the lock, then sanity-checks persisted state via getInstance() signature/hydration paths.
  • Telemetry wiring – _init_logging() attaches a QueueListener fan-out to StatusMessenger, controller-scoped log files, and a console error stream; try_redis_set_log_level() dynamically adjusts levels via DB 15.
  • Status channels – _status_channel resolves to <runid>:<controller> (pup runs routed to runid:omni).
  • Trigger events – TriggerEvents enum documents lifecycle hooks (e.g., LANDUSE_BUILD_COMPLETE) that mods and UI components listen for when orchestrating runs.

When extending NoDb, prefer these utilities over bespoke implementations—custom locking or logging code frequently regresses cross-worker behavior. See the module docstring in wepppy/nodb/base.py for deeper context and example usage.

Authoritative Contract

NoDbBase lock ownership, stale-write rejection, atomic write behavior, cache hydration, and NFS-focused durability/error classification are specified in:

  • docs/schemas/nodb-persistence-concurrency-contract.md

If this README and implementation behavior diverge, treat the schema contract as authoritative and update this README in the same change set.

Disk hydration pairs decoded state with the version of the same opened file. If an atomic replacement occurs during decoding, the older complete state keeps its older signature: cache reuse refreshes it and a stale write is rejected. Detectable changes during the read raise ESTALE under the existing bounded initial-read policy. See Coherent disk-read versions.

PRISM revision and RAP analysis also verify required main-file bytes at collection and finalization, detecting equal-size changes even when mtime is restored. Existing metadata transaction checks remain conservative. Indirect raster dependencies need separate closure; see Derived input byte verification.

Project-config executable identities use verified SHA-256 reads with bounded cache reuse. Restored timestamps cannot alone authorize an old executable hash; read/execute checks and atomic registry availability rules still apply.

Writer Ownership, Contention, and Retry

Prefer one writer per NoDb file during a concurrent orchestration phase. For parallel RQ work, each worker should write its own per-run artifact and use RQ metadata for live job state. A dependency finalizer should merge those results into the shared controller after workers reach terminal states.

Different attributes or dictionary keys are not independent write scopes. A NoDb dump replaces the whole serialized controller, so two workers updating different _runs[run_id] entries can still lose one another's changes if they commit from independently hydrated objects.

Multiple writers are permitted when a single writer or finalizer is impractical. Use this transaction shape for every shared mutation:

  1. Complete expensive work outside the lock.
  2. Acquire the distributed lock.
  3. Refresh the controller from durable state while holding the lock.
  4. Apply a small, idempotent mutation that preserves unrelated fields.
  5. Atomically dump and unlock.

Use bounded backoff for NoDbAlreadyLockedError. On NoDbStaleWriteError, discard the stale mutation base, reload current durable state, and reapply the entire operation; never retry dump() on the stale object. If the update cannot be safely merged or reapplied, fail explicitly.

Keep locks out of model execution, raster processing, remote requests, and other long-running work. Multi-writer paths require concurrency regression coverage demonstrating that representative interleavings do not lose unrelated updates. See the authoritative contract's "Writer Ownership and Mutation Topology" section for the normative requirements.

Long-running derived builders may use the collect-then-finalize variant: snapshot the inputs that determine the result, collect outside the lock, then rehydrate durable state under a short finalizer lock. The finalizer rejects changed relevant inputs and applies only an explicit derived-field allowlist; it does not merge a stale whole-controller object.

Observed GridMET/PRISM and RAP time-series operations stage derived artifacts, then validate captured inputs against fresh durable state under the lock. Unrelated edits survive; changed inputs produce an explicit superseded error. See Climate/RAP finalization and recovery for the implemented boundaries, rollback behavior, and regression evidence.

Failed edits and recovery

A failed high-level edit must leave its held controller at the current durable state, or make that instance refuse reuse until authoritative recovery succeeds. An unchanged file and a released lock do not prove that memory is clean. See the NFMS-01 contract for the required commit and reference rules. Candidate implementation validation is tracked separately; this is not a production deployment claim.

For users, an error after saving begins does not always mean nothing was saved: atomic replacement may have committed before later work failed. Inspect the current accepted settings/source before retrying. A later successful edit must not carry values rejected by the failed edit into prepared WEPP inputs. NoDb recovery does not roll back previously published artifacts or submitted jobs.

For developers, use locked() for automatic persistence and release. Manual producers need an acquired mutation recovery boundary around field changes, explicit persistence and completion work. Direct low-level dump() intentionally retains its payload after a precommit I/O error for an explicit owned retry; stale-write errors still require reloading and reapplying from fresh state. Stage nested option edits before publication when computing them outside the lock. After failure, reacquire nested options from the recovered controller; previously obtained mutable aliases are no longer a valid mutation base. Map/DEM preparation computes candidate paths locally and publishes *_is_vrt flags only at the owned commit. Nested mutation code must establish current-thread ownership; a global islocked() result does not grant mutation authority.

For operators, retain the original operation error and its recovery/cleanup context. Restore unavailable storage or Redis coordination before explicit recovery; do not force-unlock another owner, clear global caches, or overwrite durable files with an entry snapshot. A failed first initialization has no durable record to restore: retry initialization with a fresh object. Optional absent features remain valid and must not be “repaired” by inventing empty files.

Health signals are clean held-reference reads, accepted-only follow-up saves and accepted values in the exact prepared files. Danger signals are rejected values reappearing, unusable-instance errors after storage has recovered, owner-token interference, or growing logging resources. A recurrence requires a new incident record and reinspection of manual/prelock producers as well as the shared context.

WEPP Hillslope Timeout Policy

Continuous hillslope runs through WeppRunService use a 120-second per-attempt timeout for single-OFE projects (see ADR-0072). MOFE projects use a 300-second timeout because each WEPP invocation can route many OFEs for one hillslope. The timeout appears in the service log line as Running Hillslopes with max_workers=..., timeout=...s and is passed unchanged to the runner so timeout errors continue to report the command, run file, error file, attempts, and last observed WEPP output.

Path Placeholders in Configs

NoDb configs reference large, location-specific datasets through placeholders that config_get_path() resolves at runtime:

  • MODS_DIR expands to wepppy/nodb/mods, keeping legacy bundles inside the repo.
  • EXTENDED_MODS_DATA points to heavy datasets that now live outside the repo. The resolver honors the EXTENDED_MODS_DATA environment variable, falling back to the default bind mounts (/wc1/geodata/extended_mods_data, /geodata/extended_mods_data) or the legacy mods/locations folder when the external volumes are unavailable.

Use the helper script python wepppy/nodb/scripts/update_extended_mods_data.py --apply whenever locations (Portland, Seattle, Lake Tahoe) need to be relinked to the external bundle; the script rewrites the .cfg files to use the placeholder consistently.

Mapped restrictive-layer conductivity

Both ordinary and MOFE WEPP preparation create soils/kslast.tif on the project hillslope grid and assign each hillslope its area mean. All its OFEs receive that value, retaining the developed-soil exemption. soils/kslast_summary.json records source/grid/map hashes, normalization counts and per-hillslope default fractions. A configured scalar fills only missing area; missing coverage without a default fails before soil workers start. Nonpositive/nonfinite conductivity is missing. The map is rebuilt on prep and retains nodata. Existing runs adopt the change when prepared again. See the kslast map contract for units, coverage policy, directory boundaries and diagnostics. The native release must export identify_area_weighted_mean_single_raster_key before restarting workers with this code.

Batch task boundary

See Batch hillslope and watershed jobs for phase ownership, job-tree inspection, durable handoff records and retry.

MOFE pair-count freshness

Normal Landuse.build_managements() reuses counts only after joint content validation of subwatershed/MOFE rasters and the MOFE ID structure. Old persisted metadata signatures miss once; no manual NoDb migration or deletion is needed. Updated native counts reach management areas and coverage. A detected source change rejects the build before replacing prior summaries/count associations; retry after the writer completes. Unverified raster layouts count natively on each build. Management assignments, units and generated WEPP formats are unchanged. Coverage and coherence limits are in the raster dependency contract.

Geneva geometry and auto-aligned burn caches use the source/legend/grid identity specified in Geneva's derived freshness contract. A legacy artifact rebuilds through the normal request. If inputs change during native generation, the request reports changed_source (409); finish the input update and retry the normal operation. Inspect retained geneva/cache_attempts/<uuid>/status.json and candidates when diagnosing failures. Unknown source layouts run uncached. Existing auxiliary-bearing aligned TIFFs retain native overwrite behavior and its weaker failure guarantee until a clean output can establish provenance. This does not add freshness to the separate prepare_hrus(force_rebuild=False) summary cache or update an already-open browser automatically.