Skip to content

fix(os/gsession): eliminate concurrent empty-session reads on non-Unix platforms - #4977

Open
lingcoder wants to merge 2 commits into
gogf:masterfrom
lingcoder:fix/issue-4792-windows-atomic
Open

lingcoder wants to merge 2 commits into
gogf:masterfrom
lingcoder:fix/issue-4792-windows-atomic

Conversation

@lingcoder

Copy link
Copy Markdown
Contributor

updates #4792

#4910 fixed the race on Unix using temp-file + rename. On non-Unix platforms
(Windows), os.Rename is blocked by any open reader handle, so the atomic
path was not safe there and the original O_TRUNC + two-Write implementation
was kept. This patch closes the remaining gap.

Measured before / after (Windows amd64, 2 s, 2 writers + 4 readers)

Implementation total reads nil reads nil rate
baseline (O_TRUNC + 2 Writes, master) 7 157 911 12.7 %
single Write concat (not taken) 11 105 2 133 19.2 %
temp-file + Rename (not viable) — — fails SharedReader
this PR: RWMutex + single Write 61 000+ 0 0 %

Changes

os/gsession/gsession_storage_file.go

  • Add sync.RWMutex to StorageFile (used only by the !unix path).
  • GetSession calls readSessionBytes (platform method) instead of gfile.GetBytes.

os/gsession/gsession_storage_file_nonunix.go

  • setSessionFile: concatenates the timestamp header and JSON payload in
    memory, then writes the complete buffer in a single file.Write call
    under the storage write lock. The O_TRUNC-to-Write gap that let
    concurrent readers observe an empty file is eliminated.
  • readSessionBytes: holds the read lock around gfile.GetBytes so a read
    can never overlap an in-progress truncate+write.

os/gsession/gsession_storage_file_unix.go

  • Add a readSessionBytes stub that delegates to gfile.GetBytes; on Unix
    the rename path makes a lock unnecessary.

os/gsession/gsession_z_unit_storage_file_windows_test.go

  • Add Test_Issue4792_WindowsConcurrentReadWrite: two writers + four readers
    sharing the same session ID for two seconds; asserts zero nil reads.
  • Test_StorageFileSharedReader (existing) confirms an open reader handle
    does not block SetSession — the write lock is released before returning.

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 85.30%. Comparing base (8949047) to head (0161dec).

Additional details and impacted files
@@            Coverage Diff             @@
##           master    #4977      +/-   ##
==========================================
- Coverage   85.31%   85.30%   -0.01%     
==========================================
  Files         894      894              
  Lines       47196    47197       +1     
==========================================
- Hits        40263    40260       -3     
- Misses       6933     6937       +4     
Flag Coverage Δ
go-1.27-core 73.26% <100.00%> (-0.02%) ⬇️
go-1.27-drivers-1 27.59% <0.00%> (-0.01%) ⬇️
go-1.27-drivers-2 27.43% <0.00%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@lingcoder
lingcoder force-pushed the fix/issue-4792-windows-atomic branch from e9f8021 to d75dbf6 Compare November 15, 2026 05:01
…x platforms

updates gogf#4792

gogf#4910 fixed the race on Unix with temp-file+rename. On non-Unix platforms
(Windows) os.Rename is blocked by any open reader handle, so the atomic path
was not taken there, and the original O_TRUNC + two-Write implementation was
kept as-is.

This patch closes the remaining gap without changing the platform split:

  gsession_storage_file.go
  - Add a sync.RWMutex field to StorageFile, used only by the !unix path.
  - GetSession now calls readSessionBytes (platform method) instead of
    gfile.GetBytes directly.

  gsession_storage_file_nonunix.go  (!unix — includes Windows)
  - setSessionFile: concatenates the 8-byte timestamp header and the JSON
    payload in memory, then writes the complete buffer in a single file.Write
    call under the storage write lock. The O_TRUNC-to-Write gap that allowed
    concurrent readers to see an empty file is eliminated.
  - readSessionBytes: holds the read lock around gfile.GetBytes so that a read
    can never overlap an in-progress truncate+write.

  gsession_storage_file_unix.go  (unix — no behaviour change)
  - Add readSessionBytes stub that delegates to gfile.GetBytes; on Unix the
    rename path makes a lock unnecessary.

  gsession_z_unit_storage_file_windows_test.go
  - Add Test_Issue4792_WindowsConcurrentReadWrite: two writers and four readers
    share the same session ID for two seconds; asserts zero nil reads.
    Before this fix: ~700-1000 nil reads in a 2-second run.
    After: 0.

Existing Test_StorageFileSharedReader confirms that an open reader handle does
not block SetSession — the write lock is released before the caller returns.
@lingcoder
lingcoder force-pushed the fix/issue-4792-windows-atomic branch from d75dbf6 to 0b21217 Compare November 15, 2026 10:44
@gqcn

gqcn commented Nov 18, 2026

Copy link
Copy Markdown
Member

The non-Unix RWMutex around truncate-and-write in setSessionFile, together with readSessionBytes, does close the empty-file window between GetSession and SetSession. Two gaps still leave that guarantee incomplete:

  • updateSessionTTl (os/gsession/gsession_storage_file.go:283) still WriteAts the timestamp without mu, and checkAndClearSessionFile (os/gsession/gsession_storage_file.go:299) still reads and may delete that same file without it. On non-Unix those calls can overlap O_TRUNC plus Write, so the header can still tear and GetSession can still return nil. Taking the same lock on those paths would match the new field comment. The Unix rename path never locks mu, so doing this from the shared methods would not change Unix publish behavior.
  • Test_Issue4792_WindowsConcurrentReadWrite (os/gsession/gsession_z_unit_storage_file_windows_test.go:88) drops the SetSession error, and total is never asserted. If every concurrent write fails, the initial session is still readable, so nilReads == 0 passes without exercising the race. This file is built only on Windows, so the current Linux CI does not compile it. Failing on the first write error, and asserting that a concurrent write and a read both happened, would make the regression real.

I have not added the bot-approved label.

@hailaz hailaz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review / 评审意见

Thanks for closing the remaining gap on this — combining the timestamp and payload into a single Write and guarding it with a read/write lock is the right shape for platforms where os.Rename cannot be atomic. A few points before this can land.

感谢补齐这块遗留缺口——把时间戳和 payload 合并成一次 Write 并用读写锁保护,对于 os.Rename 无法保证原子的平台方向是对的。合并前有几点需要处理。


1. The mutex does not cover all writers (correctness) / 锁没有覆盖所有写入路径(正确性)

The header comment in gsession_storage_file_nonunix.go claims the lock serializes writers against readers, but updateSessionTTl still writes outside it:

gsession_storage_file_nonunix.go 的文件头注释声称该锁能序列化读写,但 updateSessionTTl 仍然绕过了它:

