helios-semantic 0.3.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,18 @@
1
+ tpcds/
2
+ *.parquet
3
+ __pycache__/
4
+ .env
5
+ .env.sh
6
+ /requirements.lock
7
+ .helios-python/
8
+ state/
9
+ *.db-wal
10
+ *.db-shm
11
+ node_modules/
12
+ *.tsbuildinfo
13
+ .cursor/
14
+ runs/
15
+ run_archive/
16
+ .DS_Store
17
+ *.pptx
18
+ .venv/
@@ -0,0 +1,129 @@
1
+ Metadata-Version: 2.5
2
+ Name: helios-semantic
3
+ Version: 0.3.0
4
+ Summary: Helios: build semantic models of your data and query them; the package a developer installs
5
+ Project-URL: Homepage, https://github.com/christopheraburns/helios
6
+ Project-URL: Documentation, https://github.com/christopheraburns/helios/tree/main/packages/helios-semantic#readme
7
+ Project-URL: Repository, https://github.com/christopheraburns/helios
8
+ Project-URL: Issues, https://github.com/christopheraburns/helios/issues
9
+ Author: Helios Team
10
+ License-Expression: Apache-2.0
11
+ Keywords: duckdb,llm,ossie,semantic layer,semantic model,text-to-sql
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3 :: Only
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Database
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.11
23
+ Requires-Dist: helios-cortex>=0.3.0
24
+ Requires-Dist: helios-model>=0.3.0
25
+ Requires-Dist: helios-serve>=0.3.0
26
+ Provides-Extra: all
27
+ Requires-Dist: helios-cloudera>=0.3.0; extra == 'all'
28
+ Requires-Dist: helios-cortex[azure]>=0.3.0; extra == 'all'
29
+ Requires-Dist: helios-cortex[gcs]>=0.3.0; extra == 'all'
30
+ Requires-Dist: helios-cortex[llm]>=0.3.0; extra == 'all'
31
+ Requires-Dist: helios-cortex[ontology]>=0.3.0; extra == 'all'
32
+ Requires-Dist: helios-cortex[ozone]>=0.3.0; extra == 'all'
33
+ Requires-Dist: helios-cortex[postgres]>=0.3.0; extra == 'all'
34
+ Requires-Dist: helios-cortex[s3]>=0.3.0; extra == 'all'
35
+ Requires-Dist: helios-cortex[trino]>=0.3.0; extra == 'all'
36
+ Requires-Dist: helios-mcp>=0.3.0; extra == 'all'
37
+ Requires-Dist: helios-serve[eval]>=0.3.0; extra == 'all'
38
+ Provides-Extra: azure
39
+ Requires-Dist: helios-cortex[azure]>=0.3.0; extra == 'azure'
40
+ Provides-Extra: cloudera
41
+ Requires-Dist: helios-cloudera>=0.3.0; extra == 'cloudera'
42
+ Provides-Extra: gcs
43
+ Requires-Dist: helios-cortex[gcs]>=0.3.0; extra == 'gcs'
44
+ Provides-Extra: llm
45
+ Requires-Dist: helios-cortex[llm]>=0.3.0; extra == 'llm'
46
+ Requires-Dist: helios-serve[eval]>=0.3.0; extra == 'llm'
47
+ Provides-Extra: mcp
48
+ Requires-Dist: helios-mcp>=0.3.0; extra == 'mcp'
49
+ Provides-Extra: ontology
50
+ Requires-Dist: helios-cortex[ontology]>=0.3.0; extra == 'ontology'
51
+ Provides-Extra: ozone
52
+ Requires-Dist: helios-cortex[ozone]>=0.3.0; extra == 'ozone'
53
+ Provides-Extra: postgres
54
+ Requires-Dist: helios-cortex[postgres]>=0.3.0; extra == 'postgres'
55
+ Provides-Extra: s3
56
+ Requires-Dist: helios-cortex[s3]>=0.3.0; extra == 's3'
57
+ Provides-Extra: trino
58
+ Requires-Dist: helios-cortex[trino]>=0.3.0; extra == 'trino'
59
+ Description-Content-Type: text/markdown
60
+
61
+ # helios-semantic
62
+
63
+ Helios builds semantic models of your data (datasets, fields, metrics, relationships)
64
+ and answers questions with them: it compiles metrics and dimensions to SQL and runs it on
65
+ your warehouse as the person asking. This is the package to install.
66
+
67
+ ```sh
68
+ pip install helios-semantic # DuckDB and SQLite, on a laptop
69
+ pip install "helios-semantic[cloudera,llm]" # Impala and Atlas; an LLM to propose models
70
+ ```
71
+
72
+ ## The `Helios` facade
73
+
74
+ ```python
75
+ from helios_semantic import Helios
76
+
77
+ helios = Helios.from_settings() # helios.toml, HELIOS_* variables, then defaults
78
+
79
+ helios.models() # [{"name": "shop", "status": "published"}]
80
+ helios.search("revenue by region") # the datasets, fields and metrics involved
81
+ helios.compile(["revenue"], ["shop.customers.c_region"]).sql
82
+ result = helios.query(["revenue"], ["shop.customers.c_region"],
83
+ filters=[{"column": "shop.customers.c_region", "op": "=", "value": "east"}])
84
+ result.records() # [{"c_region": "east", "revenue": 3750.0}]
85
+
86
+ helios.publish("20261110T120000Z", accept_pending=True) # a discovery run's proposals
87
+ helios.health()
88
+ ```
89
+
90
+ A method raises `HeliosError` (with `code`, `message` and `retryable`) where a tool
91
+ refuses: an unknown metric is `invalid_semantic_query`, a model nobody published
92
+ `model_not_found`.
93
+
94
+ **Who runs the queries.** `Helios.from_settings()` with no caller is your own program,
95
+ running with the credentials you configured, so a connection in `service` identity mode
96
+ runs its queries. `Helios.from_settings(caller=Caller("alice"))`, or
97
+ `helios.as_caller(Caller("alice"))`, acts for alice: the warehouse runs the query as her
98
+ (`impersonate` or `token` mode) and enforces her permissions, and a service-identity
99
+ connection refuses. A server for many users gives each request its own `as_caller`, or
100
+ uses helios-serve's tools directly.
101
+
102
+ ## The `helios` command
103
+
104
+ ```sh
105
+ helios init # a starter helios.toml
106
+ helios init --sample # or a sample project: a TPC-DS star in DuckDB, its model published
107
+ helios harvest --source warehouse --database shop --model shop
108
+ helios profile && helios propose && helios publish --accept-pending
109
+ helios eval sample-suite.json # with [llm]: score an LLM on the sample's questions
110
+ ```
111
+
112
+ ## Extras
113
+
114
+ | Extra | Adds |
115
+ |---|---|
116
+ | `cloudera` | helios-cloudera: the Impala engine, the Atlas catalog, the Workbench settings profile |
117
+ | `llm` | an LLM client, to propose models and run `helios eval` |
118
+ | `postgres`, `trino` | a Postgres registry and engine; the Trino engine |
119
+ | `s3`, `azure`, `gcs`, `ozone` | published models on object storage |
120
+ | `ontology` | LinkML ontology parsing |
121
+ | `mcp` | helios-mcp: `helios mcp`, the tools over MCP for your coding agent |
122
+ | `all` | all of the above |
123
+
124
+ ## The libraries
125
+
126
+ helios-semantic installs helios-cortex (settings, compiler, engines, registry, the
127
+ `helios` command), helios-model (harvest, profile, propose, publish) and helios-serve
128
+ (the tools, their registry, health and evaluation). Use them directly for more control;
129
+ helios-mcp (a local MCP server for your agent) and helios-cloudera install separately.
@@ -0,0 +1,69 @@
1
+ # helios-semantic
2
+
3
+ Helios builds semantic models of your data (datasets, fields, metrics, relationships)
4
+ and answers questions with them: it compiles metrics and dimensions to SQL and runs it on
5
+ your warehouse as the person asking. This is the package to install.
6
+
7
+ ```sh
8
+ pip install helios-semantic # DuckDB and SQLite, on a laptop
9
+ pip install "helios-semantic[cloudera,llm]" # Impala and Atlas; an LLM to propose models
10
+ ```
11
+
12
+ ## The `Helios` facade
13
+
14
+ ```python
15
+ from helios_semantic import Helios
16
+
17
+ helios = Helios.from_settings() # helios.toml, HELIOS_* variables, then defaults
18
+
19
+ helios.models() # [{"name": "shop", "status": "published"}]
20
+ helios.search("revenue by region") # the datasets, fields and metrics involved
21
+ helios.compile(["revenue"], ["shop.customers.c_region"]).sql
22
+ result = helios.query(["revenue"], ["shop.customers.c_region"],
23
+ filters=[{"column": "shop.customers.c_region", "op": "=", "value": "east"}])
24
+ result.records() # [{"c_region": "east", "revenue": 3750.0}]
25
+
26
+ helios.publish("20261110T120000Z", accept_pending=True) # a discovery run's proposals
27
+ helios.health()
28
+ ```
29
+
30
+ A method raises `HeliosError` (with `code`, `message` and `retryable`) where a tool
31
+ refuses: an unknown metric is `invalid_semantic_query`, a model nobody published
32
+ `model_not_found`.
33
+
34
+ **Who runs the queries.** `Helios.from_settings()` with no caller is your own program,
35
+ running with the credentials you configured, so a connection in `service` identity mode
36
+ runs its queries. `Helios.from_settings(caller=Caller("alice"))`, or
37
+ `helios.as_caller(Caller("alice"))`, acts for alice: the warehouse runs the query as her
38
+ (`impersonate` or `token` mode) and enforces her permissions, and a service-identity
39
+ connection refuses. A server for many users gives each request its own `as_caller`, or
40
+ uses helios-serve's tools directly.
41
+
42
+ ## The `helios` command
43
+
44
+ ```sh
45
+ helios init # a starter helios.toml
46
+ helios init --sample # or a sample project: a TPC-DS star in DuckDB, its model published
47
+ helios harvest --source warehouse --database shop --model shop
48
+ helios profile && helios propose && helios publish --accept-pending
49
+ helios eval sample-suite.json # with [llm]: score an LLM on the sample's questions
50
+ ```
51
+
52
+ ## Extras
53
+
54
+ | Extra | Adds |
55
+ |---|---|
56
+ | `cloudera` | helios-cloudera: the Impala engine, the Atlas catalog, the Workbench settings profile |
57
+ | `llm` | an LLM client, to propose models and run `helios eval` |
58
+ | `postgres`, `trino` | a Postgres registry and engine; the Trino engine |
59
+ | `s3`, `azure`, `gcs`, `ozone` | published models on object storage |
60
+ | `ontology` | LinkML ontology parsing |
61
+ | `mcp` | helios-mcp: `helios mcp`, the tools over MCP for your coding agent |
62
+ | `all` | all of the above |
63
+
64
+ ## The libraries
65
+
66
+ helios-semantic installs helios-cortex (settings, compiler, engines, registry, the
67
+ `helios` command), helios-model (harvest, profile, propose, publish) and helios-serve
68
+ (the tools, their registry, health and evaluation). Use them directly for more control;
69
+ helios-mcp (a local MCP server for your agent) and helios-cloudera install separately.
@@ -0,0 +1,61 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "helios-semantic"
7
+ version = "0.3.0"
8
+ description = "Helios: build semantic models of your data and query them; the package a developer installs"
9
+ readme = "README.md"
10
+ authors = [{name = "Helios Team"}]
11
+ license = "Apache-2.0"
12
+ requires-python = ">=3.11"
13
+ keywords = ["semantic layer", "semantic model", "text-to-sql", "ossie", "llm", "duckdb"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Operating System :: OS Independent",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
23
+ "Topic :: Database",
24
+ "Typing :: Typed",
25
+ ]
26
+ # The Helios libraries a developer needs on a laptop. The `helios` command comes with
27
+ # helios-cortex; helios-model adds harvest/profile/propose/publish, helios-serve eval.
28
+ dependencies = [
29
+ "helios-cortex>=0.3.0",
30
+ "helios-model>=0.3.0",
31
+ "helios-serve>=0.3.0",
32
+ ]
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/christopheraburns/helios"
36
+ Documentation = "https://github.com/christopheraburns/helios/tree/main/packages/helios-semantic#readme"
37
+ Repository = "https://github.com/christopheraburns/helios"
38
+ Issues = "https://github.com/christopheraburns/helios/issues"
39
+
40
+ [project.optional-dependencies]
41
+ # Cloudera: the Impala engine, the Atlas catalog and the Workbench settings profile.
42
+ cloudera = ["helios-cloudera>=0.3.0"]
43
+ # An LLM provider, to propose models and run evaluations.
44
+ llm = ["helios-cortex[llm]>=0.3.0", "helios-serve[eval]>=0.3.0"]
45
+ # Databases and engines beyond DuckDB and SQLite.
46
+ postgres = ["helios-cortex[postgres]>=0.3.0"]
47
+ trino = ["helios-cortex[trino]>=0.3.0"]
48
+ # Object storage for published models.
49
+ s3 = ["helios-cortex[s3]>=0.3.0"]
50
+ azure = ["helios-cortex[azure]>=0.3.0"]
51
+ gcs = ["helios-cortex[gcs]>=0.3.0"]
52
+ ozone = ["helios-cortex[ozone]>=0.3.0"]
53
+ # LinkML ontology parsing.
54
+ ontology = ["helios-cortex[ontology]>=0.3.0"]
55
+ # helios mcp: the tools over MCP on stdio, for one developer's local agent.
56
+ mcp = ["helios-mcp>=0.3.0"]
57
+ # Everything above.
58
+ all = ["helios-semantic[cloudera,llm,mcp,postgres,trino,s3,azure,gcs,ozone,ontology]"]
59
+
60
+ [tool.hatch.build.targets.wheel]
61
+ packages = ["src/helios_semantic"]
@@ -0,0 +1,33 @@
1
+ """Helios: build semantic models of your data and query them (burndown 6.6).
2
+
3
+ from helios_semantic import Helios
4
+
5
+ helios = Helios.from_settings() # helios.toml, HELIOS_* variables, defaults
6
+ helios.models()
7
+ helios.query(["revenue"], ["shop.customers.c_region"]).records()
8
+
9
+ ``Helios`` is a facade over the libraries this package installs: helios-cortex (settings,
10
+ compiler, engines, registry, the ``helios`` command), helios-model (discovery and
11
+ publishing) and helios-serve (the tools). Extras add the rest:
12
+ ``pip install "helios-semantic[cloudera,llm]"``.
13
+ """
14
+
15
+ _EXPORTS = {name: "facade" for name in ("Helios", "HeliosError", "CompiledQuery", "QueryResult")}
16
+
17
+ __all__ = sorted(_EXPORTS)
18
+
19
+
20
+ def __getattr__(name: str):
21
+ # Exports are imported on first use, so importing helios_semantic loads nothing heavy.
22
+ if name in _EXPORTS:
23
+ from importlib import import_module
24
+
25
+ return getattr(import_module(f"helios_semantic.{_EXPORTS[name]}"), name)
26
+ if name == "__version__":
27
+ from importlib.metadata import PackageNotFoundError, version
28
+
29
+ try:
30
+ return version("helios-semantic")
31
+ except PackageNotFoundError: # running from a source path without an install
32
+ return "0.0.0+unknown"
33
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
@@ -0,0 +1,210 @@
1
+ """The ``Helios`` facade: one object for a developer's program.
2
+
3
+ helios = Helios.from_settings()
4
+ helios.models() # the published models
5
+ helios.search("revenue by region") # what a question involves
6
+ helios.compile(["revenue"], ["shop.customers.c_region"]).sql
7
+ helios.query(["revenue"], ["shop.customers.c_region"]).records()
8
+ helios.publish("20261110T120000Z", accept_pending=True) # a discovery run's reviewed proposals
9
+
10
+ Each method calls the helios-serve tool of the same purpose (or helios-model's
11
+ ``Publisher``) and raises ``HeliosError`` where the tool returns an error.
12
+
13
+ Who runs the queries: a facade built with no caller is one user's program, running with
14
+ the configured credentials, so a connection in ``service`` identity mode runs its
15
+ queries (helios-serve's ``single_user_policy``). ``Helios.from_settings(caller=...)`` or
16
+ ``helios.as_caller(caller)`` act for that caller instead: the warehouse runs the query as
17
+ them (``impersonate`` or ``token`` mode) and a service-identity connection refuses, as in
18
+ every shared deployment. A host serving many users gives each request its own
19
+ ``as_caller``, or uses helios-serve's tools directly.
20
+ """
21
+ from __future__ import annotations
22
+
23
+ import dataclasses
24
+ import os
25
+ from collections.abc import Sequence
26
+ from dataclasses import dataclass
27
+ from typing import TYPE_CHECKING, Any
28
+
29
+ from helios_cortex.caller import Caller
30
+
31
+ if TYPE_CHECKING:
32
+ from helios_cortex.settings import Settings
33
+ from helios_model import Proposals, Publication
34
+ from helios_serve import Registry, Stores
35
+
36
+
37
+ class HeliosError(Exception):
38
+ """What a tool refused or could not do: ``code`` (helios-serve's error codes, such as
39
+ ``invalid_semantic_query`` or ``model_not_found``), ``message`` and ``retryable``."""
40
+
41
+ def __init__(self, code: str, message: str, *, retryable: bool = False):
42
+ super().__init__(f"{code}: {message}")
43
+ self.code = code
44
+ self.message = message
45
+ self.retryable = retryable
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class CompiledQuery:
50
+ sql: str
51
+ dialect: str
52
+ dataset: str # the fact table
53
+ joins: tuple[str, ...] # the other tables it joins
54
+ columns: tuple[str, ...]
55
+
56
+
57
+ @dataclass(frozen=True)
58
+ class QueryResult:
59
+ sql: str
60
+ columns: tuple[str, ...]
61
+ rows: tuple[tuple[Any, ...], ...]
62
+ dataset: str
63
+ joins: tuple[str, ...]
64
+
65
+ def records(self) -> list[dict[str, Any]]:
66
+ """The rows as dicts by column name."""
67
+ return [dict(zip(self.columns, row)) for row in self.rows]
68
+
69
+
70
+ def _list(value: str | Sequence[str] | None) -> list[str] | None:
71
+ if value is None:
72
+ return None
73
+ return [value] if isinstance(value, str) else list(value)
74
+
75
+
76
+ class Helios:
77
+ """Published semantic models, for one caller (None: this program's own user)."""
78
+
79
+ def __init__(self, stores: Stores, *, caller: Caller | None = None, registry: Registry | None = None):
80
+ self.stores = stores
81
+ self.caller = caller
82
+ self._registry = registry
83
+
84
+ @classmethod
85
+ def from_settings(cls, settings: Settings | None = None, *, profile: str | None = None,
86
+ config: str | os.PathLike[str] | None = None, caller: Caller | None = None,
87
+ **overrides: Any) -> Helios:
88
+ """The registry and published models ``settings`` name (default: ``load_settings``
89
+ with ``profile`` and ``config``, as the ``helios`` command reads them).
90
+ ``overrides`` replace parts of helios-serve's ``Stores`` (``visibility``,
91
+ ``data_policy``, ``audit``, ``engines``, ``catalogs``, ``registry``, ``models``)."""
92
+ from helios_serve import Stores, single_user_policy
93
+
94
+ if settings is None:
95
+ from helios_cortex.settings import load_settings
96
+
97
+ settings = load_settings(profile, config)
98
+ elif profile is not None or config is not None:
99
+ raise TypeError("pass settings, or profile/config to load them, not both")
100
+ if caller is None and "data_policy" not in overrides:
101
+ overrides["data_policy"] = single_user_policy()
102
+ return cls(Stores.from_settings(settings, **overrides), caller=caller)
103
+
104
+ def as_caller(self, caller: Caller | None) -> Helios:
105
+ """The same models, acting for ``caller``: queries run as them, under the default
106
+ data policy (the warehouse enforces their access) unless the host set its own."""
107
+ from helios_cortex.data_authorization import DataPolicy
108
+ from helios_serve.stores import SingleUserAuthorizer
109
+
110
+ stores = self.stores
111
+ if caller is not None and isinstance(stores.data_policy.platform, SingleUserAuthorizer):
112
+ stores = dataclasses.replace(stores, data_policy=DataPolicy(restrictions=stores.data_policy.restrictions))
113
+ return Helios(stores, caller=caller, registry=self._registry)
114
+
115
+ @property
116
+ def settings(self) -> Settings:
117
+ return self.stores.settings
118
+
119
+ @property
120
+ def tools(self) -> Registry:
121
+ """helios-serve's tool registry, for a program that offers the tools to an agent."""
122
+ if self._registry is None:
123
+ from helios_serve import load_registry
124
+
125
+ self._registry = load_registry()
126
+ return self._registry
127
+
128
+ def _call(self, name: str, **arguments: Any) -> dict[str, Any]:
129
+ from helios_serve import tools
130
+
131
+ result = getattr(tools, name)(self.caller, self.stores, **arguments)
132
+ if isinstance(result, dict) and result.get("error"):
133
+ raise HeliosError(str(result["error"]), str(result.get("message") or result["error"]),
134
+ retryable=result.get("retryable") is True)
135
+ return result
136
+
137
+ # ------------------------------------------------------------------ reading
138
+ def models(self) -> list[dict[str, Any]]:
139
+ """The published models this caller may see: ``[{"name", "status"}]``."""
140
+ return self._call("list_models")["models"]
141
+
142
+ def describe(self, model: str | None = None) -> dict[str, Any]:
143
+ """A model's datasets, fields, metrics and relationships (the first model by default)."""
144
+ return self._call("describe_model", model=model)
145
+
146
+ def search(self, question: str, *, limit: int = 10, model: str | None = None) -> list[dict[str, Any]]:
147
+ """The datasets, fields and metrics ``question`` involves, best first."""
148
+ return self._call("search_semantics", question=question, limit=limit, model=model)["matches"]
149
+
150
+ def compile(self, metrics: str | Sequence[str], dimensions: str | Sequence[str] | None = None,
151
+ filters: Sequence[dict[str, Any]] | None = None, *, limit: int = 100, dialect: str | None = None,
152
+ model: str | None = None) -> CompiledQuery:
153
+ """The SQL for ``metrics`` by ``dimensions`` (database.table.column), filtered by
154
+ ``filters`` (``{"column", "op", "value"}``), in ``dialect`` (default: the model's
155
+ own warehouse's)."""
156
+ compiled = self._call("compile_query", metrics=_list(metrics), dimensions=_list(dimensions),
157
+ filters=list(filters) if filters is not None else None, limit=limit,
158
+ dialect=dialect, model=model)
159
+ return CompiledQuery(compiled["sql"], compiled["dialect"], compiled["dataset"], tuple(compiled["joins"]),
160
+ tuple(compiled["columns"]))
161
+
162
+ def query(self, metrics: str | Sequence[str], dimensions: str | Sequence[str] | None = None,
163
+ filters: Sequence[dict[str, Any]] | None = None, *, limit: int = 100,
164
+ model: str | None = None) -> QueryResult:
165
+ """Compile and run on the model's warehouse, as this facade's caller. Values are
166
+ as the engine returns them (``Decimal``, ``date``, ...)."""
167
+ result = self._call("query_values", metrics=_list(metrics), dimensions=_list(dimensions),
168
+ filters=list(filters) if filters is not None else None, limit=limit, model=model)
169
+ return QueryResult(result["sql"], tuple(result["columns"]), tuple(tuple(r) for r in result["rows"]),
170
+ result["dataset"], tuple(result["joins"]))
171
+
172
+ def health(self, *, deep: bool = False) -> dict[str, Any]:
173
+ """helios-serve's ``health``: the registry and the models, and with ``deep`` the
174
+ warehouse connections and the catalog."""
175
+ from helios_serve import health
176
+
177
+ return health(self.stores, deep=deep)
178
+
179
+ # ------------------------------------------------------------------ publishing
180
+ def publish(self, proposals: Proposals | str, *, accept_pending: bool = False,
181
+ min_confidence: float | None = None) -> Publication:
182
+ """Publish a discovery run's reviewed proposals (``Proposals``, or the run id) as
183
+ the model's new active revision, recorded as published by this facade's caller.
184
+ ``accept_pending`` (or ``min_confidence``) first accepts the elements nobody has
185
+ decided on, as ``helios publish --accept-pending`` does. The model must be in the
186
+ registry. Raises HeliosError (``model_not_registered``, ``publication_invalid`` or
187
+ ``discovery_failed``) before writing anything."""
188
+ from helios_model import DiscoveryError, ModelNotRegistered, Proposer, Publisher
189
+ from helios_model.publication import PublicationValidationError
190
+
191
+ artifacts = getattr(self.stores.models, "artifacts", None)
192
+ try:
193
+ proposer = Proposer(self.settings, artifacts=artifacts)
194
+ if isinstance(proposals, str):
195
+ proposals = proposer.load(proposals)
196
+ if accept_pending or min_confidence is not None:
197
+ proposals.accept_all(min_confidence or 0.0)
198
+ proposer.save_review(proposals, self.caller)
199
+ publisher = Publisher(self.settings, registry=self.stores.registry, artifacts=artifacts)
200
+ return publisher.publish(proposals, self.caller)
201
+ except ModelNotRegistered as exc:
202
+ raise HeliosError("model_not_registered", str(exc)) from exc
203
+ except PublicationValidationError as exc:
204
+ raise HeliosError("publication_invalid", str(exc)) from exc
205
+ except DiscoveryError as exc:
206
+ raise HeliosError("discovery_failed", str(exc)) from exc
207
+
208
+ def __repr__(self) -> str:
209
+ who = self.caller.username if self.caller is not None and self.caller.username else "this program's user"
210
+ return f"Helios(caller={who!r})"
File without changes
@@ -0,0 +1,148 @@
1
+ """The Helios facade (burndown 6.6) on a DuckDB laptop: discover a model with
2
+ helios-model (a scripted LLM), publish it through the facade, then list, search, compile
3
+ and query it; who the queries run as; and the errors a developer sees."""
4
+ from decimal import Decimal
5
+
6
+ import duckdb
7
+ import pytest
8
+
9
+ from helios_cortex import Caller, IdentityMode
10
+ from helios_cortex.data_authorization import DataPolicy, PlatformDataDecision
11
+ from helios_cortex.domain import DataSource, DataSourceReference, Model
12
+ from helios_cortex.registry import SqlRegistry
13
+ from helios_cortex.settings import Settings
14
+ from helios_model import Catalog, Profiler, Proposer
15
+ from helios_semantic import CompiledQuery, Helios, HeliosError, QueryResult
16
+
17
+ RUN = "20261112T120000Z"
18
+ SOURCE = DataSource("warehouse", "Warehouse", "duckdb", "default")
19
+
20
+
21
+ class LLM:
22
+ """What a careful LLM proposes for the two tables."""
23
+
24
+ provider, model, calls = "scripted", "m", 0
25
+
26
+ def complete_json(self, system, user):
27
+ if "fact_tables" in user:
28
+ return {"metrics": [{"name": "Revenue", "dataset": "shop.orders", "expression": "SUM(o_amount)",
29
+ "confidence": 0.8, "rationale": "Money in."}]}
30
+ if '"table": "shop.orders"' in user:
31
+ return {"name": "Orders", "kind": "fact", "confidence": 0.9,
32
+ "fields": [{"column": "o_amount", "role": "measure", "confidence": 0.9}]}
33
+ if '"table"' in user:
34
+ return {"name": "Customers", "kind": "dimension", "confidence": 0.9,
35
+ "fields": [{"column": "c_region", "role": "dimension", "label": "Region", "confidence": 0.9}]}
36
+ return {"decisions": []}
37
+
38
+
39
+ @pytest.fixture
40
+ def settings(tmp_path):
41
+ warehouse = tmp_path / "warehouse.duckdb"
42
+ with duckdb.connect(str(warehouse)) as db:
43
+ db.execute("CREATE SCHEMA shop")
44
+ db.execute("CREATE TABLE shop.customers AS SELECT i AS c_customer_id, "
45
+ "CASE WHEN i % 2 = 0 THEN 'east' ELSE 'west' END AS c_region FROM range(1, 21) t(i)")
46
+ db.execute("CREATE TABLE shop.orders AS SELECT i AS o_order_id, 1 + i % 20 AS o_customer_id, "
47
+ "i * 1.5 AS o_amount FROM range(1, 101) t(i)")
48
+ settings = Settings(data_dir=tmp_path / "data", connections={"default": {"engine": "duckdb",
49
+ "path": str(warehouse)}})
50
+ registry = SqlRegistry.from_settings(settings)
51
+ registry.save_data_source(SOURCE)
52
+ registry.save_model(Model("sales", "Sales", (DataSourceReference("warehouse"),)))
53
+ harvest = Catalog(settings).harvest(SOURCE, None, databases=["shop"], model_id="sales", run_id=RUN)
54
+ Proposer(settings, llm=LLM()).propose(Profiler(settings).profile(harvest))
55
+ return settings
56
+
57
+
58
+ @pytest.fixture
59
+ def helios(settings):
60
+ helios = Helios.from_settings(settings)
61
+ helios.publish(RUN, accept_pending=True)
62
+ return helios
63
+
64
+
65
+ def test_publish_then_list_search_compile_and_query(settings):
66
+ helios = Helios.from_settings(settings)
67
+ assert helios.models() == []
68
+ publication = helios.publish(RUN, accept_pending=True)
69
+ assert publication.model_id == "sales" and publication.revision.published_by is None # this program's user
70
+
71
+ assert helios.models() == [{"name": "sales", "status": "published"}]
72
+ assert helios.describe()["model"] == "sales"
73
+ assert helios.search("revenue")[0]["name"] == "revenue" # published names are slugs
74
+
75
+ compiled = helios.compile("Revenue", "shop.customers.c_region") # a name or a list
76
+ assert isinstance(compiled, CompiledQuery) and compiled.dialect == "duckdb"
77
+ assert compiled.dataset == "shop.orders" and compiled.joins == ("shop.customers",)
78
+ assert "SUM(orders.o_amount)" in compiled.sql
79
+ assert helios.compile(["Revenue"], dialect="trino").dialect == "trino"
80
+
81
+ result = helios.query(["Revenue"], ["shop.customers.c_region"],
82
+ filters=[{"column": "shop.customers.c_region", "op": "=", "value": "east"}])
83
+ assert isinstance(result, QueryResult) and result.sql.startswith("SELECT")
84
+ assert result.records() == [{"c_region": "east", "revenue": Decimal("3750.0")}] # the engine's values
85
+
86
+
87
+ def test_a_tool_error_is_a_helios_error(helios):
88
+ with pytest.raises(HeliosError) as raised:
89
+ helios.query(["Profit"])
90
+ assert raised.value.code == "invalid_semantic_query" and "search_semantics" in raised.value.message
91
+ assert not raised.value.retryable
92
+ with pytest.raises(HeliosError, match="model_not_found"):
93
+ helios.describe("nowhere")
94
+
95
+
96
+ def test_publishing_is_refused_before_anything_is_written(settings, tmp_path):
97
+ helios = Helios.from_settings(settings)
98
+ with pytest.raises(HeliosError, match="discovery_failed"):
99
+ helios.publish("19990101T000000Z")
100
+ unregistered = Helios.from_settings(settings, registry=SqlRegistry(f"sqlite:///{tmp_path / 'other.db'}"))
101
+ unregistered.stores.registry.upgrade()
102
+ with pytest.raises(HeliosError, match="model_not_registered"):
103
+ unregistered.publish(RUN, accept_pending=True)
104
+ assert helios.models() == []
105
+
106
+
107
+ def test_a_caller_runs_queries_as_themselves(helios, settings):
108
+ """The DuckDB connection is in service mode: it cannot run a query as alice, so it refuses."""
109
+ alice = helios.as_caller(Caller("alice"))
110
+ assert alice.caller == Caller("alice") and alice.models() == helios.models()
111
+ with pytest.raises(HeliosError, match="data_authorization_denied"):
112
+ alice.query(["Revenue"])
113
+ with pytest.raises(HeliosError, match="data_authorization_denied"):
114
+ Helios.from_settings(settings, caller=Caller("alice")).query(["Revenue"])
115
+ assert helios.query(["Revenue"]).rows # the program itself still can
116
+ assert helios.as_caller(None).query(["Revenue"]).rows
117
+
118
+
119
+ def test_a_hosts_own_data_policy_is_kept(settings):
120
+ class Platform:
121
+ def can_access(self, caller, resource, action):
122
+ assert resource.identity_mode is IdentityMode.SERVICE
123
+ return PlatformDataDecision.allow("the host vouches for its callers")
124
+
125
+ policy = DataPolicy(Platform())
126
+ helios = Helios.from_settings(settings, caller=Caller("alice"), data_policy=policy)
127
+ helios.publish(RUN, accept_pending=True)
128
+ assert helios.query(["Revenue"]).rows
129
+ assert helios.as_caller(Caller("bob")).stores.data_policy is policy
130
+ published = helios.stores.registry.semantic_revisions("sales")[0]
131
+ assert published.published_by == "alice"
132
+
133
+
134
+ def test_health_and_tools(helios):
135
+ assert helios.health()["status"] == "healthy" and helios.health()["model_count"] == 1
136
+ assert {"list_models", "run_query"} <= set(helios.tools)
137
+
138
+
139
+ def test_from_settings_reads_a_config_file(settings, tmp_path):
140
+ config = tmp_path / "helios.toml"
141
+ config.write_text(f'data_dir = "{settings.data_dir}"\n\n[connections.default]\nengine = "duckdb"\n'
142
+ f'path = "{settings.connections["default"].options["path"]}"\n')
143
+ helios = Helios.from_settings(config=config)
144
+ assert helios.settings.data_dir == settings.data_dir
145
+ helios.publish(RUN, accept_pending=True)
146
+ assert helios.query(["Revenue"]).rows
147
+ with pytest.raises(TypeError, match="not both"):
148
+ Helios.from_settings(settings, config=config)
@@ -0,0 +1,70 @@
1
+ """helios-semantic is the package a developer installs (burndown 6.6): the libraries, the
2
+ `helios` command through helios-cortex, and extras that name real extras."""
3
+ import json
4
+ import re
5
+ import subprocess
6
+ import sys
7
+ import tomllib
8
+ from importlib.metadata import distribution
9
+ from pathlib import Path
10
+
11
+ import helios_semantic
12
+
13
+ PACKAGES = Path(__file__).resolve().parents[2]
14
+ PROJECT = tomllib.loads((PACKAGES / "helios-semantic" / "pyproject.toml").read_text())["project"]
15
+ FLOOR = (0, 2, 0) # every Helios requirement's lower bound: 0.1.0 of helios-cortex and helios-model on PyPI is older code (9.4)
16
+
17
+
18
+ def version_of(package):
19
+ return tomllib.loads((PACKAGES / package / "pyproject.toml").read_text())["project"]["version"]
20
+
21
+
22
+ def numbers(version):
23
+ return tuple(int(n) for n in re.match(r"\d+\.\d+\.\d+", version).group(0).split("."))
24
+
25
+
26
+ def bounded(package, bound):
27
+ """A Helios requirement's bound is at least FLOOR and no higher than the package as it is here
28
+ (scripts/release.py raises it on a release; a test never pins the number)."""
29
+ return bound is not None and FLOOR <= numbers(bound.removeprefix(">=")) <= numbers(version_of(package))
30
+
31
+
32
+ def test_the_package_reports_its_version_and_installs_the_libraries():
33
+ assert helios_semantic.__version__ == PROJECT["version"]
34
+ found = [re.fullmatch(r"([a-z-]+)(>=[0-9.]+)", r).groups() for r in PROJECT["dependencies"]]
35
+ assert [package for package, _ in found] == ["helios-cortex", "helios-model", "helios-serve"]
36
+ assert all(bounded(package, bound) for package, bound in found), PROJECT["dependencies"]
37
+
38
+
39
+ def test_each_extra_names_an_extra_its_package_declares():
40
+ extras = PROJECT["optional-dependencies"]
41
+ for name, requirements in extras.items():
42
+ for requirement in requirements:
43
+ package, _, wanted, bound = re.fullmatch(r"([a-z-]+)(\[([a-z0-9,]+)\])?(>=[0-9.]+)?",
44
+ requirement).groups()
45
+ if package == "helios-semantic":
46
+ assert name == "all" and set(wanted.split(",")) == set(extras) - {"all"}
47
+ continue
48
+ assert (PACKAGES / package).is_dir() and bounded(package, bound), requirement
49
+ if wanted:
50
+ declared = tomllib.loads((PACKAGES / package / "pyproject.toml").read_text())["project"]
51
+ assert set(wanted.split(",")) <= set(declared["optional-dependencies"]), requirement
52
+ # The extras from 3.2, the object stores Phase 4 added, and helios-mcp (9.4); [unstructured] waits for helios-crawl.
53
+ assert set(extras) == {"cloudera", "llm", "mcp", "postgres", "trino", "s3", "azure", "gcs", "ozone", "ontology",
54
+ "all"}
55
+
56
+
57
+ def test_the_helios_command_comes_with_it():
58
+ scripts = {e.name: e.value for e in distribution("helios-cortex").entry_points if e.group == "console_scripts"}
59
+ assert scripts["helios"] == "helios_cortex.cli:main"
60
+ listed = subprocess.run([sys.executable, "-m", "helios_cortex.cli", "--help"], capture_output=True, text=True)
61
+ assert listed.returncode == 0
62
+ assert all(command in listed.stdout for command in ("harvest", "publish", "eval"))
63
+
64
+
65
+ def test_importing_it_loads_nothing_heavy():
66
+ probe = ("import json, sys, helios_semantic; "
67
+ "print(json.dumps(sorted({m.partition('.')[0] for m in sys.modules})))")
68
+ loaded = set(json.loads(subprocess.run([sys.executable, "-c", probe], capture_output=True, text=True,
69
+ check=True).stdout))
70
+ assert not loaded & {"apps", "mcp", "helios_model", "helios_serve", "helios_cloudera", "duckdb", "sqlglot"}