Skip to content

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

:construction_worker: Run API tests in balanced shards https://github.com/siyuan-note/siyuan/issues/20491

Danield62bef947104
diff --git a/kernel/api/lute_clipboard_style_test.go b/kernel/api/lute_clipboard_style_test.go
index b76d413c46..57844d6b93 100644
--- a/kernel/api/lute_clipboard_style_test.go
+++ b/kernel/api/lute_clipboard_style_test.go
@@ -37,6 +37,9 @@ func githubClipboardFixture(t *testing.T) string {
}
func TestMatchHTMLClipboardElements(t *testing.T) {
+ originalMarkdown := util.MarkdownSettings.Load()
+ util.MarkdownSettings.Store(util.NewMarkdown())
+ t.Cleanup(func() { util.MarkdownSettings.Store(originalMarkdown) })
input := render.Sanitize(githubClipboardFixture(t)) + `<h2 style="color:red;background:yellow;font:20px serif">` +
`<strong>heading</strong></h2><p style="color:gray;font-size:1rem">text ` +
`<a href="https://example.com" title="title" style="color:blue;background-color:transparent;` +
@@ -73,6 +76,18 @@ func TestMatchHTMLClipboardElements(t *testing.T) {
}
}
+func TestMatchHTMLClipboardElementsRestoresMarkdownSettings(t *testing.T) {
+ originalMarkdown := util.MarkdownSettings.Load()
+ settings := util.NewMarkdown()
+ settings.InlineAsterisk, settings.InlineStrikethrough = false, false
+ util.MarkdownSettings.Store(settings)
+ t.Cleanup(func() { util.MarkdownSettings.Store(originalMarkdown) })
+ t.Run("default syntax", TestMatchHTMLClipboardElements)
+ if util.MarkdownSettings.Load() != settings {
+ t.Fatal("clipboard fixture did not restore the previous Markdown settings")
+ }
+}
+
func TestMatchHTMLClipboardElementsAcrossSources(t *testing.T) {
for _, input := range []string{
`<div data-lark-html-role="root"><div style="color:gray;font-size:14px">text<span style="color:red;background:yellow">mark</span></div></div>`,
diff --git a/kernel/mcp/tools/file_limit_test.go b/kernel/mcp/tools/file_limit_test.go
index 8c0640841c..a0ee8966c0 100644
--- a/kernel/mcp/tools/file_limit_test.go
+++ b/kernel/mcp/tools/file_limit_test.go
@@ -13,6 +13,8 @@ func TestFileQueryLimits(t *testing.T) {
writeProbeFile(t, filepath.Join(workspace, "data", "query", fmt.Sprintf("%03d.txt", i)), "match\n")
}
writeProbeFile(t, filepath.Join(workspace, "data", "lines.txt"), strings.Repeat("match\n", 205))
+ // 子用例只读取共享夹具,限制查询并发,避免同时遍历大量文件。
+ querySlots := make(chan struct{}, 2)
for _, operation := range []string{"list", "find", "grep", "grep-file"} {
for _, tc := range []struct {
name string
@@ -25,6 +27,9 @@ func TestFileQueryLimits(t *testing.T) {
{"positive", float64(3), 3},
} {
t.Run(operation+"/"+tc.name, func(t *testing.T) {
+ t.Parallel()
+ querySlots <- struct{}{}
+ defer func() { <-querySlots }()
args := map[string]any{"path": "data/query", "pattern": "match"}
if tc.limit != nil {
args["limit"] = tc.limit
diff --git a/scripts/kernel-api-test-durations.json b/scripts/kernel-api-test-durations.json
new file mode 100644
index 0000000000..3c08b2e661
--- /dev/null
+++ b/scripts/kernel-api-test-durations.json
@@ -0,0 +1,782 @@
+{
+ "prefixLength": 16,
+ "defaultSeconds": 0.2,
+ "buckets": {
+ "TestAIEditorActi": {
+ "seconds": 0.03,
+ "tests": 1
+ },
+ "TestAPIContractA": {
+ "seconds": 7.76,
+ "tests": 34
+ },
+ "TestAPIContractB": {
+ "seconds": 2.89,
+ "tests": 11
+ },
+ "TestAPIContractC": {
+ "seconds": 2.23,
+ "tests": 7
+ },
+ "TestAPIContractD": {
+ "seconds": 6.16,
+ "tests": 10
+ },
+ "TestAPIContractE": {
+ "seconds": 5.19,
+ "tests": 11
+ },
+ "TestAPIContractF": {
+ "seconds": 2.84,
+ "tests": 12
+ },
+ "TestAPIContractG": {
+ "seconds": 1.13,
+ "tests": 5
+ },
+ "TestAPIContractH": {
+ "seconds": 10.05,
+ "tests": 4
+ },
+ "TestAPIContractI": {
+ "seconds": 0.83,
+ "tests": 7
+ },
+ "TestAPIContractJ": {
+ "seconds": 0.71,
+ "tests": 3
+ },
+ "TestAPIContractL": {
+ "seconds": 0.18,
+ "tests": 3
+ },
+ "TestAPIContractM": {
+ "seconds": 3.26,
+ "tests": 4
+ },
+ "TestAPIContractN": {
+ "seconds": 2.9,
+ "tests": 17
+ },
+ "TestAPIContractO": {
+ "seconds": 2.84,
+ "tests": 16
+ },
+ "TestAPIContractP": {
+ "seconds": 6.28,
+ "tests": 18
+ },
+ "TestAPIContractR": {
+ "seconds": 2.28,
+ "tests": 10
+ },
+ "TestAPIContractS": {
+ "seconds": 7.87,
+ "tests": 59
+ },
+ "TestAPIContractT": {
+ "seconds": 0.59,
+ "tests": 4
+ },
+ "TestAPIContractU": {
+ "seconds": 16.56,
+ "tests": 4
+ },
+ "TestAPIContractW": {
+ "seconds": 0.34,
+ "tests": 4
+ },
+ "TestAVContractAu": {
+ "seconds": 1.67,
+ "tests": 1
+ },
+ "TestAVContractCa": {
+ "seconds": 1.57,
+ "tests": 4
+ },
+ "TestAVContractCo": {
+ "seconds": 0.13,
+ "tests": 1
+ },
+ "TestAVContractDe": {
+ "seconds": 1.65,
+ "tests": 1
+ },
+ "TestAVContractLi": {
+ "seconds": 0.22,
+ "tests": 1
+ },
+ "TestAVContractLo": {
+ "seconds": 0.27,
+ "tests": 3
+ },
+ "TestAVContractLu": {
+ "seconds": 0.16,
+ "tests": 1
+ },
+ "TestAVContractPu": {
+ "seconds": 0.52,
+ "tests": 2
+ },
+ "TestAVContractRe": {
+ "seconds": 0.4,
+ "tests": 4
+ },
+ "TestAVContractRo": {
+ "seconds": 0.04,
+ "tests": 1
+ },
+ "TestAVContractTr": {
+ "seconds": 0.13,
+ "tests": 1
+ },
+ "TestAVRelationCa": {
+ "seconds": 0.55,
+ "tests": 2
+ },
+ "TestAVRelationIt": {
+ "seconds": 0.36,
+ "tests": 1
+ },
+ "TestAndroidNotif": {
+ "seconds": 0.64,
+ "tests": 1
+ },
+ "TestAssetAdminEn": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestAssetAnnotat": {
+ "seconds": 0.13,
+ "tests": 1
+ },
+ "TestAssetOCRMiss": {
+ "seconds": 0.11,
+ "tests": 1
+ },
+ "TestAssetRelinkA": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestAssetRelinkC": {
+ "seconds": 0.15,
+ "tests": 1
+ },
+ "TestAssetUnusedS": {
+ "seconds": 0.24,
+ "tests": 1
+ },
+ "TestAssetUploadC": {
+ "seconds": 0.05,
+ "tests": 1
+ },
+ "TestAssetUploadR": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestAttributeVie": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestAuthFilePubl": {
+ "seconds": 0.05,
+ "tests": 2
+ },
+ "TestBacklinkCont": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestBacklinkRequ": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestBatchNoteboo": {
+ "seconds": 1.52,
+ "tests": 1
+ },
+ "TestBazaarContra": {
+ "seconds": 0.06,
+ "tests": 4
+ },
+ "TestBazaarPackag": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestBlockAttrsRe": {
+ "seconds": 0.25,
+ "tests": 1
+ },
+ "TestBlockOperati": {
+ "seconds": 0.07,
+ "tests": 1
+ },
+ "TestBlockPublish": {
+ "seconds": 0.11,
+ "tests": 1
+ },
+ "TestBootAppearan": {
+ "seconds": 0.05,
+ "tests": 1
+ },
+ "TestCanonicalBac": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestCheckBlockRe": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestClipboardMat": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestConfTransfer": {
+ "seconds": 0.13,
+ "tests": 1
+ },
+ "TestConfigureFor": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestContractBatc": {
+ "seconds": 1.58,
+ "tests": 1
+ },
+ "TestContractBloc": {
+ "seconds": 2.1,
+ "tests": 1
+ },
+ "TestContractBrea": {
+ "seconds": 2.31,
+ "tests": 2
+ },
+ "TestContractChec": {
+ "seconds": 8.84,
+ "tests": 6
+ },
+ "TestContractChil": {
+ "seconds": 1.21,
+ "tests": 1
+ },
+ "TestContractDOMN": {
+ "seconds": 1.28,
+ "tests": 1
+ },
+ "TestContractDOMs": {
+ "seconds": 1.76,
+ "tests": 1
+ },
+ "TestContractDail": {
+ "seconds": 4.43,
+ "tests": 2
+ },
+ "TestContractDocI": {
+ "seconds": 1.39,
+ "tests": 1
+ },
+ "TestContractEmbe": {
+ "seconds": 2.91,
+ "tests": 2
+ },
+ "TestContractGetD": {
+ "seconds": 1.32,
+ "tests": 1
+ },
+ "TestContractMiss": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestContractRefI": {
+ "seconds": 1.42,
+ "tests": 1
+ },
+ "TestContractSibl": {
+ "seconds": 1.35,
+ "tests": 1
+ },
+ "TestContractTail": {
+ "seconds": 1.4,
+ "tests": 1
+ },
+ "TestContractTree": {
+ "seconds": 2.66,
+ "tests": 2
+ },
+ "TestConvertClipb": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestCopyExportFi": {
+ "seconds": 0.05,
+ "tests": 4
+ },
+ "TestCriteriaCRUD": {
+ "seconds": 0.08,
+ "tests": 1
+ },
+ "TestDeferredAsse": {
+ "seconds": 4.83,
+ "tests": 1
+ },
+ "TestDocSaveAsTem": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestDownloadCust": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestEventSourceP": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestExplicitNote": {
+ "seconds": 1.23,
+ "tests": 1
+ },
+ "TestExportBrowse": {
+ "seconds": 0.02,
+ "tests": 2
+ },
+ "TestFilterBlockA": {
+ "seconds": 0.09,
+ "tests": 1
+ },
+ "TestFilterClipbo": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestFilterFileTr": {
+ "seconds": 0.08,
+ "tests": 1
+ },
+ "TestForwardProxy": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestFullTextSear": {
+ "seconds": 0.54,
+ "tests": 2
+ },
+ "TestGenerateType": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestGetAttribute": {
+ "seconds": 0.01,
+ "tests": 2
+ },
+ "TestGetBazaarPac": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestGetBlockInfo": {
+ "seconds": 6.23,
+ "tests": 3
+ },
+ "TestGetConfUILay": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestGetDocBlocks": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestGetDocInfoRe": {
+ "seconds": 0.73,
+ "tests": 1
+ },
+ "TestGetDocOption": {
+ "seconds": 0.07,
+ "tests": 1
+ },
+ "TestGetDynamicIc": {
+ "seconds": 0.43,
+ "tests": 2
+ },
+ "TestGetEncrypted": {
+ "seconds": 0.03,
+ "tests": 1
+ },
+ "TestGetFileAdmin": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestGetFileAllow": {
+ "seconds": 0.04,
+ "tests": 1
+ },
+ "TestGetFileDenie": {
+ "seconds": 0.15,
+ "tests": 1
+ },
+ "TestGetFileEdito": {
+ "seconds": 0.09,
+ "tests": 1
+ },
+ "TestGetFileJunct": {
+ "seconds": 0.15,
+ "tests": 1
+ },
+ "TestGetFileReade": {
+ "seconds": 0.23,
+ "tests": 3
+ },
+ "TestGetLocalStor": {
+ "seconds": 0.02,
+ "tests": 1
+ },
+ "TestGetMobileWor": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestGetNotebookC": {
+ "seconds": 0.04,
+ "tests": 1
+ },
+ "TestGetNotebookI": {
+ "seconds": 0.16,
+ "tests": 2
+ },
+ "TestGetOutlineSt": {
+ "seconds": 0.02,
+ "tests": 1
+ },
+ "TestGetUniqueFil": {
+ "seconds": 0.02,
+ "tests": 2
+ },
+ "TestGetViewState": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestHTML2BlockDO": {
+ "seconds": 1.45,
+ "tests": 6
+ },
+ "TestHTTPProxyRes": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestHashBacklink": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestHoldAttribut": {
+ "seconds": 0.1,
+ "tests": 1
+ },
+ "TestImplicitNote": {
+ "seconds": 1.24,
+ "tests": 1
+ },
+ "TestInlineStyles": {
+ "seconds": 0.03,
+ "tests": 2
+ },
+ "TestInsertLocalA": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestIsPathInTemp": {
+ "seconds": 0.02,
+ "tests": 1
+ },
+ "TestIsValidSYImp": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestLimitHTML2Bl": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestListDocsByPa": {
+ "seconds": 0.12,
+ "tests": 1
+ },
+ "TestListNotebook": {
+ "seconds": 0.08,
+ "tests": 1
+ },
+ "TestMCPOAuthCall": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestMatchHTMLCli": {
+ "seconds": 0,
+ "tests": 4
+ },
+ "TestMoveBlockRej": {
+ "seconds": 0.06,
+ "tests": 1
+ },
+ "TestMutateViewSt": {
+ "seconds": 0.06,
+ "tests": 1
+ },
+ "TestNewAgentSess": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestNewBacklinkR": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestNormalizeCli": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestNormalizeCus": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestNormalizeIFr": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestNormalizeMSW": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestNormalizeWPS": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestNotebookPubl": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestOfficeHTMLCl": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestOperationNot": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestParseBacklin": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestParseDocVers": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestParsePandocS": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestParseSearchS": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestPrepareHTMLC": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestPreserveImpo": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestPreserveMCPS": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestPublishAcces": {
+ "seconds": 0.03,
+ "tests": 1
+ },
+ "TestPublishReade": {
+ "seconds": 0.07,
+ "tests": 3
+ },
+ "TestPublishSearc": {
+ "seconds": 0.53,
+ "tests": 1
+ },
+ "TestReadCustomEm": {
+ "seconds": 0.01,
+ "tests": 2
+ },
+ "TestRefreshBackl": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestRejectMobile": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestRemoveWorksp": {
+ "seconds": 0.15,
+ "tests": 2
+ },
+ "TestRenameAssetM": {
+ "seconds": 0.06,
+ "tests": 1
+ },
+ "TestRenderAttrib": {
+ "seconds": 0.21,
+ "tests": 1
+ },
+ "TestRenderTempla": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestReorderDocsR": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestRepoContract": {
+ "seconds": 0.11,
+ "tests": 4
+ },
+ "TestRepoFileWire": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestRepoSnapshot": {
+ "seconds": 0.08,
+ "tests": 1
+ },
+ "TestResolveAIPro": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestResolveAgent": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestResolveHTMLC": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestResolveReque": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSessionDeadl": {
+ "seconds": 0,
+ "tests": 2
+ },
+ "TestSetAIRejects": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSetAccessAut": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestSetAttrViewC": {
+ "seconds": 0.21,
+ "tests": 1
+ },
+ "TestSetBazaarPac": {
+ "seconds": 0,
+ "tests": 3
+ },
+ "TestSetBazaarPet": {
+ "seconds": 0.04,
+ "tests": 1
+ },
+ "TestSetDocSortMo": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSetFileAnnot": {
+ "seconds": 0.01,
+ "tests": 1
+ },
+ "TestSetFiletreeP": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSetNotebookI": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSetOIDCRejec": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSetPetalPubl": {
+ "seconds": 0.05,
+ "tests": 1
+ },
+ "TestSetSortRejec": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSettingContr": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSettingWrite": {
+ "seconds": 0.11,
+ "tests": 1
+ },
+ "TestShouldBroadc": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSimplePandoc": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestSnapshotAPIE": {
+ "seconds": 0.1,
+ "tests": 1
+ },
+ "TestSpinBlockDOM": {
+ "seconds": 0.12,
+ "tests": 2
+ },
+ "TestStageAndClai": {
+ "seconds": 0.02,
+ "tests": 1
+ },
+ "TestStdioMCPServ": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestTemplatePrev": {
+ "seconds": 0.02,
+ "tests": 1
+ },
+ "TestTransactionC": {
+ "seconds": 0.4,
+ "tests": 5
+ },
+ "TestUndoStateRed": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestUndoStateRet": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestUnusedAttrib": {
+ "seconds": 0.52,
+ "tests": 1
+ },
+ "TestUnzipRejects": {
+ "seconds": 0.39,
+ "tests": 2
+ },
+ "TestUnzipWorkspa": {
+ "seconds": 0.52,
+ "tests": 2
+ },
+ "TestViewStateAPI": {
+ "seconds": 0,
+ "tests": 1
+ },
+ "TestWPSPresentat": {
+ "seconds": 0.1,
+ "tests": 9
+ },
+ "TestZipRejectsEn": {
+ "seconds": 0.35,
+ "tests": 2
+ }
+ }
+}
diff --git a/scripts/test-kernel.mjs b/scripts/test-kernel.mjs
index 2e6479bc38..1aab151664 100644
--- a/scripts/test-kernel.mjs
+++ b/scripts/test-kernel.mjs
@@ -1,5 +1,5 @@
import {spawn, spawnSync} from "node:child_process";
-import {createWriteStream, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, symlinkSync, writeFileSync} from "node:fs";
+import {copyFileSync, createWriteStream, existsSync, 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";
@@ -8,13 +8,23 @@ 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 apiPackage = "github.com/siyuan-note/siyuan/kernel/api";
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));
+// 核数较少时保留包间并行,避免 API 分片占用模型包有限的运行名额。
+export const testPackageConfigurations = (shards, modelOnly, cores) => {
+ const configurations = [{name: "model", package: modelPackage, count: shards}];
+ if (!modelOnly && cores >= 4) {
+ configurations.push({name: "api", package: apiPackage, count: Math.min(2, shards)});
+ }
+ return configurations;
+};
+
// 按短前缀聚合,再按历史耗时均衡分配;每次从当前测试二进制读取用例,避免遗漏新增测试。
export const planShards = (names, count, durations) => {
if (!Number.isInteger(count) || count < 1 || count > 16 || new Set(names).size !== names.length) {
@@ -51,19 +61,29 @@ export const planShards = (names, count, durations) => {
};
// 每个进程使用独立的当前目录,测试资源通过目录链接复用,隔离相对路径写入。
-export const prepareModelWorkspace = (repository, workspace) => {
- const cwd = join(workspace, "kernel", "model");
+export const preparePackageWorkspace = (repository, workspace, name) => {
+ if (!["model", "api"].includes(name)) {
+ throw new Error("Unsupported test package workspace: " + name);
+ }
+ const cwd = join(workspace, "kernel", name);
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 resource of ["app", "docs", "scripts"]) {
+ if (existsSync(join(repository, resource))) {
+ link(join(repository, resource), join(workspace, resource));
+ }
+ }
for (const entry of readdirSync(join(repository, "kernel"), {withFileTypes: true})) {
- if (entry.isDirectory() && entry.name !== "model") {
+ if (entry.isDirectory() && entry.name !== name) {
link(join(repository, "kernel", entry.name), join(workspace, "kernel", entry.name));
}
}
- for (const entry of readdirSync(join(repository, "kernel", "model"), {withFileTypes: true})) {
+ for (const entry of readdirSync(join(repository, "kernel", name), {withFileTypes: true})) {
if (entry.isDirectory()) {
- link(join(repository, "kernel", "model", entry.name), join(cwd, entry.name));
+ link(join(repository, "kernel", name, entry.name), join(cwd, entry.name));
+ } else if (entry.isFile() && entry.name.endsWith(".go")) {
+ // API 用例会解析同目录的处理器源文件,副本保留检查且隔离运行时文件。
+ copyFileSync(join(repository, "kernel", name, entry.name), join(cwd, entry.name));
}
}
return cwd;
@@ -174,41 +194,62 @@ const main = async () => {
let otherJob;
let otherFinished = false;
try {
- // 其他包的编译和测试与 model 测试二进制的编译重叠,保留完整套件的包间并行。
- if (!options.modelOnly) {
- const packages = command(["list", ...tags, "./..."]).trim().split(/\r?\n/).filter(name => name !== modelPackage);
+ const configurations = testPackageConfigurations(options.shards, options.modelOnly, availableParallelism());
+ const startOtherPackages = () => {
+ const sharded = new Set(configurations.map(configuration => configuration.package));
+ const packages = command(["list", ...tags, "./..."]).trim().split(/\r?\n/).filter(name => !sharded.has(name));
otherJob = runJSONJob({name: "other-packages", cwd: kernel,
args: ["test", ...tags, "-p", String(packageParallelism), "-json", "-count=1", ...packages]}, output)
.finally(() => { otherFinished = true; });
+ };
+ if (!options.modelOnly && configurations.length === 1) {
+ startOtherPackages();
}
- const binary = join(workspace, process.platform === "win32" ? "model.test.exe" : "model.test");
+ const binaries = join(workspace, "binaries");
+ mkdirSync(binaries);
+ // 同一次 Go 构建共享依赖,每个包只链接一次,原生编译与测试运行分开控制并发。
await new Promise((resolve, reject) => {
- const compiler = spawn("go", ["test", ...tags, "-p", String(packageParallelism), "-c", "-o", binary, "./model"], {
+ const compiler = spawn("go", ["test", ...tags, "-p", String(packageParallelism), "-c", "-o", binaries,
+ ...configurations.map(configuration => "./" + configuration.name)], {
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)));
+ compiler.on("close", code => code === 0 ? resolve() : reject(new Error("Sharded 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 jobs = [];
+ const inventory = {};
+ for (const configuration of configurations) {
+ const base = join(binaries, configuration.name + ".test");
+ const binary = process.platform === "win32" && existsSync(base + ".exe") ? base + ".exe" : base;
+ const listed = spawnSync(binary, ["-test.list=."], {
+ cwd: join(kernel, configuration.name), 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 tests discovered for " + configuration.package);
+ }
+ const durations = JSON.parse(readFileSync(join(root, "scripts", "kernel-" + configuration.name + "-test-durations.json"), "utf8"));
+ const shards = planShards(names, configuration.count, durations);
+ inventory[configuration.name] = {tests: names.length, shards: shards.length};
+ jobs.push(...shards.map((shard, i) => ({name: configuration.name + "-" + (i + 1), seconds: shard.seconds, expectedTests: shard.names,
+ cwd: preparePackageWorkspace(root, join(workspace, configuration.name + "-shard-" + i), configuration.name),
+ args: ["tool", "test2json", "-t", "-p", configuration.package, binary, "-test.v=test2json", "-test.count=1", "-test.timeout=10m", "-test.run=" + shard.regex]})));
}
- const names = listTests(listed.stdout);
- if (!names.length) {
- throw new Error("No model tests discovered");
+ if (!options.modelOnly && !otherJob) {
+ startOtherPackages();
}
- 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));
+ console.log(`Running ${jobs.length} model/API shards; ${concurrency} concurrent jobs; logs: ${output}`);
+ const results = await runJobs(jobs.sort((a, b) => b.seconds - a.seconds || a.name.localeCompare(b.name, "en")),
+ 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};
+ const summary = {seconds: (performance.now() - started) / 1000, modelTests: inventory.model.tests, shards: inventory.model.shards,
+ apiTests: inventory.api?.tests ?? 0, apiShards: inventory.api?.shards ?? 0, 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;
diff --git a/scripts/test-kernel.test.mjs b/scripts/test-kernel.test.mjs
index 39fedfb892..968a3d8d3d 100644
--- a/scripts/test-kernel.test.mjs
+++ b/scripts/test-kernel.test.mjs
@@ -1,9 +1,9 @@
import {test} from "node:test";
import * as assert from "node:assert/strict";
-import {mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync} from "node:fs";
+import {existsSync, 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";
+import {listTests, planShards, preparePackageWorkspace, runJSONJob, runJobs, testPackageConfigurations} 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},
@@ -22,6 +22,13 @@ test("test discovery includes examples and fuzz seeds without enabling benchmark
["TestOne", "ExampleTwo", "FuzzThree"]);
});
+test("API sharding respects low-core and model-only execution without duplicating packages", () => {
+ assert.deepEqual(testPackageConfigurations(4, false, 2).map(item => item.name), ["model"]);
+ assert.deepEqual(testPackageConfigurations(4, true, 16).map(item => item.name), ["model"]);
+ assert.deepEqual(testPackageConfigurations(4, false, 16).map(item => [item.name, item.count]), [["model", 4], ["api", 2]]);
+ assert.deepEqual(testPackageConfigurations(1, false, 4).map(item => item.count), [1, 1]);
+});
+
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"];
@@ -70,7 +77,7 @@ test("each model process has isolated relative writes while retaining repository
writeFileSync(join(repository, relative, "fixture.txt"), relative);
}
const workspaces = [join(directory, "one"), join(directory, "two")];
- const [one, two] = workspaces.map(workspace => prepareModelWorkspace(repository, workspace));
+ const [one, two] = workspaces.map(workspace => preparePackageWorkspace(repository, workspace, "model"));
writeFileSync(join(one, "conf.json"), "one");
writeFileSync(join(two, "conf.json"), "two");
assert.equal(readFileSync(join(one, "conf.json"), "utf8"), "one");
@@ -84,6 +91,33 @@ test("each model process has isolated relative writes while retaining repository
assert.equal(readFileSync(join(two, "../treenode/testdata/fixture.txt"), "utf8"), "kernel/treenode/testdata");
});
+test("API processes retain source checks and isolate configuration from the repository and other shards", t => {
+ const directory = temporary(t);
+ const repository = join(directory, "repository");
+ for (const relative of ["app/guide", "docs", "kernel/api/testdata", "kernel/model/testdata"]) {
+ mkdirSync(join(repository, relative), {recursive: true});
+ writeFileSync(join(repository, relative, "fixture.txt"), relative);
+ }
+ const api = join(repository, "kernel/api");
+ writeFileSync(join(api, "handler.go"), "package api\n");
+ writeFileSync(join(api, "conf.json"), "old configuration");
+ writeFileSync(join(api, "index.queue"), "old queue");
+ const one = preparePackageWorkspace(repository, join(directory, "one"), "api");
+ const two = preparePackageWorkspace(repository, join(directory, "two"), "api");
+ assert.equal(readFileSync(join(one, "handler.go"), "utf8"), "package api\n");
+ assert.equal(existsSync(join(one, "conf.json")), false);
+ assert.equal(existsSync(join(one, "index.queue")), false);
+ writeFileSync(join(one, "handler.go"), "package copied\n");
+ writeFileSync(join(one, "conf.json"), "one");
+ writeFileSync(join(two, "conf.json"), "two");
+ assert.equal(readFileSync(join(api, "handler.go"), "utf8"), "package api\n");
+ assert.equal(readFileSync(join(api, "conf.json"), "utf8"), "old configuration");
+ assert.equal(readFileSync(join(two, "conf.json"), "utf8"), "two");
+ assert.equal(readFileSync(join(one, "../../docs/fixture.txt"), "utf8"), "docs");
+ assert.equal(readFileSync(join(one, "../model/testdata/fixture.txt"), "utf8"), "kernel/model/testdata");
+ assert.throws(() => preparePackageWorkspace(repository, join(directory, "invalid"), "../api"));
+});
+
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", () => {});