@stalfh233/omc-cli 0.6.86 → 0.6.88

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.
@@ -14,6 +14,8 @@ import { closestMatch } from "../closest-match.js";
14
14
  import { getInstanceBaseInfo, getReplayToken, listInstanceActivities, searchWorkItems, wireString } from "../workflow-support.js";
15
15
  import { PLATFORM_ADMIN_START_BYPASS, resolvePermissionActor } from "../identity.js";
16
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";
17
19
  import { SYSTEM_FIELD_CODES, familyName } from "../field-families.js";
18
20
  import { applicationResolutionOf, resolveApplicationScope } from "../support.js";
19
21
  /** r29b F8: keep ids/itemsPreview through governedRead's compact diet. */
@@ -172,6 +174,7 @@ export function extractBizObjectPage(value) {
172
174
  const content = Array.isArray(candidate.content) ? candidate.content.filter((row) => !!row && typeof row === "object") : [];
173
175
  return {
174
176
  total: typeof candidate.totalElements === "number" ? candidate.totalElements : 0,
177
+ totalKnown: typeof candidate.totalElements === "number",
175
178
  totalPages: typeof candidate.totalPages === "number" ? candidate.totalPages : 0,
176
179
  page: typeof candidate.page === "number" ? candidate.page : undefined,
177
180
  size: typeof candidate.size === "number" ? candidate.size : undefined,
@@ -310,6 +313,70 @@ function emptyBusinessProjection(items) {
310
313
  return items.length > 0 && businessColumns > 0;
311
314
  }
312
315
  const VIEW_PROJECTION_HINT = "该面仅回视图投影列;业务字段全 null 不代表未写入,真值用 data.load,或用 listview.configure 配列。";
316
+ /**
317
+ * 从 items 里找「null 业务列」(跨行全 null;任何一行有值就算已投影有数据),
318
+ * 按视图列证据分类。无 null 业务列时返回 undefined(正常读取零噪音,与旧行为一致)。
319
+ */
320
+ export function projectionHintFace(items, evidence) {
321
+ const allNull = [];
322
+ const hasValue = new Set();
323
+ for (const item of items) {
324
+ for (const [key, value] of Object.entries(item.fields)) {
325
+ if (RUNTIME_SYSTEM_FIELD_CODES.has(key) || key.endsWith("_"))
326
+ continue;
327
+ if (value === null || value === undefined) {
328
+ if (!hasValue.has(key) && !allNull.includes(key))
329
+ allNull.push(key);
330
+ }
331
+ else {
332
+ hasValue.add(key);
333
+ }
334
+ }
335
+ }
336
+ const nullColumns = allNull.filter((key) => !hasValue.has(key));
337
+ if (items.length === 0 || nullColumns.length === 0)
338
+ return undefined;
339
+ const base = {
340
+ hint: "null 可能=未投影进视图列,判真值用 data.load --args {schemaCode,bizObjectId}",
341
+ projectionKnown: false,
342
+ ...(evidence !== undefined ? { viewColumnsCount: evidence.viewColumnsCount } : {}),
343
+ };
344
+ const codes = evidence?.viewColumnCodes;
345
+ if (codes === undefined)
346
+ return base;
347
+ const inView = new Set(codes);
348
+ const projectedFields = nullColumns.filter((code) => inView.has(code));
349
+ const unprojected = nullColumns.filter((code) => !inView.has(code));
350
+ return {
351
+ ...base,
352
+ projectionKnown: true,
353
+ ...(projectedFields.length > 0 ? { projectedFields } : {}),
354
+ ...(unprojected.length > 0 ? { unprojected } : {}),
355
+ };
356
+ }
357
+ /**
358
+ * data.list 的视图证据读取(query/get 失败/无视图 → undefined = 无证据)。
359
+ * 拿到 queryColumns 数组才算可判定证据;视图对象在但 queryColumns 非数组 →
360
+ * 只保留列数 0 的兼容口径(projectionKnown 仍 false)。
361
+ */
362
+ async function listViewProjectionEvidence(session, schemaCode, queryCode) {
363
+ try {
364
+ const view = (await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode, code: queryCode, clientType: "PC" } })).data;
365
+ if (view === null || typeof view !== "object")
366
+ return undefined;
367
+ if (Array.isArray(view.queryColumns)) {
368
+ const codes = view.queryColumns
369
+ .map((column) => String(column.propertyCode ?? ""))
370
+ .filter((code) => code.length > 0);
371
+ return { viewColumnsCount: codes.length, viewColumnCodes: codes };
372
+ }
373
+ return { viewColumnsCount: 0 };
374
+ }
375
+ catch {
376
+ // Projection diagnostics must never make data.list fail.
377
+ return undefined;
378
+ }
379
+ }
313
380
  /**
314
381
  * Default-compact a runtime record: drop only KNOWN engine noise — `*_` keys are
315
382
  * flow-engine internals (`activityName_`, `participants_`, …) and the staff/dept
@@ -1065,6 +1132,126 @@ async function diagnoseDbException(session, schemaCode, error) {
1065
1132
  /** `data.aggregate` caps: server-total counts are exact; the local-scan fallback shares data.list's row cap. */
