File size: 148,697 Bytes
ebcde1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
"""Atomic producer and verifier for the frozen four-session M8 L2 study.

The development lock is verified before either held-out payload can be opened.
Every session coordinate and both of its control-file digests are supplied by
the caller; this module never discovers a ``latest`` directory.  Publication is
terminal-marker based and never overwrites an existing run.
"""

from __future__ import annotations

import ctypes
import errno
import hashlib
import json
import math
import os
import shutil
import stat
import sys
import tempfile
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from pathlib import Path, PurePosixPath
from typing import Any, Literal, cast

import polars as pl
import pyarrow.parquet as pq  # type: ignore[import-untyped]

from microstructure.m8_l2_analysis_config import (
    M8L2AnalysisConfig,
    load_m8_l2_analysis_config,
)
from microstructure.m8_l2_capture import (
    M8L2SessionBundle,
    current_m8_l2_runtime_fingerprint_sha256,
    verify_m8_l2_session_bundle,
)
from microstructure.m8_l2_config import (
    M8_L2_PROTOCOL_SHA256,
    M8L2StudyConfig,
    load_m8_l2_config,
)
from microstructure.m8_l2_development import (
    L2DevelopmentLockResult,
    verify_m8_l2_development_lock,
)
from microstructure.m8_l2_inputs import (
    L2CampaignRuntimeIdentity,
    L2SessionFileAuthority,
    VerifiedL2SessionInput,
    verify_m8_l2_development_input,
    verify_m8_l2_heldout_input,
)
from microstructure.provenance import (
    ImportOriginError,
    assert_project_module_origins,
    git_source_tree_sha256,
    runtime_metadata,
    sha256_file,
    strict_git_state,
    utc_now_iso,
)
from microstructure.reporting.l2 import (
    L2ReportData,
    canonical_report_data_sha256,
    render_l2_executive_memo,
    render_l2_model_comparison,
    render_l2_technical_report,
)
from microstructure.research.analysis import RegimeThresholds
from microstructure.research.l2_analysis import (
    L2DescriptiveAnalysis,
    build_l2_descriptive_analysis,
)
from microstructure.research.l2_evaluation import (
    L2EvaluationResult,
    L2ExecutionReference,
    L2HeldoutEndpointFrame,
    LockedL2EndpointState,
    evaluate_locked_l2_endpoints,
    run_locked_l2_market_execution,
)
from microstructure.research.l2_multidate import (
    L2EndpointSpec,
    L2RegimeFit,
    apply_l2_regimes,
    build_l2_endpoint_frames,
    l2_model_feature_columns,
    validate_l2_endpoint_frame,
)
from microstructure.research.multidate import FinalFittedState

M8L2StudyRunStatus = Literal["COMPLETE", "INSUFFICIENT_DATA"]

_SCHEMA_VERSION = "m8-l2-study-run-v2"
_REPORT_INPUT_SCHEMA_VERSION = "m8-l2-report-inputs-v1"
_CHECKSUMS_NAME = "CHECKSUMS.sha256"
_SUCCESS_NAME = "_SUCCESS"
_INSUFFICIENT_NAME = "INSUFFICIENT_DATA"
_SUCCESS_BYTES = b"complete\n"
_INSUFFICIENT_BYTES = b"terminal\n"
_EXPECTED_COORDINATES = (
    ("2026-08-10", "train"),
    ("2026-08-11", "validation"),
    ("2026-08-12", "primary_test"),
    ("2026-08-13", "replication_test"),
)
_GIB = 1024**3
# Fail-closed producer/verifier workspace partition for a 16 GiB host.  The
# categories deliberately sum below the host ceiling even at their limits:
# causal 4 + current raw 2 + evaluation 2 + descriptive 2 + execution 2 =
# 12 GiB, leaving 4 GiB for Python/Polars/runtime and publication overhead.
_MAX_FINAL_RAW_BYTES = 2 * _GIB
_MAX_FINAL_CAUSAL_BYTES = 4 * _GIB
_MAX_CAUSAL_COORDINATE_BYTES = 2 * _GIB
_MAX_EVALUATION_WORKSPACE_BYTES = 2 * _GIB
_MAX_DESCRIPTIVE_WORKSPACE_BYTES = 2 * _GIB
_MAX_EXECUTION_WORKSPACE_BYTES = 2 * _GIB
_CAUSAL_ENDPOINT_ROW_UPPER_BYTES = 4 * 1024
_PREDICTION_ROW_UPPER_BYTES = 1536
_PYTHON_CELL_UPPER_BYTES = 192
_PYTHON_ROW_BASE_UPPER_BYTES = 512
_PYTHON_LEDGER_ROW_UPPER_BYTES = 2048
_POLARS_LEDGER_ROW_UPPER_BYTES = 1024

_L2_VALIDATION_COLUMNS = (
    "study_date",
    "study_role",
    "endpoint_name",
    "endpoint_domain",
    "symbol",
    "continuity_id",
    "observed_interval_id",
    "observed_interval_start_ns",
    "observed_interval_end_ns_exclusive",
    "decision_ts_ns",
    "decision_sequence",
    "feature_cutoff_ts_ns",
    "max_feature_source_ts_ns",
    "max_feature_source_sequence",
    "feature_continuity_id",
    "label_start_ts_ns",
    "label_start_sequence",
    "right_censored",
    "future_mid_return",
    "future_mid_up",
    "label_information_end_ts_ns",
    "label_information_end_sequence",
    "label_continuity_id",
    "ofi_signed_future_mid_markout_bps",
    "sample_id",
)
_DESCRIPTIVE_COLUMNS = (
    "endpoint_horizon_value",
    "endpoint_horizon_unit",
    "spread_bps",
    "depth_total_l1",
    "depth_total_l5",
    "depth_total_l10",
    "queue_imbalance_l1",
    "realized_volatility_w100",
    "bid_quantity",
    "ask_quantity",
    "signed_markout_side_source",
    "liquidity_regime",
    "volatility_regime",
)
_EXECUTION_EVENT_COLUMNS = (
    *_L2_VALIDATION_COLUMNS,
    "best_bid",
    "best_ask",
    "bid_quantity",
    "ask_quantity",
    "mid_price",
    "tick_size",
    "lot_size",
)
_EXECUTION_PREDICTION_COLUMNS = (
    "sample_id",
    "symbol",
    "study_date",
    "study_role",
    "endpoint_name",
    "decision_sequence",
    "selected_probability",
    "is_oos",
    "split",
    "child_lock_sha256",
    "aggregate_lock_sha256",
    "endpoint_impact_ofi_window",
)


class M8L2StudyPipelineError(RuntimeError):
    """Raised when final-study production or verification must fail closed."""


class M8L2StudyRunVerificationError(M8L2StudyPipelineError):
    """Raised when a terminal M8 L2 run differs from its authorities."""


def _frame_bytes(frame: pl.DataFrame) -> int:
    return int(frame.estimated_size("b"))


def _frames_bytes(frames: Sequence[pl.DataFrame]) -> int:
    return sum(_frame_bytes(frame) for frame in frames)


def _require_memory_budget(observed: int, maximum: int, label: str) -> None:
    if observed < 0 or observed > maximum:
        raise M8L2StudyPipelineError(
            f"{label} exceeds the fail-closed memory budget ({observed} > {maximum} bytes)"
        )


def _require_verification_memory_budget(observed: int, maximum: int, label: str) -> None:
    if observed < 0 or observed > maximum:
        raise M8L2StudyRunVerificationError(
            f"{label} exceeds the bounded verifier memory budget ({observed} > {maximum} bytes)"
        )


def _parquet_metadata_bytes(root: Path, artifact: object, label: str) -> tuple[int, int]:
    """Inspect Parquet row-group sizes without opening column payloads."""

    relative = getattr(artifact, "relative_path", None)
    claimed_rows = getattr(artifact, "rows", None)
    if not isinstance(relative, str) or not isinstance(claimed_rows, int):
        raise M8L2StudyPipelineError(f"{label} lacks bounded Parquet metadata authority")
    safe = _safe_relative(relative)
    path = root / safe
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
    try:
        descriptor = os.open(path, flags)
        before = os.fstat(descriptor)
        if not stat.S_ISREG(before.st_mode):
            raise M8L2StudyPipelineError(f"{label} is not a regular Parquet file")
        with os.fdopen(descriptor, "rb", closefd=True) as handle:
            parquet = pq.ParquetFile(handle)
            metadata = parquet.metadata
            rows = int(metadata.num_rows)
            uncompressed = sum(
                int(metadata.row_group(index).total_byte_size)
                for index in range(metadata.num_row_groups)
            )
            after = os.fstat(handle.fileno())
        if (before.st_dev, before.st_ino, before.st_size, before.st_mtime_ns) != (
            after.st_dev,
            after.st_ino,
            after.st_size,
            after.st_mtime_ns,
        ):
            raise M8L2StudyPipelineError(f"{label} changed during memory admission")
    except M8L2StudyPipelineError:
        raise
    except (OSError, ValueError, TypeError) as error:
        raise M8L2StudyPipelineError(f"cannot inspect {label} memory metadata") from error
    if rows != claimed_rows or rows < 1 or uncompressed < 1:
        raise M8L2StudyPipelineError(f"{label} Parquet metadata differs from its authority")
    return uncompressed, rows


def _preflight_symbol_raw(value: VerifiedL2SessionInput, symbol: str) -> tuple[int, int] | None:
    """Return (uncompressed raw bytes, book rows) before payload materialization.

    Verified production inputs always expose artifact descriptors.  Injected
    test loaders may omit them and are then guarded by the immediate post-load
    check in ``_build_one_symbol_frames``.
    """

    descriptor = value.symbols.get(symbol)
    books = getattr(descriptor, "book_observations", None)
    deltas = getattr(descriptor, "depth_deltas", None)
    if books is None or deltas is None:
        return None
    book_bytes, book_rows = _parquet_metadata_bytes(
        value.root, books, f"{value.session_date} {symbol} book observations"
    )
    delta_bytes, _ = _parquet_metadata_bytes(
        value.root, deltas, f"{value.session_date} {symbol} depth deltas"
    )
    return book_bytes + delta_bytes, book_rows


def _loaded_bytes(value: Any) -> int:
    books = cast(pl.DataFrame, value.book_observations)
    deltas = cast(pl.DataFrame, value.depth_deltas)
    intervals = cast(Sequence[object], value.intervals)
    return _frame_bytes(books) + _frame_bytes(deltas) + len(intervals) * 1024


def _projected_frame_bytes(frame: pl.DataFrame, columns: Sequence[str], label: str) -> int:
    selected = tuple(dict.fromkeys(columns))
    missing = sorted(set(selected).difference(frame.columns))
    if missing:
        raise M8L2StudyPipelineError(f"{label} projection lacks required columns: {missing}")
    return sum(int(frame.get_column(name).estimated_size("b")) for name in selected)


def _project_frame(frame: pl.DataFrame, columns: Sequence[str], label: str) -> pl.DataFrame:
    _projected_frame_bytes(frame, columns, label)
    return frame.select(*tuple(dict.fromkeys(columns)))


def _evaluation_workspace_upper_bytes(
    heldout: Sequence[L2HeldoutEndpointFrame], *, feature_count: int
) -> int:
    if feature_count < 1:
        raise M8L2StudyPipelineError("evaluation memory admission requires model features")
    rows = sum(item.frame.height for item in heldout)
    full_width_sort_and_filter = 2 * _frames_bytes([item.frame for item in heldout])
    child_and_concat = 2 * rows * _PREDICTION_ROW_UPPER_BYTES
    numpy_scratch = rows * (feature_count * 8 + 8 * 8)
    return full_width_sort_and_filter + child_and_concat + numpy_scratch


def _descriptive_projection_columns(feature_columns: Sequence[str]) -> tuple[str, ...]:
    return tuple(dict.fromkeys((*_L2_VALIDATION_COLUMNS, *_DESCRIPTIVE_COLUMNS, *feature_columns)))


def _descriptive_workspace_upper_bytes(
    causal: Sequence[pl.DataFrame], *, columns: Sequence[str]
) -> int:
    projected = sum(
        _projected_frame_bytes(frame, columns, "descriptive endpoint") for frame in causal
    )
    rows = sum(frame.height for frame in causal)
    # Projected inputs, combined concat, largest grouped/sorted temporary and
    # retained outputs are charged as four full projected equivalents.
    return 4 * projected + rows * 512


def _python_projected_rows_upper_bytes(frame: pl.DataFrame, columns: Sequence[str]) -> int:
    payload = _projected_frame_bytes(frame, columns, "Python-row input")
    return payload + frame.height * (
        _PYTHON_ROW_BASE_UPPER_BYTES + len(tuple(dict.fromkeys(columns))) * _PYTHON_CELL_UPPER_BYTES
    )


def _execution_workspace_upper_bytes(
    event_frame: pl.DataFrame,
    predictions: pl.DataFrame,
) -> int:
    signal_rows = predictions.filter(
        (pl.col("selected_probability") >= 0.55) | (pl.col("selected_probability") <= 0.45)
    ).height
    # One possible forced liquidation row is included in every scenario.
    ledger_rows_per_scenario = signal_rows + 1
    scenario_count = 9
    projected_inputs = _projected_frame_bytes(
        event_frame, _EXECUTION_EVENT_COLUMNS, "execution event"
    ) + _projected_frame_bytes(predictions, _EXECUTION_PREDICTION_COLUMNS, "execution prediction")
    python_inputs = _python_projected_rows_upper_bytes(
        event_frame, _EXECUTION_EVENT_COLUMNS
    ) + _python_projected_rows_upper_bytes(predictions, _EXECUTION_PREDICTION_COLUMNS)
    # simulate_predictions holds order/fill/position dictionaries and an
    # event-aligned equity ledger for only the current scenario.
    current_python_ledgers = (
        4 * ledger_rows_per_scenario + event_frame.height
    ) * _PYTHON_LEDGER_ROW_UPPER_BYTES
    # run_locked_l2_market_execution retains the three Polars ledgers from all
    # nine completed scenarios until its final coordinate concat.
    retained_polars_ledgers = (
        3 * ledger_rows_per_scenario * scenario_count * _POLARS_LEDGER_ROW_UPPER_BYTES
    )
    # Caller projection plus the execution layer's ordered event/prediction
    # projections can coexist; charge three complete projected input sets.
    return 3 * projected_inputs + python_inputs + current_python_ledgers + retained_polars_ledgers


def _assert_final_producer_import_origins(project_root: Path) -> None:
    try:
        assert_project_module_origins(
            project_root,
            "microstructure.m8_l2_pipeline",
            "microstructure.m8_l2_development",
            "microstructure.m8_l2_inputs",
            "microstructure.research.l2_analysis",
            "microstructure.research.l2_evaluation",
            "microstructure.research.l2_multidate",
            "microstructure.research.multidate",
            "microstructure.reporting.l2",
        )
    except ImportOriginError as error:
        raise M8L2StudyPipelineError(
            "final-study producer has a foreign or mixed import origin"
        ) from error


@dataclass(frozen=True, slots=True)
class L2StudySessionAuthority:
    """An explicit session path plus independent control-file digests."""

    bundle_path: Path
    manifest_sha256: str
    checksums_sha256: str

    def __post_init__(self) -> None:
        object.__setattr__(self, "bundle_path", Path(self.bundle_path).absolute())
        _require_sha256(self.manifest_sha256, "session manifest authority")
        _require_sha256(self.checksums_sha256, "session checksums authority")

    @property
    def file_authority(self) -> L2SessionFileAuthority:
        return L2SessionFileAuthority(self.manifest_sha256, self.checksums_sha256)

    def to_dict(self) -> dict[str, object]:
        return {
            "bundle_path": str(self.bundle_path),
            "manifest_sha256": self.manifest_sha256,
            "checksums_sha256": self.checksums_sha256,
        }


@dataclass(frozen=True, slots=True)
class M8L2StudyRunResult:
    """One verified terminal final-study bundle."""

    root: Path
    status: M8L2StudyRunStatus
    manifest_path: Path
    manifest_sha256: str
    checksum_path: Path
    checksum_sha256: str
    marker_path: Path
    reason_codes: tuple[str, ...]

    @property
    def technical_report_path(self) -> Path:
        return self.root / "reports" / "technical_report.md"

    @property
    def executive_memo_path(self) -> Path:
        return self.root / "reports" / "executive_memo.md"

    @property
    def model_comparison_path(self) -> Path:
        return self.root / "reports" / "model_comparison.md"


def reproduce_m8_l2_study(
    capture_config: M8L2StudyConfig,
    analysis_config: M8L2AnalysisConfig,
    train_session: L2StudySessionAuthority,
    validation_session: L2StudySessionAuthority,
    development_lock_dir: str | Path,
    expected_development_lock_sha256: str,
    primary_session: L2StudySessionAuthority,
    replication_session: L2StudySessionAuthority,
    run_dir: str | Path,
    *,
    expected_existing_manifest_sha256: str | None = None,
    expected_existing_checksums_sha256: str | None = None,
) -> M8L2StudyRunResult:
    """Produce a run, or reuse one only under caller-held output authority."""

    return _reproduce_m8_l2_study(
        capture_config,
        analysis_config,
        train_session,
        validation_session,
        development_lock_dir,
        expected_development_lock_sha256,
        primary_session,
        replication_session,
        run_dir,
        expected_existing_manifest_sha256=expected_existing_manifest_sha256,
        expected_existing_checksums_sha256=expected_existing_checksums_sha256,
    )


def verify_m8_l2_study_run(
    capture_config: M8L2StudyConfig,
    analysis_config: M8L2AnalysisConfig,
    train_session: L2StudySessionAuthority,
    validation_session: L2StudySessionAuthority,
    development_lock_dir: str | Path,
    expected_development_lock_sha256: str,
    primary_session: L2StudySessionAuthority,
    replication_session: L2StudySessionAuthority,
    run_dir: str | Path,
    *,
    expected_manifest_sha256: str | None = None,
    expected_checksums_sha256: str | None = None,
) -> M8L2StudyRunResult:
    """Recursively verify a terminal run and every external authority."""

    return _verify_m8_l2_study_run(
        capture_config,
        analysis_config,
        train_session,
        validation_session,
        development_lock_dir,
        expected_development_lock_sha256,
        primary_session,
        replication_session,
        run_dir,
        expected_manifest_sha256=expected_manifest_sha256,
        expected_checksums_sha256=expected_checksums_sha256,
    )


def load_m8_l2_report_data(
    capture_config: M8L2StudyConfig,
    analysis_config: M8L2AnalysisConfig,
    train_session: L2StudySessionAuthority,
    validation_session: L2StudySessionAuthority,
    development_lock_dir: str | Path,
    expected_development_lock_sha256: str,
    primary_session: L2StudySessionAuthority,
    replication_session: L2StudySessionAuthority,
    run_dir: str | Path,
    *,
    expected_manifest_sha256: str | None = None,
    expected_checksums_sha256: str | None = None,
) -> L2ReportData:
    """Load report inputs only after complete terminal and authority verification."""

    if expected_manifest_sha256 is None or expected_checksums_sha256 is None:
        raise M8L2StudyRunVerificationError(
            "report loading requires caller-held manifest and checksum authorities"
        )

    verified = verify_m8_l2_study_run(
        capture_config,
        analysis_config,
        train_session,
        validation_session,
        development_lock_dir,
        expected_development_lock_sha256,
        primary_session,
        replication_session,
        run_dir,
        expected_manifest_sha256=expected_manifest_sha256,
        expected_checksums_sha256=expected_checksums_sha256,
    )
    data = _load_report_data_snapshot(verified.root)
    confirmed = verify_m8_l2_study_run(
        capture_config,
        analysis_config,
        train_session,
        validation_session,
        development_lock_dir,
        expected_development_lock_sha256,
        primary_session,
        replication_session,
        run_dir,
        expected_manifest_sha256=expected_manifest_sha256,
        expected_checksums_sha256=expected_checksums_sha256,
    )
    if confirmed != verified:
        raise M8L2StudyRunVerificationError(
            "final run authority changed while report inputs were loaded"
        )
    return data


@dataclass(frozen=True, slots=True)
class _SourceIdentity:
    commit: str
    source_tree_sha256: str
    dirty: bool

    def to_dict(self) -> dict[str, object]:
        return {
            "commit": self.commit,
            "source_tree_sha256": self.source_tree_sha256,
            "dirty": self.dirty,
        }


@dataclass(frozen=True, slots=True)
class _SessionSnapshot:
    authority: L2StudySessionAuthority
    bundle: M8L2SessionBundle
    manifest: Mapping[str, Any]
    campaign: L2CampaignRuntimeIdentity


@dataclass(frozen=True, slots=True)
class _LockMaterial:
    result: L2DevelopmentLockResult
    aggregate: Mapping[str, Any]
    campaign: L2CampaignRuntimeIdentity
    source: _SourceIdentity
    states: Mapping[tuple[str, str], LockedL2EndpointState]
    regimes: Mapping[str, L2RegimeFit]
    references: Mapping[str, L2ExecutionReference]
    development_frame_sha256: Mapping[tuple[str, str], str]
    snapshot_files: tuple[Path, ...]


@dataclass(frozen=True, slots=True)
class _ParentIdentity:
    device: int
    inode: int


def _is_sha256(value: str) -> bool:
    return len(value) == 64 and all(character in "0123456789abcdef" for character in value)


def _require_sha256(value: str, label: str) -> None:
    if not _is_sha256(value):
        raise M8L2StudyPipelineError(f"{label} must be a lowercase SHA-256")


def _canonical_json_bytes(value: Mapping[str, object]) -> bytes:
    try:
        return (
            json.dumps(
                dict(value),
                sort_keys=True,
                separators=(",", ":"),
                ensure_ascii=True,
                allow_nan=False,
            )
            + "\n"
        ).encode("ascii")
    except (TypeError, ValueError) as error:
        raise M8L2StudyPipelineError("M8 L2 authority is not finite canonical JSON") from error


def _decode_json(raw: bytes, label: str) -> dict[str, Any]:
    def reject_duplicates(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
        result: dict[str, Any] = {}
        for key, value in pairs:
            if key in result:
                raise M8L2StudyPipelineError(f"{label} repeats key {key!r}")
            result[key] = value
        return result

    def reject_constant(value: str) -> object:
        raise M8L2StudyPipelineError(f"{label} contains forbidden constant {value}")

    try:
        value = json.loads(
            raw,
            object_pairs_hook=reject_duplicates,
            parse_constant=reject_constant,
        )
    except M8L2StudyPipelineError:
        raise
    except (UnicodeDecodeError, json.JSONDecodeError) as error:
        raise M8L2StudyPipelineError(f"{label} is not valid UTF-8 JSON") from error
    if not isinstance(value, dict) or not all(type(key) is str for key in value):
        raise M8L2StudyPipelineError(f"{label} must be a JSON object")
    return cast(dict[str, Any], value)


def _safe_relative(value: str) -> str:
    candidate = PurePosixPath(value)
    if (
        not value
        or "\\" in value
        or "\x00" in value
        or candidate.is_absolute()
        or any(part in {"", ".", ".."} for part in candidate.parts)
        or candidate.as_posix() != value
    ):
        raise M8L2StudyPipelineError(f"unsafe M8 L2 relative path {value!r}")
    return value


def _join(root: Path, relative: str) -> Path:
    return root.joinpath(*PurePosixPath(_safe_relative(relative)).parts)


def _reject_symlink_components(path: Path) -> None:
    requested = path.absolute()
    current = Path(requested.anchor)
    for part in requested.parts[1:]:
        current /= part
        try:
            metadata = current.lstat()
        except FileNotFoundError:
            continue
        except OSError as error:
            raise M8L2StudyPipelineError(f"cannot inspect path component {current}") from error
        if stat.S_ISLNK(metadata.st_mode):
            raise M8L2StudyPipelineError(f"M8 L2 path contains symlink component {current}")


def _relative(path: Path, root: Path) -> str:
    try:
        return path.relative_to(root).as_posix()
    except ValueError as error:
        raise M8L2StudyPipelineError("artifact escapes the M8 L2 run root") from error


def _same_stat(left: os.stat_result, right: os.stat_result) -> bool:
    return (
        left.st_dev,
        left.st_ino,
        left.st_mode,
        left.st_size,
        left.st_mtime_ns,
        left.st_ctime_ns,
    ) == (
        right.st_dev,
        right.st_ino,
        right.st_mode,
        right.st_size,
        right.st_mtime_ns,
        right.st_ctime_ns,
    )


def _read_regular(
    path: Path,
    *,
    label: str,
    maximum_bytes: int = 64 * 1024 * 1024,
    expected_sha256: str | None = None,
) -> bytes:
    try:
        before_path = path.lstat()
    except OSError as error:
        raise M8L2StudyPipelineError(f"cannot stat {label}") from error
    if (
        not stat.S_ISREG(before_path.st_mode)
        or before_path.st_size < 0
        or before_path.st_size > maximum_bytes
    ):
        raise M8L2StudyPipelineError(f"{label} is not a bounded regular file")
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
    try:
        descriptor = os.open(path, flags)
    except OSError as error:
        raise M8L2StudyPipelineError(f"cannot open {label} without following links") from error
    try:
        before = os.fstat(descriptor)
        if not stat.S_ISREG(before.st_mode) or not _same_stat(before_path, before):
            raise M8L2StudyPipelineError(f"{label} changed before its descriptor snapshot")
        chunks: list[bytes] = []
        remaining = maximum_bytes + 1
        while remaining > 0:
            chunk = os.read(descriptor, min(1 << 20, remaining))
            if not chunk:
                break
            chunks.append(chunk)
            remaining -= len(chunk)
        raw = b"".join(chunks)
        after = os.fstat(descriptor)
        after_path = path.lstat()
        if len(raw) > maximum_bytes or len(raw) != before.st_size:
            raise M8L2StudyPipelineError(f"{label} exceeds its bounded snapshot")
        if not _same_stat(before, after) or not _same_stat(after, after_path):
            raise M8L2StudyPipelineError(f"{label} changed during its descriptor snapshot")
        digest = hashlib.sha256(raw).hexdigest()
        if expected_sha256 is not None and digest != expected_sha256:
            raise M8L2StudyPipelineError(f"{label} differs from its SHA-256 authority")
        return raw
    finally:
        os.close(descriptor)


def _read_json(
    path: Path,
    label: str,
    *,
    expected_sha256: str | None = None,
) -> tuple[dict[str, Any], bytes]:
    raw = _read_regular(path, label=label, expected_sha256=expected_sha256)
    return _decode_json(raw, label), raw


def _fsync_directory(path: Path) -> None:
    descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
    try:
        os.fsync(descriptor)
    finally:
        os.close(descriptor)


def _write_bytes(path: Path, raw: bytes) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0)
    descriptor = os.open(path, flags, 0o644)
    try:
        view = memoryview(raw)
        while view:
            written = os.write(descriptor, view)
            if written < 1:
                raise OSError("short M8 L2 artifact write")
            view = view[written:]
        os.fsync(descriptor)
    finally:
        os.close(descriptor)
    _fsync_directory(path.parent)


def _write_json(path: Path, payload: Mapping[str, object]) -> str:
    raw = _canonical_json_bytes(payload)
    _write_bytes(path, raw)
    return hashlib.sha256(raw).hexdigest()


def _write_parquet(path: Path, frame: pl.DataFrame) -> str:
    path.parent.mkdir(parents=True, exist_ok=True)
    if path.exists() or path.is_symlink():
        raise M8L2StudyPipelineError(f"refusing to overwrite M8 L2 artifact {path}")
    frame.write_parquet(path, compression="zstd", statistics=True)
    descriptor = os.open(path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0))
    try:
        os.fsync(descriptor)
    finally:
        os.close(descriptor)
    _fsync_directory(path.parent)
    return sha256_file(path)


def _copy_exact(source: Path, destination: Path, *, expected_sha256: str | None = None) -> str:
    raw = _read_regular(
        source,
        label=f"authority snapshot {source}",
        maximum_bytes=128 * 1024 * 1024,
        expected_sha256=expected_sha256,
    )
    _write_bytes(destination, raw)
    return hashlib.sha256(raw).hexdigest()


def _parse_checksums(raw: bytes, label: str) -> dict[str, str]:
    try:
        lines = raw.decode("ascii").splitlines(keepends=True)
    except UnicodeDecodeError as error:
        raise M8L2StudyPipelineError(f"{label} must be ASCII") from error
    result: dict[str, str] = {}
    for line in lines:
        if len(line) < 68 or not line.endswith("\n") or line[64:66] != "  ":
            raise M8L2StudyPipelineError(f"{label} has a malformed line")
        digest = line[:64]
        relative = _safe_relative(line[66:-1])
        _require_sha256(digest, f"{label} entry")
        if relative in result:
            raise M8L2StudyPipelineError(f"{label} repeats {relative}")
        result[relative] = digest
    if not result or list(result) != sorted(result):
        raise M8L2StudyPipelineError(f"{label} is empty or not canonically ordered")
    return result


def _frame_sha256(frame: pl.DataFrame) -> str:
    digest = hashlib.sha256()
    schema = [(name, str(dtype)) for name, dtype in frame.schema.items()]
    digest.update(json.dumps(schema, separators=(",", ":")).encode())
    for chunk in frame.hash_rows(seed=0, seed_1=1, seed_2=2, seed_3=3).get_chunks():
        digest.update(chunk.to_numpy().astype("<u8", copy=False).tobytes(order="C"))
    digest.update(str(frame.height).encode())
    return digest.hexdigest()


def _revalidate_configs(
    capture_config: M8L2StudyConfig,
    analysis_config: M8L2AnalysisConfig,
) -> tuple[M8L2StudyConfig, M8L2AnalysisConfig]:
    try:
        capture = load_m8_l2_config(capture_config.path)
        analysis = load_m8_l2_analysis_config(analysis_config.path)
    except (OSError, ValueError) as error:
        raise M8L2StudyPipelineError("frozen M8 L2 configs cannot be reloaded") from error
    if capture != capture_config or analysis != analysis_config:
        raise M8L2StudyPipelineError("in-memory M8 L2 configs differ from exact frozen bytes")
    coordinates = tuple((item.date.isoformat(), item.role) for item in capture.sessions)
    if coordinates != _EXPECTED_COORDINATES:
        raise M8L2StudyPipelineError("M8 L2 session calendar differs from the freeze")
    if (
        analysis.study.capture_config_source_sha256 != capture.source_sha256
        or analysis.study.capture_protocol_sha256 != M8_L2_PROTOCOL_SHA256
        or analysis.study.symbols != capture.study.symbols
        or analysis.study.seed != capture.study.seed
    ):
        raise M8L2StudyPipelineError("capture and analysis configs do not bind one study")
    return capture, analysis


def _current_source_identity(capture: M8L2StudyConfig) -> _SourceIdentity:
    project_root = capture.path.parent.parent.resolve()
    before = strict_git_state(project_root)
    source_tree_sha256 = git_source_tree_sha256(project_root)
    after = strict_git_state(project_root)
    if before != after:
        raise M8L2StudyPipelineError("Git identity changed during final source snapshot")
    result = _SourceIdentity(
        commit=before.commit,
        source_tree_sha256=source_tree_sha256,
        dirty=before.dirty,
    )
    if result.dirty:
        raise M8L2StudyPipelineError("final M8 L2 production requires a clean Git source tree")
    if len(result.commit) != 40 or any(char not in "0123456789abcdef" for char in result.commit):
        raise M8L2StudyPipelineError("final M8 L2 producer commit is not a lowercase Git SHA-1")
    _require_sha256(result.source_tree_sha256, "final M8 L2 source tree")
    return result


def _campaign_from_manifest(manifest: Mapping[str, Any]) -> L2CampaignRuntimeIdentity:
    authority = manifest.get("authority")
    if not isinstance(authority, Mapping):
        raise M8L2StudyPipelineError("session manifest lacks campaign authority")
    return L2CampaignRuntimeIdentity(
        campaign_authority_sha256=str(authority.get("campaign_authority_sha256")),
        runtime_commit=str(authority.get("runtime_commit")),
        runtime_source_tree_sha256=str(authority.get("runtime_source_tree_sha256")),
        runtime_fingerprint_sha256=str(authority.get("runtime_fingerprint_sha256")),
        runtime_dirty=authority.get("runtime_dirty") is not False,
    )


def _verify_session_authority(
    authority: L2StudySessionAuthority,
    *,
    capture: M8L2StudyConfig,
    expected_date: str,
    expected_role: str,
    expected_campaign: L2CampaignRuntimeIdentity | None,
) -> _SessionSnapshot:
    try:
        first = verify_m8_l2_session_bundle(authority.bundle_path, expected_config=capture)
    except Exception as error:
        raise M8L2StudyPipelineError(
            f"session {expected_date} {expected_role} failed capture verification"
        ) from error
    if first.session_date != expected_date or first.role != expected_role:
        raise M8L2StudyPipelineError("session authority has the wrong frozen coordinate")
    manifest, _ = _read_json(
        first.manifest_path,
        f"{expected_role} session manifest",
        expected_sha256=authority.manifest_sha256,
    )
    _read_regular(
        first.checksum_path,
        label=f"{expected_role} session checksums",
        expected_sha256=authority.checksums_sha256,
    )
    if first.manifest_sha256 != authority.manifest_sha256:
        raise M8L2StudyPipelineError("session capture verifier and manifest authority disagree")
    campaign = _campaign_from_manifest(manifest)
    if expected_campaign is not None and campaign != expected_campaign:
        raise M8L2StudyPipelineError("four-session campaign/source identity changed")
    try:
        second = verify_m8_l2_session_bundle(authority.bundle_path, expected_config=capture)
    except Exception as error:
        raise M8L2StudyPipelineError("session changed during authority snapshot") from error
    if second != first:
        raise M8L2StudyPipelineError("session verifier result changed during authority snapshot")
    return _SessionSnapshot(authority, first, manifest, campaign)


def _mapping(value: object, label: str) -> Mapping[str, Any]:
    if not isinstance(value, Mapping) or not all(type(key) is str for key in value):
        raise M8L2StudyPipelineError(f"{label} must be an object")
    return cast(Mapping[str, Any], value)


def _string(value: object, label: str) -> str:
    if type(value) is not str or not value:
        raise M8L2StudyPipelineError(f"{label} must be nonempty text")
    return value


def _finite(value: object, label: str, *, positive: bool = False) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise M8L2StudyPipelineError(f"{label} must be a finite number")
    result = float(value)
    if not math.isfinite(result) or (positive and result <= 0.0):
        raise M8L2StudyPipelineError(
            f"{label} must be finite" + (" and positive" if positive else "")
        )
    return result


