glosslayer-flowfile 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .venv/
5
+ dist/
6
+ build/
7
+ .pytest_cache/
8
+ .ruff_cache/
9
+ *.db
10
+ *.db-shm
11
+ *.db-wal
12
+ report.html
13
+ .DS_Store
14
+ .idea/
15
+ .vscode/
16
+ .coverage
17
+ htmlcov/
18
+ *.yaml.bak
19
+ # working notes that are not part of the project
20
+ REVIEW.md
@@ -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
+ Gloss
2
+ Copyright 2026 Gloss contributors
3
+
4
+ This product includes the Apache Ossie core JSON Schema
5
+ (src/glosslayer/ossie/ossie-schema.json) and an example semantic model
6
+ (tests/ossie_renamed_fields.yaml), developed at The Apache Software
7
+ Foundation (https://www.apache.org/) and licensed under the Apache
8
+ License, Version 2.0.
9
+
10
+ Gloss is an independent project and is not affiliated with or endorsed
11
+ by The Apache Software Foundation. "Apache" and "Apache Ossie" are
12
+ trademarks of The Apache Software Foundation.
@@ -0,0 +1,127 @@
1
+ Metadata-Version: 2.5
2
+ Name: glosslayer-flowfile
3
+ Version: 0.1.0
4
+ Summary: Gloss plugin for the Flowfile catalog: catalog seam plus lineage-based proposals.
5
+ Project-URL: Homepage, https://github.com/Edwardvaneechoud/glosslayer
6
+ Project-URL: Repository, https://github.com/Edwardvaneechoud/glosslayer
7
+ Project-URL: Issues, https://github.com/Edwardvaneechoud/glosslayer/issues
8
+ Project-URL: Changelog, https://github.com/Edwardvaneechoud/glosslayer/blob/main/CHANGELOG.md
9
+ Author: Gloss contributors
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ License-File: NOTICE
13
+ Keywords: data-catalog,flowfile,lineage,metadata,ossie,semantic-layer
14
+ Classifier: Development Status :: 3 - Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
21
+ Classifier: Programming Language :: Python :: 3.14
22
+ Classifier: Programming Language :: Python :: 3.15
23
+ Classifier: Topic :: Database
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: glosslayer<0.2,>=0.1.0
26
+ Description-Content-Type: text/markdown
27
+
28
+ # glosslayer-flowfile
29
+
30
+ Gloss plugin for [Flowfile](https://github.com/Edwardvaneechoud/Flowfile)'s catalog.
31
+
32
+ | Part | Name | What it does |
33
+ |---|---|---|
34
+ | Catalog | `FlowfileCatalog` (entry point `flowfile`) | Lists Flowfile catalog tables as `catalog.schema.table`, with columns and types. Knows whether its listing is the whole catalog or one user's view. Writes accepted table descriptions back. |
35
+ | Source | `LineageSource` (entry point `flowfile-lineage`) | Uses table lineage (producing flow → tables it reads) to propose confidentiality, classification and descriptions downstream. |
36
+ | Backend glue | `Embedded`, `FlowfilePolicy`, `policy_for`, `actor_for`, `Directory` | Catalog events, per-request views, and a policy answered from the rights the backend already resolved. |
37
+
38
+ Nothing in this package imports Flowfile: it is handed Flowfile's objects and plain values. It is tested
39
+ against a fake `CatalogService` with the shape of Flowfile's `CatalogTableOut`, not a running Flowfile.
40
+
41
+ ## Install
42
+
43
+ ```bash
44
+ pip install glosslayer-flowfile # pulls in the matching glosslayer core
45
+ ```
46
+
47
+ ## Embedded in Flowfile's backend
48
+
49
+ ```python
50
+ import glosslayer
51
+ from glosslayer_flowfile import Embedded, FlowfileCatalog, LineageSource, policy_for
52
+
53
+ # 1. Schema: from a Flowfile Alembic revision (and again whenever Gloss is upgraded)
54
+ glosslayer.schema.upgrade(op.get_bind())
55
+
56
+ # 2. One ledger on Flowfile's engine. Gloss adds no listeners and runs no DDL here.
57
+ g = glosslayer.Gloss(glosslayer.SQLStore(engine), policy=policy_for(sharing=sharing_enabled()))
58
+
59
+ # 3. The catalog, through a CatalogService built WITHOUT an access resolver: the whole local catalog.
60
+ semantics = Embedded(g, FlowfileCatalog(service=CatalogService(repo)))
61
+ semantics.sync() # at startup, as the backend itself
62
+
63
+ # 4. From Flowfile's own table paths, where the change is made
64
+ semantics.table_written(qualified_name) # created, overwritten with new columns
65
+ semantics.table_renamed(old_qualified_name, new_qualified_name) # update_table(name=…/namespace_id=…)
66
+ semantics.table_deleted(qualified_name) # delete_table
67
+
68
+ # 5. Per request: who is asking, and what the backend already knows about their rights
69
+ view = semantics.view(
70
+ user_id=user.id,
71
+ admin=user.is_admin,
72
+ manage=paths_of(access.writable_namespace_ids()), # namespace ids → "catalog.schema" paths
73
+ read=None, # or the readable paths where the catalog is private
74
+ )
75
+ app.include_router(create_router(lambda user=Depends(get_current_active_user): view_for(user)),
76
+ prefix="/semantic")
77
+
78
+ # 6. Proposals from lineage, whenever convenient
79
+ g.propose_many(LineageSource(semantics.catalog).proposals(g), source=LineageSource.source_id)
80
+ ```
81
+
82
+ What the pieces take care of:
83
+
84
+ - **Never sync per user.** A `CatalogService` with an access resolver lists only what that user may see.
85
+ `FlowfileCatalog` then reports its listing as incomplete, so a sync through it can discover and update
86
+ tables but never marks a table it cannot see as gone. Build the service without a resolver for the
87
+ backend's own sync.
88
+ - **Renames.** Flowfile's `update_table` can change a table's name and namespace, and table ids can be
89
+ reused after a delete, so neither is an identity on its own. Call `table_renamed` from the update path
90
+ and everything known about the table moves with it. A full `sync()` also recognises a rename when the id
91
+ matches *and* the columns are unchanged.
92
+ - **Hub tables.** Rows Flowfile shows from a connected hub (`source="hub"`, negated ids) are skipped: their
93
+ meaning lives in the hub's ledger. Use `glosslayer.client.Federation` to show both ledgers as one.
94
+ - **Who decides.** `policy_for(sharing=False)` is the desktop app: one user, their own edits accepted at
95
+ once, AI suggestions still queued. With sharing on, people decide where they manage the namespace, and
96
+ the policy answers from the `manage`/`read`/`admin` values passed to `view()`, so no database lookups
97
+ happen inside a batch.
98
+ - **Descriptions.** Gloss owns meaning. When a table description is accepted, `Embedded` writes it to
99
+ Flowfile's own `description` field (`own_descriptions=False` turns that off). Flowfile stores no
100
+ description per column; those stay in Gloss.
101
+ - **Actors are ids.** `actor_for(user.id)` puts the user's id in the log, not their name; give
102
+ `glosslayer.Gloss(..., directory=Directory(lookup))` a lookup to show names. Flowfile's integer id is stable
103
+ on one machine. A ledger shared between machines needs an id every machine agrees on.
104
+
105
+ ### Packaging (PyInstaller)
106
+
107
+ - Register plugins in code so nothing depends on distribution metadata:
108
+ `glosslayer.plugins.register("catalog", "flowfile", FlowfileCatalog)`.
109
+ - Add `collect_data_files("glosslayer")` for `glosslayer/ossie/ossie-schema.json` (only needed for `validate()`).
110
+ - Gloss's core needs SQLAlchemy and PyYAML, both already Flowfile dependencies.
111
+
112
+ ## Standalone
113
+
114
+ ```bash
115
+ export FLOWFILE_TOKEN=... # a Flowfile JWT: one user's view, so nothing is ever marked gone
116
+ gloss sync flowfile:http://localhost:63578
117
+ gloss import flowfile-lineage http://localhost:63578
118
+ gloss pending --source inferred:
119
+ ```
120
+
121
+ ## Roadmap
122
+
123
+ - Column-level lineage from the flow graph (select / rename / formula nodes)
124
+ - Relationship proposals from join nodes
125
+ - Metric candidates from group-by aggregations
126
+ - Profiling proposals (candidate keys, uniqueness) via Polars on the Delta tables
127
+ - A Vue review panel for the Flowfile catalog page
@@ -0,0 +1,100 @@
1
+ # glosslayer-flowfile
2
+
3
+ Gloss plugin for [Flowfile](https://github.com/Edwardvaneechoud/Flowfile)'s catalog.
4
+
5
+ | Part | Name | What it does |
6
+ |---|---|---|
7
+ | Catalog | `FlowfileCatalog` (entry point `flowfile`) | Lists Flowfile catalog tables as `catalog.schema.table`, with columns and types. Knows whether its listing is the whole catalog or one user's view. Writes accepted table descriptions back. |
8
+ | Source | `LineageSource` (entry point `flowfile-lineage`) | Uses table lineage (producing flow → tables it reads) to propose confidentiality, classification and descriptions downstream. |
9
+ | Backend glue | `Embedded`, `FlowfilePolicy`, `policy_for`, `actor_for`, `Directory` | Catalog events, per-request views, and a policy answered from the rights the backend already resolved. |
10
+
11
+ Nothing in this package imports Flowfile: it is handed Flowfile's objects and plain values. It is tested
12
+ against a fake `CatalogService` with the shape of Flowfile's `CatalogTableOut`, not a running Flowfile.
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install glosslayer-flowfile # pulls in the matching glosslayer core
18
+ ```
19
+
20
+ ## Embedded in Flowfile's backend
21
+
22
+ ```python
23
+ import glosslayer
24
+ from glosslayer_flowfile import Embedded, FlowfileCatalog, LineageSource, policy_for
25
+
26
+ # 1. Schema: from a Flowfile Alembic revision (and again whenever Gloss is upgraded)
27
+ glosslayer.schema.upgrade(op.get_bind())
28
+
29
+ # 2. One ledger on Flowfile's engine. Gloss adds no listeners and runs no DDL here.
30
+ g = glosslayer.Gloss(glosslayer.SQLStore(engine), policy=policy_for(sharing=sharing_enabled()))
31
+
32
+ # 3. The catalog, through a CatalogService built WITHOUT an access resolver: the whole local catalog.
33
+ semantics = Embedded(g, FlowfileCatalog(service=CatalogService(repo)))
34
+ semantics.sync() # at startup, as the backend itself
35
+
36
+ # 4. From Flowfile's own table paths, where the change is made
37
+ semantics.table_written(qualified_name) # created, overwritten with new columns
38
+ semantics.table_renamed(old_qualified_name, new_qualified_name) # update_table(name=…/namespace_id=…)
39
+ semantics.table_deleted(qualified_name) # delete_table
40
+
41
+ # 5. Per request: who is asking, and what the backend already knows about their rights
42
+ view = semantics.view(
43
+ user_id=user.id,
44
+ admin=user.is_admin,
45
+ manage=paths_of(access.writable_namespace_ids()), # namespace ids → "catalog.schema" paths
46
+ read=None, # or the readable paths where the catalog is private
47
+ )
48
+ app.include_router(create_router(lambda user=Depends(get_current_active_user): view_for(user)),
49
+ prefix="/semantic")
50
+
51
+ # 6. Proposals from lineage, whenever convenient
52
+ g.propose_many(LineageSource(semantics.catalog).proposals(g), source=LineageSource.source_id)
53
+ ```
54
+
55
+ What the pieces take care of:
56
+
57
+ - **Never sync per user.** A `CatalogService` with an access resolver lists only what that user may see.
58
+ `FlowfileCatalog` then reports its listing as incomplete, so a sync through it can discover and update
59
+ tables but never marks a table it cannot see as gone. Build the service without a resolver for the
60
+ backend's own sync.
61
+ - **Renames.** Flowfile's `update_table` can change a table's name and namespace, and table ids can be
62
+ reused after a delete, so neither is an identity on its own. Call `table_renamed` from the update path
63
+ and everything known about the table moves with it. A full `sync()` also recognises a rename when the id
64
+ matches *and* the columns are unchanged.
65
+ - **Hub tables.** Rows Flowfile shows from a connected hub (`source="hub"`, negated ids) are skipped: their
66
+ meaning lives in the hub's ledger. Use `glosslayer.client.Federation` to show both ledgers as one.
67
+ - **Who decides.** `policy_for(sharing=False)` is the desktop app: one user, their own edits accepted at
68
+ once, AI suggestions still queued. With sharing on, people decide where they manage the namespace, and
69
+ the policy answers from the `manage`/`read`/`admin` values passed to `view()`, so no database lookups
70
+ happen inside a batch.
71
+ - **Descriptions.** Gloss owns meaning. When a table description is accepted, `Embedded` writes it to
72
+ Flowfile's own `description` field (`own_descriptions=False` turns that off). Flowfile stores no
73
+ description per column; those stay in Gloss.
74
+ - **Actors are ids.** `actor_for(user.id)` puts the user's id in the log, not their name; give
75
+ `glosslayer.Gloss(..., directory=Directory(lookup))` a lookup to show names. Flowfile's integer id is stable
76
+ on one machine. A ledger shared between machines needs an id every machine agrees on.
77
+
78
+ ### Packaging (PyInstaller)
79
+
80
+ - Register plugins in code so nothing depends on distribution metadata:
81
+ `glosslayer.plugins.register("catalog", "flowfile", FlowfileCatalog)`.
82
+ - Add `collect_data_files("glosslayer")` for `glosslayer/ossie/ossie-schema.json` (only needed for `validate()`).
83
+ - Gloss's core needs SQLAlchemy and PyYAML, both already Flowfile dependencies.
84
+
85
+ ## Standalone
86
+
87
+ ```bash
88
+ export FLOWFILE_TOKEN=... # a Flowfile JWT: one user's view, so nothing is ever marked gone
89
+ gloss sync flowfile:http://localhost:63578
90
+ gloss import flowfile-lineage http://localhost:63578
91
+ gloss pending --source inferred:
92
+ ```
93
+
94
+ ## Roadmap
95
+
96
+ - Column-level lineage from the flow graph (select / rename / formula nodes)
97
+ - Relationship proposals from join nodes
98
+ - Metric candidates from group-by aggregations
99
+ - Profiling proposals (candidate keys, uniqueness) via Polars on the Delta tables
100
+ - A Vue review panel for the Flowfile catalog page
@@ -0,0 +1,41 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.27"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "glosslayer-flowfile"
7
+ version = "0.1.0"
8
+ description = "Gloss plugin for the Flowfile catalog: catalog seam plus lineage-based proposals."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Gloss contributors" }]
13
+ keywords = ["semantic-layer", "ossie", "flowfile", "data-catalog", "lineage", "metadata"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Intended Audience :: Developers",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Programming Language :: Python :: 3.15",
24
+ "Topic :: Database",
25
+ ]
26
+ dependencies = ["glosslayer>=0.1.0,<0.2"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/Edwardvaneechoud/glosslayer"
30
+ Repository = "https://github.com/Edwardvaneechoud/glosslayer"
31
+ Issues = "https://github.com/Edwardvaneechoud/glosslayer/issues"
32
+ Changelog = "https://github.com/Edwardvaneechoud/glosslayer/blob/main/CHANGELOG.md"
33
+
34
+ [project.entry-points."gloss.catalogs"]
35
+ flowfile = "glosslayer_flowfile:FlowfileCatalog"
36
+
37
+ [project.entry-points."gloss.sources"]
38
+ flowfile-lineage = "glosslayer_flowfile:LineageSource"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/glosslayer_flowfile"]
@@ -0,0 +1,17 @@
1
+ """Gloss plugin for Flowfile (https://github.com/Edwardvaneechoud/Flowfile)."""
2
+
3
+ from .catalog import FlowfileCatalog, is_remote, table_key
4
+ from .embedding import Directory, Embedded, FlowfilePolicy, actor_for, policy_for
5
+ from .lineage import LineageSource
6
+
7
+ __all__ = [
8
+ "Directory",
9
+ "Embedded",
10
+ "FlowfileCatalog",
11
+ "FlowfilePolicy",
12
+ "LineageSource",
13
+ "actor_for",
14
+ "is_remote",
15
+ "policy_for",
16
+ "table_key",
17
+ ]
@@ -0,0 +1,163 @@
1
+ """Flowfile catalog seam.
2
+
3
+ Two ways to connect:
4
+
5
+ * **Embedded** (inside Flowfile's backend): pass a Flowfile ``CatalogService`` built *without*
6
+ an access resolver, so the listing is the whole local catalog. No HTTP.
7
+
8
+ FlowfileCatalog(service=CatalogService(repo))
9
+
10
+ * **Remote** (standalone Gloss, CLI): talk to a running Flowfile core over REST.
11
+
12
+ gloss sync flowfile:http://localhost:63578 # token from FLOWFILE_TOKEN
13
+
14
+ Dataset keys are Flowfile's fully qualified ``catalog.schema.table`` names, which is also how
15
+ Flowfile itself addresses a table across machines.
16
+
17
+ A listing made for one user (a service with an access resolver, or a user's token) only shows
18
+ what that user may see. Such a catalog reports ``Coverage(complete=False)``, so a sync through it
19
+ discovers and updates tables and never concludes that a table it cannot see is gone.
20
+
21
+ Tables that belong to a connected hub are skipped: their meaning lives in the hub's ledger.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import json
27
+ import os
28
+ import urllib.request
29
+ from collections.abc import Callable
30
+ from typing import Any
31
+
32
+ from glosslayer.seams import AssetSchema, Column, Coverage, asset_fingerprint
33
+
34
+
35
+ def _get(obj: Any, name: str, default: Any = None) -> Any:
36
+ """Read a field from a pydantic model (embedded) or a dict (REST)."""
37
+ if isinstance(obj, dict):
38
+ return obj.get(name, default)
39
+ return getattr(obj, name, default)
40
+
41
+
42
+ def table_key(table: Any) -> str:
43
+ """A table's dataset key: its qualified ``catalog.schema.table`` name, falling back to older fields."""
44
+ return _get(table, "qualified_name") or _get(table, "full_table_name") or _get(table, "name")
45
+
46
+
47
+ def is_remote(table: Any) -> bool:
48
+ """A row Flowfile shows from a connected hub (it carries ``source="hub"`` and a negated id)."""
49
+ tid = _get(table, "id")
50
+ return _get(table, "source", "local") != "local" or (isinstance(tid, int) and tid < 0)
51
+
52
+
53
+ class FlowfileCatalog:
54
+ """Flowfile's catalog as a Gloss catalog, embedded (a ``CatalogService``) or remote (``fetch_tables``).
55
+
56
+ Tables from a connected hub are left out, and so are virtual tables with ``include_virtual=False``.
57
+ """
58
+
59
+ def __init__(
60
+ self,
61
+ *,
62
+ service: Any | None = None,
63
+ fetch_tables: Callable[[], list[Any]] | None = None,
64
+ name: str = "flowfile",
65
+ include_virtual: bool = True,
66
+ complete: bool | None = None,
67
+ ):
68
+ """``complete`` says the listing is the whole local catalog.
69
+
70
+ By default that is assumed only for an embedded service without an access resolver.
71
+ """
72
+ if fetch_tables is None:
73
+ if service is None:
74
+ raise ValueError("Pass a Flowfile CatalogService (embedded) or use FlowfileCatalog.from_spec(url)")
75
+ fetch_tables = service.list_tables
76
+ if complete is None:
77
+ complete = getattr(service, "access", None) is None
78
+ self._fetch = fetch_tables
79
+ self._service = service
80
+ self.name = name
81
+ self.include_virtual = include_virtual
82
+ self.complete = bool(complete)
83
+ self._tables: dict[str, Any] | None = None
84
+
85
+ # -- construction -------------------------------------------------------
86
+ @classmethod
87
+ def from_spec(cls, arg: str, **kwargs: Any) -> FlowfileCatalog:
88
+ """``flowfile:<base-url>``; the bearer token comes from ``FLOWFILE_TOKEN``.
89
+
90
+ A token is one user's view, so the listing is not taken as complete unless ``complete=True``.
91
+ """
92
+ base = arg.rstrip("/") if arg else "http://localhost:63578"
93
+ token = kwargs.pop("token", None) or os.environ.get("FLOWFILE_TOKEN")
94
+
95
+ def fetch() -> list[dict[str, Any]]:
96
+ req = urllib.request.Request(f"{base}/catalog/tables")
97
+ if token:
98
+ req.add_header("Authorization", f"Bearer {token}")
99
+ with urllib.request.urlopen(req, timeout=30) as resp: # noqa: S310 (user-supplied URL by design)
100
+ return json.loads(resp.read())
101
+
102
+ return cls(fetch_tables=fetch, **kwargs)
103
+
104
+ # -- Catalog protocol ---------------------------------------------------
105
+ def tables(self, refresh: bool = False) -> dict[str, Any]:
106
+ """The local tables by key, cached until ``refresh``."""
107
+ if self._tables is None or refresh:
108
+ out = {}
109
+ for t in self._fetch():
110
+ if is_remote(t):
111
+ continue
112
+ if not self.include_virtual and _get(t, "table_type", "physical") != "physical":
113
+ continue
114
+ out[table_key(t)] = t
115
+ self._tables = out
116
+ return self._tables
117
+
118
+ def coverage(self) -> Coverage:
119
+ """Complete only when the listing is the whole local catalog (see ``complete``)."""
120
+ return Coverage(complete=self.complete)
121
+
122
+ def list_assets(self) -> list[str]:
123
+ """The keys of a fresh listing."""
124
+ return list(self.tables(refresh=True))
125
+
126
+ def describe(self, key: str) -> AssetSchema:
127
+ """The table from the cached listing, refreshed once if the key is unknown."""
128
+ tables = self.tables()
129
+ if key not in tables:
130
+ tables = self.tables(refresh=True)
131
+ t = tables[key]
132
+ cols = [Column(name=_get(c, "name"), dtype=str(_get(c, "dtype", ""))) for c in _get(t, "schema_columns") or []]
133
+ tid = _get(t, "id")
134
+ extra = {
135
+ "flowfile_table_id": tid,
136
+ "table_type": _get(t, "table_type", "physical"),
137
+ "produced_by_flow": _get(t, "source_registration_name") or _get(t, "producer_registration_name"),
138
+ "row_count": _get(t, "row_count"),
139
+ }
140
+ return AssetSchema(
141
+ key=key,
142
+ columns=cols,
143
+ description=_get(t, "description"),
144
+ source=key,
145
+ extra={k: v for k, v in extra.items() if v is not None},
146
+ # Flowfile's ids can be reused after a delete, so sync only trusts them together with
147
+ # unchanged columns; report renames directly where possible (glosslayer.sync.asset_moved).
148
+ uid=str(tid) if tid is not None else None,
149
+ )
150
+
151
+ def fingerprint(self, key: str) -> str:
152
+ """``asset_fingerprint`` of the described table."""
153
+ return asset_fingerprint(self.describe(key))
154
+
155
+ def write_back(self, key: str, facts: dict[str, Any]) -> None:
156
+ """Show accepted dataset descriptions in Flowfile's catalog (embedded mode only).
157
+
158
+ Flowfile stores no description per column, so field descriptions stay in Gloss.
159
+ """
160
+ if self._service is None:
161
+ raise NotImplementedError("write_back needs embedded mode (a CatalogService)")
162
+ if "description" in facts:
163
+ self._service.update_table(_get(self.tables()[key], "id"), description=facts["description"])
@@ -0,0 +1,157 @@
1
+ """Wiring Gloss into the Flowfile backend: identity, permissions and catalog events.
2
+
3
+ Nothing here imports Flowfile. The host hands over plain values it already has (a user's id,
4
+ the namespace paths they manage), so this module is tested without a running Flowfile and the
5
+ core stays free of host imports.
6
+
7
+ semantics = Embedded(g, catalog)
8
+
9
+ # startup, and whenever in doubt
10
+ semantics.sync()
11
+
12
+ # from Flowfile's own table paths, right where the change is made
13
+ semantics.table_written("main.sales.orders")
14
+ semantics.table_renamed("main.sales.orders", "main.sales.order_lines")
15
+ semantics.table_deleted("main.sales.orders")
16
+
17
+ # per request
18
+ view = semantics.view(user_id=user.id, admin=user.is_admin, manage=["main.sales"])
19
+ view.pending()
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ from collections.abc import Callable, Iterable, Mapping
25
+ from dataclasses import dataclass
26
+ from typing import Any
27
+
28
+ from glosslayer import Gloss, Human
29
+ from glosslayer.actors import actor_kind, split_actor
30
+ from glosslayer.ids import path_covers
31
+ from glosslayer.model import Assertion
32
+ from glosslayer.policy import SOLO, TEAM, Context, DefaultPolicy
33
+ from glosslayer.sync import SyncReport, asset_moved, asset_removed, sync, sync_asset, write_back
34
+
35
+
36
+ def actor_for(user_id: Any) -> Human:
37
+ """The actor for a Flowfile user.
38
+
39
+ Pass an id that never changes for that person. Flowfile's integer user id is stable on one
40
+ machine; a ledger shared between machines needs an id every machine agrees on.
41
+ """
42
+ return Human(str(user_id))
43
+
44
+
45
+ @dataclass
46
+ class FlowfilePolicy(DefaultPolicy):
47
+ """Flowfile's access rules as a Gloss policy, answered from memory.
48
+
49
+ The host resolves a user's rights **once per request** and passes them in the view's context
50
+ (``Embedded.view`` does this):
51
+
52
+ * ``admin`` may decide and read everywhere;
53
+ * ``manage`` namespace paths the user manages: there they accept, reject, retract, re-key;
54
+ * ``read`` namespace paths the user may read; leave it out where the catalog is not private.
55
+
56
+ Desktop mode has one user and no sharing: construct with ``mode="solo"`` and every table is
57
+ theirs to decide.
58
+ """
59
+
60
+ def _attrs(self, context: Context | None) -> Mapping[str, Any]:
61
+ return context.attrs if context else {}
62
+
63
+ def _manages(self, context: Context | None, path: str | None) -> bool:
64
+ attrs = self._attrs(context)
65
+ if attrs.get("admin") or self.mode == SOLO:
66
+ return True
67
+ return any(path_covers(p, path) for p in attrs.get("manage") or ())
68
+
69
+ def may_decide(self, actor: str, assertion: Assertion | None, context: Context | None) -> bool:
70
+ """Admins and solo mode decide all; others must manage the fact's path (and a re-key's target)."""
71
+ if assertion is None:
72
+ return bool(self._attrs(context).get("admin")) or self.mode == SOLO
73
+ if not self._manages(context, assertion.scope_path):
74
+ return False
75
+ target = self._attrs(context).get("to")
76
+ if target:
77
+ from glosslayer.ids import SubjectId
78
+
79
+ return self._manages(context, SubjectId.parse(target).scope_path)
80
+ return True
81
+
82
+ def readable_prefixes(self, actor: str, context: Context | None) -> tuple[str, ...] | None:
83
+ """A person's ``read`` plus ``manage`` paths; all for admins, non-humans or an unset ``read``."""
84
+ attrs = self._attrs(context)
85
+ if actor_kind(actor) != "human" or attrs.get("admin") or attrs.get("read") is None:
86
+ return None
87
+ return tuple(dict.fromkeys([*attrs["read"], *(attrs.get("manage") or ())]))
88
+
89
+
90
+ def policy_for(*, sharing: bool) -> FlowfilePolicy:
91
+ """``sharing=False`` for the desktop app (one user, own edits accepted at once), else team review."""
92
+ return FlowfilePolicy(mode=TEAM if sharing else SOLO)
93
+
94
+
95
+ class Directory:
96
+ """Shows actors by name, using a lookup the host provides (``user id -> display name or None``)."""
97
+
98
+ def __init__(self, lookup: Callable[[str], str | None]):
99
+ self._lookup = lookup
100
+
101
+ def display_name(self, actor: str) -> str | None:
102
+ """A person's name from the host's lookup; other actors show their id."""
103
+ kind, ident = split_actor(actor)
104
+ return self._lookup(ident) if kind == "human" else ident
105
+
106
+
107
+ class Embedded:
108
+ """The ledger plus the Flowfile catalog, with the calls the backend makes."""
109
+
110
+ def __init__(self, gloss: Gloss, catalog: Any, *, own_descriptions: bool = True):
111
+ """``own_descriptions`` keeps Flowfile's table description in step with the accepted one."""
112
+ self.gloss = gloss
113
+ self.catalog = catalog
114
+ self._stop = write_back(gloss, catalog) if own_descriptions else None
115
+
116
+ def close(self) -> None:
117
+ """Stop writing accepted descriptions back to the catalog; safe to call twice."""
118
+ if self._stop is not None:
119
+ self._stop()
120
+ self._stop = None
121
+
122
+ # -- catalog events: run as the catalog's own principal, over everything ---------
123
+ def sync(self) -> SyncReport:
124
+ """Pull sync of the whole catalog: at startup, and whenever events may have been missed."""
125
+ return sync(self.gloss, self.catalog)
126
+
127
+ def table_written(self, key: str) -> SyncReport:
128
+ """Call after Flowfile creates or overwrites a table."""
129
+ return sync_asset(self.gloss, self.catalog, key)
130
+
131
+ def table_renamed(self, old_key: str, new_key: str) -> SyncReport:
132
+ """Call from Flowfile's table update path on a rename or move, so the table's facts follow it.
133
+
134
+ Flowfile emits no table-change event, so a rename the host does not report looks like
135
+ drop + add to a pull sync.
136
+ """
137
+ self.catalog.tables(refresh=True)
138
+ return asset_moved(self.gloss, self.catalog, old_key, new_key)
139
+
140
+ def table_deleted(self, key: str) -> SyncReport:
141
+ """Call from Flowfile's table delete path: the table's facts are marked stale."""
142
+ return asset_removed(self.gloss, self.catalog, key)
143
+
144
+ # -- per request -----------------------------------------------------------------
145
+ def view(
146
+ self,
147
+ *,
148
+ user_id: Any,
149
+ admin: bool = False,
150
+ manage: Iterable[str] = (),
151
+ read: Iterable[str] | None = None,
152
+ via: str | None = None,
153
+ **context: Any,
154
+ ) -> Gloss:
155
+ """A ledger view for one signed-in user, with their rights resolved by the host."""
156
+ attrs = {"admin": admin, "manage": tuple(manage), "read": None if read is None else tuple(read), **context}
157
+ return self.gloss.as_actor(actor_for(user_id), via=via, context=attrs)
@@ -0,0 +1,130 @@
1
+ """Lineage-based proposals from Flowfile.
2
+
3
+ Flowfile knows which flow produced each table and which tables each flow
4
+ reads. That gives table-level lineage: the *upstream* tables of a table are
5
+ the tables read by the flow that produced it.
6
+
7
+ What this source proposes today
8
+ -------------------------------
9
+ * **Confidentiality and classification follow the data.** When an upstream
10
+ column is accepted as e.g. ``confidential`` / ``pii.email``, a downstream
11
+ column with the same name is *proposed* with the same level (confidence 0.6,
12
+ as it is a name match). If a downstream table has upstream confidential data
13
+ at all, the table itself is proposed at that level (confidence 0.5).
14
+ * **Descriptions carry over** for same-named columns that have no accepted
15
+ description downstream (confidence 0.5).
16
+
17
+ Every proposal records the upstream table, the flow and the rule as evidence.
18
+
19
+ TODO (needs Flowfile's flow graph, available in embedded mode):
20
+ * column-level lineage through select/rename/formula nodes (raises confidence to ~0.9);
21
+ * relationships from join nodes (join keys → from_columns/to_columns);
22
+ * metric candidates from group-by + aggregate nodes.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ from collections.abc import Iterator
28
+ from typing import TYPE_CHECKING, Any
29
+
30
+ from glosslayer.ids import SubjectId
31
+ from glosslayer.ledger import Proposal
32
+ from glosslayer.model import Confidentiality, Status
33
+
34
+ from .catalog import FlowfileCatalog, _get
35
+
36
+ if TYPE_CHECKING:
37
+ from glosslayer.ledger import Gloss
38
+
39
+ _ATTRS = ("confidentiality", "classification", "description")
40
+
41
+
42
+ class LineageSource:
43
+ """Source plugin: proposes confidentiality, classification and descriptions along table lineage."""
44
+
45
+ source_id = "inferred:flowfile-lineage"
46
+
47
+ def __init__(self, catalog: FlowfileCatalog):
48
+ self.catalog = catalog
49
+
50
+ @classmethod
51
+ def from_spec(cls, arg: str, **kwargs: Any) -> LineageSource:
52
+ """``arg`` is a Flowfile base URL, as for ``FlowfileCatalog.from_spec``."""
53
+ return cls(FlowfileCatalog.from_spec(arg, **kwargs))
54
+
55
+ def upstream(self) -> dict[str, list[tuple[str, str | None]]]:
56
+ """{table_key: [(upstream_key, flow_name), ...]}"""
57
+ tables = self.catalog.tables(refresh=True)
58
+ readers: dict[int, list[str]] = {}
59
+ for key, t in tables.items():
60
+ for flow in _get(t, "read_by_flows") or []:
61
+ readers.setdefault(_get(flow, "id"), []).append(key)
62
+ out: dict[str, list[tuple[str, str | None]]] = {}
63
+ for key, t in tables.items():
64
+ producer = _get(t, "source_registration_id") or _get(t, "producer_registration_id")
65
+ if producer is None:
66
+ continue
67
+ flow_name = _get(t, "source_registration_name") or _get(t, "producer_registration_name")
68
+ ups = [(u, flow_name) for u in readers.get(producer, []) if u != key]
69
+ if ups:
70
+ out[key] = ups
71
+ return out
72
+
73
+ def proposals(self, gloss: Gloss) -> Iterator[Proposal]:
74
+ """Accepted upstream facts proposed for same-named downstream columns (and tables) lacking one."""
75
+ lineage = self.upstream()
76
+ columns = {key: [c.name for c in self.catalog.describe(key).columns] for key in lineage}
77
+
78
+ # everything this run needs to know, in two lookups instead of several per column
79
+ wanted: set[str] = set()
80
+ for key, ups in lineage.items():
81
+ for table in (key, *(u for u, _ in ups)):
82
+ wanted.add(str(SubjectId.for_dataset(table)))
83
+ wanted.update(str(SubjectId.for_field(table, col)) for col in columns[key])
84
+ known = gloss.current_many(wanted, attributes=_ATTRS)
85
+ open_levels = {
86
+ a.subject
87
+ for a in gloss.find(kind="dataset", attribute="confidentiality",
88
+ statuses=[Status.PROPOSED, Status.REVIEWED])
89
+ }
90
+
91
+ def facts(subject: SubjectId) -> dict[str, Any]:
92
+ return known.get(str(subject), {})
93
+
94
+ for key, ups in lineage.items():
95
+ strongest: Confidentiality | None = None
96
+ for up_key, flow in ups:
97
+ ev_base = {"upstream": up_key, "flow": flow}
98
+ ds_level = facts(SubjectId.for_dataset(up_key)).get("confidentiality")
99
+ for col in columns[key]:
100
+ up_facts = facts(SubjectId.for_field(up_key, col))
101
+ if not up_facts:
102
+ continue
103
+ down_subj = SubjectId.for_field(key, col)
104
+ down_facts = facts(down_subj)
105
+ level = up_facts.get("confidentiality") or ds_level
106
+ if level and Confidentiality(level) > Confidentiality.INTERNAL:
107
+ if "confidentiality" not in down_facts:
108
+ yield Proposal(
109
+ str(down_subj), "confidentiality", level, 0.6,
110
+ [{**ev_base, "rule": "same-name column downstream of confidential column"}],
111
+ )
112
+ lvl = Confidentiality(level)
113
+ strongest = lvl if strongest is None or lvl > strongest else strongest
114
+ if up_facts.get("classification") and "classification" not in down_facts:
115
+ yield Proposal(
116
+ str(down_subj), "classification", up_facts["classification"], 0.6,
117
+ [{**ev_base, "rule": "classification propagated by column name"}],
118
+ )
119
+ if up_facts.get("description") and "description" not in down_facts:
120
+ yield Proposal(
121
+ str(down_subj), "description", up_facts["description"], 0.5,
122
+ [{**ev_base, "rule": "description carried over from same-named upstream column"}],
123
+ )
124
+ if strongest is not None:
125
+ ds_subj = SubjectId.for_dataset(key)
126
+ if "confidentiality" not in facts(ds_subj) and str(ds_subj) not in open_levels:
127
+ yield Proposal(
128
+ str(ds_subj), "confidentiality", strongest.value, 0.5,
129
+ [{"upstream": [u for u, _ in ups], "rule": "contains data derived from confidential columns"}],
130
+ )
@@ -0,0 +1,196 @@
1
+ """Tests against a fake of Flowfile's CatalogService (same shape as CatalogTableOut).
2
+
3
+ The fake mirrors what matters for embedding: ``access`` is None for an unrestricted service,
4
+ and a restricted one lists only what its user may see.
5
+ """
6
+
7
+ import pytest
8
+
9
+ import glosslayer
10
+ from glosslayer import AI, PermissionDenied, Status
11
+ from glosslayer.sync import sync
12
+ from glosslayer_flowfile import Directory, Embedded, FlowfileCatalog, LineageSource, actor_for, policy_for
13
+
14
+
15
+ def _table(id, name, cols, *, produced_by=None, read_by=(), description=None, source="local"):
16
+ return {
17
+ "id": id,
18
+ "name": name.rsplit(".", 1)[-1],
19
+ "qualified_name": name,
20
+ "description": description,
21
+ "schema_columns": [{"name": c, "dtype": t} for c, t in cols],
22
+ "table_type": "physical",
23
+ "source_registration_id": produced_by,
24
+ "source_registration_name": f"flow_{produced_by}" if produced_by else None,
25
+ "read_by_flows": [{"id": f, "name": f"flow_{f}"} for f in read_by],
26
+ "source": source,
27
+ }
28
+
29
+
30
+ class FakeService:
31
+ def __init__(self, tables, *, visible_ids=None):
32
+ self.tables = tables
33
+ self.access = None if visible_ids is None else object() # a resolver means a user's view
34
+ self._visible = visible_ids
35
+ self.updated = {}
36
+
37
+ def list_tables(self, namespace_id=None, user_id=None):
38
+ return [t for t in self.tables if self._visible is None or t["id"] in self._visible]
39
+
40
+ def update_table(self, table_id, name=None, description=None, **_):
41
+ self.updated[table_id] = description
42
+ for t in self.tables:
43
+ if t["id"] == table_id and description is not None:
44
+ t["description"] = description
45
+
46
+
47
+ CUSTOMER_COLS = [("customer_id", "Int64"), ("email", "Utf8"), ("country", "Utf8")]
48
+
49
+
50
+ def make_tables():
51
+ return [
52
+ _table(1, "main.raw.customers", CUSTOMER_COLS, read_by=[7]),
53
+ _table(2, "main.mart.customers_clean", CUSTOMER_COLS, produced_by=7),
54
+ ]
55
+
56
+
57
+ def test_catalog_seam_embedded():
58
+ svc = FakeService(make_tables())
59
+ cat = FlowfileCatalog(service=svc)
60
+ assert cat.list_assets() == ["main.raw.customers", "main.mart.customers_clean"]
61
+ assert cat.coverage().complete
62
+ schema = cat.describe("main.mart.customers_clean")
63
+ assert schema.extra["produced_by_flow"] == "flow_7" and schema.uid == "2"
64
+ with glosslayer.open("sqlite://") as g:
65
+ rep = sync(g, cat)
66
+ assert len(rep.new) == 2
67
+ assert g.current("field:main.raw.customers/customer_id")["datatype"] == "Integer"
68
+ cat.write_back("main.raw.customers", {"description": "Raw CRM export"})
69
+ assert svc.updated == {1: "Raw CRM export"}
70
+
71
+
72
+ def test_a_users_listing_never_marks_other_users_tables_gone():
73
+ tables = make_tables()
74
+ with glosslayer.open("sqlite://") as g:
75
+ sync(g, FlowfileCatalog(service=FakeService(tables))) # the backend's own, unrestricted sync
76
+ bobs = g.propose("dataset:main.mart.customers_clean", "description", "Bob's mart", source="human:2")
77
+ g.accept(bobs.id, actor="human:2")
78
+
79
+ alice = FlowfileCatalog(service=FakeService(tables, visible_ids={1})) # what Alice may see
80
+ assert not alice.coverage().complete
81
+ rep = sync(g, alice)
82
+ assert rep.gone == [] and rep.staled == 0
83
+ assert g.get(bobs.id).status is Status.ACCEPTED
84
+
85
+ remote = FlowfileCatalog(fetch_tables=lambda: tables[:1]) # a user's token over REST: same caution
86
+ assert sync(g, remote).gone == []
87
+
88
+
89
+ def test_hub_rows_are_not_copied_into_the_local_ledger():
90
+ tables = make_tables() + [_table(-5, "org.finance.invoices", [("total", "Float64")], source="hub")]
91
+ cat = FlowfileCatalog(service=FakeService(tables))
92
+ assert "org.finance.invoices" not in cat.list_assets()
93
+ with glosslayer.open("sqlite://") as g:
94
+ sync(g, cat)
95
+ assert g.find(dataset="org.finance.invoices") == []
96
+
97
+
98
+ def test_backend_events_keep_meaning_with_the_table():
99
+ tables = make_tables()
100
+ svc = FakeService(tables)
101
+ with glosslayer.open("sqlite://", policy=policy_for(sharing=False)) as g:
102
+ semantics = Embedded(g, FlowfileCatalog(service=svc))
103
+ semantics.sync()
104
+ me = semantics.view(user_id=1)
105
+ # desktop mode: one user, own edits accepted at once, and Flowfile's description follows
106
+ a = me.propose("dataset:main.raw.customers", "description", "Raw CRM export")
107
+ assert a.status is Status.ACCEPTED and svc.updated == {1: "Raw CRM export"}
108
+ me.propose("field:main.raw.customers/email", "confidentiality", "restricted")
109
+
110
+ tables[0].update(name="clients", qualified_name="main.raw.clients") # Flowfile's update_table(name=…)
111
+ rep = semantics.table_renamed("main.raw.customers", "main.raw.clients")
112
+ assert rep.moved == {"main.raw.customers": "main.raw.clients"} and rep.staled == 0
113
+ assert g.current("dataset:main.raw.clients")["description"] == "Raw CRM export"
114
+ assert g.current("field:main.raw.clients/email")["confidentiality"] == "restricted"
115
+ assert semantics.sync().gone == []
116
+
117
+ tables[0]["schema_columns"].append({"name": "phone", "dtype": "Utf8"})
118
+ assert semantics.table_written("main.raw.clients").changed == ["main.raw.clients"]
119
+ assert g.current("field:main.raw.clients/phone")["datatype"] == "String"
120
+
121
+ del tables[0]
122
+ assert semantics.table_deleted("main.raw.clients").gone == ["main.raw.clients"]
123
+ assert g.find(dataset="main.raw.clients", statuses=[Status.ACCEPTED]) == []
124
+ semantics.close()
125
+
126
+
127
+ def test_policy_from_request_context():
128
+ with glosslayer.open("sqlite://", policy=policy_for(sharing=True)) as g:
129
+ semantics = Embedded(g, FlowfileCatalog(service=FakeService(make_tables())), own_descriptions=False)
130
+ semantics.sync()
131
+ alice = semantics.view(user_id="u-alice", manage=["main.raw"], read=["main.raw"])
132
+ bob = semantics.view(user_id="u-bob", manage=["main.mart"], read=["main.mart", "main.raw"])
133
+ admin = semantics.view(user_id="u-root", admin=True)
134
+
135
+ mine = alice.propose("dataset:main.raw.customers", "description", "Raw CRM export")
136
+ assert mine.status is Status.PROPOSED # shared mode: queued
137
+ with pytest.raises(PermissionDenied):
138
+ bob.accept(mine.id) # he reads main.raw but does not manage it
139
+ assert alice.accept(mine.id).status is Status.ACCEPTED
140
+ assert [t.key for t in alice.tables()] == ["main.raw.customers"]
141
+ assert len(bob.tables()) == 2 and len(admin.tables()) == 2
142
+ with pytest.raises(PermissionDenied):
143
+ alice.rekey("dataset:main.raw.customers", "dataset:main.mart.customers") # needs both ends
144
+ admin.rekey("dataset:main.raw.customers", "dataset:main.mart.customers")
145
+ agent = semantics.view(user_id="u-alice", manage=["main.raw"], via="ai:assistant")
146
+ idea = agent.propose("dataset:main.mart.customers", "synonyms", ["clients"], source=AI("assistant"))
147
+ with pytest.raises(PermissionDenied):
148
+ agent.accept(idea.id)
149
+
150
+
151
+ def test_actors_are_ids_and_names_come_from_the_host():
152
+ assert actor_for(42) == "human:42"
153
+ names = Directory({"42": "Ann"}.get)
154
+ assert names.display_name("human:42") == "Ann"
155
+ assert names.display_name("human:7") is None # someone who left: the log names no one
156
+ assert names.display_name("ai:assistant") == "assistant"
157
+
158
+
159
+ def test_lineage_propagates_confidentiality_and_descriptions():
160
+ cat = FlowfileCatalog(service=FakeService(make_tables()))
161
+ with glosslayer.open("sqlite://") as g:
162
+ sync(g, cat)
163
+ for attr, val in (("confidentiality", "restricted"), ("classification", ["pii.email"]),
164
+ ("description", "Login e-mail")):
165
+ a = g.propose("field:main.raw.customers/email", attr, val, source="human:dpo")
166
+ g.accept(a.id, actor="human:dpo")
167
+
168
+ src = LineageSource(cat)
169
+ assert src.upstream() == {"main.mart.customers_clean": [("main.raw.customers", "flow_7")]}
170
+ res = g.propose_many(src.proposals(g), source=src.source_id)
171
+ got = {(r.assertion.subject, r.assertion.attribute): r.assertion for r in res}
172
+
173
+ conf = got[("field:main.mart.customers_clean/email", "confidentiality")]
174
+ assert conf.value == "restricted" and conf.confidence == 0.6 and conf.status is Status.PROPOSED
175
+ assert conf.evidence[0]["upstream"] == "main.raw.customers"
176
+ assert got[("field:main.mart.customers_clean/email", "classification")].value == ["pii.email"]
177
+ assert got[("dataset:main.mart.customers_clean", "confidentiality")].value == "restricted"
178
+ assert ("field:main.mart.customers_clean/country", "confidentiality") not in got
179
+
180
+ # running again does not duplicate proposals
181
+ again = g.propose_many(src.proposals(g), source=src.source_id)
182
+ assert {r.outcome for r in again} == {"unchanged"}
183
+
184
+
185
+ def test_lineage_reads_in_batches(monkeypatch):
186
+ wide = [(f"c{i}", "Utf8") for i in range(40)]
187
+ tables = [_table(1, "main.raw.wide", wide, read_by=[7]), _table(2, "main.mart.wide", wide, produced_by=7)]
188
+ cat = FlowfileCatalog(service=FakeService(tables))
189
+ with glosslayer.open("sqlite://") as g:
190
+ sync(g, cat)
191
+ calls = []
192
+ for name in ("find", "find_for_subjects", "get", "get_many"):
193
+ original = getattr(g.store, name)
194
+ monkeypatch.setattr(g.store, name, lambda *a, _o=original, _n=name, **k: (calls.append(_n), _o(*a, **k))[1])
195
+ list(LineageSource(cat).proposals(g))
196
+ assert len(calls) <= 3 # not several lookups per column