@stalfh233/omc-cli 0.6.85 → 0.6.87

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { z } from "zod";
3
3
  import { FilterDslError, injectPropertyTypes, SIMPLE_OP_MAP, toQueryCondition } from "../data-list-filter.js";
4
+ import { DEFAULT_SCAN_CONCURRENCY, isThrottleClassError, mapWithConcurrency } from "../concurrency.js";
4
5
  import { ENDPOINTS } from "../endpoints.js";
5
6
  import { capabilityArg, environmentArg } from "../args.js";
6
7
  import { governedRead } from "../read.js";
@@ -13,6 +14,8 @@ import { closestMatch } from "../closest-match.js";
13
14
  import { getInstanceBaseInfo, getReplayToken, listInstanceActivities, searchWorkItems, wireString } from "../workflow-support.js";
14
15
  import { PLATFORM_ADMIN_START_BYPASS, resolvePermissionActor } from "../identity.js";
15
16
  import { ENGINE_OWNED_KEYS, RUNTIME_DATA_LANE_CONTRACT, RUNTIME_DATA_WIRE, runtimeFormDataArg, } from "./runtime-data-contract.js";
17
+ import { scanPages } from "./runtime-paging.js";
18
+ import { decodeJsonColumn, JSON_COLUMN_NULL_COALESCE } from "../json-column.js";
16
19
  import { SYSTEM_FIELD_CODES, familyName } from "../field-families.js";
17
20
  import { applicationResolutionOf, resolveApplicationScope } from "../support.js";
18
21
  /** r29b F8: keep ids/itemsPreview through governedRead's compact diet. */
@@ -171,6 +174,7 @@ export function extractBizObjectPage(value) {
171
174
  const content = Array.isArray(candidate.content) ? candidate.content.filter((row) => !!row && typeof row === "object") : [];
172
175
  return {
173
176
  total: typeof candidate.totalElements === "number" ? candidate.totalElements : 0,
177
+ totalKnown: typeof candidate.totalElements === "number",
174
178
  totalPages: typeof candidate.totalPages === "number" ? candidate.totalPages : 0,
175
179
  page: typeof candidate.page === "number" ? candidate.page : undefined,
176
180
  size: typeof candidate.size === "number" ? candidate.size : undefined,
@@ -1064,6 +1068,126 @@ async function diagnoseDbException(session, schemaCode, error) {
1064
1068
  /** `data.aggregate` caps: server-total counts are exact; the local-scan fallback shares data.list's row cap. */
1065
1069
  const AGGREGATE_CAP = 1000;
1066
1070
  const AGGREGATE_PAGE_SIZE = 200;
1071
+ /**
1072
+ * 0.6.87 D2:策略标记不靠调用方猜 `complete`。
1073
+ * - `server-total`:count 走服务端 totalElements(精确);
1074
+ * - `paged-local-scan`:本地扫描真的翻了页(pagesConsumed>1);
1075
+ * - `local-scan`:本地扫描一页取齐(无分页发生)。
1076
+ * `/sum` 命中时另用 `server-aggregate`(D5)。
1077
+ */
1078
+ function localScanMode(pagesConsumed) {
1079
+ return pagesConsumed > 1 ? "paged-local-scan" : "local-scan";
1080
+ }
1081
+ /**
1082
+ * 0.6.87 D5:`/sum` 的 GET_LIST 守卫(平台证据:
1083
+ * `DomainServiceImpl.query` 只在 CODING → SourceCodeLauncher、BIZ_SERVICE →
1084
+ * integration 时偏离 DB;默认 GET_LIST 仍 `queryFromDb`;`BizObjectRuleUtils
1085
+ * .isOperateDbForQuery` 是同一判据;`/sum` 直接 `aggregateBizObjects` →
1086
+ * `executeScalar`,**不经过** `DomainServiceImpl.query`,所以只有「可执行
1087
+ * GET_LIST 规则仍读 DB」时两边才是同一真相)。
1088
+ *
1089
+ * 可证明路径:DRAFT 行的 enabled/status/developmentMode 决定 getExecutable 是否
1090
+ * 返回规则;DEFAULT 时执行的是 latest PUBLISH 行,故还要读 runtime 面的
1091
+ * PUBLISH 行并核对它的 GET_LIST 节点 dataSourceType。任一步读不到/解析不了 →
1092
+ * `isDatabase:false`(不能证明 → 本地扫描),fail closed。
1093
+ */
1094
+ const GET_LIST_RULE_CODE = "getlist";
1095
+ function developmentModeName(value) {
1096
+ if (typeof value === "number")
1097
+ return value === 0 ? "DEFAULT" : value === 1 ? "CODING" : value === 2 ? "DECISION" : String(value);
1098
+ return String(value ?? "").toUpperCase();
1099
+ }
1100
+ function getListRuleRow(rows) {
1101
+ return rows.find((row) => String(row.code ?? "").toLowerCase() === GET_LIST_RULE_CODE);
1102
+ }
1103
+ function ruleNodesOf(row) {
1104
+ if (row === undefined)
1105
+ return undefined;
1106
+ const nodes = decodeJsonColumn(row.node, JSON_COLUMN_NULL_COALESCE);
1107
+ return Array.isArray(nodes) ? nodes : undefined;
1108
+ }
1109
+ async function probeGetListReadsDatabase(session, schemaCode) {
1110
+ let wireCalls = 0;
1111
+ try {
1112
+ // app 面 list 投影 DRAFT 行(getExecutable 的 enabled/status 判据在 DRAFT 上)。
1113
+ const drafts = wireRows((await wireCall(session, { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode } })).data);
1114
+ wireCalls += 1;
1115
+ const draft = getListRuleRow(drafts);
1116
+ if (draft === undefined)
1117
+ return { isDatabase: true, wireCalls, reason: "no-get-list-rule" };
1118
+ if (draft.enabled === undefined)
1119
+ return { isDatabase: false, wireCalls, reason: "get-list-enabled-unknown" };
1120
+ if (draft.enabled !== true)
1121
+ return { isDatabase: true, wireCalls, reason: "get-list-disabled" };
1122
+ if (String(draft.status ?? "").toUpperCase() === "DISABLED")
1123
+ return { isDatabase: true, wireCalls, reason: "get-list-disabled" };
1124
+ const draftMode = developmentModeName(draft.developmentMode);
1125
+ if (draftMode !== "DEFAULT")
1126
+ return { isDatabase: false, wireCalls, reason: `get-list-development-mode-${draftMode || "unknown"}` };
1127
+ // DEFAULT 时真正执行的是 latest PUBLISH 行,节点以它为准。
1128
+ const published = getListRuleRow(wireRows((await wireCall(session, { path: ENDPOINTS.runtimeBusinessRuleListBySchemaCode, query: { schemaCode } })).data));
1129
+ wireCalls += 1;
1130
+ if (published === undefined)
1131
+ return { isDatabase: false, wireCalls, reason: "no-published-get-list" };
1132
+ const publishedMode = published.developmentMode === undefined ? "DEFAULT" : developmentModeName(published.developmentMode);
1133
+ if (publishedMode !== "DEFAULT")
1134
+ return { isDatabase: false, wireCalls, reason: `published-development-mode-${publishedMode || "unknown"}` };
1135
+ let nodes = ruleNodesOf(published);
1136
+ if (nodes === undefined) {
1137
+ const id = typeof published.id === "string" && published.id !== "" ? published.id : undefined;
1138
+ if (id === undefined)
1139
+ return { isDatabase: false, wireCalls, reason: "get-list-node-unreadable" };
1140
+ wireCalls += 1;
1141
+ const detail = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id } })).data;
1142
+ nodes = ruleNodesOf(detail && typeof detail === "object" ? detail : undefined);
1143
+ }
1144
+ if (nodes === undefined)
1145
+ return { isDatabase: false, wireCalls, reason: "get-list-node-unreadable" };
1146
+ const getList = nodes.find((node) => !!node && typeof node === "object" && String(node.nodeType ?? "") === "GET_LIST");
1147
+ if (getList === undefined)
1148
+ return { isDatabase: false, wireCalls, reason: "get-list-node-missing" };
1149
+ const dataSource = getList.dataSourceType;
1150
+ const dataSourceName = dataSource === undefined || dataSource === null ? "GET_LIST" : String(dataSource).toUpperCase();
1151
+ return { isDatabase: dataSourceName === "GET_LIST", wireCalls, reason: dataSourceName === "GET_LIST" ? "get-list-db" : `get-list-datasource-${dataSourceName}` };
1152
+ }
1153
+ catch (error) {
1154
+ const detail = error instanceof WireError ? (error.errcode !== undefined ? `errcode ${error.errcode}` : error.kind) : "transport";
1155
+ return { isDatabase: false, wireCalls, reason: `get-list-probe-failed:${detail}` };
1156
+ }
1157
+ }
1158
+ /**
1159
+ * D5:调用平台 `/sum` ALL_DATA 并做**运行时键校验**。后端固定回
1160
+ * `{COUNT,SUM,MAX,MIN,AVG}`(`BizObjectFacadeImpl.executeAggregateQueries`,
1161
+ * decompiled 5667-5674);键缺失/非数 → 视为形状不符,回退本地扫描而不是猜。
1162
+ */
1163
+ async function tryServerSum(session, body, field, metric) {
1164
+ try {
1165
+ const response = await wireCall(session, {
1166
+ path: ENDPOINTS.runtimeQuerySum,
1167
+ method: "POST",
1168
+ body: { ...body, sumItemList: [{ propertyCode: field, sumDataType: "ALL_DATA" }] },
1169
+ });
1170
+ const payload = response.data;
1171
+ const row = payload && typeof payload === "object" && !Array.isArray(payload) ? payload[field] : undefined;
1172
+ if (!row || typeof row !== "object" || Array.isArray(row))
1173
+ return { ok: false, reason: "sum-shape-invalid", detail: "missing-field-map" };
1174
+ const record = row;
1175
+ const count = aggregateNumeric(record.COUNT);
1176
+ if (count === null)
1177
+ return { ok: false, reason: "sum-shape-invalid", detail: "COUNT" };
1178
+ if (count === 0)
1179
+ return { ok: true, value: null, nonNullCount: 0 };
1180
+ const key = metric === "sum" ? "SUM" : metric === "avg" ? "AVG" : metric === "min" ? "MIN" : "MAX";
1181
+ const raw = aggregateNumeric(record[key]);
1182
+ if (raw === null)
1183
+ return { ok: false, reason: "sum-shape-invalid", detail: key };
1184
+ return { ok: true, value: metric === "sum" || metric === "avg" ? aggregateTidy(raw) : raw, nonNullCount: count };
1185
+ }
1186
+ catch (error) {
1187
+ const detail = error instanceof WireError ? (error.errcode !== undefined ? `errcode ${error.errcode}` : error.kind) : "transport";
1188
+ return { ok: false, reason: "sum-failed", detail };
1189
+ }
1190
+ }
1067
1191
  /** 数值聚合的字段拒绝面:publishedFields 只列前 N 个(与 data.list 的过滤目录同口径)。 */
