Repository navigation
feat: collect model performance metrics - #4635
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (26)
WalkthroughAdds an end-to-end model performance metrics system: in-memory hot buckets + Redis counters, periodic flush to DB, new PerfMetric ORM and migrations, GET /api/perf-metrics handler, backend instrumentation points, settings and UI for aggregation/flush/retention, plus frontend types and translations. ChangesModel Performance Metrics (single cohesive DAG)
Sequence Diagram(s)sequenceDiagram
participant Client
participant QueryAPI as Query API
participant Metrics as MetricsCollector
participant Hot as HotBucket
participant Redis
participant DB as Database
participant Relay
Relay->>Metrics: RecordRelaySample(relayInfo, success)
activate Metrics
Metrics->>Hot: Record(sample) (atomicBucket.add)
Hot-->>Metrics: ack
Metrics->>Redis: recordRedis(sample) (incr per-bucket counters)
Redis-->>Metrics: ack
deactivate Metrics
loop Periodic flush
Metrics->>Hot: flushCompletedBuckets (drain)
activate Hot
Hot->>DB: UpsertPerfMetric(metric)
DB-->>Hot: ack
Hot-->>Metrics: ack
deactivate Hot
Metrics->>DB: DeletePerfMetricsBefore(cutoff)
DB-->>Metrics: ack
end
Client->>QueryAPI: GET /api/perf-metrics?model=X&hours=24
activate QueryAPI
QueryAPI->>Metrics: Query(params)
activate Metrics
Metrics->>DB: GetPerfMetrics(start,end)
DB-->>Metrics: []PerfMetric
Metrics->>Redis: merge active buckets
Metrics->>Hot: snapshot in-memory buckets
Metrics-->>QueryAPI: QueryResult (groups, series)
deactivate Metrics
QueryAPI-->>Client: 200 JSON
deactivate QueryAPI
Estimated code review effort🎯 4 (Complex) | ⏱️ ~75 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 15
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
web/default/src/i18n/locales/ru.json (1)
32-3549: 🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy liftMigrate newly added i18n keys to a hierarchical namespace instead of flat English sentences.
The newly added keys continue the flat-key pattern (e.g., Line 226, Line 1309, Line 2238), which conflicts with the repo’s i18n key-structure rule. Please add these under a scoped namespace (for example
performance.metrics.*) and wire usages accordingly.As per coding guidelines, use hierarchical and semantically clear translation key names such as
dashboard.overview.titleand maintain naming consistency.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/default/src/i18n/locales/ru.json` around lines 32 - 3549, Several newly added i18n entries use flat English-sentence keys (e.g., "Average latency", "Average TTFT", "Success rate") which violates our hierarchical key convention; move these keys into a scoped namespace like performance.metrics.averageLatency, performance.metrics.averageTTFT, performance.metrics.successRate (or similar semantic names under performance.metrics.*), update the ru.json entries to use those new keys, and then update all references in the codebase that consume the old flat keys (components/pages that call the i18n lookup for "Average latency", "Average TTFT", "Success rate", etc.) to use the new namespaced keys; also add temporary fallback mappings (or keep the old flat keys referencing the new keys) to avoid runtime breakage during rollout and ensure naming consistency with existing keys such as dashboard.overview.title.service/quota.go (1)
159-258:⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
PostWssConsumeQuotais missing the perf-metric recording.
PostAudioConsumeQuota(line 379) andPostTextConsumeQuotaboth end withgopool.Go(func() { perfmetrics.RecordRelaySample(relayInfo, true) }), but the realtime/WSS success path here does not. As a result, successful realtime sessions will not contribute to TTFT/latency/success-rate aggregates surfaced by/api/perf-metrics, which is the same gap noted on the relay error path. If the omission is intentional (e.g., realtime semantics differ), please confirm; otherwise mirror the same async record at the end of this function.♻️ Suggested addition (mirrors PostAudioConsumeQuota)
model.RecordConsumeLog(ctx, relayInfo.UserId, model.RecordConsumeLogParams{ ... Other: other, }) + gopool.Go(func() { + perfmetrics.RecordRelaySample(relayInfo, true) + }) }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@service/quota.go` around lines 159 - 258, PostWssConsumeQuota is missing the async perf-metric recording done in PostAudioConsumeQuota/PostTextConsumeQuota; add the same non-blocking call after the successful flow (after model.RecordConsumeLog returns) by invoking gopool.Go(func() { perfmetrics.RecordRelaySample(relayInfo, true) }) so successful realtime/WSS sessions are included in TTFT/latency/success-rate aggregates.
🧹 Nitpick comments (5)
web/default/src/i18n/locales/fr.json (1)
226-226: 🏗️ Heavy liftUse hierarchical i18n keys for the newly added performance-metrics entries.
These additions keep sentence-style keys instead of semantic hierarchical keys, which makes key reuse and maintenance harder over time.
♻️ Suggested direction
- "Model performance metrics": "Indicateurs de performance des modèles", - "Average latency": "Latence moyenne", - "Success rate": "Taux de réussite", + "performance.metrics.model.title": "Indicateurs de performance des modèles", + "performance.metrics.latency.average": "Latence moyenne", + "performance.metrics.successRate": "Taux de réussite",As per coding guidelines, "Use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency".
Also applies to: 432-443, 724-724, 1309-1309, 1675-1675, 2238-2238, 3125-3126, 3175-3175, 3549-3549
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/default/src/i18n/locales/fr.json` at line 226, The translation key "Aggregation bucket" (and the other listed sentence-style keys) should be renamed to hierarchical, semantic keys (e.g. performanceMetrics.aggregationBucket or dashboard.performance.aggregationBucket) and the corresponding references updated where used; locate the key string "Aggregation bucket" in fr.json and replace it with a semantically-nested key (follow existing naming pattern such as performanceMetrics.* or dashboard.*), update the matching keys for the other ranges (432-443, 724, 1309, 1675, 2238, 3125-3126, 3175, 3549) to use the same hierarchical convention, and ensure any code or components referencing these keys are updated to the new key names (search for literal usages of "Aggregation bucket" and the other sentence-style keys and replace with the new dotted keys).setting/perf_metrics_setting/config.go (1)
27-37: ⚡ Quick winValidate/normalize
BucketTimeinstead of silently defaulting on unknown values.At Line 35–36, unsupported values quietly map to
3600, which can hide config mistakes. Consider normalizing input (strings.ToLower) and validating against allowed values at load time so bad config is visible early.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@setting/perf_metrics_setting/config.go` around lines 27 - 37, GetBucketSeconds currently silently returns 3600 for any unknown perfMetricsSetting.BucketTime; instead validate and normalize the value early: normalize perfMetricsSetting.BucketTime with strings.ToLower and either return an explicit error or panic/log and fallback when loading the configuration (e.g., in the config loader that sets perfMetricsSetting) if the value is not one of the allowed set {"minute","5min","hour"}; update GetBucketSeconds to assume a validated value (or return an error/ok pair) and document allowed values so misconfiguration surfaces at startup rather than quietly mapping to 3600.web/default/src/i18n/locales/ja.json (1)
226-226: ⚡ Quick winNamespace the new performance-metrics translation keys.
These additions keep using English display strings as keys. Please move the new perf-metrics entries under a dedicated namespace such as
perfMetrics.*so this feature follows the repo’s i18n convention and stays maintainable as the surface grows.As per coding guidelines, "Use hierarchical and semantically clear translation key names such as
dashboard.overview.titleand maintain naming consistency".Also applies to: 432-443, 724-725, 1309-1309, 1675-1675, 2238-2238, 2414-2414, 3125-3126, 3175-3175, 3549-3549
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/default/src/i18n/locales/ja.json` at line 226, Several new i18n entries (e.g., the key "Aggregation bucket" and the other keys referenced at lines 432-443, 724-725, 1309, 1675, 2238, 2414, 3125-3126, 3175, 3549) are using English display strings as top-level keys; rename and nest them under a dedicated namespace like perfMetrics (for example perfMetrics.aggregationBucket) to follow the repo convention. Update the JSON keys in web/default/src/i18n/locales/ja.json accordingly (replace the raw English keys with perfMetrics.* keys) and ensure any code referencing these keys (components rendering performance-metrics UI) is updated to use the new perfMetrics.<key> names so translations resolve correctly.web/default/src/features/pricing/components/model-details-performance.tsx (2)
142-142: 💤 Low valueDefensive optional chaining on the inner
dataenvelope.
metricsQuery.data?.data.groupsonly guards the outermetricsQuery.data. The backend response is a{ success, message?, data: { ... } }envelope, and on certain failure shapes (e.g., the handler returns{ success: false, message }with HTTP 500 — seecontroller/perf_metrics.go) thedatafield will be absent. If response interceptors ever resolve such payloads instead of throwing, this access will throw on.groups. A second?.is essentially free.- const groups = metricsQuery.data?.data.groups ?? [] + const groups = metricsQuery.data?.data?.groups ?? []🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/default/src/features/pricing/components/model-details-performance.tsx` at line 142, The assignment to groups uses only metricsQuery.data?.data.groups which can throw if the inner response envelope lacks data; update the expression that defines the const groups (the line binding the variable named groups from metricsQuery) to defensively optional-chain the inner envelope (use metricsQuery.data?.data?.groups) and keep the fallback (?? []) so groups is always an array; locate the const groups assignment in the component (reference symbols: metricsQuery and groups) and apply the extra ?. to the inner data access.
137-141: ⚡ Quick winInclude
hoursinqueryKeyto avoid stale-cache bugs if it becomes dynamic.
hoursis hardcoded to24today, but thequeryKeyonly containsmodel_name. If a caller later parameterizeshours(e.g., 1h/24h/7d toggles), React Query will return cached data from a previous range untilstaleTimeelapses. Cheap to make the key fully describe the request now.♻️ Suggested change
- const metricsQuery = useQuery({ - queryKey: ['perf-metrics', props.model.model_name], - queryFn: () => getPerfMetrics(props.model.model_name, 24), - staleTime: 60 * 1000, - }) + const hours = 24 + const metricsQuery = useQuery({ + queryKey: ['perf-metrics', props.model.model_name, hours], + queryFn: () => getPerfMetrics(props.model.model_name, hours), + staleTime: 60 * 1000, + })As per coding guidelines: "configure a unique
queryKey(preferably as an array with consistent hierarchy)".🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@web/default/src/features/pricing/components/model-details-performance.tsx` around lines 137 - 141, The useQuery call for metricsQuery currently keys only by ['perf-metrics', props.model.model_name] while getPerfMetrics is called with a hardcoded 24; make the key fully describe the request by adding an hours variable into the queryKey (e.g., ['perf-metrics', props.model.model_name, hours]) and use that same hours variable in the queryFn call to getPerfMetrics so the cache updates correctly if hours becomes dynamic; update the metricsQuery initialization (useQuery, metricsQuery, getPerfMetrics, props.model.model_name) to reflect this change.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@controller/perf_metrics.go`:
- Around line 22-27: Validate the parsed hours value after strconv.Atoi: if
rawHours is provided, ensure the resulting hours is within an acceptable
positive range (e.g., >=1 and <= a max like 168 or another configured cap) and
reject invalid values instead of silently using them; return a 400 Bad Request
(using the controller's context response methods) for non-positive or oversized
inputs so perfmetrics.Query never receives -/zero/huge ranges. Check/adjust the
variable named hours (and rawHours) in controller/perf_metrics.go where you call
strconv.Atoi and before passing hours to perfmetrics.Query.
- Around line 34-39: The handler currently returns err.Error() to the client (in
the c.JSON block) which can leak internal DB/redis details; instead log the
original error server-side (e.g., using your existing logger or log.Printf) and
respond with a generic message like "internal server error" or "failed to fetch
performance metrics"; update the error branch surrounding perfmetrics.Query and
the c.JSON call to emit the generic message to the client while preserving the
full err in server logs for debugging.
In `@model/perf_metric.go`:
- Around line 13-15: Add a non-unique composite index on (model_name, bucket_ts)
so queries filtering by ModelName and BucketTs can use an efficient range scan;
update the GORM tags on the ModelName and BucketTs struct fields (ModelName and
BucketTs) to include a shared index name (e.g. index:idx_perf_model_bucket) with
appropriate priorities (priority:1 on ModelName, priority:2 on BucketTs) while
keeping the existing uniqueIndex idx_perf_model_group_bucket unchanged.
In `@pkg/perf_metrics/flush.go`:
- Around line 36-38: After a successful flush we must remove empty bucket
entries immediately to avoid growing dead sync.Map entries: in the branch that
checks drained.requestCount == 0 (and the similar branch around the 57-65
range), call deleteOldEmptyBucket(k, key) and return true right after confirming
drained.requestCount is zero so the (model, group, bucketTs) entry is removed
instead of being left for 24h; ensure you update both places that currently
leave empty buckets alive so they both delete and return immediately.
In `@pkg/perf_metrics/metrics.go`:
- Around line 18-20: Init currently only starts the background flushLoop so
there's no way to synchronously drain hotBuckets on shutdown; add an exported
FlushNow or Shutdown function that triggers an immediate flush and waits for
completion. Implement this by giving flushLoop a control channel (e.g.,
flushTrigger chan struct{} and done chan struct{}) or a context/WaitGroup so
flushLoop listens for a trigger and signals when the flush finished; export
FlushNow/Shutdown to send on that channel or cancel the context and block until
the flush completes, then return; update Init to initialize the control
channels/ctx so callers can call FlushNow before closing the DB. Ensure the
flush routine that reads hotBuckets is reused by both periodic ticks and the
synchronous trigger so no metrics are lost.
- Around line 221-235: The Redis TTL is hard-coded to time.Hour in the pipeline
(pipe.Expire(ctx, redisKey, time.Hour)); update this to use a configured TTL or
compute it from your existing bucket/flush settings instead: retrieve the
configured TTL (or compute e.g. based on bucket size and flush interval) and
replace the literal with that variable before calling pipe.Expire so
redisBucketKey counters won't expire prematurely; update code paths that build
the pipeline in the function using redisBucketKey/TxPipeline/Expire to reference
the new ttl value.
- Around line 74-105: The Query implementation builds a merged map from DB rows
and in-process hotBuckets but never incorporates Redis-backed active counters;
call mergeRedisActiveBuckets with the same params and merged map (e.g.
mergeRedisActiveBuckets(params.Model, params.Group, startTs, endTs, merged))
after the hotBuckets.Range merge and before calling buildQueryResult, handle and
return any error from mergeRedisActiveBuckets so the Query returns the combined
in-memory+Redis data.
In `@pkg/perf_metrics/types.go`:
- Around line 73-105: The bucket methods (atomicBucket.add, snapshot, drain)
race because hotBuckets holds pointers but the five fields are updated/loaded
separately; fix by making updates and reads atomic across all fields—either add
a sync.Mutex (e.g., put mu in atomicBucket and lock in add, snapshot, drain) or
replace the five atomics with a single atomic.Value holding a counters struct
and use Load/Store/CompareAndSwap to update; ensure Record(), Query(), and the
flush loop use the new atomicBucket API so each sample is applied or drained as
a single atomic operation and no fields can be split across flushes.
In `@web/default/src/features/pricing/components/model-details-performance.tsx`:
- Around line 164-170: The current check conflates loading, empty, and error
states; update the render logic in model-details-performance.tsx to branch
explicitly on metricsQuery.isLoading (show a spinner or skeleton),
metricsQuery.isError (call handleServerError(metricsQuery.error) and render an
i18n error message with a retry affordance that calls metricsQuery.refetch), and
finally when performances.length === 0 render the existing "Performance data is
not yet available" copy; reference metricsQuery, performances,
handleServerError, and metricsQuery.refetch when implementing these branches and
use i18n keys for any user-facing text.
In `@web/default/src/features/system-settings/maintenance/config.ts`:
- Around line 78-81: The default perf metrics config currently enables metrics
collection ('perf_metrics_setting.enabled' = true) and sets
'perf_metrics_setting.retention_days' = 0 which causes indefinite retention;
change the defaults to avoid unbounded storage growth by either disabling
collection by default (set 'perf_metrics_setting.enabled' = false) or assigning
a finite retention window (e.g., set 'perf_metrics_setting.retention_days' to a
sensible default like 30) and keep 'perf_metrics_setting.flush_interval' and
'perf_metrics_setting.bucket_time' as-is; update the config in config.ts where
these keys are defined and add a short comment clarifying the rationale for the
new default.
In
`@web/default/src/features/system-settings/maintenance/performance-section.tsx`:
- Around line 62-65: The schema currently allows decimals for
'perf_metrics_setting.flush_interval' and 'perf_metrics_setting.retention_days'
so change their validators to use z.coerce.number().int().min(...) (i.e., make
both .int()) to enforce integer input, and update the corresponding number input
components in performance-section.tsx for those fields to include step={1} (and
keep min={1} for flush_interval and min={0} for retention_days) so the UI and
schema match the backend int contract.
In `@web/default/src/i18n/locales/en.json`:
- Line 32: Replace the source-text translation key "{{count}} incidents in the
last 24 hours" with a hierarchical, semantic key (e.g.,
"incidents.recent.count24h") and keep the English sentence as the value; update
any consumers to use the new key. Do the same for the other listed keys (lines
referenced: occurrences at 63, 67, 70, 93, 226, 432, 437-438, 440, 443, 724,
1309, 1675, 2238, 2414, 3125-3126, 3175, 3549) using consistent namespaced
patterns like "incidents.*", "dashboard.*" or "performance.*" as appropriate,
and ensure translation lookups (e.g., calls reading these JSON keys) are updated
to the new semantic keys.
- Line 724: Update the user-facing string that currently reads "Collect relay
latency and success-rate metrics for the model square." to use the product name
capitalized: "Collect relay latency and success-rate metrics for the Model
Square." Locate and edit the matching JSON entry where the key/value contains
"Collect relay latency and success-rate metrics for the model square." and
replace the lowercase "model square" with "Model Square" so both key and value
reflect the corrected product-name capitalization.
In `@web/default/src/i18n/locales/ru.json`:
- Line 1675: The translation for the key "Flush interval (minutes)" uses
"Интервал записи" which implies a write interval; update the value in ru.json
for the string "Flush interval (minutes)" to a more accurate term like "Интервал
сброса (минуты)" or "Интервал выгрузки (минуты)" to reflect flush/drain
semantics while preserving the original key exactly.
In `@web/default/src/i18n/locales/vi.json`:
- Line 226: The translation key "Aggregation bucket" in vi.json uses a raw
English sentence key; rename it to a hierarchical semantic key (e.g.,
performance.metrics.aggregationBucket) and update the corresponding key in all
other locale files and components that reference the old key (see other affected
ranges noted) so lookups use performance.metrics.aggregationBucket instead of
"Aggregation bucket"; ensure you adjust any code that calls the string (e.g.,
components or hooks that reference "Aggregation bucket") to the new hierarchical
key and keep the same Vietnamese value.
---
Outside diff comments:
In `@service/quota.go`:
- Around line 159-258: PostWssConsumeQuota is missing the async perf-metric
recording done in PostAudioConsumeQuota/PostTextConsumeQuota; add the same
non-blocking call after the successful flow (after model.RecordConsumeLog
returns) by invoking gopool.Go(func() { perfmetrics.RecordRelaySample(relayInfo,
true) }) so successful realtime/WSS sessions are included in
TTFT/latency/success-rate aggregates.
In `@web/default/src/i18n/locales/ru.json`:
- Around line 32-3549: Several newly added i18n entries use flat
English-sentence keys (e.g., "Average latency", "Average TTFT", "Success rate")
which violates our hierarchical key convention; move these keys into a scoped
namespace like performance.metrics.averageLatency,
performance.metrics.averageTTFT, performance.metrics.successRate (or similar
semantic names under performance.metrics.*), update the ru.json entries to use
those new keys, and then update all references in the codebase that consume the
old flat keys (components/pages that call the i18n lookup for "Average latency",
"Average TTFT", "Success rate", etc.) to use the new namespaced keys; also add
temporary fallback mappings (or keep the old flat keys referencing the new keys)
to avoid runtime breakage during rollout and ensure naming consistency with
existing keys such as dashboard.overview.title.
---
Nitpick comments:
In `@setting/perf_metrics_setting/config.go`:
- Around line 27-37: GetBucketSeconds currently silently returns 3600 for any
unknown perfMetricsSetting.BucketTime; instead validate and normalize the value
early: normalize perfMetricsSetting.BucketTime with strings.ToLower and either
return an explicit error or panic/log and fallback when loading the
configuration (e.g., in the config loader that sets perfMetricsSetting) if the
value is not one of the allowed set {"minute","5min","hour"}; update
GetBucketSeconds to assume a validated value (or return an error/ok pair) and
document allowed values so misconfiguration surfaces at startup rather than
quietly mapping to 3600.
In `@web/default/src/features/pricing/components/model-details-performance.tsx`:
- Line 142: The assignment to groups uses only metricsQuery.data?.data.groups
which can throw if the inner response envelope lacks data; update the expression
that defines the const groups (the line binding the variable named groups from
metricsQuery) to defensively optional-chain the inner envelope (use
metricsQuery.data?.data?.groups) and keep the fallback (?? []) so groups is
always an array; locate the const groups assignment in the component (reference
symbols: metricsQuery and groups) and apply the extra ?. to the inner data
access.
- Around line 137-141: The useQuery call for metricsQuery currently keys only by
['perf-metrics', props.model.model_name] while getPerfMetrics is called with a
hardcoded 24; make the key fully describe the request by adding an hours
variable into the queryKey (e.g., ['perf-metrics', props.model.model_name,
hours]) and use that same hours variable in the queryFn call to getPerfMetrics
so the cache updates correctly if hours becomes dynamic; update the metricsQuery
initialization (useQuery, metricsQuery, getPerfMetrics, props.model.model_name)
to reflect this change.
In `@web/default/src/i18n/locales/fr.json`:
- Line 226: The translation key "Aggregation bucket" (and the other listed
sentence-style keys) should be renamed to hierarchical, semantic keys (e.g.
performanceMetrics.aggregationBucket or dashboard.performance.aggregationBucket)
and the corresponding references updated where used; locate the key string
"Aggregation bucket" in fr.json and replace it with a semantically-nested key
(follow existing naming pattern such as performanceMetrics.* or dashboard.*),
update the matching keys for the other ranges (432-443, 724, 1309, 1675, 2238,
3125-3126, 3175, 3549) to use the same hierarchical convention, and ensure any
code or components referencing these keys are updated to the new key names
(search for literal usages of "Aggregation bucket" and the other sentence-style
keys and replace with the new dotted keys).
In `@web/default/src/i18n/locales/ja.json`:
- Line 226: Several new i18n entries (e.g., the key "Aggregation bucket" and the
other keys referenced at lines 432-443, 724-725, 1309, 1675, 2238, 2414,
3125-3126, 3175, 3549) are using English display strings as top-level keys;
rename and nest them under a dedicated namespace like perfMetrics (for example
perfMetrics.aggregationBucket) to follow the repo convention. Update the JSON
keys in web/default/src/i18n/locales/ja.json accordingly (replace the raw
English keys with perfMetrics.* keys) and ensure any code referencing these keys
(components rendering performance-metrics UI) is updated to use the new
perfMetrics.<key> names so translations resolve correctly.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 1a7b42c4-6fee-4f7a-929a-50b95d3e9be5
📒 Files selected for processing (26)
controller/perf_metrics.gocontroller/relay.gomain.gomodel/main.gomodel/perf_metric.gopkg/perf_metrics/flush.gopkg/perf_metrics/metrics.gopkg/perf_metrics/types.gorouter/api-router.goservice/quota.goservice/text_quota.gosetting/perf_metrics_setting/config.goweb/default/src/features/pricing/api.tsweb/default/src/features/pricing/components/model-details-charts.tsxweb/default/src/features/pricing/components/model-details-performance.tsxweb/default/src/features/pricing/components/model-details.tsxweb/default/src/features/system-settings/maintenance/config.tsweb/default/src/features/system-settings/maintenance/performance-section.tsxweb/default/src/features/system-settings/maintenance/section-registry.tsxweb/default/src/features/system-settings/types.tsweb/default/src/i18n/locales/en.jsonweb/default/src/i18n/locales/fr.jsonweb/default/src/i18n/locales/ja.jsonweb/default/src/i18n/locales/ru.jsonweb/default/src/i18n/locales/vi.jsonweb/default/src/i18n/locales/zh.json
💤 Files with no reviewable changes (1)
- web/default/src/features/pricing/components/model-details.tsx
| hours := 24 | ||
| if rawHours := c.Query("hours"); rawHours != "" { | ||
| if parsed, err := strconv.Atoi(rawHours); err == nil { | ||
| hours = parsed | ||
| } | ||
| } |
There was a problem hiding this comment.
Validate hours bounds (and reject non-positive / oversized values).
hours is parsed via strconv.Atoi without any range check, so values like -1, 0, or 999999 are accepted and forwarded into perfmetrics.Query. Combined with the route being protected by TryUserAuth (anonymous-friendly), this lets unauthenticated callers issue arbitrarily expensive lookups against PerfMetric, and also produces undefined behavior for non-positive ranges depending on Query's assumptions.
🛡️ Suggested clamp
hours := 24
if rawHours := c.Query("hours"); rawHours != "" {
- if parsed, err := strconv.Atoi(rawHours); err == nil {
- hours = parsed
- }
+ if parsed, err := strconv.Atoi(rawHours); err == nil && parsed > 0 {
+ if parsed > 24*7 { // cap to a week (or your retention window)
+ parsed = 24 * 7
+ }
+ hours = parsed
+ }
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| hours := 24 | |
| if rawHours := c.Query("hours"); rawHours != "" { | |
| if parsed, err := strconv.Atoi(rawHours); err == nil { | |
| hours = parsed | |
| } | |
| } | |
| hours := 24 | |
| if rawHours := c.Query("hours"); rawHours != "" { | |
| if parsed, err := strconv.Atoi(rawHours); err == nil && parsed > 0 { | |
| if parsed > 24*7 { // cap to a week (or your retention window) | |
| parsed = 24 * 7 | |
| } | |
| hours = parsed | |
| } | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@controller/perf_metrics.go` around lines 22 - 27, Validate the parsed hours
value after strconv.Atoi: if rawHours is provided, ensure the resulting hours is
within an acceptable positive range (e.g., >=1 and <= a max like 168 or another
configured cap) and reject invalid values instead of silently using them; return
a 400 Bad Request (using the controller's context response methods) for
non-positive or oversized inputs so perfmetrics.Query never receives -/zero/huge
ranges. Check/adjust the variable named hours (and rawHours) in
controller/perf_metrics.go where you call strconv.Atoi and before passing hours
to perfmetrics.Query.
| if err != nil { | ||
| c.JSON(http.StatusInternalServerError, gin.H{ | ||
| "success": false, | ||
| "message": err.Error(), | ||
| }) | ||
| return |
There was a problem hiding this comment.
Avoid leaking raw internal errors to the client.
err.Error() from perfmetrics.Query may surface DB driver text, table/column names, or redis details to anonymous callers (route uses TryUserAuth). Log the original error server-side and respond with a generic message.
🔒️ Suggested change
- if err != nil {
- c.JSON(http.StatusInternalServerError, gin.H{
- "success": false,
- "message": err.Error(),
- })
- return
- }
+ if err != nil {
+ common.SysError("perf-metrics query failed: " + err.Error())
+ c.JSON(http.StatusInternalServerError, gin.H{
+ "success": false,
+ "message": "failed to query performance metrics",
+ })
+ return
+ }📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if err != nil { | |
| c.JSON(http.StatusInternalServerError, gin.H{ | |
| "success": false, | |
| "message": err.Error(), | |
| }) | |
| return | |
| if err != nil { | |
| common.SysError("perf-metrics query failed: " + err.Error()) | |
| c.JSON(http.StatusInternalServerError, gin.H{ | |
| "success": false, | |
| "message": "failed to query performance metrics", | |
| }) | |
| return | |
| } |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@controller/perf_metrics.go` around lines 34 - 39, The handler currently
returns err.Error() to the client (in the c.JSON block) which can leak internal
DB/redis details; instead log the original error server-side (e.g., using your
existing logger or log.Printf) and respond with a generic message like "internal
server error" or "failed to fetch performance metrics"; update the error branch
surrounding perfmetrics.Query and the c.JSON call to emit the generic message to
the client while preserving the full err in server logs for debugging.
| ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"` | ||
| Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"` | ||
| BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"` |
There was a problem hiding this comment.
Add a (model_name, bucket_ts) index for the main query path.
GetPerfMetrics always filters by model_name and bucket_ts, but the only composite index here is (model_name, group, bucket_ts). When group is omitted, MySQL/PostgreSQL cannot use the bucket_ts range efficiently, so model-wide reads will degrade as retention grows.
Suggested index change
type PerfMetric struct {
Id int `json:"id" gorm:"primaryKey"`
- ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"`
+ ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1;index:idx_perf_model_bucket,priority:1"`
Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"`
- BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"`
+ BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts;index:idx_perf_model_bucket,priority:2"`
RequestCount int64 `json:"request_count" gorm:"default:0"`📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1"` | |
| Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"` | |
| BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts"` | |
| type PerfMetric struct { | |
| Id int `json:"id" gorm:"primaryKey"` | |
| ModelName string `json:"model_name" gorm:"size:128;uniqueIndex:idx_perf_model_group_bucket,priority:1;index:idx_perf_model_bucket,priority:1"` | |
| Group string `json:"group" gorm:"column:group;size:64;uniqueIndex:idx_perf_model_group_bucket,priority:2"` | |
| BucketTs int64 `json:"bucket_ts" gorm:"uniqueIndex:idx_perf_model_group_bucket,priority:3;index:idx_perf_bucket_ts;index:idx_perf_model_bucket,priority:2"` | |
| RequestCount int64 `json:"request_count" gorm:"default:0"` |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@model/perf_metric.go` around lines 13 - 15, Add a non-unique composite index
on (model_name, bucket_ts) so queries filtering by ModelName and BucketTs can
use an efficient range scan; update the GORM tags on the ModelName and BucketTs
struct fields (ModelName and BucketTs) to include a shared index name (e.g.
index:idx_perf_model_bucket) with appropriate priorities (priority:1 on
ModelName, priority:2 on BucketTs) while keeping the existing uniqueIndex
idx_perf_model_group_bucket unchanged.
| func Init() { | ||
| go flushLoop() | ||
| } |
There was a problem hiding this comment.
Expose a shutdown flush for the perf-metrics worker.
Init only starts the background loop. There is no way to drain hotBuckets before process exit, so every deploy/restart can drop up to one full flush interval of metrics. Please add a synchronous FlushNow/Shutdown path and call it during server shutdown before the DB is closed.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@pkg/perf_metrics/metrics.go` around lines 18 - 20, Init currently only starts
the background flushLoop so there's no way to synchronously drain hotBuckets on
shutdown; add an exported FlushNow or Shutdown function that triggers an
immediate flush and waits for completion. Implement this by giving flushLoop a
control channel (e.g., flushTrigger chan struct{} and done chan struct{}) or a
context/WaitGroup so flushLoop listens for a trigger and signals when the flush
finished; export FlushNow/Shutdown to send on that channel or cancel the context
and block until the flush completes, then return; update Init to initialize the
control channels/ctx so callers can call FlushNow before closing the DB. Ensure
the flush routine that reads hotBuckets is reused by both periodic ticks and the
synchronous trigger so no metrics are lost.
| 'perf_metrics_setting.enabled': z.boolean(), | ||
| 'perf_metrics_setting.flush_interval': z.coerce.number().min(1), | ||
| 'perf_metrics_setting.bucket_time': z.enum(['minute', '5min', 'hour']), | ||
| 'perf_metrics_setting.retention_days': z.coerce.number().min(0), |
There was a problem hiding this comment.
Validate flush_interval and retention_days as integers.
The backend contract models both fields as int, but this schema accepts decimals. Values like 1.5 will pass client validation and then be truncated or rejected server-side. Please make these .int() here and set step={1} on the corresponding inputs.
🛠️ Proposed fix
- 'perf_metrics_setting.flush_interval': z.coerce.number().min(1),
+ 'perf_metrics_setting.flush_interval': z.coerce.number().int().min(1),
'perf_metrics_setting.bucket_time': z.enum(['minute', '5min', 'hour']),
- 'perf_metrics_setting.retention_days': z.coerce.number().min(0),
+ 'perf_metrics_setting.retention_days': z.coerce.number().int().min(0),<Input type='number' min={1} step={1} {...field} disabled={!perfMetricsEnabled} />
<Input type='number' min={0} step={1} {...field} disabled={!perfMetricsEnabled} />🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/default/src/features/system-settings/maintenance/performance-section.tsx`
around lines 62 - 65, The schema currently allows decimals for
'perf_metrics_setting.flush_interval' and 'perf_metrics_setting.retention_days'
so change their validators to use z.coerce.number().int().min(...) (i.e., make
both .int()) to enforce integer input, and update the corresponding number input
components in performance-section.tsx for those fields to include step={1} (and
keep min={1} for flush_interval and min={0} for retention_days) so the UI and
schema match the backend int contract.
| "{{count}} disabled channel(s) deleted": "{{count}} disabled channel(s) deleted", | ||
| "{{count}} hours ago": "{{count}} hours ago", | ||
| "{{count}} incidents": "{{count}} incidents", | ||
| "{{count}} incidents in the last 24 hours": "{{count}} incidents in the last 24 hours", |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift
Use hierarchical semantic i18n keys for new entries
These new keys are source-text phrases instead of semantic keys, which makes localization maintenance and cross-locale consistency brittle. Please add new keys using a namespaced pattern (e.g., performance.metrics.averageLatency) and keep the English string in the value.
As per coding guidelines, web/default/src/i18n/**/*.{ts,tsx,json}: "Use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency".
Also applies to: 63-63, 67-67, 70-70, 93-93, 226-226, 432-432, 437-438, 440-440, 443-443, 724-724, 1309-1309, 1675-1675, 2238-2238, 2414-2414, 3125-3126, 3175-3175, 3549-3549
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/default/src/i18n/locales/en.json` at line 32, Replace the source-text
translation key "{{count}} incidents in the last 24 hours" with a hierarchical,
semantic key (e.g., "incidents.recent.count24h") and keep the English sentence
as the value; update any consumers to use the new key. Do the same for the other
listed keys (lines referenced: occurrences at 63, 67, 70, 93, 226, 432, 437-438,
440, 443, 724, 1309, 1675, 2238, 2414, 3125-3126, 3175, 3549) using consistent
namespaced patterns like "incidents.*", "dashboard.*" or "performance.*" as
appropriate, and ensure translation lookups (e.g., calls reading these JSON
keys) are updated to the new semantic keys.
| "Cohere": "Cohere", | ||
| "Collapse": "Collapse", | ||
| "Collapse All": "Collapse All", | ||
| "Collect relay latency and success-rate metrics for the model square.": "Collect relay latency and success-rate metrics for the model square.", |
There was a problem hiding this comment.
Capitalize product name in user-facing copy
The sentence uses model square in lowercase; this should be Model Square for product-name consistency.
✏️ Proposed text fix
- "Collect relay latency and success-rate metrics for the model square.": "Collect relay latency and success-rate metrics for the model square.",
+ "Collect relay latency and success-rate metrics for the Model Square.": "Collect relay latency and success-rate metrics for the Model Square.",📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| "Collect relay latency and success-rate metrics for the model square.": "Collect relay latency and success-rate metrics for the model square.", | |
| "Collect relay latency and success-rate metrics for the Model Square.": "Collect relay latency and success-rate metrics for the Model Square.", |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/default/src/i18n/locales/en.json` at line 724, Update the user-facing
string that currently reads "Collect relay latency and success-rate metrics for
the model square." to use the product name capitalized: "Collect relay latency
and success-rate metrics for the Model Square." Locate and edit the matching
JSON entry where the key/value contains "Collect relay latency and success-rate
metrics for the model square." and replace the lowercase "model square" with
"Model Square" so both key and value reflect the corrected product-name
capitalization.
| "Fixed price (USD)": "Фиксированная цена (USD)", | ||
| "Floating": "Плавающая", | ||
| "FluentRead extension not detected. Please ensure it is installed and active.": "Расширение FluentRead не обнаружено. Убедитесь, что оно установлено и активно.", | ||
| "Flush interval (minutes)": "Интервал записи (минуты)", |
There was a problem hiding this comment.
Adjust wording of “Flush interval” translation for technical accuracy.
At Line 1675, "Интервал записи" reads as write interval; for flush/drain semantics, "Интервал сброса" (or "Интервал выгрузки") is clearer.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/default/src/i18n/locales/ru.json` at line 1675, The translation for the
key "Flush interval (minutes)" uses "Интервал записи" which implies a write
interval; update the value in ru.json for the string "Flush interval (minutes)"
to a more accurate term like "Интервал сброса (минуты)" or "Интервал выгрузки
(минуты)" to reflect flush/drain semantics while preserving the original key
exactly.
| "Aggregated traffic by upstream model provider": "Lưu lượng tổng hợp theo nhà cung cấp mô hình", | ||
| "Aggregated usage metrics and trend charts.": "Chỉ số sử dụng tổng hợp và biểu đồ xu hướng.", | ||
| "aggregates 50+ AI providers behind one unified API. Manage access, track costs, and scale effortlessly.": "tổng hợp hơn 50 nhà cung cấp AI sau một API thống nhất. Quản lý truy cập, theo dõi chi phí và mở rộng dễ dàng.", | ||
| "Aggregation bucket": "Khoảng tổng hợp", |
There was a problem hiding this comment.
🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy lift
Use hierarchical i18n keys for newly introduced metrics strings
These newly added keys continue the raw-English-sentence key pattern instead of hierarchical semantic keys (e.g., performance.metrics.successRate). Please align new entries to hierarchical naming and keep naming consistent across locales/components for this feature slice.
As per coding guidelines, web/default/src/i18n/**/*.{ts,tsx,json}: Use hierarchical and semantically clear translation key names such as dashboard.overview.title and maintain naming consistency.
Also applies to: 432-443, 724-724, 1309-1309, 1675-1675, 2238-2238, 3125-3126, 3175-3175, 3549-3549
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@web/default/src/i18n/locales/vi.json` at line 226, The translation key
"Aggregation bucket" in vi.json uses a raw English sentence key; rename it to a
hierarchical semantic key (e.g., performance.metrics.aggregationBucket) and
update the corresponding key in all other locale files and components that
reference the old key (see other affected ranges noted) so lookups use
performance.metrics.aggregationBucket instead of "Aggregation bucket"; ensure
you adjust any code that calls the string (e.g., components or hooks that
reference "Aggregation bucket") to the new hierarchical key and keep the same
Vietnamese value.
4038ed8 to
5dd413a
Compare
Important
📝 变更描述 / Description
新增模型性能指标采集链路,用内存热聚合并定期持久化到数据库,提供模型广场可读取的真实 TTFT、延迟和成功率数据。前端性能页改为调用真实接口,并在维护设置中增加独立的性能指标配置项。
🚀 变更类型 / Type of change
🔗 关联任务 / Related Issue
✅ 提交前检查项 / Checklist
Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。📸 运行证明 / Proof of Work
go test ./model ./controller ./service ./pkg/perf_metrics ./setting/perf_metrics_setting ./routercd web/default && bun run typecheckcd web/default && bun run i18n:syncSummary by CodeRabbit