// os/gsession/gsession_storage_file.go
file, err := gfile.OpenWithFlag(path, os.O_WRONLY)
...
if _, err = file.WriteAt(gbinary.EncodeInt64(gtime.TimestampMilli()), 0); err != nil {

An 8-byte WriteAt can still tear against a concurrent gfile.GetBytes. If the torn value happens to be small, GetSession treats the session as expired and returns nil, nil — exactly the "empty session read" this PR sets out to eliminate. Please route this path through the same lock (e.g. a small updateSessionTTLStamp(path) platform method), otherwise the invariant documented in the header does not hold.

8 字节的 WriteAt 在并发 gfile.GetBytes 下仍可能撕裂。若撕裂出的值刚好很小,GetSession 会把会话当成已过期并返回 nil, nil,这正是本 PR 想消除的"空会话读取"。请让该路径也走同一把锁(例如抽出一个 updateSessionTTLStamp(path) 平台方法),否则文件头声明的不变式不成立。

Scope note / 范围说明: mu 属于 *StorageFile 实例,两个指向同一目录的 storage 之间仍然不同步(Test_Issue4792 正是这种场景,net/ghttp/ghttp_server.go 也是每个 server 各自 NewStorageFile)。建议在描述里说明"仅保护同实例",避免被误读为对 #4792 的完整修复。


2. The new non-Unix code never runs in CI / 新增的非 Unix 代码在 CI 中零执行

.github/workflows/ci-main.yml is ubuntu-latest only, so gsession_storage_file_nonunix.go is never compiled or executed — the locking behaviour has no test coverage on any CI job. Suggest extracting the snapshot logic into build-tag-free helpers and letting the !unix methods delegate:

CI 只有 ubuntu-latest,gsession_storage_file_nonunix.go 从未被编译或执行,锁的行为在任何 CI job 上都没有覆盖。建议把快照读写抽成无 build tag 的公共函数,!unix 方法只做委托:

func (s *StorageFile) writeSessionSnapshotLocked(path string, content []byte) error
func (s *StorageFile) readSessionSnapshotLocked(path string) []byte

That makes the behaviour testable on Linux and keeps the repo's ">= 80% coverage for new code" rule satisfiable.

这样 Linux 上就能直接验证,也能满足仓库"新增代码覆盖率 ≥ 80%"的要求。


3. The Windows regression test hides the failure it targets / Windows 回归测试会掩盖它要抓的失败

// os/gsession/gsession_z_unit_storage_file_windows_test.go
got, err := storage.GetSession(ctx, sessionId, ttl)
if err == nil && got == nil {
    atomic.AddInt64(&nilReads, 1)
}

A torn read typically surfaces as a json.UnmarshalUseNumber error rather than nil, so err == nil && lets the test pass while the bug is still present. SetSession's error is also discarded by the writers, and total is incremented but never asserted — if every write fails, nilReads == 0 still succeeds.

撕裂读通常表现为 json.UnmarshalUseNumber 返回错误而不是 nil,err == nil && 会让 bug 存在时测试照样通过。此外写协程丢弃了 SetSession 的错误,total 只自增从未断言——即使所有写都失败,nilReads == 0 依然成立。

Please count err != nil as a failure as well, propagate write errors, and assert total > 0. The 2s time.Sleep can likely drop to a few hundred milliseconds without losing reproduction power.

建议把 err != nil 也算作失败、收集写错误并断言 total > 0;2 秒的 time.Sleep 应可缩短到几百毫秒而不影响复现。


4. Minor / 其他

  • Test_StorageFileSharedReader's comment still describes "the rename path falls back to direct write", which no longer exists on Windows. — 该测试注释描述的 rename 回退路径在 Windows 上已不存在。
  • gsession_z_unit_storage_file_expiry_test.go puts //go:build !windows after the license header; other files in the package keep build tags on line 1. — build tag 位置与包内其它文件不一致。
  • The new expiry / ttl tests overlap with gsession_z_unit_storage_file_path_internal_test.go (lines 47, 64, 171) and do not touch the code this PR changes. Either drop them or state why they belong here. — 新增测试与既有测试重复,且未覆盖本 PR 改动的代码,建议移除或说明理由。

Verified locally / 本地验证:go test ./os/gsession/ -count=1 -race passes; GOOS=windows, plan9, js/wasm cross-builds all succeed; golangci-lint -c .golangci.yml ./os/gsession/... reports 0 issues.

Happy to re-review once the updateSessionTTl locking and the Windows test assertions are addressed.
处理完 updateSessionTTl 的加锁和 Windows 测试断言后,我很乐意再评审一次。

@gqcn

gqcn commented Nov 26, 2026

Copy link
Copy Markdown
Member

Thanks for keeping at the Windows side of #4792. Putting the timestamp and payload into one Write under s.mu in setSessionFile, and reading through readSessionBytes, does close the empty-file window between SetSession and GetSession on a single StorageFile. Merging master did not change the points already raised on 0b212175, and they still apply to this head:

  • updateSessionTTl (os/gsession/gsession_storage_file.go:283) still WriteAts the timestamp without s.mu, and checkAndClearSessionFile (os/gsession/gsession_storage_file.go:299) still reads that file and may delete it without the lock. The header in os/gsession/gsession_storage_file_nonunix.go says this lock stops readers from observing a half-written file. A concurrent 8-byte WriteAt can still tear the timestamp; GetSession then treats a too-small value as expired and returns nil, nil, which is the same user-visible failure. A torn timestamp in the hourly cleaner can also delete a live session file. Holding s.mu on those two paths as well would match the header. Unix setSessionFile and readSessionBytes do not take mu, so this would not change the Unix rename publish path.
  • Test_Issue4792_WindowsConcurrentReadWrite (os/gsession/gsession_z_unit_storage_file_windows_test.go:88 and :100) still ignores the SetSession error, and only counts err == nil && got == nil. A torn payload usually comes back from json.UnmarshalUseNumber as an error, so the test can stay green while that failure is still present. total is never asserted, so a run where every write fails also passes. This file is //go:build windows, and the new lock is in //go:build !unix, so Linux CI never compiles it. It would help to fail on the first write or read error, assert that a write and a read both happened, and move the snapshot and lock helpers into a file without a build tag so CI actually runs them.
  • Two smaller notes are still open. The comment on Test_StorageFileSharedReader (os/gsession/gsession_z_unit_storage_file_windows_test.go:29) still says the rename path falls back to a direct write, which this change removed on Windows. The new expiry and TTL tests overlap os/gsession/gsession_z_unit_storage_file_path_internal_test.go and do not execute the non-Unix lock.
  • CI (codecov/project) failed on the current head: project coverage moved from 85.31% to 85.30% (+4 misses), while codecov/patch is green. Report: https://app.codecov.io/gh/gogf/gf/pull/4977 . This check needs to be green before merge. If the extra misses are outside this diff, rerunning coverage should be enough; unrelated tests are not needed for a noise drop.

I have not added the bot-approved label.

感谢继续补 #4792 在 Windows 上的缺口。setSessionFile 在 s.mu 下把时间戳和内容合成一次 Write,再经 readSessionBytes 读取,确实能关掉同一个 StorageFile 上 SetSession 与 GetSession 之间的空文件窗口。合并 master 并没有改掉此前在 0b212175 上提过的问题,它们在当前 head 上仍然成立:

  • updateSessionTTl(os/gsession/gsession_storage_file.go:283)仍在不持有 s.mu 的情况下 WriteAt 时间戳,checkAndClearSessionFile(os/gsession/gsession_storage_file.go:299)也会在不持锁时读取并可能删除同一文件。os/gsession/gsession_storage_file_nonunix.go 的文件头写的是这把锁能避免读者看到写了一半的文件。并发的 8 字节 WriteAt 仍可能把时间戳撕开;GetSession 会把偏小的值当成过期并返回 nil, nil,用户看到的还是同一种掉登录。清理任务若读到撕裂的时间戳,还可能删掉仍有效的会话文件。这两条路径也持有 s.mu 才和文件头一致。Unix 的 setSessionFile 和 readSessionBytes 并不使用 mu,因此这样做不会改变 Unix 上 rename 发布的行为。
  • Test_Issue4792_WindowsConcurrentReadWrite(os/gsession/gsession_z_unit_storage_file_windows_test.go:88 与 :100)仍然丢掉 SetSession 的错误,并且只统计 err == nil && got == nil。内容被撕裂时,json.UnmarshalUseNumber 通常返回错误,这样 bug 还在时测试也能通过。total 没有断言,所有写入都失败时测试同样会过。该文件是 //go:build windows,新锁在 //go:build !unix 里,Linux CI 不会编译到它们。建议写或读一出错就失败,并断言读写都实际发生过;把快照和加锁放到没有 build tag 的文件里,CI 才能跑到这条回归。
  • 还有两处较小的问题。Test_StorageFileSharedReader 的注释(os/gsession/gsession_z_unit_storage_file_windows_test.go:29)仍写着 rename 会退回直接写,这条路径在 Windows 上已经被本次改动去掉了。新增的过期和 TTL 测试与 os/gsession/gsession_z_unit_storage_file_path_internal_test.go 重叠,也没有执行到非 Unix 的锁。
  • CI(codecov/project)在当前 head 上失败了:项目覆盖率从 85.31% 降到 85.30%(多 4 行未覆盖),而 codecov/patch 是通过的。报告:https://app.codecov.io/gh/gogf/gf/pull/4977 。合并前需要先让这项检查变绿。如果多出来的未覆盖行不在本次 diff 里,重跑覆盖率即可,不必为这种波动去补无关测试。

这次还没有添加 bot-approved 标签。

This branch has not been deployed

No deployments
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.

3 participants