new-api icon indicating copy to clipboard operation
new-api copied to clipboard

[Feature] Native atomic async-task settlement/refund and recovery after terminal CAS

Open iamluxe77 opened this issue 1 month ago • 1 comments

Read This First

  • Docs: https://docs.newapi.ai/
  • Usage questions first: https://deepwiki.com/QuantumNous/new-api
  • Do not report issues when pass-through is enabled; pass-through sends content as-is and does not go through new-api processing logic.
  • State facts and evidence concisely. Do not paste unfiltered AI-generated text in the issue body or in later comments.
  • Reports about Coding Plan services, reverse-engineered channels, third-party API wrappers, or compatibility issues caused by exposing a Codex endpoint through a reverse proxy as a general-purpose API are not accepted. Protocols or behavior specific to the Codex API should not be treated as standard OpenAI API behavior; confirm such issues with the channel or API provider first.
  • This project does not provide official hosting and does not support third-party hosting sites, relays, or API services; contact their operator instead.
  • Warning: issues with this template removed, section headings deleted, or content cleared may be closed directly. Repeated submissions of unfiltered AI-generated text, or repeated abusive submissions, may result in a block.

Your current newapi version

Official self-hosted v1.0.0-rc.41@sha256:3293fc3d13bbf243ae720d9c4e0b8049e8ed01f5c130d3bdcdad8a1a2c7e57ed. Source review также охватывает rc.43 c6741c36a9a1a729554ad94ee99f21602a214a23.

Submission Checks

  • [x] Non-duplicate issue: поиск Issues/PR и ближайшие совпадения перечислены в Duplicate check; полный recovery-контракт ими не закрыт.
  • [x] Read this first: рассмотрены официальные docs/README/plugin API и код; это новый контракт, не настройка. DeepWiki сейчас HTTP429, primary source указан.
  • [x] Supported version: запрос относится к неизменённому официальному rc.41; rc.43 дополнительно проверен по исходникам.
  • [x] Not a third-party service: запрос о штатных task/billing механизмах New API, не о стороннем сервисе или форке.
  • [x] Not pass-through: forwarding/pass-through defect не заявлен.
  • [x] Channel and protocol boundary: не Coding Plan, reverse-engineered API, wrapper либо Codex proxy; отдельный supplier dialect не нужен.
  • [x] Template intact: сохранены поля Feature Request и все разделы agent-only .agents/github/ISSUE.md, включая точную цитату владельца.
  • [x] Maintainer time: факты и ограничения отделены от желаемой гарантии; implementation dump не предлагается.

Feature Description

Native atomic/idempotent settlement/refund и recovery terminal async tasks. В rc.43 service/task_polling.go:608 фиксирует terminal CAS до :626 financial finalization; model/task.go:384 исключает terminal tasks после restart. Source fixture воспроизводит это окно; production потери не заявляются.

Use Case

Перезапуск worker или DB failure не должны оставлять завершённую генерацию без окончательных финансов и не должны требовать повторного paid submit/refund. Просим сначала согласовать поддержанный native контракт, без PR до согласования.

Agent

  • Tool: Codex
  • Tool version: runtime session metadata 0.162.0-alpha.17.2
  • Model (full id): gpt-6.1-sol (session metadata)
  • Host (CLI / IDE / GitHub coding agent / other): Codex desktop, local executor
  • Date (UTC): 2026-10-11

User request

  • Verbatim: «Ты можешь им issues накатать чего не хватает в движке для нас?»
  • Later constraints or corrections from the user (quote, or none): none. Действующее ограничение владельца: «Движок не менять, чужой WIP сохранять.»

Out of scope — refuse

  • Matched: no. Запрос о штатном lifecycle New API Task и native quota, не о поставщике, wrapper, pass-through или протоколе Codex.
  • If yes, what was told to the user (stop here; do not file): не применимо.

File gate — do not file unless all are satisfied

  • Out of scope (including pass-through): no.
  • Usage / configuration / integration (answered instead of filing): no; требуется новый host recovery-контракт.
  • Required facts present without invention (actual behavior, impact, frequency, evidence in new-api, applicable type fields): yes; source и изолированная fixture, ограничения ниже.
  • Body is short and factual; no unfiltered AI-generated text: yes; только относящиеся к этому контракту факты.
  • File: yes.
  • If no, what was told to the user (stop here): не применимо.

Kind

  • [ ] Bug
  • [x] Feature
  • [ ] Investigation
  • [ ] Other:

Usage / configuration / integration check

  • https://docs.newapi.ai/ — прочитана документация deployment/settings и Task Plugin; batch OFF не объединяет task/funding/token в транзакцию.
  • https://deepwiki.com/QuantumNous/new-api — попытка актуального чтения 11.10 вернула HTTP429; вывод основан на первичном коде и plugin API, не на недоступной странице.
  • README / repo docs: README разделы Asynchronous tasks/Task plugins, docs/plugin-api/v1.md, .agents/rules/billing.md.
  • Relevant code paths and conclusion: terminal CAS предшествует отдельным финансовым операциям; recovery query исключает terminal rows.
  • Can the current version already do this? (required for feature requests): в проверенных rc.41, rc.43 и main нет этого общего контракта.
  • Verdict: new feature; maintainer alignment до PR.

Environment

  • new-api version / commit / image tag (not latest / unknown): deployed v1.0.0-rc.41@sha256:3293fc3d13bbf243ae720d9c4e0b8049e8ed01f5c130d3bdcdad8a1a2c7e57ed; source 2035a82aeb5414253a728bd937d4b8f97aa99b9b. Дополнительно проверены rc.43 c6741c36a9a1a729554ad94ee99f21602a214a23 и main 0f38a14a5e8e322ea741478b0e49878be3130e1d.
  • Deploy source (repo release / official image / main source / other): неизменённый официальный docker.io/calciumion/new-api; собственный engine не используется.
  • Database (sqlite / mysql / postgres): production PostgreSQL + Redis; описанная isolated fixture — SQLite, cache OFF.

Problem facts

  • Actual behavior: polling сохраняет SUCCESS/FAILURE через CAS до settlement/refund; после restart обычная eligibility query не выбирает такую строку.
  • Impact: остановка между этими шагами может оставить завершённую генерацию без окончательной доплаты/возврата. Частичный settlement нельзя безопасно восстановить по одной старой task quota.
  • Frequency: зависит от fault point. В сохранённой synthetic fixture воспроизведены оба terminal случая; частота реальных клиентских потерь не измерена и не заявляется.
  • Evidence that the problem is in new-api rather than the client or upstream: порядок операций и selection находятся в штатных service/model; supplier error для этого сценария не нужен.

Type-specific details

Relay / API

  • Не применимо: это native task recovery feature, не отчёт об API forwarding. Новые upstream generation requests для исследования не отправлялись.

Billing

  • Request endpoint and model: synthetic native async Task без supplier POST; выбранный provider/model не является причиной запроса.
  • Response usage: fixture completion facts seconds=4, reference_seconds=6; это тестовые факты, не живой usage клиента.
  • Relevant ratio or pricing configuration: frozen tier("video", u("seconds") + u("reference_seconds")), quotaPerUnit1000, GroupRatio1; reserve4000, final10000. Тестовая конфигурация, не рекомендация ставок.
  • Consumption log: после остановки сразу за terminal CAS финальный adjustment/refund log отсутствует; обычный restart task не выбирает.
  • Expected charge and calculation basis: SUCCESS должен довести сумму до10000 один раз; FAILURE — вернуть reserve4000 один раз. Funding/token/task/counters должны согласоваться.

Frontend

  • Не применимо: UI не изменяется и не является источником этого требования.

Deployment / upgrade

  • Не применимо как upgrade report: deployed официальный rc.41, Linux/amd64, PostgreSQL; rc.43 не установлен, migration/startup результаты не заявляются.

