Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .factory/factory-local.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@
"review_basis": "CONTRIBUTING.md 规格引用(wop-specs/docs/specs/wop-sdk-spec.md)+ 既有测试形态",
"final_gate_cmd": "scripts/run_tests.sh --no-lock",
"pr_review_skills": [],
"upstream_repo": "im47cn/awesome-rules",
"upstream_path": "~/sources/awesome-rules",
"upstream_repo": "im47cn/awesome-factory",
"upstream_path": "~/sources/awesome-factory",
"port_point": "011d8d8c",
"feedback_branch_prefix": "feedback/wop-python-sdk"
}
3 changes: 3 additions & 0 deletions .factory/factory_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1444,6 +1444,9 @@ def main(argv: list[str]) -> int:
# 不可读/内容畸形 = 死(SIGKILL 残锁过期同判)。退出码 0=活 1=死
# 2=参数错。PG 形态(SUPABASE_DB)租约在库中,调用方不得用本
# 命令的输出断言死活(保守 unknown)。
if len(argv) < 3:
print("lease-fresh: 缺锁文件路径参数", file=sys.stderr)
return 2
Comment on lines +1447 to +1449

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 中 · 多余的租约参数看起来有效

当 lease-fresh 命令接收到锁路径以及一个或多个额外参数时,main 只读取 argv[2] 并忽略其余参数,因此格式错误的调用会返回锁的存活/失效状态,而不是文档规定的参数错误状态码 2;调用方可能会误以为这是有效的租约检查结果。

要求恰好提供一个锁路径参数,其他任何参数数量都返回 2。

面向 AI 代理的提示
在 `.factory/factory_lib.py` 第 1447–1449 行:

**多余的租约参数看起来有效**

当 `lease-fresh` 命令接收到锁路径以及一个或多个额外参数时,`main` 只读取 `argv[2]` 并忽略其余参数,因此格式错误的调用会返回锁的存活/失效状态,而不是文档规定的参数错误状态码 2;调用方可能会误以为这是有效的租约检查结果。

要求恰好提供一个锁路径参数,其他任何参数数量都返回 2。
Original comment in English

🟡 Medium · Extra lease arguments look valid

When the lease-fresh command is called with a lock path and one or more extra arguments, main reads only argv[2] and ignores remaining arguments, so a malformed invocation returns the lock’s live/dead status instead of the documented parameter-error status 2; a caller can mistake the result for a valid lease check.

Require exactly one lock-path argument and return 2 for any other argument count.

Prompt for AI agents
In `.factory/factory_lib.py` at lines 1447-1449:

**Extra lease arguments look valid**

When the `lease-fresh` command is called with a lock path and one or more extra arguments, `main` reads only `argv[2]` and ignores remaining arguments, so a malformed invocation returns the lock’s live/dead status instead of the documented parameter-error status 2; a caller can mistake the result for a valid lease check.

Require exactly one lock-path argument and return 2 for any other argument count.

lock = Path(argv[2])
try:
line = lock.read_text(encoding="utf-8").strip().splitlines()[0]
Expand Down
9 changes: 8 additions & 1 deletion .factory/hosting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1097,10 +1097,17 @@ def _add_label_lock(self, p, name):
time.sleep(0.05)
continue
break
with contextlib.suppress(OSError):
try:
with open(os.path.join(lock_dir, "pid"), "w",
encoding="ascii") as fh:
fh.write(str(os.getpid()))
except OSError as e:
# 无 pid 残锁会被判陈旧致另一进程接管(双写):释放并拒持锁
shutil.rmtree(lock_dir, ignore_errors=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟠 高 · 替换后的锁被删除

如果 pid 文件创建或写入失败,而不含 pid 的目录在陈旧锁宽限期过后仍然存在,并且另一个调用者重新获取了该锁,OSError 处理程序就会按路径调用 shutil.rmtree(lock_dir),却不验证所有权,从而删除新所有者正在使用的锁;随后另一个调用者会进入临界区,并可能发布重复标签。

只有在确认 lock_dir 仍是此写入者创建的锁目录后,才将其删除。

面向 AI 代理的提示
在 `.factory/hosting.py` 第 1106 行:

**替换后的锁被删除**

如果 pid 文件创建或写入失败,而不含 pid 的目录在陈旧锁宽限期过后仍然存在,并且另一个调用者重新获取了该锁,OSError 处理程序就会按路径调用 `shutil.rmtree(lock_dir)`,却不验证所有权,从而删除新所有者正在使用的锁;随后另一个调用者会进入临界区,并可能发布重复标签。

只有在确认 `lock_dir` 仍是此写入者创建的锁目录后,才将其删除。
Original comment in English

🟠 High · Replacement lock gets deleted

When pid-file creation or writing fails after the pid-less directory outlives the stale-lock grace period and another caller reclaims it, the OSError handler calls shutil.rmtree(lock_dir) by pathname without verifying ownership, deleting the replacement owner's active lock; another caller then enters the critical section and can post a duplicate label.

Remove lock_dir only after verifying it is still the lock directory created by this writer.

Prompt for AI agents
In `.factory/hosting.py` at line 1106:

**Replacement lock gets deleted**

When pid-file creation or writing fails after the pid-less directory outlives the stale-lock grace period and another caller reclaims it, the OSError handler calls `shutil.rmtree(lock_dir)` by pathname without verifying ownership, deleting the replacement owner's active lock; another caller then enters the critical section and can post a duplicate label.

Remove `lock_dir` only after verifying it is still the lock directory created by this writer.

raise HostingError(
f"add {name}: 锁 pid 写入失败({e}),fail-closed 拒持锁",
code=1,
) from e
try:
yield
finally:
Expand Down
10 changes: 10 additions & 0 deletions .factory/tests/test_factory_lib.py
Original file line number Diff line number Diff line change
Expand Up @@ -621,3 +621,13 @@ def test_multi_suite_roundtrip_read_d(self, capsys):
assert raw.endswith("\0")
assert raw[:-1].split("\0") == [
"skills/api-guard/scripts", "skills/doc review/scripts"]


class TestLeaseFreshArgv:
"""lease-fresh 缺锁路径参数 → exit 2(文档承诺 0=活 1=死 2=参数错):
裸 IndexError 走 exit 1 会被调用方当「锁死」接管活锁(awesome-
rules@80ce34ad 血统既有检查移植;wop-skills#25 审查实证)。"""

def test_missing_lock_path_returns_2(self, capsys):
assert main(["factory_lib.py", "lease-fresh"]) == 2
assert "缺锁文件路径参数" in capsys.readouterr().err
22 changes: 22 additions & 0 deletions .factory/tests/test_hosting.py
Original file line number Diff line number Diff line change
Expand Up @@ -1123,6 +1123,28 @@ def test_pidless_crash_dir_reclaimed_after_grace(self, monkeypatch, tmp_path):
assert os.path.isdir(lock_dir)
assert not os.path.isdir(lock_dir)

def test_pid_write_failure_refuses_lock(self, monkeypatch, tmp_path):
"""pid 写失败 → 释放锁目录 + HostingError fail-closed 拒持锁:
无 pid 裸持锁越过年龄宽限即被他进程判死接管 = 双写,且先者的
finally 清理会误删后继活锁(awesome-rules@80ce34ad 血统既有
保护移植;wop-skills#25 审查以 suppress 形态实证接管窗口)。"""
monkeypatch.setenv("FACTORY_LOCK_DIR", str(tmp_path))
ad = hosting.CodeupAdapter()
lock_dir = hosting._label_lock_dir(".", 7, "factory:needs-review")
real_open = open

def flaky_open(path, *a, **k):
if str(path).endswith("/pid"):
raise OSError("模拟写盘失败")
return real_open(path, *a, **k)

monkeypatch.setattr("builtins.open", flaky_open)
with pytest.raises(hosting.HostingError) as e:
with ad._add_label_lock(7, "factory:needs-review"):
pass
assert e.value.code == 1
assert not os.path.isdir(lock_dir) # 拒持锁前已释放,不留无 pid 残锁

def test_parallel_add_posts_exactly_once(self, monkeypatch, tmp_path):
"""并发回归(核心契约):两独立适配器实例(双进程/双链形态)
同仓同 PR 同名 add 并发——锁串行化 + 后到者锁内重预检幂等跳过,
Expand Down
4 changes: 2 additions & 2 deletions .factory/upstream-lock.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"anchor": "181618c32492fb41f5a2a14f52515449fdc1c9eb",
"anchor": "36a8749c9385dba755ef495e523f6a4358d483f9",
"upstream": "/Users/dreambt/sources/awesome-factory",
"synced_at": "2026-11-01T03:45:40+00:00"
"synced_at": "2026-11-09T05:51:11+00:00"
}
14 changes: 14 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -149,3 +149,17 @@ jobs:
run: pip install griffe==1.14.0
- name: API snapshot gate (regenerate to temp file, git diff --exit-code)
run: python3 scripts/check-api-snapshot.py

# ruff 静态检查(E4/E7/E9/F;配置见 pyproject.toml [tool.ruff],vendored .factory
# 已排除)。版本锁定保证检查集稳定;纯静态、秒级。
lint:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 中 · Lint 失败未被追踪

当 lint 任务失败,而 test 和 oldest-deps 通过时,notify-failure 和 notify-recovery 都不依赖 lint 任务,因此这次失败不会被追踪;即使工作流处于失败状态,恢复任务仍可能关闭现有的失败问题单。

将 lint 任务加入 notify-failure 和 notify-recovery 两者的依赖项中。

面向 AI 代理的提示
在 `.github/workflows/ci.yml` 第 155 行:

**Lint 失败未被追踪**

当 lint 任务失败,而 `test` 和 `oldest-deps` 通过时,`notify-failure` 和 `notify-recovery` 都不依赖 lint 任务,因此这次失败不会被追踪;即使工作流处于失败状态,恢复任务仍可能关闭现有的失败问题单。

将 lint 任务加入 `notify-failure` 和 `notify-recovery` 两者的依赖项中。
Original comment in English

🟡 Medium · Lint failures go untracked

When the lint job fails while test and oldest-deps pass, notify-failure and notify-recovery do not depend on the lint job, so the failure goes untracked and the recovery job can close an existing failure issue while the workflow is red.

Include the lint job in the dependencies of both notify-failure and notify-recovery.

Prompt for AI agents
In `.github/workflows/ci.yml` at line 155:

**Lint failures go untracked**

When the lint job fails while `test` and `oldest-deps` pass, `notify-failure` and `notify-recovery` do not depend on the lint job, so the failure goes untracked and the recovery job can close an existing failure issue while the workflow is red.

Include the lint job in the dependencies of both `notify-failure` and `notify-recovery`.

runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install pinned ruff
run: pip install ruff==0.17.3
- name: ruff check
run: ruff check .
6 changes: 3 additions & 3 deletions .lefthook/commitmsg-check.sh
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#!/usr/bin/env bash
# commit message 规范校验(awesome-rules tools/git 分发,由 lefthook 调用)
# 用法: bash .lefthook/commitmsg-check.sh <msg-file>
# 单一规则源: commitlint + 项目内 commitlint.config.js;缺 commitlint 时自动安装(一次性)。
# 单一规则源: commitlint + 项目内 commitlint.config.cjs;缺 commitlint 时自动安装(一次性)。
# 无 node/npm 时提示后放行 —— commit 钩子不阻塞环境问题,只拦规范违规。
set -u
MSG_FILE="${1:-}"
Expand Down Expand Up @@ -34,8 +34,8 @@ if [ -z "$CL" ]; then
fi

# 规则配置是分发物之一,缺失说明未跑 install.sh
[ -f "$(git rev-parse --show-toplevel)/commitlint.config.js" ] || {
echo "⚠ [commitmsg] 缺 commitlint.config.js,请跑 awesome-rules tools/git/install.sh;本次放行"
[ -f "$(git rev-parse --show-toplevel)/commitlint.config.cjs" ] || {
echo "⚠ [commitmsg] 缺 commitlint.config.cjs,请跑 awesome-rules tools/git/install.sh;本次放行"
exit 0
}

Expand Down
File renamed without changes.
15 changes: 14 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "wop-python-sdk"
version = "0.2.0"
version = "0.2.1"
description = "WOP 商户侧官方 Python SDK:协议核心(签名/摘要/数字信封/验签解密)+ 可插拔 HTTP 适配层"
readme = "README.md"
license = { text = "MIT" }
Expand Down Expand Up @@ -64,3 +64,16 @@ branch = true
[tool.coverage.report]
show_missing = true
precision = 2

[tool.ruff]
target-version = "py39"
line-length = 120
# .factory:从上游同步的 vendored 工厂副本,不在本仓维护,排除以免同步覆盖与噪声
extend-exclude = [".factory"]

[tool.ruff.lint]
# E4/E7/E9/F:语法/未定义名/未用导入变量/重定义等真实错误。
# E741/E702/E731 是历史代码纯风格(歧义单字母名、分号多语句、lambda 赋值——后者
# 是模块级公共 API `request_id_generator`,改为 def 会动 griffe API 快照),基线忽略。
select = ["E4", "E7", "E9", "F"]
ignore = ["E741", "E702", "E731"]
2 changes: 1 addition & 1 deletion src/wop_sdk/config/_loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import threading
from importlib import resources
from pathlib import Path
from typing import Callable, Dict, Optional, Union
from typing import Callable, Dict, Union

from ..errors import ConfigurationError
from ._models import WopSdkConfig
Expand Down
2 changes: 1 addition & 1 deletion src/wop_sdk/config/_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import json
import math
from typing import Any, Dict, List, Mapping, MutableMapping, Tuple
from typing import Any, Dict, List, Mapping, Tuple

from ..errors import ConfigurationError
from ._models import DEFAULT_EXPIRED_SECONDS, HttpClientSettings, WopSdkConfig
Expand Down
2 changes: 1 addition & 1 deletion src/wop_sdk/transport_discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import importlib.util
import os
from typing import Dict, List
from typing import Dict, List # noqa: F401 — List 是 wildcard 导出的 API 别名(tests/api_snapshot.json 记录),非内部使用

from .errors import ConfigurationError
from .transports import Transport, UrllibTransport
Expand Down
1 change: 0 additions & 1 deletion tests/test_bdd.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import base64
import hashlib
import json
import os
import re

import pytest
Expand Down
4 changes: 1 addition & 3 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,13 @@
from __future__ import annotations

import json
import os
import threading
from pathlib import Path
from unittest import mock

import pytest

from wop_sdk.client import WopClient, WopConfig
from wop_sdk.config import HttpClientSettings, WopSdkConfig, clear_cache, load, load_default
from wop_sdk.config import WopSdkConfig, clear_cache, load, load_default
from wop_sdk.config._parser import parse_config_json
from wop_sdk.config._validator import join_url, validate_api_path, validate_gateway_url
from wop_sdk.errors import ConfigurationError, WopGatewayResponseError
Expand Down
1 change: 0 additions & 1 deletion tests/test_config_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
transport_discovery 59%),PR 新增加载链未带测试。本文件按 term-missing 行号逐段闭合。
"""
import json
import sys
from pathlib import Path

import pytest
Expand Down
2 changes: 1 addition & 1 deletion tests/test_suites.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pytest

from wop_sdk.errors import SuiteParseError, UnsupportedSuiteError
from wop_sdk.suites import Suite, parse_suite
from wop_sdk.suites import parse_suite


class TestParsePositive:
Expand Down
Loading