Commit Graph

1957 Commits (de2dfd3034a7b506fa269910401bbdcbd4efc71d)

Author SHA1 Message Date
Wen.Vale de2dfd3034
fix(multimodal): bound remote image downloads by the file size limit (#3906)
* fix(multimodal): bound remote image downloads by the file size limit

* style(utils): wrap over-long lines in the DownloadBytes test

---------

Co-authored-by: Wen.Vale <224270013+SEVEN-us@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:14:04 +08:00
linus-liu-web 4eb23a8560
fix(qdrant): CopyIndices 用服务端返回的 next_page_offset 翻页,不再按页尾 id 回填 (#3882)
* fix(qdrant): 复制索引改用服务端返回的游标,重复游标报错并给分页加跳数上限

CopyIndices 用"上一页最后一个点的 id"当游标(repository.go:987)。Qdrant 的
scroll offset 是**包含**语义 —— proto 里写的是 "Start with this ID",实测下一页
正是从该 id 本身开始返回,所以每翻一页都会把上一页的最后一个点再读一次、再写一份
到目标库。服务端本来就把下一页该用的游标放在 ScrollResponse.next_page_offset
("Use this offset for the next query")里,而客户端只在 ScrollAndOffset() 中返回它,
本函数调用的 Scroll() 恰好把它丢掉了;终止条件也只能退化成"这一页比 64 短"。

在真实 Qdrant 1.19.1 上实测:150 个源 chunk 复制出 152 个目标点,chunk-63 与
chunk-126 各被复制两次(每个页边界一个),totalCopied 同步虚高。源库只要超过一页
(>64 个 chunk)就会命中,不需要服务端有任何异常行为。

本次修改:

- 改用 q.client.ScrollAndOffset,游标直接取服务端返回的 next_page_offset;终止
  条件改为"服务端没有下一页"(next_page_offset == nil),不再用短页推断读完。
- 记录用过的游标,重复即返回 "copy indices made no progress at cursor ...",
  检测点在整页处理之前,重复的那一页不会再多写一份。
- 分页跳数上限 maxCopyPaginationHops(10000 页);触顶打印 Warn 并返回错误,
  而不是把这一轮复制当成成功。
- 修复后同一份数据在真实 Qdrant 上测得 150 个目标点、0 重复。

回归用例用假 gRPC 服务端(拦截 unary RPC,对齐 repository_test.go 的
newInterceptedQdrantClient)复刻真实服务端的游标语义:150 个源 chunk 必须各复制
一次(修复前 152 个点、2 个重复);游标恒定不动的源端必须报 no progress
(修复前 5 秒写入 3127040 个点仍未返回);一直推进但永不结束的源端在第 10000 页
被拦下。

* fix(qdrant): drop the CopyIndices page cap

10000 pages of 64 points capped a copy at 640k points and failed the
whole clone beyond that. The scroll walks every point of the source
knowledge base (a single-knowledge clone included), so a cap derived from
the chunk map would cut off small clones out of large bases too.
next_page_offset only moves forward, so the repeated-cursor check already
stops a walk that cannot finish, and the task context bounds the rest.

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:04:43 +08:00
Perfecto 336f84c3be
fix(data-analysis): skip style-only worksheets before DuckDB loading (#3660)
* fix(data-analysis): skip style-only worksheets before DuckDB loading

* chore: retrigger CI for XLSX sheet fix

* fix(data-analysis): keep all sheets when the worksheet preflight fails

The style-only sheet preflight is best-effort: if it cannot read the
workbook parts, log a warning and load the sheets DuckDB enumerated
instead of failing the whole workbook. Context cancellation still
aborts the load.

---------

Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 13:04:29 +08:00
linus-liu-web dabbdaf156
fix(notion): 分页循环补重复游标防护与跳数上限 (#3890)
paginatePages 与 GetBlockChildrenFlat 都只以 has_more / 空 next_cursor 为终止
条件:既不记录用过的游标,也没有页数上限。Notion(或中间网关)只要回
has_more=true 且 next_cursor 不前进——包括"空 results + has_more=true"这种厂商
形状——循环就永远退不出来,同一页被反复抓取:SearchPages(资源发现)与
QueryDatabaseAll(数据库记录)都汇入 paginatePages,客户端自带 3 req/s 限流,
所以表现为以 3 rps 稳定空转到任务 deadline,同步任务永不进终态;若伴随非空
results,allPages 还会无界增长。

同文件的 getBlockChildrenRecursive 已有 maxBlocksPerPage 兜底,Confluence
(seen + maxPaginationHops)、DingTalk(seenTokens + maxPages)也有同族守卫,
这两条循环漏了。

改动:
- 抽一条 advancePaginationCursor:每页取回 next_cursor 后调用,重复游标立即报
  错,页数达到 maxPaginationHops(10000,对齐 Confluence)时 Warn 并报错。触顶
  必须留日志:从外部看这种失败和"还在正常同步"一模一样。
- paginatePages 与 GetBlockChildrenFlat 一并接入(同文件同型缺陷,发现阶段扫子
  页面走的正是后者)。

新增用例:重复游标(第 2 次请求即报错,含"空页 + has_more=true"形态)、跳数上限
(正好 10000 次请求后报错且日志含 "pagination exceeded 10000 pages")、真实多页
仍正常合并。测试把 3 rps 限流换成不限速,否则回归场景要跑 55 分钟。去掉本次改动
后三条用例全部失败(重复游标场景实测跑到 10006 次请求才被假服务器的预算拦下)。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 01:29:20 +08:00
linus-liu-web 5077f35800
fix(notion): 超过 block 上限截断时补 Warn,避免内容与子页面静默缺失 (#3771)
* fix(notion): 超过 block 上限截断时补 Warn,避免内容与子页面静默缺失

单个页面/块超过 maxBlocksPerPage(1000) 时客户端会静默停止分页:第 1000
个 block 之后的正文不会进入 markdown,其后的 child_page/child_database
也不会被 fetchPage 递归同步。又因为游标记录的是 last_edited_time,页面
未变更时同步会直接跳过该页,截断因此长期存在且无任何提示。飞书同类上限
(feishu/core/blocks.go 的 maxDocumentBlocks)已有 Warn,这里对齐其措辞
补齐可观测性。

- cap 触发且 API 仍有下一页时打一条 Warn,含块/页面 ID 与上限数字,说明
  剩余 block 不会被同步;是否真为截断由纯函数 blocksTruncated 判定,恰好
  1000 个 block 的页面不会误报;
- 不改 cap 数值、page_size、递归逻辑与游标语义。

测试 truncation_test.go:伪造返回 1001 个 block 的 children 接口,断言
Warn 内容且第 11 次请求未发出;另覆盖恰好 1000 的边界与 blocksTruncated
真值表。

* fix(notion): has_more 但 cursor 为空时不再静默丢内容

blocksTruncated 的第三个条件 nextCursor != "" 在 Notion 契约下与 has_more
冗余:has_more=false 时 next_cursor 必为 null。于是"has_more=true 但
next_cursor 为空"这种异常响应仍会静默截断——未命中 cap 时循环本就因空游标
break,命中 cap 时又因该条件跳过 Warn,两种情况都不留痕迹。

- 谓词收敛为 currentCount >= maxBlocksPerPage && hasMore,不再要求游标非空:
  cap 命中且 has_more=true 即视为截断;
- has_more=true 而 next_cursor 为空时单独打一条 Warn,带上块 ID 与已取块数,
  说明无法继续翻页、剩余内容不会被同步(无论是否命中 cap 都打);
- 不改 cap 数值、break 条件、page_size、递归深度与游标语义。

测试:真值表去掉游标列,并删掉把"cap 命中 + 空游标 = 不告警"固化成期望的
用例;新增 TestBlockCapWarnsWhenHasMoreHasNoCursor(cap 命中 + has_more=true
+ 空游标须同时出现 cap Warn 与游标 Warn,且不发出第 11 次请求)与
TestHasMoreWithoutCursorWarnsBelowTheCap(cap 以下同样要告警);原有正常翻页
用例补断言:格式正确的分页不得出现游标异常 Warn。反向验证:谓词还原为原样
后两个新用例均失败。

* test(notion): rename block-cap log helper to avoid clashing with #3845

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-10-08 01:29:12 +08:00
ordinary being 6057a81017
fix(middleware): stop buffering whole request bodies in the access log (#3927)
Logger() runs ahead of Auth and of every route handler, and read the entire
request body with io.ReadAll before any per-route http.MaxBytesReader was
installed. Bound the read to the log budget and hand the unread remainder back
to the handler through io.MultiReader.
2026-10-08 01:29:05 +08:00
kevin 20038cbda6
fix(asynqdl): truncate dead-letter errors on a rune boundary (#3964) 2026-10-08 01:28:59 +08:00
Fei.Chen dad81cb8c1
fix(sandbox): reclassify exec races with the idle sweep as NotFound so rebinding heals (#3980)
An exec that collided with the idle sweeper's delete (#3942 mechanism A)
surfaced as a non-zero exit with an empty stderr, which the filesystem op
wrappers classified as InvalidRequest — outside CanReplaceRemoteBinding's
NotFound/Terminal allow-list, so the rebinding self-heal never ran and the
failure reached the user (empty answer, zero steps). The op wrappers now
re-inspect on failure and reclassify as NotFound when the Engine confirms
the container is gone, making the sweeper's 'deleting needs no coordination
with the binding store' premise hold for the mid-flight window too. Only a
confirmed 404 reclassifies; transport errors keep the original kind.

The shared message now carries the exit code — with an empty stderr it was
the one missing clue during the original diagnosis (#3942).

Co-authored-by: vicfei <vicfei@users.noreply.github.com>
2026-10-08 01:28:53 +08:00
Fei.Chen b8d83eab1c
fix(skills): skip vendored dep trees in install verification script enumeration (#3943)
* fix(skills): skip vendored dep trees in install verification script enumeration

sortedScriptPaths fed every .py/.js/.sh in the bundle into one shell 'for
f in ...' command. A skill that vendors a scientific venv (pandas/scipy/
matplotlib etc.) carries thousands of .py files under .venv/, and the
generated command exceeds the exec single-argument limit (MAX_ARG_STRLEN,
128KiB): /bin/sh fails with 'argument list too long' (exit 255) before
any check runs, so no dependency-heavy skill can ever install.

Vendored trees are installed dependencies, not scripts the model can
name; their health is already covered by the dependency verification
passes. Skip .venv/ and node_modules/ prefixes in sortedScriptPaths,
which fixes the tree check, the per-language parse passes and the
runtime prerequisite pass at once.

Verified by installing a 4862-file / 105MB quant skill (pandas+numpy+
scipy+statsmodels+matplotlib venv, real interpreter binary instead of
symlinks since zips cannot carry them): install failed before the fix,
reaches ready after it.

* fix(skills): skip vendored trees at any depth, not only at the bundle root

Bundles are author-zipped, so tools/.venv/ or sub/package/node_modules/
are as legal as root-level trees and enumerated just the same. The
filter now matches vendored trees under any prefix; nested placements
are covered by a regression test.

---------

Co-authored-by: vicfei <vicfei@users.noreply.github.com>
2026-10-08 01:28:45 +08:00
VictorMaznyuk 3206e15e83
fix(docs): make `make docs` reproduce the committed Swagger again (#3751)
Running `make docs` on main no longer reproduces the committed docs/*:
every definition loses its package-qualified name (types.* instead of
github_com_Tencent_WeKnora_internal_types.*), enums disappear, ErrorCode
becomes a plain integer, and docs/swagger_contract_test.go fails
(TestModelDeleteUsageContract).

Cause: internal/localsandbox is not a dependency of cmd/server (its
importers are behind the `desktop` build tag), but swag's directory walk
reaches it. Its `const X = core.X` aliases make swag load
internal/localsandbox/core again through go/loader, and that second load
re-registers every already-deduplicated type under its short name without
enum values. Excluding the directory removes the second load.

That load was also hiding a second problem: skill_handler.go references
errors.AppError in @Failure without importing internal/errors, so with the
exclude swag stops with "cannot find type definition: errors.AppError".
A blank import lets swag resolve it.

Co-authored-by: Victor Maznyuk <victor@maznyuk.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 01:26:08 +08:00
linus-liu-web 626185a120
fix(wiki): 重建链接逐页写失败不再静默,半成品不再回 200 (#3884)
RebuildLinks 的保存循环把每页 UpdateMeta 的失败降级成一条 Warn,函数最后
无条件 return nil,于是 handler 里既有的 err != nil 分支永远进不去:任意
一页写失败(行锁等待、死锁、连接中断、超时)时调用方仍拿到
200 "Links rebuilt successfully",而这些页面的 in_links/out_links 保持旧
值,反向链接与图谱继续显示过期关系,且没有任何途径知道"只重建了一部分"。

保持尽力而为的语义不变(一页失败不影响其余页面继续写入),但把失败页聚合
起来在结尾返回,沿用同仓库 knowledge_delete.go / wiki_ingest.go 的
errors.Join 写法,以及同文件 MovePage 对同一个 UpdateMeta 调用的报错写法。
handler 无需改动:其既有 500 分支会如实返回 "N of M pages failed" 与失败页
slug。

回归用例用 SQLite 触发器让指定页的 UPDATE 真的报错(不是 mock),走真实仓库
与真实 handler:
- 部分失败:RebuildLinks 返回聚合错误,可写页仍被刷新,失败页保持旧值;
- 全部失败:错误里含 3 of 3 与全部 slug;
- HTTP 层:部分失败回 500 且错误体含失败页与底层原因,全部成功才回 200。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 01:25:53 +08:00
xxxxx 4d7e663128
fix(wiki): preserve pending work when source lookups fail (#3715)
* fix(wiki): preserve pending work when source lookups fail

* test(weaviate): snapshot schema state before probe barrier
2026-10-08 01:25:45 +08:00
sun fac9ebabf2
fix(knowledge): close spans left open on terminal rows and superseded attempts (#3855)
Sweep A only selects pending/processing/finalizing, so a row that reaches a
terminal state while its attempt is still open is never revisited: its spans
stay "running" and the document timeline shows a permanent 进行中. Found in
production with four root spans stuck for 11 and 27 days.

- housekeeping: add Sweep D (reapTerminalSpans) closing spans still open on
  terminal rows, carrying the row own error_message so the timeline still
  names the real cause. A self-healing backstop for every failure path that
  forgets to close its attempt, including rows stranded by older releases.
- span tracker: OpenAttempt now cancels spans left open by earlier attempts
  (ATTEMPT_SUPERSEDED). A reparse used to open its new root alongside the
  previous attempt dead root, which is what made historical runs look
  like they had been reactivated.

Co-authored-by: asmh1989 <minhua.sun@velavigo.com>
2026-10-08 01:25:38 +08:00
诉说晚秋 95691daab2
fix(knowledge): retry document processing after transient indexing failures (#3915)
processChunks marked the knowledge failed and returned nil when BatchIndex
failed, so ProcessDocument acked the task and the configured document-task
retries never ran. A short embedding or vector-store outage left the row
permanently failed; unchanged data-source syncs did not reprocess it.

While attempts remain, still clean up the partial chunks and vectors but
keep the row processing and return the error to the queue. The final
attempt (or a caller without a retry loop) records the failure as before.
2026-10-08 01:25:31 +08:00
洛根 c0c194f625
fix(im/wecom): preserve image in mixed messages with text captions (#3901)
* fix(im/wecom): preserve image in mixed messages with text captions

convertMixedMessage discarded the image whenever a mixed (text+image)
message contained any text, so the most common shape — a question plus
a screenshot — reached the QA pipeline as text-only and the model never
saw the image, despite the IM integration docs promising images are
handled as QA attachments.

Keep the first image as the message attachment and carry the text as
its caption: the IM service already supports captioned images
(prepareIMAttachments downloads the file while fileMessageQAContent
preserves msg.Content as the query), so the adapter just has to emit
MessageTypeImage with Content set instead of MessageTypeText.

Text-only, image-only, and empty mixed messages keep their previous
behavior. Multiple images still collapse to the first one; supporting
several attachments requires a multi-attachment IncomingMessage and is
left out of this minimal fix.

* fix(im/wecom): wrap over-length line in mixed_test to satisfy lll lint
2026-10-08 01:25:25 +08:00
Captain 172d0a85ab
fix(mcp): pass embedded resources in tool results to the agent (#3766)
CallTool kept only text and image content from a tool result. A tool
can also return audio, a link to a resource, or a resource embedded in
the result, and GitHub's MCP server returns files that way:
get_file_contents answers with a short message and the file as an
embedded resource. The agent only ever saw the message.

Convert audio, embedded resources (text or blob) and resource links,
recording the resource URI. The agent now follows the reference to a
text resource with its text, and shows links and binary resources as
references. Base64 data of any kind, not only images, is redacted from
the logged content items.
2026-10-08 01:25:04 +08:00
Captain 28734725a3
fix(mcp): reconnect after the server forgets the session (#3765)
On a session-based protocol version, a server answers a request for a
session it no longer knows, after a restart or when the session expired,
with 404, and the spec has the client start a new session. mcp-go
reports it as transport.ErrSessionTerminated. checkErrorAndDisconnectIfNeeded
only looked for two error messages some servers send, so the client
stayed connected and GetOrCreateClient kept handing out the dead
session: every call to the service failed until WeKnora restarted.

Disconnect on ErrSessionTerminated too, so the next use reconnects.
2026-10-08 01:24:57 +08:00
Captain f559473498
fix(mcp): keep the client secret from dynamic client registration (#3763)
StartAuthorization stored only the client ID from dynamic client
registration. When the authorization server registers a confidential
client and returns a client secret, the secret was lost: the callback
rebuilds the OAuth handler from the stored client, so the code exchange,
and every later refresh, went out without it and the server rejected
them as invalid_client.

Store the secret along with the ID. The model already has the column,
encrypts it on save, and both handlers read it back.
2026-10-08 01:24:51 +08:00
linus-liu-web e394c7adec
fix(agent): 工具自起 goroutine 的 panic 自行兜底,MCP 预热不再带走进程 (#3846)
recover 只对调用它的那个 goroutine 生效。executeRecovered(registry.go)覆盖的是
tool.Execute 这次调用本身,act.go 的 errgroup 回调同理:工具自己起的 goroutine 上
发生 panic,两处都接不到,整个进程退出,正在进行的对话、上传、同步全部中断。

修复站点:
- mcp_exposure.go 的 catalog 预热 goroutine 与最多 8 个 worker 各装一道屏障;worker
  内按服务再兜一层,panic 时沿用文件里既有的 store/status 机制把该服务标记为
  "error"(与加载报错同一个状态)、清掉 partial snapshot,close(preloadDone) 照常
  执行,prepareMCPToolsWithMode 的 select 仍能返回。
- search_knowledge.go 检索扇出的三处 goroutine(embedding 分组、合并 KB 检索、单 KB
  检索):panic 记日志后按既有的 fail() 机制把对应知识库报成失败,工具调用降级为
  失败结果而不是进程退出。
- think.go 的 stream stall 看门狗改用同一屏障(stallTimeout 非正时 NewTicker 会 panic)。

新增 internal/agent/tools/goroutine.go:
- GoRecovered(ctx, fn):起 goroutine 并兜住 panic,供工具内部统一使用;
- RecoverGoroutine(ctx, label, onPanic):defer 形式,onPanic 在同一 goroutine 上记录
  失败单元,panic 值不外传。
registry.go 的 executeRecovered 注释补上"recover 只覆盖本 goroutine,工具自起的
goroutine 必须自己兜底"。

回归测试:
- TestMCPPreloadWorkerPanicIsContained:loader panic 后进程存活、PrepareMCPTools 正常
  返回、该服务 status 为 error 且不保留缓存工具;
- TestMCPPreloadFailureMarkingKeepsReadySnapshots:协调者屏障只标记未完成的加载,
  ready 快照不动;
- TestToolChildGoroutinePanicDegradesToFailedResult:走真实 executeToolCallsParallel,
  子 goroutine panic 降级为失败结果;
- TestGoRecoveredContainsPanicAndRunsDefers / TestRecoverGoroutineReportsPanicToCaller。

去掉屏障后上述用例的测试进程 exit=1,装回后全部通过。

Fixes #3837

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 01:24:36 +08:00
诉说晚秋 fa4f85d3dd
fix(agent): 拒绝将断流摘要保存为记忆检查点 (#3994) 2026-10-08 01:24:30 +08:00
澍 52893006ad
fix(agent): validate tool string lengths by Unicode code points (#3937)
Fixes Tencent/WeKnora#3935
2026-10-08 01:22:18 +08:00
诉说晚秋 f6119ae5fd
fix(agent): 保留数据分析 SQL 字符串字面量 (#3812) 2026-10-08 01:22:11 +08:00
tsumon 188d9026d8
fix(models): honor OpenRouter native thinking for legacy defaults (#3807) 2026-10-08 01:22:04 +08:00
linus-liu-web 9de0946e53
fix(docparser): anydoc 内嵌 EMF/WMF 图片的扩展名与 Rust 侧对齐 (#3938)
anydoc 把内嵌图片就地渲染成 `![alt](images/image-N<ext>)`,`<ext>` 来自
asset_links.rs::extension_for;ImageResolver 再拿这个字符串去一张 map 里查,
键是 anydoc.ImageDir + Asset.Name,而 Name 由 backend_cgo.go::extensionFor 拼出。
查表是精确匹配,两边必须逐字符一致。

EMF/WMF 上两边并不一致:anydoc 对这两类 part 硬编码产出 image/emf 与
image/wmf(shared/assets.rs::media_type_for、shared/officeart.rs),Rust 表
落到 `.bin`,而 Go 侧去查平台 MIME 注册表——在装了 media-types 的 Debian
镜像上拿到 `.emf`/`.wmf`。链接与 ref 于是永远对不上,saveReferencedImage
找不到条目,图片字节从不落盘,且没有任何日志。

- asset_links.rs::extension_for 补 image/emf 与 image/wmf
- backend_cgo.go::extensionFor 补同样两项,并改成纯查表

去掉 mime.ExtensionsByType 是有意的:让扩展名取决于宿主的 /etc/mime.types
正是这个 bug 的成因,何况这张表本来就要和 Rust 的静态表逐字符对齐。未知
类型两边都落到 .bin,仍满足「不写出无扩展名 blob」的原意。

新增 TestEmbeddedVectorImageLinksResolve:在内存里构造一个含一张 EMF 与
一张 WMF 的最小 docx,转换后要求每一条 Markdown 图片引用都能在 resolver
建的 ImageRef 表里命中,并固定扩展名为 .emf/.wmf(避免两边一起退化成
.bin 也能通过)。

Co-authored-by: linus-liu-web <linus-liu-web@users.noreply.github.com>
2026-10-08 01:21:57 +08:00
linus-liu-web a6c6c35ad2
fix(ima): 三条游标分页循环补重复游标防护与跳数上限 (#3889)
ListResources 的两条循环(get_addable_knowledge_base_list、search_knowledge_base
兜底)与 listAllKBFiles 的 get_knowledge_list 循环都只以 is_end / 空 next_cursor
为终止条件:既不记录用过的游标,也没有跳数上限。厂商只要回 is_end=false 且
next_cursor 不前进,循环就会一直请求同一页,bases / out 随迭代重复增长,直到任务
deadline —— 资源选择器接口不返回,同步任务永远不进终态。

同族的 DingTalk(seenTokens + maxPages)、Confluence(seen +
maxPaginationHops)、飞书(seenPageTokens)都已有守卫,本包漏了。

改动:
- 抽一条 nextPageCursor:每页取回 next_cursor 后调用,重复游标立即返回错误(不再
  重试),页数达到 maxPaginationHops(10000,对齐 Confluence)时 Warn 并报错。
  触顶必须留日志:从外部看这种失败和"还在正常同步"一模一样。
- 三条循环按同一写法接入;listAllKBFiles 的守卫错误补上 get_knowledge_list 前缀。
- 假 IMA 服务器支持覆盖某个 action 的分页字段(固定游标 / 每次换新游标 / 有限页数 /
  每次换 payload / 请求预算),并给"无防护时会空转"的场景设请求上限,使回归用例失
  败而不是挂死。

新增用例:三条循环的重复游标(都在第 2 次请求即报错)、跳数上限(正好 10000 次
请求后报错且日志含 "pagination exceeded 10000 pages")、真实多页仍正常合并。
去掉本次改动后这四条用例全部失败(重复游标场景实测跑到 10006 次请求才被假服务器
的预算拦下)。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 01:21:44 +08:00
linus-liu-web a2aeb97a01
fix(gitlab): 分页循环补重复页防护与跳数上限 (#3841)
projects() 与 tree() 只依据服务端返回的 X-Next-Page 判断是否继续,
该值重复或不前进时循环不会结束:同一页被反复请求、结果切片持续
增长,只能等上层 context 到期。

两条循环改用 trackPage:页码已请求过即返回错误,不静默当作读完;
页数达到 maxPaginationHops 时记警告并返回错误。正常翻页路径不变。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 01:21:37 +08:00
linus-liu-web b5c74b2dd6
fix(feishu): 多维表格字段分页补重复 page_token 防护与条数上限 (#3840)
内嵌多维表格的 list-fields 分页循环只判断 has_more 与 token 是否为空:
厂商在 has_more=true 时返回已读过的 page_token,循环就会反复请求同一页并把
同一批字段重复追加进 cols,直到任务 deadline(实测 2s 内 5 万余次请求仍未
返回)。该循环也是同文件里唯一既无去重、又无尺寸上限的分页循环。

- 按同库 wiki 空间/节点与云盘分页已有写法加 seenFieldPageTokens 集合,重复的
  非空 token 立即返回 error,不再静默当作读完;
- 补 maxBitableFields = 5000 的条数上限,命中时 Warn 并截断。

测试:重复 token 在第二次出现时报错并停止请求;厂商每页都返回新 token 时在
第 5000 个字段处停止并打 Warn;正常 100 条/页 分页不受影响。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 01:21:31 +08:00
LuckVd 0d3a053eb6
fix(yuque): don't acknowledge failed detail fetches in the incremental cursor (#3702)
A partial sync recorded each doc's new content_updated_at before fetching
its detail. When a detail request failed after client retries, the cursor
still held the new version, so every later incremental sync treated the
doc as unchanged and never re-fetched it (mixed success/failure batches
persist the cursor; only all-failed batches are aborted).

Rewind the cursor entry to the previously synced version (existing docs)
or drop it (new docs) on detail failure so recovery re-syncs the doc.
Deletion detection is unaffected: currentDocs is set at listing time.

Fixes #3690

Co-authored-by: LuckVd <LuckVd@users.noreply.github.com>
2026-10-08 01:21:23 +08:00
Lukas 98feef38de
fix(chunker): count an escaped pipe as cell text when matching table widths (#3979)
The header tracker compares a row's column count with the active table
header's to tell a new table from more rows of the same one.
tableRowColumnCount split rows on every `|`, so a cell holding an escaped
pipe (`\|`, which GFM writers such as anydoc emit for a pipe in a cell)
counted as one more column. The tracker took that row for the start of a
new table and dropped the header, so the chunks after it no longer began
with the column names.

Split rows on unescaped pipes only. A pipe after an odd run of
backslashes is text inside the cell, as in GFM.
2026-10-08 01:21:16 +08:00
Yeager0204 e915adb147
fix(chunker): preserve source offsets for table child chunks (#3969)
Co-authored-by: kwsYegar <331533331+kwsYegar@users.noreply.github.com>
2026-10-08 01:21:08 +08:00
linus-liu-web a15dfdd941
fix(summary): 坏 JSON 不再冒充文档摘要(截断/畸形 JSON 走失败路径,纯文本兜底保留) (#3769)
* fix(summary): 坏 JSON 不再冒充文档摘要

非流式文档摘要(Chat)解析失败时原先把模型原文当摘要落库:被 MaxTokens
截断的半截 JSON 会写进 knowledges.description、置 SummaryStatus=Completed
(Asynq 不再重试),同一段文本还会被 buildSummaryChunkContent 索引进 RAG。

- parseDocumentSummaryOutput 改为返回 (*documentSummaryResult, error):
  回复形如 JSON(含 markdown 代码围栏)却解析失败、或解析成功但取不到
  summary/gist 时返回 errSummaryOutputNotParsable,绝不回退成原文;
  非 JSON 的纯文本仍走原有的原文兜底,自定义模板 / 老模型不受影响。
- validateSummaryOutput 复用 chatpipeline.IsLengthFinishReason,
  FinishReason 为 length 类取值时返回 errSummaryOutputTruncated。
- 两个 sentinel 经 getSummary 汇入既有失败路径(ProcessSummaryGeneration
  的 handleRetryableSummaryFailure、RegenerateKnowledgeSummary 的
  handleGenerationFailure):保留旧描述、置 pending/failed 交给 Asynq 重试,
  不再以 Completed 落库。

测试:TestParseDocumentSummaryOutput 改为表驱动(截断 JSON、含裸换行 JSON、
无文本 JSON 必须报错且不能把原文当 Summary;纯文本兜底继续通过);
TestValidateSummaryOutput 增加 length / max_tokens 截断用例;
TestGetSummaryRejectsUnusableModelOutput 锁住 getSummary 的错误传播。

* fix(summary): length 截断判定收窄到 JSON 形状回复

非流式文档摘要在校验模型回复时先看 finish_reason:只要 provider 报告
length/max_tokens 就返回 errSummaryOutputTruncated。该判定不认识内容形状,
于是自定义纯文本模板一旦顶到输出预算,就从「截断但可用」变成重试直到
SummaryStatusFailed,与上一提交承诺的「非 JSON 的纯文本仍走原兜底」相反。

- validateSummaryOutput 恢复为只看内容是否为空;新增
  validateStructuredSummaryDocument 供 getSummary 使用:先判形状再判
  length,只有确实在产结构化摘要(能解析成对象/数组,或 { 开头、[ 开头接
  对象/数组/字符串元素)且被预算截断时才返回 errSummaryOutputTruncated。
- 形状判定剥离 UTF-8 BOM、前后空白与一层 markdown 围栏后再尝试
  json.Unmarshal;「[文档摘要] …」「[1] …」这类带方括号引用的纯文本不再被
  误判成坏 JSON,而截断的 {summary: 与截断的 JSON 数组仍然报错。
- parseDocumentSummaryOutput 同步剥离 BOM:BOM 前缀的截断 JSON 之前会被
  当成纯文本落库。
- 表格描述 / 列描述仍走 validateSummaryOutput,截断的描述照旧可索引。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-08 01:21:01 +08:00
Ankit Jha 27b9ee74a0
fix(storage): use virtual-hosted addressing for Tencent COS through the S3 driver (#3722)
newS3Client forced path-style for every non-AWS endpoint, so a COS
endpoint such as https://cos.ap-shanghai.myqcloud.com sent requests to
cos.<region>.myqcloud.com/<bucket>/<key>. COS rejects path-style for
buckets created from 2024-01-01, so STORAGE_TYPE=s3 could not reach new
COS buckets, and force_path_style=false had no way to turn it off.

Treat *.myqcloud.com like AWS and use virtual-hosted style. An explicit
force_path_style still wins, and other S3-compatible endpoints keep
path-style.

Fixes #3134

Signed-off-by: Ankit Jha <ankit.jha@tradomate.one>
2026-10-08 01:20:54 +08:00
Perfecto a8c291c6ff
fix: keep failed data-analysis table loads retryable (#3745) 2026-10-08 01:20:48 +08:00
诉说晚秋 7c284e7fc9
fix(faq): 保留克隆状态同步时的正文和索引状态 (#3993) 2026-10-08 01:20:39 +08:00
knqiufan e29301115a
fix(graph): preserve relationship direction and document provenance (#3950)
* fix(graph): preserve direction and document provenance in graph retrieval

* test(graph): verify live query bounds and seed evidence ordering

* fix(graph): deduplicate expansion using bounded seed identities

* ci: retry upstream scan after missing CodeCC report
2026-10-08 00:48:51 +08:00
AI即世界 afc6cbd502
fix(milvus): validate connections and preserve gRPC resolver defaults (#3654)
* fix(docreader): preserve gRPC resolver defaults

* fix(milvus): validate connection with SDK handshake

* fix(docparser): preserve gRPC resolver defaults

* fix(milvus): satisfy connection check lint

---------

Co-authored-by: tunan <tunan@ahyk.com>
2026-10-08 00:48:45 +08:00
Mohamed Arbi 9fa9e7c29d
fix: use consistent qdrant env settings (#3960)
* fix qdrant env settings

* fix test formatting
2026-10-07 23:59:56 +08:00
linus-liu-web 9490035f15
fix(agent): 图谱查询的三处截断必须可见,模型不再把子图当全集 (#3885)
query_knowledge_graph 有三处静默上限:返回关系 30 条、每个知识库抓取的
证据 chunk 10 条、送进图谱存储的实体词 8 个。命中上限后既不计数也不提示,
输出还按截断后的长度报告 "Found N relations",读起来就是"该实体的关系就
这么多"。模型据此把被砍过的子图当作实体的完整邻域作答,漏答或得出与图谱
事实不符的结论,且没有任何信号提示它应当收窄实体。同一仓库的图谱存储层
(neo4j/repository.go 的 graphSearchMaxRows 告警)已经把"截断必须可见"
写成明确要求,工具层没有遵守。

改动:
- 关系去重后继续计数,Data 增加 relations_total / relations_omitted;
- 证据 chunk 边取边计数,Data 增加 graph_chunks_total / graph_chunks_omitted
  (未接 chunk 仓库、抓取失败都不计入,避免把错误报成截断);
- 被上限丢弃的查询词计数进入 Data(query_terms_total / query_terms_omitted);
- 命中上限时 Output 追加 "=== ⚠️ Truncated ===" 段并给出收窄建议,主行改为
  "Found 30 of 42 relations";未命中上限不输出任何内容,沉默只表示没有丢弃;
- modelcontext 的 <retrieval> 视图补 <graph_truncated .../>:模型在有 chunk
  行时读的是重建视图,标记只写 Output 到不了模型。

上限数值、去重语义与检索行为不变,只让截断可见。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 23:59:50 +08:00
linus-liu-web 5648d24a93
fix(retriever/milvus): CopyIndices 按映射分块读源行,去掉会静默漏向量的 offset 窗口 (#3883)
CopyIndices 用 offset/limit 窗口遍历源知识库:offset 是"跨请求保持不变的结果
顺序"上的游标,而普通 query 不承诺这个顺序(结果按 segment 合并,且本次拷贝
每页都在往同一个 collection 写目标行),窗口一漂移就会跳过落在新窗口之前的行、
并重读被窗口退回的行;终止条件"短页即结束"(count < batchSize)又把因此提前
出现的短页当成读完了,剩余向量被静默丢掉,函数仍然返回 nil。用进程内假 Milvus
(gRPC 服务 + DisableConn,走真实 client.Query/Upsert 路径)在每次写入被确认后
旋转结果顺序复现:200 个源 chunk 全部返回成功、日志 total copied: 200,但
3 个 chunk 的向量从未写入目标库、另有 3 个被写了两遍(offsets=[0 64 128 192])。

改成按映射里的源 chunk ID 分块读:谓词 = knowledge_base_id 相等 + chunk_id in
(本批 64 个),读到的行集合由谓词唯一确定,没有游标可漂。拷贝的集合与改动前一致
(原先读到但不在映射里的行本来也会被跳过),只是不再按 offset 前进。同一文件的
chunk_id 批量读(updateChunkEnabledStatusInCollection、BatchUpdateChunkTagID)与
SQLite 版 CopyIndices 用的就是这个形状。

回归用例用进程内假 gRPC Milvus 注入跨页顺序漂移:去掉本修复该用例必失败
(missing=[target-chunk-064 target-chunk-129 target-chunk-194]、
repeated=[target-chunk-000 target-chunk-001 target-chunk-002] 而函数返回 nil),
修复后 offsets 全为 0、无缺失无重复。

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 23:59:44 +08:00
linus-liu-web 5f5093b9f7
fix(retriever): Qdrant/Milvus 关键词检索整批失败返回 error,不再当成「没有匹配」 (#3847)
* fix(retriever): Qdrant/Milvus 关键词检索整批失败不再当成没有匹配

Qdrant 与 Milvus 的 KeywordsRetrieve 逐个 collection 检索,单个 collection 失败只降级成
一条日志后 continue。循环结束后按结果条数分支:全部 collection 失败与确实零命中都会打印
"No keyword matches found"、返回空结果与 nil error。上层只看第二个返回值,据此判定知识库
没有相关内容,用户与模型都无法区分"没有这个词"和"检索没有执行成功"。

改为在循环内累计匹配到的 collection 数与失败的 collection 数,全部匹配 collection 都失败
时返回带底层原因的聚合 error,例如
"qdrant keyword search failed in all 2 matched collections: <cause>"。计数放在 collection
名前缀/维度匹配之后,名字不匹配的 collection 不参与统计;匹配到的 collection 为 0 时维持
原行为,不报错。Milvus 的三处 continue(Search / convertResultSet /
buildMilvusIndexResults)全部计入,另有两处同样会跳过 collection 的失败路径(analyzer mode
探测、过滤器构建)一并计入,这三处的日志补上 collection 名。

部分失败时不再打印结论性的 "No keyword matches found":有结果时改为提示结果不完整,无结果
时说明有多少个 collection 应答过、多少个失败;只有本次调用没有发生任何错误时才继续打印该
结论。RetrieveResult.Error 保持原样(仓库内没有读取方),改动面最小、语义最清晰的暴露方式
是整批失败返回 error。

回归测试:
- Qdrant(repository_test.go):假 Qdrant gRPC 服务让 Scroll 全失败时返回 error 且不打印
  结论日志;只有一个 collection 失败时结果与 nil error 不变;全部成功且零命中时仍返回空结果
  + nil error 并保留结论日志。
- Milvus(新增 keywords_test.go):*client.Client 没有接口缝隙,改用进程内 Milvus gRPC 假
  服务(ShowCollections / DescribeCollection / Search)覆盖同样三种情形,走真实 Search 与
  结果转换路径。
- go.mod:milvus-proto 由新测试直接导入,去掉该依赖的 // indirect 标记。

反向验证:把两个 repository.go 改回原样后,两条"全部失败"用例分别以
"all-collections failure must surface as an error, got <nil>" 与
"An error is expected but got nil" 失败,部分失败与零命中两条用例保持通过;随后逐字节还原
修复。

* fix(retriever): 关键词检索部分失败随结果一起暴露,不再被当成完整结果

Qdrant/Milvus 的 KeywordsRetrieve 逐 collection 检索,部分 collection 失败时保留其余
collection 的结果并返回 nil error。上层拿到的是"结果 + nil error":既不知道少了几个
collection 的内容,也没有任何读取方,RetrieveResult.Error 因此长期是死字段。上一个
commit 只处理了"全部匹配 collection 都失败",部分失败仍然静默降级,模型与用户看到的
都是不完整结果。

让部分失败沿着结果走完这条链路:

- repository(qdrant/milvus):部分失败时把
  "… keyword search failed in N of M matched collections: <cause>" 写进
  RetrieveResult.Error —— 结果照常返回、调用级 error 仍为 nil;全部失败仍是调用级
  error,真正的零命中仍然 Error == nil;
- CompositeRetrieveEngine:读取每个结果集的 Error 并聚合,连同结果一起返回
  ("retrieve returned partial results: …");引擎级 error 仍然丢弃全部结果,
  all-or-nothing 策略不变;
- retrieveFromStores(该接口的唯一消费方):结果与 error 同时非空即"部分失败",打出
  带 store group 与原因的 WARN 并保留结果返回 —— 既不会把降级 store 升级成整次搜索
  失败,也不会让上层把不完整结果当完整结果;
- matched == 0(没有任何 collection 匹配 base name)单独打一条 Warn,与"检索成功但
  零命中"区分开;
- milvus/repository.go 的 allFields 块按 gofumpt 重排,四个包 gofumpt -l 干净。

回归测试:

- qdrant/milvus:部分失败(有命中 / 零命中)结果集带 Error 且调用 error 为 nil;全部
  成功零命中仍 Error == nil 且保留结论日志;全部失败仍是 error;matched == 0 打专属
  Warn 且不发任何 Scroll/Search;
- CompositeRetrieveEngine:结果集带 Error → (结果, error) 同时返回;结果集完整(含零
  命中)→ 无 error;引擎级 error → 丢弃全部结果;
- retrieveFromStores:单 store / 多 store 部分失败都打 WARN 且保留结果,完整零命中不
  打 partial 日志,引擎级 error 仍然失败。

反向验证:去掉四个源文件的可见性改动后,17 条新/改用例中 9 条失败(qdrant 3、milvus 3、
composite 1、retrieveFromStores 2),钉住"行为不变"的 8 条保持通过;还原后 diff 与
改动前逐字节一致。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 23:59:38 +08:00
linus-liu-web f9eeb8dc85
fix(retriever/es): _bulk 的 per-item 失败不再被吞,全部被拒时 BatchSave 返回错误 (#3842)
Elasticsearch 受理 _bulk 请求即返回 HTTP 200,单个文档的写入失败只体现在响应体的
errors 与 items[].<op>.error。v8 把响应对象整个丢弃,只看传输层错误;v7 读了响应,
却只把结论降级成一行告警,响应体解析失败同样返回 nil。两个驱动的 BatchSave 因此在
文档被逐条拒绝时仍返回成功:调用方不标记 failed、不清理 chunks,阶段数据照写全部
条数,文档从此搜不到也不会重试。触发条件都是常规运维事件——mapping 不符、磁盘水位
只读、index 缺失、写压力下的 item 级拒绝。

修复:
- v8 接收 typed bulk 响应对象,resp.Errors 为真时遍历 resp.Items 聚合失败项。
- v7 把 countBulkErrors 的结论从"仅告警"升级为返回错误;响应体解析失败同样返回
  错误,不再把结果未知当成成功。
- 错误信息只带文档 _id 与有界的 error.type,最多摘要 5 条,失败条数覆盖全部失败
  项;error.reason 可能含文档正文,只写 debug 日志。写法对齐 OpenSearch 驱动既有
  的 inspectBulkResponse。

回归测试(v7/v8 各一份,httptest 假 ES + 真实构造函数):全部被拒返回错误、部分
失败返回错误且能看出失败条数、全部成功返回 nil;v7 另覆盖响应体损坏。断言同时确认
返回的错误不含 error.reason 中的文档内容。

反向验证:把两个驱动改回原实现后,新增用例 v7 失败 3 条、v8 失败 2 条;恢复修复后
全部通过。

Fixes #3832

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 23:59:32 +08:00
linus-liu-web a8a2c17b89
fix(sqlite): 索引行写入失败不再被丢弃,BatchSave 回滚而不是留下「主行在、索引行不在」 (#3843)
* fix(sqlite): 索引行写入失败让 Save/BatchSave 报错并回滚

Lite(DB_DRIVER=sqlite)的 vec0 / FTS 索引行 helper 丢弃 Exec 返回值:
BatchSave 的事务末尾无条件 return nil,于是 chunk 主行提交而索引行缺失,
Save/BatchSave 仍报成功,向量与关键词两条检索路径都静默漏召回;CopyIndices
的 copyVec 同样可能报成功而向量行没有复制过去。

- insertVec / syncFTS5Insert / copyVec / deleteRowsAndVecs 返回 error,在
  BatchSave(事务内)与 CopyIndices 的调用点检查并上抛:事务回滚,
  BatchIndex 报错后走 knowledge_process.go 既有的清理与 failed 标记路径;
  删除路径在索引行删除失败时不再删除主行。
- ensureVecTable 校验同名对象确实是 vec0 表之后才缓存"已就绪",失败上抛
  (BatchSave 与 vectorRetrieve);向量写失败时清掉该维度的缓存,下一次写入
  重新建表,而不是被永久短路。
- initFTS5 返回 error,并把建表与回填放进同一个事务(半回填的索引会静默丢
  召回);驱动未编译 fts5 模块(上游 go test 不带 -tags sqlite_fts5)时只
  记录一次并跳过关键词写入,而不是让每次入库失败;Lite 发布构建始终带该 tag。

新增 index_write_errors_test.go:覆盖 vec0 / FTS 表缺失、vec0 维度不匹配、
同名对象占位、索引删除失败、CopyIndices 向量复制失败,以及正常路径与无 fts5
模块构建。把修复改回原样后,其中 6 个用例必失败。

Fixes #3833

* fix(sqlite): CopyIndices 行复制失败累计上报,不再 Warn 后跳过

克隆/搬运知识库时逐行 Create 失败原先只记 Warn 并 continue:目标库会缺
主行/索引行却仍报成功。现改为逐行累计错误,FTS 与向量复制失败同样累计
而不是遇到第一条就返回,最后 errors.Join 交给调用方;错误里带源/目标
chunk id 便于定位失败行,不含正文。调用方沿用既有 rollbackIndices 回滚
与 failed 标记路径。

新增回归用例:触发器拒单行 -> 调用方拿到可定位到该行的错误、同 chunk 的
其它行照常复制;DROP FTS 表 -> 错误带上表和 chunk id 且向量行仍写入。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 23:59:26 +08:00
linus-liu-web 72b8a106c7
fix(sqlite): 检索后端批量更新索引副本失败不再吞掉错误 (#3768)
* fix(sqlite): 检索后端批量更新索引副本失败不再吞掉错误

Lite(DB_DRIVER=sqlite)的 BatchUpdateChunkEnabledStatus 与
BatchUpdateChunkTagID 逐条执行 Update 后丢弃 gorm 的 .Error 并无条件
return nil:索引副本更新失败被吞,接口仍报成功。

服务层是"先写权威 chunks 行(成功)→ 再同步检索索引副本"
(knowledge_faq.go:877-889 等),而检索只读索引副本
(lite_embeddings.is_enabled / tag_id)。因此索引 UPDATE 失败
(SQLITE_BUSY、磁盘满)或未命中任何行时,接口返回成功、UI 显示新标签
或已停用,但按新标签过滤搜不到、刚停用的条目仍会被召回。postgres 后端
同名函数在 result.Error != nil 时本就 return result.Error,sqlite 与之
对齐:逐条检查 .Error,非 nil 时用 fmt.Errorf 包装 chunkID 与操作名
返回。postgres 不把 0 行当错误(仅记录 RowsAffected 日志),故此处也
不引入"0 行即错误"。

新增 batch_update_test.go:用 DROP TABLE 与触发器构造必然失败的
UPDATE,断言返回非 nil 错误(修复前返回 nil),并覆盖成功路径。

注:本条是 sqlite 后端"执行了但吞掉错误",与 #3426 的 weaviate 后端
"未真正执行操作"属于不同后端的不同机制。

* fix(sqlite): 批量更新索引副本累计错误后汇总返回,并让 0 行可见

BatchUpdateChunkEnabledStatus / BatchUpdateChunkTagID 逐条执行 UPDATE,上一版
改成"首个错误即 return":语义从"尽力更新全部"退化成"只更新一个前缀",而前缀
取决于 map 迭代顺序。同类后端不是这么做的:milvus 与 qdrant 都是把每条错误
累计进切片后 errors.Join 并继续跑完。因此改为循环内累计错误、跑完全部行,最后
errors.Join 返回;错误信息仍带 chunkID 与操作名,调用方观察到的"失败即 error"
不变。

另外上一版只检查 .Error,没有看 RowsAffected:"索引 UPDATE 匹配 0 行"在
sqlite 上依然完全不可见。0 行仍不算错误(索引副本允许落后于权威 chunks 行,
postgres 后端同样只记日志),但现在会打一条 Warn,带表名、列名与 chunk_id,
不含正文内容。

测试(internal/application/repository/retriever/sqlite/batch_update_test.go):
- ReportsEveryFailingStatementInBatch:触发器让批内 5 条全部失败,断言
  errors.Join 中 5 个 chunk 都出现、失败消息出现 5 次。首错即 return 时只有
  1 条,用例必失败。
- KeepsUpdatingAfterStatementFailure:批内 chunk-3 失败时 chunk-4/5 仍被更新;
  断言落在结果行而非"第几条",因为 map 迭代顺序随机。
- WarnsWhenStatementMatchesNoRow:命中 0 行仍成功返回,但日志里有带
  lite_embeddings.<列名> 与 chunk_id 的 Warn。

顺带补 gofumpt 要求的函数间空行(main 上既有的格式差异),使该文件 gofumpt 干净。
默认构建与 -tags sqlite_fts5 两种构建下
go test ./internal/application/repository/retriever/sqlite/... -count=1 均通过。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 23:59:19 +08:00
linus-liu-web 402f69832e
fix(notion): 查询撞厂商上限被截断时不再静默,截断轮次不下发删除 (#3845)
* fix(notion): 查询撞厂商行数上限不再静默截断,截断轮次跳过删除判定

Notion 单次 data source 查询最多返回 10,000 行。撞到上限时厂商把 has_more 置为
false,并在响应里带 request_status.type == "incomplete"
(incomplete_reason = "query_result_limit_reached"),而 connector 只认
has_more、不解析 request_status,于是"被截断"与"读完"在代码里完全同形:

- QueryDatabaseAll 返回 err == nil、10,000 条记录,日志照常打
  "database <id> (<title>): 10000 records",同步看起来完全成功;
- 增量同步里,本轮查询未返回、又没被 /v1/search 带出来的行,会被当成源端已删除
  下发 IsDeleted。开启删除同步时,已在库的文档连同向量被真实删除,而同步日志仍
  显示成功。

改动:

- types.go:paginatedResponse 增加 request_status 解析(notionRequestStatus /
  isIncomplete)。
- client.go:paginatePages 在每一页反序列化后判定 incomplete(厂商文档要求逐页
  检查,标记可能出现在最后一页之前),命中即返回可识别的
  errQueryResultTruncated,连同该页已取回的行,调用方既能拿到部分数据,也不会
  再把缺失行当作"源端已删除"的证据;QueryDatabaseAll 遇到截断不再走
  "当作 database_id 再解析一次"的回退,避免重复同一次受限查询并把截断错误埋在
  查找失败后面。
- connector.go:截断信号经 queryDatabaseRecords 传到
  fetchDatabaseIncremental / fetchDatabase / fetchPage,本轮只要出现过截断,删除
  判定整体跳过(与 #3682"发现请求失败即中止、不删"同一取向);计数与日志改为
  带截断标记的 Warn,让"同步成功但文档数偏少"可解释。

新增回归测试 internal/datasource/connector/notion/query_truncation_test.go:截断
(含中途页截断)必须返回哨兵错误且不重试、端到端不产生 IsDeleted、子数据库路径
同样传出截断;同时锁定正常 has_more=false 无 request_status 的结果集行为不变
(正常读完仍照旧判定删除)。反向验证:去掉逐页判定后 4 条断言失败的用例失败、
3 条保护性用例通过,随后逐字节还原。

按 created_time 开新窗口的分页改写(厂商大数据源食谱)改动面较大,留作后续改动:
本次修复只保证截断可见、不误删;超过上限的记录仍不会被这批同步收进知识库。

* fix(notion): 数据源查询按 created_time 开窗口,超过 10,000 行的记录也能取全

Notion 单次 data source 查询最多返回 10,000 行:撞限时厂商把 has_more 置为 false,
并带 request_status.type == "incomplete"(incomplete_reason ==
"query_result_limit_reached")。本 PR 的前一版让截断可见、不再误删,但被截断的记录
仍然进不了知识库——一次查询的上限就是一次查询的上限,只跟着 next_cursor 走永远读
不到第 10,001 行。

按厂商"大数据源"食谱改为时间窗口分页(用 created_time,不用会随编辑移动边界的
last_edited_time):

- types.go:notionPage 增加 created_time,作为窗口边界。
- client.go:数据源查询改走 queryDataSourceAll / queryDataSourceWindow。每个窗口都
  带 sorts: [{timestamp: created_time, direction: ascending}],窗口内继续按
  next_cursor 翻页;只要该窗口任意一页带 incomplete 标记(厂商明确要求逐页检查,
  标记可能出现在最后一页之前),就用 filter.created_time.on_or_after = 本窗口最后
  一行的时间戳开下一个窗口,累计结果按行 ID 去重(相邻窗口共享边界行,边界行只会
  入库一次)。窗口推进必须严格前进:没有任何行带 created_time,或窗口最后一行的时间
  戳没有超过窗口起点(同一 created_time 的行数超过单次查询上限)时停止续窗、打 Warn
  并返回 errQueryResultTruncated,绝不原地重查。每次续窗都打一条 Warn,截断仍然留痕。
- connector.go:queryDatabaseRecords 的截断日志改为"撞上限且窗口无法推进";"截断轮次
  跳过删除判定"的行为保持不变(现在的截断只可能来自无法推进的窗口)。

回归测试:新增 query_windowing_test.go,用按请求里的窗口过滤条件返回数据的假服务端
覆盖跨 4 个窗口取全 5 行并按行 ID 去重、同一窗口内的重复行去重、incomplete 标记落在
非末页时仍然开新窗口、未撞上限的正常路径行为不变(request_status 为 complete 与完全
缺失两种形态)。query_truncation_test.go 改写为:窗口无法推进(同一 created_time 超
限、行不带 created_time、空窗口仍 incomplete)时停止并告警、端到端不产生 IsDeleted;
另加窗口取全后仍照常判定源端真实删除的用例,防止"一有窗口就不再删"的过度修复。

反向验证:把窗口续读改回"撞上限即中止"后,窗口取全相关用例全部失败(QueryDatabaseAll
报 "vendor limit reached ... 2 records fetched",端到端漏报 r4 的删除),"正常路径行为
不变"与"截断不误删"的用例继续通过,随后逐字节还原。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
2026-10-07 23:54:08 +08:00
hailongzhao bccb4b151b fix(embed): 内嵌网页只传图片不输入文字时不再返回 400
内嵌网页的输入框允许只带图片或附件就点击发送,但 CreateKnowledgeQARequest.Query
带有 binding:"required",parseQARequest 也拒绝空 query,于是只传图片直接返回
400 "Query content cannot be empty"。

入口处理:去掉 binding:"required";文字为空但带有内联图片数据或内联附件时,
用 types.UploadOnlyQuestion 生成一句替用户提问的问题(中文界面为「请根据我
上传的内容回答。」,其他语言为英文),交给模型、检索、标题、会话历史索引、
追问建议和记忆使用。只有 URL 的图片不算上传,因为客户端传入的图片 URL 会被
清掉;预上传的 attachment_ids 也不算,这类文件在流开始后才解析,可能失败或
超时,届时模型没有任何内容可答。其余空 query 仍返回 400。

存储与显示:qaRequestContext 新增 userInput,保存用户消息时只存用户实际
输入,只传图片时为空,刷新后与发送当下显示一致;query 仍是给模型的问题。
steer 追问复制上一轮的请求上下文,显式设置 userInput,避免在只传图片的一轮
之后把追问存成空消息。

会话历史:文字为空但带图片或附件的用户消息,在两处历史重建里补上同一句
问题。知识问答流水线(loadAndProcessHistory)原先会整轮丢弃;Agent 历史
(LoadAgentHistory)原先会发出空的用户消息,被 SanitizeMessages 剔除后
前后两条回答被合并。

去掉 binding 标签会让 gofmt 重新对齐整个 CreateKnowledgeQARequest 的行尾
注释,这些既有的超长行因此会被 PR 的增量 lint 视为新增。按仓库惯例把字段
注释移到字段上一行(注释文字不变,swagger 描述不受影响),并把 Go 字段
KnowledgeIds 改名为 KnowledgeIDs(JSON 名仍是 knowledge_ids,接口不变)。

同步更新 swagger 文档,query 不再是必填字段。
2026-09-30 15:26:51 +08:00
wizardchen 75fc0ad159 feat(docparser): upgrade AnyDoc to 0.2.4 and parse assets once 2026-09-30 15:25:01 +08:00
linus-liu-web 1dbe9d0c1a
fix(gitlab): 仓库文件下载补体积上限,超限报错而不是无界读入 (#3887)
* fix(gitlab): 仓库文件下载没有体积上限,超限改为显式报错

getRaw 直接用 io.ReadAll 缓冲整个 blob,get/getPage 的 JSON 读取同样无界。
GitLab 的 tree/compare 接口不返回 blob 大小,下载处是唯一能拦的地方,所以
同步一个音频或大 PDF 就会把一个完整 blob 读进进程内存。

对齐兄弟 connector(钉钉 16MiB JSON 上限、飞书 512MiB 下载上限):

- maxJSONResponseBytes(16 MiB)用于 get/getPage;
- maxRawFileBytes(512 MiB,与飞书 maxFeishuDownloadBytes 对齐)用于 getRaw;
- base64 回退走 getCapped,其请求体是 base64 后的 blob(约 4/3)加信封。

超限返回错误而不是截断:截断的正文会被当成完整文档入库。非 2xx 状态先于
读取判定,避免超大错误页把真实状态码盖掉。

* fix(gitlab): 将 compare 响应上限与元数据分开

compare 正文包含完整提交和 patch,沿用 16MiB 元数据上限会中断增量同步且游标无法前进。超限错误改为带上未编码的仓库路径。

---------

Co-authored-by: linus-liu-web <11640009+linus-liu-web@users.noreply.github.com>
Co-authored-by: wizardchen <wizardchen@tencent.com>
2026-09-30 14:33:15 +08:00
linus-liu-web b71b31c897 fix(ima): 笔记正文被清空后旧正文仍留在知识库
fetchNote 在正文为空时返回 fetchSkipped,walk 只把该 key 记进增量游标而
不产出任何 item。于是重新读到一篇已被清空的笔记时,入库层收不到「内容变
空」的信号:旧正文既不会被替换,游标还把它记为已同步。

Notion(b9be7d0d)与 Confluence 早就是这个写法:正文为空时仍然产出只有
标题的 markdown,让入库去替换旧正文。这里对齐同一写法,空正文改成
"# <title>\n" 照常走 fetchOK。
2026-09-30 13:43:55 +08:00
linus-liu-web 2ec1774623 fix(auth): 令牌写入失败不再当成登录成功,查询失败不再谎称已撤销
generateTokensForTenant 把两次 CreateToken 的错误都丢给了 `_`,然后照常返回
token 对。签发出去的 JWT 签名正确、语法合法,但 auth_tokens 里没有行,
ValidateToken / RefreshToken 在下一次请求就把它拒掉——用户看到的是"刚登录就掉
线,反复登录都一样"。更糟的是校验侧把"查不到"和"已撤销"合并成同一个分支:

    if err != nil || tokenRecord == nil || tokenRecord.IsRevoked {
        return nil, 0, errors.New("token is revoked")
    }

于是真实的插入错误既没有落日志,也被贴上了一个从未发生过的原因("token is
revoked"),把排查方向引向"会话被踢"。触发条件只是常规基础设施抖动:语句超时、
连接池耗尽、连接被重置。

同文件的对照写得很清楚:SwitchTenant 对同类写入 `return fmt.Errorf(...)`("a
200 response is also a durable landing-preference update"),Logout 直接返回
RevokeTokensByUserID 的错误;这两处是全文件唯一"写完不检查"的地方。

改动:
- 两次 CreateToken 都检查错误,失败即 `persist access token/refresh token: %w`
  返回,保证"登录成功"一定对应已持久化。正常路径不变:两行都写成功才返回令牌对。
- ValidateToken / RefreshToken 把查询错误与"已撤销/不存在"拆开:查询失败按基础
  设施错误上报(`look up token: %w`),`IsRevoked` 仍然报 "token is revoked",
  不再用一句假话掩盖查询失败。

新增用例(internal/application/service/user_token_persistence_test.go):
- 写入失败时 Login 必须 Success=false 且不下发任何令牌;
- 访问令牌/刷新令牌任一写入失败都不得返回令牌;
- 正常路径回归:两行都落库、access token 随后能通过 ValidateToken;
- 查询失败如实上报(errors.Is 命中原始错误,且不含 "token is revoked");
- 真的被撤销时 "token is revoked" 仍然保留。

L2 复现(假 token repo 返回写失败):修复前 Login 返回 success=true、
tokenIssued=true,紧接着用该 token 请求得到 "token is revoked";修复后 Login
返回 success=false、message="Login failed"、不下发令牌。去掉 user.go 的改动后
新增用例 5 个子用例全红,两条正常路径回归用例仍绿。整个 service 包
`go test ./internal/application/service/` 通过,scoped golangci-lint 0 issues。
2026-09-30 13:40:51 +08:00
hailongzhao 176aa0d02b fix(sandbox): build real arm64 sandbox images and ship arm64 Cube variants
The global `ARG TARGETPLATFORM=linux/amd64` in Dockerfile.sandbox overrode
the per-platform value BuildKit injects, so the multi-platform CI build ran
every platform on the amd64 rootfs and only relabeled the arm64 config.
The published arm64 entries of main, latest and main-desktop are byte-for-byte
the amd64 layers. The stage-level `ARG TARGETARCH=amd64` had the same effect,
so the cube "amd64 only" guard could never fire.

- Declare TARGETPLATFORM without a default and fall back to linux/amd64 in
  FROM only when it is empty (legacy builder).
- Fail the runtime stage when the rootfs architecture differs from
  TARGETARCH.
- cubesandbox-base:2026.16 publishes linux/arm64 as well, and Cube runs on
  arm64 bare-metal KVM (PVM stays x86_64-only). Follow TARGETPLATFORM for
  cube-base, replace the amd64-only guard with an envd-vs-rootfs check, and
  build cube / desktop-cube for linux/amd64,linux/arm64 in CI and
  build_images.sh.
2026-09-30 13:34:01 +08:00