Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:bug: Reconcile repaired block identities and preserve ambiguous data https://github.com/siyuan-note/siyuan/issues/20928

Daniel99a5ac824161
diff --git a/kernel/model/index_fix.go b/kernel/model/index_fix.go
index 1146045b8f..9eba8145d2 100644
--- a/kernel/model/index_fix.go
+++ b/kernel/model/index_fix.go
@@ -36,6 +36,7 @@ import (
"github.com/88250/lute/parse"
"github.com/siyuan-note/filelock"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/av"
"github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
@@ -247,6 +248,10 @@ func resetDuplicateBlocksOnFileSysBeforeWrite(beforeWrite func(*parse.Tree)) err
if IsEncryptedBox(box.ID) && !IsBoxUnlocked(box.ID) {
continue
}
+ boundary := ""
+ if IsEncryptedBox(box.ID) {
+ boundary = box.ID
+ }
// 校验索引阶段自动删除历史遗留的笔记本 history 文件夹
legacyHistory := filepath.Join(util.DataDir, box.ID, ".siyuan", "history")
if gulu.File.IsDir(legacyHistory) {
@@ -321,11 +326,12 @@ func resetDuplicateBlocksOnFileSysBeforeWrite(beforeWrite func(*parse.Tree)) err
if "" == n.ID {
needOverwrite = true
treenode.ResetNodeID(n)
+ blockIDs[boundary+"/"+n.ID] = true
return ast.WalkContinue
}
- if !blockIDs[n.ID] {
- blockIDs[n.ID] = true
+ if !blockIDs[boundary+"/"+n.ID] {
+ blockIDs[boundary+"/"+n.ID] = true
return ast.WalkContinue
}
@@ -341,7 +347,22 @@ func resetDuplicateBlocksOnFileSysBeforeWrite(beforeWrite func(*parse.Tree)) err
// 其他情况,重置节点 ID
needOverwrite = true
+ oldID := n.ID
treenode.ResetNodeID(n)
+ blockIDs[boundary+"/"+n.ID] = true
+ // A tab's selected child has an explicit structural owner, unlike global block references.
+ if n.Type == ast.NodeTabItem && n.Parent != nil && n.Parent.IALAttr(treenode.TabsActiveIDAttr) == oldID {
+ count := 0
+ for child := n.Parent.FirstChild; child != nil; child = child.Next {
+ if child == n || child.ID == oldID {
+ count++
+ }
+ }
+ if count == 1 {
+ n.Parent.SetIALAttr(treenode.TabsActiveIDAttr, n.ID)
+ }
+ }
+ logging.LogWarnf("duplicate block ID repaired [%s%s]: [%s] -> [%s]; ambiguous references, database bindings and flashcard records retain their original IDs for manual review", tree.Box, tree.Path, oldID, n.ID)
needRefreshUI = true
return ast.WalkContinue
})
@@ -351,11 +372,32 @@ func resetDuplicateBlocksOnFileSysBeforeWrite(beforeWrite func(*parse.Tree)) err
beforeWrite(tree)
}
logging.LogWarnf("exist more than one node with the same id in tree [%s], reset it", box.ID+p)
+ if err := saveIndexRepairHistory(tree, original); err != nil {
+ return err
+ }
if _, writeErr := filesys.WriteTreeIfUnchanged(tree, original); nil != writeErr {
logging.LogErrorf("write tree [%s] failed: %s", p, writeErr)
return writeErr
}
}
+ if !duplicateRoot && (needOverwrite || !indexRepairIdentitiesMatch(tree)) {
+ var mirrors []*ast.Node
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && node.Type == ast.NodeAttributeView {
+ mirrors = append(mirrors, node)
+ }
+ return ast.WalkContinue
+ })
+ if err := av.AddCopiedBlockRels(boundary, mirrors); err != nil {
+ return err
+ }
+ // Queue recovery before publishing the new block identities. If interrupted before
+ // this point, the next scan still sees the source/index mismatch, even at equal timestamps.
+ sql.UpsertTreeQueue(tree)
+ if err := treenode.ReplaceBlockTree(tree); err != nil {
+ return err
+ }
+ }
return nil
}); walkErr != nil {
return walkErr
@@ -379,6 +421,65 @@ func resetDuplicateBlocksOnFileSysBeforeWrite(beforeWrite func(*parse.Tree)) err
return nil
}
+func indexRepairIdentitiesMatch(tree *parse.Tree) bool {
+ indexed := treenode.GetBlockTreesByRootIDInBox(tree.ID, tree.Box)
+ nodes := map[string]*ast.Node{}
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && node.IsBlock() && node.ID != "" {
+ nodes[node.ID] = node
+ }
+ return ast.WalkContinue
+ })
+ if len(indexed) != len(nodes) {
+ return false
+ }
+ for _, block := range indexed {
+ node := nodes[block.ID]
+ if node == nil || block.BoxID != tree.Box || block.Path != tree.Path || block.Type != treenode.TypeAbbr(node.Type.String()) {
+ return false
+ }
+ if node.Parent != nil && block.ParentID != node.Parent.ID {
+ return false
+ }
+ }
+ return true
+}
+
+// Keep the exact source bytes, including existing encryption, before changing identities.
+func saveIndexRepairHistory(tree *parse.Tree, original []byte) error {
+ if util.HistoryDir == "" {
+ return errors.New("document repair history directory is unavailable")
+ }
+ if err := os.MkdirAll(util.HistoryDir, 0700); err != nil {
+ return err
+ }
+ stamp := time.Now()
+ for attempt := 0; attempt < 1000; attempt++ {
+ dir := filepath.Join(util.HistoryDir, stamp.Add(time.Duration(attempt)*time.Second).Format("2006-01-02-150405")+"-"+HistoryOpFormat)
+ filename := filepath.Join(dir, tree.Box, tree.Path)
+ if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {
+ return err
+ }
+ file, err := os.OpenFile(filename, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0600)
+ if os.IsExist(err) {
+ continue
+ }
+ if err != nil {
+ return err
+ }
+ _, writeErr := file.Write(original)
+ if writeErr == nil {
+ writeErr = file.Sync()
+ }
+ err = errors.Join(writeErr, file.Close())
+ if err == nil {
+ generateAvHistoryInTree(tree, dir)
+ }
+ return err
+ }
+ return errors.New("document repair history names exhausted")
+}
+
func recreateTree(tree *parse.Tree, absPath string, original []byte) error {
FlushTxQueue()
flushLock.Lock()
diff --git a/kernel/model/index_fix_concurrency_test.go b/kernel/model/index_fix_concurrency_test.go
index b6303a01b6..ce1e8c7e30 100644
--- a/kernel/model/index_fix_concurrency_test.go
+++ b/kernel/model/index_fix_concurrency_test.go
@@ -14,6 +14,9 @@ import (
func TestIndexFixPreservesNewerDocumentEdit(t *testing.T) {
fixture := setupFileOperationTest(t)
+ previousHistory := util.HistoryDir
+ util.HistoryDir = t.TempDir()
+ t.Cleanup(func() { util.HistoryDir = previousHistory })
target, err := LoadTreeByBlockID(fixture.targetID)
if err != nil {
t.Fatal(err)
@@ -76,3 +79,27 @@ func TestIndexFixRootRecreationRejectsStaleSnapshot(t *testing.T) {
t.Fatalf("root recreation changed newer source: %v", err)
}
}
+
+func TestIndexFixHistoryDoesNotOverwriteEarlierRepair(t *testing.T) {
+ fixture := setupFileOperationTest(t)
+ previousHistory := util.HistoryDir
+ util.HistoryDir = t.TempDir()
+ t.Cleanup(func() { util.HistoryDir = previousHistory })
+ tree, original, err := filesys.LoadTreeSnapshot(fixture.box.ID, fixture.sourcePath, util.NewLute())
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, snapshot := range [][]byte{original, append(append([]byte{}, original...), '\n')} {
+ if err = saveIndexRepairHistory(tree, snapshot); err != nil {
+ t.Fatal(err)
+ }
+ }
+ histories, err := filepath.Glob(filepath.Join(util.HistoryDir, "*-format", tree.Box, filepath.Base(tree.Path)))
+ if err != nil || len(histories) != 2 {
+ t.Fatalf("repair history was overwritten: %v %v", histories, err)
+ }
+ first, err := os.ReadFile(histories[0])
+ if err != nil || !bytes.Equal(first, original) {
+ t.Fatal("the earlier repair snapshot changed", err)
+ }
+}
diff --git a/kernel/model/index_fix_identity_fts5_test.go b/kernel/model/index_fix_identity_fts5_test.go
new file mode 100644
index 0000000000..bf0fc255ea
--- /dev/null
+++ b/kernel/model/index_fix_identity_fts5_test.go
@@ -0,0 +1,201 @@
+//go:build fts5
+
+package model
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func isolateIndexRepairPaths(t *testing.T) {
+ t.Helper()
+ oldHistory, oldQueue := util.HistoryDir, util.QueueDir
+ util.HistoryDir, util.QueueDir = t.TempDir(), t.TempDir()
+ t.Cleanup(func() { util.HistoryDir, util.QueueDir = oldHistory, oldQueue })
+}
+
+func assertIndexRepairDocument(t *testing.T, tree *parse.Tree) {
+ t.Helper()
+ if !indexRepairIdentitiesMatch(tree) {
+ t.Fatal("source and block-tree identities differ")
+ }
+ ast.Walk(tree.Root, func(node *ast.Node, entering bool) ast.WalkStatus {
+ if entering && node.IsBlock() && node.ID != "" {
+ block := sql.GetBlockInBox(node.ID, tree.Box)
+ if block == nil || block.RootID != tree.ID || block.Path != tree.Path {
+ t.Fatalf("source and SQL identities differ for %s: %+v", node.ID, block)
+ }
+ }
+ return ast.WalkContinue
+ })
+}
+
+func TestIndexFixDuplicateChildRebuildsIndexesAndPreservesAmbiguousData(t *testing.T) {
+ fixture, view, _, _ := setupAttributeViewItemsTest(t, false)
+ isolateIndexRepairPaths(t)
+ source, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ target, err := LoadTreeByBlockID(fixture.targetID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ oldTargetID := target.Root.FirstChild.ID
+ sql.UpsertTreeQueue(source)
+ sql.UpsertTreeQueue(target)
+ sql.FlushQueue()
+ duplicateID := source.Root.FirstChild.ID
+ duplicated := target.Root.FirstChild
+ duplicated.ID = duplicateID
+ duplicated.SetIALAttr("id", duplicateID)
+ duplicated.SetIALAttr(av.NodeAttrNameAvs, view.ID)
+ duplicated.SetIALAttr(NodeAttrRiffDecks, "20230218211946-2kw8jgx")
+ duplicated.AppendChild(&ast.Node{Type: ast.NodeTextMark, TextMarkType: "block-ref", TextMarkBlockRefID: duplicateID, TextMarkBlockRefSubtype: "s", TextMarkTextContent: "Ambiguous"})
+ row := view.GetBlockKeyValues().Values[0]
+ row.IsDetached, row.Block.ID = false, duplicateID
+ if err = av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ viewPath := av.GetAttributeViewDataPath(view.ID)
+ viewBefore, err := os.ReadFile(viewPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err = filesys.WriteTree(target); err != nil {
+ t.Fatal(err)
+ }
+ updated := target.Root.IALAttr("updated")
+ filename := filepath.Join(util.DataDir, target.Box, target.Path)
+ original, err := os.ReadFile(filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = resetDuplicateBlocksOnFileSys(); err != nil {
+ t.Fatal(err)
+ }
+ sql.FlushQueue()
+ repaired, _, err := filesys.ReadTreeSnapshot(target.Box, target.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ node := repaired.Root.FirstChild
+ if node.ID == duplicateID || repaired.Root.IALAttr("updated") != updated {
+ t.Fatal("fixture did not exercise ID repair without a root timestamp change")
+ }
+ assertIndexRepairDocument(t, source)
+ assertIndexRepairDocument(t, repaired)
+ if treenode.GetBlockTreeInExactBox(oldTargetID, target.Box) != nil || sql.GetBlockInBox(oldTargetID, target.Box) != nil {
+ t.Fatal("obsolete target identity remained indexed")
+ }
+ if node.LastChild.TextMarkBlockRefID != duplicateID || node.IALAttr(av.NodeAttrNameAvs) != view.ID || node.IALAttr(NodeAttrRiffDecks) != "20230218211946-2kw8jgx" {
+ t.Fatal("repair guessed or discarded ambiguous associations")
+ }
+ refs := sql.QueryRefsByDefIDInBox(duplicateID, false, target.Box)
+ if len(refs) != 1 || refs[0].BlockID != node.ID || refs[0].RootID != repaired.ID {
+ t.Fatalf("reference source was not reindexed: %+v", refs)
+ }
+ if current, readErr := os.ReadFile(viewPath); readErr != nil || !bytes.Equal(current, viewBefore) {
+ t.Fatal("repair changed database bindings or field values", readErr)
+ }
+ histories, err := filepath.Glob(filepath.Join(util.HistoryDir, "*-format", target.Box, filepath.Base(target.Path)))
+ if err != nil || len(histories) != 1 {
+ t.Fatalf("missing original repair history: %v %v", histories, err)
+ }
+ if backup, readErr := os.ReadFile(histories[0]); readErr != nil || !bytes.Equal(backup, original) {
+ t.Fatal("repair did not preserve exact original source", readErr)
+ }
+ after, _ := os.ReadFile(filename)
+ if err = resetDuplicateBlocksOnFileSys(); err != nil {
+ t.Fatal(err)
+ }
+ sql.FlushQueue()
+ current, err := os.ReadFile(filename)
+ if err != nil || !bytes.Equal(current, after) {
+ t.Fatal("repeated repair changed a completed source", err)
+ }
+}
+
+func TestIndexFixRepairsExplicitTabAndMirrorOwnership(t *testing.T) {
+ fixture, view, _, _ := setupAttributeViewItemsTest(t, false)
+ isolateIndexRepairPaths(t)
+ source, err := LoadTreeByBlockID(fixture.sourceID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ target, err := LoadTreeByBlockID(fixture.targetID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ mirrorID := ast.NewNodeID()
+ for _, tree := range []*parse.Tree{source, target} {
+ node := &ast.Node{ID: mirrorID, Type: ast.NodeAttributeView, AttributeViewID: view.ID, AttributeViewType: "table"}
+ node.SetIALAttr("id", mirrorID)
+ tree.Root.AppendChild(node)
+ }
+ av.UpsertBlockRel(view.ID, mirrorID)
+ oldItemID := source.Root.FirstChild.ID
+ tabs := &ast.Node{ID: ast.NewNodeID(), Type: ast.NodeTabs}
+ tabs.SetIALAttr("id", tabs.ID)
+ tabs.SetIALAttr(treenode.TabsActiveIDAttr, oldItemID)
+ item := &ast.Node{ID: oldItemID, Type: ast.NodeTabItem}
+ item.SetIALAttr("id", item.ID)
+ item.AppendChild(treenode.NewParagraph(""))
+ tabs.AppendChild(item)
+ target.Root.AppendChild(tabs)
+ for _, tree := range []*parse.Tree{source, target} {
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err = resetDuplicateBlocksOnFileSys(); err != nil {
+ t.Fatal(err)
+ }
+ repaired, _, err := filesys.ReadTreeSnapshot(target.Box, target.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ tabs = repaired.Root.LastChild
+ if tabs.FirstChild.ID == oldItemID || tabs.IALAttr(treenode.TabsActiveIDAttr) != tabs.FirstChild.ID {
+ t.Fatal("selected tab did not follow its structurally owned item")
+ }
+ newMirrorID := repaired.Root.LastChild.Previous.ID
+ rels := av.GetBlockRels()[view.ID]
+ if len(rels) != 2 || !((rels[0] == mirrorID && rels[1] == newMirrorID) || (rels[1] == mirrorID && rels[0] == newMirrorID)) {
+ t.Fatalf("mirror ownership was not repaired while preserving the original: %v", rels)
+ }
+}
+
+func TestIndexFixResumesSourceOnlyIdentityRepair(t *testing.T) {
+ fixture := setupStructureTransactionTest(t)
+ setupFoldTransactionDatabase(t, fixture)
+ isolateIndexRepairPaths(t)
+ tree, err := LoadTreeByBlockID(fixture.targetID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ oldID := tree.Root.FirstChild.ID
+ treenode.ResetNodeID(tree.Root.FirstChild)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ // Simulate interruption after source replacement, before queueing or updating either index.
+ if err = resetDuplicateBlocksOnFileSys(); err != nil {
+ t.Fatal(err)
+ }
+ sql.FlushQueue()
+ assertIndexRepairDocument(t, tree)
+ if treenode.GetBlockTreeInExactBox(oldID, tree.Box) != nil || sql.GetBlockInBox(oldID, tree.Box) != nil {
+ t.Fatal("interrupted repair left obsolete identities")
+ }
+}
diff --git a/kernel/model/index_fix_identity_sqlcipher_test.go b/kernel/model/index_fix_identity_sqlcipher_test.go
new file mode 100644
index 0000000000..fd9f375311
--- /dev/null
+++ b/kernel/model/index_fix_identity_sqlcipher_test.go
@@ -0,0 +1,79 @@
+//go:build fts5 && (sqlcipher || libsqlcipher)
+
+package model
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestIndexFixEncryptedDuplicateIdentity(t *testing.T) {
+ if !prepareStructuredTitlesCryptoTest(t) {
+ return
+ }
+ box := newStructuredTitlesEncryptedBox(t)
+ first := createStructuredTitlesEncryptedDoc(t, box, nil, "First")
+ second := createStructuredTitlesEncryptedDoc(t, box, nil, "Second")
+ if first.Path > second.Path {
+ first, second = second, first
+ }
+ source, _, err := filesys.ReadTreeSnapshot(box, first.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ target, _, err := filesys.ReadTreeSnapshot(box, second.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ duplicateID := source.Root.FirstChild.ID
+ target.Root.FirstChild.ID = duplicateID
+ target.Root.FirstChild.SetIALAttr("id", duplicateID)
+ if _, err = filesys.WriteTree(target); err != nil {
+ t.Fatal(err)
+ }
+ original := structuredTitlesCiphertext(t, second)
+ if err = resetDuplicateBlocksOnFileSys(); err != nil {
+ t.Fatal(err)
+ }
+ sql.FlushQueue()
+ repaired, _, err := filesys.ReadTreeSnapshot(box, second.Path)
+ if err != nil || repaired.Root.FirstChild.ID == duplicateID {
+ t.Fatalf("encrypted duplicate was not repaired: %v", err)
+ }
+ assertIndexRepairDocument(t, source)
+ assertIndexRepairDocument(t, repaired)
+ if sql.GetBlock(repaired.Root.FirstChild.ID) != nil {
+ t.Fatal("private repaired block leaked into the global SQL index")
+ }
+ histories, err := filepath.Glob(filepath.Join(util.HistoryDir, "*-format", box, filepath.Base(second.Path)))
+ if err != nil || len(histories) != 1 {
+ t.Fatalf("encrypted repair history missing: %v %v", histories, err)
+ }
+ backup, err := os.ReadFile(histories[0])
+ if err != nil || !bytes.Equal(backup, original) {
+ t.Fatal("encrypted repair history lost the exact ciphertext", err)
+ }
+ // A duplicate identity in another encryption boundary is independent and remains untouched.
+ otherBox := newStructuredTitlesEncryptedBox(t)
+ other := createStructuredTitlesEncryptedDoc(t, otherBox, nil, "Independent")
+ otherTree, _, err := filesys.ReadTreeSnapshot(otherBox, other.Path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ otherTree.Root.FirstChild.ID = duplicateID
+ otherTree.Root.FirstChild.SetIALAttr("id", duplicateID)
+ if err = indexWriteTreeUpsertQueue(otherTree); err != nil {
+ t.Fatal(err)
+ }
+ before := structuredTitlesCiphertext(t, other)
+ if err = resetDuplicateBlocksOnFileSys(); err != nil {
+ t.Fatal(err)
+ }
+ assertEncryptedFileBytes(t, filepath.Join(util.DataDir, otherBox, other.Path), before)
+}
diff --git a/kernel/treenode/blocktree.go b/kernel/treenode/blocktree.go
index c678be81d1..754284fac8 100644
--- a/kernel/treenode/blocktree.go
+++ b/kernel/treenode/blocktree.go
@@ -700,7 +700,13 @@ func IndexBlockTree(tree *parse.Tree) {
indexBlockTree(tree, false)
}
-func indexBlockTree(tree *parse.Tree, replace bool) {
+// ReplaceBlockTree replaces all derived block identities for an authenticated source.
+// Repair and rollback callers must observe failures instead of publishing partial success.
+func ReplaceBlockTree(tree *parse.Tree) error {
+ return indexBlockTree(tree, true)
+}
+
+func indexBlockTree(tree *parse.Tree, replace bool) error {
tree.HPath = CurrentParentHPath(tree)
var changedNodes []*ast.Node
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
@@ -713,7 +719,7 @@ func indexBlockTree(tree *parse.Tree, replace bool) {
})
if 1 > len(changedNodes) {
- return
+ return nil
}
indexBlockTreeLock.Lock()
@@ -722,13 +728,13 @@ func indexBlockTree(tree *parse.Tree, replace bool) {
// 加密笔记本用独立 blocktree db;非加密笔记本用全局 db(两者都可能为 nil——重建过程中)
if nil == db && getEncryptedBlockTreeDB(tree.Box) == nil {
logging.LogErrorf("database is nil")
- return
+ return fmt.Errorf("block-tree database is unavailable")
}
tx, err := beginTxForBox(tree.Box)
if err != nil {
logging.LogErrorf("begin transaction failed: %s", err)
- return
+ return err
}
if replace {
@@ -736,7 +742,7 @@ func indexBlockTree(tree *parse.Tree, replace bool) {
if _, err = tx.Exec("DELETE FROM blocktrees WHERE root_id = ?", tree.ID); err != nil {
tx.Rollback()
logging.LogErrorf("replace document block tree failed: %s", err)
- return
+ return err
}
}
execInsertBlocktrees(tx, tree, changedNodes)
@@ -744,6 +750,7 @@ func indexBlockTree(tree *parse.Tree, replace bool) {
if err = tx.Commit(); err != nil {
logging.LogErrorf("commit transaction failed: %s", err)
}
+ return err
}
func UpsertBlockTree(tree *parse.Tree) {
diff --git a/kernel/treenode/blocktree_replace_test.go b/kernel/treenode/blocktree_replace_test.go
new file mode 100644
index 0000000000..fe949838ef
--- /dev/null
+++ b/kernel/treenode/blocktree_replace_test.go
@@ -0,0 +1,34 @@
+package treenode
+
+import "testing"
+
+func TestReplaceBlockTreeIsAtomicAndReportsFailure(t *testing.T) {
+ for _, fail := range []bool{false, true} {
+ t.Run(map[bool]string{false: "success", true: "insert-failure"}[fail], func(t *testing.T) {
+ box := withDocumentMetadataDB(t, false)
+ tree := NewTree(box, "/20261026000000-root001.sy", "/Original", "Original")
+ if err := ReplaceBlockTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ oldID := tree.Root.FirstChild.ID
+ const replacement = "20261026000001-new0001"
+ tree.Root.FirstChild.ID = replacement
+ tree.Root.FirstChild.SetIALAttr("id", replacement)
+ if fail {
+ if _, err := db.Exec("CREATE TRIGGER fail_repair BEFORE INSERT ON blocktrees WHEN NEW.id = '" + replacement + "' BEGIN SELECT RAISE(ABORT, 'injected block-tree failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+ }
+ err := ReplaceBlockTree(tree)
+ if (err != nil) != fail {
+ t.Fatalf("replace failure was not reported: %v", err)
+ }
+ if (GetBlockTreeInExactBox(oldID, box) != nil) != fail || (GetBlockTreeInExactBox(replacement, box) != nil) == fail {
+ t.Fatal("replacement did not publish or roll back its complete identity set")
+ }
+ if root := GetBlockTreeInExactBox(tree.ID, box); root == nil || root.Path != tree.Path {
+ t.Fatal("replacement lost the document identity")
+ }
+ })
+ }
+}