graphos-client 0.14.12__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 (29) hide show
  1. graphos_client-0.14.12/.gitignore +46 -0
  2. graphos_client-0.14.12/DEVELOPMENT.md +92 -0
  3. graphos_client-0.14.12/LICENSE +201 -0
  4. graphos_client-0.14.12/NOTICE +12 -0
  5. graphos_client-0.14.12/PKG-INFO +227 -0
  6. graphos_client-0.14.12/README.md +194 -0
  7. graphos_client-0.14.12/THIRD_PARTY_NOTICES.md +133 -0
  8. graphos_client-0.14.12/examples/01_quickstart.py +57 -0
  9. graphos_client-0.14.12/examples/02_bulk_load.py +89 -0
  10. graphos_client-0.14.12/examples/03_explore.py +62 -0
  11. graphos_client-0.14.12/examples/04_communities.py +53 -0
  12. graphos_client-0.14.12/examples/05_tenant_pool.py +49 -0
  13. graphos_client-0.14.12/examples/06_rule_based_edges.py +50 -0
  14. graphos_client-0.14.12/examples/07_background_jobs.py +65 -0
  15. graphos_client-0.14.12/examples/08_demo_ecosystem.py +336 -0
  16. graphos_client-0.14.12/examples/09_better_answers.py +104 -0
  17. graphos_client-0.14.12/pyproject.toml +63 -0
  18. graphos_client-0.14.12/src/graphos_client/__init__.py +226 -0
  19. graphos_client-0.14.12/src/graphos_client/_auth.py +161 -0
  20. graphos_client-0.14.12/src/graphos_client/_client.py +2550 -0
  21. graphos_client-0.14.12/src/graphos_client/_drift.py +194 -0
  22. graphos_client-0.14.12/src/graphos_client/_errors.py +113 -0
  23. graphos_client-0.14.12/src/graphos_client/_models.py +1109 -0
  24. graphos_client-0.14.12/src/graphos_client/_pool.py +206 -0
  25. graphos_client-0.14.12/src/graphos_client/py.typed +0 -0
  26. graphos_client-0.14.12/tests/test_client.py +1603 -0
  27. graphos_client-0.14.12/tests/test_models.py +109 -0
  28. graphos_client-0.14.12/tests/test_pool.py +219 -0
  29. graphos_client-0.14.12/tests/test_schema_manager.py +701 -0
@@ -0,0 +1,46 @@
1
+ # Python build / caches
2
+ __pycache__/
3
+ *.pyc
4
+ *.pyo
5
+ .pytest_cache/
6
+ .ruff_cache/
7
+ .mypy_cache/
8
+ *.egg-info/
9
+ build/
10
+ dist/
11
+
12
+ # Virtual envs
13
+ .venv/
14
+ venv/
15
+ env/
16
+
17
+ # Coverage
18
+ .coverage
19
+ .coverage.*
20
+ htmlcov/
21
+ coverage.xml
22
+ coverage-*.xml
23
+
24
+ # Local env / secrets — everything in deploy/secrets except *.example and .gitkeep
25
+ services/graphos/deploy/secrets/*
26
+ !services/graphos/deploy/secrets/*.example
27
+ !services/graphos/deploy/secrets/.gitkeep
28
+
29
+ # Editor / OS
30
+ .vscode/
31
+ .idea/
32
+ *.swp
33
+ .DS_Store
34
+ Thumbs.db
35
+
36
+ # Local override files
37
+ .env
38
+ .env.local
39
+ docker-compose.override.yml
40
+
41
+ # Local design notes, never committed
42
+ docs/design/
43
+
44
+ # Crash dumps from Windows / Cygwin tools
45
+ *.stackdump
46
+
@@ -0,0 +1,92 @@
1
+ # Developing the Python client
2
+
3
+ How to work on `graphos-client`, the async Python client in
4
+ `clients/python/`. The rules for the whole repository (docs, test stacks,
5
+ git, privacy) are in [`development.md`](../../docs/guide/development.md); they apply here too.
6
+ Its users' guide is the [client README](README.md).
7
+
8
+ ## 1. Where to look
9
+
10
+ Paths are under `clients/python/`.
11
+
12
+ | Question | Look in |
13
+ |---|---|
14
+ | A method, its URL, retries and errors | `src/graphos_client/_client.py` (`GraphosClient`) |
15
+ | Request and response models | `src/graphos_client/_models.py` |
16
+ | `ensure_tenant`'s drift lines | `src/graphos_client/_drift.py` |
17
+ | Sign-in and token renewal | `src/graphos_client/_auth.py` (`PasswordAuth`, `BearerAuth`) |
18
+ | One client per tenant, re-registration | `src/graphos_client/_pool.py` (`GraphosPool`, `TenantSchema`) |
19
+ | Errors raised | `src/graphos_client/_errors.py` |
20
+ | What the package exports | `src/graphos_client/__init__.py` |
21
+ | Runnable examples | `examples/0*_*.py` |
22
+ | The service side of a model | `services/graphos/src/graphos/contracts/` |
23
+
24
+ ## 2. Setup, test, lint
25
+
26
+ In a venv at `.venv` in the checkout
27
+ ([development.md, Python environment](../../docs/guide/development.md#python-environment)):
28
+
29
+ ```bash
30
+ pip install -e "clients/python[dev]"
31
+ ruff check clients/python/src clients/python/tests clients/python/examples
32
+ pytest clients/python/tests
33
+ ```
34
+
35
+ The tests need no server: they use httpx's `MockTransport` and assert the
36
+ request the client builds and the model it parses. To run an example
37
+ against a running stack, set `GRAPHOS_URL` (default
38
+ `http://127.0.0.1:8080`), `GRAPHOS_USER` and `GRAPHOS_PASSWORD`.
39
+
40
+ ## 3. Rules
41
+
42
+ - **Published on its own.** The client depends on `httpx` and `pydantic`
43
+ only, never on the `graphos` service package. Keep it that way.
44
+ - **Models mirror the service 1:1.** `_models.py` is a copy of
45
+ `graphos.contracts`; when a contract changes, the model changes in the
46
+ same commit. A field the service added recently gets a default (`None`
47
+ or empty), so the client still reads older servers.
48
+ - **Async only** (`asyncio` + `httpx`), one pooled `httpx.AsyncClient` per
49
+ client, one tenant per client.
50
+ - **Retries only what is safe to repeat.** Network errors and 5xx are
51
+ retried with backoff. A call that is long or must not run twice (a
52
+ recompute, an import, a Cypher query, a job submission, a delete with
53
+ data) passes `idempotent=False`. A `504`, a `507` (the database out of disk
54
+ space) and 4xx errors are never retried.
55
+ - **Errors:** a non-2xx response raises `GraphosError`; a 503 raises
56
+ `GraphosNotReady`.
57
+ - **Every public name is exported** from `__init__.py`. The package ships
58
+ `py.typed`; every function is annotated.
59
+
60
+ ## 4. Code conventions
61
+
62
+ - **Ruff** with the config in `clients/python/pyproject.toml`: line length
63
+ 100, target `py311`, rules `E F I B UP SIM RET PL` (`PLR0913` ignored:
64
+ methods mirror the API's parameters). Same ruff range as the service
65
+ (`>=0.16,<0.17`); lint with the newest 0.16.x, as CI does.
66
+ - Module docstrings, typing and comments follow the service's conventions
67
+ ([services/graphos/DEVELOPMENT.md §4](../../services/graphos/DEVELOPMENT.md#4-code-conventions)).
68
+ - Tests live in `clients/python/tests/test_<area>.py`; names say what is
69
+ checked. A new method gets a test of its request and of its parsed
70
+ response.
71
+ - Examples read their settings from the environment and use the neutral
72
+ example tenants (`acme`, `library`, `team_*`, `demo`). Lint covers them.
73
+
74
+ ## 5. When the client changes
75
+
76
+ Besides the shared list in [development.md §3](../../docs/guide/development.md#3-docs-discipline):
77
+
78
+ - the README's "What the client covers" table lists every method; "Not
79
+ wrapped" lists what is left to plain HTTP;
80
+ - the README's examples table lists every script in `examples/`;
81
+ - a change in retries or errors updates the README's "Behaviour" section;
82
+ - a change to what the client promises (async only, its dependencies, what
83
+ it retries) gets an [ADR](../../docs/guide/adrs/README.md) first.
84
+
85
+ ## 6. Release
86
+
87
+ The client shares its version with the service and the UI
88
+ (`node tools/release/version.mjs <version>`). It is published to PyPI by
89
+ hand: the `graphos-client-release` workflow, run from a version tag
90
+ (`.github/workflows/client-release.yml`). A version tag does not publish it.
91
+ Never tag or publish without the owner's approval
92
+ ([development.md §6](../../docs/guide/development.md#6-git)).
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,12 @@
1
+ graphos
2
+
3
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
4
+
5
+ graphos runs on Apache AGE (https://age.apache.org/), a project of the
6
+ Apache Software Foundation, licensed under the Apache License, Version 2.0.
7
+ Apache AGE is used as an unmodified upstream container image and is not
8
+ redistributed in this repository. "Apache", "Apache AGE" and the Apache
9
+ feather logo are trademarks of The Apache Software Foundation.
10
+
11
+ See THIRD_PARTY_NOTICES.md for the licences of Apache AGE, PostgreSQL and the
12
+ Python dependencies.
@@ -0,0 +1,227 @@
1
+ Metadata-Version: 2.5
2
+ Name: graphos-client
3
+ Version: 0.14.12
4
+ Summary: Async HTTP client for the graphos graph service.
5
+ Project-URL: Homepage, https://github.com/pomentum/graphos
6
+ Project-URL: Documentation, https://github.com/pomentum/graphos/tree/main/clients/python
7
+ Project-URL: Source, https://github.com/pomentum/graphos
8
+ Project-URL: Issues, https://github.com/pomentum/graphos/issues
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ License-File: NOTICE
12
+ License-File: THIRD_PARTY_NOTICES.md
13
+ Keywords: apache-age,asyncio,client,cypher,graph,graph-database,postgresql
14
+ Classifier: Development Status :: 4 - Beta
15
+ Classifier: Framework :: AsyncIO
16
+ Classifier: Intended Audience :: Developers
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Database :: Front-Ends
23
+ Classifier: Typing :: Typed
24
+ Requires-Python: >=3.11
25
+ Requires-Dist: httpx<1.0,>=0.27
26
+ Requires-Dist: pydantic<3.0,>=2.7
27
+ Provides-Extra: dev
28
+ Requires-Dist: pytest-asyncio<1.0,>=0.24; extra == 'dev'
29
+ Requires-Dist: pytest-cov<7.0,>=5.0; extra == 'dev'
30
+ Requires-Dist: pytest<9.0,>=8.3; extra == 'dev'
31
+ Requires-Dist: ruff<0.17,>=0.16; extra == 'dev'
32
+ Description-Content-Type: text/markdown
33
+
34
+ # graphos-client
35
+
36
+ Async Python client for [graphos](https://github.com/pomentum/graphos), a multi-tenant graph service built on PostgreSQL and Apache AGE. Typed request and response models, pooled connections, and a tenant pool for services that write to many tenants.
37
+
38
+ ```bash
39
+ pip install graphos-client # from PyPI
40
+ pip install -e clients/python # from a checkout of the repository
41
+ ```
42
+
43
+ Requires Python 3.11+. The client is async-only (`asyncio` + `httpx`).
44
+
45
+ ## Quickstart
46
+
47
+ ```python
48
+ import asyncio
49
+ import os
50
+
51
+ from graphos_client import EdgeUpsert, GraphosClient, NodeUpsert, PasswordAuth
52
+
53
+
54
+ async def main() -> None:
55
+ async with GraphosClient(
56
+ base_url="http://127.0.0.1:8080",
57
+ # A service account allowed to create the tenant (create_tenants), or an admin.
58
+ # Without auth=, the client signs in as GRAPHOS_USER / GRAPHOS_PASSWORD.
59
+ auth=PasswordAuth("loader", os.environ["GRAPHOS_PASSWORD"]),
60
+ tenant="acme",
61
+ ) as g:
62
+ await g.register_tenant(vertex_labels=["User", "Document"], edge_labels=["AUTHORED"])
63
+
64
+ await g.upsert_nodes([
65
+ NodeUpsert(id="u1", label="User", properties={"name": "ada"}),
66
+ NodeUpsert(id="d1", label="Document", properties={"name": "graphs-101"}),
67
+ ])
68
+ await g.upsert_edges([
69
+ EdgeUpsert(src_id="u1", src_label="User", dst_id="d1",
70
+ dst_label="Document", type="AUTHORED"),
71
+ ])
72
+
73
+ hits = await g.search(q="ada") # hit.properties["id"] is your id
74
+ around = await g.neighbors(node_id="u1")
75
+ reach = await g.expand(node_id="u1", max_hops=2)
76
+ print(len(hits.nodes), len(around.neighbors), len(reach.paths))
77
+
78
+
79
+ asyncio.run(main())
80
+ ```
81
+
82
+ ## Many tenants: `GraphosPool`
83
+
84
+ A service that writes to one tenant per customer, project or team can let the pool manage the clients. Each tenant gets its own client, is registered with the shared schema on first use, and is re-registered (then retried once) if the server no longer knows a label. A registration is one plain request by default; `GraphosPool(..., on_drift="warn")` (or `"fail"`) registers through `ensure_tenant` with that mode instead (below): a dry run first, its drift logged.
85
+
86
+ ```python
87
+ from graphos_client import GraphosPool, PasswordAuth, TenantSchema
88
+
89
+ schema = TenantSchema(
90
+ vertex_labels=["User", "Document"],
91
+ edge_labels=["AUTHORED"],
92
+ property_indexes=[{"label": "Document", "properties": ["kind"]}], # serves `where kind = ...`
93
+ )
94
+
95
+ async with GraphosPool(base_url=URL, auth=PasswordAuth("loader", SECRET), schema=schema) as pool:
96
+ await pool.call("team_red", lambda g: g.upsert_nodes(nodes)) # registers, writes
97
+ cli = await pool.client("team_red") # the same client
98
+ ```
99
+
100
+ ## A program's schema: `ensure_tenant`
101
+
102
+ A program that declares its schema in code and registers it on every start can learn what people
103
+ changed in the tenant meanwhile (in the web UI, say) instead of undoing it unseen:
104
+
105
+ ```python
106
+ await cli.ensure_tenant(vertex_labels=["User", "Document"], edge_labels=["AUTHORED"],
107
+ on_drift="warn") # or "fail", or "ignore" (no dry run)
108
+ ```
109
+
110
+ It runs the registration as a dry run first and logs the dry run's `drift` on the logger
111
+ `graphos_client.drift`, one line per item. At INFO: what the tenant has that the call does not
112
+ declare (a merge keeps it; most programs declare less than the tenant has). At WARNING: what a
113
+ `force_shrink` would remove, entries the call would replace with a different value, settings it
114
+ would change (`strict_endpoints`, the property mode, the community algorithm), and labels, edge
115
+ types or label pairs dropped earlier that the call creates again. Then it registers, with
116
+ `If-Match` set to the dry run's `ETag`, so it applies exactly what was previewed. If the schema
117
+ changed in between (another replica of the program starting at the same time), it runs the dry
118
+ run once more on the new version, logs it, and registers with that; a second change raises
119
+ `GraphosError` 412 and nothing is registered, as when someone unregistered the tenant in between
120
+ (registering would restore it, undoing that). A tenant the dry run found not registered is
121
+ registered with `If-None-Match: *` (unless it said the call restores an unregistered tenant), so
122
+ one someone else created meanwhile is not registered unchecked. An `if_match=` you pass pins the version: the second dry run is then refused with 412.
123
+ Each drift line is logged once, also across the second dry run. With `on_drift="fail"` it raises `SchemaDriftError` (its `drift` is the report) and
124
+ registers nothing when the call would remove, replace or change something, or bring a removed
125
+ item back; what is only not declared never fails it.
126
+
127
+ A tenant can name one **schema manager**: `schema_manager="user:loader"` (an existing graphos user
128
+ or service account), `"oidc-sub:<sub>"` (a caller signed in through the identity provider) or
129
+ `"self"` (the caller, whatever it signs in with) on `register_tenant`, `ensure_tenant` or
130
+ `import_schema`; `manage_schema=True` is `"self"`; `None` releases it; set by an owner, refused
131
+ (422) by a server with authentication disabled. On a managed tenant only the manager changes more
132
+ than the styles (`display`): anyone else's such write raises `GraphosError` 409 with
133
+ `code == "schema_managed"` and `schema_manager` naming the manager. `get_tenant()` and `schema()`
134
+ show it (`schema_manager` and `schema_manager_since`, `None` when there is none).
135
+
136
+ After a registration that names a manager, the client checks the answer's `schema_manager`: a
137
+ server older than the schema manager ignores the field, and the client then raises
138
+ `SchemaManagerNotApplied` (a `GraphosError` with status 0: the rest of the registration was
139
+ applied, the manager was not). An import of more than 5,000 label pairs sends the manager with
140
+ its last call, so the calls before it are not refused.
141
+
142
+ How the styles sent merge is `display_merge=`: `"entries"` (an entry sent replaces the stored
143
+ one, `None` removes it) or `"missing_only"` (only the styles the tenant lacks are added; a
144
+ `force_shrink` keeps the stored styles of the labels and edge types it keeps and drops the
145
+ others). Left out, the manager's registrations get `"missing_only"`, so people's
146
+ styles stay, and anyone else's `"entries"`; a manager that wants to correct a style it shipped
147
+ sends `"entries"`.
148
+
149
+ ## Copying a tenant
150
+
151
+ ```python
152
+ await cli.export_dataset("acme.ndjson.gz") # every node and edge, and the schema
153
+ await cli.import_dataset("acme.ndjson.gz", name="acme_copy", # a new tenant, restored exactly:
154
+ schema="apply", mode="empty") # schema from the file, then the data
155
+ ```
156
+
157
+ Both stream: the file is never held in memory. The result says whether the file was complete.
158
+
159
+ ## Copying a schema
160
+
161
+ ```python
162
+ doc = await cli.export_schema() # the whole schema, a dict
163
+ preview = await cli.import_schema(doc, name="acme_copy", dry_run=True)
164
+ print(preview["changes"], preview["warnings"]) # what it would change, and cost
165
+ await cli.import_schema(doc, name="acme_copy") # merge into (or create) acme_copy
166
+ await cli.import_schema(doc, replace=True) # replace this tenant's schema
167
+ ```
168
+
169
+ The document is what `GET /v1/tenants/{name}/spec` answers: a registration body, so it can be kept
170
+ in git and reviewed as a diff. More than 5,000 declared label pairs are sent over several calls.
171
+
172
+ ## Examples
173
+
174
+ **Signing in.** `auth=PasswordAuth(user, secret)` (or `GRAPHOS_USER` / `GRAPHOS_PASSWORD`) signs in
175
+ and renews the 15-minute token by itself. A program that holds credentials at graphos's identity
176
+ provider can use `auth=BearerAuth(source)` instead: `source` is an async callable answering
177
+ `(access token, seconds valid)`, called again before expiry and once on a `401`.
178
+
179
+ Runnable scripts in [`examples/`](https://github.com/pomentum/graphos/tree/main/clients/python/examples). Each reads `GRAPHOS_URL` (default `http://127.0.0.1:8080`) and signs in as `GRAPHOS_USER` / `GRAPHOS_PASSWORD`: an admin, or a service account with `create_tenants` on the example tenants (`acme`, `library`, `team_red`, `team_green`, `team_blue`, and `demo` or `GRAPHOS_DEMO_TENANT`), which makes it their owner. `07_background_jobs.py` also vacuums, which needs an admin.
180
+
181
+ | Script | Shows |
182
+ |---|---|
183
+ | [`01_quickstart.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/01_quickstart.py) | register a tenant, write nodes and edges, search / neighbours / expand |
184
+ | [`02_bulk_load.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/02_bulk_load.py) | batched NDJSON bulk writes and a one-request snapshot import |
185
+ | [`03_explore.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/03_explore.py) | paginated scans, scoped and induced subgraphs, aggregates, top-K, node properties, cache |
186
+ | [`04_communities.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/04_communities.py) | communities (Louvain, or Leiden with `algorithm="leiden"`): compute, summarise, look up |
187
+ | [`05_tenant_pool.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/05_tenant_pool.py) | `GraphosPool` serving several tenants with one schema |
188
+ | [`06_rule_based_edges.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/06_rule_based_edges.py) | declaring a property-match rule and letting the server write the edges |
189
+ | [`07_background_jobs.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/07_background_jobs.py) | long operations as background jobs: submit, wait, the one-recompute rule, cancel |
190
+ | [`08_demo_ecosystem.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/08_demo_ecosystem.py) | the demo tenant (an invented software ecosystem, about 450 nodes) and every graph algorithm on it: metrics, the top nodes by PageRank and betweenness, communities |
191
+ | [`09_better_answers.py`](https://github.com/pomentum/graphos/blob/main/clients/python/examples/09_better_answers.py) | better answers from the algorithms on the demo tenant: search ranked by PageRank, a walk scoped to a community, the best hit per community, the bridges |
192
+
193
+ ## What the client covers
194
+
195
+ | Area | Methods |
196
+ |---|---|
197
+ | Tenants | `register_tenant` (with `edge_endpoints`, `strict_endpoints`, `display`, `property_schema`, `deprecated`, `schema_manager` / `manage_schema`, `display_merge`, `force_shrink`, `dry_run`; the answer's `etag`), `ensure_tenant` (a dry run's drift logged, or `SchemaDriftError`, then the registration with its `ETag` as `If-Match`), `export_schema`, `import_schema`, `remove_edge_endpoint`, `rename_label`, `rename_edge_type`, `rename_property` (a job: `wait_for_job(result.job_id)`), `drop_label` (a deprecated, empty one), `list_tenants`, `get_tenant`, `unregister_tenant` (`drop_data=True` deletes it with its data), `restore_tenant`, `list_unregistered_tenants`, `me`, `schema`, `schema_summary` (the schema as a model needs it, with the values) |
198
+ | Cypher console (on unless the server turns it off) | `cypher` (read-only, `$name` parameters; write clauses and functions that are not Cypher's are refused with 400), `saved_queries`, `save_query`, `run_saved_query`, `saved_query` (one by name), `delete_saved_query` |
199
+ | Dataset | `export_dataset` (streamed to a file, gzip by suffix), `import_dataset` (streamed from one; `mode="empty"` to restore, `schema="apply"` to register the file's schema first), `read_dataset_header` |
200
+ | Writes | `upsert_nodes`, `upsert_edges`, `bulk_upsert_nodes`, `bulk_upsert_edges`, `import_csv_nodes`, `import_csv_edges`, `snapshot_import`, `upsert_node_properties`, `patch_node`, `patch_edge`, `delete_node`, `delete_nodes` (a batch, by `NodeRef`), `delete_edge`, `delete_by_property`, `reconcile_node_edges` / `reconcile_type_edges` (a scope made exactly a given set), `resolve_edges` (`mode="reconcile"`) |
201
+ | Reads | `search`, `get_node`, `get_edge`, `check_edges` (many edges at once, by `EdgeCheckItem`), `find_paths`, `neighbors`, `expand`, `induced_edges`, `scoped_subgraph`, `sample_subgraph`, `scan_nodes` / `scan_nodes_iter`, `scan_edges` / `scan_edges_iter`, `export_graph` |
202
+ | Aggregates | `graph_map`, `map_hubs`, `label_top_by_edge`, `aggregate_nodes` (`missing=True` counts nodes without the property under `""`; `total` and `distinct` count nodes and values before `limit`, `None` from older servers), `aggregate_edges`, `tenant_stats` (`analyses`: when metrics and communities were computed, `stale`) |
203
+ | Communities | `recompute_communities` (`algorithm="louvain"` or `"leiden"`, the tenant's when omitted; `from_scratch=True` makes Leiden ignore the stored groups), `community_map`, `list_communities`, `community_summary`, `community_ids` |
204
+ | Graph metrics | `compute_metrics` (degree, PageRank, components, betweenness, stored as `graphos_*` node properties) |
205
+ | Property definitions | `property_definitions` (every label's and type's definitions and mode), `check_properties` (the stored rows against them, `maintain`; writes nothing) |
206
+ | Rule-based edges | `resolve_edges`, `catalogue` |
207
+ | Cache | `cache_put`, `cache_get`, `cache_delete` |
208
+ | Change feed | `changes`, `changes_head`, `iter_changes`, `stream_changes` (reconnects with `Last-Event-ID`), `changes_history` (newest first, for showing the past) |
209
+ | Operations | `healthz`, `readyz`, `info` (no token; versions and features), and for admins `db_stats`, `slow_queries`, `vacuum` |
210
+ | Background jobs | `submit_recompute_communities`, `submit_compute_metrics`, `submit_resolve_edges`, `submit_check_properties`, `submit_vacuum` (each returns a `Job`), `get_job`, `list_jobs`, `cancel_job`, `wait_for_job` |
211
+
212
+ Not wrapped (use HTTP, see the [usage guide](https://github.com/pomentum/graphos/blob/main/docs/guide/usage.md)): users, grants and sign-in (`/v1/users`, `/v1/grants`, `/v1/auth/*`, `/v1/me/password`), `PATCH /v1/me/preferences`, and the MCP endpoint `/mcp`, which is for agents (see the [agents guide](https://github.com/pomentum/graphos/blob/main/docs/guide/agents.md)).
213
+
214
+ ## Behaviour
215
+
216
+ - **Errors.** Non-2xx responses raise `GraphosError` (`status_code`, `detail`, and `body`, `code` and `schema_manager` from a JSON body: `code == "schema_managed"` is a write refused on a tenant whose schema someone else manages); `ensure_tenant(on_drift="fail")` raises `SchemaDriftError` (`drift`, status 0) before registering; a registration naming a schema manager the server did not apply raises `SchemaManagerNotApplied` (status 0, after the registration); a 503 raises `GraphosNotReady` (graphos starting or without its database, or the database out of memory or connections). A statement timeout on the server is a `504`, the database out of disk space a `507`, both with an `application/problem+json` body and not retried.
217
+ - **Retries.** Network errors and 5xx responses are retried with exponential backoff (`retries`, `retry_backoff_s`), except `504` timeouts, `507` (the database out of disk space), read and write timeouts, and calls that are long or should not run twice (community recompute, graph metrics, rule-based edge resolution, snapshot and dataset import, vacuum, Cypher queries, restoring or deleting a tenant with its data), job submissions and cancels, which are never re-run automatically. 4xx errors are raised at once.
218
+ - **One tenant per client.** The tenant is part of every data-plane URL; what a token may touch is enforced by the server.
219
+ - **Connections.** One pooled `httpx.AsyncClient` per client; use `async with` or call `close()`. Pass `transport=` to supply your own `httpx` transport (tests, proxies).
220
+
221
+ ## Development
222
+
223
+ Working on the client: see [DEVELOPMENT.md](https://github.com/pomentum/graphos/blob/main/clients/python/DEVELOPMENT.md) in the repository.
224
+
225
+ ## Licence
226
+
227
+ Apache-2.0. See [LICENSE](https://github.com/pomentum/graphos/blob/main/clients/python/LICENSE) and [NOTICE](https://github.com/pomentum/graphos/blob/main/clients/python/NOTICE).