1066
1133
  const AGGREGATE_CAP = 1000;
1067
1134
  const AGGREGATE_PAGE_SIZE = 200;
1135
+ /**
1136
+ * 0.6.87 D2:策略标记不靠调用方猜 `complete`。
1137
+ * - `server-total`:count 走服务端 totalElements(精确);
1138
+ * - `paged-local-scan`:本地扫描真的翻了页(pagesConsumed>1);
1139
+ * - `local-scan`:本地扫描一页取齐(无分页发生)。
1140
+ * `/sum` 命中时另用 `server-aggregate`(D5)。
1141
+ */
1142
+ function localScanMode(pagesConsumed) {
1143
+ return pagesConsumed > 1 ? "paged-local-scan" : "local-scan";
1144
+ }
1145
+ /**
1146
+ * 0.6.87 D5:`/sum` 的 GET_LIST 守卫(平台证据:
1147
+ * `DomainServiceImpl.query` 只在 CODING → SourceCodeLauncher、BIZ_SERVICE →
1148
+ * integration 时偏离 DB;默认 GET_LIST 仍 `queryFromDb`;`BizObjectRuleUtils
1149
+ * .isOperateDbForQuery` 是同一判据;`/sum` 直接 `aggregateBizObjects` →
1150
+ * `executeScalar`,**不经过** `DomainServiceImpl.query`,所以只有「可执行
1151
+ * GET_LIST 规则仍读 DB」时两边才是同一真相)。
1152
+ *
1153
+ * 可证明路径:DRAFT 行的 enabled/status/developmentMode 决定 getExecutable 是否
1154
+ * 返回规则;DEFAULT 时执行的是 latest PUBLISH 行,故还要读 runtime 面的
1155
+ * PUBLISH 行并核对它的 GET_LIST 节点 dataSourceType。任一步读不到/解析不了 →
1156
+ * `isDatabase:false`(不能证明 → 本地扫描),fail closed。
1157
+ */
1158
+ const GET_LIST_RULE_CODE = "getlist";
1159
+ function developmentModeName(value) {
1160
+ if (typeof value === "number")
1161
+ return value === 0 ? "DEFAULT" : value === 1 ? "CODING" : value === 2 ? "DECISION" : String(value);
1162
+ return String(value ?? "").toUpperCase();
1163
+ }
1164
+ function getListRuleRow(rows) {
1165
+ return rows.find((row) => String(row.code ?? "").toLowerCase() === GET_LIST_RULE_CODE);
1166
+ }
1167
+ function ruleNodesOf(row) {
1168
+ if (row === undefined)
1169
+ return undefined;
1170
+ const nodes = decodeJsonColumn(row.node, JSON_COLUMN_NULL_COALESCE);
1171
+ return Array.isArray(nodes) ? nodes : undefined;
1172
+ }
1173
+ async function probeGetListReadsDatabase(session, schemaCode) {
1174
+ let wireCalls = 0;
1175
+ try {
1176
+ // app 面 list 投影 DRAFT 行(getExecutable 的 enabled/status 判据在 DRAFT 上)。
1177
+ const drafts = wireRows((await wireCall(session, { path: ENDPOINTS.businessRuleListBySchemaCode, query: { schemaCode } })).data);
1178
+ wireCalls += 1;
1179
+ const draft = getListRuleRow(drafts);
1180
+ if (draft === undefined)
1181
+ return { isDatabase: true, wireCalls, reason: "no-get-list-rule" };
1182
+ if (draft.enabled === undefined)
1183
+ return { isDatabase: false, wireCalls, reason: "get-list-enabled-unknown" };
1184
+ if (draft.enabled !== true)
1185
+ return { isDatabase: true, wireCalls, reason: "get-list-disabled" };
1186
+ if (String(draft.status ?? "").toUpperCase() === "DISABLED")
1187
+ return { isDatabase: true, wireCalls, reason: "get-list-disabled" };
1188
+ const draftMode = developmentModeName(draft.developmentMode);
1189
+ if (draftMode !== "DEFAULT")
1190
+ return { isDatabase: false, wireCalls, reason: `get-list-development-mode-${draftMode || "unknown"}` };
1191
+ // DEFAULT 时真正执行的是 latest PUBLISH 行,节点以它为准。
1192
+ const published = getListRuleRow(wireRows((await wireCall(session, { path: ENDPOINTS.runtimeBusinessRuleListBySchemaCode, query: { schemaCode } })).data));
1193
+ wireCalls += 1;
1194
+ if (published === undefined)
1195
+ return { isDatabase: false, wireCalls, reason: "no-published-get-list" };
1196
+ const publishedMode = published.developmentMode === undefined ? "DEFAULT" : developmentModeName(published.developmentMode);
1197
+ if (publishedMode !== "DEFAULT")
1198
+ return { isDatabase: false, wireCalls, reason: `published-development-mode-${publishedMode || "unknown"}` };
1199
+ let nodes = ruleNodesOf(published);
1200
+ if (nodes === undefined) {
1201
+ const id = typeof published.id === "string" && published.id !== "" ? published.id : undefined;
1202
+ if (id === undefined)
1203
+ return { isDatabase: false, wireCalls, reason: "get-list-node-unreadable" };
1204
+ wireCalls += 1;
1205
+ const detail = (await wireCall(session, { path: ENDPOINTS.businessRuleGet, query: { id } })).data;
1206
+ nodes = ruleNodesOf(detail && typeof detail === "object" ? detail : undefined);
1207
+ }
1208
+ if (nodes === undefined)
1209
+ return { isDatabase: false, wireCalls, reason: "get-list-node-unreadable" };
1210
+ const getList = nodes.find((node) => !!node && typeof node === "object" && String(node.nodeType ?? "") === "GET_LIST");
1211
+ if (getList === undefined)
1212
+ return { isDatabase: false, wireCalls, reason: "get-list-node-missing" };
1213
+ const dataSource = getList.dataSourceType;
1214
+ const dataSourceName = dataSource === undefined || dataSource === null ? "GET_LIST" : String(dataSource).toUpperCase();
1215
+ return { isDatabase: dataSourceName === "GET_LIST", wireCalls, reason: dataSourceName === "GET_LIST" ? "get-list-db" : `get-list-datasource-${dataSourceName}` };
1216
+ }
1217
+ catch (error) {
1218
+ const detail = error instanceof WireError ? (error.errcode !== undefined ? `errcode ${error.errcode}` : error.kind) : "transport";
1219
+ return { isDatabase: false, wireCalls, reason: `get-list-probe-failed:${detail}` };
1220
+ }
1221
+ }
1222
+ /**
1223
+ * D5:调用平台 `/sum` ALL_DATA 并做**运行时键校验**。后端固定回
1224
+ * `{COUNT,SUM,MAX,MIN,AVG}`(`BizObjectFacadeImpl.executeAggregateQueries`,
1225
+ * decompiled 5667-5674);键缺失/非数 → 视为形状不符,回退本地扫描而不是猜。
1226
+ */
1227
+ async function tryServerSum(session, body, field, metric) {
1228
+ try {
1229
+ const response = await wireCall(session, {
1230
+ path: ENDPOINTS.runtimeQuerySum,
1231
+ method: "POST",
1232
+ body: { ...body, sumItemList: [{ propertyCode: field, sumDataType: "ALL_DATA" }] },
1233
+ });
1234
+ const payload = response.data;
1235
+ const row = payload && typeof payload === "object" && !Array.isArray(payload) ? payload[field] : undefined;
1236
+ if (!row || typeof row !== "object" || Array.isArray(row))
1237
+ return { ok: false, reason: "sum-shape-invalid", detail: "missing-field-map" };
1238
+ const record = row;
1239
+ const count = aggregateNumeric(record.COUNT);
1240
+ if (count === null)
1241
+ return { ok: false, reason: "sum-shape-invalid", detail: "COUNT" };
1242
+ if (count === 0)
1243
+ return { ok: true, value: null, nonNullCount: 0 };
1244
+ const key = metric === "sum" ? "SUM" : metric === "avg" ? "AVG" : metric === "min" ? "MIN" : "MAX";
1245
+ const raw = aggregateNumeric(record[key]);
1246
+ if (raw === null)
1247
+ return { ok: false, reason: "sum-shape-invalid", detail: key };
1248
+ return { ok: true, value: metric === "sum" || metric === "avg" ? aggregateTidy(raw) : raw, nonNullCount: count };
1249
+ }
1250
+ catch (error) {
1251
+ const detail = error instanceof WireError ? (error.errcode !== undefined ? `errcode ${error.errcode}` : error.kind) : "transport";
1252
+ return { ok: false, reason: "sum-failed", detail };
1253
+ }
1254
+ }
1068
1255
  /** 数值聚合的字段拒绝面:publishedFields 只列前 N 个(与 data.list 的过滤目录同口径)。 */