def _endpoint_specs(analysis: M8L2AnalysisConfig) -> tuple[L2EndpointSpec, ...]:
    windows = set(analysis.features.rolling_windows)
    result: list[L2EndpointSpec] = []
    for endpoint in analysis.endpoints:
        impact_window = (
            endpoint.horizon_value
            if endpoint.domain == "event"
            else endpoint.nominal_event_block_width
        )
        if impact_window not in windows:
            impact_window = min(windows, key=lambda item: abs(item - impact_window))
        result.append(
            L2EndpointSpec(
                name=endpoint.name,
                domain=endpoint.domain,
                horizon_value=endpoint.horizon_value,
                horizon_unit=endpoint.unit,
                paired_block_events=(
                    endpoint.paired_block_width if endpoint.domain == "event" else None
                ),
                paired_block_milliseconds=(
                    endpoint.paired_block_width if endpoint.domain == "clock" else None
                ),
                impact_ofi_window=impact_window,
            )
        )
    return tuple(result)


def _campaign_from_aggregate(aggregate: Mapping[str, Any]) -> L2CampaignRuntimeIdentity:
    campaign = _mapping(aggregate.get("campaign_identity"), "development campaign identity")
    return L2CampaignRuntimeIdentity(
        campaign_authority_sha256=_string(
            campaign.get("campaign_authority_sha256"), "development campaign SHA-256"
        ),
        runtime_commit=_string(campaign.get("runtime_commit"), "development runtime commit"),
        runtime_source_tree_sha256=_string(
            campaign.get("runtime_source_tree_sha256"), "development runtime source tree"
        ),
        runtime_fingerprint_sha256=_string(
            campaign.get("runtime_fingerprint_sha256"),
            "development runtime fingerprint",
        ),
        runtime_dirty=campaign.get("runtime_dirty") is not False,
    )


def _assert_current_runtime(campaign: L2CampaignRuntimeIdentity) -> None:
    if current_m8_l2_runtime_fingerprint_sha256() != campaign.runtime_fingerprint_sha256:
        raise M8L2StudyPipelineError(
            "final producer runtime differs from the frozen capture campaign"
        )


def _explicit_development_authority(
    aggregate: Mapping[str, Any],
    train: L2StudySessionAuthority,
    validation: L2StudySessionAuthority,
) -> None:
    raw_inputs = aggregate.get("development_inputs")
    if not isinstance(raw_inputs, list) or len(raw_inputs) != 2:
        raise M8L2StudyPipelineError("development lock has no exact two-session input set")
    for claim, supplied, coordinate in zip(
        raw_inputs,
        (train, validation),
        _EXPECTED_COORDINATES[:2],
        strict=True,
    ):
        payload = _mapping(claim, "development input claim")
        file_authority = _mapping(payload.get("file_authority"), "development input file authority")
        expected = {
            "date": coordinate[0],
            "role": coordinate[1],
            "manifest_sha256": supplied.manifest_sha256,
            "checksums_sha256": supplied.checksums_sha256,
        }
        observed = {
            "date": payload.get("date"),
            "role": payload.get("role"),
            "manifest_sha256": file_authority.get("manifest_sha256"),
            "checksums_sha256": file_authority.get("checksums_sha256"),
        }
        if observed != expected:
            raise M8L2StudyPipelineError(
                "caller development session authority differs from the aggregate lock"
            )


def _verify_lock_context(
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    train: L2StudySessionAuthority,
    validation: L2StudySessionAuthority,
    lock_dir: str | Path,
    expected_lock_sha256: str,
) -> tuple[L2DevelopmentLockResult, Mapping[str, Any], L2CampaignRuntimeIdentity, _SourceIdentity]:
    _require_sha256(expected_lock_sha256, "development aggregate lock authority")
    try:
        result = verify_m8_l2_development_lock(
            capture,
            analysis,
            train.bundle_path,
            validation.bundle_path,
            lock_dir,
            expected_lock_sha256=expected_lock_sha256,
        )
    except Exception as error:
        raise M8L2StudyPipelineError("development lock failed recursive verification") from error
    aggregate, _ = _read_json(
        result.aggregate_path,
        "aggregate development lock",
        expected_sha256=expected_lock_sha256,
    )
    _explicit_development_authority(aggregate, train, validation)
    campaign = _campaign_from_aggregate(aggregate)
    source = _current_source_identity(capture)
    producer = _mapping(
        aggregate.get("producer_source_identity"), "development producer source identity"
    )
    expected_source = source.to_dict()
    if dict(producer) != expected_source:
        raise M8L2StudyPipelineError("current producer source differs from development lock")
    if (
        campaign.runtime_commit != source.commit
        or campaign.runtime_source_tree_sha256 != source.source_tree_sha256
        or campaign.runtime_dirty
    ):
        raise M8L2StudyPipelineError("development lock and campaign source identities disagree")
    return result, aggregate, campaign, source


def _regime_from_payload(payload: Mapping[str, Any], *, symbol: str) -> L2RegimeFit:
    if (
        payload.get("schema_version") != "m8-l2-regime-thresholds-v1"
        or payload.get("artifact_kind") != "train_only_l2_regime_thresholds"
        or payload.get("symbol") != symbol
        or payload.get("study_date") != "2026-08-10"
        or payload.get("fit_scope") != "train_session_only"
    ):
        raise M8L2StudyPipelineError("train-only regime snapshot has invalid semantics")
    thresholds = _mapping(payload.get("thresholds"), "regime thresholds")
    return L2RegimeFit(
        symbol=symbol,
        study_date="2026-08-10",
        volatility_column=_string(payload.get("volatility_column"), "regime feature"),
        lower_quantile=_finite(payload.get("lower_quantile"), "lower regime quantile"),
        upper_quantile=_finite(payload.get("upper_quantile"), "upper regime quantile"),
        thresholds=RegimeThresholds(
            volatility_low=_finite(thresholds.get("volatility_low"), "volatility low"),
            volatility_high=_finite(thresholds.get("volatility_high"), "volatility high"),
            spread_tight_bps=_finite(thresholds.get("spread_tight_bps"), "tight spread"),
            spread_wide_bps=_finite(thresholds.get("spread_wide_bps"), "wide spread"),
            depth_low=_finite(thresholds.get("depth_low"), "low depth"),
            depth_high=_finite(thresholds.get("depth_high"), "high depth"),
        ),
    )


def _execution_reference_from_payload(
    payload: Mapping[str, Any],
    *,
    symbol: str,
    aggregate_sha256: str,
) -> L2ExecutionReference:
    if (
        payload.get("schema_version") != "m8-l2-execution-reference-v1"
        or payload.get("artifact_kind") != "train_only_execution_reference"
        or payload.get("symbol") != symbol
        or payload.get("fit_date") != "2026-08-10"
        or payload.get("fit_role") != "train"
        or payload.get("reference_price_statistic") != "train_median_mid_price"
        or payload.get("reference_depth_statistic") != "train_q05_min_bid_ask_l1_depth"
    ):
        raise M8L2StudyPipelineError("train-only execution snapshot has invalid semantics")
    return L2ExecutionReference.create(
        symbol=symbol,
        training_date="2026-08-10",
        reference_mid_price=_finite(
            payload.get("reference_mid_price"), "execution reference midpoint", positive=True
        ),
        train_l1_depth_q05=_finite(
            payload.get("reference_l1_depth_q05"), "execution reference depth", positive=True
        ),
        lot_size=_finite(payload.get("lot_size"), "execution reference lot", positive=True),
        reference_quantity=_finite(
            payload.get("reference_quantity"), "execution reference quantity", positive=True
        ),
        aggregate_lock_sha256=aggregate_sha256,
    )


def _load_lock_material(
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    result: L2DevelopmentLockResult,
    aggregate: Mapping[str, Any],
    campaign: L2CampaignRuntimeIdentity,
    source: _SourceIdentity,
) -> _LockMaterial:
    endpoint_specs = {item.name: item for item in _endpoint_specs(analysis)}
    states: dict[tuple[str, str], LockedL2EndpointState] = {}
    regimes: dict[str, L2RegimeFit] = {}
    references: dict[str, L2ExecutionReference] = {}
    development_hashes: dict[tuple[str, str], str] = {}
    snapshot_files: dict[str, Path] = {
        _relative(result.aggregate_path, result.root): result.aggregate_path,
        "development_lock.sha256": result.root / "development_lock.sha256",
    }
    if result.status == "NOT_CREATED":
        development_checksums_path = result.root / _CHECKSUMS_NAME
        development_checksums = _parse_checksums(
            _read_regular(
                development_checksums_path,
                label="NOT_CREATED development checksum authority",
                maximum_bytes=4 << 20,
            ),
            "NOT_CREATED development checksum authority",
        )
        for relative, digest in development_checksums.items():
            path = _join(result.root, relative)
            if _stable_file_sha256_for_pipeline(path, relative) != digest:
                raise M8L2StudyPipelineError(
                    f"NOT_CREATED development snapshot changed for {relative}"
                )
            snapshot_files[relative] = path
        snapshot_files[_CHECKSUMS_NAME] = development_checksums_path
        not_created_marker = result.root / "_NOT_CREATED"
        if (
            _read_regular(
                not_created_marker,
                label="NOT_CREATED development terminal marker",
                maximum_bytes=32,
            )
            != b"not-created\n"
        ):
            raise M8L2StudyPipelineError("NOT_CREATED development marker differs")
        snapshot_files["_NOT_CREATED"] = not_created_marker
        return _LockMaterial(
            result=result,
            aggregate=aggregate,
            campaign=campaign,
            source=source,
            states={},
            regimes={},
            references={},
            development_frame_sha256={},
            snapshot_files=tuple(snapshot_files[key] for key in sorted(snapshot_files)),
        )
    child_by_key = {(item.symbol, item.endpoint): item for item in result.children}
    expected_keys = tuple(
        (symbol, endpoint.name)
        for symbol in capture.study.symbols
        for endpoint in analysis.endpoints
    )
    if tuple(child_by_key) != expected_keys:
        raise M8L2StudyPipelineError("development result has an incomplete child order")
    for symbol, endpoint_name in expected_keys:
        child_claim = child_by_key[(symbol, endpoint_name)]
        child, _ = _read_json(
            child_claim.path,
            f"{symbol} {endpoint_name} child lock",
            expected_sha256=child_claim.sha256,
        )
        state_relative = _safe_relative(
            _string(child.get("final_fitted_state_path"), "fitted-state path")
        )
        state_sha = _string(child.get("final_fitted_state_sha256"), "fitted-state SHA-256")
        _require_sha256(state_sha, "fitted-state SHA-256")
        state_path = _join(result.root, state_relative)
        state_raw = _read_regular(
            state_path,
            label=f"{symbol} {endpoint_name} fitted state",
        )
        if not state_raw.endswith(b"\n"):
            raise M8L2StudyPipelineError("fitted-state snapshot lacks canonical newline")
        try:
            fitted_state = FinalFittedState.restore(state_raw[:-1].decode("ascii"), state_sha)
        except (UnicodeDecodeError, ValueError) as error:
            raise M8L2StudyPipelineError("fitted-state snapshot cannot be restored") from error

        regime_relative = _safe_relative(
            _string(child.get("regime_thresholds_path"), "regime path")
        )
        regime_sha = _string(child.get("regime_thresholds_sha256"), "regime SHA-256")
        _require_sha256(regime_sha, "regime SHA-256")
        regime_path = _join(result.root, regime_relative)
        if symbol not in regimes:
            regime_payload, _ = _read_json(
                regime_path,
                f"{symbol} regime thresholds",
                expected_sha256=regime_sha,
            )
            regimes[symbol] = _regime_from_payload(regime_payload, symbol=symbol)

        execution_relative = _safe_relative(
            _string(child.get("execution_reference_path"), "execution reference path")
        )
        execution_sha = _string(
            child.get("execution_reference_sha256"), "execution reference SHA-256"
        )
        _require_sha256(execution_sha, "execution reference SHA-256")
        execution_path = _join(result.root, execution_relative)
        if symbol not in references:
            execution_payload, _ = _read_json(
                execution_path,
                f"{symbol} execution reference",
                expected_sha256=execution_sha,
            )
            references[symbol] = _execution_reference_from_payload(
                execution_payload,
                symbol=symbol,
                aggregate_sha256=result.aggregate_sha256,
            )

        states[(symbol, endpoint_name)] = LockedL2EndpointState(
            symbol=symbol,
            endpoint=endpoint_specs[endpoint_name],
            child_lock_sha256=child_claim.sha256,
            aggregate_lock_sha256=result.aggregate_sha256,
            regime_thresholds_sha256=regime_sha,
            fitted_state=fitted_state,
        )
        development_sha = _string(
            child.get("development_frame_sha256"), "development-frame SHA-256"
        )
        _require_sha256(development_sha, "development-frame SHA-256")
        development_hashes[(symbol, endpoint_name)] = development_sha
        selection_relative = _safe_relative(
            _string(child.get("selection_lock_path"), "selection-lock path")
        )
        for path in (
            child_claim.path,
            state_path,
            regime_path,
            execution_path,
            _join(result.root, selection_relative),
        ):
            snapshot_files[_relative(path, result.root)] = path
    development_checksums_path = result.root / _CHECKSUMS_NAME
    development_checksums_raw = _read_regular(
        development_checksums_path,
        label="development-lock checksum authority",
        maximum_bytes=4 << 20,
    )
    development_checksums = _parse_checksums(
        development_checksums_raw, "development-lock checksum authority"
    )
    for relative, digest in development_checksums.items():
        path = _join(result.root, relative)
        if _stable_file_sha256_for_pipeline(path, relative) != digest:
            raise M8L2StudyPipelineError(f"development-lock snapshot source changed for {relative}")
        snapshot_files[relative] = path
    snapshot_files[_CHECKSUMS_NAME] = development_checksums_path
    locked_marker = result.root / "_LOCKED"
    if (
        _read_regular(locked_marker, label="development-lock terminal marker", maximum_bytes=32)
        != b"locked\n"
    ):
        raise M8L2StudyPipelineError("development-lock terminal marker differs")
    snapshot_files["_LOCKED"] = locked_marker
    return _LockMaterial(
        result=result,
        aggregate=aggregate,
        campaign=campaign,
        source=source,
        states=states,
        regimes=regimes,
        references=references,
        development_frame_sha256=development_hashes,
        snapshot_files=tuple(snapshot_files[key] for key in sorted(snapshot_files)),
    )


def _stable_file_sha256_for_pipeline(path: Path, label: str) -> str:
    try:
        before = path.lstat()
    except OSError as error:
        raise M8L2StudyPipelineError(f"cannot stat {label}") from error
    if not stat.S_ISREG(before.st_mode):
        raise M8L2StudyPipelineError(f"{label} must be a regular file")
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
    descriptor = os.open(path, flags)
    try:
        opened = os.fstat(descriptor)
        if not _same_stat(before, opened):
            raise M8L2StudyPipelineError(f"{label} changed before hashing")
        digest = hashlib.sha256()
        while chunk := os.read(descriptor, 1 << 20):
            digest.update(chunk)
        after = os.fstat(descriptor)
        if not _same_stat(opened, after) or not _same_stat(after, path.lstat()):
            raise M8L2StudyPipelineError(f"{label} changed while hashing")
        return digest.hexdigest()
    finally:
        os.close(descriptor)


def _verify_all_sessions(
    capture: M8L2StudyConfig,
    material: _LockMaterial,
    authorities: Sequence[L2StudySessionAuthority],
) -> tuple[_SessionSnapshot, ...]:
    if len(authorities) != 4:
        raise M8L2StudyPipelineError("the final L2 study requires four explicit sessions")
    snapshots: list[_SessionSnapshot] = []
    for supplied, (expected_date, expected_role) in zip(
        authorities, _EXPECTED_COORDINATES, strict=True
    ):
        snapshots.append(
            _verify_session_authority(
                supplied,
                capture=capture,
                expected_date=expected_date,
                expected_role=expected_role,
                expected_campaign=material.campaign,
            )
        )
    development_incomplete = any(item.bundle.status != "COMPLETE" for item in snapshots[:2])
    if material.result.status == "LOCKED" and development_incomplete:
        raise M8L2StudyPipelineError(
            "train/validation failure cannot be promoted without a valid development lock"
        )
    if material.result.status == "NOT_CREATED" and not development_incomplete:
        raise M8L2StudyPipelineError(
            "NOT_CREATED development authority requires an insufficient development session"
        )
    return tuple(snapshots)


def _reverify_material(
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    train: L2StudySessionAuthority,
    validation: L2StudySessionAuthority,
    lock_dir: str | Path,
    expected_lock_sha256: str,
    expected: _LockMaterial,
) -> None:
    result, aggregate, campaign, source = _verify_lock_context(
        capture,
        analysis,
        train,
        validation,
        lock_dir,
        expected_lock_sha256,
    )
    if (
        result.aggregate_sha256 != expected.result.aggregate_sha256
        or dict(aggregate) != dict(expected.aggregate)
        or campaign != expected.campaign
        or source != expected.source
        or result.children != expected.result.children
        or result.status != expected.result.status
        or result.reason_codes != expected.result.reason_codes
    ):
        raise M8L2StudyPipelineError("development lock/source changed during final production")


def _development_input(
    snapshot: _SessionSnapshot,
    *,
    capture: M8L2StudyConfig,
    campaign: L2CampaignRuntimeIdentity,
) -> VerifiedL2SessionInput:
    role = cast(Literal["train", "validation"], snapshot.bundle.role)
    return verify_m8_l2_development_input(
        snapshot.authority.bundle_path,
        expected_config=capture,
        expected_date=snapshot.bundle.session_date,
        expected_role=role,
        expected_file_authority=snapshot.authority.file_authority,
        expected_campaign=campaign,
    )


def _heldout_input(
    snapshot: _SessionSnapshot,
    *,
    capture: M8L2StudyConfig,
    campaign: L2CampaignRuntimeIdentity,
    lock_sha256: str,
) -> VerifiedL2SessionInput:
    role = cast(Literal["primary_test", "replication_test"], snapshot.bundle.role)
    return verify_m8_l2_heldout_input(
        snapshot.authority.bundle_path,
        expected_config=capture,
        expected_date=snapshot.bundle.session_date,
        expected_role=role,
        development_lock_sha256=lock_sha256,
        expected_file_authority=snapshot.authority.file_authority,
        expected_campaign=campaign,
    )


def _build_one_symbol_frames(
    verified: VerifiedL2SessionInput,
    *,
    symbol: str,
    analysis: M8L2AnalysisConfig,
    material: _LockMaterial,
) -> Mapping[str, pl.DataFrame]:
    admission = _preflight_symbol_raw(verified, symbol)
    if admission is not None:
        _require_memory_budget(
            admission[0],
            _MAX_FINAL_RAW_BYTES,
            f"{verified.session_date} {symbol} raw Parquet admission",
        )
        _require_memory_budget(
            admission[1] * len(analysis.endpoints) * _CAUSAL_ENDPOINT_ROW_UPPER_BYTES,
            _MAX_CAUSAL_COORDINATE_BYTES,
            f"{verified.session_date} {symbol} causal build admission",
        )
    loaded = verified.load_symbol_frames(symbol)
    _require_memory_budget(
        _loaded_bytes(loaded),
        _MAX_FINAL_RAW_BYTES,
        f"{verified.session_date} {symbol} raw materialization",
    )
    if admission is None:
        _require_memory_budget(
            loaded.book_observations.height
            * len(analysis.endpoints)
            * _CAUSAL_ENDPOINT_ROW_UPPER_BYTES,
            _MAX_CAUSAL_COORDINATE_BYTES,
            f"{verified.session_date} {symbol} causal build admission",
        )
    built = dict(
        build_l2_endpoint_frames(
            loaded.book_observations,
            loaded.depth_deltas,
            loaded.intervals,
            study_date=verified.session_date,
            study_role=cast(Any, verified.role),
            feature_windows=analysis.features.rolling_windows,
            volatility_window=analysis.features.volatility_window,
            clock_max_state_age_ms=analysis.features.clock_max_state_age_ms,
            endpoints=_endpoint_specs(analysis),
        )
    )
    _require_memory_budget(
        _frames_bytes(list(built.values())),
        _MAX_CAUSAL_COORDINATE_BYTES,
        f"{verified.session_date} {symbol} causal builder output",
    )
    del loaded
    result: dict[str, pl.DataFrame] = {}
    for endpoint in analysis.endpoints:
        source = built.pop(endpoint.name)
        frame = apply_l2_regimes(source, material.regimes[symbol])
        _require_memory_budget(
            _frames_bytes([*built.values(), *result.values(), source, frame]),
            _MAX_CAUSAL_COORDINATE_BYTES,
            f"{verified.session_date} {symbol} causal output/scratch",
        )
        if (
            l2_model_feature_columns(frame, windows=analysis.features.rolling_windows)
            != analysis.features.model_feature_columns
        ):
            raise M8L2StudyPipelineError("rebuilt causal frame has the wrong model features")
        validate_l2_endpoint_frame(frame)
        result[endpoint.name] = frame
        del source
    _require_memory_budget(
        _frames_bytes(list(result.values())),
        _MAX_CAUSAL_COORDINATE_BYTES,
        f"{verified.session_date} {symbol} causal coordinate output",
    )
    return result


def _build_causal_frames(
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    snapshots: Sequence[_SessionSnapshot],
    material: _LockMaterial,
    *,
    train: L2StudySessionAuthority,
    validation: L2StudySessionAuthority,
    lock_dir: str | Path,
    lock_sha256: str,
) -> tuple[
    dict[tuple[str, str, str, str], pl.DataFrame],
    tuple[L2HeldoutEndpointFrame, ...],
]:
    inputs: list[VerifiedL2SessionInput] = [
        _development_input(snapshots[0], capture=capture, campaign=material.campaign),
        _development_input(snapshots[1], capture=capture, campaign=material.campaign),
    ]
    for heldout_snapshot in snapshots[2:]:
        _reverify_material(
            capture,
            analysis,
            train,
            validation,
            lock_dir,
            lock_sha256,
            material,
        )
        inputs.append(
            _heldout_input(
                heldout_snapshot,
                capture=capture,
                campaign=material.campaign,
                lock_sha256=lock_sha256,
            )
        )

    causal: dict[tuple[str, str, str, str], pl.DataFrame] = {}
    heldout: list[L2HeldoutEndpointFrame] = []
    causal_bytes = 0
    for verified in inputs:
        for symbol in capture.study.symbols:
            # This check is intentionally adjacent to every held-out payload load.
            if verified.role in {"primary_test", "replication_test"}:
                _reverify_material(
                    capture,
                    analysis,
                    train,
                    validation,
                    lock_dir,
                    lock_sha256,
                    material,
                )
            frames = _build_one_symbol_frames(
                verified,
                symbol=symbol,
                analysis=analysis,
                material=material,
            )
            for endpoint in analysis.endpoints:
                frame = frames[endpoint.name]
                key = (verified.session_date, verified.role, symbol, endpoint.name)
                causal[key] = frame
                causal_bytes += _frame_bytes(frame)
                _require_memory_budget(
                    causal_bytes,
                    _MAX_FINAL_CAUSAL_BYTES,
                    "32-frame accumulated causal output",
                )
                if verified.role in {"primary_test", "replication_test"}:
                    heldout.append(
                        L2HeldoutEndpointFrame(
                            symbol=symbol,
                            endpoint_name=endpoint.name,
                            study_date=verified.session_date,
                            study_role=cast(Any, verified.role),
                            frame=frame,
                        )
                    )
            del frames, frame
    expected_count = 4 * len(capture.study.symbols) * len(analysis.endpoints)
    if len(causal) != expected_count or len(heldout) != expected_count // 2:
        raise M8L2StudyPipelineError("rebuilt causal frame set is incomplete")
    for symbol in capture.study.symbols:
        for endpoint in analysis.endpoints:
            train_frame = causal[("2026-08-10", "train", symbol, endpoint.name)]
            validation_frame = causal[("2026-08-11", "validation", symbol, endpoint.name)]
            _require_memory_budget(
                2 * (_frame_bytes(train_frame) + _frame_bytes(validation_frame)),
                _MAX_CAUSAL_COORDINATE_BYTES,
                f"{symbol} {endpoint.name} development-hash concat scratch",
            )
            development = pl.concat(
                [train_frame, validation_frame],
                how="vertical",
            )
            if (
                _frame_sha256(development)
                != material.development_frame_sha256[(symbol, endpoint.name)]
            ):
                raise M8L2StudyPipelineError(
                    "rebuilt train/validation causal frame differs from the locked development hash"
                )
            del development, train_frame, validation_frame
    return causal, tuple(heldout)


def _heldout_availability_reasons(
    heldout: Sequence[L2HeldoutEndpointFrame],
) -> tuple[str, ...]:
    reasons: list[str] = []
    for item in heldout:
        eligible = item.frame.filter(
            pl.col("feature_ready")
            & (~pl.col("right_censored"))
            & pl.col("future_mid_up").is_not_null()
        )
        if eligible.is_empty():
            reasons.append(
                f"NO_ELIGIBLE_LABELS::{item.study_role}::{item.symbol}::{item.endpoint_name}"
            )
    return tuple(sorted(reasons))


def _session_gate_rows(snapshots: Sequence[_SessionSnapshot]) -> tuple[Mapping[str, Any], ...]:
    rows: list[Mapping[str, Any]] = []
    for item in snapshots:
        symbols = item.manifest.get("symbols")
        symbol_payload = symbols if isinstance(symbols, Mapping) else {}
        rows.append(
            {
                "study_date": item.bundle.session_date,
                "study_role": item.bundle.role,
                "status": item.bundle.status,
                "BTCUSDT_gate": (
                    _mapping(symbol_payload.get("BTCUSDT"), "BTC session claim").get("status")
                    if "BTCUSDT" in symbol_payload
                    else "NOT_AVAILABLE"
                ),
                "ETHUSDT_gate": (
                    _mapping(symbol_payload.get("ETHUSDT"), "ETH session claim").get("status")
                    if "ETHUSDT" in symbol_payload
                    else "NOT_AVAILABLE"
                ),
                "overlap_seconds": item.manifest.get("cross_symbol_observed_overlap_seconds", 0.0),
                "reason_codes": list(item.bundle.reason_codes),
                "manifest_sha256": item.authority.manifest_sha256,
                "checksums_sha256": item.authority.checksums_sha256,
            }
        )
    return tuple(rows)


def _not_created_final_reasons(
    snapshots: Sequence[_SessionSnapshot],
) -> tuple[str, ...]:
    reasons: set[str] = set()
    for index, item in enumerate(snapshots):
        if item.bundle.status == "COMPLETE":
            continue
        prefix = "DEVELOPMENT_SESSION_INSUFFICIENT" if index < 2 else "HELDOUT_SESSION_INSUFFICIENT"
        reasons.update(
            f"{prefix}::{item.bundle.role}::{reason}"
            for reason in (item.bundle.reason_codes or ("SESSION_INSUFFICIENT_DATA",))
        )
    return tuple(sorted(reasons))


def _causal_relative(key: tuple[str, str, str, str]) -> str:
    study_date, role, symbol, endpoint = key
    return f"causal_frames/{study_date}-{role}/{symbol.lower()}/{endpoint}.parquet"


_EVALUATION_PATHS = (
    "evaluation/predictions.parquet",
    "evaluation/predictive_metrics.parquet",
    "evaluation/paired_by_session_regime.parquet",
    "evaluation/equal_session_summary.parquet",
    "evaluation/signed_markout.parquet",
)
_DESCRIPTIVE_PATHS = (
    "descriptive/intraday_liquidity.parquet",
    "descriptive/ofi_return_association.parquet",
    "descriptive/signal_half_life.parquet",
    "descriptive/liquidity_recovery.parquet",
    "descriptive/regime_diagnostics.parquet",
    "descriptive/feature_stability.parquet",
    "descriptive/cross_instrument_stability.parquet",
)
_REPORT_PATHS = (
    "reports/technical_report.md",
    "reports/executive_memo.md",
    "reports/model_comparison.md",
)


def _execution_relative(item: L2HeldoutEndpointFrame, name: str) -> str:
    return (
        f"execution/partitions/{item.study_date}-{item.study_role}/"
        f"{item.symbol.lower()}/{item.endpoint_name}/{name}.parquet"
    )


def _authority_sources(
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    snapshots: Sequence[_SessionSnapshot],
    material: _LockMaterial,
) -> Mapping[str, tuple[Path, str]]:
    project_root = capture.path.parent.parent.resolve()
    protocol = project_root / "docs" / "M8_L2_PROTOCOL.md"
    result: dict[str, tuple[Path, str]] = {
        "authority/m8_l2_capture_study.toml": (capture.path, capture.source_sha256),
        "authority/m8_l2_analysis.toml": (analysis.path, analysis.source_sha256),
        "authority/M8_L2_PROTOCOL.md": (protocol, M8_L2_PROTOCOL_SHA256),
        "authority/campaign_authority.json": (
            snapshots[0].authority.bundle_path / "authority" / "campaign_authority.json",
            material.campaign.campaign_authority_sha256,
        ),
    }
    for snapshot in snapshots:
        prefix = f"authority/sessions/{snapshot.bundle.session_date}-{snapshot.bundle.role}"
        result[f"{prefix}/session_manifest.json"] = (
            snapshot.bundle.manifest_path,
            snapshot.authority.manifest_sha256,
        )
        result[f"{prefix}/CHECKSUMS.sha256"] = (
            snapshot.bundle.checksum_path,
            snapshot.authority.checksums_sha256,
        )
    for source in material.snapshot_files:
        relative = _relative(source, material.result.root)
        result[f"authority/development_lock/{relative}"] = (source, sha256_file(source))
    return dict(sorted(result.items()))


def _artifact_kind(relative: str) -> str:
    if relative.startswith("authority/"):
        return "authority_snapshot"
    if relative.startswith("causal_frames/"):
        return "causal_endpoint_frame"
    if relative.startswith("evaluation/"):
        return "locked_evaluation"
    if relative.startswith("execution/"):
        return "market_scenario"
    if relative.startswith("descriptive/"):
        return "descriptive_analysis"
    if relative.startswith("reports/"):
        return "human_report"
    if relative == "provenance.json":
        return "provenance"
    if relative.startswith("report_inputs"):
        return "report_authority"
    raise M8L2StudyPipelineError(f"cannot classify run artifact {relative}")


def _planned_paths(
    *,
    authority_paths: Sequence[str],
    causal: Mapping[tuple[str, str, str, str], pl.DataFrame],
    heldout: Sequence[L2HeldoutEndpointFrame],
    complete: bool,
) -> tuple[str, ...]:
    paths = set(authority_paths)
    paths.update(_causal_relative(key) for key in causal)
    if complete:
        paths.update(_EVALUATION_PATHS)
        paths.update(_DESCRIPTIVE_PATHS)
        for item in heldout:
            paths.update(
                _execution_relative(item, name) for name in ("orders", "fills", "positions")
            )
        paths.update(("execution/metrics.parquet", "execution/assumptions.parquet"))
    paths.update(
        {
            "provenance.json",
            "report_inputs.json",
            "report_inputs.sha256",
            *_REPORT_PATHS,
        }
    )
    return tuple(sorted(paths))


def _development_authority_claim(material: _LockMaterial) -> dict[str, object]:
    return {
        "status": material.result.status,
        "authority_sha256": material.result.aggregate_sha256,
        "reason_codes": list(material.result.reason_codes),
    }


def _run_identity(
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    material: _LockMaterial,
    snapshots: Sequence[_SessionSnapshot],
) -> str:
    payload = {
        "schema_version": _SCHEMA_VERSION,
        "capture_config_source_sha256": capture.source_sha256,
        "analysis_config_source_sha256": analysis.source_sha256,
        "development_lock_sha256": material.result.aggregate_sha256,
        "development_authority": _development_authority_claim(material),
        "campaign": material.campaign.to_dict(),
        "source": material.source.to_dict(),
        "sessions": [
            {
                "date": item.bundle.session_date,
                "role": item.bundle.role,
                "manifest_sha256": item.authority.manifest_sha256,
                "checksums_sha256": item.authority.checksums_sha256,
            }
            for item in snapshots
        ],
    }
    encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()
    return hashlib.sha256(encoded).hexdigest()


def _provenance_payload(
    *,
    status: M8L2StudyRunStatus,
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    material: _LockMaterial,
    snapshots: Sequence[_SessionSnapshot],
    generated_at_utc: str,
    run_id: str,
) -> dict[str, object]:
    return {
        "schema_version": _SCHEMA_VERSION,
        "artifact_kind": "m8_l2_final_study_provenance",
        "status": status,
        "generated_at_utc": generated_at_utc,
        "run_id": run_id,
        "git": material.source.to_dict(),
        "runtime": runtime_metadata(),
        "inputs": {
            "capture_config_sha256": capture.hash,
            "capture_config_source_sha256": capture.source_sha256,
            "capture_protocol_sha256": M8_L2_PROTOCOL_SHA256,
            "analysis_config_sha256": analysis.hash,
            "analysis_config_source_sha256": analysis.source_sha256,
            "development_lock_sha256": material.result.aggregate_sha256,
            "development_lock_dir": str(material.result.root),
            "development_authority": _development_authority_claim(material),
            "campaign_identity": material.campaign.to_dict(),
            "sessions": [
                {
                    "date": item.bundle.session_date,
                    "role": item.bundle.role,
                    "external_bundle_path": str(item.authority.bundle_path),
                    "session_id": item.bundle.session_id,
                    "status": item.bundle.status,
                    "manifest_sha256": item.authority.manifest_sha256,
                    "checksums_sha256": item.authority.checksums_sha256,
                }
                for item in snapshots
            ],
        },
        "phase_separation": {
            "development_lock_verified_before_heldout_payload": (
                material.result.status == "LOCKED"
            ),
            "development_authority_status": material.result.status,
            "heldout_economic_payload_accessed": (
                material.result.status == "LOCKED"
                and all(item.bundle.status == "COMPLETE" for item in snapshots[2:])
            ),
            "heldout_fit_or_update_allowed": False,
            "model_updated_between_test_dates": False,
            "directory_discovery_used": False,
        },
        "claims": {
            "p_values": False,
            "significance": False,
            "cross_symbol_pooling": False,
            "capacity": False,
            "realized_execution": False,
            "profitability": False,
        },
    }


def _research_payload(capture: M8L2StudyConfig, analysis: M8L2AnalysisConfig) -> dict[str, object]:
    return {
        "question": (
            "Do frozen book-state models reduce future-mid direction log loss versus a "
            "historical prior on both untouched sessions?"
        ),
        "period_start_utc": capture.sessions[0].start.isoformat().replace("+00:00", "Z"),
        "period_end_utc": capture.sessions[-1].end.isoformat().replace("+00:00", "Z"),
        "symbols": list(capture.study.symbols),
        "endpoint_names": [item.name for item in analysis.endpoints],
    }


def _manifest_payload(
    *,
    status: M8L2StudyRunStatus,
    reason_codes: Sequence[str],
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    material: _LockMaterial,
    snapshots: Sequence[_SessionSnapshot],
    generated_at_utc: str,
    run_id: str,
    artifact_paths: Sequence[str],
    tabular_claims: Mapping[str, Mapping[str, object]],
) -> dict[str, object]:
    research = _research_payload(capture, analysis)
    return {
        "schema_version": _SCHEMA_VERSION,
        "artifact_kind": "m8_prospective_live_l2_final_study",
        "status": status,
        "reason_codes": list(reason_codes),
        "generated_at_utc": generated_at_utc,
        "run_id": run_id,
        "evidence_tier": "FULL_DATA",
        "effective_evidence_tier": ("FULL_DATA" if status == "COMPLETE" else "INSUFFICIENT_DATA"),
        "live_trading": False,
        "research": research,
        "authority": {
            "capture_config_sha256": capture.hash,
            "capture_config_source_sha256": capture.source_sha256,
            "capture_protocol_sha256": M8_L2_PROTOCOL_SHA256,
            "analysis_config_sha256": analysis.hash,
            "analysis_config_source_sha256": analysis.source_sha256,
            "development_lock_sha256": material.result.aggregate_sha256,
            "development_authority": _development_authority_claim(material),
            "campaign_identity": material.campaign.to_dict(),
            "producer_source_identity": material.source.to_dict(),
        },
        "sessions": [dict(row) for row in _session_gate_rows(snapshots)],
        "artifacts": [
            {"path": relative, "kind": _artifact_kind(relative)} for relative in artifact_paths
        ],
        "tabular_outputs": [
            {"path": relative, **dict(tabular_claims[relative])}
            for relative in sorted(tabular_claims)
        ],
        "evaluation": {
            "status": "COMPLETE" if status == "COMPLETE" else "NOT_RUN",
            "selection_roles": ["train", "validation"],
            "heldout_roles": ["primary_test", "replication_test"],
            "model_refit_after_development_lock": False,
            "p_values_computed": False,
            "cross_symbol_pooling": False,
        },
        "execution": {
            "status": "SCENARIO_ONLY" if status == "COMPLETE" else "NOT_RUN",
            "market_orders_only": True,
            "live_trading": False,
            "realized_execution": False,
            "capacity_claim_authorized": False,
            "profitability_claim_authorized": False,
        },
        "claims": {
            "p_values": False,
            "significance": False,
            "cross_symbol_pooling": False,
            "capacity": False,
            "realized_execution": False,
            "profitability": False,
        },
        "terminal_marker": {
            "path": _SUCCESS_NAME if status == "COMPLETE" else _INSUFFICIENT_NAME,
            "bytes": "complete\\n" if status == "COMPLETE" else "terminal\\n",
        },
    }


def _normalize_nonfinite(frame: pl.DataFrame) -> pl.DataFrame:
    float_columns = [name for name, dtype in frame.schema.items() if dtype.is_float()]
    if not float_columns:
        return frame
    return frame.with_columns(
        *[
            pl.when(pl.col(name).is_finite().fill_null(False))
            .then(pl.col(name))
            .otherwise(None)
            .alias(name)
            for name in float_columns
        ]
    )


def _require_finite_causal(frame: pl.DataFrame, label: str) -> None:
    for name, dtype in frame.schema.items():
        if (
            dtype.is_float()
            and frame.select((~pl.col(name).is_finite()).fill_null(False).any()).item()
        ):
            raise M8L2StudyPipelineError(f"{label} contains non-finite {name}")


def _tabular_claim(frame: pl.DataFrame) -> dict[str, object]:
    return {
        "rows": frame.height,
        "frame_sha256": _frame_sha256(frame),
        "columns": frame.columns,
    }


def _write_claimed_frame(
    stage: Path,
    relative: str,
    frame: pl.DataFrame,
    claims: dict[str, Mapping[str, object]],
    *,
    causal: bool = False,
) -> None:
    output = frame
    if causal:
        _require_finite_causal(output, relative)
    else:
        output = _normalize_nonfinite(output)
    claims[relative] = _tabular_claim(output)
    _write_parquet(_join(stage, relative), output)


def _write_complete_tabular_outputs(
    stage: Path,
    *,
    causal: Mapping[tuple[str, str, str, str], pl.DataFrame],
    heldout: Sequence[L2HeldoutEndpointFrame],
    evaluation: L2EvaluationResult,
    descriptive: L2DescriptiveAnalysis,
    references: Mapping[str, L2ExecutionReference],
) -> Mapping[str, Mapping[str, object]]:
    claims: dict[str, Mapping[str, object]] = {}
    for key in sorted(causal):
        _write_claimed_frame(stage, _causal_relative(key), causal[key], claims, causal=True)
    evaluation_frames = {
        _EVALUATION_PATHS[0]: evaluation.predictions,
        _EVALUATION_PATHS[1]: evaluation.predictive_metrics,
        _EVALUATION_PATHS[2]: evaluation.paired_by_session_regime,
        _EVALUATION_PATHS[3]: evaluation.equal_session_summary,
        _EVALUATION_PATHS[4]: evaluation.signed_markout,
    }
    for relative, frame in evaluation_frames.items():
        _write_claimed_frame(stage, relative, frame, claims)
    descriptive_frames = {
        _DESCRIPTIVE_PATHS[0]: descriptive.intraday_liquidity,
        _DESCRIPTIVE_PATHS[1]: descriptive.ofi_return_association,
        _DESCRIPTIVE_PATHS[2]: descriptive.signal_half_life,
        _DESCRIPTIVE_PATHS[3]: descriptive.liquidity_recovery,
        _DESCRIPTIVE_PATHS[4]: descriptive.regime_diagnostics,
        _DESCRIPTIVE_PATHS[5]: descriptive.feature_stability,
        _DESCRIPTIVE_PATHS[6]: descriptive.cross_instrument_stability,
    }
    for relative, frame in descriptive_frames.items():
        _write_claimed_frame(stage, relative, frame, claims)

    metric_frames: list[pl.DataFrame] = []
    assumption_frames: list[pl.DataFrame] = []
    for item in sorted(
        heldout,
        key=lambda value: (value.study_date, value.symbol, value.endpoint_name),
    ):
        coordinate_predictions = (
            evaluation.predictions.lazy()
            .filter(
                (pl.col("study_date") == item.study_date)
                & (pl.col("symbol") == item.symbol)
                & (pl.col("endpoint_name") == item.endpoint_name)
                & (pl.col("study_role") == item.study_role)
            )
            .select(*_EXECUTION_PREDICTION_COLUMNS)
            .collect()
        )
        _require_memory_budget(
            _execution_workspace_upper_bytes(item.frame, coordinate_predictions),
            _MAX_EXECUTION_WORKSPACE_BYTES,
            (
                f"{item.study_date} {item.symbol} {item.endpoint_name} "
                "execution input/Python-row/ledger admission"
            ),
        )
        projected_events = _project_frame(
            item.frame,
            _EXECUTION_EVENT_COLUMNS,
            "execution coordinate events",
        )
        coordinate_evaluation = L2EvaluationResult(
            predictions=coordinate_predictions,
            predictive_metrics=pl.DataFrame(),
            paired_by_session_regime=pl.DataFrame(),
            equal_session_summary=pl.DataFrame(),
            signed_markout=pl.DataFrame(),
        )
        execution_item = L2HeldoutEndpointFrame(
            symbol=item.symbol,
            endpoint_name=item.endpoint_name,
            study_date=item.study_date,
            study_role=item.study_role,
            frame=projected_events,
        )
        execution = run_locked_l2_market_execution(
            coordinate_evaluation,
            (execution_item,),
            (references[item.symbol],),
        )
        execution_outputs = (
            execution.orders,
            execution.fills,
            execution.positions,
            execution.metrics,
            execution.assumptions,
        )
        _require_memory_budget(
            _frames_bytes([coordinate_predictions, projected_events, *execution_outputs]),
            _MAX_EXECUTION_WORKSPACE_BYTES,
            (
                f"{item.study_date} {item.symbol} {item.endpoint_name} "
                "execution projected inputs and retained ledgers"
            ),
        )
        for name, frame in (
            ("orders", execution.orders),
            ("fills", execution.fills),
            ("positions", execution.positions),
        ):
            _write_claimed_frame(stage, _execution_relative(item, name), frame, claims)
        metric_frames.append(execution.metrics)
        assumption_frames.append(execution.assumptions)
        del (
            coordinate_predictions,
            projected_events,
            coordinate_evaluation,
            execution_item,
            execution_outputs,
            execution,
        )
    _require_memory_budget(
        _frames_bytes([*metric_frames, *assumption_frames]) * 2,
        _MAX_EXECUTION_WORKSPACE_BYTES,
        "execution metric/assumption concat admission",
    )
    metrics = _normalize_nonfinite(pl.concat(metric_frames, how="diagonal_relaxed"))
    assumptions = _normalize_nonfinite(pl.concat(assumption_frames, how="diagonal_relaxed"))
    _write_claimed_frame(stage, "execution/metrics.parquet", metrics, claims)
    _write_claimed_frame(stage, "execution/assumptions.parquet", assumptions, claims)
    return claims


def _write_insufficient_causal_outputs(
    stage: Path,
    causal: Mapping[tuple[str, str, str, str], pl.DataFrame],
) -> Mapping[str, Mapping[str, object]]:
    claims: dict[str, Mapping[str, object]] = {}
    for key in sorted(causal):
        _write_claimed_frame(stage, _causal_relative(key), causal[key], claims, causal=True)
    return claims


def _json_rows(frame: pl.DataFrame) -> tuple[Mapping[str, Any], ...]:
    normalized = _normalize_nonfinite(frame)
    rows = tuple(cast(Mapping[str, Any], row) for row in normalized.to_dicts())
    try:
        json.dumps(rows, allow_nan=False)
    except (TypeError, ValueError) as error:
        raise M8L2StudyPipelineError("report metric rows are not strict finite JSON") from error
    return rows


def _hypothesis_payload(
    status: M8L2StudyRunStatus,
    reason_codes: Sequence[str],
    evaluation: L2EvaluationResult | None,
) -> dict[str, object]:
    if status == "INSUFFICIENT_DATA":
        return {
            "status": "INSUFFICIENT_DATA",
            "conclusion": (
                "The frozen study is INSUFFICIENT_DATA and no held-out predictive or "
                f"execution conclusion is authorized. Reasons: {', '.join(reason_codes)}."
            ),
            "directionally_replicated_pairs": 0,
            "declared_pairs": 8,
        }
    assert evaluation is not None
    overall = evaluation.equal_session_summary.filter(pl.col("regime") == "ALL")
    replicated = overall.filter(pl.col("directionally_replicated")).height
    total = overall.height
    return {
        "status": "DESCRIPTIVE_COMPLETE",
        "conclusion": (
            f"Directional improvement replicated on both untouched sessions for {replicated} "
            f"of {total} symbol-endpoint pairs. This is descriptive, not a significance, "
            "capacity, realized-execution, or profitability claim."
        ),
        "directionally_replicated_pairs": replicated,
        "declared_pairs": total,
    }


def _report_data(
    *,
    manifest: Mapping[str, Any],
    provenance: Mapping[str, Any],
    snapshots: Sequence[_SessionSnapshot],
    status: M8L2StudyRunStatus,
    reason_codes: Sequence[str],
    evaluation: L2EvaluationResult | None,
    execution_metrics: pl.DataFrame | None,
) -> L2ReportData:
    paired_rows: tuple[Mapping[str, Any], ...] = ()
    equal_rows: tuple[Mapping[str, Any], ...] = ()
    predictive_rows: tuple[Mapping[str, Any], ...] = ()
    if evaluation is not None:
        predictive_rows = _json_rows(evaluation.predictive_metrics)
        paired_rows = tuple(
            {**dict(row), "status": row.get("bootstrap_status")}
            for row in _json_rows(evaluation.paired_by_session_regime)
        )
        equal_rows = tuple(
            {**dict(row), "status": row.get("replication_status")}
            for row in _json_rows(evaluation.equal_session_summary)
        )
    return L2ReportData(
        manifest=manifest,
        provenance=provenance,
        session_gates=_session_gate_rows(snapshots),
        hypothesis=_hypothesis_payload(status, reason_codes, evaluation),
        predictive_metrics=predictive_rows,
        paired_metrics=paired_rows,
        equal_session_metrics=equal_rows,
        execution_metrics=(_json_rows(execution_metrics) if execution_metrics is not None else ()),
    )


def _report_snapshot_payload(data: L2ReportData) -> dict[str, object]:
    return {
        "schema_version": _REPORT_INPUT_SCHEMA_VERSION,
        "artifact_kind": "m8_l2_verified_report_inputs",
        "report_data_sha256": canonical_report_data_sha256(data),
        "data": {
            "manifest": dict(data.manifest),
            "provenance": dict(data.provenance),
            "session_gates": [dict(row) for row in data.session_gates],
            "hypothesis": dict(data.hypothesis),
            "predictive_metrics": [dict(row) for row in data.predictive_metrics],
            "paired_metrics": [dict(row) for row in data.paired_metrics],
            "equal_session_metrics": [dict(row) for row in data.equal_session_metrics],
            "execution_metrics": [dict(row) for row in data.execution_metrics],
        },
    }


def _write_report_artifacts(stage: Path, data: L2ReportData) -> None:
    snapshot = _report_snapshot_payload(data)
    snapshot_sha = _write_json(stage / "report_inputs.json", snapshot)
    _write_bytes(stage / "report_inputs.sha256", f"{snapshot_sha}  report_inputs.json\n".encode())
    _write_bytes(
        stage / "reports" / "technical_report.md",
        render_l2_technical_report(data).encode("utf-8"),
    )
    _write_bytes(
        stage / "reports" / "executive_memo.md",
        render_l2_executive_memo(data).encode("utf-8"),
    )
    _write_bytes(
        stage / "reports" / "model_comparison.md",
        render_l2_model_comparison(data).encode("utf-8"),
    )


def _walk_regular(root: Path) -> dict[str, Path]:
    result: dict[str, Path] = {}
    pending = [root]
    while pending:
        directory = pending.pop()
        try:
            entries = sorted(os.scandir(directory), key=lambda item: item.name)
        except OSError as error:
            raise M8L2StudyPipelineError("cannot enumerate final-run inventory") from error
        for entry in entries:
            path = Path(entry.path)
            relative = _relative(path, root)
            if entry.is_symlink():
                raise M8L2StudyPipelineError(f"final-run inventory contains symlink {relative}")
            if entry.is_dir(follow_symlinks=False):
                pending.append(path)
            elif entry.is_file(follow_symlinks=False):
                result[relative] = path
            else:
                raise M8L2StudyPipelineError(
                    f"final-run inventory contains non-regular entry {relative}"
                )
    return dict(sorted(result.items()))


def _write_checksum_manifest(stage: Path, expected_paths: Sequence[str]) -> str:
    files = _walk_regular(stage)
    expected = set(expected_paths) | {"run_manifest.json"}
    if set(files) != expected:
        raise M8L2StudyPipelineError(
            "preterminal final-run inventory differs from manifest-declared artifacts "
            f"(missing={sorted(expected - set(files))}, extra={sorted(set(files) - expected)})"
        )
    raw = "".join(f"{sha256_file(path)}  {relative}\n" for relative, path in files.items()).encode(
        "ascii"
    )
    _write_bytes(stage / _CHECKSUMS_NAME, raw)
    return hashlib.sha256(raw).hexdigest()


def _parent_identity(path: Path) -> _ParentIdentity:
    metadata = path.lstat()
    if not stat.S_ISDIR(metadata.st_mode):
        raise M8L2StudyPipelineError("M8 L2 publication parent is not a directory")
    return _ParentIdentity(metadata.st_dev, metadata.st_ino)


def _reserve_stage(target: Path) -> tuple[Path, _ParentIdentity]:
    target.parent.mkdir(parents=True, exist_ok=True)
    _reject_symlink_components(target.parent)
    if target.exists() or target.is_symlink():
        raise M8L2StudyPipelineError(
            f"M8 L2 run destination already exists and is not reusable: {target}"
        )
    identity = _parent_identity(target.parent)
    stage = Path(tempfile.mkdtemp(prefix=f".{target.name}.stage-", dir=target.parent))
    if _parent_identity(stage.parent) != identity:
        shutil.rmtree(stage, ignore_errors=True)
        raise M8L2StudyPipelineError("M8 L2 publication parent changed during stage reservation")
    _fsync_directory(target.parent)
    return stage, identity


def _atomic_rename_no_replace(stage: Path, target: Path) -> None:
    """Use the platform's exclusive directory rename; never fall back to replace."""

    library = ctypes.CDLL(None, use_errno=True)
    source = os.fsencode(stage)
    destination = os.fsencode(target)
    if sys.platform == "darwin" and hasattr(library, "renameatx_np"):
        operation = library.renameatx_np
        operation.argtypes = [
            ctypes.c_int,
            ctypes.c_char_p,
            ctypes.c_int,
            ctypes.c_char_p,
            ctypes.c_uint,
        ]
        operation.restype = ctypes.c_int
        result = operation(-2, source, -2, destination, 0x00000004)  # RENAME_EXCL
    elif hasattr(library, "renameat2"):
        operation = library.renameat2
        operation.argtypes = [
            ctypes.c_int,
            ctypes.c_char_p,
            ctypes.c_int,
            ctypes.c_char_p,
            ctypes.c_uint,
        ]
        operation.restype = ctypes.c_int
        result = operation(-100, source, -100, destination, 1)  # RENAME_NOREPLACE
    else:  # pragma: no cover - supported production platforms expose one primitive
        raise M8L2StudyPipelineError(
            "platform lacks an atomic no-replace directory publication primitive"
        )
    if result != 0:
        observed_errno = ctypes.get_errno()
        if observed_errno in {errno.EEXIST, errno.ENOTEMPTY}:
            raise M8L2StudyPipelineError("M8 L2 run destination appeared during atomic publication")
        raise M8L2StudyPipelineError(f"atomic M8 L2 publication failed with errno {observed_errno}")


def _publish_stage_no_overwrite(
    stage: Path, target: Path, expected_parent: _ParentIdentity
) -> None:
    _reject_symlink_components(target.parent)
    if _parent_identity(target.parent) != expected_parent or stage.parent != target.parent:
        raise M8L2StudyPipelineError("M8 L2 publication parent identity changed")
    if target.exists() or target.is_symlink():
        raise M8L2StudyPipelineError("M8 L2 run destination appeared during atomic publication")
    _atomic_rename_no_replace(stage, target)
    if _parent_identity(target.parent) != expected_parent:
        raise M8L2StudyPipelineError("M8 L2 publication parent changed after rename")
    _fsync_directory(target.parent)


def _copy_authorities(stage: Path, sources: Mapping[str, tuple[Path, str]]) -> None:
    for relative, (source, expected_sha256) in sources.items():
        observed = _copy_exact(
            source,
            _join(stage, relative),
            expected_sha256=expected_sha256,
        )
        if observed != expected_sha256:
            raise M8L2StudyPipelineError("authority snapshot copy changed its digest")


def _terminal_revalidation(
    *,
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    train: L2StudySessionAuthority,
    validation: L2StudySessionAuthority,
    primary: L2StudySessionAuthority,
    replication: L2StudySessionAuthority,
    lock_dir: str | Path,
    lock_sha256: str,
    material: _LockMaterial,
    snapshots: Sequence[_SessionSnapshot],
    require_current_runtime: bool = False,
) -> None:
    reloaded_capture, reloaded_analysis = _revalidate_configs(capture, analysis)
    if reloaded_capture != capture or reloaded_analysis != analysis:
        raise M8L2StudyPipelineError("frozen configs changed during final production")
    _reverify_material(
        capture,
        analysis,
        train,
        validation,
        lock_dir,
        lock_sha256,
        material,
    )
    repeated = _verify_all_sessions(capture, material, (train, validation, primary, replication))
    if tuple(repeated) != tuple(snapshots):
        raise M8L2StudyPipelineError("session authorities changed during final production")
    if require_current_runtime:
        _assert_current_runtime(material.campaign)
        # This is deliberately last: after marker durability on the second
        # producer call, no authority work remains between this loaded-code
        # origin proof and the exclusive terminal-directory rename.
        _assert_final_producer_import_origins(capture.path.parent.parent.resolve())


def _publish_run(
    *,
    status: M8L2StudyRunStatus,
    reason_codes: Sequence[str],
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    train: L2StudySessionAuthority,
    validation: L2StudySessionAuthority,
    primary: L2StudySessionAuthority,
    replication: L2StudySessionAuthority,
    lock_dir: str | Path,
    lock_sha256: str,
    material: _LockMaterial,
    snapshots: Sequence[_SessionSnapshot],
    causal: Mapping[tuple[str, str, str, str], pl.DataFrame],
    heldout: Sequence[L2HeldoutEndpointFrame],
    evaluation: L2EvaluationResult | None,
    descriptive: L2DescriptiveAnalysis | None,
    run_dir: str | Path,
) -> M8L2StudyRunResult:
    target = Path(run_dir).absolute()
    stage, parent_identity = _reserve_stage(target)
    marker = stage / (_SUCCESS_NAME if status == "COMPLETE" else _INSUFFICIENT_NAME)
    published = False
    try:
        sources = _authority_sources(capture, analysis, snapshots, material)
        _copy_authorities(stage, sources)
        if status == "COMPLETE":
            if evaluation is None or descriptive is None:
                raise M8L2StudyPipelineError("complete final run lacks economic outputs")
            tabular_claims = _write_complete_tabular_outputs(
                stage,
                causal=causal,
                heldout=heldout,
                evaluation=evaluation,
                descriptive=descriptive,
                references=material.references,
            )
            execution_metrics = pl.read_parquet(stage / "execution" / "metrics.parquet")
        else:
            tabular_claims = _write_insufficient_causal_outputs(stage, causal)
            execution_metrics = None
        artifact_paths = _planned_paths(
            authority_paths=tuple(sources),
            causal=causal,
            heldout=heldout,
            complete=status == "COMPLETE",
        )
        generated_at = utc_now_iso()
        run_id = _run_identity(capture, analysis, material, snapshots)
        provenance = _provenance_payload(
            status=status,
            capture=capture,
            analysis=analysis,
            material=material,
            snapshots=snapshots,
            generated_at_utc=generated_at,
            run_id=run_id,
        )
        _write_json(stage / "provenance.json", provenance)
        manifest = _manifest_payload(
            status=status,
            reason_codes=reason_codes,
            capture=capture,
            analysis=analysis,
            material=material,
            snapshots=snapshots,
            generated_at_utc=generated_at,
            run_id=run_id,
            artifact_paths=artifact_paths,
            tabular_claims=tabular_claims,
        )
        _write_json(stage / "run_manifest.json", manifest)
        report_data = _report_data(
            manifest=manifest,
            provenance=provenance,
            snapshots=snapshots,
            status=status,
            reason_codes=reason_codes,
            evaluation=evaluation,
            execution_metrics=execution_metrics,
        )
        _write_report_artifacts(stage, report_data)
        _terminal_revalidation(
            capture=capture,
            analysis=analysis,
            train=train,
            validation=validation,
            primary=primary,
            replication=replication,
            lock_dir=lock_dir,
            lock_sha256=lock_sha256,
            material=material,
            snapshots=snapshots,
            require_current_runtime=True,
        )
        _write_checksum_manifest(stage, artifact_paths)
        _fsync_directory(stage)
        _write_bytes(marker, _SUCCESS_BYTES if status == "COMPLETE" else _INSUFFICIENT_BYTES)
        _fsync_directory(stage)
        # Checksumming and durable terminal staging can be materially slower
        # than the earlier authority check.  Revalidate every external input,
        # lock, config, and source identity again at the actual publication
        # boundary so a transient or sustained drift cannot be renamed into a
        # terminal authority.
        _terminal_revalidation(
            capture=capture,
            analysis=analysis,
            train=train,
            validation=validation,
            primary=primary,
            replication=replication,
            lock_dir=lock_dir,
            lock_sha256=lock_sha256,
            material=material,
            snapshots=snapshots,
            require_current_runtime=True,
        )
        _publish_stage_no_overwrite(stage, target, parent_identity)
        published = True
        return _verify_m8_l2_study_run(
            capture,
            analysis,
            train,
            validation,
            lock_dir,
            lock_sha256,
            primary,
            replication,
            target,
            expected_manifest_sha256=sha256_file(target / "run_manifest.json"),
            expected_checksums_sha256=sha256_file(target / _CHECKSUMS_NAME),
        )
    except BaseException:
        if not published:
            shutil.rmtree(stage, ignore_errors=True)
            _fsync_directory(target.parent)
        raise


def _reproduce_m8_l2_study(
    capture_config: M8L2StudyConfig,
    analysis_config: M8L2AnalysisConfig,
    train_session: L2StudySessionAuthority,
    validation_session: L2StudySessionAuthority,
    development_lock_dir: str | Path,
    expected_development_lock_sha256: str,
    primary_session: L2StudySessionAuthority,
    replication_session: L2StudySessionAuthority,
    run_dir: str | Path,
    *,
    expected_existing_manifest_sha256: str | None,
    expected_existing_checksums_sha256: str | None,
) -> M8L2StudyRunResult:
    _assert_final_producer_import_origins(capture_config.path.parent.parent.resolve())
    capture, analysis = _revalidate_configs(capture_config, analysis_config)
    target = Path(run_dir).absolute()
    lock_result, aggregate, campaign, source = _verify_lock_context(
        capture,
        analysis,
        train_session,
        validation_session,
        development_lock_dir,
        expected_development_lock_sha256,
    )
    _assert_current_runtime(campaign)
    if (expected_existing_manifest_sha256 is None) != (expected_existing_checksums_sha256 is None):
        raise M8L2StudyPipelineError(
            "existing-run manifest and checksum authorities must be supplied together"
        )
    if target.exists() or target.is_symlink():
        if target.is_symlink() or not target.is_dir():
            raise M8L2StudyPipelineError("existing M8 L2 run target is not a regular directory")
        terminal = [
            name for name in (_SUCCESS_NAME, _INSUFFICIENT_NAME) if (target / name).exists()
        ]
        if len(terminal) != 1:
            raise M8L2StudyPipelineError(
                "existing M8 L2 target is unterminated or has conflicting terminal markers"
            )
        if expected_existing_manifest_sha256 is None or expected_existing_checksums_sha256 is None:
            raise M8L2StudyPipelineError(
                "existing M8 L2 target requires caller-held manifest and checksum authorities"
            )
        return _verify_m8_l2_study_run(
            capture,
            analysis,
            train_session,
            validation_session,
            development_lock_dir,
            expected_development_lock_sha256,
            primary_session,
            replication_session,
            target,
            expected_manifest_sha256=expected_existing_manifest_sha256,
            expected_checksums_sha256=expected_existing_checksums_sha256,
        )
    if expected_existing_manifest_sha256 is not None:
        raise M8L2StudyPipelineError(
            "existing-run authorities were supplied but the target does not exist"
        )

    material = _load_lock_material(capture, analysis, lock_result, aggregate, campaign, source)
    snapshots = _verify_all_sessions(
        capture,
        material,
        (train_session, validation_session, primary_session, replication_session),
    )
    if getattr(getattr(material, "result", None), "status", "LOCKED") == "NOT_CREATED":
        reasons = _not_created_final_reasons(snapshots)
        if not reasons or tuple(material.result.reason_codes) != tuple(
            reason for reason in reasons if reason.startswith("DEVELOPMENT_")
        ):
            raise M8L2StudyPipelineError(
                "NOT_CREATED development reasons differ from the four-session authority"
            )
        return _publish_run(
            status="INSUFFICIENT_DATA",
            reason_codes=reasons,
            capture=capture,
            analysis=analysis,
            train=train_session,
            validation=validation_session,
            primary=primary_session,
            replication=replication_session,
            lock_dir=development_lock_dir,
            lock_sha256=expected_development_lock_sha256,
            material=material,
            snapshots=snapshots,
            causal={},
            heldout=(),
            evaluation=None,
            descriptive=None,
            run_dir=target,
        )
    heldout_failures = [item for item in snapshots[2:] if item.bundle.status != "COMPLETE"]
    if heldout_failures:
        reasons = tuple(
            sorted(
                {
                    f"{item.bundle.role}::{reason}"
                    for item in heldout_failures
                    for reason in (item.bundle.reason_codes or ("SESSION_INSUFFICIENT_DATA",))
                }
            )
        )
        return _publish_run(
            status="INSUFFICIENT_DATA",
            reason_codes=reasons,
            capture=capture,
            analysis=analysis,
            train=train_session,
            validation=validation_session,
            primary=primary_session,
            replication=replication_session,
            lock_dir=development_lock_dir,
            lock_sha256=expected_development_lock_sha256,
            material=material,
            snapshots=snapshots,
            causal={},
            heldout=(),
            evaluation=None,
            descriptive=None,
            run_dir=target,
        )

    causal, heldout = _build_causal_frames(
        capture,
        analysis,
        snapshots,
        material,
        train=train_session,
        validation=validation_session,
        lock_dir=development_lock_dir,
        lock_sha256=expected_development_lock_sha256,
    )
    availability_reasons = _heldout_availability_reasons(heldout)
    if availability_reasons:
        return _publish_run(
            status="INSUFFICIENT_DATA",
            reason_codes=availability_reasons,
            capture=capture,
            analysis=analysis,
            train=train_session,
            validation=validation_session,
            primary=primary_session,
            replication=replication_session,
            lock_dir=development_lock_dir,
            lock_sha256=expected_development_lock_sha256,
            material=material,
            snapshots=snapshots,
            causal=causal,
            heldout=heldout,
            evaluation=None,
            descriptive=None,
            run_dir=target,
        )
    _require_memory_budget(
        _evaluation_workspace_upper_bytes(
            heldout,
            feature_count=len(analysis.features.model_feature_columns),
        ),
        _MAX_EVALUATION_WORKSPACE_BYTES,
        "held-out evaluation child-frame/concat admission",
    )
    evaluation = evaluate_locked_l2_endpoints(
        tuple(material.states[key] for key in sorted(material.states)),
        heldout,
        bootstrap_samples=analysis.bootstrap.samples,
        seed=analysis.study.seed,
        calibration_bins=analysis.calibration.bins,
    )
    evaluation_frames = (
        evaluation.predictions,
        evaluation.predictive_metrics,
        evaluation.paired_by_session_regime,
        evaluation.equal_session_summary,
        evaluation.signed_markout,
    )
    _require_memory_budget(
        _frames_bytes(evaluation_frames),
        _MAX_EVALUATION_WORKSPACE_BYTES,
        "held-out evaluation retained outputs",
    )

    causal_values = tuple(causal[key] for key in sorted(causal))
    descriptive_columns = _descriptive_projection_columns(analysis.features.model_feature_columns)
    _require_memory_budget(
        _descriptive_workspace_upper_bytes(causal_values, columns=descriptive_columns),
        _MAX_DESCRIPTIVE_WORKSPACE_BYTES,
        "descriptive projection/concat/output admission",
    )
    descriptive_inputs = tuple(
        _project_frame(frame, descriptive_columns, "descriptive endpoint")
        for frame in causal_values
    )
    descriptive = build_l2_descriptive_analysis(
        descriptive_inputs,
        feature_columns=analysis.features.model_feature_columns,
        stability_bins=analysis.calibration.bins,
    )
    descriptive_outputs = (
        descriptive.intraday_liquidity,
        descriptive.ofi_return_association,
        descriptive.signal_half_life,
        descriptive.liquidity_recovery,
        descriptive.regime_diagnostics,
        descriptive.feature_stability,
        descriptive.cross_instrument_stability,
    )
    _require_memory_budget(
        _frames_bytes([*descriptive_inputs, *descriptive_outputs]),
        _MAX_DESCRIPTIVE_WORKSPACE_BYTES,
        "descriptive projected inputs and retained outputs",
    )
    del causal_values, descriptive_inputs, descriptive_outputs, evaluation_frames
    return _publish_run(
        status="COMPLETE",
        reason_codes=(),
        capture=capture,
        analysis=analysis,
        train=train_session,
        validation=validation_session,
        primary=primary_session,
        replication=replication_session,
        lock_dir=development_lock_dir,
        lock_sha256=expected_development_lock_sha256,
        material=material,
        snapshots=snapshots,
        causal=causal,
        heldout=heldout,
        evaluation=evaluation,
        descriptive=descriptive,
        run_dir=target,
    )


def _stable_file_sha256(path: Path, label: str) -> str:
    try:
        before_path = path.lstat()
    except OSError as error:
        raise M8L2StudyRunVerificationError(f"cannot stat {label}") from error
    if not stat.S_ISREG(before_path.st_mode):
        raise M8L2StudyRunVerificationError(f"{label} is not a regular file")
    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0)
    try:
        descriptor = os.open(path, flags)
    except OSError as error:
        raise M8L2StudyRunVerificationError(f"cannot securely open {label}") from error
    try:
        before = os.fstat(descriptor)
        if not _same_stat(before_path, before):
            raise M8L2StudyRunVerificationError(f"{label} changed before hashing")
        digest = hashlib.sha256()
        while chunk := os.read(descriptor, 1 << 20):
            digest.update(chunk)
        after = os.fstat(descriptor)
        after_path = path.lstat()
        if not _same_stat(before, after) or not _same_stat(after, after_path):
            raise M8L2StudyRunVerificationError(f"{label} changed while hashing")
        return digest.hexdigest()
    finally:
        os.close(descriptor)


def _report_mapping_tuple(value: object, label: str) -> tuple[Mapping[str, Any], ...]:
    if not isinstance(value, list):
        raise M8L2StudyRunVerificationError(f"{label} must be an array")
    return tuple(_mapping(item, f"{label} entry") for item in value)


def _load_report_data_snapshot(root: Path) -> L2ReportData:
    payload, raw = _read_json(root / "report_inputs.json", "L2 report-input snapshot")
    if set(payload) != {
        "schema_version",
        "artifact_kind",
        "report_data_sha256",
        "data",
    } or (
        payload.get("schema_version") != _REPORT_INPUT_SCHEMA_VERSION
        or payload.get("artifact_kind") != "m8_l2_verified_report_inputs"
    ):
        raise M8L2StudyRunVerificationError("L2 report-input snapshot schema differs")
    sidecar = _read_regular(
        root / "report_inputs.sha256",
        label="L2 report-input digest sidecar",
        maximum_bytes=256,
    )
    snapshot_sha = hashlib.sha256(raw).hexdigest()
    if sidecar != f"{snapshot_sha}  report_inputs.json\n".encode("ascii"):
        raise M8L2StudyRunVerificationError("L2 report-input digest sidecar differs")
    raw_data = _mapping(payload.get("data"), "L2 report inputs")
    if set(raw_data) != {
        "manifest",
        "provenance",
        "session_gates",
        "hypothesis",
        "predictive_metrics",
        "paired_metrics",
        "equal_session_metrics",
        "execution_metrics",
    }:
        raise M8L2StudyRunVerificationError("L2 report-input data keys differ")
    data = L2ReportData(
        manifest=_mapping(raw_data.get("manifest"), "report manifest"),
        provenance=_mapping(raw_data.get("provenance"), "report provenance"),
        session_gates=_report_mapping_tuple(raw_data.get("session_gates"), "session gates"),
        hypothesis=_mapping(raw_data.get("hypothesis"), "report hypothesis"),
        predictive_metrics=_report_mapping_tuple(
            raw_data.get("predictive_metrics"), "predictive metrics"
        ),
        paired_metrics=_report_mapping_tuple(raw_data.get("paired_metrics"), "paired metrics"),
        equal_session_metrics=_report_mapping_tuple(
            raw_data.get("equal_session_metrics"), "equal-session metrics"
        ),
        execution_metrics=_report_mapping_tuple(
            raw_data.get("execution_metrics"), "execution metrics"
        ),
    )
    if payload.get("report_data_sha256") != canonical_report_data_sha256(data):
        raise M8L2StudyRunVerificationError("L2 report inputs differ from their canonical digest")
    return data


def _verify_report_artifacts(
    root: Path,
    manifest: Mapping[str, Any],
    provenance: Mapping[str, Any],
) -> None:
    data = _load_report_data_snapshot(root)
    if dict(data.manifest) != dict(manifest) or dict(data.provenance) != dict(provenance):
        raise M8L2StudyRunVerificationError(
            "report-input snapshot differs from run manifest/provenance"
        )
    expected = {
        "reports/technical_report.md": render_l2_technical_report(data).encode("utf-8"),
        "reports/executive_memo.md": render_l2_executive_memo(data).encode("utf-8"),
        "reports/model_comparison.md": render_l2_model_comparison(data).encode("utf-8"),
    }
    for relative, raw in expected.items():
        if (
            _read_regular(
                _join(root, relative), label=f"rendered report {relative}", maximum_bytes=32 << 20
            )
            != raw
        ):
            raise M8L2StudyRunVerificationError(
                f"rendered report {relative} differs from verified machine artifacts"
            )


def _tabular_claims_from_manifest(
    manifest: Mapping[str, Any],
) -> Mapping[str, Mapping[str, Any]]:
    raw = manifest.get("tabular_outputs")
    if not isinstance(raw, list):
        raise M8L2StudyRunVerificationError("run manifest tabular_outputs must be an array")
    result: dict[str, Mapping[str, Any]] = {}
    for item in raw:
        claim = _mapping(item, "tabular output claim")
        if set(claim) != {"path", "rows", "frame_sha256", "columns"}:
            raise M8L2StudyRunVerificationError("tabular output claim keys differ")
        relative = _safe_relative(_string(claim.get("path"), "tabular output path"))
        rows = claim.get("rows")
        columns = claim.get("columns")
        digest = claim.get("frame_sha256")
        if (
            isinstance(rows, bool)
            or not isinstance(rows, int)
            or rows < 0
            or not isinstance(columns, list)
            or not all(type(value) is str for value in columns)
            or type(digest) is not str
            or not _is_sha256(digest)
            or relative in result
        ):
            raise M8L2StudyRunVerificationError("tabular output claim is malformed")
        result[relative] = claim
    if list(result) != sorted(result):
        raise M8L2StudyRunVerificationError("tabular output claims are not canonically ordered")
    return result


def _read_claimed_parquet(
    root: Path,
    relative: str,
    claim: Mapping[str, Any],
) -> pl.DataFrame:
    try:
        frame = pl.read_parquet(_join(root, relative))
    except (OSError, pl.exceptions.PolarsError) as error:
        raise M8L2StudyRunVerificationError(
            f"cannot restore claimed tabular artifact {relative}"
        ) from error
    if (
        frame.height != claim.get("rows")
        or frame.columns != claim.get("columns")
        or _frame_sha256(frame) != claim.get("frame_sha256")
    ):
        raise M8L2StudyRunVerificationError(
            f"tabular artifact {relative} differs from its semantic claim"
        )
    return frame


def _verify_one_causal_output(
    frame: pl.DataFrame,
    *,
    analysis: M8L2AnalysisConfig,
    expected_key: tuple[str, str, str, str],
) -> None:
    validate_l2_endpoint_frame(frame)
    coordinate = frame.select("study_date", "study_role", "symbol", "endpoint_name").unique()
    if coordinate.height != 1:
        raise M8L2StudyRunVerificationError("causal artifact has multiple coordinates")
    row = coordinate.row(0, named=True)
    observed_key = (
        str(row["study_date"]),
        str(row["study_role"]),
        str(row["symbol"]),
        str(row["endpoint_name"]),
    )
    if observed_key != expected_key:
        raise M8L2StudyRunVerificationError("causal artifact path/coordinate differs")
    if (
        l2_model_feature_columns(frame, windows=analysis.features.rolling_windows)
        != analysis.features.model_feature_columns
    ):
        raise M8L2StudyRunVerificationError("causal artifact feature contract differs")
    _require_finite_causal(frame, _causal_relative(expected_key))


def _verify_partition_frame(
    frame: pl.DataFrame,
    *,
    key: tuple[str, str, str, str],
    family: str,
    aggregate_lock_sha256: str,
) -> None:
    study_date, role, symbol, endpoint = key
    required = {
        "scenario_id",
        "scenario_symbol",
        "study_date",
        "study_role",
        "endpoint_name",
        "decision_latency_events",
        "order_latency_events",
        "child_lock_sha256",
        "aggregate_lock_sha256",
    }
    if not required.issubset(frame.columns):
        raise M8L2StudyRunVerificationError(f"execution {family} partition lacks authority columns")
    if frame.is_empty():
        return
    expected_values: Mapping[str, object] = {
        "scenario_symbol": symbol,
        "study_date": study_date,
        "study_role": role,
        "endpoint_name": endpoint,
        "aggregate_lock_sha256": aggregate_lock_sha256,
    }
    for column, expected in expected_values.items():
        if set(frame.get_column(column).unique().to_list()) != {expected}:
            raise M8L2StudyRunVerificationError(f"execution {family} partition coordinate differs")
    if frame.get_column("scenario_id").n_unique() > 9:
        raise M8L2StudyRunVerificationError(f"execution {family} partition has extra scenarios")
    if (
        family == "orders"
        and "order_type" in frame.columns
        and set(frame.get_column("order_type").drop_nulls().unique()).difference({"market"})
    ):
        raise M8L2StudyRunVerificationError("execution orders contain a non-market order")
    if (
        family == "fills"
        and "liquidity" in frame.columns
        and set(frame.get_column("liquidity").drop_nulls().unique()).difference({"taker"})
    ):
        raise M8L2StudyRunVerificationError("execution fills contain non-taker liquidity")


def _verify_tabular_outputs_streaming(
    root: Path,
    claims: Mapping[str, Mapping[str, Any]],
    *,
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    material: _LockMaterial,
    status: M8L2StudyRunStatus,
    reasons: Sequence[str],
) -> Mapping[str, pl.DataFrame]:
    if getattr(material.result, "status", "LOCKED") == "NOT_CREATED" and claims:
        raise M8L2StudyRunVerificationError(
            "NOT_CREATED final run must not contain economic tabular outputs"
        )
    expected_causal_keys = tuple(
        (session.date.isoformat(), session.role, symbol, endpoint.name)
        for session in capture.sessions
        for symbol in capture.study.symbols
        for endpoint in analysis.endpoints
    )
    causal_paths = {path for path in claims if path.startswith("causal_frames/")}
    expected_causal_paths = {_causal_relative(key) for key in expected_causal_keys}
    if status == "COMPLETE" and causal_paths != expected_causal_paths:
        raise M8L2StudyRunVerificationError("complete run lacks all 32 causal frames")
    if status == "INSUFFICIENT_DATA" and causal_paths and causal_paths != expected_causal_paths:
        raise M8L2StudyRunVerificationError("insufficient run has a partial causal-frame set")
    if (
        causal_paths
        and status == "INSUFFICIENT_DATA"
        and not all(reason.startswith("NO_ELIGIBLE_LABELS::") for reason in reasons)
    ):
        raise M8L2StudyRunVerificationError(
            "capture-gate insufficient run must not publish economic frames"
        )

    observed_availability_reasons: list[str] = []
    if causal_paths:
        for symbol in capture.study.symbols:
            for endpoint in analysis.endpoints:
                train_key = ("2026-08-10", "train", symbol, endpoint.name)
                validation_key = ("2026-08-11", "validation", symbol, endpoint.name)
                train_path = _causal_relative(train_key)
                validation_path = _causal_relative(validation_key)
                train_frame = _read_claimed_parquet(root, train_path, claims[train_path])
                _require_verification_memory_budget(
                    _frame_bytes(train_frame),
                    _MAX_CAUSAL_COORDINATE_BYTES,
                    "train causal verification coordinate",
                )
                _verify_one_causal_output(train_frame, analysis=analysis, expected_key=train_key)
                validation_frame = _read_claimed_parquet(
                    root, validation_path, claims[validation_path]
                )
                _require_verification_memory_budget(
                    _frame_bytes(train_frame) + _frame_bytes(validation_frame),
                    _MAX_CAUSAL_COORDINATE_BYTES,
                    "development causal verification pair",
                )
                _verify_one_causal_output(
                    validation_frame, analysis=analysis, expected_key=validation_key
                )
                development = pl.concat([train_frame, validation_frame], how="vertical")
                _require_verification_memory_budget(
                    _frame_bytes(train_frame)
                    + _frame_bytes(validation_frame)
                    + _frame_bytes(development),
                    _MAX_CAUSAL_COORDINATE_BYTES,
                    "development causal verification concat",
                )
                if (
                    _frame_sha256(development)
                    != material.development_frame_sha256[(symbol, endpoint.name)]
                ):
                    raise M8L2StudyRunVerificationError(
                        "published development causal frame differs from child lock"
                    )
                del train_frame, validation_frame, development
                for study_date, role in _EXPECTED_COORDINATES[2:]:
                    key = (study_date, role, symbol, endpoint.name)
                    relative = _causal_relative(key)
                    frame = _read_claimed_parquet(root, relative, claims[relative])
                    _require_verification_memory_budget(
                        _frame_bytes(frame),
                        _MAX_CAUSAL_COORDINATE_BYTES,
                        "held-out causal verification coordinate",
                    )
                    _verify_one_causal_output(frame, analysis=analysis, expected_key=key)
                    eligible = frame.filter(
                        pl.col("feature_ready")
                        & (~pl.col("right_censored"))
                        & pl.col("future_mid_up").is_not_null()
                    )
                    if eligible.is_empty():
                        observed_availability_reasons.append(
                            f"NO_ELIGIBLE_LABELS::{role}::{symbol}::{endpoint.name}"
                        )
                    del frame, eligible
    if status == "COMPLETE" and observed_availability_reasons:
        raise M8L2StudyRunVerificationError("complete run contains an empty held-out endpoint")
    if (
        status == "INSUFFICIENT_DATA"
        and causal_paths
        and tuple(sorted(observed_availability_reasons)) != tuple(reasons)
    ):
        raise M8L2StudyRunVerificationError(
            "insufficient reasons differ from published causal availability"
        )

    partition_paths = {path for path in claims if path.startswith("execution/partitions/")}
    expected_partition_paths: dict[str, tuple[tuple[str, str, str, str], str]] = {}
    if status == "COMPLETE":
        for study_date, role in _EXPECTED_COORDINATES[2:]:
            for symbol in capture.study.symbols:
                for endpoint in analysis.endpoints:
                    key = (study_date, role, symbol, endpoint.name)
                    for family in ("orders", "fills", "positions"):
                        relative = (
                            f"execution/partitions/{study_date}-{role}/{symbol.lower()}/"
                            f"{endpoint.name}/{family}.parquet"
                        )
                        expected_partition_paths[relative] = (key, family)
    if partition_paths != set(expected_partition_paths):
        raise M8L2StudyRunVerificationError("execution partition inventory differs")
    for relative in sorted(partition_paths):
        frame = _read_claimed_parquet(root, relative, claims[relative])
        _require_verification_memory_budget(
            _frame_bytes(frame),
            _MAX_EXECUTION_WORKSPACE_BYTES,
            "execution partition verification coordinate",
        )
        key, family = expected_partition_paths[relative]
        _verify_partition_frame(
            frame,
            key=key,
            family=family,
            aggregate_lock_sha256=material.result.aggregate_sha256,
        )
        del frame

    retained_paths = set(claims) - causal_paths - partition_paths
    retained: dict[str, pl.DataFrame] = {}
    retained_bytes = {"evaluation": 0, "descriptive": 0, "execution": 0}
    for relative in sorted(retained_paths):
        frame = _read_claimed_parquet(root, relative, claims[relative])
        category = relative.split("/", 1)[0]
        if category not in retained_bytes:
            raise M8L2StudyRunVerificationError(f"unclassified retained tabular output {relative}")
        retained_bytes[category] += _frame_bytes(frame)
        maximum = {
            "evaluation": _MAX_EVALUATION_WORKSPACE_BYTES,
            "descriptive": _MAX_DESCRIPTIVE_WORKSPACE_BYTES,
            "execution": _MAX_EXECUTION_WORKSPACE_BYTES,
        }[category]
        _require_verification_memory_budget(
            retained_bytes[category], maximum, f"retained {category} verification outputs"
        )
        retained[relative] = frame
    return retained


def _all_false(frame: pl.DataFrame, columns: Sequence[str], label: str) -> None:
    for column in columns:
        if (
            column not in frame.columns
            or frame.get_column(column).null_count()
            or bool(frame.get_column(column).any())
        ):
            raise M8L2StudyRunVerificationError(f"{label} does not keep {column}=false")


def _require_nullable_unit_interval_columns(
    frame: pl.DataFrame, columns: Sequence[str], label: str
) -> None:
    missing = sorted(set(columns).difference(frame.columns))
    if missing:
        raise M8L2StudyRunVerificationError(f"{label} lacks ratio columns: {missing}")
    for column in columns:
        dtype = frame.schema[column]
        if not (dtype.is_float() or dtype.is_integer()):
            raise M8L2StudyRunVerificationError(f"{label} {column} is not numeric")
        values = frame.get_column(column).drop_nulls().to_list()
        if any(
            not math.isfinite(float(value)) or not 0.0 <= float(value) <= 1.0 for value in values
        ):
            raise M8L2StudyRunVerificationError(
                f"{label} {column} must be null or finite in [0, 1]"
            )


def _verify_complete_semantics(
    frames: Mapping[str, pl.DataFrame],
    *,
    capture: M8L2StudyConfig,
    analysis: M8L2AnalysisConfig,
    material: _LockMaterial,
) -> None:
    expected_noncausal = (
        set(_EVALUATION_PATHS)
        | set(_DESCRIPTIVE_PATHS)
        | {
            "execution/metrics.parquet",
            "execution/assumptions.parquet",
        }
    )
    if not expected_noncausal.issubset(frames):
        raise M8L2StudyRunVerificationError("complete run lacks declared result tables")
    predictions = frames[_EVALUATION_PATHS[0]]
    required_prediction_columns = {
        "sample_id",
        "symbol",
        "study_date",
        "study_role",
        "endpoint_name",
        "is_oos",
        "split",
        "child_lock_sha256",
        "aggregate_lock_sha256",
        "test_used_for_selection",
        "model_updated_between_test_dates",
        "p_value_computed",
        "significance_claim_authorized",
    }
    if not required_prediction_columns.issubset(predictions.columns):
        raise M8L2StudyRunVerificationError("prediction artifact lacks lock/OOS boundaries")
    if (
        predictions.is_empty()
        or predictions.get_column("sample_id").n_unique() != predictions.height
        or set(predictions.get_column("study_role").unique())
        != {"primary_test", "replication_test"}
        or set(predictions.get_column("split").unique()) != {"final_test"}
        or not bool(predictions.get_column("is_oos").all())
        or set(predictions.get_column("aggregate_lock_sha256").unique())
        != {material.result.aggregate_sha256}
    ):
        raise M8L2StudyRunVerificationError("prediction artifact is not exact held-out OOS data")
    _all_false(
        predictions,
        (
            "test_used_for_selection",
            "model_updated_between_test_dates",
            "p_value_computed",
            "significance_claim_authorized",
        ),
        "prediction artifact",
    )
    for relative in (_EVALUATION_PATHS[1], _EVALUATION_PATHS[2], _EVALUATION_PATHS[3]):
        frame = frames[relative]
        _all_false(
            frame,
            ("p_value_computed", "significance_claim_authorized"),
            relative,
        )
        if "cross_symbol_pooling" in frame.columns:
            _all_false(frame, ("cross_symbol_pooling",), relative)
    metrics = frames["execution/metrics.parquet"]
    assumptions = frames["execution/assumptions.parquet"]
    expected_scenarios = 2 * len(capture.study.symbols) * len(analysis.endpoints) * 3 * 3
    if metrics.height != expected_scenarios or assumptions.height != expected_scenarios:
        raise M8L2StudyRunVerificationError("execution scenario grid is incomplete")
    if metrics.get_column("scenario_id").n_unique() != expected_scenarios:
        raise M8L2StudyRunVerificationError("execution scenario identities collide")
    _require_nullable_unit_interval_columns(
        metrics,
        ("fill_ratio", "fill_ratio_requested", "partial_fill_order_ratio"),
        "execution metrics",
    )
    _all_false(
        metrics,
        (
            "capacity_claim_authorized",
            "realized_execution_claim_authorized",
            "profitability_claim_authorized",
        ),
        "execution metrics",
    )
    _all_false(
        assumptions,
        (
            "live_trading",
            "capacity_claim_authorized",
            "realized_execution_claim_authorized",
            "profitability_claim_authorized",
        ),
        "execution assumptions",
    )
    if set(metrics.get_column("order_type").unique()) != {"market"} or not bool(
        assumptions.get_column("market_orders_only").all()
    ):
        raise M8L2StudyRunVerificationError("execution output is not market-only")


def _artifact_paths_from_manifest(manifest: Mapping[str, Any]) -> tuple[str, ...]:
    raw = manifest.get("artifacts")
    if not isinstance(raw, list):
        raise M8L2StudyRunVerificationError("run manifest artifacts must be an array")
    result: list[str] = []
    for item in raw:
        claim = _mapping(item, "run artifact claim")
        if set(claim) != {"path", "kind"}:
            raise M8L2StudyRunVerificationError("run artifact claim keys differ")
        relative = _safe_relative(_string(claim.get("path"), "run artifact path"))
        if claim.get("kind") != _artifact_kind(relative):
            raise M8L2StudyRunVerificationError("run artifact kind differs from its path")
        result.append(relative)
    if result != sorted(set(result)):
        raise M8L2StudyRunVerificationError("run artifact paths are duplicate or unordered")
    return tuple(result)


def _reverify_internal_terminal_snapshot(
    root: Path,
    *,
    root_identity: _ParentIdentity,
    initial_files: Mapping[str, Path],
    terminal_name: str,
    terminal_bytes: bytes,
    checksums_raw: bytes,
    checksums: Mapping[str, str],
) -> None:
    """Rebind every internal byte after semantic and external verification.

    The first pass supports semantic parsing.  This second stable-descriptor pass
    occurs at the return boundary so an artifact changed after its semantic read
    cannot inherit the earlier verification result.
    """

    try:
        _reject_symlink_components(root)
        before = root.lstat()
    except (M8L2StudyPipelineError, OSError) as error:
        raise M8L2StudyRunVerificationError(
            "final M8 L2 run path changed before return-boundary verification"
        ) from error
    if (
        not stat.S_ISDIR(before.st_mode)
        or _ParentIdentity(before.st_dev, before.st_ino) != root_identity
    ):
        raise M8L2StudyRunVerificationError(
            "final M8 L2 run directory identity changed before return"
        )
    observed_files = _walk_regular(root)
    if set(observed_files) != set(initial_files):
        raise M8L2StudyRunVerificationError(
            "final-run inventory changed after semantic verification"
        )
    if (
        _read_regular(
            root / terminal_name,
            label="return-boundary terminal marker",
            maximum_bytes=32,
        )
        != terminal_bytes
    ):
        raise M8L2StudyRunVerificationError(
            "final-run terminal marker changed after semantic verification"
        )
    if (
        _read_regular(
            root / _CHECKSUMS_NAME,
            label="return-boundary checksums",
            maximum_bytes=16 << 20,
        )
        != checksums_raw
    ):
        raise M8L2StudyRunVerificationError(
            "final-run checksums changed after semantic verification"
        )
    for relative, expected_digest in checksums.items():
        if _stable_file_sha256(_join(root, relative), f"return-boundary {relative}") != (
            expected_digest
        ):
            raise M8L2StudyRunVerificationError(
                f"final-run artifact changed after semantic verification: {relative}"
            )
    try:
        after = root.lstat()
    except OSError as error:
        raise M8L2StudyRunVerificationError(
            "final M8 L2 run path disappeared before verification returned"
        ) from error
    if (
        not stat.S_ISDIR(after.st_mode)
        or _ParentIdentity(after.st_dev, after.st_ino) != root_identity
    ):
        raise M8L2StudyRunVerificationError(
            "final M8 L2 run directory identity changed at verification return"
        )


def _verify_m8_l2_study_run(
    capture_config: M8L2StudyConfig,
    analysis_config: M8L2AnalysisConfig,
    train_session: L2StudySessionAuthority,
    validation_session: L2StudySessionAuthority,
    development_lock_dir: str | Path,
    expected_development_lock_sha256: str,
    primary_session: L2StudySessionAuthority,
    replication_session: L2StudySessionAuthority,
    run_dir: str | Path,
    *,
    expected_manifest_sha256: str | None = None,
    expected_checksums_sha256: str | None = None,
) -> M8L2StudyRunResult:
    capture, analysis = _revalidate_configs(capture_config, analysis_config)
    if expected_manifest_sha256 is not None:
        _require_sha256(expected_manifest_sha256, "expected final-run manifest")
    if expected_checksums_sha256 is not None:
        _require_sha256(expected_checksums_sha256, "expected final-run checksums")
    lock_result, aggregate, campaign, source = _verify_lock_context(
        capture,
        analysis,
        train_session,
        validation_session,
        development_lock_dir,
        expected_development_lock_sha256,
    )
    material = _load_lock_material(capture, analysis, lock_result, aggregate, campaign, source)
    snapshots = _verify_all_sessions(
        capture,
        material,
        (train_session, validation_session, primary_session, replication_session),
    )
    for snapshot in snapshots[2:]:
        if material.result.status == "LOCKED" and snapshot.bundle.status == "COMPLETE":
            _reverify_material(
                capture,
                analysis,
                train_session,
                validation_session,
                development_lock_dir,
                expected_development_lock_sha256,
                material,
            )
            _heldout_input(
                snapshot,
                capture=capture,
                campaign=material.campaign,
                lock_sha256=expected_development_lock_sha256,
            )

    root = Path(run_dir).absolute()
    try:
        _reject_symlink_components(root)
    except M8L2StudyPipelineError as error:
        raise M8L2StudyRunVerificationError(
            "final M8 L2 run path contains an unsafe component"
        ) from error
    try:
        metadata = root.lstat()
    except OSError as error:
        raise M8L2StudyRunVerificationError("final M8 L2 run directory is unavailable") from error
    if not stat.S_ISDIR(metadata.st_mode):
        raise M8L2StudyRunVerificationError("final M8 L2 run must be a regular directory")
    root_identity = _ParentIdentity(metadata.st_dev, metadata.st_ino)
    files = _walk_regular(root)
    terminal_names = [name for name in (_SUCCESS_NAME, _INSUFFICIENT_NAME) if name in files]
    if len(terminal_names) != 1:
        raise M8L2StudyRunVerificationError("final M8 L2 run requires exactly one terminal marker")
    terminal_name = terminal_names[0]
    marker_path = root / terminal_name
    expected_marker_bytes = (
        _SUCCESS_BYTES if terminal_name == _SUCCESS_NAME else _INSUFFICIENT_BYTES
    )
    if (
        _read_regular(marker_path, label="final M8 L2 terminal marker", maximum_bytes=32)
        != expected_marker_bytes
    ):
        raise M8L2StudyRunVerificationError("final M8 L2 terminal marker bytes differ")
    if _CHECKSUMS_NAME not in files or "run_manifest.json" not in files:
        raise M8L2StudyRunVerificationError("final M8 L2 run lacks control authorities")
    checksums_raw = _read_regular(
        root / _CHECKSUMS_NAME,
        label="final M8 L2 checksums",
        maximum_bytes=16 << 20,
    )
    checksums_sha = hashlib.sha256(checksums_raw).hexdigest()
    if expected_checksums_sha256 is not None and checksums_sha != expected_checksums_sha256:
        raise M8L2StudyRunVerificationError("final-run checksums differ from caller authority")
    checksums = _parse_checksums(checksums_raw, "final M8 L2 checksums")
    expected_inventory = set(checksums) | {_CHECKSUMS_NAME, terminal_name}
    if set(files) != expected_inventory:
        raise M8L2StudyRunVerificationError(
            "final-run physical inventory differs from checksums "
            f"(missing={sorted(expected_inventory - set(files))}, "
            f"extra={sorted(set(files) - expected_inventory)})"
        )
    for relative, expected_digest in checksums.items():
        if _stable_file_sha256(_join(root, relative), relative) != expected_digest:
            raise M8L2StudyRunVerificationError(f"final-run checksum mismatch for {relative}")

    manifest, manifest_raw = _read_json(root / "run_manifest.json", "final-run manifest")
    manifest_sha = hashlib.sha256(manifest_raw).hexdigest()
    if expected_manifest_sha256 is not None and manifest_sha != expected_manifest_sha256:
        raise M8L2StudyRunVerificationError("final-run manifest differs from caller authority")
    if checksums.get("run_manifest.json") != manifest_sha:
        raise M8L2StudyRunVerificationError("final-run checksums do not bind the manifest")
    expected_manifest_keys = {
        "schema_version",
        "artifact_kind",
        "status",
        "reason_codes",
        "generated_at_utc",
        "run_id",
        "evidence_tier",
        "effective_evidence_tier",
        "live_trading",
        "research",
        "authority",
        "sessions",
        "artifacts",
        "tabular_outputs",
        "evaluation",
        "execution",
        "claims",
        "terminal_marker",
    }
    if set(manifest) != expected_manifest_keys:
        raise M8L2StudyRunVerificationError("final-run manifest keys differ")
    status_raw = manifest.get("status")
    if status_raw not in {"COMPLETE", "INSUFFICIENT_DATA"}:
        raise M8L2StudyRunVerificationError("final-run status is unsupported")
    status = cast(M8L2StudyRunStatus, status_raw)
    expected_terminal = _SUCCESS_NAME if status == "COMPLETE" else _INSUFFICIENT_NAME
    expected_terminal_claim = {
        "path": expected_terminal,
        "bytes": "complete\\n" if status == "COMPLETE" else "terminal\\n",
    }
    if (
        terminal_name != expected_terminal
        or manifest.get("terminal_marker") != expected_terminal_claim
    ):
        raise M8L2StudyRunVerificationError("final-run status and terminal marker disagree")
    raw_reasons = manifest.get("reason_codes")
    if not isinstance(raw_reasons, list) or not all(type(item) is str for item in raw_reasons):
        raise M8L2StudyRunVerificationError("final-run reason codes must be strings")
    reasons = tuple(cast(list[str], raw_reasons))
    if list(reasons) != sorted(set(reasons)) or (status == "COMPLETE") == bool(reasons):
        raise M8L2StudyRunVerificationError("final-run reason/status boundary is inconsistent")
    if (
        manifest.get("schema_version") != _SCHEMA_VERSION
        or manifest.get("artifact_kind") != "m8_prospective_live_l2_final_study"
        or manifest.get("evidence_tier") != "FULL_DATA"
        or manifest.get("effective_evidence_tier")
        != ("FULL_DATA" if status == "COMPLETE" else "INSUFFICIENT_DATA")
        or manifest.get("live_trading") is not False
    ):
        raise M8L2StudyRunVerificationError("final-run evidence boundary differs")

    run_id = _run_identity(capture, analysis, material, snapshots)
    if manifest.get("run_id") != run_id:
        raise M8L2StudyRunVerificationError("final-run deterministic identity differs")
    authority = _mapping(manifest.get("authority"), "final-run authority")
    expected_authority = {
        "capture_config_sha256": capture.hash,
        "capture_config_source_sha256": capture.source_sha256,
        "capture_protocol_sha256": M8_L2_PROTOCOL_SHA256,
        "analysis_config_sha256": analysis.hash,
        "analysis_config_source_sha256": analysis.source_sha256,
        "development_lock_sha256": material.result.aggregate_sha256,
        "development_authority": _development_authority_claim(material),
        "campaign_identity": material.campaign.to_dict(),
        "producer_source_identity": material.source.to_dict(),
    }
    if dict(authority) != expected_authority:
        raise M8L2StudyRunVerificationError("final-run authority differs from external evidence")
    if manifest.get("sessions") != [dict(row) for row in _session_gate_rows(snapshots)]:
        raise M8L2StudyRunVerificationError("final-run session claims differ from external bundles")
    if status == "COMPLETE" and any(item.bundle.status != "COMPLETE" for item in snapshots):
        raise M8L2StudyRunVerificationError("complete run contains an insufficient session")
    if status == "INSUFFICIENT_DATA":
        if material.result.status == "NOT_CREATED":
            if reasons != _not_created_final_reasons(snapshots):
                raise M8L2StudyRunVerificationError(
                    "NOT_CREATED final reasons differ from all session authorities"
                )
        else:
            session_reasons = {
                f"{item.bundle.role}::{reason}"
                for item in snapshots[2:]
                if item.bundle.status != "COMPLETE"
                for reason in (item.bundle.reason_codes or ("SESSION_INSUFFICIENT_DATA",))
            }
            if session_reasons:
                if set(reasons) != session_reasons:
                    raise M8L2StudyRunVerificationError(
                        "insufficient reasons differ from held-out capture gates"
                    )
            elif not all(reason.startswith("NO_ELIGIBLE_LABELS::") for reason in reasons):
                raise M8L2StudyRunVerificationError(
                    "insufficient final run lacks a typed data-availability boundary"
                )

    provenance, provenance_raw = _read_json(root / "provenance.json", "final-run provenance")
    if _canonical_json_bytes(cast(Mapping[str, object], provenance)) != provenance_raw:
        raise M8L2StudyRunVerificationError("final-run provenance is not canonical JSON")
    generated_at = _string(manifest.get("generated_at_utc"), "manifest generation time")
    expected_provenance = _provenance_payload(
        status=status,
        capture=capture,
        analysis=analysis,
        material=material,
        snapshots=snapshots,
        generated_at_utc=generated_at,
        run_id=run_id,
    )
    if provenance != expected_provenance:
        raise M8L2StudyRunVerificationError("final-run provenance differs from exact authorities")

    artifact_paths = _artifact_paths_from_manifest(manifest)
    if set(artifact_paths) != set(checksums) - {"run_manifest.json"}:
        raise M8L2StudyRunVerificationError(
            "manifest-declared artifacts differ from checksum inventory"
        )
    authority_sources = _authority_sources(capture, analysis, snapshots, material)
    if set(authority_sources) != {path for path in artifact_paths if path.startswith("authority/")}:
        raise M8L2StudyRunVerificationError("self-contained authority snapshot set differs")
    for relative, (external, expected_digest) in authority_sources.items():
        if (
            _stable_file_sha256(external, f"external {relative}") != expected_digest
            or _stable_file_sha256(_join(root, relative), relative) != expected_digest
        ):
            raise M8L2StudyRunVerificationError(
                f"self-contained authority snapshot changed for {relative}"
            )

    tabular_claims = _tabular_claims_from_manifest(manifest)
    expected_parquets = {
        path
        for path in artifact_paths
        if path.endswith(".parquet") and not path.startswith("authority/")
    }
    if set(tabular_claims) != expected_parquets:
        raise M8L2StudyRunVerificationError(
            "tabular semantic claims differ from declared Parquet artifacts"
        )
    frames = _verify_tabular_outputs_streaming(
        root,
        tabular_claims,
        capture=capture,
        analysis=analysis,
        material=material,
        status=status,
        reasons=reasons,
    )
    if status == "COMPLETE":
        _verify_complete_semantics(
            frames,
            capture=capture,
            analysis=analysis,
            material=material,
        )
    elif any(
        path.startswith(("evaluation/", "execution/", "descriptive/")) for path in tabular_claims
    ):
        raise M8L2StudyRunVerificationError(
            "insufficient final run improperly contains promoted economic results"
        )
    _verify_report_artifacts(root, manifest, provenance)
    report_data = _load_report_data_snapshot(root)
    if tuple(dict(row) for row in report_data.session_gates) != tuple(
        dict(row) for row in _session_gate_rows(snapshots)
    ):
        raise M8L2StudyRunVerificationError("report session gates differ from external evidence")
    _terminal_revalidation(
        capture=capture,
        analysis=analysis,
        train=train_session,
        validation=validation_session,
        primary=primary_session,
        replication=replication_session,
        lock_dir=development_lock_dir,
        lock_sha256=expected_development_lock_sha256,
        material=material,
        snapshots=snapshots,
    )
    _reverify_internal_terminal_snapshot(
        root,
        root_identity=root_identity,
        initial_files=files,
        terminal_name=terminal_name,
        terminal_bytes=expected_marker_bytes,
        checksums_raw=checksums_raw,
        checksums=checksums,
    )
    return M8L2StudyRunResult(
        root=root,
        status=status,
        manifest_path=root / "run_manifest.json",
        manifest_sha256=manifest_sha,
        checksum_path=root / _CHECKSUMS_NAME,
        checksum_sha256=checksums_sha,
        marker_path=marker_path,
        reason_codes=reasons,
    )


__all__ = [
    "L2StudySessionAuthority",
    "M8L2StudyPipelineError",
    "M8L2StudyRunResult",
    "M8L2StudyRunStatus",
    "M8L2StudyRunVerificationError",
    "load_m8_l2_report_data",
    "reproduce_m8_l2_study",
    "verify_m8_l2_study_run",
]