Skip to content

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

:bug: Recover relation configuration and completed document moves https://github.com/siyuan-note/siyuan/issues/20932

Danielb49a46cde580
diff --git a/kernel/av/relation.go b/kernel/av/relation.go
index c134dd7f09..61e9f2836a 100644
--- a/kernel/av/relation.go
+++ b/kernel/av/relation.go
@@ -56,29 +56,43 @@ func readRelations(boxID string) (avRels map[string][]string, err error) {
}
// writeRelations 写入 relations 索引(boxID 非空时加密)。
-func writeRelations(boxID string, avRels map[string][]string) {
+func writeRelations(boxID string, avRels map[string][]string) error {
p := relationsPath(boxID)
if err := os.MkdirAll(filepath.Dir(p), 0755); err != nil {
logging.LogErrorf("create attribute view dir failed: %s", err)
- return
+ return err
}
data, err := msgpack.Marshal(avRels)
if err != nil {
logging.LogErrorf("marshal attribute view relations failed: %s", err)
- return
+ return err
}
if boxID != "" {
enc, encErr := encryptAVData(boxID, "relation", data)
if encErr != nil {
logging.LogErrorf("encrypt attribute view relations failed: %s", encErr)
- return
+ return encErr
}
data = enc
}
+ if value, ok := relationWriteRecorders.Load(boxID); ok {
+ before, readErr := filelock.ReadFile(p)
+ if os.IsNotExist(readErr) {
+ before, readErr = nil, nil
+ }
+ if readErr != nil {
+ return readErr
+ }
+ if err = value.(SourceWriteRecorder)(boxID, before, data); err != nil {
+ return err
+ }
+ return util.WriteFileIfUnchanged(p, before, data)
+ }
if err = filelock.WriteFile(p, data); err != nil {
logging.LogErrorf("write attribute view relations failed: %s", err)
- return
+ return err
}
+ return nil
}
// relationsBoxIDByAvID 由 destAvID 反查归属 boxID,决定 relations 索引的存储位置。
@@ -140,19 +154,24 @@ func collectSrcAvIDsForRefresh(destAvIDs []string, getSrcAvIDs func(string) []st
}
func RemoveAvRel(srcAvID, destAvID string) {
+ if err := RemoveAvRelWithErr(srcAvID, destAvID); err != nil {
+ logging.LogErrorf("remove attribute view relation failed: %s", err)
+ }
+}
+
+func RemoveAvRelWithErr(srcAvID, destAvID string) error {
attributeViewRelationsLock.Lock()
defer attributeViewRelationsLock.Unlock()
boxID := relationsBoxIDByAvID(destAvID)
avRels, err := readRelations(boxID)
if err != nil {
- logging.LogErrorf("read attribute view relations failed: %s", err)
- return
+ return err
}
srcAvIDs := avRels[destAvID]
if nil == srcAvIDs {
- return
+ return nil
}
var newAvIDs []string
@@ -162,10 +181,16 @@ func RemoveAvRel(srcAvID, destAvID string) {
}
}
avRels[destAvID] = newAvIDs
- writeRelations(boxID, avRels)
+ return writeRelations(boxID, avRels)
}
func UpsertAvBackRel(srcAvID, destAvID string) {
+ if err := UpsertAvBackRelWithErr(srcAvID, destAvID); err != nil {
+ logging.LogErrorf("upsert attribute view relation failed: %s", err)
+ }
+}
+
+func UpsertAvBackRelWithErr(srcAvID, destAvID string) error {
attributeViewRelationsLock.Lock()
defer attributeViewRelationsLock.Unlock()
@@ -178,20 +203,19 @@ func UpsertAvBackRel(srcAvID, destAvID string) {
destEnc := destBox != "" && AVIsEncryptedBox(destBox)
if srcEnc != destEnc || (srcEnc && destEnc && srcBox != destBox) {
logging.LogWarnf("skip cross-boundary AV relation: src=%s(box=%s) dest=%s(box=%s)", srcAvID, srcBox, destAvID, destBox)
- return
+ return fmt.Errorf("cross-boundary database relation")
}
}
boxID := destBox
avRels, err := readRelations(boxID)
if err != nil {
- logging.LogErrorf("read attribute view relations failed: %s", err)
- return
+ return err
}
srcAvIDs := avRels[destAvID]
srcAvIDs = append(srcAvIDs, srcAvID)
srcAvIDs = gulu.Str.RemoveDuplicatedElem(srcAvIDs)
avRels[destAvID] = srcAvIDs
- writeRelations(boxID, avRels)
+ return writeRelations(boxID, avRels)
}
diff --git a/kernel/av/relation_write_recorder_test.go b/kernel/av/relation_write_recorder_test.go
new file mode 100644
index 0000000000..9550e275ad
--- /dev/null
+++ b/kernel/av/relation_write_recorder_test.go
@@ -0,0 +1,47 @@
+package av
+
+import (
+ "bytes"
+ "errors"
+ "os"
+ "testing"
+
+ "github.com/88250/lute/ast"
+)
+
+func TestRelationSourceRecorderRejectsIncompleteDependencyWrites(t *testing.T) {
+ setupCollectionIndexTest(t)
+ source, target, peer := ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID()
+ if err := UpsertAvBackRelWithErr(source, target); err != nil {
+ t.Fatal(err)
+ }
+ filename := relationsPath("")
+ original, err := os.ReadFile(filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ injected := errors.New("injected relation journal failure")
+ calls := 0
+ release := RecordRelationWrites("", func(box string, before, after []byte) error {
+ calls++
+ if box != "" || !bytes.Equal(before, original) || bytes.Equal(before, after) {
+ t.Fatal("missing exact dependency-index write bytes")
+ }
+ return injected
+ })
+ defer release()
+ if err = UpsertAvBackRelWithErr(peer, target); !errors.Is(err, injected) {
+ t.Fatal("dependency insertion ignored recovery failure", err)
+ }
+ if err = RemoveAvRelWithErr(source, target); !errors.Is(err, injected) {
+ t.Fatal("dependency removal ignored recovery failure", err)
+ }
+ current, err := os.ReadFile(filename)
+ if err != nil || !bytes.Equal(current, original) || calls != 2 {
+ t.Fatal("rejected dependency write changed its source", err, calls)
+ }
+ release()
+ if err = UpsertAvBackRelWithErr(peer, target); err != nil {
+ t.Fatal("released dependency recorder remained active", err)
+ }
+}
diff --git a/kernel/av/write_recorder.go b/kernel/av/write_recorder.go
index d19e4c6556..13f8b2016f 100644
--- a/kernel/av/write_recorder.go
+++ b/kernel/av/write_recorder.go
@@ -6,6 +6,15 @@ type SourceWriteRecorder func(boxID string, before, after []byte) error
var sourceWriteRecorders sync.Map // storage boundary + database ID -> *sourceWriteRecord
+var relationWriteRecorders sync.Map // storage boundary -> SourceWriteRecorder
+
+// RecordRelationWrites includes the dependency index in the same recovery boundary
+// as a serialized relation-configuration transaction. Bytes are already encrypted.
+func RecordRelationWrites(box string, record SourceWriteRecorder) func() {
+ relationWriteRecorders.Store(box, record)
+ return func() { relationWriteRecorders.Delete(box) }
+}
+
type sourceWriteRecord struct {
active func() bool
record SourceWriteRecorder
diff --git a/kernel/mcp/tools/database_key_test.go b/kernel/mcp/tools/database_key_test.go
index 4a2f1e3246..1421f1c7f5 100644
--- a/kernel/mcp/tools/database_key_test.go
+++ b/kernel/mcp/tools/database_key_test.go
@@ -15,14 +15,18 @@ import (
"github.com/88250/lute/ast"
"github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
func databaseKeyTestWorkspace(t *testing.T) {
t.Helper()
- originalDataDir := util.DataDir
- util.DataDir = t.TempDir()
- t.Cleanup(func() { util.DataDir = originalDataDir })
+ originalDataDir, originalQueueDir, originalConf := util.DataDir, util.QueueDir, model.Conf
+ util.DataDir, util.QueueDir = t.TempDir(), t.TempDir()
+ model.Conf = model.NewAppConf()
+ model.Conf.Sync.Store(conf.NewSync())
+ t.Cleanup(func() { util.DataDir, util.QueueDir, model.Conf = originalDataDir, originalQueueDir, originalConf })
}
func databaseKeyTestFixture(t *testing.T, keys ...*av.KeyValues) *av.AttributeView {
diff --git a/kernel/model/attribute_view.go b/kernel/model/attribute_view.go
index 52c75be6cb..78021ea941 100644
--- a/kernel/model/attribute_view.go
+++ b/kernel/model/attribute_view.go
@@ -4668,6 +4668,9 @@ func updateAttributeViewColRollup(operation *Operation) (err error) {
}
func (tx *Transaction) doUpdateAttrViewColRelation(operation *Operation) (ret *TxErr) {
+ if err := tx.prepareRelationSourceJournal(operation); err != nil {
+ return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
+ }
err := updateAttributeViewColRelation(operation)
if err != nil {
return &TxErr{code: TxErrHandleAttributeView, id: operation.AvID, msg: err.Error()}
@@ -4853,12 +4856,18 @@ func updateAttributeViewColRelation(operation *Operation) (err error) {
}
}
if !stillRelated {
- av.RemoveAvRel(srcAv.ID, oldDestAvID)
+ if err = av.RemoveAvRelWithErr(srcAv.ID, oldDestAvID); err != nil {
+ return
+ }
}
}
- av.UpsertAvBackRel(srcAv.ID, destAv.ID)
+ if err = av.UpsertAvBackRelWithErr(srcAv.ID, destAv.ID); err != nil {
+ return
+ }
if operation.IsTwoWay && !isSameAv {
- av.UpsertAvBackRel(destAv.ID, srcAv.ID)
+ if err = av.UpsertAvBackRelWithErr(destAv.ID, srcAv.ID); err != nil {
+ return
+ }
}
if "" != oldDestAvID && oldDestAvID != operation.ID && oldDestAvID != srcAv.ID {
ReloadAttrView(oldDestAvID)
diff --git a/kernel/model/attribute_view_key_config.go b/kernel/model/attribute_view_key_config.go
index ab7d3bb7e9..343734b89b 100644
--- a/kernel/model/attribute_view_key_config.go
+++ b/kernel/model/attribute_view_key_config.go
@@ -304,7 +304,8 @@ func updateAttributeViewKeyRelation(key *av.Key, op *Operation, value any) error
}
}
}
- err = updateAttributeViewColRelation(op)
+ op.Action = "updateAttrViewColRelation"
+ err = PerformTxSync(&Transaction{fromAPI: true, DoOperations: []*Operation{op}})
if nil == err {
ReloadAttrView(config.AvID)
if nil != key.Relation && key.Relation.AvID != config.AvID {
diff --git a/kernel/model/attribute_view_relation_transaction_sqlcipher_test.go b/kernel/model/attribute_view_relation_transaction_sqlcipher_test.go
new file mode 100644
index 0000000000..be1ff21887
--- /dev/null
+++ b/kernel/model/attribute_view_relation_transaction_sqlcipher_test.go
@@ -0,0 +1,20 @@
+//go:build fts5 && (sqlcipher || libsqlcipher)
+
+package model
+
+import (
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestRelationConfigurationEncryptedTransactionRollback(t *testing.T) {
+ if !prepareStructuredTitlesCryptoTest(t) {
+ return
+ }
+ util.Lang = "en"
+ util.AttrViewLangs = map[string]map[string]any{"en": {"key": "Key", "table": "Table", "select": "Select"}}
+ testRelationConfigurationTransactionRollback(t, func(t *testing.T) string {
+ return newStructuredTitlesEncryptedBox(t)
+ })
+}
diff --git a/kernel/model/attribute_view_relation_transaction_test.go b/kernel/model/attribute_view_relation_transaction_test.go
new file mode 100644
index 0000000000..30120069c9
--- /dev/null
+++ b/kernel/model/attribute_view_relation_transaction_test.go
@@ -0,0 +1,182 @@
+package model
+
+import (
+ "bytes"
+ "errors"
+ "os"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/av"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestRelationConfigurationTransactionRollback(t *testing.T) {
+ testRelationConfigurationTransactionRollback(t, func(t *testing.T) string {
+ setupAttributeViewValidationTest(t)
+ queue := util.QueueDir
+ util.QueueDir = t.TempDir()
+ t.Cleanup(func() { util.QueueDir = queue })
+ return ""
+ })
+}
+
+func testRelationConfigurationTransactionRollback(t *testing.T, prepare func(*testing.T) string) {
+ for _, mode := range []string{"source-save", "target-save", "later-operation", "interrupted", "success", "key-config-source-save", "key-config-target-save", "key-config-success"} {
+ t.Run(mode, func(t *testing.T) {
+ failure := strings.TrimPrefix(mode, "key-config-")
+ boundary := prepare(t)
+ source, oldTarget, target := av.NewAttributeView(ast.NewNodeID()), av.NewAttributeView(ast.NewNodeID()), av.NewAttributeView(ast.NewNodeID())
+ key, oldBack, newBack := ast.NewNodeID(), ast.NewNodeID(), ast.NewNodeID()
+ source.KeyValues = append(source.KeyValues, &av.KeyValues{Key: &av.Key{ID: key, Name: "Relation", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: oldTarget.ID, IsTwoWay: true, BackKeyID: oldBack}}})
+ oldTarget.KeyValues = append(oldTarget.KeyValues, &av.KeyValues{Key: &av.Key{ID: oldBack, Name: "Back", Type: av.KeyTypeRelation,
+ Relation: &av.Relation{AvID: source.ID, IsTwoWay: true, BackKeyID: key}}})
+ before := map[string][]byte{}
+ for _, view := range []*av.AttributeView{source, oldTarget, target} {
+ av.SetAVBoxID(view.ID, boundary)
+ if err := av.SaveAttributeView(view); err != nil {
+ t.Fatal(err)
+ }
+ filename, _ := av.FindAttributeViewPath(view.ID)
+ data, err := os.ReadFile(filename)
+ if err != nil {
+ t.Fatal(err)
+ }
+ before[filename] = data
+ }
+ av.UpsertAvBackRel(source.ID, oldTarget.ID)
+ av.UpsertAvBackRel(oldTarget.ID, source.ID)
+ peer := ast.NewNodeID()
+ if boundary != "" {
+ av.SetAVBoxID(peer, boundary)
+ if err := av.SaveAttributeView(av.NewAttributeView(peer)); err != nil {
+ t.Fatal(err)
+ }
+ }
+ av.UpsertAvBackRel(peer, oldTarget.ID)
+ relations := filepath.Join(util.DataDir, boundary, "storage", "av", "relations.msgpack")
+ data, readErr := os.ReadFile(relations)
+ if readErr != nil {
+ t.Fatal(readErr)
+ }
+ before[relations] = data
+ injected := errors.New("injected relation configuration save failure")
+ originalSaved := av.AttributeViewSaved
+ var release func()
+ av.AttributeViewSaved = func(id, box string) {
+ var fail *av.AttributeView
+ if failure == "source-save" && id == oldTarget.ID {
+ fail = source
+ }
+ if failure == "target-save" && id == source.ID {
+ fail = target
+ }
+ if fail != nil {
+ release = av.RecordSourceWrites(fail, func() bool { return true }, func(string, []byte, []byte) error { release(); return injected })
+ }
+ }
+ t.Cleanup(func() {
+ av.AttributeViewSaved = originalSaved
+ if release != nil {
+ release()
+ }
+ })
+ op := &Operation{Action: "updateAttrViewColRelation", AvID: source.ID, ID: target.ID, KeyID: key,
+ Format: "Changed", IsTwoWay: true, BackRelationKeyID: newBack, Name: "New back"}
+ tx := &Transaction{fromAPI: true, DoOperations: []*Operation{op}, m: &sync.Mutex{}}
+ defer func() {
+ av.AttributeViewSaved = originalSaved
+ if tx.state.Load() == 1 {
+ tx.rollback()
+ }
+ }()
+ managed := strings.HasPrefix(mode, "key-config-") || failure == "later-operation"
+ var executeErr error
+ if strings.HasPrefix(mode, "key-config-") {
+ executeErr = UpdateAttributeViewKeyConfig(source.ID, key, map[string]any{"relation": map[string]any{"avID": target.ID, "isTwoWay": true, "backKeyName": "New back"}})
+ } else if failure == "later-operation" {
+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: "sortAttrViewView", AvID: source.ID, ID: ast.NewNodeID()})
+ executeErr = PerformTxSync(tx)
+ } else {
+ if err := tx.begin(); err != nil {
+ t.Fatal(err)
+ }
+ if err := tx.doUpdateAttrViewColRelation(op); err != nil {
+ executeErr = err
+ }
+ }
+ if (failure == "source-save" || failure == "target-save" || failure == "later-operation") && executeErr == nil {
+ t.Fatal("expected injected save error")
+ }
+ if (failure == "success" || failure == "interrupted") && executeErr != nil {
+ t.Fatal(executeErr)
+ }
+ av.AttributeViewSaved = originalSaved
+ if failure == "success" {
+ if !managed {
+ if err := tx.commit(); err != nil {
+ tx.rollback()
+ t.Fatal(err)
+ }
+ }
+ updated, err := av.ParseAttributeView(source.ID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ field, _ := updated.GetKey(key)
+ if field.Relation.AvID != target.ID || !slices.Contains(av.GetSrcAvIDs(target.ID), source.ID) {
+ t.Fatal("successful relation configuration was not committed")
+ }
+ return
+ }
+ if failure == "interrupted" {
+ journals, err := readDocumentSourceJournals()
+ if err != nil || len(journals) != 1 || journals[0].Forward {
+ t.Fatal("missing durable relation recovery", err)
+ }
+ if boundary != "" {
+ for _, file := range journals[0].Files {
+ if !util.IsCiphertext(file.Before) || !util.IsCiphertext(file.After) {
+ t.Fatal("private recovery record contains plaintext")
+ }
+ }
+ }
+ // Drop all volatile transaction state, retaining only its durable record.
+ tx.finishAttributeViewMutation(false)
+ tx.releaseDocumentSources(false)
+ tx.state.Store(3)
+ tx.m.Unlock()
+ if err = recoverDocumentSources(); err != nil {
+ t.Fatal(err)
+ }
+ } else if !managed {
+ tx.rollback()
+ }
+ if tx.sourceRollbackErr != nil {
+ t.Fatal(tx.sourceRollbackErr)
+ }
+ for filename, original := range before {
+ current, err := os.ReadFile(filename)
+ if err != nil || !bytes.Equal(current, original) {
+ t.Errorf("partial relation configuration persisted in %s: %v", filepath.Base(filename), err)
+ }
+ }
+ if !slices.Contains(av.GetSrcAvIDs(oldTarget.ID), source.ID) || !slices.Contains(av.GetSrcAvIDs(oldTarget.ID), peer) || slices.Contains(av.GetSrcAvIDs(target.ID), source.ID) {
+ t.Error("relation dependencies were not restored")
+ }
+ if journals, err := readDocumentSourceJournals(); err != nil || len(journals) != 0 {
+ t.Fatal("completed relation recovery retained its record", err)
+ }
+ if boundary != "" {
+ if _, err := os.Stat(filepath.Join(util.DataDir, "storage", "av", "relations.msgpack")); !os.IsNotExist(err) {
+ t.Fatal("private dependencies leaked to the global index", err)
+ }
+ }
+ })
+ }
+}
diff --git a/kernel/model/box.go b/kernel/model/box.go
index aa1009f5d8..8dd3b38bf3 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -712,35 +712,16 @@ func isSkipFile(filename string) bool {
return strings.HasPrefix(filename, ".") || "node_modules" == filename || "dist" == filename || "target" == filename
}
-func moveTree(tree *parse.Tree) error {
- treenode.SetBlockTreePath(tree)
- sql.MoveTreeQueue(tree)
-
- box := Conf.Box(tree.Box)
- subFiles, err := box.listFilesForIndex(tree.Path)
- if err != nil {
- return err
- }
- paths := make([]string, 0, len(subFiles))
- for _, subFile := range subFiles {
- if !strings.HasSuffix(subFile.path, ".sy") {
- continue
- }
- paths = append(paths, subFile.path)
- }
- // 只读源快照重新构造 HPath,避免持有源提交锁时触发修复写入。
- if err = filesys.WalkTreeSnapshots(box.ID, paths, func(subTree *parse.Tree) error {
- treenode.SetBlockTreePath(subTree)
- sql.MoveTreeQueue(subTree)
- msg := fmt.Sprintf(Conf.Language(107), html.EscapeString(subTree.HPath))
- util.PushStatusBar(msg)
- return nil
- }); err != nil {
- return err
- }
-
- refreshDocInfoWithoutParent(tree)
- return nil
+func moveTree(trees []*parse.Tree) (err error) {
+ for _, tree := range trees {
+ // Continue publishing every physically moved document after an index error.
+ // The durable move record forces authenticated index recovery on restart.
+ err = errors.Join(err, treenode.ReplaceBlockTree(tree))
+ sql.MoveTreeQueue(tree)
+ util.PushStatusBar(fmt.Sprintf(Conf.Language(107), html.EscapeString(tree.HPath)))
+ }
+ refreshDocInfoWithoutParent(trees[0])
+ return
}
func parseKTree(kramdown []byte) (ret *parse.Tree) {
diff --git a/kernel/model/document_move.go b/kernel/model/document_move.go
index 7a0aae0335..145342df92 100644
--- a/kernel/model/document_move.go
+++ b/kernel/model/document_move.go
@@ -13,11 +13,7 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-// preflightDocumentMove 检查整棵子树,未知格式、认证失败和目标冲突都先于首次改动。
-func preflightDocumentMove(fromBox, fromPath, toBox, toPath string) ([]*treenode.BlockTree, error) {
- return preflightDocumentMoveSnapshots(fromBox, fromPath, toBox, toPath, nil)
-}
-
+// preflightDocumentMoveSnapshots 检查整棵子树,未知格式、认证失败和目标冲突都先于首次改动。
func preflightDocumentMoveSnapshots(fromBox, fromPath, toBox, toPath string,
visit func(before *parse.Tree, destination string)) ([]*treenode.BlockTree, error) {
if err := filesys.CheckDocumentAddressing(toBox); err != nil {
diff --git a/kernel/model/document_move_failure_test.go b/kernel/model/document_move_failure_test.go
new file mode 100644
index 0000000000..73c108697d
--- /dev/null
+++ b/kernel/model/document_move_failure_test.go
@@ -0,0 +1,172 @@
+//go:build fts5
+
+package model
+
+import (
+ "bytes"
+ gosql "database/sql"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/88250/lute/parse"
+ "github.com/gorilla/websocket"
+ "github.com/olahol/melody"
+ "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 TestDocumentMoveIndexFailurePublishesCompletedSubtree(t *testing.T) {
+ for _, failed := range []string{"root", "child"} {
+ t.Run(failed, func(t *testing.T) {
+ f := setupFileOperationTest(t)
+ setupFoldTransactionDatabase(t, f)
+ root, _, err := filesys.ReadTreeSnapshot(f.box.ID, f.sourcePath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ child := addDocumentCollectionChild(t, root)
+ grandchild := addDocumentCollectionChild(t, child)
+ trees := []*treenode.BlockTree{}
+ before := map[string][]byte{}
+ for _, tree := range []*parse.Tree{root, child, grandchild} {
+ treenode.UpsertBlockTree(tree)
+ sql.UpsertTreeQueue(tree)
+ trees = append(trees, &treenode.BlockTree{ID: tree.ID, BoxID: tree.Box, Path: tree.Path, HPath: tree.HPath})
+ before[tree.ID], err = os.ReadFile(filepath.Join(util.DataDir, tree.Box, tree.Path))
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ sql.FlushQueue()
+ ws := documentMoveTestSocket(t)
+ database, err := gosql.Open("sqlite3", util.BlockTreeDBPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer database.Close()
+ failedID := root.ID
+ if failed == "child" {
+ failedID = child.ID
+ }
+ if _, err = database.Exec("CREATE TRIGGER fail_move BEFORE INSERT ON blocktrees WHEN NEW.id = '" + failedID + "' AND NEW.path != '" + trees[map[string]int{"root": 0, "child": 1}[failed]].Path + "' BEGIN SELECT RAISE(ABORT, 'injected move index failure'); END"); err != nil {
+ t.Fatal(err)
+ }
+ revision := pendingSync.begin()
+ if err = MoveDocs([]string{root.Path}, f.box.ID, f.targetPath, "move-failure-test"); err == nil {
+ t.Fatal("index failure was not returned")
+ }
+ if pendingSync.begin() <= revision {
+ t.Error("completed physical move did not mark synchronization pending")
+ }
+ order, err := readSortConfMap(filepath.Join(util.DataDir, f.box.ID, ".siyuan", "sort.json"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, ok := order[root.ID]; !ok {
+ t.Error("completed physical move was omitted from sibling order")
+ }
+ sql.FlushQueue()
+ for _, tree := range trees {
+ newPath := path.Join(strings.TrimSuffix(f.targetPath, ".sy"), tree.Path)
+ current, err := os.ReadFile(filepath.Join(util.DataDir, tree.BoxID, newPath))
+ if err != nil || !bytes.Equal(current, before[tree.ID]) {
+ t.Fatal("move changed source bytes", tree.ID, err)
+ }
+ block := sql.GetBlockInBox(tree.ID, tree.BoxID)
+ if block == nil || block.Path != newPath || block.HPath != "/Target"+tree.HPath {
+ t.Errorf("SQL path did not follow completed move: %+v", block)
+ }
+ }
+ seen := map[string]bool{}
+ batch := false
+ ws.SetReadDeadline(time.Now().Add(5 * time.Second))
+ for !batch || len(seen) < len(trees) {
+ _, data, err := ws.ReadMessage()
+ if err != nil {
+ t.Fatal("missing move notifications", seen, batch, err)
+ }
+ var event struct {
+ Cmd string `json:"cmd"`
+ Data json.RawMessage `json:"data"`
+ }
+ if err = json.Unmarshal(data, &event); err != nil {
+ t.Fatal(err)
+ }
+ if event.Cmd == "moveDoc" {
+ var result moveDocResult
+ if err = json.Unmarshal(event.Data, &result); err != nil {
+ t.Fatal(err)
+ }
+ for _, previous := range trees {
+ if previous.ID == util.GetTreeID(result.NewPath) && (result.FromPath != previous.Path || result.FromNotebook != f.box.ID || result.ToNotebook != f.box.ID) {
+ t.Fatalf("move notification did not preserve the actual source identity: %+v", result)
+ }
+ }
+ seen[util.GetTreeID(result.NewPath)] = true
+ }
+ if event.Cmd == "moveDocs" {
+ var result struct {
+ Moves []moveDocResult `json:"moves"`
+ }
+ if err = json.Unmarshal(event.Data, &result); err != nil {
+ t.Fatal(err)
+ }
+ batch = len(result.Moves) == 1 && result.Moves[0].NewPath == "/"+f.targetID+"/"+root.ID+".sy"
+ }
+ }
+ journals, err := readDocumentSourceJournals()
+ if err != nil || len(journals) != 1 || !journals[0].Forward {
+ t.Fatal("failed indexing lost its recovery record", err)
+ }
+ if _, err = database.Exec("DROP TRIGGER fail_move"); err != nil {
+ t.Fatal(err)
+ }
+ if err = recoverDocumentSources(); err != nil {
+ t.Fatal(err)
+ }
+ indexBox(f.box.ID)
+ sql.FlushQueue()
+ for _, previous := range trees {
+ newPath := path.Join(strings.TrimSuffix(f.targetPath, ".sy"), previous.Path)
+ tree, _, err := filesys.ReadTreeSnapshot(previous.BoxID, newPath)
+ if err != nil {
+ t.Fatal(err)
+ }
+ assertIndexRepairDocument(t, tree)
+ }
+ if hasDocumentSourceRecovery(f.box.ID) {
+ t.Error("successful authenticated reindex retained move recovery")
+ }
+ })
+ }
+}
+
+func documentMoveTestSocket(t *testing.T) *websocket.Conn {
+ t.Helper()
+ m := melody.New()
+ connected := make(chan struct{}, 1)
+ m.HandleConnect(func(s *melody.Session) { util.AddPushChan(s); connected <- struct{}{} })
+ m.HandleDisconnect(util.RemovePushChan)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _ = m.HandleRequest(w, r) }))
+ connection, _, err := websocket.DefaultDialer.Dial("ws"+strings.TrimPrefix(server.URL, "http")+"/?app=move-failure-test&id=main&type=main", nil)
+ if err != nil {
+ server.Close()
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { connection.Close(); m.Close(); server.Close() })
+ select {
+ case <-connected:
+ case <-time.After(5 * time.Second):
+ t.Fatal("test socket did not connect")
+ }
+ return connection
+}
diff --git a/kernel/model/document_source_journal.go b/kernel/model/document_source_journal.go
index 4c97270224..ffb86d77fc 100644
--- a/kernel/model/document_source_journal.go
+++ b/kernel/model/document_source_journal.go
@@ -30,6 +30,12 @@ type documentSourceFile struct {
}
func (file *documentSourceFile) filename() (string, error) {
+ if file.Kind == "relations" {
+ if (file.Box != "" && !ast.IsNodeIDPattern(file.Box)) || file.Path != "/storage/av/relations.msgpack" {
+ return "", errors.New("invalid database relation recovery path")
+ }
+ return filepath.Join(util.DataDir, file.Box, filepath.FromSlash(file.Path)), nil
+ }
if file.Kind == "database" {
id := strings.TrimSuffix(strings.TrimPrefix(file.Path, "/storage/av/"), ".json")
if (file.Box != "" && !ast.IsNodeIDPattern(file.Box)) || !ast.IsNodeIDPattern(id) || file.Path != "/storage/av/"+id+".json" {
@@ -253,7 +259,7 @@ func (j *documentSourceJournal) rollback() error {
id := strings.TrimSuffix(path.Base(file.Path), ".json")
cache.RemoveAVDataInBox(id, file.Box)
av.ClearBlockCollectionIndex(file.Box)
- } else {
+ } else if file.Kind == "" {
cache.RemoveTreeDataInBox(util.GetTreeID(file.Path), file.Box)
cache.RemoveDocIALInBox(file.Path, file.Box)
}
@@ -278,6 +284,11 @@ func recoverDocumentSources() error {
return err
}
}
+ if !slices.ContainsFunc(entry.Files, func(file *documentSourceFile) bool { return file.Kind == "" }) {
+ if err = os.Remove(entry.filename()); err != nil {
+ return err
+ }
+ }
}
return nil
}
diff --git a/kernel/model/file.go b/kernel/model/file.go
index 2fe48d33b0..d77a12fcec 100644
--- a/kernel/model/file.go
+++ b/kernel/model/file.go
@@ -1904,16 +1904,18 @@ func moveDocs(fromPaths []string, toBoxID, toPath string, callback any, placeByC
var newPath string
newPath, err = moveDoc(fromBox, fromPath, toBox, toPath, luteEngine, callback, refresh)
+ if newPath != "" {
+ movedDocs = append(movedDocs, moveDocResult{
+ FromNotebook: fromBox.ID,
+ FromPath: fromPath,
+ ToNotebook: toBox.ID,
+ ToPath: toPath,
+ NewPath: newPath,
+ })
+ }
if err != nil {
return
}
- movedDocs = append(movedDocs, moveDocResult{
- FromNotebook: fromBox.ID,
- FromPath: fromPath,
- ToNotebook: toBox.ID,
- ToPath: toPath,
- NewPath: newPath,
- })
before := collectionBefore[fromPath]
var after []*parse.Tree
for id := range before {
@@ -2019,9 +2021,45 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin
}
needMoveSubDocs := fromBox.Exist(fromFolder)
- newPath = path.Join(toFolder, tree.ID+".sy")
+ destinationPath := path.Join(toFolder, tree.ID+".sy")
+ var movingTrees []*parse.Tree
+ var recovery *documentSourceJournal
err = filesys.MutateDocumentSourceSet(func() ([]*treenode.BlockTree, error) {
- return preflightDocumentMove(fromBox.ID, fromPath, toBox.ID, toPath)
+ movingTrees = nil
+ documents, err := preflightDocumentMoveSnapshots(fromBox.ID, fromPath, toBox.ID, toPath, func(snapshot *parse.Tree, destination string) {
+ snapshot.Box, snapshot.Path = toBox.ID, destination
+ movingTrees = append(movingTrees, snapshot)
+ })
+ if err != nil {
+ return nil, err
+ }
+ oldHPath := movingTrees[0].HPath
+ newHPath := "/" + treenode.ReadDocumentTitle(movingTrees[0].Root).Text
+ if toPath != "/" {
+ parent, _, readErr := filesys.ReadTreeSnapshot(toBox.ID, toPath)
+ if readErr != nil {
+ return nil, readErr
+ }
+ newHPath = parent.HPath + newHPath
+ }
+ for _, snapshot := range movingTrees {
+ snapshot.HPath = newHPath + strings.TrimPrefix(snapshot.HPath, oldHPath)
+ }
+ // All sources are authenticated under the source-write lock before renaming.
+ // No post-rename source read or directory walk can interrupt publication.
+ recovery = &documentSourceJournal{Version: 1, ID: ast.NewNodeID(), State: "pending", Forward: true}
+ seen := map[string]bool{}
+ for _, doc := range documents {
+ key := doc.BoxID + doc.Path
+ if !seen[key] {
+ seen[key] = true
+ recovery.Files = append(recovery.Files, &documentSourceFile{Box: doc.BoxID, Path: doc.Path})
+ }
+ }
+ if err = recovery.save(); err != nil {
+ return nil, err
+ }
+ return documents, nil
}, func() error {
oldFolder := filepath.Join(util.DataDir, fromBox.ID, fromFolder)
newFolder := filepath.Join(util.DataDir, toBox.ID, toFolder, tree.ID)
@@ -2038,20 +2076,24 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin
}
}
if err := filelock.RenameWithoutFatal(filepath.Join(util.DataDir, fromBox.ID, fromPath),
- filepath.Join(util.DataDir, toBox.ID, newPath)); err != nil {
+ filepath.Join(util.DataDir, toBox.ID, destinationPath)); err != nil {
if needMoveSubDocs {
err = errors.Join(err, filelock.RenameWithoutFatal(newFolder, oldFolder))
}
return err
}
- var readErr error
- tree, _, readErr = filesys.ReadTreeSnapshot(toBox.ID, newPath)
- if readErr != nil {
- return readErr
- }
- return moveTree(tree)
+ newPath = destinationPath // The caller must publish this move even if indexing fails.
+ tree = movingTrees[0]
+ return moveTree(movingTrees)
})
- if err != nil {
+ if recovery != nil {
+ if err == nil {
+ err = os.Remove(recovery.filename())
+ } else {
+ util.MarkIndexFixDirty()
+ }
+ }
+ if newPath == "" {
return
}
if !isSameBox {
@@ -2064,12 +2106,10 @@ func moveDoc(fromBox *Box, fromPath string, toBox *Box, toPath string, luteEngin
if needMoveSubDocs {
// 将其所有子文档的移动事件推送到前端 https://github.com/siyuan-note/siyuan/issues/11661
- subDocsFolder := path.Join(toFolder, tree.ID)
- syFiles := listSyFiles(path.Join(toBox.ID, subDocsFolder))
- for _, syFile := range syFiles {
- relPath := strings.TrimPrefix(syFile, "/"+path.Join(toBox.ID, toFolder))
+ for _, subTree := range movingTrees[1:] {
+ relPath := strings.TrimPrefix(subTree.Path, toFolder)
subFromPath := path.Join(path.Dir(fromPath), relPath)
- subToPath := path.Join(toFolder, relPath)
+ subToPath := subTree.Path
evt := util.NewCmdResult("moveDoc", 0, util.PushModeBroadcast)
evt.Data = map[string]any{
diff --git a/kernel/model/transaction.go b/kernel/model/transaction.go
index 8a7683eb80..3205d28183 100644
--- a/kernel/model/transaction.go
+++ b/kernel/model/transaction.go
@@ -2807,6 +2807,7 @@ type Transaction struct {
sourceRollbackErr error
sourceWatchers []func()
sourceDatabaseBefore map[string]*documentSourceFile
+ sourceRelationBoundaries map[string]bool
attributeViewRollback *attributeViewRollback
attributeViewAutomations *attributeViewAutomationState
pushAutomationMessage func(string, int) string
@@ -2889,6 +2890,7 @@ func (tx *Transaction) WaitForCommit() {
func (tx *Transaction) begin() (err error) {
tx.sourceJournal, tx.sourceLeases = nil, nil
tx.sourceDatabaseBefore = nil
+ tx.sourceRelationBoundaries = nil
tx.sourceErr, tx.sourceRollbackErr = nil, nil
expectedTemplateDocTreeRoot := tx.templateDocTreeRootSnapshot
expectedTemplateDocTreeRevision := tx.templateDocTreeRootRevision
diff --git a/kernel/model/transaction_source.go b/kernel/model/transaction_source.go
index a9aaff0e36..0f38426252 100644
--- a/kernel/model/transaction_source.go
+++ b/kernel/model/transaction_source.go
@@ -101,6 +101,75 @@ func (tx *Transaction) watchSourceDatabase(view *av.AttributeView) {
tx.sourceWatchers = append(tx.sourceWatchers, release)
}
+// Relation configuration can save several databases without touching a document.
+// Establish the durable boundary before its first save, including old targets.
+func (tx *Transaction) prepareRelationSourceJournal(op *Operation) error {
+ if !tx.usesDocumentSourceJournal() {
+ return nil
+ }
+ source, err := av.ParseAttributeView(op.AvID)
+ if err != nil {
+ return err
+ }
+ _, boundary := av.FindAttributeViewPath(source.ID)
+ ids := []string{source.ID, op.ID}
+ if key, _ := source.GetKey(op.KeyID); key != nil && key.Relation != nil && key.Relation.IsTwoWay {
+ ids = append(ids, key.Relation.AvID)
+ }
+ for _, id := range ids {
+ _, box := av.FindAttributeViewPath(id)
+ if box != boundary {
+ return errors.New("cross-boundary database relation")
+ }
+ if _, err = tx.readAttributeViewForMutation(id, "", box); err != nil {
+ return err
+ }
+ }
+ if tx.sourceErr != nil {
+ return tx.sourceErr
+ }
+ if tx.sourceJournal == nil {
+ tx.sourceJournal = &documentSourceJournal{Version: 1, ID: ast.NewNodeID(), State: "pending"}
+ for _, file := range tx.sourceDatabaseBefore {
+ name, _ := file.filename()
+ file.After, err = os.ReadFile(name)
+ if err != nil {
+ return err
+ }
+ tx.sourceJournal.Files = append(tx.sourceJournal.Files, file)
+ }
+ }
+ tx.sourceJournal.Forward = false
+ if err = tx.sourceJournal.save(); err != nil {
+ return err
+ }
+ if tx.sourceRelationBoundaries == nil {
+ tx.sourceRelationBoundaries = map[string]bool{}
+ }
+ if !tx.sourceRelationBoundaries[boundary] {
+ tx.sourceRelationBoundaries[boundary] = true
+ tx.sourceWatchers = append(tx.sourceWatchers, av.RecordRelationWrites(boundary, func(box string, before, after []byte) error {
+ var file *documentSourceFile
+ for _, candidate := range tx.sourceJournal.Files {
+ if candidate.Kind == "relations" && candidate.Box == box {
+ file = candidate
+ break
+ }
+ }
+ if file == nil {
+ file = &documentSourceFile{Kind: "relations", Box: box, Path: "/storage/av/relations.msgpack", Before: before, After: before}
+ tx.sourceJournal.Files = append(tx.sourceJournal.Files, file)
+ }
+ if !bytes.Equal(before, file.After) {
+ return util.ErrFileChanged
+ }
+ file.After = after
+ return tx.sourceJournal.save()
+ }))
+ }
+ return nil
+}
+
func (tx *Transaction) readDocumentSource(box, p string) (*parse.Tree, []byte, error) {
if !tx.usesDocumentSourceJournal() {
tree, err := filesys.LoadTree(box, p, tx.luteEngine)
@@ -212,6 +281,9 @@ func (tx *Transaction) rollbackDocumentSources() {
// Rebuild from actual authenticated sources, including failure before the first save.
// Queue replacement after any already-enqueued partial saves so SQL converges to the rollback.
for _, file := range j.Files {
+ if file.Kind == "relations" {
+ continue
+ }
if file.Kind == "database" {
id := strings.TrimSuffix(path.Base(file.Path), ".json")
av.NotifyAttributeViewSaved(id, file.Box)
@@ -247,6 +319,7 @@ func (tx *Transaction) releaseDocumentSources(committed bool) {
}
tx.sourceWatchers = nil
tx.sourceDatabaseBefore = nil
+ tx.sourceRelationBoundaries = nil
if committed && tx.sourceJournal != nil {
if err := os.Remove(tx.sourceJournal.filename()); err != nil {
logging.LogWarnf("retain committed transaction recovery [%s]: %s", tx.sourceJournal.ID, err)