Reproduction and expected result

  • Steps to reproduce: изолированная source fixture с synthetic native reservation останавливает дочерний процесс os.Exit(91) в test-only GORM callback сразу после committed terminal task update; новый процесс вызывает настоящую GetAllUnFinishSyncTasks. SUCCESS/FAILURE не выбраны, quota остаётся4000, финального журнала нет; IN_PROGRESS контроль восстанавливается.
  • Expected result: durable financial intent остаётся доступным recovery независимо от generation status; replay не делает второй debit/refund.
  • Related screenshots (optional): отсутствуют.

Feature (feature requests only)

  • Feature description: native идемпотентное financial completion и recovery для terminal async tasks, включая условное funding/token изменение, durable completion marker и результат commit.
  • Use case: рестарт worker или transient DB failure не должны требовать новой платной генерации либо ручного повторного refund.

Duplicate check

  • Search queries (issues, PRs, discussions): Issues/PR: atomic task, terminal CAS, task billing, 任务 退款, settlement, outbox; подходящего совпадения полного контракта не найдено. Отдельный поиск Discussions не выполнялся.
  • Closest existing threads: #7657, #4211, #6754, #6795, #6366, #6201.
  • Why this is not a duplicate: #7657 — tail batch/shutdown flush; #4211/#6754/#6795 — usage counters после refund; #6366 — исторический image billing/Redis compensation. Закрытый #6201 прямо оставляет terminal CAS и billing side effects вне одной durable transaction. Здесь нужен recovery между terminal commit и финальным billing.

Research

Docs

  • https://docs.newapi.ai/ : настройки batch/Redis и штатные task plugins; конфигурационная настройка атомарного completion не установлена.
  • https://deepwiki.com/QuantumNous/new-api : HTTP429 при актуальном чтении, не использован как доказательство.
  • README / other repo docs: Task Plugin API, billing rules.
  • Conclusions: JS usage hooks не являются SQL transaction/recovery hooks.

Code

Experiments

  • Command or redacted request: ранее выполненная source test-only overlay go test -race -p 1 -overlay=<test-overlay> ./service -run '^TestSeedanceNativeProcessRecoveryBoundary$' -count=1 -timeout=120s -v; synthetic SQLite reservation, процесс остановлен exit91 после committed status. Здесь fixture повторно не запускалась.
  • Direct upstream result: не применимо; supplier HTTP не используется.
  • Result through new-api: SUCCESS и FAILURE остаются terminal с quota4000 и без final billing log; fresh-process eligibility выбирает0.
  • Conclusion: это воспроизведение stock completion ordering в source fixture, не официальный image/PostgreSQL/Redis fault acceptance и не подтверждение live потери клиента.

Working theory

  • What is broken or missing: durable checkpoint общего financial completion и recovery terminal rows.
  • Why: generation CAS завершается раньше отдельных side effects.
  • What would falsify this: доступный официальный handler, который восстанавливает эти terminal financial intents с доказанной идемпотентностью и атомарностью.

Scope

  • In scope for a later PR: общий native task settlement/refund/recovery контракт; SQLite/MySQL/PostgreSQL и current Redis/log topology должны иметь явные гарантии.
  • Out of scope / not this repo: provider pricing, повтор supplier POST, ручное исправление клиентских балансов.
  • Large or directional feature? If yes, this issue is for maintainer alignment; do not open a PR yet: да, сначала согласование поддержанного контракта.

Proposed direction

Financial pending переживает restart; partial writes либо откатываются, либо завершаются общим commit. Один task/evidence даёт один debit/refund. Terminal generation не удаляет financial recovery из selection; Redis и отдельная LOG_DB имеют явный recovery-контракт, а не объявляются участниками SQL transaction.

Not verified

Новый fix не реализован; rc.43 image, реальный SIGKILL/OOM в production, MySQL и PostgreSQL/Redis crash matrix этим source experiment не проверены. Batch OFF и успешный обычный цикл не считаются полным recovery доказательством.

Related

iamluxe77 avatar Oct 11 '26 05:10 iamluxe77

[Bot Review]

感谢您的提交。我们发现该 Issue 并未使用项目提供的标准模板。为了帮助我们更高效地定位和处理问题,请使用官方提供的 Bug Report 或 Feature Request 模板重新提交,并确保填写完整必需的字段。谢谢您的配合!