authorized-recall 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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: authorized-recall
3
+ Version: 0.1.0
4
+ Summary: Authorized Recall@K — retrieval quality measured over the subset a principal is permitted to use
5
+ Author: Alexander Chernov
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/agentic-datasets/reference
8
+ Project-URL: Documentation, https://agenticdatasets.org/reference/
9
+ Project-URL: Source, https://github.com/agentic-datasets/reference/tree/main/packages/authorized-recall
10
+ Keywords: information retrieval,evaluation metric,authorization,access control,multi-tenant,RAG,ABAC,RBAC
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
13
+ Classifier: Intended Audience :: Science/Research
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # Authorized Recall@K
22
+
23
+ **Retrieval quality measured over the subset a principal may actually use.**
24
+
25
+ This package has no dependency on the rest of the repository. The metric takes
26
+ a predicate, not a `Principal`, so a system using RBAC, ABAC, row-level
27
+ security or per-tenant vector namespaces can adopt the measurement without
28
+ adopting anything else here.
29
+
30
+ ```bash
31
+ pip install authorized-recall
32
+ python -m authorized_recall # or: authorized-recall
33
+ ```
34
+
35
+ ---
36
+
37
+ ## Why
38
+
39
+ A retrieval system that surfaces a dataset the caller is not permitted to use
40
+ has not helped them. They cannot act on it; the only thing that changed is that
41
+ they now know it exists. Standard Recall@K scores that as a success, and it has
42
+ also spent one of the K slots doing it.
43
+
44
+ In the corpus measured here, **68.8% of what retrieval returns is unusable to
45
+ the principal who asked**, and Recall@K cannot see it.
46
+
47
+ ## Definition
48
+
49
+ Let
50
+
51
+ - $D$ — the corpus,
52
+ - $q$ — a query, with relevant set $R(q) \subseteq D$,
53
+ - $p$ — a principal, with authorization predicate $A_p : D \to \{0,1\}$,
54
+ - $L_K(q,p)$ — the ordered list of at most $K$ items the system returns.
55
+
56
+ The **authorized relevant set** is
57
+
58
+ $$R_A(q,p) = \{\, d \in R(q) : A_p(d) = 1 \,\}$$
59
+
60
+ and
61
+
62
+ $$\mathrm{ARecall}@K(q,p) = \frac{|R_A(q,p) \cap L_K(q,p)|}{|R_A(q,p)|},
63
+ \qquad \mathrm{ARecall}@K \triangleq 1 \ \text{ when } R_A = \emptyset .$$
64
+
65
+ Compare
66
+
67
+ $$\mathrm{Recall}@K(q) = \frac{|R(q) \cap L_K|}{|R(q)|} .$$
68
+
69
+ **When $A_p \equiv 1$, $\mathrm{ARecall}@K = \mathrm{Recall}@K$.** The metric is
70
+ a strict generalisation, not a different measurement.
71
+
72
+ ### Two conventions, stated because they change the mean
73
+
74
+ 1. $R_A = \emptyset \Rightarrow \mathrm{ARecall}@K = 1$. The system cannot be
75
+ faulted for failing to surface what it must not surface. Over a population
76
+ containing such pairs this inflates the mean, so report the restricted mean
77
+ — over pairs with $R_A \neq \emptyset$ — alongside it. The experiment here
78
+ prints both.
79
+ 2. Retrieved-but-unauthorized items are neither credited nor penalised inside
80
+ ARecall. They are a separate quantity:
81
+
82
+ $$U@K(q,p) = \frac{|\{\, d \in L_K : A_p(d) = 0 \,\}|}{K}$$
83
+
84
+ ## Where the filter sits
85
+
86
+ ARecall is computed over the list the system **returns**, so it is sensitive to
87
+ whether truncation happens before or after the authorization filter:
88
+
89
+ $$L_K^{\text{post}} = \sigma_{A_p}\big(\mathrm{top}_K(\mathrm{rank}(D))\big)
90
+ \qquad
91
+ L_K^{\text{pre}} = \mathrm{top}_K\big(\sigma_{A_p}(\mathrm{rank}(D))\big)$$
92
+
93
+ **Claim.** $L_K^{\text{post}} \subseteq L_K^{\text{pre}}$ for every ranking,
94
+ $K$ and $A_p$, hence
95
+
96
+ $$\Delta@K = \mathrm{ARecall}^{\text{pre}}@K - \mathrm{ARecall}^{\text{post}}@K \;\geq\; 0 .$$
97
+
98
+ *Proof.* Filtering preserves relative order. An item in $L_K^{\text{post}}$ is
99
+ authorized and appears within the first $K$ positions of the ranking, so at
100
+ most $K-1$ items precede it, so at most $K-1$ *authorized* items precede it,
101
+ so it appears within the first $K$ authorized items — which is
102
+ $L_K^{\text{pre}}$. ∎
103
+
104
+ The gap is therefore non-negative by construction rather than by luck of the
105
+ corpus. What the corpus determines is its *size*.
106
+
107
+ ## Measured
108
+
109
+ 40 synthetic datasets over 8 domains, 24 queries, 4 authorization profiles,
110
+ 96 query-principal pairs. Relevance by construction: a dataset is relevant to a
111
+ query when it is in the query's domain. Retrieval is TF-IDF cosine.
112
+
113
+ ```
114
+ K Recall ARecall ARecall gap unusable
115
+ post pre in top-K
116
+ 1 0.200 0.750 0.750 +0.000 68.8%
117
+ 3 0.483 0.835 0.863 +0.027 68.8%
118
+ 5 0.867 0.954 0.988 +0.033 68.5%
119
+ 10 1.000 1.000 1.000 +0.000 39.1%
120
+ ```
121
+
122
+ Restricted to the 30 pairs with $R_A \neq \emptyset$:
123
+
124
+ ```
125
+ K ARecall post ARecall pre gap
126
+ 1 0.200 0.200 +0.000
127
+ 3 0.473 0.560 +0.087
128
+ 5 0.853 0.960 +0.107
129
+ 10 1.000 1.000 +0.000
130
+ ```
131
+
132
+ **At K=5, moving the filter ahead of truncation takes ARecall@5 from 0.853 to
133
+ 0.960 (+0.107). Recall@5 stays at 0.867 and cannot see the difference.**
134
+
135
+ ## What this does and does not establish
136
+
137
+ The absolute values belong to this corpus: relevance is by construction, the
138
+ retriever is TF-IDF, and MRR is 1.000, so the retrieval task is easy. A harder
139
+ corpus or a better retriever moves all three columns.
140
+
141
+ The *gap* is what the metric was defined to isolate, and the claim above is
142
+ that it is a property of filter placement rather than of retrieval quality. The
143
+ proof makes its sign certain; the experiment gives its size in one setting.
144
+
145
+ Applying it to a real corpus with real authorization data is the obvious next
146
+ measurement, and this package is separable precisely so that someone else can
147
+ do it.
@@ -0,0 +1,127 @@
1
+ # Authorized Recall@K
2
+
3
+ **Retrieval quality measured over the subset a principal may actually use.**
4
+
5
+ This package has no dependency on the rest of the repository. The metric takes
6
+ a predicate, not a `Principal`, so a system using RBAC, ABAC, row-level
7
+ security or per-tenant vector namespaces can adopt the measurement without
8
+ adopting anything else here.
9
+
10
+ ```bash
11
+ pip install authorized-recall
12
+ python -m authorized_recall # or: authorized-recall
13
+ ```
14
+
15
+ ---
16
+
17
+ ## Why
18
+
19
+ A retrieval system that surfaces a dataset the caller is not permitted to use
20
+ has not helped them. They cannot act on it; the only thing that changed is that
21
+ they now know it exists. Standard Recall@K scores that as a success, and it has
22
+ also spent one of the K slots doing it.
23
+
24
+ In the corpus measured here, **68.8% of what retrieval returns is unusable to
25
+ the principal who asked**, and Recall@K cannot see it.
26
+
27
+ ## Definition
28
+
29
+ Let
30
+
31
+ - $D$ — the corpus,
32
+ - $q$ — a query, with relevant set $R(q) \subseteq D$,
33
+ - $p$ — a principal, with authorization predicate $A_p : D \to \{0,1\}$,
34
+ - $L_K(q,p)$ — the ordered list of at most $K$ items the system returns.
35
+
36
+ The **authorized relevant set** is
37
+
38
+ $$R_A(q,p) = \{\, d \in R(q) : A_p(d) = 1 \,\}$$
39
+
40
+ and
41
+
42
+ $$\mathrm{ARecall}@K(q,p) = \frac{|R_A(q,p) \cap L_K(q,p)|}{|R_A(q,p)|},
43
+ \qquad \mathrm{ARecall}@K \triangleq 1 \ \text{ when } R_A = \emptyset .$$
44
+
45
+ Compare
46
+
47
+ $$\mathrm{Recall}@K(q) = \frac{|R(q) \cap L_K|}{|R(q)|} .$$
48
+
49
+ **When $A_p \equiv 1$, $\mathrm{ARecall}@K = \mathrm{Recall}@K$.** The metric is
50
+ a strict generalisation, not a different measurement.
51
+
52
+ ### Two conventions, stated because they change the mean
53
+
54
+ 1. $R_A = \emptyset \Rightarrow \mathrm{ARecall}@K = 1$. The system cannot be
55
+ faulted for failing to surface what it must not surface. Over a population
56
+ containing such pairs this inflates the mean, so report the restricted mean
57
+ — over pairs with $R_A \neq \emptyset$ — alongside it. The experiment here
58
+ prints both.
59
+ 2. Retrieved-but-unauthorized items are neither credited nor penalised inside
60
+ ARecall. They are a separate quantity:
61
+
62
+ $$U@K(q,p) = \frac{|\{\, d \in L_K : A_p(d) = 0 \,\}|}{K}$$
63
+
64
+ ## Where the filter sits
65
+
66
+ ARecall is computed over the list the system **returns**, so it is sensitive to
67
+ whether truncation happens before or after the authorization filter:
68
+
69
+ $$L_K^{\text{post}} = \sigma_{A_p}\big(\mathrm{top}_K(\mathrm{rank}(D))\big)
70
+ \qquad
71
+ L_K^{\text{pre}} = \mathrm{top}_K\big(\sigma_{A_p}(\mathrm{rank}(D))\big)$$
72
+
73
+ **Claim.** $L_K^{\text{post}} \subseteq L_K^{\text{pre}}$ for every ranking,
74
+ $K$ and $A_p$, hence
75
+
76
+ $$\Delta@K = \mathrm{ARecall}^{\text{pre}}@K - \mathrm{ARecall}^{\text{post}}@K \;\geq\; 0 .$$
77
+
78
+ *Proof.* Filtering preserves relative order. An item in $L_K^{\text{post}}$ is
79
+ authorized and appears within the first $K$ positions of the ranking, so at
80
+ most $K-1$ items precede it, so at most $K-1$ *authorized* items precede it,
81
+ so it appears within the first $K$ authorized items — which is
82
+ $L_K^{\text{pre}}$. ∎
83
+
84
+ The gap is therefore non-negative by construction rather than by luck of the
85
+ corpus. What the corpus determines is its *size*.
86
+
87
+ ## Measured
88
+
89
+ 40 synthetic datasets over 8 domains, 24 queries, 4 authorization profiles,
90
+ 96 query-principal pairs. Relevance by construction: a dataset is relevant to a
91
+ query when it is in the query's domain. Retrieval is TF-IDF cosine.
92
+
93
+ ```
94
+ K Recall ARecall ARecall gap unusable
95
+ post pre in top-K
96
+ 1 0.200 0.750 0.750 +0.000 68.8%
97
+ 3 0.483 0.835 0.863 +0.027 68.8%
98
+ 5 0.867 0.954 0.988 +0.033 68.5%
99
+ 10 1.000 1.000 1.000 +0.000 39.1%
100
+ ```
101
+
102
+ Restricted to the 30 pairs with $R_A \neq \emptyset$:
103
+
104
+ ```
105
+ K ARecall post ARecall pre gap
106
+ 1 0.200 0.200 +0.000
107
+ 3 0.473 0.560 +0.087
108
+ 5 0.853 0.960 +0.107
109
+ 10 1.000 1.000 +0.000
110
+ ```
111
+
112
+ **At K=5, moving the filter ahead of truncation takes ARecall@5 from 0.853 to
113
+ 0.960 (+0.107). Recall@5 stays at 0.867 and cannot see the difference.**
114
+
115
+ ## What this does and does not establish
116
+
117
+ The absolute values belong to this corpus: relevance is by construction, the
118
+ retriever is TF-IDF, and MRR is 1.000, so the retrieval task is easy. A harder
119
+ corpus or a better retriever moves all three columns.
120
+
121
+ The *gap* is what the metric was defined to isolate, and the claim above is
122
+ that it is a property of filter placement rather than of retrieval quality. The
123
+ proof makes its sign certain; the experiment gives its size in one setting.
124
+
125
+ Applying it to a real corpus with real authorization data is the obvious next
126
+ measurement, and this package is separable precisely so that someone else can
127
+ do it.
@@ -0,0 +1,44 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "authorized-recall"
7
+ version = "0.1.0"
8
+ description = "Authorized Recall@K — retrieval quality measured over the subset a principal is permitted to use"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Alexander Chernov" }]
14
+ keywords = [
15
+ "information retrieval", "evaluation metric", "authorization",
16
+ "access control", "multi-tenant", "RAG", "ABAC", "RBAC",
17
+ ]
18
+ # No "License ::" classifier: PEP 639 supersedes them with the expression above.
19
+ classifiers = [
20
+ "Programming Language :: Python :: 3",
21
+ "Topic :: Scientific/Engineering :: Information Analysis",
22
+ "Intended Audience :: Science/Research",
23
+ ]
24
+
25
+ # No dependencies, and that is the point: the metric is a property of
26
+ # policy-conditioned retrieval, not of any particular stack. It takes an
27
+ # authorization predicate, so a system using RBAC, ABAC, row-level security or
28
+ # per-tenant vector namespaces can adopt the measurement without adopting
29
+ # anything else.
30
+ dependencies = []
31
+
32
+ [project.optional-dependencies]
33
+ dev = ["pytest>=8"]
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/agentic-datasets/reference"
37
+ Documentation = "https://agenticdatasets.org/reference/"
38
+ Source = "https://github.com/agentic-datasets/reference/tree/main/packages/authorized-recall"
39
+
40
+ [project.scripts]
41
+ authorized-recall = "authorized_recall.experiment:main"
42
+
43
+ [tool.setuptools.packages.find]
44
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,28 @@
1
+ """Authorized Recall@K — retrieval quality over the subset a principal may use.
2
+
3
+ Self-contained: nothing in this package imports the rest of the repository, so
4
+ the metric can be adopted without adopting the control plane. See README.md
5
+ here for the definition and the non-negativity proof for the pre/post-filter
6
+ gap.
7
+ """
8
+
9
+ from .metric import (
10
+ Authorized,
11
+ authorized_recall_at_k,
12
+ ndcg_at_k,
13
+ post_filter,
14
+ pre_filter,
15
+ precision_at_k,
16
+ recall_at_k,
17
+ reciprocal_rank,
18
+ unusable_fraction_at_k,
19
+ )
20
+ from .retrieval import TfIdfIndex
21
+
22
+ __version__ = "0.1.0"
23
+
24
+ __all__ = [
25
+ "Authorized", "TfIdfIndex", "__version__", "authorized_recall_at_k", "ndcg_at_k",
26
+ "post_filter", "pre_filter", "precision_at_k", "recall_at_k",
27
+ "reciprocal_rank", "unusable_fraction_at_k",
28
+ ]
@@ -0,0 +1,4 @@
1
+ from .experiment import main
2
+
3
+ if __name__ == "__main__":
4
+ main()
@@ -0,0 +1,160 @@
1
+ """The discovery corpus. Deterministic, so the numbers are reproducible.
2
+
3
+ Forty datasets across eight domains, twenty-four queries, four authorization
4
+ profiles. Relevance is defined by construction -- a dataset is relevant to a
5
+ query if it belongs to the query's domain -- because a ground truth argued
6
+ after the fact is a ground truth fitted to the retriever.
7
+
8
+ `build()` returns the corpus in memory, so the experiment runs with no data
9
+ files present. `python -m authorized_recall.corpus` also writes
10
+ it to `evals/datasets/*.json`, which are committed as the record of what was
11
+ measured.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ from pathlib import Path
18
+
19
+ DEFAULT_OUT = Path("corpus")
20
+
21
+ DOMAINS = {
22
+ "purification": {
23
+ "vocabulary": "purification recovery yield elution buffer capture polish load",
24
+ "facets": ["batch records", "step yields", "buffer conditions", "load challenges", "elution pools"],
25
+ "sensitivity": "internal",
26
+ },
27
+ "chromatography": {
28
+ "vocabulary": "chromatography column peak resolution retention gradient pooling",
29
+ "facets": ["peak tables", "column performance", "gradient profiles", "pooling decisions", "resolution trends"],
30
+ "sensitivity": "internal",
31
+ },
32
+ "fermentation": {
33
+ "vocabulary": "fermentation bioreactor viability titer feed dissolved oxygen",
34
+ "facets": ["viability curves", "titer profiles", "feed schedules", "oxygen transfer", "harvest criteria"],
35
+ "sensitivity": "internal",
36
+ },
37
+ "analytics": {
38
+ "vocabulary": "assay analytical potency purity impurity release specification",
39
+ "facets": ["potency assays", "purity results", "impurity profiles", "release testing", "specification limits"],
40
+ "sensitivity": "confidential",
41
+ },
42
+ "clinical": {
43
+ "vocabulary": "clinical subject endpoint adverse dose cohort visit",
44
+ "facets": ["subject observations", "endpoint summaries", "adverse events", "dose cohorts", "visit schedules"],
45
+ "sensitivity": "restricted",
46
+ },
47
+ "supply": {
48
+ "vocabulary": "supply inventory lot shipment warehouse cold chain logistics",
49
+ "facets": ["lot inventory", "shipment tracking", "cold chain excursions", "warehouse stock", "logistics routes"],
50
+ "sensitivity": "internal",
51
+ },
52
+ "equipment": {
53
+ "vocabulary": "equipment calibration maintenance asset downtime utilisation sensor",
54
+ "facets": ["calibration records", "maintenance logs", "downtime events", "asset utilisation", "sensor streams"],
55
+ "sensitivity": "internal",
56
+ },
57
+ "quality": {
58
+ "vocabulary": "quality deviation capa audit complaint change control batch disposition",
59
+ "facets": ["deviations", "CAPA records", "audit findings", "complaints", "batch disposition"],
60
+ "sensitivity": "confidential",
61
+ },
62
+ }
63
+
64
+ CAPABILITIES = ["search", "aggregate", "compare", "summarize"]
65
+
66
+ # principal class -> domains it holds capabilities on
67
+ PROFILES = {
68
+ "process-engineer": ["purification", "chromatography", "fermentation", "equipment"],
69
+ "analyst": ["analytics", "chromatography", "quality"],
70
+ "clinical-reviewer": ["clinical", "analytics"],
71
+ "external-auditor": ["quality"],
72
+ }
73
+
74
+ CLEARANCE = {
75
+ "process-engineer": "confidential",
76
+ "analyst": "confidential",
77
+ "clinical-reviewer": "restricted",
78
+ "external-auditor": "internal",
79
+ }
80
+
81
+
82
+ def build() -> tuple[list[dict], list[dict], dict]:
83
+ datasets: list[dict] = []
84
+ for domain, spec in DOMAINS.items():
85
+ for index, facet in enumerate(spec["facets"], start=1):
86
+ datasets.append(
87
+ {
88
+ "dataset": f"{domain}-{facet.replace(' ', '-').lower()}",
89
+ "domain": domain,
90
+ "version": "2026.09.01",
91
+ "revision": f"rev-{domain}-{index:02d}",
92
+ "schema_version": "1",
93
+ "description": f"{facet.capitalize()} for {domain}: {spec['vocabulary']}.",
94
+ "schemas": [facet.replace(" ", "_")],
95
+ "capabilities": [
96
+ {
97
+ "name": name,
98
+ "effect": "read" if name in ("search", "compare") else "compute",
99
+ "sensitivity": spec["sensitivity"],
100
+ "description": f"{name} over {facet} in {domain}",
101
+ }
102
+ for name in CAPABILITIES
103
+ ],
104
+ "prohibited": ["delete_source", "bypass_governance"],
105
+ "policies": [f"POL-{domain.upper()[:4]}-001"],
106
+ "freshness": {"maximum_age_s": 86400},
107
+ "age_s": 3600,
108
+ "provenance": {"system": "volume", "source": "synthetic"},
109
+ }
110
+ )
111
+
112
+ queries: list[dict] = []
113
+ for domain, spec in DOMAINS.items():
114
+ for facet in spec["facets"][:3]:
115
+ queries.append(
116
+ {
117
+ "query": f"what do the {facet} tell us about {spec['vocabulary'].split()[1]}",
118
+ "domain": domain,
119
+ "relevant": [d["dataset"] for d in datasets if d["domain"] == domain],
120
+ }
121
+ )
122
+
123
+ profiles = {
124
+ name: {
125
+ "principal_class": name,
126
+ "clearance": CLEARANCE[name],
127
+ "grants": {
128
+ d["dataset"]: CAPABILITIES
129
+ for d in datasets
130
+ if d["domain"] in domains
131
+ },
132
+ }
133
+ for name, domains in PROFILES.items()
134
+ }
135
+ return datasets, queries, profiles
136
+
137
+
138
+ def main(out: Path | str | None = None) -> None:
139
+ import argparse
140
+
141
+ if out is None:
142
+ parser = argparse.ArgumentParser(prog="authorized_recall.corpus")
143
+ parser.add_argument("--out", default=str(DEFAULT_OUT),
144
+ help="directory to write corpus.json, queries.json "
145
+ "and profiles.json into")
146
+ out = parser.parse_args().out
147
+ out = Path(out)
148
+ out.mkdir(parents=True, exist_ok=True)
149
+ datasets, queries, profiles = build()
150
+ (out / "corpus.json").write_text(json.dumps({"datasets": datasets}, indent=2) + "\n")
151
+ (out / "queries.json").write_text(json.dumps({"queries": queries}, indent=2) + "\n")
152
+ (out / "profiles.json").write_text(json.dumps({"profiles": profiles}, indent=2) + "\n")
153
+ print(
154
+ f"{len(datasets)} datasets across {len(DOMAINS)} domains, "
155
+ f"{len(queries)} queries, {len(profiles)} authorization profiles"
156
+ )
157
+
158
+
159
+ if __name__ == "__main__":
160
+ main()
@@ -0,0 +1,205 @@
1
+ """The Authorized Recall@K measurement.
2
+
3
+ python -m authorized_recall
4
+
5
+ Runs on the in-memory corpus by default, so it needs no data files. `--json`
6
+ reads the committed `evals/datasets/*.json` instead; both produce the same
7
+ numbers, because they come from the same generator.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import json
14
+ import statistics
15
+ from pathlib import Path
16
+ from typing import Callable
17
+
18
+ from .corpus import CAPABILITIES, build
19
+ from .metric import (
20
+ authorized_recall_at_k,
21
+ ndcg_at_k,
22
+ post_filter,
23
+ pre_filter,
24
+ precision_at_k,
25
+ recall_at_k,
26
+ reciprocal_rank,
27
+ unusable_fraction_at_k,
28
+ )
29
+ from .retrieval import TfIdfIndex
30
+
31
+ KS = (1, 3, 5, 10)
32
+
33
+
34
+ def _load_from_json(data_dir: Path) -> tuple[list[dict], list[dict], dict]:
35
+ corpus = json.loads((data_dir / "corpus.json").read_text())["datasets"]
36
+ queries = json.loads((data_dir / "queries.json").read_text())["queries"]
37
+ profiles = json.loads((data_dir / "profiles.json").read_text())["profiles"]
38
+ return corpus, queries, profiles
39
+
40
+
41
+ def _document(dataset: dict) -> str:
42
+ """The text a dataset is indexed under.
43
+
44
+ Identical to `descriptor.DatasetDescriptor.text` in the reference
45
+ implementation. It has to be: this experiment and the one reachable through
46
+ the control plane are the same experiment, and two document constructions
47
+ would give two nDCG columns both claiming to be it.
48
+ """
49
+ parts = [dataset["dataset"].replace("-", " "), dataset.get("description", "")]
50
+ parts += [c["name"].replace("_", " ") for c in dataset.get("capabilities", ())]
51
+ parts += [c.get("description", "") for c in dataset.get("capabilities", ())]
52
+ parts += [s.replace("_", " ") for s in dataset.get("schemas", ())]
53
+ return " ".join(p for p in parts if p)
54
+
55
+
56
+ def _predicate(profile: dict) -> Callable[[str], bool]:
57
+ """A profile becomes a predicate. Nothing downstream knows what a principal is."""
58
+ granted = set(profile["grants"])
59
+ return lambda dataset_id: dataset_id in granted
60
+
61
+
62
+ def run(from_json: Path | str | None = None) -> dict:
63
+ """Measure. Builds the corpus in memory unless a data directory is given.
64
+
65
+ Deliberately no default path: this package ships no data and does not know
66
+ where a repository put any. `from_json` exists so a committed corpus can be
67
+ checked against the generator.
68
+ """
69
+ datasets, queries, profiles = (
70
+ _load_from_json(Path(from_json)) if from_json else build()
71
+ )
72
+ index = TfIdfIndex({d["dataset"]: _document(d) for d in datasets})
73
+ pool = len(datasets)
74
+
75
+ rows: dict[int, dict[str, list[float]]] = {
76
+ k: {key: [] for key in
77
+ ("recall", "arecall_post", "arecall_pre", "precision", "ndcg",
78
+ "unusable", "arecall_post_nz", "arecall_pre_nz")}
79
+ for k in KS
80
+ }
81
+ mrr: list[float] = []
82
+ unauthorized_relevant = total_relevant = 0
83
+
84
+ for query in queries:
85
+ relevant = query["relevant"]
86
+ ranking = index.rank(query["query"], k=pool)
87
+ mrr.append(reciprocal_rank(ranking, relevant))
88
+ for profile in profiles.values():
89
+ authorized = _predicate(profile)
90
+ authorized_relevant = [d for d in relevant if authorized(d)]
91
+ total_relevant += len(relevant)
92
+ unauthorized_relevant += len(relevant) - len(authorized_relevant)
93
+ for k in KS:
94
+ post = post_filter(ranking, authorized, k)
95
+ pre = pre_filter(ranking, authorized, k)
96
+ r = rows[k]
97
+ r["recall"].append(recall_at_k(ranking, relevant, k))
98
+ r["precision"].append(precision_at_k(ranking, relevant, k))
99
+ r["ndcg"].append(ndcg_at_k(ranking, relevant, k))
100
+ r["unusable"].append(unusable_fraction_at_k(ranking, authorized, k))
101
+ r["arecall_post"].append(
102
+ authorized_recall_at_k(post, relevant, authorized, k)
103
+ )
104
+ r["arecall_pre"].append(
105
+ authorized_recall_at_k(pre, relevant, authorized, k)
106
+ )
107
+ if authorized_relevant:
108
+ r["arecall_post_nz"].append(r["arecall_post"][-1])
109
+ r["arecall_pre_nz"].append(r["arecall_pre"][-1])
110
+
111
+ results = {}
112
+ for k in KS:
113
+ r = rows[k]
114
+ results[k] = {
115
+ "recall": statistics.mean(r["recall"]),
116
+ "arecall_post": statistics.mean(r["arecall_post"]),
117
+ "arecall_pre": statistics.mean(r["arecall_pre"]),
118
+ "precision": statistics.mean(r["precision"]),
119
+ "ndcg": statistics.mean(r["ndcg"]),
120
+ "unusable": statistics.mean(r["unusable"]),
121
+ "arecall_post_nonempty": statistics.mean(r["arecall_post_nz"]),
122
+ "arecall_pre_nonempty": statistics.mean(r["arecall_pre_nz"]),
123
+ "n_nonempty": len(r["arecall_pre_nz"]),
124
+ }
125
+ results[k]["gap"] = results[k]["arecall_pre"] - results[k]["arecall_post"]
126
+ results[k]["gap_nonempty"] = (
127
+ results[k]["arecall_pre_nonempty"] - results[k]["arecall_post_nonempty"]
128
+ )
129
+ return {
130
+ "datasets": len(datasets),
131
+ "queries": len(queries),
132
+ "profiles": len(profiles),
133
+ "pairs": len(queries) * len(profiles),
134
+ "unauthorized_relevant": unauthorized_relevant,
135
+ "total_relevant": total_relevant,
136
+ "mrr": statistics.mean(mrr),
137
+ "k": results,
138
+ }
139
+
140
+
141
+ def report(out: dict) -> str:
142
+ lines = [
143
+ f"corpus: {out['datasets']} datasets, {out['queries']} queries, "
144
+ f"{out['profiles']} authorization profiles ({out['pairs']} query-principal pairs)",
145
+ f"relevant-but-unauthorized pairs: {out['unauthorized_relevant']}/"
146
+ f"{out['total_relevant']} "
147
+ f"({out['unauthorized_relevant'] / out['total_relevant']:.1%})",
148
+ f"MRR (authorization-blind): {out['mrr']:.3f}",
149
+ "",
150
+ f"{'K':>3} {'Recall':>7} {'ARecall':>8} {'ARecall':>8} {'gap':>6} "
151
+ f"{'P@K':>6} {'nDCG':>6} {'unusable':>8}",
152
+ f"{'':>3} {'':>7} {'post':>8} {'pre':>8} {'':>6} {'':>6} {'':>6} {'in top-K':>8}",
153
+ ]
154
+ for k in KS:
155
+ v = out["k"][k]
156
+ lines.append(
157
+ f"{k:>3} {v['recall']:>7.3f} {v['arecall_post']:>8.3f} "
158
+ f"{v['arecall_pre']:>8.3f} {v['gap']:>+6.3f} "
159
+ f"{v['precision']:>6.3f} {v['ndcg']:>6.3f} {v['unusable']:>8.1%}"
160
+ )
161
+ n = out["k"][KS[0]]["n_nonempty"]
162
+ lines += [
163
+ "",
164
+ f"excluding query-principal pairs where nothing relevant is authorized "
165
+ f"(n={n} of {out['pairs']}):",
166
+ f"{'K':>3} {'ARecall post':>12} {'ARecall pre':>12} {'gap':>7}",
167
+ ]
168
+ for k in KS:
169
+ v = out["k"][k]
170
+ lines.append(
171
+ f"{k:>3} {v['arecall_post_nonempty']:>12.3f} "
172
+ f"{v['arecall_pre_nonempty']:>12.3f} {v['gap_nonempty']:>+7.3f}"
173
+ )
174
+ five = out["k"][5]
175
+ lines += [
176
+ "",
177
+ "At K=5, moving the authorization filter ahead of truncation changes",
178
+ f"Authorized Recall@5 from {five['arecall_post_nonempty']:.3f} to "
179
+ f"{five['arecall_pre_nonempty']:.3f} ({five['gap_nonempty']:+.3f}) on the "
180
+ f"{five['n_nonempty']} pairs where anything",
181
+ f"relevant is authorized at all, while plain Recall@5 stays at "
182
+ f"{five['recall']:.3f} and cannot",
183
+ "see the difference. The gap's sign is guaranteed by the ordering argument in",
184
+ "this package's README; its size is what the corpus determines.",
185
+ ]
186
+ return "\n".join(lines)
187
+
188
+
189
+ def main() -> None:
190
+ parser = argparse.ArgumentParser(prog="authorized-recall")
191
+ parser.add_argument("--json", metavar="DIR", default=None,
192
+ help="read corpus.json, queries.json and profiles.json "
193
+ "from DIR instead of building the corpus in memory")
194
+ parser.add_argument("--emit", metavar="PATH",
195
+ help="write the result dictionary as JSON")
196
+ args = parser.parse_args()
197
+ out = run(from_json=args.json)
198
+ print(report(out))
199
+ if args.emit:
200
+ Path(args.emit).write_text(
201
+ json.dumps({"k": {str(k): v for k, v in out["k"].items()},
202
+ **{x: out[x] for x in
203
+ ("datasets", "queries", "profiles", "pairs", "mrr")}},
204
+ indent=2) + "\n"
205
+ )
@@ -0,0 +1,129 @@
1
+ """Authorized Recall@K, defined over a predicate rather than over a control plane.
2
+
3
+ The metric takes `authorized: Callable[[str], bool]`, not a `Principal`, and
4
+ nothing else in this package imports the reference implementation. That is
5
+ deliberate: the quantity is a property of policy-conditioned retrieval, not of
6
+ this architecture, and a system with RBAC, ABAC, row-level security or a
7
+ multi-tenant vector store can use it without adopting anything here.
8
+
9
+ See README.md in this directory for the mathematical definition and for the
10
+ proof that the pre/post-filter gap is non-negative.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from typing import Callable, Iterable, Sequence
17
+
18
+ __all__ = [
19
+ "Authorized",
20
+ "recall_at_k",
21
+ "authorized_recall_at_k",
22
+ "precision_at_k",
23
+ "reciprocal_rank",
24
+ "ndcg_at_k",
25
+ "unusable_fraction_at_k",
26
+ "post_filter",
27
+ "pre_filter",
28
+ ]
29
+
30
+ Authorized = Callable[[str], bool]
31
+
32
+
33
+ def recall_at_k(retrieved: Sequence[str], relevant: Iterable[str], k: int) -> float:
34
+ """|R ∩ L_K| / |R|. Authorization-blind, and 1.0 on an empty relevant set."""
35
+ rel = set(relevant)
36
+ if not rel:
37
+ return 1.0
38
+ return len(rel & set(retrieved[:k])) / len(rel)
39
+
40
+
41
+ def authorized_recall_at_k(
42
+ retrieved: Sequence[str],
43
+ relevant: Iterable[str],
44
+ authorized: Authorized,
45
+ k: int,
46
+ ) -> float:
47
+ """|R_A ∩ L_K| / |R_A|, where R_A = { d ∈ R : authorized(d) }.
48
+
49
+ Recall over the subset the caller may actually use. Plain Recall@K counts a
50
+ retrieved item the caller cannot touch as a success; it is not one, and it
51
+ has spent one of the K slots.
52
+
53
+ Two conventions, decided rather than left to fall out of the arithmetic:
54
+
55
+ * **R_A empty → 1.0.** The system cannot be faulted for failing to surface
56
+ what it must not surface. This inflates the mean over a population
57
+ containing such pairs, so report the restricted mean alongside it.
58
+ * **Retrieved-but-unauthorized items are neither credited nor penalised
59
+ here.** They are a separate quantity, `unusable_fraction_at_k`.
60
+
61
+ When `authorized` is identically true this equals `recall_at_k`.
62
+ """
63
+ rel = set(relevant)
64
+ authorized_relevant = {d for d in rel if authorized(d)}
65
+ if not authorized_relevant:
66
+ return 1.0
67
+ return len(authorized_relevant & set(retrieved[:k])) / len(authorized_relevant)
68
+
69
+
70
+ def unusable_fraction_at_k(
71
+ retrieved: Sequence[str], authorized: Authorized, k: int
72
+ ) -> float:
73
+ """Fraction of the K returned slots the caller cannot act on.
74
+
75
+ Reported separately from ARecall because it answers a different question:
76
+ not "did we find what they can use" but "how much of the answer was noise
77
+ to them".
78
+ """
79
+ if k == 0:
80
+ return 0.0
81
+ window = retrieved[:k]
82
+ return sum(1 for d in window if not authorized(d)) / k
83
+
84
+
85
+ def precision_at_k(retrieved: Sequence[str], relevant: Iterable[str], k: int) -> float:
86
+ rel = set(relevant)
87
+ return len(rel & set(retrieved[:k])) / k if k else 0.0
88
+
89
+
90
+ def reciprocal_rank(retrieved: Sequence[str], relevant: Iterable[str]) -> float:
91
+ rel = set(relevant)
92
+ for i, item in enumerate(retrieved, start=1):
93
+ if item in rel:
94
+ return 1.0 / i
95
+ return 0.0
96
+
97
+
98
+ def ndcg_at_k(retrieved: Sequence[str], relevant: Iterable[str], k: int) -> float:
99
+ rel = set(relevant)
100
+ dcg = sum(
101
+ 1.0 / math.log2(i + 1)
102
+ for i, item in enumerate(retrieved[:k], start=1)
103
+ if item in rel
104
+ )
105
+ ideal = sum(1.0 / math.log2(i + 1) for i in range(1, min(len(rel), k) + 1))
106
+ return dcg / ideal if ideal else 0.0
107
+
108
+
109
+ # -- where the filter sits ------------------------------------------------
110
+ #
111
+ # The two arrangements the experiment compares. They differ only in whether
112
+ # truncation happens before or after the authorization filter, and that
113
+ # difference is the whole finding.
114
+
115
+ def post_filter(ranking: Sequence[str], authorized: Authorized, k: int) -> list[str]:
116
+ """Truncate, then filter. The naive arrangement: unusable items occupy slots."""
117
+ return [d for d in ranking[:k] if authorized(d)]
118
+
119
+
120
+ def pre_filter(ranking: Sequence[str], authorized: Authorized, k: int) -> list[str]:
121
+ """Filter, then truncate. K slots of usable answers.
122
+
123
+ `pre_filter` returns a superset of `post_filter` for every ranking, k and
124
+ predicate, because filtering preserves relative order: the authorized items
125
+ within the first K of the ranking are among the first K authorized items of
126
+ the ranking. That is why the measured gap is non-negative by construction
127
+ and not an artefact of the corpus.
128
+ """
129
+ return [d for d in ranking if authorized(d)][:k]
@@ -0,0 +1,43 @@
1
+ """A TF-IDF index, so the package measures something without pulling in a retriever.
2
+
3
+ Deliberately plain. The metric is a property of where the authorization filter
4
+ sits, and a stronger retriever moves every column together -- so the retriever
5
+ here only has to be reproducible, which an embedding model would not be.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import math
11
+ import re
12
+ from collections import Counter
13
+ from typing import Mapping
14
+
15
+ __all__ = ["TfIdfIndex"]
16
+
17
+ _TOKEN = re.compile(r"[a-z0-9]+")
18
+
19
+
20
+ class TfIdfIndex:
21
+ def __init__(self, documents: Mapping[str, str]) -> None:
22
+ self._docs = {k: Counter(_TOKEN.findall(v.lower())) for k, v in documents.items()}
23
+ n = len(self._docs) or 1
24
+ df: Counter = Counter()
25
+ for counts in self._docs.values():
26
+ df.update(counts.keys())
27
+ self._idf = {t: math.log((n + 1) / (c + 1)) + 1.0 for t, c in df.items()}
28
+
29
+ def _vector(self, counts: Mapping[str, int]) -> dict[str, float]:
30
+ vec = {t: (1 + math.log(c)) * self._idf.get(t, 1.0) for t, c in counts.items()}
31
+ norm = math.sqrt(sum(v * v for v in vec.values())) or 1.0
32
+ return {t: v / norm for t, v in vec.items()}
33
+
34
+ def rank(self, query: str, k: int) -> list[str]:
35
+ q = self._vector(Counter(_TOKEN.findall(query.lower())))
36
+ scored = []
37
+ for doc_id, counts in self._docs.items():
38
+ d = self._vector(counts)
39
+ score = sum(w * d.get(t, 0.0) for t, w in q.items())
40
+ if score > 0:
41
+ scored.append((doc_id, score))
42
+ scored.sort(key=lambda pair: (-pair[1], pair[0]))
43
+ return [doc_id for doc_id, _ in scored[:k]]
@@ -0,0 +1,147 @@
1
+ Metadata-Version: 2.4
2
+ Name: authorized-recall
3
+ Version: 0.1.0
4
+ Summary: Authorized Recall@K — retrieval quality measured over the subset a principal is permitted to use
5
+ Author: Alexander Chernov
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/agentic-datasets/reference
8
+ Project-URL: Documentation, https://agenticdatasets.org/reference/
9
+ Project-URL: Source, https://github.com/agentic-datasets/reference/tree/main/packages/authorized-recall
10
+ Keywords: information retrieval,evaluation metric,authorization,access control,multi-tenant,RAG,ABAC,RBAC
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
13
+ Classifier: Intended Audience :: Science/Research
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # Authorized Recall@K
22
+
23
+ **Retrieval quality measured over the subset a principal may actually use.**
24
+
25
+ This package has no dependency on the rest of the repository. The metric takes
26
+ a predicate, not a `Principal`, so a system using RBAC, ABAC, row-level
27
+ security or per-tenant vector namespaces can adopt the measurement without
28
+ adopting anything else here.
29
+
30
+ ```bash
31
+ pip install authorized-recall
32
+ python -m authorized_recall # or: authorized-recall
33
+ ```
34
+
35
+ ---
36
+
37
+ ## Why
38
+
39
+ A retrieval system that surfaces a dataset the caller is not permitted to use
40
+ has not helped them. They cannot act on it; the only thing that changed is that
41
+ they now know it exists. Standard Recall@K scores that as a success, and it has
42
+ also spent one of the K slots doing it.
43
+
44
+ In the corpus measured here, **68.8% of what retrieval returns is unusable to
45
+ the principal who asked**, and Recall@K cannot see it.
46
+
47
+ ## Definition
48
+
49
+ Let
50
+
51
+ - $D$ — the corpus,
52
+ - $q$ — a query, with relevant set $R(q) \subseteq D$,
53
+ - $p$ — a principal, with authorization predicate $A_p : D \to \{0,1\}$,
54
+ - $L_K(q,p)$ — the ordered list of at most $K$ items the system returns.
55
+
56
+ The **authorized relevant set** is
57
+
58
+ $$R_A(q,p) = \{\, d \in R(q) : A_p(d) = 1 \,\}$$
59
+
60
+ and
61
+
62
+ $$\mathrm{ARecall}@K(q,p) = \frac{|R_A(q,p) \cap L_K(q,p)|}{|R_A(q,p)|},
63
+ \qquad \mathrm{ARecall}@K \triangleq 1 \ \text{ when } R_A = \emptyset .$$
64
+
65
+ Compare
66
+
67
+ $$\mathrm{Recall}@K(q) = \frac{|R(q) \cap L_K|}{|R(q)|} .$$
68
+
69
+ **When $A_p \equiv 1$, $\mathrm{ARecall}@K = \mathrm{Recall}@K$.** The metric is
70
+ a strict generalisation, not a different measurement.
71
+
72
+ ### Two conventions, stated because they change the mean
73
+
74
+ 1. $R_A = \emptyset \Rightarrow \mathrm{ARecall}@K = 1$. The system cannot be
75
+ faulted for failing to surface what it must not surface. Over a population
76
+ containing such pairs this inflates the mean, so report the restricted mean
77
+ — over pairs with $R_A \neq \emptyset$ — alongside it. The experiment here
78
+ prints both.
79
+ 2. Retrieved-but-unauthorized items are neither credited nor penalised inside
80
+ ARecall. They are a separate quantity:
81
+
82
+ $$U@K(q,p) = \frac{|\{\, d \in L_K : A_p(d) = 0 \,\}|}{K}$$
83
+
84
+ ## Where the filter sits
85
+
86
+ ARecall is computed over the list the system **returns**, so it is sensitive to
87
+ whether truncation happens before or after the authorization filter:
88
+
89
+ $$L_K^{\text{post}} = \sigma_{A_p}\big(\mathrm{top}_K(\mathrm{rank}(D))\big)
90
+ \qquad
91
+ L_K^{\text{pre}} = \mathrm{top}_K\big(\sigma_{A_p}(\mathrm{rank}(D))\big)$$
92
+
93
+ **Claim.** $L_K^{\text{post}} \subseteq L_K^{\text{pre}}$ for every ranking,
94
+ $K$ and $A_p$, hence
95
+
96
+ $$\Delta@K = \mathrm{ARecall}^{\text{pre}}@K - \mathrm{ARecall}^{\text{post}}@K \;\geq\; 0 .$$
97
+
98
+ *Proof.* Filtering preserves relative order. An item in $L_K^{\text{post}}$ is
99
+ authorized and appears within the first $K$ positions of the ranking, so at
100
+ most $K-1$ items precede it, so at most $K-1$ *authorized* items precede it,
101
+ so it appears within the first $K$ authorized items — which is
102
+ $L_K^{\text{pre}}$. ∎
103
+
104
+ The gap is therefore non-negative by construction rather than by luck of the
105
+ corpus. What the corpus determines is its *size*.
106
+
107
+ ## Measured
108
+
109
+ 40 synthetic datasets over 8 domains, 24 queries, 4 authorization profiles,
110
+ 96 query-principal pairs. Relevance by construction: a dataset is relevant to a
111
+ query when it is in the query's domain. Retrieval is TF-IDF cosine.
112
+
113
+ ```
114
+ K Recall ARecall ARecall gap unusable
115
+ post pre in top-K
116
+ 1 0.200 0.750 0.750 +0.000 68.8%
117
+ 3 0.483 0.835 0.863 +0.027 68.8%
118
+ 5 0.867 0.954 0.988 +0.033 68.5%
119
+ 10 1.000 1.000 1.000 +0.000 39.1%
120
+ ```
121
+
122
+ Restricted to the 30 pairs with $R_A \neq \emptyset$:
123
+
124
+ ```
125
+ K ARecall post ARecall pre gap
126
+ 1 0.200 0.200 +0.000
127
+ 3 0.473 0.560 +0.087
128
+ 5 0.853 0.960 +0.107
129
+ 10 1.000 1.000 +0.000
130
+ ```
131
+
132
+ **At K=5, moving the filter ahead of truncation takes ARecall@5 from 0.853 to
133
+ 0.960 (+0.107). Recall@5 stays at 0.867 and cannot see the difference.**
134
+
135
+ ## What this does and does not establish
136
+
137
+ The absolute values belong to this corpus: relevance is by construction, the
138
+ retriever is TF-IDF, and MRR is 1.000, so the retrieval task is easy. A harder
139
+ corpus or a better retriever moves all three columns.
140
+
141
+ The *gap* is what the metric was defined to isolate, and the claim above is
142
+ that it is a property of filter placement rather than of retrieval quality. The
143
+ proof makes its sign certain; the experiment gives its size in one setting.
144
+
145
+ Applying it to a real corpus with real authorization data is the obvious next
146
+ measurement, and this package is separable precisely so that someone else can
147
+ do it.
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/authorized_recall/__init__.py
5
+ src/authorized_recall/__main__.py
6
+ src/authorized_recall/corpus.py
7
+ src/authorized_recall/experiment.py
8
+ src/authorized_recall/metric.py
9
+ src/authorized_recall/retrieval.py
10
+ src/authorized_recall.egg-info/PKG-INFO
11
+ src/authorized_recall.egg-info/SOURCES.txt
12
+ src/authorized_recall.egg-info/dependency_links.txt
13
+ src/authorized_recall.egg-info/entry_points.txt
14
+ src/authorized_recall.egg-info/requires.txt
15
+ src/authorized_recall.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ authorized-recall = authorized_recall.experiment:main
@@ -0,0 +1 @@
1
+ authorized_recall