An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:construction_worker: Run kernel model tests in duration-balanced shards https://github.com/siyuan-note/siyuan/issues/20491
Daniel62f43279797c
diff --git a/.github/workflows/cd.yml b/.github/workflows/cd.ymlindex 5e05f9e835..a696d101c8 100644--- a/.github/workflows/cd.yml+++ b/.github/workflows/cd.yml@@ -212,11 +212,13 @@ jobs:sudo apt-get install -y strace- name: Prepare native OCR verification resourcesrun: python3 scripts/prepare-ocr.py --runtime linux-amd64 --build-worker+ - name: Test kernel test runner+ run: node --test scripts/test-kernel.test.mjs- name: Test all kernel packagesid: test_all_kernel_packages# 测试失败只记录结果,不阻塞后续发布构建。continue-on-error: true- run: go test -tags "fts5 sqlcipher" ./... -count=1+ run: node ../scripts/test-kernel.mjs --shards 4 --output "${{ runner.temp }}/kernel-test-results"working-directory: kernelenv:SIYUAN_OCR_TEST_ASSETS: ${{ github.workspace }}/app/stage/ocr/models@@ -231,6 +233,14 @@ jobs:TMPDIR: /tmpGOTMPDIR: ${{ runner.temp }}+ - name: Upload kernel test logs+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: kernel-tests-linux+ path: ${{ runner.temp }}/kernel-test-results+ if-no-files-found: ignore+- name: Report non-blocking step outcomesif: always()env:@@ -260,17 +270,27 @@ jobs:msystem: UCRT64path-type: inheritinstall: mingw-w64-ucrt-x86_64-gcc+ - name: Test kernel test runner+ run: node --test scripts/test-kernel.test.mjs- name: Test all Windows kernel packagesid: test_windows_kernel_packages# 测试失败只记录结果,不阻塞后续发布构建。continue-on-error: trueshell: msys2 {0}- run: go test -tags "fts5 sqlcipher" ./... -count=1+ run: node ../scripts/test-kernel.mjs --shards 4 --output "${{ runner.temp }}/kernel-test-results"working-directory: kernelenv:CGO_ENABLED: 1CC: gcc+ - name: Upload kernel test logs+ if: always()+ uses: actions/upload-artifact@v7+ with:+ name: kernel-tests-windows+ path: ${{ runner.temp }}/kernel-test-results+ if-no-files-found: ignore+- name: Report non-blocking step outcomesif: always()env:diff --git a/kernel/model/attribute_view_items_fts5_test.go b/kernel/model/attribute_view_items_fts5_test.goindex 05e4bc3e9f..2250117d6f 100644--- a/kernel/model/attribute_view_items_fts5_test.go+++ b/kernel/model/attribute_view_items_fts5_test.go@@ -418,6 +418,9 @@ func setupAttributeViewItemsTest(t *testing.T, bound bool) (*fileOperationTestFiGlobalUndoLog = newUndoLog(64)cache.ClearAVCache()t.Cleanup(func() {+ // 等待事务和后台分组刷新结束,再恢复测试语言及工作区状态。+ FlushTxQueue()+ backgroundRefreshWaitGroup.Wait()util.Lang, util.AttrViewLangs, GlobalUndoLog = oldLang, oldAVLangs, oldUndoLogcache.ClearAVCache()})diff --git a/kernel/model/export_system_log_test.go b/kernel/model/export_system_log_test.goindex 2327b9d6ac..8c6d9d42e9 100644--- a/kernel/model/export_system_log_test.go+++ b/kernel/model/export_system_log_test.go@@ -2,10 +2,14 @@ package modelimport ("archive/zip"+ "errors""io""os"+ "os/exec""path/filepath"+ "runtime""strings"+ "syscall""testing""time"@@ -13,6 +17,16 @@ import ()func TestBlockedTransactionWaitSavesDiagnostic(t *testing.T) {+ // 在独立进程中验证诊断,隔离全局限流状态及其他用例的后台任务。+ const childEnv = "SIYUAN_TEST_BLOCKED_TRANSACTION_DIAGNOSTIC"+ if os.Getenv(childEnv) != "1" {+ command := exec.Command(os.Args[0], "-test.run=^TestBlockedTransactionWaitSavesDiagnostic$", "-test.timeout=30s")+ command.Env = append(os.Environ(), childEnv+"=1")+ if output, err := command.CombinedOutput(); err != nil {+ t.Fatalf("blocked transaction diagnostic subprocess failed: %v\n%s", err, output)+ }+ return+ }oldTemp := util.TempDirutil.TempDir = t.TempDir()t.Cleanup(func() { util.TempDir = oldTemp })@@ -41,7 +55,9 @@ func TestBlockedTransactionWaitSavesDiagnostic(t *testing.T) {}return}- if !os.IsNotExist(err) {+ // Windows 上快照文件可能暂时被占用,继续在既有超时范围内等待可读取状态。+ sharingViolation := runtime.GOOS == "windows" && errors.Is(err, syscall.Errno(32))+ if !os.IsNotExist(err) && !sharingViolation {t.Fatal(err)}if time.Now().After(deadline) {diff --git a/kernel/model/file_queue_cleanup_fts5_test.go b/kernel/model/file_queue_cleanup_fts5_test.gonew file mode 100644index 0000000000..20c6156e6a--- /dev/null+++ b/kernel/model/file_queue_cleanup_fts5_test.go@@ -0,0 +1,41 @@+//go:build fts5++package model++import (+ "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 TestFileOperationFixtureDropsPendingIndexAfterDatabaseClose(t *testing.T) {+ oldQueueDir := util.QueueDir+ queueDir := t.TempDir()+ t.Cleanup(func() { util.QueueDir = oldQueueDir })+ t.Run("fixture", func(t *testing.T) {+ fixture := setupFileOperationTest(t)+ // 数据库夹具关闭后追加索引,模拟未初始化数据库的用例留下待处理文档。+ t.Cleanup(func() {+ util.QueueDir = queueDir+ tree, err := filesys.LoadTree(fixture.box.ID, fixture.sourcePath, util.NewLute())+ if err != nil {+ t.Fatal(err)+ }+ sql.IndexTreeQueue(tree)+ })+ setupFoldTransactionDatabase(t, fixture)+ })+ data, err := os.ReadFile(filepath.Join(queueDir, "index.queue"))+ if err != nil && !os.IsNotExist(err) {+ t.Fatal(err)+ }+ if len(data) != 0 {+ t.Fatalf("deleted fixture retained pending index data: %s", data)+ }+ // 后续用例清理密钥时刷新队列,不应访问已关闭的数据库或已释放的配置。+ sql.FlushQueue()+}diff --git a/kernel/model/file_test.go b/kernel/model/file_test.goindex 1fa2c570d9..0c4dee9ad3 100644--- a/kernel/model/file_test.go+++ b/kernel/model/file_test.go@@ -85,6 +85,10 @@ func setupFileOperationTest(t *testing.T) *fileOperationTestFixture {}t.Cleanup(func() {+ FlushTxQueue()+ backgroundRefreshWaitGroup.Wait()+ // 测试文档即将删除,其待处理索引不能留给后续用例刷新。+ sql.ClearQueue()cache.RemoveTreeData(sourceTree.ID)cache.RemoveTreeData(targetTree.ID)cache.RemoveDocIAL(sourceTree.Path)diff --git a/kernel/model/push_reload.go b/kernel/model/push_reload.goindex a2b20aa683..29520e90c4 100644--- a/kernel/model/push_reload.go+++ b/kernel/model/push_reload.go@@ -43,6 +43,21 @@ import ("github.com/siyuan-note/siyuan/kernel/util")+var backgroundRefreshWaitGroup sync.WaitGroup++// runBackgroundRefresh 跟踪延迟刷新任务,便于工作区释放前等待任务结束。+func runBackgroundRefresh(delay time.Duration, refresh func()) {+ backgroundRefreshWaitGroup.Add(1)+ go func() {+ defer backgroundRefreshWaitGroup.Done()+ time.Sleep(delay)+ // 与编辑事务串行刷新,避免异步分组写回覆盖撤销、重做后的数据。+ flushLock.Lock()+ defer flushLock.Unlock()+ refresh()+ }()+}+func PushReloadSnippet(snippet *conf.Snpt) {util.BroadcastByType("main", "setSnippet", 0, "", snippet)}@@ -194,10 +209,9 @@ func refreshDocInfoWithSize(tree *parse.Tree, size uint64) {}refreshDocInfo0(tree, size)- go func() {- time.Sleep(128 * time.Millisecond)+ runBackgroundRefresh(128*time.Millisecond, func() {refreshParentDocInfo(tree)- }()+ })}func refreshParentDocInfo(tree *parse.Tree) {diff --git a/kernel/model/transaction.go b/kernel/model/transaction.goindex 2663a13ab9..a90b045f94 100644--- a/kernel/model/transaction.go+++ b/kernel/model/transaction.go@@ -2166,12 +2166,11 @@ func (tx *Transaction) doUpdate(operation *Operation) (ret *TxErr) {if avNames := getAvNames(updatedNode.IALAttr(av.NodeAttrNameAvs)); "" != avNames {// updateBlock 会清空数据库角标 https://github.com/siyuan-note/siyuan/issues/16549- go func() {- time.Sleep(200 * time.Millisecond)+ runBackgroundRefresh(200*time.Millisecond, func() {oldAttrs := parse.IAL2Map(updatedNode.KramdownIAL)updatedNode.SetIALAttr(av.NodeAttrViewNames, avNames)pushBlockAttrs(oldAttrs, updatedNode)- }()+ })}treenode.CreatedUpdated(updatedNode)@@ -2325,8 +2324,7 @@ func upsertAvBlockRel(node *ast.Node) {})}- go func() {- time.Sleep(100 * time.Millisecond)+ runBackgroundRefresh(100*time.Millisecond, func() {affectedAvIDs = gulu.Str.RemoveDuplicatedElem(affectedAvIDs)relatedAvIDs := av.GetSrcAvIDsForRefresh(affectedAvIDs)@@ -2340,7 +2338,7 @@ func upsertAvBlockRel(node *ast.Node) {ReloadAttrView(avID)}- }()+ })}func (tx *Transaction) doUpdateUpdated(operation *Operation) (ret *TxErr) {diff --git a/scripts/kernel-model-test-durations.json b/scripts/kernel-model-test-durations.jsonnew file mode 100644index 0000000000..89c8d57920--- /dev/null+++ b/scripts/kernel-model-test-durations.json@@ -0,0 +1,430 @@+{+ "prefixLength": 6,+ "defaultSeconds": 0.2,+ "buckets": {+ "TestAI": {+ "seconds": 0.07,+ "tests": 5+ },+ "TestAc": {+ "seconds": 0.05,+ "tests": 5+ },+ "TestAd": {+ "seconds": 0.16,+ "tests": 9+ },+ "TestAg": {+ "seconds": 0.24,+ "tests": 6+ },+ "TestAl": {+ "seconds": 0.02,+ "tests": 1+ },+ "TestAn": {+ "seconds": 0.21,+ "tests": 3+ },+ "TestAp": {+ "seconds": 2.28,+ "tests": 20+ },+ "TestAs": {+ "seconds": 8.27,+ "tests": 28+ },+ "TestAt": {+ "seconds": 74.77,+ "tests": 137+ },+ "TestAu": {+ "seconds": 10.77,+ "tests": 22+ },+ "TestBa": {+ "seconds": 5.82,+ "tests": 23+ },+ "TestBl": {+ "seconds": 20.4,+ "tests": 7+ },+ "TestBo": {+ "seconds": 3.64,+ "tests": 18+ },+ "TestBu": {+ "seconds": 0.01,+ "tests": 39+ },+ "TestCa": {+ "seconds": 1.95,+ "tests": 5+ },+ "TestCh": {+ "seconds": 0.95,+ "tests": 22+ },+ "TestCl": {+ "seconds": 1.67,+ "tests": 37+ },+ "TestCo": {+ "seconds": 1.08,+ "tests": 36+ },+ "TestCr": {+ "seconds": 11.39,+ "tests": 16+ },+ "TestCu": {+ "seconds": 0.14,+ "tests": 4+ },+ "TestDA": {+ "seconds": 0,+ "tests": 1+ },+ "TestDa": {+ "seconds": 0.2,+ "tests": 2+ },+ "TestDe": {+ "seconds": 1.78,+ "tests": 18+ },+ "TestDo": {+ "seconds": 10.22,+ "tests": 46+ },+ "TestDr": {+ "seconds": 0.07,+ "tests": 1+ },+ "TestDu": {+ "seconds": 2.61,+ "tests": 7+ },+ "TestDy": {+ "seconds": 0.6,+ "tests": 3+ },+ "TestEf": {+ "seconds": 0,+ "tests": 1+ },+ "TestEm": {+ "seconds": 0.05,+ "tests": 12+ },+ "TestEn": {+ "seconds": 3.6,+ "tests": 27+ },+ "TestEs": {+ "seconds": 0,+ "tests": 1+ },+ "TestEx": {+ "seconds": 9.6,+ "tests": 53+ },+ "TestFT": {+ "seconds": 0,+ "tests": 2+ },+ "TestFi": {+ "seconds": 5.52,+ "tests": 45+ },+ "TestFl": {+ "seconds": 0.52,+ "tests": 9+ },+ "TestFo": {+ "seconds": 0.01,+ "tests": 3+ },+ "TestFr": {+ "seconds": 0,+ "tests": 4+ },+ "TestFu": {+ "seconds": 0.01,+ "tests": 1+ },+ "TestGe": {+ "seconds": 1.08,+ "tests": 44+ },+ "TestGl": {+ "seconds": 10.04,+ "tests": 4+ },+ "TestGr": {+ "seconds": 0.02,+ "tests": 4+ },+ "TestHT": {+ "seconds": 0.02,+ "tests": 5+ },+ "TestHa": {+ "seconds": 0.01,+ "tests": 4+ },+ "TestHe": {+ "seconds": 0,+ "tests": 10+ },+ "TestHi": {+ "seconds": 0.32,+ "tests": 10+ },+ "TestIO": {+ "seconds": 1.42,+ "tests": 1+ },+ "TestIm": {+ "seconds": 1.82,+ "tests": 18+ },+ "TestIn": {+ "seconds": 3.94,+ "tests": 31+ },+ "TestIs": {+ "seconds": 0.04,+ "tests": 17+ },+ "TestJW": {+ "seconds": 0,+ "tests": 1+ },+ "TestLA": {+ "seconds": 0,+ "tests": 2+ },+ "TestLa": {+ "seconds": 0.53,+ "tests": 1+ },+ "TestLe": {+ "seconds": 0.27,+ "tests": 9+ },+ "TestLi": {+ "seconds": 14.96,+ "tests": 23+ },+ "TestLo": {+ "seconds": 0.6,+ "tests": 13+ },+ "TestMa": {+ "seconds": 5.93,+ "tests": 30+ },+ "TestMe": {+ "seconds": 0.07,+ "tests": 6+ },+ "TestMi": {+ "seconds": 1.78,+ "tests": 21+ },+ "TestMo": {+ "seconds": 4.71,+ "tests": 16+ },+ "TestMu": {+ "seconds": 0.15,+ "tests": 7+ },+ "TestNe": {+ "seconds": 0.04,+ "tests": 11+ },+ "TestNo": {+ "seconds": 12.99,+ "tests": 38+ },+ "TestOC": {+ "seconds": 0.55,+ "tests": 3+ },+ "TestOI": {+ "seconds": 0.01,+ "tests": 8+ },+ "TestOb": {+ "seconds": 0.23,+ "tests": 4+ },+ "TestOr": {+ "seconds": 0,+ "tests": 1+ },+ "TestPD": {+ "seconds": 3.08,+ "tests": 2+ },+ "TestPa": {+ "seconds": 1.21,+ "tests": 20+ },+ "TestPe": {+ "seconds": 1.39,+ "tests": 8+ },+ "TestPi": {+ "seconds": 0.59,+ "tests": 6+ },+ "TestPl": {+ "seconds": 0.48,+ "tests": 6+ },+ "TestPr": {+ "seconds": 0.69,+ "tests": 28+ },+ "TestPu": {+ "seconds": 1.25,+ "tests": 8+ },+ "TestQu": {+ "seconds": 0.1,+ "tests": 3+ },+ "TestRa": {+ "seconds": 0,+ "tests": 1+ },+ "TestRe": {+ "seconds": 14.18,+ "tests": 109+ },+ "TestRo": {+ "seconds": 0.04,+ "tests": 2+ },+ "TestS3": {+ "seconds": 0.3,+ "tests": 4+ },+ "TestSH": {+ "seconds": 0,+ "tests": 1+ },+ "TestSQ": {+ "seconds": 0.28,+ "tests": 3+ },+ "TestSa": {+ "seconds": 0.01,+ "tests": 5+ },+ "TestSc": {+ "seconds": 0,+ "tests": 2+ },+ "TestSe": {+ "seconds": 3.79,+ "tests": 41+ },+ "TestSh": {+ "seconds": 0.01,+ "tests": 9+ },+ "TestSi": {+ "seconds": 0,+ "tests": 1+ },+ "TestSn": {+ "seconds": 0.64,+ "tests": 5+ },+ "TestSo": {+ "seconds": 7.43,+ "tests": 15+ },+ "TestSt": {+ "seconds": 0.04,+ "tests": 6+ },+ "TestSw": {+ "seconds": 0.09,+ "tests": 1+ },+ "TestSy": {+ "seconds": 15.07,+ "tests": 48+ },+ "TestTa": {+ "seconds": 1.29,+ "tests": 12+ },+ "TestTe": {+ "seconds": 5.46,+ "tests": 23+ },+ "TestTh": {+ "seconds": 0.06,+ "tests": 2+ },+ "TestTo": {+ "seconds": 0,+ "tests": 1+ },+ "TestTr": {+ "seconds": 0.59,+ "tests": 5+ },+ "TestTw": {+ "seconds": 0.05,+ "tests": 1+ },+ "TestTx": {+ "seconds": 0,+ "tests": 1+ },+ "TestUn": {+ "seconds": 0.93,+ "tests": 17+ },+ "TestUp": {+ "seconds": 0.19,+ "tests": 24+ },+ "TestVa": {+ "seconds": 0.14,+ "tests": 13+ },+ "TestVe": {+ "seconds": 0.05,+ "tests": 1+ },+ "TestVi": {+ "seconds": 0.02,+ "tests": 4+ },+ "TestWa": {+ "seconds": 0.07,+ "tests": 4+ },+ "TestWi": {+ "seconds": 0,+ "tests": 1+ },+ "TestWo": {+ "seconds": 0.01,+ "tests": 1+ },+ "TestWr": {+ "seconds": 0.01,+ "tests": 4+ }+ }+}diff --git a/scripts/test-kernel.mjs b/scripts/test-kernel.mjsnew file mode 100644index 0000000000..2e6479bc38--- /dev/null+++ b/scripts/test-kernel.mjs@@ -0,0 +1,232 @@+import {spawn, spawnSync} from "node:child_process";+import {createWriteStream, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync} from "node:fs";+import {availableParallelism, tmpdir} from "node:os";+import {basename, dirname, join, resolve} from "node:path";+import {performance} from "node:perf_hooks";+import {fileURLToPath} from "node:url";++const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");+const kernel = join(root, "kernel");+const modelPackage = "github.com/siyuan-note/siyuan/kernel/model";+const tags = ["-tags", "fts5 sqlcipher"];+// 为模型分片保留内存,限制其余包同时进行重型原生链接的数量。+const packageParallelism = Math.min(2, availableParallelism());+const escapeRegex = value => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");++export const listTests = output => output.split(/\r?\n/).filter(name => /^(Test|Example|Fuzz)\S*$/.test(name));++// 按短前缀聚合,再按历史耗时均衡分配;每次从当前测试二进制读取用例,避免遗漏新增测试。+export const planShards = (names, count, durations) => {+ if (!Number.isInteger(count) || count < 1 || count > 16 || new Set(names).size !== names.length) {+ throw new Error("Invalid shard count or duplicate test names");+ }+ const buckets = new Map();+ for (const name of names) {+ const prefix = name.slice(0, durations.prefixLength);+ const bucket = buckets.get(prefix) ?? {prefix, names: []};+ bucket.names.push(name);+ buckets.set(prefix, bucket);+ }+ const shards = Array.from({length: Math.min(count, buckets.size)}, () => ({seconds: 0, names: [], prefixes: []}));+ for (const bucket of [...buckets.values()]) {+ const measured = durations.buckets[bucket.prefix];+ bucket.seconds = measured ? measured.seconds + Math.max(0, bucket.names.length - measured.tests) * durations.defaultSeconds :+ bucket.names.length * durations.defaultSeconds;+ }+ const ordered = [...buckets.values()].sort((a, b) => b.seconds - a.seconds || a.prefix.localeCompare(b.prefix, "en"));+ for (const bucket of ordered) {+ const shard = shards.reduce((best, item) => item.seconds < best.seconds ? item : best);+ shard.seconds += bucket.seconds;+ shard.names.push(...bucket.names);+ shard.prefixes.push(escapeRegex(bucket.prefix) + (bucket.prefix.length < durations.prefixLength ? "$" : ""));+ }+ for (const shard of shards) {+ shard.regex = "^(" + shard.prefixes.sort().join("|") + ")";+ const matches = names.filter(name => new RegExp(shard.regex).test(name)).sort();+ if (JSON.stringify(matches) !== JSON.stringify([...shard.names].sort())) {+ throw new Error("Shard selection does not match its assigned tests");+ }+ }+ return shards;+};++// 每个进程使用独立的当前目录,测试资源通过目录链接复用,隔离相对路径写入。+export const prepareModelWorkspace = (repository, workspace) => {+ const cwd = join(workspace, "kernel", "model");+ mkdirSync(cwd, {recursive: true});+ const link = (source, destination) => symlinkSync(source, destination, process.platform === "win32" ? "junction" : "dir");+ link(join(repository, "app"), join(workspace, "app"));+ for (const entry of readdirSync(join(repository, "kernel"), {withFileTypes: true})) {+ if (entry.isDirectory() && entry.name !== "model") {+ link(join(repository, "kernel", entry.name), join(workspace, "kernel", entry.name));+ }+ }+ for (const entry of readdirSync(join(repository, "kernel", "model"), {withFileTypes: true})) {+ if (entry.isDirectory()) {+ link(join(repository, "kernel", "model", entry.name), join(cwd, entry.name));+ }+ }+ return cwd;+};++const command = (args, cwd = kernel) => {+ const result = spawnSync("go", args, {cwd, encoding: "utf8", windowsHide: true, maxBuffer: 16 * 1024 * 1024});+ if (result.error || result.status !== 0) {+ throw result.error ?? new Error(result.stderr || result.stdout || `go exited with ${result.status}`);+ }+ return result.stdout;+};++export const runJSONJob = async ({name, args, cwd, expectedTests, executable = "go"}, output) => {+ const started = performance.now();+ const logPath = join(output, name + ".jsonl");+ const log = createWriteStream(logPath);+ const child = spawn(executable, args, {cwd, windowsHide: true, stdio: ["ignore", "pipe", "pipe"]});+ let pending = "";+ const completed = new Set();+ const failed = new Set();+ const tail = [];+ const consume = line => {+ log.write(line + "\n");+ try {+ const event = JSON.parse(line);+ if (event.Output) {+ tail.push(event.Output.trimEnd());+ if (tail.length > 100) {+ tail.shift();+ }+ }+ if (event.Test && !event.Test.includes("/") && ["pass", "fail", "skip"].includes(event.Action)) {+ completed.add(event.Test);+ }+ if (event.Action === "fail") {+ failed.add(event.Test ?? event.Package);+ }+ } catch {+ tail.push(line);+ }+ };+ child.stdout.setEncoding("utf8");+ child.stdout.on("data", data => {+ pending += data;+ const lines = pending.split("\n");+ pending = lines.pop();+ lines.forEach(consume);+ });+ child.stderr.setEncoding("utf8");+ child.stderr.on("data", data => {+ log.write(data);+ tail.push(data.trimEnd());+ });+ const code = await new Promise(resolve => {+ child.on("error", error => { tail.push(error.message); });+ child.on("close", resolve);+ });+ if (pending) {+ consume(pending);+ }+ await new Promise(resolve => log.end(resolve));+ const missing = expectedTests?.filter(test => !completed.has(test)) ?? [];+ const unexpected = expectedTests ? [...completed].filter(test => !expectedTests.includes(test)) : [];+ const result = {name, code: code ?? 1, seconds: (performance.now() - started) / 1000, tests: completed.size,+ failed: [...failed], missing, unexpected, logPath};+ if (result.code || failed.size || missing.length || unexpected.length) {+ result.code = 1;+ console.error(`${name} failed\n${tail.join("\n")}\nMissing: ${missing.join(", ")}\nUnexpected: ${unexpected.join(", ")}`);+ }+ console.log(`${name}: ${result.code ? "FAIL" : "PASS"}, ${result.tests} tests, ${result.seconds.toFixed(1)}s`);+ return result;+};++export const runJobs = async (jobs, concurrency, run) => {+ let next = 0;+ const results = new Array(jobs.length);+ await Promise.all(Array.from({length: Math.min(concurrency, jobs.length)}, async () => {+ while (next < jobs.length) {+ const index = next++;+ results[index] = await run(jobs[index]);+ }+ }));+ return results;+};++const main = async () => {+ const options = {shards: Math.min(4, availableParallelism()), modelOnly: false, output: undefined};+ for (let i = 2; i < process.argv.length; i++) {+ const argument = process.argv[i];+ if (argument === "--model-only") {+ options.modelOnly = true;+ } else if (argument === "--shards") {+ options.shards = Number(process.argv[++i]);+ } else if (argument === "--output") {+ options.output = resolve(process.argv[++i]);+ } else {+ throw new Error("Unknown argument: " + argument);+ }+ }+ if (!Number.isInteger(options.shards) || options.shards < 1 || options.shards > 16) {+ throw new Error("--shards must be an integer between 1 and 16");+ }+ const started = performance.now();+ const workspace = mkdtempSync(join(tmpdir(), "siyuan-kernel-tests-"));+ const output = options.output ?? mkdtempSync(join(tmpdir(), "siyuan-kernel-results-"));+ mkdirSync(output, {recursive: true});+ let otherJob;+ let otherFinished = false;+ try {+ // 其他包的编译和测试与 model 测试二进制的编译重叠,保留完整套件的包间并行。+ if (!options.modelOnly) {+ const packages = command(["list", ...tags, "./..."]).trim().split(/\r?\n/).filter(name => name !== modelPackage);+ otherJob = runJSONJob({name: "other-packages", cwd: kernel,+ args: ["test", ...tags, "-p", String(packageParallelism), "-json", "-count=1", ...packages]}, output)+ .finally(() => { otherFinished = true; });+ }+ const binary = join(workspace, process.platform === "win32" ? "model.test.exe" : "model.test");+ await new Promise((resolve, reject) => {+ const compiler = spawn("go", ["test", ...tags, "-p", String(packageParallelism), "-c", "-o", binary, "./model"], {+ cwd: kernel, windowsHide: true, stdio: "inherit",+ });+ compiler.on("error", reject);+ compiler.on("close", code => code === 0 ? resolve() : reject(new Error("Model test compilation failed: " + code)));+ });+ const listed = spawnSync(binary, ["-test.list=."], {cwd: join(kernel, "model"), encoding: "utf8", windowsHide: true});+ if (listed.error || listed.status !== 0) {+ throw listed.error ?? new Error(listed.stderr);+ }+ const names = listTests(listed.stdout);+ if (!names.length) {+ throw new Error("No model tests discovered");+ }+ const durations = JSON.parse(readFileSync(join(root, "scripts", "kernel-model-test-durations.json"), "utf8"));+ const shards = planShards(names, options.shards, durations);+ const jobs = shards.map((shard, i) => ({name: "model-" + (i + 1), expectedTests: shard.names,+ cwd: prepareModelWorkspace(root, join(workspace, "shard-" + i)),+ args: ["tool", "test2json", "-t", "-p", modelPackage, binary, "-test.v=test2json", "-test.count=1", "-test.timeout=10m", "-test.run=" + shard.regex]}));+ const concurrency = Math.min(4, Math.max(1, availableParallelism() - (otherJob && !otherFinished ? 1 : 0)));+ console.log(`Running ${names.length} model tests in ${shards.length} shards; ${concurrency} concurrent jobs; logs: ${output}`);+ const results = await runJobs(jobs, concurrency, job => runJSONJob(job, output));+ if (otherJob) {+ results.unshift(await otherJob);+ }+ const summary = {seconds: (performance.now() - started) / 1000, modelTests: names.length, shards: shards.length, results};+ writeFileSync(join(output, "summary.json"), JSON.stringify(summary, null, 2) + "\n");+ console.log(`Kernel tests: ${summary.seconds.toFixed(1)}s; summary: ${join(output, "summary.json")}`);+ process.exitCode = results.some(result => result.code) ? 1 : 0;+ } finally {+ if (otherJob) {+ await otherJob;+ }+ // 只删除本次创建的临时目录;目录链接的目标资源保留。+ if (dirname(resolve(workspace)) !== resolve(tmpdir()) || !basename(workspace).startsWith("siyuan-kernel-tests-")) {+ throw new Error("Unsafe temporary workspace path");+ }+ rmSync(workspace, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ }+};++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ main().catch(error => {+ console.error(error);+ process.exitCode = 1;+ });+}diff --git a/scripts/test-kernel.test.mjs b/scripts/test-kernel.test.mjsnew file mode 100644index 0000000000..39fedfb892--- /dev/null+++ b/scripts/test-kernel.test.mjs@@ -0,0 +1,102 @@+import {test} from "node:test";+import * as assert from "node:assert/strict";+import {mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";+import {tmpdir} from "node:os";+import {dirname, join, resolve} from "node:path";+import {listTests, planShards, prepareModelWorkspace, runJSONJob, runJobs} from "./test-kernel.mjs";++const durations = {prefixLength: 6, defaultSeconds: 0.2, buckets: {+ TestSl: {seconds: 40, tests: 2}, TestMe: {seconds: 20, tests: 2}, TestFa: {seconds: 10, tests: 2},+}};+const temporary = t => {+ const directory = mkdtempSync(join(tmpdir(), "siyuan-kernel-runner-test-"));+ t.after(() => {+ assert.equal(dirname(resolve(directory)), resolve(tmpdir()));+ rmSync(directory, {recursive: true, force: true, maxRetries: 5, retryDelay: 100});+ });+ return directory;+};++test("test discovery includes examples and fuzz seeds without enabling benchmarks", () => {+ assert.deepEqual(listTests("TestOne\r\nExampleTwo\r\nFuzzThree\r\nBenchmarkFour\r\nPASS\r\n"),+ ["TestOne", "ExampleTwo", "FuzzThree"]);+});++test("duration balancing discovers new families and selects every current test exactly once", () => {+ const names = ["TestSlowOne", "TestSlowTwo", "TestMediumOne", "TestMediumTwo", "TestFastOne", "TestFastTwo",+ "TestNewOne", "TestNewTwo", "FuzzNew", "ExampleNew", "TestA", "TestAB", "TestABC", "TestAbcNew"];+ const shards = planShards(names, 4, durations);+ assert.equal(shards.length, 4);+ assert.deepEqual(shards.flatMap(shard => shard.names).sort(), [...names].sort());+ for (const name of names) {+ assert.equal(shards.filter(shard => new RegExp(shard.regex).test(name)).length, 1, name);+ }+ assert.equal(Math.max(...shards.map(shard => shard.seconds)), 40);+ assert.deepEqual(planShards([...names].reverse(), 4, durations).map(shard => shard.regex), shards.map(shard => shard.regex));+ const removed = names.filter(name => name !== "TestSlowTwo");+ assert.deepEqual(planShards(removed, 4, durations).flatMap(shard => shard.names).sort(), removed.sort());+});++test("invalid shard counts and duplicate names fail before running tests", () => {+ for (const count of [0, -1, 1.5, 17, NaN]) {+ assert.throws(() => planShards(["TestOne"], count, durations));+ }+ assert.throws(() => planShards(["TestOne", "TestOne"], 4, durations));+});++test("parallel jobs remain bounded and a failed job does not omit later shards", async () => {+ const jobs = [0, 1, 2, 3, 4];+ let active = 0;+ let peak = 0;+ const visited = [];+ const results = await runJobs(jobs, 2, async job => {+ active++;+ peak = Math.max(peak, active);+ visited.push(job);+ await new Promise(resolve => setTimeout(resolve, 5));+ active--;+ return {code: job === 1 ? 1 : 0};+ });+ assert.equal(peak, 2);+ assert.deepEqual(visited.sort(), jobs);+ assert.deepEqual(results.map(result => result.code), [0, 1, 0, 0, 0]);+});++test("each model process has isolated relative writes while retaining repository fixtures", t => {+ const directory = temporary(t);+ const repository = join(directory, "repository");+ for (const relative of ["app/guide", "kernel/av/testdata", "kernel/model/testdata", "kernel/treenode/testdata"]) {+ mkdirSync(join(repository, relative), {recursive: true});+ writeFileSync(join(repository, relative, "fixture.txt"), relative);+ }+ const workspaces = [join(directory, "one"), join(directory, "two")];+ const [one, two] = workspaces.map(workspace => prepareModelWorkspace(repository, workspace));+ writeFileSync(join(one, "conf.json"), "one");+ writeFileSync(join(two, "conf.json"), "two");+ assert.equal(readFileSync(join(one, "conf.json"), "utf8"), "one");+ assert.equal(readFileSync(join(two, "conf.json"), "utf8"), "two");+ assert.equal(readFileSync(join(one, "../../app/guide/fixture.txt"), "utf8"), "app/guide");+ assert.equal(readFileSync(join(two, "../av/testdata/fixture.txt"), "utf8"), "kernel/av/testdata");+ assert.equal(readFileSync(join(one, "testdata/fixture.txt"), "utf8"), "kernel/model/testdata");+ assert.equal(dirname(resolve(workspaces[0])), resolve(directory));+ rmSync(workspaces[0], {recursive: true, force: true});+ assert.equal(readFileSync(join(repository, "app/guide/fixture.txt"), "utf8"), "app/guide");+ assert.equal(readFileSync(join(two, "../treenode/testdata/fixture.txt"), "utf8"), "kernel/treenode/testdata");+});++test("process failures, missing tests and truncated coverage cannot produce a passing shard", async t => {+ t.mock.method(console, "log", () => {});+ t.mock.method(console, "error", () => {});+ const output = temporary(t);+ const run = async (name, events, status, expectedTests) => {+ const source = `process.stdout.write(${JSON.stringify(events.map(event => JSON.stringify(event)).join("\n") + "\n")}); process.exitCode = ${status};`;+ return runJSONJob({name, args: ["-e", source], executable: process.execPath, cwd: output, expectedTests}, output);+ };+ assert.equal((await run("pass", [{Action: "pass", Test: "TestOne"}], 0, ["TestOne"])).code, 0);+ const missing = await run("missing", [{Action: "pass", Test: "TestOne"}], 0, ["TestOne", "TestTwo"]);+ assert.equal(missing.code, 1);+ assert.deepEqual(missing.missing, ["TestTwo"]);+ assert.equal((await run("unexpected", [{Action: "pass", Test: "TestOther"}], 0, ["TestOne"])).code, 1);+ assert.equal((await run("failure", [{Action: "fail", Test: "TestOne"}], 0, ["TestOne"])).code, 1);+ assert.equal((await run("crash", [], 2, ["TestOne"])).code, 1);+});diff --git a/scripts/test_editor_e2e_workflow.py b/scripts/test_editor_e2e_workflow.pyindex ba305b6d7f..ed59a9cd87 100644--- a/scripts/test_editor_e2e_workflow.py+++ b/scripts/test_editor_e2e_workflow.py@@ -35,7 +35,7 @@ class EditorWorkflowTests(unittest.TestCase):self.assertIn("path-type: inherit", compiler)self.assertIn("mingw-w64-ucrt-x86_64-gcc", compiler)step = kernel.split("- name: Test all Windows kernel packages\n", 1)[1].split(" - ", 1)[0]- self.assertIn('run: go test -tags "fts5 sqlcipher" ./... -count=1', step)+ self.assertIn('run: node ../scripts/test-kernel.mjs --shards 4 --output "${{ runner.temp }}/kernel-test-results"', step)self.assertIn("shell: msys2 {0}", step)self.assertIn("CGO_ENABLED: 1", step)self.assertIn("CC: gcc", step)@@ -113,7 +113,7 @@ class EditorWorkflowTests(unittest.TestCase):self.assertIn("sudo apt-get install -y strace", linux)self.assertIn("python3 scripts/prepare-ocr.py --runtime linux-amd64 --build-worker", linux)full = linux.split("- name: Test all kernel packages\n", 1)[1].split(" - ", 1)[0]- self.assertIn('run: go test -tags "fts5 sqlcipher" ./... -count=1', full)+ self.assertIn('run: node ../scripts/test-kernel.mjs --shards 4 --output "${{ runner.temp }}/kernel-test-results"', full)self.assertIn("continue-on-error: true", full)self.assertIn("SIYUAN_OCR_TEST_ASSETS: ${{ github.workspace }}/app/stage/ocr/models", full)self.assertIn("SIYUAN_OCR_TEST_LIBRARY: ${{ github.workspace }}/app/stage/ocr/runtime/linux-amd64/libonnxruntime.so", full)@@ -129,6 +129,15 @@ class EditorWorkflowTests(unittest.TestCase):step = linux.split(f"- name: {hard_step}\n", 1)[1].split(" - ", 1)[0]self.assertNotIn("continue-on-error:", step)+ def test_kernel_shard_runner_and_logs_are_checked_on_both_platforms(self):+ for platform in ["linux", "windows"]:+ kernel = job(f"kernel-tests-{platform}")+ self.assertIn("run: node --test scripts/test-kernel.test.mjs", kernel)+ upload = kernel.split("- name: Upload kernel test logs\n", 1)[1].split(" - ", 1)[0]+ self.assertIn("if: always()", upload)+ self.assertIn(f"name: kernel-tests-{platform}", upload)+ self.assertIn("path: ${{ runner.temp }}/kernel-test-results", upload)+def test_go_cache_and_builds_share_job_level_module_directory(self):for build in [DESKTOP.split("jobs:\n build:\n", 1)[1], job("build_android")]:header, steps = build.split(" steps:\n", 1)