Compare commits
13 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6e67034fbd | |||
| 76671e0784 | |||
| 8835a473dd | |||
| 93aabc8a81 | |||
| 3e7fcce0b1 | |||
| 74ba737b1e | |||
| 013ce4a24e | |||
| 90901a4458 | |||
| 3566f208e0 | |||
| 2ea2111420 | |||
| 828c2c5fa0 | |||
| 4b3aaff321 | |||
| 9556db1ef0 |
+369
-1
@@ -4,6 +4,17 @@
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
|
||||
|
||||
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
|
||||
|
||||
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。基础数量与本期经确认新增的质量比例分开显示;不接 AI 模型、不定义绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
|
||||
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
- 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
@@ -26,6 +37,8 @@
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
@@ -60,9 +73,364 @@
|
||||
> **版本怎么走**(两行就够):
|
||||
> · **正式版本** = 下面那条 `## [x.y.z] - 日期`,是**发版事实**,由人批准后打注释 tag `vX.Y.Z`;
|
||||
> · **开发版本自动递增** = `<正式版本的主.次>.<自那个 tag 以来的提交数>`(正式 `0.1.0` 之后第 12 个提交 =
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**,**不写进本文件** ⇒ 每个提交都有自己的版本号,
|
||||
> `0.1.12`),由 `scripts/version.py` 从 git **算出来**;开发交付的独立说明写入本文件“开发快照”章节,并打 `snapshot/vX.Y.Z` 注释标签 ⇒ 每次开发交付均可追溯,
|
||||
> 但"发布版本"仍然只能由人定(CI 不会自动升版本、不会打 tag)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.32 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问题统计看板按参考布局提供完整十一项:2.0 累计问题、本周新增、覆盖率与正确率半环、问题类型饼图、产品横条排行、所选自然周逐日折线、区域平均使用频率与使用覆盖率、两条历史质量周趋势。未知分类保留为未分类,未知分母及历史缺失点不伪造为零。
|
||||
- 支持导出当前完整看板 PNG,包含所有图形、中文、图例与数值,独立于屏幕滚动高度;不包含导航、筛选控件、按钮或个人月明细。桌面与窄屏共享同一份数据及响应式图形。
|
||||
- 治理侧保存自然周质量冻结快照与逐条标量贡献;普通 worker 在符合采集条件的下一周一自动冻结上一周,保存实际时点、源观测、版本和分子分母。首次启用前、错过采集或没有完整观测的历史周保持空白,后续人工改判不回写已冻结比率。
|
||||
|
||||
### Changed
|
||||
|
||||
- 看板通过单一只读一致性接口聚合治理副本、有效质量与组织版本,不连接源端、不下载全部长答案;累计、所选自然周和截止月分别计算,原问题关键词按字面筛选。区域分母使用配置后的通讯录去重人数,仅用于使用统计,个人月明细与四页共享查询保留。
|
||||
- 新增加表迁移 52。应用回退保留加表;发现冻结历史时拒绝有损 down。未接入翻译/AI 评估模型、绩效名单、1.0 归档或自动发送。
|
||||
|
||||
### Security
|
||||
|
||||
- 统计接口维持固定租户、管理员会话、同源动作头、严格 JSON 和 no-store;输入指纹变化返回冲突,不混合新旧结论。数据库拒绝修改、删除或追加已提交的冻结贡献;浏览器查询不写指标,PNG 使用自包含 SVG,不加载外部图片或执行原始 HTML。
|
||||
|
||||
## 开发快照 snapshot/v0.1.31 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 区域配置支持新增、改名业务区域;稳定区域 ID 与部门映射同版本保存,改名不丢失归属。部门按一级、二级、三级及更深层级展示,支持层级/完整路径筛选、多选及批量归属。
|
||||
- 勾选、批量应用、预览和保存分离;取消本次勾选不删除既有映射,批量配置父部门不清除未选子部门的显式规则。预览核对去重人数,保存后独立读取并校验配置版本。
|
||||
|
||||
### Changed
|
||||
|
||||
- 新增治理库迁移 51,为历史区域修订补齐原四区目录;业务目录与映射原子留档,跨页问答、看板、使用统计、个人月明细和周报共用同一版本及名称。旧请求未传目录时沿用当前目录,不恢复固定四区白名单。
|
||||
- 迁移回退发现自定义区域历史时拒绝丢失目录;应用回退可保留加列迁移。统计人数不升级为在职或绩效分母,不改钉钉组织、DobotAI 原始数据及旧 Excel 流程。
|
||||
|
||||
### Security
|
||||
|
||||
- 配置请求拒绝缺失版本、重复 JSON 字段及嵌套 null;区域目录校验稳定 ID、重名及保留键,名称按文本展示,自定义名称不读取原型属性。保留管理员同源写入、租户隔离和双版本冲突保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.30 - 2026-10-18
|
||||
|
||||
### Changed
|
||||
|
||||
- 继续清理问答运营的冗余提示:质量统计移除完整范围留档、模型接入和读取时间说明;个人月明细移除重复的绩效/零记录解释及读取时间,保留实际数量、范围版本、分页和真实错误。质量统计按钮使用简短名称,不改统计与审计逻辑。
|
||||
|
||||
## 开发快照 snapshot/v0.1.29 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营调整为“问题流水、问题统计看板、区域配置、周报生成”四页,流水与看板共用年份、自然周和查询条件;区域页不再显示问题查询框,完整字段及人工复核入口保留。
|
||||
- 重做统计看板:展示完整筛选范围的问题量、覆盖率、正确率、人工复核、北京时间每日趋势、质量分布、区域、问题类型和产品分类;个人月明细折叠保留,未知分类与零分母不虚构结论。
|
||||
- 周报页提供手动草稿、Markdown 预览及 MD/完整明细 CSV 下载。核对副本版本、完整数量、质量范围与覆盖分布后生成;CSV 保留完整十五列并防护公式注入,不发送、不归档、不作为正式持久化周报验收。
|
||||
|
||||
### Changed
|
||||
|
||||
- 删除问答记录、同步栏和区域页中的冗余解释文字、读取时间与源连接提示,保留真实错误、未同步、权限阻断和安全告警。
|
||||
|
||||
## 开发快照 snapshot/v0.1.28 - 2026-10-18
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营新增持久本地副本,每 5 分钟后台同步并支持立即同步;列表、详情、检索、质量范围和使用统计改为读取本地数据库。
|
||||
- AI 答案详情提供安全 Markdown 预览与原文查看,支持表格、代码块和链接;不执行原始 HTML,外部图片默认不请求。
|
||||
|
||||
### Changed
|
||||
|
||||
- 增加治理侧问答副本表与同步状态;同步由普通 worker 执行,使用独立只读源连接,源失败保留最后成功副本,权限校验失败阻断读取。
|
||||
- 副本激活与质量输入变化的复核失效同事务提交;同步持久去重、租约校验及重启恢复不改变源问答或现有生产写入。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 本地读取不再逐条重复写质量留档或解压完整范围长答案来统计字段,保留完整列、输入版本一致性和真实缺失值。
|
||||
- 初次观察即已同步完成时自动重查列表,避免较早的首次未同步错误一直停留。
|
||||
|
||||
## 开发快照 snapshot/v0.1.27 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- 并行分支存在同号开发提交时,历史变更说明与补记标签计划按完整 SHA 选择,不再被前一条同号记录遮蔽;不强改推导版本号或移动既有标签。
|
||||
|
||||
## 开发快照 snapshot/v0.1.26 - 2026-10-18
|
||||
|
||||
### Fixed
|
||||
|
||||
- 版本记录收录已交付开发快照与当前运行提交,不再只同步 main;开发版本显示对应的独立变更说明。
|
||||
- 修复同步重复返回旧已完成任务:进行中同步合并,完成后允许新一轮同步。
|
||||
- 构建启动后自动请求版本同步;部署后独立读回当前完整 SHA、开发标签与变更说明,缺失时不宣称交付完成。
|
||||
|
||||
### Added
|
||||
|
||||
- 增加开发快照计划、显式发布及远端读回工具;历史说明按原提交补记,正式 tag 与 Release 保持独立授权。
|
||||
|
||||
## 开发快照 snapshot/v0.1.25 - 2026-10-18
|
||||
|
||||
目标提交:90901a4458054aca721047c9a2896f2130d46b5c
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增“本周”快捷查询,默认展示北京时间本周数据;所选范围自动读取全部记录,校验完整数量后展示,不再需要分页或加载更多。固定展示完整字段,空列不再隐藏,中文原文直接展示、外语未翻译明确标记;保留源端有界传输、取消和失败保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.24 - 2026-10-18
|
||||
|
||||
目标提交:3566f208e0e15fdec2cc98c29f93c46f5f7c91ca
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答记录新增年份与自然周选择,周次展示起止日期,支持跨年及每年实际周数;按北京时间周一至周日填入查询范围,默认本周且仅查询截至当前的数据。保留自定义时间与原查询按钮,浏览器时区不改变查询边界。
|
||||
|
||||
## 开发快照 snapshot/v0.1.23 - 2026-10-18
|
||||
|
||||
目标提交:2ea2111420e501fec37e0ea0c4bcd3cd8c866403
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 修复通过带端口的 HTTP 地址访问问答运营时,正常同源操作被误报“拒绝跨站配置请求”:网页代理保留原始 Host 及端口,使缺少 Fetch Metadata 的浏览器也能正确执行 Origin 校验。保留后端跨站、异端口、伪造转发头与缺失操作意图的拒绝保护。
|
||||
|
||||
## 开发快照 snapshot/v0.1.22 - 2026-10-18
|
||||
|
||||
目标提交:828c2c5fa0d4e3e0eee3987085a4d782872f7e95
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营按已确认口径显示知识覆盖率、回答正确率及原始分子/分母、排除数量与构成。使用完整筛选范围和当前有效人工优先结论,精确规则命中的未覆盖可进入覆盖分母;部分覆盖不算完全覆盖,待确认/未评估/失效/不计入按对应指标排除,零分母显示“暂无可计算数据”。返回独立规则版本,AI 模型与绩效范围仍未接入。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。基础数量与本期经确认新增的质量比例分开显示;不接 AI 模型、不定义绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
## 开发快照 snapshot/v0.1.21 - 2026-10-17
|
||||
|
||||
目标提交:4b3aaff3219e78ae3dfd5d12ba36f82e323a21ba
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答详情支持治理侧人工复核及不可变审计:覆盖、正确性、产品分类、问题类型、根因与理由由管理员明确填写,操作人取登录身份;保存后独立读回复核历史。保留源端判断和自动规则,输入变化使旧人工结论失效,已观测的内容回退不自动恢复旧结论;并发修改冲突、重复请求不重复留档。
|
||||
- 新增覆盖复检历史、已采集输入快照和完整筛选范围质量数量。批量统计只传指纹与规则命中元数据,原文在读取问答/复核时采集,未采集版本明确提示而非伪造空快照;源事务时点阻止延迟旧扫描回退新输入。仅提供数量,不接 AI 模型、不定义质量率或绩效分母、不回写 DobotAI 原问答。
|
||||
|
||||
## 开发快照 snapshot/v0.1.20 - 2026-10-17
|
||||
|
||||
目标提交:9556db1ef01add21064553f64be6a7e25f838e9e
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 「使用统计 → 个人月明细」按北京时间自然月及截止时点展示当前应用可见名册的人员用量(包含本源零记录),支持部门含子部门、区域/待核对状态、姓名/完整部门路径和已有提问/零记录筛选。稳定身份关联去重、不可关联问答单列、过期组织版本阻断翻页;源端姓名可缺失并提示重新同步,不按姓名匹配身份。姓名筛选通过有界只读 POST 请求体传递、不进入 URL,原始员工标识不返回浏览器;名册不作为在职/考核分母,当月进度不作为绩效结论。
|
||||
|
||||
## 开发快照 snapshot/v0.1.19 - 2026-10-17
|
||||
|
||||
目标提交:56b8cabed9213911b6beb4aeaac9baa22e872a00
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 问答运营按稳定身份关联当前治理通讯录,缺失部门/区域补全并保留源快照及目录/区域版本;空列判断包含完整筛选结果,不混合配置已变化的分页。新增完整时间/关键词范围的使用统计,问答计次、名册内人员去重,跨区/未匹配/身份缺失分列,不输出绩效结论;不回写 DobotAI 原表。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。基础使用统计见本期新增,不代表绩效验收;翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估尚未接入,不标为第一阶段完成。
|
||||
|
||||
## 开发快照 snapshot/v0.1.18 - 2026-10-17
|
||||
|
||||
目标提交:cc4906b6a9f33683a5c0017d83b24d96d5c997b1
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 「问答运营 → 区域使用」支持管理员从网页发起持久化通讯录同步,重复请求重放、进行中操作合并;按服务器固定范围注册后台执行器,未接线或未检测到心跳时不创建新任务。界面显示真实任务状态、不编造百分比;失败保留旧快照与区域规则,同步完成不覆盖未保存草稿。旧执行器丢失租约后不能激活结果,重启接管和已提交快照的续跑使用原任务。
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;问答组织关联尚未接入。同步默认关闭,容器启用仍需批准的既有周报 SDK/配置及兼容 Python 运行时挂载。
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
|
||||
## 开发快照 snapshot/v0.1.17 - 2026-10-17
|
||||
|
||||
目标提交:6adfdcdd4fe0e5c35018bf0e4857c203dd24e5d1
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 区域归属表支持长部门路径换行,避免继承全局不换行规则后将生效区域与归属依据列挤出桌面面板。
|
||||
|
||||
## 开发快照 snapshot/v0.1.16 - 2026-10-17
|
||||
|
||||
目标提交:5874134e049b0896a202b41d9d400d1be5386f89
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- 新增治理侧通讯录实时桥接,复用既有周报读取能力,向源端读取真实缺失祖先以补齐部门树;不改旧周报脚本、配置或输出。私有 JSON 与受控子进程执行器拒绝不完整数据、模拟同步、公开文件和异常输出,超时清理临时人员文件;网页触发的后台同步队列及问答组织关联尚未接入。
|
||||
|
||||
## 开发快照 snapshot/v0.1.15 - 2026-10-17
|
||||
|
||||
目标提交:dab74b706b5b87da3ecb71a8e0f6b6caa5fba4ad
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「问答运营 → 区域使用」区域归属配置切片**:按稳定部门 ID 搜索和勾选完整路径,预览去重归属人数,保存版本后重新读取;父部门包含子部门、子部门显式配置优先,多部门跨区域人员单独待核对。预览不写入,过期版本和不完整部门树被阻断。当前不是实时通讯录同步或使用/绩效统计验收,翻译及 AI 评估模型接入按用户要求暂缓。
|
||||
- 新增治理侧组织快照与区域修订迁移、受确认保护的后台导入命令;不修改 DobotAI 原表或钉钉组织结构。
|
||||
|
||||
## 开发快照 snapshot/v0.1.14 - 2026-10-17
|
||||
|
||||
目标提交:fd04bf7886aa4eba68b247dd7c1092894a5282da
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「问答运营 → 问答记录」首个开发切片**:在现有导航中查看 DobotAI 2.0 钉钉问答,支持半开时间范围、原问题关键词、稳定游标分页和完整详情;按整个筛选结果隐藏空列,反馈聚合不放大问答条数。外语翻译、AI 评估、人员区域映射尚未接入,不标为第一阶段完成。
|
||||
- 治理侧重新检查答案:包含 `暂无已发布` 即未覆盖,引用和源端 covered 不能抵消;未命中仍待评估,源端规则单独保留作对照。独立只读源默认关闭、租户后端固定、管理员会话鉴权,源故障不回退治理主库;安全告警明确保留 TEMP/TLS 尚未整改状态。
|
||||
- **「版本记录」页**(一级入口):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
|
||||
## 开发快照 snapshot/v0.1.13 - 2026-10-14
|
||||
|
||||
目标提交:c1d49adb622f3bf18e51bddb415795a894ed227e
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 补三Agent交接闭环工作流(状态机、快照tag与验收模板)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.12 - 2026-10-14
|
||||
|
||||
目标提交:9a8a3e77956149d116360bbb561efd67e20fb062
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **登记钉钉知识库失败(HTTP 409 `space_registration_conflict`)的真实原因与修复**:`source_connections.name` 有唯一约束,而早期路径登记的钉钉来源(`base_url` 为空、id 与 dws 现在推导的确定性 id 不同)被**归档后仍占着名字槽位** ⇒ 重新登记时 INSERT 撞唯一约束;处理器又把**所有**存储层错误都翻译成同一个 409,真实原因被吞掉(线上只能看到一个无细节的错误码)。现在:① 同名来源**已归档**时,把它改名腾位(`…(已下架 · <短ID>)`,归档行不显示、数据与审计一行不动);② 同名来源**仍在使用**时返回 `space_name_conflict` + 可行动提示(先「去掉来源」);③ 同一登记键指向别的空间且该行仍在用时返回 `space_identity_conflict`(已归档的行则允许就地改写 —— 这就是"去掉后再用 dws 重新获取");④ 其余内部故障改回 **500** `space_registration_failed`,不再伪装成冲突;前端优先显示后端 `hint`,并为这两个新码补了中文说明。
|
||||
|
||||
## 开发快照 snapshot/v0.1.11 - 2026-10-14
|
||||
|
||||
目标提交:2c7265efc47a2cd6b324bf278fa5ddb0c4a9fe57
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → 数据源配置」**收敛成两个入口**:**dws 导入**(按当前钉钉账号列出可访问的知识库与钉盘空间)与 **PP 导入**。AList(已由钉盘文件替代)、静态登记的钉钉知识库、本地手工导入与 PP legacy 都**不再出现在这一页**;已接入的这类来源用**归档**下架(`POST /api/v1/source-connections/{id}/archive`,管理员、幂等,带写意图头与幂等键):从列表、来源与目录、计划刷新与手动扫描里消失,**目录快照、发布记录与审计数据一行不删**。恢复用 `…/restore`(保持停用、不自动带回调度),或让 dws 重新登记同一来源 —— 钉钉空间登记是确定性 ID + `ON CONFLICT`,**原地复活同一行、不产生重复**。卡片上新增「去掉来源」按钮(管理员,带确认弹窗)。
|
||||
- 迁移 `000047_source_connection_archive`:新增 `archived_at` / `archived_by` 与只覆盖未归档行的部分索引;列表、目录、计划刷新、手动扫描四类查询一律排除归档行(漏一条就等于入口没去掉)。
|
||||
|
||||
## 开发快照 snapshot/v0.1.10 - 2026-10-14
|
||||
|
||||
目标提交:64b32c2da64881b3c9bf6de6b8f9af3f833128fd
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 「系统设置 → 数据源配置」默认只列 PP 资料与「可加入的来源」:AList 来源(已由钉盘文件替代)与静态登记的钉钉知识库来源(改为按当前钉钉账号发现)**不再默认列出**,收进「显示 AList/钉钉知识库来源(N)」折叠开关 —— **来源一个都没删**,展开后照旧可改刷新周期与启停,「来源与目录」里的内容不变。手动导入来源(本地手工验收)不在这次范围内,照旧显示。
|
||||
|
||||
## 开发快照 snapshot/v0.1.9 - 2026-10-14
|
||||
|
||||
目标提交:b7f7e4f12101569db5bb76af9d836043eefc342b
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- **上线前护栏 + 事故复盘**:`scripts/deploy-api-web.sh` 现在先校验 `.env` 的键值形状(值里再出现 `KEY=` 或键名不合法 ⇒ **拒绝上线**),配置校验失败时也会给出"两行粘成一行"的线索。事故:`.env` 最后一行没有结尾换行、又被追加新键 ⇒ 两行粘成一行 ⇒ `VERSION_HISTORY_GITEA_BASE_URL` 变成非法值 ⇒ api/worker 按设计拒绝启动、崩溃重启(平台整体不可用)。已修数据、加护栏、加回归用例。
|
||||
|
||||
## 开发快照 snapshot/v0.1.8 - 2026-10-14
|
||||
|
||||
目标提交:4cb51108454c3559e8a6305ad3316f74ed4e2daf
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 「版本记录」页的链接改为**抓取与链接分离**:抓取仍走配置的(内网)地址,页面上的「查看提交 / 查看 tag」用 `VERSION_HISTORY_LINK_ORIGIN`(公网 origin)拼 —— 原先两者共用内网地址,内网外的浏览器点开是空白;另外 tag 记录原先不带链接(空 `href` 点下去没反应),现在补上链接、没有链接就不渲染该按钮。
|
||||
|
||||
## 开发快照 snapshot/v0.1.7 - 2026-10-14
|
||||
|
||||
目标提交:90db243a68a5d16d643dd0273614b93666d65ca7
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 前端入口与静态资源的缓存语义("新功能看起来没上线"与"页面偶尔裸奔/空白"的根因):
|
||||
|
||||
## 开发快照 snapshot/v0.1.6 - 2026-10-14
|
||||
|
||||
目标提交:062a3b3cb60ede5ebcca64a0f14df53fffa1f359
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Fixed
|
||||
|
||||
- 前端入口的缓存策略:`index.html` 此前没有缓存头,CDN/浏览器会启发式缓存它,于是**页面会一直停在旧构建上**(实测被腾讯云 EdgeOne 卡住:源站已是新包,公网入口仍发旧包,看起来像"新菜单/新页面没上线")。现在 `index.html` 每次回源校验(`no-cache, must-revalidate`)、带内容哈希的 `/assets/` 长缓存(`immutable`),旧哈希资源明确 404 而不是回退成 HTML。
|
||||
|
||||
## 开发快照 snapshot/v0.1.5 - 2026-10-14
|
||||
|
||||
目标提交:4d43a9386a8a97969a1568956213f6f17b13edfb
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- tag 之前的提交不再被编号 + 部署脚本注入构建身份。
|
||||
|
||||
## 开发快照 snapshot/v0.1.4 - 2026-10-13
|
||||
|
||||
目标提交:0974d8dfa2aad5650eefbcee3edb365a8afd4868
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Added
|
||||
|
||||
- **「版本记录」页**(一级菜单第 5 项):只读时间线追踪**远端 main 可达的全部提交**(含合并提交与已并入 main 的侧分支提交),按提交时间倒序显示标题/正文、`[正式版本] / [开发版本] / [历史提交]` 徽标、短 SHA、提交内变更记录与 `[查看提交]`/`[查看 tag]`;支持「全部 / 正式 / 开发 / 历史」筛选与游标翻页,窄屏单列。
|
||||
- 新增只读接口 `GET /api/v1/build-info`(当前运行产物的构建身份)、`GET /api/v1/version-history`(快照游标分页,不返回伪造的 total)、`POST /api/v1/version-history/sync`(仅管理员手动同步,并发同步复用同一作业)。
|
||||
- 新增迁移 `000046_version_history`(提交记录 + 同步状态):`commit_sha` 是唯一身份,**版本号不是唯一键** —— 两个提交算出同一个开发号时各占一行,用 SHA 区分。
|
||||
- 「当前运行」只认运行产物注入的**完整 SHA 精确匹配**:匹配到就标该条;开发构建显式标注"开发构建";拿不到标识就显示"当前运行版本未知",**不拿最新 main 或最新 tag 顶替**;CI 成功不等于已部署。
|
||||
|
||||
### Security
|
||||
|
||||
- 版本记录同步**匿名只读**远端仓库(**不使用任何凭据**),来源限配置里批准的 origin 与固定仓库:拒绝任意 URL、拒绝跨主机重定向,单个响应设大小上限与超时、5xx/429 才有退避重试。
|
||||
- 提交正文与变更记录一律按**纯文本**渲染(不产生 HTML/脚本注入面);页面不含打 tag / 发布 / 部署入口;同步动作仅管理员可用,服务端再次判角色。
|
||||
|
||||
## 开发快照 snapshot/v0.1.3 - 2026-10-13
|
||||
|
||||
目标提交:ad9c5d20d467a077e88bbfe63b1a56355d263e51
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- Merge remote-tracking branch 'origin/main'。
|
||||
|
||||
## 开发快照 snapshot/v0.1.1 - 2026-10-13
|
||||
|
||||
目标提交:3a1d32da8fba90eb5081865b1f3ad424a46639ee
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 重写平台定位与能力边界并归档原说明。
|
||||
|
||||
## 开发快照 snapshot/v0.1.1 - 2026-10-13
|
||||
|
||||
目标提交:950c1b429bc814d9fa7c2c1449f999a05537af21
|
||||
|
||||
历史开发快照补记,不改变原提交、原提交时间或正式发布状态。
|
||||
|
||||
### Changed
|
||||
|
||||
- 抬档门禁(破坏性 ⇒ 0.x 抬次 / ≥1.0.0 抬主)+ 1.0.0 前置(稳定契约承诺)。
|
||||
|
||||
## [0.1.0] - 2026-10-13
|
||||
|
||||
### Added
|
||||
|
||||
+94
-1
@@ -48,6 +48,7 @@
|
||||
"get": {"tags":["QA operations"],"operationId":"getQAOrganizationSync","summary":"管理员读取通讯录同步执行器状态及最近任务的安全汇总,不返回人员名单或运行配置","responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"状态存储不可用,不伪装为空记录"}}},
|
||||
"post": {"tags":["QA operations"],"operationId":"startQAOrganizationSync","summary":"管理员同源发起持久化通讯录同步;重复请求重放同一任务,进行中任务合并;失败保留现有快照","parameters":[{"$ref":"#/components/parameters/IdempotencyKey"},{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false}}}},"responses":{"202":{"$ref":"#/components/responses/OperationEnvelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源操作"},"409":{"description":"操作标识与原请求冲突"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"同步未接线、执行器离线或入队失败;未创建新任务"}}}
|
||||
},
|
||||
"/api/v1/qa-ops/dashboard": {"post":{"operationId":"readQAOperationsDashboard","tags":["QA operations"],"summary":"管理员只读本地一致性看板:2.0累计、所选周、新增/质量/类别及截止月区域统计;历史质量仅真实冻结快照,缺失留空","description":"同一只读可重复读事务读取副本、有效质量及组织版本。不访问源端,不冻结或写入指标;区域分母为当前配置通讯录去重人数而非在职/绩效名单。冻结记录按保存的原始标量分子分母及问题文字支持字面关键词筛选,不用当前评估回填历史。","parameters":[{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-dashboard"}}],"requestBody":{"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["start","end"],"properties":{"start":{"type":"string","format":"date-time"},"end":{"type":"string","format":"date-time"},"keyword":{"type":"string","maxLength":200}}}}}},"responses":{"200":{"$ref":"#/components/responses/Envelope"},"400":{"$ref":"#/components/responses/BadRequest"},"401":{"description":"需要登录"},"403":{"description":"仅管理员同源读取"},"409":{"description":"质量输入指纹变化,拒绝混合数据"},"500":{"$ref":"#/components/responses/InternalError"},"503":{"description":"本地副本或一致性投影不可用,不返回伪零"}}}},
|
||||
"/api/v1/qa-ops/organization": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
@@ -69,7 +70,7 @@
|
||||
"operationId": "previewQAOrganizationRegions",
|
||||
"summary": "预览当前通讯录版本下的父子部门区域归属和去重人数,不保存修改",
|
||||
"parameters": [{"name":"X-Governance-Action","in":"header","required":true,"schema":{"const":"qa-organization"}}],
|
||||
"requestBody": {"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["directory_id","base_revision","rules"],"properties":{"directory_id":{"type":"string"},"base_revision":{"type":"string"},"rules":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["department_id","region"],"properties":{"department_id":{"type":"string"},"region":{"enum":["国内工业","APAC","EMEA","America"]}}}}}}}}},
|
||||
"requestBody": {"required":true,"content":{"application/json":{"schema":{"type":"object","additionalProperties":false,"required":["directory_id","base_revision","rules"],"properties":{"directory_id":{"type":"string"},"base_revision":{"type":"string"},"regions":{"type":"array","maxItems":100,"description":"可选业务区域目录;缺省沿用当前目录,空数组表示无区域;ID稳定不随名称改动。与rules同一版本原子预览/保存。","items":{"type":"object","additionalProperties":false,"required":["id","name"],"properties":{"id":{"type":"string","minLength":1,"maxLength":256},"name":{"type":"string","minLength":1,"maxLength":256}}}},"rules":{"type":"array","items":{"type":"object","additionalProperties":false,"required":["department_id","region"],"properties":{"department_id":{"type":"string"},"region":{"type":"string","description":"目录中稳定的区域ID,不是固定四区枚举"}}}}}}}}},
|
||||
"responses": {
|
||||
"200": {"$ref": "#/components/responses/Envelope"},
|
||||
"400": {"$ref": "#/components/responses/BadRequest"},
|
||||
@@ -99,7 +100,99 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/usage/people": {"post": {"tags": ["QA operations"], "operationId": "queryQAOperationsMonthlyPeople", "summary": "按北京时间自然月列出当前名册人员的2.0用量(含零记录),仅管理员,不返回原始员工标识,不作为在职/考核名单", "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "完整名册缺失或目录/区域版本变化,请同步/重新查询,不返回伪零"}}, "description": "只读查询,不写治理库或生产库;姓名筛选置于 JSON 请求体,不进入 URL;整名册指标不随人员筛选变化。第2页起须带首页目录、区域版本及 end 截止。", "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "required": ["month"], "properties": {"month": {"type": "string", "pattern": "^(?!0000)[0-9]{4}-(0[1-9]|1[0-2])$"}, "cutoff": {"type": "string", "format": "date-time"}, "region": {"type": "string", "description": "当前组织版本中的区域显示名称,或unassigned/cross_region;无效名称拒绝查询"}, "department_id": {"type": "string"}, "activity": {"type": "string", "enum": ["all", "used", "zero"]}, "search": {"type": "string", "maxLength": 100}, "page": {"type": "integer", "minimum": 1, "maximum": 100000, "default": 1}, "limit": {"type": "integer", "minimum": 1, "maximum": 100, "default": 30}, "directory_id": {"type": "string"}, "revision_id": {"type": "string"}}}}}}, "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-usage-read"]}}]}},
|
||||
"/api/v1/qa-ops/usage": {"get": {"tags": ["QA operations"], "operationId": "getQAOperationsUsage", "summary": "完整筛选范围内按当前通讯录和区域版本回看2.0问答使用;固定租户、管理员访问,不输出绩效结论", "parameters": [{"name": "start", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "end", "in": "query", "required": true, "schema": {"type": "string", "format": "date-time"}}, {"name": "keyword", "in": "query", "schema": {"type": "string", "maxLength": 200}}], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}}}},
|
||||
"/api/v1/qa-ops/quality/query": {"post": {"operationId": "queryQAQualityCounts", "summary": "按完整筛选范围读取指纹/规则元数据并留档统计,最多5000条;summary.rates 返回 quality-rates-human-first-v1、原始分子/分母、百分比与分母构成。覆盖率=covered/(covered+uncovered+partial),正确率=covered_correct/(covered_correct+covered_incorrect);失效/不计入/相应待确认与未评估排除,零分母percent=null。原文仅在读取问答/复核时采集", "parameters": [{"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"start": {"type": "string", "format": "date-time"}, "end": {"type": "string", "format": "date-time"}, "keyword": {"type": "string", "maxLength": 200}}, "required": ["start", "end"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/reviews": {"post": {"operationId": "saveQAQualityReview", "summary": "治理库追加人工复核,登录身份审计,源端只读,输入/复核乐观锁和nonce幂等;正确时根因为空,不计入须说明原因", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "X-Governance-Action", "in": "header", "required": true, "schema": {"type": "string", "enum": ["qa-quality"]}}], "requestBody": {"required": true, "content": {"application/json": {"schema": {"type": "object", "additionalProperties": false, "properties": {"input_hash": {"type": "string", "pattern": "^[a-f0-9]{64}$"}, "input_epoch": {"type": "integer", "minimum": 1}, "base_revision": {"type": "integer", "minimum": 0}, "nonce": {"type": "string", "pattern": "^[A-Za-z0-9_-]{16,128}$"}, "fields": {"type": "object", "additionalProperties": false, "properties": {"coverage": {"type": "string", "enum": ["covered", "uncovered", "partial", "pending", "excluded"]}, "correctness": {"type": "string", "enum": ["correct", "incorrect", "pending"]}, "product_category": {"type": "string", "maxLength": 128}, "problem_type": {"type": "string", "maxLength": 128}, "root_cause": {"type": "string", "maxLength": 2000}, "exclusion_reason": {"type": "string", "maxLength": 2000}}, "required": ["coverage", "correctness"]}, "reason": {"type": "string", "minLength": 1, "maxLength": 4000}}, "required": ["input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason"]}}}}, "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/quality/history": {"get": {"operationId": "listQAQualityHistory", "summary": "按当前固定租户查询不可变复检/人工历史,分别倒序分页,各20条", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "review_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}, {"name": "check_before", "in": "query", "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "输入或复核版本变化/重复操作载荷不一致,未覆盖原结论"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/records/{id}/quality/inputs/{epoch}": {"get": {"operationId": "getQAQualityInputSnapshot", "summary": "管理员读取已采集的历史质量输入快照,不另存人员关联/反馈字段;元数据留档但未采集原文返回409,不编造空快照", "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}, {"name": "epoch", "in": "path", "required": true, "schema": {"type": "integer", "minimum": 1}}], "tags": ["QA operations"], "responses": {"200": {"$ref": "#/components/responses/Envelope"}, "400": {"$ref": "#/components/responses/BadRequest"}, "401": {"description": "需要登录"}, "403": {"description": "仅管理员访问"}, "503": {"description": "独立只读源或治理组织存储不可用,不返回伪造的零值"}, "500": {"$ref": "#/components/responses/InternalError"}, "409": {"description": "该输入版本仅有指纹/规则元数据、原文未采集"}, "404": {"description": "当前授权范围内未找到记录/历史输入"}}}},
|
||||
"/api/v1/qa-ops/sync": {
|
||||
"get": {
|
||||
"operationId": "getQALocalMirrorSync",
|
||||
"summary": "读取本地问答副本与后台同步状态(只读本地,不探测生产)",
|
||||
"responses": {
|
||||
"200": {
|
||||
"description": "本地副本状态、最近成功时间、5分钟计划与安全作业进度;无问答原文/人员标识"
|
||||
},
|
||||
"400": {
|
||||
"description": "不接受查询参数"
|
||||
},
|
||||
"401": {
|
||||
"description": "未登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "仅管理员"
|
||||
},
|
||||
"500": {
|
||||
"description": "治理库不可用"
|
||||
},
|
||||
"503": {
|
||||
"description": "本地同步未接线"
|
||||
}
|
||||
}
|
||||
},
|
||||
"post": {
|
||||
"operationId": "enqueueQALocalMirrorSync",
|
||||
"summary": "同源管理员请求后台问答同步,持久去重,不同步阻塞查询",
|
||||
"parameters": [
|
||||
{
|
||||
"in": "header",
|
||||
"name": "X-Governance-Action",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"qa-records-sync"
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"in": "header",
|
||||
"name": "Idempotency-Key",
|
||||
"required": true,
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"minLength": 1,
|
||||
"maxLength": 128
|
||||
}
|
||||
}
|
||||
],
|
||||
"requestBody": {
|
||||
"required": true,
|
||||
"content": {
|
||||
"application/json": {
|
||||
"schema": {
|
||||
"type": "object",
|
||||
"additionalProperties": false
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"responses": {
|
||||
"202": {
|
||||
"description": "已入队/重放/合并;须轮询状态,不代表同步成功"
|
||||
},
|
||||
"400": {
|
||||
"description": "非法参数、null、未知字段或缺nonce"
|
||||
},
|
||||
"401": {
|
||||
"description": "未登录"
|
||||
},
|
||||
"403": {
|
||||
"description": "非管理员/跨站/缺操作意图"
|
||||
},
|
||||
"409": {
|
||||
"description": "相同nonce的操作人/载荷冲突"
|
||||
},
|
||||
"500": {
|
||||
"description": "治理库不可用"
|
||||
},
|
||||
"503": {
|
||||
"description": "本地模式或执行器未接线;未创建任务"
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
"/api/v1/qa-ops/status": {
|
||||
"get": {
|
||||
"tags": ["QA operations"],
|
||||
|
||||
+13
-1
@@ -21,7 +21,9 @@ import (
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/platform/weknora"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"knowledge-governance/internal/serviceverify"
|
||||
"knowledge-governance/internal/version"
|
||||
)
|
||||
|
||||
// dingtalkSourceLister 是「系统设置 → 数据源配置」的数据源发现实现:只读列举钉钉知识库与
|
||||
@@ -36,6 +38,9 @@ func (dingtalkSourceLister) ListAvailableDingtalkSources(ctx context.Context) (d
|
||||
func main() {
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if len(os.Args) == 2 && os.Args[1] == "--version-record-status" {
|
||||
os.Exit(versionRecordStatus(ctx, os.Getenv))
|
||||
}
|
||||
if err := run(ctx, os.Getenv); err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
@@ -125,8 +130,14 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
versionHistoryStore, versionHistoryRepo := httpapi.VersionHistoryStore(nil), ""
|
||||
if config.VersionHistoryGiteaBaseURL != "" {
|
||||
versionHistoryStore, versionHistoryRepo = postgresstore.NewStore(pool), config.VersionHistoryRepo
|
||||
info := version.Snapshot()
|
||||
if info.IdentityAvailable && info.CommitSHA != nil {
|
||||
if _, e := actionStore.EnqueueVersionHistorySync(ctx, config.VersionHistoryRepo, "system:deployment", *info.CommitSHA, time.Now()); e != nil {
|
||||
log.Print("version history deployment synchronization could not be queued")
|
||||
}
|
||||
}
|
||||
}
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL)
|
||||
qaReader, qaSettings := openQAOperations(ctx, getenv, config.DatabaseURL, pool)
|
||||
if closer, ok := qaReader.(interface{ Close() }); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
@@ -143,6 +154,7 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
qaSyncStore = qaOrganizationStore
|
||||
}
|
||||
handler, err := httpapi.NewHandler(httpapi.Config{
|
||||
QAQuality: qaopsquality.NewStore(pool, getenv("DOBOTAI_OPS_TENANT_KEY")),
|
||||
QAOrgSync: qaSyncStore,
|
||||
QAOrgSyncEnabled: qaSyncErr == nil && qaSyncSettings.Enabled,
|
||||
QAOrg: qaOrganizationStore,
|
||||
|
||||
+12
-7
@@ -2,20 +2,25 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/httpapi"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// A failed optional source must not replace or take down the main database.
|
||||
func openQAOperations(ctx context.Context, getenv func(string) string, governanceDSN string) (httpapi.QAOpsReader, dobotaiops.Settings) {
|
||||
// API serving never constructs or probes a production-source client. The worker
|
||||
// alone synchronizes the explicitly authorized local copy; this is not a fallback.
|
||||
func openQAOperations(_ context.Context, getenv func(string) string, governanceDSN string, pool *pgxpool.Pool) (httpapi.QAOpsReader, dobotaiops.Settings) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled || settings.Problem != "" {
|
||||
if !settings.Enabled {
|
||||
return nil, settings
|
||||
}
|
||||
client, err := dobotaiops.Build(ctx, settings.Connection)
|
||||
if err != nil {
|
||||
settings.Problem = "source_connection_or_permissions_failed"
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
settings.Problem = "local_mirror_tenant_invalid"
|
||||
return nil, settings
|
||||
}
|
||||
return client, settings
|
||||
// Missing/offline source credentials stop synchronization, not last-good local reads.
|
||||
settings.Problem = ""
|
||||
return qaopsmirror.NewStore(pool, settings.TenantKey), settings
|
||||
}
|
||||
|
||||
@@ -6,13 +6,13 @@ import (
|
||||
)
|
||||
|
||||
func TestQAOpsConnectionFailureIsContainedOutsideMainDatabase(t *testing.T) {
|
||||
reader, settings := openQAOperations(context.Background(), func(string) string { return "" }, "postgres://main@host/governance")
|
||||
reader, settings := openQAOperations(context.Background(), func(string) string { return "" }, "postgres://main@host/governance", nil)
|
||||
if reader != nil || settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("QA operations must be disabled by default")
|
||||
}
|
||||
env := map[string]string{"DOBOTAI_OPS_READ_ENABLED": "true", "DOBOTAI_OPS_TENANT_KEY": "approved-tenant", "DOBOTAI_OPS_READ_DSN_FILE": "/nonexistent-qaops-fixture-secret"}
|
||||
reader, settings = openQAOperations(context.Background(), func(k string) string { return env[k] }, "postgres://main@host/governance")
|
||||
if reader != nil || !settings.Enabled || settings.Problem == "" {
|
||||
t.Fatal("failed external connection must be a contained module error")
|
||||
reader, settings = openQAOperations(context.Background(), func(k string) string { return env[k] }, "postgres://main@host/governance", nil)
|
||||
if reader == nil || !settings.Enabled || settings.Problem != "" {
|
||||
t.Fatal("API serving still constructs a source connection instead of a local reader")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/appconfig"
|
||||
"knowledge-governance/internal/version"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Operator-only read-back in the existing API binary; no new public endpoint,
|
||||
// no session/credential creation and no migrations or remote forge access.
|
||||
func versionRecordStatus(ctx context.Context, getenv func(string) string) int {
|
||||
info := version.Snapshot()
|
||||
if !info.IdentityAvailable || info.CommitSHA == nil {
|
||||
return printVersionStatus(false, "build_identity_missing", "")
|
||||
}
|
||||
config, e := appconfig.Load(getenv)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "configuration_invalid", *info.CommitSHA)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
defer cancel()
|
||||
pool, e := pgxpool.New(ctx, config.DatabaseURL)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "database_unavailable", *info.CommitSHA)
|
||||
}
|
||||
defer pool.Close()
|
||||
tag := "snapshot/v" + info.DisplayVersion
|
||||
kind := "development"
|
||||
if info.BuildKind == "release" {
|
||||
tag = "v" + info.DisplayVersion
|
||||
kind = "release"
|
||||
}
|
||||
evidence, _ := json.Marshal([]map[string]any{{"name": tag, "annotated": true}})
|
||||
var ready bool
|
||||
e = pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM version_history_commits c WHERE repo_key=$1 AND commit_sha=$2 AND version_label=$3 AND record_kind=$4 AND btrim(release_notes)<>'' AND release_tags @> $5::jsonb AND snapshot_id=(SELECT max(id) FROM version_history_sync_runs WHERE repo_key=$1 AND status='completed' AND complete))`, config.VersionHistoryRepo, *info.CommitSHA, info.DisplayVersion, kind, evidence).Scan(&ready)
|
||||
if e != nil {
|
||||
return printVersionStatus(false, "database_unavailable", *info.CommitSHA)
|
||||
}
|
||||
if !ready {
|
||||
return printVersionStatus(false, "version_record_pending", *info.CommitSHA)
|
||||
}
|
||||
return printVersionStatus(true, "verified", *info.CommitSHA)
|
||||
}
|
||||
func printVersionStatus(ready bool, code, sha string) int {
|
||||
raw, _ := json.Marshal(map[string]any{"ready": ready, "code": code, "commit_sha": sha})
|
||||
fmt.Fprintln(os.Stdout, string(raw))
|
||||
if ready {
|
||||
return 0
|
||||
}
|
||||
return 1
|
||||
}
|
||||
+17
-1
@@ -56,6 +56,10 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if syncErr := configureDirectorySync(pool, getenv, handlers); syncErr != nil {
|
||||
log.Print("QA directory synchronization unavailable; handler was not registered")
|
||||
}
|
||||
mirrorStore, mirrorErr := configureRecordsSync(pool, getenv, config.DatabaseURL, handlers)
|
||||
if mirrorErr != nil {
|
||||
log.Print("QA local mirror configuration invalid; handler was not registered")
|
||||
}
|
||||
worker, err := jobs.NewWorker(jobs.WorkerConfig{
|
||||
Queue: store,
|
||||
WorkerID: config.WorkerID,
|
||||
@@ -67,6 +71,9 @@ func run(ctx context.Context, getenv func(string) string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mirrorStore != nil {
|
||||
go runRecordsSyncScheduler(ctx, mirrorStore, func(error) { log.Print("QA local mirror scheduler unavailable; last committed data retained") })
|
||||
}
|
||||
go runSourceRefreshScheduler(ctx, store, config.SourceRefreshSchedulerInterval, func(err error) {
|
||||
log.Printf("worker %s source refresh scheduler error: %v", config.WorkerID, err)
|
||||
})
|
||||
@@ -137,11 +144,20 @@ func workerHandlers(store *postgresstore.Store, config appconfig.Config) (map[st
|
||||
triggeredBy := ""
|
||||
var payload struct {
|
||||
TriggeredBy string `json:"triggered_by"`
|
||||
TargetSHA string `json:"target_sha"`
|
||||
}
|
||||
if err := json.Unmarshal(job.Payload, &payload); err == nil {
|
||||
triggeredBy = payload.TriggeredBy
|
||||
}
|
||||
run, err := syncer.Sync(ctx, job.ID, triggeredBy)
|
||||
activeSyncer := syncer
|
||||
if payload.TargetSHA != "" {
|
||||
var e error
|
||||
activeSyncer, e = versionhistory.NewSyncer(versionhistory.SyncerConfig{Source: client, Store: store, RepoKey: config.VersionHistoryRepo, MaxPages: config.VersionHistoryMaxPages, TargetSHAs: []string{payload.TargetSHA}})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
run, err := activeSyncer.Sync(ctx, job.ID, triggeredBy)
|
||||
if err != nil {
|
||||
log.Printf("version history sync failed job=%s run=%d code=%s: %v", job.ID, run.ID, run.ErrorCode, err)
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
type recordsSyncSchedulerStore interface {
|
||||
EnqueueDue(context.Context) (bool, error)
|
||||
TrackQualityWeeks(context.Context, time.Time) error
|
||||
FreezePreviousQualityWeek(context.Context, time.Time) (bool, error)
|
||||
}
|
||||
|
||||
func runRecordsSyncCycle(ctx context.Context, store recordsSyncSchedulerStore, at time.Time) error {
|
||||
_, syncErr := store.EnqueueDue(ctx)
|
||||
trackingErr := store.TrackQualityWeeks(ctx, at)
|
||||
if trackingErr != nil {
|
||||
return errors.Join(syncErr, trackingErr)
|
||||
}
|
||||
_, freezeErr := store.FreezePreviousQualityWeek(ctx, at)
|
||||
return errors.Join(syncErr, freezeErr)
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type frozenScheduleSpy struct {
|
||||
calls []string
|
||||
trackErr error
|
||||
}
|
||||
|
||||
func (s *frozenScheduleSpy) EnqueueDue(context.Context) (bool, error) {
|
||||
s.calls = append(s.calls, "sync")
|
||||
return true, nil
|
||||
}
|
||||
func (s *frozenScheduleSpy) TrackQualityWeeks(context.Context, time.Time) error {
|
||||
s.calls = append(s.calls, "track")
|
||||
return s.trackErr
|
||||
}
|
||||
func (s *frozenScheduleSpy) FreezePreviousQualityWeek(context.Context, time.Time) (bool, error) {
|
||||
s.calls = append(s.calls, "freeze")
|
||||
return true, nil
|
||||
}
|
||||
func TestRecordsSchedulerActuallyCapturesFrozenWeeklyMetrics(t *testing.T) {
|
||||
s := &frozenScheduleSpy{}
|
||||
if e := runRecordsSyncCycle(context.Background(), s, time.Now()); e != nil || !reflect.DeepEqual(s.calls, []string{"sync", "track", "freeze"}) {
|
||||
t.Fatal("weekly capture is not on the real scheduler invocation path", e, s.calls)
|
||||
}
|
||||
broken := &frozenScheduleSpy{trackErr: errors.New("isolated tracking unavailable")}
|
||||
if e := runRecordsSyncCycle(context.Background(), broken, time.Now()); e == nil || !reflect.DeepEqual(broken.calls, []string{"sync", "track"}) {
|
||||
t.Fatal("snapshot failure must not suppress source sync or freeze untracked history")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func configureRecordsSync(pool *pgxpool.Pool, getenv func(string) string, governanceDSN string, handlers map[string]jobs.Handler) (*qaopsmirror.Store, error) {
|
||||
settings := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !settings.Enabled {
|
||||
return nil, nil
|
||||
}
|
||||
if settings.TenantKey == "" || len(settings.TenantKey) > 128 || strings.ContainsRune(settings.TenantKey, 0) {
|
||||
return nil, qaopsmirror.ErrInvalid
|
||||
}
|
||||
store := qaopsmirror.NewStore(pool, settings.TenantKey)
|
||||
handlers[store.SyncJobType()] = func(ctx context.Context, job jobs.Job) error {
|
||||
return store.HandleSync(ctx, job, func(ctx context.Context) (qaopsmirror.Source, error) {
|
||||
current := dobotaiops.LoadSettings(getenv, governanceDSN)
|
||||
if !current.Enabled || current.Problem != "" || current.TenantKey != settings.TenantKey {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
// One source connection, shared by every manifest and bounded payload read in this job.
|
||||
current.Connection.MaxConns = 1
|
||||
current.Connection.MinConns = 0
|
||||
return dobotaiops.Build(ctx, current.Connection)
|
||||
})
|
||||
}
|
||||
return store, nil
|
||||
}
|
||||
|
||||
// The next due time and automatic operation key live in PostgreSQL, so a worker
|
||||
// restart does not reset the five-minute cadence or duplicate an active import.
|
||||
func runRecordsSyncScheduler(ctx context.Context, store *qaopsmirror.Store, onError func(error)) {
|
||||
tick := time.NewTicker(15 * time.Second)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
if e := runRecordsSyncCycle(ctx, store, time.Now()); e != nil && ctx.Err() == nil && onError != nil {
|
||||
onError(e)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLocalMirrorWorkerRegistrationNeverConnectsSource(t *testing.T) {
|
||||
values := map[string]string{}
|
||||
get := func(k string) string { return values[k] }
|
||||
handlers := map[string]jobs.Handler{}
|
||||
if store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers); e != nil || store != nil || len(handlers) != 0 {
|
||||
t.Fatal("disabled mirror registered")
|
||||
}
|
||||
values["DOBOTAI_OPS_READ_ENABLED"] = "true"
|
||||
values["DOBOTAI_OPS_TENANT_KEY"] = "fixture-worker-tenant"
|
||||
values["DOBOTAI_OPS_READ_DSN_FILE"] = "/nonexistent-fixture-source-secret"
|
||||
store, e := configureRecordsSync(nil, get, "postgres://fixture@localhost/local", handlers)
|
||||
if e != nil || store == nil || handlers[qaopsmirror.NewStore(nil, "fixture-worker-tenant").SyncJobType()] == nil {
|
||||
t.Fatal("local mirror handler missing; registration must not connect to source", e)
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -14,7 +14,7 @@ server {
|
||||
set $api_upstream http://api:8080;
|
||||
proxy_pass $api_upstream;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Host $http_host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
}
|
||||
@@ -22,7 +22,7 @@ server {
|
||||
location = /health {
|
||||
set $health_upstream http://api:8080;
|
||||
proxy_pass $health_upstream/health;
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header Host $http_host;
|
||||
}
|
||||
|
||||
# 带内容哈希的构建产物:可以长期缓存(换版本必然换文件名);旧哈希文件已被新构建替换
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MaxMirrorRecords = 100000
|
||||
const mirrorFingerprintSQL = `encode(sha256(convert_to((payload-'_quality_observed_at')::text,'UTF8')),'hex')`
|
||||
|
||||
type MirrorKey struct {
|
||||
ID string
|
||||
Fingerprint string
|
||||
}
|
||||
type MirrorManifest struct {
|
||||
Keys []MirrorKey
|
||||
AsOf time.Time
|
||||
Safety SourceSafety
|
||||
}
|
||||
type MirrorRecord struct {
|
||||
Key MirrorKey
|
||||
Payload json.RawMessage
|
||||
}
|
||||
|
||||
func validMirrorTenant(tenant string) bool {
|
||||
return strings.TrimSpace(tenant) == tenant && len(tenant) > 0 && len(tenant) <= 128 && !strings.ContainsRune(tenant, 0)
|
||||
}
|
||||
|
||||
// Only a manifest (IDs and stable hashes), not all long answers, crosses the
|
||||
// network on unchanged polls. Each read retains the source ACL and read-only gates.
|
||||
func (c *Client) ReadMirrorManifest(ctx context.Context, tenant string) (MirrorManifest, error) {
|
||||
out := MirrorManifest{Keys: []MirrorKey{}}
|
||||
if !validMirrorTenant(tenant) {
|
||||
return out, ErrInvalidQuery
|
||||
}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&out.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+` FROM records ORDER BY id LIMIT 100001`, tenant)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var k MirrorKey
|
||||
if rows.Scan(&k.ID, &k.Fingerprint) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out.Keys) >= MaxMirrorRecords {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out.Keys = append(out.Keys, k)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
out.Safety = c.Safety()
|
||||
return out, err
|
||||
}
|
||||
func (c *Client) ReadMirrorRecords(ctx context.Context, tenant string, ids []string) ([]MirrorRecord, error) {
|
||||
if !validMirrorTenant(tenant) || len(ids) == 0 || len(ids) > 100 {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, id := range ids {
|
||||
if id == "" || len(id) > 256 || strings.ContainsRune(id, 0) || seen[id] {
|
||||
return nil, ErrInvalidQuery
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
out := make([]MirrorRecord, 0, len(ids))
|
||||
size := 0
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
rows, e := q.Query(ctx, recordsBaseSQL+` SELECT id,`+mirrorFingerprintSQL+`,payload FROM records WHERE id=ANY($2::text[]) ORDER BY id`, tenant, ids)
|
||||
if e != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var r MirrorRecord
|
||||
if rows.Scan(&r.Key.ID, &r.Key.Fingerprint, &r.Payload) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
size += len(r.Payload)
|
||||
if len(r.Payload) > 8<<20 || size > 32<<20 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
out = append(out, r)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(out) != len(ids) {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMirrorSourceManifestDetectsUpdatesWithoutVolatileTimes(t *testing.T) {
|
||||
p := fixturePool(t)
|
||||
c := buildReadOnlyClient(t, qaRecordsFixture(t, p))
|
||||
ctx := context.Background()
|
||||
a, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(a.Keys) != 4 || a.AsOf.IsZero() {
|
||||
t.Fatal("full fixed-channel manifest is missing", e, len(a.Keys))
|
||||
}
|
||||
b, e := c.ReadMirrorManifest(ctx, "default")
|
||||
if e != nil || len(b.Keys) != len(a.Keys) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
old := map[string]string{}
|
||||
for i, k := range a.Keys {
|
||||
old[k.ID] = k.Fingerprint
|
||||
if k != b.Keys[i] {
|
||||
t.Fatal("source clock alone changed the content fingerprint")
|
||||
}
|
||||
}
|
||||
rows, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || len(rows) != 1 || rows[0].Key.Fingerprint != old["turn-3"] {
|
||||
t.Fatal("bounded safe payload fetch failed", e)
|
||||
}
|
||||
before, e := DecodeMirrorPayload(string(rows[0].Payload))
|
||||
if e != nil || before.Feedback.Up != 1 || before.Identity.StaffID == "" {
|
||||
t.Fatal("safe payload lost required fields", e)
|
||||
}
|
||||
execFixture(t, p, `UPDATE answer_feedback SET value='down' WHERE id='fb1'`)
|
||||
after, e := c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
if e != nil || after[0].Key.Fingerprint == old["turn-3"] {
|
||||
t.Fatal("feedback update on old question was missed", e)
|
||||
}
|
||||
rec, _ := DecodeMirrorPayload(string(after[0].Payload))
|
||||
if rec.QualityInputHash != before.QualityInputHash {
|
||||
t.Fatal("feedback invalidated unrelated human quality input")
|
||||
}
|
||||
execFixture(t, p, `UPDATE turns SET answer='changed answer' WHERE id='turn-3'`)
|
||||
after, e = c.ReadMirrorRecords(ctx, "default", []string{"turn-3"})
|
||||
rec, _ = DecodeMirrorPayload(string(after[0].Payload))
|
||||
if e != nil || rec.QualityInputHash == before.QualityInputHash {
|
||||
t.Fatal("answer change was missed")
|
||||
}
|
||||
if _, e = c.ReadMirrorRecords(ctx, "default", make([]string, 101)); e == nil {
|
||||
t.Fatal("unbounded payload fetch allowed")
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ type ActorIdentity struct {
|
||||
UnionID string `json:"union_id"`
|
||||
}
|
||||
type OrganizationVersion struct {
|
||||
RegionNames []string `json:"region_names"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
@@ -44,16 +45,20 @@ type UsageGroups struct {
|
||||
func decodeRecord(raw string) (Record, error) {
|
||||
var wire struct {
|
||||
Record
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
Identity ActorIdentity `json:"_identity"`
|
||||
QualityHash string `json:"_quality_hash"`
|
||||
QualityObservedAt time.Time `json:"_quality_observed_at"`
|
||||
}
|
||||
if err := json.Unmarshal([]byte(raw), &wire); err != nil {
|
||||
return Record{}, err
|
||||
}
|
||||
wire.Record.Identity = wire.Identity
|
||||
wire.Record.QualityInputHash = wire.QualityHash
|
||||
wire.Record.QualityObservedAt = wire.QualityObservedAt
|
||||
wire.Record.Coverage = CheckAnswerCoverage(wire.Record.Answer)
|
||||
return wire.Record, nil
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
func (c *RecordsRepository) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageGroups, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return UsageGroups{}, err
|
||||
}
|
||||
@@ -65,11 +70,11 @@ func (c *Client) ReadUsageGroups(ctx context.Context, query RecordQuery) (UsageG
|
||||
return UsageGroups{}, patternErr
|
||||
}
|
||||
result := UsageGroups{Groups: []UsageGroup{}}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&result.AsOf) != nil {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT identity::text,count(*),count(*) FILTER(WHERE status='succeeded'),count(*) FILTER(WHERE status='failed') FROM records WHERE `+recordFilterSQL+` GROUP BY identity`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
|
||||
@@ -27,6 +27,9 @@ func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if len(page.ScopeQuality) != 4 || len(page.Items[0].QualityInputHash) != 64 {
|
||||
t.Fatal("whole-scope quality versions missing")
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("whole-filter keys missing; later-page department would be hidden")
|
||||
}
|
||||
@@ -34,6 +37,15 @@ func TestQARecordInternalIdentityAndWholeFilterKeys(t *testing.T) {
|
||||
if err != nil || item.Identity.StaffID != "ext-actor-1" || item.Identity.UnionID != "fixture-union" {
|
||||
t.Fatalf("stable identity not read from inbound actor/message: %v", err)
|
||||
}
|
||||
scope, se := client.ReadQualityScope(context.Background(), query)
|
||||
if se != nil || len(scope.Keys) != 4 || scope.AsOf.IsZero() {
|
||||
t.Fatal("quality metadata scope incomplete", se)
|
||||
}
|
||||
for _, key := range scope.Keys {
|
||||
if len(key.InputHash) != 64 || key.ObservedAt.IsZero() {
|
||||
t.Fatal("scope omitted input version")
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(page)
|
||||
detail, _ := json.Marshal(item)
|
||||
for _, s := range []string{string(raw), string(detail)} {
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QualityScope struct {
|
||||
Keys []QualityKey
|
||||
AsOf time.Time
|
||||
}
|
||||
|
||||
func (c *RecordsRepository) ReadQualityScope(ctx context.Context, query RecordQuery) (QualityScope, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
if query.Cursor != "" {
|
||||
return QualityScope{}, ErrInvalidQuery
|
||||
}
|
||||
pattern, err := recordKeywordPattern(query.Keyword)
|
||||
if err != nil {
|
||||
return QualityScope{}, err
|
||||
}
|
||||
result := QualityScope{Keys: []QualityKey{}}
|
||||
err = c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if c.readAsOf(ctx, q, &result.AsOf) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
scopeSQL := c.baseSQL + ` SELECT id,quality_hash,strpos(payload->>'answer',$5)>0,(payload->'source_coverage')::text FROM records WHERE `
|
||||
if c.qualityScopeSQL != "" {
|
||||
scopeSQL = c.qualityScopeSQL
|
||||
}
|
||||
rows, err := q.Query(ctx, scopeSQL+recordFilterSQL+` ORDER BY id LIMIT 5001`, query.Window.TenantKey, query.Window.Start, query.Window.End, pattern, noPublishedMarker)
|
||||
if err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var key QualityKey
|
||||
var raw string
|
||||
if rows.Scan(&key.ID, &key.InputHash, &key.Marker, &raw) != nil || json.Unmarshal([]byte(raw), &key.Source) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
if len(result.Keys) >= 5000 {
|
||||
return ErrInvalidQuery
|
||||
}
|
||||
key.ObservedAt = result.AsOf
|
||||
result.Keys = append(result.Keys, key)
|
||||
}
|
||||
return rows.Err()
|
||||
})
|
||||
return result, err
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package dobotaiops
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// RecordQuerier and RecordTransaction keep the projection identical while an
|
||||
// explicitly selected reader supplies either source-ACL or local-snapshot transactions.
|
||||
type RecordRow = rowScanner
|
||||
type RecordQuerier = querier
|
||||
type RecordTransaction func(context.Context, func(context.Context, RecordQuerier) error) error
|
||||
type RecordsRepositoryOptions struct {
|
||||
BaseSQL string
|
||||
SummarySQL string
|
||||
QualityScopeSQL string
|
||||
Transaction RecordTransaction
|
||||
ValidateWindow func(Window) error
|
||||
ReadAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
TenantKey string
|
||||
}
|
||||
type RecordsRepository struct {
|
||||
baseSQL string
|
||||
summarySQL string
|
||||
qualityScopeSQL string
|
||||
transact RecordTransaction
|
||||
validateQueryWindow func(Window) error
|
||||
readAsOf func(context.Context, RecordQuerier, *time.Time) error
|
||||
tenant string
|
||||
}
|
||||
|
||||
func NewRecordsRepository(o RecordsRepositoryOptions) *RecordsRepository {
|
||||
asOf := o.ReadAsOf
|
||||
if asOf == nil {
|
||||
asOf = func(ctx context.Context, q RecordQuerier, t *time.Time) error {
|
||||
return q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(t)
|
||||
}
|
||||
}
|
||||
return &RecordsRepository{summarySQL: o.SummarySQL, qualityScopeSQL: o.QualityScopeSQL, baseSQL: o.BaseSQL, transact: o.Transaction, validateQueryWindow: o.ValidateWindow, readAsOf: asOf, tenant: o.TenantKey}
|
||||
}
|
||||
func (c *Client) recordRepository() *RecordsRepository {
|
||||
return NewRecordsRepository(RecordsRepositoryOptions{BaseSQL: recordsBaseSQL, Transaction: c.withReadOnlyTx, ValidateWindow: c.validateQueryWindow})
|
||||
}
|
||||
func (c *Client) ListRecords(ctx context.Context, q RecordQuery) (RecordPage, error) {
|
||||
return c.recordRepository().ListRecords(ctx, q)
|
||||
}
|
||||
func (c *Client) GetRecord(ctx context.Context, tenant, id string) (Record, error) {
|
||||
return c.recordRepository().GetRecord(ctx, tenant, id)
|
||||
}
|
||||
func (c *Client) ReadUsageGroups(ctx context.Context, q RecordQuery) (UsageGroups, error) {
|
||||
return c.recordRepository().ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func (c *Client) ReadQualityScope(ctx context.Context, q RecordQuery) (QualityScope, error) {
|
||||
return c.recordRepository().ReadQualityScope(ctx, q)
|
||||
}
|
||||
|
||||
// DecodeMirrorPayload accepts only the source adapter's fixed safe projection;
|
||||
// credentials and arbitrary source tables are never part of this protocol.
|
||||
func DecodeMirrorPayload(raw string) (Record, error) { return decodeRecord(raw) }
|
||||
@@ -29,8 +29,11 @@ type CoverageCheck struct {
|
||||
|
||||
// Absence of this exact substring is not evidence that knowledge covers a question.
|
||||
func CheckAnswerCoverage(answer string) CoverageCheck {
|
||||
return CheckMarkerCoverage(strings.Contains(answer, noPublishedMarker))
|
||||
}
|
||||
func CheckMarkerCoverage(matched bool) CoverageCheck {
|
||||
result := CoverageCheck{State: "pending", RuleVersion: CoverageRuleVersion}
|
||||
if strings.Contains(answer, noPublishedMarker) {
|
||||
if matched {
|
||||
result.State = "checked"
|
||||
result.Verdict = "uncovered"
|
||||
result.MatchedText = noPublishedMarker
|
||||
@@ -51,23 +54,26 @@ type RecordFeedback struct {
|
||||
}
|
||||
|
||||
type Record struct {
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
QualityObservedAt time.Time `json:"-"`
|
||||
QualityInputHash string `json:"-"`
|
||||
Quality json.RawMessage `json:"quality,omitempty"`
|
||||
Identity ActorIdentity `json:"-"`
|
||||
Organization *RecordOrganization `json:"organization,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
AskedAt time.Time `json:"asked_at"`
|
||||
TimeSource string `json:"time_source"`
|
||||
Asker string `json:"asker"`
|
||||
TriggerPerson string `json:"trigger_person"`
|
||||
Department string `json:"department"`
|
||||
Region string `json:"region"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
SourceCoverage SourceCoverage `json:"source_coverage"`
|
||||
Feedback RecordFeedback `json:"feedback"`
|
||||
Coverage CoverageCheck `json:"coverage"`
|
||||
}
|
||||
|
||||
type RecordQuery struct {
|
||||
@@ -77,15 +83,24 @@ type RecordQuery struct {
|
||||
Limit int
|
||||
}
|
||||
|
||||
type QualityKey struct {
|
||||
ObservedAt time.Time `json:"-"`
|
||||
Marker bool `json:"marker"`
|
||||
Source SourceCoverage `json:"source"`
|
||||
ID string `json:"id"`
|
||||
InputHash string `json:"input_hash"`
|
||||
}
|
||||
type RecordPage struct {
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
LocalRevision int64 `json:"local_revision,omitempty"`
|
||||
ScopeQuality []QualityKey `json:"-"`
|
||||
ScopeActors []ActorIdentity `json:"-"`
|
||||
Organization *OrganizationVersion `json:"organization,omitempty"`
|
||||
Items []Record `json:"items"`
|
||||
Columns []string `json:"columns"`
|
||||
Total int64 `json:"total"`
|
||||
HasMore bool `json:"has_more"`
|
||||
NextCursor string `json:"next_cursor"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
}
|
||||
|
||||
type recordCursor struct {
|
||||
@@ -97,11 +112,12 @@ type recordCursor struct {
|
||||
// A single inbound-message join controls names/time. Feedback is preaggregated;
|
||||
// joining each feedback row directly would multiply the business event count.
|
||||
const actorIdentitySQL = `jsonb_build_object('actor_id',COALESCE(a.id,''),'staff_id',COALESCE(a.external_actor_id,''),'union_id',COALESCE(m.actor_union_id_snapshot,''))`
|
||||
const qualityHashSQL = `encode(sha256(convert_to(jsonb_build_array('quality-input-v1',t.id,t.status,t.question,t.answer,t.references_json,COALESCE(m.media_json,'[]'::jsonb))::text,'UTF8')),'hex')`
|
||||
const recordsBaseSQL = `
|
||||
WITH records AS (
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,
|
||||
SELECT t.id,COALESCE(m.created_at,t.created_at) AS asked_at,t.question,t.status,` + actorIdentitySQL + ` AS identity,` + qualityHashSQL + ` AS quality_hash,
|
||||
jsonb_build_object(
|
||||
'_identity',` + actorIdentitySQL + `,
|
||||
'_identity',` + actorIdentitySQL + `, '_quality_hash',` + qualityHashSQL + `,'_quality_observed_at',transaction_timestamp(),
|
||||
'id',t.id,'status',t.status,'question',t.question,'answer',t.answer,
|
||||
'asked_at',COALESCE(m.created_at,t.created_at),
|
||||
'time_source',CASE WHEN m.id IS NULL THEN 'turn.created_at' ELSE 'request_message.created_at' END,
|
||||
@@ -143,7 +159,7 @@ const recordColumnsSQL = `SELECT count(*),jsonb_build_object(
|
||||
'region',COALESCE(bool_or(payload->>'region'<>''),false),
|
||||
'feedback',COALESCE(bool_or(payload->'feedback'->>'asker_value'<>'' OR
|
||||
(payload->'feedback'->>'up')::bigint>0 OR (payload->'feedback'->>'down')::bigint>0),false)
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text FROM records WHERE `
|
||||
)::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',strpos(payload->>'answer',$5)>0,'source',payload->'source_coverage')),'[]'::jsonb)::text FROM records WHERE `
|
||||
|
||||
var recordColumnOrder = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
|
||||
@@ -157,7 +173,7 @@ func recordKeywordPattern(keyword string) (string, error) {
|
||||
return "%" + strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(keyword) + "%", nil
|
||||
}
|
||||
|
||||
func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
func (c *RecordsRepository) ListRecords(ctx context.Context, query RecordQuery) (RecordPage, error) {
|
||||
if err := c.validateQueryWindow(query.Window); err != nil {
|
||||
return RecordPage{}, err
|
||||
}
|
||||
@@ -182,14 +198,24 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
}
|
||||
args := []any{query.Window.TenantKey, query.Window.Start, query.Window.End, pattern}
|
||||
page := RecordPage{Items: make([]Record, 0), Columns: make([]string, 0)}
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := q.QueryRow(ctx, "SELECT transaction_timestamp()").Scan(&page.AsOf); err != nil {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
if err := c.readAsOf(ctx, q, &page.AsOf); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var rawColumns, rawActors string
|
||||
if err := q.QueryRow(ctx, recordsBaseSQL+recordColumnsSQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors); err != nil {
|
||||
var rawColumns, rawActors, rawQuality string
|
||||
summarySQL := c.baseSQL + recordColumnsSQL
|
||||
if c.summarySQL != "" {
|
||||
summarySQL = c.summarySQL
|
||||
}
|
||||
if err := q.QueryRow(ctx, summarySQL+recordFilterSQL, append(args, noPublishedMarker)...).Scan(&page.Total, &rawColumns, &rawActors, &rawQuality); err != nil {
|
||||
return fmt.Errorf("%w: record count failed", ErrUnavailable)
|
||||
}
|
||||
if json.Unmarshal([]byte(rawQuality), &page.ScopeQuality) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
for i := range page.ScopeQuality {
|
||||
page.ScopeQuality[i].ObservedAt = page.AsOf
|
||||
}
|
||||
var available map[string]bool
|
||||
if json.Unmarshal([]byte(rawActors), &page.ScopeActors) != nil {
|
||||
return ErrUnavailable
|
||||
@@ -202,7 +228,7 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
page.Columns = append(page.Columns, column)
|
||||
}
|
||||
}
|
||||
rows, err := q.Query(ctx, recordsBaseSQL+` SELECT payload::text FROM records WHERE `+recordFilterSQL+`
|
||||
rows, err := q.Query(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE `+recordFilterSQL+`
|
||||
AND ($5::timestamptz IS NULL OR (asked_at,id)<($5,$6)) ORDER BY asked_at DESC,id DESC LIMIT $7`, append(args, before, cursor.ID, query.Limit+1)...)
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: record list failed", ErrUnavailable)
|
||||
@@ -238,14 +264,14 @@ func (c *Client) ListRecords(ctx context.Context, query RecordQuery) (RecordPage
|
||||
return page, nil
|
||||
}
|
||||
|
||||
func (c *Client) GetRecord(ctx context.Context, tenantKey, id string) (Record, error) {
|
||||
if strings.TrimSpace(tenantKey) == "" || id == "" || len(id) > 256 || strings.ContainsRune(id, 0) {
|
||||
func (c *RecordsRepository) GetRecord(ctx context.Context, tenantKey, id string) (Record, error) {
|
||||
if strings.TrimSpace(tenantKey) == "" || (c.tenant != "" && tenantKey != c.tenant) || id == "" || len(id) > 256 || strings.ContainsRune(id, 0) {
|
||||
return Record{}, ErrInvalidQuery
|
||||
}
|
||||
var item Record
|
||||
err := c.withReadOnlyTx(ctx, func(ctx context.Context, q querier) error {
|
||||
err := c.transact(ctx, func(ctx context.Context, q querier) error {
|
||||
var raw string
|
||||
err := q.QueryRow(ctx, recordsBaseSQL+` SELECT payload::text FROM records WHERE id=$2`, tenantKey, id).Scan(&raw)
|
||||
err := q.QueryRow(ctx, c.baseSQL+` SELECT payload::text FROM records WHERE id=$2`, tenantKey, id).Scan(&raw)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return ErrRecordNotFound
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
package governance
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Development headings cannot replace the formal release baseline.
|
||||
func ExtractDevelopmentNotes(changelog, version string) string {
|
||||
return developmentNotes(changelog, version, "")
|
||||
}
|
||||
func ExtractDevelopmentNotesForCommit(changelog, version, sha string) string {
|
||||
return developmentNotes(changelog, version, sha)
|
||||
}
|
||||
func developmentNotes(changelog, version, sha string) string {
|
||||
if !SemverValid(version) {
|
||||
return ""
|
||||
}
|
||||
lines := strings.Split(changelog, "\n")
|
||||
prefix := "## 开发快照 snapshot/v" + version + " - "
|
||||
for i, line := range lines {
|
||||
if strings.HasPrefix(line, prefix) {
|
||||
end := len(lines)
|
||||
for j := i + 1; j < len(lines); j++ {
|
||||
if strings.HasPrefix(lines[j], "## ") {
|
||||
end = j
|
||||
break
|
||||
}
|
||||
}
|
||||
body := strings.TrimSpace(strings.Join(lines[i+1:end], "\n"))
|
||||
if sha == "" {
|
||||
return body
|
||||
}
|
||||
for _, field := range lines[i+1 : end] {
|
||||
if strings.TrimSpace(field) == "目标提交:"+sha {
|
||||
return body
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -31,7 +31,7 @@ func recordAttribution(ctx context.Context, config Config) (*qaopsorg.Attributio
|
||||
return p, nil
|
||||
}
|
||||
func attributionVersion(p *qaopsorg.Attribution) dobotaiops.OrganizationVersion {
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory"}
|
||||
return dobotaiops.OrganizationVersion{State: p.Metadata.State, DirectoryID: p.Metadata.DirectoryID, DirectorySource: p.Metadata.DirectorySource, SyncedAt: p.Metadata.DirectorySyncedAt, RevisionID: p.Metadata.RevisionID, Basis: "current_directory", RegionNames: p.Metadata.RegionLabels()}
|
||||
}
|
||||
func enrichQARecord(item *dobotaiops.Record, p *qaopsorg.Attribution) {
|
||||
person := p.Resolve(item.Identity.StaffID, item.Identity.UnionID)
|
||||
@@ -92,7 +92,7 @@ type qaUsage struct {
|
||||
|
||||
func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, query dobotaiops.RecordQuery) qaUsage {
|
||||
result := qaUsage{Organization: attributionVersion(p), AsOf: groups.AsOf, Start: query.Window.Start, End: query.Window.End, Keyword: query.Keyword, Rows: []qaUsageRow{}}
|
||||
keys := append(append([]string{}, qaopsorg.RegionNames...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
keys := append(append([]string{}, p.Metadata.RegionLabels()...), "unassigned", "cross_region", "unmatched", "identity_conflict", "no_identity", "directory_missing")
|
||||
rows := map[string]*qaUsageRow{}
|
||||
members := map[string]map[string]bool{}
|
||||
all := map[string]bool{}
|
||||
@@ -108,7 +108,12 @@ func summarizeQAUsage(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, qu
|
||||
n = p.Metadata.View.ConflictingPeople
|
||||
default:
|
||||
var ok bool
|
||||
n, ok = p.Metadata.View.Regions[key]
|
||||
for _, region := range p.Metadata.RegionDefinitions() {
|
||||
if region.Name == key {
|
||||
n, ok = p.Metadata.View.Regions[region.ID]
|
||||
break
|
||||
}
|
||||
}
|
||||
valid = ok
|
||||
}
|
||||
if valid {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
type qaDashboardReader interface {
|
||||
ReadDashboard(context.Context, dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error)
|
||||
}
|
||||
|
||||
func qaOperationsDashboard(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-dashboard") {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request, "start", "end") != nil {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(qaDashboardReader)
|
||||
if !ok || c.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
window, e := dobotaiops.NewWindow(c.QAOpsTenantKey, request.Start, request.End, 90*24*time.Hour, c.Now())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
dashboard, e := reader.ReadDashboard(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
|
||||
if e != nil {
|
||||
if errors.Is(e, qaopsquality.ErrConflict) {
|
||||
writeQualityError(w, e)
|
||||
return
|
||||
}
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": dashboard})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type dashboardReaderSpy struct {
|
||||
attributedReader
|
||||
calls int
|
||||
query dobotaiops.RecordQuery
|
||||
err error
|
||||
}
|
||||
|
||||
func (s *dashboardReaderSpy) ReadDashboard(_ context.Context, q dobotaiops.RecordQuery) (qaopsmirror.Dashboard, error) {
|
||||
s.calls++
|
||||
s.query = q
|
||||
return qaopsmirror.Dashboard{TotalIssues: 7, NewThisWeek: 2}, s.err
|
||||
}
|
||||
func TestQADashboardIsFixedTenantAdminAndReadOnly(t *testing.T) {
|
||||
reader := &dashboardReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["dash-admin"] = "usr-boss"
|
||||
auth.sessions["dash-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: reader, QAOpsTenantKey: "fixed-dashboard-tenant", Now: func() time.Time { return time.Date(2026, 10, 18, 12, 0, 0, 0, time.UTC) }, Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
good := `{"start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00","keyword":"100%_"}`
|
||||
for _, c := range []struct {
|
||||
token, action, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"", "qa-dashboard", "", good, 401}, {"dash-viewer", "qa-dashboard", "", good, 403}, {"dash-admin", "", "", good, 403}, {"dash-admin", "qa-dashboard", "https://untrusted.invalid", good, 403},
|
||||
{"dash-admin", "qa-dashboard", "", `null`, 400}, {"dash-admin", "qa-dashboard", "", `{"start":null,"end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", `{"tenant":"other","start":"2026-10-05T00:00:00+08:00","end":"2026-10-12T00:00:00+08:00"}`, 400},
|
||||
{"dash-admin", "qa-dashboard", "", good, 200},
|
||||
} {
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(c.body))
|
||||
if c.token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: c.token})
|
||||
}
|
||||
r.Header.Set("X-Governance-Action", c.action)
|
||||
r.Header.Set("Origin", c.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != c.status {
|
||||
t.Fatalf("dashboard status=%d want=%d", w.Code, c.status)
|
||||
}
|
||||
if w.Code == 200 && w.Header().Get("Cache-Control") != "no-store" {
|
||||
t.Fatal("private dashboard response may be cached")
|
||||
}
|
||||
}
|
||||
if reader.calls != 1 || reader.query.Window.TenantKey != "fixed-dashboard-tenant" || reader.query.Keyword != "100%_" {
|
||||
t.Fatal("rejected requests reached the reader or browser controlled the tenant")
|
||||
}
|
||||
reader.err = qaopsquality.ErrConflict
|
||||
r := httptest.NewRequest(http.MethodPost, "/api/v1/qa-ops/dashboard", strings.NewReader(good))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "dash-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-dashboard")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != http.StatusConflict {
|
||||
t.Fatalf("quality input drift status=%d want409", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type mirroredQualitySource struct {
|
||||
qualitySource
|
||||
reads int
|
||||
}
|
||||
|
||||
func (s *mirroredQualitySource) ReadStoredQuality(_ context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
s.reads++
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, key := range keys {
|
||||
out[key.ID] = qaopsquality.Project(key.InputHash, 1, 0, qaopsquality.Check{Result: dobotaiops.CheckMarkerCoverage(true)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func TestMirroredQualityQueriesDoNotRepeatObservationWrites(t *testing.T) {
|
||||
source := &mirroredQualitySource{qualitySource: qualitySource{record: dobotaiops.Record{ID: "fixture-turn", Question: "fixture", Answer: "暂无已发布"}}}
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
source.record.QualityInputHash = e.Hash
|
||||
legacy := &qualityFake{fail: true}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["quality-admin"] = "usr-boss"
|
||||
h, e2 := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: source, QAOpsTenantKey: "fixed", QAQuality: legacy, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if e2 != nil {
|
||||
t.Fatal(e2)
|
||||
}
|
||||
for _, q := range []struct{ method, path, body string }{{"GET", "/api/v1/qa-ops/records/fixture-turn", ""}, {"GET", "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", ""}, {"POST", "/api/v1/qa-ops/quality/query", `{"start":"2026-10-14T00:00:00Z","end":"2026-10-15T00:00:00Z","keyword":""}`}} {
|
||||
w := qualityRequest(h, q.method, q.path, "quality-admin", q.body)
|
||||
if w.Code != http.StatusOK {
|
||||
t.Fatal("local mirror read went back through observation writes", q.path, w.Code)
|
||||
}
|
||||
}
|
||||
if source.reads != 3 || legacy.calls != 0 {
|
||||
t.Fatal("batched stored projection not used", source.reads, legacy.calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type qaMirrorSyncStore interface {
|
||||
GetSyncStatus(context.Context) (qaopsmirror.Status, error)
|
||||
EnqueueSync(context.Context, string, string) (qaopsmirror.SyncReceipt, bool, error)
|
||||
}
|
||||
|
||||
func qaRecordsSync(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if r.URL.RawQuery != "" {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步入口不接受查询参数"})
|
||||
return
|
||||
}
|
||||
store, ok := c.QAOps.(qaMirrorSyncStore)
|
||||
if !ok || !c.QAOpsEnabled {
|
||||
writeJSON(w, 503, map[string]string{"error": "本地问答同步未接线,未创建任务"})
|
||||
return
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
state, e := store.GetSyncStatus(r.Context())
|
||||
if e != nil {
|
||||
qaOpsError(w, e)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": state})
|
||||
return
|
||||
}
|
||||
if !authorizeQAIntent(w, r, "qa-records-sync") {
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if key == "" || len(key) > 128 || strings.TrimSpace(key) != key {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求需要有效 Idempotency-Key,重试须复用原标识"})
|
||||
return
|
||||
}
|
||||
var body *struct{}
|
||||
d := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1024))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(&body) != nil || body == nil || d.Decode(&struct{}{}) != io.EOF {
|
||||
writeJSON(w, 400, map[string]string{"error": "同步请求体必须是空对象"})
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, replayed, e := store.EnqueueSync(r.Context(), key, identity.Username)
|
||||
if e != nil {
|
||||
status := 503
|
||||
message := "同步未成功入队,已有本地数据保持不变"
|
||||
if errors.Is(e, qaopsmirror.ErrInvalid) {
|
||||
status = 400
|
||||
message = "同步请求标识无效"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrConflict) {
|
||||
status = 409
|
||||
message = "同步标识已用于另一操作,请重新发起"
|
||||
}
|
||||
if errors.Is(e, qaopsmirror.ErrWorkerUnavailable) {
|
||||
message = "问答同步执行器未在线,未创建任务"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message})
|
||||
return
|
||||
}
|
||||
operation := "created"
|
||||
if replayed {
|
||||
operation = "replayed"
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"data": receipt, "operation": operation})
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type mirrorSyncSpy struct {
|
||||
qaOpsSpy
|
||||
syncCalls int
|
||||
key, actor string
|
||||
}
|
||||
|
||||
func (s *mirrorSyncSpy) GetSyncStatus(context.Context) (qaopsmirror.Status, error) {
|
||||
return qaopsmirror.Status{Mode: "local", IntervalSeconds: 300, WorkerReady: true}, nil
|
||||
}
|
||||
func (s *mirrorSyncSpy) EnqueueSync(_ context.Context, key, actor string) (qaopsmirror.SyncReceipt, bool, error) {
|
||||
s.syncCalls++
|
||||
s.key = key
|
||||
s.actor = actor
|
||||
return qaopsmirror.SyncReceipt{JobID: "fixture-mirror-job"}, false, nil
|
||||
}
|
||||
func TestQAMirrorSyncRequiresSessionIntentAndIdempotency(t *testing.T) {
|
||||
spy := &mirrorSyncSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
auth.sessions["mirror-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, QAOps: spy, QAOpsEnabled: true, QAOpsTenantKey: "fixture-tenant", Auth: &AuthConfig{Store: auth}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
method, token, key, intent, origin, body string
|
||||
status int
|
||||
}{
|
||||
{"GET", "", "", "", "", "", 401}, {"GET", "mirror-viewer", "", "", "", "", 403}, {"GET", "mirror-admin", "", "", "", "", 200},
|
||||
{"POST", "mirror-admin", "op-one", "", "", "{}", 403}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "https://foreign.invalid", "{}", 403},
|
||||
{"POST", "mirror-admin", "", "qa-records-sync", "", "{}", 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "null", 400},
|
||||
{"POST", "mirror-admin", "op-one", "qa-records-sync", "", `{"tenant":"forged"}`, 400}, {"POST", "mirror-admin", "op-one", "qa-records-sync", "", "{}", 202},
|
||||
} {
|
||||
req := httptest.NewRequest(tc.method, "/api/v1/qa-ops/sync", strings.NewReader(tc.body))
|
||||
if tc.token != "" {
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: tc.token})
|
||||
}
|
||||
req.Header.Set("Idempotency-Key", tc.key)
|
||||
req.Header.Set("X-Governance-Action", tc.intent)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("%s %s got %d want %d: %s", tc.method, tc.body, w.Code, tc.status, w.Body.String())
|
||||
}
|
||||
}
|
||||
if spy.syncCalls != 1 || spy.key != "op-one" || spy.actor == "" {
|
||||
t.Fatal("invalid sync reached store or operator was not session-stamped")
|
||||
}
|
||||
req := httptest.NewRequest("GET", "/api/v1/qa-ops/status", nil)
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
var body struct {
|
||||
Data struct {
|
||||
Cache *qaopsmirror.Status `json:"cache"`
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &body) != nil || body.Data.Cache == nil || body.Data.Cache.Mode != "local" {
|
||||
t.Fatal("local serving mode missing from status")
|
||||
}
|
||||
}
|
||||
func TestQAMirrorSyncNamespaceCannotBypassEntry(t *testing.T) {
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["mirror-admin"] = "usr-boss"
|
||||
h, _ := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}})
|
||||
req := httptest.NewRequest("POST", "/api/v1/jobs", strings.NewReader(`{"type":"qaops.records.sync.fixture","payload":{},"idempotency_key":"bypass"}`))
|
||||
req.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "mirror-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, req)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("generic jobs endpoint bypassed mirror sync admission", w.Code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
_ "time/tzdata"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type monthlyFilter struct {
|
||||
Month, Region, Department, Activity, Search string
|
||||
Start, End, MonthEnd time.Time
|
||||
Page, Limit int
|
||||
}
|
||||
type monthlyPerson struct {
|
||||
Key string `json:"key"`
|
||||
Name string `json:"name"`
|
||||
State string `json:"state"`
|
||||
Region string `json:"region"`
|
||||
Departments []string `json:"departments"`
|
||||
Questions int64 `json:"questions"`
|
||||
Succeeded int64 `json:"succeeded"`
|
||||
Failed int64 `json:"failed"`
|
||||
Other int64 `json:"other"`
|
||||
}
|
||||
type monthlyDepartment struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
}
|
||||
type monthlyPeople struct {
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
Source string `json:"source"`
|
||||
Timezone string `json:"timezone"`
|
||||
Month string `json:"month"`
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
MonthEnd time.Time `json:"month_end"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
Partial bool `json:"partial"`
|
||||
Questions int64 `json:"questions"`
|
||||
LinkedQuestions int64 `json:"linked_questions"`
|
||||
UnresolvedQuestions int64 `json:"unresolved_questions"`
|
||||
RosterPeople int `json:"roster_people"`
|
||||
UsedPeople int `json:"used_people"`
|
||||
ZeroPeople int `json:"zero_people"`
|
||||
MissingNames int `json:"missing_names"`
|
||||
Total int `json:"total"`
|
||||
Page int `json:"page"`
|
||||
Limit int `json:"limit"`
|
||||
HasMore bool `json:"has_more"`
|
||||
Rows []monthlyPerson `json:"rows"`
|
||||
DepartmentOptions []monthlyDepartment `json:"department_options"`
|
||||
}
|
||||
|
||||
func parseMonthlyFilter(values url.Values, now time.Time) (monthlyFilter, error) {
|
||||
f := monthlyFilter{Month: values.Get("month"), Region: values.Get("region"), Department: values.Get("department_id"), Activity: values.Get("activity"), Search: values.Get("search"), Page: 1, Limit: 30}
|
||||
allowed := map[string]bool{"month": true, "cutoff": true, "region": true, "department_id": true, "activity": true, "search": true, "page": true, "limit": true, "directory_id": true, "revision_id": true}
|
||||
for key, v := range values {
|
||||
if !allowed[key] || len(v) != 1 {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
}
|
||||
loc, err := time.LoadLocation("Asia/Shanghai")
|
||||
if err != nil {
|
||||
return f, dobotaiops.ErrUnavailable
|
||||
}
|
||||
f.Start, err = time.ParseInLocation("2006-01", f.Month, loc)
|
||||
if err != nil || len(f.Month) != 7 || f.Start.Year() < 1 || f.Start.Format("2006-01") != f.Month || !f.Start.Before(now) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
f.MonthEnd = f.Start.AddDate(0, 1, 0)
|
||||
f.End = f.MonthEnd
|
||||
if now.Before(f.End) {
|
||||
f.End = now.In(loc)
|
||||
}
|
||||
if raw := values.Get("cutoff"); raw != "" {
|
||||
cutoff, e := time.Parse(time.RFC3339Nano, raw)
|
||||
if e != nil || !cutoff.After(f.Start) || cutoff.After(f.MonthEnd) || cutoff.After(now) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
f.End = cutoff.In(loc)
|
||||
}
|
||||
if f.Activity == "" {
|
||||
f.Activity = "all"
|
||||
}
|
||||
if f.Activity != "all" && f.Activity != "used" && f.Activity != "zero" {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Region) || len(f.Region) > 256 || strings.TrimSpace(f.Region) != f.Region || strings.ContainsAny(f.Region, "\x00\r\n") {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !utf8.ValidString(f.Search) || utf8.RuneCountInString(f.Search) > 100 || strings.ContainsRune(f.Search, 0) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
for key, target := range map[string]*int{"page": &f.Page, "limit": &f.Limit} {
|
||||
if raw := values.Get(key); raw != "" {
|
||||
n, e := strconv.Atoi(raw)
|
||||
if e != nil || n < 1 || n > 100000 {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
*target = n
|
||||
}
|
||||
}
|
||||
if f.Limit > 100 || f.Page > 1 && (!values.Has("directory_id") || !values.Has("revision_id")) {
|
||||
return f, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
func monthlyHasDepartment(person qaopsorg.PersonAttribution, department string, parents map[string]string) bool {
|
||||
if department == "" {
|
||||
return true
|
||||
}
|
||||
for _, id := range person.DepartmentIDs {
|
||||
for cur := id; cur != ""; cur = parents[cur] {
|
||||
if cur == department {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func monthlyResult(groups dobotaiops.UsageGroups, p *qaopsorg.Attribution, f monthlyFilter) monthlyPeople {
|
||||
result := monthlyPeople{Organization: attributionVersion(p), Source: "2.0", Timezone: "Asia/Shanghai", Month: f.Month, Start: f.Start, End: f.End, MonthEnd: f.MonthEnd, AsOf: groups.AsOf, Partial: f.End.Before(f.MonthEnd), Page: f.Page, Limit: f.Limit, Rows: []monthlyPerson{}, DepartmentOptions: []monthlyDepartment{}}
|
||||
totals := map[string]dobotaiops.UsageGroup{}
|
||||
for _, group := range groups.Groups {
|
||||
result.Questions += group.Total
|
||||
person := p.Resolve(group.Identity.StaffID, group.Identity.UnionID)
|
||||
if person.PersonID == "" {
|
||||
result.UnresolvedQuestions += group.Total
|
||||
continue
|
||||
}
|
||||
n := totals[person.PersonID]
|
||||
n.Total += group.Total
|
||||
n.Succeeded += group.Succeeded
|
||||
n.Failed += group.Failed
|
||||
totals[person.PersonID] = n
|
||||
result.LinkedQuestions += group.Total
|
||||
}
|
||||
parents := map[string]string{}
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
parents[d.ID] = d.ParentID
|
||||
result.DepartmentOptions = append(result.DepartmentOptions, monthlyDepartment{ID: d.ID, Path: d.Path})
|
||||
}
|
||||
rows := []monthlyPerson{}
|
||||
people := p.Members()
|
||||
result.RosterPeople = len(people)
|
||||
search := strings.ToLower(f.Search)
|
||||
for _, person := range people {
|
||||
n := totals[person.PersonID]
|
||||
if n.Total > 0 {
|
||||
result.UsedPeople++
|
||||
} else {
|
||||
result.ZeroPeople++
|
||||
}
|
||||
if person.Name == "" {
|
||||
result.MissingNames++
|
||||
}
|
||||
if f.Region != "" && f.Region != person.Region && f.Region != person.State {
|
||||
continue
|
||||
}
|
||||
if !monthlyHasDepartment(person, f.Department, parents) {
|
||||
continue
|
||||
}
|
||||
if f.Activity == "used" && n.Total == 0 || f.Activity == "zero" && n.Total > 0 {
|
||||
continue
|
||||
}
|
||||
if search != "" && !strings.Contains(strings.ToLower(person.Name), search) && !strings.Contains(strings.ToLower(strings.Join(person.Departments, ";")), search) {
|
||||
continue
|
||||
}
|
||||
// This is a stable row key, not an anonymisation claim or a new user identifier.
|
||||
sum := sha256.Sum256([]byte(p.Metadata.DirectoryID + "\x00" + person.PersonID))
|
||||
rows = append(rows, monthlyPerson{Key: "person-" + hex.EncodeToString(sum[:]), Name: person.Name, State: person.State, Region: person.Region, Departments: person.Departments, Questions: n.Total, Succeeded: n.Succeeded, Failed: n.Failed, Other: n.Total - n.Succeeded - n.Failed})
|
||||
}
|
||||
sort.Slice(rows, func(i, j int) bool {
|
||||
a, b := rows[i], rows[j]
|
||||
if a.Name == "" && b.Name != "" {
|
||||
return false
|
||||
}
|
||||
if a.Name != "" && b.Name == "" {
|
||||
return true
|
||||
}
|
||||
if a.Name != b.Name {
|
||||
return a.Name < b.Name
|
||||
}
|
||||
return a.Key < b.Key
|
||||
})
|
||||
result.Total = len(rows)
|
||||
start := (f.Page - 1) * f.Limit
|
||||
if start < len(rows) {
|
||||
end := min(start+f.Limit, len(rows))
|
||||
result.Rows = rows[start:end]
|
||||
result.HasMore = end < len(rows)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// Names remain in the bounded read-query body, not URLs/access logs. The source
|
||||
// reader and governance store are still strictly read-only on this route.
|
||||
func monthlyRequestValues(w http.ResponseWriter, r *http.Request) (url.Values, error) {
|
||||
values := url.Values{}
|
||||
if r.URL.RawQuery != "" || r.Header.Get("X-Governance-Action") != "qa-usage-read" {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 8192))
|
||||
token, err := decoder.Token()
|
||||
if err != nil || token != json.Delim('{') {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
for decoder.More() {
|
||||
token, err = decoder.Token()
|
||||
key, ok := token.(string)
|
||||
if err != nil || !ok || values.Has(key) {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
var raw json.RawMessage
|
||||
if decoder.Decode(&raw) != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if key == "page" || key == "limit" {
|
||||
var n int
|
||||
if json.Unmarshal(raw, &n) != nil {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
values.Set(key, strconv.Itoa(n))
|
||||
} else {
|
||||
var text string
|
||||
if json.Unmarshal(raw, &text) != nil {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
values.Set(key, text)
|
||||
}
|
||||
}
|
||||
if _, err = decoder.Token(); err != nil {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
var extra any
|
||||
if decoder.Decode(&extra) != io.EOF {
|
||||
return nil, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
func qaMonthlyPeople(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
values, err := monthlyRequestValues(w, r)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
f, err := parseMonthlyFilter(values, config.Now())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
p, err := recordAttribution(r.Context(), config)
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
if p.Metadata.State != "ready" {
|
||||
writeJSON(w, 409, map[string]string{"code": "directory_missing", "error": "尚无完整通讯录,请先从区域使用页同步;不能生成零记录人员名单"})
|
||||
return
|
||||
}
|
||||
|
||||
if values.Has("directory_id") || values.Has("revision_id") {
|
||||
if !values.Has("directory_id") || !values.Has("revision_id") {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
if values.Get("directory_id") != p.Metadata.DirectoryID || values.Get("revision_id") != p.Metadata.RevisionID {
|
||||
writeJSON(w, 409, map[string]string{"code": "organization_changed", "error": "通讯录或区域配置已变化,请重新查询个人月明细"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Region != "" && f.Region != "unassigned" && f.Region != "cross_region" {
|
||||
found := false
|
||||
for _, name := range p.Metadata.RegionLabels() {
|
||||
found = found || f.Region == name
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
if f.Department != "" {
|
||||
found := false
|
||||
for _, d := range p.Metadata.View.Departments {
|
||||
found = found || d.ID == f.Department
|
||||
}
|
||||
if !found {
|
||||
qaOpsError(w, dobotaiops.ErrInvalidQuery)
|
||||
return
|
||||
}
|
||||
}
|
||||
reader, ok := config.QAOps.(qaUsageReader)
|
||||
if !ok || config.QAOpsTenantKey == "" {
|
||||
qaOpsError(w, dobotaiops.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
groups, err := reader.ReadUsageGroups(r.Context(), dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: config.QAOpsTenantKey, Start: f.Start, End: f.End}})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": monthlyResult(groups, p, f)})
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type monthlyReaderSpy struct {
|
||||
attributedReader
|
||||
query dobotaiops.RecordQuery
|
||||
calls int
|
||||
}
|
||||
|
||||
func (s *monthlyReaderSpy) ReadUsageGroups(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) {
|
||||
s.calls++
|
||||
s.query = q
|
||||
return s.attributedReader.ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func monthlyRequest(h http.Handler, path, token string) *httptest.ResponseRecorder {
|
||||
u, _ := url.Parse(path)
|
||||
body := map[string]any{}
|
||||
for k, v := range u.Query() {
|
||||
if len(v) != 1 {
|
||||
body[k] = v
|
||||
continue
|
||||
}
|
||||
if k == "page" || k == "limit" {
|
||||
if n, e := strconv.Atoi(v[0]); e == nil {
|
||||
body[k] = n
|
||||
} else {
|
||||
body[k] = v[0]
|
||||
}
|
||||
} else {
|
||||
body[k] = v[0]
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(body)
|
||||
r := httptest.NewRequest(http.MethodPost, u.Path, bytes.NewReader(raw))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("X-Governance-Action", "qa-usage-read")
|
||||
if token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
|
||||
func monthlyHandler(t *testing.T) (http.Handler, *attributionOrgSpy, *monthlyReaderSpy) {
|
||||
t.Helper()
|
||||
d := qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "示例根"}, {ID: "child", ParentID: "root", Name: "子部门"}}, People: []qaopsorg.Person{{ID: "fixture-private-staff", Name: "同名示例", UnionID: "fixture-private-union", DepartmentIDs: []string{"root"}}, {ID: "private-zero", Name: "同名示例", DepartmentIDs: []string{"child"}}, {ID: "private-cross", Name: "跨区域示例", DepartmentIDs: []string{"root", "child"}}, {ID: "private-unnamed", DepartmentIDs: []string{"child"}}}}
|
||||
now := time.Date(2026, 10, 17, 8, 0, 0, 0, time.UTC)
|
||||
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "monthly-directory", DirectorySource: "weekly_report_live", DirectorySyncedAt: &now, RevisionID: "monthly-regions", Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "国内工业"}, {DepartmentID: "child", Region: "APAC"}}}, d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
org := &attributionOrgSpy{projection: p}
|
||||
reader := &monthlyReaderSpy{}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["attribution-admin"] = "usr-boss"
|
||||
auth.sessions["attribution-viewer"] = "usr-eye"
|
||||
h, err := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: reader, QAOpsTenantKey: "fixed", QAOrg: org, Now: func() time.Time { return now }})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return h, org, reader
|
||||
}
|
||||
func TestQAMonthlyPeopleIncludesZeroUseAndKeepsUnresolvedEvents(t *testing.T) {
|
||||
h, _, reader := monthlyHandler(t)
|
||||
path := "/api/v1/qa-ops/usage/people?month=2026-10&limit=2"
|
||||
w := monthlyRequest(h, path, "attribution-admin")
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Code, w.Body.String())
|
||||
}
|
||||
var result struct {
|
||||
Data struct {
|
||||
Month string
|
||||
Timezone string
|
||||
Partial bool
|
||||
Questions int64
|
||||
LinkedQuestions int64 `json:"linked_questions"`
|
||||
UnresolvedQuestions int64 `json:"unresolved_questions"`
|
||||
RosterPeople int `json:"roster_people"`
|
||||
UsedPeople int `json:"used_people"`
|
||||
ZeroPeople int `json:"zero_people"`
|
||||
MissingNames int `json:"missing_names"`
|
||||
Total int
|
||||
HasMore bool `json:"has_more"`
|
||||
Rows []struct {
|
||||
Key string
|
||||
Name string
|
||||
Questions int64
|
||||
State string
|
||||
}
|
||||
}
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &result) != nil {
|
||||
t.Fatal("invalid monthly JSON")
|
||||
}
|
||||
v := result.Data
|
||||
if v.Month != "2026-10" || v.Timezone != "Asia/Shanghai" || !v.Partial || v.Questions != 7 || v.LinkedQuestions != 5 || v.UnresolvedQuestions != 2 || v.RosterPeople != 4 || v.UsedPeople != 1 || v.ZeroPeople != 3 || v.MissingNames != 1 || v.Total != 4 || len(v.Rows) != 2 || !v.HasMore {
|
||||
t.Fatal("monthly roster, zero count or alias dedup wrong", w.Body.String())
|
||||
}
|
||||
if reader.query.Window.TenantKey != "fixed" || reader.query.Window.Start.Format(time.RFC3339) != "2026-10-01T00:00:00+08:00" || reader.query.Window.End.Format(time.RFC3339) != "2026-10-17T16:00:00+08:00" {
|
||||
t.Fatal("month was not normalized to the named timezone")
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "private-") || strings.Contains(w.Body.String(), "performance") || strings.Contains(w.Body.String(), "staff_id") {
|
||||
t.Fatal("raw identities or unapproved verdict exposed")
|
||||
}
|
||||
page2 := monthlyRequest(h, path+"&page=2&directory_id=monthly-directory&revision_id=monthly-regions", "attribution-admin")
|
||||
if page2.Code != 200 {
|
||||
t.Fatal(page2.Body.String())
|
||||
}
|
||||
for _, extra := range []string{"&activity=zero", "®ion=cross_region", "&department_id=child", "&search=" + url.QueryEscape("子部门")} {
|
||||
r := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2026-10"+extra, "attribution-admin")
|
||||
if r.Code != 200 {
|
||||
t.Fatal("valid monthly filter failed", r.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestQAMonthlyScopeAndVersionFailClosed(t *testing.T) {
|
||||
h, org, reader := monthlyHandler(t)
|
||||
base := "/api/v1/qa-ops/usage/people?month=2026-10"
|
||||
for _, tc := range []struct {
|
||||
suffix, token string
|
||||
status int
|
||||
}{{"", "", 401}, {"", "attribution-viewer", 403}, {"&tenant=forged", "attribution-admin", 400}, {"&threshold=5", "attribution-admin", 400}, {"&month=duplicate", "attribution-admin", 400}, {"&page=0", "attribution-admin", 400}, {"&limit=101", "attribution-admin", 400}, {"&activity=under5", "attribution-admin", 400}, {"®ion=invalid", "attribution-admin", 400}, {"&department_id=invalid", "attribution-admin", 400}, {"&page=2", "attribution-admin", 400}, {"&page=2&directory_id=changed&revision_id=monthly-regions", "attribution-admin", 409}, {"&cutoff=2026-11-01T00:00:00Z", "attribution-admin", 400}} {
|
||||
w := monthlyRequest(h, base+tc.suffix, tc.token)
|
||||
if w.Code != tc.status {
|
||||
t.Fatalf("monthly %s: %d want %d", tc.suffix, w.Code, tc.status)
|
||||
}
|
||||
}
|
||||
for _, month := range []string{"2026-1", " 2026-10", "2026-13", "0000-01", "2026-11"} {
|
||||
r := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month="+url.QueryEscape(month), "attribution-admin")
|
||||
if r.Code != 400 {
|
||||
t.Fatal("invalid/future month accepted")
|
||||
}
|
||||
}
|
||||
if reader.calls != 0 {
|
||||
t.Fatal("invalid or unauthorized monthly request reached source")
|
||||
}
|
||||
org.projection, _ = qaopsorg.BuildAttribution(qaopsorg.State{State: "empty"}, qaopsorg.Directory{})
|
||||
if w := monthlyRequest(h, base, "attribution-admin"); w.Code != 409 {
|
||||
t.Fatal("no roster presented as zero-use list")
|
||||
}
|
||||
org.err = qaopsorg.ErrUnavailable
|
||||
if w := monthlyRequest(h, base, "attribution-admin"); w.Code != 503 {
|
||||
t.Fatal("store failure hidden as empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAMonthlyPersonFiltersDoNotGuessNamesOrDuplicateDescendantMembers(t *testing.T) {
|
||||
h, _, _ := monthlyHandler(t)
|
||||
for _, tc := range []struct {
|
||||
filter string
|
||||
total int
|
||||
}{{"&activity=used", 1}, {"&activity=zero", 3}, {"®ion=cross_region", 1}, {"®ion=APAC", 2}, {"&department_id=child", 3}, {"&department_id=root", 4}, {"&search=" + url.QueryEscape("同名示例"), 2}, {"&search=" + url.QueryEscape("子部门"), 3}, {"&search=%25_", 0}} {
|
||||
w := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2026-10"+tc.filter, "attribution-admin")
|
||||
var payload struct{ Data monthlyPeople }
|
||||
if w.Code != 200 || json.Unmarshal(w.Body.Bytes(), &payload) != nil || payload.Data.Total != tc.total || payload.Data.Questions != 7 {
|
||||
t.Fatal("person-scope filter did not preserve source totals or person dedup", tc.filter)
|
||||
}
|
||||
for _, r := range payload.Data.Rows {
|
||||
if tc.filter == "&activity=zero" && r.Questions != 0 {
|
||||
t.Fatal("used member labeled zero")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestQAMonthlyReadBodyRejectsDuplicateNullTrailingAndOversizedInput(t *testing.T) {
|
||||
h, _, reader := monthlyHandler(t)
|
||||
for _, body := range []string{`{"month":"2026-10","month":"2026-10"}`, `{"month":"2026-10","search":null}`, `{"month":"2026-10","page":"1"}`, `{"month":"2026-10"}{}`, `[]`, `{"month":"2026-10","search":"` + strings.Repeat("x", 9000) + `"}`} {
|
||||
r := httptest.NewRequest("POST", "/api/v1/qa-ops/usage/people", strings.NewReader(body))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "attribution-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-usage-read")
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("invalid read body reached source", w.Code)
|
||||
}
|
||||
}
|
||||
for _, method := range []string{"POST", "GET"} {
|
||||
r := httptest.NewRequest(method, "/api/v1/qa-ops/usage/people?search=sensitive-example", strings.NewReader(`{"month":"2026-10"}`))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "attribution-admin"})
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 400 && w.Code != 405 {
|
||||
t.Fatal("URL-based name query accepted")
|
||||
}
|
||||
}
|
||||
if reader.calls != 0 {
|
||||
t.Fatal("invalid body read production source")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAMonthlyPastLeapMonthUsesClosedCalendarWindow(t *testing.T) {
|
||||
h, _, reader := monthlyHandler(t)
|
||||
w := monthlyRequest(h, "/api/v1/qa-ops/usage/people?month=2024-02", "attribution-admin")
|
||||
if w.Code != 200 {
|
||||
t.Fatal(w.Body.String())
|
||||
}
|
||||
if reader.query.Window.End.Format(time.RFC3339) != "2024-03-01T00:00:00+08:00" || reader.query.Window.End.Sub(reader.query.Window.Start) != 29*24*time.Hour {
|
||||
t.Fatal("leap month boundary incorrect")
|
||||
}
|
||||
var raw struct{ Data struct{ Partial bool } }
|
||||
_ = json.Unmarshal(w.Body.Bytes(), &raw)
|
||||
if raw.Data.Partial {
|
||||
t.Fatal("past natural month mislabeled as current progress")
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,16 @@ func qaOpsStatus(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
warnings = append(warnings, "database_transport_unencrypted")
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}})
|
||||
data := map[string]any{"state": state, "code": code, "warnings": warnings, "read_only": true, "source_version": "2.0", "channel": "dingtalk"}
|
||||
if mirror, ok := config.QAOps.(qaMirrorSyncStore); ok {
|
||||
cache, err := mirror.GetSyncStatus(r.Context())
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
data["cache"] = cache
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": data})
|
||||
}
|
||||
|
||||
func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
@@ -104,6 +113,10 @@ func listQAOpsRecords(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
enrichQAPage(&page, projection)
|
||||
if err := enrichQAQualityPage(r.Context(), config, &page); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": page})
|
||||
}
|
||||
|
||||
@@ -130,13 +143,17 @@ func getQAOpsRecord(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
enrichQARecord(&item, projection)
|
||||
if err := enrichQAQualityRecord(r.Context(), config, &item); err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"data": item})
|
||||
}
|
||||
|
||||
func qaOpsError(w http.ResponseWriter, err error) {
|
||||
status := http.StatusServiceUnavailable
|
||||
code := "source_unavailable"
|
||||
message := "问答数据源不可用,请检查独立只读连接;原有知识治理功能不受影响"
|
||||
message := "问答记录当前不可用;本地模式请检查同步状态,原有知识治理功能不受影响"
|
||||
if errors.Is(err, errQAOrganization) {
|
||||
code = "organization_unavailable"
|
||||
message = "通讯录或区域配置读取失败,未将不可用数据伪装成空列,请重试"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
@@ -36,9 +37,14 @@ func qaOrganization(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
return
|
||||
}
|
||||
var request qaopsorg.SaveRequest
|
||||
decoder := json.NewDecoder(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
raw, readErr := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
var fields map[string]json.RawMessage
|
||||
var extra any
|
||||
invalidJSON := readErr != nil || json.Unmarshal(raw, &fields) != nil || fields == nil || fields["base_revision"] == nil || walkQualityJSON(check) != nil || check.Decode(&extra) != io.EOF
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.DisallowUnknownFields()
|
||||
if decoder.Decode(&request) != nil || decoder.Decode(&struct{}{}) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
if invalidJSON || decoder.Decode(&request) != nil || decoder.Decode(&extra) != io.EOF || request.DirectoryID == "" || request.Rules == nil {
|
||||
writeOrgError(w, qaopsorg.ErrInvalid)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -17,8 +17,11 @@ type QAOrgSyncStore interface {
|
||||
}
|
||||
|
||||
func authorizeQAOrganizationWrite(w http.ResponseWriter, r *http.Request) bool {
|
||||
if r.Header.Get("X-Governance-Action") != "qa-organization" || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "区域配置需要同源操作意图"})
|
||||
return authorizeQAIntent(w, r, "qa-organization")
|
||||
}
|
||||
func authorizeQAIntent(w http.ResponseWriter, r *http.Request, intent string) bool {
|
||||
if r.Header.Get("X-Governance-Action") != intent || r.Header.Get("Sec-Fetch-Site") == "cross-site" {
|
||||
writeJSON(w, 403, map[string]string{"error": "此操作需要同源操作意图"})
|
||||
return false
|
||||
}
|
||||
// Fetch Metadata survives same-origin proxies that rewrite Host; untrusted
|
||||
|
||||
@@ -52,6 +52,12 @@ func TestQAOrganizationGuardsIdentityIntentAndErrors(t *testing.T) {
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{} {}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":null}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":null,"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[null],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","regions":[{"id":"edu","name":null}],"rules":[]}`, 400},
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[],"rules":[]}`, 400},
|
||||
|
||||
{"PUT", base + "/regions", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
{"POST", base + "/preview", "org-admin", "qa-organization", "", `{"directory_id":"d","base_revision":"","rules":[]}`, 200},
|
||||
} {
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// HTTP LAN/tailnet origins may omit Fetch Metadata. nginx must preserve the
|
||||
// external authority including its port so Origin can be checked without it.
|
||||
func TestQAProxyPreservesBrowserAuthority(t *testing.T) {
|
||||
config, err := os.ReadFile("../../deploy/nginx.conf")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hosts := regexp.MustCompile(`(?m)^\s*proxy_set_header\s+Host\s+([^;]+);`).FindAllStringSubmatch(string(config), -1)
|
||||
if len(hosts) < 2 {
|
||||
t.Fatal("API and health proxy Host directives must both be explicit")
|
||||
}
|
||||
for _, host := range hosts {
|
||||
if host[1] != "$http_host" {
|
||||
t.Fatalf("proxy drops browser authority/port: got %q, want $http_host", host[1])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAIntentWithoutFetchMetadataChecksExactAuthority(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, host, origin, forwarded, site, intent string
|
||||
allowed bool
|
||||
}{
|
||||
{"LAN same authority", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "", "qa-quality", true},
|
||||
{"tailnet same authority", "100.92.49.78:8088", "http://100.92.49.78:8088", "", "", "qa-quality", true},
|
||||
{"proxy stripped port", "192.168.50.134", "http://192.168.50.134:8088", "", "", "qa-quality", false},
|
||||
{"foreign origin", "192.168.50.134:8088", "http://foreign.invalid:8088", "", "", "qa-quality", false},
|
||||
{"different port", "192.168.50.134:8088", "http://192.168.50.134:8089", "", "", "qa-quality", false},
|
||||
{"forwarded header cannot grant", "192.168.50.134:8088", "http://foreign.invalid:8088", "foreign.invalid:8088", "", "qa-quality", false},
|
||||
{"opaque origin", "192.168.50.134:8088", "null", "", "", "qa-quality", false},
|
||||
{"explicit cross site", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "cross-site", "qa-quality", false},
|
||||
{"missing intent", "192.168.50.134:8088", "http://192.168.50.134:8088", "", "", "", false},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
req := httptest.NewRequest("POST", "http://"+tc.host+"/api/v1/qa-ops/quality/query", nil)
|
||||
req.Header.Set("Origin", tc.origin)
|
||||
req.Header.Set("X-Governance-Action", tc.intent)
|
||||
if tc.forwarded != "" {
|
||||
req.Header.Set("X-Forwarded-Host", tc.forwarded)
|
||||
}
|
||||
if tc.site != "" {
|
||||
req.Header.Set("Sec-Fetch-Site", tc.site)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
if got := authorizeQAIntent(rec, req, "qa-quality"); got != tc.allowed {
|
||||
t.Fatalf("authorized=%v want %v, HTTP=%d", got, tc.allowed, rec.Code)
|
||||
}
|
||||
if !tc.allowed && rec.Code != 403 {
|
||||
t.Fatalf("rejected authority should be 403, got %d", rec.Code)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
)
|
||||
|
||||
type QAQualityStore interface {
|
||||
ObserveKeys(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
Observe(context.Context, []dobotaiops.Record) (map[string]qaopsquality.View, error)
|
||||
Save(context.Context, dobotaiops.Record, qaopsquality.SaveRequest, string) (qaopsquality.Receipt, error)
|
||||
Columns(context.Context, []dobotaiops.QualityKey) ([]string, error)
|
||||
History(context.Context, string, int64, int64) (qaopsquality.History, error)
|
||||
Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error)
|
||||
}
|
||||
|
||||
type storedQAQualityReader interface {
|
||||
ReadStoredQuality(context.Context, []dobotaiops.QualityKey) (map[string]qaopsquality.View, error)
|
||||
}
|
||||
|
||||
func qaQualityViews(ctx context.Context, c Config, records []dobotaiops.Record) (map[string]qaopsquality.View, error) {
|
||||
if reader, ok := c.QAOps.(storedQAQualityReader); ok {
|
||||
keys := make([]dobotaiops.QualityKey, 0, len(records))
|
||||
for _, r := range records {
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.ID, InputHash: r.QualityInputHash})
|
||||
}
|
||||
return reader.ReadStoredQuality(ctx, keys)
|
||||
}
|
||||
return c.QAQuality.Observe(ctx, records)
|
||||
}
|
||||
|
||||
type qaQualityReader interface {
|
||||
ReadQualityScope(context.Context, dobotaiops.RecordQuery) (dobotaiops.QualityScope, error)
|
||||
}
|
||||
|
||||
func writeQualityError(w http.ResponseWriter, err error) {
|
||||
status, code, message := 503, "quality_unavailable", "质量留档/复核存储不可用,未将失败伪装为空值或零统计"
|
||||
switch {
|
||||
case errors.Is(err, qaopsquality.ErrInvalid) || errors.Is(err, dobotaiops.ErrInvalidQuery):
|
||||
status, code, message = 400, "invalid_quality_request", "质量操作参数无效:请核对结论、理由、版本和筛选范围(最多5000条/32MiB)"
|
||||
case errors.Is(err, qaopsquality.ErrConflict):
|
||||
status, code, message = 409, "quality_conflict", "原始问答或人工复核版本已变化,请重新读取问答后核对;未覆盖现有结论"
|
||||
case errors.Is(err, qaopsquality.ErrSnapshotMissing):
|
||||
status, code, message = 409, "quality_input_metadata_only", "此版本仅留存指纹与复检元数据,未采集原文;未编造空问题或空答案"
|
||||
case errors.Is(err, qaopsquality.ErrNotFound):
|
||||
status, code, message = 404, "quality_input_not_found", "未找到当前授权范围的输入版本"
|
||||
}
|
||||
writeJSON(w, status, map[string]string{"error": message, "code": code})
|
||||
}
|
||||
func enrichQAQualityRecord(ctx context.Context, c Config, item *dobotaiops.Record) error {
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := qaQualityViews(ctx, c, []dobotaiops.Record{*item})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
v, ok := views[item.ID]
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
item.Quality, err = json.Marshal(v)
|
||||
return err
|
||||
}
|
||||
func enrichQAQualityPage(ctx context.Context, c Config, page *dobotaiops.RecordPage) error {
|
||||
if c.QAQuality == nil {
|
||||
return nil
|
||||
}
|
||||
views, err := qaQualityViews(ctx, c, page.Items)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range page.Items {
|
||||
v, ok := views[page.Items[i].ID]
|
||||
if !ok {
|
||||
return qaopsquality.ErrUnavailable
|
||||
}
|
||||
page.Items[i].Quality, err = json.Marshal(v)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
columns, err := c.QAQuality.Columns(ctx, page.ScopeQuality)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
dobotaiops.AddRecordColumns(page, columns...)
|
||||
return nil
|
||||
}
|
||||
func walkQualityJSON(d *json.Decoder) error {
|
||||
token, err := d.Token()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if token == nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
if delimiter, ok := token.(json.Delim); ok {
|
||||
if delimiter != '{' && delimiter != '[' {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys := map[string]bool{}
|
||||
for d.More() {
|
||||
if delimiter == '{' {
|
||||
key, e := d.Token()
|
||||
name, ok := key.(string)
|
||||
if e != nil || !ok || keys[name] {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
keys[name] = true
|
||||
}
|
||||
if walkQualityJSON(d) != nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
}
|
||||
_, err = d.Token()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func decodeQualityJSON(w http.ResponseWriter, r *http.Request, target any, required ...string) error {
|
||||
if r.URL.RawQuery != "" {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
raw, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 64<<10))
|
||||
if err != nil || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
var top map[string]json.RawMessage
|
||||
if json.Unmarshal(raw, &top) != nil || top == nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
for _, key := range required {
|
||||
if _, ok := top[key]; !ok {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
}
|
||||
check := json.NewDecoder(bytes.NewReader(raw))
|
||||
if walkQualityJSON(check) != nil {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
var extra any
|
||||
if check.Decode(&extra) != io.EOF {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
d := json.NewDecoder(bytes.NewReader(raw))
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(target) != nil || d.Decode(&extra) != io.EOF {
|
||||
return qaopsquality.ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func qaQualityReview(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-quality") {
|
||||
return
|
||||
}
|
||||
var request qaopsquality.SaveRequest
|
||||
if decodeQualityJSON(w, r, &request, "input_hash", "input_epoch", "base_revision", "nonce", "fields", "reason") != nil || qaopsquality.Validate(request) != nil {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil || c.QAOps == nil || c.QAOpsTenantKey == "" {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
record, err := c.QAOps.GetRecord(r.Context(), c.QAOpsTenantKey, r.PathValue("id"))
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
identity, _ := sessionFrom(r.Context())
|
||||
receipt, err := c.QAQuality.Save(r.Context(), record, request, identity.Username)
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": receipt})
|
||||
}
|
||||
func qaQualityQuery(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) || !authorizeQAIntent(w, r, "qa-quality") {
|
||||
return
|
||||
}
|
||||
var request struct {
|
||||
Start string `json:"start"`
|
||||
End string `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
}
|
||||
if decodeQualityJSON(w, r, &request) != nil {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
window, err := dobotaiops.NewWindow(c.QAOpsTenantKey, request.Start, request.End, 90*24*time.Hour, c.Now())
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
reader, ok := c.QAOps.(qaQualityReader)
|
||||
if !ok || c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
scope, err := reader.ReadQualityScope(r.Context(), dobotaiops.RecordQuery{Window: window, Keyword: request.Keyword})
|
||||
if err != nil {
|
||||
qaOpsError(w, err)
|
||||
return
|
||||
}
|
||||
var views map[string]qaopsquality.View
|
||||
if stored, ok := c.QAOps.(storedQAQualityReader); ok {
|
||||
views, err = stored.ReadStoredQuality(r.Context(), scope.Keys)
|
||||
} else {
|
||||
views, err = c.QAQuality.ObserveKeys(r.Context(), scope.Keys)
|
||||
}
|
||||
if err != nil || len(views) != len(scope.Keys) {
|
||||
if err == nil {
|
||||
err = qaopsquality.ErrUnavailable
|
||||
}
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": map[string]any{"summary": qaopsquality.Summarize(views), "start": window.Start, "end": window.End, "keyword": request.Keyword, "as_of": scope.AsOf, "ai_state": "not_configured", "scope": "whole_filter"}})
|
||||
}
|
||||
func qaQualityHistory(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
values := r.URL.Query()
|
||||
for key, v := range values {
|
||||
if (key != "review_before" && key != "check_before") || len(v) != 1 {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
}
|
||||
cursors := map[string]int64{}
|
||||
for _, key := range []string{"review_before", "check_before"} {
|
||||
raw := values.Get(key)
|
||||
if raw == "" {
|
||||
continue
|
||||
}
|
||||
n, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil || n < 1 {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
cursors[key] = n
|
||||
}
|
||||
value, err := c.QAQuality.History(r.Context(), r.PathValue("id"), cursors["review_before"], cursors["check_before"])
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": value})
|
||||
}
|
||||
func qaQualitySnapshot(w http.ResponseWriter, r *http.Request, c Config) {
|
||||
if !authorizeQAOps(w, r) {
|
||||
return
|
||||
}
|
||||
epoch, err := strconv.ParseInt(r.PathValue("epoch"), 10, 64)
|
||||
if err != nil || epoch < 1 || r.URL.RawQuery != "" {
|
||||
writeQualityError(w, qaopsquality.ErrInvalid)
|
||||
return
|
||||
}
|
||||
if c.QAQuality == nil {
|
||||
writeQualityError(w, qaopsquality.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
value, err := c.QAQuality.Snapshot(r.Context(), r.PathValue("id"), epoch)
|
||||
if err != nil {
|
||||
writeQualityError(w, err)
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"data": value})
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type qualityFake struct {
|
||||
actor string
|
||||
calls int
|
||||
fail bool
|
||||
}
|
||||
|
||||
func (s *qualityFake) Observe(_ context.Context, records []dobotaiops.Record) (map[string]qaopsquality.View, error) {
|
||||
s.calls++
|
||||
if s.fail {
|
||||
return nil, qaopsquality.ErrUnavailable
|
||||
}
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, r := range records {
|
||||
e, _ := qaopsquality.EvidenceFor(r)
|
||||
out[r.ID] = qaopsquality.Project(e.Hash, 1, 0, qaopsquality.Check{InputEpoch: 1, InputHash: e.Hash, Result: dobotaiops.CheckAnswerCoverage(r.Answer)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *qualityFake) ObserveKeys(_ context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
s.calls++
|
||||
out := map[string]qaopsquality.View{}
|
||||
for _, key := range keys {
|
||||
out[key.ID] = qaopsquality.Project(key.InputHash, 1, 0, qaopsquality.Check{Result: dobotaiops.CheckMarkerCoverage(key.Marker)}, nil)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *qualityFake) Save(_ context.Context, r dobotaiops.Record, q qaopsquality.SaveRequest, actor string) (qaopsquality.Receipt, error) {
|
||||
s.actor = actor
|
||||
v := qaopsquality.Project(q.InputHash, 1, 1, qaopsquality.Check{Result: dobotaiops.CheckAnswerCoverage(r.Answer)}, &qaopsquality.Review{InputEpoch: 1, InputHash: q.InputHash, Fields: q.Fields, Reason: q.Reason, Reviewer: actor})
|
||||
return qaopsquality.Receipt{View: v, SavedRevision: 1}, nil
|
||||
}
|
||||
func (s *qualityFake) Columns(_ context.Context, keys []dobotaiops.QualityKey) ([]string, error) {
|
||||
return []string{"is_correct", "product_category"}, nil
|
||||
}
|
||||
func (s *qualityFake) History(context.Context, string, int64, int64) (qaopsquality.History, error) {
|
||||
return qaopsquality.History{Reviews: []qaopsquality.Review{}, Checks: []qaopsquality.Check{}}, nil
|
||||
}
|
||||
func (s *qualityFake) Snapshot(context.Context, string, int64) (qaopsquality.Snapshot, error) {
|
||||
return qaopsquality.Snapshot{}, qaopsquality.ErrNotFound
|
||||
}
|
||||
|
||||
type qualitySource struct {
|
||||
attributedReader
|
||||
record dobotaiops.Record
|
||||
tenant string
|
||||
scopeCalls int
|
||||
}
|
||||
|
||||
func (s *qualitySource) GetRecord(_ context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
s.tenant = tenant
|
||||
return s.record, nil
|
||||
}
|
||||
func (s *qualitySource) ListRecords(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
return dobotaiops.RecordPage{Items: []dobotaiops.Record{s.record}, Columns: []string{"question"}, Total: 2, AsOf: time.Now()}, nil
|
||||
}
|
||||
func (s *qualitySource) ReadQualityScope(_ context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
s.scopeCalls++
|
||||
s.tenant = q.Window.TenantKey
|
||||
second := s.record
|
||||
second.ID = "second-turn"
|
||||
keys := []dobotaiops.QualityKey{}
|
||||
for _, r := range []dobotaiops.Record{s.record, second} {
|
||||
e, _ := qaopsquality.EvidenceFor(r)
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.ID, InputHash: e.Hash, Marker: e.Result.Verdict == "uncovered", Source: r.SourceCoverage})
|
||||
}
|
||||
return dobotaiops.QualityScope{Keys: keys, AsOf: time.Now()}, nil
|
||||
}
|
||||
func qualityTestHandler(t *testing.T) (http.Handler, *qualityFake, *qualitySource) {
|
||||
t.Helper()
|
||||
store := &qualityFake{}
|
||||
source := &qualitySource{record: dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例", Answer: "暂无已发布"}}
|
||||
auth := newFakeAuthStore()
|
||||
auth.sessions["quality-admin"] = "usr-boss"
|
||||
auth.sessions["quality-viewer"] = "usr-eye"
|
||||
h, e := NewHandler(Config{Store: &fakeJobStore{}, Auth: &AuthConfig{Store: auth}, QAOps: source, QAOpsTenantKey: "fixed", QAQuality: store, Now: func() time.Time { return time.Date(2026, 10, 17, 0, 0, 0, 0, time.UTC) }})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return h, store, source
|
||||
}
|
||||
func qualityRequest(h http.Handler, method, path, token, body string) *httptest.ResponseRecorder {
|
||||
r := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
r.Header.Set("Content-Type", "application/json")
|
||||
r.Header.Set("X-Governance-Action", "qa-quality")
|
||||
if token != "" {
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: token})
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
return w
|
||||
}
|
||||
func TestQAQualityDetailListAndWholeScopeCounts(t *testing.T) {
|
||||
h, store, source := qualityTestHandler(t)
|
||||
w := qualityRequest(h, "GET", "/api/v1/qa-ops/records/fixture-turn", "quality-admin", "")
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"quality"`) {
|
||||
t.Fatal("persisted quality absent in detail", w.Code)
|
||||
}
|
||||
w = qualityRequest(h, "GET", "/api/v1/qa-ops/records?start=2026-10-14T00:00:00Z&end=2026-10-15T00:00:00Z", "quality-admin", "")
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"is_correct"`) {
|
||||
t.Fatal("whole-filter quality columns absent")
|
||||
}
|
||||
w = qualityRequest(h, "POST", "/api/v1/qa-ops/quality/query", "quality-admin", `{"start":"2026-10-14T00:00:00Z","end":"2026-10-15T00:00:00Z","keyword":""}`)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"unreviewed":2`) || source.scopeCalls != 1 || source.tenant != "fixed" || store.calls < 2 {
|
||||
t.Fatal("quality summary estimated from page instead of scope", w.Code, w.Body.String())
|
||||
}
|
||||
var counts struct {
|
||||
Data struct {
|
||||
Summary qaopsquality.Summary `json:"summary"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(w.Body.Bytes(), &counts) != nil || counts.Data.Summary.Rates.Coverage.Denominator != 2 || counts.Data.Summary.Rates.Coverage.Numerator != 0 || counts.Data.Summary.Rates.Correctness.Percent != nil {
|
||||
t.Fatal("confirmed quality metrics were not computed for the whole scope")
|
||||
}
|
||||
store.fail = true
|
||||
w = qualityRequest(h, "GET", "/api/v1/qa-ops/records/fixture-turn", "quality-admin", "")
|
||||
if w.Code != 503 || !strings.Contains(w.Body.String(), "quality_unavailable") {
|
||||
t.Fatal("quality storage failure presented as empty success")
|
||||
}
|
||||
}
|
||||
func TestQAQualityReviewUsesSessionActorAndStrictReadOnlySourceBoundary(t *testing.T) {
|
||||
h, store, source := qualityTestHandler(t)
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
q := qaopsquality.SaveRequest{InputHash: e.Hash, InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "uncovered", Correctness: "pending"}, Reason: "人工核对"}
|
||||
raw, _ := json.Marshal(q)
|
||||
path := "/api/v1/qa-ops/records/fixture-turn/reviews"
|
||||
w := qualityRequest(h, "POST", path, "quality-admin", string(raw))
|
||||
if w.Code != 200 || store.actor != "boss" || source.tenant != "fixed" {
|
||||
t.Fatal("manual review failed or actor came from request", w.Code, store.actor)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
token, body string
|
||||
status int
|
||||
}{{"", string(raw), 401}, {"quality-viewer", string(raw), 403}, {"quality-admin", strings.TrimSuffix(string(raw), "}") + `,"reviewer":"forged"}`, 400}, {"quality-admin", `null`, 400}, {"quality-admin", string(raw) + `{}`, 400}, {"quality-admin", `{"nonce":"a","nonce":"b"}`, 400}} {
|
||||
w = qualityRequest(h, "POST", path, tc.token, tc.body)
|
||||
if w.Code != tc.status {
|
||||
t.Fatal("review boundary failed", w.Code, tc.status)
|
||||
}
|
||||
}
|
||||
r := httptest.NewRequest("POST", path, strings.NewReader(string(raw)))
|
||||
r.AddCookie(&http.Cookie{Name: sessionCookieName, Value: "quality-admin"})
|
||||
r.Header.Set("X-Governance-Action", "qa-quality")
|
||||
r.Header.Set("Sec-Fetch-Site", "cross-site")
|
||||
w = httptest.NewRecorder()
|
||||
h.ServeHTTP(w, r)
|
||||
if w.Code != 403 {
|
||||
t.Fatal("cross-site review accepted")
|
||||
}
|
||||
w = qualityRequest(h, "GET", path+"/invalid", "quality-admin", "")
|
||||
if w.Code != 404 {
|
||||
t.Fatal("unknown endpoint silently accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQAQualityReviewRejectsMissingRevisionAndNestedNull(t *testing.T) {
|
||||
h, _, source := qualityTestHandler(t)
|
||||
e, _ := qaopsquality.EvidenceFor(source.record)
|
||||
q := qaopsquality.SaveRequest{InputHash: e.Hash, InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "pending", Correctness: "pending"}, Reason: "示例复核"}
|
||||
raw, _ := json.Marshal(q)
|
||||
for _, body := range []string{strings.Replace(string(raw), `"base_revision":0,`, "", 1), strings.Replace(string(raw), `"base_revision":0`, `"base_revision":null`, 1), strings.Replace(string(raw), `"product_category":""`, `"product_category":null`, 1)} {
|
||||
w := qualityRequest(h, "POST", "/api/v1/qa-ops/records/fixture-turn/reviews", "quality-admin", body)
|
||||
if w.Code != 400 {
|
||||
t.Fatal("missing/null version or field silently became a default", w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQAUsageConsumesTheCustomRegionCatalog(t *testing.T) {
|
||||
p, err := qaopsorg.BuildAttribution(qaopsorg.State{State: "ready", DirectoryID: "fixture-directory", Regions: []qaopsorg.RegionDefinition{{ID: "edu", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "edu"}}}, qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "a", Name: "示例部门"}}, People: []qaopsorg.Person{{ID: "fixture-person", DepartmentIDs: []string{"a"}}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
usage := summarizeQAUsage(dobotaiops.UsageGroups{Groups: []dobotaiops.UsageGroup{{Identity: dobotaiops.ActorIdentity{StaffID: "fixture-person"}, Total: 3, Succeeded: 2, Failed: 1}}}, p, dobotaiops.RecordQuery{})
|
||||
if usage.Questions != 3 || usage.IdentifiedUsers != 1 {
|
||||
t.Fatal("the historical whitelist dropped custom-region events")
|
||||
}
|
||||
found := false
|
||||
for _, row := range usage.Rows {
|
||||
if row.Key == "国内教育" {
|
||||
found = true
|
||||
if row.Questions != 3 || row.RosterPeople == nil || *row.RosterPeople != 1 || row.Users == nil || *row.Users != 1 {
|
||||
t.Fatal("custom-region counts or roster denominator were lost")
|
||||
}
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("custom-region row missing")
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import (
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/monitoring"
|
||||
postgresstore "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsmirror"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
)
|
||||
|
||||
@@ -102,6 +103,7 @@ type Store interface {
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
QAQuality QAQualityStore
|
||||
QAOrgSync QAOrgSyncStore
|
||||
QAOrgSyncEnabled bool
|
||||
QAOrg QAOrgStore
|
||||
@@ -175,12 +177,21 @@ func NewHandler(config Config) (http.Handler, error) {
|
||||
config.NewID = newID
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/dashboard", func(w http.ResponseWriter, r *http.Request) { qaOperationsDashboard(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/quality/query", func(w http.ResponseWriter, r *http.Request) { qaQualityQuery(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/records/{id}/reviews", func(w http.ResponseWriter, r *http.Request) { qaQualityReview(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/history", func(w http.ResponseWriter, r *http.Request) { qaQualityHistory(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/records/{id}/quality/inputs/{epoch}", func(w http.ResponseWriter, r *http.Request) { qaQualitySnapshot(w, r, config) })
|
||||
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/usage/people", func(w http.ResponseWriter, r *http.Request) { qaMonthlyPeople(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/usage", func(w http.ResponseWriter, r *http.Request) { qaOpsUsage(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/organization/sync", func(w http.ResponseWriter, r *http.Request) { qaOrganizationSync(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/organization", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/organization/preview", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("PUT /api/v1/qa-ops/organization/regions", func(w http.ResponseWriter, r *http.Request) { qaOrganization(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/sync", func(w http.ResponseWriter, r *http.Request) { qaRecordsSync(w, r, config) })
|
||||
mux.HandleFunc("POST /api/v1/qa-ops/sync", func(w http.ResponseWriter, r *http.Request) { qaRecordsSync(w, r, config) })
|
||||
mux.HandleFunc("GET /api/v1/qa-ops/status", func(w http.ResponseWriter, r *http.Request) {
|
||||
qaOpsStatus(w, r, config)
|
||||
})
|
||||
@@ -562,7 +573,7 @@ func createJob(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid JSON request"})
|
||||
return
|
||||
}
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) {
|
||||
if strings.HasPrefix(input.Type, qaopsorg.SyncJobPrefix) || strings.HasPrefix(input.Type, qaopsmirror.SyncJobPrefix) {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "通讯录同步任务只能从问答运营的管理员入口创建"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -225,10 +225,26 @@ func versionHistorySync(w http.ResponseWriter, r *http.Request, config Config) {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "构造同步任务失败")
|
||||
return
|
||||
}
|
||||
if queue, ok := config.Store.(interface {
|
||||
EnqueueVersionHistorySync(context.Context, string, string, string, time.Time) (*jobs.Job, error)
|
||||
}); ok {
|
||||
target := ""
|
||||
info := version.Snapshot()
|
||||
if info.IdentityAvailable && info.CommitSHA != nil {
|
||||
target = *info.CommitSHA
|
||||
}
|
||||
job, e := queue.EnqueueVersionHistorySync(r.Context(), config.VersionHistoryRepo, triggeredBy, target, now)
|
||||
if e != nil || job == nil {
|
||||
versionHistoryError(w, 500, "version_history_unavailable", "入队同步任务失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, 202, map[string]any{"job_id": job.ID, "status": job.State})
|
||||
return
|
||||
}
|
||||
requestedID := fmt.Sprintf("version-history-sync-%d", now.UnixNano())
|
||||
job, err := config.Store.Enqueue(r.Context(), jobs.EnqueueRequest{ID: requestedID,
|
||||
Type: VersionHistoryJobType, Payload: payload, AvailableAt: now, MaxAttempts: 3,
|
||||
IdempotencyKey: "version-history.sync:" + config.VersionHistoryRepo}, now)
|
||||
IdempotencyKey: "version-history.sync:" + config.VersionHistoryRepo + ":" + requestedID}, now)
|
||||
if err != nil || job == nil {
|
||||
versionHistoryError(w, http.StatusInternalServerError, "version_history_unavailable", "入队同步任务失败")
|
||||
return
|
||||
|
||||
@@ -237,7 +237,7 @@ func TestVersionHistorySyncRequiresAdminAndEnqueuesOnce(t *testing.T) {
|
||||
if recorder.Code != http.StatusAccepted {
|
||||
t.Fatalf("首次同步应 202,得到 %d(%s)", recorder.Code, recorder.Body.String())
|
||||
}
|
||||
if queue.enqueued.Type != VersionHistoryJobType || queue.enqueued.IdempotencyKey != "version-history.sync:Weknora/knowledge-governance" {
|
||||
if queue.enqueued.Type != VersionHistoryJobType || queue.enqueued.IdempotencyKey != "version-history.sync:Weknora/knowledge-governance:"+queue.enqueued.ID {
|
||||
t.Fatalf("入队参数不对:%+v", queue.enqueued)
|
||||
}
|
||||
if queue.enqueued.MaxAttempts != 3 || queue.enqueued.AvailableAt != now {
|
||||
|
||||
@@ -0,0 +1,4 @@
|
||||
DROP TABLE qa_ops_quality_reviews;
|
||||
DROP TABLE qa_ops_quality_checks;
|
||||
DROP TABLE qa_ops_quality_inputs;
|
||||
DROP TABLE qa_ops_quality_records;
|
||||
@@ -0,0 +1,13 @@
|
||||
CREATE TABLE qa_ops_quality_records (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,observed_at TIMESTAMPTZ,input_hash TEXT NOT NULL DEFAULT '',input_epoch BIGINT NOT NULL DEFAULT 0 CHECK(input_epoch>=0),review_revision BIGINT NOT NULL DEFAULT 0 CHECK(review_revision>=0),PRIMARY KEY(tenant_key,record_id)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_inputs (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,input_epoch BIGINT NOT NULL CHECK(input_epoch>0),input_hash TEXT NOT NULL CHECK(input_hash ~ '^[a-f0-9]{64}$'),payload JSONB CHECK(payload IS NULL OR jsonb_typeof(payload)='object'),created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,record_id,input_epoch),FOREIGN KEY(tenant_key,record_id) REFERENCES qa_ops_quality_records(tenant_key,record_id)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_checks (
|
||||
id BIGSERIAL PRIMARY KEY,tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,input_epoch BIGINT NOT NULL,rule_version TEXT NOT NULL,result JSONB NOT NULL CHECK(jsonb_typeof(result)='object'),source JSONB NOT NULL CHECK(jsonb_typeof(source)='object'),created_at TIMESTAMPTZ NOT NULL DEFAULT now(),UNIQUE(tenant_key,record_id,input_epoch,rule_version),FOREIGN KEY(tenant_key,record_id,input_epoch) REFERENCES qa_ops_quality_inputs(tenant_key,record_id,input_epoch)
|
||||
);
|
||||
CREATE TABLE qa_ops_quality_reviews (
|
||||
tenant_key TEXT NOT NULL,record_id TEXT NOT NULL,revision BIGINT NOT NULL CHECK(revision>0),input_epoch BIGINT NOT NULL,input_hash TEXT NOT NULL CHECK(input_hash ~ '^[a-f0-9]{64}$'),fields JSONB NOT NULL CHECK(jsonb_typeof(fields)='object'),reason TEXT NOT NULL CHECK(length(btrim(reason))>0),reviewer TEXT NOT NULL CHECK(length(btrim(reviewer))>0),nonce TEXT NOT NULL,request_hash TEXT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY(tenant_key,record_id,revision),UNIQUE(tenant_key,record_id,nonce),FOREIGN KEY(tenant_key,record_id,input_epoch) REFERENCES qa_ops_quality_inputs(tenant_key,record_id,input_epoch)
|
||||
);
|
||||
CREATE INDEX idx_qa_quality_checks_history ON qa_ops_quality_checks(tenant_key,record_id,id DESC);
|
||||
@@ -0,0 +1,2 @@
|
||||
DROP TABLE qa_ops_mirror_records;
|
||||
DROP TABLE qa_ops_mirror_state;
|
||||
@@ -0,0 +1,14 @@
|
||||
CREATE TABLE qa_ops_mirror_state (
|
||||
tenant_key TEXT PRIMARY KEY CHECK(length(tenant_key) BETWEEN 1 AND 128),
|
||||
ready BOOLEAN NOT NULL DEFAULT false, blocked BOOLEAN NOT NULL DEFAULT false,
|
||||
revision BIGINT NOT NULL DEFAULT 0 CHECK(revision>=0), record_count BIGINT NOT NULL DEFAULT 0 CHECK(record_count>=0),
|
||||
source_observed_at TIMESTAMPTZ, synced_at TIMESTAMPTZ, next_sync_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
last_error TEXT NOT NULL DEFAULT '', source_safety JSONB NOT NULL DEFAULT '{}'::jsonb
|
||||
);
|
||||
CREATE TABLE qa_ops_mirror_records (
|
||||
tenant_key TEXT NOT NULL REFERENCES qa_ops_mirror_state(tenant_key), id TEXT NOT NULL,
|
||||
fingerprint TEXT NOT NULL CHECK(fingerprint ~ '^[a-f0-9]{64}$'), asked_at TIMESTAMPTZ NOT NULL,
|
||||
question TEXT NOT NULL, status TEXT NOT NULL, identity JSONB NOT NULL, quality_hash TEXT NOT NULL CHECK(quality_hash ~ '^[a-f0-9]{64}$'),
|
||||
payload JSONB NOT NULL CHECK(jsonb_typeof(payload)='object'), PRIMARY KEY(tenant_key,id)
|
||||
);
|
||||
CREATE INDEX idx_qa_mirror_records_window ON qa_ops_mirror_records(tenant_key,asked_at DESC,id DESC);
|
||||
@@ -0,0 +1,6 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS (SELECT 1 FROM qa_ops_region_revisions WHERE region_definitions <> '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb) THEN
|
||||
RAISE EXCEPTION 'custom region catalog exists; application rollback may keep migration 51, destructive catalog rollback refused';
|
||||
END IF;
|
||||
END $$;
|
||||
ALTER TABLE qa_ops_region_revisions DROP COLUMN region_definitions;
|
||||
@@ -0,0 +1 @@
|
||||
ALTER TABLE qa_ops_region_revisions ADD COLUMN region_definitions JSONB NOT NULL DEFAULT '[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]'::jsonb CHECK (jsonb_typeof(region_definitions)='array');
|
||||
@@ -0,0 +1,10 @@
|
||||
DO $$ BEGIN
|
||||
IF EXISTS(SELECT 1 FROM qa_ops_weekly_quality_snapshots) THEN
|
||||
RAISE EXCEPTION 'frozen weekly quality history exists; keep additive schema during application rollback';
|
||||
END IF;
|
||||
END $$;
|
||||
DROP TABLE qa_ops_weekly_quality_snapshot_records;
|
||||
DROP TABLE qa_ops_weekly_quality_snapshots;
|
||||
DROP TABLE qa_ops_weekly_quality_tracking;
|
||||
DROP FUNCTION qa_ops_require_new_weekly_quality_header();
|
||||
DROP FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
@@ -0,0 +1,50 @@
|
||||
CREATE TABLE qa_ops_weekly_quality_tracking (
|
||||
tenant_key TEXT PRIMARY KEY CHECK(length(tenant_key) BETWEEN 1 AND 128),
|
||||
started_at TIMESTAMPTZ NOT NULL, first_data_at TIMESTAMPTZ
|
||||
);
|
||||
CREATE TABLE qa_ops_weekly_quality_snapshots (
|
||||
tenant_key TEXT NOT NULL, week_start TIMESTAMPTZ NOT NULL, week_end TIMESTAMPTZ NOT NULL,
|
||||
frozen_at TIMESTAMPTZ NOT NULL, mirror_revision BIGINT NOT NULL CHECK(mirror_revision>=0),
|
||||
source_observed_at TIMESTAMPTZ NOT NULL, policy_version TEXT NOT NULL,
|
||||
record_count INTEGER NOT NULL CHECK(record_count>=0),
|
||||
coverage_numerator INTEGER NOT NULL CHECK(coverage_numerator>=0), coverage_denominator INTEGER NOT NULL CHECK(coverage_denominator>=coverage_numerator),
|
||||
correctness_numerator INTEGER NOT NULL CHECK(correctness_numerator>=0), correctness_denominator INTEGER NOT NULL CHECK(correctness_denominator>=correctness_numerator),
|
||||
PRIMARY KEY(tenant_key,week_start), CHECK(week_end=week_start+interval '7 days'),
|
||||
CHECK(date_trunc('day',week_start AT TIME ZONE 'Asia/Shanghai')=week_start AT TIME ZONE 'Asia/Shanghai'),
|
||||
CHECK(EXTRACT(ISODOW FROM week_start AT TIME ZONE 'Asia/Shanghai')=1),
|
||||
CHECK(frozen_at>=week_end), CHECK(source_observed_at>=week_end AND source_observed_at<=frozen_at),
|
||||
CHECK(coverage_denominator<=record_count AND correctness_denominator<=record_count)
|
||||
);
|
||||
-- Frozen scalar contributions preserve the original formula under future policy
|
||||
-- changes and allow literal keyword filtering without recalculating old reviews.
|
||||
-- No answers, staff IDs, names or organization memberships are duplicated here.
|
||||
CREATE TABLE qa_ops_weekly_quality_snapshot_records (
|
||||
tenant_key TEXT NOT NULL, week_start TIMESTAMPTZ NOT NULL, record_id TEXT NOT NULL,
|
||||
question TEXT NOT NULL,
|
||||
coverage_numerator SMALLINT NOT NULL CHECK(coverage_numerator BETWEEN 0 AND 1),
|
||||
coverage_denominator SMALLINT NOT NULL CHECK(coverage_denominator BETWEEN coverage_numerator AND 1),
|
||||
correctness_numerator SMALLINT NOT NULL CHECK(correctness_numerator BETWEEN 0 AND 1),
|
||||
correctness_denominator SMALLINT NOT NULL CHECK(correctness_denominator BETWEEN correctness_numerator AND 1),
|
||||
PRIMARY KEY(tenant_key,week_start,record_id),
|
||||
FOREIGN KEY(tenant_key,week_start) REFERENCES qa_ops_weekly_quality_snapshots(tenant_key,week_start) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE FUNCTION qa_ops_reject_frozen_quality_mutation() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'committed weekly quality snapshots are immutable' USING ERRCODE='55000';
|
||||
END $$;
|
||||
CREATE TRIGGER immutable_weekly_quality_header BEFORE UPDATE OR DELETE ON qa_ops_weekly_quality_snapshots FOR EACH ROW EXECUTE FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
CREATE TRIGGER immutable_weekly_quality_records BEFORE UPDATE OR DELETE ON qa_ops_weekly_quality_snapshot_records FOR EACH ROW EXECUTE FUNCTION qa_ops_reject_frozen_quality_mutation();
|
||||
|
||||
-- Contributions may only be inserted in the SAME transaction as their header.
|
||||
-- This rejects a later append while allowing the initial atomic CopyFrom batch.
|
||||
CREATE FUNCTION qa_ops_require_new_weekly_quality_header() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
DECLARE parent_xid bigint;
|
||||
BEGIN
|
||||
SELECT xmin::text::bigint INTO parent_xid FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=NEW.tenant_key AND week_start=NEW.week_start;
|
||||
IF parent_xid IS NULL OR parent_xid <> mod(pg_current_xact_id()::text::numeric,4294967296)::bigint THEN
|
||||
RAISE EXCEPTION 'cannot append to a committed weekly quality snapshot' USING ERRCODE='55000';
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
CREATE TRIGGER append_only_new_weekly_quality BEFORE INSERT ON qa_ops_weekly_quality_snapshot_records FOR EACH ROW EXECUTE FUNCTION qa_ops_require_new_weekly_quality_header();
|
||||
@@ -11,8 +11,8 @@ func TestEmbeddedMigrationsAreVersionSorted(t *testing.T) {
|
||||
if err != nil {
|
||||
t.Fatalf("loadMigrations() error = %v", err)
|
||||
}
|
||||
if len(migrations) != 48 {
|
||||
t.Fatalf("migration count = %d, want 48", len(migrations))
|
||||
if len(migrations) != 52 {
|
||||
t.Fatalf("migration count = %d, want 52", len(migrations))
|
||||
}
|
||||
if migrations[0].Version != 1 || !strings.Contains(migrations[0].UpSQL, "CREATE TABLE IF NOT EXISTS jobs") {
|
||||
t.Fatalf("migration 1 = %#v", migrations[0])
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRegionCatalogMigrationIsAdditiveAndRefusesLossyDown(t *testing.T) {
|
||||
migrations, e := loadMigrations()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var up, down string
|
||||
for _, m := range migrations {
|
||||
if m.Version == 51 {
|
||||
up = m.UpSQL
|
||||
down = m.DownSQL
|
||||
}
|
||||
}
|
||||
for _, fragment := range []string{"ADD COLUMN region_definitions JSONB NOT NULL DEFAULT", "jsonb_typeof(region_definitions)='array'", "国内工业", "APAC", "EMEA", "America"} {
|
||||
if !strings.Contains(up, fragment) {
|
||||
t.Fatal("missing additive/backfill region contract", fragment)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(down, "RAISE EXCEPTION") || !strings.Contains(down, "region_definitions <>") || !strings.Contains(down, "DROP COLUMN region_definitions") {
|
||||
t.Fatal("lossy down migration was not guarded")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWeeklyQualityMigrationPreservesFrozenHistory(t *testing.T) {
|
||||
migrations, e := loadMigrations()
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var up, down string
|
||||
for _, m := range migrations {
|
||||
if m.Version == 52 {
|
||||
up = m.UpSQL
|
||||
down = m.DownSQL
|
||||
}
|
||||
}
|
||||
for _, part := range []string{"CREATE TABLE qa_ops_weekly_quality_tracking", "first_data_at TIMESTAMPTZ", "CREATE TABLE qa_ops_weekly_quality_snapshots", "CREATE TABLE qa_ops_weekly_quality_snapshot_records", "AT TIME ZONE 'Asia/Shanghai'", "BEFORE UPDATE OR DELETE", "BEFORE INSERT", "pg_current_xact_id()", "coverage_denominator<=record_count"} {
|
||||
if !strings.Contains(up, part) {
|
||||
t.Fatal("missing frozen weekly quality contract", part)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(down, "IF EXISTS(SELECT 1 FROM qa_ops_weekly_quality_snapshots)") || !strings.Contains(down, "RAISE EXCEPTION") || !strings.Contains(down, "DROP FUNCTION qa_ops_require_new_weekly_quality_header()") {
|
||||
t.Fatal("lossy history rollback or stale trigger functions")
|
||||
}
|
||||
for _, forbidden := range []string{"ALTER TABLE qa_ops_mirror_records", "UPDATE qa_ops_quality_reviews", "answer TEXT", "staff_id TEXT"} {
|
||||
if strings.Contains(up, forbidden) {
|
||||
t.Fatal("snapshot migration widened into original records or employee identity")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) EnqueueVersionHistorySync(ctx context.Context, repo, actor, target string, now time.Time) (*jobs.Job, error) {
|
||||
if strings.Count(repo, "/") != 1 || strings.TrimSpace(repo) != repo || len(repo) > 200 || actor == "" || len(actor) > 256 || target != "" && !regexp.MustCompile(`^[a-f0-9]{40}$`).MatchString(target) {
|
||||
return nil, errors.New("invalid version synchronization request")
|
||||
}
|
||||
tx, e := s.db.Begin(ctx)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if _, e = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, "version-history:"+repo); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
// Retire exhausted expired owners. Terminal jobs are history, not a perpetual
|
||||
// idempotency key: a later refresh must be allowed to execute again.
|
||||
if _, e = tx.Exec(ctx, `UPDATE jobs SET state='failed',lease_owner=NULL,lease_until=NULL,updated_at=$3 WHERE type=$1 AND payload->>'repo_key'=$2 AND state='running' AND lease_until<clock_timestamp() AND attempt>=max_attempts`, versionhistory.JobType, repo, now); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
var active string
|
||||
e = tx.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND payload->>'repo_key'=$2 AND state IN ('pending','running','retry') ORDER BY created_at DESC,id DESC LIMIT 1`, versionhistory.JobType, repo).Scan(&active)
|
||||
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
|
||||
return nil, e
|
||||
}
|
||||
if active != "" {
|
||||
job, e := scanJob(tx.QueryRow(ctx, `SELECT id,type,payload,state,priority,available_at,lease_owner,lease_until,attempt,max_attempts,last_error,idempotency_key,created_at,updated_at FROM jobs WHERE id=$1`, active))
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
var random [16]byte
|
||||
if _, e = rand.Read(random[:]); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
id := "vh-" + hex.EncodeToString(random[:])
|
||||
payload, _ := json.Marshal(map[string]string{"repo_key": repo, "triggered_by": actor, "target_sha": target})
|
||||
job, e := NewStore(tx).Enqueue(ctx, jobs.EnqueueRequest{ID: id, Type: versionhistory.JobType, Payload: payload, AvailableAt: now, MaxAttempts: 3, IdempotencyKey: "version-history:" + repo + ":" + id}, now)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if e = tx.Commit(ctx); e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return job, nil
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/versionhistory"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestVersionHistorySyncQueueCanRefreshAfterCompletion(t *testing.T) {
|
||||
dsn := os.Getenv("KG_VERSION_HISTORY_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit disposable version-history DB required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_version_history_test_") {
|
||||
t.Fatal("refusing shared database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
p, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer p.Close()
|
||||
if e = ApplyMigrations(ctx, p); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
s := NewStore(p)
|
||||
one, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("a", 40), time.Now())
|
||||
if e != nil || one == nil {
|
||||
t.Fatal("first sync missing", e)
|
||||
}
|
||||
same, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("a", 40), time.Now())
|
||||
if e != nil || same.ID != one.ID {
|
||||
t.Fatal("pending sync not coalesced", e)
|
||||
}
|
||||
claimed, e := s.Claim(ctx, "fixture-worker", []string{versionhistory.JobType}, time.Now(), time.Minute)
|
||||
if e != nil || claimed == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = s.Complete(ctx, claimed.ID, claimed.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next, e := s.EnqueueVersionHistorySync(ctx, "fixture/repo", "fixture-admin", strings.Repeat("b", 40), time.Now())
|
||||
if e != nil || next == nil || next.ID == one.ID || next.State != "pending" {
|
||||
t.Fatal("completed request was replayed forever instead of starting a new refresh", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"time"
|
||||
)
|
||||
|
||||
type DashboardCount struct {
|
||||
Label string `json:"label"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
type DashboardDaily struct {
|
||||
Date string `json:"date"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
type DashboardFrozen struct {
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
WeekEnd time.Time `json:"week_end"`
|
||||
FrozenAt *time.Time `json:"frozen_at"`
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
Records int `json:"records"`
|
||||
Coverage qaopsquality.Rate `json:"coverage"`
|
||||
Correctness qaopsquality.Rate `json:"correctness"`
|
||||
}
|
||||
type DashboardRegion struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Questions int `json:"questions"`
|
||||
Users *int `json:"users"`
|
||||
RosterPeople *int `json:"roster_people"`
|
||||
Frequency *float64 `json:"frequency"`
|
||||
UsageCoverage qaopsquality.Rate `json:"usage_coverage"`
|
||||
}
|
||||
type Dashboard struct {
|
||||
Start time.Time `json:"start"`
|
||||
End time.Time `json:"end"`
|
||||
Keyword string `json:"keyword"`
|
||||
AsOf time.Time `json:"as_of"`
|
||||
LocalRevision int64 `json:"local_revision"`
|
||||
Organization dobotaiops.OrganizationVersion `json:"organization"`
|
||||
TotalIssues int `json:"total_issues"`
|
||||
NewThisWeek int `json:"new_this_week"`
|
||||
WeekStart time.Time `json:"week_start"`
|
||||
MonthStart time.Time `json:"month_start"`
|
||||
Quality qaopsquality.Summary `json:"quality"`
|
||||
IssueTypes []DashboardCount `json:"issue_types"`
|
||||
Products []DashboardCount `json:"products"`
|
||||
Daily []DashboardDaily `json:"daily"`
|
||||
Regions []DashboardRegion `json:"regions"`
|
||||
FrozenWeeks []DashboardFrozen `json:"frozen_weeks"`
|
||||
}
|
||||
|
||||
var dashboardLocation = time.FixedZone("Asia/Shanghai", 8*60*60)
|
||||
|
||||
func dashboardDay(at time.Time) time.Time {
|
||||
t := at.In(dashboardLocation)
|
||||
return time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, dashboardLocation)
|
||||
}
|
||||
func dashboardWeek(at time.Time) time.Time {
|
||||
d := dashboardDay(at)
|
||||
return d.AddDate(0, 0, -((int(d.Weekday()) + 6) % 7))
|
||||
}
|
||||
func dashboardPeriods(end time.Time) (time.Time, time.Time) {
|
||||
cutoff := end.Add(-time.Nanosecond).In(dashboardLocation)
|
||||
return time.Date(cutoff.Year(), cutoff.Month(), 1, 0, 0, 0, 0, dashboardLocation), dashboardWeek(cutoff)
|
||||
}
|
||||
func dashboardFrozenSeries(first, end time.Time, snapshots map[string]DashboardFrozen) []DashboardFrozen {
|
||||
out := []DashboardFrozen{}
|
||||
if first.IsZero() || !first.Before(end) {
|
||||
return out
|
||||
}
|
||||
for at := dashboardWeek(first); at.Before(end) && len(out) < 5200; at = at.AddDate(0, 0, 7) {
|
||||
key := at.Format("2006-01-02")
|
||||
point, ok := snapshots[key]
|
||||
if !ok {
|
||||
point = DashboardFrozen{WeekStart: at, WeekEnd: at.AddDate(0, 0, 7)}
|
||||
}
|
||||
out = append(out, point)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) TrackQualityWeeks(ctx context.Context, at time.Time) error {
|
||||
if !s.valid() || at.IsZero() {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
_, e := s.pool.Exec(ctx, `INSERT INTO qa_ops_weekly_quality_tracking(tenant_key,started_at,first_data_at) VALUES($1,$2,(SELECT min(asked_at) FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at<=$2)) ON CONFLICT(tenant_key) DO UPDATE SET first_data_at=LEAST(qa_ops_weekly_quality_tracking.first_data_at,EXCLUDED.first_data_at) WHERE EXCLUDED.first_data_at IS NOT NULL AND (qa_ops_weekly_quality_tracking.first_data_at IS NULL OR EXCLUDED.first_data_at<qa_ops_weekly_quality_tracking.first_data_at)`, s.tenant, at)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Capture only during the following Monday, after a complete post-boundary
|
||||
// source observation. A missed capture remains a gap, never retrospective data.
|
||||
// Scheduling is local worker-owned; browser reads never freeze or write metrics.
|
||||
func (s *Store) FreezePreviousQualityWeek(ctx context.Context, at time.Time) (bool, error) {
|
||||
if !s.valid() || at.IsZero() {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if at.In(dashboardLocation).Weekday() != time.Monday {
|
||||
return false, nil
|
||||
}
|
||||
end := dashboardWeek(at)
|
||||
start := end.AddDate(0, 0, -7)
|
||||
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
tx, e := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead})
|
||||
if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
var locked bool
|
||||
if tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,17))`, s.tenant+":qa-quality-freeze:"+start.Format("2006-01-02")).Scan(&locked) != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !locked {
|
||||
return false, nil
|
||||
}
|
||||
var tracked time.Time
|
||||
if e = tx.QueryRow(ctx, `SELECT started_at FROM qa_ops_weekly_quality_tracking WHERE tenant_key=$1`, s.tenant).Scan(&tracked); e == pgx.ErrNoRows {
|
||||
return false, nil
|
||||
} else if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !tracked.Before(end) {
|
||||
return false, nil
|
||||
}
|
||||
var exists bool
|
||||
if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=$1 AND week_start=$2)`, s.tenant, start).Scan(&exists) != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if exists {
|
||||
return false, nil
|
||||
}
|
||||
state, e := s.readState(ctx, txQuery{tx})
|
||||
if e != nil {
|
||||
return false, e
|
||||
}
|
||||
if state.Blocked || !state.Ready || state.SourceObservedAt == nil || state.LastSuccessAt == nil || state.SourceObservedAt.Before(end) || state.SourceObservedAt.After(at) || state.LastSuccessAt.Before(end) || state.LastSuccessAt.After(at) {
|
||||
return false, nil
|
||||
}
|
||||
rows, e := tx.Query(ctx, `SELECT id,question,quality_hash FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 ORDER BY id LIMIT 100001`, s.tenant, start, end)
|
||||
if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
type frozenRecord struct {
|
||||
id, question, hash string
|
||||
coverage, correctness qaopsquality.Rate
|
||||
}
|
||||
records := []frozenRecord{}
|
||||
keys := []dobotaiops.QualityKey{}
|
||||
for rows.Next() {
|
||||
var r frozenRecord
|
||||
if rows.Scan(&r.id, &r.question, &r.hash) != nil {
|
||||
rows.Close()
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
records = append(records, r)
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.id, InputHash: r.hash})
|
||||
if len(records) > dobotaiops.MaxMirrorRecords {
|
||||
rows.Close()
|
||||
return false, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
views := map[string]qaopsquality.View{}
|
||||
quality := qaopsquality.NewStore(s.pool, s.tenant)
|
||||
for begin := 0; begin < len(keys); begin += 5000 {
|
||||
stop := begin + 5000
|
||||
if stop > len(keys) {
|
||||
stop = len(keys)
|
||||
}
|
||||
batch, err := quality.ReadViewsInTx(ctx, tx, keys[begin:stop])
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for id, v := range batch {
|
||||
views[id] = v
|
||||
}
|
||||
}
|
||||
rates := qaopsquality.ComputeRates(views)
|
||||
for i := range records {
|
||||
r := &records[i]
|
||||
v, ok := views[r.id]
|
||||
if !ok {
|
||||
return false, qaopsquality.ErrUnavailable
|
||||
}
|
||||
if v.Automatic.CreatedAt.After(at) || (v.LatestReview != nil && v.LatestReview.CreatedAt.After(at)) {
|
||||
return false, qaopsquality.ErrConflict
|
||||
}
|
||||
one := qaopsquality.ComputeRates(map[string]qaopsquality.View{r.id: v})
|
||||
r.coverage = one.Coverage
|
||||
r.correctness = one.Correctness
|
||||
}
|
||||
tag, e := tx.Exec(ctx, `INSERT INTO qa_ops_weekly_quality_snapshots(tenant_key,week_start,week_end,frozen_at,mirror_revision,source_observed_at,policy_version,record_count,coverage_numerator,coverage_denominator,correctness_numerator,correctness_denominator) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12) ON CONFLICT(tenant_key,week_start) DO NOTHING`, s.tenant, start, end, at, state.Revision, *state.SourceObservedAt, rates.PolicyVersion, len(records), rates.Coverage.Numerator, rates.Coverage.Denominator, rates.Correctness.Numerator, rates.Correctness.Denominator)
|
||||
if e != nil || tag.RowsAffected() != 1 {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
count, e := tx.CopyFrom(ctx, pgx.Identifier{"qa_ops_weekly_quality_snapshot_records"}, []string{"tenant_key", "week_start", "record_id", "question", "coverage_numerator", "coverage_denominator", "correctness_numerator", "correctness_denominator"}, pgx.CopyFromSlice(len(records), func(i int) ([]any, error) {
|
||||
r := records[i]
|
||||
return []any{s.tenant, start, r.id, r.question, r.coverage.Numerator, r.coverage.Denominator, r.correctness.Numerator, r.correctness.Denominator}, nil
|
||||
}))
|
||||
if e != nil || count != int64(len(records)) {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var verified int
|
||||
if tx.QueryRow(ctx, `SELECT count(*) FROM qa_ops_weekly_quality_snapshot_records WHERE tenant_key=$1 AND week_start=$2`, s.tenant, start).Scan(&verified) != nil || verified != len(records) {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) readFrozenDashboard(ctx context.Context, tx pgx.Tx, keyword string, end time.Time) (map[string]DashboardFrozen, error) {
|
||||
rows, e := tx.Query(ctx, `SELECT h.week_start,h.week_end,h.frozen_at,h.policy_version,h.record_count,count(r.record_id),count(r.record_id) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),COALESCE(sum(r.coverage_numerator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0),COALESCE(sum(r.coverage_denominator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0),COALESCE(sum(r.correctness_numerator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0),COALESCE(sum(r.correctness_denominator) FILTER(WHERE $2='' OR position(lower($2) IN lower(r.question))>0),0) FROM qa_ops_weekly_quality_snapshots h LEFT JOIN qa_ops_weekly_quality_snapshot_records r ON r.tenant_key=h.tenant_key AND r.week_start=h.week_start WHERE h.tenant_key=$1 AND h.week_start<$3 GROUP BY h.week_start,h.week_end,h.frozen_at,h.policy_version,h.record_count ORDER BY h.week_start`, s.tenant, keyword, end)
|
||||
if e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]DashboardFrozen{}
|
||||
for rows.Next() {
|
||||
var p DashboardFrozen
|
||||
var total, actual, cn, cd, an, ad int
|
||||
if rows.Scan(&p.WeekStart, &p.WeekEnd, &p.FrozenAt, &p.PolicyVersion, &total, &actual, &p.Records, &cn, &cd, &an, &ad) != nil || actual != total || cn > cd || an > ad || cd > p.Records || ad > p.Records {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
p.Coverage = dashboardRate(cn, cd)
|
||||
p.Correctness = dashboardRate(an, ad)
|
||||
out[p.WeekStart.In(dashboardLocation).Format("2006-01-02")] = p
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDashboardUsesLifetimeWeekMonthAndDeduplicatedRegionalRoster(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-dashboard")
|
||||
queue := pg.NewStore(p)
|
||||
dates := []string{"2026-09-28T08:00:00+08:00", "2026-10-02T08:00:00+08:00", "2026-10-06T08:00:00+08:00", "2026-10-10T08:00:00+08:00"}
|
||||
source := &fixtureSource{}
|
||||
for i, date := range dates {
|
||||
entry := fixtureEntry([]string{"older", "month", "covered", "uncovered"}[i], "暂无已发布")
|
||||
var wire map[string]any
|
||||
_ = json.Unmarshal(entry.Payload, &wire)
|
||||
wire["asked_at"] = date
|
||||
wire["question"] = "needle 100%_ fixture"
|
||||
entry.Payload, _ = json.Marshal(wire)
|
||||
source.rows = append(source.rows, entry)
|
||||
}
|
||||
job := claimMirrorJob(t, s, queue, "dashboard-seed")
|
||||
if e := s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
org := qaopsorg.NewStore(p, s.tenant)
|
||||
state, e := org.ReplaceDirectory(ctx, qaopsorg.Import{Source: "weekly_report_snapshot", SyncedAt: time.Date(2026, 10, 10, 0, 0, 0, 0, time.UTC), Complete: true, Directory: qaopsorg.Directory{Departments: []qaopsorg.Department{{ID: "root", Name: "示例组织"}}, People: []qaopsorg.Person{{ID: "s", DepartmentIDs: []string{"root"}}, {ID: "zero-use", DepartmentIDs: []string{"root"}}}}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = org.SaveRules(ctx, qaopsorg.SaveRequest{DirectoryID: state.DirectoryID, Regions: []qaopsorg.RegionDefinition{{ID: "education", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "root", Region: "education"}}}, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
record, e := s.GetRecord(ctx, s.tenant, "covered")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
quality := qaopsquality.NewStore(p, s.tenant)
|
||||
views, e := quality.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views[record.ID]
|
||||
_, e = quality.Save(ctx, record, qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: strings.Repeat("d", 32), Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "CR", ProblemType: "使用咨询"}, Reason: "explicit isolated test review"}, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
start, _ := time.Parse(time.RFC3339, "2026-10-05T00:00:00+08:00")
|
||||
end := start.AddDate(0, 0, 7)
|
||||
data, e := s.ReadDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, Keyword: "100%_"})
|
||||
if e != nil {
|
||||
t.Fatal("dashboard must read one local snapshot without a source client", e)
|
||||
}
|
||||
if data.TotalIssues != 4 || data.NewThisWeek != 2 || data.Quality.Total != 2 || data.Quality.Rates.Coverage.Numerator != 1 || data.Quality.Rates.Coverage.Denominator != 2 {
|
||||
t.Fatal("lifetime/selected-week quality were mixed")
|
||||
}
|
||||
if len(data.Daily) != 7 || len(data.Regions) != 1 {
|
||||
t.Fatal("daily range or custom region catalog missing")
|
||||
}
|
||||
r := data.Regions[0]
|
||||
if r.Questions != 3 || r.Users == nil || *r.Users != 1 || r.RosterPeople == nil || *r.RosterPeople != 2 || r.Frequency == nil || *r.Frequency != 1.5 || r.UsageCoverage.Percent == nil || *r.UsageCoverage.Percent != 50 {
|
||||
t.Fatal("monthly regional scope or full-roster denominator was replaced by active users")
|
||||
}
|
||||
if len(data.FrozenWeeks) != 2 {
|
||||
t.Fatal("historical weeks did not start at first data week")
|
||||
}
|
||||
for _, point := range data.FrozenWeeks {
|
||||
if point.FrozenAt != nil || point.Coverage.Percent != nil || point.Correctness.Percent != nil {
|
||||
t.Fatal("current quality was backfilled into absent frozen history")
|
||||
}
|
||||
}
|
||||
|
||||
t.Run("historical quality is frozen once and never backfilled", func(t *testing.T) {
|
||||
tracked := start.AddDate(0, 0, 2)
|
||||
if e := s.TrackQualityWeeks(ctx, tracked); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
freezeAt := end.Add(6 * time.Minute)
|
||||
// Explicit fake-clock fixture: the source snapshot and review existed before the closing capture.
|
||||
if _, e = p.Exec(ctx, "UPDATE qa_ops_mirror_state SET source_observed_at=$2,synced_at=$2 WHERE tenant_key=$1", s.tenant, freezeAt.Add(-time.Minute)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, "UPDATE qa_ops_quality_reviews SET created_at=$2 WHERE tenant_key=$1", s.tenant, end.Add(-time.Hour)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, "UPDATE qa_ops_quality_checks SET created_at=$2 WHERE tenant_key=$1", s.tenant, end.Add(-time.Hour)); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
frozen, e := s.FreezePreviousQualityWeek(ctx, freezeAt)
|
||||
if e != nil || !frozen {
|
||||
t.Fatal("first eligible Monday capture was not frozen", e)
|
||||
}
|
||||
for _, statement := range []string{
|
||||
`UPDATE qa_ops_weekly_quality_snapshots SET policy_version=policy_version||'-changed' WHERE tenant_key=$1`,
|
||||
`UPDATE qa_ops_weekly_quality_snapshot_records SET question=question||' changed' WHERE tenant_key=$1`,
|
||||
`DELETE FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=$1`,
|
||||
`DELETE FROM qa_ops_weekly_quality_snapshot_records WHERE tenant_key=$1`,
|
||||
`INSERT INTO qa_ops_weekly_quality_snapshot_records SELECT tenant_key,week_start,record_id||'-late',question,coverage_numerator,coverage_denominator,correctness_numerator,correctness_denominator FROM qa_ops_weekly_quality_snapshot_records WHERE tenant_key=$1 LIMIT 1`,
|
||||
} {
|
||||
mutation, err := p.Begin(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = mutation.Exec(ctx, statement, s.tenant)
|
||||
_ = mutation.Rollback(ctx)
|
||||
var dbError *pgconn.PgError
|
||||
if !errors.As(err, &dbError) || dbError.Code != "55000" {
|
||||
t.Fatal("committed snapshot mutation was not rejected by the immutable guard", err)
|
||||
}
|
||||
}
|
||||
historical, e := s.ReadDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, Keyword: "100%_"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
last := historical.FrozenWeeks[len(historical.FrozenWeeks)-1]
|
||||
if last.FrozenAt == nil || last.Coverage.Percent == nil || *last.Coverage.Percent != 50 || last.Correctness.Percent == nil || *last.Correctness.Percent != 100 {
|
||||
t.Fatal("frozen ratios or literal keyword projection were lost")
|
||||
}
|
||||
latest, e := quality.ReadViews(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: v.InputHash}})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
current := latest[record.ID]
|
||||
if _, e = quality.Save(ctx, record, qaopsquality.SaveRequest{InputHash: current.InputHash, InputEpoch: current.InputEpoch, BaseRevision: current.Revision, Nonce: strings.Repeat("e", 32), Fields: qaopsquality.Fields{Coverage: "uncovered", Correctness: "incorrect"}, Reason: "later isolated correction, must not rewrite frozen history"}, "fixture-admin"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
repeated, e := s.FreezePreviousQualityWeek(ctx, freezeAt.Add(time.Minute))
|
||||
if e != nil || repeated {
|
||||
t.Fatal("immutable weekly snapshot was replaced")
|
||||
}
|
||||
changed, e := s.ReadDashboard(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: start, End: end}, Keyword: "100%_"})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
point := changed.FrozenWeeks[len(changed.FrozenWeeks)-1]
|
||||
if changed.Quality.Rates.Coverage.Numerator != 0 || point.Coverage.Percent == nil || *point.Coverage.Percent != 50 || changed.FrozenWeeks[0].FrozenAt != nil {
|
||||
t.Fatal("current correction rewrote frozen history or backfilled pre-tracking weeks")
|
||||
}
|
||||
})
|
||||
raw, _ := json.Marshal(data)
|
||||
if strings.Contains(string(raw), "zero-use") || strings.Contains(string(raw), "needle") {
|
||||
t.Fatal("dashboard leaked identity or original question rows")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsorg"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
type dashboardRecord struct {
|
||||
id, hash string
|
||||
at time.Time
|
||||
identity dobotaiops.ActorIdentity
|
||||
}
|
||||
|
||||
func dashboardRate(n, d int) qaopsquality.Rate {
|
||||
r := qaopsquality.Rate{Numerator: n, Denominator: d}
|
||||
if d > 0 {
|
||||
p := 100 * float64(n) / float64(d)
|
||||
r.Percent = &p
|
||||
}
|
||||
return r
|
||||
}
|
||||
func dashboardCategories(counts map[string]int) []DashboardCount {
|
||||
out := []DashboardCount{}
|
||||
for label, count := range counts {
|
||||
out = append(out, DashboardCount{Label: label, Count: count})
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
if out[i].Count == out[j].Count {
|
||||
return out[i].Label < out[j].Label
|
||||
}
|
||||
return out[i].Count > out[j].Count
|
||||
})
|
||||
return out
|
||||
}
|
||||
func dashboardCategory(value string) string {
|
||||
if value = strings.TrimSpace(value); value != "" {
|
||||
return value
|
||||
}
|
||||
return "未分类"
|
||||
}
|
||||
|
||||
// ReadDashboard never fetches answer payloads or opens a source connection. All
|
||||
// scopes, quality inputs and organizational attribution use ONE local snapshot.
|
||||
func (s *Store) ReadDashboard(ctx context.Context, q dobotaiops.RecordQuery) (Dashboard, error) {
|
||||
out := Dashboard{Start: q.Window.Start, End: q.Window.End, Keyword: q.Keyword, IssueTypes: []DashboardCount{}, Products: []DashboardCount{}, Daily: []DashboardDaily{}, Regions: []DashboardRegion{}, FrozenWeeks: []DashboardFrozen{}}
|
||||
if !s.valid() {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if q.Window.TenantKey != s.tenant || !utf8.ValidString(q.Keyword) || utf8.RuneCountInString(q.Keyword) > 200 || strings.ContainsRune(q.Keyword, 0) {
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if _, e := dobotaiops.NewWindow(s.tenant, q.Window.Start.Format(time.RFC3339Nano), q.Window.End.Format(time.RFC3339Nano), 90*24*time.Hour, time.Now()); e != nil {
|
||||
return out, e
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
||||
defer cancel()
|
||||
tx, e := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
state, e := s.readState(ctx, txQuery{tx})
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
if state.Blocked {
|
||||
return out, dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready || state.SourceObservedAt == nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
out.AsOf = *state.SourceObservedAt
|
||||
out.LocalRevision = state.Revision
|
||||
attribution, e := qaopsorg.NewStore(s.pool, s.tenant).GetAttributionInTx(ctx, tx)
|
||||
if e != nil {
|
||||
return out, e
|
||||
}
|
||||
meta := attribution.Metadata
|
||||
out.Organization = dobotaiops.OrganizationVersion{State: meta.State, DirectoryID: meta.DirectoryID, DirectorySource: meta.DirectorySource, SyncedAt: meta.DirectorySyncedAt, RevisionID: meta.RevisionID, Basis: "current_directory", RegionNames: meta.RegionLabels()}
|
||||
out.MonthStart, out.WeekStart = dashboardPeriods(q.Window.End)
|
||||
var first *time.Time
|
||||
if e = tx.QueryRow(ctx, `SELECT count(*),LEAST((SELECT min(asked_at) FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at<$2),(SELECT first_data_at FROM qa_ops_weekly_quality_tracking WHERE tenant_key=$1),(SELECT min(week_start) FROM qa_ops_weekly_quality_snapshots WHERE tenant_key=$1 AND week_start<$2)) FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at<$2 AND ($3='' OR position(lower($3) IN lower(question))>0)`, s.tenant, q.Window.End, q.Keyword).Scan(&out.TotalIssues, &first); e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
lower := q.Window.Start
|
||||
if out.MonthStart.Before(lower) {
|
||||
lower = out.MonthStart
|
||||
}
|
||||
if out.WeekStart.Before(lower) {
|
||||
lower = out.WeekStart
|
||||
}
|
||||
rows, e := tx.Query(ctx, `SELECT id,asked_at,identity,quality_hash FROM qa_ops_mirror_records WHERE tenant_key=$1 AND asked_at>=$2 AND asked_at<$3 AND ($4='' OR position(lower($4) IN lower(question))>0) ORDER BY id LIMIT 100001`, s.tenant, lower, q.Window.End, q.Keyword)
|
||||
if e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
records := []dashboardRecord{}
|
||||
keys := []dobotaiops.QualityKey{}
|
||||
for rows.Next() {
|
||||
var r dashboardRecord
|
||||
var identity []byte
|
||||
if rows.Scan(&r.id, &r.at, &identity, &r.hash) != nil || json.Unmarshal(identity, &r.identity) != nil {
|
||||
rows.Close()
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
records = append(records, r)
|
||||
if len(records) > dobotaiops.MaxMirrorRecords {
|
||||
rows.Close()
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
if !r.at.Before(q.Window.Start) {
|
||||
keys = append(keys, dobotaiops.QualityKey{ID: r.id, InputHash: r.hash})
|
||||
}
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
views := map[string]qaopsquality.View{}
|
||||
quality := qaopsquality.NewStore(s.pool, s.tenant)
|
||||
for begin := 0; begin < len(keys); begin += 5000 {
|
||||
end := begin + 5000
|
||||
if end > len(keys) {
|
||||
end = len(keys)
|
||||
}
|
||||
batch, err := quality.ReadViewsInTx(ctx, tx, keys[begin:end])
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
for id, v := range batch {
|
||||
views[id] = v
|
||||
}
|
||||
}
|
||||
out.Quality = qaopsquality.Summarize(views)
|
||||
products, types, daily := map[string]int{}, map[string]int{}, map[string]int{}
|
||||
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
daily[day.Format("2006-01-02")] = 0
|
||||
}
|
||||
regionIndex := map[string]int{}
|
||||
users := map[string]map[string]bool{}
|
||||
for _, region := range meta.RegionDefinitions() {
|
||||
r := DashboardRegion{ID: region.ID, Name: region.Name}
|
||||
if meta.State == "ready" {
|
||||
n := meta.View.Regions[region.ID]
|
||||
r.RosterPeople = &n
|
||||
r.Users = new(int)
|
||||
}
|
||||
regionIndex[region.Name] = len(out.Regions)
|
||||
users[region.Name] = map[string]bool{}
|
||||
out.Regions = append(out.Regions, r)
|
||||
}
|
||||
for _, r := range records {
|
||||
if !r.at.Before(out.WeekStart) {
|
||||
out.NewThisWeek++
|
||||
daily[r.at.In(dashboardLocation).Format("2006-01-02")]++
|
||||
}
|
||||
if !r.at.Before(q.Window.Start) {
|
||||
v, ok := views[r.id]
|
||||
if !ok {
|
||||
return out, qaopsquality.ErrUnavailable
|
||||
}
|
||||
products[dashboardCategory(v.Effective.ProductCategory)]++
|
||||
types[dashboardCategory(v.Effective.ProblemType)]++
|
||||
}
|
||||
if !r.at.Before(out.MonthStart) {
|
||||
person := attribution.Resolve(r.identity.StaffID, r.identity.UnionID)
|
||||
if index, ok := regionIndex[person.Region]; ok && person.PersonID != "" {
|
||||
out.Regions[index].Questions++
|
||||
users[person.Region][person.PersonID] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
out.Products = dashboardCategories(products)
|
||||
out.IssueTypes = dashboardCategories(types)
|
||||
for day := out.WeekStart; day.Before(q.Window.End); day = day.AddDate(0, 0, 1) {
|
||||
date := day.Format("2006-01-02")
|
||||
out.Daily = append(out.Daily, DashboardDaily{Date: date, Count: daily[date]})
|
||||
}
|
||||
for i := range out.Regions {
|
||||
r := &out.Regions[i]
|
||||
if r.Users != nil {
|
||||
*r.Users = len(users[r.Name])
|
||||
if *r.Users > *r.RosterPeople {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
r.UsageCoverage = dashboardRate(*r.Users, *r.RosterPeople)
|
||||
if *r.RosterPeople > 0 {
|
||||
frequency := float64(r.Questions) / float64(*r.RosterPeople)
|
||||
r.Frequency = &frequency
|
||||
}
|
||||
}
|
||||
}
|
||||
if first != nil {
|
||||
snapshots, err := s.readFrozenDashboard(ctx, tx, q.Keyword, q.Window.End)
|
||||
if err != nil {
|
||||
return out, err
|
||||
}
|
||||
out.FrozenWeeks = dashboardFrozenSeries(*first, q.Window.End, snapshots)
|
||||
if len(out.FrozenWeeks) > 0 && out.FrozenWeeks[len(out.FrozenWeeks)-1].WeekEnd.Before(q.Window.End) {
|
||||
return out, dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return out, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestDashboardPeriodsUseBeijingAndPreviousSundayAtExclusiveEnd(t *testing.T) {
|
||||
end := time.Date(2026, 11, 2, 0, 0, 0, 0, time.FixedZone("CST", 8*3600))
|
||||
month, week := dashboardPeriods(end)
|
||||
if month.Format(time.RFC3339) != "2026-11-01T00:00:00+08:00" || week.Format(time.RFC3339) != "2026-10-26T00:00:00+08:00" {
|
||||
t.Fatal("exclusive Monday end was assigned to the wrong source week/month")
|
||||
}
|
||||
}
|
||||
func TestDashboardFrozenGapsNeverUseCurrentRates(t *testing.T) {
|
||||
start := time.Date(2026, 9, 28, 0, 0, 0, 0, time.FixedZone("CST", 8*3600))
|
||||
end := start.AddDate(0, 0, 21)
|
||||
points := dashboardFrozenSeries(start, end, nil)
|
||||
if len(points) != 3 {
|
||||
t.Fatal("must include each source natural week including missing snapshots")
|
||||
}
|
||||
for _, point := range points {
|
||||
if point.FrozenAt != nil || point.Coverage.Percent != nil || point.Correctness.Percent != nil {
|
||||
t.Fatal("missing historical snapshots were fabricated from current data")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorFailuresUpdatesAndReviewPreservation(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-failures")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
first := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("one", "old answer")}}
|
||||
run := func(source *fixtureSource, key string) error {
|
||||
j := claimMirrorJob(t, s, q, key)
|
||||
e := s.HandleSync(ctx, *j, func(context.Context) (Source, error) { return source, nil })
|
||||
if e == nil {
|
||||
if e = q.Complete(ctx, j.ID, j.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
} else {
|
||||
if _, cleanupErr := p.Exec(ctx, `UPDATE jobs SET state='failed',lease_owner=NULL,lease_until=NULL WHERE id=$1`, j.ID); cleanupErr != nil {
|
||||
t.Fatal(cleanupErr)
|
||||
}
|
||||
}
|
||||
return e
|
||||
}
|
||||
if e := run(first, "initial-good"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
quality := qaopsquality.NewStore(p, s.tenant)
|
||||
record, _ := s.GetRecord(ctx, s.tenant, "one")
|
||||
views, e := quality.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
v := views["one"]
|
||||
saved, e := quality.Save(ctx, record, qaopsquality.SaveRequest{InputHash: v.InputHash, InputEpoch: v.InputEpoch, BaseRevision: v.Revision, Nonce: strings.Repeat("a", 32), Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct"}, Reason: "explicit synthetic review"}, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
unchanged := &fixtureSource{rows: first.rows}
|
||||
if e = run(unchanged, "unchanged-check"); e != nil || unchanged.payloadCalls != 0 {
|
||||
t.Fatal("unchanged poll transferred long answers", e)
|
||||
}
|
||||
state, _ := s.GetSyncStatus(ctx)
|
||||
if state.Revision != 1 {
|
||||
t.Fatal("unchanged poll invalidated query generations")
|
||||
}
|
||||
current, e := quality.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil || current["one"].State != "reviewed" || current["one"].Revision != saved.SavedRevision {
|
||||
t.Fatal("unchanged synchronization damaged review", e)
|
||||
}
|
||||
partial := &fixtureSource{payloadError: errors.New("fixture interrupted payload"), failAfter: 2}
|
||||
partial.rows = append(partial.rows, fixtureEntry("one", "new answer"))
|
||||
for n := 0; n < 101; n++ {
|
||||
partial.rows = append(partial.rows, fixtureEntry(fmt.Sprintf("extra-%03d", n), "additional answer"))
|
||||
}
|
||||
if e = run(partial, "interrupted-full-copy"); e == nil {
|
||||
t.Fatal("partial fetch was called complete")
|
||||
}
|
||||
old, e := s.GetRecord(ctx, s.tenant, "one")
|
||||
state, _ = s.GetSyncStatus(ctx)
|
||||
if e != nil || old.Answer != "old answer" || state.Records != 1 || state.Revision != 1 || state.ErrorCode == "" || !state.Ready {
|
||||
t.Fatal("partial failure mutated last-good local copy", e)
|
||||
}
|
||||
current, e = quality.Observe(ctx, []dobotaiops.Record{old})
|
||||
if e != nil || current["one"].State != "reviewed" {
|
||||
t.Fatal("partial source fetch advanced review input", e)
|
||||
}
|
||||
changed := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("one", "changed answer")}}
|
||||
if e = run(changed, "changed-old-record"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, _ := s.GetRecord(ctx, s.tenant, "one")
|
||||
current, e = quality.Observe(ctx, []dobotaiops.Record{fresh})
|
||||
if e != nil || current["one"].State != "stale" || current["one"].LatestReview == nil || current["one"].LatestReview.Revision != saved.SavedRevision {
|
||||
t.Fatal("answer change lost history or retained an obsolete judgment", e)
|
||||
}
|
||||
denied := &fixtureSource{err: dobotaiops.ErrNotReadOnly}
|
||||
if e = run(denied, "authorization-denied"); e == nil {
|
||||
t.Fatal("source authorization failure ignored")
|
||||
}
|
||||
if e = s.Available(ctx); !errors.Is(e, dobotaiops.ErrNotReadOnly) {
|
||||
t.Fatal("revoked source left local reads enabled", e)
|
||||
}
|
||||
recovered := &fixtureSource{rows: changed.rows}
|
||||
if e = run(recovered, "authorization-recovered"); e != nil || s.Available(ctx) != nil {
|
||||
t.Fatal("verified recovery failed", e)
|
||||
}
|
||||
}
|
||||
func TestLocalMirrorRejectsUnadmittedJobsBeforeSource(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-unadmitted")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
_, e := q.Enqueue(ctx, jobs.EnqueueRequest{ID: "fixture-bypass", Type: s.SyncJobType(), Payload: []byte(`{}`), AvailableAt: time.Now(), MaxAttempts: 1, IdempotencyKey: "fixture-bypass"}, time.Now())
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
j, e := q.Claim(ctx, "fixture-bypass-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || j == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
calls := 0
|
||||
e = s.HandleSync(ctx, *j, func(context.Context) (Source, error) { calls++; return &fixtureSource{}, nil })
|
||||
if !errors.Is(e, ErrLease) || calls != 0 {
|
||||
t.Fatal("unadmitted job reached source", e, calls)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package qaopsmirror
|
||||
|
||||
import "knowledge-governance/internal/dobotaiops"
|
||||
|
||||
// The complete fixed-column UI does not need to repeatedly decompress every
|
||||
// large answer on every page just to rediscover which headings exist. Exact
|
||||
// marker/source evidence was committed atomically with each mirror payload.
|
||||
const localMetadataBase = `WITH records AS (SELECT m.id,m.asked_at,m.question,m.identity,m.quality_hash,COALESCE(c.result->>'verdict'='uncovered',false) AS marker,COALESCE(c.source,'{}'::jsonb) AS source_coverage FROM qa_ops_mirror_records m LEFT JOIN qa_ops_quality_records h ON h.tenant_key=m.tenant_key AND h.record_id=m.id AND h.input_hash=m.quality_hash LEFT JOIN qa_ops_quality_checks c ON c.tenant_key=h.tenant_key AND c.record_id=h.record_id AND c.input_epoch=h.input_epoch AND c.rule_version='` + dobotaiops.CoverageRuleVersion + `' WHERE m.tenant_key=$1)`
|
||||
const localSummarySQL = localMetadataBase + ` SELECT count(*),'{}'::text,COALESCE(jsonb_agg(DISTINCT identity),'[]'::jsonb)::text,COALESCE(jsonb_agg(jsonb_build_object('id',id,'input_hash',quality_hash,'marker',marker,'source',source_coverage)),'[]'::jsonb)::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
const localQualityScopeSQL = localMetadataBase + ` SELECT id,quality_hash,marker,source_coverage::text FROM records WHERE $5::text IS NOT NULL AND `
|
||||
@@ -0,0 +1,39 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorSchedulerRecoversExhaustedCrash(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-crashed-scheduler")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
if _, e := q.Claim(ctx, "fixture-crashed-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := p.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key,next_sync_at) VALUES($1,now()-interval '1 hour')`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if yes, e := s.EnqueueDue(ctx); e != nil || !yes {
|
||||
t.Fatal(e)
|
||||
}
|
||||
job, e := q.Claim(ctx, "fixture-crashed-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || job == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Model death after claiming the final attempt, before any failure checkpoint.
|
||||
if _, e = p.Exec(ctx, `UPDATE jobs SET attempt=max_attempts,lease_until=now()-interval '1 second' WHERE id=$1`, job.ID); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = s.EnqueueDue(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
state, e := s.GetSyncStatus(ctx)
|
||||
if e != nil || state.NextSyncAt == nil || !state.NextSyncAt.After(time.Now()) || state.ErrorCode != "mirror_sync_interrupted" {
|
||||
t.Fatal("scheduler replayed an exhausted operation forever instead of persisting a new retry due time", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
// Package qaopsmirror serves an explicitly synchronized local copy, never an implicit source fallback.
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const Interval = 5 * time.Minute
|
||||
const localBaseSQL = `WITH records AS (SELECT id,asked_at,question,status,identity,quality_hash,payload FROM qa_ops_mirror_records WHERE tenant_key=$1)`
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
tenant string
|
||||
mu sync.RWMutex
|
||||
safety dobotaiops.SourceSafety
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }
|
||||
|
||||
type Status struct {
|
||||
Mode string `json:"mode"`
|
||||
Ready bool `json:"ready"`
|
||||
Blocked bool `json:"blocked"`
|
||||
Revision int64 `json:"revision"`
|
||||
Records int64 `json:"records"`
|
||||
SourceObservedAt *time.Time `json:"source_observed_at"`
|
||||
LastSuccessAt *time.Time `json:"last_success_at"`
|
||||
NextSyncAt *time.Time `json:"next_sync_at"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
IntervalSeconds int `json:"interval_seconds"`
|
||||
WorkerReady bool `json:"worker_ready"`
|
||||
Job *SyncJob `json:"job"`
|
||||
Safety dobotaiops.SourceSafety `json:"-"`
|
||||
}
|
||||
type SyncJob struct {
|
||||
ID string `json:"id"`
|
||||
State string `json:"state"`
|
||||
Loaded int `json:"loaded"`
|
||||
Expected int `json:"expected"`
|
||||
Changed int `json:"changed"`
|
||||
ErrorCode string `json:"error_code"`
|
||||
}
|
||||
|
||||
func (s *Store) valid() bool {
|
||||
return s != nil && s.pool != nil && strings.TrimSpace(s.tenant) == s.tenant && len(s.tenant) > 0 && len(s.tenant) <= 128 && !strings.ContainsRune(s.tenant, 0)
|
||||
}
|
||||
func (s *Store) readState(ctx context.Context, q dobotaiops.RecordQuerier) (Status, error) {
|
||||
out := Status{Mode: "local", IntervalSeconds: int(Interval / time.Second)}
|
||||
var safety []byte
|
||||
err := q.QueryRow(ctx, `SELECT ready,blocked,revision,record_count,source_observed_at,synced_at,next_sync_at,last_error,source_safety FROM qa_ops_mirror_state WHERE tenant_key=$1`, s.tenant).Scan(&out.Ready, &out.Blocked, &out.Revision, &out.Records, &out.SourceObservedAt, &out.LastSuccessAt, &out.NextSyncAt, &out.ErrorCode, &safety)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
out.ErrorCode = "initial_sync_pending"
|
||||
return out, nil
|
||||
}
|
||||
if err != nil || json.Unmarshal(safety, &out.Safety) != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.safety = out.Safety
|
||||
s.mu.Unlock()
|
||||
return out, nil
|
||||
}
|
||||
|
||||
type txQuery struct{ pgx.Tx }
|
||||
|
||||
func (q txQuery) QueryRow(ctx context.Context, sql string, args ...any) dobotaiops.RecordRow {
|
||||
return q.Tx.QueryRow(ctx, sql, args...)
|
||||
}
|
||||
|
||||
type poolQuery struct{ *pgxpool.Pool }
|
||||
|
||||
func (q poolQuery) QueryRow(ctx context.Context, sql string, args ...any) dobotaiops.RecordRow {
|
||||
return q.Pool.QueryRow(ctx, sql, args...)
|
||||
}
|
||||
func (s *Store) Available(ctx context.Context) error {
|
||||
if !s.valid() {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
state, e := s.readState(ctx, poolQuery{s.pool})
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if state.Blocked {
|
||||
return dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) Safety() dobotaiops.SourceSafety { s.mu.RLock(); defer s.mu.RUnlock(); return s.safety }
|
||||
func (s *Store) repository(revision *int64) *dobotaiops.RecordsRepository {
|
||||
return dobotaiops.NewRecordsRepository(dobotaiops.RecordsRepositoryOptions{
|
||||
BaseSQL: localBaseSQL, SummarySQL: localSummarySQL, QualityScopeSQL: localQualityScopeSQL, TenantKey: s.tenant,
|
||||
ValidateWindow: func(w dobotaiops.Window) error {
|
||||
if w.TenantKey != s.tenant {
|
||||
return dobotaiops.ErrInvalidQuery
|
||||
}
|
||||
_, e := dobotaiops.NewWindow(w.TenantKey, w.Start.Format(time.RFC3339Nano), w.End.Format(time.RFC3339Nano), 90*24*time.Hour, time.Now())
|
||||
return e
|
||||
},
|
||||
ReadAsOf: func(ctx context.Context, q dobotaiops.RecordQuerier, t *time.Time) error {
|
||||
return q.QueryRow(ctx, `SELECT source_observed_at FROM qa_ops_mirror_state WHERE tenant_key=$1`, s.tenant).Scan(t)
|
||||
},
|
||||
Transaction: func(ctx context.Context, fn func(context.Context, dobotaiops.RecordQuerier) error) error {
|
||||
if !s.valid() {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, 15*time.Second)
|
||||
defer cancel()
|
||||
tx, e := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
q := txQuery{tx}
|
||||
state, e := s.readState(ctx, q)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if state.Blocked {
|
||||
return dobotaiops.ErrNotReadOnly
|
||||
}
|
||||
if !state.Ready {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
if revision != nil {
|
||||
*revision = state.Revision
|
||||
}
|
||||
if e = fn(ctx, q); e != nil {
|
||||
return e
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
},
|
||||
})
|
||||
}
|
||||
func (s *Store) ListRecords(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.RecordPage, error) {
|
||||
var rev int64
|
||||
p, e := s.repository(&rev).ListRecords(ctx, q)
|
||||
p.LocalRevision = rev
|
||||
p.Columns = []string{"question_chinese", "answer", "coverage", "is_correct", "product_category", "problem_type", "root_cause", "asked_at", "asker", "question", "language", "trigger_person", "department", "region", "feedback"}
|
||||
return p, e
|
||||
}
|
||||
func (s *Store) GetRecord(ctx context.Context, tenant, id string) (dobotaiops.Record, error) {
|
||||
return s.repository(nil).GetRecord(ctx, tenant, id)
|
||||
}
|
||||
func (s *Store) ReadUsageGroups(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.UsageGroups, error) {
|
||||
return s.repository(nil).ReadUsageGroups(ctx, q)
|
||||
}
|
||||
func (s *Store) ReadQualityScope(ctx context.Context, q dobotaiops.RecordQuery) (dobotaiops.QualityScope, error) {
|
||||
return s.repository(nil).ReadQualityScope(ctx, q)
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func mirrorFixture(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
dsn := os.Getenv("KG_QAOPS_MIRROR_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit disposable mirror database required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_mirror_test_") || os.Getenv("KG_QAOPS_MIRROR_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("refusing shared mirror database")
|
||||
}
|
||||
p, e := pgxpool.New(context.Background(), dsn)
|
||||
if e != nil {
|
||||
t.Fatal("fixture connection failed")
|
||||
}
|
||||
t.Cleanup(p.Close)
|
||||
if e = pg.ApplyMigrations(context.Background(), p); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
return p
|
||||
}
|
||||
func TestLocalMirrorQueriesNeverRequireSource(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
s := NewStore(p, "fixture-mirror")
|
||||
if s.Available(ctx) == nil {
|
||||
t.Fatal("an unsynchronized mirror pretended to be empty/ready")
|
||||
}
|
||||
asked := time.Now().UTC().Add(-time.Hour).Truncate(time.Second)
|
||||
wire := map[string]any{"id": "fixture-one", "status": "succeeded", "question": "literal 100%_ question", "answer": "# local answer\n暂无已发布", "asked_at": asked, "time_source": "turn.created_at", "asker": "fixture name", "trigger_person": "", "department": "", "region": "", "references": []any{}, "media": []any{}, "source_coverage": map[string]string{"verdict": "covered", "reason_code": "", "evaluator_version": "v5"}, "feedback": map[string]any{"asker_value": "up", "up": 1, "down": 0}, "_identity": map[string]string{"actor_id": "actor1", "staff_id": "staff1", "union_id": ""}, "_quality_hash": strings.Repeat("a", 64), "_quality_observed_at": time.Now().UTC()}
|
||||
raw, _ := json.Marshal(wire)
|
||||
if _, e := p.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key,ready,revision,record_count,source_observed_at,synced_at) VALUES($1,true,1,1,now(),now())`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := p.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,'fixture-one',$2,$3,$4,'succeeded',$5,$2,$6)`, s.tenant, strings.Repeat("a", 64), asked, wire["question"], `{"actor_id":"actor1","staff_id":"staff1","union_id":""}`, raw); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// No source client or source credentials have been constructed anywhere in this test.
|
||||
if e := s.Available(ctx); e != nil {
|
||||
t.Fatal("local serving still requires a remote source", e)
|
||||
}
|
||||
q := dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: s.tenant, Start: asked.Add(-time.Minute), End: asked.Add(time.Minute)}, Keyword: "100%_", Limit: 1}
|
||||
page, e := s.ListRecords(ctx, q)
|
||||
if e != nil || page.Total != 1 || len(page.Items) != 1 || page.Items[0].Answer != wire["answer"] {
|
||||
t.Fatal("local fixed-tenant literal query failed", e, page.Total)
|
||||
}
|
||||
if page.Items[0].Identity.StaffID != "staff1" || page.Items[0].Coverage.Verdict != "uncovered" {
|
||||
t.Fatal("local copy lost source identity or deterministic rule")
|
||||
}
|
||||
out, _ := json.Marshal(page)
|
||||
if strings.Contains(string(out), "staff1") || strings.Contains(string(out), "_identity") {
|
||||
t.Fatal("private identity leaked to browser")
|
||||
}
|
||||
got, e := s.GetRecord(ctx, s.tenant, "fixture-one")
|
||||
if e != nil || got.Answer != wire["answer"] {
|
||||
t.Fatal("detail is not served from local data", e)
|
||||
}
|
||||
if _, e = s.GetRecord(ctx, "other-tenant", "fixture-one"); !errors.Is(e, dobotaiops.ErrInvalidQuery) {
|
||||
t.Fatal("cross-tenant detail was not rejected", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
)
|
||||
|
||||
// Payload activation observes quality atomically. Browser reads must not repeat
|
||||
// per-record write transactions; mismatched inputs fail closed in ReadViews.
|
||||
func (s *Store) ReadStoredQuality(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]qaopsquality.View, error) {
|
||||
return qaopsquality.NewStore(s.pool, s.tenant).ReadViews(ctx, keys)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorMetadataDoesNotReadLargeAnswerPayload(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
tenant := "fixture-metadata-acl"
|
||||
record := dobotaiops.Record{ID: "metadata-one", Question: "fixture", Answer: "暂无已发布", QualityObservedAt: time.Now()}
|
||||
views, e := qaopsquality.NewStore(p, tenant).Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
hash := views[record.ID].InputHash
|
||||
if _, e = p.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key,ready,revision,record_count,source_observed_at,synced_at) VALUES($1,true,1,1,now(),now());`, tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,$2,$3,now()-interval '1 hour','fixture','succeeded','{}',$3,'{}')`, tenant, record.ID, hash); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
role := fmt.Sprintf("kg_mirror_metadata_%d", time.Now().UnixNano())
|
||||
if _, e = p.Exec(ctx, "CREATE ROLE "+role+" NOLOGIN"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer func() { p.Exec(ctx, "DROP OWNED BY "+role); p.Exec(ctx, "DROP ROLE "+role) }()
|
||||
if _, e = p.Exec(ctx, "GRANT SELECT(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash) ON qa_ops_mirror_records TO "+role+";GRANT SELECT ON qa_ops_mirror_state,qa_ops_quality_records,qa_ops_quality_inputs,qa_ops_quality_checks TO "+role); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
config := p.Config().Copy()
|
||||
config.AfterConnect = func(ctx context.Context, c *pgx.Conn) error { _, e := c.Exec(ctx, "SET ROLE "+role); return e }
|
||||
limited, e := pgxpool.NewWithConfig(ctx, config)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer limited.Close()
|
||||
scope, e := NewStore(limited, tenant).ReadQualityScope(ctx, dobotaiops.RecordQuery{Window: dobotaiops.Window{TenantKey: tenant, Start: time.Now().Add(-2 * time.Hour), End: time.Now()}, Limit: 100})
|
||||
if e != nil || len(scope.Keys) != 1 || !scope.Keys[0].Marker {
|
||||
t.Fatal("local metadata still requires SELECT on large payload instead of committed quality evidence", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalMirrorStoredQualityUsesReadOnlyBatchedProjection(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
ctx := context.Background()
|
||||
tenant := "fixture-read-stored"
|
||||
record := dobotaiops.Record{ID: "stored-one", Question: "fixture question", Answer: "暂无已发布", QualityObservedAt: time.Now()}
|
||||
views, e := qaopsquality.NewStore(p, tenant).Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
hash := views[record.ID].InputHash
|
||||
config := p.Config().Copy()
|
||||
config.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
readonly, e := pgxpool.NewWithConfig(ctx, config)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer readonly.Close()
|
||||
store := NewStore(readonly, tenant)
|
||||
keys := []dobotaiops.QualityKey{{ID: record.ID, InputHash: hash}}
|
||||
got, e := store.ReadStoredQuality(ctx, keys)
|
||||
if e != nil || len(got) != 1 || got[record.ID].InputHash != hash {
|
||||
t.Fatal("synchronized quality must be readable without any write transaction", e)
|
||||
}
|
||||
keys[0].InputHash = strings.Repeat("f", 64)
|
||||
if _, e = store.ReadStoredQuality(ctx, keys); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("stale mirror input paired with newer quality", e)
|
||||
}
|
||||
if _, e = NewStore(readonly, "other-tenant").ReadStoredQuality(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: hash}}); e == nil {
|
||||
t.Fatal("stored quality crossed tenant scope")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const SyncJobPrefix = "qaops.records.sync."
|
||||
|
||||
func (s *Store) EnqueueDue(ctx context.Context) (bool, error) {
|
||||
if !s.valid() {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
// A final-attempt process can die before recordFailure. Rotate the persisted
|
||||
// due time once, otherwise ExecuteOperation would replay its dead receipt forever.
|
||||
if _, e := s.pool.Exec(ctx, `WITH latest AS (SELECT state,attempt,max_attempts,lease_until,updated_at FROM jobs WHERE type=$2 ORDER BY created_at DESC,id DESC LIMIT 1) UPDATE qa_ops_mirror_state s SET next_sync_at=clock_timestamp()+interval '5 minutes',last_error='mirror_sync_interrupted' FROM latest j WHERE s.tenant_key=$1 AND s.next_sync_at<=j.updated_at AND(j.state='failed' OR(j.state='running' AND j.attempt>=j.max_attempts AND j.lease_until<clock_timestamp()))`, s.tenant, s.SyncJobType()); e != nil {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var next time.Time
|
||||
var due bool
|
||||
e := s.pool.QueryRow(ctx, `SELECT next_sync_at,next_sync_at<=clock_timestamp() FROM qa_ops_mirror_state WHERE tenant_key=$1`, s.tenant).Scan(&next, &due)
|
||||
if e != nil && !errors.Is(e, pgx.ErrNoRows) {
|
||||
return false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if e == nil && !due {
|
||||
return false, nil
|
||||
}
|
||||
key := "automatic:initial"
|
||||
if !next.IsZero() {
|
||||
key = "automatic:" + next.UTC().Format(time.RFC3339Nano)
|
||||
}
|
||||
receipt, replayed, e := s.EnqueueSync(ctx, key, "system:qa-record-sync")
|
||||
return e == nil && !replayed && !receipt.Deduplicated, e
|
||||
}
|
||||
|
||||
var ErrWorkerUnavailable = errors.New("local mirror worker is unavailable")
|
||||
var ErrInvalid = errors.New("invalid local mirror request")
|
||||
var ErrConflict = errors.New("local mirror request conflict")
|
||||
var ErrLease = errors.New("local mirror lease lost")
|
||||
var ErrSync = errors.New("local mirror source synchronization failed; last committed data retained")
|
||||
|
||||
type SyncReceipt struct {
|
||||
JobID string `json:"job_id"`
|
||||
Deduplicated bool `json:"deduplicated"`
|
||||
}
|
||||
|
||||
func (s *Store) SyncJobType() string {
|
||||
h := sha256.Sum256([]byte(s.tenant))
|
||||
return SyncJobPrefix + hex.EncodeToString(h[:])
|
||||
}
|
||||
|
||||
const workerReadySQL = `SELECT EXISTS(SELECT 1 FROM worker_heartbeats WHERE $1=ANY(string_to_array(job_types,',')) AND last_seen_at>clock_timestamp()-interval '2 minutes') OR EXISTS(SELECT 1 FROM jobs WHERE type=$1 AND state='running' AND lease_until>clock_timestamp())`
|
||||
|
||||
func validToken(v string, n int) bool {
|
||||
return strings.TrimSpace(v) == v && len(v) > 0 && len(v) <= n && utf8.ValidString(v) && !strings.ContainsRune(v, 0)
|
||||
}
|
||||
func (s *Store) EnqueueSync(ctx context.Context, key, actor string) (SyncReceipt, bool, error) {
|
||||
if !s.valid() {
|
||||
return SyncReceipt{}, false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !validToken(key, 128) || !validToken(actor, 256) {
|
||||
return SyncReceipt{}, false, ErrInvalid
|
||||
}
|
||||
fp := sha256.Sum256([]byte(actor))
|
||||
now := time.Now()
|
||||
raw, replay, err := pg.NewStore(s.pool).ExecuteOperation(ctx, s.SyncJobType(), key, hex.EncodeToString(fp[:]), now, func(tx pgx.Tx) (json.RawMessage, error) {
|
||||
if _, e := tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, s.SyncJobType()); e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if _, e := tx.Exec(ctx, `UPDATE jobs SET state='failed',last_error='local mirror worker interrupted',last_error_code='mirror_sync_interrupted',lease_owner=NULL,lease_until=NULL,updated_at=now() WHERE type=$1 AND state='running' AND lease_until<clock_timestamp() AND attempt>=max_attempts`, s.SyncJobType()); e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var active string
|
||||
e := tx.QueryRow(ctx, `SELECT id FROM jobs WHERE type=$1 AND state IN ('pending','running','retry') ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&active)
|
||||
if e == nil {
|
||||
return json.Marshal(SyncReceipt{JobID: active, Deduplicated: true})
|
||||
}
|
||||
if !errors.Is(e, pgx.ErrNoRows) {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var ready bool
|
||||
if tx.QueryRow(ctx, workerReadySQL, s.SyncJobType()).Scan(&ready) != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
if !ready {
|
||||
return nil, ErrWorkerUnavailable
|
||||
}
|
||||
if _, e = tx.Exec(ctx, `INSERT INTO qa_ops_mirror_state(tenant_key) VALUES($1) ON CONFLICT DO NOTHING`, s.tenant); e != nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
h := sha256.Sum256([]byte(s.SyncJobType() + ":" + key))
|
||||
payload, _ := json.Marshal(map[string]string{"triggered_by": actor})
|
||||
job, e := pg.NewStore(tx).Enqueue(ctx, jobs.EnqueueRequest{ID: "job-" + hex.EncodeToString(h[:16]), Type: s.SyncJobType(), Payload: payload, AvailableAt: now, MaxAttempts: 3, IdempotencyKey: s.SyncJobType() + ":" + key}, now)
|
||||
if e != nil || job == nil {
|
||||
return nil, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return json.Marshal(SyncReceipt{JobID: job.ID})
|
||||
})
|
||||
if errors.Is(err, pg.ErrOperationRequestConflict) {
|
||||
return SyncReceipt{}, false, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return SyncReceipt{}, false, err
|
||||
}
|
||||
var receipt SyncReceipt
|
||||
if json.Unmarshal(raw, &receipt) != nil || receipt.JobID == "" {
|
||||
return receipt, false, dobotaiops.ErrUnavailable
|
||||
}
|
||||
return receipt, replay, nil
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestLocalMirrorDurableQueueCoalescesAndAudits(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-queue")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
if _, _, e := s.EnqueueSync(ctx, "fixture-no-worker", "fixture-admin"); !errors.Is(e, ErrWorkerUnavailable) {
|
||||
t.Fatal("offline worker accepted work", e)
|
||||
}
|
||||
if _, e := q.Claim(ctx, "fixture-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
ids := make(chan string, 8)
|
||||
errs := make(chan error, 8)
|
||||
for range 8 {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
r, _, e := s.EnqueueSync(ctx, "fixture-same-action", "fixture-admin")
|
||||
if e != nil {
|
||||
errs <- e
|
||||
return
|
||||
}
|
||||
ids <- r.JobID
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
close(ids)
|
||||
for e := range errs {
|
||||
t.Fatal("durable enqueue failed", e)
|
||||
}
|
||||
id := ""
|
||||
n := 0
|
||||
for got := range ids {
|
||||
if got == "" || id != "" && got != id {
|
||||
t.Fatal("same action created different effects")
|
||||
}
|
||||
id = got
|
||||
n++
|
||||
}
|
||||
if n != 8 {
|
||||
t.Fatal("lost enqueue results")
|
||||
}
|
||||
again, _, e := s.EnqueueSync(ctx, "fixture-another-click", "fixture-admin")
|
||||
if e != nil || !again.Deduplicated || again.JobID != id {
|
||||
t.Fatal("in-flight synchronization did not coalesce", e)
|
||||
}
|
||||
if _, _, e = s.EnqueueSync(ctx, "fixture-same-action", "different-admin"); !errors.Is(e, ErrConflict) {
|
||||
t.Fatal("replay changed actor", e)
|
||||
}
|
||||
var count int
|
||||
if p.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE type=$1`, s.SyncJobType()).Scan(&count) != nil || count != 1 {
|
||||
t.Fatal("duplicate jobs")
|
||||
}
|
||||
job, e := q.Claim(ctx, "fixture-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || job == nil || job.ID != id {
|
||||
t.Fatal("job not durable", e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"regexp"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Source interface {
|
||||
ReadMirrorManifest(context.Context, string) (dobotaiops.MirrorManifest, error)
|
||||
ReadMirrorRecords(context.Context, string, []string) ([]dobotaiops.MirrorRecord, error)
|
||||
}
|
||||
type SourceFactory func(context.Context) (Source, error)
|
||||
|
||||
var hashPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
|
||||
func (s *Store) lease(ctx context.Context, q dobotaiops.RecordQuerier, j jobs.Job, lock bool) (bool, error) {
|
||||
if j.Type != s.SyncJobType() || j.LeaseOwner == "" {
|
||||
return false, ErrLease
|
||||
}
|
||||
sql := `SELECT payload ? 'mirror_result' FROM jobs WHERE id=$1 AND type=$2 AND state='running' AND lease_owner=$3 AND attempt=$4 AND lease_until>clock_timestamp() AND EXISTS(SELECT 1 FROM operation_requests op WHERE op.operation_type=jobs.type AND op.result->>'job_id'=jobs.id)`
|
||||
if lock {
|
||||
sql += " FOR UPDATE"
|
||||
}
|
||||
var done bool
|
||||
if q.QueryRow(ctx, sql, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt).Scan(&done) != nil {
|
||||
return false, ErrLease
|
||||
}
|
||||
return done, nil
|
||||
}
|
||||
func (s *Store) progress(ctx context.Context, j jobs.Job, loaded, expected, changed int) error {
|
||||
p, _ := json.Marshal(map[string]int{"loaded": loaded, "expected": expected, "changed": changed})
|
||||
tag, e := s.pool.Exec(ctx, `UPDATE jobs SET payload=jsonb_set(payload,'{mirror_progress}',$5::jsonb),updated_at=now() WHERE id=$1 AND type=$2 AND lease_owner=$3 AND attempt=$4 AND state='running' AND lease_until>clock_timestamp()`, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt, p)
|
||||
if e != nil || tag.RowsAffected() != 1 {
|
||||
return ErrLease
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) recordFailure(j jobs.Job, cause error) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
||||
defer cancel()
|
||||
code := "mirror_source_unavailable"
|
||||
blocked := errors.Is(cause, dobotaiops.ErrNotReadOnly)
|
||||
if blocked {
|
||||
code = "mirror_source_authorization_failed"
|
||||
}
|
||||
_, _ = s.pool.Exec(ctx, `UPDATE qa_ops_mirror_state SET last_error=$2,blocked=blocked OR $3,next_sync_at=clock_timestamp()+interval '5 minutes' WHERE tenant_key=$1 AND EXISTS(SELECT 1 FROM jobs WHERE id=$4 AND type=$5 AND state='running' AND lease_owner=$6 AND attempt=$7 AND lease_until>clock_timestamp())`, s.tenant, code, blocked, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt)
|
||||
}
|
||||
func (s *Store) HandleSync(ctx context.Context, j jobs.Job, factory SourceFactory) (err error) {
|
||||
if !s.valid() || factory == nil {
|
||||
return ErrSync
|
||||
}
|
||||
done, e := s.lease(ctx, poolQuery{s.pool}, j, false)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
defer func() {
|
||||
if err != nil && !errors.Is(err, ErrLease) {
|
||||
s.recordFailure(j, err)
|
||||
if errors.Is(err, dobotaiops.ErrNotReadOnly) {
|
||||
err = jobs.Permanent("mirror_source_authorization_failed", ErrSync)
|
||||
} else {
|
||||
err = ErrSync
|
||||
}
|
||||
}
|
||||
}()
|
||||
source, e := factory(ctx)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if closer, ok := source.(interface{ Close() }); ok {
|
||||
defer closer.Close()
|
||||
}
|
||||
known := map[string]string{}
|
||||
rows, e := s.pool.Query(ctx, `SELECT id,fingerprint FROM qa_ops_mirror_records WHERE tenant_key=$1`, s.tenant)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
for rows.Next() {
|
||||
var id, fp string
|
||||
if rows.Scan(&id, &fp) != nil {
|
||||
rows.Close()
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
known[id] = fp
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
manifest, e := source.ReadMirrorManifest(ctx, s.tenant)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if manifest.AsOf.IsZero() || manifest.AsOf.After(time.Now().Add(5*time.Minute)) || len(manifest.Keys) > dobotaiops.MaxMirrorRecords {
|
||||
return ErrSync
|
||||
}
|
||||
// A sudden completely empty scope is not accepted as authority to erase a populated local history.
|
||||
if len(manifest.Keys) == 0 && len(known) > 0 {
|
||||
return ErrSync
|
||||
}
|
||||
keys := map[string]string{}
|
||||
changed := []string{}
|
||||
ids := make([]string, 0, len(manifest.Keys))
|
||||
for _, k := range manifest.Keys {
|
||||
if !validToken(k.ID, 256) || !hashPattern.MatchString(k.Fingerprint) || keys[k.ID] != "" {
|
||||
return ErrSync
|
||||
}
|
||||
keys[k.ID] = k.Fingerprint
|
||||
ids = append(ids, k.ID)
|
||||
if known[k.ID] != k.Fingerprint {
|
||||
changed = append(changed, k.ID)
|
||||
}
|
||||
}
|
||||
sort.Strings(changed)
|
||||
loaded := len(ids) - len(changed)
|
||||
if e = s.progress(ctx, j, loaded, len(ids), 0); e != nil {
|
||||
return e
|
||||
}
|
||||
collected := make([]dobotaiops.MirrorRecord, 0, len(changed))
|
||||
totalBytes := 0
|
||||
for start := 0; start < len(changed); start += 100 {
|
||||
if _, e = s.lease(ctx, poolQuery{s.pool}, j, false); e != nil {
|
||||
return e
|
||||
}
|
||||
batch := changed[start:min(start+100, len(changed))]
|
||||
got, e := source.ReadMirrorRecords(ctx, s.tenant, batch)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if len(got) != len(batch) {
|
||||
return ErrSync
|
||||
}
|
||||
expected := map[string]bool{}
|
||||
for _, id := range batch {
|
||||
expected[id] = true
|
||||
}
|
||||
for _, row := range got {
|
||||
if !expected[row.Key.ID] || !hashPattern.MatchString(row.Key.Fingerprint) {
|
||||
return ErrSync
|
||||
}
|
||||
delete(expected, row.Key.ID)
|
||||
record, e := dobotaiops.DecodeMirrorPayload(string(row.Payload))
|
||||
if e != nil || record.ID != row.Key.ID || !hashPattern.MatchString(record.QualityInputHash) || record.QualityObservedAt.IsZero() || record.AskedAt.IsZero() || len(row.Payload) > 8<<20 {
|
||||
return ErrSync
|
||||
}
|
||||
totalBytes += len(row.Payload)
|
||||
if totalBytes > 256<<20 {
|
||||
return ErrSync
|
||||
}
|
||||
// A row can complete between manifest and payload reads. Keep that newer full
|
||||
// row, never store an old manifest hash against a different current payload.
|
||||
keys[row.Key.ID] = row.Key.Fingerprint
|
||||
if record.QualityObservedAt.After(manifest.AsOf) {
|
||||
manifest.AsOf = record.QualityObservedAt
|
||||
}
|
||||
collected = append(collected, row)
|
||||
}
|
||||
loaded += len(got)
|
||||
if e = s.progress(ctx, j, loaded, len(ids), len(collected)); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
return s.activate(ctx, j, manifest, ids, known, collected)
|
||||
}
|
||||
func (s *Store) activate(ctx context.Context, j jobs.Job, m dobotaiops.MirrorManifest, ids []string, known map[string]string, rows []dobotaiops.MirrorRecord) error {
|
||||
tx, e := s.pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.Background()) }()
|
||||
if _, e = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(hashtextextended($1,0))`, s.SyncJobType()); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
done, e := s.lease(ctx, txQuery{tx}, j, true)
|
||||
if e != nil {
|
||||
return e
|
||||
}
|
||||
if done {
|
||||
return nil
|
||||
}
|
||||
quality := qaopsquality.NewStore(s.pool, s.tenant)
|
||||
for start := 0; start < len(rows); start += 100 {
|
||||
batch := rows[start:min(start+100, len(rows))]
|
||||
records := make([]dobotaiops.Record, 0, len(batch))
|
||||
for _, row := range batch {
|
||||
rec, e := dobotaiops.DecodeMirrorPayload(string(row.Payload))
|
||||
if e != nil {
|
||||
return ErrSync
|
||||
}
|
||||
records = append(records, rec)
|
||||
identity, _ := json.Marshal(rec.Identity)
|
||||
if _, e = tx.Exec(ctx, `INSERT INTO qa_ops_mirror_records(tenant_key,id,fingerprint,asked_at,question,status,identity,quality_hash,payload) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9) ON CONFLICT(tenant_key,id) DO UPDATE SET fingerprint=EXCLUDED.fingerprint,asked_at=EXCLUDED.asked_at,question=EXCLUDED.question,status=EXCLUDED.status,identity=EXCLUDED.identity,quality_hash=EXCLUDED.quality_hash,payload=EXCLUDED.payload`, s.tenant, rec.ID, row.Key.Fingerprint, rec.AskedAt, rec.Question, rec.Status, identity, rec.QualityInputHash, row.Payload); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
}
|
||||
if e = quality.ObserveRecordsInTx(ctx, tx, records); e != nil {
|
||||
return e
|
||||
}
|
||||
}
|
||||
deleted, e := tx.Exec(ctx, `DELETE FROM qa_ops_mirror_records WHERE tenant_key=$1 AND NOT(id=ANY($2::text[]))`, s.tenant, ids)
|
||||
if e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
changed := len(rows) > 0 || deleted.RowsAffected() > 0
|
||||
var revision int64
|
||||
var wasReady bool
|
||||
if tx.QueryRow(ctx, `SELECT revision,ready FROM qa_ops_mirror_state WHERE tenant_key=$1 FOR UPDATE`, s.tenant).Scan(&revision, &wasReady) != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
if changed || !wasReady {
|
||||
revision++
|
||||
}
|
||||
safety, _ := json.Marshal(m.Safety)
|
||||
if _, e = tx.Exec(ctx, `UPDATE qa_ops_mirror_state SET ready=true,blocked=false,revision=$2,record_count=$3,source_observed_at=$4,synced_at=clock_timestamp(),next_sync_at=clock_timestamp()+interval '5 minutes',last_error='',source_safety=$5 WHERE tenant_key=$1`, s.tenant, revision, len(ids), m.AsOf, safety); e != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
result, _ := json.Marshal(map[string]any{"records": len(ids), "changed": len(rows), "deleted": deleted.RowsAffected(), "revision": revision})
|
||||
tag, e := tx.Exec(ctx, `UPDATE jobs SET payload=jsonb_set(payload,'{mirror_result}',$5::jsonb),updated_at=now() WHERE id=$1 AND type=$2 AND lease_owner=$3 AND attempt=$4 AND state='running' AND lease_until>clock_timestamp()`, j.ID, s.SyncJobType(), j.LeaseOwner, j.Attempt, result)
|
||||
if e != nil || tag.RowsAffected() != 1 {
|
||||
return ErrLease
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return dobotaiops.ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) GetSyncStatus(ctx context.Context) (Status, error) {
|
||||
if !s.valid() {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
state, e := s.readState(ctx, poolQuery{s.pool})
|
||||
if e != nil {
|
||||
return state, e
|
||||
}
|
||||
if s.pool.QueryRow(ctx, workerReadySQL, s.SyncJobType()).Scan(&state.WorkerReady) != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var j SyncJob
|
||||
var payload []byte
|
||||
var expired bool
|
||||
var attempt, maxAttempts int
|
||||
e = s.pool.QueryRow(ctx, `SELECT id,state,payload,COALESCE(last_error_code,''),COALESCE(state='running' AND lease_until<clock_timestamp(),false),attempt,max_attempts FROM jobs WHERE type=$1 ORDER BY created_at DESC,id DESC LIMIT 1`, s.SyncJobType()).Scan(&j.ID, &j.State, &payload, &j.ErrorCode, &expired, &attempt, &maxAttempts)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return state, nil
|
||||
}
|
||||
if e != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
var data struct {
|
||||
Progress struct {
|
||||
Loaded int `json:"loaded"`
|
||||
Expected int `json:"expected"`
|
||||
Changed int `json:"changed"`
|
||||
} `json:"mirror_progress"`
|
||||
}
|
||||
if json.Unmarshal(payload, &data) != nil {
|
||||
return Status{}, dobotaiops.ErrUnavailable
|
||||
}
|
||||
j.Loaded = data.Progress.Loaded
|
||||
j.Expected = data.Progress.Expected
|
||||
j.Changed = data.Progress.Changed
|
||||
if expired {
|
||||
j.State = "retry"
|
||||
if attempt >= maxAttempts {
|
||||
j.State = "failed"
|
||||
}
|
||||
j.ErrorCode = "mirror_sync_interrupted"
|
||||
}
|
||||
state.Job = &j
|
||||
return state, nil
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
package qaopsmirror
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"knowledge-governance/internal/jobs"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
type fixtureSource struct {
|
||||
rows []dobotaiops.MirrorRecord
|
||||
calls int
|
||||
payloadCalls int
|
||||
err error
|
||||
payloadError error
|
||||
failAfter int
|
||||
hook func()
|
||||
}
|
||||
|
||||
func (f *fixtureSource) ReadMirrorManifest(context.Context, string) (dobotaiops.MirrorManifest, error) {
|
||||
f.calls++
|
||||
m := dobotaiops.MirrorManifest{AsOf: time.Now().UTC(), Safety: dobotaiops.SourceSafety{SSL: true, TablesChecked: 5, ConnectionLimit: 1}}
|
||||
for _, r := range f.rows {
|
||||
m.Keys = append(m.Keys, r.Key)
|
||||
}
|
||||
return m, f.err
|
||||
}
|
||||
func (f *fixtureSource) ReadMirrorRecords(_ context.Context, _ string, ids []string) ([]dobotaiops.MirrorRecord, error) {
|
||||
f.payloadCalls++
|
||||
if f.payloadError != nil && f.payloadCalls >= f.failAfter {
|
||||
return nil, f.payloadError
|
||||
}
|
||||
out := []dobotaiops.MirrorRecord{}
|
||||
for _, id := range ids {
|
||||
for _, r := range f.rows {
|
||||
if r.Key.ID == id {
|
||||
out = append(out, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
if f.hook != nil {
|
||||
f.hook()
|
||||
}
|
||||
return out, f.err
|
||||
}
|
||||
func fixtureEntry(id, answer string) dobotaiops.MirrorRecord {
|
||||
qh := sha256.Sum256([]byte(id + answer))
|
||||
fp := sha256.Sum256([]byte("source:" + id + answer))
|
||||
now := time.Now().UTC()
|
||||
p, _ := json.Marshal(map[string]any{"id": id, "status": "succeeded", "question": "fixture question", "answer": answer, "asked_at": now.Add(-time.Hour), "time_source": "turn.created_at", "asker": "", "trigger_person": "", "department": "", "region": "", "references": []any{}, "media": []any{}, "source_coverage": map[string]string{"verdict": "covered", "reason_code": "", "evaluator_version": "v5"}, "feedback": map[string]any{"asker_value": "", "up": 0, "down": 0}, "_identity": map[string]string{"actor_id": "a", "staff_id": "s", "union_id": ""}, "_quality_hash": hex.EncodeToString(qh[:]), "_quality_observed_at": now})
|
||||
return dobotaiops.MirrorRecord{Key: dobotaiops.MirrorKey{ID: id, Fingerprint: hex.EncodeToString(fp[:])}, Payload: p}
|
||||
}
|
||||
func claimMirrorJob(t *testing.T, s *Store, q *pg.Store, key string) *jobs.Job {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
if _, e := q.Claim(ctx, "fixture-sync-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, _, e := s.EnqueueSync(ctx, key, "fixture-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
j, e := q.Claim(ctx, "fixture-sync-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || j == nil {
|
||||
t.Fatal("missing durable sync job", e)
|
||||
}
|
||||
return j
|
||||
}
|
||||
func TestLocalMirrorPeriodicSyncIsDurableAndDueOnly(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-periodic")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
if _, e := q.Claim(ctx, "fixture-periodic-worker", []string{s.SyncJobType()}, time.Now(), time.Minute); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if enqueued, e := s.EnqueueDue(ctx); e != nil || !enqueued {
|
||||
t.Fatal("first automatic sync was not scheduled", e)
|
||||
}
|
||||
if _, e := s.EnqueueDue(ctx); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var count int
|
||||
if p.QueryRow(ctx, `SELECT count(*) FROM jobs WHERE type=$1`, s.SyncJobType()).Scan(&count) != nil || count != 1 {
|
||||
t.Fatal("scheduler duplicated active job")
|
||||
}
|
||||
job, e := q.Claim(ctx, "fixture-periodic-worker", []string{s.SyncJobType()}, time.Now(), time.Minute)
|
||||
if e != nil || job == nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("auto-one", "automatic")}}
|
||||
if e = s.HandleSync(ctx, *job, func(context.Context) (Source, error) { return source, nil }); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = q.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if enqueued, e := s.EnqueueDue(ctx); e != nil || enqueued {
|
||||
t.Fatal("automatic sync ignored the persisted five-minute interval", e)
|
||||
}
|
||||
if _, e = p.Exec(ctx, `UPDATE qa_ops_mirror_state SET next_sync_at=now()-interval '1 second' WHERE tenant_key=$1`, s.tenant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if enqueued, e := s.EnqueueDue(ctx); e != nil || !enqueued {
|
||||
t.Fatal("due sync did not resume", e)
|
||||
}
|
||||
}
|
||||
func TestLocalMirrorSyncActivatesAndCheckpoints(t *testing.T) {
|
||||
p := mirrorFixture(t)
|
||||
s := NewStore(p, "fixture-sync")
|
||||
q := pg.NewStore(p)
|
||||
ctx := context.Background()
|
||||
job := claimMirrorJob(t, s, q, "fixture-first-sync")
|
||||
source := &fixtureSource{rows: []dobotaiops.MirrorRecord{fixtureEntry("one", "# first answer")}}
|
||||
factory := func(context.Context) (Source, error) { return source, nil }
|
||||
if e := s.HandleSync(ctx, *job, factory); e != nil {
|
||||
t.Fatal("first full sync did not activate", e)
|
||||
}
|
||||
state, e := s.GetSyncStatus(ctx)
|
||||
if e != nil || !state.Ready || state.Records != 1 || state.Revision != 1 || state.LastSuccessAt == nil || state.NextSyncAt == nil || state.NextSyncAt.Sub(*state.LastSuccessAt) < Interval-time.Second {
|
||||
t.Fatal("incomplete local sync state", e, state)
|
||||
}
|
||||
record, e := s.GetRecord(ctx, s.tenant, "one")
|
||||
if e != nil || record.Answer != "# first answer" {
|
||||
t.Fatal("committed local answer missing", e)
|
||||
}
|
||||
var inputs int
|
||||
if p.QueryRow(ctx, `SELECT count(*) FROM qa_ops_quality_inputs WHERE tenant_key=$1 AND payload IS NOT NULL`, s.tenant).Scan(&inputs) != nil || inputs != 1 {
|
||||
t.Fatal("quality evidence did not commit with mirror")
|
||||
}
|
||||
calls := source.calls
|
||||
if e = s.HandleSync(ctx, *job, factory); e != nil || source.calls != calls {
|
||||
t.Fatal("restart after commit fetched source twice", e)
|
||||
}
|
||||
if e = q.Complete(ctx, job.ID, job.LeaseOwner, time.Now()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -2,14 +2,17 @@ package qaopsorg
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"sort"
|
||||
)
|
||||
|
||||
type PersonAttribution struct {
|
||||
State string `json:"state"`
|
||||
PersonID string `json:"-"`
|
||||
Departments []string `json:"departments"`
|
||||
Region string `json:"region"`
|
||||
Name string `json:"name"`
|
||||
DepartmentIDs []string `json:"-"`
|
||||
State string `json:"state"`
|
||||
PersonID string `json:"-"`
|
||||
Departments []string `json:"departments"`
|
||||
Region string `json:"region"`
|
||||
}
|
||||
type Attribution struct {
|
||||
Metadata State
|
||||
@@ -17,6 +20,18 @@ type Attribution struct {
|
||||
unions map[string]string
|
||||
}
|
||||
|
||||
func (p *Attribution) Members() []PersonAttribution {
|
||||
result := []PersonAttribution{}
|
||||
if p == nil {
|
||||
return result
|
||||
}
|
||||
for _, person := range p.people {
|
||||
result = append(result, person)
|
||||
}
|
||||
sort.Slice(result, func(i, j int) bool { return result[i].PersonID < result[j].PersonID })
|
||||
return result
|
||||
}
|
||||
|
||||
func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
p := &Attribution{Metadata: state, people: map[string]PersonAttribution{}, unions: map[string]string{}}
|
||||
if state.State == "empty" {
|
||||
@@ -25,7 +40,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if state.State != "ready" || state.DirectoryID == "" {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
view, err := Preview(directory, state.Rules)
|
||||
view, err := PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
@@ -43,7 +58,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
regions[d.Region] = true
|
||||
}
|
||||
}
|
||||
item := PersonAttribution{State: "unassigned", PersonID: person.ID, Departments: []string{}}
|
||||
item := PersonAttribution{Name: person.Name, DepartmentIDs: append([]string{}, person.DepartmentIDs...), State: "unassigned", PersonID: person.ID, Departments: []string{}}
|
||||
for path := range paths {
|
||||
item.Departments = append(item.Departments, path)
|
||||
}
|
||||
@@ -51,7 +66,7 @@ func BuildAttribution(state State, directory Directory) (*Attribution, error) {
|
||||
if len(regions) == 1 {
|
||||
item.State = "matched"
|
||||
for region := range regions {
|
||||
item.Region = region
|
||||
item.Region = state.RegionLabel(region)
|
||||
}
|
||||
} else if len(regions) > 1 {
|
||||
item.State = "cross_region"
|
||||
@@ -97,6 +112,16 @@ func (p *Attribution) Resolve(staff, union string) PersonAttribution {
|
||||
}
|
||||
return none
|
||||
}
|
||||
func (s *Store) GetAttributionInTx(ctx context.Context, tx pgx.Tx) (*Attribution, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
state, directory, err := s.read(ctx, tx, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return BuildAttribution(state, directory)
|
||||
}
|
||||
func (s *Store) GetAttribution(ctx context.Context) (*Attribution, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
package qaopsorg
|
||||
|
||||
import "unicode/utf8"
|
||||
|
||||
// IDs are immutable mapping keys; names are editable labels. Existing keys remain
|
||||
// intact when migrating the historical four-region configuration.
|
||||
type RegionDefinition struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
func DefaultRegions() []RegionDefinition {
|
||||
result := make([]RegionDefinition, 0, len(RegionNames))
|
||||
for _, name := range RegionNames {
|
||||
result = append(result, RegionDefinition{ID: name, Name: name})
|
||||
}
|
||||
return result
|
||||
}
|
||||
func (s State) RegionDefinitions() []RegionDefinition {
|
||||
if s.Regions == nil {
|
||||
return DefaultRegions()
|
||||
}
|
||||
return s.Regions
|
||||
}
|
||||
func (s State) RegionLabels() []string {
|
||||
labels := []string{}
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
labels = append(labels, region.Name)
|
||||
}
|
||||
return labels
|
||||
}
|
||||
func (s State) RegionLabel(id string) string {
|
||||
for _, region := range s.RegionDefinitions() {
|
||||
if region.ID == id {
|
||||
return region.Name
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
func validRegions(regions []RegionDefinition) bool {
|
||||
if len(regions) > 100 {
|
||||
return false
|
||||
}
|
||||
reserved := map[string]bool{"unassigned": true, "cross_region": true, "unmatched": true, "identity_conflict": true, "no_identity": true, "directory_missing": true, "__proto__": true, "constructor": true, "prototype": true}
|
||||
ids, names := map[string]bool{}, map[string]bool{}
|
||||
for _, region := range regions {
|
||||
if !validID(region.ID) || !validID(region.Name) || !utf8.ValidString(region.ID) || !utf8.ValidString(region.Name) || reserved[region.ID] || reserved[region.Name] || ids[region.ID] || names[region.Name] {
|
||||
return false
|
||||
}
|
||||
ids[region.ID] = true
|
||||
names[region.Name] = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCustomRegionCatalogRejectsAmbiguousOrReservedDefinitions(t *testing.T) {
|
||||
for _, regions := range [][]RegionDefinition{
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "one", Name: "国外工业Amercia"}},
|
||||
{{ID: "one", Name: "国内教育"}, {ID: "two", Name: "国内教育"}},
|
||||
{{ID: "unassigned", Name: "区域"}}, {{ID: "one", Name: "cross_region"}},
|
||||
{{ID: "__proto__", Name: "区域"}}, {{ID: "one", Name: "constructor"}},
|
||||
{{ID: "one", Name: ""}}, {{ID: "one", Name: " 区域"}},
|
||||
} {
|
||||
if _, err := PreviewRegions(exampleDirectory(), nil, regions); err == nil {
|
||||
t.Fatal("invalid region catalog was accepted")
|
||||
}
|
||||
}
|
||||
if _, err := PreviewRegions(exampleDirectory(), []Rule{{DepartmentID: "sales", Region: "missing"}}, []RegionDefinition{{ID: "education", Name: "国内教育"}}); err == nil {
|
||||
t.Fatal("unknown mapping ID accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomRegionCatalogBindsStableIDAndRenamePreservesRules(t *testing.T) {
|
||||
directory := exampleDirectory()
|
||||
state := State{State: "ready", DirectoryID: "d", Rules: []Rule{}}
|
||||
var request SaveRequest
|
||||
if err := json.Unmarshal([]byte(`{"directory_id":"d","base_revision":"","regions":[{"id":"education","name":"国内教育"},{"id":"overseas","name":"国外工业Amercia"}],"rules":[{"department_id":"sales","region":"education"},{"department_id":"apac","region":"overseas"}]}`), &request); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
next, err := applyRequest(state, directory, request)
|
||||
if err != nil {
|
||||
t.Fatalf("custom business regions must not be rejected by the old four-name whitelist: %v", err)
|
||||
}
|
||||
if next.View.Regions["education"] != 1 || next.View.Regions["overseas"] != 1 || next.View.ConflictingPeople != 1 {
|
||||
t.Fatal("inheritance or stable-ID person dedup changed")
|
||||
}
|
||||
projection, err := BuildAttribution(next, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("attribution did not use the same catalog display name")
|
||||
}
|
||||
raw, _ := json.Marshal(request)
|
||||
var body map[string]any
|
||||
_ = json.Unmarshal(raw, &body)
|
||||
body["regions"].([]any)[1].(map[string]any)["name"] = "国外工业 EMEA"
|
||||
raw, _ = json.Marshal(body)
|
||||
_ = json.Unmarshal(raw, &request)
|
||||
renamed, err := applyRequest(next, directory, request)
|
||||
if err != nil || renamed.Rules[0].Region != next.Rules[0].Region {
|
||||
t.Fatal("renaming changed the stable mapping")
|
||||
}
|
||||
projection, err = BuildAttribution(renamed, directory)
|
||||
if err != nil || projection.Resolve("p2", "").Region != "国外工业 EMEA" {
|
||||
t.Fatal("renamed catalog not consumed by attribution")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package qaopsorg
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMembersKeepNamedAndUnnamedRosterPeopleWithoutRawIdentifiers(t *testing.T) {
|
||||
d := Directory{Departments: []Department{{ID: "root", Name: "fixture"}}, People: []Person{{ID: "private-a", Name: "<源端姓名>", UnionID: "private-union", DepartmentIDs: []string{"root"}}, {ID: "private-zero", DepartmentIDs: []string{"root"}}}}
|
||||
p, err := BuildAttribution(State{State: "ready", DirectoryID: "directory"}, d)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
members := p.Members()
|
||||
if len(members) != 2 {
|
||||
t.Fatal("zero-use roster member omitted")
|
||||
}
|
||||
if p.Resolve("private-a", "").Name != "<源端姓名>" || p.Resolve("private-zero", "").Name != "" {
|
||||
t.Fatal("display name lost or guessed")
|
||||
}
|
||||
raw, _ := json.Marshal(members)
|
||||
if strings.Contains(string(raw), "private-") || strings.Contains(string(raw), "department_ids") {
|
||||
t.Fatal("internal identifiers serialized")
|
||||
}
|
||||
d.People[0].Name = "bad\x00name"
|
||||
if _, err = BuildAttribution(State{State: "ready", DirectoryID: "directory"}, d); err == nil {
|
||||
t.Fatal("invalid display name accepted")
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ type Department struct {
|
||||
Name string `json:"name"`
|
||||
}
|
||||
type Person struct {
|
||||
Name string `json:"name,omitempty"`
|
||||
ID string `json:"id"`
|
||||
UnionID string `json:"union_id,omitempty"`
|
||||
DepartmentIDs []string `json:"department_ids"`
|
||||
@@ -45,12 +46,18 @@ type PreviewResult struct {
|
||||
|
||||
// Identity is department ID. Names and legacy keyword rules never decide ownership.
|
||||
func Preview(directory Directory, rules []Rule) (PreviewResult, error) {
|
||||
return PreviewRegions(directory, rules, DefaultRegions())
|
||||
}
|
||||
func PreviewRegions(directory Directory, rules []Rule, regions []RegionDefinition) (PreviewResult, error) {
|
||||
result := PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}, TotalPeople: len(directory.People)}
|
||||
if len(directory.Departments) == 0 || len(directory.Departments) > 20000 || len(directory.People) == 0 || len(directory.People) > 100000 || len(rules) > 20000 {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range RegionNames {
|
||||
result.Regions[region] = 0
|
||||
if !validRegions(regions) {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
for _, region := range regions {
|
||||
result.Regions[region.ID] = 0
|
||||
}
|
||||
departments := make(map[string]Department, len(directory.Departments))
|
||||
for _, d := range directory.Departments {
|
||||
@@ -107,7 +114,7 @@ func Preview(directory Directory, rules []Rule) (PreviewResult, error) {
|
||||
}
|
||||
people := map[string]bool{}
|
||||
for _, person := range directory.People {
|
||||
if !validID(person.ID) || people[person.ID] || len(person.DepartmentIDs) > 1000 {
|
||||
if !validID(person.ID) || people[person.ID] || len(person.DepartmentIDs) > 1000 || len(person.Name) > 1000 || strings.ContainsRune(person.Name, 0) {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
people[person.ID] = true
|
||||
|
||||
+32
-21
@@ -26,20 +26,22 @@ type Import struct {
|
||||
Directory Directory `json:"directory"`
|
||||
}
|
||||
type SaveRequest struct {
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
Regions []RegionDefinition `json:"regions,omitempty"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
BaseRevision string `json:"base_revision"`
|
||||
Rules []Rule `json:"rules"`
|
||||
}
|
||||
type State struct {
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
DirectorySyncedAt *time.Time `json:"directory_synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Rules []Rule `json:"rules"`
|
||||
View PreviewResult `json:"view"`
|
||||
Regions []RegionDefinition `json:"regions"`
|
||||
State string `json:"state"`
|
||||
DirectoryID string `json:"directory_id"`
|
||||
DirectorySource string `json:"directory_source"`
|
||||
DirectorySyncedAt *time.Time `json:"directory_synced_at"`
|
||||
RevisionID string `json:"revision_id"`
|
||||
UpdatedBy string `json:"updated_by"`
|
||||
UpdatedAt *time.Time `json:"updated_at"`
|
||||
Rules []Rule `json:"rules"`
|
||||
View PreviewResult `json:"view"`
|
||||
}
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
@@ -53,12 +55,14 @@ type orgQuerier interface {
|
||||
QueryRow(context.Context, string, ...any) pgx.Row
|
||||
}
|
||||
|
||||
const readStateSQL = `SELECT d.id,d.source,d.synced_at,d.payload,COALESCE(r.id,''),COALESCE(r.rules,'[]'::jsonb),COALESCE(r.updated_by,''),r.created_at
|
||||
const defaultRegionsJSON = `[{"id":"国内工业","name":"国内工业"},{"id":"APAC","name":"APAC"},{"id":"EMEA","name":"EMEA"},{"id":"America","name":"America"}]`
|
||||
|
||||
const readStateSQL = `SELECT d.id,d.source,d.synced_at,d.payload,COALESCE(r.id,''),COALESCE(r.rules,'[]'::jsonb),COALESCE(r.updated_by,''),r.created_at,COALESCE(r.region_definitions,'` + defaultRegionsJSON + `'::jsonb)
|
||||
FROM qa_ops_organization_state st JOIN qa_ops_directory_snapshots d ON d.tenant_key=st.tenant_key AND d.id=st.directory_id
|
||||
LEFT JOIN qa_ops_region_revisions r ON r.tenant_key=st.tenant_key AND r.id=st.revision_id WHERE st.tenant_key=$1`
|
||||
|
||||
func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Directory, error) {
|
||||
state := State{State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
state := State{Regions: DefaultRegions(), State: "empty", Rules: []Rule{}, View: PreviewResult{Departments: []DepartmentView{}, Regions: map[string]int{}, MissingDepartments: []string{}}}
|
||||
for _, r := range RegionNames {
|
||||
state.View.Regions[r] = 0
|
||||
}
|
||||
@@ -67,15 +71,15 @@ func (s *Store) read(ctx context.Context, q orgQuerier, lock bool) (State, Direc
|
||||
if lock {
|
||||
query += " FOR UPDATE OF st"
|
||||
}
|
||||
var payload, rules []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt)
|
||||
var payload, rules, regions []byte
|
||||
err := q.QueryRow(ctx, query, s.tenant).Scan(&state.DirectoryID, &state.DirectorySource, &state.DirectorySyncedAt, &payload, &state.RevisionID, &rules, &state.UpdatedBy, &state.UpdatedAt, ®ions)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return state, directory, nil
|
||||
}
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil {
|
||||
if err != nil || json.Unmarshal(payload, &directory) != nil || json.Unmarshal(rules, &state.Rules) != nil || json.Unmarshal(regions, &state.Regions) != nil || state.Regions == nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
state.View, err = Preview(directory, state.Rules)
|
||||
state.View, err = PreviewRegions(directory, state.Rules, state.RegionDefinitions())
|
||||
if err != nil {
|
||||
return State{}, directory, ErrUnavailable
|
||||
}
|
||||
@@ -106,7 +110,11 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
if request.DirectoryID != state.DirectoryID || request.BaseRevision != state.RevisionID {
|
||||
return State{}, ErrConflict
|
||||
}
|
||||
view, err := Preview(directory, request.Rules)
|
||||
regions := request.Regions
|
||||
if regions == nil {
|
||||
regions = state.RegionDefinitions()
|
||||
}
|
||||
view, err := PreviewRegions(directory, request.Rules, regions)
|
||||
if err != nil {
|
||||
return State{}, err
|
||||
}
|
||||
@@ -123,6 +131,7 @@ func applyRequest(state State, directory Directory, request SaveRequest) (State,
|
||||
}
|
||||
}
|
||||
state.View = view
|
||||
state.Regions = append([]RegionDefinition{}, regions...)
|
||||
state.Rules = append([]Rule{}, request.Rules...)
|
||||
sort.Slice(state.Rules, func(i, j int) bool { return state.Rules[i].DepartmentID < state.Rules[j].DepartmentID })
|
||||
return state, nil
|
||||
@@ -151,7 +160,9 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
sort.Slice(before, func(i, j int) bool { return before[i].DepartmentID < before[j].DepartmentID })
|
||||
oldJSON, _ := json.Marshal(before)
|
||||
newJSON, _ := json.Marshal(next.Rules)
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) {
|
||||
oldRegions, _ := json.Marshal(current.RegionDefinitions())
|
||||
newRegions, _ := json.Marshal(next.RegionDefinitions())
|
||||
if current.RevisionID != "" && string(oldJSON) == string(newJSON) && string(oldRegions) == string(newRegions) {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
@@ -164,7 +175,7 @@ func (s *Store) SaveRules(ctx context.Context, request SaveRequest, actor string
|
||||
next.RevisionID = "reg-" + hex.EncodeToString(nonce[:])
|
||||
next.UpdatedBy = actor
|
||||
var at time.Time
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by) VALUES($1,$2,$3,$4,$5) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor).Scan(&at); err != nil {
|
||||
if err = tx.QueryRow(ctx, `INSERT INTO qa_ops_region_revisions(tenant_key,id,directory_id,rules,updated_by,region_definitions) VALUES($1,$2,$3,$4,$5,$6) RETURNING created_at`, s.tenant, next.RevisionID, next.DirectoryID, newJSON, actor, newRegions).Scan(&at); err != nil {
|
||||
return State{}, ErrUnavailable
|
||||
}
|
||||
next.UpdatedAt = &at
|
||||
|
||||
@@ -134,6 +134,91 @@ func TestOrganizationStoreRoundTripAndOptimisticConflict(t *testing.T) {
|
||||
if err = pool.QueryRow(ctx, "SELECT count(*) FROM qa_ops_region_revisions WHERE tenant_key=$1", "fixture-tenant").Scan(&revisions); err != nil || revisions != 2 {
|
||||
t.Fatal("revision history changed unexpectedly")
|
||||
}
|
||||
|
||||
t.Run("custom catalog persists with the mapping and rename advances revision", func(t *testing.T) {
|
||||
custom := qaopsorg.NewStore(pool, "catalog-fixture")
|
||||
imported, e := custom.ReplaceDirectory(ctx, input)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
request := qaopsorg.SaveRequest{DirectoryID: imported.DirectoryID, Regions: []qaopsorg.RegionDefinition{{ID: "education", Name: "国内教育"}}, Rules: []qaopsorg.Rule{{DepartmentID: "a", Region: "education"}}}
|
||||
preview, e := custom.PreviewRules(ctx, request)
|
||||
if e != nil || preview.View.Regions["education"] != 1 {
|
||||
t.Fatal("custom preview failed", e)
|
||||
}
|
||||
unchanged, _ := custom.GetView(ctx)
|
||||
if unchanged.RevisionID != "" {
|
||||
t.Fatal("catalog preview wrote data")
|
||||
}
|
||||
saved, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
fresh, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer fresh.Close()
|
||||
read, e := qaopsorg.NewStore(fresh, "catalog-fixture").GetView(ctx)
|
||||
if e != nil || len(read.Regions) != 1 || read.Regions[0].Name != "国内教育" || read.Rules[0].Region != "education" {
|
||||
t.Fatal("catalog was not persisted with its rules", e)
|
||||
}
|
||||
request.BaseRevision = saved.RevisionID
|
||||
request.Regions[0].Name = "国外工业Amercia"
|
||||
renamed, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || renamed.RevisionID == saved.RevisionID {
|
||||
t.Fatal("rename did not create an atomic revision", e)
|
||||
}
|
||||
projection, e := custom.GetAttribution(ctx)
|
||||
if e != nil || projection.Resolve("u1", "").Region != "国外工业Amercia" {
|
||||
t.Fatal("renamed labels not shared by the read paths")
|
||||
}
|
||||
if _, e = custom.SaveRules(ctx, request, "stale-admin"); !errors.Is(e, qaopsorg.ErrConflict) {
|
||||
t.Fatal("rename allowed stale overwrite")
|
||||
}
|
||||
request.BaseRevision = renamed.RevisionID
|
||||
repeated, e := custom.SaveRules(ctx, request, "catalog-admin")
|
||||
if e != nil || repeated.RevisionID != renamed.RevisionID {
|
||||
t.Fatal("unchanged catalog appended another revision")
|
||||
}
|
||||
// Pin the catalog down test to migration 51, not a later additive feature.
|
||||
for {
|
||||
var latest int64
|
||||
if err := pool.QueryRow(ctx, "SELECT max(version) FROM schema_migrations").Scan(&latest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if latest <= 51 {
|
||||
break
|
||||
}
|
||||
if err := postgresstore.RollbackLatestMigration(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if e = postgresstore.RollbackLatestMigration(ctx, pool); e == nil {
|
||||
t.Fatal("down migration discarded a custom catalog")
|
||||
}
|
||||
if _, e = custom.GetView(ctx); e != nil {
|
||||
t.Fatal("refused down migration damaged last-good catalog")
|
||||
}
|
||||
for _, table := range []string{"qa_ops_organization_state", "qa_ops_region_revisions", "qa_ops_directory_snapshots"} {
|
||||
if _, e = pool.Exec(ctx, "DELETE FROM "+table+" WHERE tenant_key=$1", "catalog-fixture"); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
})
|
||||
// This test exercises migration 48, not whichever unrelated migration is latest.
|
||||
for {
|
||||
var latest int64
|
||||
if pool.QueryRow(ctx, "SELECT max(version) FROM schema_migrations").Scan(&latest) != nil {
|
||||
t.Fatal("migration version unavailable")
|
||||
}
|
||||
if latest <= 48 {
|
||||
break
|
||||
}
|
||||
if postgresstore.RollbackLatestMigration(ctx, pool) != nil {
|
||||
t.Fatal("could not reach organization migration")
|
||||
}
|
||||
}
|
||||
if err = postgresstore.RollbackLatestMigration(ctx, pool); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
var hashPattern = regexp.MustCompile(`^[a-f0-9]{64}$`)
|
||||
var noncePattern = regexp.MustCompile(`^[A-Za-z0-9_-]{16,128}$`)
|
||||
|
||||
func validText(s string, max int) bool {
|
||||
return utf8.ValidString(s) && utf8.RuneCountInString(s) <= max && !strings.ContainsRune(s, 0)
|
||||
}
|
||||
func validID(s string) bool { return strings.TrimSpace(s) != "" && validText(s, 256) }
|
||||
func canonical(raw json.RawMessage) (json.RawMessage, error) {
|
||||
if len(raw) == 0 {
|
||||
return json.RawMessage("null"), nil
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(raw))
|
||||
decoder.UseNumber()
|
||||
var v any
|
||||
if decoder.Decode(&v) != nil {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
var extra any
|
||||
if decoder.Decode(&extra) != io.EOF {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
out, err := json.Marshal(v)
|
||||
return out, err
|
||||
}
|
||||
func EvidenceFor(record dobotaiops.Record) (Evidence, error) {
|
||||
if !validID(record.ID) {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
refs, err := canonical(record.References)
|
||||
if err != nil {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
media, err := canonical(record.Media)
|
||||
if err != nil {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
// Keep only assessment inputs, never personnel or mutable feedback/organisation.
|
||||
payload, err := json.Marshal(struct {
|
||||
Version string `json:"version"`
|
||||
ID string `json:"id"`
|
||||
Status string `json:"status"`
|
||||
Question string `json:"question"`
|
||||
Answer string `json:"answer"`
|
||||
References json.RawMessage `json:"references"`
|
||||
Media json.RawMessage `json:"media"`
|
||||
}{"dobotai-2.0-dingtalk-quality-v1", record.ID, record.Status, record.Question, record.Answer, refs, media})
|
||||
if err != nil || len(payload) > 8<<20 {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
sum := sha256.Sum256(payload)
|
||||
hash := hex.EncodeToString(sum[:])
|
||||
if record.QualityInputHash != "" {
|
||||
if !hashPattern.MatchString(record.QualityInputHash) {
|
||||
return Evidence{}, ErrInvalid
|
||||
}
|
||||
hash = record.QualityInputHash
|
||||
}
|
||||
return Evidence{Hash: hash, Payload: payload, Record: record, Result: dobotaiops.CheckAnswerCoverage(record.Answer)}, nil
|
||||
}
|
||||
func Validate(r SaveRequest) error {
|
||||
if !hashPattern.MatchString(r.InputHash) || r.InputEpoch < 1 || r.BaseRevision < 0 || !noncePattern.MatchString(r.Nonce) || strings.TrimSpace(r.Reason) == "" || !validText(r.Reason, 4000) {
|
||||
return ErrInvalid
|
||||
}
|
||||
f := r.Fields
|
||||
validCoverage := false
|
||||
for _, s := range []string{"covered", "uncovered", "partial", "pending", "excluded"} {
|
||||
validCoverage = validCoverage || f.Coverage == s
|
||||
}
|
||||
if !validCoverage || (f.Correctness != "correct" && f.Correctness != "incorrect" && f.Correctness != "pending") {
|
||||
return ErrInvalid
|
||||
}
|
||||
if !validText(f.ProductCategory, 128) || !validText(f.ProblemType, 128) || !validText(f.RootCause, 2000) || !validText(f.ExclusionReason, 2000) {
|
||||
return ErrInvalid
|
||||
}
|
||||
if f.Correctness == "correct" && f.RootCause != "" || f.Coverage == "excluded" && strings.TrimSpace(f.ExclusionReason) == "" || f.Coverage != "excluded" && f.ExclusionReason != "" {
|
||||
return ErrInvalid
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func Project(hash string, epoch, revision int64, automatic Check, review *Review) View {
|
||||
view := View{InputHash: hash, InputEpoch: epoch, Revision: revision, State: "unreviewed", Automatic: automatic, LatestReview: review, Effective: Fields{Coverage: automatic.Result.Verdict}}
|
||||
if review == nil {
|
||||
return view
|
||||
}
|
||||
view.State = "stale"
|
||||
if review.InputEpoch == epoch && review.InputHash == hash {
|
||||
view.State = "reviewed"
|
||||
view.Effective = review.Fields
|
||||
}
|
||||
return view
|
||||
}
|
||||
func Summarize(views map[string]View) Summary {
|
||||
result := Summary{Total: len(views), Rates: ComputeRates(views)}
|
||||
for _, v := range views {
|
||||
switch v.State {
|
||||
case "reviewed":
|
||||
result.Reviewed++
|
||||
if v.Effective.Coverage == "pending" || v.Effective.Correctness == "pending" {
|
||||
result.PendingConfirmation++
|
||||
}
|
||||
case "stale":
|
||||
result.Stale++
|
||||
default:
|
||||
result.Unreviewed++
|
||||
}
|
||||
if v.Automatic.Result.Verdict == "uncovered" {
|
||||
result.RuleUncovered++
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid quality request")
|
||||
var ErrConflict = errors.New("quality input or review revision changed")
|
||||
var ErrUnavailable = errors.New("quality store unavailable")
|
||||
var ErrNotFound = errors.New("quality input snapshot not found")
|
||||
var ErrSnapshotMissing = errors.New("only quality metadata was observed for this input")
|
||||
|
||||
type Fields struct {
|
||||
Coverage string `json:"coverage"`
|
||||
Correctness string `json:"correctness"`
|
||||
ProductCategory string `json:"product_category"`
|
||||
ProblemType string `json:"problem_type"`
|
||||
RootCause string `json:"root_cause"`
|
||||
ExclusionReason string `json:"exclusion_reason"`
|
||||
}
|
||||
type SaveRequest struct {
|
||||
InputHash string `json:"input_hash"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
BaseRevision int64 `json:"base_revision"`
|
||||
Nonce string `json:"nonce"`
|
||||
Fields Fields `json:"fields"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
type Review struct {
|
||||
Revision int64 `json:"revision"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
InputHash string `json:"input_hash"`
|
||||
Fields Fields `json:"fields"`
|
||||
Reason string `json:"reason"`
|
||||
Reviewer string `json:"reviewer"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
type Check struct {
|
||||
InputAvailable bool `json:"input_available"`
|
||||
ID int64 `json:"id"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
InputHash string `json:"input_hash"`
|
||||
Result dobotaiops.CoverageCheck `json:"result"`
|
||||
Source dobotaiops.SourceCoverage `json:"source"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
type View struct {
|
||||
InputHash string `json:"input_hash"`
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
Revision int64 `json:"revision"`
|
||||
State string `json:"state"`
|
||||
Automatic Check `json:"automatic"`
|
||||
LatestReview *Review `json:"latest_review"`
|
||||
Effective Fields `json:"effective"`
|
||||
}
|
||||
type History struct {
|
||||
Reviews []Review `json:"reviews"`
|
||||
Checks []Check `json:"checks"`
|
||||
NextReview int64 `json:"next_review"`
|
||||
NextCheck int64 `json:"next_check"`
|
||||
}
|
||||
type Summary struct {
|
||||
Rates Rates `json:"rates"`
|
||||
Total int `json:"total"`
|
||||
Reviewed int `json:"reviewed"`
|
||||
Unreviewed int `json:"unreviewed"`
|
||||
Stale int `json:"stale"`
|
||||
PendingConfirmation int `json:"pending_confirmation"`
|
||||
RuleUncovered int `json:"rule_uncovered"`
|
||||
}
|
||||
type Receipt struct {
|
||||
View View `json:"view"`
|
||||
SavedRevision int64 `json:"saved_revision"`
|
||||
Replayed bool `json:"replayed"`
|
||||
}
|
||||
type Evidence struct {
|
||||
Result dobotaiops.CoverageCheck
|
||||
Hash string
|
||||
Payload json.RawMessage
|
||||
Record dobotaiops.Record
|
||||
}
|
||||
|
||||
type Snapshot struct {
|
||||
InputEpoch int64 `json:"input_epoch"`
|
||||
InputHash string `json:"input_hash"`
|
||||
Payload json.RawMessage `json:"payload"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
tenant string
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool, tenant string) *Store { return &Store{pool: pool, tenant: tenant} }
|
||||
@@ -0,0 +1,73 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestEvidenceBindsQualityInputsNotPeopleFeedbackOrJSONKeyOrder(t *testing.T) {
|
||||
record := dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例问题", Answer: "有暂无已发布但存在引用", References: json.RawMessage(`[{"b":2,"a":1}]`), Media: json.RawMessage(`[]`)}
|
||||
a, err := EvidenceFor(record)
|
||||
if err != nil || len(a.Hash) != 64 || !strings.Contains(string(a.Payload), record.Answer) {
|
||||
t.Fatal("quality inputs not snapshotted")
|
||||
}
|
||||
record.Asker = "another-person"
|
||||
record.Department = "changed"
|
||||
record.Feedback.Up = 10
|
||||
record.References = json.RawMessage(`[{"a":1,"b":2}]`)
|
||||
b, _ := EvidenceFor(record)
|
||||
if b.Hash != a.Hash {
|
||||
t.Fatal("irrelevant identity/feedback or JSON object ordering invalidated review")
|
||||
}
|
||||
record.Answer = "原答案变更"
|
||||
b, _ = EvidenceFor(record)
|
||||
if b.Hash == a.Hash {
|
||||
t.Fatal("answer change undetected")
|
||||
}
|
||||
}
|
||||
func TestHumanProjectionKeepsRuleAndStalesObservedInputChanges(t *testing.T) {
|
||||
automatic := Check{Result: dobotaiops.CheckAnswerCoverage("暂无已发布"), InputEpoch: 2, InputHash: strings.Repeat("a", 64)}
|
||||
review := &Review{InputEpoch: 1, InputHash: automatic.InputHash, Fields: Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "MG400"}}
|
||||
view := Project(automatic.InputHash, 2, 1, automatic, review)
|
||||
if view.State != "stale" || view.Effective.Coverage != "uncovered" || view.Effective.Correctness != "" {
|
||||
t.Fatal("old conclusion remained effective after input epoch changed")
|
||||
}
|
||||
review.InputEpoch = 2
|
||||
view = Project(automatic.InputHash, 2, 1, automatic, review)
|
||||
if view.State != "reviewed" || view.Effective.Coverage != "covered" || view.Automatic.Result.Verdict != "uncovered" {
|
||||
t.Fatal("human and immutable rule not separated")
|
||||
}
|
||||
summary := Summarize(map[string]View{"a": view, "b": Project(automatic.InputHash, 3, 1, automatic, review), "c": Project(automatic.InputHash, 1, 0, automatic, nil)})
|
||||
if summary.Total != 3 || summary.Reviewed != 1 || summary.Stale != 1 || summary.Unreviewed != 1 || summary.PendingConfirmation != 0 {
|
||||
t.Fatal("quality counts invent rates or unknown judgments")
|
||||
}
|
||||
}
|
||||
func TestReviewRequiresExplicitOutcomesAndEvidence(t *testing.T) {
|
||||
valid := SaveRequest{InputHash: strings.Repeat("a", 64), InputEpoch: 1, Nonce: strings.Repeat("n", 32), Fields: Fields{Coverage: "uncovered", Correctness: "pending"}, Reason: "人工核对引用与答案,证据不足"}
|
||||
if Validate(valid) != nil {
|
||||
t.Fatal("valid review rejected")
|
||||
}
|
||||
for _, field := range []string{"reason", "hash", "coverage", "correctness", "root", "exclusion"} {
|
||||
bad := valid
|
||||
switch field {
|
||||
case "reason":
|
||||
bad.Reason = " "
|
||||
case "hash":
|
||||
bad.InputHash = "malformed"
|
||||
case "coverage":
|
||||
bad.Fields.Coverage = ""
|
||||
case "correctness":
|
||||
bad.Fields.Correctness = ""
|
||||
case "root":
|
||||
bad.Fields.Correctness = "correct"
|
||||
bad.Fields.RootCause = "知识缺失"
|
||||
case "exclusion":
|
||||
bad.Fields.Coverage = "excluded"
|
||||
}
|
||||
if Validate(bad) == nil {
|
||||
t.Fatal("invalid review accepted", field)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package qaopsquality
|
||||
|
||||
type Rate struct {
|
||||
Numerator int `json:"numerator"`
|
||||
Denominator int `json:"denominator"`
|
||||
Percent *float64 `json:"percent"`
|
||||
}
|
||||
type RateBreakdown struct {
|
||||
Covered int `json:"covered"`
|
||||
Uncovered int `json:"uncovered"`
|
||||
Partial int `json:"partial"`
|
||||
Pending int `json:"pending"`
|
||||
Unassessed int `json:"unassessed"`
|
||||
Excluded int `json:"excluded"`
|
||||
Stale int `json:"stale"`
|
||||
CoveredCorrect int `json:"covered_correct"`
|
||||
CoveredIncorrect int `json:"covered_incorrect"`
|
||||
CoveredPending int `json:"covered_pending"`
|
||||
CoveredUnassessed int `json:"covered_unassessed"`
|
||||
}
|
||||
type Rates struct {
|
||||
PolicyVersion string `json:"policy_version"`
|
||||
Coverage Rate `json:"coverage"`
|
||||
Correctness Rate `json:"correctness"`
|
||||
Breakdown RateBreakdown `json:"breakdown"`
|
||||
}
|
||||
|
||||
func ComputeRates(views map[string]View) Rates {
|
||||
out := Rates{PolicyVersion: "quality-rates-human-first-v1"}
|
||||
b := &out.Breakdown
|
||||
for _, v := range views {
|
||||
if v.State == "stale" {
|
||||
b.Stale++
|
||||
continue
|
||||
}
|
||||
switch v.Effective.Coverage {
|
||||
case "covered":
|
||||
b.Covered++
|
||||
switch v.Effective.Correctness {
|
||||
case "correct":
|
||||
b.CoveredCorrect++
|
||||
case "incorrect":
|
||||
b.CoveredIncorrect++
|
||||
case "pending":
|
||||
b.CoveredPending++
|
||||
default:
|
||||
b.CoveredUnassessed++
|
||||
}
|
||||
case "uncovered":
|
||||
b.Uncovered++
|
||||
case "partial":
|
||||
b.Partial++
|
||||
case "pending":
|
||||
b.Pending++
|
||||
case "excluded":
|
||||
b.Excluded++
|
||||
default:
|
||||
b.Unassessed++
|
||||
}
|
||||
}
|
||||
out.Coverage = makeRate(b.Covered, b.Covered+b.Uncovered+b.Partial)
|
||||
out.Correctness = makeRate(b.CoveredCorrect, b.CoveredCorrect+b.CoveredIncorrect)
|
||||
return out
|
||||
}
|
||||
func makeRate(numerator, denominator int) Rate {
|
||||
r := Rate{Numerator: numerator, Denominator: denominator}
|
||||
if denominator > 0 {
|
||||
p := 100 * float64(numerator) / float64(denominator)
|
||||
r.Percent = &p
|
||||
}
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"math"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestQualityRatesUseEffectiveCurrentConclusionsAndExplicitDenominators(t *testing.T) {
|
||||
views := map[string]View{}
|
||||
for i, fields := range []Fields{{Coverage: "covered", Correctness: "correct"}, {Coverage: "covered", Correctness: "incorrect"}, {Coverage: "covered", Correctness: "pending"}, {Coverage: "uncovered"}, {Coverage: "partial", Correctness: "correct"}, {Coverage: "pending", Correctness: "correct"}, {}, {Coverage: "excluded", Correctness: "pending"}, {Coverage: "covered", Correctness: "correct"}, {Coverage: "covered"}} {
|
||||
state := "reviewed"
|
||||
if i == 3 || i == 6 {
|
||||
state = "unreviewed"
|
||||
}
|
||||
if i == 8 {
|
||||
state = "stale"
|
||||
}
|
||||
views[string(rune('a'+i))] = View{State: state, Effective: fields, Automatic: Check{Result: dobotaiops.CheckAnswerCoverage("暂无已发布")}}
|
||||
}
|
||||
r := ComputeRates(views)
|
||||
if r.PolicyVersion != "quality-rates-human-first-v1" || r.Coverage.Numerator != 4 || r.Coverage.Denominator != 6 || r.Correctness.Numerator != 1 || r.Correctness.Denominator != 2 {
|
||||
t.Fatal("effective decisions, partial or exclusion scopes incorrect", r)
|
||||
}
|
||||
if r.Coverage.Percent == nil || math.Abs(*r.Coverage.Percent-100*float64(4)/6) > 1e-10 || r.Correctness.Percent == nil || *r.Correctness.Percent != 50 {
|
||||
t.Fatal("ratio value disagrees with raw counts")
|
||||
}
|
||||
b := r.Breakdown
|
||||
if b.Covered+b.Uncovered+b.Partial+b.Pending+b.Unassessed+b.Excluded+b.Stale != len(views) || b.CoveredCorrect+b.CoveredIncorrect+b.CoveredPending+b.CoveredUnassessed != b.Covered {
|
||||
t.Fatal("denominator breakdown not conserved")
|
||||
}
|
||||
if got := Summarize(views); got.Rates.Coverage.Denominator != 6 {
|
||||
t.Fatal("scope summary did not consume the one shared calculation")
|
||||
}
|
||||
}
|
||||
func TestQualityRatesEmptyScopeHasNullPercent(t *testing.T) {
|
||||
r := ComputeRates(map[string]View{})
|
||||
raw, _ := json.Marshal(r)
|
||||
if r.Coverage.Percent != nil || r.Correctness.Percent != nil || strings.Count(string(raw), `"percent":null`) != 2 {
|
||||
t.Fatal("zero denominator fabricated zero or full rate")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
)
|
||||
|
||||
// ReadViews projects quality already observed by mirror activation. It performs
|
||||
// one SELECT, never inserts inputs/checks or advances an observation epoch.
|
||||
type viewQuerier interface {
|
||||
Query(context.Context, string, ...any) (pgx.Rows, error)
|
||||
}
|
||||
|
||||
func (s *Store) ReadViews(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
return s.readViews(ctx, s.pool, keys)
|
||||
}
|
||||
|
||||
// ReadViewsInTx shares the caller's repeatable-read snapshot with mirror and organization metadata.
|
||||
func (s *Store) ReadViewsInTx(ctx context.Context, tx pgx.Tx, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
return s.readViews(ctx, tx, keys)
|
||||
}
|
||||
func (s *Store) readViews(ctx context.Context, q viewQuerier, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if len(keys) > 5000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
expected := map[string]string{}
|
||||
ids := make([]string, 0, len(keys))
|
||||
for _, k := range keys {
|
||||
if !validID(k.ID) || !hashPattern.MatchString(k.InputHash) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
if old, exists := expected[k.ID]; exists {
|
||||
if old != k.InputHash {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
continue
|
||||
}
|
||||
expected[k.ID] = k.InputHash
|
||||
ids = append(ids, k.ID)
|
||||
}
|
||||
out := map[string]View{}
|
||||
if len(ids) == 0 {
|
||||
return out, nil
|
||||
}
|
||||
rows, e := q.Query(ctx, `SELECT h.record_id,h.input_hash,h.input_epoch,h.review_revision,`+checkObject+`::text,COALESCE((SELECT `+reviewObject+` FROM qa_ops_quality_reviews r WHERE r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision),'null'::jsonb)::text FROM qa_ops_quality_records h JOIN qa_ops_quality_inputs i ON i.tenant_key=h.tenant_key AND i.record_id=h.record_id AND i.input_epoch=h.input_epoch JOIN qa_ops_quality_checks c ON c.tenant_key=h.tenant_key AND c.record_id=h.record_id AND c.input_epoch=h.input_epoch AND c.rule_version=$3 WHERE h.tenant_key=$1 AND h.record_id=ANY($2::text[])`, s.tenant, ids, dobotaiops.CoverageRuleVersion)
|
||||
if e != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var id, hash, checkRaw, reviewRaw string
|
||||
var epoch, revision int64
|
||||
if rows.Scan(&id, &hash, &epoch, &revision, &checkRaw, &reviewRaw) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if expected[id] != hash {
|
||||
return nil, ErrConflict
|
||||
}
|
||||
var automatic Check
|
||||
var review *Review
|
||||
if json.Unmarshal([]byte(checkRaw), &automatic) != nil || json.Unmarshal([]byte(reviewRaw), &review) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
out[id] = Project(hash, epoch, revision, automatic, review)
|
||||
}
|
||||
if rows.Err() != nil || len(out) != len(ids) {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
package qaopsquality
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
"sort"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (s *Store) Columns(ctx context.Context, keys []dobotaiops.QualityKey) ([]string, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
if len(keys) > 100000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
for _, key := range keys {
|
||||
if !validID(key.ID) || !hashPattern.MatchString(key.InputHash) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
raw, err := json.Marshal(keys)
|
||||
if err != nil {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
var coverage, correctness, product, problem, root bool
|
||||
err = s.pool.QueryRow(ctx, `SELECT COALESCE(bool_or(r.fields->>'coverage'<>''),false),COALESCE(bool_or(r.fields->>'correctness'<>''),false),COALESCE(bool_or(r.fields->>'product_category'<>''),false),COALESCE(bool_or(r.fields->>'problem_type'<>''),false),COALESCE(bool_or(r.fields->>'root_cause'<>''),false) FROM jsonb_to_recordset($2::jsonb) k(id text,input_hash text) JOIN qa_ops_quality_records h ON h.tenant_key=$1 AND h.record_id=k.id AND h.input_hash=k.input_hash JOIN qa_ops_quality_reviews r ON r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision AND r.input_epoch=h.input_epoch`, s.tenant, raw).Scan(&coverage, &correctness, &product, &problem, &root)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
out := []string{}
|
||||
for _, c := range []struct {
|
||||
key string
|
||||
yes bool
|
||||
}{{"coverage", coverage}, {"is_correct", correctness}, {"product_category", product}, {"problem_type", problem}, {"root_cause", root}} {
|
||||
if c.yes {
|
||||
out = append(out, c.key)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
func (s *Store) Snapshot(ctx context.Context, id string, epoch int64) (Snapshot, error) {
|
||||
if !s.available() {
|
||||
return Snapshot{}, ErrUnavailable
|
||||
}
|
||||
if !validID(id) || epoch < 1 {
|
||||
return Snapshot{}, ErrInvalid
|
||||
}
|
||||
var value Snapshot
|
||||
value.InputEpoch = epoch
|
||||
err := s.pool.QueryRow(ctx, `SELECT input_hash,payload,created_at FROM qa_ops_quality_inputs WHERE tenant_key=$1 AND record_id=$2 AND input_epoch=$3`, s.tenant, id, epoch).Scan(&value.InputHash, &value.Payload, &value.CreatedAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return Snapshot{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return Snapshot{}, ErrUnavailable
|
||||
}
|
||||
if len(value.Payload) == 0 {
|
||||
return Snapshot{}, ErrSnapshotMissing
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
func (s *Store) available() bool { return s != nil && s.pool != nil && validID(s.tenant) }
|
||||
func (s *Store) observeLocked(ctx context.Context, tx pgx.Tx, e Evidence) error {
|
||||
id := e.Record.ID
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_records(tenant_key,record_id) VALUES($1,$2) ON CONFLICT DO NOTHING`, s.tenant, id); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
var previous string
|
||||
var epoch int64
|
||||
var observedAt *time.Time
|
||||
if tx.QueryRow(ctx, `SELECT input_hash,input_epoch,observed_at FROM qa_ops_quality_records WHERE tenant_key=$1 AND record_id=$2 FOR UPDATE`, s.tenant, id).Scan(&previous, &epoch, &observedAt) != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
// Source transaction time orders concurrent page/detail/scope observations.
|
||||
// A late different input is rejected, never projected against a newer answer.
|
||||
if observedAt != nil && !e.Record.QualityObservedAt.IsZero() && e.Record.QualityObservedAt.Before(*observedAt) && previous != e.Hash {
|
||||
return ErrConflict
|
||||
}
|
||||
if !e.Record.QualityObservedAt.IsZero() {
|
||||
if _, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET observed_at=$3 WHERE tenant_key=$1 AND record_id=$2 AND(observed_at IS NULL OR observed_at<$3)`, s.tenant, id, e.Record.QualityObservedAt); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
var payload any
|
||||
if len(e.Payload) > 0 {
|
||||
payload = e.Payload
|
||||
}
|
||||
if previous != e.Hash {
|
||||
epoch++
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_inputs(tenant_key,record_id,input_epoch,input_hash,payload) VALUES($1,$2,$3,$4,$5)`, s.tenant, id, epoch, e.Hash, payload); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET input_hash=$3,input_epoch=$4 WHERE tenant_key=$1 AND record_id=$2`, s.tenant, id, e.Hash, epoch)
|
||||
if err != nil || tag.RowsAffected() != 1 {
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
if payload != nil {
|
||||
if _, err := tx.Exec(ctx, `UPDATE qa_ops_quality_inputs SET payload=$4 WHERE tenant_key=$1 AND record_id=$2 AND input_epoch=$3 AND payload IS NULL`, s.tenant, id, epoch, payload); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
}
|
||||
automatic, _ := json.Marshal(e.Result)
|
||||
source, _ := json.Marshal(e.Record.SourceCoverage)
|
||||
if _, err := tx.Exec(ctx, `INSERT INTO qa_ops_quality_checks(tenant_key,record_id,input_epoch,rule_version,result,source) VALUES($1,$2,$3,$4,$5,$6) ON CONFLICT(tenant_key,record_id,input_epoch,rule_version) DO NOTHING`, s.tenant, id, epoch, dobotaiops.CoverageRuleVersion, automatic, source); err != nil {
|
||||
return ErrUnavailable
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
const checkObject = `jsonb_build_object('id',c.id,'input_epoch',c.input_epoch,'input_hash',i.input_hash,'result',c.result,'source',c.source,'created_at',c.created_at,'input_available',i.payload IS NOT NULL)`
|
||||
const reviewObject = `jsonb_build_object('revision',r.revision,'input_epoch',r.input_epoch,'input_hash',r.input_hash,'fields',r.fields,'reason',r.reason,'reviewer',r.reviewer,'created_at',r.created_at)`
|
||||
|
||||
func (s *Store) view(ctx context.Context, tx pgx.Tx, id string) (View, error) {
|
||||
var hash, checkRaw, reviewRaw string
|
||||
var epoch, revision int64
|
||||
err := tx.QueryRow(ctx, `SELECT h.input_hash,h.input_epoch,h.review_revision,`+checkObject+`::text,COALESCE((SELECT `+reviewObject+` FROM qa_ops_quality_reviews r WHERE r.tenant_key=h.tenant_key AND r.record_id=h.record_id AND r.revision=h.review_revision),'null'::jsonb)::text FROM qa_ops_quality_records h JOIN qa_ops_quality_inputs i ON i.tenant_key=h.tenant_key AND i.record_id=h.record_id AND i.input_epoch=h.input_epoch JOIN qa_ops_quality_checks c ON c.tenant_key=h.tenant_key AND c.record_id=h.record_id AND c.input_epoch=h.input_epoch AND c.rule_version=$3 WHERE h.tenant_key=$1 AND h.record_id=$2`, s.tenant, id, dobotaiops.CoverageRuleVersion).Scan(&hash, &epoch, &revision, &checkRaw, &reviewRaw)
|
||||
var automatic Check
|
||||
var review *Review
|
||||
if err != nil || json.Unmarshal([]byte(checkRaw), &automatic) != nil || json.Unmarshal([]byte(reviewRaw), &review) != nil {
|
||||
return View{}, ErrUnavailable
|
||||
}
|
||||
return Project(hash, epoch, revision, automatic, review), nil
|
||||
}
|
||||
|
||||
// ObserveRecordsInTx makes mirror activation and review invalidation one commit.
|
||||
// Only the caller owns commit/rollback; no remote I/O occurs while these locks are held.
|
||||
func (s *Store) ObserveRecordsInTx(ctx context.Context, tx pgx.Tx, records []dobotaiops.Record) error {
|
||||
if !s.available() || tx == nil || len(records) > 100 {
|
||||
return ErrInvalid
|
||||
}
|
||||
items := make([]Evidence, 0, len(records))
|
||||
size := 0
|
||||
for _, r := range records {
|
||||
e, err := EvidenceFor(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
size += len(e.Payload)
|
||||
if size > 32<<20 {
|
||||
return ErrInvalid
|
||||
}
|
||||
items = append(items, e)
|
||||
}
|
||||
sort.Slice(items, func(i, j int) bool { return items[i].Record.ID < items[j].Record.ID })
|
||||
for _, e := range items {
|
||||
if err := s.observeLocked(ctx, tx, e); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *Store) Observe(ctx context.Context, records []dobotaiops.Record) (map[string]View, error) {
|
||||
if len(records) > 5000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
items := make([]Evidence, 0, len(records))
|
||||
for _, record := range records {
|
||||
e, err := EvidenceFor(record)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, e)
|
||||
}
|
||||
return s.observeEvidence(ctx, items)
|
||||
}
|
||||
func (s *Store) ObserveKeys(ctx context.Context, keys []dobotaiops.QualityKey) (map[string]View, error) {
|
||||
if len(keys) > 5000 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
items := make([]Evidence, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
if !validID(key.ID) || !hashPattern.MatchString(key.InputHash) {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
items = append(items, Evidence{Hash: key.InputHash, Record: dobotaiops.Record{ID: key.ID, SourceCoverage: key.Source, QualityObservedAt: key.ObservedAt}, Result: dobotaiops.CheckMarkerCoverage(key.Marker)})
|
||||
}
|
||||
return s.observeEvidence(ctx, items)
|
||||
}
|
||||
func (s *Store) observeEvidence(ctx context.Context, items []Evidence) (map[string]View, error) {
|
||||
if !s.available() {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
evidence := map[string]Evidence{}
|
||||
ids := []string{}
|
||||
bytes := 0
|
||||
for _, e := range items {
|
||||
id := e.Record.ID
|
||||
if old, ok := evidence[id]; ok {
|
||||
if old.Hash != e.Hash || old.Result != e.Result {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
continue
|
||||
}
|
||||
evidence[id] = e
|
||||
ids = append(ids, id)
|
||||
bytes += len(e.Payload)
|
||||
if bytes > 32<<20 {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
}
|
||||
sort.Strings(ids)
|
||||
result := map[string]View{}
|
||||
if len(ids) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
for _, id := range ids {
|
||||
if err = s.observeLocked(ctx, tx, evidence[id]); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := s.view(ctx, tx, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[id] = v
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return nil, ErrUnavailable
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
func (s *Store) Save(ctx context.Context, record dobotaiops.Record, request SaveRequest, actor string) (Receipt, error) {
|
||||
if !s.available() {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
if Validate(request) != nil || !validID(actor) {
|
||||
return Receipt{}, ErrInvalid
|
||||
}
|
||||
e, err := EvidenceFor(record)
|
||||
if err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
payload, _ := json.Marshal(request)
|
||||
sum := sha256.Sum256(payload)
|
||||
requestHash := hex.EncodeToString(sum[:])
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
defer tx.Rollback(context.Background())
|
||||
if err = s.observeLocked(ctx, tx, e); err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
var existingHash, existingActor string
|
||||
var savedRevision int64
|
||||
err = tx.QueryRow(ctx, `SELECT request_hash,reviewer,revision FROM qa_ops_quality_reviews WHERE tenant_key=$1 AND record_id=$2 AND nonce=$3`, s.tenant, record.ID, request.Nonce).Scan(&existingHash, &existingActor, &savedRevision)
|
||||
replay := err == nil
|
||||
if err != nil && !errors.Is(err, pgx.ErrNoRows) {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
current, err := s.view(ctx, tx, record.ID)
|
||||
if err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
if replay {
|
||||
if existingHash != requestHash || existingActor != actor {
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
} else {
|
||||
if current.InputHash != request.InputHash || current.InputEpoch != request.InputEpoch || current.Revision != request.BaseRevision {
|
||||
if tx.Commit(ctx) != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
savedRevision = current.Revision + 1
|
||||
fields, _ := json.Marshal(request.Fields)
|
||||
if _, err = tx.Exec(ctx, `INSERT INTO qa_ops_quality_reviews(tenant_key,record_id,revision,input_epoch,input_hash,fields,reason,reviewer,nonce,request_hash) VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10)`, s.tenant, record.ID, savedRevision, current.InputEpoch, current.InputHash, fields, request.Reason, actor, request.Nonce, requestHash); err != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
tag, err := tx.Exec(ctx, `UPDATE qa_ops_quality_records SET review_revision=$3 WHERE tenant_key=$1 AND record_id=$2`, s.tenant, record.ID, savedRevision)
|
||||
if err != nil || tag.RowsAffected() != 1 {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
current, err = s.view(ctx, tx, record.ID)
|
||||
if err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return Receipt{}, ErrUnavailable
|
||||
}
|
||||
return Receipt{View: current, SavedRevision: savedRevision, Replayed: replay}, nil
|
||||
}
|
||||
func (s *Store) History(ctx context.Context, id string, reviewBefore, checkBefore int64) (History, error) {
|
||||
result := History{Reviews: []Review{}, Checks: []Check{}}
|
||||
if !s.available() {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
if !validID(id) || reviewBefore < 0 || checkBefore < 0 {
|
||||
return result, ErrInvalid
|
||||
}
|
||||
rows, err := s.pool.Query(ctx, `SELECT `+reviewObject+`::text FROM qa_ops_quality_reviews r WHERE tenant_key=$1 AND record_id=$2 AND ($3::bigint=0 OR revision<$3) ORDER BY revision DESC LIMIT 21`, s.tenant, id, reviewBefore)
|
||||
if err != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var value Review
|
||||
if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &value) != nil {
|
||||
rows.Close()
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
result.Reviews = append(result.Reviews, value)
|
||||
}
|
||||
err = rows.Err()
|
||||
rows.Close()
|
||||
if err != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
if len(result.Reviews) > 20 {
|
||||
result.Reviews = result.Reviews[:20]
|
||||
result.NextReview = result.Reviews[19].Revision
|
||||
}
|
||||
rows, err = s.pool.Query(ctx, `SELECT `+checkObject+`::text FROM qa_ops_quality_checks c JOIN qa_ops_quality_inputs i USING(tenant_key,record_id,input_epoch) WHERE c.tenant_key=$1 AND c.record_id=$2 AND ($3::bigint=0 OR c.id<$3) ORDER BY c.id DESC LIMIT 21`, s.tenant, id, checkBefore)
|
||||
if err != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var raw string
|
||||
var value Check
|
||||
if rows.Scan(&raw) != nil || json.Unmarshal([]byte(raw), &value) != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
result.Checks = append(result.Checks, value)
|
||||
}
|
||||
if rows.Err() != nil {
|
||||
return result, ErrUnavailable
|
||||
}
|
||||
if len(result.Checks) > 20 {
|
||||
result.Checks = result.Checks[:20]
|
||||
result.NextCheck = result.Checks[19].ID
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -0,0 +1,219 @@
|
||||
package qaopsquality_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"knowledge-governance/internal/dobotaiops"
|
||||
pg "knowledge-governance/internal/platform/postgres"
|
||||
"knowledge-governance/internal/qaopsquality"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestQualityStoreImmutableHistoryReplayConcurrencyAndStaleness(t *testing.T) {
|
||||
dsn := os.Getenv("KG_QAOPS_QUALITY_TEST_DSN")
|
||||
if dsn == "" {
|
||||
t.Skip("explicit disposable quality DB required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || u.Hostname() != "127.0.0.1" || !strings.HasPrefix(u.Path, "/kg_qaops_quality_test_") || os.Getenv("KG_QAOPS_QUALITY_TEST_ISOLATED") != "1" {
|
||||
t.Fatal("refusing shared quality database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal("fixture connection failed")
|
||||
}
|
||||
defer pool.Close()
|
||||
if e = pg.ApplyMigrations(ctx, pool); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
store := qaopsquality.NewStore(pool, "fixture-tenant")
|
||||
record := dobotaiops.Record{ID: "fixture-turn", Status: "succeeded", Question: "示例", Answer: "暂无已发布", AskedAt: time.Now()}
|
||||
views, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil {
|
||||
t.Fatal("source observation not persisted", e)
|
||||
}
|
||||
first := views[record.ID]
|
||||
again, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil || again[record.ID].Automatic.ID != first.Automatic.ID {
|
||||
t.Fatal("repeated GET duplicated immutable checks")
|
||||
}
|
||||
metaKey := dobotaiops.QualityKey{ID: "metadata-only-turn", InputHash: strings.Repeat("f", 64), Marker: true}
|
||||
meta, me := store.ObserveKeys(ctx, []dobotaiops.QualityKey{metaKey})
|
||||
if me != nil || meta[metaKey.ID].Automatic.InputAvailable {
|
||||
t.Fatal("compact scope observation not stored honestly", me)
|
||||
}
|
||||
if _, me = store.Snapshot(ctx, metaKey.ID, 1); !errors.Is(me, qaopsquality.ErrSnapshotMissing) {
|
||||
t.Fatal("metadata-only input fabricated an empty original")
|
||||
}
|
||||
full, me := store.Observe(ctx, []dobotaiops.Record{{ID: metaKey.ID, QualityInputHash: metaKey.InputHash, Question: "示例", Answer: "暂无已发布"}})
|
||||
if me != nil || !full[metaKey.ID].Automatic.InputAvailable || full[metaKey.ID].Automatic.ID != meta[metaKey.ID].Automatic.ID {
|
||||
t.Fatal("reading full content duplicated/replaced the same check")
|
||||
}
|
||||
req := qaopsquality.SaveRequest{InputHash: first.InputHash, InputEpoch: first.InputEpoch, BaseRevision: first.Revision, Nonce: strings.Repeat("n", 32), Fields: qaopsquality.Fields{Coverage: "covered", Correctness: "correct", ProductCategory: "MG400", ProblemType: "咨询"}, Reason: "人工核对有效引用"}
|
||||
saved, e := store.Save(ctx, record, req, "fixture-admin")
|
||||
if e != nil || saved.View.State != "reviewed" || saved.View.Effective.Coverage != "covered" || saved.View.Automatic.Result.Verdict != "uncovered" || saved.View.LatestReview.Reviewer != "fixture-admin" {
|
||||
t.Fatal("manual override lost audit/rule separation", e)
|
||||
}
|
||||
cols, ce := store.Columns(ctx, []dobotaiops.QualityKey{{ID: record.ID, InputHash: first.InputHash}})
|
||||
if ce != nil || len(cols) != 4 {
|
||||
t.Fatal("review fields absent from whole-scope projection", ce)
|
||||
}
|
||||
replay, e := store.Save(ctx, record, req, "fixture-admin")
|
||||
if e != nil || !replay.Replayed || replay.SavedRevision != saved.SavedRevision {
|
||||
t.Fatal("retry duplicated review")
|
||||
}
|
||||
bad := req
|
||||
bad.Reason = "changed body"
|
||||
if _, e = store.Save(ctx, record, bad, "fixture-admin"); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("nonce reused with different request")
|
||||
}
|
||||
if _, e = store.Save(ctx, record, req, "other-admin"); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("nonce replay changed operator")
|
||||
}
|
||||
record.Answer = "新答案"
|
||||
changed, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
if e != nil || changed[record.ID].State != "stale" || changed[record.ID].Effective.Correctness != "" {
|
||||
t.Fatal("old manual result silently survived change")
|
||||
}
|
||||
if _, e = store.Save(ctx, record, req, "fixture-admin"); e != nil {
|
||||
t.Fatal("old completed request should replay without a new review")
|
||||
}
|
||||
record.Answer = "暂无已发布"
|
||||
reverted, e := store.Observe(ctx, []dobotaiops.Record{record})
|
||||
v := reverted[record.ID]
|
||||
if e != nil || v.InputHash != first.InputHash || v.InputEpoch <= first.InputEpoch || v.State != "stale" {
|
||||
t.Fatal("answer revert reactivated old judgment")
|
||||
}
|
||||
req.InputHash = v.InputHash
|
||||
req.InputEpoch = v.InputEpoch
|
||||
req.BaseRevision = v.Revision
|
||||
start := make(chan struct{})
|
||||
results := make(chan error, 2)
|
||||
for _, nonce := range []string{strings.Repeat("a", 32), strings.Repeat("b", 32)} {
|
||||
go func(nonce string) {
|
||||
q := req
|
||||
q.Nonce = nonce
|
||||
<-start
|
||||
_, err := store.Save(ctx, record, q, "fixture-admin")
|
||||
results <- err
|
||||
}(nonce)
|
||||
}
|
||||
close(start)
|
||||
success, conflict := 0, 0
|
||||
for range 2 {
|
||||
e = <-results
|
||||
if e == nil {
|
||||
success++
|
||||
} else if errors.Is(e, qaopsquality.ErrConflict) {
|
||||
conflict++
|
||||
} else {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
if success != 1 || conflict != 1 {
|
||||
t.Fatal("concurrent reviewers overwrote each other")
|
||||
}
|
||||
h, e := store.History(ctx, record.ID, 0, 0)
|
||||
if e != nil || len(h.Reviews) != 2 || len(h.Checks) != 3 || h.Checks[0].InputEpoch != 3 {
|
||||
t.Fatal("history missing/replaced", e)
|
||||
}
|
||||
oldInput, oe := store.Snapshot(ctx, record.ID, 1)
|
||||
if oe != nil || oldInput.InputHash != first.InputHash || !strings.Contains(string(oldInput.Payload), "暂无已发布") {
|
||||
t.Fatal("old assessment evidence not readable")
|
||||
}
|
||||
// A slow older source scan must not roll back a newer observed input.
|
||||
ordered := dobotaiops.Record{ID: "ordered-source-turn", Answer: "旧输入", QualityObservedAt: time.Now().Add(-time.Minute)}
|
||||
oldEvidence, _ := qaopsquality.EvidenceFor(ordered)
|
||||
if _, e = store.Observe(ctx, []dobotaiops.Record{ordered}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
ordered.Answer = "新输入"
|
||||
ordered.QualityObservedAt = ordered.QualityObservedAt.Add(time.Second)
|
||||
newViews, ne := store.Observe(ctx, []dobotaiops.Record{ordered})
|
||||
if ne != nil {
|
||||
t.Fatal(ne)
|
||||
}
|
||||
newView := newViews[ordered.ID]
|
||||
if _, e = store.ObserveKeys(ctx, []dobotaiops.QualityKey{{ID: ordered.ID, InputHash: oldEvidence.Hash, ObservedAt: ordered.QualityObservedAt.Add(-time.Second)}}); !errors.Is(e, qaopsquality.ErrConflict) {
|
||||
t.Fatal("late old source scan rolled back the current input")
|
||||
}
|
||||
current, ce := store.Observe(ctx, []dobotaiops.Record{ordered})
|
||||
if ce != nil || current[ordered.ID].InputEpoch != newView.InputEpoch {
|
||||
t.Fatal("stale scan created extra input epochs")
|
||||
}
|
||||
// Independent cursors must enumerate more than one page without loss.
|
||||
paging := dobotaiops.Record{ID: "history-paging-turn", Answer: "示例"}
|
||||
pageSeen := map[int64]bool{}
|
||||
checkSeen := map[int64]bool{}
|
||||
for i := 0; i < 23; i++ {
|
||||
paging.Answer = fmt.Sprintf("示例输入%d", i)
|
||||
vv, ee := store.Observe(ctx, []dobotaiops.Record{paging})
|
||||
if ee != nil {
|
||||
t.Fatal(ee)
|
||||
}
|
||||
value := vv[paging.ID]
|
||||
_, ee = store.Save(ctx, paging, qaopsquality.SaveRequest{InputHash: value.InputHash, InputEpoch: value.InputEpoch, BaseRevision: value.Revision, Nonce: fmt.Sprintf("history_%020d", i), Fields: qaopsquality.Fields{Coverage: "pending", Correctness: "pending"}, Reason: "隔离分页验证"}, "fixture-admin")
|
||||
if ee != nil {
|
||||
t.Fatal(ee)
|
||||
}
|
||||
}
|
||||
rc, cc := int64(0), int64(0)
|
||||
for {
|
||||
page, ee := store.History(ctx, paging.ID, rc, cc)
|
||||
if ee != nil {
|
||||
t.Fatal(ee)
|
||||
}
|
||||
for _, r := range page.Reviews {
|
||||
if pageSeen[r.Revision] {
|
||||
t.Fatal("duplicate history review")
|
||||
}
|
||||
pageSeen[r.Revision] = true
|
||||
}
|
||||
for _, c := range page.Checks {
|
||||
if checkSeen[c.ID] {
|
||||
t.Fatal("duplicate history check")
|
||||
}
|
||||
checkSeen[c.ID] = true
|
||||
}
|
||||
rc, cc = page.NextReview, page.NextCheck
|
||||
if rc == 0 && cc == 0 {
|
||||
break
|
||||
}
|
||||
if rc == 0 || cc == 0 {
|
||||
t.Fatal("unexpected fixture cursor shape")
|
||||
}
|
||||
}
|
||||
if len(pageSeen) != 23 || len(checkSeen) != 23 {
|
||||
t.Fatal("history cursor omitted immutable rows")
|
||||
}
|
||||
freshPool, fe := pgxpool.New(ctx, dsn)
|
||||
if fe != nil {
|
||||
t.Fatal(fe)
|
||||
}
|
||||
persisted, fe := qaopsquality.NewStore(freshPool, "fixture-tenant").History(ctx, record.ID, 0, 0)
|
||||
freshPool.Close()
|
||||
if fe != nil || len(persisted.Reviews) != 2 || len(persisted.Checks) != 3 {
|
||||
t.Fatal("history did not survive a new connection pool")
|
||||
}
|
||||
// History survives a fresh store/connection, not merely an in-memory cache.
|
||||
if h, e = qaopsquality.NewStore(pool, "other-tenant").History(ctx, record.ID, 0, 0); e != nil || len(h.Reviews) != 0 || len(h.Checks) != 0 {
|
||||
t.Fatal("quality history crossed tenants")
|
||||
}
|
||||
if e = pg.RollbackLatestMigration(ctx, pool); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
var gone bool
|
||||
if pool.QueryRow(ctx, `SELECT to_regclass('qa_ops_quality_records') IS NULL AND to_regclass('qa_ops_quality_inputs') IS NULL AND to_regclass('qa_ops_quality_checks') IS NULL AND to_regclass('qa_ops_quality_reviews') IS NULL`).Scan(&gone) != nil || !gone {
|
||||
t.Fatal("quality down migration left data tables")
|
||||
}
|
||||
if e = pg.ApplyMigrations(ctx, pool); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package versionhistory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/governance"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (s *Syncer) includeDeliveredCommits(ctx context.Context, commits []RawCommit, tags []RawTag) ([]RawCommit, error) {
|
||||
seen := map[string]bool{}
|
||||
for _, c := range commits {
|
||||
seen[c.SHA] = true
|
||||
}
|
||||
refs := append([]string{}, s.targetSHAs...)
|
||||
snapshots := []RawTag{}
|
||||
for _, tag := range tags {
|
||||
if tag.Annotated && strings.HasPrefix(tag.Name, "snapshot/v") && governance.SemverValid(strings.TrimPrefix(tag.Name, "snapshot/v")) {
|
||||
snapshots = append(snapshots, tag)
|
||||
}
|
||||
}
|
||||
sort.Slice(snapshots, func(i, j int) bool {
|
||||
return governance.CompareSemver(strings.TrimPrefix(snapshots[i].Name, "snapshot/v"), strings.TrimPrefix(snapshots[j].Name, "snapshot/v")) > 0
|
||||
})
|
||||
for _, tag := range snapshots {
|
||||
refs = append(refs, tag.TargetSHA)
|
||||
}
|
||||
for _, ref := range refs {
|
||||
if seen[ref] {
|
||||
continue
|
||||
}
|
||||
if !fullSHA.MatchString(ref) {
|
||||
return nil, fmt.Errorf("开发快照缺少完整提交身份")
|
||||
}
|
||||
extra, total, e := s.fetchCommitsAt(ctx, ref)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if total > 0 && len(extra) != total {
|
||||
return nil, codeError{code: ErrorCodeCountMismatch, message: "开发快照提交历史不完整"}
|
||||
}
|
||||
found := false
|
||||
for _, c := range extra {
|
||||
if c.SHA == ref {
|
||||
found = true
|
||||
}
|
||||
if !seen[c.SHA] {
|
||||
seen[c.SHA] = true
|
||||
commits = append(commits, c)
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return nil, codeError{code: ErrorCodeIncompletePages, message: "开发快照目标没有被取回"}
|
||||
}
|
||||
}
|
||||
return commits, nil
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package versionhistory
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"knowledge-governance/internal/governance"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestGiteaSnapshotRefIsExplicitAndNotesArePreserved(t *testing.T) {
|
||||
server := fakeGitea(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/commits" {
|
||||
if r.URL.Query().Get("sha") != shaB {
|
||||
t.Error("snapshot commit history silently used default branch")
|
||||
}
|
||||
fmt.Fprintf(w, `[{"sha":%q,"parents":[],"commit":{"message":"fixture"}}]`, shaB)
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/api/v1/repos/Weknora/knowledge-governance/git/refs/tags" {
|
||||
fmt.Fprintf(w, `[{"ref":"refs/tags/snapshot/v0.1.1","object":{"type":"tag","sha":%q}}]`, shaT)
|
||||
return
|
||||
}
|
||||
fmt.Fprintf(w, `{"message":"development notes","object":{"type":"commit","sha":%q}}`, shaB)
|
||||
})
|
||||
c, _ := NewGiteaClient(validConfig(server.URL))
|
||||
if _, _, e := c.ListCommitsAtRef(context.Background(), shaB, 1, 50); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
tags, e := c.ListTags(context.Background())
|
||||
if e != nil || len(tags) != 1 || tags[0].Message != "development notes" {
|
||||
t.Fatal("annotated snapshot notes lost", e)
|
||||
}
|
||||
}
|
||||
func TestDevelopmentVersionsHaveTheirOwnChangelogNotes(t *testing.T) {
|
||||
a, b := shaA, shaB
|
||||
now := time.Now()
|
||||
text := "# Changelog\n\n## [Unreleased]\n\n### Added\n\n- unrelated future work\n\n## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- fix specifically delivered here\n\n## [0.1.0] - 2026-10-13\n\n### Added\n\n- baseline\n"
|
||||
result := DeriveVersions(DeriveInput{Commits: []RawCommit{{SHA: a, CommittedAt: now}, {SHA: b, Parents: []string{a}, CommittedAt: now}}, Tags: []RawTag{{Name: "v0.1.0", TargetSHA: a, Annotated: true}}, Changelog: func(string) (string, error) { return text, nil }})
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == b && (v.ReleaseNotes != "### Fixed\n\n- fix specifically delivered here" || v.RecordKind != governance.RecordKindDevelopment) {
|
||||
t.Fatalf("development version lacks its own notes: %q", v.ReleaseNotes)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHistoricDevelopmentArchiveBindsExactCommit(t *testing.T) {
|
||||
archive := "## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n目标提交:" + shaB + "\n\n### Fixed\n\n- historic delivery notes\n"
|
||||
input := DeriveInput{DeliveryArchive: archive, Commits: []RawCommit{{SHA: shaA}, {SHA: shaB, Parents: []string{shaA}}}, Tags: []RawTag{{Name: "v0.1.0", TargetSHA: shaA, Annotated: true}}, Changelog: func(string) (string, error) { return "## [0.1.0] - 2026-10-13\n\n### Added\n\n- baseline", nil }}
|
||||
result := DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && !strings.Contains(v.ReleaseNotes, "historic delivery notes") {
|
||||
t.Fatal("archived notes missing")
|
||||
}
|
||||
}
|
||||
// Parallel branch histories may legitimately have the same derived number.
|
||||
input.DeliveryArchive = strings.ReplaceAll(archive, shaB, strings.Repeat("c", 40)) + "\n" + archive
|
||||
result = DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && !strings.Contains(v.ReleaseNotes, "historic delivery notes") {
|
||||
t.Fatal("same-number archive hid notes for exact commit")
|
||||
}
|
||||
}
|
||||
input.DeliveryArchive = strings.ReplaceAll(archive, shaB, strings.Repeat("c", 40))
|
||||
result = DeriveVersions(input)
|
||||
for _, v := range result.Records {
|
||||
if v.CommitSHA == shaB && v.ReleaseNotes != "" {
|
||||
t.Fatal("different commit reused same-number archive notes")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type snapshotRefSource struct {
|
||||
fakeSource
|
||||
other []RawCommit
|
||||
}
|
||||
|
||||
func (s *snapshotRefSource) ListCommitsAtRef(_ context.Context, _ string, page, limit int) ([]RawCommit, int, error) {
|
||||
if page == 1 {
|
||||
return s.other, len(s.other), nil
|
||||
}
|
||||
return nil, len(s.other), nil
|
||||
}
|
||||
func TestSyncIncludesDeliveredSnapshotOutsideMain(t *testing.T) {
|
||||
a := RawCommit{SHA: shaA}
|
||||
b := RawCommit{SHA: shaB, Parents: []string{shaA}}
|
||||
src := &snapshotRefSource{fakeSource: fakeSource{commits: []RawCommit{a}, total: 1, pageSize: 50, head: shaA, tags: []RawTag{{Name: "snapshot/v0.1.1", TargetSHA: shaB, Annotated: true}}}, other: []RawCommit{b, a}}
|
||||
store := &fakeStore{}
|
||||
run, e := newTestSyncer(t, src, store).Sync(context.Background(), "fixture", "admin")
|
||||
if e != nil || len(store.saved) != 1 || len(store.saved[0].records) != 2 || !run.Complete {
|
||||
t.Fatal("delivered non-main snapshot omitted", e, run.FetchedCount)
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,12 @@ var errGiteaNotFound = newGiteaError(KindNotFound, http.StatusNotFound, "版本
|
||||
|
||||
// ListCommits 读一页提交;同时返回 X-Total-Count(用于完整性对账,不做假 total)。
|
||||
func (c *GiteaClient) ListCommits(ctx context.Context, page, limit int) ([]RawCommit, int, error) {
|
||||
return c.ListCommitsAtRef(ctx, "main", page, limit)
|
||||
}
|
||||
func (c *GiteaClient) ListCommitsAtRef(ctx context.Context, ref string, page, limit int) ([]RawCommit, int, error) {
|
||||
if ref != "main" && !fullSHA.MatchString(ref) {
|
||||
return nil, 0, newGiteaError(KindParse, 0, "版本记录:只接受 main 或完整提交 SHA", nil)
|
||||
}
|
||||
if limit <= 0 || limit > giteaDefaultPageSize {
|
||||
limit = giteaDefaultPageSize
|
||||
}
|
||||
@@ -196,6 +202,7 @@ func (c *GiteaClient) ListCommits(ctx context.Context, page, limit int) ([]RawCo
|
||||
query.Set("page", fmt.Sprintf("%d", page))
|
||||
query.Set("stat", "false")
|
||||
query.Set("verification", "false")
|
||||
query.Set("sha", ref)
|
||||
body, header, err := c.get(ctx, c.apiURL("/commits", query))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
@@ -322,7 +329,8 @@ func (c *GiteaClient) ListTags(ctx context.Context) ([]RawTag, error) {
|
||||
return nil, err
|
||||
}
|
||||
var annotated struct {
|
||||
Object struct {
|
||||
Message string `json:"message"`
|
||||
Object struct {
|
||||
SHA string `json:"sha"`
|
||||
} `json:"object"`
|
||||
}
|
||||
@@ -333,6 +341,7 @@ func (c *GiteaClient) ListTags(ctx context.Context) ([]RawTag, error) {
|
||||
continue
|
||||
}
|
||||
tag.TargetSHA = annotated.Object.SHA
|
||||
tag.Message = annotated.Message
|
||||
}
|
||||
tags = append(tags, tag)
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ package versionhistory
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"knowledge-governance/internal/governance"
|
||||
@@ -25,6 +26,7 @@ type RawCommit struct {
|
||||
|
||||
// RawTag 是一个 tag 及其可核验属性;Annotated=false 表示轻量 tag(不算正式版本的证据)。
|
||||
type RawTag struct {
|
||||
Message string
|
||||
Name string
|
||||
TagSHA string
|
||||
TargetSHA string
|
||||
@@ -36,13 +38,14 @@ type ChangelogSource func(sha string) (string, error)
|
||||
|
||||
// DeriveInput 是一次换算的全部输入。
|
||||
type DeriveInput struct {
|
||||
RepoKey string
|
||||
CommitURLBase string // 形如 "<origin>/<owner>/<repo>/commit/",由配置拼好,不接受外部传入
|
||||
TagURLBase string // 形如 "<origin>/<owner>/<repo>/src/tag/";空则不下发 tag 链接
|
||||
Commits []RawCommit
|
||||
Tags []RawTag
|
||||
Changelog ChangelogSource
|
||||
SnapshotID int64
|
||||
DeliveryArchive string
|
||||
RepoKey string
|
||||
CommitURLBase string // 形如 "<origin>/<owner>/<repo>/commit/",由配置拼好,不接受外部传入
|
||||
TagURLBase string // 形如 "<origin>/<owner>/<repo>/src/tag/";空则不下发 tag 链接
|
||||
Commits []RawCommit
|
||||
Tags []RawTag
|
||||
Changelog ChangelogSource
|
||||
SnapshotID int64
|
||||
}
|
||||
|
||||
// DeriveResult 是换算结果。
|
||||
@@ -192,6 +195,22 @@ func DeriveVersions(in DeriveInput) DeriveResult {
|
||||
}
|
||||
if kind == governance.RecordKindRelease {
|
||||
record.ReleaseNotes = governance.ExtractReleaseNotes(changelog, label)
|
||||
} else if kind == governance.RecordKindDevelopment {
|
||||
record.ReleaseNotes = governance.ExtractDevelopmentNotes(changelog, label)
|
||||
if record.ReleaseNotes == "" {
|
||||
record.ReleaseNotes = governance.ExtractDevelopmentNotesForCommit(in.DeliveryArchive, label, commit.SHA)
|
||||
}
|
||||
if record.ReleaseNotes == "" {
|
||||
for _, tag := range tagsByTarget[commit.SHA] {
|
||||
if tag.Annotated && tag.Name == "snapshot/v"+label {
|
||||
_, body, found := strings.Cut(tag.Message, "\n\n")
|
||||
if found {
|
||||
record.ReleaseNotes = strings.TrimSpace(body)
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
records = append(records, record)
|
||||
}
|
||||
|
||||
@@ -130,22 +130,24 @@ type SyncOutcome struct {
|
||||
|
||||
// SyncerConfig 装配同步器。
|
||||
type SyncerConfig struct {
|
||||
Source Source
|
||||
Store SyncStore
|
||||
RepoKey string
|
||||
Changelog string // 提交内的变更记录文件路径,默认 CHANGELOG.md
|
||||
Now func() time.Time
|
||||
MaxPages int
|
||||
Source Source
|
||||
Store SyncStore
|
||||
RepoKey string
|
||||
Changelog string // 提交内的变更记录文件路径,默认 CHANGELOG.md
|
||||
Now func() time.Time
|
||||
MaxPages int
|
||||
TargetSHAs []string
|
||||
}
|
||||
|
||||
// Syncer 抓取远端 main 可达的全部提交并换算版本记录。
|
||||
type Syncer struct {
|
||||
source Source
|
||||
store SyncStore
|
||||
repoKey string
|
||||
changelog string
|
||||
now func() time.Time
|
||||
maxPages int
|
||||
source Source
|
||||
store SyncStore
|
||||
repoKey string
|
||||
changelog string
|
||||
now func() time.Time
|
||||
maxPages int
|
||||
targetSHAs []string
|
||||
}
|
||||
|
||||
const syncerDefaultMaxPages = 200
|
||||
@@ -170,7 +172,12 @@ func NewSyncer(config SyncerConfig) (*Syncer, error) {
|
||||
if maxPages <= 0 {
|
||||
maxPages = syncerDefaultMaxPages
|
||||
}
|
||||
return &Syncer{source: config.Source, store: config.Store, repoKey: config.RepoKey,
|
||||
for _, sha := range config.TargetSHAs {
|
||||
if !fullSHA.MatchString(sha) {
|
||||
return nil, errors.New("版本记录:运行身份必须是完整 SHA")
|
||||
}
|
||||
}
|
||||
return &Syncer{targetSHAs: append([]string{}, config.TargetSHAs...), source: config.Source, store: config.Store, repoKey: config.RepoKey,
|
||||
changelog: changelog, now: now, maxPages: maxPages}, nil
|
||||
}
|
||||
|
||||
@@ -204,9 +211,22 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
return fail(err)
|
||||
}
|
||||
|
||||
commits, err = s.includeDeliveredCommits(ctx, commits, tags)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
total = len(commits)
|
||||
deliveryArchive := ""
|
||||
if len(s.targetSHAs) > 0 {
|
||||
deliveryArchive, err = s.source.ReadFile(ctx, s.targetSHAs[0], s.changelog)
|
||||
if err != nil {
|
||||
return fail(err)
|
||||
}
|
||||
}
|
||||
derived := DeriveVersions(DeriveInput{RepoKey: s.repoKey, CommitURLBase: s.source.CommitURLBase(),
|
||||
TagURLBase: s.source.TagURLBase(),
|
||||
Commits: commits, Tags: tags, SnapshotID: runID,
|
||||
TagURLBase: s.source.TagURLBase(),
|
||||
DeliveryArchive: deliveryArchive,
|
||||
Commits: commits, Tags: tags, SnapshotID: runID,
|
||||
Changelog: func(sha string) (string, error) {
|
||||
return s.source.ReadFile(ctx, sha, s.changelog)
|
||||
}})
|
||||
@@ -220,6 +240,9 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
} else {
|
||||
sourceHead = headSHA(commits) // 读分支失败不致命:退回提交列表最新一条
|
||||
}
|
||||
if len(s.targetSHAs) > 0 {
|
||||
sourceHead = s.targetSHAs[0]
|
||||
}
|
||||
outcome := SyncOutcome{SourceHeadSHA: sourceHead, FetchedCount: len(commits),
|
||||
ExpectedCount: total, Complete: derived.GraphComplete && (total == 0 || len(commits) == total)}
|
||||
if err := s.store.FinishVersionHistorySync(ctx, runID, outcome, s.now().UTC()); err != nil {
|
||||
@@ -232,6 +255,9 @@ func (s *Syncer) Sync(ctx context.Context, jobID, triggeredBy string) (governanc
|
||||
|
||||
// fetchAllCommits 逐页抓取并按 SHA 去重;短页即终止(也防住服务端忽略 page 参数)。
|
||||
func (s *Syncer) fetchAllCommits(ctx context.Context) ([]RawCommit, int, error) {
|
||||
return s.fetchCommitsAt(ctx, "")
|
||||
}
|
||||
func (s *Syncer) fetchCommitsAt(ctx context.Context, ref string) ([]RawCommit, int, error) {
|
||||
pageSize := s.source.PageSize()
|
||||
if pageSize <= 0 {
|
||||
pageSize = giteaDefaultPageSize
|
||||
@@ -240,7 +266,18 @@ func (s *Syncer) fetchAllCommits(ctx context.Context) ([]RawCommit, int, error)
|
||||
commits := make([]RawCommit, 0, pageSize)
|
||||
total := 0
|
||||
for page := 1; page <= s.maxPages; page++ {
|
||||
pageCommits, pageTotal, err := s.source.ListCommits(ctx, page, pageSize)
|
||||
var pageCommits []RawCommit
|
||||
var pageTotal int
|
||||
var err error
|
||||
if ref == "" {
|
||||
pageCommits, pageTotal, err = s.source.ListCommits(ctx, page, pageSize)
|
||||
} else if source, ok := s.source.(interface {
|
||||
ListCommitsAtRef(context.Context, string, int, int) ([]RawCommit, int, error)
|
||||
}); ok {
|
||||
pageCommits, pageTotal, err = source.ListCommitsAtRef(ctx, ref, page, pageSize)
|
||||
} else {
|
||||
return nil, 0, errors.New("版本来源不支持开发快照历史")
|
||||
}
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -356,6 +356,9 @@ def cmd_internal_web_test() -> int:
|
||||
def cmd_internal_contracts(go: str) -> int:
|
||||
"""版本契约:结构 + 注入身份必须**真 PASS**(SKIP 判红),
|
||||
并且**开发构建不许自称正式版**(负例:标成 release ⇒ 必须红)。"""
|
||||
snapshot_rc = subprocess.run(py("scripts/development_snapshot.py","--self-test"),cwd=ROOT).returncode
|
||||
if snapshot_rc:
|
||||
return 1
|
||||
rc = subprocess.run(py("scripts/check_changelog.py"), cwd=ROOT).returncode
|
||||
if rc:
|
||||
return 1
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# 重建并上线 governance api + web(本机 docker build 需要宿主代理 + --network host)
|
||||
set -u
|
||||
cd /home/zheromiku/knowledge-governance || exit 1
|
||||
cd "$(dirname "${BASH_SOURCE[0]}")/.." || exit 1
|
||||
[ -z "$(git status --porcelain --untracked-files=normal)" ] || { printf "%s\n" "REFUSED_DIRTY_SOURCE"; exit 1; }
|
||||
TS=$(date +%Y%m%d-%H%M%S)
|
||||
PROXY_ARGS=(--build-arg HTTP_PROXY=http://127.0.0.1:7890 --build-arg HTTPS_PROXY=http://127.0.0.1:7890 --build-arg NO_PROXY=localhost,127.0.0.1 --build-arg GOPROXY=https://goproxy.cn,direct)
|
||||
|
||||
@@ -123,4 +124,12 @@ if docker exec knowledge-governance-p1-api-1 sh -lc "strings /app/api | grep -q
|
||||
else
|
||||
echo "INJECTION_MISSING(产物里没有 $INJECTED —— 页面会显示当前运行未知)"
|
||||
fi
|
||||
echo "=== 10. 版本记录同步读回(当前 SHA + 注释快照 + 独立变更说明)"
|
||||
# Startup queues the read-only history job. A healthy API alone is not proof.
|
||||
VERIFIED=0
|
||||
for ((attempt=0;attempt<90;attempt++)); do
|
||||
if docker exec knowledge-governance-p1-api-1 /app/api --version-record-status; then VERIFIED=1; break; fi
|
||||
sleep 2
|
||||
done
|
||||
[ "$VERIFIED" = "1" ] || { printf '%s\n' 'VERSION_RECORD_NOT_VERIFIED'; exit 1; }
|
||||
echo "DONE"
|
||||
@@ -0,0 +1,85 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Explicit development delivery tags; never creates formal tags or releases."""
|
||||
import argparse,json,re,subprocess,tempfile
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parent.parent
|
||||
SHA=re.compile(r'^[a-f0-9]{40}$')
|
||||
def git(root,*args):
|
||||
p=subprocess.run(['git',*args],cwd=root,text=True,capture_output=True)
|
||||
if p.returncode:raise RuntimeError('git operation failed: '+args[0])
|
||||
return p.stdout.strip()
|
||||
def notes(text,version,sha=None):
|
||||
for heading in re.finditer(r'^## 开发快照 snapshot/v'+re.escape(version)+r' - \d{4}-\d{2}-\d{2}\s*$',text,re.M):
|
||||
body=re.split(r'^##\s',text[heading.end():],maxsplit=1,flags=re.M)[0].strip()
|
||||
if sha is None or ('目标提交:'+sha) in body.splitlines():return body
|
||||
return ''
|
||||
def plan(root,sha,backfill=False):
|
||||
if not sha or not SHA.fullmatch(sha):raise ValueError('exact 40-character commit SHA required')
|
||||
if git(root,'cat-file','-t',sha)!='commit':raise ValueError('snapshot target must be a commit')
|
||||
text=git(root,'show',sha+':CHANGELOG.md');m=re.search(r'^##\s*\[(\d+\.\d+\.\d+)\]',text,re.M)
|
||||
if not m:raise ValueError('formal baseline missing')
|
||||
baseline=m.group(1);base='v'+baseline
|
||||
if git(root,'cat-file','-t','refs/tags/'+base)!='tag':raise ValueError('annotated formal baseline missing')
|
||||
git(root,'merge-base','--is-ancestor',base,sha)
|
||||
n=int(git(root,'rev-list','--count',base+'..'+sha));version='.'.join(baseline.split('.')[:2]+[str(n)])
|
||||
if n<=0:raise ValueError('formal baseline cannot be tagged as a development delivery')
|
||||
body=notes(text,version)
|
||||
if not body and backfill:
|
||||
body=notes(git(root,'show','HEAD:CHANGELOG.md'),version,sha)
|
||||
if '目标提交:'+sha not in body:raise ValueError('backfilled notes must bind the exact historic SHA')
|
||||
if not body:raise ValueError('this development version has no independent CHANGELOG entry')
|
||||
if not re.search(r'^### (Added|Changed|Fixed|Security)\s*$',body,re.M):raise ValueError('snapshot notes have no change category')
|
||||
return {'commit_sha':sha,'display_version':version,'tag':'snapshot/v'+version,'message':'Development snapshot '+version+'\n\n'+body,'backfilled':bool(backfill)}
|
||||
def publish(root,p):
|
||||
# Only explicitly named development refs are written. Existing refs, including
|
||||
# legacy misnumbered snapshots, are never moved or overwritten.
|
||||
tag=p['tag'];sha=p['commit_sha'];ref='refs/tags/'+tag
|
||||
remote=git(root,'ls-remote','origin');pairs=[line.split() for line in remote.splitlines() if line.strip()];refs={name:obj for obj,name in pairs}
|
||||
if ref in refs:
|
||||
if refs.get(ref+'^{}')!=sha:raise ValueError('remote snapshot already exists with different or non-annotated identity')
|
||||
return {'tag':tag,'commit_sha':sha,'state':'already_published'}
|
||||
reachable=False
|
||||
for obj,name in pairs:
|
||||
if name.startswith('refs/heads/') and subprocess.run(['git','merge-base','--is-ancestor',sha,obj],cwd=root,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode==0:reachable=True;break
|
||||
if not reachable:raise ValueError('snapshot target has not been pushed to a remote branch')
|
||||
exists=subprocess.run(['git','show-ref','--verify','--quiet',ref],cwd=root).returncode==0
|
||||
if exists:
|
||||
if git(root,'cat-file','-t',ref)!='tag' or git(root,'rev-parse',ref+'^{}')!=sha:raise ValueError('local snapshot conflicts with requested identity')
|
||||
if git(root,'for-each-ref','--format=%(contents)',ref).strip()!=p['message'].strip():raise ValueError('existing snapshot annotation differs; will not overwrite')
|
||||
else:
|
||||
with tempfile.NamedTemporaryFile(mode='w',prefix='kg-snapshot-note-',encoding='utf-8') as f:
|
||||
f.write(p['message']+'\n');f.flush();git(root,'tag','-a',tag,sha,'-F',f.name)
|
||||
git(root,'push','origin',ref+':'+ref)
|
||||
readback={line.split()[1]:line.split()[0] for line in git(root,'ls-remote','--tags','origin',ref,ref+'^{}').splitlines()}
|
||||
if readback.get(ref+'^{}')!=sha or readback.get(ref)!=git(root,'rev-parse',ref):raise RuntimeError('remote snapshot read-back failed')
|
||||
return {'tag':tag,'commit_sha':sha,'state':'published_and_read_back'}
|
||||
def self_test():
|
||||
with tempfile.TemporaryDirectory(prefix='kg-snapshot-test-') as d:
|
||||
r=Path(d);git(r,'init','-b','main');git(r,'config','user.name','Fixture');git(r,'config','user.email','fixture@example.invalid')
|
||||
base='# Changelog\n\n## [0.1.0] - 2026-10-13\n\n### Added\n\n- fixture baseline\n'
|
||||
(r/'CHANGELOG.md').write_text(base);git(r,'add','CHANGELOG.md');git(r,'commit','-m','feat: fixture baseline');git(r,'tag','-a','v0.1.0','-m','fixture')
|
||||
(r/'CHANGELOG.md').write_text('## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n### Fixed\n\n- specific fixture fix\n\n'+base);git(r,'add','CHANGELOG.md');git(r,'commit','-m','fix: fixture change')
|
||||
sha=git(r,'rev-parse','HEAD');before=git(r,'tag');p=plan(r,sha)
|
||||
assert p['tag']=='snapshot/v0.1.1' and 'specific fixture fix' in p['message']
|
||||
duplicate='## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n目标提交:'+('a'*40)+'\n\n### Fixed\n\n- wrong branch\n\n## 开发快照 snapshot/v0.1.1 - 2026-10-18\n\n目标提交:'+sha+'\n\n### Fixed\n\n- exact branch'
|
||||
assert 'exact branch' in notes(duplicate,'0.1.1',sha) and 'wrong branch' not in notes(duplicate,'0.1.1',sha)
|
||||
assert before==git(r,'tag'),'planning wrote a tag'
|
||||
try:plan(r,'a'*7)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('short SHA accepted')
|
||||
bare=r/'remote.git';git(r,'init','--bare',str(bare));git(r,'remote','add','origin',str(bare));git(r,'push','origin','main')
|
||||
out=publish(r,p);assert out['state']=='published_and_read_back'
|
||||
assert git(r,'rev-parse',p['tag']+'^{}')==sha
|
||||
assert publish(r,p)['state']=='already_published'
|
||||
wrong=dict(p,commit_sha='a'*40)
|
||||
try:publish(r,wrong)
|
||||
except ValueError:pass
|
||||
else:raise AssertionError('conflicting remote snapshot overwritten')
|
||||
assert git(r,'tag','--list','v*').splitlines()==['v0.1.0'],'formal tags changed'
|
||||
print('development snapshot fixture passed; real repository tags untouched')
|
||||
def main():
|
||||
a=argparse.ArgumentParser();a.add_argument('--sha');a.add_argument('--backfill',action='store_true');a.add_argument('--publish',action='store_true');a.add_argument('--self-test',action='store_true');o=a.parse_args()
|
||||
if o.self_test:return self_test()
|
||||
p=plan(ROOT,o.sha,o.backfill)
|
||||
print(json.dumps(publish(ROOT,p) if o.publish else p,ensure_ascii=False))
|
||||
if __name__=='__main__':main()
|
||||
@@ -36,6 +36,9 @@ def _validate_directory(departments, people):
|
||||
seen.add(current)
|
||||
current = int(departments[current].get('parent_id') or 0)
|
||||
for identity, person in people.items():
|
||||
name = person.get('name')
|
||||
if name is not None and (not isinstance(name, str) or len(name.encode('utf-8')) > 1000 or '\x00' in name):
|
||||
raise DirectorySyncError('directory_integrity_failed')
|
||||
if not identity or str(person.get('user_id') or '') != str(identity):
|
||||
raise DirectorySyncError('directory_integrity_failed')
|
||||
if not person.get('department_ids') or any(int(d) not in departments for d in person['department_ids']):
|
||||
@@ -78,7 +81,7 @@ def collect_directory(client, fetch_departments, fetch_users, get_detail, logger
|
||||
# List membership provides stable staff IDs; do not reuse the old
|
||||
# guessed primary department, employment policy or openId fallback.
|
||||
'people': [
|
||||
{'id': str(identity), 'union_id': str((p.get('raw_payload') or {}).get('unionid') or (p.get('raw_payload') or {}).get('unionId') or ''), 'department_ids': [str(d) for d in sorted(p['department_ids'])]}
|
||||
{'id': str(identity), **({'name': p['name']} if p.get('name') else {}), 'union_id': str((p.get('raw_payload') or {}).get('unionid') or (p.get('raw_payload') or {}).get('unionId') or ''), 'department_ids': [str(d) for d in sorted(p['department_ids'])]}
|
||||
for identity, p in sorted(people.items())
|
||||
],
|
||||
},
|
||||
|
||||
+41
-2
@@ -9,8 +9,22 @@
|
||||
"⚠️ 文件缺失或解析不了 ⇒ 门禁红:范围声明不出来时,不许默认放行。"
|
||||
],
|
||||
"optional": [
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQARecordInternalIdentityAndWholeFilterKeys", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{"package": "knowledge-governance/internal/dobotaiops", "test": "TestQAUsageGroupsCountEventsOnceOverTheFullFilter", "reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"},
|
||||
{"package":"knowledge-governance/internal/qaopsmirror","reason":"本包所有集成用例只在显式一次性 loopback kg_qaops_mirror_test_ 库运行;默认 CI 不连共享或生产库;隔离 PG -race 另行实跑"},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsquality",
|
||||
"test": "TestQualityStoreImmutableHistoryReplayConcurrencyAndStaleness",
|
||||
"reason": "仅在显式一次性 loopback kg_qaops_quality_test_ 库执行;默认 CI 不连接共享/生产库,隔离 PG 另行实跑"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/dobotaiops",
|
||||
"test": "TestQARecordInternalIdentityAndWholeFilterKeys",
|
||||
"reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/dobotaiops",
|
||||
"test": "TestQAUsageGroupsCountEventsOnceOverTheFullFilter",
|
||||
"reason": "必须显式一次性隔离PG;验证真实只读SQL身份关联/计数及隐私,不连接生产;默认无库时明确跳过,另行本地补验"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsorg",
|
||||
"test": "TestDirectorySyncQueueDurableReplayAndLeaseFencing",
|
||||
@@ -110,6 +124,31 @@
|
||||
"package": "knowledge-governance/internal/versionhistory",
|
||||
"test": "TestLiveSyncAgainstRealRepository",
|
||||
"reason": "真实仓库的只读同步用例需要内部可达的 Gitea(**匿名**,不读凭据);无环境即跳过(补验路径:设 VERSION_HISTORY_LIVE_BASE_URL 后单跑这条)"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorQueriesNeverRequireSource",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorDurableQueueCoalescesAndAudits",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorSyncActivatesAndCheckpoints",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/qaopsmirror",
|
||||
"test": "TestLocalMirrorPeriodicSyncIsDurableAndDueOnly",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
},
|
||||
{
|
||||
"package": "knowledge-governance/internal/dobotaiops",
|
||||
"test": "TestMirrorSourceManifestDetectsUpdatesWithoutVolatileTimes",
|
||||
"reason": "仅显式一次性隔离PG验证本地副本/持久同步或专门只读源夹具;默认CI不连接共享与生产库,另行实际执行隔离验收"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
@@ -24,6 +24,13 @@ def root_detail(client,logger,department_id):
|
||||
return {'id':department_id,'parent_id':0,'name':'真实源端返回的示例根部门'},False,False
|
||||
|
||||
class DirectoryBridgeTests(unittest.TestCase):
|
||||
def test_real_display_name_is_retained_without_guessing_or_requiring_it(self):
|
||||
def users(*args,**kwargs):
|
||||
return {'u':{'user_id':'u','name':'<示例员工>','department_ids':{10},'raw_payload':{}}},set(),set()
|
||||
result=sync.collect_directory(FakeClient(),full_departments,users,root_detail,logging.getLogger('fixture'))
|
||||
self.assertEqual(result['directory']['people'][0].get('name'),'<示例员工>')
|
||||
result=sync.collect_directory(FakeClient(),full_departments,full_users,root_detail,logging.getLogger('fixture'))
|
||||
self.assertNotIn('name',result['directory']['people'][0])
|
||||
def test_fetches_the_real_missing_root_and_preserves_stable_identities(self):
|
||||
result=sync.collect_directory(FakeClient(),full_departments,full_users,root_detail,logging.getLogger('fixture'))
|
||||
self.assertTrue(result['complete'])
|
||||
|
||||
Generated
+1493
-6
File diff suppressed because it is too large
Load Diff
+3
-1
@@ -13,7 +13,9 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"react": "19.1.1",
|
||||
"react-dom": "19.1.1"
|
||||
"react-dom": "19.1.1",
|
||||
"react-markdown": "10.1.0",
|
||||
"remark-gfm": "4.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/react": "19.1.10",
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { QAAnswerMarkdown } from './QAAnswerMarkdown'
|
||||
describe('AI answer Markdown preview', () => {
|
||||
it('renders headings, tables, code, links and keeps original source', () => {
|
||||
const answer =
|
||||
'# 安装步骤\n\n- **先断电**\n- 检查接线\n\n| 参数 | 值 |\n| --- | --- |\n| 速度 | 50 |\n\n```python\nprint("ready")\n```\n\n[说明](https://example.invalid/guide)'
|
||||
const html = renderToStaticMarkup(<QAAnswerMarkdown answer={answer} />)
|
||||
expect(html).toContain('<h1>安装步骤</h1>')
|
||||
expect(html).toContain('<strong>先断电</strong>')
|
||||
expect(html).toContain('<table>')
|
||||
expect(html).toContain('language-python')
|
||||
expect(html).toContain('href="https://example.invalid/guide"')
|
||||
expect(html).toContain('noopener noreferrer')
|
||||
expect(html).toContain('查看 Markdown 原文')
|
||||
})
|
||||
it('never executes raw HTML, unsafe URL schemes or automatically loads external images', () => {
|
||||
const answer =
|
||||
'<script>globalThis.PWNED=true</script>\n\n<img src="x" onerror="alert(1)">\n\n[unsafe](javascript:alert%281%29)\n\n'
|
||||
const html = renderToStaticMarkup(<QAAnswerMarkdown answer={answer} />)
|
||||
expect(html).not.toContain('<script>')
|
||||
expect(html).not.toContain('<img ')
|
||||
expect(html).not.toContain('href="javascript:')
|
||||
expect(html.split('<details')[0]).not.toContain('onerror=')
|
||||
expect(html).toContain('查看图片')
|
||||
})
|
||||
it('does not confuse an empty answer with a positive assessment', () => {
|
||||
expect(renderToStaticMarkup(<QAAnswerMarkdown answer="" />)).toContain('暂无答案')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,67 @@
|
||||
import { useState } from 'react'
|
||||
import Markdown from 'react-markdown'
|
||||
import remarkGfm from 'remark-gfm'
|
||||
import './qaAnswer.css'
|
||||
|
||||
export function safeAnswerURL(value: string): string {
|
||||
if (!value || /[\u0000-\u0020\u007f\\]/.test(value) || value.startsWith('//')) return ''
|
||||
if (!/^[a-z][a-z0-9+.-]*:/i.test(value)) return value
|
||||
try {
|
||||
const url = new URL(value)
|
||||
return ['http:', 'https:'].includes(url.protocol) && !url.username && !url.password ? value : ''
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function QAAnswerMarkdown({ answer }: { answer: string }) {
|
||||
const [showImages, setShowImages] = useState(false)
|
||||
if (!answer) return <p>暂无答案</p>
|
||||
return (
|
||||
<div className="qa-answer">
|
||||
<div className="qa-answer-tools">
|
||||
<span>Markdown 预览</span>
|
||||
{/!\[/.test(answer) ? (
|
||||
<button type="button" onClick={() => setShowImages(!showImages)} aria-pressed={showImages}>
|
||||
{showImages ? '隐藏图片' : '显示答案图片'}
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
<div className="qa-answer-markdown">
|
||||
<Markdown
|
||||
remarkPlugins={[remarkGfm]}
|
||||
skipHtml
|
||||
urlTransform={safeAnswerURL}
|
||||
components={{
|
||||
a: ({ href, children }) =>
|
||||
href ? (
|
||||
<a href={href} target="_blank" rel="noopener noreferrer" referrerPolicy="no-referrer">
|
||||
{children}
|
||||
</a>
|
||||
) : (
|
||||
<span>{children}</span>
|
||||
),
|
||||
img: ({ src, alt }) =>
|
||||
src ? (
|
||||
showImages ? (
|
||||
<img src={src} alt={alt ?? ''} loading="lazy" referrerPolicy="no-referrer" />
|
||||
) : (
|
||||
<a href={src} target="_blank" rel="noopener noreferrer" referrerPolicy="no-referrer">
|
||||
查看图片{alt ? `:${alt}` : ''}
|
||||
</a>
|
||||
)
|
||||
) : (
|
||||
<span>{alt || '图片地址不可用'}</span>
|
||||
),
|
||||
}}
|
||||
>
|
||||
{answer}
|
||||
</Markdown>
|
||||
</div>
|
||||
<details className="qa-answer-source">
|
||||
<summary>查看 Markdown 原文</summary>
|
||||
<pre>{answer}</pre>
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { renderToStaticMarkup } from 'react-dom/server'
|
||||
import { describe, it, expect, vi } from 'vitest'
|
||||
import { qaDailySeries, qaCategorySeries } from './qaDashboard'
|
||||
import { QADashboardView } from './QADashboard'
|
||||
import { parseQADashboard } from './qaDashboardData'
|
||||
import { dashboardFixture } from './qaDashboard.fixture'
|
||||
import type { QARecord, QAQuery } from './qaOps'
|
||||
const query: QAQuery = { start: '2026-10-11T16:00:00Z', end: '2026-10-13T16:00:00Z', keyword: '', cursor: '' }
|
||||
const records = [
|
||||
{ id: 'a', asked_at: '2026-10-11T16:30:00Z', product_category: '<img src=x onerror=alert(1)>', problem_type: '通信' },
|
||||
{ id: 'b', asked_at: '2026-10-12T16:01:00Z' },
|
||||
] as QARecord[]
|
||||
describe('question dashboard projections', () => {
|
||||
it('groups by Beijing day and keeps zero days instead of using the browser timezone', () => {
|
||||
expect(qaDailySeries(records, query)).toEqual([
|
||||
{ label: '2026-10-12', count: 1 },
|
||||
{ label: '2026-10-13', count: 1 },
|
||||
])
|
||||
expect(qaDailySeries([], query).map((p) => p.count)).toEqual([0, 0])
|
||||
})
|
||||
it('keeps unclassified records distinct without inventing a category', () => {
|
||||
expect(qaCategorySeries(records, 'problem_type')).toEqual([
|
||||
{ label: '通信', count: 1 },
|
||||
{ label: '未分类', count: 1 },
|
||||
])
|
||||
})
|
||||
it('renders the real dashboard panels and escaped category text', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
<QADashboardView data={parseQADashboard(dashboardFixture)} loading={false} error="" onRetry={vi.fn()} />
|
||||
)
|
||||
for (const title of ['问题总数', '本周新增', '覆盖率趋势', '正确率趋势', '产品问题排行', '导出看板图片'])
|
||||
expect(html).toContain(title)
|
||||
expect(html).not.toContain('<img src=x')
|
||||
expect((html.match(/data-panel=/g) || []).length).toBe(11)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import type { QAQuery } from './qaOps'
|
||||
import { fetchQADashboard } from './qaDashboardData'
|
||||
import type { QADashboardData } from './qaDashboardData'
|
||||
import { QADashboardDrawing } from './QADashboardDrawing'
|
||||
import { createDashboardPNG } from './qaDashboardExport'
|
||||
import { currentQAWeek } from './qaWeeks'
|
||||
import { QAMonthly } from './QAMonthly'
|
||||
import './qaDashboard.css'
|
||||
export interface QADashboardProps {
|
||||
data: QADashboardData | null
|
||||
loading: boolean
|
||||
error: string
|
||||
onRetry: () => void
|
||||
}
|
||||
export function QADashboardView({ data, loading, error, onRetry }: QADashboardProps) {
|
||||
const host = useRef<HTMLDivElement>(null),
|
||||
svg = useRef<SVGSVGElement>(null)
|
||||
const [width, setWidth] = useState(1280),
|
||||
[exporting, setExporting] = useState(false),
|
||||
[exportError, setExportError] = useState('')
|
||||
useEffect(() => {
|
||||
const element = host.current
|
||||
if (!element) return
|
||||
const update = () => setWidth(Math.max(240, Math.floor(element.clientWidth)))
|
||||
update()
|
||||
const observer = new ResizeObserver(update)
|
||||
observer.observe(element)
|
||||
return () => observer.disconnect()
|
||||
}, [])
|
||||
useEffect(() => setExportError(''), [data])
|
||||
async function download() {
|
||||
if (!svg.current || !data || loading || error || exporting) return
|
||||
setExporting(true)
|
||||
setExportError('')
|
||||
try {
|
||||
const blob = await createDashboardPNG(svg.current),
|
||||
url = URL.createObjectURL(blob),
|
||||
link = document.createElement('a'),
|
||||
week = currentQAWeek(new Date(data.week_start))
|
||||
link.href = url
|
||||
link.download = `DobotAI_QA_Dashboard_${week.year}_W${String(week.week).padStart(2, '0')}.png`
|
||||
document.body.append(link)
|
||||
link.click()
|
||||
link.remove()
|
||||
window.setTimeout(() => URL.revokeObjectURL(url), 1000)
|
||||
} catch (e) {
|
||||
setExportError(e instanceof Error ? e.message : '看板图片生成失败')
|
||||
} finally {
|
||||
setExporting(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<section className="qa-dashboard" aria-label="问题统计看板">
|
||||
<div className="qa-dashboard-toolbar">
|
||||
<button type="button" disabled={!data || loading || !!error || exporting} onClick={() => void download()}>
|
||||
{exporting ? '正在生成图片…' : '导出看板图片'}
|
||||
</button>
|
||||
</div>
|
||||
{error ? (
|
||||
<div role="alert" className="error-banner">
|
||||
{error}{' '}
|
||||
<button type="button" onClick={onRetry}>
|
||||
重新读取
|
||||
</button>
|
||||
</div>
|
||||
) : null}
|
||||
{exportError ? (
|
||||
<div role="alert" className="error-banner">
|
||||
{exportError}
|
||||
</div>
|
||||
) : null}
|
||||
{loading ? <p role="status">正在读取完整统计范围…</p> : null}
|
||||
<div className="qa-dashboard-canvas" ref={host}>
|
||||
{!loading && !error && data ? <QADashboardDrawing data={data} width={width} svgRef={svg} /> : null}
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
export function QADashboard({
|
||||
query,
|
||||
error,
|
||||
revision,
|
||||
onRetry,
|
||||
}: {
|
||||
query: QAQuery | null
|
||||
error: string | null
|
||||
revision: number
|
||||
onRetry: () => void
|
||||
}) {
|
||||
const [data, setData] = useState<QADashboardData | null>(null),
|
||||
[failure, setFailure] = useState(''),
|
||||
[loading, setLoading] = useState(false),
|
||||
[monthly, setMonthly] = useState(false)
|
||||
useEffect(() => {
|
||||
setData(null)
|
||||
setFailure('')
|
||||
if (!query) {
|
||||
setLoading(false)
|
||||
return
|
||||
}
|
||||
const abort = new AbortController()
|
||||
setLoading(true)
|
||||
void fetchQADashboard(query, abort.signal)
|
||||
.then((v) => {
|
||||
if (!abort.signal.aborted) setData(v)
|
||||
})
|
||||
.catch((e) => {
|
||||
if (!abort.signal.aborted) setFailure(e instanceof Error ? e.message : '统计看板读取失败')
|
||||
})
|
||||
.finally(() => {
|
||||
if (!abort.signal.aborted) setLoading(false)
|
||||
})
|
||||
return () => abort.abort()
|
||||
}, [query, revision])
|
||||
return (
|
||||
<div className="qa-dashboard-scroll">
|
||||
<QADashboardView data={data} loading={loading} error={error || failure} onRetry={onRetry} />
|
||||
<details className="qa-monthly-disclosure" onToggle={(e) => setMonthly(e.currentTarget.open)}>
|
||||
<summary>个人月明细</summary>
|
||||
{monthly ? <QAMonthly /> : null}
|
||||
</details>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user