airflow-provider-specstream 0.1.0__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.
@@ -0,0 +1,68 @@
1
+ # Python
2
+ .venv/
3
+ __pycache__/
4
+ *.py[cod]
5
+ .pytest_cache/
6
+ .mypy_cache/
7
+ .ruff_cache/
8
+ .coverage
9
+ coverage/
10
+
11
+ # Node/frontend
12
+ node_modules/
13
+ build/
14
+ dist/
15
+ playwright-report/
16
+ test-results/
17
+ .react-router/
18
+
19
+ # Runtime/output
20
+ site-*/
21
+ *.log
22
+ *.dump
23
+ /exports/*
24
+ /growth/email/out/
25
+ screenshots/
26
+
27
+ # Secrets
28
+ .env
29
+ .env.*
30
+ !.env.example
31
+ *.pem
32
+ *.key
33
+
34
+ # Editors/OS
35
+ .DS_Store
36
+ .idea/
37
+ .vscode/
38
+
39
+ # Isolated engine verification state
40
+ .engine-local/
41
+
42
+ # Isolated product-hardening verification state
43
+ .hardening-local/
44
+
45
+ # Isolated product-maturation verification state (short Unix socket paths)
46
+ /.maturation-local/
47
+ /.t/
48
+
49
+ .runtime/
50
+ /design/brand/street-world/specstream-street-world.zip
51
+
52
+ /artifacts/launch-validation/
53
+
54
+ /artifacts/launch-package/
55
+
56
+ # Website build output read by the pages (page dates from git)
57
+ apps/website/src/data/lastmod.generated.json
58
+ plugins/openai/ui/harness/harness.js
59
+ apps/workspace/dist-chatgpt/
60
+ marketing/native/*/
61
+ marketing/native/START-HERE.html
62
+
63
+ # the crew board and its runs (ops/crew.py): a database and job scripts, not source
64
+ /var/crew/
65
+
66
+ # Work trees of parallel helpers: full copies of the repo. Searches and git must not walk them
67
+ # (Nov 12: 50 copies inside the repo kept the /home disk at 100% busy).
68
+ .claude/worktrees
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 SpecStream SAS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.5
2
+ Name: airflow-provider-specstream
3
+ Version: 0.1.0
4
+ Summary: SpecStream for Apache Airflow: the live web data engine. Search API, Extract API and Deep Search operators and a hook.
5
+ Project-URL: Homepage, https://specstream.ai
6
+ Project-URL: Documentation, https://specstream.ai/docs
7
+ Project-URL: Repository, https://github.com/specstream/specstream-tools/tree/main/packages/airflow-provider-specstream
8
+ Project-URL: Issues, https://github.com/specstream/specstream-tools/issues
9
+ Project-URL: Pricing, https://specstream.ai/pricing
10
+ Author-email: SpecStream <support@specstream.ai>
11
+ License-Expression: MIT
12
+ License-File: LICENSE
13
+ Keywords: airflow,airflow-provider,apache-airflow,etl,extract,live-web,specstream,web-data,web-search
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: Apache Airflow
16
+ Classifier: Framework :: Apache Airflow :: Provider
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Topic :: Internet :: WWW/HTTP
25
+ Classifier: Typing :: Typed
26
+ Requires-Python: >=3.10
27
+ Requires-Dist: apache-airflow>=2.9.0
28
+ Provides-Extra: test
29
+ Requires-Dist: pytest>=8; extra == 'test'
30
+ Description-Content-Type: text/markdown
31
+
32
+ # airflow-provider-specstream
33
+
34
+ [SpecStream](https://specstream.ai) is the live web data engine. One platform to build, search, extract, enrich, map, and monitor data across the entire web.
35
+
36
+ Ask for any dataset in plain words, and SpecStream builds it from the entire live web: every match found, extracted and enriched into structured records, then monitored for change. It runs through the API and MCP, and inside Sheets, CRMs, Slack, n8n, Zapier and the other tools teams already use.
37
+
38
+ Source URL and read time on every value.
39
+
40
+ This package is the SpecStream provider for Apache Airflow 2.9 and later, Airflow 3 included: a hook, a `specstream` connection type and three operators.
41
+
42
+ ```bash
43
+ pip install airflow-provider-specstream
44
+ ```
45
+
46
+ ## Connection
47
+
48
+ Create a connection of type **SpecStream** named `specstream_default` and put your API key (Agents & API in your SpecStream workspace) in the **API key** field. Or set it in the environment:
49
+
50
+ ```bash
51
+ export AIRFLOW_CONN_SPECSTREAM_DEFAULT='{"conn_type": "specstream", "password": "<your API key>"}'
52
+ ```
53
+
54
+ A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
55
+
56
+ ## Operators
57
+
58
+ | Operator | API | Price |
59
+ | --- | --- | --- |
60
+ | `SpecStreamSearchOperator` | Search API, `GET /v1/web-search` | $5 per 1,000 searches of up to 10 results; $1 per 1,000 with `speed="fast"` |
61
+ | `SpecStreamExtractOperator` | Extract API, `POST /v1/extract`, 1 to 20 URLs | $0.80 per 1,000 pages; a page with no text is free |
62
+ | `SpecStreamDeepSearchOperator` | Deep Search | 5 cents, 15 cents or $1 per delivered row |
63
+
64
+ Each operator returns the API's reply, which Airflow pushes to XCom.
65
+
66
+ ```python
67
+ from specstream_provider.operators.specstream import (
68
+ SpecStreamDeepSearchOperator,
69
+ SpecStreamExtractOperator,
70
+ SpecStreamSearchOperator,
71
+ )
72
+
73
+ search = SpecStreamSearchOperator(task_id="search", query="Apache Airflow latest release", speed="fast")
74
+ read = SpecStreamExtractOperator(task_id="read", urls="{{ ti.xcom_pull(task_ids='search')['sources'][0]['url'] }}")
75
+ deep = SpecStreamDeepSearchOperator(
76
+ task_id="deep_search",
77
+ request="Open-source workflow orchestrators with their website and license",
78
+ max_results=25,
79
+ max_price_usd=5,
80
+ retries=2,
81
+ )
82
+ search >> read
83
+ ```
84
+
85
+ `SpecStreamDeepSearchOperator` starts a run only when its quoted maximum is at or below `max_price_usd`; otherwise nothing runs and the task fails with the price. A retry of the same task instance continues the same list and never buys it twice. When the list is still running after `wait_seconds` (420 by default), the task fails so that its retry picks the list up; set `fail_if_unfinished=False` to return the rows found so far. The result holds `list_id`, `status`, `list_link`, `row_count` and `rows`; each row carries `source_url` and `checked_at`.
86
+
87
+ A full DAG is in `specstream_provider/example_dags/example_specstream.py`.
88
+
89
+ ## License
90
+
91
+ MIT
@@ -0,0 +1,60 @@
1
+ # airflow-provider-specstream
2
+
3
+ [SpecStream](https://specstream.ai) is the live web data engine. One platform to build, search, extract, enrich, map, and monitor data across the entire web.
4
+
5
+ Ask for any dataset in plain words, and SpecStream builds it from the entire live web: every match found, extracted and enriched into structured records, then monitored for change. It runs through the API and MCP, and inside Sheets, CRMs, Slack, n8n, Zapier and the other tools teams already use.
6
+
7
+ Source URL and read time on every value.
8
+
9
+ This package is the SpecStream provider for Apache Airflow 2.9 and later, Airflow 3 included: a hook, a `specstream` connection type and three operators.
10
+
11
+ ```bash
12
+ pip install airflow-provider-specstream
13
+ ```
14
+
15
+ ## Connection
16
+
17
+ Create a connection of type **SpecStream** named `specstream_default` and put your API key (Agents & API in your SpecStream workspace) in the **API key** field. Or set it in the environment:
18
+
19
+ ```bash
20
+ export AIRFLOW_CONN_SPECSTREAM_DEFAULT='{"conn_type": "specstream", "password": "<your API key>"}'
21
+ ```
22
+
23
+ A free account comes with $10 of credit and needs no card: [specstream.ai](https://specstream.ai/signup).
24
+
25
+ ## Operators
26
+
27
+ | Operator | API | Price |
28
+ | --- | --- | --- |
29
+ | `SpecStreamSearchOperator` | Search API, `GET /v1/web-search` | $5 per 1,000 searches of up to 10 results; $1 per 1,000 with `speed="fast"` |
30
+ | `SpecStreamExtractOperator` | Extract API, `POST /v1/extract`, 1 to 20 URLs | $0.80 per 1,000 pages; a page with no text is free |
31
+ | `SpecStreamDeepSearchOperator` | Deep Search | 5 cents, 15 cents or $1 per delivered row |
32
+
33
+ Each operator returns the API's reply, which Airflow pushes to XCom.
34
+
35
+ ```python
36
+ from specstream_provider.operators.specstream import (
37
+ SpecStreamDeepSearchOperator,
38
+ SpecStreamExtractOperator,
39
+ SpecStreamSearchOperator,
40
+ )
41
+
42
+ search = SpecStreamSearchOperator(task_id="search", query="Apache Airflow latest release", speed="fast")
43
+ read = SpecStreamExtractOperator(task_id="read", urls="{{ ti.xcom_pull(task_ids='search')['sources'][0]['url'] }}")
44
+ deep = SpecStreamDeepSearchOperator(
45
+ task_id="deep_search",
46
+ request="Open-source workflow orchestrators with their website and license",
47
+ max_results=25,
48
+ max_price_usd=5,
49
+ retries=2,
50
+ )
51
+ search >> read
52
+ ```
53
+
54
+ `SpecStreamDeepSearchOperator` starts a run only when its quoted maximum is at or below `max_price_usd`; otherwise nothing runs and the task fails with the price. A retry of the same task instance continues the same list and never buys it twice. When the list is still running after `wait_seconds` (420 by default), the task fails so that its retry picks the list up; set `fail_if_unfinished=False` to return the rows found so far. The result holds `list_id`, `status`, `list_link`, `row_count` and `rows`; each row carries `source_url` and `checked_at`.
55
+
56
+ A full DAG is in `specstream_provider/example_dags/example_specstream.py`.
57
+
58
+ ## License
59
+
60
+ MIT
@@ -0,0 +1,54 @@
1
+ [project]
2
+ name = "airflow-provider-specstream"
3
+ version = "0.1.0"
4
+ description = "SpecStream for Apache Airflow: the live web data engine. Search API, Extract API and Deep Search operators and a hook."
5
+ readme = "README.md"
6
+ requires-python = ">=3.10"
7
+ license = "MIT"
8
+ license-files = ["LICENSE"]
9
+ authors = [{ name = "SpecStream", email = "support@specstream.ai" }]
10
+ keywords = ["airflow", "apache-airflow", "airflow-provider", "specstream", "web-search", "web-data", "live-web", "extract", "etl"]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Framework :: Apache Airflow",
14
+ "Framework :: Apache Airflow :: Provider",
15
+ "Intended Audience :: Developers",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3 :: Only",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Topic :: Internet :: WWW/HTTP",
23
+ "Typing :: Typed",
24
+ ]
25
+ dependencies = ["apache-airflow>=2.9.0"]
26
+
27
+ [project.optional-dependencies]
28
+ test = ["pytest>=8"]
29
+
30
+ [dependency-groups]
31
+ dev = ["pytest>=8"]
32
+
33
+ [project.entry-points.apache_airflow_provider]
34
+ provider_info = "specstream_provider:get_provider_info"
35
+
36
+ [project.urls]
37
+ Homepage = "https://specstream.ai"
38
+ Documentation = "https://specstream.ai/docs"
39
+ Repository = "https://github.com/specstream/specstream-tools/tree/main/packages/airflow-provider-specstream"
40
+ Issues = "https://github.com/specstream/specstream-tools/issues"
41
+ Pricing = "https://specstream.ai/pricing"
42
+
43
+ [build-system]
44
+ requires = ["hatchling>=1.27,<2"]
45
+ build-backend = "hatchling.build"
46
+
47
+ [tool.hatch.build.targets.wheel]
48
+ packages = ["specstream_provider"]
49
+
50
+ [tool.hatch.build.targets.sdist]
51
+ include = ["specstream_provider", "tests", "README.md", "LICENSE"]
52
+
53
+ [tool.pytest.ini_options]
54
+ testpaths = ["tests"]
@@ -0,0 +1,26 @@
1
+ """SpecStream provider for Apache Airflow."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+
6
+ def get_provider_info() -> dict:
7
+ """Read by Airflow through the apache_airflow_provider entry point."""
8
+ return {
9
+ "package-name": "airflow-provider-specstream",
10
+ "name": "SpecStream",
11
+ "description": "SpecStream is the live web data engine. One platform to build, search, extract, enrich, map, and monitor data across the entire web.",
12
+ "versions": [__version__],
13
+ "connection-types": [
14
+ {"connection-type": "specstream", "hook-class-name": "specstream_provider.hooks.specstream.SpecStreamHook"},
15
+ ],
16
+ "hook-class-names": ["specstream_provider.hooks.specstream.SpecStreamHook"],
17
+ "operators": [
18
+ {"integration-name": "SpecStream", "python-modules": ["specstream_provider.operators.specstream"]},
19
+ ],
20
+ "hooks": [
21
+ {"integration-name": "SpecStream", "python-modules": ["specstream_provider.hooks.specstream"]},
22
+ ],
23
+ "integrations": [
24
+ {"integration-name": "SpecStream", "external-doc-url": "https://specstream.ai/docs", "tags": ["service"]},
25
+ ],
26
+ }
@@ -0,0 +1,255 @@
1
+ """The SpecStream REST calls the hook makes: search, extract, and a Deep Search list run within a maximum price."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import time
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+ from dataclasses import dataclass
11
+ from typing import Any, Callable
12
+
13
+ DEFAULT_BASE_URL = "https://api.specstream.ai"
14
+ USER_AGENT = "airflow-provider-specstream/0.1.0"
15
+ # A list runs for up to about five minutes, so a task waits a little longer than that by default.
16
+ DEFAULT_WAIT_SECONDS = 420.0
17
+ FINISHED = {"completed", "partial"}
18
+ STOPPED = {"failed", "cancelled", "canceled", "expired"}
19
+ # Fields every row carries; a column with the same name is renamed so it can't overwrite them.
20
+ RESERVED = {"list_id", "list_link", "position", "source_url", "checked_at"}
21
+ SPEEDS = {"default", "fast"}
22
+
23
+ Opener = Callable[[urllib.request.Request, float], Any]
24
+
25
+
26
+ class SpecStreamError(RuntimeError):
27
+ """SpecStream refused a call or answered with something this package can't read."""
28
+
29
+
30
+ def _dollars(cents: int) -> str:
31
+ return f"${cents / 100:.2f}"
32
+
33
+
34
+ def list_link(find_id: str) -> str:
35
+ return f"https://specstream.ai/workspace/collections/{urllib.parse.quote(find_id, safe='')}"
36
+
37
+
38
+ def flatten_row(find_id: str, record: dict[str, Any], flat: dict[str, Any] | None = None) -> dict[str, Any]:
39
+ """One row as flat fields: each column's label holds what the list shows, and each value's page
40
+ (<field>_source) plus the page that put the row in the list (source_url, checked_at)."""
41
+ flat = flat or {}
42
+ sources = {k: v for k, v in flat.items() if k.endswith("_source") and k[: -len("_source")] in flat}
43
+ row: dict[str, Any] = {"list_id": find_id, "position": record.get("ordinal")}
44
+ for cell in record.get("details") or record.get("cells") or []:
45
+ label = str(cell.get("label") or cell.get("column_id") or "").strip()
46
+ if not label:
47
+ continue
48
+ if label in RESERVED or label in sources:
49
+ label = f"{label} (column)"
50
+ if cell.get("absence"):
51
+ value: Any = ""
52
+ elif cell.get("display") is not None:
53
+ value = cell["display"]
54
+ else:
55
+ value = cell.get("value") if cell.get("value") is not None else ""
56
+ row[label] = value
57
+ row.update(sources)
58
+ row["source_url"] = flat.get("source_url") or ""
59
+ row["checked_at"] = flat.get("checked_at") or ""
60
+ row["list_link"] = list_link(find_id)
61
+ return row
62
+
63
+
64
+ @dataclass
65
+ class SpecStreamAPI:
66
+ api_key: str
67
+ base_url: str = DEFAULT_BASE_URL
68
+ timeout: float = 150.0
69
+ opener: Opener | None = None
70
+ sleep: Callable[[float], None] = time.sleep
71
+ clock: Callable[[], float] = time.monotonic
72
+
73
+ def request(self, method: str, path: str, body: dict[str, Any] | None = None, *, allow_404: bool = False) -> dict[str, Any] | None:
74
+ key = (self.api_key or "").strip()
75
+ if not key:
76
+ raise SpecStreamError(
77
+ "The SpecStream connection has no API key. Put the key in the connection's API key (password) field; "
78
+ "create one under Agents & API in your SpecStream workspace."
79
+ )
80
+ request = urllib.request.Request(
81
+ (self.base_url or DEFAULT_BASE_URL).rstrip("/") + path,
82
+ data=None if body is None else json.dumps(body).encode(),
83
+ method=method,
84
+ headers={
85
+ "Authorization": key if key.lower().startswith("bearer ") else f"Bearer {key}",
86
+ "Accept": "application/json",
87
+ "Content-Type": "application/json",
88
+ "User-Agent": USER_AGENT,
89
+ },
90
+ )
91
+ open_ = self.opener or (lambda req, timeout: urllib.request.urlopen(req, timeout=timeout))
92
+ try:
93
+ response = open_(request, self.timeout)
94
+ try:
95
+ raw = response.read()
96
+ finally:
97
+ response.close()
98
+ except urllib.error.HTTPError as error:
99
+ if allow_404 and error.code == 404:
100
+ return None
101
+ raise SpecStreamError(_error_message(error)) from None
102
+ except urllib.error.URLError as error:
103
+ raise SpecStreamError(f"Couldn't reach SpecStream: {error.reason}") from None
104
+ try:
105
+ payload = json.loads(raw or b"{}")
106
+ except ValueError:
107
+ payload = None
108
+ if not isinstance(payload, dict) or not isinstance(payload.get("data"), dict):
109
+ raise SpecStreamError("SpecStream returned a response this package couldn't read.")
110
+ return payload["data"]
111
+
112
+ def web_search(
113
+ self,
114
+ q: str,
115
+ *,
116
+ passages: bool = False,
117
+ speed: str = "default",
118
+ num: int | None = None,
119
+ news: bool = False,
120
+ country: str | None = None,
121
+ language: str | None = None,
122
+ ) -> dict[str, Any]:
123
+ """GET /v1/web-search: $5 per 1,000 searches of up to 10 results, $1 per 1,000 with speed="fast"."""
124
+ query = (q or "").strip()
125
+ if not query or len(query) > 2000:
126
+ raise ValueError("q must be between 1 and 2,000 characters.")
127
+ if speed not in SPEEDS:
128
+ raise ValueError('speed must be "default" or "fast".')
129
+ params: dict[str, str] = {"q": query}
130
+ if passages:
131
+ params["passages"] = "true"
132
+ if speed != "default":
133
+ params["speed"] = speed
134
+ if num is not None:
135
+ if not 1 <= int(num) <= 200:
136
+ raise ValueError("num must be between 1 and 200.")
137
+ params["num"] = str(int(num))
138
+ if news:
139
+ params["news"] = "true"
140
+ if country:
141
+ params["country"] = country
142
+ if language:
143
+ params["language"] = language
144
+ return self.request("GET", f"/v1/web-search?{urllib.parse.urlencode(params)}") or {}
145
+
146
+ def extract_pages(self, urls: list[str], *, format: str = "markdown") -> dict[str, Any]:
147
+ """POST /v1/extract: the main text of 1 to 20 URLs, $0.80 per 1,000 pages; a page with no text is free."""
148
+ cleaned = [str(u or "").strip() for u in (urls or []) if str(u or "").strip()]
149
+ if not 1 <= len(cleaned) <= 20:
150
+ raise ValueError("Provide 1 to 20 http or https URLs.")
151
+ fmt = "text" if format == "text" else "markdown"
152
+ return self.request("POST", "/v1/extract", {"urls": cleaned, "format": fmt}) or {}
153
+
154
+ def results(self, find_id: str) -> dict[str, Any]:
155
+ """Every row found so far for a list, following the pages."""
156
+ rows: list[dict[str, Any]] = []
157
+ cursor: str | None = None
158
+ status = "running"
159
+ while True:
160
+ query = {"limit": "100", **({"cursor": cursor} if cursor else {})}
161
+ page = self.request("GET", f"/v1/finds/{urllib.parse.quote(find_id, safe='')}/rows?{urllib.parse.urlencode(query)}") or {}
162
+ status = page.get("status") or status
163
+ flat = {str(item.get("id")): item for item in page.get("flat_rows") or []}
164
+ rows.extend(
165
+ flatten_row(find_id, record, flat.get(f"{find_id}:{record.get('entity_id')}")) for record in page.get("rows") or []
166
+ )
167
+ cursor = page.get("next_cursor")
168
+ if not cursor:
169
+ break
170
+ return {"list_id": find_id, "status": status, "list_link": list_link(find_id), "row_count": len(rows), "rows": rows}
171
+
172
+ def find_list(
173
+ self,
174
+ request: str,
175
+ *,
176
+ max_results: int,
177
+ max_price_usd: float,
178
+ idempotency_key: str,
179
+ wait_seconds: float = DEFAULT_WAIT_SECONDS,
180
+ poll_interval: float = 5.0,
181
+ locale: str = "en-US",
182
+ ) -> dict[str, Any]:
183
+ """A Deep Search list. The same idempotency_key returns the run it already started, so a retried
184
+ task never buys the list twice. Nothing runs when the quote is above max_price_usd."""
185
+ q = (request or "").strip()
186
+ if not q:
187
+ raise ValueError("Describe the list to find.")
188
+ if not isinstance(max_results, int) or max_results < 1:
189
+ raise ValueError("max_results must be 1 or more.")
190
+ max_cents = round(float(max_price_usd) * 100)
191
+ if max_cents <= 0:
192
+ raise ValueError("max_price_usd must be greater than 0.")
193
+ if not idempotency_key:
194
+ raise ValueError("idempotency_key is required.")
195
+
196
+ existing = self.request("GET", f"/v1/capacity/requests/{urllib.parse.quote(idempotency_key, safe='')}", allow_404=True)
197
+ if existing and existing.get("find_id"):
198
+ find_id = existing["find_id"]
199
+ maximum_cents = int(existing.get("maximum_cents") or max_cents)
200
+ else:
201
+ reading = self.request("POST", "/v1/parse", {"q": q, "locale": locale}) or {}
202
+ if reading.get("status") != "runnable":
203
+ read_as = reading.get("canonical_sentence") or q
204
+ return {
205
+ "status": "needs_edit",
206
+ "request": q,
207
+ "message": f'SpecStream needs a clearer request before it can price it. It read: "{read_as}". Add the place or what every row must meet.',
208
+ }
209
+ quote = (
210
+ self.request("POST", "/v1/capacity/quotes", {"ast_hash": reading["ast_hash"], "operation": "find", "requested_units": max_results})
211
+ or {}
212
+ )
213
+ maximum_cents = int(quote.get("maximum_cents") or 0)
214
+ if maximum_cents > max_cents:
215
+ return {
216
+ "status": "over_maximum",
217
+ "request": q,
218
+ "maximum_price_usd": maximum_cents / 100,
219
+ "message": f"Nothing ran: this list can cost up to {_dollars(maximum_cents)}, above the maximum of {_dollars(max_cents)}. Ask for fewer results or raise max_price_usd.",
220
+ }
221
+ run = (
222
+ self.request(
223
+ "POST",
224
+ "/v1/capacity/executions",
225
+ {
226
+ "quote_id": quote["quote_id"],
227
+ "quote_hash": quote["quote_hash"],
228
+ "confirm_max_cents": maximum_cents,
229
+ "idempotency_key": idempotency_key,
230
+ },
231
+ )
232
+ or {}
233
+ )
234
+ find_id = run["find_id"]
235
+
236
+ deadline = self.clock() + max(0.0, wait_seconds)
237
+ while True:
238
+ result = self.results(find_id)
239
+ if result["status"] in FINISHED | STOPPED or self.clock() >= deadline:
240
+ break
241
+ self.sleep(poll_interval)
242
+ result.update({"request": q, "maximum_price_usd": maximum_cents / 100})
243
+ if result["status"] not in FINISHED | STOPPED:
244
+ result["message"] = "Still running. A retry of this task continues the same list; open list_link to see it."
245
+ return result
246
+
247
+
248
+ def _error_message(error: urllib.error.HTTPError) -> str:
249
+ try:
250
+ payload = json.loads(error.read() or b"{}")
251
+ except ValueError:
252
+ payload = {}
253
+ detail = payload.get("error") if isinstance(payload, dict) else None
254
+ message = detail.get("message") if isinstance(detail, dict) else detail if isinstance(detail, str) else None
255
+ return f"SpecStream answered {error.code}: {message or error.reason}"
@@ -0,0 +1,38 @@
1
+ """Search the live web, read the pages it found, and build a list, each in its own task.
2
+
3
+ Set up a connection named specstream_default of type SpecStream with your API key, or export
4
+ AIRFLOW_CONN_SPECSTREAM_DEFAULT='{"conn_type": "specstream", "password": "<your API key>"}'.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ from datetime import datetime
10
+
11
+ try:
12
+ from airflow.sdk import DAG
13
+ except ImportError:
14
+ from airflow import DAG
15
+
16
+ from specstream_provider.operators.specstream import (
17
+ SpecStreamDeepSearchOperator,
18
+ SpecStreamExtractOperator,
19
+ SpecStreamSearchOperator,
20
+ )
21
+
22
+ with DAG(dag_id="example_specstream", start_date=datetime(2026, 1, 1), schedule=None, catchup=False, tags=["specstream"]):
23
+ search = SpecStreamSearchOperator(task_id="search", query="Apache Airflow latest release", speed="fast")
24
+
25
+ read = SpecStreamExtractOperator(
26
+ task_id="read",
27
+ urls="{{ ti.xcom_pull(task_ids='search')['sources'][0]['url'] }}",
28
+ )
29
+
30
+ deep = SpecStreamDeepSearchOperator(
31
+ task_id="deep_search",
32
+ request="Open-source workflow orchestrators with their website and license",
33
+ max_results=25,
34
+ max_price_usd=5,
35
+ retries=2,
36
+ )
37
+
38
+ search >> read
@@ -0,0 +1,3 @@
1
+ from specstream_provider.hooks.specstream import SpecStreamHook
2
+
3
+ __all__ = ["SpecStreamHook"]
@@ -0,0 +1,83 @@
1
+ """The SpecStream hook: one Airflow connection (conn type "specstream") holds the API key."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ try: # Airflow 3.1 and later
8
+ from airflow.sdk import BaseHook
9
+ except ImportError: # Airflow 2.9 to 3.0
10
+ from airflow.hooks.base import BaseHook
11
+
12
+ from specstream_provider._api import DEFAULT_BASE_URL, DEFAULT_WAIT_SECONDS, SpecStreamAPI
13
+
14
+
15
+ class SpecStreamHook(BaseHook):
16
+ """Calls the SpecStream API with the key in an Airflow connection.
17
+
18
+ The connection's password field holds the API key (Agents & API in your SpecStream workspace).
19
+ The host field is optional and replaces https://api.specstream.ai.
20
+ """
21
+
22
+ conn_name_attr = "specstream_conn_id"
23
+ default_conn_name = "specstream_default"
24
+ conn_type = "specstream"
25
+ hook_name = "SpecStream"
26
+
27
+ def __init__(self, specstream_conn_id: str = default_conn_name, timeout: float = 150.0, **kwargs: Any) -> None:
28
+ super().__init__(**kwargs)
29
+ self.specstream_conn_id = specstream_conn_id
30
+ self.timeout = timeout
31
+ self._api: SpecStreamAPI | None = None
32
+
33
+ @classmethod
34
+ def get_ui_field_behaviour(cls) -> dict[str, Any]:
35
+ return {
36
+ "hidden_fields": ["schema", "login", "port", "extra"],
37
+ "relabeling": {"password": "API key", "host": "API address (optional)"},
38
+ "placeholders": {"host": DEFAULT_BASE_URL},
39
+ }
40
+
41
+ def get_conn(self) -> SpecStreamAPI:
42
+ if self._api is None:
43
+ conn = self.get_connection(self.specstream_conn_id)
44
+ host = (conn.host or "").strip()
45
+ if host and "://" not in host:
46
+ host = f"https://{host}"
47
+ self._api = SpecStreamAPI(api_key=conn.password or "", base_url=host or DEFAULT_BASE_URL, timeout=self.timeout)
48
+ return self._api
49
+
50
+ def test_connection(self) -> tuple[bool, str]:
51
+ """Checks the key with a fast search, which costs $0.001."""
52
+ try:
53
+ self.get_conn().web_search("SpecStream", speed="fast", num=1)
54
+ except Exception as error: # the UI shows the message
55
+ return False, str(error)
56
+ return True, "Connection successfully tested"
57
+
58
+ def web_search(self, q: str, **kwargs: Any) -> dict[str, Any]:
59
+ return self.get_conn().web_search(q, **kwargs)
60
+
61
+ def extract_pages(self, urls: list[str], *, format: str = "markdown") -> dict[str, Any]:
62
+ return self.get_conn().extract_pages(urls, format=format)
63
+
64
+ def find_list(
65
+ self,
66
+ request: str,
67
+ *,
68
+ max_results: int,
69
+ max_price_usd: float,
70
+ idempotency_key: str,
71
+ wait_seconds: float = DEFAULT_WAIT_SECONDS,
72
+ poll_interval: float = 5.0,
73
+ locale: str = "en-US",
74
+ ) -> dict[str, Any]:
75
+ return self.get_conn().find_list(
76
+ request,
77
+ max_results=max_results,
78
+ max_price_usd=max_price_usd,
79
+ idempotency_key=idempotency_key,
80
+ wait_seconds=wait_seconds,
81
+ poll_interval=poll_interval,
82
+ locale=locale,
83
+ )
@@ -0,0 +1,7 @@
1
+ from specstream_provider.operators.specstream import (
2
+ SpecStreamDeepSearchOperator,
3
+ SpecStreamExtractOperator,
4
+ SpecStreamSearchOperator,
5
+ )
6
+
7
+ __all__ = ["SpecStreamDeepSearchOperator", "SpecStreamExtractOperator", "SpecStreamSearchOperator"]
@@ -0,0 +1,170 @@
1
+ """SpecStream operators: Search API, Extract API and Deep Search. Each pushes its result to XCom."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ from collections.abc import Sequence
7
+ from functools import cached_property
8
+ from typing import Any
9
+
10
+ try: # Airflow 3
11
+ from airflow.sdk import BaseOperator
12
+ except ImportError: # Airflow 2.9 and later 2.x
13
+ from airflow.models import BaseOperator
14
+
15
+ from airflow.exceptions import AirflowException
16
+
17
+ from specstream_provider._api import DEFAULT_WAIT_SECONDS, FINISHED, STOPPED, SpecStreamError
18
+ from specstream_provider.hooks.specstream import SpecStreamHook
19
+
20
+
21
+ class _SpecStreamOperator(BaseOperator):
22
+ def __init__(self, *, specstream_conn_id: str = SpecStreamHook.default_conn_name, timeout: float = 150.0, **kwargs: Any) -> None:
23
+ super().__init__(**kwargs)
24
+ self.specstream_conn_id = specstream_conn_id
25
+ self.timeout = timeout
26
+
27
+ @cached_property
28
+ def hook(self) -> SpecStreamHook:
29
+ return SpecStreamHook(specstream_conn_id=self.specstream_conn_id, timeout=self.timeout)
30
+
31
+ def _call(self, fn, *args: Any, **kwargs: Any) -> dict[str, Any]:
32
+ try:
33
+ return fn(*args, **kwargs)
34
+ except (SpecStreamError, ValueError) as error:
35
+ raise AirflowException(str(error)) from None
36
+
37
+
38
+ class SpecStreamSearchOperator(_SpecStreamOperator):
39
+ """Searches the live web with GET /v1/web-search and returns the answer, rows and ranked sources.
40
+
41
+ $5 per 1,000 searches of up to 10 results; speed="fast" gives the results alone in about a second
42
+ for $1 per 1,000.
43
+ """
44
+
45
+ template_fields: Sequence[str] = ("query", "country", "language")
46
+ ui_color = "#e8f1fb"
47
+
48
+ def __init__(
49
+ self,
50
+ *,
51
+ query: str,
52
+ passages: bool = False,
53
+ speed: str = "default",
54
+ num: int | None = None,
55
+ news: bool = False,
56
+ country: str | None = None,
57
+ language: str | None = None,
58
+ **kwargs: Any,
59
+ ) -> None:
60
+ super().__init__(**kwargs)
61
+ self.query = query
62
+ self.passages = passages
63
+ self.speed = speed
64
+ self.num = num
65
+ self.news = news
66
+ self.country = country
67
+ self.language = language
68
+
69
+ def execute(self, context: Any) -> dict[str, Any]:
70
+ return self._call(
71
+ self.hook.web_search,
72
+ self.query,
73
+ passages=self.passages,
74
+ speed=self.speed,
75
+ num=self.num,
76
+ news=self.news,
77
+ country=self.country,
78
+ language=self.language,
79
+ )
80
+
81
+
82
+ class SpecStreamExtractOperator(_SpecStreamOperator):
83
+ """Reads the main text, title and published date of 1 to 20 URLs with POST /v1/extract.
84
+
85
+ $0.80 per 1,000 pages; a page with no text is not charged.
86
+ """
87
+
88
+ template_fields: Sequence[str] = ("urls",)
89
+ ui_color = "#e8f1fb"
90
+
91
+ def __init__(self, *, urls: list[str] | str, format: str = "markdown", **kwargs: Any) -> None:
92
+ super().__init__(**kwargs)
93
+ self.urls = urls
94
+ self.format = format
95
+
96
+ def execute(self, context: Any) -> dict[str, Any]:
97
+ urls = [self.urls] if isinstance(self.urls, str) else list(self.urls or [])
98
+ return self._call(self.hook.extract_pages, urls, format=self.format)
99
+
100
+
101
+ def _run_key(context: Any, request: str, max_results: int, max_cents: int) -> str:
102
+ """One key per task instance and request: a retry of the same run continues the same list."""
103
+ ti = context.get("ti") or context.get("task_instance")
104
+ parts = [
105
+ str(getattr(ti, "dag_id", "") or ""),
106
+ str(getattr(ti, "task_id", "") or ""),
107
+ str(getattr(ti, "run_id", "") or context.get("run_id") or ""),
108
+ str(getattr(ti, "map_index", -1)),
109
+ request,
110
+ str(max_results),
111
+ str(max_cents),
112
+ ]
113
+ return "airflow-" + hashlib.sha256("|".join(parts).encode()).hexdigest()[:32]
114
+
115
+
116
+ class SpecStreamDeepSearchOperator(_SpecStreamOperator):
117
+ """Builds a list of every match on the live web as structured rows (Deep Search).
118
+
119
+ The run starts only when its quoted maximum is at or below ``max_price_usd``; otherwise nothing
120
+ runs and the task fails. Each delivered row is charged 5 cents, 15 cents or $1 depending on
121
+ what it needs. A retry of the same task instance continues the same list and never buys it twice.
122
+ Returns ``list_id``, ``status``, ``list_link``, ``row_count`` and ``rows``.
123
+ """
124
+
125
+ template_fields: Sequence[str] = ("request",)
126
+ ui_color = "#e8f1fb"
127
+
128
+ def __init__(
129
+ self,
130
+ *,
131
+ request: str,
132
+ max_price_usd: float,
133
+ max_results: int = 25,
134
+ wait_seconds: float = DEFAULT_WAIT_SECONDS,
135
+ poll_interval: float = 5.0,
136
+ locale: str = "en-US",
137
+ fail_if_unfinished: bool = True,
138
+ **kwargs: Any,
139
+ ) -> None:
140
+ super().__init__(**kwargs)
141
+ self.request = request
142
+ self.max_price_usd = max_price_usd
143
+ self.max_results = max_results
144
+ self.wait_seconds = wait_seconds
145
+ self.poll_interval = poll_interval
146
+ self.locale = locale
147
+ self.fail_if_unfinished = fail_if_unfinished
148
+
149
+ def execute(self, context: Any) -> dict[str, Any]:
150
+ request = (self.request or "").strip()
151
+ key = _run_key(context, request, int(self.max_results), round(float(self.max_price_usd) * 100))
152
+ result = self._call(
153
+ self.hook.find_list,
154
+ request,
155
+ max_results=self.max_results,
156
+ max_price_usd=self.max_price_usd,
157
+ idempotency_key=key,
158
+ wait_seconds=self.wait_seconds,
159
+ poll_interval=self.poll_interval,
160
+ locale=self.locale,
161
+ )
162
+ status = result.get("status")
163
+ if status in {"needs_edit", "over_maximum"}:
164
+ raise AirflowException(result["message"])
165
+ if status in STOPPED:
166
+ raise AirflowException(f"The list {result.get('list_link')} stopped with status {status}.")
167
+ if status not in FINISHED and self.fail_if_unfinished:
168
+ raise AirflowException(f"The list {result.get('list_link')} is still running; a retry of this task continues it.")
169
+ self.log.info("SpecStream list %s: %s rows (%s)", result.get("list_id"), result.get("row_count"), status)
170
+ return result
@@ -0,0 +1,7 @@
1
+ import os
2
+ import tempfile
3
+
4
+ # Airflow reads its home and config on import: keep both in a throwaway folder, with no database.
5
+ os.environ.setdefault("AIRFLOW_HOME", tempfile.mkdtemp(prefix="airflow-home-"))
6
+ os.environ.setdefault("AIRFLOW__CORE__LOAD_EXAMPLES", "False")
7
+ os.environ.setdefault("AIRFLOW__CORE__UNIT_TEST_MODE", "True")
@@ -0,0 +1,218 @@
1
+ import io
2
+ import json
3
+ import urllib.error
4
+ import urllib.parse
5
+ from importlib.metadata import entry_points
6
+ from types import SimpleNamespace
7
+
8
+ import pytest
9
+ from airflow.exceptions import AirflowException
10
+
11
+ from specstream_provider import _api, get_provider_info
12
+ from specstream_provider.hooks.specstream import SpecStreamHook
13
+ from specstream_provider.operators.specstream import (
14
+ SpecStreamDeepSearchOperator,
15
+ SpecStreamExtractOperator,
16
+ SpecStreamSearchOperator,
17
+ )
18
+
19
+ FIND_ID = "fnd_test123"
20
+
21
+
22
+ @pytest.fixture(autouse=True)
23
+ def connection(monkeypatch):
24
+ monkeypatch.setenv("AIRFLOW_CONN_SPECSTREAM_DEFAULT", json.dumps({"conn_type": "specstream", "password": "ss_test"}))
25
+ monkeypatch.setenv("AIRFLOW_CONN_SPECSTREAM_LOCAL", json.dumps({"conn_type": "specstream", "password": "ss_other", "host": "localhost:9000"}))
26
+
27
+
28
+ class Recorder:
29
+ """Stands in for the network: records each request and answers with the next scripted reply."""
30
+
31
+ def __init__(self, *replies):
32
+ self.replies = list(replies)
33
+ self.requests = []
34
+
35
+ def __call__(self, request, timeout):
36
+ self.requests.append(request)
37
+ reply = self.replies.pop(0) if len(self.replies) > 1 else self.replies[0]
38
+ if isinstance(reply, Exception):
39
+ raise reply
40
+ return io.BytesIO(json.dumps({"data": reply}).encode())
41
+
42
+
43
+ def _context(run_id="manual__1", try_number=1):
44
+ return {"ti": SimpleNamespace(dag_id="d", task_id="t", run_id=run_id, map_index=-1, try_number=try_number)}
45
+
46
+
47
+ def test_provider_info_names_the_hook_and_is_registered():
48
+ info = get_provider_info()
49
+ assert info["package-name"] == "airflow-provider-specstream"
50
+ assert info["connection-types"] == [{"connection-type": "specstream", "hook-class-name": "specstream_provider.hooks.specstream.SpecStreamHook"}]
51
+ names = {ep.value for ep in entry_points(group="apache_airflow_provider")}
52
+ assert "specstream_provider:get_provider_info" in names
53
+
54
+
55
+ def test_hook_reads_key_and_host_from_the_connection():
56
+ api = SpecStreamHook().get_conn()
57
+ assert (api.api_key, api.base_url) == ("ss_test", "https://api.specstream.ai")
58
+ api = SpecStreamHook(specstream_conn_id="specstream_local").get_conn()
59
+ assert (api.api_key, api.base_url) == ("ss_other", "https://localhost:9000")
60
+
61
+
62
+ def test_search_operator_sends_query_speed_and_key(monkeypatch):
63
+ recorder = Recorder({"query": "q", "sources": [{"url": "https://a.example"}]})
64
+ op = SpecStreamSearchOperator(task_id="s", query="airflow release", speed="fast", num=5)
65
+ op.hook.get_conn().opener = recorder
66
+ out = op.execute(_context())
67
+ assert out["sources"][0]["url"] == "https://a.example"
68
+ request = recorder.requests[0]
69
+ url = urllib.parse.urlparse(request.full_url)
70
+ assert (url.netloc, url.path) == ("api.specstream.ai", "/v1/web-search")
71
+ assert urllib.parse.parse_qs(url.query) == {"q": ["airflow release"], "speed": ["fast"], "num": ["5"]}
72
+ assert request.get_header("Authorization") == "Bearer ss_test"
73
+ assert request.get_method() == "GET"
74
+
75
+
76
+ def test_search_operator_refuses_a_bad_speed_without_a_call():
77
+ recorder = Recorder({})
78
+ op = SpecStreamSearchOperator(task_id="s", query="x", speed="turbo")
79
+ op.hook.get_conn().opener = recorder
80
+ with pytest.raises(AirflowException, match="speed"):
81
+ op.execute(_context())
82
+ assert recorder.requests == []
83
+
84
+
85
+ def test_extract_operator_posts_urls_and_accepts_a_single_templated_url():
86
+ recorder = Recorder({"results": [{"url": "https://a.example", "text": "hi"}]})
87
+ op = SpecStreamExtractOperator(task_id="e", urls="https://a.example", format="text")
88
+ op.hook.get_conn().opener = recorder
89
+ out = op.execute(_context())
90
+ assert out["results"][0]["text"] == "hi"
91
+ request = recorder.requests[0]
92
+ assert request.get_method() == "POST"
93
+ assert request.full_url.endswith("/v1/extract")
94
+ assert json.loads(request.data) == {"urls": ["https://a.example"], "format": "text"}
95
+
96
+
97
+ def test_api_error_becomes_an_airflow_error_with_the_message():
98
+ error = urllib.error.HTTPError("u", 401, "Unauthorized", {}, io.BytesIO(json.dumps({"error": {"message": "bad key"}}).encode()))
99
+ op = SpecStreamSearchOperator(task_id="s", query="x")
100
+ op.hook.get_conn().opener = Recorder(error)
101
+ with pytest.raises(AirflowException, match="401: bad key"):
102
+ op.execute(_context())
103
+
104
+
105
+ def _row(ordinal, name):
106
+ return {"entity_id": f"e{ordinal}", "ordinal": ordinal, "details": [{"label": "Organization", "display": name}]}
107
+
108
+
109
+ def _rows_page(status, *names):
110
+ rows = [_row(i + 1, n) for i, n in enumerate(names)]
111
+ flat = [{"id": f"{FIND_ID}:e{i + 1}", "Organization": n, "Organization_source": f"https://src/{n}", "source_url": f"https://src/{n}", "checked_at": "2026-11-12T00:00:00Z"} for i, n in enumerate(names)]
112
+ return {"status": status, "rows": rows, "flat_rows": flat}
113
+
114
+
115
+ class FakeApi:
116
+ def __init__(self, maximum_cents=300, existing=None, pages=None, parse=None):
117
+ self.calls = []
118
+ self.maximum_cents = maximum_cents
119
+ self.existing = existing
120
+ self.pages = pages or [_rows_page("completed", "Alpha", "Beta")]
121
+ self.parse = parse or {"status": "runnable", "ast_hash": "h1"}
122
+
123
+ def request(self, method, path, body=None, *, allow_404=False):
124
+ self.calls.append((method, path, body))
125
+ if path.startswith("/v1/capacity/requests/"):
126
+ return self.existing
127
+ if path == "/v1/parse":
128
+ return self.parse
129
+ if path == "/v1/capacity/quotes":
130
+ return {"quote_id": "q1", "quote_hash": "qh", "maximum_cents": self.maximum_cents}
131
+ if path == "/v1/capacity/executions":
132
+ return {"find_id": FIND_ID}
133
+ if "/rows" in path:
134
+ return self.pages.pop(0) if len(self.pages) > 1 else self.pages[0]
135
+ raise AssertionError(path)
136
+
137
+ def paths(self):
138
+ return [p for _, p, _ in self.calls]
139
+
140
+
141
+ @pytest.fixture
142
+ def fake(monkeypatch):
143
+ def install(**kwargs):
144
+ api = FakeApi(**kwargs)
145
+ monkeypatch.setattr(_api.SpecStreamAPI, "request", lambda self, *a, **k: api.request(*a, **k))
146
+ return api
147
+
148
+ return install
149
+
150
+
151
+ def _deep(**kwargs):
152
+ op = SpecStreamDeepSearchOperator(task_id="t", request=kwargs.pop("request", "Open-source orchestrators"), max_price_usd=kwargs.pop("max_price_usd", 5), poll_interval=0, **kwargs)
153
+ op.hook.get_conn().sleep = lambda s: None
154
+ return op
155
+
156
+
157
+ def test_deep_search_buys_within_the_maximum_and_returns_rows_with_sources(fake):
158
+ api = fake()
159
+ out = _deep().execute(_context())
160
+ assert api.paths()[1:4] == ["/v1/parse", "/v1/capacity/quotes", "/v1/capacity/executions"]
161
+ execution = api.calls[3][2]
162
+ assert execution["confirm_max_cents"] == 300 and execution["idempotency_key"].startswith("airflow-")
163
+ assert out["status"] == "completed" and out["row_count"] == 2
164
+ assert out["rows"][0]["Organization"] == "Alpha"
165
+ assert out["rows"][0]["Organization_source"] == "https://src/Alpha"
166
+ assert out["rows"][0]["list_link"].endswith(FIND_ID)
167
+
168
+
169
+ def test_deep_search_over_the_maximum_runs_nothing(fake):
170
+ api = fake(maximum_cents=900)
171
+ with pytest.raises(AirflowException, match=r"up to \$9.00"):
172
+ _deep(max_price_usd=5).execute(_context())
173
+ assert "/v1/capacity/executions" not in api.paths()
174
+
175
+
176
+ def test_deep_search_unclear_request_runs_nothing(fake):
177
+ api = fake(parse={"status": "needs_input", "canonical_sentence": "things"})
178
+ with pytest.raises(AirflowException, match="clearer request"):
179
+ _deep().execute(_context())
180
+ assert "/v1/capacity/quotes" not in api.paths()
181
+
182
+
183
+ def test_a_retry_continues_the_same_list_and_never_buys_twice(fake):
184
+ first = fake()
185
+ _deep().execute(_context(try_number=1))
186
+ key = first.calls[3][2]["idempotency_key"]
187
+ retry = fake(existing={"find_id": FIND_ID, "maximum_cents": 300})
188
+ out = _deep().execute(_context(try_number=2))
189
+ assert retry.paths()[0] == f"/v1/capacity/requests/{key}"
190
+ assert "/v1/capacity/executions" not in retry.paths()
191
+ assert out["list_id"] == FIND_ID
192
+
193
+
194
+ def test_another_run_gets_another_key(fake):
195
+ a = fake()
196
+ _deep().execute(_context(run_id="r1"))
197
+ b = fake()
198
+ _deep().execute(_context(run_id="r2"))
199
+ assert a.calls[3][2]["idempotency_key"] != b.calls[3][2]["idempotency_key"]
200
+
201
+
202
+ def test_deep_search_still_running_fails_for_a_retry_unless_asked_not_to(fake):
203
+ fake(pages=[_rows_page("running", "Alpha")])
204
+ with pytest.raises(AirflowException, match="still running"):
205
+ _deep(wait_seconds=0).execute(_context())
206
+ fake(pages=[_rows_page("running", "Alpha")])
207
+ out = _deep(wait_seconds=0, fail_if_unfinished=False).execute(_context())
208
+ assert out["status"] == "running" and out["row_count"] == 1
209
+
210
+
211
+ def test_deep_search_failed_list_fails_the_task(fake):
212
+ fake(pages=[_rows_page("failed")])
213
+ with pytest.raises(AirflowException, match="stopped with status failed"):
214
+ _deep().execute(_context())
215
+
216
+
217
+ def test_example_dag_loads():
218
+ from specstream_provider.example_dags import example_specstream # noqa: F401