1068
1192
  const AGGREGATE_FIELD_SAMPLE_LIMIT = 20;
1069
1193
  /**
@@ -1456,28 +1580,29 @@ export function registerRuntimeDataLane(tools) {
1456
1580
  const firstBody = { ...body, page: 0, size: pageSize };
1457
1581
  const first = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: firstBody });
1458
1582
  const firstPage = extractBizObjectPage(first.data);
1459
- const total = Number(firstPage.total ?? 0);
1460
- if (total === 0 || firstPage.content.length === 0)
1583
+ // 0.6.87 D1:翻页语义统一进 scanPages(首页 total 唯一基准 / 页码序消费 /
1584
+ // 空页停止 / 超 total 尾页裁剪 / total 缺失不得当全集)。这里只保留
1585
+ // 「真空模型」早退(total 已知为 0),其余路径(含 total 缺失、首页空但
1586
+ // total>0 的漂移)走共享扫描并如实上报 total/totalUnknown。
1587
+ if (firstPage.totalKnown && firstPage.total === 0)
1461
1588
  return { schemaCode: args.schemaCode, ...application, total: 0, page: "all", size: 0, pagesFetched: 0, items: [], itemsCount: 0, itemsReturned: 0, resultTruncated: false, itemsExternalized: false, ...(choiceFilterFields.length > 0 ? { filterValueHint: choiceFilterValueHint(choiceFilterFields) } : {}) };
1462
- const rows = [...firstPage.content];
1463
- const target = Math.min(total, CAP);
1464
- let pageIndex = 1;
1465
- while (rows.length < target) {
1466
- const next = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: { ...body, page: pageIndex, size: pageSize } });
1467
- const nextPage = extractBizObjectPage(next.data);
1468
- if (nextPage.content.length === 0)
1469
- break;
1470
- rows.push(...nextPage.content);
1471
- pageIndex += 1;
1472
- }
1473
- // 翻页按 size=200 走,最后一页可能越过 total(total=999 会拉到 1000 行);
1474
- // 先按 total 夹一次,itemsCount/items.length 才与 total 可比。
1475
- const collected = rows.length > total ? rows.slice(0, total) : rows;
1476
- // GitLab #18 P1-2:`capped = rows.length > CAP` 是死代码——target 已被
1477
- // Math.min(total, CAP) 夹住,rows 永远到不了 CAP+1,于是 total>1000 时
1478
- // 返回「total:1043 / items:1000 / 无任何标记」,43 条静默消失(实测被
1479
- // 读成"数据就这么多")。真正的截断判据是「拿到的比总量少」。
1480
- const truncatedByCap = collected.length < total;
1589
+ const scan = await scanPages({
1590
+ cap: CAP,
1591
+ pageSize,
1592
+ fetchPage: async (pageIndex) => {
1593
+ if (pageIndex === 0)
1594
+ return { totalKnown: firstPage.totalKnown, total: firstPage.total, content: firstPage.content };
1595
+ const next = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: { ...body, page: pageIndex, size: pageSize } });
1596
+ const nextPage = extractBizObjectPage(next.data);
1597
+ return { totalKnown: nextPage.totalKnown, total: nextPage.total, content: nextPage.content };
1598
+ },
1599
+ });
1600
+ const total = scan.total;
1601
+ const collected = scan.rows;
1602
+ const pageIndex = scan.pagesConsumed;
1603
+ // GitLab #18 P1-2:`capped = rows.length > CAP` 是死代码——真正的截断判据
1604
+ // 是「拿到的比总量少」(total 缺失时 = 停在 cap,见 scanPages.truncatedByCap)。
1605
+ const truncatedByCap = scan.truncatedByCap;
1481
1606
  const items = collected.map((row0) => {
1482
1607
  const row = row0;
1483
1608
  const rawData = row.data && typeof row.data === "object" ? row.data : {};
@@ -1530,8 +1655,17 @@ export function registerRuntimeDataLane(tools) {
1530
1655
  truncated: true,
1531
1656
  capped: true,
1532
1657
  cap: CAP,
1533
- missingCount: total - collected.length,
1534
- capNotice: `已取前 ${collected.length} 条 / 共 ${total} 条(安全上限 ${CAP})——还差 ${total - collected.length} 条没返回。不要把它当全集:加 filters 分片(如按日期/业务键)分别拉取,或去掉 all 用 page/size 手动翻页。`,
1658
+ ...(total !== null
1659
+ ? {
1660
+ missingCount: total - collected.length,
1661
+ capNotice: `已取前 ${collected.length} 条 / 共 ${total} 条(安全上限 ${CAP})——还差 ${total - collected.length} 条没返回。不要把它当全集:加 filters 分片(如按日期/业务键)分别拉取,或去掉 all 用 page/size 手动翻页。`,
1662
+ }
1663
+ : {
1664
+ // D1:total 缺失(showTotal:false / 面未回 totalElements)——
1665
+ // 缺口不可算,但截断事实(停在 cap)必须说清,不得当全集。
1666
+ totalUnknown: true,
1667
+ capNotice: `首页未回 totalElements(showTotal:false 或该面不回 total):已按安全上限 ${CAP} 扫描并取回 ${collected.length} 条,total 未知、缺多少条不可算——不要当全集。要精确计数用 size:1 + filter 读 total,或去掉 all 用 page/size 手动翻页。`,
1668
+ }),
1535
1669
  }
1536
1670
  : {}),
1537
1671
  ...(nullProjection ? { projectionHint: { hint: "null 可能=未投影进视图列,判真值用 data.load --args {schemaCode,bizObjectId}", ...(viewColumnsCount !== undefined ? { viewColumnsCount } : {}) } } : {}),
@@ -1927,7 +2061,7 @@ export function registerRuntimeDataLane(tools) {
1927
2061
  return extractBizObjectPage(response.data).total;
1928
2062
  };
1929
2063
  const topN = args.topN ?? 10;
1930
- // 数值指标(sum/avg/min/max):平台无服务端聚合面 → 列投影 + size:200 翻页
2064
+ // 数值指标(sum/avg/min/max):平台无 group-by 面(数值有 /sum,受 GET_LIST 规则限制)→ 列投影 + size:200 翻页
1931
2065
  // 本地折叠至 cap 1000。null 行不进聚合;扫不完就给 complete:false + capNotice,
1932
2066
  // 绝不按扫描比例外推(与 count 的自由文本路径同一诚实口径)。
1933
2067
  if (numeric) {
@@ -1937,63 +2071,110 @@ export function registerRuntimeDataLane(tools) {
1937
2071
  const overall = emptyAcc();
1938
2072
  const nullBucket = emptyAcc();
1939
2073
  const buckets = new Map();
1940
- let rowsScanned = 0;
1941
- let total = 0;
1942
- let pages = 0;
1943
- for (let pageIndex = 0; rowsScanned < AGGREGATE_CAP; pageIndex += 1) {
1944
- const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, pageIndex) });
1945
- pages += 1;
1946
- const pageData = extractBizObjectPage(response.data);
1947
- if (pages === 1)
1948
- total = pageData.total;
1949
- if (pageData.content.length === 0)
1950
- break;
1951
- for (const row of pageData.content) {
1952
- // 平台 query/list 无服务端列投影面:投影在本地做(只读这两列,其余不落内存)。
1953
- const data = row.data && typeof row.data === "object" ? row.data : row;
1954
- const value = aggregateNumeric(data[target]);
1955
- let bucket;
1956
- if (groupBy !== undefined) {
1957
- const raw = data[groupBy];
1958
- if (raw === null || raw === undefined)
1959
- bucket = nullBucket;
1960
- else {
1961
- const key = String(raw);
1962
- bucket = buckets.get(key);
1963
- if (bucket === undefined) {
1964
- bucket = emptyAcc();
1965
- buckets.set(key, bucket);
1966
- }
1967
- }
2074
+ const numericMetric = metric;
2075
+ // D5:首页探针同时给出 total(是否值得走 /sum)和本地扫描的首页行
2076
+ // (回退零额外读)。只有「无 groupBy + total 已知且 > 一页」才考虑 /sum。
2077
+ const probe = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, 0) });
2078
+ const probePage = extractBizObjectPage(probe.data);
2079
+ let strategyFallback;
2080
+ let guardCalls = 0;
2081
+ let sumAttempts = 0;
2082
+ if (groupBy === undefined && probePage.totalKnown && probePage.total > AGGREGATE_PAGE_SIZE) {
2083
+ const path = await probeGetListReadsDatabase(session, args.schemaCode);
2084
+ guardCalls = path.wireCalls;
2085
+ if (path.isDatabase) {
2086
+ sumAttempts = 1;
2087
+ const sum = await tryServerSum(session, queryBody(1, 0), target, numericMetric);
2088
+ if (sum.ok) {
2089
+ const total = probePage.total;
2090
+ const nonNullCount = sum.nonNullCount;
2091
+ return {
2092
+ schemaCode: args.schemaCode,
2093
+ metric,
2094
+ field: target,
2095
+ value: sum.value,
2096
+ count: total,
2097
+ nonNullCount,
2098
+ nullCount: Math.max(0, total - nonNullCount),
2099
+ ...(sum.value === null ? { note: "no numeric values in matched rows" } : {}),
2100
+ coverage: { mode: "server-aggregate", rowsScanned: 0, cap: null, complete: true },
2101
+ filter: draftFilter,
2102
+ wire: {
2103
+ calls: metaCalls + 1 + path.wireCalls + 1,
2104
+ plan: `1 metadata + 1 probe + ${path.wireCalls} guard + 1 /sum ALL_DATA`,
2105
+ strategy: "server-sum",
2106
+ },
2107
+ };
1968
2108
  }
1969
- for (const acc of bucket === undefined ? [overall] : [overall, bucket]) {
1970
- acc.count += 1;
1971
- if (value === null)
1972
- continue;
1973
- acc.nonNullCount += 1;
1974
- acc.sum += value;
1975
- if (value < acc.min)
1976
- acc.min = value;
1977
- if (value > acc.max)
1978
- acc.max = value;
2109
+ strategyFallback = { strategy: "server-sum", reason: sum.reason, detail: sum.detail, guardCalls: path.wireCalls };
2110
+ }
2111
+ else {
2112
+ strategyFallback = { strategy: "server-sum", reason: path.reason, guardCalls: path.wireCalls };
2113
+ }
2114
+ }
2115
+ // 0.6.87 D1:翻页语义统一走 scanPages(首页 total 唯一基准 / 页码序消费 /
2116
+ // 空页停止 / 超 total 尾页裁剪 / total 缺失不当全集)。本路径只负责折叠。
2117
+ const scan = await scanPages({
2118
+ cap: AGGREGATE_CAP,
2119
+ pageSize: AGGREGATE_PAGE_SIZE,
2120
+ fetchPage: async (pageIndex) => {
2121
+ if (pageIndex === 0)
2122
+ return { totalKnown: probePage.totalKnown, total: probePage.total, content: probePage.content };
2123
+ const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, pageIndex) });
2124
+ const pageData = extractBizObjectPage(response.data);
2125
+ return { totalKnown: pageData.totalKnown, total: pageData.total, content: pageData.content };
2126
+ },
2127
+ });
2128
+ for (const row of scan.rows) {
2129
+ // 平台 query/list 无服务端列投影面:投影在本地做(只读这两列,其余不落内存)。
2130
+ const data = row.data && typeof row.data === "object" ? row.data : row;
2131
+ const value = aggregateNumeric(data[target]);
2132
+ let bucket;
2133
+ if (groupBy !== undefined) {
2134
+ const raw = data[groupBy];
2135
+ if (raw === null || raw === undefined)
2136
+ bucket = nullBucket;
2137
+ else {
2138
+ const key = String(raw);
2139
+ bucket = buckets.get(key);
2140
+ if (bucket === undefined) {
2141
+ bucket = emptyAcc();
2142
+ buckets.set(key, bucket);
2143
+ }
1979
2144
  }
1980
2145
  }
1981
- rowsScanned += pageData.content.length;
1982
- if (rowsScanned >= total)
1983
- break;
2146
+ for (const acc of bucket === undefined ? [overall] : [overall, bucket]) {
2147
+ acc.count += 1;
2148
+ if (value === null)
2149
+ continue;
2150
+ acc.nonNullCount += 1;
2151
+ acc.sum += value;
2152
+ if (value < acc.min)
2153
+ acc.min = value;
2154
+ if (value > acc.max)
2155
+ acc.max = value;
2156
+ }
1984
2157
  }
1985
- const complete = rowsScanned >= total;
1986
- const numericMetric = metric;
2158
+ const rowsScanned = scan.rows.length;
2159
+ const total = scan.total;
2160
+ const complete = scan.complete;
1987
2161
  const scanValue = (acc) => aggregateValue(numericMetric, acc.sum, acc.nonNullCount, acc.min, acc.max);
1988
2162
  const coverage = {
1989
- mode: "local-scan",
2163
+ mode: localScanMode(scan.pagesConsumed),
1990
2164
  rowsScanned,
1991
2165
  cap: AGGREGATE_CAP,
1992
2166
  complete,
1993
- ...(complete ? {} : { missingCount: Math.max(0, total - rowsScanned) }),
2167
+ ...(complete || total === null ? {} : { missingCount: Math.max(0, total - rowsScanned) }),
2168
+ };
2169
+ const capNotice = total !== null
2170
+ ? `数值列本地折叠:已扫前 ${rowsScanned}/${total} 行,${metric} 只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`
2171
+ : `数值列本地折叠:首页未回 totalElements(showTotal:false 或该面不回 total),已按安全上限 ${AGGREGATE_CAP} 扫到 ${rowsScanned} 行;total 未知、缺口不可算,不要当全集。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`;
2172
+ const strategyNote = guardCalls + sumAttempts > 0 ? `${guardCalls} guard + ${sumAttempts} /sum + ` : "";
2173
+ const wire = {
2174
+ calls: metaCalls + scan.wireCalls + guardCalls + sumAttempts,
2175
+ plan: `1 metadata + ${strategyNote}${scan.wireCalls} pages`,
2176
+ ...(scan.concurrency !== undefined ? { concurrency: scan.concurrency } : {}),
1994
2177
  };
1995
- const capNotice = `数值列本地折叠:已扫前 ${rowsScanned}/${total} 行,${metric} 只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`;
1996
- const wire = { calls: metaCalls + pages, plan: `1 metadata + ${pages} pages` };
1997
2178
  if (groupBy === undefined) {
1998
2179
  const value = scanValue(overall);
1999
2180
  return {
@@ -2008,6 +2189,7 @@ export function registerRuntimeDataLane(tools) {
2008
2189
  coverage,
2009
2190
  filter: draftFilter,
2010
2191
  ...(complete ? {} : { capNotice }),
2192
+ ...(strategyFallback !== undefined ? { strategyFallback } : {}),
2011
2193
  wire,
2012
2194
  };
2013
2195
  }
@@ -2034,6 +2216,7 @@ export function registerRuntimeDataLane(tools) {
2034
2216
  coverage,
2035
2217
  filter: draftFilter,
2036
2218
  ...(complete ? {} : { capNotice }),
2219
+ ...(strategyFallback !== undefined ? { strategyFallback } : {}),
2037
2220
  wire,
2038
2221
  };
2039
2222
  }
@@ -2052,17 +2235,57 @@ export function registerRuntimeDataLane(tools) {
2052
2235
  // 2/3) groupBy:值域可枚举 → 值域×count;否则 1 列投影本地扫描。
2053
2236
  const meta = await fieldMeta();
2054
2237
  const groupField = meta?.get(args.groupBy);
2055
- const codes = groupField?.choiceCodes ?? [];
2238
+ const rawCodes = groupField?.choiceCodes ?? [];
2239
+ // 0.6.87 D4:重复 choiceCodes 会让同一值域被 count 两次,U+null 之和超过
2240
+ // base total(负 unaccounted)。按输入序去重并显式告警,不静默重复计。
2241
+ const codes = [...new Set(rawCodes)];
2242
+ const shapeWarnings = [];
2243
+ if (codes.length !== rawCodes.length)
2244
+ shapeWarnings.push(`choiceCodes-duplicate: groupBy ${args.groupBy} 的选项/字典码有 ${rawCodes.length - codes.length} 个重复(${rawCodes.length}→${codes.length}),已去重;否则同一值域会被重复计数`);
2056
2245
  if (groupField && Number.isInteger(groupField.type) && codes.length > 0) {
2057
- const baseTotal = await countAt();
2058
- const buckets = [];
2059
- for (const code of codes) {
2060
- const count = await countAt(aggregateLeafGroup(args.groupBy, groupField.type, "Eq", code));
2061
- buckets.push({ key: code, count });
2246
+ // R88 S1:值域×count 扇出(base + 每值域 Eq + IsNull)彼此独立,走有界
2247
+ // 并发(窗口 4)。fieldMeta() 已在前一行完成,绝不进并发窗口(metaCalls
2248
+ // 双计 + session 缓存);unit 结果按输入序重组,再走既有排序/topN——与
2249
+ // 串行逐字段一致,并发完成顺序不抖动输出。
2250
+ const groupBy = args.groupBy;
2251
+ const groupType = groupField.type;
2252
+ const units = [
2253
+ { kind: "base" },
2254
+ ...codes.map((code) => ({ kind: "bucket", code, leaf: aggregateLeafGroup(groupBy, groupType, "Eq", code) })),
2255
+ { kind: "null", leaf: aggregateLeafGroup(groupBy, groupType, "IsNull", "") },
2256
+ ];
2257
+ const leafOf = (unit) => (unit.kind === "base" ? undefined : unit.leaf);
2258
+ const scan = await mapWithConcurrency(units, DEFAULT_SCAN_CONCURRENCY, (unit) => countAt(leafOf(unit)));
2259
+ const values = new Array(units.length);
2260
+ scan.outcomes.forEach((outcome, index) => {
2261
+ if (outcome.ok)
2262
+ values[index] = outcome.value;
2263
+ });
2264
+ if (scan.failed.length > 0) {
2265
+ // 失败语义保持串行的 fail-fast:绝不返回「少一个桶」的部分结果。
2266
+ // 非限流类(业务拒绝)直接抛最低索引(不重试、不降级,也不被限流
2267
+ // 重试掩盖);全灭抛最低索引(确定性,等同串行);只有限流类且非
2268
+ // 全灭时,失败项串行重放一次(并发窗口的突发限流串行往往能过),
2269
+ // 仍失败抛最低索引。
2270
+ const businessFailure = scan.failed.find((failure) => !isThrottleClassError(failure.error));
2271
+ if (businessFailure !== undefined)
2272
+ throw businessFailure.error;
2273
+ if (scan.failed.length === units.length)
2274
+ throw scan.failed[0].error;
2275
+ // 串行重放是 unit 级重执行;wire.calls 仍按逻辑请求数,concurrency 直接
2276
+ // 复用窗口内 stats(与 workflow.list / rule.references 同口径)。
2277
+ for (const failure of scan.failed)
2278
+ values[failure.index] = await countAt(leafOf(units[failure.index]));
2062
2279
  }
2063
- const nullCount = await countAt(aggregateLeafGroup(args.groupBy, groupField.type, "IsNull", ""));
2280
+ const baseTotal = values[0];
2281
+ const buckets = codes.map((code, index) => ({ key: code, count: values[index + 1] }));
2282
+ const nullCount = values[units.length - 1];
2064
2283
  const sums = buckets.reduce((sum, bucket) => sum + bucket.count, 0);
2065
2284
  const unaccounted = baseTotal - sums - nullCount;
2285
+ // D4:负 unaccounted 不得静默丢(旧代码只在 >0 时给键,负值连信号都没有)。
2286
+ // 归零 + 显式 warning:桶计数是平台 COUNT 结果,不在这里改写数字本身。
2287
+ if (unaccounted < 0)
2288
+ shapeWarnings.push(`unaccounted-negative: 桶和 ${sums} + null ${nullCount} > base total ${baseTotal}(差 ${unaccounted}),已归零;通常是重复 choiceCodes 或平台 COUNT 漂移——不要把分桶当精确闭环`);
2066
2289
  buckets.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
2067
2290
  const shown = buckets.slice(0, topN);
2068
2291
  return {
@@ -2074,43 +2297,45 @@ export function registerRuntimeDataLane(tools) {
2074
2297
  nullBucket: { count: nullCount },
2075
2298
  truncatedBuckets: buckets.length > shown.length,
2076
2299
  bucketsTruncatedCount: buckets.length - shown.length,
2077
- ...(unaccounted > 0 ? { unaccountedCount: unaccounted } : {}),
2300
+ ...(unaccounted > 0 ? { unaccountedCount: unaccounted } : unaccounted < 0 ? { unaccountedCount: 0 } : {}),
2301
+ ...(shapeWarnings.length > 0 ? { shapeWarnings } : {}),
2078
2302
  coverage: { mode: "server-total", rowsScanned: 0, cap: AGGREGATE_CAP, complete: true },
2079
2303
  filter: draftFilter,
2080
- wire: { calls: metaCalls + 1 + codes.length + 1, plan: `1 metadata + 1 base + ${codes.length} buckets + 1 null` },
2304
+ wire: {
2305
+ calls: metaCalls + 1 + codes.length + 1,
2306
+ plan: `1 metadata + 1 base + ${codes.length} buckets + 1 null`,
2307
+ ...(units.length > 1 ? { concurrency: scan.stats } : {}),
2308
+ },
2081
2309
  };
2082
2310
  }
2083
2311
  // 自由文本/高基数:翻页取前 cap 行,只投影 groupBy 列本地计数;绝不按扫描比例外推。
2084
2312
  const counts = new Map();
2085
2313
  let nullCount = 0;
2086
- let rowsScanned = 0;
2087
- let total = 0;
2088
- let pages = 0;
2089
- for (let page = 0; rowsScanned < AGGREGATE_CAP; page += 1) {
2090
- const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, page) });
2091
- pages += 1;
2092
- const pageData = extractBizObjectPage(response.data);
2093
- if (pages === 1)
2094
- total = pageData.total;
2095
- if (pageData.content.length === 0)
2096
- break;
2097
- for (const row of pageData.content) {
2098
- const data = row.data && typeof row.data === "object" ? row.data : row;
2099
- const raw = data[args.groupBy];
2100
- if (raw === null || raw === undefined)
2101
- nullCount += 1;
2102
- else {
2103
- const key = String(raw);
2104
- counts.set(key, (counts.get(key) ?? 0) + 1);
2105
- }
2314
+ // 0.6.87 D1:与数值路径共用 scanPages 的翻页/裁剪/空页/total 语义。
2315
+ const scan = await scanPages({
2316
+ cap: AGGREGATE_CAP,
2317
+ pageSize: AGGREGATE_PAGE_SIZE,
2318
+ fetchPage: async (pageIndex) => {
2319
+ const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, pageIndex) });
2320
+ const pageData = extractBizObjectPage(response.data);
2321
+ return { totalKnown: pageData.totalKnown, total: pageData.total, content: pageData.content };
2322
+ },
2323
+ });
2324
+ for (const row of scan.rows) {
2325
+ const data = row.data && typeof row.data === "object" ? row.data : row;
2326
+ const raw = data[args.groupBy];
2327
+ if (raw === null || raw === undefined)
2328
+ nullCount += 1;
2329
+ else {
2330
+ const key = String(raw);
2331
+ counts.set(key, (counts.get(key) ?? 0) + 1);
2106
2332
  }
2107
- rowsScanned += pageData.content.length;
2108
- if (rowsScanned >= total)
2109
- break;
2110
2333
  }
2334
+ const rowsScanned = scan.rows.length;
2335
+ const total = scan.total;
2336
+ const complete = scan.complete;
2111
2337
  const allBuckets = [...counts].map(([key, count]) => ({ key, count })).sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
2112
2338
  const shown = allBuckets.slice(0, topN);
2113
- const complete = rowsScanned >= total;
2114
2339
  return {
2115
2340
  schemaCode: args.schemaCode,
2116
2341
  metric: "count",
@@ -2120,12 +2345,24 @@ export function registerRuntimeDataLane(tools) {
2120
2345
  nullBucket: { count: nullCount },
2121
2346
  truncatedBuckets: allBuckets.length > shown.length,
2122
2347
  bucketsTruncatedCount: allBuckets.length - shown.length,
2123
- coverage: { mode: "local-scan", rowsScanned, cap: AGGREGATE_CAP, complete, missingCount: Math.max(0, total - rowsScanned) },
2348
+ coverage: {
2349
+ mode: localScanMode(scan.pagesConsumed),
2350
+ rowsScanned,
2351
+ cap: AGGREGATE_CAP,
2352
+ complete,
2353
+ ...(total === null ? {} : { missingCount: Math.max(0, total - rowsScanned) }),
2354
+ },
2124
2355
  filter: draftFilter,
2125
2356
  ...(complete ? {} : {
2126
- capNotice: `值域非可枚举:已扫前 ${rowsScanned}/${total} 行,桶只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`,
2357
+ capNotice: total !== null
2358
+ ? `值域非可枚举:已扫前 ${rowsScanned}/${total} 行,桶只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`
2359
+ : `值域非可枚举:首页未回 totalElements(showTotal:false 或该面不回 total),已按安全上限 ${AGGREGATE_CAP} 扫到 ${rowsScanned} 行;total 未知、缺口不可算,不要当全集。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`,
2127
2360
  }),
2128
- wire: { calls: metaCalls + pages, plan: `${metaCalls > 0 ? "1 metadata + " : ""}${pages} pages` },
2361
+ wire: {
2362
+ calls: metaCalls + scan.wireCalls,
2363
+ plan: `${metaCalls > 0 ? "1 metadata + " : ""}${scan.wireCalls} pages`,
2364
+ ...(scan.concurrency !== undefined ? { concurrency: scan.concurrency } : {}),
2365
+ },
2129
2366
  };
2130
2367
  }, { target: `data.aggregate:${JSON.stringify({ schemaCode: args.schemaCode, metric: args.metric, field: args.field, filter: args.filter, filters: args.filters, filterGroup: args.filterGroup, groupBy: args.groupBy, topN: args.topN ?? 10, includeDrafts: args.includeDrafts ?? null })}` });
2131
2368
  },