Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
00f97a4e8a | ||
|
|
252709709c |
No files matched your search
@@ -0,0 +1,39 @@
|
||||
# Module Boundary Summary
|
||||
|
||||
## Module Scope
|
||||
|
||||
- Target area: 字段映射与规则判断。新的映射、规则、输入修订和试算,挂在已有查询定义上。
|
||||
- Related areas: 查询定义与只读预览;控制台页面;管理员角色门禁。
|
||||
- Cross-area impact: 试算会调用查询当前版本的预览。不改查询正文、版本不可变和 SQL Server 拒绝试跑。报警、场景、通知不在本模块落表。
|
||||
|
||||
## Modifiability
|
||||
|
||||
- Modifiable: `services/watchman` 中新增的映射/规则/输入代码、新迁移、对应测试;确认原型之后的 `web/apps/console` 新页面;`docs/tasks/M05.md`、`docs/progress.md`、`docs/decisions.md`。
|
||||
- Restricted areas: 查询执行器只可调用,不可放宽只读和 SQL Server 限制。权限检查沿用服务端角色门禁。
|
||||
- Forbidden areas: 报警、场景、Cron、企微、原因分析;`.env.local`、`.cursor/mcp.json`;生产库和未授权提交。
|
||||
|
||||
## Loaded Context
|
||||
|
||||
- `docs/project/knowledge-map.md` 的产品范围、公司规范、控制台界面。
|
||||
- `docs/current/frontend-ui.md` 由 D25 指向,列表和页脚在实现 UI 时读取。
|
||||
- 未把 `docs/target/` 当作当前行为。
|
||||
|
||||
## Dependency Direction
|
||||
|
||||
查询定义和预览结果流向映射。映射的列流向规则。规则试算只读这些列。报警以后读取输入身份,本模块不反向依赖报警。
|
||||
|
||||
## Boundary Risks
|
||||
|
||||
- 身份修订若写成新输入,会把 M06 的去重做坏。
|
||||
- 权限点不能在需求里编造后直接当已注册编码。
|
||||
- 迁移版本号与查询迁移串行,不能并行改 `migrations/versions`。
|
||||
|
||||
## Recommended Modification Path
|
||||
|
||||
1. 先持久化映射和版本,再写身份修订,再写规则结构,再写纯计算。
|
||||
2. 接口和权限放在计算可用之后。
|
||||
3. HTML 原型确认后才写 Vue。
|
||||
|
||||
## Uncertainty
|
||||
|
||||
- 新权限点的注册表里还没有映射/规则编码。实现该切片时再核对规范,对不上就停。
|
||||
@@ -0,0 +1,133 @@
|
||||
# Task Context Pack
|
||||
|
||||
## Task Goal
|
||||
|
||||
实现 M05:查询上的字段映射、可配置身份、结构化规则,以及正常/异常/未知试算。不创建报警。
|
||||
|
||||
## Knowledge Posture
|
||||
|
||||
- Mode: standard
|
||||
- Maturity: L1
|
||||
|
||||
## Current Slice Or Group
|
||||
|
||||
S6 HTML 原型已给出。S7 未批准,须先确认原型。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- Recommended: strict
|
||||
- Selected: autonomous
|
||||
- finalApprovalRequired: true
|
||||
- Policy Notes: 配置默认是 balanced。用户指定 autonomous。该选择不取消分析确认、计划 critic、`risk_score >= 4`、原型确认和最终验收。
|
||||
|
||||
## Bugfix Context
|
||||
|
||||
本任务不是缺陷修复。
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-18/m05-mapping-rules/requirement.md`
|
||||
|
||||
## Implementation Source
|
||||
|
||||
`.task/2026-11-18/m05-mapping-rules/implementation-plan.md`
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
查询定义(只调用预览)、新建映射与规则、控制台新页面、管理员门禁。
|
||||
|
||||
## Loaded Context
|
||||
|
||||
### Global Rules
|
||||
|
||||
`AGENTS.md` 项目本地段要求一个会话聚焦 M05,主 Agent 不代替独立审查。公司规范篇目在写代码前按切片再查最新版本。
|
||||
|
||||
### Knowledge Map Matches
|
||||
|
||||
产品范围指向 `docs/progress.md`、`docs/decisions.md`。控制台界面指向 `docs/current/frontend-ui.md`,只在 S7 读取。
|
||||
|
||||
### Path-Proximity Rules
|
||||
|
||||
目标目录下没有另外的 `MODULE_RULES.md`。
|
||||
|
||||
### Excluded Context
|
||||
|
||||
未读阶段 B/C 文档,未读 Cron 复用文档。那些属于 M08 及以后。
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- `AGENTS.md`
|
||||
- `.cursor/rules/sy-standards.mdc`
|
||||
- `.cursor/rules/workflow-rules.mdc`
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `docs/tasks/INDEX.md`
|
||||
- `docs/decisions.md`(D27)
|
||||
- `需求冻结文档_V1.1_交接稿.md` 第 5~6 章
|
||||
- `.task/2026-11-18/m05-mapping-rules/boundary.md`
|
||||
|
||||
## Execution Mode
|
||||
|
||||
- Mode: sequential
|
||||
- Current Slice Or Group: S6
|
||||
- Parallel Members: 无
|
||||
- Fallback Order: S1 到 S8
|
||||
- Shared Files: `services/watchman/migrations`、`auth/access.py`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 迁移和权限串行
|
||||
- Validation Level: slice
|
||||
|
||||
## Execution Chain
|
||||
|
||||
计划确认 → 计划 critic → S1 → 审查 → 因 S2 为 risk 4 而停下。后续每片按计划里的 gateClass 和 risk_score 决定是否还要单独确认。
|
||||
|
||||
## Allowed Modification Scope
|
||||
|
||||
确认 S1 之后,只允许计划中 S1 的路径。当前允许的写入只有任务文档。
|
||||
|
||||
## Forbidden Modification Scope
|
||||
|
||||
报警、场景、Cron、企微、查询只读边界、原型确认前的 Vue、密钥文件。
|
||||
|
||||
## Key Existing Classes Or Entrypoints
|
||||
|
||||
- 查询:`services/watchman/src/watchman/api/routes/queries.py`、`services/watchman/src/watchman/services/queries.py`
|
||||
- 权限:`services/watchman/src/watchman/auth/access.py` 中的 `watchman-admin` 与 `perm:data:emp:watchman.query.*`
|
||||
- 控制台查询页:`web/apps/console/src/queries/`
|
||||
|
||||
## Required Behavior
|
||||
|
||||
以 requirement.md 的 Business Rules 和 Acceptance Criteria 为准。结论用正常、异常、未知。不勾身份列时多行取第一行并提示跳过行数。
|
||||
|
||||
## Non-goals
|
||||
|
||||
报警、场景、原因分析、脚本、SQL Server 试跑。
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
见实现计划。当前不执行。
|
||||
|
||||
## Validation Commands
|
||||
|
||||
- 后端:在 `services/watchman` 运行 `uv run pytest`
|
||||
- 迁移:`alembic upgrade head`
|
||||
- 前端:在 `web/apps/console` 运行 `pnpm test:unit`
|
||||
- UI 切片另加 Playwright。未跑的命令记为未运行。
|
||||
|
||||
## Assumptions
|
||||
|
||||
与 requirement.md 的 Assumptions 相同。其中版本方式、嵌套深度 4、普通试算不落库,用户还没单独点名,但是按 D26 和“试算不产生报警”写下的。
|
||||
|
||||
## Risks
|
||||
|
||||
第一行依赖结果顺序。身份修订不能变成新业务事件。权限点编码实现时再核对。
|
||||
|
||||
## Stop Conditions
|
||||
|
||||
- 用户尚未确认本计划。
|
||||
- S1 前的计划 critic 尚未通过。
|
||||
- S4 前显式停下,即使 S3 已通过。判定语义不自动开写。
|
||||
- S7 前必须有原型确认。
|
||||
- 权限点规范与项目先例冲突时停下。
|
||||
- 最终 DONE_LOCAL 需要用户确认。
|
||||
@@ -0,0 +1,508 @@
|
||||
# M05 字段映射与规则判断 Implementation Plan
|
||||
|
||||
## Requirement Source
|
||||
|
||||
`.task/2026-11-18/m05-mapping-rules/requirement.md`(D27)
|
||||
|
||||
## Scope Summary
|
||||
|
||||
查询上的映射与规则、可配置身份、正常/异常/未知试算、原型确认后的控制台。不写报警和场景。
|
||||
|
||||
## Involved Modules Or Areas
|
||||
|
||||
- `services/watchman`:模型、迁移、映射、身份修订、规则校验、判定函数、API、权限。
|
||||
- `web/apps/console`:仅 S7,且 S6 原型已确认。
|
||||
- 查询预览只调用,不改只读边界。
|
||||
|
||||
## Loaded Rules
|
||||
|
||||
- `AGENTS.md` 项目本地段
|
||||
- `.cursor/rules/sy-standards.mdc`
|
||||
- `standards://api/permission-nodes?version=1.0.0`
|
||||
- `standards://api/api-envelope?version=1.1.0`
|
||||
- 本任务 `gatePolicy.selected=autonomous`,建议 strict
|
||||
|
||||
## Loaded Docs
|
||||
|
||||
- `docs/tasks/INDEX.md` M05
|
||||
- `docs/decisions.md` D05、D22、D24、D25、D26、D27
|
||||
- `docs/current/frontend-ui.md`(UI 切片再读)
|
||||
- `.task/2026-11-18/m05-mapping-rules/boundary.md`
|
||||
|
||||
## Global Forbidden Scope
|
||||
|
||||
- 报警、场景、Cron、企微、原因分析、任意脚本
|
||||
- 放宽 SQL Server 查询试跑或查询只读限制
|
||||
- 原型确认前修改 `web/apps/console` 的正式页面
|
||||
- `.env.local`、`.cursor/mcp.json`、凭证、生产库
|
||||
- `git reset --hard`、未授权 commit
|
||||
- 把未知写成报警,或把执行失败写成正常/未知
|
||||
|
||||
## Execution Strategy
|
||||
|
||||
- Complexity: complex
|
||||
- Default Execution: sequential
|
||||
- Parallel Execution: not-needed
|
||||
- Fallback Execution: sequential
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Resolution Rule: 迁移目录和权限模块串行;后一片不得改前一片已冻结的结论枚举。
|
||||
|
||||
开工前先做一次计划 critic。Tier L 的 reviewLevel 为 critic-required,这里把它写成 S1 之前的显式停点。autonomous 不跳过它,也不跳过 `risk_score >= 4` 和原型确认。
|
||||
|
||||
## Slice Dependency Graph
|
||||
|
||||
| Slice | Depends On | Can Run In Parallel With | Fallback Order | Shared Files | Merge Owner | Conflict Risk |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| S1 映射与版本 | 计划确认且 critic 通过 | 无 | 1 | `services/watchman/migrations` | 主 Agent | high |
|
||||
| S2 身份与修订 | S1 | 无 | 2 | `services/watchman/migrations` | 主 Agent | high |
|
||||
| S3 规则结构 | S1 | 无 | 3 | `services/watchman/migrations` | 主 Agent | high |
|
||||
| S4 判定函数 | S3 | 无 | 4 | 无共享迁移 | 主 Agent | low |
|
||||
| S5 API 与权限 | S2、S4 | 无 | 5 | `auth/access.py` | 主 Agent | high |
|
||||
| S6 HTML 原型 | S5 的字段口径 | 无 | 6 | `.task/.../prototype` | 主 Agent | low |
|
||||
| S7 Vue | S6 用户确认原型 | 无 | 7 | `web/apps/console` | 主 Agent | medium |
|
||||
| S8 模块审查与测试 | S7 | 无 | 8 | 证据目录 | 主 Agent | low |
|
||||
|
||||
## Implementation Slices
|
||||
|
||||
### Slice 1: 映射模型与不可变版本
|
||||
|
||||
#### Goal
|
||||
|
||||
能保存映射:所属查询、选用列、类型、身份勾选、乘数和偏移;保存产生不可变版本并设为当前版本。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/models/`
|
||||
- `services/watchman/src/watchman/services/` 中新建的映射服务
|
||||
- `services/watchman/migrations/versions/`
|
||||
- `services/watchman/tests/` 中本切片测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 规则判定、API 路由、前端、报警表
|
||||
- 既有查询迁移文件的改写
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: 分析确认,且计划 critic 通过
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 任何其他迁移切片
|
||||
- Fallback Order: 1
|
||||
- Shared Files: `services/watchman/migrations`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: database-schema, immutable-version
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 单人实现后独立审查
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 映射定义、列配置、不可变版本和当前版本指针。新表都带 `tenant_id`,按 `20261118_0006` 的形式 `ENABLE`/`FORCE ROW LEVEL SECURITY`、建立 `tenant_isolation` 策略,并 `GRANT` 给 `watchman_app`。
|
||||
2. 保存即新版本。历史版本不可更新、不可删除。数据库层沿用 `20261118_0007`:对版本表 `REVOKE UPDATE, DELETE`,并加语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器。
|
||||
3. 列类型只接受数值、文本、布尔、日期时间。身份列为布尔标记。每条映射最多一列可标为观测时间,该标记不代替身份列。换算只存乘数和偏移。日期时间列与比较值用 `timestamptz`;无时区的值在进入比较前即为非法,不按机器本地时区解释。比较归一到 UTC。
|
||||
4. 对照查询当前版本的输出列;缺失列拒绝保存。
|
||||
|
||||
#### Validation
|
||||
|
||||
- 在 `services/watchman` 运行 `uv run pytest`,至少包含:跨租户读写被拒;对历史映射版本 `UPDATE` 被拒;对历史映射版本 `DELETE` 被拒。
|
||||
- `alembic upgrade head` 与对应 downgrade 都在真实 PostgreSQL 上跑通。SQLite 不能代替 FORCE RLS。命令没跑就记未运行,不记通过。
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 1 的数据侧成立:多列可保存,类型、身份标记和可选观测时间标记可回读。
|
||||
- 上述跨租户、UPDATE 被拒、DELETE 被拒三条测试实际通过。
|
||||
- 版本内容不可改,由数据库拒绝证明,不单靠服务层。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 向下迁移先 `DROP POLICY`,再删除触发器,然后删除本切片新增表。不改查询表。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
|
||||
|
||||
### Slice 2: 输入身份与修订
|
||||
|
||||
#### Goal
|
||||
|
||||
按 D27 持久化输入。勾选身份列时按列值唯一;不勾时每条映射只有一条输入。值变化追加修订,相同值不追加。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- S1 已建立的映射服务及其测试
|
||||
- 新的输入/修订模型与迁移
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 报警表、判定枚举的报警副作用、前端
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S1
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S3 同时写迁移
|
||||
- Fallback Order: 2
|
||||
- Shared Files: `services/watchman/migrations`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: input-identity, dedup-contract
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 单人实现后独立审查
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 唯一约束落在租户、映射加身份值上,不包含度量值和运行号。
|
||||
2. 不勾身份列时使用固定的映射级身份。
|
||||
3. 身份列为空的行拒绝形成输入。
|
||||
4. 度量变化写修订;相同度量不写新修订。
|
||||
5. 同一次结果里多行身份值相同:按返回顺序保留第一行,其余计入跳过重复行,不写第二条修订。
|
||||
6. 输入表和修订表同样带 `tenant_id`,按 S1 启用 FORCE RLS、`tenant_isolation` 和 `watchman_app` 授权,并有跨租户被拒测试。修订行追加后禁止 UPDATE/DELETE,强制方式与映射版本相同。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`:多身份、第一行策略的持久化入口、同身份重复行只留第一行、修订、重读
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 2、3 的持久化侧成立。
|
||||
- 测试证明运行号不会把同一身份拆开。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 向下迁移先 `DROP POLICY`、再删除修订表触发器,然后删除输入表和修订表。不删除映射定义。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
|
||||
|
||||
### Slice 3: 规则结构校验
|
||||
|
||||
#### Goal
|
||||
|
||||
保存结构化条件。非法运算符、过深嵌套、空组、文本上的大小比较,在保存时拒绝。不执行用户代码。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- 规则模型、迁移、校验服务、测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 判定真值表实现放在 S4
|
||||
- 前端、报警
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S1
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S2 的迁移文件
|
||||
- Fallback Order: 3
|
||||
- Shared Files: `services/watchman/migrations`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: database-schema, reject-code-execution
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 单人实现后独立审查
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 规则属于映射,保存即不可变版本。规则定义和规则版本表带 `tenant_id`,按 S1 启用 FORCE RLS。规则版本在数据库层禁止 UPDATE/DELETE,方式与映射版本相同,并有 UPDATE 被拒、DELETE 被拒测试。
|
||||
2. 条件节点只含列引用、白名单运算符、比较值和 AND/OR。日期时间比较值必须带时区,缺时区在保存时拒绝。
|
||||
3. 深度上限 4。比较值类型须与列类型相容。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`:拒绝脚本片段、未知运算符、超深树、错误类型比较
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 非法规则不能保存。
|
||||
- 合法规则回读与提交结构一致。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 向下迁移先 `DROP POLICY`、再删除规则版本触发器,然后删除规则表。不删除映射表和输入表。downgrade 未在真实 PostgreSQL 跑通时,不得宣称可回滚。
|
||||
|
||||
### Slice 4: 正常/异常/未知计算
|
||||
|
||||
#### Goal
|
||||
|
||||
纯函数按冻结真值表计算。缺失与非法都得出未知,但原因不同。换算只使用已配置的乘数和偏移。执行失败不进入这三种结论。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- 判定与映射转换的纯函数及测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 写报警、改身份唯一约束、前端
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S3
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 4
|
||||
- Shared Files: 无
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: standard
|
||||
- Risk Score: 3
|
||||
- Gate Reasons: judgment-semantics, explicit-stop-before-slice
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 测试先固定真值表,再写函数
|
||||
|
||||
S4 固化判定语义。即便上一片是已批准的 S3,开始 S4 前仍停下确认真值表测试范围。autonomous 不跳过这个显式停点。
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 固定 AND/OR 和比较边界的测试,用 `normal`/`abnormal`/`unknown` 做断言,展示文案仍是正常、异常、未知。
|
||||
2. 实现转换:缺失保持缺失;非法不变成 0 或空字符串。
|
||||
3. 未配置换算的单位差记为非法。
|
||||
4. 多行且无身份列时,计算只用第一行,并返回跳过行数。
|
||||
5. 零行返回空结果,不返回正常、未知或执行失败。
|
||||
6. 至少一条跨时区用例:同一时刻的两个带时区值比较为相等;无时区值记为非法。
|
||||
7. 当前查询版本已删除映射列时,计算拒绝并指出缺失列,不静默跳过。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest` 覆盖验收标准 4、5、6 的计算部分
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 真值表测试通过。
|
||||
- 没有一条测试把执行异常断言成未知。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 删除判定函数不影响已写入的映射版本。
|
||||
|
||||
### Slice 5: API 与权限
|
||||
|
||||
#### Goal
|
||||
|
||||
管理员可以维护映射、规则并试算。其他角色被拒绝。普通试算不写正式输入。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `services/watchman/src/watchman/api/`
|
||||
- `services/watchman/src/watchman/auth/access.py` 及对应依赖
|
||||
- API 测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 新角色名、前端页面、报警路由
|
||||
- 未对照权限点规范就发明另一套检查
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S2、S4
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 5
|
||||
- Shared Files: `auth/access.py`
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: high
|
||||
- Gate Class: high-risk
|
||||
- Risk Score: 4
|
||||
- Gate Reasons: permissions, api-contract
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 先核对 `standards://api/permission-nodes?version=1.0.0`,编码与查询模块先例不一致时停
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 读写和试算只允许 `watchman-admin`。试算复用既有查询预览执行器,不新写一套只读执行。SQL Server 仍拒绝试跑。预览所用权限点先核对规范:能沿用 `perm:data:emp:watchman.query.preview` 就沿用;要新编码时对不上注册表就停。
|
||||
2. 信封按 `standards://api/api-envelope?version=1.1.0`。
|
||||
3. 结论码用 `normal`、`abnormal`、`unknown`。界面只显示正常、异常、未知。不把中文词写成数据库枚举。
|
||||
4. 试算响应分开:结论、缺失、非法、无法形成身份、采用第一行、同身份重复行被跳过、空结果、映射列在当前查询版本中已不存在、执行失败。
|
||||
5. 查询预览失败时不返回正常或未知。零行不返回正常。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`:管理员成功,操作者与查看者拒绝,试算无报警行
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 7 的“试算不产生报警”和验收标准 8 成立。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 去掉新路由和权限函数。不改查询权限点的含义。
|
||||
|
||||
### Slice 6: HTML 原型
|
||||
|
||||
#### Goal
|
||||
|
||||
用静态页面把映射、规则和试算走通,供确认后再写 Vue。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `.task/2026-11-18/m05-mapping-rules/prototype/`
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- `web/apps/console` 正式页面
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S5 的响应字段
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: S7
|
||||
- Fallback Order: 6
|
||||
- Shared Files: 无
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: simple
|
||||
- Risk Score: 2
|
||||
- Gate Reasons: prototype-before-vue
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 主 Agent 给出原型并停下等确认
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 列表、映射表单、规则条件、预览结果。
|
||||
2. 按钮位置按 D22、D25 的静态结构摆放。
|
||||
3. 文案使用正常、异常、未知。
|
||||
|
||||
#### Validation
|
||||
|
||||
- 人工打开原型,核对多列、身份列可空、第一行提示、三种结论。
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 原型覆盖验收标准 1、2、6 的可见部分。
|
||||
- 用户确认前不开始 S7。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 删除原型目录不影响服务。
|
||||
|
||||
### Slice 7: Vue 控制台
|
||||
|
||||
#### Goal
|
||||
|
||||
按已确认原型做控制台页面,接上 S5 的接口。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- `web/apps/console/src/` 下新建的映射与规则页面、路由和本模块测试
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 未确认原型就改页面
|
||||
- 查询编辑页的行为改变,除非只增加入口链接
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S6 的用户确认
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 7
|
||||
- Shared Files: 控制台路由
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: medium
|
||||
- Gate Class: standard
|
||||
- Risk Score: 3
|
||||
- Gate Reasons: prototype-confirmed, ui-contract
|
||||
- Validation Level: slice
|
||||
- Recommended Agent Strategy: 对照 `standards://frontend/frontend-stack` 与 `standards://frontend/element-plus` 的最新版本
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 实现前重读 `docs/current/frontend-ui.md`。
|
||||
2. 列表、编辑、试算。
|
||||
3. 页面按钮位置按 D22、D25。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `pnpm test:unit`(`web/apps/console`)
|
||||
- 浏览器走通保存、重开、试算、非管理员不可写
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 验收标准 1、2、6、7 的界面侧成立。
|
||||
- 试算结果与接口一致。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 撤回新页面和路由入口。不删服务端数据。
|
||||
|
||||
### Slice 8: 模块审查与正式测试
|
||||
|
||||
#### Goal
|
||||
|
||||
对 S1~S7 做一次整体独立审查,并在通过的候选上跑正式测试。
|
||||
|
||||
#### Allowed Modification Scope
|
||||
|
||||
- 审查指出的切片内缺陷
|
||||
- `docs/tasks/M05.md`、`docs/progress.md`、`docs/evidence/M05/`
|
||||
|
||||
#### Forbidden Scope
|
||||
|
||||
- 借修复扩大到报警或场景
|
||||
- 未重新审查就标 DONE_LOCAL
|
||||
|
||||
#### Execution
|
||||
|
||||
- Mode: sequential
|
||||
- Depends On: S7
|
||||
- Can Run With: 无
|
||||
- Must Not Run With: 无
|
||||
- Fallback Order: 8
|
||||
- Shared Files: 证据目录
|
||||
- Merge Owner: 主 Agent
|
||||
- Conflict Risk: low
|
||||
- Gate Class: boundary-sensitive
|
||||
- Risk Score: 3
|
||||
- Gate Reasons: module-acceptance
|
||||
- Validation Level: final
|
||||
- Recommended Agent Strategy: 审查用与实现不同的模型系列;审查者默认不改代码
|
||||
|
||||
#### Steps
|
||||
|
||||
1. 独立审查边界、真值表、身份和权限。
|
||||
2. 修复后再审,最多三轮,然后停下来问。
|
||||
3. 正式 pytest、前端单测、Playwright 和截图。
|
||||
|
||||
#### Validation
|
||||
|
||||
- `uv run pytest`
|
||||
- `pnpm test:unit`
|
||||
- Playwright 覆盖映射保存、试算三种结论、第一行提示
|
||||
|
||||
#### Done Criteria
|
||||
|
||||
- 审查通过,命令实际跑过,证据路径写在 `docs/tasks/M05.md`。
|
||||
- DONE_LOCAL 仍等用户最终确认。
|
||||
|
||||
#### Rollback Notes
|
||||
|
||||
- 不回滚已通过的迁移,除非审查认定迁移本身错误。那种情况先停。
|
||||
|
||||
## Parallel Slice Groups
|
||||
|
||||
无。迁移和权限文件串行。
|
||||
|
||||
## Final Validation
|
||||
|
||||
- 后端 `uv run pytest`
|
||||
- 控制台 `pnpm test:unit`
|
||||
- 映射与试算的 Playwright
|
||||
- 非管理员拒绝的接口测试
|
||||
|
||||
## Documentation Update Requirement
|
||||
|
||||
- 实现过程更新 `docs/tasks/M05.md` 与 `docs/progress.md`。
|
||||
- S8 同步 `docs/tasks/INDEX.md` 里 M05 的 PASS/FAIL/UNKNOWN 措辞,改为正常/异常/未知。M06 里「不改原始 FAIL」改成「不改原始异常判定」,不改变 M06 的范围。
|
||||
- 行为口径有变时才改 `docs/decisions.md`。
|
||||
- 不把源码清单写进 `docs/project/knowledge-map.md`。
|
||||
|
||||
## Risks
|
||||
|
||||
- S2 的第一行策略依赖查询顺序。计划里已写成假设,测试要用有 ORDER BY 的样例,并另有一条记录“无排序时第一行不稳定”。
|
||||
- S5 的权限点若规范不允许按查询模块先例新增,该切片停止,不改用前端隐藏代替。
|
||||
@@ -0,0 +1,46 @@
|
||||
# Task Intake Result
|
||||
|
||||
## Task Type
|
||||
|
||||
feature。Tier L(新模块、迁移、输入身份、判定语义;后续报警与场景会依赖这份契约)。
|
||||
|
||||
## Current Understanding
|
||||
|
||||
- M04 已 DONE_LOCAL。本会话推进 M05:字段映射、类型/空值、输入身份、结构化规则、PASS/FAIL/UNKNOWN、样例测试(INDEX;A-021~A-026;冻结稿 A-04、第 6 章)。
|
||||
- 不做:报警创建/合并(M06)、场景草稿与 Cron(M08)、规则原因分析(M12)、任意脚本、数据质量规则转人工。
|
||||
- O06 仍 OPEN。已确认的只有 D05:同一输入不重新触发;关闭后新周期或新独立事件可新建。同周期值更正如何改报警,不在本模块自行决定。
|
||||
- 查询侧已有不可变版本、`current_version_no`、只读预览(PostgreSQL/MySQL)。SQL Server 查询试跑仍不做。
|
||||
|
||||
## Gate Policy
|
||||
|
||||
- config/default: balanced
|
||||
- allowTaskOverride: true
|
||||
- recommended: strict
|
||||
- selected: autonomous
|
||||
- reason or override reason: 用户在本任务入口明确指定 autonomous。建议 strict 是因为有迁移、输入身份和判定语义,且 tier-policy 对 Tier L 的 gateHint 为 prefer-strict。建议不覆盖用户选择。
|
||||
- effective: autonomous
|
||||
- finalApprovalRequired: true
|
||||
|
||||
autonomous 不取消:分析到编码的确认、最终验收、high-risk/boundary-sensitive、需要 critic 的切片、显式停点、危险命令,以及 `risk_score >= 4`。
|
||||
|
||||
## Blocking Questions
|
||||
|
||||
已关闭(D27)。身份列可配置、可为空;不勾时多行取结果顺序的第一行。日期只是可选身份列。
|
||||
|
||||
## Non-blocking Assumptions
|
||||
|
||||
- 版本方式沿用 D26:保存即插入不可变版本并设为当前;可激活历史版本。不恢复草稿/发布两步。
|
||||
- 权限沿用查询模块:仅 `watchman-admin`。公司权限点规范(`standards://api/permission-nodes?version=1.0.0`)要求编码先存在于注册表,禁止编造。现有查询点是项目内 `perm:data:emp:watchman.query.*`,规范目录里没有映射/规则点。编码阶段再按同一项目先例声明,不在本轮把新编码写成已注册事实。
|
||||
- 正式 Vue 前先确认 HTML 原型(D21/D24 先例)。
|
||||
- 列表遵循 D25。
|
||||
- 比较运算符以冻结稿已列的等于、不等于、大于、大于等于、小于、小于等于为上限。不含正则、脚本、窗口和跨事件序列。
|
||||
- 条件嵌套深度上限暂按 4。空条件组在保存时拒绝。
|
||||
- 样例试算不创建报警、不发通知、不写正式运行。
|
||||
|
||||
## Recommended Next Step
|
||||
|
||||
用户确认计划。确认后做计划 critic,通过后再进入 S1。当前不编码。
|
||||
|
||||
## Suggested Prompt For Next Step
|
||||
|
||||
确认 M05 计划后做计划 critic,通过再实现 S1。不写业务代码,直到计划被确认。
|
||||
@@ -0,0 +1,294 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>Watchman M05 映射与规则 · 静态原型(S6)</title>
|
||||
<style>
|
||||
:root {
|
||||
--primary: #5e6ad2; --primary-soft: #eef0fb; --text: #1f2328; --text-2: #59636e; --muted: #8b949e;
|
||||
--surface: #ffffff; --soft: #f6f8fa; --border: #d0d7de; --border-2: #eaeef2;
|
||||
--ok: #1a7f37; --ok-bg: #e9f6ec; --warn: #9a6700; --warn-bg: #fff8e1; --err: #cf222e; --err-bg: #fdecee;
|
||||
--radius: 8px;
|
||||
--font: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", "Noto Sans CJK SC", sans-serif;
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html, body { margin: 0; height: 100%; }
|
||||
body { font-family: var(--font); font-size: 13.5px; color: var(--text); background: var(--soft); line-height: 1.55; }
|
||||
button, input, select { font: inherit; color: inherit; }
|
||||
[hidden] { display: none !important; }
|
||||
.proto { background: #fffbe6; border-bottom: 1px dashed #d4b106; padding: 8px 16px; display: flex; flex-wrap: wrap; gap: 8px 16px; align-items: center; font-size: 12.5px; }
|
||||
.proto-title { font-weight: 600; color: #7a5b00; }
|
||||
.proto-group { display: flex; align-items: center; gap: 6px; }
|
||||
.proto-btn { border: 1px solid var(--border); background: #fff; border-radius: 6px; padding: 2px 9px; cursor: pointer; }
|
||||
.proto-btn.on { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.proto-note { flex-basis: 100%; color: #7a5b00; }
|
||||
.shell { display: flex; height: calc(100vh - 78px); min-height: 520px; }
|
||||
.side { width: 196px; flex: none; background: var(--surface); border-right: 1px solid var(--border-2); padding: 14px 10px; display: flex; flex-direction: column; }
|
||||
.brand { font-weight: 700; font-size: 16px; padding: 4px 10px 14px; }
|
||||
.nav-item { padding: 7px 10px; border-radius: 6px; color: var(--text-2); }
|
||||
.nav-item.cur { background: var(--primary-soft); color: var(--primary); font-weight: 600; }
|
||||
.nav-item.off { color: var(--muted); }
|
||||
.side .who { margin-top: auto; padding: 10px; color: var(--text-2); font-size: 12.5px; }
|
||||
.main { flex: 1; display: flex; flex-direction: column; min-width: 0; }
|
||||
.top { height: 48px; flex: none; background: var(--surface); border-bottom: 1px solid var(--border-2); display: flex; align-items: center; padding: 0 20px; }
|
||||
.crumb { color: var(--text-2); } .crumb b { color: var(--text); font-weight: 600; }
|
||||
.content { flex: 1; overflow: auto; padding: 16px 20px; min-height: 0; }
|
||||
.pagefoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); display: flex; align-items: center; justify-content: center; gap: 8px; padding: 12px 20px; }
|
||||
.listfoot { flex: none; background: var(--surface); border-top: 1px solid var(--border-2); display: flex; justify-content: flex-end; padding: 8px 20px; color: var(--text-2); font-size: 12.5px; }
|
||||
.tools { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; }
|
||||
.tools .grow { flex: 1; }
|
||||
.tools input, .tools select { width: 180px; }
|
||||
.btn { border: 1px solid var(--border); background: var(--surface); border-radius: 6px; padding: 5px 14px; cursor: pointer; }
|
||||
.btn.primary { background: var(--primary); border-color: var(--primary); color: #fff; }
|
||||
.btn.link { border: 0; background: none; color: var(--primary); padding: 1px 6px; }
|
||||
.btn:disabled { color: var(--muted); background: var(--soft); cursor: not-allowed; }
|
||||
input, select { border: 1px solid var(--border); border-radius: 6px; padding: 6px 10px; background: #fff; width: 100%; }
|
||||
.card { background: var(--surface); border: 1px solid var(--border-2); border-radius: var(--radius); padding: 16px 18px; margin-bottom: 16px; }
|
||||
.card h3 { margin: 0 0 12px; font-size: 14.5px; }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; font-weight: 600; color: var(--text-2); background: var(--soft); padding: 9px 12px; border-bottom: 1px solid var(--border-2); }
|
||||
td { padding: 8px 12px; border-bottom: 1px solid var(--border-2); vertical-align: middle; }
|
||||
.table-wrap { border: 1px solid var(--border-2); border-radius: var(--radius); background: #fff; overflow: auto; }
|
||||
.ops { white-space: nowrap; width: 196px; text-align: right; }
|
||||
.modal-mask { position: fixed; inset: 0; background: rgba(31,35,40,.4); display: flex; align-items: center; justify-content: center; z-index: 20; }
|
||||
.modal { background: #fff; border-radius: var(--radius); padding: 18px 20px; width: 640px; max-width: 92vw; max-height: 80vh; overflow: auto; }
|
||||
.modal h3 { margin: 0 0 8px; font-size: 15px; }
|
||||
.modal .actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 14px; }
|
||||
.tag { display: inline-block; padding: 0 8px; border-radius: 10px; font-size: 12px; line-height: 20px; }
|
||||
.tag.abnormal { background: var(--err-bg); color: var(--err); }
|
||||
.tag.normal { background: var(--ok-bg); color: var(--ok); }
|
||||
.tag.unknown { background: var(--warn-bg); color: var(--warn); }
|
||||
.tag.grey { background: var(--soft); color: var(--text-2); border: 1px solid var(--border-2); }
|
||||
.miss { background: #fff8e1; }
|
||||
.badcell { background: var(--err-bg); }
|
||||
.note { border-radius: var(--radius); padding: 8px 12px; font-size: 12.5px; background: var(--soft); border: 1px solid var(--border-2); color: var(--text-2); margin-bottom: 12px; }
|
||||
.note.warn { background: var(--warn-bg); border-color: #f1dc9a; color: var(--warn); }
|
||||
.flash { border-radius: var(--radius); padding: 8px 12px; margin-bottom: 12px; background: var(--ok-bg); border: 1px solid #b7e0c2; color: #145c2a; }
|
||||
.empty { text-align: center; padding: 56px 20px; background: #fff; border: 1px dashed var(--border); border-radius: var(--radius); }
|
||||
.result { border-radius: var(--radius); padding: 12px 14px; border: 1px solid; margin-top: 12px; }
|
||||
.result.abnormal { background: var(--err-bg); border-color: #f4b8be; }
|
||||
.result.normal { background: var(--ok-bg); border-color: #b7e0c2; }
|
||||
.result.unknown { background: var(--warn-bg); border-color: #f1dc9a; }
|
||||
.result.empty { background: var(--soft); border-color: var(--border); }
|
||||
.result.error { background: var(--err-bg); border-color: #f4b8be; }
|
||||
.hint { color: var(--muted); font-size: 12px; }
|
||||
.mono { font-family: ui-monospace, Consolas, monospace; font-size: 12.5px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="proto">
|
||||
<span class="proto-title">静态原型 · 不是正式页面</span>
|
||||
<span class="proto-group"><span>角色</span>
|
||||
<button class="proto-btn on" data-role="admin">管理员</button>
|
||||
<button class="proto-btn" data-role="operator">处理者</button>
|
||||
<button class="proto-btn" data-role="viewer">查看者</button>
|
||||
</span>
|
||||
<span class="proto-group"><span>试算样例</span>
|
||||
<button class="proto-btn on" data-out="abnormal">异常</button>
|
||||
<button class="proto-btn" data-out="normal">正常</button>
|
||||
<button class="proto-btn" data-out="missing">未知·缺失</button>
|
||||
<button class="proto-btn" data-out="invalid">未知·非法</button>
|
||||
<button class="proto-btn" data-out="empty">空结果</button>
|
||||
<button class="proto-btn" data-out="error">执行失败</button>
|
||||
<button class="proto-btn" data-out="first">只用第一行</button>
|
||||
</span>
|
||||
<div class="proto-note">映射和判断规则共用一个版本。切换版本时字段和条件一起换。基于某一版编辑后,另存为新版本,旧版本不改。</div>
|
||||
</div>
|
||||
<div class="shell">
|
||||
<aside class="side">
|
||||
<div class="brand">预警平台</div>
|
||||
<div class="nav-item off">数据源</div>
|
||||
<div class="nav-item off">查询</div>
|
||||
<div class="nav-item cur">映射与规则</div>
|
||||
<div class="who" id="who">管理员</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<div class="top"><div class="crumb" id="crumb">预警平台 / <b>映射与规则</b></div></div>
|
||||
<div class="content" id="content"></div>
|
||||
<div class="pagefoot" id="foot" hidden></div>
|
||||
<div class="listfoot" id="listfoot" hidden>共 1 条</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="modal-mask" id="mask" hidden>
|
||||
<div class="modal" id="modal"></div>
|
||||
</div>
|
||||
<script>
|
||||
var state = { view: "list", role: "admin", outcome: "abnormal", flash: "", editing: null, ruleEditing: null };
|
||||
function col(name, label, type, extra) {
|
||||
extra = extra || {};
|
||||
return { name: name, label: label, type: type, identity: !!extra.identity, observe: !!extra.observe, multiply: extra.multiply || "", offset: extra.offset || "" };
|
||||
}
|
||||
var versions = [
|
||||
{ no: 1, columns: [col("temperature", "温度", "number"), col("pressure", "压力", "number")], rules: [{ column: "温度", op: "大于", value: "90" }] },
|
||||
{ no: 2, columns: [col("temperature", "温度", "number"), col("pressure", "压力", "number"), col("serial", "设备", "string", { identity: true }), col("observed_at", "观测时间", "datetime", { observe: true })], rules: [{ column: "温度", op: "大于", value: "80" }, { column: "压力", op: "大于", value: "10" }] }
|
||||
];
|
||||
var current = 2;
|
||||
var draft = null;
|
||||
|
||||
function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return { "&": "&", "<": "<", ">": ">", '"': """ }[c]; }); }
|
||||
|
||||
function render() {
|
||||
document.querySelectorAll("[data-role]").forEach(function (b) { b.classList.toggle("on", b.dataset.role === state.role); });
|
||||
document.querySelectorAll("[data-out]").forEach(function (b) { b.classList.toggle("on", b.dataset.out === state.outcome); });
|
||||
document.getElementById("who").textContent = { admin: "管理员", operator: "处理者", viewer: "查看者" }[state.role];
|
||||
var crumb = "预警平台 / <b>映射与规则</b>";
|
||||
if (state.view === "detail") crumb += " / <b>详情</b>";
|
||||
if (state.view === "trial") crumb += " / <b>试算</b>";
|
||||
document.getElementById("crumb").innerHTML = crumb;
|
||||
var denied = state.role !== "admin";
|
||||
var foot = document.getElementById("foot");
|
||||
var listfoot = document.getElementById("listfoot");
|
||||
foot.hidden = true;
|
||||
listfoot.hidden = true;
|
||||
var html = "";
|
||||
if (denied) {
|
||||
html = '<div class="empty"><h3>无法进入映射与规则</h3><p>只有管理员可以维护映射、规则和试算。</p></div>';
|
||||
} else if (state.view === "list") {
|
||||
listfoot.hidden = false;
|
||||
html = (state.flash ? '<div class="flash">' + esc(state.flash) + "</div>" : "") +
|
||||
'<div class="tools"><input id="qname" placeholder="名称" value="炉温"><select><option>全部查询</option><option>当前炉温</option></select>' +
|
||||
'<button class="btn" id="do-filter">查询</button><button class="btn" id="do-reset">重置</button><span class="grow"></span>' +
|
||||
'<button class="btn primary" id="go-new">新建</button></div>' +
|
||||
'<div class="table-wrap"><table><thead><tr><th>名称</th><th>查询</th><th>当前版本</th><th>身份列</th><th class="ops">操作</th></tr></thead><tbody><tr>' +
|
||||
"<td>炉温与压力</td><td>当前炉温</td><td>v" + current + "</td><td>" + identityText(version(current)) + "</td>" +
|
||||
'<td class="ops"><button class="btn link" id="go-detail">打开</button><button class="btn link" id="open-switch">切换版本</button><button class="btn link" id="go-trial">试算</button></td></tr></tbody></table></div>';
|
||||
} else if (state.view === "detail") {
|
||||
foot.hidden = false;
|
||||
var base = draft.base;
|
||||
var next = versions[versions.length - 1].no + 1;
|
||||
html = '<div class="note">正在基于 v' + base + " 编辑。保存后成为 v" + next + ",并设为当前版本。v" + base + " 不会被修改。</div>" +
|
||||
'<div class="card"><h3>选用列 <span class="hint">来源 v' + base + " · 当前生效 v" + current + '</span></h3><div class="table-wrap"><table><thead><tr><th>查询列</th><th>类型</th><th>身份</th><th>观测时间</th><th>乘数</th><th>偏移</th></tr></thead><tbody>' +
|
||||
draft.columns.map(function (c, i) {
|
||||
return "<tr><td>" + esc(c.label) + " <span class=\"mono\">" + esc(c.name) + "</span></td><td>" + esc(c.type) + "</td>" +
|
||||
'<td><input type="checkbox" data-id="' + i + '"' + (c.identity ? " checked" : "") + "></td>" +
|
||||
'<td><input type="checkbox" data-obs="' + i + '"' + (c.observe ? " checked" : "") + (c.type !== "datetime" ? " disabled" : "") + "></td>" +
|
||||
"<td>" + (c.type === "number" ? '<input data-mul="' + i + '" value="' + esc(c.multiply) + '" placeholder="不换算">' : "—") + "</td>" +
|
||||
"<td>" + (c.type === "number" ? '<input data-off="' + i + '" value="' + esc(c.offset) + '" placeholder="不换算">' : "—") + "</td></tr>";
|
||||
}).join("") + "</tbody></table></div></div>" +
|
||||
'<div class="card"><h3>判断规则 <span class="hint">与字段同属 v' + base + "</span></h3>" +
|
||||
'<div class="table-wrap"><table><thead><tr><th>列</th><th>比较</th><th>比较值</th></tr></thead><tbody>' +
|
||||
draft.rules.map(function (row, i) {
|
||||
return "<tr><td>" + esc(row.column) + '</td><td><select data-op="' + i + '"><option' + (row.op === "大于" ? " selected" : "") + '>大于</option><option' + (row.op === "大于等于" ? " selected" : "") + ">大于等于</option></select></td>" +
|
||||
'<td><input data-val="' + i + '" value="' + esc(row.value) + '"></td></tr>';
|
||||
}).join("") + "</tbody></table></div>" +
|
||||
'<p class="hint">条件描述异常。成立为异常,不成立为正常。这里没有单独的规则版本。</p></div>';
|
||||
foot.innerHTML = '<button class="btn" id="back-list">返回列表</button><button class="btn" id="open-switch">切换版本</button><button class="btn primary" id="save-map">另存为新版本</button>';
|
||||
} else {
|
||||
foot.hidden = false;
|
||||
html = trialHtml();
|
||||
foot.innerHTML = '<button class="btn" id="back-list">返回列表</button><button class="btn" id="go-detail">打开当前版本</button>';
|
||||
}
|
||||
document.getElementById("content").innerHTML = html;
|
||||
bind();
|
||||
}
|
||||
|
||||
function trialHtml() {
|
||||
var o = state.outcome;
|
||||
if (o === "empty") {
|
||||
return '<div class="result empty"><b>空结果</b><div>查询没有返回行。这不是正常,也不是未知,也不是执行失败。</div></div>';
|
||||
}
|
||||
if (o === "error") {
|
||||
return '<div class="result error"><b>执行失败</b><div>当前查询版本里已经没有映射列 temperature。没有给出正常、异常或未知。</div></div>';
|
||||
}
|
||||
var skip = "";
|
||||
if (o === "first" || !hasIdentity(version(current))) {
|
||||
skip = '<div class="note warn">未勾选身份列。本次结果有 3 行,采用第一行,跳过 2 行。换行顺序要靠查询自己排序。</div>';
|
||||
}
|
||||
var tempStatus = o === "missing" ? "缺失" : (o === "invalid" ? "非法" : "有效");
|
||||
var tempVal = o === "missing" ? "—" : (o === "invalid" ? "hot" : (o === "normal" ? "70" : "81.2"));
|
||||
var code = (o === "missing" || o === "invalid") ? "unknown" : (o === "normal" ? "normal" : "abnormal");
|
||||
var label = { unknown: "未知", normal: "正常", abnormal: "异常" }[code];
|
||||
var cls = o === "missing" ? "miss" : (o === "invalid" ? "badcell" : "");
|
||||
return skip + '<div class="card"><h3>映射结果</h3><div class="table-wrap"><table><thead><tr><th>列</th><th>原始值</th><th>转换后</th><th>字段状态</th></tr></thead><tbody>' +
|
||||
'<tr class="' + cls + '"><td>温度</td><td class="mono">' + esc(tempVal) + "</td><td class=\"mono\">" + esc(tempVal) + "</td><td>" + tempStatus + "</td></tr>" +
|
||||
"<tr><td>压力</td><td class=\"mono\">12</td><td class=\"mono\">12</td><td>有效</td></tr></tbody></table></div>" +
|
||||
'<p class="hint">缺失保持为空,不会变成 0。非法值不会变成空字符串。两者的结论都是未知,但状态不同。</p></div>' +
|
||||
'<div class="result ' + code + '"><b>' + label + '</b><div>温度大于 80 且压力大于 10。实际温度 ' + esc(tempVal) + ",比较值 80。</div>" +
|
||||
'<div class="hint">接口码 ' + code + " · 版本 v" + current + " · 观测时间 " + (hasObserve(version(current)) ? "2026-11-18 09:00 +08:00" : "本次试算时间") + "</div></div>";
|
||||
}
|
||||
|
||||
function version(no) { return versions.filter(function (v) { return v.no === no; })[0]; }
|
||||
function identityText(v) {
|
||||
var names = v.columns.filter(function (c) { return c.identity; }).map(function (c) { return c.label; });
|
||||
return names.length ? names.join("、") : "未勾选";
|
||||
}
|
||||
function hasIdentity(v) { return v.columns.some(function (c) { return c.identity; }); }
|
||||
function hasObserve(v) { return v.columns.some(function (c) { return c.observe; }); }
|
||||
function cloneColumns(list) { return list.map(function (c) { return col(c.name, c.label, c.type, c); }); }
|
||||
function ruleText(v) { return v.rules.map(function (row) { return row.column + row.op + row.value; }).join(" 且 "); }
|
||||
function cloneRules(list) { return list.map(function (row) { return { column: row.column, op: row.op, value: row.value }; }); }
|
||||
function loadMap(no) {
|
||||
var source = version(no);
|
||||
draft = { base: no, columns: cloneColumns(source.columns), rules: cloneRules(source.rules) };
|
||||
state.view = "detail";
|
||||
closeModal();
|
||||
render();
|
||||
}
|
||||
function closeModal() { document.getElementById("mask").hidden = true; }
|
||||
function openSwitch() {
|
||||
var rows = versions.slice().reverse().map(function (v) {
|
||||
var active = current === v.no;
|
||||
return "<tr><td>v" + v.no + (active ? ' <span class="tag grey">当前</span>' : "") + "</td><td>" + esc(identityText(v) + " · " + ruleText(v)) + "</td><td class=\"ops\">" +
|
||||
(active ? "" : '<button class="btn link" data-act="activate" data-no="' + v.no + '">激活</button>') +
|
||||
'<button class="btn link" data-act="edit" data-no="' + v.no + '">以此编辑</button></td></tr>';
|
||||
}).join("");
|
||||
document.getElementById("modal").innerHTML = "<h3>切换版本</h3><p class=\"hint\">一个版本同时包含字段映射和判断规则。激活不产生新版本。以此编辑后另存,字段和条件一起成为新版本。</p>" +
|
||||
'<div class="table-wrap"><table><thead><tr><th>版本</th><th>内容</th><th class="ops">操作</th></tr></thead><tbody>' + rows + "</tbody></table></div>" +
|
||||
'<div class="actions"><button class="btn" id="close-modal">关闭</button></div>';
|
||||
document.getElementById("mask").hidden = false;
|
||||
document.getElementById("close-modal").onclick = closeModal;
|
||||
document.getElementById("modal").onclick = function (ev) {
|
||||
var t = ev.target;
|
||||
if (!t.dataset || !t.dataset.act) return;
|
||||
var no = +t.dataset.no;
|
||||
if (t.dataset.act === "activate") { current = no; state.flash = "已将 v" + no + " 设为当前版本。字段和判断规则一起切换,没有新增版本。"; closeModal(); render(); }
|
||||
if (t.dataset.act === "edit") loadMap(no);
|
||||
};
|
||||
}
|
||||
|
||||
function bind() {
|
||||
var go = function (id, fn) { var n = document.getElementById(id); if (n) n.onclick = fn; };
|
||||
go("go-detail", function () { state.flash = ""; loadMap(current); });
|
||||
go("go-new", function () { loadMap(current); });
|
||||
go("go-trial", function () { state.view = "trial"; render(); });
|
||||
go("back-list", function () { state.view = "list"; render(); });
|
||||
go("open-switch", function () { openSwitch(); });
|
||||
go("save-map", function () {
|
||||
readDraft();
|
||||
var no = versions[versions.length - 1].no + 1;
|
||||
var base = draft.base;
|
||||
versions.push({ no: no, columns: cloneColumns(draft.columns), rules: cloneRules(draft.rules) });
|
||||
current = no;
|
||||
state.view = "list";
|
||||
state.flash = "已按 v" + base + " 的字段和判断规则另存为 v" + no + ",并设为当前版本。v" + base + " 未改。";
|
||||
render();
|
||||
});
|
||||
go("do-filter", function () { state.flash = "已按名称筛选。输入时不会自动筛选。"; render(); });
|
||||
go("do-reset", function () { state.flash = ""; render(); });
|
||||
document.querySelectorAll("[data-id]").forEach(function (box) {
|
||||
box.onchange = function () { draft.columns[+box.dataset.id].identity = box.checked; };
|
||||
});
|
||||
document.querySelectorAll("[data-obs]").forEach(function (box) {
|
||||
box.onchange = function () {
|
||||
draft.columns.forEach(function (c, i) { c.observe = i === +box.dataset.obs && box.checked && c.type === "datetime"; });
|
||||
render();
|
||||
};
|
||||
});
|
||||
}
|
||||
function readDraft() {
|
||||
document.querySelectorAll("[data-mul]").forEach(function (input) { draft.columns[+input.dataset.mul].multiply = input.value; });
|
||||
document.querySelectorAll("[data-off]").forEach(function (input) { draft.columns[+input.dataset.off].offset = input.value; });
|
||||
document.querySelectorAll("[data-op]").forEach(function (input) { draft.rules[+input.dataset.op].op = input.value; });
|
||||
document.querySelectorAll("[data-val]").forEach(function (input) { draft.rules[+input.dataset.val].value = input.value; });
|
||||
}
|
||||
|
||||
document.querySelector(".proto").onclick = function (ev) {
|
||||
var t = ev.target;
|
||||
if (t.dataset.role) { state.role = t.dataset.role; state.view = "list"; render(); }
|
||||
if (t.dataset.out) { state.outcome = t.dataset.out; if (state.role === "admin") state.view = "trial"; render(); }
|
||||
};
|
||||
render();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,165 @@
|
||||
# M05 字段映射与规则判断 Requirement
|
||||
|
||||
## Goal
|
||||
|
||||
在已有查询定义上维护字段映射和结构化判断规则,并用样例行试算。每行给出正常、异常或未知。本模块不创建报警。
|
||||
|
||||
## Background
|
||||
|
||||
M04 已交付查询定义、不可变版本和只读预览。冻结稿 A-04、第 6 章和 A-021~A-026 把映射、输入身份和是否异常放在报警之前。D27 收口了本模块的字段和身份口径。O06 里“修订后报警怎么改”仍归 M06。
|
||||
|
||||
## In Scope
|
||||
|
||||
- 挂在查询定义上的映射:选用结果列、类型、可选身份列、可选数值换算。
|
||||
- 挂在映射上的规则:结构化条件,AND/OR,样例试算。
|
||||
- 正常/异常/未知,以及与之分开的字段状态、执行失败。
|
||||
- 输入身份和值修订的持久化。同一身份不因重读新开一条。
|
||||
- 管理界面。正式 Vue 之前先确认 HTML 原型。
|
||||
|
||||
## Out Of Scope
|
||||
|
||||
- 报警创建、合并、关闭后新周期(M06,O06 的报警半边)。
|
||||
- 场景草稿、发布、Cron(M08)。
|
||||
- 规则原因分析(M12)和数据质量规则转人工。
|
||||
- 任意脚本、正则、窗口、跨事件序列、NOT。
|
||||
- SQL Server 查询试跑。
|
||||
- 从行内单位文本自动猜换算。
|
||||
|
||||
## Current Behavior
|
||||
|
||||
查询可以定义、版本化和预览。没有映射、规则、输入身份或判定结果。
|
||||
|
||||
## Required Behavior
|
||||
|
||||
配置人员选择一条查询,勾选要使用的结果列。每列标明类型。数值列可以配置乘数和偏移。身份列由人勾选,可以不勾,也可以勾多列;日期列只有被勾成身份列时才参与区分。
|
||||
|
||||
规则引用这些列。每条条件选择一列、一个已允许的运算符和一个比较值。条件可以按 AND/OR 组合。
|
||||
|
||||
试算展示原始列、转换后的值、字段状态,以及正常/异常/未知。同时给出规则的文字说明、实际值、比较值、命中条件、规则版本、观测时间和输入依据。试算不写报警,不发通知。
|
||||
|
||||
零行是空结果,不是正常,不是未知,也不是执行失败。单行里的指标为空仍按缺失处理。
|
||||
|
||||
## User Flow
|
||||
|
||||
1. 从查询进入映射,勾选列、类型、身份列和换算,保存。
|
||||
2. 在该映射下编写规则,保存。
|
||||
3. 用贴入的样例,或对该查询当前版本做一次只读预览(仅 PostgreSQL/MySQL),查看映射和判定。
|
||||
4. 重开已保存的映射和规则,条件与保存时一致。
|
||||
|
||||
## Business Rules
|
||||
|
||||
业务结论只有三种,界面和接口都使用这些词:
|
||||
|
||||
| 结论 | 含义 |
|
||||
|---|---|
|
||||
| 正常 | 有效数据已经足以确定异常条件不成立 |
|
||||
| 异常 | 有效数据已经足以确定异常条件成立 |
|
||||
| 未知 | 必要数据不足,不能可靠确定 |
|
||||
|
||||
执行失败另记,不写成正常、异常或未知。
|
||||
|
||||
单条比较:两边都能按声明类型比较,条件成立为异常,不成立为正常。缺值或非法值为未知。
|
||||
|
||||
AND:已有一条正常,则整组正常;全部为异常,则整组异常;还没有正常且存在未知,则整组未知。
|
||||
|
||||
OR:已有一条异常,则整组异常;全部为正常,则整组正常;还没有异常且存在未知,则整组未知。
|
||||
|
||||
字段状态与结论分开:缺失、非法都导致未知,但预览里必须能看出是哪一种。缺失保持为空,不转成 0 或空字符串。
|
||||
|
||||
身份:
|
||||
|
||||
- 勾了身份列时,这些列的值合起来区分输入。值变化只追加修订,不新开身份。度量值、运行号和整行哈希都不进入身份。
|
||||
- 不勾身份列时,这条映射本身是唯一输入。结果有多行时采用本次返回顺序的第一行。
|
||||
- 身份列已勾选但该行身份值为空:该行不能形成身份,不写入输入。
|
||||
- 同一次结果里多行身份值相同:按返回顺序保留第一行,其余计入跳过的重复行,不在同一次里写多条修订。
|
||||
|
||||
未知不创建报警。本模块没有报警写入。空结果也不创建报警,不记成正常。
|
||||
|
||||
## Data Rules
|
||||
|
||||
- 一条查询可有多条映射。一条映射可有多条规则。
|
||||
- 映射和判断规则共用同一个不可变版本。切换当前版本时,字段和条件一起切换。可基于某一历史版本编辑字段和条件,保存时另存为一个新版本并设为当前,被打开的历史版本内容不变。判断规则没有单独的版本号。
|
||||
- 同一身份且度量值无变化:不追加修订。
|
||||
- 试算样例可以不落成正式输入。正式输入只在明确的保存试算中写入。默认的页面试算不写输入。见 Assumptions。
|
||||
- 列是否还存在,对照该查询的当前版本。当前版本去掉了已选列时,保存和试算都拒绝,并说明缺哪一列。
|
||||
- 新表带 `tenant_id`,并按现有业务表启用强制行级安全。映射版本内容在数据库层禁止更新和删除。
|
||||
- 日期时间列与日期时间比较值使用带时区的时间,比较前归一到 UTC。没有时区的值视为非法,不按机器本地时区猜。
|
||||
- 每条映射最多把一列标成观测时间。不标时,详情里的观测时间用本次试算时间。观测时间列不自动变成身份列。
|
||||
|
||||
## API Contract
|
||||
|
||||
对外操作:映射的维护与读取、规则的维护与读取、映射试算、规则试算。响应信封遵循 `standards://api/api-envelope?version=1.1.0`。路径在实现切片里按现有查询路由风格确定,不在本需求里另造一套信封。
|
||||
|
||||
试算响应能区分:一行结论、字段缺失、字段非法、无法形成身份、采用了第一行、同身份重复行被跳过、空结果、映射列在当前查询版本中已不存在、执行失败。
|
||||
|
||||
结论的存储和接口使用稳定英文码 `normal`、`abnormal`、`unknown`。界面文案固定为正常、异常、未知。不把这三个中文词写成数据库枚举。空结果和执行失败不使用这三个码。
|
||||
|
||||
## UI Requirements
|
||||
|
||||
- 列表遵循 D25。详情和表单的页面按钮遵循 D22。
|
||||
- 正式 Vue 前先给出 HTML 原型并经确认。
|
||||
- 映射页能勾选列、类型、身份列、最多一列观测时间、乘数和偏移。
|
||||
- 规则页用结构化条件,不用脚本框。
|
||||
- 预览高亮缺失和非法。采用第一行时写明跳过的行数。
|
||||
- 判定结果使用正常、异常、未知。
|
||||
|
||||
## Compatibility Requirements
|
||||
|
||||
- 不改查询版本不可变、只读预览和 SQL Server 不试跑的现有行为。
|
||||
- 不改已有权限角色名。`watchman-admin` 继续是配置人员角色。
|
||||
|
||||
## Error Handling
|
||||
|
||||
- 查询预览失败:执行失败,不产生正常或未知。
|
||||
- 类型对不上、未配置的单位差、无法解析:字段非法,结论未知。
|
||||
- 系统异常:执行失败。
|
||||
- 空条件、超过嵌套深度、未知运算符、对文本或布尔使用大小比较:保存时拒绝。
|
||||
|
||||
## Permissions And Security
|
||||
|
||||
仅 `watchman-admin` 可读取、保存和试算。操作者与查看者不能写,也不能靠隐藏按钮绕过。
|
||||
|
||||
权限点编码在实现时按 `standards://api/permission-nodes?version=1.0.0` 声明,并沿用现有 `perm:data:emp:watchman.query.*` 的项目写法。需求不把尚未注册的编码写成已存在事实。
|
||||
|
||||
## Assumptions
|
||||
|
||||
- 映射和规则的版本方式与 D26 相同。
|
||||
- 比较类型为数值、文本、布尔、日期时间。数值和日期时间可用等于、不等于、大于、大于等于、小于、小于等于。文本和布尔只有等于、不等于。
|
||||
- 条件嵌套深度上限为 4。根组算第 1 层,叶子也算一层。空组拒绝。
|
||||
- 第一行指本次结果集的返回顺序。顺序要稳定,由查询自己写 ORDER BY。
|
||||
- 换算写在映射上,不读取行里的单位文字。
|
||||
- 页面上的普通试算不写正式输入;持久修订由单独的保存动作写入。
|
||||
- 没有标成观测时间的列时,试算说明里的时间用本次试算时间。这条现在写进 Data Rules,因为冻结稿要求详情展示观测时间,而用户已确认日期不是必填。
|
||||
- 同一次结果中的重复身份保留第一行。这是为了和「第一行」口径一致,S2 之前若要改,先改需求再写代码。
|
||||
|
||||
## Risks
|
||||
|
||||
- 不勾身份列时,多行只留第一行。查询若没有 ORDER BY,下一次第一行可能变了,修订会记在同一条输入上。
|
||||
- 身份持久化会被 M06 拿去合并报警。本模块的修订不能被实现成新的业务事件。
|
||||
- 新权限点若与公司注册表不一致,实现时要停下来核对,不能临时改成只靠前端隐藏。
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
1. 一行中的多列指标可以同时被映射,规则的每条条件能选择其中一列。
|
||||
2. 不勾身份列时,多行样例只用第一行,并显示跳过行数;勾选身份列后,不同身份值分成不同输入。
|
||||
3. 同一身份的新度量值追加修订;相同值的重读不新开输入,也不把运行号算进身份。
|
||||
4. 缺失保持缺失,非法值不变成 0 或空字符串;两者结论都是未知,预览能区分。
|
||||
5. 未配置换算的单位差为非法。已配置的乘数和偏移按配置生效。
|
||||
6. AND/OR 符合 Business Rules 中的三值表。执行失败不显示为正常或未知。
|
||||
7. 保存后再打开,条件一致。试算不产生报警。
|
||||
8. 非管理员调用写和试算被拒绝。
|
||||
9. 查询返回零行时结果为空结果,不出现正常、未知或执行失败。
|
||||
10. 当前查询版本去掉已选列时,试算被拒绝并指出缺失列。
|
||||
11. 带时区的日期时间按 UTC 比较;没有时区的值记为非法。
|
||||
|
||||
## Deferred Questions
|
||||
|
||||
- O06:同一身份修订之后,原报警是否更新。M06 再定。
|
||||
- 普通试算与“保存为正式输入”是否分成两个按钮,若实现时界面放不下,再问一次,不自行改成每次试算都落库。
|
||||
|
||||
## Source Notes
|
||||
|
||||
- D05、D22、D24、D25、D26、D27。
|
||||
- `需求冻结文档_V1.1_交接稿.md` A-04、第 6 章。
|
||||
- `docs/tasks/INDEX.md` M05;`docs/tasks/CHECKLIST-v1.md` A-021~A-026。
|
||||
- `docs/development-plan.md` 4.2:身份不同于运行号,整行哈希不能用来丢掉跨周期事件。本模块用可配置身份列实现这一点。
|
||||
@@ -0,0 +1,166 @@
|
||||
# M05 计划 Critic 审查
|
||||
|
||||
- 模式:plan-review(S1 之前的 critic-required 停点)
|
||||
- 任务:`.task/2026-11-18/m05-mapping-rules`
|
||||
- 日期:2026-11-18
|
||||
- 审查范围:requirement.md、implementation-plan.md、context-pack.md、boundary.md、D05/D22/D24/D25/D26/D27、`docs/tasks/INDEX.md` M05、冻结稿 A-04 与第 6 章、`AGENTS.md` 项目本地段;并抽查 `models/query.py`、`auth/access.py`、`migrations/versions/`。
|
||||
- 本次审查不改任何产品代码、迁移或前端。
|
||||
|
||||
## 当前结论(第二轮复审,2026-11-18 晚)
|
||||
|
||||
**PASS_WITH_WARNINGS**
|
||||
|
||||
**S1 可以开始:是。** 没有剩余阻断项。详见文末「复审(第二轮)」。下面第一轮的 FAIL 结论已被取代,保留作为修订依据。
|
||||
|
||||
## 第一轮结论(已取代)
|
||||
|
||||
**FAIL**
|
||||
|
||||
**S1 可以开始:否。** 需要先按下面「阻断项」修订实现计划(只改 S1 的 Steps/Validation/Rollback 三段即可,不必重做整份计划),修订后再放行 S1。
|
||||
|
||||
说明:FAIL 的原因不是需求口径错了。需求与 D27、冻结稿第 6 章在语义上一致;问题集中在 S1 这一片的 schema 契约与验证证据,按现在的写法实现出来的表会违反仓库既有的租户隔离与不可变强制约定,且 S1 的 Done Criteria 没有对应测试。
|
||||
|
||||
## 先确认没有问题的部分
|
||||
|
||||
- 需求与 D27 一致:映射挂查询、一行多列、身份列可配置可为空、日期列只是可选身份列、不勾身份列时整条映射一条输入并取第一行、同一身份只追加修订、缺失与非法分开但都为未知、系统异常另记、单位只做已配置乘数与偏移、结论用正常/异常/未知。
|
||||
- 三值真值表与冻结稿 6.1 一致(异常=命中,正常=未命中,未知=信息不足;AND 已有正常即正常,OR 已有异常即异常)。
|
||||
- 安全底线未被突破:未知不创建报警、技术失败不写成正常或未知、本模块不写报警状态,这三条在需求、boundary.md 与计划的 Global Forbidden Scope 中都有明确表述。S4 的 Done Criteria「没有一条测试把执行异常断言成未知」是有效约束。
|
||||
- 身份口径完整:运行号与整行哈希都被排除在身份之外,身份列为空的行不写入输入,值变化只追加修订,相同值不追加(S2 Steps 1~4)。
|
||||
- 权限点没有被编造。需求与计划都只引用既有 `perm:data:emp:watchman.query.*` 写法,把新编码推迟到 S5 并要求先核对规范,与 `auth/access.py` 现状(admin-only 的 datasource/query 节点)一致。已通过 sy-standards 核对版本:`standards://api/permission-nodes` 最新为 1.0.0、`standards://api/api-envelope` 最新为 1.1.0,计划引用的版本号正确。
|
||||
- 门禁设置正确:S1 为 `gateClass: high-risk` + `risk_score: 4`,计划把「计划 critic 通过」写成 S1 的前置依赖,context-pack 的 Stop Conditions 明确 autonomous 不取消 critic、不取消 `risk_score >= 4` 停顿、不取消原型确认与最终验收。`marionettist.config.yaml` 的 `allowTaskOverride: true`,`.task/active.json` 为 `phase: analysis`、`allowedToCode: false`、`lastGate: plan-confirmed-awaiting-critic`,状态自洽。
|
||||
- 切片没有混入报警、场景、Cron、企微、原因分析或任意脚本;S6 原型先于 S7 的顺序和停点成立。
|
||||
- S1 的文件范围是真的:`models/query.py`、`auth/access.py`、`migrations/versions/`(head 为 `20261118_0009`)均存在,S1 Step 4 要对照的「查询当前版本输出列」在 `query_definitions.current_version_no` 与 `query_versions.output_schema` 上确实可取。
|
||||
|
||||
## 阻断项(修订后 S1 才能开始)
|
||||
|
||||
### B1. S1 的建表步骤漏了 tenant_id 与强制 RLS,会破坏既有租户隔离
|
||||
|
||||
证据:`20261117_0004_data_sources.py`、`20261118_0006_query_definitions.py` 对每张业务表都执行 `ENABLE / FORCE ROW LEVEL SECURITY`、建 `tenant_isolation` 策略(`tenant_id = current_setting('app.tenant_id', true)`)并显式 `GRANT` 给 `watchman_app`;`models/query.py` 的两张表都带 `tenant_id`;仓库已有 `tests/test_rls.py`、`tests/test_datasource_rls.py` 守这条线。
|
||||
|
||||
问题:S1 的 Steps 只写了「映射定义、列配置、不可变版本和当前版本指针」,完全没有 `tenant_id`、RLS 策略和授权。按计划字面实现出来的映射表将没有任何租户隔离,任何租户只要拿到 id 就能读写别的租户的映射,而且与 ORM 会话设置 `app.tenant_id` 的现有机制不一致。这是安全边界问题,不是风格问题。
|
||||
|
||||
要求的最小修订:S1 Steps 增加一条「新表均带 `tenant_id`,按 0006 的 `_enable_rls` 同形式启用 FORCE RLS、建 `tenant_isolation` 策略并授权 `watchman_app`」;Validation 增加一条跨租户读写被拒的测试(可仿 `test_datasource_rls.py`);Rollback Notes 补上「向下迁移同时 DROP POLICY」。
|
||||
|
||||
### B2. 「历史版本不可更新、不可删除」没有强制层,也没有对应测试
|
||||
|
||||
证据:`20261118_0007_query_versions_immutable.py` 的文件说明已经写明,0006 当时只靠「服务层拒绝」是不够的(那个 Python helper 在写路径上根本没人调用),所以改成 `REVOKE UPDATE, DELETE` + 语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器两层强制。
|
||||
|
||||
问题:S1 的 Step 2 写「保存即新版本。历史版本不可更新、不可删除」,Done Criteria 写「版本内容不可改」,但 Steps 没说在哪一层强制,Validation 只有「`uv run pytest` 覆盖本切片」和「`alembic upgrade head` 对空库可升级」。这正是审查项 7 指出的情况:S1 可以在没有任何一条测试证明不可变的情况下被宣布完成,而且很可能重犯 0007 修掉的那个缺陷。
|
||||
|
||||
要求的最小修订:S1 Steps 明确不可变由数据库层强制(沿用 0007 的 REVOKE + 语句级触发器形式);Validation 增加两条具体断言——对历史映射版本执行 UPDATE 被拒、执行 DELETE 被拒;Done Criteria 绑定这两条测试,而不是绑定一句描述。
|
||||
|
||||
### B3. 观测时间与时区在 S1 的列配置 schema 里没有位置,决定晚了就要再改一次高风险迁移
|
||||
|
||||
证据:冻结稿 4.3 要求输入契约能表达「观测时间/统计周期」,并明确「时区不可依赖执行机器隐式默认值」;6.2 要求判定详情展示「自然语言规则、实际值、比较值、命中条件、版本、观测时间和输入依据」。
|
||||
|
||||
问题:S1 的列配置只有「类型、身份布尔标记、乘数与偏移」,没有任何「哪一列是观测时间」的声明位;需求的 Required Behavior 列举试算要展示的内容时也漏了观测时间和输入依据。需求 Assumptions 里有一条「没有观测时间列时用本次试算时间」,但这条不在用户本次确认的五条假设之内,等于是未确认口径。同时,日期时间列与日期时间比较值的时区约定(存 tz-aware 还是裸值、比较时按哪个时区)在需求、S1、S3、S4 里都没有写,冻结稿恰好禁止依赖机器隐式默认。
|
||||
|
||||
为什么必须在 S1 之前定:列配置 schema 和日期时间列的存储形态都是 S1 的表结构。这两件事留到 S4/S5 再决定,就要对一张 `risk_score: 4` 的表再加一次迁移。
|
||||
|
||||
要求的最小修订(二选一,并把选择写进 requirement 的 Assumptions 与 S1 Steps):
|
||||
- 在列配置中增加一个可选的「观测时间列」声明,与身份标记并列;或
|
||||
- 明确记录「本模块不声明观测时间列,判定详情一律使用试算时间」,并作为需要用户点头的口径列出。
|
||||
|
||||
无论选哪一种,都要在 S1 Steps 写死日期时间列与日期时间比较值的时区约定(建议统一 tz-aware 存储、比较前归一),并在 S4 的真值表测试里固定一条跨时区用例。
|
||||
|
||||
## 非阻断警告(S1 可以带着走,但要在指定切片前落实)
|
||||
|
||||
### W1. 空结果(零行)语义缺失 —— S4/S5 之前必须补
|
||||
|
||||
冻结稿 4.3 明确「空结果、单行指标为空、源连接失败是不同情况」,且空结果「不自动代表指标为零、业务正常或报警恢复」。requirement 的 Business Rules、Error Handling、Acceptance Criteria,以及 S4 Steps、S5 Step 3 的响应状态列表,都没有「查询返回零行」这一种。不勾身份列时更直接:没有第一行可取。按现状实现,S4 很可能把零行落成「正常」或笼统的「未知」,两种都踩到冻结稿红线。补法:在 requirement 增加一条明确结论与一条验收标准,并把「空结果」加进 S5 的响应状态枚举。
|
||||
|
||||
### W2. 「当前版本删掉了已选列」在试算侧没有落片 —— S4/S5 之前补
|
||||
|
||||
requirement 的 Data Rules 要求「当前版本去掉了已选列时,映射不能静默继续试算」。S1 Step 4 只覆盖了保存时拒绝,试算时的这条路径没有任何切片负责,S5 Step 3 的响应状态里也没有这一种。请在 S5 的响应状态中增加「映射列在当前查询版本中已不存在」,并在 S4 或 S5 的 Validation 里加一条用例。
|
||||
|
||||
### W3. 同一次结果中多行命中同一身份值,行为未定义 —— S2 之前定
|
||||
|
||||
S2 Step 1 把唯一约束落在「映射 + 身份值」上,但没说同一次试算里两行身份值相同时怎么办(取第一行?按顺序各写一条修订?拒绝?)。这会直接决定唯一约束冲突时的处理,也会影响 M06 的合并口径。请在 S2 开工前写死,并配一条测试。
|
||||
|
||||
### W4. `docs/tasks/INDEX.md` 仍写 PASS/FAIL/UNKNOWN,与 D27 的正常/异常/未知冲突
|
||||
|
||||
INDEX(2026-11-17)M05 验收段写的是「PASS/FAIL/UNKNOWN」,M06 还写「不改原始 FAIL」。按冲突顺序,D27(2026-11-18,用户逐项确认)优先,需求用中文三词是对的。但计划的 Documentation Update Requirement 只列了 `docs/tasks/M05.md` 和 `docs/progress.md`,没有列 INDEX。这会让后续审查者拿 INDEX 当权威。请在 S8 的文档同步里加上修订 INDEX 的 M05/M06 措辞。
|
||||
|
||||
### W5. 「接口也用正常/异常/未知」要区分枚举码与展示文案 —— S5 决定
|
||||
|
||||
D27 的原意是术语统一,不等于要把中文字面量作为线上枚举值或数据库枚举。S5 请对照 `standards://api/api-envelope?version=1.1.0`(最新版,已核)决定是「稳定英文码 + 中文展示文案」还是中文值,并写进 S5 Steps。界面文案保持正常/异常/未知不变。无论选哪种,都不要把三词写死进数据库枚举类型。
|
||||
|
||||
### W6. S5 调用查询预览的路径没有写成步骤
|
||||
|
||||
requirement 允许试算对当前版本做一次只读预览(仅 PostgreSQL/MySQL),但没有任何切片的 Steps 写「复用既有查询预览执行器」。boundary.md 写了「查询执行器只可调用」,建议把这句落到 S5 Steps 里,并顺带明确预览权限点是沿用 `perm:data:emp:watchman.query.preview` 还是另立——仍然按 B 项原则:核对规范,对不上就停,不编码。
|
||||
|
||||
### W7. S1 的 Rollback Notes 不完整,且没有 downgrade 验证
|
||||
|
||||
「向下迁移只删除本切片新增表」漏了策略与触发器(0006 的 downgrade 是先 DROP POLICY 再 drop_table)。另外 Validation 只验 `upgrade head`,没有验 downgrade,而 Rollback Notes 却承诺可回滚。建议要么补一条 downgrade 验证,要么如实写明该命令未运行。
|
||||
|
||||
### W8. RLS 相关测试需要真实 Postgres,环境不具备时必须记 NOT_RUN
|
||||
|
||||
`alembic upgrade head` 与 RLS 用例依赖真实 Postgres(FORCE RLS 在 SQLite 上无意义)。请在 S1 的 Validation 里写明运行环境,命令没真正跑就按 `AGENTS.md` 第 7 条如实记为未运行,不要写成 PASS。
|
||||
|
||||
### W9. autonomous 下 S3 → S4 会自动连推,建议对 S4 另设停点(建议性)
|
||||
|
||||
S4 是 `standard` + `risk_score: 3`,按 autonomous 规则可以在 S3(risk 4)完成后不经确认直接进入。S4 固化的是本模块的核心语义(三值真值表、缺失与非法的区分、第一行与跳过行数)。考虑到 W1、W2、B3 的时区用例都要在 S4 落地,建议在计划里把 S4 之前也写成显式停点,或要求 S4 先把真值表测试提交给审查。这是建议,不是阻断。
|
||||
|
||||
## 放行条件
|
||||
|
||||
按 B1、B2、B3 修订 `implementation-plan.md` 的 S1 Steps/Validation/Rollback Notes,并把 B3 选定的观测时间口径与时区约定回写到 `requirement.md` 的 Assumptions(若选「不声明观测时间列」,该条需用户确认)。这些改完之后 S1 即可开始,W1~W9 按各自标注的切片时点处理。
|
||||
|
||||
---
|
||||
|
||||
# 复审(第二轮)
|
||||
|
||||
- 模式:plan-review 复审
|
||||
- 时间:2026-11-18 晚
|
||||
- 依据:重新完整读取 `requirement.md`、`implementation-plan.md`、`context-pack.md` 当前内容,未沿用上一轮记忆。
|
||||
- 结论:**PASS_WITH_WARNINGS**,**S1 可以开始:是**,无剩余阻断项。
|
||||
|
||||
## 阻断项核验
|
||||
|
||||
**B1(tenant_id 与强制 RLS)已修复。** S1 Step 1 明确「新表都带 `tenant_id`,按 `20261118_0006` 的形式 `ENABLE`/`FORCE ROW LEVEL SECURITY`、建立 `tenant_isolation` 策略,并 `GRANT` 给 `watchman_app`」;Validation 要求跨租户读写被拒的测试;Rollback Notes 要求先 `DROP POLICY`。与 0006 的既有形式一致。
|
||||
|
||||
**B2(不可变版本的强制层与证据)已修复。** S1 Step 2 指明沿用 `20261118_0007`:版本表 `REVOKE UPDATE, DELETE` 加语句级 BEFORE UPDATE/DELETE/TRUNCATE 触发器;Validation 列出 `UPDATE` 被拒、`DELETE` 被拒两条测试;Done Criteria 写成「由数据库拒绝证明,不单靠服务层」。这条堵住了上一轮「S1 可以在零证据下宣布完成」的口子。
|
||||
|
||||
**B3(观测时间与时区)已修复,且位置正确。** 口径写进了 `requirement.md` 的 Data Rules(每条映射最多一列观测时间、不标时用试算时间、观测时间列不自动变身份列;日期时间用带时区值、比较前归一 UTC、无时区视为非法),不再是未确认假设;Required Behavior 补上了「观测时间和输入依据」,与冻结稿 6.2 的判定详情要求对齐;S1 Step 3 与 Done Criteria 承接了 schema 侧,S4 Step 6 有跨时区与无时区用例,AC11 可验收。
|
||||
|
||||
## 非阻断警告核验
|
||||
|
||||
W1 空结果(需求 Required Behavior/Business Rules/API Contract/AC9、S4 Step 5、S5 Step 5)、W2 缺列保存与试算双侧拒绝(Data Rules/AC10、S1 Step 4、S4 Step 7、S5 Step 4)、W3 同次重复身份保留第一行(Business Rules、S2 Step 5)、W4 INDEX 措辞归入 S8(Documentation Update Requirement,含 M06「不改原始异常判定」且声明不改 M06 范围)、W5 英文码加中文文案且不建中文数据库枚举(API Contract、S4 Step 1、S5 Step 3)、W6 复用既有查询预览执行器并先核对预览权限点(S5 Step 1)、W7/W8 downgrade 与真实 PostgreSQL 写进 S1 Validation 且未跑记未运行、W9 S4 显式停点(S4 Execution 段与 context-pack Stop Conditions),均已落实。
|
||||
|
||||
## 本轮新增的非阻断警告
|
||||
|
||||
### R1. S2 新建输入/修订表时没有重复 B1 的 RLS 模式 —— S2 开工前补
|
||||
|
||||
S2 的 Allowed Modification Scope 含「新的输入/修订模型与迁移」,Step 1 的唯一约束已包含租户,说明表上会有 `tenant_id`。但 S2 的 Steps 没有写 `ENABLE`/`FORCE ROW LEVEL SECURITY`、`tenant_isolation` 策略与 `GRANT`,Validation 也没有跨租户被拒用例和真实 PostgreSQL 的 upgrade/downgrade 要求。这是与 B1 同一类的问题,只是落在另一片。S2 是独立的 `risk_score: 4` 停点,不影响 S1 开工,但在 S2 批准前必须按 S1 的写法补齐。
|
||||
|
||||
### R2. S3 规则版本既没有 RLS 模式,也没有 B2 的不可变强制 —— S3 开工前补
|
||||
|
||||
`requirement.md` Data Rules 写「映射和规则各自保存即产生不可变版本」,但数据库层那条只写了「映射版本内容在数据库层禁止更新和删除」,没有覆盖规则版本。对应地,S3 Step 1 只说「保存即不可变版本」,没有 `REVOKE UPDATE, DELETE` 与触发器,也没有 RLS 与 `tenant_id`;S3 Validation 只有四条拒绝非法规则的用例,没有跨租户、`UPDATE` 被拒、`DELETE` 被拒。建议把需求那句改成覆盖映射版本与规则版本,并把 S3 的 Steps/Validation 对齐 S1。
|
||||
|
||||
### R3. 规则里配置的无时区日期时间比较值,是保存时拒绝还是运行时非法,没有写死 —— S3 开工前定
|
||||
|
||||
S1 Step 3 把「无时区值为非法」同时写给了列和比较值,但比较值由 S3 的规则表存储,S3 Step 3 只要求「比较值类型须与列类型相容」。需求 Error Handling 的保存时拒绝清单里也没有这一项,而 AC11 的措辞偏向运行时字段非法。建议明确:人工配置的比较值在保存时拒绝(配置错误应当早失败),行数据里的无时区值在运行时记为非法、结论未知。两者分开写,避免 S3 与 S4 各写一半。
|
||||
|
||||
### R4. S4、S5 的 Validation 行没有跟上新增的步骤和验收标准
|
||||
|
||||
S4 Steps 已覆盖空结果、跨时区、缺列三件事,但 Validation 仍写「覆盖验收标准 4、5、6 的计算部分」,没有点名 AC9、AC10、AC11;S5 Steps 4、5 已列出空结果、重复身份跳过、缺列三种响应状态,但 Validation 仍只有「管理员成功,操作者与查看者拒绝,试算无报警行」。按现状,这些新口径有实现而无门禁。建议把 AC9~AC11 和三种新响应状态分别写进 S4、S5 的 Validation。
|
||||
|
||||
### R5. 零行时是否写入正式输入,没有写明
|
||||
|
||||
「保存试算」会写正式输入,但空结果既不是三种结论也没有行可用。S2 与 S5 都没说零行时不写输入与修订。建议在 S2 加一句「空结果不写输入、不写修订」,避免实现时顺手写一条空身份。
|
||||
|
||||
### R6. `context-pack.md` 有三处与修订后的计划/需求不同步 —— S1 开工前刷新
|
||||
|
||||
这份文件是实现者直接读的,当前落后于另外两份:
|
||||
1. Validation Commands 仍写「迁移:`alembic upgrade head`」,没有 S1 已要求的真实 PostgreSQL 与 downgrade。
|
||||
2. Assumptions 仍写「版本方式、嵌套深度 4、普通试算不落库,用户还没单独点名」,但用户已在 2026-11-18 确认了这几条(含第一行口径与身份值为空的行不形成输入)。保留旧措辞会让后续 Agent 把已确认口径当成待确认。
|
||||
3. Required Behavior 只提中文三词,没有提 `normal`/`abnormal`/`unknown` 接口码、空结果和观测时间。
|
||||
|
||||
这三处都是文档同步,不改变实现方向,但建议在 S1 动工前顺手改掉。
|
||||
|
||||
### R7. 两处措辞小问题(可选)
|
||||
|
||||
S1 的 Goal 一句仍只列「所属查询、选用列、类型、身份勾选、乘数和偏移」,没带观测时间标记,而 Step 3 与 Done Criteria 都有;另外需求说「结论的存储和接口使用稳定英文码」,但没有任何切片说明结论会被落到哪张表(试算是瞬态,修订存的是度量值)。若本模块实际不持久化结论,建议把「存储」二字改成只约束接口,免得 S2 多建一列。
|
||||
|
||||
## 放行结论
|
||||
|
||||
S1 可以按现在的 `implementation-plan.md` 开始。R1、R2、R3、R5 必须在对应切片(S2、S3)批准前落实,R4、R6 建议在 S1 动工前后顺手处理,R7 为可选。S2、S3、S5 仍是 `risk_score: 4` 的独立停点,S4 前有显式停点,这些都不因本次 PASS_WITH_WARNINGS 而放宽。
|
||||
@@ -0,0 +1,24 @@
|
||||
# S1 Review
|
||||
|
||||
- 切片:S1 映射模型与不可变版本
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS
|
||||
- 阻断项:无
|
||||
|
||||
## 已核对
|
||||
|
||||
- 三张新表有 `tenant_id`,并启用强制行级安全。
|
||||
- 版本表和列配置表由数据库拒绝 UPDATE/DELETE/TRUNCATE。
|
||||
- 观测时间列最多一列。身份标记和乘数、偏移已保存。
|
||||
- 保存时会拒绝当前查询版本里不存在的列。
|
||||
- 没有接口、权限点、报警表或输入修订表。
|
||||
|
||||
## 警告
|
||||
|
||||
1. 测试只拒绝了版本表的 UPDATE/DELETE,没有对列配置表做同样的拒绝测试。迁移里已经保护了列配置表。
|
||||
2. 外键只核对 id,不核对租户。与查询模块现有写法相同。服务层按当前租户查找父行。
|
||||
3. 观测时间列没有限制必须是日期时间类型。需求只写了最多一列。S4 把该列当时间用之前要补上类型限制。
|
||||
4. 版本指针没有外键,与查询定义的指针方式相同。
|
||||
5. 声明类型和查询输出类型的比较留到试算,不在 S1。
|
||||
|
||||
实现方报告:真实 PostgreSQL 上 `alembic upgrade head`、`downgrade -1` 再升级通过。主 Agent 重跑 `uv run pytest tests/test_mapping_versions.py`:6 passed。审查未重跑测试。
|
||||
@@ -0,0 +1,26 @@
|
||||
# S2 Review
|
||||
|
||||
- 切片:S2 输入身份与修订
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS
|
||||
- 阻断项:无
|
||||
|
||||
## 已核对
|
||||
|
||||
- 唯一约束是租户、映射、身份键。度量值和运行号不在键里。
|
||||
- 不勾身份列时使用固定的映射级身份,一批只取第一行。
|
||||
- 勾了身份列时,同一批里同一身份只保留第一行。
|
||||
- 值变化追加修订,相同值不追加。
|
||||
- 两张新表有 `tenant_id` 和强制行级安全。修订行在数据库层拒绝 UPDATE、DELETE、TRUNCATE。
|
||||
- 没有接口、权限点、报警或规则判定。
|
||||
|
||||
## 警告
|
||||
|
||||
1. 身份列只有 `None` 或缺失会跳过。空字符串和纯空格仍会建成输入。需求写的是“身份值为空”,空字符串算不算空,留到下次改这段持久化之前确认。
|
||||
2. 修订表自己的跨租户读写、不勾身份列时的重读、身份值为 `None`,测试里还没有。
|
||||
3. 个别测试按全表取修订行,库里有别的数据时可能拿错行。
|
||||
4. 身份键对类型敏感:数值 `1`、字符串 `"1"` 会变成两个身份。
|
||||
5. 一批里出现不带时区的日期时间时,整批失败。判定阶段才把这种值记为非法。
|
||||
6. `mappings.py` 模块注释仍写着不做输入持久化,和现在的代码不符。
|
||||
|
||||
实现方报告:真实 PostgreSQL 上升级、降一级再升级通过。主 Agent 重跑 `uv run pytest tests/test_mapped_input_revisions.py tests/test_mapping_versions.py`:14 passed。审查未重跑。
|
||||
@@ -0,0 +1,25 @@
|
||||
# S3 Review
|
||||
|
||||
- 切片:S3 规则结构校验
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS
|
||||
- 阻断项:无
|
||||
|
||||
## 已核对
|
||||
|
||||
- 规则定义和规则版本带 `tenant_id`,并启用强制行级安全。
|
||||
- 历史规则版本在数据库层拒绝 UPDATE、DELETE、TRUNCATE。
|
||||
- 条件只接受 AND/OR 组和叶子。叶子只有列、运算符、比较值。
|
||||
- 文本和布尔拒绝大小比较。日期时间比较值没有时区时,保存即拒绝。
|
||||
- 深度按根组第 1 层、叶子也算一层,上限 4。空组拒绝。
|
||||
- 保存时不执行用户代码,也没有正常/异常/未知的计算。
|
||||
- 没有接口和权限点。
|
||||
|
||||
## 警告
|
||||
|
||||
1. 运算符如果不是字符串,而是列表或对象,会抛出未处理的类型错误。规则不会保存,但调用方看到的不是校验失败。S5 之前改成先判断类型。
|
||||
2. 深度计数已按上面的口径写进需求。还缺一条“刚好 4 层可以保存”的测试。
|
||||
3. 拒绝测试大多只断言抛了校验错误,没有断言原因。布尔列的大小比较、列不在当前映射版本里、组运算符非法,都还没有对应用例。
|
||||
4. 规则版本没有记下校验时所对照的映射版本。试算前仍要再核对列是否还在。
|
||||
|
||||
审查重跑 `uv run pytest tests/test_rule_versions.py`:8 passed。主 Agent 重跑 S1 至 S3 共 22 passed。迁移升级和降级由实现方在真实 PostgreSQL 报告通过,审查未重跑。
|
||||
@@ -0,0 +1,26 @@
|
||||
# S4 Review
|
||||
|
||||
- 切片:S4 正常/异常/未知计算
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS(第三次复审)
|
||||
- 阻断项:无
|
||||
|
||||
## 过程
|
||||
|
||||
第一次审查为 BLOCKED:真值表覆盖不足,缺列检查只看规则列,比较中的意外错误被写成未知。修复后第二次仍为 BLOCKED:浮点行值乘以 Decimal 乘数会抛错。第三次复审关闭了这个问题。
|
||||
|
||||
## 已核对
|
||||
|
||||
- 结论码是 `normal`、`abnormal`、`unknown`。零行是 `empty`。缺映射列是 `error`,并给出列名。
|
||||
- AND/OR 的未知组合、等值边界、缺失和非法的字段状态都有测试。
|
||||
- 配置了乘数或偏移时,整数和浮点先转成 Decimal 再运算。非有限数值是非法,结论为未知。
|
||||
- 没有写报警,没有迁移。
|
||||
|
||||
## 警告
|
||||
|
||||
- 还没有用例证明“配置的比较值非法时会抛出,而不是返回未知”。
|
||||
- 多行且有身份列时,顶层结论只代表第一行。
|
||||
- 条件树的运算符若不是 `and`,计算函数会按 OR 处理。保存规则时已经拒绝这种树。
|
||||
- 函数说明仍写着只检查规则列,代码已经检查全部映射列。
|
||||
|
||||
主 Agent 重跑 `uv run pytest tests/test_judgment.py`:12 passed。审查同样重跑 12 passed。
|
||||
@@ -0,0 +1,26 @@
|
||||
# S5 Review
|
||||
|
||||
- 切片:S5 接口与权限
|
||||
- 审查:独立审查,与实现不是同一模型系列
|
||||
- 推荐:PASS_WITH_WARNINGS(复审)
|
||||
- 阻断项:无
|
||||
|
||||
## 过程
|
||||
|
||||
第一次审查为 BLOCKED:查询试算没有提交,预览审计会丢;规则版本保存不核对规则是否属于地址里的映射。两处已改,复审通过。
|
||||
|
||||
## 已核对
|
||||
|
||||
- 权限点是 `perm:data:emp:watchman.mapping.read`、`write`、`trial`,只放行 `watchman-admin`。
|
||||
- 贴入样例的试算不写正式输入,也不要求查询预览权限。
|
||||
- 重跑当前查询的试算同时要求映射试算和既有查询预览权限,并调用既有预览。失败时结果是错误,不是正常或未知。预览之后会提交,审计记录保留。
|
||||
- 规则不属于该映射时,保存版本返回 404。
|
||||
- 没有新角色,没有报警写入,没有新的 SQL 执行器。
|
||||
|
||||
## 警告
|
||||
|
||||
- 保存规则版本时先按未加锁的读取核对归属,并发保存同一条规则可能得到 500,唯一约束仍会挡住重复行。
|
||||
- 规则 id 不是合法 UUID 时,可能是 500 而不是 404。
|
||||
- 接口测试只有 2 个用例,没有覆盖 SQL Server 拒绝和只读路由的 403。
|
||||
|
||||
主 Agent 与审查都重跑了 `uv run pytest tests/test_mapping_api.py`:2 passed。
|
||||
@@ -0,0 +1,23 @@
|
||||
# S7 Review
|
||||
|
||||
- 切片:S7 正式页面,以及判断规则并入映射版本
|
||||
- 审查:独立审查
|
||||
- 推荐:BLOCKED(第三次)
|
||||
- 已用复查次数:3
|
||||
|
||||
## 已成立
|
||||
|
||||
- 映射版本上有 `condition_tree`,保存时字段和条件在同一个新版本里。
|
||||
- 激活只改当前版本号,不新增版本。
|
||||
- 列表没有「判断规则」按钮。
|
||||
- 打开已有版本时会读服务端的当前版本,试算提交的是页面上的 JSON 行。
|
||||
|
||||
## 仍阻断
|
||||
|
||||
新建映射还没有版本。详情页把空的当前版本当成 0 去读取,请求失败后,页面上仍留着写死的列 `n` 和条件 `n eq 1`。这时点「另存为新版本」会把这份占位内容存成 v1。
|
||||
|
||||
## 修复后复审
|
||||
|
||||
推荐:PASS_WITH_WARNINGS。
|
||||
|
||||
新建映射没有版本时,不再请求版本 0。初始字段来自该查询的输出列,页面里不再有占位列 `n`。`seed.spec.ts` 通过。编辑页是否跳过版本加载,还没有组件测试。
|
||||
@@ -0,0 +1,30 @@
|
||||
# S8 模块审查
|
||||
|
||||
- 推荐:PASS_WITH_WARNINGS(修复后复审)
|
||||
- 第一次为 BLOCKED:数值字符串比较、粘贴试算不核对查询列、ISO 时间被判非法、条件组重开被清空。
|
||||
- 修复后复审通过。
|
||||
|
||||
## 已核对
|
||||
|
||||
- 正常、异常、未知、空结果、执行失败分开。
|
||||
- 字段和判断条件存在同一个映射版本。激活不新增版本。
|
||||
- 列表没有「判断规则」按钮。
|
||||
- 新建映射不请求版本 0,不用占位列 `n`。
|
||||
- 管理员权限、行级安全和版本不可改仍在。
|
||||
|
||||
## 警告
|
||||
|
||||
- 比较值留空时,页面会提示保存失败。
|
||||
- 组合条件用「并且/或者」和一条条条件编辑,不再用 JSON 文本框。
|
||||
- 列表总数会跟着名称和查询筛选走。
|
||||
- 试算会显示「采用第一行,跳过 N 行」。
|
||||
- Playwright 已跑通,截图在 `docs/evidence/M05/ui/`。
|
||||
- 旧的独立规则版本接口还在,新页面不用它。
|
||||
- 映射 Playwright:1 passed。截图:trial-normal.png、trial-abnormal.png、trial-unknown.png、trial-first-row.png。
|
||||
|
||||
## 测试
|
||||
|
||||
- `uv run pytest tests/test_judgment.py tests/test_mapping_api.py tests/test_rule_versions.py tests/test_mapping_versions.py`:28 passed。
|
||||
- `pnpm test:unit`:95 passed。
|
||||
- 全量 `uv run pytest`:3 个数据源列表用例失败,失败点是新建记录不在返回的第一页,不是本模块断言。
|
||||
- Playwright:未运行。
|
||||
@@ -0,0 +1,35 @@
|
||||
{
|
||||
"taskId": "2026-11-18/m05-mapping-rules",
|
||||
"module": "M05",
|
||||
"title": "字段映射与规则判断模块",
|
||||
"type": "feature",
|
||||
"tier": "L",
|
||||
"phase": "done",
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "S8",
|
||||
"proposedNextSlice": null,
|
||||
"lastGate": "user-closed-done-local",
|
||||
"status": "DONE_LOCAL",
|
||||
"gatePolicy": {
|
||||
"selected": "autonomous",
|
||||
"effective": "autonomous",
|
||||
"recommended": "strict",
|
||||
"finalApprovalRequired": true,
|
||||
"allowTaskOverride": true,
|
||||
"overrideReason": "用户在任务入口明确指定 autonomous"
|
||||
},
|
||||
"gates": {
|
||||
"requirementFrozen": true,
|
||||
"planApproved": true,
|
||||
"contextPackReady": true,
|
||||
"criticPassed": true,
|
||||
"implementationDone": true,
|
||||
"reviewPassed": true,
|
||||
"validationPassed": true
|
||||
},
|
||||
"notes": [
|
||||
"User confirmed the plan on 2026-11-18 with 继续, including the listed assumptions.",
|
||||
"Plan critic recheck PASS_WITH_WARNINGS. S1 may start. S2/S3 must repeat RLS; S3 versions must be immutable in the database."
|
||||
],
|
||||
"updatedAt": "2026-11-19T02:05:00Z"
|
||||
}
|
||||
@@ -1,17 +1,17 @@
|
||||
{
|
||||
"taskId": "2026-11-18/m04-version-activate",
|
||||
"taskId": "2026-11-18/m05-mapping-rules",
|
||||
"type": "feature",
|
||||
"phase": "done",
|
||||
"allowedToCode": false,
|
||||
"currentSlice": "S4",
|
||||
"lastGate": "user-approved-done-local",
|
||||
"nextCommand": "start M05 when ready",
|
||||
"currentSlice": "S8",
|
||||
"lastGate": "user-closed-done-local",
|
||||
"nextCommand": "none",
|
||||
"gatePolicy": {
|
||||
"selected": "balanced",
|
||||
"effective": "balanced",
|
||||
"recommended": "balanced",
|
||||
"selected": "autonomous",
|
||||
"effective": "autonomous",
|
||||
"recommended": "strict",
|
||||
"finalApprovalRequired": true,
|
||||
"allowTaskOverride": true
|
||||
},
|
||||
"updatedAt": "2026-11-18T10:31:00Z"
|
||||
"updatedAt": "2026-11-19T02:05:00Z"
|
||||
}
|
||||
@@ -32,6 +32,8 @@
|
||||
| D24 | M04:查询正文采用参数化 SQL 模板(命名参数绑定;不可绑标识符白名单;不靠 SELECT 前缀)。本轮交付不可变查询版本(草稿可编辑,publish 生成只读快照;库级禁止 UPDATE/DELETE)。正式定时/场景采集留给 M08;本轮含定义 CRUD、版本、只读预览与配套 UI。执行必须经 M03 usable/熔断。仅 watchman-admin。正式 Vue 前须确认 HTML 原型。SQL Server 本轮不做查询试跑(无服务端强制只读会话),连接测试仍可用;预览仅 PostgreSQL/MySQL | 2026-11-18 用户确认 1=A、2b 及 Marionettist 计划;审查复审后收紧 SQL Server 与版本不可变 |
|
||||
| D25 | 控制台业务列表默认:表格上方有筛选条件(至少名称模糊;有类型/归属/状态则一并提供),「查询/重置」按钮提交筛选(禁止输入即筛),「新建」等页面按钮靠右;表头 `sortable=custom` 走后端 SQL 排序并配合分页;操作列按按钮数固定宽度。用户对本页另有说明时从其说明。细则见 `docs/current/frontend-ui.md` | 2026-11-18 用户明确要求;同日补充查询/重置、服务端排序分页、操作列宽 |
|
||||
| D26 | M04 增补:去掉查询「草稿/发布」两步。保存内容即插入下一不可变版本并自动设为 `current_version_no`;可激活任一历史版本为当前生效(详情与列表均可切换)。版本内容仍不可变。`draft_*` 列本轮保留并镜像 current,对外 API/UI 不暴露 draft。权限沿用既有 query write/publish,不新造权限点 | 2026-11-18 用户确认 1=C、2=A 并批准实现计划 |
|
||||
| D27 | M05:映射和规则挂在查询上,一条查询可有多条映射,一条映射可有多条规则;场景仍归 M08。查询列名即字段,不固定六格;一行可有多列指标,规则的每条条件自选列。身份列可配置、可为空,日期只是可选身份列。不勾身份列时整条映射是一条输入,多行取结果顺序的第一行。同一身份的值变化只追加修订。缺失与非法分开记录,结论都是未知;系统异常另记。单位只做已配置的乘数和偏移。条件成立为异常,不成立为正常;界面和接口用正常/异常/未知 | 2026-11-18 用户在 M05 入口逐项确认,最后明确多行默认第一行且身份/日期可配置 |
|
||||
| D28 | M05 映射与判断规则共用一个版本,不给规则单独编号。历史版本不可改;可切换当前版本,字段和条件一起换;可基于某一历史版本编辑,保存时另存为新版本并设为当前。列表不单设「判断规则」入口,规则在映射详情里一起编辑 | 2026-11-18 用户在原型上明确:规则与映射同版,并去掉列表上的判断规则按钮 |
|
||||
|
||||
## 冻结前/相关模块实现前必须确认
|
||||
|
||||
|
||||
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 27 KiB |
|
After Width: | Height: | Size: 58 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 43 KiB |
|
After Width: | Height: | Size: 40 KiB |
|
After Width: | Height: | Size: 40 KiB |
@@ -2,11 +2,11 @@
|
||||
|
||||
## 当前快照
|
||||
|
||||
- 当前阶段:M04 查询定义与采集 **DONE_LOCAL**(D24 查询模块 + D25 列表筛选排序 + D26 保存即版本/激活;用户确认可提交)。
|
||||
- 当前大任务:无(M04 已完成)。下一候选:M05(见 `docs/tasks/INDEX.md`)。
|
||||
- 用户授权:D21–D26。收尾任务 `gatePolicy.selected=balanced`。
|
||||
- Git:用户授权 commit/push。
|
||||
- 下一步:按 INDEX 进入 M05。
|
||||
- 当前阶段:M05 **DONE_LOCAL**。
|
||||
- 当前大任务:M05 已关闭。下一步是 M06,尚未开工。
|
||||
- 用户授权:D21–D28。本任务 `gatePolicy.selected=autonomous`。用户已确认收口并要求提交、推送。
|
||||
- Git:候选提交见下方台账。
|
||||
- 下一步:M06 开工前另确认。
|
||||
|
||||
## 大任务状态
|
||||
|
||||
@@ -15,7 +15,8 @@
|
||||
| M01 基础框架 | DONE_LOCAL | 实现 Composer;审查/复审异系列 | `8fb16f4` | PASS_WITH_WARNINGS(必改已关) | pytest 23;unit 8;e2e 3 | 已完成 |
|
||||
| M02 统一登录与权限 | DONE_LOCAL | 主 Agent;复审 claude-opus | `f8e1c77` | 复审阻塞已由 D20 关闭 | pytest 58;unit 10;登录 Playwright 4 | 已完成 |
|
||||
| M03 数据源配置 | DONE_LOCAL | 实现 Claude Sonnet;审查 GPT | `e6d37d1` | S1–S8 片审通过;用户联调收尾 | pytest 262+;console unit 39;datasources e2e 18;证据 `docs/evidence/M03/ui/` | 已完成 |
|
||||
| M04 查询定义与采集 | DONE_LOCAL | 主 Agent 编排;D26 激活切片已实现 | `21cc721` | 模块复审 PASS;D26 回归 pytest/e2e | query* pytest 201;queries unit 52;e2e queries 16;`docs/evidence/M04/ui/` | 已完成;下一 M05 |
|
||||
| M04 查询定义与采集 | DONE_LOCAL | 主 Agent 编排;D26 激活切片已实现 | `21cc721` | 模块复审 PASS;D26 回归 pytest/e2e | query* pytest 201;queries unit 52;e2e queries 16;`docs/evidence/M04/ui/` | 已完成 |
|
||||
| M05 字段映射与规则判断 | DONE_LOCAL | 主 Agent 收尾 | `2527097` | S8 PASS_WITH_WARNINGS | 映射 pytest;console 单测;Playwright 1;查询试算已在浏览器看过;证据 `docs/evidence/M05/ui/` | 已完成 |
|
||||
|
||||
## 当前阻塞
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
| M02 | 统一登录与权限模块 | M01 | Casdoor/OIDC 接入、后端授权、前端会话、范围及权限测试;真实配置缺失单列 |
|
||||
| M03 | 数据源配置模块 | M02 | 数据源 API+列表/编辑+连接测试、凭证保护及引用提示 |
|
||||
| M04 | 查询定义与采集模块 | M03 | 受控查询、参数与输出契约、只读执行、预览和配套界面;不开放任意脚本 |
|
||||
| M05 | 字段映射与规则判断模块 | M04 | 映射预览、类型/空值、输入身份、结构化规则编辑、PASS/FAIL/UNKNOWN、测试 |
|
||||
| M05 | 字段映射与规则判断模块 | M04 | 映射预览、类型/空值、输入身份、结构化规则编辑、正常/异常/未知、测试 |
|
||||
| M06 | 报警中心与人工处理模块 | M05 | 报警创建/合并、详情/列表、接手、进展、关闭、新周期规则与 UI;不发送真实消息 |
|
||||
| M07 | 企业微信通知模块 | M06 | 应用和机器人、目标/模板、多目标任务、试发、结果和失败重试、完整 UI |
|
||||
| M08 | 场景配置与 Cron 调度模块 | M05、M07 | 组合场景、草稿/发布/启停、开源 Cron 编辑/解析/定时触发、样例运行;基础正式链可验证 |
|
||||
@@ -54,7 +54,7 @@ M01 基础框架中包含最小授权接口契约,正式登录在 M02;不允
|
||||
### M05 字段映射与规则判断
|
||||
|
||||
- 内部分解示例:映射与转换 → 输入身份 → 条件 schema → 计算器 → 编辑/样例 UI → 边界测试。
|
||||
- 验收:比较边界、AND/OR 缺失真值表、重复输入与新周期;UNKNOWN 不默认报警。规则原因分析不在此模块。
|
||||
- 验收:比较边界、AND/OR 缺失真值表、重复输入与新周期;未知不默认报警。规则原因分析不在此模块。
|
||||
|
||||
### M06 报警中心与人工处理
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
# M05 字段映射与规则判断模块
|
||||
|
||||
一个会话聚焦本模块。S1~S8 已审查。用户于 2026-11-19 确认收口,标 DONE_LOCAL。
|
||||
|
||||
## 内部步骤
|
||||
|
||||
- [x] 关闭阻塞口径,冻结需求并切片。
|
||||
- [x] 用户以「继续」确认计划(含版本方式、深度 4、试算不落库、第一行顺序)。
|
||||
- [x] 计划 critic 复审 PASS_WITH_WARNINGS。
|
||||
- [x] S1 映射模型、强制行级安全、版本不可变。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S2 输入身份与修订。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S3 规则结构校验。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S4 正常/异常/未知计算。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S5 接口与权限。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S6 HTML 原型。浏览器点过列表、详情保存、试算、规则和越权拒绝。
|
||||
- [x] S7 正式页面。判断规则与映射同版。新建无版本时用查询输出列。审查 PASS_WITH_WARNINGS。
|
||||
- [x] S8 模块复审 PASS_WITH_WARNINGS。映射相关 pytest 已过;控制台 unit 95 passed。Playwright 1 passed,截图在 `docs/evidence/M05/ui/`。
|
||||
- [x] 用户确认收口,标 DONE_LOCAL。
|
||||
|
||||
## 目标与边界
|
||||
|
||||
- 前置:M04 DONE_LOCAL。
|
||||
- 范围:A-021~A-026。映射预览、类型与空值、输入身份、结构化条件、正常/异常/未知、样例测试。
|
||||
- 明确不做:报警(M06)、场景与 Cron(M08)、原因分析(M12)、任意脚本。
|
||||
- 已确认 D27:映射/规则挂在查询上;列不固定;身份列可空;不勾身份列时多行取第一行;结论用正常/异常/未知。
|
||||
- O06 的报警更新仍归 M06。
|
||||
|
||||
## 证据与结论
|
||||
|
||||
- 证据:`docs/tasks/M05.md`;需求与计划在 `.task/2026-11-18/m05-mapping-rules/`
|
||||
- 状态:DONE_LOCAL。`gatePolicy.selected=autonomous`。
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Create versioned query mappings with forced tenant isolation.
|
||||
|
||||
Revision ID: 20261118_0010
|
||||
Revises: 20261118_0009
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0010"
|
||||
down_revision: Union[str, None] = "20261118_0009"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
DEFINITIONS = "mapping_definitions"
|
||||
VERSIONS = "mapping_versions"
|
||||
COLUMNS = "mapping_column_configs"
|
||||
FUNCTION = "mapping_versions_reject_mutation"
|
||||
TRIGGER = "trg_mapping_versions_append_only"
|
||||
COLUMN_FUNCTION = "mapping_column_configs_reject_mutation"
|
||||
COLUMN_TRIGGER = "trg_mapping_column_configs_append_only"
|
||||
|
||||
|
||||
def _enable_rls(table: str) -> None:
|
||||
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
||||
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE POLICY tenant_isolation ON {table}
|
||||
FOR ALL
|
||||
TO {APP_ROLE}
|
||||
USING (tenant_id = current_setting('app.tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
|
||||
"""
|
||||
)
|
||||
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {table} TO {APP_ROLE}")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
DEFINITIONS,
|
||||
sa.Column(
|
||||
"id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
server_default=sa.text("gen_random_uuid()"),
|
||||
primary_key=True,
|
||||
),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
"query_definition_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("query_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("latest_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("current_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.CheckConstraint(
|
||||
"latest_version_no IS NULL OR latest_version_no >= 1",
|
||||
name="ck_mapping_definitions_latest_version",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"current_version_no IS NULL OR current_version_no >= 1",
|
||||
name="ck_mapping_definitions_current_version",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_mapping_definitions_query_definition_id", DEFINITIONS, ["query_definition_id"]
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
VERSIONS,
|
||||
sa.Column(
|
||||
"id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
server_default=sa.text("gen_random_uuid()"),
|
||||
primary_key=True,
|
||||
),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
"definition_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey(f"{DEFINITIONS}.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("version_no", sa.Integer(), nullable=False),
|
||||
sa.Column("saved_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("saved_by", sa.String(length=128), nullable=True),
|
||||
sa.UniqueConstraint("definition_id", "version_no", name="uq_mapping_versions_definition_version"),
|
||||
sa.CheckConstraint("version_no >= 1", name="ck_mapping_versions_version_no"),
|
||||
)
|
||||
|
||||
op.create_table(
|
||||
COLUMNS,
|
||||
sa.Column(
|
||||
"id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
server_default=sa.text("gen_random_uuid()"),
|
||||
primary_key=True,
|
||||
),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
"mapping_version_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey(f"{VERSIONS}.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("source_column_name", sa.String(length=128), nullable=False),
|
||||
sa.Column("value_type", sa.String(length=16), nullable=False),
|
||||
sa.Column("is_identity", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||
sa.Column("is_observation_time", sa.Boolean(), server_default=sa.text("false"), nullable=False),
|
||||
sa.Column("numeric_multiply", sa.Numeric(precision=24, scale=8), nullable=True),
|
||||
sa.Column("numeric_offset", sa.Numeric(precision=24, scale=8), nullable=True),
|
||||
sa.UniqueConstraint(
|
||||
"mapping_version_id",
|
||||
"source_column_name",
|
||||
name="uq_mapping_column_configs_version_source",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"value_type IN ('number', 'string', 'boolean', 'datetime')",
|
||||
name="ck_mapping_column_configs_value_type",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"(value_type = 'number') OR (numeric_multiply IS NULL AND numeric_offset IS NULL)",
|
||||
name="ck_mapping_column_configs_numeric_only",
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
"uq_mapping_column_configs_one_observation_time",
|
||||
COLUMNS,
|
||||
["mapping_version_id"],
|
||||
unique=True,
|
||||
postgresql_where=sa.text("is_observation_time"),
|
||||
)
|
||||
|
||||
for table in (DEFINITIONS, VERSIONS, COLUMNS):
|
||||
_enable_rls(table)
|
||||
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {VERSIONS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {VERSIONS} TO {APP_ROLE}")
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {COLUMNS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {COLUMNS} TO {APP_ROLE}")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {FUNCTION}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'mapping_versions is append-only: saved versions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {COLUMN_FUNCTION}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'mapping_column_configs is append-only: saved versions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {VERSIONS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {COLUMN_TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {COLUMNS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {COLUMN_FUNCTION}()
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in (COLUMNS, VERSIONS, DEFINITIONS):
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {COLUMN_TRIGGER} ON {COLUMNS}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {VERSIONS}")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {COLUMN_FUNCTION}()")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
|
||||
op.drop_index("uq_mapping_column_configs_one_observation_time", table_name=COLUMNS)
|
||||
op.drop_table(COLUMNS)
|
||||
op.drop_table(VERSIONS)
|
||||
op.drop_index("ix_mapping_definitions_query_definition_id", table_name=DEFINITIONS)
|
||||
op.drop_table(DEFINITIONS)
|
||||
@@ -0,0 +1,138 @@
|
||||
"""Create tenant-scoped mapped-input identities and append-only revisions.
|
||||
|
||||
Revision ID: 20261118_0011
|
||||
Revises: 20261118_0010
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0011"
|
||||
down_revision: Union[str, None] = "20261118_0010"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
INPUTS = "mapped_inputs"
|
||||
REVISIONS = "mapped_input_revisions"
|
||||
FUNCTION = "mapped_input_revisions_reject_mutation"
|
||||
TRIGGER = "trg_mapped_input_revisions_append_only"
|
||||
|
||||
|
||||
def _enable_rls(table: str) -> None:
|
||||
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
||||
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE POLICY tenant_isolation ON {table}
|
||||
FOR ALL
|
||||
TO {APP_ROLE}
|
||||
USING (tenant_id = current_setting('app.tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
|
||||
"""
|
||||
)
|
||||
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {table} TO {APP_ROLE}")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
INPUTS,
|
||||
sa.Column(
|
||||
"id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
server_default=sa.text("gen_random_uuid()"),
|
||||
primary_key=True,
|
||||
),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
"mapping_definition_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("identity_key", sa.String(length=4096), nullable=False),
|
||||
sa.Column("latest_revision_no", sa.Integer(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.UniqueConstraint(
|
||||
"tenant_id",
|
||||
"mapping_definition_id",
|
||||
"identity_key",
|
||||
name="uq_mapped_inputs_tenant_mapping_identity",
|
||||
),
|
||||
sa.CheckConstraint(
|
||||
"latest_revision_no IS NULL OR latest_revision_no >= 1",
|
||||
name="ck_mapped_inputs_latest_revision",
|
||||
),
|
||||
)
|
||||
op.create_index("ix_mapped_inputs_mapping_definition_id", INPUTS, ["mapping_definition_id"])
|
||||
|
||||
op.create_table(
|
||||
REVISIONS,
|
||||
sa.Column(
|
||||
"id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
server_default=sa.text("gen_random_uuid()"),
|
||||
primary_key=True,
|
||||
),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column(
|
||||
"input_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("mapped_inputs.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"mapping_version_id",
|
||||
postgresql.UUID(as_uuid=True),
|
||||
sa.ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("revision_no", sa.Integer(), nullable=False),
|
||||
sa.Column("mapped_values", postgresql.JSONB(), nullable=False),
|
||||
sa.Column("recorded_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.UniqueConstraint("input_id", "revision_no", name="uq_mapped_input_revisions_input_revision"),
|
||||
sa.CheckConstraint("revision_no >= 1", name="ck_mapped_input_revisions_revision_no"),
|
||||
)
|
||||
op.create_index("ix_mapped_input_revisions_input_id", REVISIONS, ["input_id"])
|
||||
|
||||
for table in (INPUTS, REVISIONS):
|
||||
_enable_rls(table)
|
||||
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {REVISIONS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {REVISIONS} TO {APP_ROLE}")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {FUNCTION}() RETURNS trigger
|
||||
LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'mapped_input_revisions is append-only: revisions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {REVISIONS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in (REVISIONS, INPUTS):
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {REVISIONS}")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
|
||||
op.drop_index("ix_mapped_input_revisions_input_id", table_name=REVISIONS)
|
||||
op.drop_table(REVISIONS)
|
||||
op.drop_index("ix_mapped_inputs_mapping_definition_id", table_name=INPUTS)
|
||||
op.drop_table(INPUTS)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""Create immutable structured rules for mappings.
|
||||
|
||||
Revision ID: 20261118_0012
|
||||
Revises: 20261118_0011
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0012"
|
||||
down_revision: Union[str, None] = "20261118_0011"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
APP_ROLE = "watchman_app"
|
||||
DEFINITIONS = "rule_definitions"
|
||||
VERSIONS = "rule_versions"
|
||||
FUNCTION = "rule_versions_reject_mutation"
|
||||
TRIGGER = "trg_rule_versions_append_only"
|
||||
|
||||
|
||||
def _enable_rls(table: str) -> None:
|
||||
op.execute(f"ALTER TABLE {table} ENABLE ROW LEVEL SECURITY")
|
||||
op.execute(f"ALTER TABLE {table} FORCE ROW LEVEL SECURITY")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE POLICY tenant_isolation ON {table}
|
||||
FOR ALL TO {APP_ROLE}
|
||||
USING (tenant_id = current_setting('app.tenant_id', true))
|
||||
WITH CHECK (tenant_id = current_setting('app.tenant_id', true))
|
||||
"""
|
||||
)
|
||||
op.execute(f"GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE {table} TO {APP_ROLE}")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
DEFINITIONS,
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column("mapping_definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("mapping_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||
sa.Column("latest_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("current_version_no", sa.Integer(), nullable=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.CheckConstraint("latest_version_no IS NULL OR latest_version_no >= 1", name="ck_rule_definitions_latest_version"),
|
||||
sa.CheckConstraint("current_version_no IS NULL OR current_version_no >= 1", name="ck_rule_definitions_current_version"),
|
||||
)
|
||||
op.create_index("ix_rule_definitions_mapping_definition_id", DEFINITIONS, ["mapping_definition_id"])
|
||||
op.create_table(
|
||||
VERSIONS,
|
||||
sa.Column("id", postgresql.UUID(as_uuid=True), server_default=sa.text("gen_random_uuid()"), primary_key=True),
|
||||
sa.Column("tenant_id", sa.String(length=64), nullable=False),
|
||||
sa.Column("definition_id", postgresql.UUID(as_uuid=True), sa.ForeignKey("rule_definitions.id", ondelete="RESTRICT"), nullable=False),
|
||||
sa.Column("version_no", sa.Integer(), nullable=False),
|
||||
sa.Column("condition_tree", postgresql.JSONB(), nullable=False),
|
||||
sa.Column("saved_at", sa.DateTime(timezone=True), server_default=sa.text("now()"), nullable=False),
|
||||
sa.Column("saved_by", sa.String(length=128), nullable=True),
|
||||
sa.UniqueConstraint("definition_id", "version_no", name="uq_rule_versions_definition_version"),
|
||||
sa.CheckConstraint("version_no >= 1", name="ck_rule_versions_version_no"),
|
||||
)
|
||||
for table in (DEFINITIONS, VERSIONS):
|
||||
_enable_rls(table)
|
||||
op.execute(f"REVOKE UPDATE, DELETE ON TABLE {VERSIONS} FROM {APP_ROLE}")
|
||||
op.execute(f"GRANT SELECT, INSERT ON TABLE {VERSIONS} TO {APP_ROLE}")
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE FUNCTION {FUNCTION}() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'rule_versions is append-only: saved versions are immutable'
|
||||
USING ERRCODE = 'restrict_violation';
|
||||
END;
|
||||
$$
|
||||
"""
|
||||
)
|
||||
op.execute(
|
||||
f"""
|
||||
CREATE TRIGGER {TRIGGER}
|
||||
BEFORE UPDATE OR DELETE OR TRUNCATE ON {VERSIONS}
|
||||
FOR EACH STATEMENT EXECUTE FUNCTION {FUNCTION}()
|
||||
"""
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
for table in (VERSIONS, DEFINITIONS):
|
||||
op.execute(f"DROP POLICY IF EXISTS tenant_isolation ON {table}")
|
||||
op.execute(f"DROP TRIGGER IF EXISTS {TRIGGER} ON {VERSIONS}")
|
||||
op.execute(f"DROP FUNCTION IF EXISTS {FUNCTION}()")
|
||||
op.drop_table(VERSIONS)
|
||||
op.drop_index("ix_rule_definitions_mapping_definition_id", table_name=DEFINITIONS)
|
||||
op.drop_table(DEFINITIONS)
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Store mapping condition trees on immutable mapping versions.
|
||||
|
||||
Revision ID: 20261118_0013
|
||||
Revises: 20261118_0012
|
||||
Create Date: 2026-11-18
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
from sqlalchemy.dialects import postgresql
|
||||
|
||||
revision: str = "20261118_0013"
|
||||
down_revision: Union[str, None] = "20261118_0012"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("mapping_versions", sa.Column("condition_tree", postgresql.JSONB(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("mapping_versions", "condition_tree")
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Seed three mapping examples on the M04 demo source.
|
||||
|
||||
One simple threshold, one nested condition group, and one time-and-value group.
|
||||
Re-running keeps an existing mapping instead of appending another version.
|
||||
Does not print passwords or connection strings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
|
||||
from watchman.core.config import get_settings, merge_layered_env, reload_settings
|
||||
from watchman.core.db import session_scope
|
||||
from watchman.models.mapping import MappingDefinition
|
||||
from watchman.services import datasources as ds_service
|
||||
from watchman.services import mappings as mapping_service
|
||||
from watchman.services.judgment import evaluate_rows
|
||||
from watchman.services.queries import list_queries
|
||||
|
||||
from seed_m04_demo import (
|
||||
DS_NAME,
|
||||
OUTPUT_SCHEMA,
|
||||
PARAM_SCHEMA_OPTIONAL,
|
||||
SQL_OPTIONAL,
|
||||
_require_pg,
|
||||
ensure_datasource,
|
||||
ensure_query,
|
||||
)
|
||||
|
||||
COLUMNS = [
|
||||
{"source_column_name": "line_code", "value_type": "string", "is_identity": True, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "lot_no", "value_type": "string", "is_identity": True, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "metric", "value_type": "string", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "reading_value", "value_type": "number", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "sampled_at", "value_type": "datetime", "is_identity": False, "is_observation_time": True, "numeric_multiply": None, "numeric_offset": None},
|
||||
]
|
||||
|
||||
ROWS = [
|
||||
{"line_code": "L1", "lot_no": "LOT-1002", "metric": "temp_c", "reading_value": 91, "sampled_at": "2026-11-18T02:05:00+00:00"},
|
||||
{"line_code": "L2", "lot_no": "LOT-2001", "metric": "temp_c", "reading_value": 72.3, "sampled_at": "2026-11-18T02:10:00+00:00"},
|
||||
{"line_code": "L1", "lot_no": "LOT-1001", "metric": "pressure_kpa", "reading_value": 101.2, "sampled_at": "2026-11-18T02:01:00+00:00"},
|
||||
{"line_code": "L2", "lot_no": "LOT-2001", "metric": "pressure_kpa", "reading_value": 98, "sampled_at": "2026-11-18T02:11:00+00:00"},
|
||||
{"line_code": "L3", "lot_no": "LOT-3001", "metric": "temp_c", "reading_value": None, "sampled_at": "2026-11-18T02:20:00+00:00"},
|
||||
{"line_code": "L3", "lot_no": "LOT-3002", "metric": "temp_c", "reading_value": 91, "sampled_at": "2026-11-18T02:30:00"},
|
||||
]
|
||||
|
||||
EXAMPLES = [
|
||||
{
|
||||
"name": "示例·简单规则·读数大于85",
|
||||
"description": "一条条件:reading_value 大于 85。不看指标名。",
|
||||
"tree": {"column": "reading_value", "operator": "gt", "value": 85},
|
||||
},
|
||||
{
|
||||
"name": "示例·规则组·温度或压力超限",
|
||||
"description": "两组条件用「或者」连接:温度大于 85,或压力大于 100。",
|
||||
"tree": {
|
||||
"op": "or",
|
||||
"items": [
|
||||
{"op": "and", "items": [
|
||||
{"column": "metric", "operator": "eq", "value": "temp_c"},
|
||||
{"column": "reading_value", "operator": "gt", "value": 85},
|
||||
]},
|
||||
{"op": "and", "items": [
|
||||
{"column": "metric", "operator": "eq", "value": "pressure_kpa"},
|
||||
{"column": "reading_value", "operator": "gt", "value": 100},
|
||||
]},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
"name": "示例·规则组·观测时间并且读数大于80",
|
||||
"description": "同一组里两条都要满足:观测时间晚于 2026-11-18 02:00(带时区),并且读数大于 80。",
|
||||
"tree": {
|
||||
"op": "and",
|
||||
"items": [
|
||||
{"column": "sampled_at", "operator": "gt", "value": "2026-11-18T02:00:00+00:00"},
|
||||
{"column": "reading_value", "operator": "gt", "value": 80},
|
||||
],
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def ensure_mapping(query_id: str, tree: dict) -> str:
|
||||
from sqlalchemy import select
|
||||
|
||||
with session_scope() as session:
|
||||
row = session.scalar(select(MappingDefinition).where(MappingDefinition.query_definition_id == query_id))
|
||||
if row is not None and row.current_version_no:
|
||||
print(f"mapping kept: query={query_id} current=v{row.current_version_no}")
|
||||
return str(row.id)
|
||||
if row is None:
|
||||
row = mapping_service.create_mapping(session, query_definition_id=query_id)
|
||||
version = mapping_service.save_mapping_version(session, str(row.id), COLUMNS, condition_tree=tree, saved_by="seed_m05_examples")
|
||||
session.commit()
|
||||
print(f"mapping saved: id={row.id} current=v{version.version_no}")
|
||||
return str(row.id)
|
||||
|
||||
|
||||
def show_trial(name: str, tree: dict) -> None:
|
||||
judged = evaluate_rows(ROWS, COLUMNS, tree, [column["source_column_name"] for column in COLUMNS])
|
||||
codes = [item["code"] for item in judged.get("rows", [])]
|
||||
print(f"trial {name}: {judged.get('outcome')} {codes or judged}")
|
||||
empty = evaluate_rows([], COLUMNS, tree, [column["source_column_name"] for column in COLUMNS])
|
||||
print(f"trial {name} empty: {empty.get('outcome')}")
|
||||
|
||||
|
||||
def main() -> int:
|
||||
reload_settings()
|
||||
env = merge_layered_env()
|
||||
pg = _require_pg(env)
|
||||
print(f"tenant={get_settings().tenant_id}")
|
||||
datasource_id = ensure_datasource(pg)
|
||||
with session_scope() as session:
|
||||
source = next((row for row in ds_service.list_datasources(session) if row.name == DS_NAME), None)
|
||||
if source is None:
|
||||
raise SystemExit("demo datasource is missing")
|
||||
datasource_id = str(source.id)
|
||||
for example in EXAMPLES:
|
||||
query_id = ensure_query(
|
||||
datasource_id,
|
||||
name=example["name"],
|
||||
description=example["description"],
|
||||
sql_template=SQL_OPTIONAL,
|
||||
param_schema=PARAM_SCHEMA_OPTIONAL,
|
||||
)
|
||||
ensure_mapping(query_id, example["tree"])
|
||||
show_trial(example["name"], example["tree"])
|
||||
with session_scope() as session:
|
||||
names = [row.name for row in list_queries(session)]
|
||||
print("queries now include: " + ", ".join(name for name in names if name.startswith("示例·")))
|
||||
print("output schema columns: " + ", ".join(item["name"] for item in OUTPUT_SCHEMA))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -10,7 +10,7 @@ from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
|
||||
from watchman.api.routes import auth, datasources, health, platform, queries
|
||||
from watchman.api.routes import auth, datasources, health, mappings, platform, queries
|
||||
from watchman.core.config import ensure_runtime_config, get_settings, is_non_production
|
||||
from watchman.core.errors import AppError, ValidationError
|
||||
from watchman.core.request_id import REQUEST_ID_HEADER, resolve_request_id
|
||||
@@ -79,6 +79,7 @@ def create_app(*, validate_runtime: bool = True) -> FastAPI:
|
||||
app.include_router(platform.router)
|
||||
app.include_router(datasources.router)
|
||||
app.include_router(queries.router)
|
||||
app.include_router(mappings.router)
|
||||
|
||||
@app.exception_handler(AppError)
|
||||
async def app_error_handler(request: Request, exc: AppError) -> JSONResponse:
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
"""Mapping, rule, and trial routes using existing mapping, rule, query-preview, and judgment services.
|
||||
|
||||
Boundary: validates request shapes and permissions; it never persists trial rows or executes SQL directly.
|
||||
Depends on service-layer persistence and the existing query preview path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.auth.principal import (
|
||||
require_mapping_reader, require_mapping_trialer, require_mapping_writer, require_query_previewer,
|
||||
)
|
||||
from watchman.core.db import get_db_session
|
||||
from watchman.core.errors import NotFoundError, ValidationError
|
||||
from watchman.core.response import success_body
|
||||
from watchman.models.mapping import MappingColumnConfig, MappingDefinition, MappingVersion, RuleDefinition, RuleVersion
|
||||
from watchman.models.query import QueryDefinition
|
||||
from watchman.services import mappings as mapping_service
|
||||
from watchman.services import queries as query_service
|
||||
from watchman.services import rules as rule_service
|
||||
from watchman.services.judgment import evaluate_rows
|
||||
|
||||
router = APIRouter(prefix="/mappings", tags=["mappings"])
|
||||
|
||||
|
||||
class MappingCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
query_definition_id: str
|
||||
|
||||
|
||||
class MappingVersionCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
columns: list[dict[str, Any]]
|
||||
condition_tree: dict[str, Any] | None = None
|
||||
|
||||
|
||||
class RuleCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
|
||||
|
||||
class RuleVersionCreate(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
condition_tree: dict[str, Any]
|
||||
|
||||
|
||||
class TrialBody(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
condition_tree: dict[str, Any] | None = None
|
||||
rows: list[dict[str, Any]] | None = None
|
||||
query_params: dict[str, Any] = Field(default_factory=dict)
|
||||
row_limit: int | None = None
|
||||
|
||||
|
||||
def _row_limit(value: int | None) -> int:
|
||||
"""Default the query trial to 10 rows and keep a caller-chosen limit inside 1..100."""
|
||||
chosen = 10 if value is None else value
|
||||
return min(100, max(1, chosen))
|
||||
|
||||
|
||||
def _ok(request: Request, data: Any) -> JSONResponse:
|
||||
return JSONResponse(content=success_body(data, request_id=request.state.request_id))
|
||||
|
||||
|
||||
def _mapping(session: Session, mapping_id: str) -> MappingDefinition:
|
||||
return mapping_service._get_mapping(session, mapping_id, lock=False)
|
||||
|
||||
|
||||
def _snapshot(session: Session, mapping: MappingDefinition) -> tuple[MappingVersion, list[MappingColumnConfig]]:
|
||||
version, columns = mapping_service._current_mapping_snapshot(session, mapping)
|
||||
return version, columns
|
||||
|
||||
|
||||
@router.post("")
|
||||
def create_mapping(request: Request, body: MappingCreate, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = mapping_service.create_mapping(session, query_definition_id=body.query_definition_id)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "query_definition_id": str(row.query_definition_id)})
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_mappings(
|
||||
request: Request, name: str | None = None, query: str | None = None, page: int = 1,
|
||||
page_size: int = 20, sort_by: str = "created_at", sort_order: str = "desc",
|
||||
_: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
stmt = select(MappingDefinition, QueryDefinition.name).join(QueryDefinition, QueryDefinition.id == MappingDefinition.query_definition_id)
|
||||
if name:
|
||||
stmt = stmt.where(QueryDefinition.name.ilike(f"%{name}%"))
|
||||
if query:
|
||||
stmt = stmt.where(QueryDefinition.name.ilike(f"%{query}%"))
|
||||
order = MappingDefinition.created_at.desc() if sort_order == "desc" else MappingDefinition.created_at.asc()
|
||||
rows = session.execute(stmt.order_by(order).offset((page - 1) * page_size).limit(page_size)).all()
|
||||
count = select(func.count()).select_from(MappingDefinition).join(QueryDefinition, QueryDefinition.id == MappingDefinition.query_definition_id)
|
||||
if name:
|
||||
count = count.where(QueryDefinition.name.ilike(f"%{name}%"))
|
||||
if query:
|
||||
count = count.where(QueryDefinition.name.ilike(f"%{query}%"))
|
||||
total = session.scalar(count) or 0
|
||||
return _ok(request, {"items": [{"id": str(row.id), "name": query_name, "query": query_name, "current_version_no": row.current_version_no} for row, query_name in rows], "total": total, "page": page, "page_size": page_size})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}")
|
||||
def get_mapping(request: Request, mapping_id: str, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = _mapping(session, mapping_id)
|
||||
return _ok(request, {"id": str(row.id), "query_definition_id": str(row.query_definition_id), "current_version_no": row.current_version_no})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/versions")
|
||||
def save_mapping_version(request: Request, mapping_id: str, body: MappingVersionCreate, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = mapping_service.save_mapping_version(session, mapping_id, body.columns, condition_tree=body.condition_tree)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "version_no": row.version_no, "condition_tree": row.condition_tree})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}/versions")
|
||||
def list_mapping_versions(request: Request, mapping_id: str, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
rows = session.scalars(select(MappingVersion).where(MappingVersion.definition_id == mapping.id).order_by(MappingVersion.version_no.desc()))
|
||||
return _ok(request, {"items": [{"id": str(row.id), "version_no": row.version_no} for row in rows]})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}/versions/{version_no}")
|
||||
def get_mapping_version(request: Request, mapping_id: str, version_no: int, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version = session.scalar(select(MappingVersion).where(MappingVersion.definition_id == mapping.id, MappingVersion.version_no == version_no))
|
||||
if version is None:
|
||||
raise NotFoundError("Mapping version not found")
|
||||
columns = list(session.scalars(select(MappingColumnConfig).where(MappingColumnConfig.mapping_version_id == version.id)))
|
||||
return _ok(request, {"id": str(version.id), "version_no": version.version_no, "condition_tree": version.condition_tree, "columns": [{"source_column_name": c.source_column_name, "value_type": c.value_type, "is_identity": c.is_identity, "is_observation_time": c.is_observation_time, "numeric_multiply": str(c.numeric_multiply) if c.numeric_multiply is not None else None, "numeric_offset": str(c.numeric_offset) if c.numeric_offset is not None else None} for c in columns]})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/versions/{version_no}/activate")
|
||||
def activate_mapping_version(request: Request, mapping_id: str, version_no: int, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version = session.scalar(select(MappingVersion).where(MappingVersion.definition_id == mapping.id, MappingVersion.version_no == version_no))
|
||||
if version is None:
|
||||
raise NotFoundError("Mapping version not found")
|
||||
mapping.current_version_no = version_no
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(mapping.id), "current_version_no": mapping.current_version_no})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/rules")
|
||||
def create_rule(request: Request, mapping_id: str, body: RuleCreate | None = None, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
row = rule_service.create_rule(session, mapping_definition_id=mapping_id)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "mapping_definition_id": str(row.mapping_definition_id)})
|
||||
|
||||
|
||||
@router.get("/{mapping_id}/rules/{rule_id}")
|
||||
def get_rule(request: Request, mapping_id: str, rule_id: str, _: None = Depends(require_mapping_reader), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
rule = session.get(RuleDefinition, rule_id)
|
||||
if rule is None or str(rule.mapping_definition_id) != mapping_id:
|
||||
raise NotFoundError("Rule not found")
|
||||
return _ok(request, {"id": str(rule.id), "current_version_no": rule.current_version_no})
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/rules/{rule_id}/versions")
|
||||
def save_rule_version(request: Request, mapping_id: str, rule_id: str, body: RuleVersionCreate, _: None = Depends(require_mapping_writer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
rule = session.get(RuleDefinition, rule_id)
|
||||
if rule is None or str(rule.mapping_definition_id) != mapping_id:
|
||||
raise NotFoundError("Rule not found")
|
||||
row = rule_service.save_rule_version(session, rule_id, body.condition_tree)
|
||||
session.commit()
|
||||
return _ok(request, {"id": str(row.id), "version_no": row.version_no, "condition_tree": row.condition_tree})
|
||||
|
||||
|
||||
def _judge(session: Session, mapping: MappingDefinition, columns: list[Any], tree: dict[str, Any] | None, rows: list[dict[str, Any]], names: list[str]) -> dict[str, Any]:
|
||||
chosen = tree if isinstance(tree, dict) and tree else None
|
||||
if chosen is None:
|
||||
return {"outcome": "error", "details": {"reason": "rule_missing"}}
|
||||
types = {column.source_column_name: column.value_type for column in columns}
|
||||
try:
|
||||
rule_service._validate_tree(chosen, types)
|
||||
except ValidationError as exc:
|
||||
return {"outcome": "error", "details": getattr(exc, "details", {})}
|
||||
return evaluate_rows(rows, columns, chosen, names)
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/trial")
|
||||
def trial_mapping(request: Request, mapping_id: str, body: TrialBody, _: None = Depends(require_mapping_trialer), session: Session = Depends(get_db_session)) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version, columns = _snapshot(session, mapping)
|
||||
names = mapping_service.current_query_column_names(session, mapping)
|
||||
return _ok(request, _judge(session, mapping, columns, body.condition_tree or version.condition_tree, body.rows or [], names))
|
||||
|
||||
|
||||
@router.post("/{mapping_id}/trial-query")
|
||||
def trial_mapping_query(
|
||||
request: Request, mapping_id: str, body: TrialBody,
|
||||
_: None = Depends(require_mapping_trialer), __: None = Depends(require_query_previewer),
|
||||
session: Session = Depends(get_db_session),
|
||||
) -> JSONResponse:
|
||||
mapping = _mapping(session, mapping_id)
|
||||
version, columns = _snapshot(session, mapping)
|
||||
limit = _row_limit(body.row_limit)
|
||||
preview = query_service.preview_current(session, str(mapping.query_definition_id), body.query_params)
|
||||
if preview["status"] not in ("success", "empty"):
|
||||
session.commit()
|
||||
return _ok(request, {"outcome": "error", "details": preview.get("details", {})})
|
||||
source_rows = list(preview.get("rows") or [])[:limit]
|
||||
data = _judge(session, mapping, columns, body.condition_tree or version.condition_tree, source_rows, preview.get("columns") or [])
|
||||
data["input_rows"] = source_rows
|
||||
session.commit()
|
||||
return _ok(request, data)
|
||||
@@ -21,6 +21,9 @@ QUERY_READ_NODE = "perm:data:emp:watchman.query.read"
|
||||
QUERY_WRITE_NODE = "perm:data:emp:watchman.query.write"
|
||||
QUERY_PUBLISH_NODE = "perm:data:emp:watchman.query.publish"
|
||||
QUERY_PREVIEW_NODE = "perm:data:emp:watchman.query.preview"
|
||||
MAPPING_READ_NODE = "perm:data:emp:watchman.mapping.read"
|
||||
MAPPING_WRITE_NODE = "perm:data:emp:watchman.mapping.write"
|
||||
MAPPING_TRIAL_NODE = "perm:data:emp:watchman.mapping.trial"
|
||||
|
||||
ROLE_ADMIN = "watchman-admin"
|
||||
ROLE_OPERATOR = "watchman-operator"
|
||||
@@ -94,6 +97,24 @@ def require_query_preview(role_names: list[str]) -> None:
|
||||
raise ForbiddenError(permission_node=QUERY_PREVIEW_NODE)
|
||||
|
||||
|
||||
def require_mapping_read(role_names: list[str]) -> None:
|
||||
"""Allow mapping and rule reads only for watchman-admin."""
|
||||
if ROLE_ADMIN not in role_names:
|
||||
raise ForbiddenError(permission_node=MAPPING_READ_NODE)
|
||||
|
||||
|
||||
def require_mapping_write(role_names: list[str]) -> None:
|
||||
"""Allow mapping and rule writes only for watchman-admin."""
|
||||
if ROLE_ADMIN not in role_names:
|
||||
raise ForbiddenError(permission_node=MAPPING_WRITE_NODE)
|
||||
|
||||
|
||||
def require_mapping_trial(role_names: list[str]) -> None:
|
||||
"""Allow mapping and rule trials only for watchman-admin."""
|
||||
if ROLE_ADMIN not in role_names:
|
||||
raise ForbiddenError(permission_node=MAPPING_TRIAL_NODE)
|
||||
|
||||
|
||||
def require_object_access(role_names: list[str], object_id: str) -> None:
|
||||
"""Reject every object id until a later module grants row access.
|
||||
|
||||
|
||||
@@ -18,6 +18,9 @@ from watchman.auth.access import (
|
||||
require_datasource_read,
|
||||
require_datasource_test,
|
||||
require_datasource_write,
|
||||
require_mapping_read,
|
||||
require_mapping_trial,
|
||||
require_mapping_write,
|
||||
require_platform_write,
|
||||
require_query_preview,
|
||||
require_query_publish,
|
||||
@@ -233,3 +236,27 @@ def require_query_previewer(
|
||||
) -> None:
|
||||
"""Reject a draft or version preview unless the session is admin."""
|
||||
require_query_preview(_load_session_roles(request, session_token, sessions, directory))
|
||||
|
||||
|
||||
def require_mapping_reader(
|
||||
request: Request, session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store), directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> None:
|
||||
"""Reject mapping reads unless the session is watchman-admin."""
|
||||
require_mapping_read(_load_session_roles(request, session_token, sessions, directory))
|
||||
|
||||
|
||||
def require_mapping_writer(
|
||||
request: Request, session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store), directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> None:
|
||||
"""Reject mapping writes unless the session is watchman-admin."""
|
||||
require_mapping_write(_load_session_roles(request, session_token, sessions, directory))
|
||||
|
||||
|
||||
def require_mapping_trialer(
|
||||
request: Request, session_token: str | None = Cookie(default=None, alias=SESSION_COOKIE_NAME),
|
||||
sessions: SessionStore = Depends(get_session_store), directory: RoleDirectory = Depends(get_role_directory),
|
||||
) -> None:
|
||||
"""Reject mapping trials unless the session is watchman-admin."""
|
||||
require_mapping_trial(_load_session_roles(request, session_token, sessions, directory))
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from watchman.models.auth_session import AuthSession
|
||||
from watchman.models.datasource import DataSource
|
||||
from watchman.models.mapping import MappingColumnConfig, MappingDefinition, MappingVersion
|
||||
from watchman.models.platform import AuditEvent, RunRecord
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
|
||||
@@ -9,6 +10,9 @@ __all__ = [
|
||||
"AuthSession",
|
||||
"AuditEvent",
|
||||
"DataSource",
|
||||
"MappingColumnConfig",
|
||||
"MappingDefinition",
|
||||
"MappingVersion",
|
||||
"QueryDefinition",
|
||||
"QueryVersion",
|
||||
"RunRecord",
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
"""Tenant-scoped query mappings and immutable column snapshots.
|
||||
|
||||
Boundary: stores mapping definitions and their versioned column selections; validation and
|
||||
version creation live in `watchman.services.mappings`. Depends on query definitions only.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
from sqlalchemy import (
|
||||
Boolean,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
Integer,
|
||||
Numeric,
|
||||
String,
|
||||
UniqueConstraint,
|
||||
func,
|
||||
text,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import JSONB, UUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from watchman.models.base import Base
|
||||
|
||||
MAPPING_VALUE_TYPES = ("number", "string", "boolean", "datetime")
|
||||
|
||||
|
||||
class MappingDefinition(Base):
|
||||
"""One configurable mapping attached to a query definition and its active version."""
|
||||
|
||||
__tablename__ = "mapping_definitions"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"latest_version_no IS NULL OR latest_version_no >= 1",
|
||||
name="ck_mapping_definitions_latest_version",
|
||||
),
|
||||
CheckConstraint(
|
||||
"current_version_no IS NULL OR current_version_no >= 1",
|
||||
name="ck_mapping_definitions_current_version",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
query_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("query_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
latest_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
current_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class MappingVersion(Base):
|
||||
"""An append-only snapshot of a mapping definition; content lives in its column rows."""
|
||||
|
||||
__tablename__ = "mapping_versions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("definition_id", "version_no", name="uq_mapping_versions_definition_version"),
|
||||
CheckConstraint("version_no >= 1", name="ck_mapping_versions_version_no"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
condition_tree: Mapped[dict[str, object] | None] = mapped_column(JSONB, nullable=True)
|
||||
saved_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
saved_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
|
||||
|
||||
class MappingColumnConfig(Base):
|
||||
"""A selected query-output column and its declared mapping configuration."""
|
||||
|
||||
__tablename__ = "mapping_column_configs"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"mapping_version_id",
|
||||
"source_column_name",
|
||||
name="uq_mapping_column_configs_version_source",
|
||||
),
|
||||
CheckConstraint(
|
||||
"value_type IN ('number', 'string', 'boolean', 'datetime')",
|
||||
name="ck_mapping_column_configs_value_type",
|
||||
),
|
||||
CheckConstraint(
|
||||
"(value_type = 'number') OR (numeric_multiply IS NULL AND numeric_offset IS NULL)",
|
||||
name="ck_mapping_column_configs_numeric_only",
|
||||
),
|
||||
Index(
|
||||
"uq_mapping_column_configs_one_observation_time",
|
||||
"mapping_version_id",
|
||||
unique=True,
|
||||
postgresql_where=text("is_observation_time"),
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
source_column_name: Mapped[str] = mapped_column(String(128), nullable=False)
|
||||
value_type: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
is_identity: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, server_default=text("false")
|
||||
)
|
||||
is_observation_time: Mapped[bool] = mapped_column(
|
||||
Boolean, nullable=False, server_default=text("false")
|
||||
)
|
||||
numeric_multiply: Mapped[Decimal | None] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
numeric_offset: Mapped[Decimal | None] = mapped_column(Numeric(24, 8), nullable=True)
|
||||
|
||||
|
||||
class MappedInput(Base):
|
||||
"""A stable mapped-input identity whose latest revision pointer may advance."""
|
||||
|
||||
__tablename__ = "mapped_inputs"
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
"tenant_id",
|
||||
"mapping_definition_id",
|
||||
"identity_key",
|
||||
name="uq_mapped_inputs_tenant_mapping_identity",
|
||||
),
|
||||
CheckConstraint(
|
||||
"latest_revision_no IS NULL OR latest_revision_no >= 1",
|
||||
name="ck_mapped_inputs_latest_revision",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
identity_key: Mapped[str] = mapped_column(String(4096), nullable=False)
|
||||
latest_revision_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class MappedInputRevision(Base):
|
||||
"""An append-only non-identity value snapshot for one mapped input."""
|
||||
|
||||
__tablename__ = "mapped_input_revisions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("input_id", "revision_no", name="uq_mapped_input_revisions_input_revision"),
|
||||
CheckConstraint("revision_no >= 1", name="ck_mapped_input_revisions_revision_no"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
input_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapped_inputs.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
mapping_version_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_versions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
revision_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
mapped_values: Mapped[dict[str, object]] = mapped_column(JSONB, nullable=False)
|
||||
recorded_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class RuleDefinition(Base):
|
||||
"""A rule attached to one mapping definition with a mutable current-version pointer."""
|
||||
|
||||
__tablename__ = "rule_definitions"
|
||||
__table_args__ = (
|
||||
CheckConstraint(
|
||||
"latest_version_no IS NULL OR latest_version_no >= 1",
|
||||
name="ck_rule_definitions_latest_version",
|
||||
),
|
||||
CheckConstraint(
|
||||
"current_version_no IS NULL OR current_version_no >= 1",
|
||||
name="ck_rule_definitions_current_version",
|
||||
),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
mapping_definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("mapping_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
latest_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
current_version_no: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
|
||||
|
||||
class RuleVersion(Base):
|
||||
"""An append-only validated condition tree for one rule definition."""
|
||||
|
||||
__tablename__ = "rule_versions"
|
||||
__table_args__ = (
|
||||
UniqueConstraint("definition_id", "version_no", name="uq_rule_versions_definition_version"),
|
||||
CheckConstraint("version_no >= 1", name="ck_rule_versions_version_no"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True), primary_key=True, server_default=text("gen_random_uuid()")
|
||||
)
|
||||
tenant_id: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
definition_id: Mapped[uuid.UUID] = mapped_column(
|
||||
UUID(as_uuid=True),
|
||||
ForeignKey("rule_definitions.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
)
|
||||
version_no: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
condition_tree: Mapped[dict[str, object]] = mapped_column(JSONB, nullable=False)
|
||||
saved_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, server_default=func.now()
|
||||
)
|
||||
saved_by: Mapped[str | None] = mapped_column(String(128), nullable=True)
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Pure mapped-row judgment with explicit normal, abnormal, unknown, empty, and error outcomes.
|
||||
|
||||
Boundary: transforms supplied rows only; it opens no sessions and never persists inputs or alarms.
|
||||
Depends only on Python value coercion and declarative mapping/rule structures.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from decimal import Decimal
|
||||
from typing import Any, Mapping, Sequence
|
||||
|
||||
|
||||
def _aware_datetime(raw: Any) -> datetime | None:
|
||||
parsed = raw
|
||||
if isinstance(raw, str):
|
||||
try:
|
||||
parsed = datetime.fromisoformat(raw)
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(parsed, datetime) or parsed.tzinfo is None or parsed.utcoffset() is None:
|
||||
return None
|
||||
return parsed.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _finite_number(value: Any) -> Decimal:
|
||||
if isinstance(value, bool) or isinstance(value, str) and not value.strip():
|
||||
raise ValueError("comparison value is not a finite number")
|
||||
try:
|
||||
number = value if isinstance(value, Decimal) else Decimal(str(value))
|
||||
except Exception as exc:
|
||||
raise ValueError("comparison value is not a finite number") from exc
|
||||
if not number.is_finite():
|
||||
raise ValueError("comparison value is not a finite number")
|
||||
return number
|
||||
|
||||
|
||||
def _get(config: Any, name: str) -> Any:
|
||||
return config.get(name) if isinstance(config, Mapping) else getattr(config, name)
|
||||
|
||||
|
||||
def _value(raw: Any, config: Any) -> tuple[Any, str | None]:
|
||||
if raw is None:
|
||||
return None, "missing"
|
||||
kind = _get(config, "value_type")
|
||||
if kind == "number":
|
||||
if isinstance(raw, bool) or not isinstance(raw, (int, float, Decimal)):
|
||||
return None, "invalid"
|
||||
if isinstance(raw, Decimal):
|
||||
if not raw.is_finite():
|
||||
return None, "invalid"
|
||||
elif not math.isfinite(raw):
|
||||
return None, "invalid"
|
||||
multiply = _get(config, "numeric_multiply")
|
||||
offset = _get(config, "numeric_offset")
|
||||
if multiply is not None or offset is not None:
|
||||
value = raw if isinstance(raw, Decimal) else Decimal(str(raw))
|
||||
return value * (multiply if multiply is not None else Decimal(1)) + (
|
||||
offset if offset is not None else Decimal(0)
|
||||
), None
|
||||
return raw, None
|
||||
if kind == "datetime":
|
||||
parsed = _aware_datetime(raw)
|
||||
if parsed is None:
|
||||
return None, "invalid"
|
||||
return parsed, None
|
||||
if (kind == "string" and not isinstance(raw, str)) or (kind == "boolean" and not isinstance(raw, bool)):
|
||||
return None, "invalid"
|
||||
return raw, None
|
||||
|
||||
|
||||
def _leaf(node: Mapping[str, Any], row: Mapping[str, Any], configs: dict[str, Any], status: dict[str, str]) -> str:
|
||||
column = node["column"]
|
||||
value, problem = _value(row.get(column), configs[column])
|
||||
if problem:
|
||||
status[column] = problem
|
||||
return "unknown"
|
||||
expected = node["value"]
|
||||
kind = _get(configs[column], "value_type")
|
||||
if kind == "number":
|
||||
expected = _finite_number(expected)
|
||||
value = value if isinstance(value, Decimal) else Decimal(str(value))
|
||||
if kind == "datetime":
|
||||
expected = _aware_datetime(expected)
|
||||
if expected is None:
|
||||
raise ValueError("configured datetime comparison value must include a timezone")
|
||||
operators = {"eq": lambda: value == expected, "ne": lambda: value != expected, "gt": lambda: value > expected, "gte": lambda: value >= expected, "lt": lambda: value < expected, "lte": lambda: value <= expected}
|
||||
return "abnormal" if operators[node["operator"]]() else "normal"
|
||||
|
||||
|
||||
def _tree(node: Mapping[str, Any], row: Mapping[str, Any], configs: dict[str, Any], status: dict[str, str]) -> str:
|
||||
if "items" not in node:
|
||||
return _leaf(node, row, configs, status)
|
||||
codes = [_tree(item, row, configs, status) for item in node["items"]]
|
||||
if node["op"] == "and":
|
||||
return "normal" if "normal" in codes else ("abnormal" if all(c == "abnormal" for c in codes) else "unknown")
|
||||
return "abnormal" if "abnormal" in codes else ("normal" if all(c == "normal" for c in codes) else "unknown")
|
||||
|
||||
|
||||
def evaluate_rows(
|
||||
rows: Sequence[Mapping[str, Any]],
|
||||
mapping_columns: Sequence[Any],
|
||||
condition_tree: Mapping[str, Any],
|
||||
current_query_columns: Sequence[str],
|
||||
) -> dict[str, Any]:
|
||||
"""Evaluate supplied rows without persistence; missing rule columns return error, never unknown."""
|
||||
try:
|
||||
configs = {_get(config, "source_column_name"): config for config in mapping_columns}
|
||||
required = set(configs) | {node["column"] for node in _leaves(condition_tree)}
|
||||
missing = sorted(required - set(current_query_columns))
|
||||
if missing:
|
||||
return {"outcome": "error", "missing_columns": missing}
|
||||
if not rows:
|
||||
return {"outcome": "empty", "skipped_rows": 0}
|
||||
candidates = rows if any(_get(c, "is_identity") for c in mapping_columns) else rows[:1]
|
||||
results = []
|
||||
for row in candidates:
|
||||
status: dict[str, str] = {}
|
||||
results.append({"code": _tree(condition_tree, row, configs, status), "field_status": status})
|
||||
except (KeyError, TypeError, ValueError):
|
||||
return {"outcome": "error"}
|
||||
return {**results[0], "outcome": "result", "rows": results, "skipped_rows": len(rows) - len(candidates)}
|
||||
|
||||
|
||||
def _leaves(node: Mapping[str, Any]):
|
||||
if "items" not in node:
|
||||
yield node
|
||||
else:
|
||||
for item in node["items"]:
|
||||
yield from _leaves(item)
|
||||
@@ -0,0 +1,472 @@
|
||||
"""Mapping-definition creation and immutable version saving.
|
||||
|
||||
Boundary: validates selected output columns against a query's current version and only inserts
|
||||
mapping snapshots. No rule evaluation, input identity persistence, HTTP, or audit writes.
|
||||
Depends on query and mapping persistence models plus the server tenant setting.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from collections.abc import Mapping, Sequence
|
||||
from datetime import date, datetime, timezone
|
||||
from decimal import Decimal, InvalidOperation
|
||||
import json
|
||||
import math
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from watchman.models.mapping import (
|
||||
MAPPING_VALUE_TYPES,
|
||||
MappingColumnConfig,
|
||||
MappingDefinition,
|
||||
MappingVersion,
|
||||
MappedInput,
|
||||
MappedInputRevision,
|
||||
)
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
from watchman.queries.schema import parse_output_schema
|
||||
|
||||
_COLUMN_FIELDS = frozenset(
|
||||
{
|
||||
"source_column_name",
|
||||
"value_type",
|
||||
"is_identity",
|
||||
"is_observation_time",
|
||||
"numeric_multiply",
|
||||
"numeric_offset",
|
||||
}
|
||||
)
|
||||
_MAX_SAVED_BY_LENGTH = 128
|
||||
_MAPPING_SINGLETON_IDENTITY = "mapping-singleton:v1"
|
||||
|
||||
|
||||
def _tenant_id() -> str:
|
||||
# GUARD: mapping tenant scope comes from server configuration, never caller input.
|
||||
return get_settings().tenant_id
|
||||
|
||||
|
||||
def _now() -> datetime:
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def _parse_id(raw: str, *, subject: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(raw)
|
||||
except ValueError:
|
||||
raise NotFoundError(f"{subject} not found") from None
|
||||
|
||||
|
||||
def _get_query(session: Session, query_definition_id: str) -> QueryDefinition:
|
||||
row = session.scalar(
|
||||
select(QueryDefinition).where(
|
||||
QueryDefinition.id == _parse_id(query_definition_id, subject="Query"),
|
||||
QueryDefinition.tenant_id == _tenant_id(),
|
||||
)
|
||||
)
|
||||
if row is None:
|
||||
raise NotFoundError("Query not found")
|
||||
return row
|
||||
|
||||
|
||||
def _get_mapping(session: Session, mapping_definition_id: str, *, lock: bool) -> MappingDefinition:
|
||||
statement = select(MappingDefinition).where(
|
||||
MappingDefinition.id == _parse_id(mapping_definition_id, subject="Mapping"),
|
||||
MappingDefinition.tenant_id == _tenant_id(),
|
||||
)
|
||||
if lock:
|
||||
statement = statement.execution_options(populate_existing=True).with_for_update()
|
||||
row = session.scalar(statement)
|
||||
if row is None:
|
||||
raise NotFoundError("Mapping not found")
|
||||
return row
|
||||
|
||||
|
||||
def current_query_column_names(session: Session, mapping: MappingDefinition) -> list[str]:
|
||||
"""Names declared by the mapping's query current version."""
|
||||
query = session.scalar(
|
||||
select(QueryDefinition).where(
|
||||
QueryDefinition.id == mapping.query_definition_id,
|
||||
QueryDefinition.tenant_id == _tenant_id(),
|
||||
)
|
||||
)
|
||||
if query is None:
|
||||
raise ConflictError("Mapping query is unavailable", details={"reason": "mapping_query_missing"})
|
||||
return list(_current_output_schema(session, query))
|
||||
|
||||
|
||||
def _current_output_schema(session: Session, query: QueryDefinition) -> dict[str, str]:
|
||||
if query.current_version_no is None:
|
||||
raise ConflictError(
|
||||
"Query has no current version",
|
||||
details={"reason": "query_has_no_current_version"},
|
||||
)
|
||||
version = session.scalar(
|
||||
select(QueryVersion).where(
|
||||
QueryVersion.tenant_id == _tenant_id(),
|
||||
QueryVersion.definition_id == query.id,
|
||||
QueryVersion.version_no == query.current_version_no,
|
||||
)
|
||||
)
|
||||
if version is None:
|
||||
raise ConflictError(
|
||||
"Query current version is unavailable",
|
||||
details={"reason": "query_current_version_missing"},
|
||||
)
|
||||
return parse_output_schema(version.output_schema)
|
||||
|
||||
|
||||
def _as_decimal(value: Any, *, field: str) -> Decimal | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float, Decimal, str)):
|
||||
raise ValidationError("Invalid mapping column", details={"fields": [field]})
|
||||
try:
|
||||
converted = Decimal(str(value))
|
||||
except (InvalidOperation, ValueError):
|
||||
raise ValidationError("Invalid mapping column", details={"fields": [field]}) from None
|
||||
if not converted.is_finite():
|
||||
raise ValidationError("Invalid mapping column", details={"fields": [field]})
|
||||
return converted
|
||||
|
||||
|
||||
def _normalize_columns(
|
||||
raw_columns: Sequence[Mapping[str, Any]], output_schema: Mapping[str, str]
|
||||
) -> list[dict[str, Any]]:
|
||||
if not raw_columns:
|
||||
raise ValidationError(
|
||||
"A mapping needs at least one column",
|
||||
details={"reason": "mapping_columns_empty", "fields": ["columns"]},
|
||||
)
|
||||
|
||||
normalized: list[dict[str, Any]] = []
|
||||
source_names: set[str] = set()
|
||||
missing: list[str] = []
|
||||
observation_count = 0
|
||||
for raw in raw_columns:
|
||||
if not isinstance(raw, Mapping) or set(raw) - _COLUMN_FIELDS:
|
||||
raise ValidationError(
|
||||
"Invalid mapping column",
|
||||
details={"reason": "mapping_column_invalid", "fields": ["columns"]},
|
||||
)
|
||||
source = raw.get("source_column_name")
|
||||
value_type = raw.get("value_type")
|
||||
is_identity = raw.get("is_identity", False)
|
||||
is_observation_time = raw.get("is_observation_time", False)
|
||||
if (
|
||||
not isinstance(source, str)
|
||||
or not source
|
||||
or len(source) > 128
|
||||
or source in source_names
|
||||
or value_type not in MAPPING_VALUE_TYPES
|
||||
or not isinstance(is_identity, bool)
|
||||
or not isinstance(is_observation_time, bool)
|
||||
):
|
||||
raise ValidationError(
|
||||
"Invalid mapping column",
|
||||
details={"reason": "mapping_column_invalid", "fields": ["columns"]},
|
||||
)
|
||||
source_names.add(source)
|
||||
if source not in output_schema:
|
||||
missing.append(source)
|
||||
observation_count += int(is_observation_time)
|
||||
multiply = _as_decimal(raw.get("numeric_multiply"), field="numeric_multiply")
|
||||
offset = _as_decimal(raw.get("numeric_offset"), field="numeric_offset")
|
||||
if value_type != "number" and (multiply is not None or offset is not None):
|
||||
raise ValidationError(
|
||||
"Numeric conversion applies only to number columns",
|
||||
details={
|
||||
"reason": "mapping_numeric_conversion_non_numeric",
|
||||
"fields": ["numeric_multiply", "numeric_offset"],
|
||||
},
|
||||
)
|
||||
normalized.append(
|
||||
{
|
||||
"source_column_name": source,
|
||||
"value_type": value_type,
|
||||
"is_identity": is_identity,
|
||||
"is_observation_time": is_observation_time,
|
||||
"numeric_multiply": multiply,
|
||||
"numeric_offset": offset,
|
||||
}
|
||||
)
|
||||
|
||||
if missing:
|
||||
raise ValidationError(
|
||||
"Selected columns are absent from the current query version",
|
||||
details={"reason": "mapping_columns_missing", "fields": sorted(missing)},
|
||||
)
|
||||
if observation_count > 1:
|
||||
raise ValidationError(
|
||||
"Only one observation-time column is allowed",
|
||||
details={"reason": "mapping_observation_time_multiple", "fields": ["columns"]},
|
||||
)
|
||||
return normalized
|
||||
|
||||
|
||||
def create_mapping(session: Session, *, query_definition_id: str) -> MappingDefinition:
|
||||
"""Create an empty mapping definition for a current-tenant query; version saving is separate."""
|
||||
query = _get_query(session, query_definition_id)
|
||||
row = MappingDefinition(
|
||||
tenant_id=_tenant_id(),
|
||||
query_definition_id=query.id,
|
||||
created_at=_now(),
|
||||
updated_at=_now(),
|
||||
)
|
||||
session.add(row)
|
||||
session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def save_mapping_version(
|
||||
session: Session,
|
||||
mapping_definition_id: str,
|
||||
columns: Sequence[Mapping[str, Any]],
|
||||
*,
|
||||
condition_tree: dict[str, Any] | None = None,
|
||||
saved_by: str | None = None,
|
||||
) -> MappingVersion:
|
||||
"""Append a validated mapping version, its column snapshot, and move the current pointer."""
|
||||
definition = _get_mapping(session, mapping_definition_id, lock=True)
|
||||
query = session.scalar(
|
||||
select(QueryDefinition).where(
|
||||
QueryDefinition.id == definition.query_definition_id,
|
||||
QueryDefinition.tenant_id == _tenant_id(),
|
||||
)
|
||||
)
|
||||
if query is None:
|
||||
raise ConflictError("Mapping query is unavailable", details={"reason": "mapping_query_missing"})
|
||||
normalized = _normalize_columns(columns, _current_output_schema(session, query))
|
||||
if condition_tree is not None:
|
||||
from watchman.services.rules import _validate_tree
|
||||
_validate_tree(condition_tree, {column["source_column_name"]: column["value_type"] for column in normalized})
|
||||
version_no = (definition.latest_version_no or 0) + 1
|
||||
version = MappingVersion(
|
||||
tenant_id=definition.tenant_id,
|
||||
definition_id=definition.id,
|
||||
version_no=version_no,
|
||||
condition_tree=condition_tree,
|
||||
saved_at=_now(),
|
||||
saved_by=saved_by[:_MAX_SAVED_BY_LENGTH] if saved_by else None,
|
||||
)
|
||||
session.add(version)
|
||||
try:
|
||||
with session.begin_nested():
|
||||
session.flush()
|
||||
except IntegrityError:
|
||||
raise ConflictError("Mapping version already exists", details={"reason": "version_conflict"}) from None
|
||||
|
||||
session.add_all(
|
||||
MappingColumnConfig(
|
||||
tenant_id=definition.tenant_id,
|
||||
mapping_version_id=version.id,
|
||||
**column,
|
||||
)
|
||||
for column in normalized
|
||||
)
|
||||
definition.latest_version_no = version_no
|
||||
definition.current_version_no = version_no
|
||||
definition.updated_at = _now()
|
||||
session.flush()
|
||||
return version
|
||||
|
||||
|
||||
def _current_mapping_snapshot(
|
||||
session: Session, definition: MappingDefinition
|
||||
) -> tuple[MappingVersion, list[MappingColumnConfig]]:
|
||||
if definition.current_version_no is None:
|
||||
raise ConflictError(
|
||||
"Mapping has no current version",
|
||||
details={"reason": "mapping_has_no_current_version"},
|
||||
)
|
||||
version = session.scalar(
|
||||
select(MappingVersion).where(
|
||||
MappingVersion.tenant_id == _tenant_id(),
|
||||
MappingVersion.definition_id == definition.id,
|
||||
MappingVersion.version_no == definition.current_version_no,
|
||||
)
|
||||
)
|
||||
if version is None:
|
||||
raise ConflictError(
|
||||
"Mapping current version is unavailable",
|
||||
details={"reason": "mapping_current_version_missing"},
|
||||
)
|
||||
columns = list(
|
||||
session.scalars(
|
||||
select(MappingColumnConfig)
|
||||
.where(
|
||||
MappingColumnConfig.tenant_id == _tenant_id(),
|
||||
MappingColumnConfig.mapping_version_id == version.id,
|
||||
)
|
||||
.order_by(MappingColumnConfig.source_column_name)
|
||||
)
|
||||
)
|
||||
return version, columns
|
||||
|
||||
|
||||
def _json_value(value: Any) -> Any:
|
||||
"""Return a JSON-safe representation that keeps stable values comparable across rereads."""
|
||||
if value is None or isinstance(value, (str, bool, int)):
|
||||
return value
|
||||
if isinstance(value, float):
|
||||
if not math.isfinite(value):
|
||||
raise ValidationError(
|
||||
"Mapped row contains a non-finite value",
|
||||
details={"reason": "mapped_value_invalid"},
|
||||
)
|
||||
return value
|
||||
if isinstance(value, Decimal):
|
||||
if not value.is_finite():
|
||||
raise ValidationError(
|
||||
"Mapped row contains a non-finite value",
|
||||
details={"reason": "mapped_value_invalid"},
|
||||
)
|
||||
return {"$decimal": format(value, "f")}
|
||||
if isinstance(value, datetime):
|
||||
if value.tzinfo is None or value.utcoffset() is None:
|
||||
raise ValidationError(
|
||||
"Mapped datetime must include a timezone",
|
||||
details={"reason": "mapped_datetime_timezone_missing"},
|
||||
)
|
||||
return {"$datetime": value.astimezone(timezone.utc).isoformat()}
|
||||
if isinstance(value, date):
|
||||
return {"$date": value.isoformat()}
|
||||
raise ValidationError(
|
||||
"Mapped row contains an unsupported value",
|
||||
details={"reason": "mapped_value_invalid"},
|
||||
)
|
||||
|
||||
|
||||
def _identity_key(identity_columns: Sequence[MappingColumnConfig], row: Mapping[str, Any]) -> str | None:
|
||||
if not identity_columns:
|
||||
return _MAPPING_SINGLETON_IDENTITY
|
||||
values: dict[str, Any] = {}
|
||||
for column in identity_columns:
|
||||
if column.source_column_name not in row or row[column.source_column_name] is None:
|
||||
return None
|
||||
values[column.source_column_name] = _json_value(row[column.source_column_name])
|
||||
return "identity:v1:" + json.dumps(values, sort_keys=True, separators=(",", ":"))
|
||||
|
||||
|
||||
def _non_identity_values(
|
||||
columns: Sequence[MappingColumnConfig], row: Mapping[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
# Missing selected columns remain absent; this is distinct from a selected column set to null.
|
||||
return {
|
||||
column.source_column_name: _json_value(row[column.source_column_name])
|
||||
for column in columns
|
||||
if not column.is_identity and column.source_column_name in row
|
||||
}
|
||||
|
||||
|
||||
def _get_input(
|
||||
session: Session, definition: MappingDefinition, identity_key: str
|
||||
) -> MappedInput | None:
|
||||
return session.scalar(
|
||||
select(MappedInput)
|
||||
.where(
|
||||
MappedInput.tenant_id == _tenant_id(),
|
||||
MappedInput.mapping_definition_id == definition.id,
|
||||
MappedInput.identity_key == identity_key,
|
||||
)
|
||||
.execution_options(populate_existing=True)
|
||||
.with_for_update()
|
||||
)
|
||||
|
||||
|
||||
def _latest_revision(session: Session, row: MappedInput) -> MappedInputRevision | None:
|
||||
if row.latest_revision_no is None:
|
||||
return None
|
||||
return session.scalar(
|
||||
select(MappedInputRevision).where(
|
||||
MappedInputRevision.tenant_id == _tenant_id(),
|
||||
MappedInputRevision.input_id == row.id,
|
||||
MappedInputRevision.revision_no == row.latest_revision_no,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def persist_mapped_rows(
|
||||
session: Session,
|
||||
mapping_definition_id: str,
|
||||
rows: Sequence[Mapping[str, Any]],
|
||||
*,
|
||||
run_id: str | None = None,
|
||||
) -> dict[str, int]:
|
||||
"""Persist first-seen identities and changed values; run_id is intentionally not persisted.
|
||||
|
||||
Inputs are grouped only by the mapping definition and canonical identity key. Missing
|
||||
identity values and later duplicate identities in the same result set are skipped.
|
||||
"""
|
||||
# GUARD: run_id is provenance outside the identity contract and never enters persistence keys.
|
||||
del run_id
|
||||
definition = _get_mapping(session, mapping_definition_id, lock=True)
|
||||
version, columns = _current_mapping_snapshot(session, definition)
|
||||
identity_columns = [column for column in columns if column.is_identity]
|
||||
candidates = rows[:1] if not identity_columns else rows
|
||||
result = {
|
||||
"inputs_created": 0,
|
||||
"revisions_appended": 0,
|
||||
"skipped_rows": max(0, len(rows) - len(candidates)),
|
||||
"skipped_duplicate_rows": 0,
|
||||
"skipped_missing_identity_rows": 0,
|
||||
}
|
||||
seen_identities: set[str] = set()
|
||||
|
||||
for row in candidates:
|
||||
if not isinstance(row, Mapping):
|
||||
raise ValidationError(
|
||||
"Mapped row must be an object",
|
||||
details={"reason": "mapped_row_invalid"},
|
||||
)
|
||||
identity_key = _identity_key(identity_columns, row)
|
||||
if identity_key is None:
|
||||
result["skipped_rows"] += 1
|
||||
result["skipped_missing_identity_rows"] += 1
|
||||
continue
|
||||
if identity_key in seen_identities:
|
||||
result["skipped_rows"] += 1
|
||||
result["skipped_duplicate_rows"] += 1
|
||||
continue
|
||||
seen_identities.add(identity_key)
|
||||
values = _non_identity_values(columns, row)
|
||||
input_row = _get_input(session, definition, identity_key)
|
||||
if input_row is None:
|
||||
input_row = MappedInput(
|
||||
tenant_id=definition.tenant_id,
|
||||
mapping_definition_id=definition.id,
|
||||
identity_key=identity_key,
|
||||
latest_revision_no=1,
|
||||
created_at=_now(),
|
||||
updated_at=_now(),
|
||||
)
|
||||
session.add(input_row)
|
||||
session.flush()
|
||||
revision_no = 1
|
||||
result["inputs_created"] += 1
|
||||
else:
|
||||
latest = _latest_revision(session, input_row)
|
||||
if latest is not None and latest.mapped_values == values:
|
||||
continue
|
||||
revision_no = (input_row.latest_revision_no or 0) + 1
|
||||
input_row.latest_revision_no = revision_no
|
||||
input_row.updated_at = _now()
|
||||
|
||||
session.add(
|
||||
MappedInputRevision(
|
||||
tenant_id=definition.tenant_id,
|
||||
input_id=input_row.id,
|
||||
mapping_version_id=version.id,
|
||||
revision_no=revision_no,
|
||||
mapped_values=values,
|
||||
recorded_at=_now(),
|
||||
)
|
||||
)
|
||||
result["revisions_appended"] += 1
|
||||
session.flush()
|
||||
return result
|
||||
@@ -0,0 +1,183 @@
|
||||
"""Structured rule validation and immutable version saving.
|
||||
|
||||
Boundary: validates declarative condition trees against a mapping snapshot; it never evaluates
|
||||
conditions or executes user text. Depends on mapping models and tenant-scoped persistence.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from watchman.models.mapping import (
|
||||
MappingColumnConfig,
|
||||
MappingDefinition,
|
||||
MappingVersion,
|
||||
RuleDefinition,
|
||||
RuleVersion,
|
||||
)
|
||||
|
||||
_GROUP_KEYS = frozenset({"op", "items"})
|
||||
_LEAF_KEYS = frozenset({"column", "operator", "value"})
|
||||
_OPERATORS = frozenset({"eq", "ne", "gt", "gte", "lt", "lte"})
|
||||
_ORDER_OPERATORS = frozenset({"gt", "gte", "lt", "lte"})
|
||||
_MAX_DEPTH = 4
|
||||
|
||||
|
||||
def _tenant_id() -> str:
|
||||
# GUARD: rule persistence always scopes through the server tenant, never a caller field.
|
||||
return get_settings().tenant_id
|
||||
|
||||
|
||||
def _parse_id(raw: str, subject: str) -> uuid.UUID:
|
||||
try:
|
||||
return uuid.UUID(raw)
|
||||
except ValueError:
|
||||
raise NotFoundError(f"{subject} not found") from None
|
||||
|
||||
|
||||
def _mapping(session: Session, mapping_id: str, *, lock: bool) -> MappingDefinition:
|
||||
statement = select(MappingDefinition).where(
|
||||
MappingDefinition.id == _parse_id(mapping_id, "Mapping"),
|
||||
MappingDefinition.tenant_id == _tenant_id(),
|
||||
)
|
||||
if lock:
|
||||
statement = statement.with_for_update()
|
||||
row = session.scalar(statement)
|
||||
if row is None:
|
||||
raise NotFoundError("Mapping not found")
|
||||
return row
|
||||
|
||||
|
||||
def _columns(session: Session, mapping: MappingDefinition) -> dict[str, str]:
|
||||
if mapping.current_version_no is None:
|
||||
raise ConflictError("Mapping has no current version", details={"reason": "mapping_has_no_current_version"})
|
||||
version = session.scalar(
|
||||
select(MappingVersion).where(
|
||||
MappingVersion.tenant_id == _tenant_id(),
|
||||
MappingVersion.definition_id == mapping.id,
|
||||
MappingVersion.version_no == mapping.current_version_no,
|
||||
)
|
||||
)
|
||||
if version is None:
|
||||
raise ConflictError(
|
||||
"Mapping current version is unavailable",
|
||||
details={"reason": "mapping_current_version_missing"},
|
||||
)
|
||||
return dict(
|
||||
session.execute(
|
||||
select(MappingColumnConfig.source_column_name, MappingColumnConfig.value_type).where(
|
||||
MappingColumnConfig.tenant_id == _tenant_id(),
|
||||
MappingColumnConfig.mapping_version_id == version.id,
|
||||
)
|
||||
).all()
|
||||
)
|
||||
|
||||
|
||||
def _invalid(reason: str) -> ValidationError:
|
||||
return ValidationError("Invalid rule condition tree", details={"reason": reason})
|
||||
|
||||
|
||||
def _validate_leaf(node: dict[str, Any], columns: dict[str, str]) -> None:
|
||||
if set(node) != _LEAF_KEYS:
|
||||
raise _invalid("rule_leaf_invalid")
|
||||
column, operator, value = node["column"], node["operator"], node["value"]
|
||||
if not isinstance(column, str) or column not in columns:
|
||||
raise _invalid("rule_column_unknown")
|
||||
if operator not in _OPERATORS:
|
||||
raise _invalid("rule_operator_unknown")
|
||||
value_type = columns[column]
|
||||
if operator in _ORDER_OPERATORS and value_type in ("string", "boolean"):
|
||||
raise _invalid("rule_operator_incompatible")
|
||||
if value_type == "number":
|
||||
if isinstance(value, str):
|
||||
try:
|
||||
value = float(value) if any(mark in value for mark in ".eE") else int(value)
|
||||
except ValueError:
|
||||
raise _invalid("rule_value_incompatible") from None
|
||||
node["value"] = value
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value):
|
||||
raise _invalid("rule_value_incompatible")
|
||||
elif value_type == "string":
|
||||
if not isinstance(value, str):
|
||||
raise _invalid("rule_value_incompatible")
|
||||
elif value_type == "boolean":
|
||||
if not isinstance(value, bool):
|
||||
raise _invalid("rule_value_incompatible")
|
||||
elif value_type == "datetime":
|
||||
if not isinstance(value, str):
|
||||
raise _invalid("rule_value_incompatible")
|
||||
try:
|
||||
parsed = datetime.fromisoformat(value)
|
||||
except ValueError:
|
||||
raise _invalid("rule_datetime_invalid") from None
|
||||
if parsed.tzinfo is None or parsed.utcoffset() is None:
|
||||
raise _invalid("rule_datetime_timezone_missing")
|
||||
else:
|
||||
raise _invalid("rule_column_type_invalid")
|
||||
|
||||
|
||||
def _validate_tree(node: Any, columns: dict[str, str], depth: int = 1) -> None:
|
||||
if depth > _MAX_DEPTH or not isinstance(node, dict):
|
||||
raise _invalid("rule_depth_or_shape_invalid")
|
||||
if "items" in node or "op" in node:
|
||||
if set(node) != _GROUP_KEYS or node.get("op") not in ("and", "or"):
|
||||
raise _invalid("rule_group_invalid")
|
||||
items = node.get("items")
|
||||
if not isinstance(items, list) or not items:
|
||||
raise _invalid("rule_group_empty")
|
||||
for item in items:
|
||||
_validate_tree(item, columns, depth + 1)
|
||||
return
|
||||
_validate_leaf(node, columns)
|
||||
|
||||
|
||||
def create_rule(session: Session, *, mapping_definition_id: str) -> RuleDefinition:
|
||||
"""Create an empty tenant-scoped rule header; callers save its first version separately."""
|
||||
mapping = _mapping(session, mapping_definition_id, lock=False)
|
||||
row = RuleDefinition(tenant_id=mapping.tenant_id, mapping_definition_id=mapping.id)
|
||||
session.add(row)
|
||||
session.flush()
|
||||
return row
|
||||
|
||||
|
||||
def save_rule_version(
|
||||
session: Session,
|
||||
rule_definition_id: str,
|
||||
condition_tree: dict[str, Any],
|
||||
*,
|
||||
saved_by: str | None = None,
|
||||
) -> RuleVersion:
|
||||
"""Validate and append one immutable rule version, then advance only the header pointer."""
|
||||
rule = session.scalar(
|
||||
select(RuleDefinition)
|
||||
.where(
|
||||
RuleDefinition.id == _parse_id(rule_definition_id, "Rule"),
|
||||
RuleDefinition.tenant_id == _tenant_id(),
|
||||
)
|
||||
.with_for_update()
|
||||
)
|
||||
if rule is None:
|
||||
raise NotFoundError("Rule not found")
|
||||
mapping = _mapping(session, str(rule.mapping_definition_id), lock=False)
|
||||
_validate_tree(condition_tree, _columns(session, mapping))
|
||||
version_no = (rule.latest_version_no or 0) + 1
|
||||
version = RuleVersion(
|
||||
tenant_id=rule.tenant_id,
|
||||
definition_id=rule.id,
|
||||
version_no=version_no,
|
||||
condition_tree=condition_tree,
|
||||
saved_by=saved_by[:128] if saved_by else None,
|
||||
)
|
||||
session.add(version)
|
||||
rule.latest_version_no = version_no
|
||||
rule.current_version_no = version_no
|
||||
session.flush()
|
||||
return version
|
||||
@@ -293,7 +293,7 @@ def test_wrong_role_is_42000_with_node(cleanup, no_network, roles, method, path_
|
||||
def test_admin_can_read(cleanup) -> None:
|
||||
created = _create(_client(cleanup, ADMIN))
|
||||
client = _client(cleanup, ADMIN)
|
||||
listing = client.get("/datasources")
|
||||
listing = client.get("/datasources?sort_order=desc&page_size=100")
|
||||
assert listing.status_code == 200
|
||||
assert created["id"] in [item["id"] for item in listing.json()["data"]["items"]]
|
||||
assert client.get(f"/datasources/{created['id']}").status_code == 200
|
||||
|
||||
@@ -509,11 +509,11 @@ def test_usable_list_filters_disabled_and_open_sources(cleanup, monkeypatch, clo
|
||||
assert response.status_code == 200
|
||||
return {item["id"] for item in response.json()["data"]["items"]}
|
||||
|
||||
everything = ids("/datasources")
|
||||
everything = ids("/datasources?sort_order=desc&page_size=100")
|
||||
assert {good, disabled, tripped} <= everything
|
||||
usable = ids("/datasources?usable=true")
|
||||
assert good in usable and disabled not in usable and tripped not in usable
|
||||
assert ids("/datasources?usable=false") == everything
|
||||
assert ids("/datasources?usable=false&sort_order=desc&page_size=100") == everything
|
||||
|
||||
clock.advance(601) # cooldown over: usable again, and the circuit is persisted closed
|
||||
assert tripped in ids("/datasources?usable=true")
|
||||
@@ -551,7 +551,7 @@ def test_plain_list_closes_elapsed_cooldown(cleanup, monkeypatch, clock) -> None
|
||||
client.post(f"/datasources/{ds_id}/disable") # disabled rows are normalized too
|
||||
|
||||
clock.advance(601)
|
||||
items = client.get("/datasources").json()["data"]["items"]
|
||||
items = client.get("/datasources?sort_order=desc&page_size=100").json()["data"]["items"]
|
||||
item = next(entry for entry in items if entry["id"] == ds_id)
|
||||
assert item["circuit_state"] == "closed"
|
||||
assert item["circuit_opened_at"] is None and item["circuit_open_until"] is None
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
"""S4 truth-table tests for the pure mapping judgment evaluator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from watchman.services.judgment import evaluate_rows
|
||||
|
||||
CONFIGS = [
|
||||
{"source_column_name": "n", "value_type": "number", "is_identity": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "s", "value_type": "string", "is_identity": True, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "at", "value_type": "datetime", "is_identity": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
]
|
||||
CURRENT = ["n", "s", "at"]
|
||||
|
||||
|
||||
def test_truth_table_and_or_and_missing_invalid() -> None:
|
||||
and_tree = {"op": "and", "items": [{"column": "n", "operator": "gt", "value": 2}, {"column": "n", "operator": "lt", "value": 10}]}
|
||||
assert evaluate_rows([{"n": 1, "s": "a"}], CONFIGS, and_tree, CURRENT)["code"] == "normal"
|
||||
assert evaluate_rows([{"n": 5, "s": "a"}], CONFIGS, and_tree, CURRENT)["code"] == "abnormal"
|
||||
missing = evaluate_rows([{"n": None, "s": "a"}], CONFIGS, and_tree, CURRENT)
|
||||
assert missing["code"] == "unknown" and missing["field_status"]["n"] == "missing"
|
||||
invalid = evaluate_rows([{"n": "bad", "s": "a"}], CONFIGS, and_tree, CURRENT)
|
||||
assert invalid["code"] == "unknown" and invalid["field_status"]["n"] == "invalid"
|
||||
or_tree = {"op": "or", "items": [{"column": "n", "operator": "gt", "value": 2}, {"column": "n", "operator": "lt", "value": 0}]}
|
||||
assert evaluate_rows([{"n": 1, "s": "a"}], CONFIGS, or_tree, CURRENT)["code"] == "normal"
|
||||
|
||||
|
||||
def test_empty_first_row_missing_column_and_datetime_rules() -> None:
|
||||
tree = {"column": "n", "operator": "eq", "value": 2}
|
||||
assert evaluate_rows([], CONFIGS, tree, CURRENT)["outcome"] == "empty"
|
||||
no_identity = [{**CONFIGS[0]}, {**CONFIGS[2]}]
|
||||
result = evaluate_rows([{"n": 2}, {"n": 1}], no_identity, tree, ["n", "at"])
|
||||
assert result["code"] == "abnormal" and result["skipped_rows"] == 1
|
||||
assert evaluate_rows([{"n": 2}], CONFIGS, tree, ["s"]) == {"outcome": "error", "missing_columns": ["at", "n"]}
|
||||
time_tree = {"column": "at", "operator": "eq", "value": "2026-01-01T00:00:00+00:00"}
|
||||
assert evaluate_rows([{"at": "2026-01-01T00:00:00+00:00", "s": "a"}], CONFIGS, time_tree, CURRENT)["code"] == "abnormal"
|
||||
assert evaluate_rows([{"n": 5, "s": "a"}], CONFIGS, {"column": "n", "operator": "eq", "value": "5"}, CURRENT)["code"] == "abnormal"
|
||||
assert evaluate_rows([{"n": 1, "s": "a"}], CONFIGS, {}, CURRENT)["outcome"] == "error"
|
||||
assert evaluate_rows([{"at": datetime(2025, 12, 31, 19, tzinfo=timezone(timedelta(hours=-5))), "s": "a"}], CONFIGS, time_tree, CURRENT)["code"] == "abnormal"
|
||||
assert evaluate_rows([{"at": datetime(2026, 1, 1), "s": "a"}], CONFIGS, time_tree, CURRENT)["field_status"]["at"] == "invalid"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("op", "value", "code"),
|
||||
[("eq", 2, "abnormal"), ("ne", 2, "normal"), ("gte", 2, "abnormal"), ("lte", 2, "abnormal")],
|
||||
)
|
||||
def test_single_leaf_boundaries(op: str, value: int, code: str) -> None:
|
||||
assert evaluate_rows([{"n": 2, "s": "a"}], CONFIGS, {"column": "n", "operator": op, "value": value}, CURRENT)["code"] == code
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("op", "row", "code"),
|
||||
[
|
||||
("and", {"n": 5, "s": None}, "unknown"),
|
||||
("and", {"n": 1, "s": None}, "normal"),
|
||||
("or", {"n": 5, "s": None}, "abnormal"),
|
||||
("or", {"n": 5, "s": "a"}, "abnormal"),
|
||||
("or", {"n": 1, "s": None}, "unknown"),
|
||||
],
|
||||
)
|
||||
def test_truth_table_unknown_combinations(op: str, row: dict[str, object], code: str) -> None:
|
||||
tree = {"op": op, "items": [{"column": "n", "operator": "gt", "value": 2}, {"column": "s", "operator": "eq", "value": "x"}]}
|
||||
assert evaluate_rows([row], CONFIGS, tree, CURRENT)["code"] == code
|
||||
|
||||
|
||||
def test_numeric_conversion_is_optional_and_accepts_decimal() -> None:
|
||||
converted = [{**CONFIGS[0], "numeric_multiply": Decimal("2"), "numeric_offset": Decimal("1")}, *CONFIGS[1:]]
|
||||
tree = {"column": "n", "operator": "eq", "value": 5}
|
||||
assert evaluate_rows([{"n": Decimal("2"), "s": "a"}], converted, tree, CURRENT)["code"] == "abnormal"
|
||||
assert evaluate_rows([{"n": 2.0, "s": "a"}], converted, tree, CURRENT)["code"] == "abnormal"
|
||||
assert evaluate_rows([{"n": Decimal("2"), "s": "a"}], CONFIGS, {"column": "n", "operator": "eq", "value": 2}, CURRENT)["code"] == "abnormal"
|
||||
result = evaluate_rows([{"n": Decimal("sNaN"), "s": "a"}], CONFIGS, tree, CURRENT)
|
||||
assert result["code"] == "unknown" and result["field_status"]["n"] == "invalid"
|
||||
@@ -0,0 +1,348 @@
|
||||
"""S2 persistence tests for mapped-input identities and append-only revisions.
|
||||
|
||||
Boundary: covers identity deduplication, revision appends, and tenant isolation on PostgreSQL;
|
||||
does not test preview, rule evaluation, alarms, or HTTP routes. Depends on S1 mappings.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from _privileged_cleanup import _superuser_engine, purge_query_rows
|
||||
from watchman.core.config import get_settings, reload_settings
|
||||
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
|
||||
from watchman.models.datasource import DataSource
|
||||
from watchman.models.mapping import (
|
||||
MappedInput,
|
||||
MappedInputRevision,
|
||||
MappingDefinition,
|
||||
)
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
from watchman.services.mappings import create_mapping, persist_mapped_rows, save_mapping_version
|
||||
|
||||
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def input_factory():
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
_ensure_after_begin_listener()
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||
datasource_ids: list[uuid.UUID] = []
|
||||
yield factory, datasource_ids, settings
|
||||
try:
|
||||
for datasource_id in datasource_ids:
|
||||
_purge_mapped_input_rows(datasource_id)
|
||||
purge_query_rows(datasource_id=datasource_id)
|
||||
finally:
|
||||
engine.dispose()
|
||||
reset_engine()
|
||||
|
||||
|
||||
def _purge_mapped_input_rows(datasource_id: uuid.UUID) -> None:
|
||||
"""Remove synthetic S1/S2 rows with the test-only superuser cleanup boundary."""
|
||||
engine = _superuser_engine()
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
params = {"datasource_id": str(datasource_id)}
|
||||
definition_ids = (
|
||||
"SELECT id FROM mapping_definitions WHERE query_definition_id IN "
|
||||
"(SELECT id FROM query_definitions WHERE datasource_id = :datasource_id)"
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM mapped_input_revisions WHERE input_id IN "
|
||||
f"(SELECT id FROM mapped_inputs WHERE mapping_definition_id IN ({definition_ids}))"
|
||||
),
|
||||
params,
|
||||
)
|
||||
conn.execute(
|
||||
text(f"DELETE FROM mapped_inputs WHERE mapping_definition_id IN ({definition_ids})"),
|
||||
params,
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM mapping_column_configs WHERE mapping_version_id IN "
|
||||
"(SELECT id FROM mapping_versions WHERE definition_id IN "
|
||||
f"({definition_ids}))"
|
||||
),
|
||||
params,
|
||||
)
|
||||
conn.execute(
|
||||
text(f"DELETE FROM mapping_versions WHERE definition_id IN ({definition_ids})"),
|
||||
params,
|
||||
)
|
||||
conn.execute(text(f"DELETE FROM mapping_definitions WHERE id IN ({definition_ids})"), params)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _mapping(
|
||||
session: Session,
|
||||
tenant_id: str,
|
||||
registry: list[uuid.UUID],
|
||||
*,
|
||||
with_identity: bool,
|
||||
) -> MappingDefinition:
|
||||
"""Build an S1 mapping snapshot with an optional stable serial-number identity column."""
|
||||
datasource = DataSource(
|
||||
tenant_id=tenant_id,
|
||||
name=f"input-ds-{uuid.uuid4().hex[:12]}",
|
||||
kind="database",
|
||||
engine="postgresql",
|
||||
host="127.0.0.1",
|
||||
port=5432,
|
||||
database_name="synthetic",
|
||||
username="synthetic_user",
|
||||
secret_ciphertext=FAKE_CIPHERTEXT,
|
||||
)
|
||||
session.add(datasource)
|
||||
session.flush()
|
||||
registry.append(datasource.id)
|
||||
query = QueryDefinition(
|
||||
tenant_id=tenant_id,
|
||||
name=f"input-query-{uuid.uuid4().hex[:12]}",
|
||||
datasource_id=datasource.id,
|
||||
draft_sql_template="SELECT 1",
|
||||
current_version_no=1,
|
||||
latest_published_version_no=1,
|
||||
)
|
||||
session.add(query)
|
||||
session.flush()
|
||||
session.add(
|
||||
QueryVersion(
|
||||
tenant_id=tenant_id,
|
||||
definition_id=query.id,
|
||||
version_no=1,
|
||||
sql_template="SELECT 1",
|
||||
param_schema=[],
|
||||
output_schema=[
|
||||
{"name": "serial", "type": "string"},
|
||||
{"name": "temperature", "type": "number"},
|
||||
],
|
||||
allowed_identifiers=[],
|
||||
timeout_ms=10000,
|
||||
max_rows=100,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||
save_mapping_version(
|
||||
session,
|
||||
str(definition.id),
|
||||
[
|
||||
{
|
||||
"source_column_name": "serial",
|
||||
"value_type": "string",
|
||||
"is_identity": with_identity,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
{
|
||||
"source_column_name": "temperature",
|
||||
"value_type": "number",
|
||||
"is_identity": False,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
],
|
||||
)
|
||||
session.commit()
|
||||
return definition
|
||||
|
||||
|
||||
def _counts(session: Session, definition_id: uuid.UUID) -> tuple[int, int]:
|
||||
inputs = session.scalar(
|
||||
select(text("count(*)")).select_from(MappedInput).where(
|
||||
MappedInput.mapping_definition_id == definition_id
|
||||
)
|
||||
)
|
||||
revisions = session.scalar(
|
||||
select(text("count(*)"))
|
||||
.select_from(MappedInputRevision)
|
||||
.join(MappedInput, MappedInput.id == MappedInputRevision.input_id)
|
||||
.where(MappedInput.mapping_definition_id == definition_id)
|
||||
)
|
||||
return int(inputs or 0), int(revisions or 0)
|
||||
|
||||
|
||||
def test_two_identity_values_create_distinct_inputs(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=True)
|
||||
result = persist_mapped_rows(
|
||||
session,
|
||||
str(mapping.id),
|
||||
[{"serial": "A", "temperature": 1}, {"serial": "B", "temperature": 1}],
|
||||
run_id="run-1",
|
||||
)
|
||||
session.commit()
|
||||
assert result["inputs_created"] == 2
|
||||
assert _counts(session, mapping.id) == (2, 2)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_run_id_does_not_split_an_identity_or_append_unchanged_revision(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=True)
|
||||
persist_mapped_rows(
|
||||
session, str(mapping.id), [{"serial": "A", "temperature": 1}], run_id="run-1"
|
||||
)
|
||||
session.commit()
|
||||
result = persist_mapped_rows(
|
||||
session, str(mapping.id), [{"serial": "A", "temperature": 1}], run_id="run-2"
|
||||
)
|
||||
session.commit()
|
||||
assert result["inputs_created"] == 0
|
||||
assert result["revisions_appended"] == 0
|
||||
assert _counts(session, mapping.id) == (1, 1)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_changed_measure_appends_one_revision(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=True)
|
||||
persist_mapped_rows(session, str(mapping.id), [{"serial": "A", "temperature": 1}])
|
||||
session.commit()
|
||||
result = persist_mapped_rows(
|
||||
session, str(mapping.id), [{"serial": "A", "temperature": 2}]
|
||||
)
|
||||
session.commit()
|
||||
assert result["revisions_appended"] == 1
|
||||
assert _counts(session, mapping.id) == (1, 2)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_duplicate_identity_in_one_batch_keeps_first_row(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=True)
|
||||
result = persist_mapped_rows(
|
||||
session,
|
||||
str(mapping.id),
|
||||
[{"serial": "A", "temperature": 1}, {"serial": "A", "temperature": 2}],
|
||||
)
|
||||
session.commit()
|
||||
revision = session.scalar(select(MappedInputRevision))
|
||||
assert result["skipped_duplicate_rows"] == 1
|
||||
assert _counts(session, mapping.id) == (1, 1)
|
||||
assert revision is not None
|
||||
assert revision.mapped_values == {"temperature": 1}
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_blank_identity_column_does_not_create_input(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=True)
|
||||
result = persist_mapped_rows(session, str(mapping.id), [{"temperature": 1}])
|
||||
session.commit()
|
||||
assert result["skipped_missing_identity_rows"] == 1
|
||||
assert _counts(session, mapping.id) == (0, 0)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_no_identity_uses_first_row_and_mapping_singleton(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=False)
|
||||
result = persist_mapped_rows(
|
||||
session,
|
||||
str(mapping.id),
|
||||
[{"serial": "first", "temperature": 1}, {"serial": "later", "temperature": 2}],
|
||||
)
|
||||
session.commit()
|
||||
assert result["skipped_rows"] == 1
|
||||
assert _counts(session, mapping.id) == (1, 1)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_other_tenant_cannot_read_or_write_mapped_inputs(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=True)
|
||||
persist_mapped_rows(session, str(mapping.id), [{"serial": "A", "temperature": 1}])
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
other: Session = factory()
|
||||
try:
|
||||
set_tenant(other, "other-tenant")
|
||||
assert other.execute(
|
||||
text("SELECT count(*) FROM mapped_inputs WHERE mapping_definition_id = :id"),
|
||||
{"id": mapping.id},
|
||||
).scalar_one() == 0
|
||||
with pytest.raises(DBAPIError):
|
||||
other.execute(
|
||||
text(
|
||||
"INSERT INTO mapped_inputs "
|
||||
"(id, tenant_id, mapping_definition_id, identity_key) "
|
||||
"VALUES (gen_random_uuid(), :tenant, :mapping, 'identity:v1:foreign')"
|
||||
),
|
||||
{"tenant": settings.tenant_id, "mapping": mapping.id},
|
||||
)
|
||||
other.commit()
|
||||
other.rollback()
|
||||
finally:
|
||||
other.close()
|
||||
|
||||
|
||||
def test_app_role_cannot_update_or_delete_input_revision(input_factory) -> None:
|
||||
factory, registry, settings = input_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
mapping = _mapping(session, settings.tenant_id, registry, with_identity=True)
|
||||
persist_mapped_rows(session, str(mapping.id), [{"serial": "A", "temperature": 1}])
|
||||
session.commit()
|
||||
revision = session.scalar(select(MappedInputRevision))
|
||||
assert revision is not None
|
||||
with pytest.raises(DBAPIError) as update_exc:
|
||||
session.execute(
|
||||
text("UPDATE mapped_input_revisions SET revision_no = 2 WHERE id = :id"),
|
||||
{"id": revision.id},
|
||||
)
|
||||
assert getattr(update_exc.value.orig, "sqlstate", None) == "42501"
|
||||
session.rollback()
|
||||
with pytest.raises(DBAPIError) as delete_exc:
|
||||
session.execute(
|
||||
text("DELETE FROM mapped_input_revisions WHERE id = :id"), {"id": revision.id}
|
||||
)
|
||||
assert getattr(delete_exc.value.orig, "sqlstate", None) == "42501"
|
||||
session.rollback()
|
||||
finally:
|
||||
session.close()
|
||||
@@ -0,0 +1,72 @@
|
||||
"""S5 API permission and no-persistence trial tests."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import text
|
||||
|
||||
from test_datasource_api import ADMIN, OPERATOR, VIEWER, _client, _create, cleanup # noqa: F401
|
||||
from _privileged_cleanup import purge_query_rows
|
||||
from test_mapped_input_revisions import _purge_mapped_input_rows
|
||||
from watchman.core.db import get_session_factory, set_tenant
|
||||
from watchman.core.config import get_settings
|
||||
from watchman.models.platform import AuditEvent
|
||||
from watchman.api.routes import mappings
|
||||
|
||||
|
||||
def test_non_admins_are_rejected_before_mapping_write_or_trial(cleanup) -> None:
|
||||
for roles in (OPERATOR, VIEWER):
|
||||
client = _client(cleanup, roles)
|
||||
assert client.post("/mappings", json={"query_definition_id": str(uuid.uuid4())}).status_code == 403
|
||||
assert client.post(f"/mappings/{uuid.uuid4()}/trial", json={"condition_tree": {}, "rows": []}).status_code == 403
|
||||
assert client.post(f"/mappings/{uuid.uuid4()}/trial-query", json={"condition_tree": {}}).status_code == 403
|
||||
|
||||
|
||||
def test_admin_pasted_trial_does_not_persist_input(cleanup, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
client = _client(cleanup, ADMIN)
|
||||
datasource = _create(client)
|
||||
query = client.post("/queries", json={
|
||||
"name": f"mapping-api-{uuid.uuid4().hex[:8]}", "datasource_id": datasource["id"],
|
||||
"sql_template": "SELECT 1 AS n", "param_schema": [],
|
||||
"output_schema": [{"name": "n", "type": "number"}], "allowed_identifiers": [],
|
||||
"timeout_ms": 5000, "max_rows": 10,
|
||||
}).json()["data"]
|
||||
mapping = client.post("/mappings", json={"query_definition_id": query["id"]}).json()["data"]
|
||||
columns = [{"source_column_name": "n", "value_type": "number", "is_identity": False,
|
||||
"is_observation_time": False, "numeric_multiply": None, "numeric_offset": None}]
|
||||
tree = {"column": "n", "operator": "eq", "value": 1}
|
||||
saved = client.post(f"/mappings/{mapping['id']}/versions", json={"columns": columns, "condition_tree": tree})
|
||||
assert saved.status_code == 200 and saved.json()["data"]["condition_tree"] == tree
|
||||
rule = client.post(f"/mappings/{mapping['id']}/rules", json={}).json()["data"]
|
||||
assert client.post(f"/mappings/{mapping['id']}/rules/{rule['id']}/versions", json={"condition_tree": tree}).status_code == 200
|
||||
other = client.post("/mappings", json={"query_definition_id": query["id"]}).json()["data"]
|
||||
assert client.post(f"/mappings/{other['id']}/rules/{rule['id']}/versions", json={"condition_tree": tree}).status_code == 404
|
||||
response = client.post(f"/mappings/{mapping['id']}/trial", json={"condition_tree": tree, "rows": [{"n": 1}]})
|
||||
assert response.status_code == 200 and response.json()["data"]["code"] == "abnormal"
|
||||
session = get_session_factory()()
|
||||
try:
|
||||
set_tenant(session, get_settings().tenant_id)
|
||||
before_activate = session.execute(text("SELECT count(*) FROM mapping_versions WHERE definition_id = :id"), {"id": mapping["id"]}).scalar_one()
|
||||
assert client.post(f"/mappings/{mapping['id']}/versions/1/activate").status_code == 200
|
||||
assert session.execute(text("SELECT count(*) FROM mapping_versions WHERE definition_id = :id"), {"id": mapping["id"]}).scalar_one() == before_activate
|
||||
assert session.execute(text("SELECT count(*) FROM mapped_inputs WHERE mapping_definition_id = :id"), {"id": mapping["id"]}).scalar_one() == 0
|
||||
finally:
|
||||
session.close()
|
||||
marker = f"mapping-trial-query-{uuid.uuid4().hex}"
|
||||
def failed_preview(session, *_args, **_kwargs):
|
||||
session.add(AuditEvent(tenant_id=get_settings().tenant_id, action=marker, payload={}, idempotency_key=marker))
|
||||
return {"status": "failure", "details": {"reason": "synthetic"}}
|
||||
monkeypatch.setattr(mappings.query_service, "preview_current", failed_preview)
|
||||
response = client.post(f"/mappings/{mapping['id']}/trial-query", json={"condition_tree": tree, "row_limit": 10})
|
||||
assert response.status_code == 200 and response.json()["data"]["outcome"] == "error"
|
||||
session = get_session_factory()()
|
||||
try:
|
||||
set_tenant(session, get_settings().tenant_id)
|
||||
assert session.execute(text("SELECT count(*) FROM audit_events WHERE action = :action"), {"action": marker}).scalar_one() == 1
|
||||
assert session.execute(text("SELECT count(*) FROM mapped_inputs WHERE mapping_definition_id = :id"), {"id": mapping["id"]}).scalar_one() == 0
|
||||
finally:
|
||||
session.close()
|
||||
_purge_mapped_input_rows(uuid.UUID(datasource["id"]))
|
||||
purge_query_rows(datasource_id=uuid.UUID(datasource["id"]))
|
||||
@@ -0,0 +1,334 @@
|
||||
"""S1 persistence tests for versioned query mappings on local PostgreSQL.
|
||||
|
||||
Boundary: verifies mapping snapshots, tenant RLS, and database-enforced append-only versions;
|
||||
does not cover identity revisions, rules, API routes, or alarms. Depends on real PostgreSQL.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, select, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from _privileged_cleanup import purge_query_rows
|
||||
from watchman.core.config import get_settings, reload_settings
|
||||
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
|
||||
from watchman.core.errors import ValidationError
|
||||
from watchman.models import (
|
||||
DataSource,
|
||||
MappingColumnConfig,
|
||||
MappingDefinition,
|
||||
MappingVersion,
|
||||
QueryDefinition,
|
||||
QueryVersion,
|
||||
)
|
||||
from watchman.services.mappings import create_mapping, save_mapping_version
|
||||
|
||||
FAKE_CIPHERTEXT = "gAAAA-test-placeholder-ciphertext"
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def mapping_factory():
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
_ensure_after_begin_listener()
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||
datasource_ids: list[uuid.UUID] = []
|
||||
yield factory, datasource_ids, settings
|
||||
try:
|
||||
for datasource_id in datasource_ids:
|
||||
_purge_mapping_rows(datasource_id)
|
||||
purge_query_rows(datasource_id=datasource_id)
|
||||
finally:
|
||||
engine.dispose()
|
||||
reset_engine()
|
||||
|
||||
|
||||
def _purge_mapping_rows(datasource_id: uuid.UUID) -> None:
|
||||
"""Remove only synthetic mapping rows while append-only triggers are explicitly bypassed."""
|
||||
from _privileged_cleanup import _superuser_engine
|
||||
|
||||
engine = _superuser_engine()
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
params = {"datasource_id": str(datasource_id)}
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM mapping_column_configs WHERE mapping_version_id IN "
|
||||
"(SELECT v.id FROM mapping_versions v JOIN mapping_definitions d "
|
||||
"ON d.id = v.definition_id WHERE d.query_definition_id IN "
|
||||
"(SELECT id FROM query_definitions WHERE datasource_id = :datasource_id))"
|
||||
),
|
||||
params,
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM mapping_versions WHERE definition_id IN "
|
||||
"(SELECT id FROM mapping_definitions WHERE query_definition_id IN "
|
||||
"(SELECT id FROM query_definitions WHERE datasource_id = :datasource_id))"
|
||||
),
|
||||
params,
|
||||
)
|
||||
conn.execute(
|
||||
text(
|
||||
"DELETE FROM mapping_definitions WHERE query_definition_id IN "
|
||||
"(SELECT id FROM query_definitions WHERE datasource_id = :datasource_id)"
|
||||
),
|
||||
params,
|
||||
)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _query(session: Session, tenant_id: str, registry: list[uuid.UUID]) -> QueryDefinition:
|
||||
"""Create a current query version with the output schema used by S1 mapping checks."""
|
||||
datasource = DataSource(
|
||||
tenant_id=tenant_id,
|
||||
name=f"mapping-ds-{uuid.uuid4().hex[:12]}",
|
||||
kind="database",
|
||||
engine="postgresql",
|
||||
host="127.0.0.1",
|
||||
port=5432,
|
||||
database_name="synthetic",
|
||||
username="synthetic_user",
|
||||
secret_ciphertext=FAKE_CIPHERTEXT,
|
||||
)
|
||||
session.add(datasource)
|
||||
session.flush()
|
||||
registry.append(datasource.id)
|
||||
query = QueryDefinition(
|
||||
tenant_id=tenant_id,
|
||||
name=f"mapping-query-{uuid.uuid4().hex[:12]}",
|
||||
datasource_id=datasource.id,
|
||||
draft_sql_template="SELECT 1",
|
||||
current_version_no=1,
|
||||
latest_published_version_no=1,
|
||||
)
|
||||
session.add(query)
|
||||
session.flush()
|
||||
session.add(
|
||||
QueryVersion(
|
||||
tenant_id=tenant_id,
|
||||
definition_id=query.id,
|
||||
version_no=1,
|
||||
sql_template="SELECT 1",
|
||||
param_schema=[],
|
||||
output_schema=[
|
||||
{"name": "temperature", "type": "number"},
|
||||
{"name": "serial", "type": "string"},
|
||||
{"name": "observed_at", "type": "datetime"},
|
||||
],
|
||||
allowed_identifiers=[],
|
||||
timeout_ms=10000,
|
||||
max_rows=100,
|
||||
)
|
||||
)
|
||||
session.commit()
|
||||
return query
|
||||
|
||||
|
||||
def _columns() -> list[dict[str, object]]:
|
||||
return [
|
||||
{
|
||||
"source_column_name": "temperature",
|
||||
"value_type": "number",
|
||||
"is_identity": False,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": "1.8",
|
||||
"numeric_offset": "32",
|
||||
},
|
||||
{
|
||||
"source_column_name": "serial",
|
||||
"value_type": "string",
|
||||
"is_identity": True,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
{
|
||||
"source_column_name": "observed_at",
|
||||
"value_type": "datetime",
|
||||
"is_identity": False,
|
||||
"is_observation_time": True,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def test_mapping_tables_force_rls_and_are_not_owned_by_app_role() -> None:
|
||||
reload_settings()
|
||||
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
|
||||
with engine.connect() as conn:
|
||||
for table in ("mapping_definitions", "mapping_versions", "mapping_column_configs"):
|
||||
owner = conn.execute(
|
||||
text(
|
||||
"SELECT tableowner FROM pg_tables "
|
||||
"WHERE schemaname = 'public' AND tablename = :table"
|
||||
),
|
||||
{"table": table},
|
||||
).scalar_one()
|
||||
flags = conn.execute(
|
||||
text(
|
||||
"SELECT relrowsecurity, relforcerowsecurity FROM pg_class "
|
||||
"WHERE relname = :table"
|
||||
),
|
||||
{"table": table},
|
||||
).one()
|
||||
assert owner != "watchman_app"
|
||||
assert flags.relrowsecurity is True
|
||||
assert flags.relforcerowsecurity is True
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def test_save_creates_immutable_version_and_round_trips_multiple_columns(mapping_factory) -> None:
|
||||
factory, registry, settings = mapping_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
query = _query(session, settings.tenant_id, registry)
|
||||
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||
first = save_mapping_version(
|
||||
session, str(definition.id), _columns(), saved_by="mapping-test"
|
||||
)
|
||||
session.commit()
|
||||
|
||||
assert first.version_no == 1
|
||||
assert definition.current_version_no == 1
|
||||
stored = list(
|
||||
session.scalars(
|
||||
select(MappingColumnConfig)
|
||||
.where(MappingColumnConfig.mapping_version_id == first.id)
|
||||
.order_by(MappingColumnConfig.source_column_name)
|
||||
)
|
||||
)
|
||||
assert [column.source_column_name for column in stored] == [
|
||||
"observed_at",
|
||||
"serial",
|
||||
"temperature",
|
||||
]
|
||||
assert sum(column.is_observation_time for column in stored) == 1
|
||||
assert next(column for column in stored if column.source_column_name == "serial").is_identity
|
||||
|
||||
second = save_mapping_version(session, str(definition.id), _columns())
|
||||
session.commit()
|
||||
assert second.version_no == 2
|
||||
assert definition.current_version_no == 2
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_save_rejects_column_missing_from_current_query_version(mapping_factory) -> None:
|
||||
factory, registry, settings = mapping_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
query = _query(session, settings.tenant_id, registry)
|
||||
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||
with pytest.raises(ValidationError) as exc:
|
||||
save_mapping_version(
|
||||
session,
|
||||
str(definition.id),
|
||||
[
|
||||
{
|
||||
"source_column_name": "gone",
|
||||
"value_type": "number",
|
||||
"is_identity": False,
|
||||
"is_observation_time": False,
|
||||
"numeric_multiply": None,
|
||||
"numeric_offset": None,
|
||||
}
|
||||
],
|
||||
)
|
||||
assert exc.value.details["reason"] == "mapping_columns_missing"
|
||||
assert exc.value.details["fields"] == ["gone"]
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_other_tenant_cannot_read_mapping_rows(mapping_factory) -> None:
|
||||
factory, registry, settings = mapping_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
query = _query(session, settings.tenant_id, registry)
|
||||
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||
version = save_mapping_version(session, str(definition.id), _columns())
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
other: Session = factory()
|
||||
try:
|
||||
set_tenant(other, "other-tenant")
|
||||
assert other.execute(
|
||||
text("SELECT count(*) FROM mapping_definitions WHERE id = :id"),
|
||||
{"id": definition.id},
|
||||
).scalar_one() == 0
|
||||
assert other.execute(
|
||||
text("SELECT count(*) FROM mapping_versions WHERE id = :id"),
|
||||
{"id": version.id},
|
||||
).scalar_one() == 0
|
||||
assert other.execute(
|
||||
text("SELECT count(*) FROM mapping_column_configs WHERE mapping_version_id = :id"),
|
||||
{"id": version.id},
|
||||
).scalar_one() == 0
|
||||
finally:
|
||||
other.close()
|
||||
|
||||
|
||||
def test_app_role_cannot_update_or_delete_historical_mapping_version(mapping_factory) -> None:
|
||||
factory, registry, settings = mapping_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
query = _query(session, settings.tenant_id, registry)
|
||||
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||
version = save_mapping_version(session, str(definition.id), _columns())
|
||||
session.commit()
|
||||
|
||||
with pytest.raises(DBAPIError) as update_exc:
|
||||
session.execute(
|
||||
text("UPDATE mapping_versions SET saved_by = 'tampered' WHERE id = :id"),
|
||||
{"id": version.id},
|
||||
)
|
||||
assert getattr(update_exc.value.orig, "sqlstate", None) == "42501"
|
||||
session.rollback()
|
||||
|
||||
with pytest.raises(DBAPIError) as delete_exc:
|
||||
session.execute(text("DELETE FROM mapping_versions WHERE id = :id"), {"id": version.id})
|
||||
assert getattr(delete_exc.value.orig, "sqlstate", None) == "42501"
|
||||
session.rollback()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_owner_trigger_rejects_mapping_version_mutation(mapping_factory) -> None:
|
||||
factory, registry, settings = mapping_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
query = _query(session, settings.tenant_id, registry)
|
||||
definition = create_mapping(session, query_definition_id=str(query.id))
|
||||
version = save_mapping_version(session, str(definition.id), _columns())
|
||||
session.commit()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
owner_engine = create_engine(settings.database_migrator_url, pool_pre_ping=True)
|
||||
try:
|
||||
with owner_engine.connect() as conn:
|
||||
with pytest.raises(DBAPIError) as exc:
|
||||
conn.execute(
|
||||
text("DELETE FROM mapping_versions WHERE id = :id"), {"id": version.id}
|
||||
)
|
||||
assert getattr(exc.value.orig, "sqlstate", None) == "23001"
|
||||
conn.rollback()
|
||||
finally:
|
||||
owner_engine.dispose()
|
||||
@@ -0,0 +1,157 @@
|
||||
"""S3 tests for structured rule validation and immutable rule versions."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.exc import DBAPIError
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
|
||||
from _privileged_cleanup import _superuser_engine, purge_query_rows
|
||||
from watchman.core.config import get_settings, reload_settings
|
||||
from watchman.core.db import _ensure_after_begin_listener, reset_engine, set_tenant
|
||||
from watchman.core.errors import ValidationError
|
||||
from watchman.models.datasource import DataSource
|
||||
from watchman.models.mapping import RuleVersion
|
||||
from watchman.models.query import QueryDefinition, QueryVersion
|
||||
from watchman.services.mappings import create_mapping, save_mapping_version
|
||||
from watchman.services.rules import create_rule, save_rule_version
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def rule_factory():
|
||||
reload_settings()
|
||||
reset_engine()
|
||||
_ensure_after_begin_listener()
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.database_url, pool_pre_ping=True)
|
||||
factory = sessionmaker(bind=engine, autoflush=False, autocommit=False, expire_on_commit=False)
|
||||
datasource_ids: list[uuid.UUID] = []
|
||||
yield factory, datasource_ids, settings
|
||||
for datasource_id in datasource_ids:
|
||||
_purge_rules(datasource_id)
|
||||
purge_query_rows(datasource_id=datasource_id)
|
||||
engine.dispose()
|
||||
reset_engine()
|
||||
|
||||
|
||||
def _purge_rules(datasource_id: uuid.UUID) -> None:
|
||||
engine = _superuser_engine()
|
||||
try:
|
||||
with engine.begin() as conn:
|
||||
conn.execute(text("SET LOCAL session_replication_role = replica"))
|
||||
params = {"datasource_id": str(datasource_id)}
|
||||
mapping_ids = (
|
||||
"SELECT id FROM mapping_definitions WHERE query_definition_id IN "
|
||||
"(SELECT id FROM query_definitions WHERE datasource_id = :datasource_id)"
|
||||
)
|
||||
conn.execute(text(f"DELETE FROM rule_versions WHERE definition_id IN (SELECT id FROM rule_definitions WHERE mapping_definition_id IN ({mapping_ids}))"), params)
|
||||
conn.execute(text(f"DELETE FROM rule_definitions WHERE mapping_definition_id IN ({mapping_ids})"), params)
|
||||
conn.execute(text(f"DELETE FROM mapping_column_configs WHERE mapping_version_id IN (SELECT id FROM mapping_versions WHERE definition_id IN ({mapping_ids}))"), params)
|
||||
conn.execute(text(f"DELETE FROM mapping_versions WHERE definition_id IN ({mapping_ids})"), params)
|
||||
conn.execute(text(f"DELETE FROM mapping_definitions WHERE id IN ({mapping_ids})"), params)
|
||||
finally:
|
||||
engine.dispose()
|
||||
|
||||
|
||||
def _rule(session: Session, tenant: str, registry: list[uuid.UUID]):
|
||||
datasource = DataSource(tenant_id=tenant, name=f"rule-ds-{uuid.uuid4().hex}", kind="database", engine="postgresql", host="127.0.0.1", port=5432, database_name="synthetic", username="synthetic", secret_ciphertext="gAAAA-test-placeholder-ciphertext")
|
||||
session.add(datasource)
|
||||
session.flush()
|
||||
registry.append(datasource.id)
|
||||
query = QueryDefinition(tenant_id=tenant, name=f"rule-q-{uuid.uuid4().hex}", datasource_id=datasource.id, draft_sql_template="SELECT 1", current_version_no=1, latest_published_version_no=1)
|
||||
session.add(query)
|
||||
session.flush()
|
||||
session.add(QueryVersion(tenant_id=tenant, definition_id=query.id, version_no=1, sql_template="SELECT 1", param_schema=[], output_schema=[{"name": "amount", "type": "number"}, {"name": "label", "type": "string"}, {"name": "flag", "type": "boolean"}, {"name": "occurred_at", "type": "datetime"}], allowed_identifiers=[], timeout_ms=10000, max_rows=100))
|
||||
session.commit()
|
||||
mapping = create_mapping(session, query_definition_id=str(query.id))
|
||||
save_mapping_version(session, str(mapping.id), [
|
||||
{"source_column_name": "amount", "value_type": "number", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "label", "value_type": "string", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "flag", "value_type": "boolean", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
{"source_column_name": "occurred_at", "value_type": "datetime", "is_identity": False, "is_observation_time": False, "numeric_multiply": None, "numeric_offset": None},
|
||||
])
|
||||
session.commit()
|
||||
return create_rule(session, mapping_definition_id=str(mapping.id))
|
||||
|
||||
|
||||
def _save(session: Session, rule, tree):
|
||||
version = save_rule_version(session, str(rule.id), tree)
|
||||
session.commit()
|
||||
return version
|
||||
|
||||
|
||||
def _legal_tree():
|
||||
return {"op": "and", "items": [{"column": "amount", "operator": "gte", "value": 10}, {"column": "label", "operator": "ne", "value": "ignored"}]}
|
||||
|
||||
|
||||
@pytest.mark.parametrize("tree", [
|
||||
{"column": "amount", "operator": "eq", "value": 1, "script": "x"},
|
||||
{"column": "amount", "operator": "matches", "value": 1},
|
||||
{"op": "and", "items": []},
|
||||
{"column": "label", "operator": "gt", "value": "a"},
|
||||
{"column": "occurred_at", "operator": "eq", "value": "2026-11-18T08:00:00"},
|
||||
])
|
||||
def test_rejects_invalid_rule_shapes_and_types(rule_factory, tree) -> None:
|
||||
factory, registry, settings = rule_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
rule = _rule(session, settings.tenant_id, registry)
|
||||
with pytest.raises(ValidationError):
|
||||
save_rule_version(session, str(rule.id), tree)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_rejects_tree_deeper_than_four(rule_factory) -> None:
|
||||
factory, registry, settings = rule_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
rule = _rule(session, settings.tenant_id, registry)
|
||||
tree = {"op": "and", "items": [{"op": "and", "items": [{"op": "and", "items": [{"op": "and", "items": [{"column": "amount", "operator": "eq", "value": 1}]}]}]}]}
|
||||
with pytest.raises(ValidationError):
|
||||
save_rule_version(session, str(rule.id), tree)
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_legal_rule_round_trips_and_is_immutable(rule_factory) -> None:
|
||||
factory, registry, settings = rule_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
rule = _rule(session, settings.tenant_id, registry)
|
||||
tree = _legal_tree()
|
||||
version = _save(session, rule, tree)
|
||||
assert version.condition_tree == tree
|
||||
stored = session.get(RuleVersion, version.id)
|
||||
assert stored is not None and stored.condition_tree == tree
|
||||
with pytest.raises(DBAPIError):
|
||||
session.execute(text("UPDATE rule_versions SET version_no = 2 WHERE id = :id"), {"id": version.id})
|
||||
session.rollback()
|
||||
with pytest.raises(DBAPIError):
|
||||
session.execute(text("DELETE FROM rule_versions WHERE id = :id"), {"id": version.id})
|
||||
session.rollback()
|
||||
finally:
|
||||
session.close()
|
||||
|
||||
|
||||
def test_other_tenant_cannot_read_rule_version(rule_factory) -> None:
|
||||
factory, registry, settings = rule_factory
|
||||
session: Session = factory()
|
||||
try:
|
||||
set_tenant(session, settings.tenant_id)
|
||||
rule = _rule(session, settings.tenant_id, registry)
|
||||
version = _save(session, rule, _legal_tree())
|
||||
finally:
|
||||
session.close()
|
||||
other: Session = factory()
|
||||
try:
|
||||
set_tenant(other, "other-tenant")
|
||||
assert other.execute(text("SELECT count(*) FROM rule_versions WHERE id = :id"), {"id": version.id}).scalar_one() == 0
|
||||
finally:
|
||||
other.close()
|
||||
@@ -0,0 +1,101 @@
|
||||
import { expect, test, type Page, type Route } from "@playwright/test";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const evidenceDir = path.resolve(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
"../../../../docs/evidence/M05/ui",
|
||||
);
|
||||
|
||||
const MAP_ID = "44444444-4444-4444-8444-444444444444";
|
||||
|
||||
function ok(data: unknown): string {
|
||||
return JSON.stringify({ success: true, data, request_id: "pw-m" });
|
||||
}
|
||||
|
||||
const columns = [
|
||||
{ source_column_name: "temperature", value_type: "number", is_identity: false, is_observation_time: false, numeric_multiply: null, numeric_offset: null },
|
||||
];
|
||||
|
||||
const tree = { column: "temperature", operator: "gt", value: 80 };
|
||||
|
||||
async function signIn(page: Page): Promise<void> {
|
||||
await page.route("**/auth/me", async (route) => {
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ subject: "user-1", display_name: "管理员", roles: ["watchman-admin"] }) });
|
||||
});
|
||||
await page.route("**/health", async (route) => {
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ status: "ok", app: "watchman", version: "0.1.0" }) });
|
||||
});
|
||||
}
|
||||
|
||||
async function mockApi(page: Page): Promise<void> {
|
||||
await page.route("**/mappings**", async (route: Route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const pathname = url.pathname;
|
||||
if (!pathname.startsWith("/mappings")) {
|
||||
await route.continue();
|
||||
return;
|
||||
}
|
||||
if (route.request().method() === "GET" && pathname === "/mappings") {
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ items: [{ id: MAP_ID, name: "当前炉温", query: "当前炉温", current_version_no: 1 }], total: 1, page: 1, page_size: 20 }) });
|
||||
return;
|
||||
}
|
||||
if (route.request().method() === "GET" && pathname === `/mappings/${MAP_ID}`) {
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ id: MAP_ID, query_definition_id: "q1", current_version_no: 1 }) });
|
||||
return;
|
||||
}
|
||||
if (route.request().method() === "GET" && pathname === `/mappings/${MAP_ID}/versions`) {
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ items: [{ version_no: 1 }] }) });
|
||||
return;
|
||||
}
|
||||
if (route.request().method() === "GET" && pathname.startsWith(`/mappings/${MAP_ID}/versions/`)) {
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ version_no: 1, columns, condition_tree: tree }) });
|
||||
return;
|
||||
}
|
||||
if (route.request().method() === "POST" && pathname === `/mappings/${MAP_ID}/versions`) {
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ version_no: 2, condition_tree: tree }) });
|
||||
return;
|
||||
}
|
||||
if (route.request().method() === "POST" && pathname === `/mappings/${MAP_ID}/trial`) {
|
||||
const body = route.request().postDataJSON() as { rows?: { temperature?: number }[] };
|
||||
const value = body.rows?.[0]?.temperature;
|
||||
const code = value == null ? "unknown" : value > 80 ? "abnormal" : "normal";
|
||||
const skipped = (body.rows?.length ?? 1) > 1 ? (body.rows?.length ?? 1) - 1 : 0;
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: ok({ code, outcome: "result", skipped_rows: skipped }) });
|
||||
return;
|
||||
}
|
||||
await route.fulfill({ status: 404, contentType: "application/json", body: ok({}) });
|
||||
});
|
||||
}
|
||||
|
||||
test("mapping save and trial show the three conclusions and the first-row note", async ({ page }) => {
|
||||
await signIn(page);
|
||||
await mockApi(page);
|
||||
await page.goto("/#/mappings");
|
||||
await expect(page.getByTestId("nav-mappings")).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: "判断规则" })).toHaveCount(0);
|
||||
await page.getByTestId("mapping-open").click();
|
||||
await expect(page.getByText("判断规则")).toBeVisible();
|
||||
await page.getByTestId("mapping-value-0").fill("80");
|
||||
await page.getByTestId("mapping-save").click();
|
||||
await page.getByRole("button", { name: "手填数据" }).click();
|
||||
await page.getByTestId("mapping-rows").fill(JSON.stringify([{ temperature: 90 }]));
|
||||
await page.getByTestId("mapping-trial").click();
|
||||
await expect(page.getByTestId("mapping-outcome")).toContainText("异常");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "trial-abnormal.png"), fullPage: true });
|
||||
|
||||
await page.getByTestId("mapping-rows").fill(JSON.stringify([{ temperature: 70 }]));
|
||||
await page.getByTestId("mapping-trial").click();
|
||||
await expect(page.getByTestId("mapping-outcome")).toContainText("正常");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "trial-normal.png"), fullPage: true });
|
||||
|
||||
await page.getByTestId("mapping-rows").fill(JSON.stringify([{ temperature: null }]));
|
||||
await page.getByTestId("mapping-trial").click();
|
||||
await expect(page.getByTestId("mapping-outcome")).toContainText("未知");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "trial-unknown.png"), fullPage: true });
|
||||
|
||||
await page.getByTestId("mapping-rows").fill(JSON.stringify([{ temperature: 90 }, { temperature: 70 }]));
|
||||
await page.getByTestId("mapping-trial").click();
|
||||
await expect(page.getByTestId("mapping-skip")).toContainText("其余 1 行未采用");
|
||||
await page.screenshot({ path: path.join(evidenceDir, "trial-first-row.png"), fullPage: true });
|
||||
});
|
||||
@@ -37,6 +37,7 @@
|
||||
"home": "Overview",
|
||||
"datasources": "Data sources",
|
||||
"queries": "Queries",
|
||||
"mappings": "Mappings & Rules",
|
||||
"create": "New",
|
||||
"detail": "Details",
|
||||
"version": "Version v{no}"
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
"home": "ภาพรวม",
|
||||
"datasources": "แหล่งข้อมูล",
|
||||
"queries": "คิวรี",
|
||||
"mappings": "การแมปและกฎ",
|
||||
"create": "สร้างใหม่",
|
||||
"detail": "รายละเอียด",
|
||||
"version": "เวอร์ชัน v{no}"
|
||||
|
||||
@@ -38,6 +38,7 @@
|
||||
"home": "概览",
|
||||
"datasources": "数据源",
|
||||
"queries": "查询",
|
||||
"mappings": "映射与规则",
|
||||
"create": "新建",
|
||||
"detail": "详情",
|
||||
"version": "版本 v{no}"
|
||||
|
||||
@@ -37,6 +37,7 @@
|
||||
"home": "概覽",
|
||||
"datasources": "資料來源",
|
||||
"queries": "查詢",
|
||||
"mappings": "映射與規則",
|
||||
"create": "新增",
|
||||
"detail": "詳情",
|
||||
"version": "版本 v{no}"
|
||||
|
||||
@@ -18,7 +18,7 @@ const { t } = useI18n();
|
||||
const route = useRoute();
|
||||
const auth = useAuthStore();
|
||||
|
||||
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources", queries: "/queries" };
|
||||
const CRUMB_LINKS: Record<string, string> = { datasources: "/datasources", queries: "/queries", mappings: "/mappings" };
|
||||
|
||||
/** Where a non-final crumb goes. A query's "detail" crumb is the draft page of the same query. */
|
||||
function crumbLink(key: string): string | undefined {
|
||||
@@ -92,6 +92,9 @@ const activeClass = "!bg-[#eef0fb] !font-semibold !text-[var(--color-primary)]";
|
||||
>
|
||||
{{ t("nav.queries") }}
|
||||
</RouterLink>
|
||||
<RouterLink to="/mappings" :class="linkClass" :active-class="activeClass" data-testid="nav-mappings">
|
||||
{{ t("nav.mappings") }}
|
||||
</RouterLink>
|
||||
</nav>
|
||||
<div
|
||||
class="mt-3 border-t border-[var(--border-subtle)] px-2.5 pt-3"
|
||||
|
||||
@@ -0,0 +1,314 @@
|
||||
<script setup lang="ts">
|
||||
/** Shared mapping editor. Columns come from the query output; the condition tree is edited as groups. */
|
||||
import { onMounted, reactive, ref } from "vue";
|
||||
import { useRoute, useRouter } from "vue-router";
|
||||
import { ElAlert, ElButton, ElCheckbox, ElDialog, ElInput, ElTable, ElTableColumn, ElTag } from "element-plus";
|
||||
import { getQuery } from "../queries/client";
|
||||
import { buildPreviewParams, initialPreviewValues, specsFromSchema, type PreviewSpec } from "../queries/payload";
|
||||
import type { OutputType } from "../queries/types";
|
||||
import { activateMappingVersion, getMapping, getMappingVersion, listMappingVersions, saveMappingVersion, trialMapping, trialMappingQuery, type MappingColumn } from "./client";
|
||||
import { blankGroup, conditionSummary, treeForApi, treeFromApi, type GroupNode } from "./condition";
|
||||
import RuleGroup from "./RuleGroup.vue";
|
||||
import { seedColumns } from "./seed";
|
||||
|
||||
const route = useRoute();
|
||||
const router = useRouter();
|
||||
const id = String(route.params.id);
|
||||
const loadedVersion = ref(0);
|
||||
const currentVersion = ref(0);
|
||||
const switching = ref(false);
|
||||
const outcome = ref<"" | "normal" | "abnormal" | "unknown" | "empty" | "error" | "result">("");
|
||||
const columns = reactive<MappingColumn[]>([]);
|
||||
const root = reactive<GroupNode>(blankGroup(""));
|
||||
const versions = ref<number[]>([]);
|
||||
const rowsJson = ref("[]");
|
||||
const saveError = ref("");
|
||||
const skippedRows = ref(0);
|
||||
const trialMode = ref<"query" | "manual">("query");
|
||||
const rowLimit = ref("10");
|
||||
const queryName = ref("");
|
||||
const paramSpecs = ref<PreviewSpec[]>([]);
|
||||
const paramValues = ref<Record<string, string>>({});
|
||||
const paramError = ref("");
|
||||
const trialColumns = ref<string[]>([]);
|
||||
const trialTable = ref<Record<string, unknown>[]>([]);
|
||||
|
||||
const sampleRows = [
|
||||
{ line_code: "L1", lot_no: "LOT-1002", metric: "temp_c", reading_value: 91, sampled_at: "2026-11-18T02:05:00+00:00" },
|
||||
{ line_code: "L2", lot_no: "LOT-2001", metric: "temp_c", reading_value: 72.3, sampled_at: "2026-11-18T02:10:00+00:00" },
|
||||
{ line_code: "L1", lot_no: "LOT-1001", metric: "pressure_kpa", reading_value: 101.2, sampled_at: "2026-11-18T02:01:00+00:00" },
|
||||
{ line_code: "L2", lot_no: "LOT-2001", metric: "pressure_kpa", reading_value: 98, sampled_at: "2026-11-18T02:11:00+00:00" },
|
||||
{ line_code: "L3", lot_no: "LOT-3001", metric: "temp_c", reading_value: null, sampled_at: "2026-11-18T02:20:00+00:00" },
|
||||
{ line_code: "L3", lot_no: "LOT-3002", metric: "temp_c", reading_value: 91, sampled_at: "2026-11-18T02:30:00" },
|
||||
];
|
||||
|
||||
function conclusion(code: string): string {
|
||||
if (code === "result") return "已逐行判断";
|
||||
if (code === "empty") return "空结果";
|
||||
if (code === "error") return "执行失败";
|
||||
if (code === "normal") return "正常";
|
||||
if (code === "abnormal") return "异常";
|
||||
if (code === "skipped") return "未采用";
|
||||
return "未知";
|
||||
}
|
||||
|
||||
function tagType(code: string): "success" | "warning" | "danger" | "info" {
|
||||
if (code === "abnormal") return "danger";
|
||||
if (code === "normal") return "success";
|
||||
if (code === "unknown") return "warning";
|
||||
return "info";
|
||||
}
|
||||
|
||||
function cellText(value: unknown): string {
|
||||
if (value === null || value === undefined || value === "") return "—";
|
||||
if (typeof value === "object") return JSON.stringify(value);
|
||||
return String(value);
|
||||
}
|
||||
|
||||
const preferredColumns = ["line_code", "lot_no", "metric", "reading_value", "sampled_at"];
|
||||
|
||||
function showTrial(inputs: Record<string, unknown>[], data: { code?: string; outcome?: string; skipped_rows?: number; rows?: { code?: string }[] }) {
|
||||
skippedRows.value = Number(data.skipped_rows ?? 0);
|
||||
if (!inputs.length || data.outcome === "empty") {
|
||||
outcome.value = "empty";
|
||||
trialColumns.value = [];
|
||||
trialTable.value = [];
|
||||
return;
|
||||
}
|
||||
if (data.outcome === "error" && !data.rows?.length) {
|
||||
outcome.value = "error";
|
||||
trialColumns.value = [];
|
||||
trialTable.value = [];
|
||||
return;
|
||||
}
|
||||
const judged = data.rows ?? [];
|
||||
trialColumns.value = [
|
||||
...preferredColumns.filter((name) => inputs.some((row) => name in row)),
|
||||
...inputs.flatMap((row) => Object.keys(row)).filter((name, index, all) => !preferredColumns.includes(name) && all.indexOf(name) === index),
|
||||
];
|
||||
trialTable.value = inputs.map((row, index) => ({ ...row, __code: judged[index]?.code ?? "skipped" }));
|
||||
const first = data.code ?? judged[0]?.code ?? data.outcome ?? "error";
|
||||
outcome.value = trialTable.value.length > 1 ? "result" : first as typeof outcome.value;
|
||||
}
|
||||
|
||||
const typeLabel: Record<string, string> = { string: "文本", number: "数值", integer: "数值", datetime: "时间", boolean: "布尔" };
|
||||
|
||||
function replaceTree(tree: unknown): void {
|
||||
const next = treeFromApi(tree, columns[0]?.source_column_name ?? "");
|
||||
root.op = next.op;
|
||||
root.items.splice(0, root.items.length, ...next.items);
|
||||
}
|
||||
|
||||
function columnsForSave(): MappingColumn[] {
|
||||
return columns.map((column) => ({
|
||||
...column,
|
||||
numeric_multiply: column.value_type === "number" && column.numeric_multiply ? column.numeric_multiply : null,
|
||||
numeric_offset: column.value_type === "number" && column.numeric_offset ? column.numeric_offset : null,
|
||||
}));
|
||||
}
|
||||
|
||||
function fillRows() {
|
||||
const names = new Set(columns.map((column) => column.source_column_name));
|
||||
const usable = sampleRows.filter((row) => Object.keys(row).every((key) => names.has(key)));
|
||||
const rows = usable.length ? usable : [Object.fromEntries(columns.map((column) => [column.source_column_name, null]))];
|
||||
rowsJson.value = JSON.stringify(rows, null, 2);
|
||||
}
|
||||
|
||||
function fillFailure() {
|
||||
rowsJson.value = "[]";
|
||||
outcome.value = "";
|
||||
trialTable.value = [];
|
||||
trialColumns.value = [];
|
||||
skippedRows.value = 0;
|
||||
}
|
||||
|
||||
async function load(versionNo: number) {
|
||||
const data = await getMappingVersion(id, versionNo);
|
||||
loadedVersion.value = data.version_no;
|
||||
columns.splice(0, columns.length, ...data.columns);
|
||||
replaceTree(data.condition_tree);
|
||||
}
|
||||
|
||||
async function refreshVersions() {
|
||||
versions.value = (await listMappingVersions(id)).items.map((item) => item.version_no);
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saveError.value = "";
|
||||
try {
|
||||
const saved = await saveMappingVersion(id, { columns: columnsForSave(), condition_tree: treeForApi(root, columns) });
|
||||
currentVersion.value = Number((saved as { version_no: number }).version_no);
|
||||
await load(currentVersion.value);
|
||||
await refreshVersions();
|
||||
} catch {
|
||||
saveError.value = "保存失败。请检查每条条件的比较值是否已填写,并且和列的类型一致。";
|
||||
}
|
||||
}
|
||||
|
||||
async function trial() {
|
||||
paramError.value = "";
|
||||
if (currentVersion.value < 1) {
|
||||
outcome.value = "error";
|
||||
trialTable.value = [];
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const parsed = JSON.parse(rowsJson.value) as Record<string, unknown>[];
|
||||
const data = await trialMapping(id, { rows: parsed, condition_tree: treeForApi(root, columns) });
|
||||
showTrial(parsed, data as { code?: string; outcome?: string; skipped_rows?: number; rows?: { code?: string }[] });
|
||||
} catch {
|
||||
outcome.value = "error";
|
||||
trialTable.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function trialFromQuery() {
|
||||
paramError.value = "";
|
||||
if (currentVersion.value < 1) {
|
||||
outcome.value = "error";
|
||||
trialTable.value = [];
|
||||
return;
|
||||
}
|
||||
const built = buildPreviewParams(paramSpecs.value, paramValues.value);
|
||||
if (built.invalid.length) {
|
||||
paramError.value = "查询参数的格式不对。";
|
||||
return;
|
||||
}
|
||||
const limit = Math.min(100, Math.max(1, Number(rowLimit.value) || 10));
|
||||
rowLimit.value = String(limit);
|
||||
try {
|
||||
const data = await trialMappingQuery(id, { query_params: built.params, row_limit: limit, condition_tree: treeForApi(root, columns) }) as {
|
||||
code?: string;
|
||||
outcome?: string;
|
||||
skipped_rows?: number;
|
||||
rows?: { code?: string }[];
|
||||
input_rows?: Record<string, unknown>[];
|
||||
};
|
||||
showTrial(data.input_rows ?? [], data);
|
||||
} catch {
|
||||
outcome.value = "error";
|
||||
trialTable.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const mapping = await getMapping(id);
|
||||
currentVersion.value = mapping.current_version_no ?? 0;
|
||||
let outputSchema: { name: string; type: OutputType }[] = [];
|
||||
try {
|
||||
const query = await getQuery(mapping.query_definition_id);
|
||||
queryName.value = query.name;
|
||||
paramSpecs.value = specsFromSchema(query.current.param_schema ?? []);
|
||||
paramValues.value = initialPreviewValues(paramSpecs.value);
|
||||
outputSchema = query.current.output_schema ?? [];
|
||||
} catch {
|
||||
queryName.value = "";
|
||||
}
|
||||
const requested = route.query.version ? Number(route.query.version) : currentVersion.value;
|
||||
if (requested >= 1) await load(requested);
|
||||
else {
|
||||
loadedVersion.value = 0;
|
||||
columns.splice(0, columns.length, ...seedColumns(outputSchema));
|
||||
replaceTree(null);
|
||||
}
|
||||
fillRows();
|
||||
await refreshVersions();
|
||||
if (route.query.switch === "1") switching.value = true;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex h-full min-h-0 flex-col">
|
||||
<main class="min-h-0 flex-1 overflow-auto p-8">
|
||||
<ElAlert :title="loadedVersion < 1 ? '还没有版本。字段来自查询输出,另存后成为 v1。' : `正在编辑 v${loadedVersion};当前生效 v${currentVersion}。保存会另存为新版本,历史版本不会修改。`" type="info" :closable="false" />
|
||||
|
||||
<h2 class="mb-2 mt-6 text-base font-semibold">字段映射</h2>
|
||||
<p class="mb-3 text-sm text-[var(--text-secondary)]">列来自当前查询输出。身份列和观测时间都可以不选;不选身份列时,多行结果只采用第一行。</p>
|
||||
<ElTable :data="columns" row-key="source_column_name">
|
||||
<ElTableColumn prop="source_column_name" label="查询列" min-width="180" />
|
||||
<ElTableColumn label="类型" width="100">
|
||||
<template #default="{ row }">{{ typeLabel[row.value_type] ?? row.value_type }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="身份列" width="100" align="center">
|
||||
<template #default="{ row }"><ElCheckbox v-model="row.is_identity" /></template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="观测时间" width="110" align="center">
|
||||
<template #default="{ row }"><ElCheckbox v-model="row.is_observation_time" :disabled="row.value_type !== 'datetime' && !row.is_observation_time" /></template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="数值换算" min-width="240">
|
||||
<template #default="{ row }">
|
||||
<div v-if="row.value_type === 'number'" class="flex items-center gap-2">
|
||||
<span>×</span>
|
||||
<ElInput :model-value="row.numeric_multiply ?? ''" class="w-24" placeholder="乘数" @update:model-value="row.numeric_multiply = $event === '' ? null : String($event)" />
|
||||
<span>+</span>
|
||||
<ElInput :model-value="row.numeric_offset ?? ''" class="w-24" placeholder="偏移" @update:model-value="row.numeric_offset = $event === '' ? null : String($event)" />
|
||||
</div>
|
||||
<span v-else class="text-[var(--text-secondary)]">—</span>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
|
||||
<h2 class="mb-2 mt-8 text-base font-semibold">判断规则</h2>
|
||||
<p class="mb-3 text-sm text-[var(--text-secondary)]">用条件描述什么情况算异常。并且:有一条正常则整体正常;或者:有一条异常则整体异常。缺值或无法比较时为未知。</p>
|
||||
<RuleGroup :node="root" :columns="columns" :depth="1" root />
|
||||
<div class="mt-3 rounded-lg bg-[var(--fill-subtle,#f5f9fa)] px-4 py-3 text-sm">异常条件:{{ conditionSummary(root) }}</div>
|
||||
|
||||
<h2 class="mb-2 mt-8 text-base font-semibold">试算</h2>
|
||||
<div class="mb-3 flex gap-2">
|
||||
<ElButton :type="trialMode === 'query' ? 'primary' : 'default'" @click="trialMode = 'query'">用查询数据</ElButton>
|
||||
<ElButton :type="trialMode === 'manual' ? 'primary' : 'default'" @click="trialMode = 'manual'">手填数据</ElButton>
|
||||
</div>
|
||||
<div v-if="trialMode === 'query'" class="mb-3">
|
||||
<p class="mb-3 text-sm text-[var(--text-secondary)]">使用查询「{{ queryName }}」在数据源里的结果。默认取前 10 条,可以改条数。留空的可选参数不会传给查询。</p>
|
||||
<div class="mb-3 flex flex-wrap items-end gap-3">
|
||||
<div v-for="spec in paramSpecs" :key="spec.name" class="w-56">
|
||||
<div class="mb-1 text-sm">{{ spec.name }}<span v-if="spec.required" class="text-[var(--color-danger,#cf222e)]"> *</span></div>
|
||||
<ElInput v-model="paramValues[spec.name]" :placeholder="spec.required ? '必填' : '可留空'" />
|
||||
</div>
|
||||
<div class="w-28">
|
||||
<div class="mb-1 text-sm">条数</div>
|
||||
<ElInput v-model="rowLimit" type="number" data-testid="mapping-row-limit" />
|
||||
</div>
|
||||
<ElButton type="primary" data-testid="mapping-trial-query" @click="trialFromQuery">试算</ElButton>
|
||||
</div>
|
||||
<p v-if="paramError" class="text-sm text-[var(--color-danger,#cf222e)]">{{ paramError }}</p>
|
||||
</div>
|
||||
<div v-else class="mb-3">
|
||||
<p class="mb-3 text-sm text-[var(--text-secondary)]">手填查询输出行。样例里有能判异常、正常的行,也有缺值和没有时区的时间。空样例会得到空结果。</p>
|
||||
<div class="mb-3 flex gap-2">
|
||||
<ElButton @click="fillRows">能判出结果的样例</ElButton>
|
||||
<ElButton @click="fillFailure">会失败的空样例</ElButton>
|
||||
</div>
|
||||
<ElInput v-model="rowsJson" type="textarea" :rows="8" data-testid="mapping-rows" />
|
||||
<ElButton class="mt-3" data-testid="mapping-trial" @click="trial">试算</ElButton>
|
||||
</div>
|
||||
<ElAlert v-if="saveError" class="mt-3" :title="saveError" type="error" data-testid="mapping-save-error" :closable="false" />
|
||||
<ElAlert v-if="skippedRows > 0" class="mt-3" :title="`未勾选身份列时采用第一行,其余 ${skippedRows} 行未采用。`" type="warning" data-testid="mapping-skip" :closable="false" />
|
||||
<ElAlert v-if="outcome" class="mt-3" data-testid="mapping-outcome" :title="conclusion(outcome)" :type="outcome === 'abnormal' || outcome === 'error' ? 'error' : outcome === 'normal' ? 'success' : 'warning'" :closable="false" />
|
||||
<ElTable v-if="trialTable.length" class="mt-3" :data="trialTable" data-testid="mapping-trial-table">
|
||||
<ElTableColumn type="index" label="#" width="58" />
|
||||
<ElTableColumn v-for="name in trialColumns" :key="name" :label="name" min-width="140" show-overflow-tooltip>
|
||||
<template #default="{ row }">{{ cellText(row[name]) }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="结论" width="110" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<ElTag :type="tagType(String(row.__code))" effect="light">{{ conclusion(String(row.__code)) }}</ElTag>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
</main>
|
||||
<footer class="flex shrink-0 justify-center gap-2 border-t p-3">
|
||||
<ElButton @click="router.push('/mappings')">返回列表</ElButton>
|
||||
<ElButton @click="switching = true">切换版本</ElButton>
|
||||
<ElButton type="primary" data-testid="mapping-save" @click="save">另存为新版本</ElButton>
|
||||
</footer>
|
||||
<ElDialog v-model="switching" title="切换版本" width="680px" align-center append-to-body :close-on-click-modal="false">
|
||||
<p class="mb-3 text-sm text-[var(--text-secondary)]">激活仅切换当前版本;以此编辑不会修改历史版本。</p>
|
||||
<div v-for="version in versions" :key="version" class="mb-2 flex items-center gap-3">
|
||||
<span class="w-16 font-mono">v{{ version }}</span>
|
||||
<ElButton link type="primary" @click="activateMappingVersion(id, version).then((data) => currentVersion = data.current_version_no)">激活</ElButton>
|
||||
<ElButton link type="primary" @click="load(version).then(() => switching = false)">以此编辑</ElButton>
|
||||
</div>
|
||||
</ElDialog>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,94 @@
|
||||
<script setup lang="ts">
|
||||
/** Mapping list and shared-version editor entrypoint; historical versions are opened read-only. */
|
||||
import { onMounted, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
import { ElButton, ElDialog, ElInput, ElOption, ElSelect, ElTable, ElTableColumn } from "element-plus";
|
||||
import { versionLabel } from "../queries/format";
|
||||
import { createMapping, listMappings, type MappingSummary } from "./client";
|
||||
import { listQueries } from "../queries/client";
|
||||
|
||||
const name = ref("");
|
||||
const query = ref("");
|
||||
const rows = ref<MappingSummary[]>([]);
|
||||
const router = useRouter();
|
||||
const createOpen = ref(false);
|
||||
const selectedQuery = ref("");
|
||||
const queries = ref<{ id: string; name: string }[]>([]);
|
||||
const createError = ref("");
|
||||
const loadError = ref("");
|
||||
async function load() {
|
||||
loadError.value = "";
|
||||
try {
|
||||
rows.value = (await listMappings({ name: name.value, query: query.value })).items;
|
||||
} catch {
|
||||
rows.value = [];
|
||||
loadError.value = "映射列表没有加载出来。";
|
||||
}
|
||||
}
|
||||
async function openCreate() {
|
||||
createError.value = "";
|
||||
selectedQuery.value = "";
|
||||
createOpen.value = true;
|
||||
try {
|
||||
queries.value = (await listQueries({ page: 1, page_size: 100 })).items ?? [];
|
||||
if (queries.value.length === 0) createError.value = "还没有查询。请先到「查询」里新建一条,再回来建映射。";
|
||||
} catch {
|
||||
queries.value = [];
|
||||
createError.value = "查询列表没有加载出来,请再点一次新建。";
|
||||
}
|
||||
}
|
||||
async function create() {
|
||||
if (!selectedQuery.value) {
|
||||
createError.value = "请先选择一条查询。";
|
||||
return;
|
||||
}
|
||||
createError.value = "";
|
||||
try {
|
||||
const created = await createMapping(selectedQuery.value);
|
||||
createOpen.value = false;
|
||||
await router.push(`/mappings/${created.id}`);
|
||||
} catch {
|
||||
createError.value = "没有创建成功。请确认这条查询还能用,然后再试一次。";
|
||||
}
|
||||
}
|
||||
onMounted(load);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section class="flex h-full flex-col p-8">
|
||||
<div class="mb-4 flex gap-2">
|
||||
<ElInput v-model="name" placeholder="名称" class="w-64" />
|
||||
<ElInput v-model="query" placeholder="查询" class="w-48" />
|
||||
<ElButton @click="load">查询</ElButton><ElButton @click="name = ''; query = ''; load()">重置</ElButton>
|
||||
<span class="flex-1" /><ElButton type="primary" @click="openCreate">新建</ElButton>
|
||||
</div>
|
||||
<p v-if="loadError" class="mb-3 text-sm text-[var(--color-danger,#cf222e)]">{{ loadError }}</p>
|
||||
<ElTable :data="rows" row-key="id" class="min-h-0 flex-1" height="100%" empty-text="暂无映射" data-testid="mapping-table">
|
||||
<ElTableColumn prop="name" label="名称" min-width="220" show-overflow-tooltip />
|
||||
<ElTableColumn prop="query" label="查询" min-width="220" show-overflow-tooltip />
|
||||
<ElTableColumn label="当前版本" width="120">
|
||||
<template #default="{ row }">{{ versionLabel(row.current_version_no) ?? "—" }}</template>
|
||||
</ElTableColumn>
|
||||
<ElTableColumn label="操作" width="248" align="right" fixed="right">
|
||||
<template #default="{ row }">
|
||||
<div class="whitespace-nowrap">
|
||||
<ElButton link type="primary" data-testid="mapping-open" @click="router.push(`/mappings/${row.id}`)">打开</ElButton>
|
||||
<ElButton link type="primary" @click="router.push(`/mappings/${row.id}?switch=1`)">切换版本</ElButton>
|
||||
<ElButton link type="primary" @click="router.push(`/mappings/${row.id}?trial=1`)">试算</ElButton>
|
||||
</div>
|
||||
</template>
|
||||
</ElTableColumn>
|
||||
</ElTable>
|
||||
<ElDialog v-model="createOpen" title="新建映射" width="480px" align-center append-to-body :close-on-click-modal="false">
|
||||
<p class="mb-2 text-sm text-[var(--text-secondary)]">选择这条映射要使用的查询。字段会按该查询的输出列带出来。</p>
|
||||
<ElSelect v-model="selectedQuery" class="w-full" placeholder="选择查询" filterable :teleported="false">
|
||||
<ElOption v-for="item in queries" :key="item.id" :label="item.name" :value="item.id" />
|
||||
</ElSelect>
|
||||
<p v-if="createError" class="mt-3 text-sm text-[var(--color-danger,#cf222e)]">{{ createError }}</p>
|
||||
<template #footer>
|
||||
<ElButton @click="createOpen = false">取消</ElButton>
|
||||
<ElButton type="primary" @click="create">新建</ElButton>
|
||||
</template>
|
||||
</ElDialog>
|
||||
</section>
|
||||
</template>
|
||||
@@ -0,0 +1,81 @@
|
||||
<script setup lang="ts">
|
||||
/** One condition group: relation, leaf rows, and optional nested groups. Depth 4 matches the API. */
|
||||
import { ElButton, ElInput, ElOption, ElSelect } from "element-plus";
|
||||
import { blankLeaf, operatorsFor, type ColumnRef, type GroupNode, type LeafNode } from "./condition";
|
||||
import RuleGroup from "./RuleGroup.vue";
|
||||
|
||||
const props = defineProps<{ node: GroupNode; columns: ColumnRef[]; depth: number; root?: boolean }>();
|
||||
const emit = defineEmits<{ remove: [] }>();
|
||||
|
||||
function columnType(name: string): string {
|
||||
return props.columns.find((column) => column.source_column_name === name)?.value_type ?? "string";
|
||||
}
|
||||
|
||||
function onColumn(leaf: LeafNode): void {
|
||||
if (!operatorsFor(columnType(leaf.column)).some((item) => item.value === leaf.operator)) leaf.operator = "eq";
|
||||
}
|
||||
|
||||
function addLeaf(): void {
|
||||
props.node.items.push(blankLeaf(props.columns[0]?.source_column_name ?? ""));
|
||||
}
|
||||
|
||||
function addGroup(): void {
|
||||
if (props.depth >= 4) return;
|
||||
props.node.items.push({ kind: "group", op: "and", items: [blankLeaf(props.columns[0]?.source_column_name ?? "")] });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="rounded-lg border border-[var(--border-default)] bg-white p-3">
|
||||
<div class="mb-3 flex flex-wrap items-center gap-3">
|
||||
<div class="w-56 shrink-0">
|
||||
<ElSelect v-model="node.op" class="!w-full" :data-testid="root ? 'mapping-op' : undefined" aria-label="条件组关系">
|
||||
<ElOption value="and" label="全部满足 · 并且" />
|
||||
<ElOption value="or" label="任一满足 · 或者" />
|
||||
</ElSelect>
|
||||
</div>
|
||||
<span class="text-sm text-[var(--text-secondary)]">满足条件表示异常</span>
|
||||
<ElButton v-if="!root" link type="danger" @click="emit('remove')">移除组</ElButton>
|
||||
</div>
|
||||
<div v-for="(item, index) in node.items" :key="index" class="mb-2">
|
||||
<RuleGroup
|
||||
v-if="item.kind === 'group'"
|
||||
:node="item"
|
||||
:columns="columns"
|
||||
:depth="depth + 1"
|
||||
@remove="node.items.splice(index, 1)"
|
||||
/>
|
||||
<div v-else class="flex flex-wrap items-center gap-2">
|
||||
<div class="w-56 shrink-0">
|
||||
<ElSelect v-model="item.column" class="!w-full" filterable aria-label="判断字段" :data-testid="root ? `mapping-column-${index}` : undefined" @change="onColumn(item)">
|
||||
<ElOption v-for="column in columns" :key="column.source_column_name" :label="column.source_column_name" :value="column.source_column_name" />
|
||||
</ElSelect>
|
||||
</div>
|
||||
<div class="w-44 shrink-0">
|
||||
<ElSelect v-model="item.operator" class="!w-full" aria-label="运算符">
|
||||
<ElOption v-for="option in operatorsFor(columnType(item.column))" :key="option.value" :label="option.label" :value="option.value" />
|
||||
</ElSelect>
|
||||
</div>
|
||||
<div class="w-48 shrink-0">
|
||||
<ElSelect v-if="columnType(item.column) === 'boolean'" v-model="item.value" class="!w-full" aria-label="比较值" :data-testid="root ? `mapping-value-${index}` : undefined">
|
||||
<ElOption value="true" label="是" />
|
||||
<ElOption value="false" label="否" />
|
||||
</ElSelect>
|
||||
<ElInput
|
||||
v-else
|
||||
v-model="item.value"
|
||||
class="!w-full"
|
||||
aria-label="比较值"
|
||||
:placeholder="columnType(item.column) === 'datetime' ? '2026-11-19T09:00:00+08:00' : '比较值'"
|
||||
:data-testid="root ? `mapping-value-${index}` : undefined"
|
||||
/>
|
||||
</div>
|
||||
<ElButton link type="danger" aria-label="移除条件" @click="node.items.splice(index, 1)">移除</ElButton>
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-1 flex gap-2">
|
||||
<ElButton :data-testid="root ? 'mapping-add-condition' : undefined" @click="addLeaf">+ 添加条件</ElButton>
|
||||
<ElButton v-if="depth < 4" @click="addGroup">+ 添加条件组</ElButton>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,19 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
vi.mock("@watchman/api", () => ({ requestJson: vi.fn() }));
|
||||
import { requestJson } from "@watchman/api";
|
||||
import { activateMappingVersion, saveMappingVersion } from "./client";
|
||||
|
||||
const mocked = vi.mocked(requestJson);
|
||||
describe("mapping version client", () => {
|
||||
beforeEach(() => { mocked.mockReset(); mocked.mockResolvedValue({}); });
|
||||
it("saves columns and the shared condition tree together", async () => {
|
||||
await saveMappingVersion("m1", { columns: [], condition_tree: { column: "n", operator: "eq", value: 1 } });
|
||||
const [, init] = mocked.mock.calls[0];
|
||||
expect(JSON.parse(String((init as RequestInit).body))).toEqual({ columns: [], condition_tree: { column: "n", operator: "eq", value: 1 } });
|
||||
});
|
||||
it("activates without sending a new tree", async () => {
|
||||
await activateMappingVersion("m1", 2);
|
||||
const [, init] = mocked.mock.calls[0];
|
||||
expect((init as RequestInit).body).toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/** HTTP calls for shared mapping-and-condition versions. */
|
||||
import { api } from "../api";
|
||||
|
||||
const headers = { "Content-Type": "application/json" };
|
||||
const base = (id: string) => `/mappings/${encodeURIComponent(id)}`;
|
||||
|
||||
export type MappingColumn = { source_column_name: string; value_type: string; is_identity: boolean; is_observation_time: boolean; numeric_multiply: string | null; numeric_offset: string | null };
|
||||
export type MappingVersionPayload = { columns: MappingColumn[]; condition_tree: Record<string, unknown> | null };
|
||||
export type MappingSummary = { id: string; name: string; query: string; current_version_no: number | null };
|
||||
|
||||
export function saveMappingVersion(id: string, payload: MappingVersionPayload) {
|
||||
return api(`${base(id)}/versions`, { method: "POST", headers, body: JSON.stringify(payload) });
|
||||
}
|
||||
export function activateMappingVersion(id: string, versionNo: number) {
|
||||
return api<{ current_version_no: number }>(`${base(id)}/versions/${versionNo}/activate`, { method: "POST" });
|
||||
}
|
||||
export function getMappingVersion(id: string, versionNo: number) {
|
||||
return api<MappingVersionPayload & { version_no: number }>(`${base(id)}/versions/${versionNo}`);
|
||||
}
|
||||
export function getMapping(id: string) {
|
||||
return api<{ id: string; query_definition_id: string; current_version_no: number | null }>(base(id));
|
||||
}
|
||||
export function trialMapping(id: string, payload: { rows: Record<string, unknown>[]; condition_tree?: Record<string, unknown> }) {
|
||||
return api(`${base(id)}/trial`, { method: "POST", headers, body: JSON.stringify(payload) });
|
||||
}
|
||||
export function trialMappingQuery(id: string, payload: { query_params?: Record<string, unknown>; row_limit?: number; condition_tree?: Record<string, unknown> }) {
|
||||
return api(`${base(id)}/trial-query`, { method: "POST", headers, body: JSON.stringify(payload) });
|
||||
}
|
||||
export function listMappings(params: { name?: string; query?: string } = {}) {
|
||||
const search = new URLSearchParams();
|
||||
if (params.name) search.set("name", params.name);
|
||||
if (params.query) search.set("query", params.query);
|
||||
return api<{ items: MappingSummary[] }>(`/mappings${search.size ? `?${search}` : ""}`);
|
||||
}
|
||||
export function createMapping(query_definition_id: string) {
|
||||
return api<{ id: string }>("/mappings", { method: "POST", headers, body: JSON.stringify({ query_definition_id }) });
|
||||
}
|
||||
export function listMappingVersions(id: string) {
|
||||
return api<{ items: { version_no: number }[] }>(`${base(id)}/versions`);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { conditionSummary, operatorsFor, treeForApi, treeFromApi, type GroupNode } from "./condition";
|
||||
|
||||
const columns = [
|
||||
{ source_column_name: "reading_value", value_type: "number" },
|
||||
{ source_column_name: "metric", value_type: "string" },
|
||||
];
|
||||
|
||||
describe("condition tree", () => {
|
||||
it("shows a single saved leaf as one 并且 group and saves it back as a leaf", () => {
|
||||
const group = treeFromApi({ column: "reading_value", operator: "gt", value: 85 }, "reading_value");
|
||||
expect(group).toEqual({ kind: "group", op: "and", items: [{ kind: "leaf", column: "reading_value", operator: "gt", value: "85" }] });
|
||||
expect(treeForApi(group, columns)).toEqual({ column: "reading_value", operator: "gt", value: 85 });
|
||||
});
|
||||
|
||||
it("keeps an and/or group and a nested group", () => {
|
||||
const saved = {
|
||||
op: "and",
|
||||
items: [
|
||||
{ column: "metric", operator: "eq", value: "temp_c" },
|
||||
{ op: "or", items: [{ column: "reading_value", operator: "gt", value: 85 }, { column: "reading_value", operator: "lt", value: 10 }] },
|
||||
],
|
||||
};
|
||||
const group = treeFromApi(saved, "metric");
|
||||
expect(group.items[1]).toMatchObject({ kind: "group", op: "or" });
|
||||
expect(treeForApi(group, columns)).toEqual(saved);
|
||||
});
|
||||
|
||||
it("limits string columns to equal and not-equal", () => {
|
||||
expect(operatorsFor("string").map((item) => item.value)).toEqual(["eq", "ne"]);
|
||||
expect(operatorsFor("number").map((item) => item.value)).toContain("gt");
|
||||
});
|
||||
|
||||
it("writes the abnormal condition in words", () => {
|
||||
const group: GroupNode = {
|
||||
kind: "group",
|
||||
op: "and",
|
||||
items: [
|
||||
{ kind: "leaf", column: "metric", operator: "eq", value: "temp_c" },
|
||||
{ kind: "leaf", column: "reading_value", operator: "gt", value: "85" },
|
||||
],
|
||||
};
|
||||
expect(conditionSummary(group)).toBe("(metric 等于 temp_c 且 reading_value 大于 85)");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,88 @@
|
||||
/** Condition tree editing. The saved shape stays the API tree; the screen always edits a group. */
|
||||
|
||||
export type LeafNode = { kind: "leaf"; column: string; operator: string; value: string };
|
||||
export type GroupNode = { kind: "group"; op: "and" | "or"; items: ConditionNode[] };
|
||||
export type ConditionNode = LeafNode | GroupNode;
|
||||
export type ColumnRef = { source_column_name: string; value_type: string };
|
||||
|
||||
export const OPERATOR_LABELS: { value: string; label: string; word: string }[] = [
|
||||
{ value: "eq", label: "等于 =", word: "等于" },
|
||||
{ value: "ne", label: "不等于 ≠", word: "不等于" },
|
||||
{ value: "gt", label: "大于 >", word: "大于" },
|
||||
{ value: "gte", label: "大于等于 ≥", word: "大于等于" },
|
||||
{ value: "lt", label: "小于 <", word: "小于" },
|
||||
{ value: "lte", label: "小于等于 ≤", word: "小于等于" },
|
||||
];
|
||||
|
||||
const ORDER_OPERATORS = new Set(["gt", "gte", "lt", "lte"]);
|
||||
|
||||
export function operatorsFor(valueType: string): { value: string; label: string }[] {
|
||||
const ordered = valueType === "string" || valueType === "boolean"
|
||||
? OPERATOR_LABELS.filter((item) => !ORDER_OPERATORS.has(item.value))
|
||||
: OPERATOR_LABELS;
|
||||
return ordered.map(({ value, label }) => ({ value, label }));
|
||||
}
|
||||
|
||||
export function blankLeaf(column: string): LeafNode {
|
||||
return { kind: "leaf", column, operator: "eq", value: "" };
|
||||
}
|
||||
|
||||
export function blankGroup(column: string): GroupNode {
|
||||
return { kind: "group", op: "and", items: [blankLeaf(column)] };
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function nodeFromApi(tree: unknown, fallbackColumn: string): ConditionNode {
|
||||
if (!isRecord(tree)) return blankLeaf(fallbackColumn);
|
||||
if (typeof tree.column === "string") {
|
||||
return {
|
||||
kind: "leaf",
|
||||
column: tree.column,
|
||||
operator: typeof tree.operator === "string" ? tree.operator : "eq",
|
||||
value: tree.value == null ? "" : String(tree.value),
|
||||
};
|
||||
}
|
||||
const items = Array.isArray(tree.items) ? tree.items.map((item) => nodeFromApi(item, fallbackColumn)) : [];
|
||||
return { kind: "group", op: tree.op === "or" ? "or" : "and", items: items.length ? items : [blankLeaf(fallbackColumn)] };
|
||||
}
|
||||
|
||||
/** Always return a group so the editor has one relation control, even for a saved single leaf. */
|
||||
export function treeFromApi(tree: unknown, fallbackColumn: string): GroupNode {
|
||||
const node = nodeFromApi(tree, fallbackColumn);
|
||||
return node.kind === "group" ? node : { kind: "group", op: "and", items: [node] };
|
||||
}
|
||||
|
||||
function leafForApi(leaf: LeafNode, columns: ColumnRef[]): Record<string, unknown> {
|
||||
const column = columns.find((item) => item.source_column_name === leaf.column);
|
||||
if (column?.value_type === "number") {
|
||||
if (leaf.value.trim() === "" || Number.isNaN(Number(leaf.value))) throw new Error("比较值还没填好");
|
||||
return { column: leaf.column, operator: leaf.operator, value: Number(leaf.value) };
|
||||
}
|
||||
if (column?.value_type === "boolean") return { column: leaf.column, operator: leaf.operator, value: leaf.value === "true" };
|
||||
return { column: leaf.column, operator: leaf.operator, value: leaf.value };
|
||||
}
|
||||
|
||||
function nodeForApi(node: ConditionNode, columns: ColumnRef[]): Record<string, unknown> {
|
||||
if (node.kind === "leaf") return leafForApi(node, columns);
|
||||
if (!node.items.length) throw new Error("至少要有一条判断条件");
|
||||
const items = node.items.map((item) => nodeForApi(item, columns));
|
||||
if (items.length === 1 && node.op === "and" && node.items[0]?.kind === "leaf") return items[0];
|
||||
return { op: node.op, items };
|
||||
}
|
||||
|
||||
export function treeForApi(group: GroupNode, columns: ColumnRef[]): Record<string, unknown> {
|
||||
return nodeForApi(group, columns);
|
||||
}
|
||||
|
||||
export function conditionSummary(node: ConditionNode): string {
|
||||
if (node.kind === "leaf") {
|
||||
const word = OPERATOR_LABELS.find((item) => item.value === node.operator)?.word ?? node.operator;
|
||||
return `${node.column || "未选字段"} ${word} ${node.value === "" ? "(未填)" : node.value}`;
|
||||
}
|
||||
if (!node.items.length) return "未配置";
|
||||
const text = node.items.map((item) => conditionSummary(item)).join(node.op === "or" ? " 或 " : " 且 ");
|
||||
return node.items.length > 1 ? `(${text})` : text;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { seedColumns } from "./seed";
|
||||
|
||||
describe("seedColumns", () => {
|
||||
it("uses query output names and never invents a placeholder column", () => {
|
||||
expect(seedColumns([
|
||||
{ name: "temperature", type: "number" },
|
||||
{ name: "count", type: "integer" },
|
||||
{ name: "note", type: "nullish" },
|
||||
])).toEqual([
|
||||
{ source_column_name: "temperature", value_type: "number", is_identity: false, is_observation_time: false, numeric_multiply: null, numeric_offset: null },
|
||||
{ source_column_name: "count", value_type: "number", is_identity: false, is_observation_time: false, numeric_multiply: null, numeric_offset: null },
|
||||
{ source_column_name: "note", value_type: "string", is_identity: false, is_observation_time: false, numeric_multiply: null, numeric_offset: null },
|
||||
]);
|
||||
expect(seedColumns([]).some((column) => column.source_column_name === "n")).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
/** Turn a query output contract into mapping columns. Integer becomes number; nullish becomes string. */
|
||||
import type { OutputType } from "../queries/types";
|
||||
import type { MappingColumn } from "./client";
|
||||
|
||||
const DIRECT = new Set(["number", "string", "boolean", "datetime"]);
|
||||
|
||||
export function seedColumns(outputs: { name: string; type: OutputType }[]): MappingColumn[] {
|
||||
return outputs
|
||||
.filter((item) => item.name)
|
||||
.map((item) => ({
|
||||
source_column_name: item.name,
|
||||
value_type: item.type === "integer" || item.type === "number" ? "number" : DIRECT.has(item.type) ? item.type : "string",
|
||||
is_identity: false,
|
||||
is_observation_time: false,
|
||||
numeric_multiply: null,
|
||||
numeric_offset: null,
|
||||
}));
|
||||
}
|
||||
@@ -13,6 +13,8 @@ import QueryEdit from "./queries/QueryEdit.vue";
|
||||
import QueryGate from "./queries/QueryGate.vue";
|
||||
import QueryList from "./queries/QueryList.vue";
|
||||
import QueryVersionView from "./queries/QueryVersionView.vue";
|
||||
import MappingList from "./mappings/MappingList.vue";
|
||||
import MappingEdit from "./mappings/MappingEdit.vue";
|
||||
|
||||
export function createAppRouter(history: RouterHistory = createWebHashHistory()) {
|
||||
return createRouter({
|
||||
@@ -73,6 +75,8 @@ export function createAppRouter(history: RouterHistory = createWebHashHistory())
|
||||
},
|
||||
],
|
||||
},
|
||||
{ path: "/mappings", name: "mapping-list", component: MappingList, meta: { crumbs: ["mappings"] } },
|
||||
{ path: "/mappings/:id", name: "mapping-detail", component: MappingEdit, meta: { crumbs: ["mappings", "detail"] } },
|
||||
{ path: "/:pathMatch(.*)*", redirect: "/" },
|
||||
],
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ export default defineConfig({
|
||||
"/auth": "http://127.0.0.1:8000",
|
||||
"/datasources": "http://127.0.0.1:8000",
|
||||
"/queries": "http://127.0.0.1:8000",
|
||||
"/mappings": "http://127.0.0.1:8000",
|
||||
},
|
||||
},
|
||||
});
|
||||