@cartanova/qgrid-cli 2.15.1 → 2.15.2

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.
Files changed (21) hide show
  1. package/bundle/dist/application/qgrid/qgrid.frame.js +3 -2
  2. package/bundle/dist/application/request-log/request-log-cost.js +59 -0
  3. package/bundle/dist/application/request-log/request-log.model.js +55 -85
  4. package/bundle/src/application/request-log/request-log-cost.test.ts +40 -0
  5. package/bundle/src/application/request-log/request-log-cost.ts +103 -0
  6. package/bundle/src/application/request-log/request-log.model.test.ts +121 -123
  7. package/bundle/src/application/request-log/request-log.model.ts +70 -167
  8. package/bundle/web-dist/client/assets/{index-JkBenvsH.js → index-VhUpqKIg.js} +3 -3
  9. package/bundle/web-dist/client/assets/logs-BwSzVf_A.js +1 -0
  10. package/bundle/web-dist/client/assets/{monit-CQ6cVvzc.js → monit-B2CVdIml.js} +1 -1
  11. package/bundle/web-dist/client/assets/{routes-BkeaYiBN.js → routes-BOOXpy3Q.js} +1 -1
  12. package/bundle/web-dist/client/assets/{settings-DJdBEFoL.js → settings-B_a3Nr0H.js} +1 -1
  13. package/bundle/web-dist/client/assets/{show-CcKkiy8Y.js → show-D5Uxcb4a.js} +1 -1
  14. package/bundle/web-dist/client/assets/{tokens-DuLrdLMa.js → tokens-zlrqnP63.js} +1 -1
  15. package/bundle/web-dist/client/assets/{use-oauth-login-flow-CFJY-N99.js → use-oauth-login-flow-qR-56G2w.js} +1 -1
  16. package/bundle/web-dist/client/assets/{use-update-token-mutation-CrEi7wJa.js → use-update-token-mutation-B-vcLRx-.js} +1 -1
  17. package/bundle/web-dist/client/index.html +1 -1
  18. package/bundle/web-dist/server/assets/{logs-C0md5rmp.js → logs-6289J29J.js} +17 -4
  19. package/bundle/web-dist/server/entry-server.generated.js +2 -2
  20. package/package.json +1 -1
  21. package/bundle/web-dist/client/assets/logs-UozX8VD5.js +0 -1
@@ -25,6 +25,12 @@ import { type RequestLogStepSaveParams } from "../request-log-step/request-log-s
25
25
  import { type RequestLogSubsetKey, type RequestLogSubsetMapping } from "../sonamu.generated";
26
26
  import { requestLogLoaderQueries, requestLogSubsetQueries } from "../sonamu.generated.sso";
27
27
  import { renderJsonSchemaZodText, renderParsedJsonSchemaTypeText } from "./json-schema-type-text";
28
+ import {
29
+ MICRO_USD,
30
+ normalizedUsageForCost,
31
+ resolvePricingCost,
32
+ type RequestLogUsageRow,
33
+ } from "./request-log-cost";
28
34
  import {
29
35
  type HistoryItems,
30
36
  type RequestLogListParams,
@@ -35,8 +41,8 @@ import {
35
41
  } from "./request-log.types";
36
42
  import { formatZodCode } from "./zod-code-format";
37
43
 
38
- // cost_usd는 정수 micro-USD로 저장. 실제 USD = cost_usd / MICRO_USD.
39
- export const MICRO_USD = 1_000_000;
44
+ export { MICRO_USD };
45
+
40
46
  const REQUEST_LOG_RUN_LOCK_CLASS_ID = 718;
41
47
  const TOOL_ENUM_VALUE_LIMIT = 6;
42
48
 
@@ -178,27 +184,6 @@ function aggregateGenerateStepRows(rows: StepAggregateRow[]): RequestLogStepAggr
178
184
  return aggregate;
179
185
  }
180
186
 
181
- type RequestLogUsageRow = {
182
- token_name?: string | null;
183
- model_name?: string | null;
184
- input_tokens: number;
185
- output_tokens: number;
186
- cache_read_tokens: number;
187
- cache_creation_tokens: number;
188
- cache_creation_5m_tokens?: number | null;
189
- cache_creation_1h_tokens?: number | null;
190
- cost_usd?: number | null;
191
- cost_source?: string | null;
192
- };
193
-
194
- function isAnthropicUsageRow(row: Pick<RequestLogUsageRow, "token_name" | "model_name">): boolean {
195
- return (
196
- row.token_name?.startsWith("anthropic/") === true ||
197
- row.model_name?.startsWith("claude-") === true ||
198
- row.model_name?.startsWith("anthropic/claude-") === true
199
- );
200
- }
201
-
202
187
  /** Provider of a provider-qualified model id (`openai/`, `anthropic/`, `grok/`); legacy ids are unknown. */
203
188
  export function providerOfModelName(modelName: string | null | undefined): ProviderId | "unknown" {
204
189
  const slash = modelName?.indexOf("/") ?? -1;
@@ -207,47 +192,6 @@ export function providerOfModelName(modelName: string | null | undefined): Provi
207
192
  return isProviderId(prefix) ? prefix : "unknown";
208
193
  }
209
194
 
210
- function canonicalModelName(modelName: string): string {
211
- return modelName.includes("/") ? modelName.split("/").pop()! : modelName;
212
- }
213
-
214
- interface UsageForCost {
215
- model: string | null;
216
- inputTokens: number;
217
- outputTokens: number;
218
- cachedInputTokens: number;
219
- cacheCreationInputTokens: number;
220
- cacheCreationInputTokens5m?: number;
221
- cacheCreationInputTokens1h?: number;
222
- }
223
-
224
- function normalizedUsageForCost(row: RequestLogUsageRow): UsageForCost {
225
- const cacheRead = row.cache_read_tokens;
226
- const cacheCreation = row.cache_creation_tokens;
227
- const storedInput = row.input_tokens;
228
-
229
- const legacyAnthropicSplitInput =
230
- isAnthropicUsageRow(row) && storedInput < cacheRead + cacheCreation;
231
-
232
- const usage: UsageForCost = {
233
- model: row.model_name ? canonicalModelName(row.model_name) : null,
234
- inputTokens: legacyAnthropicSplitInput ? storedInput + cacheRead + cacheCreation : storedInput,
235
- outputTokens: row.output_tokens,
236
- cachedInputTokens: cacheRead,
237
- cacheCreationInputTokens: cacheCreation,
238
- };
239
-
240
- if (row.cache_creation_5m_tokens !== null && row.cache_creation_5m_tokens !== undefined) {
241
- usage.cacheCreationInputTokens5m = row.cache_creation_5m_tokens;
242
- }
243
-
244
- if (row.cache_creation_1h_tokens !== null && row.cache_creation_1h_tokens !== undefined) {
245
- usage.cacheCreationInputTokens1h = row.cache_creation_1h_tokens;
246
- }
247
-
248
- return usage;
249
- }
250
-
251
195
  function normalizeLegacyAnthropicRow<T extends RequestLogUsageRow>(row: T): T {
252
196
  // 새 row 는 당시의 provider/가격표 비용을 확정 저장한다. 현재 가격표로 덮어쓰지 않는다.
253
197
  if (row.cost_source) return row;
@@ -429,8 +373,8 @@ class RequestLogModelClass extends BaseModelClass<
429
373
  async save(spa: RequestLogSaveParams[]): Promise<number[]> {
430
374
  const wdb = this.getPuri("w");
431
375
 
432
- // register
433
- for (const sp of spa) wdb.ubRegister("request_logs", sp);
376
+ // register — 출처 없는 비용은 finishRun 과 같은 규칙으로 쓰기 시점에 확정한다.
377
+ for (const sp of spa) wdb.ubRegister("request_logs", { ...sp, ...resolvePricingCost(sp) });
434
378
 
435
379
  // transaction
436
380
  return wdb.transaction(async (trx) => {
@@ -701,10 +645,10 @@ class RequestLogModelClass extends BaseModelClass<
701
645
  if (params.history !== undefined) update.history = params.history;
702
646
  update.ttft_ms = (await this.firstGenerateStepTtft(requestLogId)) ?? 0;
703
647
 
704
- // 서버 run 경로는 step 에서 확정한 exact cost 를 넘긴다. 외부/legacy caller 가 비용을
705
- // 생략한 경우에만 저장된 모델+usage 로 계산한다.
648
+ // 서버 run 경로는 step 에서 확정한 exact cost 와 출처를 넘긴다. 출처 없이 끝난 외부/legacy
649
+ // run 은 저장된 모델+usage 로 여기서 확정해, 읽기 경로가 다시 계산하지 않게 한다.
706
650
  if (
707
- params.cost_usd === undefined &&
651
+ (params.cost_source === undefined || params.cost_source === null) &&
708
652
  params.input_tokens !== undefined &&
709
653
  params.output_tokens !== undefined
710
654
  ) {
@@ -714,34 +658,19 @@ class RequestLogModelClass extends BaseModelClass<
714
658
  .where("id", requestLogId)
715
659
  .first();
716
660
 
717
- const effectiveModelName = params.model_name ?? row?.model_name;
718
-
719
- if (effectiveModelName) {
720
- const model = canonicalModelName(effectiveModelName);
721
-
722
- const usage = normalizedUsageForCost({
723
- token_name: params.token_name,
724
- model_name: effectiveModelName,
725
- input_tokens: params.input_tokens,
726
- output_tokens: params.output_tokens,
727
- cache_read_tokens: params.cache_read_tokens ?? 0,
728
- cache_creation_tokens: params.cache_creation_tokens ?? 0,
729
- cache_creation_5m_tokens: params.cache_creation_5m_tokens,
730
- cache_creation_1h_tokens: params.cache_creation_1h_tokens,
731
- });
732
-
733
- update.cost_usd = Math.round(
734
- calculateCostUsd(model, {
735
- inputTokens: usage.inputTokens,
736
- outputTokens: usage.outputTokens,
737
- cachedInputTokens: usage.cachedInputTokens,
738
- cacheCreationInputTokens: usage.cacheCreationInputTokens,
739
- cacheCreationInputTokens5m: usage.cacheCreationInputTokens5m,
740
- cacheCreationInputTokens1h: usage.cacheCreationInputTokens1h,
741
- }) * 1_000_000,
742
- );
743
- update.cost_source = "pricing_table";
744
- }
661
+ const resolved = resolvePricingCost({
662
+ token_name: params.token_name,
663
+ model_name: params.model_name ?? row?.model_name,
664
+ input_tokens: params.input_tokens,
665
+ output_tokens: params.output_tokens,
666
+ cache_read_tokens: params.cache_read_tokens ?? 0,
667
+ cache_creation_tokens: params.cache_creation_tokens ?? 0,
668
+ cache_creation_5m_tokens: params.cache_creation_5m_tokens,
669
+ cache_creation_1h_tokens: params.cache_creation_1h_tokens,
670
+ cost_usd: params.cost_usd,
671
+ });
672
+
673
+ if (resolved) Object.assign(update, resolved);
745
674
  }
746
675
 
747
676
  const wdb = this.getPuri("w");
@@ -882,7 +811,26 @@ class RequestLogModelClass extends BaseModelClass<
882
811
  expiry.fallback_count = aggregate.fallback_count;
883
812
  expiry.cost_usd = aggregate.cost_usd;
884
813
 
885
- if (aggregate.cost_source !== undefined) expiry.cost_source = aggregate.cost_source;
814
+ if (aggregate.cost_source !== undefined) {
815
+ expiry.cost_source = aggregate.cost_source;
816
+ } else {
817
+ // 출처 없는 외부 step 만 있던 run 은 만료 시점에 가격표 비용으로 확정한다.
818
+ const run = await wdb
819
+ .from("request_logs")
820
+ .select({ token_name: "token_name", model_name: "model_name" })
821
+ .where("id", requestLogId)
822
+ .first();
823
+
824
+ Object.assign(
825
+ expiry,
826
+ resolvePricingCost({
827
+ ...aggregate,
828
+ token_name: run?.token_name,
829
+ model_name: run?.model_name,
830
+ }),
831
+ );
832
+ }
833
+
886
834
  expiry.ttft_ms = firstTtft?.ttft_ms ?? 0;
887
835
 
888
836
  const updated = await wdb
@@ -942,12 +890,9 @@ class RequestLogModelClass extends BaseModelClass<
942
890
  /**
943
891
  * 화면 표시용 총 비용. 목록과 같은 필터를 적용한다.
944
892
  *
945
- * driver와 image 비용을 함께 SUM한 뒤, legacy driver 비용의 차액만 보정한다.
946
- * 이미지 비용은 저장값을 한 번만 포함하고 가격표 재계산 대상에서 제외한다.
947
- *
948
- * legacy 보정을 남겨둔 이유: 백필로 기존 legacy 는 0 이 되었지만, 외부 로거가
949
- * `AppendStepInput`/`FinishRunInput` 으로 costSource 없이 넣으면 다시 생길 수 있다.
950
- * 그런 row 는 저장값 대신 현재 가격표 재계산값이 맞으므로 차액을 더한다.
893
+ * driver와 image 비용 저장값을 SQL로 한 번 합산한다. 출처 없는 driver 비용은 쓰기 시점에
894
+ * `resolvePricingCost`로 확정하고 기존 row 는 백필로 확정했으므로, 읽을 때 가격표로 다시
895
+ * 계산하지 않는다(`scripts/backfill-request-log-costs.ts` dry-run 으로 보정 0 을 확인).
951
896
  *
952
897
  * 필터 조건을 여기서 다시 구현하지 않고 `applyListFilters` 를 공유하는 것이 핵심이다 —
953
898
  * 두 쿼리가 각자 필터를 가지면 화면에서 필터를 걸었을 때 행 수와 비용이 조용히 어긋난다.
@@ -975,7 +920,7 @@ class RequestLogModelClass extends BaseModelClass<
975
920
  // executeCountQuery 와 같은 방식으로 select 를 비우고 집계만 남긴다.
976
921
  const stored = await totalQb
977
922
  .clear("select")
978
- // 음수 저장값(과거 버그)은 0 으로 눌러서 더한다 — JS 쪽 Math.max 와 같은 규칙.
923
+ // 음수 저장값(과거 버그)은 0 으로 눌러서 더한다.
979
924
  .select({
980
925
  total: Puri.rawNumber(
981
926
  "COALESCE(SUM(GREATEST(request_logs.cost_usd, 0) + COALESCE(request_logs.image_cost_usd, 0)), 0)",
@@ -987,81 +932,39 @@ class RequestLogModelClass extends BaseModelClass<
987
932
  })
988
933
  .first();
989
934
 
990
- const { qb: legacyQb } = this.getSubsetQueries("C");
991
- this.applyListFilters(legacyQb, params);
992
- this.applySonamuFilters(legacyQb, sonamuFilter);
993
-
994
- const legacyRows = await legacyQb
995
- .whereRaw("request_logs.cost_source IS NULL OR request_logs.cost_usd IS NULL")
996
- .clear("select")
997
- .select({
998
- token_name: "request_logs.token_name",
999
- model_name: "request_logs.model_name",
1000
- input_tokens: "request_logs.input_tokens",
1001
- output_tokens: "request_logs.output_tokens",
1002
- cache_read_tokens: "request_logs.cache_read_tokens",
1003
- cache_creation_tokens: "request_logs.cache_creation_tokens",
1004
- cache_creation_5m_tokens: "request_logs.cache_creation_5m_tokens",
1005
- cache_creation_1h_tokens: "request_logs.cache_creation_1h_tokens",
1006
- cost_usd: "request_logs.cost_usd",
1007
- });
1008
-
1009
935
  // Postgres returns SUM/COUNT as bigint, which node-postgres delivers as text
1010
936
  // even though `Puri.rawNumber` types it as number.
1011
- const storedTotal = bigintAggregate.parse(stored?.total ?? 0) / MICRO_USD;
1012
-
1013
- // legacy row 는 위 SUM 에 저장값으로 이미 포함되어 있다. 재계산값과의 차액만 더한다.
1014
- const usd = legacyRows.reduce((sum, row) => {
1015
- const alreadySummed = Math.max(row.cost_usd ?? 0, 0) / MICRO_USD;
1016
- const usage = normalizedUsageForCost(row);
1017
-
1018
- if (!usage.model) return sum;
1019
-
1020
- return (
1021
- sum +
1022
- calculateCostUsd(usage.model, {
1023
- inputTokens: usage.inputTokens,
1024
- outputTokens: usage.outputTokens,
1025
- cachedInputTokens: usage.cachedInputTokens,
1026
- cacheCreationInputTokens: usage.cacheCreationInputTokens,
1027
- cacheCreationInputTokens5m: usage.cacheCreationInputTokens5m,
1028
- cacheCreationInputTokens1h: usage.cacheCreationInputTokens1h,
1029
- }) -
1030
- alreadySummed
1031
- );
1032
- }, storedTotal);
1033
-
1034
937
  return {
1035
- usd,
938
+ usd: bigintAggregate.parse(stored?.total ?? 0) / MICRO_USD,
1036
939
  unknownImageCostCount: bigintAggregate.parse(stored?.unknownImageCostCount ?? 0),
1037
940
  unknownCostCount: bigintAggregate.parse(stored?.unknownCostCount ?? 0),
1038
941
  };
1039
942
  }
1040
943
 
1041
944
  async distinctProjectNames(): Promise<string[]> {
1042
- const rows = await this.getPuri("r")
1043
- .from("request_logs")
1044
- .distinct("project_name")
1045
- .where("project_name", "!=", null)
1046
- .orderBy("project_name", "asc")
1047
- .select({
1048
- project_name: "project_name",
1049
- });
1050
-
1051
- return rows.map((r) => r.project_name!);
945
+ return this.distinctIndexedValues("project_name");
1052
946
  }
1053
947
 
1054
948
  async distinctModelNames(): Promise<string[]> {
1055
- const rows = await this.getPuri("r")
1056
- .from("request_logs")
1057
- .distinct("model_name")
1058
- .where("model_name", "!=", null)
1059
- .orderBy("model_name", "asc")
1060
- .select({
1061
- model_name: "model_name",
1062
- });
949
+ return this.distinctIndexedValues("model_name");
950
+ }
951
+
952
+ /**
953
+ * Loose index scan: 컬럼 인덱스에서 다음 값만 찾아 건너뛴다. 일반 DISTINCT 는 전체 행 수에
954
+ * 비례하지만 이 쿼리는 고유값 수에 비례한다. NULL 제외·오름차순 의미는 DISTINCT 와 같다.
955
+ */
956
+ private async distinctIndexedValues(column: "project_name" | "model_name"): Promise<string[]> {
957
+ const result = await this.getPuri("r").knex.raw<{ rows: Array<{ v: string }> }>(
958
+ `WITH RECURSIVE t AS (
959
+ (SELECT ?? AS v FROM request_logs WHERE ?? IS NOT NULL ORDER BY ?? LIMIT 1)
960
+ UNION ALL
961
+ SELECT (SELECT ?? FROM request_logs WHERE ?? > t.v ORDER BY ?? LIMIT 1) FROM t WHERE t.v IS NOT NULL
962
+ )
963
+ SELECT v FROM t WHERE v IS NOT NULL`,
964
+ [column, column, column, column, column, column],
965
+ );
1063
966
 
1064
- return rows.map((r) => r.model_name!);
967
+ return result.rows.map((row) => row.v);
1065
968
  }
1066
969
 
1067
970
  @api({ httpMethod: "POST", clients: ["axios", "tanstack-mutation"] })