An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Roll back flashcard sources with failed document transactions https://github.com/siyuan-note/siyuan/issues/20987
Daniel6a7128d9bcde
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.tsindex 6f93691df7..722fdead8c 100644--- a/app/src/types/api/index.d.ts+++ b/app/src/types/api/index.d.ts@@ -6932,6 +6932,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin","writable"];};+ /**+ * waits for the document and deck transaction; persistence or commit+ * failures return code -1 with null data instead of reporting an unsaved deck.+ */"/api/riff/addRiffCards": {request: RiffDeckCardsRequestInput;response: { "code": 0; "data": RiffDeck | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };@@ -7012,6 +7016,10 @@ export interface APIPOSTRoutes {/** 服务器路由要求;资源权限与笔记本租约仍由内核校验 */authorization?: readonly ["authenticated","admin"];};+ /**+ * waits for the document and deck transaction; persistence or+ * commit failures return code -1 with null data. Empty deckID removes from all decks.+ */"/api/riff/removeRiffCards": {request: RiffDeckCardsRequestInput;response: { "code": 0; "data": RiffDeck | null; "msg": string; } | { "code": -1; "data": { "closeTimeout": number; } | null; "msg": string; };diff --git a/kernel/api/contract_block_transaction_test.go b/kernel/api/contract_block_transaction_test.goindex 941cc94a4f..a1e357813a 100644--- a/kernel/api/contract_block_transaction_test.go+++ b/kernel/api/contract_block_transaction_test.go@@ -157,6 +157,7 @@ func TestAPIContractHeadingTransactions(t *testing.T) {testAPIContractListConversion(t, engine, docID)testAPIContractTransactionCompletion(t, engine, docID, paragraphID)testAPIContractHistoryQueueOrder(t, engine, docID, paragraphID)+ testAPIContractRiffMutations(t, paragraphID)for _, entry := range []struct {path, id, scope stringcode intdiff --git a/kernel/api/contract_riff_test.go b/kernel/api/contract_riff_test.goindex 635579556a..ce6508b834 100644--- a/kernel/api/contract_riff_test.go+++ b/kernel/api/contract_riff_test.go@@ -45,6 +45,55 @@ func TestAPIContractRiffSerialization(t *testing.T) {}}+// Runs in the isolated, initialized document workspace of the heading contract test.+func testAPIContractRiffMutations(t *testing.T, blockID string) {+ t.Helper()+ previousDecks, previousQueue := model.Decks, util.QueueDir+ previousFlashcard := model.Conf.LoadFlashcard()+ model.Decks = map[string]*riff.Deck{}+ model.Conf.Flashcard.Store(conf.NewFlashcard())+ defer func() {+ model.Decks, util.QueueDir = previousDecks, previousQueue+ model.Conf.Flashcard.Store(previousFlashcard)+ }()+ deck, err := model.CreateDeck("contract persistence")+ if err != nil {+ t.Fatal(err)+ }+ body := `{"deckID":"` + deck.ID + `","blockIDs":["` + blockID + `"]}`+ blockedQueue := filepath.Join(t.TempDir(), "blocked-queue")+ if err := os.WriteFile(blockedQueue, []byte("blocked"), 0600); err != nil {+ t.Fatal(err)+ }+ for _, step := range []struct {+ name string+ handler gin.HandlerFunc+ fail bool+ cards int+ }{+ {"addRiffCards", addRiffCards, true, 0},+ {"addRiffCards", addRiffCards, false, 1},+ {"removeRiffCards", removeRiffCards, true, 1},+ {"removeRiffCards", removeRiffCards, false, 0},+ } {+ util.QueueDir = previousQueue+ if step.fail {+ util.QueueDir = blockedQueue+ }+ code, msg, data := riffContractRequest(t, step.name, step.handler, body)+ if step.fail {+ if code != -1 || msg == "" || string(data) != "null" {+ t.Fatalf("%s transaction failure was reported as success: %d %q %s", step.name, code, msg, data)+ }+ } else if code != 0 || string(data) == "null" {+ t.Fatalf("%s successful mutation failed: %d %q %s", step.name, code, msg, data)+ }+ if deck.CountCards() != step.cards {+ t.Fatalf("%s changed the deck despite failure: %d, want %d", step.name, deck.CountCards(), step.cards)+ }+ }+}+func riffContractRequest(t *testing.T, name string, handler gin.HandlerFunc, body string) (code int, message string, data json.RawMessage) {t.Helper()engine := gin.New()diff --git a/kernel/api/riff.go b/kernel/api/riff.goindex e974f7cb68..38e0989235 100644--- a/kernel/api/riff.go+++ b/kernel/api/riff.go@@ -129,9 +129,9 @@ var removeRiffCards = contractHandler(apicontract.RemoveRiffCards, func(c *gin.Cif err := model.ValidateFlashcardBlockIDs(blockIDs); err != nil {return apicontract.Failure[*apicontract.RiffDeck](-1, err.Error())}- transactions := []*model.Transaction{{DoOperations: []*model.Operation{{Action: "removeFlashcards", DeckID: request.DeckID, BlockIDs: blockIDs}}}}- model.PerformTransactions(&transactions)- model.WaitForTransactions(transactions)+ if err := performRiffCardsTransaction("removeFlashcards", request.DeckID, blockIDs); err != nil {+ return apicontract.Failure[*apicontract.RiffDeck](-1, err.Error())+ }if request.DeckID != "" {return apicontract.Success(deckData(model.Decks[request.DeckID]))}@@ -143,12 +143,20 @@ var addRiffCards = contractHandler(apicontract.AddRiffCards, func(c *gin.Contextif err := model.ValidateFlashcardBlockIDs(blockIDs); err != nil {return apicontract.Failure[*apicontract.RiffDeck](-1, err.Error())}- transactions := []*model.Transaction{{DoOperations: []*model.Operation{{Action: "addFlashcards", DeckID: request.DeckID, BlockIDs: blockIDs}}}}- model.PerformTransactions(&transactions)- model.WaitForTransactions(transactions)+ if err := performRiffCardsTransaction("addFlashcards", request.DeckID, blockIDs); err != nil {+ return apicontract.Failure[*apicontract.RiffDeck](-1, err.Error())+ }return apicontract.Success(deckData(model.Decks[request.DeckID]))})+func performRiffCardsTransaction(action, deckID string, blockIDs []string) error {+ // Drain earlier edits under the execution lock, retaining queue order while+ // returning the actual persistence/rollback result to this HTTP request.+ return model.WithTransactionHistory(func(execute func(*model.Transaction) error) error {+ return execute(&model.Transaction{DoOperations: []*model.Operation{{Action: action, DeckID: deckID, BlockIDs: blockIDs}}})+ })+}+var renameRiffDeck = contractHandler(apicontract.RenameRiffDeck, func(c *gin.Context, request apicontract.RenameRiffDeckRequest) apicontract.Response[apicontract.Null] {if err := model.RenameDeck(request.DeckID, request.Name); err != nil {return apicontract.Failure[apicontract.Null](-1, err.Error())diff --git a/kernel/apicontract/contracts.go b/kernel/apicontract/contracts.goindex 6e15604da8..8dda7d4573 100644--- a/kernel/apicontract/contracts.go+++ b/kernel/apicontract/contracts.go@@ -1029,7 +1029,13 @@ var SkipReviewRiffCard = define[RiffCardRequest, Null]("skipReviewRiffCard", "/avar GetNotebookRiffDueCards = define[RiffNotebookDueCardsRequest, RiffDueCardsData]("getNotebookRiffDueCards", "/api/riff/getNotebookRiffDueCards", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")var GetTreeRiffDueCards = define[RiffTreeDueCardsRequest, RiffDueCardsData]("getTreeRiffDueCards", "/api/riff/getTreeRiffDueCards", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")var GetRiffDueCards = define[RiffDueCardsRequest, RiffDueCardsData]("getRiffDueCards", "/api/riff/getRiffDueCards", AuthenticatedAccess|AdminAccess, JSONBody, ResponseOptions{}, "POST")++// RemoveRiffCards waits for the document and deck transaction; persistence or+// commit failures return code -1 with null data. Empty deckID removes from all decks.var RemoveRiffCards = define[RiffDeckCardsRequest, *RiffDeck]("removeRiffCards", "/api/riff/removeRiffCards", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")++// AddRiffCards waits for the document and deck transaction; persistence or commit+// failures return code -1 with null data instead of reporting an unsaved deck.var AddRiffCards = define[RiffDeckCardsRequest, *RiffDeck]("addRiffCards", "/api/riff/addRiffCards", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RenameRiffDeck = define[RenameRiffDeckRequest, Null]("renameRiffDeck", "/api/riff/renameRiffDeck", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")var RemoveRiffDeck = define[RiffDeckRequest, Null]("removeRiffDeck", "/api/riff/removeRiffDeck", AuthenticatedAccess|AdminAccess|WritableAccess, JSONBody, ResponseOptions{}, "POST")diff --git a/kernel/go.mod b/kernel/go.modindex 3b209fab2b..ba7790672a 100644--- a/kernel/go.mod+++ b/kernel/go.mod@@ -81,7 +81,7 @@ require (github.com/siyuan-note/filelock v0.0.0-20261025032826-1ff24a81dda9github.com/siyuan-note/httpclient v0.0.0-20260813083704-4643a83d05degithub.com/siyuan-note/logging v0.0.0-20260513050044-06b8e04d5490- github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754+ github.com/siyuan-note/riff v0.0.0-20261027020519-fcf37f980d3fgithub.com/smallnest/chanx v1.2.0github.com/soheilhy/cmux v0.1.5github.com/spf13/cast v1.10.0diff --git a/kernel/go.sum b/kernel/go.sumindex 573a5c5181..d1d12a5ffd 100644--- a/kernel/go.sum+++ b/kernel/go.sum@@ -448,6 +448,8 @@ github.com/siyuan-note/logging v0.0.0-20260513050044-06b8e04d5490 h1:z8m0SaVN/9rgithub.com/siyuan-note/logging v0.0.0-20260513050044-06b8e04d5490/go.mod h1:t3Tmt3DgQx0zqJmrckszJ+JBZ7iJrD1Ktp8FDBQ249E=github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754 h1:6QYpy7s5HlRSge09TyM/mT0vz1RDcWYZdkxEh7hmbH4=github.com/siyuan-note/riff v0.0.0-20251022131846-228528e70754/go.mod h1:/N7+N2CsZ0nleNPpP3b+06Bzqvuhy6GUmLY7Kug/zT0=+github.com/siyuan-note/riff v0.0.0-20261027020519-fcf37f980d3f h1:XR9uI0hsYkunhrT9OxRB7X88iiWFUQlMzlxzGDQ08pU=+github.com/siyuan-note/riff v0.0.0-20261027020519-fcf37f980d3f/go.mod h1:/N7+N2CsZ0nleNPpP3b+06Bzqvuhy6GUmLY7Kug/zT0=github.com/smallnest/chanx v1.2.0 h1:RLyldZBbQZ4O0dSvdkTMHo4+mDw20Bc1jXXTHf+ymZo=github.com/smallnest/chanx v1.2.0/go.mod h1:+4nWMF0+CqEcU74SnX2NxaGqZ8zX4pcQ8Jcs77DbX5A=github.com/soheilhy/cmux v0.1.5 h1:jjzc5WVemNEDTLwv9tlmemhC73tI08BNOIGwBOo10Js=diff --git a/kernel/model/document_source_journal.go b/kernel/model/document_source_journal.goindex ffb86d77fc..2cf41659d8 100644--- a/kernel/model/document_source_journal.go+++ b/kernel/model/document_source_journal.go@@ -30,6 +30,15 @@ type documentSourceFile struct {}func (file *documentSourceFile) filename() (string, error) {+ if file.Kind == "flashcard" {+ name := path.Base(file.Path)+ extension := path.Ext(name)+ id := strings.TrimSuffix(name, extension)+ if file.Box != "" || !ast.IsNodeIDPattern(id) || (extension != ".deck" && extension != ".cards") || file.Path != "/storage/riff/"+name {+ return "", errors.New("invalid flashcard recovery path")+ }+ return filepath.Join(util.DataDir, "storage", "riff", name), nil+ }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")diff --git a/kernel/model/flashcard.go b/kernel/model/flashcard.goindex 84bae0b521..9e4a90c898 100644--- a/kernel/model/flashcard.go+++ b/kernel/model/flashcard.go@@ -956,8 +956,7 @@ func getAllDueFlashcards(reviewedCardIDs []string) (ret []*Flashcard, unreviewed}func (tx *Transaction) doRemoveFlashcards(operation *Operation) (ret *TxErr) {- deckLock.Lock()- defer deckLock.Unlock()+ tx.lockFlashcardMutation()if isSyncingStorages() {ret = &TxErr{code: TxErrCodeDataIsSyncing}@@ -976,10 +975,14 @@ func (tx *Transaction) doRemoveFlashcards(operation *Operation) (ret *TxErr) {if "" == deckID { // 支持在 All 卡包中移除闪卡 https://github.com/siyuan-note/siyuan/issues/7425for _, deck := range Decks {- removeFlashcardsByBlockIDs(blockIDs, deck)+ if err := tx.removeFlashcardsByBlockIDs(blockIDs, deck); err != nil {+ return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: deck.ID}+ }}} else {- removeFlashcardsByBlockIDs(blockIDs, Decks[deckID])+ if err := tx.removeFlashcardsByBlockIDs(blockIDs, Decks[deckID]); err != nil {+ return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: deckID}+ }}return}@@ -1052,29 +1055,28 @@ func (tx *Transaction) removeBlocksDeckAttr(blockIDs []string, deckID string) (ereturn}-func removeFlashcardsByBlockIDs(blockIDs []string, deck *riff.Deck) {+func (tx *Transaction) removeFlashcardsByBlockIDs(blockIDs []string, deck *riff.Deck) error {if nil == deck {logging.LogErrorf("deck is nil")- return+ return nil}cards := deck.GetCardsByBlockIDs(blockIDs)if 1 > len(cards) {- return+ return nil+ }+ if err := tx.rememberFlashcardDeck(deck.ID); err != nil {+ return err}for _, card := range cards {deck.RemoveCard(card.ID())}- err := deck.Save()- if err != nil {- logging.LogErrorf("save deck [%s] failed: %s", deck.ID, err)- }+ return nil}func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {- deckLock.Lock()- defer deckLock.Unlock()+ tx.lockFlashcardMutation()if isSyncingStorages() {ret = &TxErr{code: TxErrCodeDataIsSyncing}@@ -1095,10 +1097,16 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {}}if !foundDeck {- deck, createErr := createDeck0("Built-in Deck", builtinDeckID)- if nil == createErr {- Decks[deck.ID] = deck+ if err := tx.rememberFlashcardDeck(builtinDeckID); err != nil {+ return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: builtinDeckID}+ }+ config := Conf.LoadFlashcard()+ deck, err := riff.LoadDeck(getRiffDir(), builtinDeckID, config.RequestRetention, config.MaximumInterval, config.Weights)+ if err != nil {+ return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: builtinDeckID}}+ deck.Name = "Built-in Deck"+ Decks[deck.ID] = deck}blockRoots := map[string]string{}@@ -1157,6 +1165,9 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {logging.LogWarnf("deck [%s] not found", deckID)return}+ if err := tx.rememberFlashcardDeck(deckID); err != nil {+ return &TxErr{code: TxErrCodeWriteTree, msg: err.Error(), id: deckID}+ }for _, blockID := range eligibleBlockIDs {cards := deck.GetCardsByBlockID(blockID)@@ -1168,10 +1179,6 @@ func (tx *Transaction) doAddFlashcards(operation *Operation) (ret *TxErr) {deck.AddCard(ast.NewNodeID(), blockID)}- if err := deck.Save(); err != nil {- logging.LogErrorf("save deck [%s] failed: %s", deckID, err)- return- }return}diff --git a/kernel/model/flashcard_transaction.go b/kernel/model/flashcard_transaction.gonew file mode 100644index 0000000000..04f72db37b--- /dev/null+++ b/kernel/model/flashcard_transaction.go@@ -0,0 +1,123 @@+package model++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"++ "github.com/88250/lute/ast"+ "github.com/siyuan-note/riff"+ "github.com/siyuan-note/siyuan/kernel/util"+)++type flashcardDeckBefore struct {+ deck *riff.Deck+ cards []riff.Card+ updated int64+}++func (tx *Transaction) lockFlashcardMutation() {+ if !tx.flashcardLocked {+ deckLock.Lock()+ tx.flashcardLocked = true+ }+}++func (tx *Transaction) rememberFlashcardDeck(id string) error {+ if !ast.IsNodeIDPattern(id) {+ return errors.New("invalid deck ID")+ }+ if tx.flashcardBefore == nil {+ tx.flashcardBefore = map[string]*flashcardDeckBefore{}+ }+ if tx.flashcardBefore[id] != nil {+ return nil+ }+ before := &flashcardDeckBefore{deck: Decks[id]}+ if before.deck != nil {+ before.updated = before.deck.Updated+ for _, card := range before.deck.GetCardsByBlockIDs(before.deck.GetBlockIDs()) {+ before.cards = append(before.cards, card.Clone())+ }+ }+ var files []*documentSourceFile+ for _, extension := range []string{".cards", ".deck"} {+ path := "/storage/riff/" + id + extension+ data, err := os.ReadFile(filepath.Join(getRiffDir(), id+extension))+ if os.IsNotExist(err) {+ data, err = nil, nil+ }+ if err != nil {+ return err+ }+ files = append(files, &documentSourceFile{Kind: "flashcard", Path: path, Before: data, After: data})+ }+ if tx.sourceJournal == nil {+ tx.sourceJournal = &documentSourceJournal{Version: 1, ID: ast.NewNodeID(), State: "pending"}+ }+ tx.sourceJournal.Forward = false+ tx.sourceJournal.Files = append(tx.sourceJournal.Files, files...)+ if err := tx.sourceJournal.save(); err != nil {+ return err+ }+ tx.flashcardBefore[id] = before+ return nil+}++func (tx *Transaction) saveFlashcardDeck(deck *riff.Deck) error {+ if err := tx.rememberFlashcardDeck(deck.ID); err != nil {+ return err+ }+ return deck.SaveWithWriter(func(name string, data []byte) error {+ for _, file := range tx.sourceJournal.Files {+ if file.Kind != "flashcard" {+ continue+ }+ path, err := file.filename()+ if err != nil {+ return err+ }+ if filepath.Clean(path) != filepath.Clean(name) {+ continue+ }+ previous := file.After+ file.After = bytes.Clone(data)+ if err := tx.sourceJournal.save(); err != nil {+ return err+ }+ write := tx.writeFlashcardFile+ if write == nil {+ write = util.WriteFileIfUnchanged+ }+ return write(name, previous, data)+ }+ return errors.New("unregistered flashcard source file")+ })+}++func (tx *Transaction) finishFlashcardMutation(rollback bool) {+ if rollback {+ for id, before := range tx.flashcardBefore {+ if before.deck == nil {+ delete(Decks, id)+ continue+ }+ deck := before.deck+ for _, card := range deck.GetCardsByBlockIDs(deck.GetBlockIDs()) {+ deck.RemoveCard(card.ID())+ }+ for _, card := range before.cards {+ deck.SetCard(card)+ }+ deck.Updated = before.updated+ Decks[id] = deck+ }+ }+ tx.flashcardBefore = nil+ tx.writeFlashcardFile = nil+ if tx.flashcardLocked {+ tx.flashcardLocked = false+ deckLock.Unlock()+ }+}diff --git a/kernel/model/flashcard_transaction_fts5_test.go b/kernel/model/flashcard_transaction_fts5_test.gonew file mode 100644index 0000000000..1e41101d96--- /dev/null+++ b/kernel/model/flashcard_transaction_fts5_test.go@@ -0,0 +1,194 @@+//go:build fts5++package model++import (+ "bytes"+ "errors"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/siyuan-note/riff"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestFlashcardTransactionFailureRestoresSources(t *testing.T) {+ for _, action := range []string{"addFlashcards", "removeFlashcards"} {+ for _, failure := range []string{"", ".cards", ".deck", "document", "later operation"} {+ t.Run(action+"/"+failure, func(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Flashcard.Store(conf.NewFlashcard())+ previous := Decks+ Decks = map[string]*riff.Deck{}+ t.Cleanup(func() { Decks = previous })+ deck, err := createDeck0("transaction", builtinDeckID)+ if err != nil {+ t.Fatal(err)+ }+ const cardID = "20261027000000-abcdefg"+ if action == "removeFlashcards" {+ deck.AddCard(cardID, fixture.childID)+ deck.Review(cardID, riff.Rating(3))+ if err := deck.Save(); err != nil {+ t.Fatal(err)+ }+ tree, err := LoadTreeByBlockID(fixture.childID)+ if err != nil {+ t.Fatal(err)+ }+ treenode.GetNodeInTree(tree, fixture.childID).SetIALAttr(NodeAttrRiffDecks, deck.ID)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ }+ paths := []string{filepath.Join(util.DataDir, fixture.box.ID, fixture.sourcePath), filepath.Join(getRiffDir(), deck.ID+".cards"), filepath.Join(getRiffDir(), deck.ID+".deck")}+ before := map[string][]byte{}+ for _, path := range paths {+ before[path], err = os.ReadFile(path)+ if err != nil {+ t.Fatal(err)+ }+ }+ tx := &Transaction{DoOperations: []*Operation{{Action: action, DeckID: deck.ID, BlockIDs: []string{fixture.childID}}}}+ if failure == "" {+ // Multiple mutations of a deck still publish each source only once.+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: action, DeckID: deck.ID, BlockIDs: []string{fixture.childID}})+ }+ injected := errors.New("injected " + failure + " failure")+ writes := 0+ tx.writeFlashcardFile = func(path string, original, data []byte) error {+ writes+++ if failure != "" && strings.HasSuffix(path, failure) {+ return injected+ }+ return util.WriteFileIfUnchanged(path, original, data)+ }+ if failure == "document" {+ tx.writeTransactionTree = func(*parse.Tree) error { return injected }+ } else if failure == "later operation" {+ tx.DoOperations = append(tx.DoOperations, &Operation{Action: "setAttrs", ID: ast.NewNodeID(), Data: `{"custom-state":"active"}`})+ }+ err = PerformTxSync(tx)+ if failure == "" {+ if err != nil || writes != 2 {+ t.Fatalf("successful transaction did not save both sources: %v, %d", err, writes)+ }+ want := 1+ if action == "removeFlashcards" {+ want = 0+ }+ if deck.CountCards() != want {+ t.Fatalf("mutation was not committed: %d, want %d", deck.CountCards(), want)+ }+ loaded, loadErr := riff.LoadDeck(getRiffDir(), deck.ID, Conf.Flashcard.Load().RequestRetention, Conf.Flashcard.Load().MaximumInterval, Conf.Flashcard.Load().Weights)+ if loadErr != nil || loaded.CountCards() != want {+ t.Fatalf("committed deck did not persist: %v", loadErr)+ }+ return+ }+ if err == nil {+ t.Fatal("transaction failure was reported as success")+ }+ if tx.sourceRollbackErr != nil {+ t.Fatalf("source compensation failed: %v", tx.sourceRollbackErr)+ }+ for path, original := range before {+ if data, err := os.ReadFile(path); err != nil || !bytes.Equal(data, original) {+ t.Fatalf("failed transaction changed %s: %v", path, err)+ }+ }+ if action == "removeFlashcards" {+ if card := deck.GetCard(cardID); card == nil || card.GetReps() != 1 {+ t.Fatalf("rollback lost the original card schedule: %v", card)+ }+ } else if deck.CountCards() != 0 {+ t.Fatal("failed addition remained in memory")+ }+ if !deckLock.TryLock() {+ t.Fatal("transaction retained the deck mutation lock")+ }+ deckLock.Unlock()+ })+ }+ }+}++func TestFlashcardSourceRecoveryPreservesPreviousFormat(t *testing.T) {+ setupFileOperationTest(t)+ Conf.Flashcard.Store(conf.NewFlashcard())+ previous := Decks+ Decks = map[string]*riff.Deck{}+ t.Cleanup(func() { Decks = previous })+ deck, err := createDeck0("recovery", builtinDeckID)+ if err != nil {+ t.Fatal(err)+ }+ journal := &documentSourceJournal{Version: 1, ID: ast.NewNodeID(), State: "pending"}+ for _, extension := range []string{".cards", ".deck"} {+ data, err := os.ReadFile(filepath.Join(getRiffDir(), deck.ID+extension))+ if err != nil {+ t.Fatal(err)+ }+ journal.Files = append(journal.Files, &documentSourceFile{Kind: "flashcard", Path: "/storage/riff/" + deck.ID + extension, Before: data, After: data})+ }+ deck.AddCard("20261027000000-abcdefg", "20261027000001-abcdefg")+ if err := deck.SaveWithWriter(func(path string, data []byte) error {+ for _, file := range journal.Files {+ if filepath.Base(file.Path) == filepath.Base(path) {+ file.After = data+ }+ }+ if err := journal.save(); err != nil {+ return err+ }+ // Simulate interruption after cards have changed, before the deck write.+ if strings.HasSuffix(path, ".deck") {+ return errors.New("interrupted")+ }+ return os.WriteFile(path, data, 0600)+ }); err == nil {+ t.Fatal("expected simulated interruption")+ }+ if err := recoverDocumentSources(); err != nil {+ t.Fatal(err)+ }+ LoadFlashcards()+ if Decks[deck.ID] == nil || Decks[deck.ID].CountCards() != 0 {+ t.Fatal("recovery did not restore the previous deck representation")+ }+}++func TestFlashcardTransactionFailedBuiltinCreation(t *testing.T) {+ fixture := setupStructureTransactionTest(t)+ setupFoldTransactionDatabase(t, fixture)+ Conf.Flashcard.Store(conf.NewFlashcard())+ previous := Decks+ Decks = map[string]*riff.Deck{}+ t.Cleanup(func() { Decks = previous })+ tx := &Transaction{DoOperations: []*Operation{{Action: "addFlashcards", DeckID: builtinDeckID, BlockIDs: []string{fixture.childID}}}}+ tx.writeFlashcardFile = func(path string, original, data []byte) error {+ if strings.HasSuffix(path, ".deck") {+ return errors.New("injected builtin deck save failure")+ }+ return util.WriteFileIfUnchanged(path, original, data)+ }+ if err := PerformTxSync(tx); err == nil || tx.sourceRollbackErr != nil {+ t.Fatalf("builtin creation did not roll back: %v, %v", err, tx.sourceRollbackErr)+ }+ if Decks[builtinDeckID] != nil {+ t.Fatal("failed builtin deck remained in memory")+ }+ for _, extension := range []string{".cards", ".deck"} {+ if _, err := os.Stat(filepath.Join(getRiffDir(), builtinDeckID+extension)); !os.IsNotExist(err) {+ t.Fatalf("failed builtin creation retained %s: %v", extension, err)+ }+ }+}diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 3205d28183..e7f329aac3 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2808,6 +2808,9 @@ type Transaction struct {sourceWatchers []func()sourceDatabaseBefore map[string]*documentSourceFilesourceRelationBoundaries map[string]bool+ flashcardLocked bool+ flashcardBefore map[string]*flashcardDeckBefore+ writeFlashcardFile func(string, []byte, []byte) errorattributeViewRollback *attributeViewRollbackattributeViewAutomations *attributeViewAutomationStatepushAutomationMessage func(string, int) string@@ -2977,6 +2980,14 @@ func (tx *Transaction) commit() (err error) {return err}}+ // Persist each staged deck only once, with write-ahead recovery for both files.+ for id := range tx.flashcardBefore {+ if deck := Decks[id]; deck != nil {+ if err = tx.saveFlashcardDeck(deck); err != nil {+ return err+ }+ }+ }if tx.attributeViewDeletionErr != nil {return tx.attributeViewDeletionErr}@@ -3175,6 +3186,7 @@ func (tx *Transaction) commit() (err error) {// releaseCommittedResources 释放执行期间的文档树;操作中的撤销快照及广播所需的文档 ID 继续保留。func (tx *Transaction) releaseCommittedResources() {tx.releaseDocumentSources(true)+ tx.finishFlashcardMutation(false)tx.trees, tx.nodes, tx.boxIcons = nil, nil, niltx.indexChanges = niltx.mindmapSummarySiblings = nil@@ -3216,6 +3228,7 @@ func (tx *Transaction) rollback() {treenode.SetBlockTreePath(tx.templateDocTreeRootSnapshot)}tx.rollbackDocumentSources()+ tx.finishFlashcardMutation(true)tx.releaseDocumentSources(false)tx.trees, tx.nodes, tx.boxIcons = nil, nil, niltx.removedCreatedDocs, tx.removedTemplateCreatedDocs = nil, nildiff --git a/kernel/model/transaction_source.go b/kernel/model/transaction_source.goindex 0f38426252..5a1bf63a82 100644--- a/kernel/model/transaction_source.go+++ b/kernel/model/transaction_source.go@@ -281,7 +281,7 @@ 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" {+ if file.Kind == "relations" || file.Kind == "flashcard" {continue}if file.Kind == "database" {