{"record":{"id":"b17997e11a480548","repo":"siyuan-note/siyuan","slug":"truncate-file-s-failed-s","errorCode":null,"errorMessage":"truncate file [%s] failed: %s","messagePattern":"truncate file \\[(.+?)\\] failed: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"critical","filePath":"kernel/util/mmap.go","lineNumber":47,"sourceCode":"// WriteFileByMmap 使用内存映射将 data 原地覆写到 filePath。\n//\n// 流程：OpenFile(O_RDWR|O_CREATE) → Truncate 到精确长度 → mmap.Map(RDWR) →\n// copy 写入 → Flush → Unmap，全程持有 filelock 的进程内互斥锁，避免并发写冲突。\n//\n// 相比 filelock.WriteFile（临时文件 + rename + fsync），此路径在进程级 I/O\n// 计数（IO Write Bytes）上几乎不计——copy 是纯内存写，不经过 I/O 子系统，\n// 只有 Flush 会产生极少量计入。出错时由调用方回退到 filelock.WriteFile。\nfunc WriteFileByMmap(filePath string, data []byte) (err error) {\n\tf, err := filelock.OpenFile(filePath, os.O_RDWR|os.O_CREATE, 0644)\n\tif err != nil {\n\t\treturn\n\t}\n\tdefer filelock.CloseFile(f)\n\n\tif err = f.Truncate(int64(len(data))); err != nil {\n\t\tmsg := fmt.Sprintf(\"truncate file [%s] failed: %s\", filePath, err)\n\t\tlogging.LogError(msg)\n\t\terr = errors.New(msg)\n\t\treturn\n\t}\n\n\tm, err := mmap.Map(f, mmap.RDWR, 0)\n\tif err != nil {\n\t\tmsg := fmt.Sprintf(\"map file [%s] failed: %s\", filePath, err)\n\t\tlogging.LogError(msg)\n\t\terr = errors.New(msg)\n\t\treturn\n\t}\n\tdefer m.Unmap()\n\n\tcopy(m, data)\n\tif err = m.Flush(); err != nil {\n\t\tmsg := fmt.Sprintf(\"flush data [%s] failed: %s\", filePath, err)\n\t\tlogging.LogError(msg)\n\t\terr = errors.New(msg)\n\t\treturn","sourceCodeStart":29,"sourceCodeEnd":65,"githubUrl":"https://github.com/siyuan-note/siyuan/blob/9f775e8a12daef8255556097396f9b2739078892/kernel/util/mmap.go#L29-L65","documentation":"WriteFileByMmap writes a file by truncating it to the new length and memory-mapping it. If f.Truncate fails (I/O error, full disk, unsupported filesystem, permission problem), the function logs and returns 'truncate file [...] failed: <os error>'. Used by WriteTree and saveAttributeView to persist .sy files and attribute views efficiently.","triggerScenarios":"Calling WriteFileByMmap (via WriteTree for a .sy document or saveAttributeView for an .av database) when the target filesystem rejects Truncate: disk full, read-only mount, file locked by another process, or a filesystem (some network mounts) that does not support ftruncate.","commonSituations":"Workspace on a full disk or quota-exceeded volume, sync client holding the file open on Windows, workspace on a network share (SMB/NFS) with poor ftruncate support, read-only mount after a crash.","solutions":["Free disk space or resolve quota limits on the workspace volume","Verify the file and volume are writable (check read-only mount, file locks, antivirus)","Check the embedded os error in the message: 'permission denied' -> fix ACLs; 'disk quota'/'no space' -> free space; 'invalid argument' -> filesystem may not support truncate, move workspace to a local disk","Retry saving after resolving; SiYuan will rewrite the file on the next save operation"],"exampleFix":null,"handlingStrategy":"try-catch","validationCode":"func canWriteFile(path string) error {\n    if st, err := os.Stat(path); err == nil && st.Mode()&0200 == 0 {\n        return errors.New(\"file is read-only\")\n    }\n    return checkDiskSpace(filepath.Dir(path))\n}","typeGuard":null,"tryCatchPattern":"if err := util.WriteFileByMmap(path, data); err != nil {\n    if strings.Contains(err.Error(), \"truncate file\") {\n        log.Errorf(\"persist failed (disk/lock/permission?): %v\", err)\n        // inspect wrapped OS error and alert the user before data loss\n    }\n    return err\n}","preventionTips":["Monitor free disk space on the workspace volume","Avoid placing the workspace on network shares or read-only mounts","Exclude workspace files from aggressive antivirus/sync file locking","Keep a backup since failed truncate may leave the file partially written"],"tags":["filesystem","mmap","io","persistence"],"backgroundTag":"file-write-failed","analyzedSha":"9f775e8a12daef8255556097396f9b2739078892","analyzedAt":"2026-09-19T03:17:15.984Z","contentChangedAt":"2026-09-19T03:17:15.984Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}