An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:perf: Append new document sort entries with local recovery https://github.com/siyuan-note/siyuan/issues/20369
Daniel1164b076314f
diff --git a/kernel/model/conf.go b/kernel/model/conf.goindex 84e647a9c5..4b2ef99243 100644--- a/kernel/model/conf.go+++ b/kernel/model/conf.go@@ -244,6 +244,10 @@ func InitConf() {if err := recoverNotebookArchiveOperations(); err != nil {logging.LogErrorf("recover notebook archive operations failed: %s", err)}+ if err := recoverSortConfAppends(); err != nil {+ logging.LogFatalf(logging.ExitCodeFileSysErr, "recover incremental sort conf failed: %s", err)+ return+ }clearEncryptedExportTempOnBoot()clearOldInstallPackages("")confPath := filepath.Join(util.ConfDir, "conf.json")diff --git a/kernel/model/export.go b/kernel/model/export.goindex 290d7ec53d..b6d6cb3ef1 100644--- a/kernel/model/export.go+++ b/kernel/model/export.go@@ -787,6 +787,9 @@ func ExportData() (zipPath string, err error) {func exportData(exportFolder string) (zipPath string, err error) {FlushTxQueue()+ if err = recoverSortConfAppends(); err != nil {+ return+ }if err = EnsureAllSyncAssets(); err != nil {return}@@ -2633,6 +2636,10 @@ func exportBoxSYZip(boxID string) (zipPath string) {func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, includeBoxConf bool) (zipPath string) {defer util.ClearPushProgress(100)+ if err := recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {+ logging.LogErrorf("recover export sort conf failed: %s", err)+ return+ }if err := prepareExportAssets(boxID, docPaths); err != nil {util.PushErrMsg(err.Error(), 7000)return@@ -2931,13 +2938,10 @@ func exportSYZip(boxID, rootDirPath, baseFolderName string, docPaths []string, ivar sortData []bytevar sortErr errorif filelock.IsExist(sortPath) {- sortData, sortErr = filelock.ReadFile(sortPath)+ fullSortIDs, sortErr = readSortConfMap(sortPath)if nil != sortErr {logging.LogErrorf("read sort conf failed: %s", sortErr)- }-- if sortErr = gulu.JSON.UnmarshalJSON(sortData, &fullSortIDs); nil != sortErr {- logging.LogErrorf("unmarshal sort conf failed: %s", sortErr)+ return}if 0 < len(fullSortIDs) {diff --git a/kernel/model/file.go b/kernel/model/file.goindex 25833a2c08..b068103791 100644--- a/kernel/model/file.go+++ b/kernel/model/file.go@@ -2510,29 +2510,49 @@ func normalizeDocTitle(title string) string {}func readSortConfMap(confPath string) (map[string]int, error) {+ ret, _, err := readSortConfMapData(confPath)+ return ret, err+}++func readSortConfMapData(confPath string) (map[string]int, []byte, error) {sortConfRecoveryLock.Lock()defer sortConfRecoveryLock.Unlock()+ if err := recoverSortConfAppend(confPath); err != nil {+ return nil, nil, err+ }if !filelock.IsExist(confPath) {- return map[string]int{}, nil+ return map[string]int{}, nil, nil}data, err := filelock.ReadFile(confPath)if err != nil {logging.LogErrorf("read sort conf [%s] failed: %s", confPath, err)- return nil, err+ return nil, nil, err}ret := map[string]int{}- if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil {- logging.LogWarnf("unmarshal sort conf [%s] failed: %s", confPath, err)- return recoverSortConfMap(confPath, data)- }- if ret == nil {- return recoverSortConfMap(confPath, data)+ err = gulu.JSON.UnmarshalJSON(data, &ret)+ if err != nil || ret == nil {+ logging.LogWarnf("unmarshal sort conf [%s] failed: %v", confPath, err)+ _, err = recoverSortConfMap(confPath, data)+ if err != nil {+ return nil, nil, err+ }+ data, err = filelock.ReadFile(confPath)+ if err != nil {+ return nil, nil, err+ }+ ret = map[string]int{}+ if err = gulu.JSON.UnmarshalJSON(data, &ret); err != nil || ret == nil {+ return nil, nil, fmt.Errorf("read recovered sort conf [%s]: %v", confPath, err)+ }}- return ret, nil+ return ret, data, nil}func writeSortConfMap(confPath string, fullSortIDs map[string]int) error {+ if err := recoverSortConfAppend(confPath); err != nil {+ return err+ }data, err := gulu.JSON.MarshalJSON(fullSortIDs)if err != nil {logging.LogErrorf("marshal sort conf [%s] failed: %s", confPath, err)@@ -3151,7 +3171,7 @@ func (box *Box) placeDocsInSiblingOrder(parentPath string, ids []string, targetIreturn fmt.Errorf("create conf dir failed: %w", err)}confPath := filepath.Join(confDir, "sort.json")- fullSortIDs, err := readSortConfMap(confPath)+ fullSortIDs, sortData, err := readSortConfMapData(confPath)if nil != err {fileTreeSortLock.Unlock()return err@@ -3192,6 +3212,17 @@ func (box *Box) placeDocsInSiblingOrder(parentPath string, ids []string, targetI}}orderedIDs = slices.Insert(orderedIDs, insertIndex, ids...)+ if "" == targetID {+ if additions, ok := newSiblingSortValues(currentIDs, ids, fullSortIDs, position); ok {+ if err = appendSortConfMap(confPath, sortData, additions); err != nil {+ fileTreeSortLock.Unlock()+ return err+ }+ fileTreeSortLock.Unlock()+ pushFiletreeSortChanged(additions)+ return nil+ }+ }sortIDs := make(map[string]int, len(orderedIDs))for i, orderedID := range orderedIDs {sortIDs[orderedID] = i + 1@@ -3206,6 +3237,52 @@ func (box *Box) placeDocsInSiblingOrder(parentPath string, ids []string, targetIreturn nil}+// newSiblingSortValues 只为未配置排序值的新文档分配首尾位置,溢出时交由完整重排处理。+func newSiblingSortValues(currentIDs, ids []string, fullSortIDs map[string]int, position string) (map[string]int, bool) {+ if len(ids) == 0 || len(ids) > 512 {+ return nil, false+ }+ moved := make(map[string]bool, len(ids))+ for _, id := range ids {+ if _, exists := fullSortIDs[id]; exists || moved[id] {+ return nil, false+ }+ moved[id] = true+ }+ minimum, maximum, found := 0, 0, false+ for _, id := range currentIDs {+ if moved[id] {+ continue+ }+ value := fullSortIDs[id]+ if !found {+ minimum, maximum, found = value, value, true+ } else {+ minimum, maximum = min(minimum, value), max(maximum, value)+ }+ }+ start := 1+ if found {+ maxInt := int(^uint(0) >> 1)+ if "after" == position {+ if maximum > maxInt-len(ids) {+ return nil, false+ }+ start = maximum + 1+ } else {+ if minimum < -maxInt-1+len(ids) {+ return nil, false+ }+ start = minimum - len(ids)+ }+ }+ ret := make(map[string]int, len(ids))+ for i, id := range ids {+ ret[id] = start + i+ }+ return ret, true+}+func (box *Box) addSort(previousPath, id string) {parentPath := path.Dir(previousPath)previousID := util.GetTreeID(previousPath)diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex d98aa7ac1a..8adaab5e6a 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -294,8 +294,8 @@ func TestCustomSortMaintenanceIgnoresEffectiveModeAndListLimit(t *testing.T) {if nil != err {t.Fatalf("read custom sort after append failed: %v", err)}- if 4 != sorts[maxID] {- t.Fatalf("append used effective display mode instead of complete custom order: got %d, want 4", sorts[maxID])+ if 31 != sorts[maxID] || sorts[extraID] != 30 {+ t.Fatalf("append did not preserve existing custom values: %v", sorts)}minID := "20260718000005-abcdefg"@@ -305,7 +305,7 @@ func TestCustomSortMaintenanceIgnoresEffectiveModeAndListLimit(t *testing.T) {if nil != err {t.Fatalf("read custom sort after prepend failed: %v", err)}- if 1 != sorts[minID] || 5 != sorts[maxID] {+ if 9 != sorts[minID] || 31 != sorts[maxID] {t.Fatalf("prepend did not preserve the complete custom order: prepend=%d, trailing=%d", sorts[minID], sorts[maxID])}diff --git a/kernel/model/mount.go b/kernel/model/mount.goindex efb9d62aa7..49922ccbe9 100644--- a/kernel/model/mount.go+++ b/kernel/model/mount.go@@ -324,6 +324,9 @@ func RemoveBox(boxID string) (err error) {defer databaseIndexDataLock.Unlock()createDocLock.Lock()defer createDocLock.Unlock()+ if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {+ return+ }if !isEncrypted {unmount0(boxID)}diff --git a/kernel/model/notebook_archive.go b/kernel/model/notebook_archive.goindex b87e66d2ed..7fb3e78c12 100644--- a/kernel/model/notebook_archive.go+++ b/kernel/model/notebook_archive.go@@ -303,6 +303,9 @@ func PrepareNotebookArchive(ids []string) (archiveID, downloadPath string, err e}defer release()for _, id := range ids {+ if err = recoverSortConfAppend(filepath.Join(util.DataDir, id, ".siyuan", "sort.json")); err != nil {+ return+ }if err = EnsureAssetPrefixLocal(filepath.Join(util.DataDir, id)); err != nil {return}diff --git a/kernel/model/repository.go b/kernel/model/repository.goindex 221b051d6c..18c44c3262 100644--- a/kernel/model/repository.go+++ b/kernel/model/repository.go@@ -3061,6 +3061,9 @@ func newCloudRepositoryWithAssetSourceLocked() (*dejavu.Repo, error) {// newRepositoryWithAssetSourceLocked 由已持有来源锁的调用方创建仓库,避免读写锁递归等待。func newRepositoryWithAssetSourceLocked() (ret *dejavu.Repo, err error) {+ if err = recoverSortConfAppends(); err != nil {+ return+ }cloudConf, err := buildCloudConf()if err != nil {returndiff --git a/kernel/model/sort_conf_append.go b/kernel/model/sort_conf_append.gonew file mode 100644index 0000000000..382d415795--- /dev/null+++ b/kernel/model/sort_conf_append.go@@ -0,0 +1,307 @@+package model++import (+ "bytes"+ "crypto/sha256"+ "encoding/json"+ "errors"+ "fmt"+ "io"+ "os"+ "path/filepath"+ "runtime"+ "strings"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/logging"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const sortConfAppendMaxRecordBytes = 64 * 1024++// sortConfAppendRecord 只保存新增尾部和未改动前缀的摘要,恢复记录留在本机,不参与同步。+type sortConfAppendRecord struct {+ Version int `json:"version"`+ Offset int64 `json:"offset"`+ OriginalSize int64 `json:"originalSize"`+ PrefixHash string `json:"prefixHash"`+ Suffix []byte `json:"suffix"`+}++func sortConfAppendDir() string {+ return filepath.Join(filepath.Dir(util.DataDir), "temp", "sort-write")+}++func sortConfAppendPath(confPath string) (string, error) {+ rel, err := filepath.Rel(util.DataDir, confPath)+ if err != nil {+ return "", err+ }+ parts := strings.Split(filepath.ToSlash(rel), "/")+ if len(parts) != 3 || !ast.IsNodeIDPattern(parts[0]) || parts[1] != ".siyuan" || parts[2] != "sort.json" {+ return "", fmt.Errorf("invalid incremental sort conf path [%s]", confPath)+ }+ return filepath.Join(sortConfAppendDir(), parts[0]+".json"), nil+}++func newSortConfAppendRecord(data []byte, additions map[string]int) (*sortConfAppendRecord, error) {+ trimmed := bytes.TrimSpace(data)+ var existing map[string]int+ if len(trimmed) < 2 || trimmed[0] != '{' || trimmed[len(trimmed)-1] != '}' ||+ json.Unmarshal(data, &existing) != nil || existing == nil {+ return nil, errors.New("invalid sort conf for incremental write")+ }+ for id := range additions {+ if !ast.IsNodeIDPattern(id) {+ return nil, fmt.Errorf("invalid sort ID [%s]", id)+ }+ if _, exists := existing[id]; exists {+ return nil, fmt.Errorf("sort ID [%s] already exists", id)+ }+ }+ encoded, err := json.Marshal(additions)+ if err != nil {+ return nil, err+ }+ suffix := encoded[1:]+ if len(existing) > 0 {+ suffix = append([]byte{','}, suffix...)+ }+ offset := bytes.LastIndexByte(data, '}')+ return &sortConfAppendRecord{+ Version: 1, Offset: int64(offset), OriginalSize: int64(len(data)),+ PrefixHash: fmt.Sprintf("%x", sha256.Sum256(data[:offset])), Suffix: suffix,+ }, nil+}++// verifySortConfAppend 校验前缀和长度,不覆盖被替换的配置或未知格式。+func verifySortConfAppend(file *os.File, record *sortConfAppendRecord) error {+ if record.Version != 1 || record.Offset < 1 || record.OriginalSize <= record.Offset ||+ len(record.PrefixHash) != sha256.Size*2 || len(record.Suffix) < 2 ||+ len(record.Suffix) > sortConfAppendMaxRecordBytes {+ return errors.New("invalid sort append recovery record")+ }+ var additions map[string]int+ if err := json.Unmarshal(append([]byte{'{'}, bytes.TrimPrefix(record.Suffix, []byte{','})...), &additions); err != nil || len(additions) == 0 {+ return errors.New("invalid sort append recovery entries")+ }+ for id := range additions {+ if !ast.IsNodeIDPattern(id) {+ return fmt.Errorf("invalid recovery sort ID [%s]", id)+ }+ }+ info, err := file.Stat()+ if err != nil {+ return err+ }+ newSize := record.Offset + int64(len(record.Suffix))+ if info.Size() < record.Offset || info.Size() > max(record.OriginalSize, newSize) {+ return errors.New("sort conf size changed outside incremental write")+ }+ digest := sha256.New()+ if _, err = io.CopyN(digest, io.NewSectionReader(file, 0, record.Offset), record.Offset); err != nil {+ return err+ }+ if fmt.Sprintf("%x", digest.Sum(nil)) != record.PrefixHash {+ return errors.New("sort conf prefix changed outside incremental write")+ }+ decoder := json.NewDecoder(io.NewSectionReader(file, 0, record.Offset))+ token, err := decoder.Token()+ if err != nil || token != json.Delim('{') || decoder.More() != (record.Suffix[0] == ',') {+ return errors.New("sort append separator does not match the source object")+ }+ tail, err := io.ReadAll(io.NewSectionReader(file, record.Offset, info.Size()-record.Offset))+ if err != nil {+ return err+ }+ tail = bytes.TrimSpace(tail)+ if !bytes.Equal(tail, []byte("}")) && !bytes.Equal(tail, record.Suffix) {+ // 完整但不同的 JSON 尾部表示配置已被其他写入替换,不把它当作未完成的写入。+ candidate := append([]byte{'{'}, bytes.TrimPrefix(tail, []byte{','})...)+ if json.Valid(candidate) {+ return errors.New("sort conf entries changed outside incremental write")+ }+ }+ return nil+}++func applySortConfAppend(file *os.File, record *sortConfAppendRecord) error {+ if err := verifySortConfAppend(file, record); err != nil {+ return err+ }+ return writeSortConfAppendTail(file, record)+}++func writeSortConfAppendTail(file *os.File, record *sortConfAppendRecord) error {+ if n, writeErr := file.WriteAt(record.Suffix, record.Offset); writeErr != nil {+ return writeErr+ } else if n != len(record.Suffix) {+ return io.ErrShortWrite+ }+ if err := file.Truncate(record.Offset + int64(len(record.Suffix))); err != nil {+ return err+ }+ return file.Sync()+}++// appendSortConfMap 保持标准 JSON 对象,只有新增条目使用可恢复的尾部写入。+func appendSortConfMap(confPath string, data []byte, additions map[string]int) (err error) {+ if err = recoverSortConfAppend(confPath); err != nil {+ return+ }+ if !filelock.IsExist(confPath) {+ if len(data) != 0 {+ return errors.New("sort conf removed before incremental write")+ }+ return writeSortConfMap(confPath, additions)+ }+ recordPath, err := sortConfAppendPath(confPath)+ if err != nil {+ return+ }+ file, err := filelock.OpenFile(confPath, os.O_RDWR, 0644)+ if err != nil {+ return+ }+ defer func() { err = errors.Join(err, filelock.CloseFile(file)) }()+ info, err := file.Stat()+ if err != nil {+ return+ }+ if info.Size() != int64(len(data)) {+ return errors.New("sort conf changed before incremental write")+ }+ record, err := newSortConfAppendRecord(data, additions)+ if err != nil {+ return+ }+ encoded, err := json.Marshal(record)+ if err != nil {+ return+ }+ if len(encoded) > sortConfAppendMaxRecordBytes {+ return errors.New("sort append recovery record exceeds size limit")+ }+ if err = verifySortConfAppend(file, record); err != nil {+ return+ }+ if err = os.MkdirAll(filepath.Dir(recordPath), 0700); err != nil {+ return+ }+ if err = syncSortConfAppendDir(filepath.Dir(filepath.Dir(recordPath))); err != nil {+ return+ }+ if err = filelock.WriteFile(recordPath, encoded); err != nil {+ return+ }+ // 刷新重命名后的恢复文件及支持目录刷新平台上的目录项,再开始修改源文件。+ if err = syncSortConfAppendRecord(recordPath); err != nil {+ return+ }+ if err = writeSortConfAppendTail(file, record); err != nil {+ // 写入失败时保留恢复记录和未改动的前缀,后续读取或启动时重放。+ return+ }+ return removeSortConfAppendRecord(recordPath)+}++func syncSortConfAppendDir(dir string) error {+ if runtime.GOOS == "windows" {+ return nil+ }+ file, err := os.Open(dir)+ if err != nil {+ return err+ }+ return errors.Join(file.Sync(), file.Close())+}++func syncSortConfAppendRecord(recordPath string) error {+ file, err := os.OpenFile(recordPath, os.O_RDWR, 0600)+ if err != nil {+ return err+ }+ if err = errors.Join(file.Sync(), file.Close()); err != nil {+ return err+ }+ return syncSortConfAppendDir(filepath.Dir(recordPath))+}++func removeSortConfAppendRecord(recordPath string) error {+ if err := os.Remove(recordPath); err != nil {+ return err+ }+ return syncSortConfAppendDir(filepath.Dir(recordPath))+}++func recoverSortConfAppend(confPath string) (err error) {+ recordPath, pathErr := sortConfAppendPath(confPath)+ if pathErr != nil {+ return nil+ }+ if _, err = os.Stat(recordPath); os.IsNotExist(err) {+ return nil+ } else if err != nil {+ return+ }+ file, err := filelock.OpenFile(confPath, os.O_RDWR, 0644)+ if err != nil {+ return+ }+ defer func() { err = errors.Join(err, filelock.CloseFile(file)) }()+ info, err := os.Stat(recordPath)+ if os.IsNotExist(err) {+ return nil+ } else if err != nil {+ return+ }+ if info.Size() > sortConfAppendMaxRecordBytes {+ return errors.New("sort append recovery record exceeds size limit")+ }+ data, err := filelock.ReadFile(recordPath)+ if err != nil {+ return+ }+ var record sortConfAppendRecord+ if err = json.Unmarshal(data, &record); err != nil {+ return+ }+ if err = applySortConfAppend(file, &record); err != nil {+ return+ }+ if err = removeSortConfAppendRecord(recordPath); err != nil {+ return+ }+ logging.LogInfof("recovered incremental sort conf [%s]", confPath)+ if Conf != nil && Conf.Sync != nil {+ IncSync()+ } else {+ // 启动恢复发生在同步配置加载前,先标记待同步状态。+ syncSameCount.Store(0)+ pendingSync.change(notifySyncPending)+ }+ return nil+}++func recoverSortConfAppends() error {+ entries, err := os.ReadDir(sortConfAppendDir())+ if os.IsNotExist(err) {+ return nil+ } else if err != nil {+ return err+ }+ for _, entry := range entries {+ if entry.IsDir() || !strings.HasSuffix(entry.Name(), ".json") {+ continue+ }+ boxID := strings.TrimSuffix(entry.Name(), ".json")+ if !ast.IsNodeIDPattern(boxID) {+ return fmt.Errorf("invalid sort recovery notebook [%s]", boxID)+ }+ if err = recoverSortConfAppend(filepath.Join(util.DataDir, boxID, ".siyuan", "sort.json")); err != nil {+ return err+ }+ }+ return nil+}diff --git a/kernel/model/sort_conf_append_test.go b/kernel/model/sort_conf_append_test.gonew file mode 100644index 0000000000..85d90f4435--- /dev/null+++ b/kernel/model/sort_conf_append_test.go@@ -0,0 +1,301 @@+package model++import (+ "bytes"+ "encoding/json"+ "fmt"+ "os"+ "path/filepath"+ "reflect"+ "testing"++ "github.com/siyuan-note/filelock"+ "github.com/siyuan-note/siyuan/kernel/util"+)++const appendSortOldID = "20261010000001-abcdefg"+const appendSortNewID = "20261010000002-abcdefg"++func TestSortConfAppendReadersObserveCompleteJSON(t *testing.T) {+ initial := []byte(`{"` + appendSortOldID + `":7}`)+ confPath := prepareSortConfAppendTest(t, initial)+ stop, done := make(chan struct{}), make(chan struct{})+ failures := make(chan error, 1)+ go func() {+ defer close(done)+ for {+ select {+ case <-stop:+ return+ default:+ }+ data, err := filelock.ReadFile(confPath)+ if err != nil || !json.Valid(data) {+ failures <- fmt.Errorf("reader observed incomplete JSON: %q, %v", data, err)+ return+ }+ }+ }()+ defer func() { close(stop); <-done }()+ for i := 0; i < 20; i++ {+ _, data, err := readSortConfMapData(confPath)+ if err != nil {+ t.Fatal(err)+ }+ id := fmt.Sprintf("20261010000002-%07d", i)+ if err = appendSortConfMap(confPath, data, map[string]int{id: i + 8}); err != nil {+ t.Fatal(err)+ }+ }+ select {+ case err := <-failures:+ t.Fatal(err)+ default:+ }+}++func prepareSortConfAppendTest(t *testing.T, data []byte) string {+ t.Helper()+ oldDataDir, oldConf := util.DataDir, Conf+ util.DataDir = filepath.Join(t.TempDir(), "data")+ Conf = NewAppConf()+ t.Cleanup(func() { util.DataDir, Conf = oldDataDir, oldConf })+ confPath := filepath.Join(util.DataDir, "20261010000000-sortbox", ".siyuan", "sort.json")+ if err := os.MkdirAll(filepath.Dir(confPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(confPath, data, 0644); err != nil {+ t.Fatal(err)+ }+ return confPath+}++func saveSortConfAppendTestRecord(t *testing.T, confPath string, record *sortConfAppendRecord) string {+ t.Helper()+ recordPath, err := sortConfAppendPath(confPath)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.MkdirAll(filepath.Dir(recordPath), 0700); err != nil {+ t.Fatal(err)+ }+ encoded, err := json.Marshal(record)+ if err != nil {+ t.Fatal(err)+ }+ if err = os.WriteFile(recordPath, encoded, 0600); err != nil {+ t.Fatal(err)+ }+ return recordPath+}++func TestSortConfAppendPreservesLegacyJSONAndBoundsWrittenBytes(t *testing.T) {+ initial := []byte("{\n\t\"" + appendSortOldID + "\": -20\n}\n")+ confPath := prepareSortConfAppendTest(t, initial)+ originalInfo, err := os.Stat(confPath)+ if err != nil {+ t.Fatal(err)+ }+ totalIncrementalBytes, totalFullBytes := 0, 0+ for i := 1; i <= 120; i++ {+ _, data, err := readSortConfMapData(confPath)+ if err != nil {+ t.Fatal(err)+ }+ id := fmt.Sprintf("20261010000002-%07d", i)+ additions := map[string]int{id: i}+ record, err := newSortConfAppendRecord(data, additions)+ if err != nil {+ t.Fatal(err)+ }+ encoded, _ := json.Marshal(record)+ written := len(encoded) + len(record.Suffix)+ if written > 512 {+ t.Fatalf("single-document write grew with notebook size: %d bytes", written)+ }+ totalIncrementalBytes += written+ if err = appendSortConfMap(confPath, data, additions); err != nil {+ t.Fatal(err)+ }+ actual, err := os.ReadFile(confPath)+ if err != nil || !json.Valid(actual) {+ t.Fatalf("append did not leave standard JSON: %q, %v", actual, err)+ }+ totalFullBytes += len(actual)+ if !bytes.HasPrefix(actual, initial[:bytes.LastIndexByte(initial, '}')]) {+ t.Fatal("append rewrote the existing JSON prefix")+ }+ sorts, err := readSortConfMap(confPath)+ if err != nil || sorts[appendSortOldID] != -20 || sorts[id] != i || len(sorts) != i+1 {+ t.Fatalf("legacy or added values lost: %v, %v", sorts, err)+ }+ }+ info, err := os.Stat(confPath)+ if err != nil || !os.SameFile(originalInfo, info) {+ t.Fatalf("incremental writes replaced the whole file: %v", err)+ }+ entries, err := os.ReadDir(sortConfAppendDir())+ if err != nil || len(entries) != 0 {+ t.Fatalf("completed appends retained recovery files: %v, %v", entries, err)+ }+ t.Logf("120 creates: incremental data and recovery records %d bytes, whole-file baseline %d bytes", totalIncrementalBytes, totalFullBytes)+}++func TestSortConfAppendRecoveryAtEveryWriteStage(t *testing.T) {+ for _, empty := range []bool{false, true} {+ initial := []byte(`{"` + appendSortOldID + `":-7}`)+ if empty {+ initial = []byte(" { } \n")+ }+ initial = append(initial, bytes.Repeat([]byte(" "), 512)...)+ for _, stage := range []string{"prepared", "partial", "written", "untruncated"} {+ t.Run(fmt.Sprintf("empty=%t/%s", empty, stage), func(t *testing.T) {+ confPath := prepareSortConfAppendTest(t, initial)+ record, err := newSortConfAppendRecord(initial, map[string]int{appendSortNewID: 8})+ if err != nil {+ t.Fatal(err)+ }+ recordPath := saveSortConfAppendTestRecord(t, confPath, record)+ if stage != "prepared" {+ n := len(record.Suffix)+ if stage == "partial" {+ n /= 2+ }+ partial := append(bytes.Clone(initial[:record.Offset]), record.Suffix[:n]...)+ if stage == "untruncated" {+ partial = append(partial, bytes.Repeat([]byte(" "), len(initial)-len(partial))...)+ }+ if err = os.WriteFile(confPath, partial, 0644); err != nil {+ t.Fatal(err)+ }+ }+ if err = recoverSortConfAppends(); err != nil {+ t.Fatal(err)+ }+ actual, err := readSortConfMap(confPath)+ want := map[string]int{appendSortNewID: 8}+ if !empty {+ want[appendSortOldID] = -7+ }+ if err != nil || !reflect.DeepEqual(actual, want) {+ t.Fatalf("interrupted write lost sorting: %v, %v", actual, err)+ }+ if _, err = os.Stat(recordPath); !os.IsNotExist(err) {+ t.Fatalf("recovery record retained: %v", err)+ }+ if err = recoverSortConfAppends(); err != nil {+ t.Fatal(err)+ }+ })+ }+ }+}++func TestSortConfAppendRecoveryRejectsChangedSourceAndUnknownRecords(t *testing.T) {+ for _, mode := range []string{"prefix", "length", "version", "entries", "separator", "replacement"} {+ t.Run(mode, func(t *testing.T) {+ initial := []byte(`{"` + appendSortOldID + `":7}`)+ confPath := prepareSortConfAppendTest(t, initial)+ record, err := newSortConfAppendRecord(initial, map[string]int{appendSortNewID: 8})+ if err != nil {+ t.Fatal(err)+ }+ actual := bytes.Clone(initial)+ switch mode {+ case "prefix":+ actual[len(actual)-2] = '9'+ case "length":+ actual = append(actual, bytes.Repeat([]byte(" "), 200)...)+ case "version":+ record.Version = 2+ case "entries":+ record.Suffix = []byte(`,"invalid":"value"}`)+ case "separator":+ record.Suffix = bytes.TrimPrefix(record.Suffix, []byte{','})+ case "replacement":+ actual = append(bytes.Clone(initial[:record.Offset]), []byte(`,"20261010000003-abcdefg":9}`)...)+ }+ recordPath := saveSortConfAppendTestRecord(t, confPath, record)+ if err = os.WriteFile(confPath, actual, 0644); err != nil {+ t.Fatal(err)+ }+ if _, err = readSortConfMap(confPath); err == nil {+ t.Fatal("invalid recovery was ignored")+ }+ preserved, err := os.ReadFile(confPath)+ if err != nil || !bytes.Equal(preserved, actual) {+ t.Fatalf("rejected recovery changed source: %q, %v", preserved, err)+ }+ if _, err = os.Stat(recordPath); err != nil {+ t.Fatalf("rejected recovery discarded the record: %v", err)+ }+ })+ }+}++func TestNewSiblingSortValuesPreservesRanksAndHandlesOverflow(t *testing.T) {+ maxInt := int(^uint(0) >> 1)+ for _, position := range []string{"before", "after"} {+ current := []string{appendSortOldID, appendSortNewID, "unranked"}+ ranks := map[string]int{appendSortOldID: -4}+ got, ok := newSiblingSortValues(current, []string{appendSortNewID}, ranks, position)+ want := 1+ if position == "before" {+ want = -5+ }+ if !ok || got[appendSortNewID] != want || ranks[appendSortOldID] != -4 {+ t.Fatalf("bad extreme rank: %v, %v", got, ok)+ }+ if position == "after" {+ ranks[appendSortOldID] = maxInt+ } else {+ ranks[appendSortOldID] = -maxInt - 1+ }+ if _, ok = newSiblingSortValues(current, []string{appendSortNewID}, ranks, position); ok {+ t.Fatal("rank overflow did not request complete reordering")+ }+ }+}++func TestSortConfAppendRecoversBeforeRepositoryCreation(t *testing.T) {+ prepareAssetDownloadRepoTest(t)+ confPath := filepath.Join(util.DataDir, "20261010000000-sortbox", ".siyuan", "sort.json")+ initial := []byte(`{"` + appendSortOldID + `":7}`)+ if err := os.MkdirAll(filepath.Dir(confPath), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(confPath, initial, 0644); err != nil {+ t.Fatal(err)+ }+ record, err := newSortConfAppendRecord(initial, map[string]int{appendSortNewID: 8})+ if err != nil {+ t.Fatal(err)+ }+ saveSortConfAppendTestRecord(t, confPath, record)+ if err = os.WriteFile(confPath, initial[:record.Offset], 0644); err != nil {+ t.Fatal(err)+ }+ repo, err := newRepository()+ if err != nil {+ t.Fatal(err)+ }+ index, err := repo.Index("recovered sort", true, nil)+ if err != nil {+ t.Fatal(err)+ }+ for _, id := range index.Files {+ file, err := repo.GetFile(id)+ if err != nil {+ t.Fatal(err)+ }+ if file.Path == "/20261010000000-sortbox/.siyuan/sort.json" {+ data, err := repo.OpenFile(file)+ var actual map[string]int+ if err != nil || json.Unmarshal(data, &actual) != nil || actual[appendSortNewID] != 8 || actual[appendSortOldID] != 7 {+ t.Fatalf("snapshot did not preserve recovered standard JSON: %q, %v", data, err)+ }+ return+ }+ }+ t.Fatal("sort conf absent from snapshot")+}