Shape storage init races with draining instance during rolling deploy (shared bind-mount)
@alco 已经在做这个了。
开始于 2026年6月30日。
评估
这个 Issue 还没有评估数据。
描述
Summary
During a rolling production deploy, two Electric instances run concurrently on the same host and bind-mount the same data directory (/var/electric/<stack_id>/...). The shape storage layer assumes it is the sole owner of that directory, so the starting instance runs destructive init (File.rm_rf, cleanup_all!) on directories the draining instance still has open — producing a burst of :enoent crashes and at least one hard NimblePool contract violation.
This was observed in production on 2026-06-17 across two hosts (ampere, faraday) within the 13:39:58–14:08:33Z "Deploy production stack" window. Five distinct Sentry issues fired, all tracing to the same root cause.
There are three independent ways to enter the destructive path, ordered from "most innocent starting state" to "least":
- Version / schema / OTP-release change — the common deploy case, healthy db. Per the doc on
ShapeStatus.initialize/1(shape_status.ex:45-53), "a change to@version, toShapeDb.Connection's@schema_version, or to the OTP release, will result in an empty database."validate_existing_shapes→count_shapesthen returns 0, which trips thevalid_shape_count == 0branch (shape_status.ex:64-68) and callscleanup_all!— wiping the whole<stack_id>dir the draining instance is actively writing into. A rolling deploy is exactly when the release changes, so this is close to the default deploy, not an edge case. The db was perfectly healthy. - Empty / freshly-created db. Same
valid_shape_count == 0 → cleanup_all!branch. - Any open failure or integrity-check failure.
delete_corrupt_db(rm_rfof the shape-db parent dir) fires on the integrity-check branch (connection.ex:271-278) and on anySqlite3.openerror (connection.ex:284-289).
Once any one of these fires, it is self-sustaining and runs on healthy data: instance A's rm_rf makes instance B's next file op fail with :enoent, which (via path 3) triggers another wipe, which breaks A, and so on — the two instances ping-pong wiping + recreating the same dir. Corruption is just one of several ways to enter the loop; the loop itself does not need a corrupt db to keep going. This is why the fix must be coordination + controlled shutdown (an ownership lock), not blind :enoent tolerance — see the proposed fix below.
Deployment context
Electric Cloud runs each logical instance as an ECS service on EC2 with deploymentMinimumHealthyPercent: 100 / maximumPercent: 200. The data dir is a host bind-mount (/mnt/nvme/electric/<instance> → container /var/electric) attached to the EC2 instance — it is not a per-task volume. So during a rolling deploy the old and new tasks share the same on-disk directory tree, keyed on the logical instance name, for the whole overlap window. The new task waits on the upstream replication-slot advisory lock before going read-write, but storage init/cleanup is not gated by that lock — it runs eagerly at boot.
Root cause — destructive init assumes sole ownership
1. Startup cleanup wipes the entire stack dir.
lib/electric/shape_cache/shape_status.ex:58-68 — on every boot, if valid_shape_count == 0 (which is true when the SQLite db was just deleted/corrupt), it calls Storage.cleanup_all!():
if valid_shape_count == 0 do
# delete any orphaned shape data
stack_id
|> Electric.ShapeCache.Storage.for_stack()
|> Electric.ShapeCache.Storage.cleanup_all!()
lib/electric/shape_cache/pure_file_storage.ex:231 — cleanup_all!/1 deletes the whole base_path (= /var/electric/<stack_id>/) and tmp_dir, including the log/ and metadata/ directories the draining instance still holds open.
2. SQLite "recovery" deletes the shape-db parent dir.
lib/electric/shape_cache/shape_status/shape_db/connection.ex:294-298:
defp delete_corrupt_db(db_path) do
with dir = Path.dirname(db_path),
{:ok, _} <- File.rm_rf(dir), # nukes shapes/meta/shape-db/
:ok <- File.mkdir_p(dir) do
:ok
end
end
Called from open_with_recovery/4 on any open failure or integrity-check failure (connection.ex:276, 287). During overlap, the two instances ping-pong wiping + recreating the same dir, which both starves and corrupts each other.
3. NimblePool contract violation turns an open failure into an unhandled crash.
When recovery exhausts its attempts (connection.ex:258-260):
defp open_with_recovery(db_path, _pool_state, _opts, 0) do
Logger.error("Unable to create database at #{db_path}") # <- ELECTRIC-8XK
{:error, "failed to open #{db_path}"}
end
init_worker/1 (connection.ex:157-162) propagates that {:error, _} verbatim:
def init_worker(pool_state) do
with {:ok, conn} <- init_worker_for_pool(pool_state) do
...
end
end
But NimblePool requires {:ok, worker, pool_state} | {:async, fun, pool_state} — so {:error, _} raises RuntimeError: unexpected return from ...init_worker/1 (ELECTRIC-8XN). The pooled path's Query.prepare!/2 similarly raises ShapeDb.Error: prepare_stmts failed: {:error, 1} (ELECTRIC-8XQ — a 492-event/sec crash-storm).
Observed Sentry issues (electricsql-04, all 2026-06-17)
| Issue | Symptom | Origin |
|---|---|---|
| ELECTRIC-8XK | Unable to create database at … |
open_with_recovery/4 exhausted |
| ELECTRIC-8XN | RuntimeError: unexpected return from …init_worker/1 (got {:error, "failed to open …sqlite"}) |
NimblePool contract violation (same event as 8XK) |
| ELECTRIC-8XQ | ShapeDb.Error: prepare_stmts failed: {:error, 1} — 492 events/sec, escalating |
Query.prepare!/2 against wiped/contended db |
| ELECTRIC-8XP | File.write! …/metadata/last_persisted_txn_offset.bin.tmp: :enoent |
PureFileStorage.WriteLoop writing into a deleted dir |
| ELECTRIC-8XM | File.open! …/log/log.latest.0.jsonfile.bin: :enoent |
WriteLoop.ensure_json_file_open/2 into a deleted dir |
Proposed fix (layered)
Primary — gate destructive storage init on directory ownership, not just the Postgres slot. The starting instance must not run cleanup_all! / delete_corrupt_db (or open the storage for write) on a shared <stack_id> dir until the previous owner has released it. Suggested: an on-disk lock acquired via flock(2) on a per-stack lock file, held by the active instance; defer all destructive/write-mode storage setup until the lock is held. This extends the existing replication-slot handoff to cover the filesystem.
Secondary — fail safe even if a race slips through:
init_worker/1must satisfy the NimblePool contract: on open failure, retry via{:async, …}/backoff or raise a typed, handled error — never return bare{:error, _}(fixes 8XN).delete_corrupt_db/1should notrm_rfa directory that a peer may be using; at minimum guard with the ownership lock above, and distinguish "db genuinely corrupt" from "dir pulled out from under me / open failed transiently."PureFileStoragewrite path (File.open!/File.write!,write_loop.exensure_json_file_open/2): when the dir was removed during a known draining/handoff, stop cleanly instead of crash-looping. The existingshape_gone?/1check (pure_file_storage.ex:1408) is racey.
Do not simply make these ops retry/ignore :enoent — that would mask genuine on-disk corruption. The fix is coordination + controlled shutdown, not blind tolerance.
Notes
- Related to #4595 (AsyncDeleter resilient boot) — both concern boot-time storage cleanup robustness, but this is a concurrency/ownership bug specific to the rolling-deploy overlap, not a full-disk bug.
cleanup_all!reachesAsyncDeleter.delete, so the two interact. - The triggering deploy ("Deploy new Electric, hibernate-then-suspend, GC tweaks") also shipped GC/hibernate changes touching storage lifecycle — worth confirming those paths don't independently call
cleanup_all!/delete_corrupt_dbon live stacks (a candidate explanation for the standalone 8XQ burst at 14:49Z, which falls outside the deploy window).
🤖 Generated with Claude Code
- 主要语言
- TypeScript
- 星标
- 10.4k
- 派生
- 399
- PR 合并指标
- 30 天内没有已合并 PR
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 没有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
electric-sql/electric 的其他 Issue
-
camelToSnake and snakeCamelMapper() drop the underscore when a digit precedes a camelCase boundary未关闭
难度 2/5 1-3 小时 新手友好度 85/100
electric-sql/electric#4855 ·
-
ShapeStream does not notify subscribers when it gives up on a non-Error value可能已有人在做 @Tyagiquamar 于 19 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 72/100
electric-sql/electric#4830 ·
-
@electric-sql/client throws SecurityError on import when the browser blocks site storage (typeof localStorage outside try)可能已有人在做 @mohanedmoh 于 37 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 72/100
electric-sql/electric#4826 · 1 条评论 ·
-
agents-chat-starter: spawn PUT goes to the durable-streams proxy, so no entity is created and agents never wake可能已有人在做 @adityavkk 于 133 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 78/100
electric-sql/electric#4687 ·
-
feature request triage
难度 2/5 1-3 小时 新手友好度 68/100
electric-sql/electric#4150 · 1 条评论 ·
查看 electric-sql/electric 的全部 Issue
相似的 Issue
-
Out of order / duplicate key error shows the key bytes as decimal or UTF-8, not hex可能已有人在做 @bardrop 今天认领。 未关闭
难度 1/5 1 小时以内 新手友好度 86/100
-
`/leaderboard`, the page and the share image say "be the first" for a program that hasn't started未关闭bug good first issue
难度 2/5 1-3 小时 新手友好度 84/100
codercops/discord-bot#152 ·
维护者通常 1 天内回复
-
bug i18n
难度 2/5 1-3 小时 新手友好度 74/100
endora-commerce/endora-commerce#1315 ·
维护者通常 1 天内回复
-
area:data-quality importer size:S
难度 2/5 1-3 小时 新手友好度 72/100
enorm-labs/event-junkie#5136 ·
维护者通常 1 天内回复
-
难度 1/5 1 小时以内 新手友好度 84/100
维护者通常 1 天内回复