Skip to content

fix(relayconvert): OpenAIResponsesResponse.response.created_at unmarshal error - #6165

Open
Windfarer wants to merge 2 commits into
QuantumNous:mainfrom
Windfarer:fix/responses-created-at-float
Open

Windfarer wants to merge 2 commits into
QuantumNous:mainfrom
Windfarer:fix/responses-created-at-float

Conversation

@Windfarer

@Windfarer Windfarer commented Jul 13, 2026 •

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

经过/v1/responses的请求报错,相关报错信息如下

json: cannot unmarshal number 1783440046.0 into Go struct field OpenAIResponsesResponse.response.created_at of type int
json: cannot unmarshal number 1783440046.0 into Go struct field OpenAIResponsesResponse.response.created_at of type int
json: cannot unmarshal number 1783440046.0 into Go struct field OpenAIResponsesResponse.response.created_at of type int

📝 变更描述 / Description

上游返回的created_at时间存在小数的情况,导致反序列化失败报错,本PR把created_at统一为int64,截断到整数秒,解决了类型反序列化错误。本次变更覆盖了/v1/responses、/v1/responses/compact、以及 responses<->chat 互转链路

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)

🔗 关联任务 / Related Issue

可能有关的PR #5787

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

dto/openai_responses_created_at_test.go 增加了测试用例

go test ./dto ./relay/channel/openai ./service/relayconvert/... -count=1

Summary by CodeRabbit

Summary by CodeRabbit

  • Bug Fixes

    • Improved created_at timestamp handling across responses and streams when provided as integers, decimals, numeric strings, or fractional values.
    • Added stricter validation to reject non-numeric strings and NaN/±Inf, while enforcing valid Unix-second ranges and truncating fractional seconds toward zero.
    • Standardized outgoing timestamp serialization to integer Unix seconds.
  • Tests

    • Added unit tests covering float and string unmarshalling, invalid string rejection, and a regression test for round-trip timestamp conversion.

@coderabbitai

coderabbitai Bot commented Jul 13, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

OpenAI response timestamps now use UnixTimestamp. JSON parsing supports numeric and numeric-string values, truncates fractions, validates ranges, and rejects invalid values. Conversion and streaming paths assign the new type, with parsing and round-trip tests.

Changes

Unix timestamp handling

Layer / File(s) Summary
UnixTimestamp parsing and serialization
dto/values.go
Adds UnixTimestamp with JSON parsing, integer serialization, fractional truncation, range validation, and invalid-value handling.
Response DTO timestamp contracts
dto/openai_response.go, dto/openai_compaction.go, dto/openai_responses_created_at_test.go
Changes response CreatedAt fields to UnixTimestamp and tests numeric, fractional, string, and invalid created_at values.
Conversion and stream timestamp wiring
service/relayconvert/internal/oai_chat/..., relay/channel/openai/chat_via_responses.go
Updates response conversion and stream fallback assignments to construct dto.UnixTimestamp values, with a round-trip conversion test.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: calcium-ion, seefs001

Poem

I’m a bunny with timestamps bright,
Fractions tucked away just right.
JSON hops through every gate,
Bad strings find a crunchy fate.
Responses bloom with seconds true! 🐇

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title matches the main fix: resolving created_at unmarshal failures in OpenAI responses.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

❤️ Share

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
dto/openai_responses_created_at_test.go (1)

11-64: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Tests cover the decimal-timestamp regression well; consider adding null and round-trip marshal cases.

The null → 0 path in parseUnixTimestampJSON and the MarshalJSON integer output are both untested. Adding a null case and a marshal round-trip would protect these invariants against future changes.

💡 Suggested additional test cases
// Add to the table in TestOpenAIResponsesResponseCreatedAtAcceptsFloat:
{
    name:     "integer timestamp",
    payload:  `{"id":"resp_1","object":"response","created_at":1710000000}`,
    expected: 1710000000,
},
{
    name:     "null timestamp",
    payload:  `{"id":"resp_1","object":"response","created_at":null}`,
    expected: 0,
},

// New test for MarshalJSON round-trip:
func TestUnixTimestampMarshalJSON(t *testing.T) {
    t.Parallel()
    ts := UnixTimestamp(1710000000)
    data, err := ts.MarshalJSON()
    require.NoError(t, err)
    assert.Equal(t, []byte("1710000000"), data)
}
🤖 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 `@dto/openai_responses_created_at_test.go` around lines 11 - 64, Extend
TestOpenAIResponsesResponseCreatedAtAcceptsFloat with integer and null
created_at payload cases, expecting the integer value and zero respectively. Add
TestUnixTimestampMarshalJSON to verify UnixTimestamp.MarshalJSON returns the
decimal integer representation for a known timestamp.
🤖 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 `@dto/values.go`:
- Line 120: Update the upper-bound checks in the parsing logic at both
occurrences to reject values equal to the rounded MaxInt64 boundary by using a
non-strict comparison; keep the existing lower-bound validation unchanged.

---

Nitpick comments:
In `@dto/openai_responses_created_at_test.go`:
- Around line 11-64: Extend TestOpenAIResponsesResponseCreatedAtAcceptsFloat
with integer and null created_at payload cases, expecting the integer value and
zero respectively. Add TestUnixTimestampMarshalJSON to verify
UnixTimestamp.MarshalJSON returns the decimal integer representation for a known
timestamp.
🪄 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: ec8bfc7d-f24f-401b-87ab-8214a4aba5a0

📥 Commits

Reviewing files that changed from the base of the PR and between 7c28993 and 19fba50.

📒 Files selected for processing (7)
  • dto/openai_compaction.go
  • dto/openai_response.go
  • dto/openai_responses_created_at_test.go
  • dto/values.go
  • relay/channel/openai/chat_via_responses.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_resp.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go

Comment thread dto/values.go Resolved
@Windfarer Windfarer changed the title fix: support float created_at in responses payloads fix(relayconvert): support float created_at in responses payloads Jul 13, 2026
@Windfarer
Windfarer force-pushed the fix/responses-created-at-float branch from 19fba50 to 5178bcf Compare July 13, 2026 09:25

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 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 `@service/relayconvert/internal/oai_chat/to_oai_responses_resp.go`:
- Around line 216-221: Update the string parsing branch in the timestamp
conversion logic to distinguish a successfully parsed Unix timestamp of zero
from parse failure. Replace the `common.String2Int`/`parsed != 0` check with an
error-aware parse or equivalent success indicator, returning
`dto.UnixTimestamp(0)` for valid `"0"` input while retaining the current-time
fallback only for invalid values.
- Around line 208-215: Validate float64 and float32 inputs in the timestamp
conversion switch before passing them to dto.UnixTimestamp, rejecting NaN,
infinities, and values outside the supported timestamp range. Preserve the
existing direct conversions for valid finite values and the int/int64 cases.
🪄 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: 55a79db6-c213-4466-b64a-322f5171f948

📥 Commits

Reviewing files that changed from the base of the PR and between 19fba50 and 5178bcf.

📒 Files selected for processing (8)
  • dto/openai_compaction.go
  • dto/openai_response.go
  • dto/openai_responses_created_at_test.go
  • dto/values.go
  • relay/channel/openai/chat_via_responses.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_resp.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_resp_test.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go
🚧 Files skipped from review as they are similar to previous changes (6)
  • dto/openai_compaction.go
  • service/relayconvert/internal/oai_chat/to_oai_responses_stream_resp.go
  • dto/openai_response.go
  • relay/channel/openai/chat_via_responses.go
  • dto/openai_responses_created_at_test.go
  • dto/values.go

@Windfarer
Windfarer force-pushed the fix/responses-created-at-float branch from 22bb372 to aa85f26 Compare July 14, 2026 02:08
@Windfarer
Windfarer force-pushed the fix/responses-created-at-float branch from aa85f26 to 772e2c2 Compare July 14, 2026 02:10
@Windfarer Windfarer changed the title fix(relayconvert): support float created_at in responses payloads fix(relayconvert): OpenAIResponsesResponse.response.created_at unmarshal error Jul 14, 2026
JacksonsY added a commit to JacksonsY/new-api that referenced this pull request Jul 19, 2026
移植自上游 PR QuantumNous#6165。OpenAIResponsesResponse/CompactionResponse
的 created_at 是 int,上游返回 1783476848.2598 这类浮点值时整条
响应解析失败。新增 dto.UnixTimestamp 类型(接受 int/float/string,
截断取整,含 NaN/Inf/越界防护),替换两个响应结构的 CreatedAt,
chatCreatedAt 同步改造并加 UnixTimestamp 分支处理进程内往返。

与原 PR 差异:UnixTimestamp 的 Unmarshaler 沿用 dto/values.go 的
encoding/json(该文件是围绕 json.Number 的自定义 Unmarshaler 适配层,
属项目既有例外),与文件内 StringValue/IntValue/BoolValue 一致,
不引入 dto→common 依赖。补 dto 层解析测试与转换往返测试。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@Calcium-Ion
Calcium-Ion force-pushed the main branch 2 times, most recently from 51fdfc5 to 2b6f1df Compare August 30, 2026 15:03

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant