a13n-service 0.0.3__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 (49) hide show
  1. a13n_service-0.0.3/.gitignore +62 -0
  2. a13n_service-0.0.3/LICENSE +201 -0
  3. a13n_service-0.0.3/PKG-INFO +222 -0
  4. a13n_service-0.0.3/README.md +196 -0
  5. a13n_service-0.0.3/a13n_service/__init__.py +10 -0
  6. a13n_service-0.0.3/a13n_service/__main__.py +4 -0
  7. a13n_service-0.0.3/a13n_service/app.py +103 -0
  8. a13n_service-0.0.3/a13n_service/asgi.py +5 -0
  9. a13n_service-0.0.3/a13n_service/cli.py +90 -0
  10. a13n_service-0.0.3/a13n_service/database/__init__.py +7 -0
  11. a13n_service-0.0.3/a13n_service/database/config.py +12 -0
  12. a13n_service-0.0.3/a13n_service/database/metadata.py +26 -0
  13. a13n_service-0.0.3/a13n_service/database/migration.py +205 -0
  14. a13n_service-0.0.3/a13n_service/database/migrations/__init__.py +1 -0
  15. a13n_service-0.0.3/a13n_service/database/migrations/env.py +30 -0
  16. a13n_service-0.0.3/a13n_service/database/migrations/script.py.mako +27 -0
  17. a13n_service-0.0.3/a13n_service/database/migrations/versions/.gitkeep +0 -0
  18. a13n_service-0.0.3/a13n_service/log.py +48 -0
  19. a13n_service-0.0.3/a13n_service/settings.py +187 -0
  20. a13n_service-0.0.3/a13n_service/storage/__init__.py +38 -0
  21. a13n_service-0.0.3/a13n_service/storage/config.py +122 -0
  22. a13n_service-0.0.3/a13n_service/storage/filesystem.py +95 -0
  23. a13n_service-0.0.3/a13n_service/storage/object_store/__init__.py +35 -0
  24. a13n_service-0.0.3/a13n_service/storage/object_store/api.py +188 -0
  25. a13n_service-0.0.3/a13n_service/storage/object_store/local.py +405 -0
  26. a13n_service-0.0.3/a13n_service/storage/object_store/s3.py +382 -0
  27. a13n_service-0.0.3/a13n_service/storage/redis.py +41 -0
  28. a13n_service-0.0.3/a13n_service/storage/relational.py +132 -0
  29. a13n_service-0.0.3/a13n_service/storage/runtime.py +135 -0
  30. a13n_service-0.0.3/a13n_service/web.py +44 -0
  31. a13n_service-0.0.3/pyproject.toml +46 -0
  32. a13n_service-0.0.3/tests/conftest.py +149 -0
  33. a13n_service-0.0.3/tests/database/test_config.py +15 -0
  34. a13n_service-0.0.3/tests/database/test_metadata.py +27 -0
  35. a13n_service-0.0.3/tests/database/test_migration.py +202 -0
  36. a13n_service-0.0.3/tests/storage/test_config.py +89 -0
  37. a13n_service-0.0.3/tests/storage/test_filesystem.py +84 -0
  38. a13n_service-0.0.3/tests/storage/test_local_object_store.py +105 -0
  39. a13n_service-0.0.3/tests/storage/test_object_store.py +149 -0
  40. a13n_service-0.0.3/tests/storage/test_redis.py +54 -0
  41. a13n_service-0.0.3/tests/storage/test_runtime.py +80 -0
  42. a13n_service-0.0.3/tests/storage/test_s3_object_store.py +61 -0
  43. a13n_service-0.0.3/tests/storage/test_sql.py +109 -0
  44. a13n_service-0.0.3/tests/test_app.py +117 -0
  45. a13n_service-0.0.3/tests/test_cli.py +47 -0
  46. a13n_service-0.0.3/tests/test_entrypoint.py +83 -0
  47. a13n_service-0.0.3/tests/test_hello.py +7 -0
  48. a13n_service-0.0.3/tests/test_log.py +26 -0
  49. a13n_service-0.0.3/tests/test_settings.py +79 -0
@@ -0,0 +1,62 @@
1
+ # Local reference and discussion material
2
+ discussion/
3
+ local-reference/
4
+
5
+ # Python bytecode and native extensions
6
+ __pycache__/
7
+ *.py[cod]
8
+ *$py.class
9
+ *.so
10
+
11
+ # Python packaging
12
+ build/
13
+ dist/
14
+ *.egg-info/
15
+ .eggs/
16
+ wheels/
17
+
18
+ # Python environments
19
+ .env
20
+ .env.*
21
+ !.env.example
22
+ .venv/
23
+ env/
24
+ venv/
25
+
26
+ # Tests, coverage, and static analysis
27
+ .coverage
28
+ .coverage.*
29
+ .cache/
30
+ .hypothesis/
31
+ .mypy_cache/
32
+ .nox/
33
+ .pyright/
34
+ .pytest_cache/
35
+ .ruff_cache/
36
+ .tox/
37
+ coverage.xml
38
+ htmlcov/
39
+
40
+ # Documentation output
41
+ site/
42
+
43
+ # Cloudflare Wrangler local state
44
+ .wrangler/
45
+
46
+ # Rust
47
+ target/
48
+ **/*.rs.bk
49
+
50
+ # Frontend tooling
51
+ node_modules/
52
+ *.tsbuildinfo
53
+ /apps/harness-ui/dist/
54
+ /packages/agent-ui/a13n_ui/static/
55
+
56
+ # Editors and operating systems
57
+ .DS_Store
58
+ .idea/
59
+
60
+ # Logs and temporary files
61
+ *.log
62
+ *.tmp
@@ -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 2026 Converge AI
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,222 @@
1
+ Metadata-Version: 2.5
2
+ Name: a13n-service
3
+ Version: 0.0.3
4
+ Summary: Hosted control and execution service for Agent Foundation
5
+ License-Expression: Apache-2.0
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.13
8
+ Requires-Dist: a13n-logging
9
+ Requires-Dist: aiobotocore[httpx2]<4,>=3.9
10
+ Requires-Dist: aiosqlite<1,>=0.21
11
+ Requires-Dist: alembic<2,>=1.17.1
12
+ Requires-Dist: anyio<5,>=4
13
+ Requires-Dist: botocore<1.43.57,>=1.43.3
14
+ Requires-Dist: click<9,>=8.2
15
+ Requires-Dist: fakeredis<3,>=2.31
16
+ Requires-Dist: fastapi<1,>=0.116
17
+ Requires-Dist: httpx2<3,>=2.5
18
+ Requires-Dist: psycopg[binary]<4,>=3.2
19
+ Requires-Dist: pydantic-settings<3,>=2.10
20
+ Requires-Dist: pydantic<3,>=2.12
21
+ Requires-Dist: redis<9,>=8
22
+ Requires-Dist: sqlalchemy[asyncio]<3,>=2.0.41
23
+ Requires-Dist: starlette<2,>=1.6
24
+ Requires-Dist: uvicorn<1,>=0.35
25
+ Description-Content-Type: text/markdown
26
+
27
+ # Foundation Service
28
+
29
+ This package contains the hosted Foundation Service executable, its internal async-first storage substrate, and its service-owned relational schema lifecycle. It is a workspace package, not a public SDK or an independently distributed provider library.
30
+
31
+ The substrate exposes capability-specific interfaces instead of one generic storage facade:
32
+
33
+ - SQL uses SQLAlchemy's async `AsyncEngine` and `AsyncSession` APIs with PostgreSQL or SQLite.
34
+ - Redis-compatible data structures use `redis.asyncio.Redis` with Redis or process-local fakeredis.
35
+ - Objects use the small Foundation-owned `ObjectStore` protocol with S3-compatible or local-directory adapters.
36
+ - Local files and deployment-mounted NFS use the same confined `pathlib` and AnyIO helpers.
37
+
38
+ Backend selection happens once during process startup. A failed network backend never falls back to local state.
39
+
40
+ ## Runtime
41
+
42
+ `ServiceSettings` owns the `FOUNDATION_*` environment contract and maps it to the frozen `StorageSettings` model. The storage package accepts typed configuration and does not read process environment variables itself. `foundation-service serve` constructs all selected providers once in FastAPI lifespan, publishes the resulting `StorageResources` on `app.state.storage`, and closes the resources during shutdown.
43
+
44
+ The default service profile keeps the existing PostgreSQL and Redis endpoints and uses separate local roots for objects and files. Set `FOUNDATION_OBJECT_BACKEND=s3` and `FOUNDATION_OBJECT_BUCKET` for a multi-process deployment; the local object adapter supports only one writing process. `FOUNDATION_FILESYSTEM_ROOT` may be an ordinary local directory or an NFS mount prepared by deployment.
45
+
46
+ ```python
47
+ from pathlib import Path
48
+
49
+ from a13n_service.storage import StorageSettings, open_storage
50
+
51
+ settings = StorageSettings.model_validate(
52
+ {
53
+ "database": {"backend": "sqlite", "path": Path("var/foundation.sqlite3")},
54
+ "redis": {"backend": "memory"},
55
+ "objects": {"backend": "local", "root": Path("var/objects")},
56
+ "filesystem": {"root": Path("var/files")},
57
+ }
58
+ )
59
+
60
+ async with open_storage(settings) as storage:
61
+ # Inject `storage` into application-owned services here.
62
+ ...
63
+ ```
64
+
65
+ `open_storage()` constructs one engine, session factory, Redis client, object store, and filesystem boundary. It checks required capabilities before yielding and closes all resources in reverse order.
66
+
67
+ A network deployment selects the corresponding backends without changing consumer code:
68
+
69
+ ```python
70
+ network_settings = StorageSettings.model_validate(
71
+ {
72
+ "database": {
73
+ "backend": "postgresql",
74
+ "url": "postgresql://foundation:password@postgres/foundation",
75
+ },
76
+ "redis": {"backend": "redis", "url": "redis://redis:6379/0"},
77
+ "objects": {
78
+ "backend": "s3",
79
+ "bucket": "foundation-objects",
80
+ "region": "us-east-1",
81
+ },
82
+ "filesystem": {"root": Path("/mnt/foundation-files")},
83
+ }
84
+ )
85
+ ```
86
+
87
+ The S3 client uses the standard AWS credential chain. Set `endpoint_url` and `force_path_style` only for a compatible non-AWS endpoint. The deployment mounts NFS at the configured filesystem root before the process starts.
88
+
89
+ ## Relational Usage
90
+
91
+ Consumers use SQLAlchemy directly. Generic storage does not define `get`, `insert`, or `do` wrappers.
92
+
93
+ ```python
94
+ from sqlalchemy import select
95
+
96
+ from a13n_service.storage import transaction
97
+
98
+ async with transaction(storage.sessions) as session:
99
+ result = await session.execute(select(Record).where(Record.id == record_id))
100
+ record = result.scalar_one_or_none()
101
+ ```
102
+
103
+ Each operation gets a short session. Never retain a session or transaction across external I/O, agent execution, sleeps, background work, or a streaming response.
104
+
105
+ PostgreSQL is the distributed-service backend. SQLite is intended for a single-process, zero-service profile and must not be placed on NFS.
106
+
107
+ ## Relational Schema and Migrations
108
+
109
+ Generic relational storage and service schema ownership are deliberately separate:
110
+
111
+ - `storage/relational.py` constructs async engines and short sessions for application I/O.
112
+ - `database/metadata.py` aggregates every service-owned ORM model.
113
+ - `database/migrations/` contains one linear Alembic history for the complete service database.
114
+ - `database/migration.py` owns the dedicated synchronous migration connection, bounded PostgreSQL advisory locking, and Alembic invocation.
115
+
116
+ The Alembic environment does not read process settings or create an engine. The runner supplies one validated connection, so CLI settings, lock policy, and schema comparison have distinct owners.
117
+
118
+ Select the database backend, then use the stable service CLI or repository commands:
119
+
120
+ ```bash
121
+ FOUNDATION_DATABASE_BACKEND=postgresql
122
+ FOUNDATION_DATABASE_URL=postgresql+psycopg://foundation:foundation@127.0.0.1:5432/foundation
123
+
124
+ make db-upgrade
125
+ make db-current
126
+ make db-check
127
+ make db-history
128
+ ```
129
+
130
+ The corresponding executable commands are `foundation-service db upgrade`, `foundation-service db current --check-heads`, `foundation-service db history`, and `foundation-service db migrate "description"`. There is one process CLI; migration implementation remains in `database/migration.py` rather than introducing a second database-only settings or command layer.
131
+
132
+ For the zero-service profile, set `FOUNDATION_DATABASE_BACKEND=sqlite` and `FOUNDATION_DATABASE_SQLITE_PATH=var/foundation.sqlite3`. The same accepted history is applied to both backends. A domain requiring PostgreSQL-only schema behavior must reject SQLite explicitly.
133
+
134
+ ### Add an ORM Model
135
+
136
+ 1. Define the model beside its owning domain using `a13n_service.database.Base`.
137
+ 2. Import that domain model module explicitly in `database/metadata.py`; there is no package scanning or plugin discovery.
138
+ 3. Run `make db-migrate msg="describe the schema change"`. The target rebuilds accepted history in a disposable PostgreSQL database before autogeneration.
139
+ 4. Review the generated revision for names, constraints, data loss, lock behavior, rolling compatibility, interruption safety, and downgrade or forward repair.
140
+ 5. Run the database tests on SQLite and PostgreSQL plus `make db-check` against an upgraded database.
141
+
142
+ Do not create revision files by hand and do not use runtime `metadata.create_all()` as schema bootstrap. Application request paths use async SQLAlchemy; migrations use a separate synchronous `NullPool` connection because they run before traffic or in a dedicated deployment job.
143
+
144
+ ## Redis Usage
145
+
146
+ The injected async redis-py client exposes strings, hashes, lists, sets, sorted sets, Streams, pipelines, transactions, and Pub/Sub without local/network branches.
147
+
148
+ ```python
149
+ await storage.redis.hset(b"run:1", mapping={b"status": b"running"})
150
+ await storage.redis.rpush(b"run:1:steps", b"step-1")
151
+ await storage.redis.xadd(b"run-events", {b"payload": payload})
152
+ ```
153
+
154
+ Response decoding is disabled for binary safety. The fakeredis backend is process-local and non-durable; use a real Redis service for multiple processes, persistence, modules, or exact server failure behavior.
155
+
156
+ ## Object Usage
157
+
158
+ Object keys are opaque names rather than filesystem paths. `put` supports unconditional, create-only, and expected-version publication.
159
+
160
+ ```python
161
+ from a13n_service.storage import ByteRange, ObjectConflict
162
+
163
+ created = await storage.objects.put(
164
+ "artifacts/result.json",
165
+ payload,
166
+ content_type="application/json",
167
+ metadata={"trace": trace_id},
168
+ if_none_match=True,
169
+ )
170
+
171
+ async with storage.objects.open("artifacts/result.json", byte_range=ByteRange(0, 64)) as reader:
172
+ prefix = b"".join([chunk async for chunk in reader])
173
+
174
+ try:
175
+ updated = await storage.objects.put(
176
+ "artifacts/result.json",
177
+ new_payload,
178
+ if_match=created.version,
179
+ )
180
+ except ObjectConflict:
181
+ # Re-read and make a new domain decision.
182
+ ...
183
+ ```
184
+
185
+ S3 endpoints must support AWS-compatible conditional writes and deletes, range reads, head requests, and ordered `ListObjectsV2` pagination. Startup rejects endpoints that silently ignore these conditions. The local adapter provides the common behavior for exactly one writing service process.
186
+
187
+ Metadata keys are normalized to lowercase and, like S3 REST metadata, keys and values must be ASCII. Keys must also be valid HTTP field names. Returned metadata mappings are immutable.
188
+
189
+ ## Filesystem Usage
190
+
191
+ Deployment mounts NFS before process startup. Application code receives the mounted root and uses the same helpers as a local directory; there is no Python NFS provider.
192
+
193
+ ```python
194
+ import anyio
195
+
196
+ from a13n_service.storage.filesystem import atomic_write, resolve_under_root
197
+
198
+ destination = await resolve_under_root(
199
+ storage.files_root,
200
+ "exports/result.json",
201
+ limiter=storage.file_limiter,
202
+ )
203
+ await atomic_write(destination, chunks, limiter=storage.file_limiter)
204
+
205
+ async with await anyio.open_file(destination, "rb") as file:
206
+ prefix = await file.read(64 * 1024)
207
+ ```
208
+
209
+ Confined resolution rejects absolute paths, parent traversal, and symlink escape. Atomic replacement is guaranteed only within one filesystem.
210
+
211
+ ## Verification
212
+
213
+ Run the infrastructure suites and package checks from the repository root:
214
+
215
+ ```bash
216
+ uv run --package a13n-service pytest packages/foundation-service/tests/storage packages/foundation-service/tests/database -q
217
+ make lint
218
+ make typecheck
219
+ uv build --package a13n-service
220
+ ```
221
+
222
+ Container-owned integration tests exercise PostgreSQL, Redis, and S3 HTTP behavior. The S3 startup-probe test also demonstrates that an endpoint missing required conditional-delete semantics is rejected rather than silently accepted.
@@ -0,0 +1,196 @@
1
+ # Foundation Service
2
+
3
+ This package contains the hosted Foundation Service executable, its internal async-first storage substrate, and its service-owned relational schema lifecycle. It is a workspace package, not a public SDK or an independently distributed provider library.
4
+
5
+ The substrate exposes capability-specific interfaces instead of one generic storage facade:
6
+
7
+ - SQL uses SQLAlchemy's async `AsyncEngine` and `AsyncSession` APIs with PostgreSQL or SQLite.
8
+ - Redis-compatible data structures use `redis.asyncio.Redis` with Redis or process-local fakeredis.
9
+ - Objects use the small Foundation-owned `ObjectStore` protocol with S3-compatible or local-directory adapters.
10
+ - Local files and deployment-mounted NFS use the same confined `pathlib` and AnyIO helpers.
11
+
12
+ Backend selection happens once during process startup. A failed network backend never falls back to local state.
13
+
14
+ ## Runtime
15
+
16
+ `ServiceSettings` owns the `FOUNDATION_*` environment contract and maps it to the frozen `StorageSettings` model. The storage package accepts typed configuration and does not read process environment variables itself. `foundation-service serve` constructs all selected providers once in FastAPI lifespan, publishes the resulting `StorageResources` on `app.state.storage`, and closes the resources during shutdown.
17
+
18
+ The default service profile keeps the existing PostgreSQL and Redis endpoints and uses separate local roots for objects and files. Set `FOUNDATION_OBJECT_BACKEND=s3` and `FOUNDATION_OBJECT_BUCKET` for a multi-process deployment; the local object adapter supports only one writing process. `FOUNDATION_FILESYSTEM_ROOT` may be an ordinary local directory or an NFS mount prepared by deployment.
19
+
20
+ ```python
21
+ from pathlib import Path
22
+
23
+ from a13n_service.storage import StorageSettings, open_storage
24
+
25
+ settings = StorageSettings.model_validate(
26
+ {
27
+ "database": {"backend": "sqlite", "path": Path("var/foundation.sqlite3")},
28
+ "redis": {"backend": "memory"},
29
+ "objects": {"backend": "local", "root": Path("var/objects")},
30
+ "filesystem": {"root": Path("var/files")},
31
+ }
32
+ )
33
+
34
+ async with open_storage(settings) as storage:
35
+ # Inject `storage` into application-owned services here.
36
+ ...
37
+ ```
38
+
39
+ `open_storage()` constructs one engine, session factory, Redis client, object store, and filesystem boundary. It checks required capabilities before yielding and closes all resources in reverse order.
40
+
41
+ A network deployment selects the corresponding backends without changing consumer code:
42
+
43
+ ```python
44
+ network_settings = StorageSettings.model_validate(
45
+ {
46
+ "database": {
47
+ "backend": "postgresql",
48
+ "url": "postgresql://foundation:password@postgres/foundation",
49
+ },
50
+ "redis": {"backend": "redis", "url": "redis://redis:6379/0"},
51
+ "objects": {
52
+ "backend": "s3",
53
+ "bucket": "foundation-objects",
54
+ "region": "us-east-1",
55
+ },
56
+ "filesystem": {"root": Path("/mnt/foundation-files")},
57
+ }
58
+ )
59
+ ```
60
+
61
+ The S3 client uses the standard AWS credential chain. Set `endpoint_url` and `force_path_style` only for a compatible non-AWS endpoint. The deployment mounts NFS at the configured filesystem root before the process starts.
62
+
63
+ ## Relational Usage
64
+
65
+ Consumers use SQLAlchemy directly. Generic storage does not define `get`, `insert`, or `do` wrappers.
66
+
67
+ ```python
68
+ from sqlalchemy import select
69
+
70
+ from a13n_service.storage import transaction
71
+
72
+ async with transaction(storage.sessions) as session:
73
+ result = await session.execute(select(Record).where(Record.id == record_id))
74
+ record = result.scalar_one_or_none()
75
+ ```
76
+
77
+ Each operation gets a short session. Never retain a session or transaction across external I/O, agent execution, sleeps, background work, or a streaming response.
78
+
79
+ PostgreSQL is the distributed-service backend. SQLite is intended for a single-process, zero-service profile and must not be placed on NFS.
80
+
81
+ ## Relational Schema and Migrations
82
+
83
+ Generic relational storage and service schema ownership are deliberately separate:
84
+
85
+ - `storage/relational.py` constructs async engines and short sessions for application I/O.
86
+ - `database/metadata.py` aggregates every service-owned ORM model.
87
+ - `database/migrations/` contains one linear Alembic history for the complete service database.
88
+ - `database/migration.py` owns the dedicated synchronous migration connection, bounded PostgreSQL advisory locking, and Alembic invocation.
89
+
90
+ The Alembic environment does not read process settings or create an engine. The runner supplies one validated connection, so CLI settings, lock policy, and schema comparison have distinct owners.
91
+
92
+ Select the database backend, then use the stable service CLI or repository commands:
93
+
94
+ ```bash
95
+ FOUNDATION_DATABASE_BACKEND=postgresql
96
+ FOUNDATION_DATABASE_URL=postgresql+psycopg://foundation:foundation@127.0.0.1:5432/foundation
97
+
98
+ make db-upgrade
99
+ make db-current
100
+ make db-check
101
+ make db-history
102
+ ```
103
+
104
+ The corresponding executable commands are `foundation-service db upgrade`, `foundation-service db current --check-heads`, `foundation-service db history`, and `foundation-service db migrate "description"`. There is one process CLI; migration implementation remains in `database/migration.py` rather than introducing a second database-only settings or command layer.
105
+
106
+ For the zero-service profile, set `FOUNDATION_DATABASE_BACKEND=sqlite` and `FOUNDATION_DATABASE_SQLITE_PATH=var/foundation.sqlite3`. The same accepted history is applied to both backends. A domain requiring PostgreSQL-only schema behavior must reject SQLite explicitly.
107
+
108
+ ### Add an ORM Model
109
+
110
+ 1. Define the model beside its owning domain using `a13n_service.database.Base`.
111
+ 2. Import that domain model module explicitly in `database/metadata.py`; there is no package scanning or plugin discovery.
112
+ 3. Run `make db-migrate msg="describe the schema change"`. The target rebuilds accepted history in a disposable PostgreSQL database before autogeneration.
113
+ 4. Review the generated revision for names, constraints, data loss, lock behavior, rolling compatibility, interruption safety, and downgrade or forward repair.
114
+ 5. Run the database tests on SQLite and PostgreSQL plus `make db-check` against an upgraded database.
115
+
116
+ Do not create revision files by hand and do not use runtime `metadata.create_all()` as schema bootstrap. Application request paths use async SQLAlchemy; migrations use a separate synchronous `NullPool` connection because they run before traffic or in a dedicated deployment job.
117
+
118
+ ## Redis Usage
119
+
120
+ The injected async redis-py client exposes strings, hashes, lists, sets, sorted sets, Streams, pipelines, transactions, and Pub/Sub without local/network branches.
121
+
122
+ ```python
123
+ await storage.redis.hset(b"run:1", mapping={b"status": b"running"})
124
+ await storage.redis.rpush(b"run:1:steps", b"step-1")
125
+ await storage.redis.xadd(b"run-events", {b"payload": payload})
126
+ ```
127
+
128
+ Response decoding is disabled for binary safety. The fakeredis backend is process-local and non-durable; use a real Redis service for multiple processes, persistence, modules, or exact server failure behavior.
129
+
130
+ ## Object Usage
131
+
132
+ Object keys are opaque names rather than filesystem paths. `put` supports unconditional, create-only, and expected-version publication.
133
+
134
+ ```python
135
+ from a13n_service.storage import ByteRange, ObjectConflict
136
+
137
+ created = await storage.objects.put(
138
+ "artifacts/result.json",
139
+ payload,
140
+ content_type="application/json",
141
+ metadata={"trace": trace_id},
142
+ if_none_match=True,
143
+ )
144
+
145
+ async with storage.objects.open("artifacts/result.json", byte_range=ByteRange(0, 64)) as reader:
146
+ prefix = b"".join([chunk async for chunk in reader])
147
+
148
+ try:
149
+ updated = await storage.objects.put(
150
+ "artifacts/result.json",
151
+ new_payload,
152
+ if_match=created.version,
153
+ )
154
+ except ObjectConflict:
155
+ # Re-read and make a new domain decision.
156
+ ...
157
+ ```
158
+
159
+ S3 endpoints must support AWS-compatible conditional writes and deletes, range reads, head requests, and ordered `ListObjectsV2` pagination. Startup rejects endpoints that silently ignore these conditions. The local adapter provides the common behavior for exactly one writing service process.
160
+
161
+ Metadata keys are normalized to lowercase and, like S3 REST metadata, keys and values must be ASCII. Keys must also be valid HTTP field names. Returned metadata mappings are immutable.
162
+
163
+ ## Filesystem Usage
164
+
165
+ Deployment mounts NFS before process startup. Application code receives the mounted root and uses the same helpers as a local directory; there is no Python NFS provider.
166
+
167
+ ```python
168
+ import anyio
169
+
170
+ from a13n_service.storage.filesystem import atomic_write, resolve_under_root
171
+
172
+ destination = await resolve_under_root(
173
+ storage.files_root,
174
+ "exports/result.json",
175
+ limiter=storage.file_limiter,
176
+ )
177
+ await atomic_write(destination, chunks, limiter=storage.file_limiter)
178
+
179
+ async with await anyio.open_file(destination, "rb") as file:
180
+ prefix = await file.read(64 * 1024)
181
+ ```
182
+
183
+ Confined resolution rejects absolute paths, parent traversal, and symlink escape. Atomic replacement is guaranteed only within one filesystem.
184
+
185
+ ## Verification
186
+
187
+ Run the infrastructure suites and package checks from the repository root:
188
+
189
+ ```bash
190
+ uv run --package a13n-service pytest packages/foundation-service/tests/storage packages/foundation-service/tests/database -q
191
+ make lint
192
+ make typecheck
193
+ uv build --package a13n-service
194
+ ```
195
+
196
+ Container-owned integration tests exercise PostgreSQL, Redis, and S3 HTTP behavior. The S3 startup-probe test also demonstrates that an endpoint missing required conditional-delete semantics is rejected rather than silently accepted.