-
Notifications
You must be signed in to change notification settings - Fork 5
Fix the C1File close-vs-write data race #1086
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -58,6 +58,15 @@ type C1File struct { | |
| closed bool | ||
| closedMu sync.Mutex | ||
|
|
||
| // dbClosed publishes handle closed-ness to concurrent callers. | ||
| // rawDb and db are written once at construction and never | ||
| // reassigned on a live C1File, so readers on other goroutines can | ||
| // load them without synchronization; closeRawDB flips this instead | ||
| // of nil-ing the fields. closedMu cannot serve this purpose because | ||
| // Close holds it across finalize, which is tens of minutes on a | ||
| // whale-scale file, and every reader would block for the duration. | ||
| dbClosed atomic.Bool | ||
|
|
||
| // bulkLoad defers secondary-index creation on a freshly-created | ||
| // destination. When set, the per-table non-unique secondary indexes | ||
| // are dropped right after table creation (instant on the empty table) | ||
|
|
@@ -640,7 +649,7 @@ func (c *C1File) Close(ctx context.Context) (retErr error) { | |
| // then dirtying via an attached-db mutation still releases the | ||
| // SQLite handle and any FDs/goroutines it owns. | ||
| if !c.dbUpdated.Load() || c.readOnly { | ||
| if c.rawDb != nil { | ||
| if c.rawDBOpen() { | ||
| if err := c.closeRawDB(ctx); err != nil { | ||
| return cleanupDbDir(c.dbFilePath, err) | ||
| } | ||
|
|
@@ -722,10 +731,16 @@ func (c *C1File) finalize(ctx context.Context) error { | |
| l := ctxzap.Extract(finalizeCtx) | ||
|
|
||
| // Only WAL-checkpoint and close the raw DB if a handle is open. | ||
| // Some callers (notably TestC1ZDecoder) manually close c.rawDb to | ||
| // Some callers (notably TestC1ZDecoder) release c.rawDb themselves to | ||
| // force a checkpoint before calling Close — that path skips both | ||
| // operations here and proceeds directly to saveC1z. | ||
| if c.rawDb != nil { | ||
| // operations here and proceeds directly to saveC1z. Checkpointing a | ||
| // released handle would fail with sql.ErrConnDone and send us down the | ||
| // cleanupDbDir branch, deleting the working database instead of saving | ||
| // it. rawDBOpen recognizes the releases that precede a Close (the | ||
| // dbClosed flip, or close-plus-nil as the decoder test does); a bare | ||
| // rawDb.Close() that leaves the field set still reads as open, so that | ||
| // idiom must never be followed by Close — see rawDBOpen's doc. | ||
| if c.rawDBOpen() { | ||
| // CRITICAL: Force a full WAL checkpoint before closing the database. | ||
| // This ensures all WAL data is written back to the main database file | ||
| // and the writes are synced to disk. Without this, on filesystems with | ||
|
|
@@ -801,22 +816,39 @@ func (c *C1File) finalize(ctx context.Context) error { | |
| return nil | ||
| } | ||
|
|
||
| // closeRawDB wraps c.rawDb.Close with a span and drops the handle | ||
| // references on the C1File so callers do not have to repeat the | ||
| // nil-out. Returns the error from rawDb.Close so error paths can | ||
| // still propagate or log it. | ||
| // rawDBOpen reports whether the SQLite handle is still usable. | ||
| // | ||
| // It sees two release idioms. closeRawDB publishes closed-ness through | ||
| // dbClosed and leaves the pointer in place, because concurrent readers | ||
| // race a nil-ing write (that race is what dbClosed exists to fix). A | ||
| // test that closes c.rawDb directly and then nils it (c1file_test.go's | ||
| // decoder test, before calling Close) reads as closed through the nil | ||
| // check. What this cannot see is a direct c.rawDb.Close() that leaves | ||
| // the field set — several tests do that to force a checkpoint before | ||
| // abandoning the handle — which still reads as OPEN here. That idiom is | ||
| // only safe on a C1File that will never see another operation; in | ||
| // particular, calling Close after it would checkpoint a closed handle | ||
| // and take the cleanupDbDir branch. Flip dbClosed (or nil the field) if | ||
| // the C1File lives on. | ||
| func (c *C1File) rawDBOpen() bool { | ||
| return c.rawDb != nil && !c.dbClosed.Load() | ||
| } | ||
|
|
||
| // closeRawDB wraps c.rawDb.Close with a span and marks the handles | ||
| // closed so subsequent callers short-circuit. Returns the error from | ||
| // rawDb.Close so error paths can still propagate or log it. | ||
| // | ||
| // The CAS makes the underlying Close happen at most once; the flag is | ||
| // published before the Close so a racing caller fails closed rather | ||
| // than entering a database/sql call that is about to be torn down. | ||
| func (c *C1File) closeRawDB(ctx context.Context) error { | ||
| _, span := tracer.Start(ctx, "C1File.closeRawDB") | ||
| var err error | ||
| defer func() { uotel.EndSpanWithError(span, err) }() | ||
| if c.rawDb == nil { | ||
| if c.rawDb == nil || !c.dbClosed.CompareAndSwap(false, true) { | ||
| return nil | ||
| } | ||
| // Copy the rawDb to a local variable to avoid race conditions. | ||
| rawDb := c.rawDb | ||
| c.rawDb = nil | ||
| err = rawDb.Close() | ||
| c.db = nil | ||
| err = c.rawDb.Close() | ||
| return err | ||
| } | ||
|
Comment on lines
844
to
853
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Suggestion (high confidence in the mechanism, residual/pre-existing): the doc says a racing caller "fails closed rather than entering a database/sql call that is about to be torn down", but the flag only fences callers that have not yet passed |
||
|
|
||
|
|
@@ -1465,15 +1497,41 @@ func (c *C1File) countBySyncAndResourceType( | |
| return out, nil | ||
| } | ||
|
|
||
| // validateDb ensures that the database has been opened. | ||
| // validateDb ensures that the database has been opened and not yet closed. | ||
| func (c *C1File) validateDb(ctx context.Context) error { | ||
| if c.db == nil { | ||
| if c.db == nil || c.dbClosed.Load() { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Suggestion: this removes the data race but not the check-then-use window. A writer can load |
||
| return ErrDbNotOpen | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
|
|
||
| // dbNotOpenOnClosed maps database/sql's own closed-handle failures onto | ||
| // ErrDbNotOpen when a concurrent closeRawDB has already flipped dbClosed. | ||
| // | ||
| // validateDb runs before a query and the connection is acquired inside it, | ||
| // so a Close landing between the two hands the writer database/sql's | ||
| // unexported "sql: database is closed" sentinel — an error callers cannot | ||
| // errors.Is against, while TestC1ZConcurrentClose pins ErrDbNotOpen as the | ||
| // close-vs-write contract for every interleaving. Both gates below matter: | ||
| // the flag check keeps a live handle's real failures untouched, and the | ||
| // error-class check keeps a failure that merely coincides with a close (a | ||
| // constraint violation, say) reporting itself rather than the close. | ||
| // | ||
| // Applied where the contract is pinned — the chunked-insert funnel every | ||
| // record Put goes through, and the sync-run stamp — rather than at all ~100 | ||
| // query sites; a path without it can still surface the driver's sentinel if | ||
| // it loses this race. | ||
| func (c *C1File) dbNotOpenOnClosed(err error) error { | ||
| if err == nil || !c.dbClosed.Load() { | ||
| return err | ||
| } | ||
| if errors.Is(err, sql.ErrConnDone) || strings.Contains(err.Error(), "sql: database is closed") { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Suggestion: this mapping hinges on |
||
| return fmt.Errorf("%w (%w)", ErrDbNotOpen, err) | ||
| } | ||
| return err | ||
| } | ||
|
|
||
| // validateSyncDb ensures that there is a sync currently running, and that the database has been opened. | ||
| func (c *C1File) validateSyncDb(ctx context.Context) error { | ||
| if c.currentSyncID == "" { | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -233,12 +233,14 @@ func (c *C1File) SnapshotTo(ctx context.Context, outPath string, opts ...C1FOpti | |
| // connection. cloneCopy reads c.rawDb to take that one connection but never | ||
| // mutates c.rawDb/c.db/c.currentSyncID/c.closed, so the live handle is left | ||
| // exactly as it was found (plus the row-copy stall). Both entry points already | ||
| // reject a closed handle; the nil-rawDb guard below is defensive against a | ||
| // future caller that does not. | ||
| // reject a closed handle; the rawDBOpen guard below repeats the check so a | ||
| // future caller that does not still fails closed instead of taking a | ||
| // connection from a handle mid-teardown (a bare nil check cannot see | ||
| // closeRawDB's release, which flips dbClosed and leaves the pointer set). | ||
| // errPrefix is the caller's error-message namespace ("clone-sync" / | ||
| // "snapshot-to") so each entry point keeps its own observable error strings. | ||
| func (c *C1File) cloneCopy(ctx context.Context, outPath string, syncID string, selectAll bool, errPrefix string, opts ...C1FOption) error { | ||
| if c.rawDb == nil { | ||
| if !c.rawDBOpen() { | ||
| return ErrDbNotOpen | ||
| } | ||
|
|
||
|
|
@@ -272,16 +274,17 @@ func (c *C1File) cloneCopy(ctx context.Context, outPath string, syncID string, s | |
| // Schema() re-run rebuilds the dropped indexes in one pass. | ||
| // We close only the rawDb to release the connection and file locks | ||
| // without triggering C1File.Close()'s cleanupDbDir which would | ||
| // remove the tmpDir we still need. | ||
| // remove the tmpDir we still need. closeRawDB rather than a direct | ||
| // rawDb.Close: it publishes closed-ness instead of leaving a handle | ||
| // that still reads as open, and it keeps "rawDb/db are never | ||
| // reassigned on a live C1File" literally true. | ||
| initFile, err := NewC1File(ctx, dbPath, opts...) | ||
| if err != nil { | ||
| return err | ||
| } | ||
| if err = initFile.rawDb.Close(); err != nil { | ||
| if err = initFile.closeRawDB(ctx); err != nil { | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Suggestion (unchanged code, adjacent): the |
||
| return err | ||
| } | ||
| initFile.rawDb = nil | ||
| initFile.db = nil | ||
|
|
||
| qCtx, canc := context.WithCancel(ctx) | ||
| defer canc() | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -866,7 +866,7 @@ func (c *C1File) endSyncRun(ctx context.Context, syncID string) error { | |
|
|
||
| _, err = c.db.ExecContext(ctx, query, args...) | ||
| if err != nil { | ||
| return err | ||
| return c.dbNotOpenOnClosed(err) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 Suggestion: |
||
| } | ||
| c.dbUpdated.Store(true) | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟡 Suggestion: one
rawDb != nilopen-check was not converted —cloneCopyatpkg/dotc1z/clone_sync.go:241still doesif c.rawDb == nil { return ErrDbNotOpen }, and its doc comment on line 236 explicitly calls it "defensive against a future caller" that does not reject a closed handle. Since a closedC1Filenow keeps a non-nilrawDb, that guard no longer detects closed-ness — the exact stale-meaning problem this PR fixes inClose,finalize,closeWithoutSave, andCopyIsolateSync. It's masked today (SnapshotTocallsvalidateDb,CloneSyncreachesgetSync/LatestSyncIDwhich do), so this is consistency rather than a live bug: switch it toc.rawDBOpen()(orvalidateDb) and drop the now-false claim in the comment.Separately, this doc says "Two idioms release the handle and both must read as closed here", but the package's most common idiom —
f.rawDb.Close()with no nil-out (snapshot_test.go:182,210,249,264,copy_isolate_sync_test.go:63,99,151,172,clone_sync_test.go:177,bulkload_test.go:189) — still reads as open. The matching new comment infinalize("recognize a released handle however it was released", line 739) overclaims for the same reason: a caller using that idiom beforeClosestill checkpoints a closed handle and takes thecleanupDbDirbranch that deletes the working database. Worth narrowing both comments to the two idioms actually covered (flag-flip, and close-plus-nil).