Skip to content

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

:bug: Skip missing attribute view definitions during asset relinking https://github.com/siyuan-note/siyuan/issues/19468

Daniel7d394f1d0c44
diff --git a/app/src/types/api/index.d.ts b/app/src/types/api/index.d.ts
index 6bfc4fc6a9..696bfdd2f0 100644
--- a/app/src/types/api/index.d.ts
+++ b/app/src/types/api/index.d.ts
@@ -510,7 +510,7 @@ export type AssetPathsData = { "paths": Array<string> | null; };
export type AssetReference = { "avID": string; "blockID": string; "notebook": string; "oldPath"?: string; "path": string; "reason": string; "reference": string; "relinkable": boolean; "replacement": string; "rootID": string; "type": string; "valueID": string; };
-export type AssetReferencesData = { "dryRun": boolean; "historyPath": string; "items"?: Array<AssetRelinkItemResult>; "references": Array<AssetReference> | null; "skippedNotebooks": Array<string> | null; "updated": number; };
+export type AssetReferencesData = { "dryRun": boolean; "historyPath": string; "items"?: Array<AssetRelinkItemResult>; "references": Array<AssetReference> | null; "skippedNotebooks": Array<string> | null; "unavailableAttributeViews"?: Array<UnavailableAssetAttributeView>; "updated": number; };
export type AssetRelinkItemResult = { "newPath": string; "ok": boolean; "oldPath": string; "reason": string; "references": Array<AssetReference> | null; "updated": number; };
@@ -2182,6 +2182,8 @@ export type TreeStatRequestInput = { "id": string; "ids"?: Array<string> | null;
export type TrimmedIDRequestInput = { "id": string; };
+export type UnavailableAssetAttributeView = { "avID": string; "blockID": string; "hPath": string; "notebook": string; "notebookName": string; "path": string; "reason": string; "rootID": string; };
+
export type UnfoldedParentData = { "parentID": string; };
export type UninstallBazaarIconRequestInput = { "keyword"?: string | null; "packageName": string; };
@@ -2594,7 +2596,7 @@ export interface APIPOSTRoutes {
};
"/api/asset/findAssetReferences": {
request: FindAssetReferencesRequestInput;
- response: { "code": 0; "data": AssetReferencesData; "msg": string; } | { "code": -1; "data": ({ "closeTimeout": number; } & { "dryRun"?: never; "historyPath"?: never; "items"?: never; "references"?: never; "skippedNotebooks"?: never; "updated"?: never; }) | null | (AssetReferencesData & { "closeTimeout"?: never; }); "msg": string; };
+ response: { "code": 0; "data": AssetReferencesData; "msg": string; } | { "code": -1; "data": ({ "closeTimeout": number; } & { "dryRun"?: never; "historyPath"?: never; "items"?: never; "references"?: never; "skippedNotebooks"?: never; "unavailableAttributeViews"?: never; "updated"?: never; }) | null | (AssetReferencesData & { "closeTimeout"?: never; }); "msg": string; };
body: "json";
};
"/api/asset/fullReindexAssetContent": {
@@ -2649,7 +2651,7 @@ export interface APIPOSTRoutes {
};
"/api/asset/relinkAsset": {
request: RelinkAssetRequestInput;
- response: { "code": 0; "data": AssetReferencesData; "msg": string; } | { "code": -1; "data": ({ "closeTimeout": number; } & { "dryRun"?: never; "historyPath"?: never; "items"?: never; "references"?: never; "skippedNotebooks"?: never; "updated"?: never; }) | null | (AssetReferencesData & { "closeTimeout"?: never; }); "msg": string; };
+ response: { "code": 0; "data": AssetReferencesData; "msg": string; } | { "code": -1; "data": ({ "closeTimeout": number; } & { "dryRun"?: never; "historyPath"?: never; "items"?: never; "references"?: never; "skippedNotebooks"?: never; "unavailableAttributeViews"?: never; "updated"?: never; }) | null | (AssetReferencesData & { "closeTimeout"?: never; }); "msg": string; };
body: "json";
};
"/api/asset/removeUnusedAsset": {
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 824588afc9..337784a628 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -140,6 +140,8 @@ Dynamic multipart endpoints use `MultipartFields` to retain every text value and
## Generation and verification
+Asset-reference scans report missing attribute-view definitions and invalid definition IDs in the optional `unavailableAttributeViews` list without blocking queries, previews, or replacement. Each entry identifies the notebook ID/name, document ID/path/human-readable path, block ID, view ID, and reason. Existing unreadable or corrupt definitions remain errors. Missing-file snapshots are revalidated before writing so a definition restored during scanning cannot be silently omitted. Attribute-view definitions are not deferred assets under the current download-path policy; the regression suite checks this assumption. The unavailable-definition regressions run through the model and actual HTTP contracts, including closed notebooks and shared definitions.
+
Asset-reference query and replacement contracts preserve scalar requests and also accept batches. Batch results retain input order and report each mapping's status, reason, references, and changed-file count; the top-level count includes each shared file once. Empty batches, duplicate sources, and chained or cyclic mappings are rejected. Independent mappings may succeed when another mapping fails; a shared-file write failure belongs to every affected mapping. Scans allow editing and validate the workspace snapshot before saving; cancellation and unchanged retries preserve source data. `TestAssetRelink` regressions cover scalar compatibility, batch validation, shared document/database/OCR persistence, history, and concurrent edits and are included in the full kernel command below.
Run from `app/`:
diff --git a/docs/API-CONTRACTS.zh-CN.md b/docs/API-CONTRACTS.zh-CN.md
index ffd6515be0..62c698e804 100644
--- a/docs/API-CONTRACTS.zh-CN.md
+++ b/docs/API-CONTRACTS.zh-CN.md
@@ -140,6 +140,8 @@ JSON SSE 接口通过 `SSEOptions` 和 `SSEEvent` 声明各事件名称及载荷
## 生成与验证
+资源引用扫描将定义文件缺失或定义 ID 无效的数据库记录到可选的 `unavailableAttributeViews` 列表,不阻断查询、预演或替换。每项包含笔记本 ID 与名称、文档 ID 与路径及人类可读路径、块 ID、数据库 ID 和原因。已存在但无法读取或内容损坏的定义仍返回错误。保存前重新校验缺失文件快照,避免漏掉扫描期间恢复的定义。当前按需下载规则不包含数据库定义,回归测试会检查这一前提。缺失定义回归覆盖模型和实际 HTTP 契约,包括关闭的笔记本和共享定义。
+
资源引用查询和替换契约保留单资源请求,同时支持批量参数。批量结果按输入顺序返回每项状态、原因、引用和改动文件数;顶层计数对共享文件去重。空批次、重复源路径、链式和循环映射会被拒绝。独立映射可以在其他项失败时完成,共享文件写入失败归属所有受影响映射。扫描期间允许编辑,保存前校验工作区快照;取消和无变化重试保留源数据。`TestAssetRelink` 回归覆盖单资源兼容、批量校验、共享文档、数据库及 OCR 保存、历史和并发编辑,已包含在下方完整内核测试命令中。
在 `app/` 下运行:
diff --git a/kernel/api/asset_relink_test.go b/kernel/api/asset_relink_test.go
index 8106a6a97d..73cdd45245 100644
--- a/kernel/api/asset_relink_test.go
+++ b/kernel/api/asset_relink_test.go
@@ -9,14 +9,31 @@ import (
"strings"
"testing"
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/render"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/apicontract"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
"github.com/siyuan-note/siyuan/kernel/util"
)
func TestAssetRelinkContract(t *testing.T) {
assets := setupAssetContractWorkspace(t)
+ const box, viewID = "20260914070000-closed0", "20260914070001-missing"
+ boxDir := filepath.Join(util.DataDir, box)
+ if err := os.MkdirAll(filepath.Join(boxDir, ".siyuan"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(boxDir, ".siyuan", "conf.json"), []byte(`{"name":"Closed notebook","closed":true}`), 0644); err != nil {
+ t.Fatal(err)
+ }
+ tree := treenode.NewTree(box, "/20260914070002-orphan0.sy", "/Orphan", "Orphan")
+ tree.Root.AppendChild(&ast.Node{Type: ast.NodeAttributeView, ID: "20260914070003-orphan1", AttributeViewID: viewID})
+ l := util.NewLute()
+ if err := os.WriteFile(filepath.Join(boxDir, tree.Path), render.NewJSONRenderer(tree, l.RenderOptions, l.ParseOptions).Render(), 0644); err != nil {
+ t.Fatal(err)
+ }
for _, name := range []string{"contract-relink.png", "contract-relink.webp"} {
if err := os.WriteFile(filepath.Join(assets, name), []byte("asset"), 0644); err != nil {
t.Fatal(err)
@@ -73,6 +90,12 @@ func TestAssetRelinkContract(t *testing.T) {
if !test.failure && (response.Data == nil || response.Data.References == nil || response.Data.SkippedNotebooks == nil) {
t.Fatal("success arrays must not be null")
}
+ if !test.failure {
+ warnings := response.Data.UnavailableAttributeViews
+ if len(warnings) != 1 || warnings[0].AvID != viewID || warnings[0].Notebook != box || warnings[0].NotebookName != "Closed notebook" || warnings[0].Path != tree.Path || warnings[0].Reason != "missing_definition" {
+ t.Fatalf("missing definition warning contract: %+v", warnings)
+ }
+ }
if !test.failure && (strings.Contains(test.body, `"paths"`) || strings.Contains(test.body, `"mappings"`)) {
if len(response.Data.Items) != 2 || !response.Data.Items[0].OK || response.Data.Items[1].OK || response.Data.Items[1].Reason == "" {
t.Fatalf("partial batch result: %+v", response.Data)
diff --git a/kernel/apicontract/asset_relink.go b/kernel/apicontract/asset_relink.go
index 7ecdf64d12..87a0281438 100644
--- a/kernel/apicontract/asset_relink.go
+++ b/kernel/apicontract/asset_relink.go
@@ -42,10 +42,22 @@ type AssetReference struct {
}
type AssetReferencesData struct {
- Items []AssetRelinkItemResult `json:"items,omitempty"`
- References []AssetReference `json:"references"`
- SkippedNotebooks []string `json:"skippedNotebooks"`
- DryRun bool `json:"dryRun"`
- HistoryPath string `json:"historyPath"`
- Updated int `json:"updated"`
+ UnavailableAttributeViews []UnavailableAssetAttributeView `json:"unavailableAttributeViews,omitempty"`
+ Items []AssetRelinkItemResult `json:"items,omitempty"`
+ References []AssetReference `json:"references"`
+ SkippedNotebooks []string `json:"skippedNotebooks"`
+ DryRun bool `json:"dryRun"`
+ HistoryPath string `json:"historyPath"`
+ Updated int `json:"updated"`
+}
+
+type UnavailableAssetAttributeView struct {
+ AvID string `json:"avID"`
+ Notebook string `json:"notebook"`
+ NotebookName string `json:"notebookName"`
+ RootID string `json:"rootID"`
+ BlockID string `json:"blockID"`
+ Path string `json:"path"`
+ HPath string `json:"hPath"`
+ Reason string `json:"reason"`
}
diff --git a/kernel/apicontract/schema.json b/kernel/apicontract/schema.json
index 427706925e..c5ac98236c 100644
--- a/kernel/apicontract/schema.json
+++ b/kernel/apicontract/schema.json
@@ -13263,6 +13263,12 @@
}
]
},
+ "unavailableAttributeViews": {
+ "type": "array",
+ "items": {
+ "$ref": "#/$defs/UnavailableAssetAttributeView"
+ }
+ },
"updated": {
"type": "integer"
}
@@ -102689,6 +102695,46 @@
],
"additionalProperties": false
},
+ "UnavailableAssetAttributeView": {
+ "type": "object",
+ "properties": {
+ "avID": {
+ "type": "string"
+ },
+ "blockID": {
+ "type": "string"
+ },
+ "hPath": {
+ "type": "string"
+ },
+ "notebook": {
+ "type": "string"
+ },
+ "notebookName": {
+ "type": "string"
+ },
+ "path": {
+ "type": "string"
+ },
+ "reason": {
+ "type": "string"
+ },
+ "rootID": {
+ "type": "string"
+ }
+ },
+ "required": [
+ "avID",
+ "blockID",
+ "hPath",
+ "notebook",
+ "notebookName",
+ "path",
+ "reason",
+ "rootID"
+ ],
+ "additionalProperties": false
+ },
"UnfoldedParentData": {
"type": "object",
"properties": {
diff --git a/kernel/model/asset_relink.go b/kernel/model/asset_relink.go
index d86fc5d51f..28ef4af83a 100644
--- a/kernel/model/asset_relink.go
+++ b/kernel/model/asset_relink.go
@@ -354,18 +354,52 @@ func (p *assetRelinkPlan) scanViews() error {
}
}
}
+ availability := map[string]string{}
+ boxNames := map[string]string{}
for _, tree := range p.trees {
- var missing string
+ var checkErr error
ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
- if entering && n.Type == ast.NodeAttributeView {
- if !ast.IsNodeIDPattern(n.AttributeViewID) || !filelock.IsExist(filepath.Join(dir, n.AttributeViewID+".json")) {
- missing = n.AttributeViewID
+ if !entering || n.Type != ast.NodeAttributeView {
+ return ast.WalkContinue
+ }
+ reason, checked := availability[n.AttributeViewID]
+ if !checked {
+ if !ast.IsNodeIDPattern(n.AttributeViewID) {
+ reason = "invalid_id"
+ } else {
+ abs := filepath.Join(dir, n.AttributeViewID+".json")
+ if checkErr = p.observe(abs); checkErr != nil {
+ return ast.WalkStop
+ }
+ info, statErr := os.Lstat(abs)
+ if os.IsNotExist(statErr) {
+ // 数据库定义不参与资源按需下载;缺失定义作为历史残留上报,保留数据库块。
+ reason = "missing_definition"
+ } else if statErr != nil {
+ checkErr = statErr
+ return ast.WalkStop
+ } else if !info.Mode().IsRegular() {
+ checkErr = fmt.Errorf("attribute view definition is not a regular file: %s", abs)
+ return ast.WalkStop
+ }
}
+ availability[n.AttributeViewID] = reason
+ }
+ if reason != "" {
+ name, loaded := boxNames[tree.Box]
+ if !loaded {
+ name = (&Box{ID: tree.Box}).GetConf().Name
+ boxNames[tree.Box] = name
+ }
+ p.result.UnavailableAttributeViews = append(p.result.UnavailableAttributeViews, apicontract.UnavailableAssetAttributeView{
+ AvID: n.AttributeViewID, Notebook: tree.Box, NotebookName: name, RootID: tree.Root.ID,
+ BlockID: n.ID, Path: tree.Path, HPath: tree.HPath, Reason: reason,
+ })
}
return ast.WalkContinue
})
- if missing != "" {
- return fmt.Errorf("attribute view is unavailable: %s", missing)
+ if checkErr != nil {
+ return fmt.Errorf("cannot inspect attribute view in notebook %s, document %s: %w", tree.Box, tree.Path, checkErr)
}
}
return nil
diff --git a/kernel/model/asset_relink_integration_test.go b/kernel/model/asset_relink_integration_test.go
index 798febc073..e7edca69fb 100644
--- a/kernel/model/asset_relink_integration_test.go
+++ b/kernel/model/asset_relink_integration_test.go
@@ -43,6 +43,7 @@ func TestAssetRelinkPersistenceAndHistory(t *testing.T) {
sql.InitAssetContentDatabase(true)
sql.InitHistoryDatabase(true)
t.Cleanup(sql.CloseDatabase)
+ orphan, orphanBefore := assetRelinkUnavailableTree(t)
writeAssetRelinkTestFile(t, "assets/a.png", []byte("original asset"))
writeAssetRelinkTestFile(t, "assets/b.webp", []byte("replacement asset"))
writeAssetRelinkTestFile(t, "assets/ocr-texts.json", []byte(`{"assets/a.png":"OCR text"}`))
@@ -77,6 +78,11 @@ func TestAssetRelinkPersistenceAndHistory(t *testing.T) {
if err != nil || result.Updated != 3 || result.HistoryPath == "" || len(result.References) != len(preview.References) {
t.Fatalf("apply: %+v %v", result, err)
}
+ checkAssetRelinkUnavailable(t, result, orphan)
+ orphanAfter, _ := os.ReadFile(filepath.Join(util.DataDir, orphan.Box, orphan.Path))
+ if !bytes.Equal(orphanBefore, orphanAfter) {
+ t.Fatal("unrelated orphan document changed during relink")
+ }
for _, source := range sources {
history, readErr := os.ReadFile(filepath.Join(result.HistoryPath, source))
if readErr != nil || !bytes.Equal(history, before[source]) {
@@ -172,7 +178,8 @@ func TestAssetRelinkPersistenceAndHistory(t *testing.T) {
if err != nil || batch.Updated != 3 || len(batch.Items) != 3 || !batch.Items[0].OK || !batch.Items[1].OK || batch.Items[2].OK || batch.Items[2].Updated != 0 {
t.Fatalf("batch apply: %+v %v", batch, err)
}
- if plan.parsedDocuments != 1 || plan.parsedViews != 1 || batch.Items[0].Updated != 2 || batch.Items[1].Updated != 3 {
+ checkAssetRelinkUnavailable(t, batch, orphan)
+ if plan.parsedDocuments != 2 || plan.parsedViews != 1 || batch.Items[0].Updated != 2 || batch.Items[1].Updated != 3 {
t.Fatalf("shared work was duplicated: documents=%d views=%d items=%+v", plan.parsedDocuments, plan.parsedViews, batch.Items)
}
for _, source := range sources {
diff --git a/kernel/model/asset_relink_unavailable_test.go b/kernel/model/asset_relink_unavailable_test.go
new file mode 100644
index 0000000000..1eeb6631e0
--- /dev/null
+++ b/kernel/model/asset_relink_unavailable_test.go
@@ -0,0 +1,118 @@
+package model
+
+import (
+ "bytes"
+ "context"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/88250/lute/render"
+ "github.com/siyuan-note/dejavu"
+ "github.com/siyuan-note/siyuan/kernel/apicontract"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const unavailableRelinkViewID = "20260914060000-missing"
+
+func assetRelinkUnavailableTree(t *testing.T) (*parse.Tree, []byte) {
+ t.Helper()
+ const box = "20260914060001-closed0"
+ writeAssetRelinkTestFile(t, box+"/.siyuan/conf.json", []byte(`{"name":"Closed notebook","closed":true}`))
+ tree := treenode.NewTree(box, "/20260914060002-orphan0.sy", "/Orphan", "Orphan")
+ for i, id := range []string{unavailableRelinkViewID, unavailableRelinkViewID, "../invalid"} {
+ node := &ast.Node{Type: ast.NodeAttributeView, ID: []string{"20260914060003-orphan1", "20260914060004-orphan2", "20260914060005-orphan3"}[i], AttributeViewID: id}
+ tree.Root.AppendChild(node)
+ }
+ l := util.NewLute()
+ data := render.NewJSONRenderer(tree, l.RenderOptions, l.ParseOptions).Render()
+ writeAssetRelinkTestFile(t, box+tree.Path, data)
+ t.Cleanup(func() { forgetRuntimeNormalBox(box) })
+ return tree, data
+}
+
+func checkAssetRelinkUnavailable(t *testing.T, result apicontract.AssetReferencesData, tree *parse.Tree) {
+ t.Helper()
+ if len(result.UnavailableAttributeViews) != 3 {
+ t.Fatalf("missing warning locations: %+v", result)
+ }
+ for i, warning := range result.UnavailableAttributeViews {
+ reason, id := "missing_definition", unavailableRelinkViewID
+ if i == 2 {
+ reason, id = "invalid_id", "../invalid"
+ }
+ if warning.AvID != id || warning.Reason != reason || warning.Notebook != tree.Box || warning.NotebookName != "Closed notebook" || warning.Path != tree.Path || warning.HPath != "/Orphan" || warning.RootID != tree.Root.ID || warning.BlockID == "" {
+ t.Fatalf("incorrect warning location: %+v", warning)
+ }
+ }
+}
+
+func TestAssetRelinkUnavailableQueries(t *testing.T) {
+ setupAssetRelinkTest(t)
+ assetRelinkTestTree(t)
+ orphan, original := assetRelinkUnavailableTree(t)
+ for _, call := range []func() (apicontract.AssetReferencesData, error){
+ func() (apicontract.AssetReferencesData, error) { return FindAssetReferences("assets/a.png") },
+ func() (apicontract.AssetReferencesData, error) {
+ return RelinkAsset("assets/a.png", "assets/b.webp", true)
+ },
+ func() (apicontract.AssetReferencesData, error) {
+ return FindAssetReferencesBatch(context.Background(), []string{"assets/a.png"})
+ },
+ func() (apicontract.AssetReferencesData, error) {
+ return RelinkAssets(context.Background(), []apicontract.AssetRelinkMapping{{OldPath: "assets/a.png", NewPath: "assets/b.webp"}}, true)
+ },
+ } {
+ result, err := call()
+ if err != nil || len(result.References) != 1 || result.Updated != 0 || result.HistoryPath != "" {
+ t.Fatalf("unrelated missing definition blocked query: %+v %v", result, err)
+ }
+ checkAssetRelinkUnavailable(t, result, orphan)
+ }
+ current, _ := os.ReadFile(filepath.Join(util.DataDir, orphan.Box, orphan.Path))
+ if !bytes.Equal(current, original) {
+ t.Fatal("query repaired or removed orphan nodes")
+ }
+ if _, err := os.Stat(util.HistoryDir); !os.IsNotExist(err) {
+ t.Fatal("query created history")
+ }
+ if dejavu.IsAssetDownloadPath("/storage/av/" + unavailableRelinkViewID + ".json") {
+ t.Fatal("attribute view definitions now require deferred-download handling")
+ }
+}
+
+func TestAssetRelinkUnavailableSnapshot(t *testing.T) {
+ setupAssetRelinkTest(t)
+ assetRelinkTestTree(t)
+ assetRelinkUnavailableTree(t)
+ plan, _ := newAssetRelinkPlan(context.Background(), []apicontract.AssetRelinkMapping{{OldPath: "assets/a.png", NewPath: "assets/b.webp"}}, false, false, true)
+ if err := plan.scan(); err != nil {
+ t.Fatal(err)
+ }
+ writeAssetRelinkTestFile(t, "storage/av/"+unavailableRelinkViewID+".json", []byte(`{}`))
+ if err := plan.apply(); err == nil {
+ t.Fatal("definition restored after scan was silently omitted")
+ }
+}
+
+func TestAssetRelinkUnavailableDoesNotHideDamage(t *testing.T) {
+ for _, kind := range []string{"corrupt", "directory"} {
+ t.Run(kind, func(t *testing.T) {
+ setupAssetRelinkTest(t)
+ assetRelinkTestTree(t)
+ assetRelinkUnavailableTree(t)
+ rel := "storage/av/" + unavailableRelinkViewID + ".json"
+ if kind == "corrupt" {
+ writeAssetRelinkTestFile(t, rel, []byte(`{"invalid"`))
+ } else if err := os.MkdirAll(filepath.Join(util.DataDir, rel), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if _, err := FindAssetReferences("assets/a.png"); err == nil {
+ t.Fatal("damaged definition treated as missing")
+ }
+ })
+ }
+}