1069
1256
  const AGGREGATE_FIELD_SAMPLE_LIMIT = 20;
1070
1257
  /**
@@ -1457,28 +1644,29 @@ export function registerRuntimeDataLane(tools) {
1457
1644
  const firstBody = { ...body, page: 0, size: pageSize };
1458
1645
  const first = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: firstBody });
1459
1646
  const firstPage = extractBizObjectPage(first.data);
1460
- const total = Number(firstPage.total ?? 0);
1461
- if (total === 0 || firstPage.content.length === 0)
1647
+ // 0.6.87 D1:翻页语义统一进 scanPages(首页 total 唯一基准 / 页码序消费 /
1648
+ // 空页停止 / 超 total 尾页裁剪 / total 缺失不得当全集)。这里只保留
1649
+ // 「真空模型」早退(total 已知为 0),其余路径(含 total 缺失、首页空但
1650
+ // total>0 的漂移)走共享扫描并如实上报 total/totalUnknown。
1651
+ if (firstPage.totalKnown && firstPage.total === 0)
1462
1652
  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) } : {}) };
1463
- const rows = [...firstPage.content];
1464
- const target = Math.min(total, CAP);
1465
- let pageIndex = 1;
1466
- while (rows.length < target) {
1467
- const next = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: { ...body, page: pageIndex, size: pageSize } });
1468
- const nextPage = extractBizObjectPage(next.data);
1469
- if (nextPage.content.length === 0)
1470
- break;
1471
- rows.push(...nextPage.content);
1472
- pageIndex += 1;
1473
- }
1474
- // 翻页按 size=200 走,最后一页可能越过 total(total=999 会拉到 1000 行);
1475
- // 先按 total 夹一次,itemsCount/items.length 才与 total 可比。
1476
- const collected = rows.length > total ? rows.slice(0, total) : rows;
1477
- // GitLab #18 P1-2:`capped = rows.length > CAP` 是死代码——target 已被
1478
- // Math.min(total, CAP) 夹住,rows 永远到不了 CAP+1,于是 total>1000 时
1479
- // 返回「total:1043 / items:1000 / 无任何标记」,43 条静默消失(实测被
1480
- // 读成"数据就这么多")。真正的截断判据是「拿到的比总量少」。
1481
- const truncatedByCap = collected.length < total;
1653
+ const scan = await scanPages({
1654
+ cap: CAP,
1655
+ pageSize,
1656
+ fetchPage: async (pageIndex) => {
1657
+ if (pageIndex === 0)
1658
+ return { totalKnown: firstPage.totalKnown, total: firstPage.total, content: firstPage.content };
1659
+ const next = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: { ...body, page: pageIndex, size: pageSize } });
1660
+ const nextPage = extractBizObjectPage(next.data);
1661
+ return { totalKnown: nextPage.totalKnown, total: nextPage.total, content: nextPage.content };
1662
+ },
1663
+ });
1664
+ const total = scan.total;
1665
+ const collected = scan.rows;
1666
+ const pageIndex = scan.pagesConsumed;
1667
+ // GitLab #18 P1-2:`capped = rows.length > CAP` 是死代码——真正的截断判据
1668
+ // 是「拿到的比总量少」(total 缺失时 = 停在 cap,见 scanPages.truncatedByCap)。
1669
+ const truncatedByCap = scan.truncatedByCap;
1482
1670
  const items = collected.map((row0) => {
1483
1671
  const row = row0;
1484
1672
  const rawData = row.data && typeof row.data === "object" ? row.data : {};
@@ -1488,16 +1676,10 @@ export function registerRuntimeDataLane(tools) {
1488
1676
  });
1489
1677
  const preview = dataListItemPreview(items);
1490
1678
  const nullProjection = items.some((item) => Object.values(item.fields).some((value) => value === null));
1491
- let viewColumnsCount;
1492
- if (nullProjection) {
1493
- try {
1494
- const view = (await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode: args.schemaCode, code: args.queryCode ?? args.schemaCode, clientType: "PC" } })).data;
1495
- viewColumnsCount = Array.isArray(view?.queryColumns) ? view.queryColumns.length : 0;
1496
- }
1497
- catch {
1498
- // Projection diagnostics must never make data.list fail.
1499
- }
1500
- }
1679
+ // F2(retro 24):出现 null 业务列才读视图证据(正常读取零额外 wire);
1680
+ // 证据链见 projectionHintFace 的源码注释。
1681
+ const viewEvidence = nullProjection ? await listViewProjectionEvidence(session, args.schemaCode, args.queryCode ?? args.schemaCode) : undefined;
1682
+ const projectionHintAll = projectionHintFace(items, viewEvidence);
1501
1683
  return {
1502
1684
  schemaCode: args.schemaCode,
1503
1685
  ...application,
@@ -1531,11 +1713,20 @@ export function registerRuntimeDataLane(tools) {
1531
1713
  truncated: true,
1532
1714
  capped: true,
1533
1715
  cap: CAP,
1534
- missingCount: total - collected.length,
1535
- capNotice: `已取前 ${collected.length} 条 / 共 ${total} 条(安全上限 ${CAP})——还差 ${total - collected.length} 条没返回。不要把它当全集:加 filters 分片(如按日期/业务键)分别拉取,或去掉 all 用 page/size 手动翻页。`,
1716
+ ...(total !== null
1717
+ ? {
1718
+ missingCount: total - collected.length,
1719
+ capNotice: `已取前 ${collected.length} 条 / 共 ${total} 条(安全上限 ${CAP})——还差 ${total - collected.length} 条没返回。不要把它当全集:加 filters 分片(如按日期/业务键)分别拉取,或去掉 all 用 page/size 手动翻页。`,
1720
+ }
1721
+ : {
1722
+ // D1:total 缺失(showTotal:false / 面未回 totalElements)——
1723
+ // 缺口不可算,但截断事实(停在 cap)必须说清,不得当全集。
1724
+ totalUnknown: true,
1725
+ capNotice: `首页未回 totalElements(showTotal:false 或该面不回 total):已按安全上限 ${CAP} 扫描并取回 ${collected.length} 条,total 未知、缺多少条不可算——不要当全集。要精确计数用 size:1 + filter 读 total,或去掉 all 用 page/size 手动翻页。`,
1726
+ }),
1536
1727
  }
1537
1728
  : {}),
1538
- ...(nullProjection ? { projectionHint: { hint: "null 可能=未投影进视图列,判真值用 data.load --args {schemaCode,bizObjectId}", ...(viewColumnsCount !== undefined ? { viewColumnsCount } : {}) } } : {}),
1729
+ ...(projectionHintAll !== undefined ? { projectionHint: projectionHintAll } : {}),
1539
1730
  items,
1540
1731
  };
1541
1732
  }
@@ -1665,17 +1856,11 @@ export function registerRuntimeDataLane(tools) {
1665
1856
  const data = row.data && typeof row.data === "object" ? row.data : row;
1666
1857
  return String(data.sequenceStatus ?? row.sequenceStatus ?? "") === "DRAFT";
1667
1858
  }).length;
1668
- let viewColumnsCount;
1859
+ // F2(retro 24):出现 null 业务列才读视图证据;证据链与语义见
1860
+ // projectionHintFace / listViewProjectionEvidence 的源码注释。
1669
1861
  const hasNullValue = items.some((item) => Object.values(item.fields).some((value) => value === null));
1670
- if (hasNullValue) {
1671
- try {
1672
- const view = (await wireCall(session, { path: ENDPOINTS.listQueryGet, query: { schemaCode: args.schemaCode, code: args.queryCode ?? args.schemaCode, clientType: "PC" } })).data;
1673
- viewColumnsCount = Array.isArray(view?.queryColumns) ? view.queryColumns.length : 0;
1674
- }
1675
- catch {
1676
- // Keep the data read authoritative if the optional diagnostic read fails.
1677
- }
1678
- }
1862
+ const viewEvidence = hasNullValue ? await listViewProjectionEvidence(session, args.schemaCode, args.queryCode ?? args.schemaCode) : undefined;
1863
+ const projectionHintPaged = projectionHintFace(items, viewEvidence);
1679
1864
  const readback = {
1680
1865
  schemaCode: args.schemaCode,
1681
1866
  ...application,
@@ -1708,7 +1893,7 @@ export function registerRuntimeDataLane(tools) {
1708
1893
  return { filter: policy };
1709
1894
  })(),
1710
1895
  ...(choiceFilterFields.length > 0 && Number(total ?? 0) === 0 ? { filterValueHint: choiceFilterValueHint(choiceFilterFields) } : {}),
1711
- ...(hasNullValue ? { projectionHint: { hint: "null 可能=未投影进视图列,判真值用 data.load --args {schemaCode,bizObjectId}", ...(viewColumnsCount !== undefined ? { viewColumnsCount } : {}) } } : {}),
1896
+ ...(projectionHintPaged !== undefined ? { projectionHint: projectionHintPaged } : {}),
1712
1897
  totalPages,
1713
1898
  itemsCount: items.length,
1714
1899
  itemsReturned: items.length,
@@ -1938,63 +2123,110 @@ export function registerRuntimeDataLane(tools) {
1938
2123
  const overall = emptyAcc();
1939
2124
  const nullBucket = emptyAcc();
1940
2125
  const buckets = new Map();
1941
- let rowsScanned = 0;
1942
- let total = 0;
1943
- let pages = 0;
1944
- for (let pageIndex = 0; rowsScanned < AGGREGATE_CAP; pageIndex += 1) {
1945
- const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, pageIndex) });
1946
- pages += 1;
1947
- const pageData = extractBizObjectPage(response.data);
1948
- if (pages === 1)
1949
- total = pageData.total;
1950
- if (pageData.content.length === 0)
1951
- break;
1952
- for (const row of pageData.content) {
1953
- // 平台 query/list 无服务端列投影面:投影在本地做(只读这两列,其余不落内存)。
1954
- const data = row.data && typeof row.data === "object" ? row.data : row;
1955
- const value = aggregateNumeric(data[target]);
1956
- let bucket;
1957
- if (groupBy !== undefined) {
1958
- const raw = data[groupBy];
1959
- if (raw === null || raw === undefined)
1960
- bucket = nullBucket;
1961
- else {
1962
- const key = String(raw);
1963
- bucket = buckets.get(key);
1964
- if (bucket === undefined) {
1965
- bucket = emptyAcc();
1966
- buckets.set(key, bucket);
1967
- }
1968
- }
2126
+ const numericMetric = metric;
2127
+ // D5:首页探针同时给出 total(是否值得走 /sum)和本地扫描的首页行
2128
+ // (回退零额外读)。只有「无 groupBy + total 已知且 > 一页」才考虑 /sum。
2129
+ const probe = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, 0) });
2130
+ const probePage = extractBizObjectPage(probe.data);
2131
+ let strategyFallback;
2132
+ let guardCalls = 0;
2133
+ let sumAttempts = 0;
2134
+ if (groupBy === undefined && probePage.totalKnown && probePage.total > AGGREGATE_PAGE_SIZE) {
2135
+ const path = await probeGetListReadsDatabase(session, args.schemaCode);
2136
+ guardCalls = path.wireCalls;
2137
+ if (path.isDatabase) {
2138
+ sumAttempts = 1;
2139
+ const sum = await tryServerSum(session, queryBody(1, 0), target, numericMetric);
2140
+ if (sum.ok) {
2141
+ const total = probePage.total;
2142
+ const nonNullCount = sum.nonNullCount;
2143
+ return {
2144
+ schemaCode: args.schemaCode,
2145
+ metric,
2146
+ field: target,
2147
+ value: sum.value,
2148
+ count: total,
2149
+ nonNullCount,
2150
+ nullCount: Math.max(0, total - nonNullCount),
2151
+ ...(sum.value === null ? { note: "no numeric values in matched rows" } : {}),
2152
+ coverage: { mode: "server-aggregate", rowsScanned: 0, cap: null, complete: true },
2153
+ filter: draftFilter,
2154
+ wire: {
2155
+ calls: metaCalls + 1 + path.wireCalls + 1,
2156
+ plan: `1 metadata + 1 probe + ${path.wireCalls} guard + 1 /sum ALL_DATA`,
2157
+ strategy: "server-sum",
2158
+ },
2159
+ };
1969
2160
  }
1970
- for (const acc of bucket === undefined ? [overall] : [overall, bucket]) {
1971
- acc.count += 1;
1972
- if (value === null)
1973
- continue;
1974
- acc.nonNullCount += 1;
1975
- acc.sum += value;
1976
- if (value < acc.min)
1977
- acc.min = value;
1978
- if (value > acc.max)
1979
- acc.max = value;
2161
+ strategyFallback = { strategy: "server-sum", reason: sum.reason, detail: sum.detail, guardCalls: path.wireCalls };
2162
+ }
2163
+ else {
2164
+ strategyFallback = { strategy: "server-sum", reason: path.reason, guardCalls: path.wireCalls };
2165
+ }
2166
+ }
2167
+ // 0.6.87 D1:翻页语义统一走 scanPages(首页 total 唯一基准 / 页码序消费 /
2168
+ // 空页停止 / 超 total 尾页裁剪 / total 缺失不当全集)。本路径只负责折叠。
2169
+ const scan = await scanPages({
2170
+ cap: AGGREGATE_CAP,
2171
+ pageSize: AGGREGATE_PAGE_SIZE,
2172
+ fetchPage: async (pageIndex) => {
2173
+ if (pageIndex === 0)
2174
+ return { totalKnown: probePage.totalKnown, total: probePage.total, content: probePage.content };
2175
+ const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, pageIndex) });
2176
+ const pageData = extractBizObjectPage(response.data);
2177
+ return { totalKnown: pageData.totalKnown, total: pageData.total, content: pageData.content };
2178
+ },
2179
+ });
2180
+ for (const row of scan.rows) {
2181
+ // 平台 query/list 无服务端列投影面:投影在本地做(只读这两列,其余不落内存)。
2182
+ const data = row.data && typeof row.data === "object" ? row.data : row;
2183
+ const value = aggregateNumeric(data[target]);
2184
+ let bucket;
2185
+ if (groupBy !== undefined) {
2186
+ const raw = data[groupBy];
2187
+ if (raw === null || raw === undefined)
2188
+ bucket = nullBucket;
2189
+ else {
2190
+ const key = String(raw);
2191
+ bucket = buckets.get(key);
2192
+ if (bucket === undefined) {
2193
+ bucket = emptyAcc();
2194
+ buckets.set(key, bucket);
2195
+ }
1980
2196
  }
1981
2197
  }
1982
- rowsScanned += pageData.content.length;
1983
- if (rowsScanned >= total)
1984
- break;
2198
+ for (const acc of bucket === undefined ? [overall] : [overall, bucket]) {
2199
+ acc.count += 1;
2200
+ if (value === null)
2201
+ continue;
2202
+ acc.nonNullCount += 1;
2203
+ acc.sum += value;
2204
+ if (value < acc.min)
2205
+ acc.min = value;
2206
+ if (value > acc.max)
2207
+ acc.max = value;
2208
+ }
1985
2209
  }
1986
- const complete = rowsScanned >= total;
1987
- const numericMetric = metric;
2210
+ const rowsScanned = scan.rows.length;
2211
+ const total = scan.total;
2212
+ const complete = scan.complete;
1988
2213
  const scanValue = (acc) => aggregateValue(numericMetric, acc.sum, acc.nonNullCount, acc.min, acc.max);
1989
2214
  const coverage = {
1990
- mode: "local-scan",
2215
+ mode: localScanMode(scan.pagesConsumed),
1991
2216
  rowsScanned,
1992
2217
  cap: AGGREGATE_CAP,
1993
2218
  complete,
1994
- ...(complete ? {} : { missingCount: Math.max(0, total - rowsScanned) }),
2219
+ ...(complete || total === null ? {} : { missingCount: Math.max(0, total - rowsScanned) }),
2220
+ };
2221
+ const capNotice = total !== null
2222
+ ? `数值列本地折叠:已扫前 ${rowsScanned}/${total} 行,${metric} 只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`
2223
+ : `数值列本地折叠:首页未回 totalElements(showTotal:false 或该面不回 total),已按安全上限 ${AGGREGATE_CAP} 扫到 ${rowsScanned} 行;total 未知、缺口不可算,不要当全集。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`;
2224
+ const strategyNote = guardCalls + sumAttempts > 0 ? `${guardCalls} guard + ${sumAttempts} /sum + ` : "";
2225
+ const wire = {
2226
+ calls: metaCalls + scan.wireCalls + guardCalls + sumAttempts,
2227
+ plan: `1 metadata + ${strategyNote}${scan.wireCalls} pages`,
2228
+ ...(scan.concurrency !== undefined ? { concurrency: scan.concurrency } : {}),
1995
2229
  };
1996
- const capNotice = `数值列本地折叠:已扫前 ${rowsScanned}/${total} 行,${metric} 只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`;
1997
- const wire = { calls: metaCalls + pages, plan: `1 metadata + ${pages} pages` };
1998
2230
  if (groupBy === undefined) {
1999
2231
  const value = scanValue(overall);
2000
2232
  return {
@@ -2009,6 +2241,7 @@ export function registerRuntimeDataLane(tools) {
2009
2241
  coverage,
2010
2242
  filter: draftFilter,
2011
2243
  ...(complete ? {} : { capNotice }),
2244
+ ...(strategyFallback !== undefined ? { strategyFallback } : {}),
2012
2245
  wire,
2013
2246
  };
2014
2247
  }
@@ -2035,6 +2268,7 @@ export function registerRuntimeDataLane(tools) {
2035
2268
  coverage,
2036
2269
  filter: draftFilter,
2037
2270
  ...(complete ? {} : { capNotice }),
2271
+ ...(strategyFallback !== undefined ? { strategyFallback } : {}),
2038
2272
  wire,
2039
2273
  };
2040
2274
  }
@@ -2053,7 +2287,13 @@ export function registerRuntimeDataLane(tools) {
2053
2287
  // 2/3) groupBy:值域可枚举 → 值域×count;否则 1 列投影本地扫描。
2054
2288
  const meta = await fieldMeta();
2055
2289
  const groupField = meta?.get(args.groupBy);
2056
- const codes = groupField?.choiceCodes ?? [];
2290
+ const rawCodes = groupField?.choiceCodes ?? [];
2291
+ // 0.6.87 D4:重复 choiceCodes 会让同一值域被 count 两次,U+null 之和超过
2292
+ // base total(负 unaccounted)。按输入序去重并显式告警,不静默重复计。
2293
+ const codes = [...new Set(rawCodes)];
2294
+ const shapeWarnings = [];
2295
+ if (codes.length !== rawCodes.length)
2296
+ shapeWarnings.push(`choiceCodes-duplicate: groupBy ${args.groupBy} 的选项/字典码有 ${rawCodes.length - codes.length} 个重复(${rawCodes.length}→${codes.length}),已去重;否则同一值域会被重复计数`);
2057
2297
  if (groupField && Number.isInteger(groupField.type) && codes.length > 0) {
2058
2298
  // R88 S1:值域×count 扇出(base + 每值域 Eq + IsNull)彼此独立,走有界
2059
2299
  // 并发(窗口 4)。fieldMeta() 已在前一行完成,绝不进并发窗口(metaCalls
@@ -2094,6 +2334,10 @@ export function registerRuntimeDataLane(tools) {
2094
2334
  const nullCount = values[units.length - 1];
2095
2335
  const sums = buckets.reduce((sum, bucket) => sum + bucket.count, 0);
2096
2336
  const unaccounted = baseTotal - sums - nullCount;
2337
+ // D4:负 unaccounted 不得静默丢(旧代码只在 >0 时给键,负值连信号都没有)。
2338
+ // 归零 + 显式 warning:桶计数是平台 COUNT 结果,不在这里改写数字本身。
2339
+ if (unaccounted < 0)
2340
+ shapeWarnings.push(`unaccounted-negative: 桶和 ${sums} + null ${nullCount} > base total ${baseTotal}(差 ${unaccounted}),已归零;通常是重复 choiceCodes 或平台 COUNT 漂移——不要把分桶当精确闭环`);
2097
2341
  buckets.sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
2098
2342
  const shown = buckets.slice(0, topN);
2099
2343
  return {
@@ -2105,7 +2349,8 @@ export function registerRuntimeDataLane(tools) {
2105
2349
  nullBucket: { count: nullCount },
2106
2350
  truncatedBuckets: buckets.length > shown.length,
2107
2351
  bucketsTruncatedCount: buckets.length - shown.length,
2108
- ...(unaccounted > 0 ? { unaccountedCount: unaccounted } : {}),
2352
+ ...(unaccounted > 0 ? { unaccountedCount: unaccounted } : unaccounted < 0 ? { unaccountedCount: 0 } : {}),
2353
+ ...(shapeWarnings.length > 0 ? { shapeWarnings } : {}),
2109
2354
  coverage: { mode: "server-total", rowsScanned: 0, cap: AGGREGATE_CAP, complete: true },
2110
2355
  filter: draftFilter,
2111
2356
  wire: {
@@ -2118,34 +2363,31 @@ export function registerRuntimeDataLane(tools) {
2118
2363
  // 自由文本/高基数:翻页取前 cap 行,只投影 groupBy 列本地计数;绝不按扫描比例外推。
2119
2364
  const counts = new Map();
2120
2365
  let nullCount = 0;
2121
- let rowsScanned = 0;
2122
- let total = 0;
2123
- let pages = 0;
2124
- for (let page = 0; rowsScanned < AGGREGATE_CAP; page += 1) {
2125
- const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, page) });
2126
- pages += 1;
2127
- const pageData = extractBizObjectPage(response.data);
2128
- if (pages === 1)
2129
- total = pageData.total;
2130
- if (pageData.content.length === 0)
2131
- break;
2132
- for (const row of pageData.content) {
2133
- const data = row.data && typeof row.data === "object" ? row.data : row;
2134
- const raw = data[args.groupBy];
2135
- if (raw === null || raw === undefined)
2136
- nullCount += 1;
2137
- else {
2138
- const key = String(raw);
2139
- counts.set(key, (counts.get(key) ?? 0) + 1);
2140
- }
2366
+ // 0.6.87 D1:与数值路径共用 scanPages 的翻页/裁剪/空页/total 语义。
2367
+ const scan = await scanPages({
2368
+ cap: AGGREGATE_CAP,
2369
+ pageSize: AGGREGATE_PAGE_SIZE,
2370
+ fetchPage: async (pageIndex) => {
2371
+ const response = await wireCall(session, { path: ENDPOINTS.runtimeQueryList, method: "POST", body: queryBody(AGGREGATE_PAGE_SIZE, pageIndex) });
2372
+ const pageData = extractBizObjectPage(response.data);
2373
+ return { totalKnown: pageData.totalKnown, total: pageData.total, content: pageData.content };
2374
+ },
2375
+ });
2376
+ for (const row of scan.rows) {
2377
+ const data = row.data && typeof row.data === "object" ? row.data : row;
2378
+ const raw = data[args.groupBy];
2379
+ if (raw === null || raw === undefined)
2380
+ nullCount += 1;
2381
+ else {
2382
+ const key = String(raw);
2383
+ counts.set(key, (counts.get(key) ?? 0) + 1);
2141
2384
  }
2142
- rowsScanned += pageData.content.length;
2143
- if (rowsScanned >= total)
2144
- break;
2145
2385
  }
2386
+ const rowsScanned = scan.rows.length;
2387
+ const total = scan.total;
2388
+ const complete = scan.complete;
2146
2389
  const allBuckets = [...counts].map(([key, count]) => ({ key, count })).sort((left, right) => right.count - left.count || left.key.localeCompare(right.key));
2147
2390
  const shown = allBuckets.slice(0, topN);
2148
- const complete = rowsScanned >= total;
2149
2391
  return {
2150
2392
  schemaCode: args.schemaCode,
2151
2393
  metric: "count",
@@ -2155,12 +2397,24 @@ export function registerRuntimeDataLane(tools) {
2155
2397
  nullBucket: { count: nullCount },
2156
2398
  truncatedBuckets: allBuckets.length > shown.length,
2157
2399
  bucketsTruncatedCount: allBuckets.length - shown.length,
2158
- coverage: { mode: "local-scan", rowsScanned, cap: AGGREGATE_CAP, complete, missingCount: Math.max(0, total - rowsScanned) },
2400
+ coverage: {
2401
+ mode: localScanMode(scan.pagesConsumed),
2402
+ rowsScanned,
2403
+ cap: AGGREGATE_CAP,
2404
+ complete,
2405
+ ...(total === null ? {} : { missingCount: Math.max(0, total - rowsScanned) }),
2406
+ },
2159
2407
  filter: draftFilter,
2160
2408
  ...(complete ? {} : {
2161
- capNotice: `值域非可枚举:已扫前 ${rowsScanned}/${total} 行,桶只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`,
2409
+ capNotice: total !== null
2410
+ ? `值域非可枚举:已扫前 ${rowsScanned}/${total} 行,桶只覆盖已扫部分(complete:false,非全集)。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`
2411
+ : `值域非可枚举:首页未回 totalElements(showTotal:false 或该面不回 total),已按安全上限 ${AGGREGATE_CAP} 扫到 ${rowsScanned} 行;total 未知、缺口不可算,不要当全集。要全集:filters 按日期/业务键 gte/lt 分片重跑,或 page/size 手动翻页。`,
2162
2412
  }),
2163
- wire: { calls: metaCalls + pages, plan: `${metaCalls > 0 ? "1 metadata + " : ""}${pages} pages` },
2413
+ wire: {
2414
+ calls: metaCalls + scan.wireCalls,
2415
+ plan: `${metaCalls > 0 ? "1 metadata + " : ""}${scan.wireCalls} pages`,
2416
+ ...(scan.concurrency !== undefined ? { concurrency: scan.concurrency } : {}),
2417
+ },
2164
2418
  };
2165
2419
  }, { 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 })}` });
2166
2420
  },