Skip to content

Release the write lock before invoking set.value hooks - #225

Merged
inhere merged 1 commit into
gookit:masterfrom
GreedyC:codex/set-hook-after-unlock
Oct 23, 2026
Merged

inhere merged 1 commit into
gookit:masterfrom
GreedyC:codex/set-hook-after-unlock

Conversation

@GreedyC

@GreedyC GreedyC commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

A set.value hook that calls cfg.String(key) deadlocks: Set invokes the hook while still holding the write lock, and the getter waits for a read lock.

Register the hook before the deferred unlock so the lock is released before the callback runs. A bounded regression checks hooks reading updated top-level, nested, and literal dotted keys.

Validation: go test ./..., go vet ./..., and go test -race . -run TestSetHookCanReadUpdatedValue -count=5 pass on macOS/arm64 with Go 1.26.5. All three new cases time out before the fix.

AI assistance: Codex helped prepare the code and tests

@inhere
inhere merged commit e63f2c7 into gookit:master Oct 23, 2026
11 checks passed
inhere added a commit that referenced this pull request Oct 23, 2026
The hook is fired after the data lock is released (#225), so a hook that reads the

whole data set - eg: SaveFileOnSet() calls DumpToFile - races with another goroutine

calling Set: go test -race reports a data race on c.data, and Go may even abort

with 'concurrent map read and map write'.

- add an outer hookMu that serializes the data change with its hook. the hook still

  runs after the data lock is released, so the getter methods do not deadlock, but

  no other Set/SetData/ClearData can change the data while the hook is running.

- the lock order is hookMu -> lock, and ClearData now swaps the data map under the

  data lock.

- extract the locked set logic to Config.setValue().

- document the hook contract on HookFunc: use the getters, do not call

  Set/SetData/ClearData in a hook, the data is stable while the hook runs.

Tests: TestSetHookKeepsDataStable (another writer must wait for a running hook) and

TestSetHookCanDumpAllData (hook dumps the data while two goroutines Set).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants