Skip to content

feat(qdl): YAML 序列化契约——类型标签 + Coeff 双态 + ISO 8601 时长 - #6

Merged
randypanding merged 2 commits into
mainfrom
feat/qdl-loader
Aug 19, 2026
Merged

randypanding merged 2 commits into
mainfrom
feat/qdl-loader

Conversation

@randypanding

@randypanding randypanding commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

概要

A3(QDL YAML loader)的第一步:为全部 QDL 类型建立 YAML 序列化契约,是 loader(下一个 PR)的地基。

  • struct tag 补齐:全类型真实 yaml 标签,键名与 Intent §2.1 字段名一一对应(修复了此前标签误入注释的问题)
  • Coeff 双态编解码(Intent §2.1 Coeff = float | ParamRef):
    • 数值标量(含整数/科学计数法)→ 常量;字符串 → 参数引用
    • 映射/序列/空串引用拒绝;序列化输出规范形并可无损往返
  • Duration 双格式:ISO 8601(PT5H/P7D/P1DT12H)与 Go 原生(5h);日期单位不得越过 T、时间单位不得在 T 前;Window.Length 改用该类型
  • go-yaml v1.19.2 转直接依赖(首批依赖提案已获批,2026-08-19)

验证

  • make check 全绿(gofmt / go vet / archlint / go test -race)
  • 新增 duration_test.go、coeff_yaml_test.go:双格式解析、非法形态拒绝、往返一致性

关联 ROADMAP:Phase 0 / A3 前置。

Summary by CodeRabbit

  • 新功能

    • 新增 QDL YAML 配置加载与序列化能力,支持文件及字节数据读取。
    • 支持 $ref 引用展开、默认值补全、规范化及严格配置校验。
    • 支持 Go 与 ISO 8601 时长格式。
    • 新增参数、分布、计费、窗口、观测和溢出配置的 YAML 编解码支持。
    • 增强错误提示,并支持多种枚举值和配置约束校验。
  • 测试

    • 新增往返一致性、引用解析、错误处理及模糊测试覆盖。

- 全部 QDL 类型补齐真实 struct tag(yaml 键名与 Intent §2.1 字段名一致)
- Coeff 双态:数值标量→常量、字符串→ParamRef;空串引用与映射/序列形态拒绝
- Duration:ISO 8601(PT5H/P7D/P1DT12H,大小写不敏感、日期/时间单位越界拒绝)
  与 Go 原生时长双格式,Window.Length 改用该类型承接种子 plan 手写窗长
- go-yaml v1.19.2 转直接依赖(首批依赖提案已获批)
@socket-security

socket-security Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Review the following changes in direct dependencies. Learn more about Socket for GitHub.

Diff Package Supply Chain
Security
Vulnerability Quality Maintenance License
Addedhub.lumenfield.work/​goccy/​go-yaml@​v1.19.299100100100100

View full report

@coderabbitai

coderabbitai Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Review Change Stack

Caution

Review failed

The pull request is closed.

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d0b88d24-de20-4848-a80b-23be29d999a7

📥 Commits

Reviewing files that changed from the base of the PR and between 2ff893b and 3d48a3f.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (19)
  • CHANGELOG.md
  • go.mod
  • internal/qdl/bucket.go
  • internal/qdl/channel.go
  • internal/qdl/charge.go
  • internal/qdl/coeff_yaml_test.go
  • internal/qdl/duration.go
  • internal/qdl/duration_test.go
  • internal/qdl/enums.go
  • internal/qdl/loader.go
  • internal/qdl/loader_test.go
  • internal/qdl/obs.go
  • internal/qdl/param.go
  • internal/qdl/plan.go
  • internal/qdl/plan_test.go
  • internal/qdl/quantize.go
  • internal/qdl/scope.go
  • internal/qdl/testdata/golden.qdl.yaml
  • internal/qdl/window.go

📝 Walkthrough

Walkthrough

新增 QDL YAML 类型系统和加载器。实现字段映射、自定义时长与系数编解码、默认值规范化、枚举校验、$ref 展开、序列化往返及 fuzz 测试。

Changes

QDL YAML 契约与编解码

Layer / File(s) Summary
YAML 字段与自定义编解码
go.mod, internal/qdl/*.go, internal/qdl/coeff_yaml_test.go, internal/qdl/duration_test.go
为 QDL 结构体增加 YAML 标签。新增 Duration、Coeff 编解码,以及窗口、计费、观测和量化配置的默认值处理。
枚举与计划校验
internal/qdl/enums.go, internal/qdl/param.go, internal/qdl/plan.go
新增枚举闭集校验、分布参数校验,以及 PlanSpec 参数先验、后验和边界顺序校验。
加载、引用展开与序列化
internal/qdl/loader.go, internal/qdl/loader_test.go, internal/qdl/testdata/golden.qdl.yaml, CHANGELOG.md
新增文件和字节加载、严格解码、默认值规范化、文档内 $ref 深拷贝展开及 PlanSpec 序列化。测试覆盖错误处理、往返稳定性、引用链和 fuzz 输入。

Possibly related PRs

Suggested labels: security, feature

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/qdl-loader

Comment @coderabbitai help to get the list of available commands.

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

建立 QDL YAML 序列化契约与双态标量编解码

✨ Enhancement 🧪 Tests ⚙️ Configuration changes 🕐 20-40 Minutes

Grey Divider

AI Description

• 为全部 QDL 结构定义与 Intent 一致的 YAML 字段契约。
• 支持 Coeff 常量、参数引用双态编解码并拒绝非法形态。
• 支持 ISO 8601、Go 时长解析、规范输出及往返测试。
Diagram

graph TD
  A["QDL YAML"] --> B["go-yaml"] --> C["Struct Tags"] --> D["PlanSpec Graph"]
  B --> E["Coeff Codec"] --> D
  B --> F["Duration Codec"] --> G["Window Length"] --> D
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. 采用专用 ISO 8601 时长库
  • ➕ 可获得更完整的标准语法覆盖
  • ➕ 减少自定义解析器的维护和边界风险
  • ➖ 引入额外第三方依赖及供应链审查成本
  • ➖ 完整日历时长语义超出 QDL 当前固定时长需求
  • ➖ 年、月到固定纳秒的转换仍需定义领域策略
2. 仅接受 Go 原生时长
  • ➕ 直接复用标准库,实现和维护成本最低
  • ➕ 不存在 ISO 日期与时间单位的歧义
  • ➖ 无法直接加载 Intent 和种子计划中的 ISO 8601 写法
  • ➖ 降低手写 QDL 与外部规范的兼容性

Recommendation: 保留当前方案:goccy/go-yaml 的扩展接口适合承载 Coeff 和 Duration 契约,而受控的 ISO 8601 子集足以覆盖种子计划且避免新增依赖。应继续明确年、月采用名义天数的领域语义,并在后续 loader 集成测试中覆盖完整 PlanSpec。

Files changed (15) +437 / -141

Enhancement (10) +277 / -139
bucket.go定义额度桶 YAML 字段映射 +16/-16

定义额度桶 YAML 字段映射

• 为 OverflowStep 和 Bucket 的全部字段补充与 QDL 契约一致的 snake_case YAML 标签。

internal/qdl/bucket.go

channel.go定义通道模型 YAML 字段映射 +30/-30

定义通道模型 YAML 字段映射

• 为可靠性、伪装配置、模型绑定、准入策略及通道结构补充完整 YAML 标签。

internal/qdl/channel.go

charge.go定义扣减规则 YAML 字段映射 +10/-10

定义扣减规则 YAML 字段映射

• 为 Term 和 ChargeRule 的固定扣减、加权项、倍率、下限及量化字段建立 YAML 契约。

internal/qdl/charge.go

duration.go新增双格式 QDL 时长类型 +113/-0

新增双格式 QDL 时长类型

• 新增 Duration YAML 类型,支持 ISO 8601 子集与 Go 原生时长解析,并规范输出 Go 时长字符串。解析器校验日期和时间单位相对 T 分隔符的位置,并按名义天数换算年、月。

internal/qdl/duration.go

obs.go定义观测绑定 YAML 字段映射 +12/-12

定义观测绑定 YAML 字段映射

• 为观测量化配置及数据源、定位器、可信度、认证和轮询字段补充 YAML 标签。

internal/qdl/obs.go

param.go实现参数模型与 Coeff YAML 契约 +46/-21

实现参数模型与 Coeff YAML 契约

• 为参数分布、漂移状态和 Parameter 补充完整 YAML 标签。实现 Coeff 的数值常量或字符串参数引用双态编解码,并拒绝空引用及非标量形态。

internal/qdl/param.go

plan.go定义顶层计划 YAML 字段映射 +30/-30

定义顶层计划 YAML 字段映射

• 为风险档案、额度授予、标度规范及 PlanSpec 顶层字段建立与 Intent 对齐的 YAML 键名。

internal/qdl/plan.go

quantize.go定义量化规则 YAML 字段映射 +2/-2

定义量化规则 YAML 字段映射

• 为 Quantize 的模式和步长字段补充 YAML 标签。

internal/qdl/quantize.go

scope.go定义额度作用域 YAML 字段映射 +8/-8

定义额度作用域 YAML 字段映射

• 为 Scope 的层级、模型、通道、端点、共享池及跨产品字段补充 snake_case YAML 标签。

internal/qdl/scope.go

window.go让窗口长度支持双格式 YAML 时长 +10/-10

让窗口长度支持双格式 YAML 时长

• 为 Window 全部字段补充 YAML 标签,并将 Length 从 time.Duration 改为 qdl.Duration。窗口长度因此可接受 ISO 8601 和 Go 原生时长格式。

internal/qdl/window.go

Tests (3) +156 / -1
coeff_yaml_test.go验证 Coeff 双态 YAML 契约 +74/-0

验证 Coeff 双态 YAML 契约

• 覆盖数值、整数和科学计数法常量以及字符串参数引用的解码。验证映射、序列、空引用拒绝及序列化往返一致性。

internal/qdl/coeff_yaml_test.go

duration_test.go覆盖时长解析与 YAML 往返 +81/-0

覆盖时长解析与 YAML 往返

• 验证 ISO 8601、Go 原生及大小写变体的解析结果,并覆盖非法单位和分隔位置。另验证 Duration 字段解码、规范序列化和无损往返。

internal/qdl/duration_test.go

plan_test.go适配 Window Length 新时长类型 +1/-1

适配 Window Length 新时长类型

• 将有效计划夹具的窗口长度从 time.Duration 调整为新增的 qdl.Duration 包装类型。

internal/qdl/plan_test.go

Other (2) +4 / -1
go.mod引入 QDL YAML 解析依赖 +2/-0

引入 QDL YAML 解析依赖

• 将 github.com/goccy/go-yaml v1.19.2 声明为直接依赖,为 QDL YAML 编解码提供基础能力。

go.mod

go.sum锁定 go-yaml 依赖校验和 +2/-1

锁定 go-yaml 依赖校验和

• 记录 goccy/go-yaml v1.19.2 模块及其 go.mod 的完整性校验和。

go.sum

@qodo-code-review

qodo-code-review Bot commented Aug 19, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (4) 📜 Skill insights (0)

Grey Divider


Action required

1. Negative window lengths accepted 🐞 Bug ≡ Correctness
Description
ParseDuration sends non-P input directly to time.ParseDuration, so YAML such as length: -5h
decodes successfully even though a window length cannot be negative. PlanSpec.Validate does not
inspect Window.Length, allowing the invalid value to reach downstream window logic.
Code

internal/qdl/duration.go[R37-40]

+	if len(s) > 0 && (s[0] == 'P' || s[0] == 'p') {
+		return parseISODuration(s)
+	}
+	return time.ParseDuration(s)
Evidence
The new YAML type stores whatever ParseDuration returns, and its non-ISO branch has no sign check.
The plan validator validates candidate presence but contains no Window.Length check, while the
tests reject only the ISO negative spelling.

internal/qdl/duration.go[21-32]
internal/qdl/duration.go[35-40]
internal/qdl/plan.go[128-165]
internal/qdl/duration_test.go[38-40]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Reject negative durations regardless of whether they use ISO 8601 or Go syntax, so `Window.Length` cannot load as a negative interval.

## Issue Context
The ISO path checks negativity, but the Go-format path directly returns `time.ParseDuration`, which accepts values such as `-5h`. Add coverage for negative Go-format values.

## Fix Focus Areas
- internal/qdl/duration.go[35-40]
- internal/qdl/duration_test.go[38-42]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Duration overflow returns success 🐞 Bug ≡ Correctness
Description
ISO components are scaled as float64, converted directly to time.Duration, and accumulated
without bounds checks, allowing unbounded or repeated inputs to overflow the signed nanosecond count
and return an unrelated zero or positive duration. For example, the accepted P200Y200Y200Y adds
three individually representable 200-year values whose cumulative overflow wraps positive, bypassing
the final total < 0 check.
Code

internal/qdl/duration.go[R74-79]

+			total += time.Duration(n * 365 * 24 * float64(time.Hour))
+		case 'm': // 日期部分=月(名义 30 天),时间部分=分钟
+			if inTime {
+				total += time.Duration(n * float64(time.Minute))
+			} else {
+				total += time.Duration(n * 30 * 24 * float64(time.Hour))
Evidence
Input magnitudes are unbounded at parse time, while time.Duration is a finite int64 nanosecond
count; every recognized unit undergoes an unchecked float-to-time.Duration conversion followed by
total +=. The only overflow-like guard checks whether the final total is negative, so it cannot
detect conversion or addition overflow that wraps to zero or a positive value, and the tests do not
exercise the approximately 290-year representable boundary.

internal/qdl/duration.go[59-67]
internal/qdl/duration.go[74-98]
internal/qdl/duration.go[109-112]
internal/qdl/duration.go[65-99]
internal/qdl/duration.go[103-112]
internal/qdl/duration_test.go[10-43]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Reject ISO duration components and totals that cannot be represented by `time.Duration`, rather than allowing unchecked conversion or accumulation to return a wrapped duration successfully.

## Issue Context
The parser accepts unbounded magnitudes and repeated components, scales them as `float64`, converts them directly to `time.Duration`, and adds them without range checks. Validate each scaled component against the remaining `time.Duration` range before conversion and addition, reject non-finite parsed values, and do not rely on the final negative-total check; `P200Y200Y200Y` demonstrates cumulative overflow that wraps positive. Add boundary tests around the approximately 290-year representable range and tests for multi-component overflow.

## Fix Focus Areas
- internal/qdl/duration.go[65-112]
- internal/qdl/duration_test.go[10-43]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Malformed ISO durations accepted 🐞 Bug ≡ Correctness
Description
parseISODuration treats T as an optional free-standing separator and does not enforce component
order, uniqueness, or the week-only form, so malformed values such as P1DT, P1D1Y, P1D2D,
P1W1D, and PT1H1H are accepted despite the documented P[nY][nM][nW][nD][T[nH][nM][nS]]
grammar. This violates the advertised ISO 8601 serialization and loader contract by silently
normalizing malformed configuration into a different valid duration string.
Code

internal/qdl/duration.go[R53-56]

+		if body[i] == 't' && !inTime {
+			inTime = true
+			i++
+			continue
Evidence
The parser loop advances past T without requiring a following time component and checks only
whether each unit is valid on the date or time side; it tracks neither the previous unit nor
already-seen units. As a result, repeated and reordered components reach successful switch branches,
even though the stated grammar requires ordered components and ISO 8601's complete designator
representation uses either the week form or ordered year/month/day and time components.

internal/qdl/duration.go[43-56]
internal/qdl/duration.go[69-105]
internal/qdl/duration_test.go[38-42]
internal/qdl/duration.go[43-45]
internal/qdl/duration.go[52-105]
🌐 Section 4.4.3.2 specifies the complete duration representation as [PnnW] or ordered [PnnYnnMnnDTnnHnnMnnS], with T preceding time components.

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Make `parseISODuration` enforce its declared ISO 8601 grammar instead of independently summing arbitrary recognized components. It must reject a free-standing `T`, duplicate or out-of-order units, and combinations of the week form with other date components.

## Issue Context
The parser currently accepts malformed inputs including `P1DT`, `P1D1Y`, `P1D2D`, `P1W1D`, and `PT1H1H`, then normalizes them to a duration rather than rejecting them under the loader contract. Require at least one time component after `T`, reject every component that is duplicated or appears after a smaller-order component while retaining the existing date/time-side checks, enforce the week-only form, and add negative tests for each malformed shape.

## Fix Focus Areas
- internal/qdl/duration.go[43-105]
- internal/qdl/duration_test.go[10-43]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

4. PlanSpec remains directly mutable 📘 Rule violation ≡ Correctness
Description
The YAML contract decodes loaded plans into exported mutable slices such as Buckets, Channels,
Grants, and Parameters. Consumers can mutate the loaded specification directly, including
through lookup methods that return pointers to slice elements.
Code

internal/qdl/plan.go[R51-54]

+	Buckets               []Bucket         `yaml:"buckets"`
+	Channels              []Channel        `yaml:"channels"`
+	Grants                []Grant          `yaml:"grants"`
+	Parameters            []Parameter      `yaml:"parameters"`
Evidence
Rule 2795233 prohibits mutable exported fields on loaded Go PlanSpec objects. The changed YAML
fields establish direct decoding into exported slices, and the existing lookup methods expose
pointers to their underlying elements.

Rule 2795233: Loaded PlanSpec objects must be immutable (no public mutators or mutable exported fields)
internal/qdl/plan.go[41-56]
internal/qdl/plan.go[59-86]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Prevent consumers from directly mutating collections belonging to a loaded `PlanSpec`.

## Issue Context
Use a mutable YAML decoding DTO or custom unmarshalling during construction, then expose an immutable PlanSpec API. Collection accessors should return copies, and lookup methods should not return pointers into internal slices.

## Fix Focus Areas
- internal/qdl/plan.go[41-56]
- internal/qdl/plan.go[59-95]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


5. Window refs bypass validation 📘 Rule violation ≡ Correctness
Description
The newly YAML-decodable Window.RefillRate and Window.Burst coefficients are not checked against
PlanSpec.Parameters. An unresolved ParamRef in either field can therefore survive
PlanSpec.Validate.
Code

internal/qdl/window.go[R40-41]

+	RefillRate          Coeff                  `yaml:"refill_rate"`    // token_bucket:单位/秒
+	Burst               Coeff                  `yaml:"burst"`          // token_bucket:突发容量
Evidence
Rule 2795164 requires every coefficient ParamRef to resolve during PlanSpec loading or validation.
The changed window fields accept YAML coefficients, Coeff.UnmarshalYAML turns strings into
references, while the bucket validation path only resolves capacity and charge coefficients.

Rule 2795164: Validate ParamRef resolution for coefficient fields against PlanSpec.parameters
internal/qdl/window.go[40-41]
internal/qdl/param.go[115-131]
internal/qdl/plan.go[121-148]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Validate YAML-decoded `Window.RefillRate` and `Window.Burst` references against `PlanSpec.Parameters`.

## Issue Context
`Coeff.UnmarshalYAML` converts strings into parameter references, but `PlanSpec.Validate` currently validates bucket capacity and charge coefficients without validating these two window coefficients.

## Fix Focus Areas
- internal/qdl/window.go[40-41]
- internal/qdl/plan.go[121-148]
- internal/qdl/plan_test.go[1-60]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. Struct-tag fix lacks regression 📘 Rule violation ▣ Testability
Description
The PR explicitly fixes QDL YAML tags that were previously ineffective, but no test decodes or
encodes the actual tagged QDL structures. The added YAML tests use local holder structs, so they
would not fail if the production struct-tag fixes were removed.
Code

internal/qdl/plan.go[R45-48]

+	PriceUSDPerPeriod     float64          `yaml:"price_usd_per_period"`
+	Period                string           `yaml:"period"` // month | year | week | one_off
+	SpecVersion           string           `yaml:"spec_version"`
+	VendorDocSnapshotHash string           `yaml:"vendor_doc_snapshot_hash"` // 页面语义 diff 用
Evidence
Rule 2787558 requires a test that fails against the prior buggy implementation. The production tag
changes cover actual QDL structures, whereas the added decoding tests declare synthetic holder
structs with their own tags and therefore do not exercise the corrected production tags.

Rule 2787558: Bug fix PRs must add a failing regression test
internal/qdl/plan.go[41-56]
internal/qdl/coeff_yaml_test.go[9-18]
internal/qdl/duration_test.go[45-53]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Add a regression test that exercises the corrected YAML tags on actual QDL model types.

## Issue Context
The PR description identifies ineffective struct tags as a bug fix. Construct representative snake_case YAML for `PlanSpec` and nested QDL types, decode it strictly, and assert the corresponding production fields; the test must fail when the tag changes are reverted.

## Fix Focus Areas
- internal/qdl/plan.go[41-56]
- internal/qdl/plan_test.go[1-60]
- internal/qdl/coeff_yaml_test.go[9-34]
- internal/qdl/duration_test.go[45-59]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View medium (1)
7. Non-gauge parameters allow freezing 📘 Rule violation ≡ Correctness
Description
The new frozen YAML contract accepts Frozen: true for non-gauge parameter provenance because
validation rejects only vendor_doc. Parameters sourced from vendor_api, estimated, or
assumed can therefore violate the gauge-only restriction.
Code

internal/qdl/param.go[R73-74]

+	SnapCandidates []float64   `yaml:"snap_candidates"`
+	Frozen         bool        `yaml:"frozen"` // gauge 锚定参数不再更新
Evidence
Rule 2795209 permits freezing only gauge-anchored parameters. The changed Frozen field is exposed
as yaml:"frozen", while the sole validation condition rejects frozen parameters only when
provenance equals vendor_doc, leaving all other non-gauge provenance values accepted.

Rule 2795209: Only gauge-anchored parameters may be frozen
internal/qdl/param.go[8-17]
internal/qdl/param.go[69-74]
internal/qdl/plan.go[107-120]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Reject every frozen parameter whose provenance is not `gauge`.

## Issue Context
The model documents `gauge` as the only provenance allowed to be frozen, but validation currently rejects only the `vendor_doc` combination. Add coverage for all non-gauge provenance values decoded through YAML.

## Fix Focus Areas
- internal/qdl/param.go[8-17]
- internal/qdl/param.go[69-74]
- internal/qdl/plan.go[107-120]
- internal/qdl/plan_test.go[45-55]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Context sources
✅ Compliance rules (platform): 16 rules
✅ Web pages:
  +7 more
Review mode: 🧠 Deep: 该 PR 同时引入 Coeff 双态编解码、ISO/Go 时长解析及全类型 YAML 标签,覆盖多个独立路径和大量编辑点,存在较高的隐蔽契约与边界缺陷密度,冗余审查有明显价值。

Grey Divider

Tip of the day
💡 Did you know, you can show, collapse, or hide each part of a finding: code, evidence, and all

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

Comment thread internal/qdl/window.go Outdated
Comment on lines +40 to +41
RefillRate Coeff `yaml:"refill_rate"` // token_bucket:单位/秒
Burst Coeff `yaml:"burst"` // token_bucket:突发容量

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

1. Window refs bypass validation 📘 Rule violation ≡ Correctness

The newly YAML-decodable Window.RefillRate and Window.Burst coefficients are not checked against
PlanSpec.Parameters. An unresolved ParamRef in either field can therefore survive
PlanSpec.Validate.
Agent Prompt
## Issue description
Validate YAML-decoded `Window.RefillRate` and `Window.Burst` references against `PlanSpec.Parameters`.

## Issue Context
`Coeff.UnmarshalYAML` converts strings into parameter references, but `PlanSpec.Validate` currently validates bucket capacity and charge coefficients without validating these two window coefficients.

## Fix Focus Areas
- internal/qdl/window.go[40-41]
- internal/qdl/plan.go[121-148]
- internal/qdl/plan_test.go[1-60]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread internal/qdl/param.go Outdated
Comment on lines +73 to +74
SnapCandidates []float64 `yaml:"snap_candidates"`
Frozen bool `yaml:"frozen"` // gauge 锚定参数不再更新

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

2. Non-gauge parameters allow freezing 📘 Rule violation ≡ Correctness

The new frozen YAML contract accepts Frozen: true for non-gauge parameter provenance because
validation rejects only vendor_doc. Parameters sourced from vendor_api, estimated, or
assumed can therefore violate the gauge-only restriction.
Agent Prompt
## Issue description
Reject every frozen parameter whose provenance is not `gauge`.

## Issue Context
The model documents `gauge` as the only provenance allowed to be frozen, but validation currently rejects only the `vendor_doc` combination. Add coverage for all non-gauge provenance values decoded through YAML.

## Fix Focus Areas
- internal/qdl/param.go[8-17]
- internal/qdl/param.go[69-74]
- internal/qdl/plan.go[107-120]
- internal/qdl/plan_test.go[45-55]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread internal/qdl/plan.go Outdated
Comment on lines +51 to +54
Buckets []Bucket `yaml:"buckets"`
Channels []Channel `yaml:"channels"`
Grants []Grant `yaml:"grants"`
Parameters []Parameter `yaml:"parameters"`

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

3. Planspec remains directly mutable 📘 Rule violation ≡ Correctness

The YAML contract decodes loaded plans into exported mutable slices such as Buckets, Channels,
Grants, and Parameters. Consumers can mutate the loaded specification directly, including
through lookup methods that return pointers to slice elements.
Agent Prompt
## Issue description
Prevent consumers from directly mutating collections belonging to a loaded `PlanSpec`.

## Issue Context
Use a mutable YAML decoding DTO or custom unmarshalling during construction, then expose an immutable PlanSpec API. Collection accessors should return copies, and lookup methods should not return pointers into internal slices.

## Fix Focus Areas
- internal/qdl/plan.go[41-56]
- internal/qdl/plan.go[59-95]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread internal/qdl/plan.go
Comment on lines +45 to +48
PriceUSDPerPeriod float64 `yaml:"price_usd_per_period"`
Period string `yaml:"period"` // month | year | week | one_off
SpecVersion string `yaml:"spec_version"`
VendorDocSnapshotHash string `yaml:"vendor_doc_snapshot_hash"` // 页面语义 diff 用

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

4. Struct-tag fix lacks regression 📘 Rule violation ▣ Testability

The PR explicitly fixes QDL YAML tags that were previously ineffective, but no test decodes or
encodes the actual tagged QDL structures. The added YAML tests use local holder structs, so they
would not fail if the production struct-tag fixes were removed.
Agent Prompt
## Issue description
Add a regression test that exercises the corrected YAML tags on actual QDL model types.

## Issue Context
The PR description identifies ineffective struct tags as a bug fix. Construct representative snake_case YAML for `PlanSpec` and nested QDL types, decode it strictly, and assert the corresponding production fields; the test must fail when the tag changes are reverted.

## Fix Focus Areas
- internal/qdl/plan.go[41-56]
- internal/qdl/plan_test.go[1-60]
- internal/qdl/coeff_yaml_test.go[9-34]
- internal/qdl/duration_test.go[45-59]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread internal/qdl/duration.go
Comment on lines +37 to +40
if len(s) > 0 && (s[0] == 'P' || s[0] == 'p') {
return parseISODuration(s)
}
return time.ParseDuration(s)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

5. Negative window lengths accepted 🐞 Bug ≡ Correctness

ParseDuration sends non-P input directly to time.ParseDuration, so YAML such as length: -5h
decodes successfully even though a window length cannot be negative. PlanSpec.Validate does not
inspect Window.Length, allowing the invalid value to reach downstream window logic.
Agent Prompt
## Issue description
Reject negative durations regardless of whether they use ISO 8601 or Go syntax, so `Window.Length` cannot load as a negative interval.

## Issue Context
The ISO path checks negativity, but the Go-format path directly returns `time.ParseDuration`, which accepts values such as `-5h`. Add coverage for negative Go-format values.

## Fix Focus Areas
- internal/qdl/duration.go[35-40]
- internal/qdl/duration_test.go[38-42]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread internal/qdl/duration.go
Comment on lines +53 to +56
if body[i] == 't' && !inTime {
inTime = true
i++
continue

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

6. Malformed iso durations accepted 🐞 Bug ≡ Correctness

parseISODuration treats T as an optional free-standing separator and does not enforce component
order, uniqueness, or the week-only form, so malformed values such as P1DT, P1D1Y, P1D2D,
P1W1D, and PT1H1H are accepted despite the documented P[nY][nM][nW][nD][T[nH][nM][nS]]
grammar. This violates the advertised ISO 8601 serialization and loader contract by silently
normalizing malformed configuration into a different valid duration string.
Agent Prompt
## Issue description
Make `parseISODuration` enforce its declared ISO 8601 grammar instead of independently summing arbitrary recognized components. It must reject a free-standing `T`, duplicate or out-of-order units, and combinations of the week form with other date components.

## Issue Context
The parser currently accepts malformed inputs including `P1DT`, `P1D1Y`, `P1D2D`, `P1W1D`, and `PT1H1H`, then normalizes them to a duration rather than rejecting them under the loader contract. Require at least one time component after `T`, reject every component that is duplicated or appears after a smaller-order component while retaining the existing date/time-side checks, enforce the week-only form, and add negative tests for each malformed shape.

## Fix Focus Areas
- internal/qdl/duration.go[43-105]
- internal/qdl/duration_test.go[10-43]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Comment thread internal/qdl/duration.go
Comment on lines +74 to +79
total += time.Duration(n * 365 * 24 * float64(time.Hour))
case 'm': // 日期部分=月(名义 30 天),时间部分=分钟
if inTime {
total += time.Duration(n * float64(time.Minute))
} else {
total += time.Duration(n * 30 * 24 * float64(time.Hour))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Action required

7. Duration overflow returns success 🐞 Bug ≡ Correctness

ISO components are scaled as float64, converted directly to time.Duration, and accumulated
without bounds checks, allowing unbounded or repeated inputs to overflow the signed nanosecond count
and return an unrelated zero or positive duration. For example, the accepted P200Y200Y200Y adds
three individually representable 200-year values whose cumulative overflow wraps positive, bypassing
the final total < 0 check.
Agent Prompt
## Issue description
Reject ISO duration components and totals that cannot be represented by `time.Duration`, rather than allowing unchecked conversion or accumulation to return a wrapped duration successfully.

## Issue Context
The parser accepts unbounded magnitudes and repeated components, scales them as `float64`, converts them directly to `time.Duration`, and adds them without range checks. Validate each scaled component against the remaining `time.Duration` range before conversion and addition, reject non-finite parsed values, and do not rely on the final negative-total check; `P200Y200Y200Y` demonstrates cumulative overflow that wraps positive. Add boundary tests around the approximately 290-year representable range and tests for multi-component overflow.

## Fix Focus Areas
- internal/qdl/duration.go[65-112]
- internal/qdl/duration_test.go[10-43]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

LoadBytes 四段管线:泛型树 $ref 展开(JSON pointer 扩展,数组段支持下标
与 id 匹配,深拷贝防共享,深度上限防环)→ goccy 严格解码 → normalizeDefaults
缺省回填 → PlanSpec.Validate(安全契约唯一执法点)。

- Quantize/分布缺省:goccy 对键缺失字段不调用自定义 unmarshaler,
  缺省统一在 normalizeDefaults 补齐(mode=none/step=1),保证往返稳定
- 类别型离散分布:probs+categories 书写形态归一到 CategoryProbs
- 全 slice/map 字段 omitempty:消除 nil vs empty 的往返差
- 测试:黄金样本抽查、往返等价、负面用例 10 项、$ref 错误专列、
  链式引用、fuzz(往返不变量)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant