fd-open-data-protocol 0.5.6__tar.gz → 0.5.7__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/PKG-INFO +12 -2
  2. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/README.md +11 -1
  3. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/__init__.py +1 -1
  4. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/schema.py +54 -2
  5. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/surface_report.py +47 -5
  6. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol.egg-info/PKG-INFO +12 -2
  7. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol.egg-info/SOURCES.txt +1 -0
  8. fd_open_data_protocol-0.5.7/tests/test_provider_plane.py +102 -0
  9. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_surface_report.py +83 -0
  10. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/LICENSE +0 -0
  11. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/conformance_adapter.py +0 -0
  12. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/constants.py +0 -0
  13. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/line_ops/__init__.py +0 -0
  14. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/line_ops/assemble.py +0 -0
  15. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/line_ops/auth_gate.py +0 -0
  16. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/line_ops/client.py +0 -0
  17. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/line_ops/config.py +0 -0
  18. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/line_ops/wellknown.py +0 -0
  19. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/loader.py +0 -0
  20. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/openalex_provider.py +0 -0
  21. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/provider.py +0 -0
  22. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/registry.py +0 -0
  23. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/registry_cli.py +0 -0
  24. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/registry_store.py +0 -0
  25. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/surface_selfcheck.py +0 -0
  26. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/alignment/foundation.yaml +0 -0
  27. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/concepts.yaml +0 -0
  28. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/crosswalks/datacommons-worldbank.yaml +0 -0
  29. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/entity_types.yaml +0 -0
  30. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/event_types.yaml +0 -0
  31. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/qualifiers.yaml +0 -0
  32. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/relation_types.yaml +0 -0
  33. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary/units.yaml +0 -0
  34. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol/vocabulary.py +0 -0
  35. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol.egg-info/dependency_links.txt +0 -0
  36. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol.egg-info/entry_points.txt +0 -0
  37. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol.egg-info/requires.txt +0 -0
  38. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/fd_open_data_protocol.egg-info/top_level.txt +0 -0
  39. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/pyproject.toml +0 -0
  40. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/setup.cfg +0 -0
  41. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_drift_inventory.py +0 -0
  42. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_line_ops.py +0 -0
  43. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_loader.py +0 -0
  44. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_openalex_provider.py +0 -0
  45. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_registry_pipeline.py +0 -0
  46. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_registry_schema.py +0 -0
  47. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_schema_vocabulary.py +0 -0
  48. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_surface_selfcheck.py +0 -0
  49. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_vocabulary.py +0 -0
  50. {fd_open_data_protocol-0.5.6 → fd_open_data_protocol-0.5.7}/tests/test_vocabulary_additive.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fd-open-data-protocol
3
- Version: 0.5.6
3
+ Version: 0.5.7
4
4
  Summary: The open-data datasource protocol: a manifest contract a datasource exposes to be ingested by fd-open-data-mcp (or any consumer).
5
5
  Author: FindDataOfficial
6
6
  License: MIT
@@ -51,6 +51,16 @@ fd-open-data-mcp migrate \
51
51
  fd-open-data-mcp serve
52
52
  ```
53
53
 
54
+ ## MCP surface self-report (self-healing)
55
+
56
+ `surface_report` 启动自报工具面给 registry。**失败不再封口**:单次上报耗尽重试后,
57
+ 后台任务按指数退避(60s 起、上限 30 分钟一次)持续复试,成功即停;进程内只有一个在飞
58
+ 任务(`ensure_started` 单次封口)。状态可经 `surface_state(mcp)` 区分 `never` / `retrying` /
59
+ `ok`、失败次数与最后尝试时刻,供检查器判断陈旧 vs 当前。
60
+
61
+ > **生效需重新发布 protocol 包并重建 5 个消费方镜像**(库打进镜像):`wire-ops-mcp`、
62
+ > `wanxing-ops-mcp`、`wire-build-mcp`、`lex-ops-mcp`、`fd-paper-trading`。
63
+
54
64
  ## The manifest
55
65
 
56
66
  A YAML/JSON file (or a Python module exposing `CATALOG`):
@@ -107,7 +117,7 @@ my-source = "my_pkg.catalog:CATALOG"
107
117
 
108
118
  ## Schema
109
119
 
110
- - **`DatasourceManifest`**: name, label, source_url, scanner_mode, ranking_seed, functions[], concepts[], entities[], entity_definitions[], relationships[], fetch.
120
+ - **`DatasourceManifest`**: name, label, source_url, scanner_mode, ranking_seed, functions[], concepts[], entities[], entity_definitions[], relationships[], fetch, `placement` (`cloud`|`edge`, default `cloud`), `credential` (`hub`|`user`, default `hub`), `provider_kind` (`data`|`process`|`both`, default `data`), capabilities[].
111
121
  - **`FunctionSpec`**: command, category, description, parameters[], columns[], frequency, verified.
112
122
  - **`ColumnSpec`**: name, type, description, meaning, semantic_type, `frequency` + `datasource` (column-level).
113
123
  - **`ConceptHint`**: column, concept, `entity_type`, `measure`, unit, frequency, confidence, `concept_family` (optional).
@@ -29,6 +29,16 @@ fd-open-data-mcp migrate \
29
29
  fd-open-data-mcp serve
30
30
  ```
31
31
 
32
+ ## MCP surface self-report (self-healing)
33
+
34
+ `surface_report` 启动自报工具面给 registry。**失败不再封口**:单次上报耗尽重试后,
35
+ 后台任务按指数退避(60s 起、上限 30 分钟一次)持续复试,成功即停;进程内只有一个在飞
36
+ 任务(`ensure_started` 单次封口)。状态可经 `surface_state(mcp)` 区分 `never` / `retrying` /
37
+ `ok`、失败次数与最后尝试时刻,供检查器判断陈旧 vs 当前。
38
+
39
+ > **生效需重新发布 protocol 包并重建 5 个消费方镜像**(库打进镜像):`wire-ops-mcp`、
40
+ > `wanxing-ops-mcp`、`wire-build-mcp`、`lex-ops-mcp`、`fd-paper-trading`。
41
+
32
42
  ## The manifest
33
43
 
34
44
  A YAML/JSON file (or a Python module exposing `CATALOG`):
@@ -85,7 +95,7 @@ my-source = "my_pkg.catalog:CATALOG"
85
95
 
86
96
  ## Schema
87
97
 
88
- - **`DatasourceManifest`**: name, label, source_url, scanner_mode, ranking_seed, functions[], concepts[], entities[], entity_definitions[], relationships[], fetch.
98
+ - **`DatasourceManifest`**: name, label, source_url, scanner_mode, ranking_seed, functions[], concepts[], entities[], entity_definitions[], relationships[], fetch, `placement` (`cloud`|`edge`, default `cloud`), `credential` (`hub`|`user`, default `hub`), `provider_kind` (`data`|`process`|`both`, default `data`), capabilities[].
89
99
  - **`FunctionSpec`**: command, category, description, parameters[], columns[], frequency, verified.
90
100
  - **`ColumnSpec`**: name, type, description, meaning, semantic_type, `frequency` + `datasource` (column-level).
91
101
  - **`ConceptHint`**: column, concept, `entity_type`, `measure`, unit, frequency, confidence, `concept_family` (optional).
@@ -5,4 +5,4 @@ concept hints + fetch reference) so that fd-open-data-mcp - or any consumer -
5
5
  can ingest it via ``register_datasource``. Ship one manifest file -> the
6
6
  datasource is added; no consumer-side wiring.
7
7
  """
8
- __version__ = "0.5.6"
8
+ __version__ = "0.5.7"
@@ -17,7 +17,7 @@ from __future__ import annotations
17
17
 
18
18
  import re
19
19
  from functools import lru_cache
20
- from typing import Any, Iterable, Optional
20
+ from typing import Any, Iterable, Literal, Optional
21
21
 
22
22
  from pydantic import BaseModel, Field, field_validator, model_validator
23
23
 
@@ -272,15 +272,53 @@ class RelationshipSpec(BaseModel):
272
272
  resolver_module: Optional[str] = None
273
273
 
274
274
 
275
+ class CapabilitySpec(BaseModel):
276
+ """A process provider's addressable capability (process-provider spec).
277
+
278
+ A process provider acts on an internal system instead of producing
279
+ ``(concept, entity, date)`` observations. Its manifest declares the
280
+ capability node identity and shape; the projection writes only this index
281
+ entry, never the system's data body (second-source ban).
282
+ """
283
+
284
+ external_key: str # semantic key, unique within (scope, kind)
285
+ description: Optional[str] = None
286
+ parameters: list[ParamSpec] = Field(default_factory=list)
287
+ returns: Optional[str] = None # description of the action result
288
+ required_scopes: list[str] = Field(default_factory=list) # e.g. crm.read
289
+
290
+ @field_validator("external_key")
291
+ @classmethod
292
+ def _key_not_blank(cls, v: str) -> str:
293
+ if not v or not v.strip():
294
+ raise ValueError("capability external_key must be non-blank")
295
+ return v.strip()
296
+
297
+ @field_validator("required_scopes")
298
+ @classmethod
299
+ def _scopes_not_blank(cls, v: list[str]) -> list[str]:
300
+ return [s.strip() for s in v if s and s.strip()]
301
+
302
+
275
303
  class DatasourceManifest(BaseModel):
276
304
  version: str = "1"
277
305
  name: str
278
306
  label: str
279
307
  source_url: Optional[str] = None
280
308
  scanner_mode: str = "upstream-curated"
309
+ # Provider placement (provider-placement spec): cloud = hub process,
310
+ # edge = customer-side runner. Omitted in old manifests -> cloud.
311
+ placement: Literal["cloud", "edge"] = "cloud"
312
+ # Credential source (provider-credential-binding spec): hub = platform's
313
+ # own env credentials, user = per-caller BYOK key.
314
+ credential: Literal["hub", "user"] = "hub"
315
+ # data = produces observations; process = acts on an internal system;
316
+ # both = both faces (two consumption paths, one manifest).
317
+ provider_kind: Literal["data", "process", "both"] = "data"
318
+ capabilities: list[CapabilitySpec] = Field(default_factory=list)
281
319
  requires: list[str] = Field(default_factory=list)
282
320
  ranking_seed: list[float] = Field(default_factory=lambda: [0.5, 0.5])
283
- functions: list[FunctionSpec]
321
+ functions: list[FunctionSpec] = Field(default_factory=list)
284
322
  concepts: list[ConceptHint] = Field(default_factory=list)
285
323
  # Entity coverage declarations (which entity types this datasource covers)
286
324
  entities: list[EntitySpec] = Field(default_factory=list)
@@ -289,6 +327,20 @@ class DatasourceManifest(BaseModel):
289
327
  relationships: list[RelationshipSpec] = Field(default_factory=list)
290
328
  fetch: Optional[FetchRef] = None
291
329
 
330
+ @model_validator(mode="after")
331
+ def _kind_face_present(self) -> "DatasourceManifest":
332
+ # Data manifests may be empty for backward compatibility (old catalogs
333
+ # with zero functions load unchanged); a process face cannot be empty,
334
+ # or the projection would publish nothing while claiming to be one.
335
+ if self.provider_kind in ("process", "both") and not self.capabilities:
336
+ raise ValueError("process provider manifest must declare at least one capability")
337
+ return self
338
+
339
+ def routes_to_capability_projection(self) -> bool:
340
+ """True when the loader must route this manifest to the capability
341
+ catalog as well as (or instead of) observation ingest."""
342
+ return self.provider_kind in ("process", "both")
343
+
292
344
 
293
345
  # ---------------------------------------------------------------------------
294
346
  # Unified indicator registry
@@ -10,7 +10,9 @@
10
10
 
11
11
  纪律:
12
12
  - 失败**不阻塞启动**——registry 不可达时服务照常提供能力;
13
- - 有界重试 15s/1m/5m/30m ×4(`REGISTRY_SURFACE_BACKOFF` 可覆盖),成功即停——不是心跳;
13
+ - 有界重试 15s/1m/5m/30m ×4(`REGISTRY_SURFACE_BACKOFF` 可覆盖),成功即停——单次上报不是心跳;
14
+ - **自愈**:单次上报失败后后台任务继续按指数退复试(60s 起、上限 30 分钟一次),成功即停;
15
+ 进程内只有一个在飞任务(`ensure_started` 单次封口),失败不刷日志(除每次复试一条 warning);
14
16
  - 未配置时**静默跳过**(本地开发/未上牌形态,零行为变化)。
15
17
 
16
18
  env(按 `prefix` 派生,默认 `WIRE`;各服务用自己前缀,见 `ensure_started(prefix=...)`):
@@ -24,6 +26,7 @@ from __future__ import annotations
24
26
  import asyncio
25
27
  import logging
26
28
  import os
29
+ import time
27
30
 
28
31
  logger = logging.getLogger(__name__)
29
32
 
@@ -143,8 +146,31 @@ def report_state(ok: bool, configured: bool) -> str:
143
146
  return "ok" if ok else "failed"
144
147
 
145
148
 
149
+ def _report_state(mcp) -> dict:
150
+ """进程内自报生命周期。status: never / retrying / ok;另记失败数与最后尝试时刻。"""
151
+ st = getattr(mcp, "_surface_report_state", None)
152
+ if st is None:
153
+ st = {"status": "never", "failures": 0, "last_attempt": None}
154
+ mcp._surface_report_state = st
155
+ return st
156
+
157
+
158
+ def surface_state(mcp) -> dict:
159
+ """自报状态只读副本:never / retrying / ok + 失败次数 + 最后尝试时刻(epoch 秒)。"""
160
+ return dict(_report_state(mcp))
161
+
162
+
163
+ def _retry_delay(failures: int) -> float:
164
+ """自愈复试退避:首次 60s,之后指数、上限 30 分钟一次。"""
165
+ return min(60.0 * (2 ** max(failures - 1, 0)), 1800.0)
166
+
167
+
146
168
  def start_background(mcp, *, prefix: str = "WIRE") -> asyncio.Task | None:
147
- """fire-and-forget 自报任务;未配置时返回 None(零行为变化)。"""
169
+ """fire-and-forget 自报任务;未配置时返回 None(零行为变化)。
170
+
171
+ 单次上报失败**不封口**:继续按 `_retry_delay` 指数退复试,成功即停。进程内
172
+ 仅一个任务(由 `ensure_started` 封口),故同一进程只允许一个在飞上报。
173
+ """
148
174
  if _configured(prefix) is None:
149
175
  return None
150
176
 
@@ -152,10 +178,26 @@ def start_background(mcp, *, prefix: str = "WIRE") -> asyncio.Task | None:
152
178
  # 吞掉一切异常:网络层失败 report_surface 自己消化,但代码层缺陷
153
179
  # (参数错、序列化炸)也不能把后台任务变成未处理异常——状态置 failed。
154
180
  try:
155
- ok = await report_surface(mcp, prefix=prefix)
156
- mcp._surface_report = report_state(ok, configured=True)
181
+ while True:
182
+ st = _report_state(mcp)
183
+ st["in_flight"] = True
184
+ st["last_attempt"] = time.time()
185
+ try:
186
+ ok = await report_surface(mcp, prefix=prefix)
187
+ finally:
188
+ st["in_flight"] = False
189
+ if ok:
190
+ st.update(status="ok", failures=0)
191
+ mcp._surface_report = "ok"
192
+ return
193
+ st["failures"] += 1
194
+ st["status"] = "retrying"
195
+ mcp._surface_report = "failed"
196
+ await asyncio.sleep(_retry_delay(st["failures"]))
157
197
  except Exception: # noqa: BLE001 — fire-and-forget 边界
158
- mcp._surface_report = report_state(False, configured=True)
198
+ st = _report_state(mcp)
199
+ st["status"] = "retrying"
200
+ mcp._surface_report = "failed"
159
201
 
160
202
  return asyncio.create_task(_runner())
161
203
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: fd-open-data-protocol
3
- Version: 0.5.6
3
+ Version: 0.5.7
4
4
  Summary: The open-data datasource protocol: a manifest contract a datasource exposes to be ingested by fd-open-data-mcp (or any consumer).
5
5
  Author: FindDataOfficial
6
6
  License: MIT
@@ -51,6 +51,16 @@ fd-open-data-mcp migrate \
51
51
  fd-open-data-mcp serve
52
52
  ```
53
53
 
54
+ ## MCP surface self-report (self-healing)
55
+
56
+ `surface_report` 启动自报工具面给 registry。**失败不再封口**:单次上报耗尽重试后,
57
+ 后台任务按指数退避(60s 起、上限 30 分钟一次)持续复试,成功即停;进程内只有一个在飞
58
+ 任务(`ensure_started` 单次封口)。状态可经 `surface_state(mcp)` 区分 `never` / `retrying` /
59
+ `ok`、失败次数与最后尝试时刻,供检查器判断陈旧 vs 当前。
60
+
61
+ > **生效需重新发布 protocol 包并重建 5 个消费方镜像**(库打进镜像):`wire-ops-mcp`、
62
+ > `wanxing-ops-mcp`、`wire-build-mcp`、`lex-ops-mcp`、`fd-paper-trading`。
63
+
54
64
  ## The manifest
55
65
 
56
66
  A YAML/JSON file (or a Python module exposing `CATALOG`):
@@ -107,7 +117,7 @@ my-source = "my_pkg.catalog:CATALOG"
107
117
 
108
118
  ## Schema
109
119
 
110
- - **`DatasourceManifest`**: name, label, source_url, scanner_mode, ranking_seed, functions[], concepts[], entities[], entity_definitions[], relationships[], fetch.
120
+ - **`DatasourceManifest`**: name, label, source_url, scanner_mode, ranking_seed, functions[], concepts[], entities[], entity_definitions[], relationships[], fetch, `placement` (`cloud`|`edge`, default `cloud`), `credential` (`hub`|`user`, default `hub`), `provider_kind` (`data`|`process`|`both`, default `data`), capabilities[].
111
121
  - **`FunctionSpec`**: command, category, description, parameters[], columns[], frequency, verified.
112
122
  - **`ColumnSpec`**: name, type, description, meaning, semantic_type, `frequency` + `datasource` (column-level).
113
123
  - **`ConceptHint`**: column, concept, `entity_type`, `measure`, unit, frequency, confidence, `concept_family` (optional).
@@ -38,6 +38,7 @@ tests/test_drift_inventory.py
38
38
  tests/test_line_ops.py
39
39
  tests/test_loader.py
40
40
  tests/test_openalex_provider.py
41
+ tests/test_provider_plane.py
41
42
  tests/test_registry_pipeline.py
42
43
  tests/test_registry_schema.py
43
44
  tests/test_schema_vocabulary.py
@@ -0,0 +1,102 @@
1
+ """Provider-plane declarations: placement, credential, and data/process kind.
2
+
3
+ Covers the protocol half of change ``unify-data-provider-plane`` (tasks 1.1-1.3):
4
+ old manifests keep loading with defaults, the new fields are readable by a
5
+ dispatcher, and a process manifest carries addressable capability nodes.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import pytest
10
+ from pydantic import ValidationError
11
+
12
+ from fd_open_data_protocol.loader import load_catalog
13
+ from fd_open_data_protocol.schema import CapabilitySpec, DatasourceManifest
14
+
15
+
16
+ def _data_manifest(**extra):
17
+ return {"name": "s", "label": "S", "functions": [{"command": "f", "columns": []}], **extra}
18
+
19
+
20
+ def _process_manifest(**extra):
21
+ return {
22
+ "name": "erp",
23
+ "label": "ERP",
24
+ "provider_kind": "process",
25
+ "capabilities": [{"external_key": "crm.contact.create", "required_scopes": ["crm.write"]}],
26
+ **extra,
27
+ }
28
+
29
+
30
+ # --- 1.1 placement + credential ------------------------------------------------
31
+
32
+
33
+ def test_old_manifest_keeps_loading_with_defaults():
34
+ m = load_catalog(_data_manifest())
35
+ assert m.placement == "cloud"
36
+ assert m.credential == "hub"
37
+ assert m.provider_kind == "data"
38
+
39
+
40
+ def test_manifest_declares_edge_and_user_credential():
41
+ m = load_catalog(_data_manifest(placement="edge", credential="user"))
42
+ assert (m.placement, m.credential) == ("edge", "user")
43
+ assert not m.routes_to_capability_projection()
44
+
45
+
46
+ @pytest.mark.parametrize("field,bad", [("placement", "on-prem"), ("credential", "tenant")])
47
+ def test_unknown_declarations_are_rejected(field, bad):
48
+ with pytest.raises(ValidationError):
49
+ load_catalog(_data_manifest(**{field: bad}))
50
+
51
+
52
+ # --- 1.2 data / process / both -------------------------------------------------#
53
+
54
+
55
+ def test_process_manifest_is_recognized_and_routed():
56
+ m = load_catalog(_process_manifest())
57
+ assert m.provider_kind == "process"
58
+ assert m.routes_to_capability_projection()
59
+ assert m.capabilities[0].external_key == "crm.contact.create"
60
+
61
+
62
+ def test_both_manifest_keeps_both_faces():
63
+ m = load_catalog(_process_manifest(
64
+ provider_kind="both",
65
+ functions=[{"command": "f", "columns": []}],
66
+ ))
67
+ assert m.routes_to_capability_projection()
68
+ assert m.functions and m.capabilities
69
+
70
+
71
+ def test_kind_must_carry_its_face():
72
+ with pytest.raises(ValidationError):
73
+ load_catalog({"name": "p", "label": "P", "provider_kind": "process"})
74
+ # A data manifest with zero functions still loads (old catalogs).
75
+ assert load_catalog({"name": "d", "label": "D", "provider_kind": "data"}).functions == []
76
+
77
+
78
+ # --- 1.3 capability node declaration shape -------------------------------------
79
+
80
+
81
+ def test_capability_declaration_shape():
82
+ cap = CapabilitySpec(
83
+ external_key="crm.contact.create",
84
+ description="Create a contact",
85
+ parameters=[{"name": "email", "type": "str", "required": True}],
86
+ returns="contact id",
87
+ required_scopes=["crm.write"],
88
+ )
89
+ assert cap.parameters[0].required is True
90
+ assert cap.required_scopes == ["crm.write"]
91
+
92
+
93
+ def test_capability_key_and_scopes_are_clean():
94
+ with pytest.raises(ValidationError):
95
+ CapabilitySpec(external_key=" ")
96
+ cap = CapabilitySpec(external_key="x", required_scopes=[" crm.read ", "", " "])
97
+ assert cap.required_scopes == ["crm.read"]
98
+
99
+
100
+ def test_manifest_is_a_dict_roundtrip():
101
+ m = DatasourceManifest(**_process_manifest())
102
+ assert DatasourceManifest(**m.model_dump()) == m
@@ -207,3 +207,86 @@ async def test_start_background_marks_failed_state(monkeypatch):
207
207
  task = sr.start_background(mcp)
208
208
  await asyncio.wait_for(task, 5)
209
209
  assert mcp._surface_report == "failed"
210
+
211
+
212
+ class _Stop(Exception):
213
+ """测试替身:让被 monkeypatch 的 asyncio.sleep 停住循环,记录已产生的退避。"""
214
+
215
+
216
+ async def test_recovers_after_transient_failure(monkeypatch):
217
+ """首次失败 → 后台复试成功 → 状态 ok(陈旧 latch 自我修复)。"""
218
+ _configure(monkeypatch)
219
+ calls: list = []
220
+
221
+ async def flaky(mcp, *, prefix="WIRE", httpx=None):
222
+ calls.append(1)
223
+ return len(calls) >= 2 # 第一次失败,第二次成功
224
+ monkeypatch.setattr(sr, "report_surface", flaky)
225
+ delays: list = []
226
+ import fd_open_data_protocol.surface_report as sr_mod
227
+ async def fake_sleep(delay: float) -> None:
228
+ delays.append(delay)
229
+ monkeypatch.setattr(sr_mod.asyncio, "sleep", fake_sleep)
230
+
231
+ mcp = FakeMCP(["t"])
232
+ assert sr.surface_state(mcp) == {"status": "never", "failures": 0, "last_attempt": None}
233
+ task = sr.start_background(mcp)
234
+ await asyncio.wait_for(task, 5)
235
+ assert mcp._surface_report == "ok"
236
+ assert len(calls) == 2
237
+ assert delays and delays[0] >= 60 # 失败后至少等一次退避才复试
238
+ assert sr.surface_state(mcp)["status"] == "ok"
239
+
240
+
241
+ async def test_persistent_failure_is_rate_limited(monkeypatch):
242
+ """持续失败:复试受退避限速(不会每次请求/每个循环立刻再打)。"""
243
+ _configure(monkeypatch)
244
+ calls: list = []
245
+
246
+ async def always_fail(mcp, *, prefix="WIRE", httpx=None):
247
+ calls.append(1)
248
+ return False
249
+ monkeypatch.setattr(sr, "report_surface", always_fail)
250
+ delays: list = []
251
+
252
+ async def fake_sleep(delay: float) -> None:
253
+ delays.append(delay)
254
+ raise _Stop() # 第一次复试等待即停,避免无限循环
255
+ import fd_open_data_protocol.surface_report as sr_mod
256
+ monkeypatch.setattr(sr_mod.asyncio, "sleep", fake_sleep)
257
+
258
+ mcp = FakeMCP(["t"])
259
+ task = sr.start_background(mcp)
260
+ try:
261
+ await asyncio.wait_for(task, 5)
262
+ except (asyncio.TimeoutError, _Stop):
263
+ task.cancel()
264
+ assert len(calls) == 1, "失败后必须经退避才复试,不得立即连打"
265
+ assert delays == [60.0], "首次失败后 60s 才复试(指数退避起点)"
266
+ st = sr.surface_state(mcp)
267
+ assert st["status"] == "retrying" and st["failures"] == 1 and st["last_attempt"]
268
+
269
+
270
+ async def test_single_in_flight_across_ensure_started(monkeypatch):
271
+ """ensure_started 重复触发只留一个在飞任务(并发安全)。"""
272
+ _configure(monkeypatch)
273
+
274
+ async def ok_report(mcp, *, prefix="WIRE", httpx=None):
275
+ return True
276
+ monkeypatch.setattr(sr, "report_surface", ok_report)
277
+ import fd_open_data_protocol.surface_report as sr_mod
278
+
279
+ async def _no_sleep(delay: float) -> None:
280
+ return None
281
+ monkeypatch.setattr(sr_mod.asyncio, "sleep", _no_sleep)
282
+
283
+ mcp = FakeMCP(["t"])
284
+ sr.ensure_started(mcp)
285
+ first = mcp._surface_task
286
+ assert first is not None
287
+ sr.ensure_started(mcp)
288
+ sr.ensure_started(mcp)
289
+ assert mcp._surface_task is first, "重复 ensure_started 不得另起任务"
290
+ await asyncio.wait_for(first, 5)
291
+ await asyncio.wait_for(first, 5) # 已完成任务不应再复位
292
+ assert mcp._surface_report == "ok"