File size: 273,062 Bytes
c4f91a4
196f3aa
ec5da4b
5b9f5a4
 
 
378131e
196f3aa
c4f91a4
 
5b9f5a4
 
196f3aa
 
cc02077
196f3aa
4529577
 
196f3aa
 
760ed06
370e5d0
 
 
 
 
 
 
196f3aa
cc02077
 
bbc317b
 
eb1f478
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
cc02077
 
 
 
 
370e5d0
 
 
cc02077
 
 
 
 
196f3aa
 
cc02077
 
 
 
 
 
 
 
 
 
 
196f3aa
cc02077
 
 
196f3aa
cc02077
 
4529577
a47e6ef
 
196f3aa
eb1f478
 
 
 
 
 
 
cc02077
eb1f478
 
 
 
196f3aa
370e5d0
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
c4f91a4
 
 
 
 
 
196f3aa
 
 
 
 
 
 
cc02077
196f3aa
 
 
 
 
c4f91a4
 
 
cc02077
 
 
196f3aa
cc02077
196f3aa
c4f91a4
 
cc02077
f3d92a2
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
760ed06
 
 
196f3aa
f3d92a2
 
 
 
cc02077
 
 
 
 
 
 
 
a47e6ef
 
 
 
 
f3d92a2
196f3aa
 
 
 
4529577
 
 
 
 
196f3aa
 
 
 
 
c4f91a4
5b9f5a4
 
4529577
 
5b9f5a4
 
 
 
 
a47e6ef
4529577
 
 
5b9f5a4
 
 
 
 
 
 
a47e6ef
 
370e5d0
cc02077
 
 
 
 
 
 
 
 
 
370e5d0
 
cc02077
bbc317b
196f3aa
 
370e5d0
 
 
196f3aa
 
 
 
 
 
 
 
 
c4f91a4
 
 
4529577
 
 
 
 
 
 
 
 
 
 
c4f91a4
370e5d0
 
 
92df43e
 
cc02077
 
92df43e
50ee98d
f6053c3
 
 
196f3aa
eb1f478
 
 
 
c17887c
c4f91a4
 
196f3aa
 
 
 
 
 
 
c4f91a4
 
4529577
 
 
196f3aa
 
 
 
 
 
 
c4f91a4
 
5b9f5a4
 
c4f91a4
 
 
5b9f5a4
 
c4f91a4
 
4529577
 
 
196f3aa
5b9f5a4
 
 
 
 
 
 
 
 
 
196f3aa
 
 
4529577
 
196f3aa
 
 
 
13a5b61
 
196f3aa
 
 
cc02077
 
13a5b61
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4529577
 
 
 
13a5b61
370e5d0
 
5b9f5a4
 
 
 
13a5b61
4529577
cc02077
 
370e5d0
5b9f5a4
 
 
 
 
13a5b61
 
 
cc02077
13a5b61
 
cc02077
5b9f5a4
 
 
13a5b61
 
 
 
 
 
196f3aa
cc02077
eb1f478
 
ec5da4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
92df43e
c4f91a4
4529577
c4f91a4
 
 
 
5b9f5a4
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
4529577
c4f91a4
 
4529577
 
 
 
 
 
92df43e
cc02077
4529577
c4f91a4
4529577
 
0ee184c
5b9f5a4
 
 
c4f91a4
 
 
196f3aa
 
cc02077
 
 
 
135ad7c
 
 
cc02077
 
 
370e5d0
 
 
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
 
 
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
5b9f5a4
 
 
 
 
13a5b61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc317b
 
196f3aa
 
c4f91a4
196f3aa
 
 
cc02077
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
196f3aa
cc02077
 
196f3aa
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135ad7c
 
 
 
 
 
 
370e5d0
 
135ad7c
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
bbc317b
 
 
 
f6053c3
 
 
cc02077
92df43e
 
 
bbc317b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6053c3
bbc317b
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
eb1f478
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
bbc317b
 
 
 
 
c4f91a4
bbc317b
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
 
 
cc02077
 
 
 
eb1f478
cc02077
 
 
 
eb1f478
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc317b
 
196f3aa
bbc317b
eb1f478
 
 
196f3aa
 
 
 
 
 
 
 
cc02077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
370e5d0
 
 
196f3aa
 
 
 
370e5d0
 
 
 
196f3aa
370e5d0
 
 
 
196f3aa
370e5d0
 
 
 
 
135ad7c
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
760ed06
 
 
196f3aa
 
 
 
 
 
760ed06
 
196f3aa
 
 
760ed06
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
13a5b61
cc02077
13a5b61
 
 
 
cc02077
 
c4f91a4
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
760ed06
 
cc02077
 
 
c4f91a4
 
 
 
 
 
 
 
 
cc02077
 
 
 
c4f91a4
cc02077
 
 
 
c4f91a4
cc02077
370e5d0
cc02077
 
 
370e5d0
cc02077
 
 
 
 
 
 
 
196f3aa
 
370e5d0
760ed06
 
cc02077
 
370e5d0
cc02077
 
196f3aa
bbc317b
cc02077
 
 
135ad7c
370e5d0
cc02077
196f3aa
 
 
 
 
760ed06
196f3aa
 
 
 
 
 
 
370e5d0
 
196f3aa
 
 
 
 
 
760ed06
196f3aa
 
 
760ed06
cc02077
370e5d0
 
cc02077
370e5d0
 
 
196f3aa
 
 
370e5d0
 
196f3aa
 
370e5d0
 
 
 
 
196f3aa
 
cc02077
370e5d0
 
 
cc02077
196f3aa
 
370e5d0
 
cc02077
 
 
 
 
 
370e5d0
 
 
cc02077
 
 
370e5d0
cc02077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370e5d0
cc02077
 
 
 
 
 
 
 
 
 
370e5d0
cc02077
 
 
 
 
 
 
 
370e5d0
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
760ed06
196f3aa
760ed06
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760ed06
 
 
 
 
 
 
 
 
 
cc02077
 
760ed06
 
196f3aa
 
 
 
 
 
 
cc02077
 
196f3aa
 
135ad7c
 
 
 
370e5d0
 
135ad7c
370e5d0
 
cc02077
196f3aa
 
bbc317b
cc02077
 
370e5d0
 
cc02077
 
196f3aa
 
 
 
 
 
 
135ad7c
cc02077
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13a5b61
196f3aa
13a5b61
 
196f3aa
 
 
 
 
 
 
 
 
 
13a5b61
196f3aa
 
13a5b61
 
 
 
 
 
 
196f3aa
 
 
 
 
13a5b61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
cc02077
 
196f3aa
 
 
 
 
cc02077
 
c4f91a4
 
370e5d0
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
bbc317b
 
 
cc02077
bbc317b
 
370e5d0
 
 
 
bbc317b
 
13a5b61
 
370e5d0
 
 
196f3aa
370e5d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13a5b61
cc02077
 
bbc317b
 
 
370e5d0
bbc317b
 
 
50ee98d
bbc317b
 
370e5d0
 
bbc317b
 
196f3aa
370e5d0
 
 
5b9f5a4
 
 
 
 
370e5d0
 
 
5b9f5a4
 
 
 
 
196f3aa
eb1f478
 
196f3aa
 
cc02077
eb1f478
370e5d0
 
 
 
 
 
cc02077
13a5b61
 
370e5d0
 
 
 
 
 
 
 
196f3aa
 
 
bbc317b
196f3aa
 
 
 
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370e5d0
 
 
 
 
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370e5d0
 
 
 
5b9f5a4
370e5d0
 
5b9f5a4
 
370e5d0
5b9f5a4
 
370e5d0
 
 
5b9f5a4
 
 
 
 
 
 
 
370e5d0
5b9f5a4
370e5d0
 
 
 
 
 
 
 
 
 
5b9f5a4
370e5d0
 
 
 
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
370e5d0
 
 
 
 
 
135ad7c
370e5d0
135ad7c
 
 
370e5d0
 
 
 
 
135ad7c
370e5d0
 
 
 
 
196f3aa
13a5b61
cc02077
196f3aa
 
cc02077
13a5b61
cc02077
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
cc02077
 
196f3aa
 
ec5da4b
 
 
 
 
196f3aa
 
ec5da4b
c4f91a4
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
5b9f5a4
c4f91a4
196f3aa
 
 
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
ec5da4b
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
c4f91a4
 
196f3aa
 
 
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4529577
196f3aa
 
4529577
 
 
 
 
 
 
5b9f5a4
4529577
 
 
 
 
196f3aa
4529577
196f3aa
 
4529577
 
 
196f3aa
4529577
 
 
 
 
196f3aa
4529577
 
196f3aa
 
 
 
 
 
 
4529577
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
4529577
 
 
196f3aa
 
4529577
598450c
 
 
 
196f3aa
 
4529577
 
 
 
 
 
196f3aa
4529577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
4529577
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
196f3aa
 
 
c4f91a4
5b9f5a4
c4f91a4
196f3aa
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
92df43e
 
196f3aa
 
 
 
 
 
 
 
 
 
 
5b9f5a4
196f3aa
c4f91a4
 
 
 
5b9f5a4
 
c4f91a4
 
 
 
196f3aa
 
 
c4f91a4
196f3aa
c4f91a4
196f3aa
c4f91a4
 
196f3aa
 
5b9f5a4
 
 
 
 
196f3aa
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
c4f91a4
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
196f3aa
760ed06
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
4529577
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
4529577
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
196f3aa
c4f91a4
196f3aa
 
760ed06
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
4529577
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
4529577
 
 
 
 
 
c4f91a4
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
4529577
 
 
 
c4f91a4
4529577
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4529577
c4f91a4
4529577
c4f91a4
 
 
4529577
 
 
c4f91a4
4529577
c4f91a4
4529577
 
c4f91a4
4529577
 
 
 
 
 
 
 
196f3aa
4529577
c4f91a4
4529577
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
196f3aa
 
 
760ed06
 
 
 
 
 
 
 
c4f91a4
760ed06
c4f91a4
760ed06
 
c4f91a4
760ed06
 
c4f91a4
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4529577
 
 
 
 
 
c4f91a4
4529577
 
 
 
c4f91a4
196f3aa
4529577
 
 
 
 
 
c4f91a4
 
4529577
 
 
 
 
 
c4f91a4
 
 
4529577
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4529577
c4f91a4
4529577
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17887c
196f3aa
c17887c
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
4529577
 
c4f91a4
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
196f3aa
c4f91a4
 
 
 
4529577
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4529577
c4f91a4
4529577
 
 
 
 
 
 
 
 
196f3aa
 
eb1f478
 
 
 
 
 
 
 
 
4529577
eb1f478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
cc02077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc02077
 
196f3aa
 
 
 
 
 
 
 
 
cc02077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc02077
196f3aa
cc02077
eb1f478
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
598450c
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
cc02077
196f3aa
 
 
 
 
 
 
 
92df43e
 
 
 
196f3aa
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
13a5b61
 
c4f91a4
 
196f3aa
cc02077
 
4529577
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
760ed06
 
 
13a5b61
cc02077
 
c4f91a4
cc02077
 
 
 
f3d92a2
 
cc02077
 
a47e6ef
 
 
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
c4f91a4
370e5d0
5b9f5a4
 
 
 
196f3aa
370e5d0
 
 
196f3aa
cc02077
 
 
196f3aa
 
 
eb1f478
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
370e5d0
 
 
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
5b9f5a4
196f3aa
 
 
4529577
 
196f3aa
 
 
13a5b61
5b9f5a4
4529577
 
13a5b61
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
f3d92a2
 
 
 
 
 
 
 
 
 
4529577
 
196f3aa
 
 
 
cc02077
 
196f3aa
 
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4529577
 
 
 
 
 
 
 
 
 
5b9f5a4
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
 
 
370e5d0
eb1f478
 
cc02077
370e5d0
 
196f3aa
 
 
 
 
cc02077
196f3aa
 
 
 
370e5d0
cc02077
196f3aa
cc02077
196f3aa
eb1f478
 
196f3aa
 
 
cc02077
eb1f478
 
196f3aa
 
 
 
 
eb1f478
 
196f3aa
 
 
 
 
 
760ed06
 
cc02077
196f3aa
 
 
 
 
 
 
 
cc02077
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
ec5da4b
5b9f5a4
4529577
 
196f3aa
c4f91a4
5b9f5a4
196f3aa
ec5da4b
 
 
c4f91a4
760ed06
cc02077
 
196f3aa
 
13a5b61
cc02077
13a5b61
196f3aa
 
 
370e5d0
 
 
c4f91a4
196f3aa
 
760ed06
370e5d0
 
 
 
 
 
 
c4f91a4
13a5b61
 
196f3aa
 
 
ec5da4b
196f3aa
 
 
 
 
ec5da4b
196f3aa
 
 
 
 
 
eb1f478
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
4529577
 
 
 
196f3aa
 
cc02077
 
5b9f5a4
 
 
 
196f3aa
cc02077
 
370e5d0
 
 
 
 
 
 
c4f91a4
196f3aa
 
13a5b61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc02077
 
 
 
 
13a5b61
 
 
370e5d0
 
 
 
 
 
 
13a5b61
 
 
 
370e5d0
 
196f3aa
 
 
eb1f478
196f3aa
 
370e5d0
 
135ad7c
 
370e5d0
 
 
 
 
 
 
 
 
5b9f5a4
 
 
 
370e5d0
 
 
13a5b61
370e5d0
 
 
 
 
 
 
 
 
135ad7c
370e5d0
13a5b61
 
 
cc02077
 
 
 
 
5b9f5a4
 
 
196f3aa
 
cc02077
 
 
 
 
5b9f5a4
 
cc02077
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc02077
4529577
 
196f3aa
13a5b61
196f3aa
 
 
 
 
 
 
13a5b61
cc02077
 
 
c4f91a4
 
 
ec5da4b
4529577
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
cc02077
196f3aa
cc02077
 
196f3aa
 
 
 
 
 
 
cc02077
13a5b61
c4f91a4
 
 
 
196f3aa
 
 
 
 
c4f91a4
cc02077
 
5b9f5a4
 
 
 
4529577
 
196f3aa
c4f91a4
196f3aa
 
4529577
cc02077
4529577
 
 
 
 
c4f91a4
 
196f3aa
5b9f5a4
196f3aa
 
 
4529577
 
5b9f5a4
 
 
 
 
cc02077
196f3aa
 
 
 
5b9f5a4
 
 
cc02077
5b9f5a4
196f3aa
cc02077
13a5b61
196f3aa
 
5b9f5a4
 
196f3aa
 
 
 
 
 
 
a47e6ef
 
 
 
 
196f3aa
 
4529577
196f3aa
a47e6ef
 
4529577
 
 
cc02077
196f3aa
 
 
a47e6ef
 
 
 
 
 
 
 
cc02077
 
13a5b61
 
cc02077
370e5d0
cc02077
 
 
 
 
 
 
5b9f5a4
cc02077
5b9f5a4
 
 
 
 
cc02077
 
 
5b9f5a4
cc02077
 
 
 
 
13a5b61
 
5b9f5a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
13a5b61
 
 
 
 
 
 
 
cc02077
 
 
 
 
4529577
 
cc02077
 
4529577
cc02077
 
 
 
13a5b61
 
cc02077
13a5b61
4529577
 
 
196f3aa
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
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
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["duckdb>=1.4", "zstandard", "huggingface_hub>=2.0", "requests[socks]", "fsspec[http]", "py7zr",
#                 "warcio", "boto3", "tqdm", "werkzeug", "pypdf[crypto]"]
# [tool.uv]
# exclude-newer = "2026-11-11T00:00:00Z"
# ///
"""Select rows of the Agentic Env Index, download the files they point to and check them against their rows.

One command, no setup (uv reads the dependencies from the block above; the copy a release publishes fixes them at that
release, see Requirements):

    uv run https://huggingface.co/datasets/Battam/agentic-env-index/resolve/main/tools/fetch.py \\
        --domain D3 --form spreadsheets --sample 3 --out ./data

or, with Python 3.10 or newer: pip install the packages of the block above, then python fetch.py with the same
options.

The index is a set of Parquet tables (one row per downloadable item). The script first resolves the sources
you name (by --source, --kind, --domain, --form or --tag) from meta/catalog.parquet, then reads only those sources'
data files (with --limit or --sample, only as many of them as the units taken need, see --sample below) and only
their rows of the tables under meta/, applies the default profile (below) and your own conditions, rebuilds each
selected row into a full pointer with meta/sources.json, downloads the item and checks it against what the row
records. Before downloading it prints how many units the selection had (with --limit or --sample, in the data files
read) and how many each criterion of the profile removed; a selection that ends empty says which criterion emptied
it. A source, kind, domain or form name that the catalog does not have stops the run with one line naming the
closest names (exit code 2).

Default profile (the criteria the task builders apply, each with its own option; --all turns off all of them except the
two benchmark criteria, benchmark and not compared, which only their own options turn off):
  duplicate       a duplicate copy of another row of the selection: the same content
                  or natural key, judged over the rows the other criteria keep       --keep-duplicates
  benchmark       matched a benchmark: a copy of benchmark data (meta/bench_overlap.parquet)
                  or a row of a collection awaiting a ruling (meta/bench_checked.parquet,
                  scope container); --allow-benchmark also keeps the next one         --allow-benchmark
  not compared    not compared with the benchmark list yet: the row's data file is not
                  listed as compared in meta/bench_checked.parquet                    --allow-not-compared
  license         the license does not let the files be shipped: the row's training
                  tier must be yes and its redistribution tier yes or conditional (the
                  rule of the catalog column license.ship)                            --any-license
  language        the row records a natural language (source_meta.language or
                  source_meta.labels.language, as an ISO 639 code) and it is not English
                  or zxx (no linguistic content); rows that record none are kept      --any-language
  personal data   the catalog's pii.level of the source is present or suspected, the
                  row's sensitive column is set, or the row's pool fields mark it
                  pseudonymous or identifiable                                        --allow-personal-data
  size            the recorded size is above 20 MB (20,000,000 bytes); rows of unknown
                  size are kept and their download stops at 20 MB                    --any-size
A unit is a group of files that the upstream publishes as one thing, delivered whole; its key is unit_id: for the rows
that share a unit_group (source_meta.unit_group: a test case, one workbook, one package), that unit_group; for a row of
its own, the row's natural key written as its uri, then @<range_offset> when it is a byte range, then !/<member_path>
when it is an archive member. unit_id is unique within a source. A row of a collection without a unit_group (the
README.md and LICENSE the index writes for a source) is a file of the source, not of a unit: it comes with the first
unit taken from that source (with --limit or --sample, when a data file read holds it). A unit is removed when any of
its files fails a criterion. Each criterion is reported with its own count and reason (benchmark and not compared
apart) and names the option that keeps what it removed.
--ext chooses units, not files: a unit is in the selection when one of its files has one of the extensions given,
and it comes with all its files and its source's files. --unit UNIT_ID chooses one unit by its unit_id (as
_meta/manifest.jsonl gives it), whole, with its source's files; with --source it names the same unit in every release
that has it. The line that starts the fetch, printed before the first download, counts the units and files taken and
their total size (the sizes their rows record; the files whose rows record none are counted apart).

Output (--out DIR):
  DIR/<domain>/<source>/<unit folder>/<file>
                                   the files of one unit, one folder per unit (a single-file unit too); <domain> is
                                   the row's pool_domain when it has one (such as D3_data), else the top-level code of
                                   the source's first domain in meta/catalog.parquet (such as D3); <unit folder> is
                                   unit_folder(unit_id), a file-system-safe name that stays the same on every run (the
                                   last part of unit_id cleaned by werkzeug's secure_filename, a hyphen and the first
                                   12 hex digits of the sha256 of unit_id); <file> is the file's path within its unit:
                                   the part of its path (pool_path, else <collection>/<the rest of its pointer_id>)
                                   under the unit_group when the path lies under it, the file name for a single-file
                                   unit, else the whole path
  DIR/<domain>/<source>/<path>     the source's own files (README.md, LICENSE), at their pool_path
  DIR/_meta/manifest.jsonl         one line per file on disk: source, path (relative to DIR), url, sha256, bytes,
                                   spdx, licence_url, publisher, retrieved, origin_kind, leaf, unit_id (null for a file
                                   of the source) and verified (true when the sha256 matched the one the index records,
                                   false when the index records none and it was computed)
  DIR/_meta/sizes.tsv              one line per source, no header: leaf, source, origin, bytes, spdx
  DIR/_meta/fetch_manifest.jsonl   one line per selected row and run, with its status, unit_id and the row's full
                                   pointer (pointer) (appended, never rewritten)
  DIR/_meta/fetch_run.json         repository, commit, arguments, date and summary of the last run
  DIR/_meta/selection.json         the selection file of the last run (see --selection below; #2337: with --inbox it
                                   goes there and not here)
Running again into the same DIR keeps what is there: files already present with the right size and sha256 are
not downloaded again, and manifest.jsonl and sizes.tsv are rewritten to cover every file of every run.

Units stored inside another file: a row of a collection whose unit is a member of a container (a zip or tar
archive) or is stored compressed or encoded points at that upstream file and lists in source_meta.transform the
steps that make the unit (unzip:<member>, untar:<member>, gunzip, bunzip2, unxz, unxxd, uudecode, uncompress,
gzip). The upstream file is downloaded and checked against the row, the unit is made out of it and checked against
the unit's recorded hash (source_meta.unit_sha256, or content_sha256 when the last step is gzip), and only the unit
is written, at the unit's place; its manifest line says extracted and keeps the upstream file's size and sha256
(upstream_bytes, upstream_sha256). A unit that does not match fails and the upstream file is kept as <name>.stale.
The steps run in transform.py, taken from next to this script or else from tools/ of the index at the commit read
(or of the local --data copy). A unit marked expand (an archive meant to be used as a folder) is delivered as the
archive; tools/to_pool.py unpacks it (python to_pool.py DIR --out ./pools --name <name>).

--sample N takes N units per selected source, the same ones on every run, so a category can be tried within a few MB;
--limit N takes N units over the whole selection (with --sample, N of the units --sample takes), from the selected
sources in turn (#2144): the first unit of each source, then the second of each, and so on, the sources of one turn in
the order of the sha256 of their names, so that a sample of a few hundred units spreads over the sources (when
--limit took the first units of one order over the whole selection, a run over 39 sources read the files of 15 of them
and took 115 of its 200 units from one). Both take each source's units in a fixed order of two stages (#2035): first
the sha256 of the path of the data file that holds the unit (the path the catalog's column data_files names, such as
data/npm/all/part-00060.parquet), then within that file the unit's key, the sha256 of its source and unit_group, or
of its row's natural key (source, uri, range_offset, member_path). The run reads each source's data files in that
order, whole files before their rows, a round of files at a time and only as far as these units need: --limit takes
the sources' files in turn as well (the first file of each source, then the second of each, the sources of one turn
in the same order), a round reading the next files of one turn, as many as units are still missing, until the files
read hold N units that pass your conditions and the default profile (with --sample, each source counting up to its
sample), and takes the N in turn from those; --sample alone reads the next file of each source that has fewer such
units than its sample. So a file is read only when the units of the files before it were not enough (--kind corpus
--limit 1 reads the first file of the source whose turn comes first, not the whole layer), and a source whose files
hold no unit that passes is read one file a turn, as every other. The criteria are judged over the rows of the files
read: a duplicate copy that only a file not read holds does not count, and a source's own files (README.md, LICENSE)
come when a file read holds them. The run prints how many of the selection's data files it read and in how long. The
same command at the same revision reads the same files and takes the same units.

What is checked: a row with hashes has its size (when known) and every hash checked whose algorithm the
script knows (crc32, md5, sha1, sha256, sha512, git_blob_sha1; a single-part S3 ETag, an md5, is compared where the row records
one); a hash under any other name is not checked and is listed in the manifest field unchecked_hashes. Some sources publish no
hash; such a row has its size checked when the size is known, and its manifest line says checked "size only"
and carries the sha256 computed on download (unverified says so). A row with neither a hash nor a size is
downloaded within the cap and only its sha256 is computed (manifest fields size_unknown and unverified).
Rolling files (files the source regenerates in place, such as the lichess puzzle and evaluation databases,
or a row whose source_meta has rolling set) carry no hash and their size changes between the index and the
download: a size that differs is not a failure, the manifest line says checked "rolling file, size changed"
with the size the row records in expected_bytes, and the download may grow up to the cap. A row that sets
source_meta.rolling and also carries hashes is checked as usual, but a size or hash that differs is not a
failure either: the manifest line keeps the bytes and sha256 actually downloaded, sets differs_from_index
with the recorded values in expected_bytes and expected_sha256, and every such line carries the download
date in retrieved.

Rows built from a selection file (a collection tag campaign:<name>) carry their place in a task pool in
source_meta (pool_domain, pool_leaf, pool_path, unit_group, origin_kind, pool_fields and the
others in CAMPAIGN_KEYS); the layout above follows them, and fetch_manifest.jsonl copies them as they are. Some
of these rows point at small files kept in the index repository itself (uri campaign_files/...); such a uri is
read from the same commit as the tables (or from the local --data copy), and the manifests record it as its absolute
URL at that commit (https://huggingface.co/datasets/<repo>/resolve/<commit>/campaign_files/...; for a local copy, at
--revision, else at main).

Examples:

    python fetch.py --domain D3 --form spreadsheets --sample 3 --out ./data
    python fetch.py --source uk-government-workbooks --unit workbooks/ukgov-uk-community-renewal-fund-index-model.xlsx
    python fetch.py --source apache-arrow-testing --limit 10
    python fetch.py --domain D1.6 --form test-suites --ext csv --limit 50 --out ./files
    python fetch.py --source pypi --tier yes --max-size 1000000 --limit 20
    python fetch.py --tag campaign:<name> --all --out ./collection
    python fetch.py --data ./local-copy --where "media_type = 'application/pdf'" --limit 5
    python fetch.py --source govdocs1-files --ext pdf --limit 20 --check-content --out ./govdocs
    python fetch.py --revision <commit> --domain D1.6 --limit 50
    python fetch.py --selection agentic-env-selection-<commit>.json --sample 3 --out ./data

Domains and forms: meta/catalog.parquet gives every source a domain and a form. The domain is a list of codes:
D1 to D10 are the subject areas and D<n>.<m> their leaves (D1.6 is a leaf of D1); multi marks content that spans
many domains (such as a forum or a web archive) and unclassified a source not classified yet. The form is one id
of lower-case words joined by "-" (such as test-suites or forums) and says what kind of material the source is.
--domain CODE selects the sources with a domain entry equal to CODE or, for a top-level code, any of its leaves
(D3 matches D3 and D3.5; D3.5 matches only D3.5); multi and unclassified match only themselves. --form ID
selects the sources of that form. Both options can be repeated (a source matches any of the values given);
given together, a source must match both, and with --source only the named sources that also match are read.
When no source matches, nothing is selected and the run says so. A code, form or source name that no source of
the catalog has is an error (exit code 2) naming the closest names. The domain codes and the forms are described
in catalog/domains.yaml of the pipeline repository and in the README of the index. Revisions of the index older
than these columns have no form column: --form then stops with an error and names that problem.
--tag campaign:<name> selects the rows of one collection (meta/tags.parquet, read only when --tag is given).
--kind KIND selects the sources of one layer, those whose kind in meta/catalog.parquet is KIND (the values that
column holds: material_set or corpus); it can be repeated (a source matches any of the values given) and is one
more condition next to --domain and --form, so --kind material_set --domain D3 takes the material sets of D3.

--selection FILE reads a selection file saved by the data page (Get the data): JSON with the ids of the sources
("sources"), the commit of the index ("revision") and the page's filters ("filters", a record only). Its sources are
read as --source options and its revision as --revision, so the same file selects the same sources at the same commit
later. A --revision given as well must name the same commit; a file that lists no source is an error.
Every run writes such a file for its own selection, _meta/selection.json (#1909), in the same format (format
agentic-env-selection/1, dataset, revision, filters, sources) with the sample count added: the sources the run read
(sources), the commit it read (revision), the options of SELECTION_OPTIONS it was given that choose its rows (filters,
by option name with _ for -: where, ext, tier, limit, the profile's switches as true and the others) and its --sample
(sample, null without one). --selection reads its sources and revision as above; artpool admit takes the file as
candidates of the material sets' admission and chooses the same rows again with --selection, the filters and the
sample (selection_argv), and a file this script read as a byte range, a record, an API body or an archive member
enters with the pointer of its line of _meta/fetch_manifest.jsonl.
#2337: --inbox DEST writes that file into DEST in place of _meta/selection.json: DEST is a folder given as an rclone
path (remote:path), and the file goes there by rclone rcat as selection-<the first 16 hex digits of its sha256>.json,
so a file written there is never written over. DEST is meant to be a line's folder pool_<line> of the inbox the index's
admission takes its candidates from; rclone must be on PATH, signed in to DEST by its own environment (such as the
managed identity of the machine it runs on). The summary gives the path written under inbox.

The repository gets new commits every day. Reading the index from the Hub (the default, hf://datasets/...)
reads every table at one commit (hf://datasets/<repo>@<commit>/...), so a long query is not split across an
update. --revision <commit> names that commit, so the same command selects the same rows later; a tag or
branch name is also accepted and is resolved to its commit through the Hub API (with --print-sql it is
pinned as given). Without it the script reads the release it was published in (RELEASE, the release tag
written into tools/fetch.py when the index is published), so a command names the release once, in the
script's URL; a copy with no release written (run from the code repository) asks the Hub API for the commit
the main branch points to now. Either way it prints the commit on stderr and writes it into every manifest
line, the summary and fetch_run.json (field revision). If the current commit cannot
be read, the script prints one warning line and reads the main branch (revision is then empty). A --data
root that already names a revision (@...) is read as given; --revision cannot be combined with it. With a
local --data copy (or a URL prefix that is not hf://datasets/...) --revision only records which commit that
copy holds: the value is written as given into the manifest lines, the summary and
fetch_run.json, and are not checked against the Hub.

Requirements: Python 3.10 or newer and the packages of the block above: duckdb reads the index (#2177: 1.4 or newer,
whose own HTTP log counts the requests it sends, hub_requests), huggingface_hub
resolves the index commit and the hf:// addresses, requests (with urllib3 and PySocks) downloads, fsspec reads
archives on a server by byte ranges, py7zr reads 7z archives, warcio reads WARC and ARC records, boto3 signs
requester-pays S3 requests, zstandard serves --decompress of .zst, tqdm shows the progress line and the sizes, and pypdf
reads PDFs for --check-content (its crypto extra, cryptography, decrypts the AES-encrypted ones that open without a
password, as a PDF viewer opens them). The copy published with a release (#2144) adds to the block a tool.uv table
with exclude-newer, the start (00:00 UTC) of the day its release tag names: uv run then takes every package at the
versions uploaded before that release, the same on every run of it, also with --no-config. pip does not read the
table; uv pip install --exclude-newer with that time installs the same versions. #2337: --inbox needs rclone on PATH.

Standard tool: downloads by requests (retries by urllib3 Retry, SOCKS by requests[socks]); seekable remote files by
fsspec's HTTPFile and huggingface_hub's HfFileSystem; archives by zipfile, tarfile and py7zr; WARC and ARC records by
warcio; requester-pays S3 GETs by boto3; the scanned-PDF check's fonts and text by pypdf, AES-encrypted PDFs decrypted
by cryptography (pypdf's crypto extra); the progress line and short sizes by tqdm (format_sizeof); the terminal check
by isatty; unit folder names by werkzeug's secure_filename; the units of --limit and --sample by whole data files
before their rows, in a fixed hash order so that the sample repeats (a block sample, as DuckDB's system sampling takes
whole vectors: https://duckdb.org/docs/2.0/sql/query_syntax/samples.html), each file read by DuckDB (read_units), and
the turns of --limit by DuckDB (row_number() over each source's units, pick_steps); the dependencies of a release's
copy fixed at that release by uv's exclude-newer in the inline script metadata
(https://docs.astral.sh/uv/guides/scripts/, selecting.fetch_tool_text); #2337: the selection file written to a remote
folder (--inbox) by rclone rcat (https://rclone.org/commands/rclone_rcat/).
none for the fallback over a row's addresses
(_fetch_one) and the run's package cache (download_package) (searched: https://tenacity.readthedocs.io/en/latest/,
https://pypi.org/project/backoff/, https://urllib3.readthedocs.io/en/stable/reference/urllib3.util.html,
https://www.fatiando.org/pooch/latest/, https://filesystem-spec.readthedocs.io/en/latest/features.html): the retries
of one request are urllib3 Retry's; tenacity and backoff retry one call, not the next address of a list; pooch and
fsspec's cache cannot use this script's requests session (SOCKS proxy, User-Agent, requester-pays signing) nor stop at
the size cap.

What is read: meta/catalog.parquet (one row per source) first; then, for the sources it resolves, exactly the data
files its column data_files names for them (with --tag, only the files its column batch_files names for the batches
that carry the tags, and of those only their rows), one read per file and no listing of data/, keeping each source's
rows by their column source (a file may hold rows of several sources; a revision whose catalog has no column
data_files, older than it, is not read: older_catalog), and only their rows of meta/batches.parquet,
meta/bench_overlap.parquet and meta/bench_checked.parquet (these tables are sorted by
source, so a filtered read over HTTP touches few of their row groups), and
meta/sources.json. meta/tags.parquet is read only with --tag. Those reads run in parallel; a selection whose
sources hold at most LOCAL_ROWS rows by the catalog is copied into memory once, a larger one is read in place.
With --limit or --sample the data files are read a round at a time and only as far as the units need (--sample
above): a small selection copies each round into memory, a larger one reads each round in place and then again only
the files that hold the rows taken.

Memory: DuckDB may use at most --memory-limit (default: the smaller of 4GB and a quarter of the machine's
memory) and writes what does not fit into a spill directory, --temp-dir or else a folder .fetch_spill under
--out that is removed at the end. Spill files are capped at 100GB by default; DUCKDB_MAX_TEMP changes that
limit. DuckDB runs one thread per GB of the memory limit (at least one, at most the number of CPUs;
--threads sets it). The rows are first picked with only the columns the conditions read, then copied
whole to the spill directory and sorted in parts of at most a quarter of the limit each, so a selection
larger than the limit spills to disk instead of failing. Raise --memory-limit when a large selection runs
slowly because it spills.

Ways of fetching that the script supports (the unit column of meta/sources.json says which one a source uses):
whole files over HTTP(S) (s3:// and hf:// addresses are turned into their public HTTPS form); byte ranges
(HTTP Range, the server must answer 206); WARC or ARC records (the range is one gzip member: warcio reads it,
the WARC and HTTP headers are removed and the payload hash is checked); members of zip archives (zipfile reads
the central directory and the member over a seekable file of HTTP byte ranges, then checks size and CRC32);
API responses (the body field is taken from the JSON response). Members of packages: wheels, jars and other
zip files the same way; sdists, npm .tgz and .crate files by downloading the whole package (within the cap;
kept in a temporary directory for the run) and taking the member out; members of 7z archives by py7zr over the
same seekable file (a solid block is decoded from its start up to the member, within the cap). A server that
answers a byte-range request with the whole file fails the row. Members of tar archives stored as gzip (the
arXiv source bundles): the range is one gzip member, decompressed and checked against the CRC32 and length of
its trailer. Single lichess games (rows with a game id): the public export API; rows without a game id are
fetched as the files they point to.

The duplicate criterion has no table: it is resolved here, over your own selection (with --limit or --sample, over the
rows of the data files read), after every other criterion (DuckDB window functions over the rows the others keep, so
the copy kept is one you get). A snapshot holds one
row per natural key (source, uri, range_offset, member_path); a revision written before that may hold more, and
of those only the newest version is kept, by collection time: the latest batch, then the latest part file of the
batch (part files are numbered in the order they are written; such a revision wrote a corrected row into a new part
file while its old version stayed), and its manifest line says
natural_key_conflict; the older versions leave the selection, so
they do not remove their unit; rows of a superseded snapshot are removed; of
rows with the same sha256, sha1 or md5 (md5 with the same size) one copy is kept, the first by the source's
registry order, then source, batch and place. A selection of one source keeps its rows whose copy is in another
source. The benchmark criterion: rows
found in public benchmark tasks (meta/bench_overlap.parquet, hit classes benchmark_copy, task_file and
data_address, by row or by whole collection) and rows of collections awaiting a ruling are removed as matched a
benchmark; rows whose data file is not listed in meta/bench_checked.parquet as compared are removed apart, as not
compared with the benchmark list yet (--allow-not-compared keeps them; every published data file is compared at
every release, so a file not listed belongs to an older revision of the index, or the release has not compared
it yet). Truncated rows and empty files stay in.

Sizes and caps: a cap applies only when fetching, it never removes a row from the selection. By default every
row has the overall cap (meta/size_caps.json: the 99th percentile of the sizes of all benchmark task files), and
under the profile also at most 20 MB; --max-size N uses N bytes for every row instead. To leave large rows out of
the selection, the size criterion does it at 20 MB and --max-size-filter N at N bytes (rows of unknown size stay
for both). A row whose known size is above its cap is not downloaded; a row of unknown size (manifest field
size_unknown) is downloaded until the cap. Both are recorded with status too_large, which is not a failure.
--decompress also decompresses .gz, .bz2 and .zst files within the cap. A downloaded file that turns out to be a
Git LFS pointer (a small text file naming the real object) is refused as failed.

Requester-pays buckets (such as the arXiv source bundles on S3) are charged to your own AWS account: set
AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (and AWS_SESSION_TOKEN for temporary credentials). boto3 signs
those requests (get_object with RequestPayer requester); the script contains no credentials. Without them such
rows are skipped with the reason.

Rows that need a login, a form or an access request (field access.needs_auth of the full pointer, for example
guestbook, restricted, gated or kaggle_token) are skipped: no request is sent, the manifest line has status
skipped, the reason and the needs_auth value. Embargoed rows are skipped until the date in
access.embargo_until and fetched from that day on. Requester-pays rows are fetched when the AWS credentials
above are set. The summary printed at the end counts the skipped rows by value (needs_auth_skipped). Any
other address form is reported as unsupported.

Content check (--check-content): after a verified download (and after --decompress) each file gets three
checks, recorded in the manifest field content_check. scanned_pdf: a PDF whose first five pages set text in no
font and hold fewer than 20 characters of text per page (both read by pypdf), most likely a scanned image.
error_page: an HTML, XML or plain text file whose title names an error (404, not found, access denied and
the like), or whose text is under 3000 characters and names one in its first 1500 characters. ext_mismatch:
the type that file --mime-type reports is not one of the types expected for the extension. Each check is
flagged, clean, not_applicable or skipped; a check is skipped when what it needs (the file command, or the
pypdf package of the block above) is not installed or fails on the file, and the reason is written in
content_check.skipped. A flagged or skipped check is not a failure and never changes the status.

Connection errors, HTTP 429 and 5xx answers are retried by urllib3 (3 more tries, waiting 2, 4 and 8 seconds,
or as long as a Retry-After header asks). A download whose size or hash does not match its row fails; the next
address of the row is then tried.

Pages that block scripts (#2144): a server that answers a download with an HTML page (Content-Type text/html or
application/xhtml+xml) where the row records its file as not HTML (by its ext, or its media_type; the extensions of
pages a server makes, such as php, count as HTML), the page's bytes failing the row's check, blocks scripts such as
this one: a bot check or a sign-in page stands where the file was (on 2026-11-09 dataverse.nl answered every file of
dataversenl-workbooks-cc0 with a bot check of 2,289 bytes, title "Oh noes!"). Such a row fails, with the row's check
in reason as for any other; its manifest line adds html_page (the page's content type and title), its per-file line
says that the upstream blocks scripts, and the end of the run names each such source on stderr with how many of its
files came back as a page, as does the summary (blocked). Such files can be downloaded in a web browser from the url
of their manifest lines.

Where files go: every file is written under --out, in the layout above. The domain, source, collection and
path parts are cleaned the same way; a row whose path would still land outside --out is not written and gets
status unsafe_path (the run goes on). file:// addresses are not fetched; to use a local copy pass --data.
Downloads, decompression of responses, WARC and gzip members, archives and 7z blocks all stop at the cap.
AWS signatures are sent only to S3, by boto3.

Running again with the same --out: a file already there whose size and sha256 match its row is recorded ok
without downloading it (already_present); a partly downloaded file (.part) is resumed with a Range request
and started over when the server answers with the whole file. _meta/fetch_manifest.jsonl is appended to, never
overwritten; each line carries run_id (the start time of its run), and the summary names this run's run_id with
the DuckDB query that lists its lines that are not ok. A line records the size and sha256 the
row expects (expected_size, expected_sha256) and, on failure, what was downloaded (got_bytes, got_sha256); a
file that was already at the destination of a failed row is renamed to <name>.stale (stale_path).

The files of a unit are fetched together (they share its place in the fetch order). A unit some of whose files are
not fetched is named on the line incomplete at the end of the run; the files fetched are kept.

Local reuse: with --local-root DIR (repeatable; or the ARTPOOL_LOCAL_ROOTS variable, directories separated by
':') and --staging DIR (or ARTPOOL_STAGING, where a file fetched elsewhere was placed), a whole file whose size
and every published hash match its row is copied from there with no request; the manifest line records
obtained: reused or staged and local_path, and every other row obtained: fetched. A local file of the same name
or size whose hashes do not match is never used and is reported on stderr. The run ends with the line
"local reuse: N reused, N staged, N fetched, N refused" on stderr and local_reuse in the summary.
No request is made for a reused or staged file, so its line keeps the provenance of the original fetch of the
same sha256: retrieved (the day the bytes were obtained from upstream), fetched_from, fetched_at, route and
provenance_record (where it was read). A reused file takes the earliest dated record among the fetch manifests
(fetch_manifest.jsonl: retrieved, else the date of run_id) and pool manifests (_meta/manifest.jsonl) under the
local roots; a staged file takes the line of staging_attempts.jsonl that the staging step (artpool.stage_receive)
wrote when it streamed the file in. With no such record retrieved is "unknown" and retrieved_reason says why; it
is never the date of this run, which is recorded apart as reused_at (UTC, YYYY-MM-DDTHH:MM:SSZ).

Network: --proxy URL (or the HTTPS_PROXY, HTTP_PROXY and ALL_PROXY variables) sends every request through a
proxy (socks5:// and socks5h:// through requests' PySocks). The DuckDB read of the index uses the same HTTP
proxy; DuckDB cannot use a SOCKS proxy, so with one read a local copy of the index (--data). Archive members
read by byte ranges go through fsspec, which has no SOCKS client: with a SOCKS proxy such rows fail with the
reason. --contact TEXT adds your contact (an email or URL) to the User-Agent, as some APIs ask.
Progress on stderr (--quiet turns it off): while the index is read and the selection planned, tqdm progress lines
(the tables read of the total, then the planning steps done of the total, or with --limit or --sample the data files
read of the selection's, with the time elapsed, redrawn every
second on a terminal and every minute in a log, so a read that waits on a rate limit is not silent); before the first
download, one line per selected source with what the run takes of it (#1525, #2144): its units, their files, the
source's own files (README.md, LICENSE, its companion files) and the size their rows record, then the line that starts
the fetch with the total (printed with --quiet too); while
fetching, on a terminal, one tqdm progress line, then one line per
file (status, source, path and size in short units such as 1.7 kB) sorted by source and path; otherwise one such
line per file as each finishes, so a log keeps its timing.
Before fetching, a run also names each selected source some or all of whose sampled rows read did not fetch, with its
fetch check (the catalog column fetch_check: how many of its sampled rows read fetched and matched their record, and
the day read): its upstream may not serve the files now (such bytes fail the row's check and are not kept). Only the
readings of the release read count (#2144): those of the day its tag names or later (the tag of --revision, else
RELEASE, the tag of the release this copy was published in; with neither, no reading counts). An older reading says
nothing of what the upstream serves for this release and is left out: release-2026-11-09.2 named two sources from
readings five days old, whose files fetched, and not the one whose upstream had started to block scripts since.

The run ends on stdout with its summary. On a terminal it is a few lines in words: how many files were fetched
and checked, their total size, where they were written and that the details are in _meta/fetch_run.json; the
files of units and the source's own files by status; this run's run_id with its counts by status;
and, when some line is not ok, the DuckDB query that lists those lines of _meta/fetch_manifest.jsonl. With --json,
or when stdout is not a terminal (a pipe, a file, an agent's tool call), it is one JSON object (also the field
summary of fetch_run.json) with the same: counts, files (by unit and source, then status), run_id and
not_ok_query, blocked ({source: {files, title}}, the sources whose upstream answered files with an HTML page), and
(#2177) requests: the requests the run sent to the Hub ({resolver, api, other}, the classes Hugging Face counts them
under: resolver a file's bytes by its /resolve/ URL, api its API), which a run reading the Hub also prints on stderr.

Hugging Face token: the index tables are read from the Hub with the token in HF_TOKEN (a DuckDB huggingface secret;
it overrides a token stored on the machine). Without it they are read anonymously, and the run says so once at the
start: Hugging Face allows an anonymous address fewer requests per 5 minutes than a signed-in user, and once they
are used up it answers 429 and each read waits and retries (HTTP_SETTINGS). A read token is made at
https://huggingface.co/settings/tokens.

The manifest status is one of ok, failed, too_large, skipped, unsafe_path, unsupported. The exit code is 1 when some
row failed or had an unsafe path, and 2 when the index could not be read or a source, domain or form name is not
in the catalog (the message says why).

Deletes: <dest>.part of a download (fetch_file), on an error that cannot resume, past the size cap or failing the
  row's check: a temporary file fetch_file wrote; the download is fetched again from the row's url.
Deletes: the package directory fetch-packages-* (tempfile.mkdtemp, download_package) and its files, one per package
  url named by the first 24 hex digits of the url's sha256, at the end of the run, on a failed download or when the
  package cache passes its cap: temporary files download_package wrote; a package is fetched again from its url.
Deletes: <output>.part of a decompression (decompress_file): a temporary file decompress_file wrote.
Deletes: <upstream file>.unit of extract_unit, when the unit cannot be made or does not match the index: a temporary
  file extract_unit wrote with the transform steps.
Deletes: the compressed file of a row fetched with status ok, once decompress_file has written its decompressed
  file: recomputable, downloaded again from the row's url by fetch_unit, which checks it against the row.
Deletes: <dest>.part of a local reuse copy whose bytes changed while copied (LocalFiles.take): a temporary file take
  wrote, copied from the local file.
Deletes: a download that is a Git LFS pointer file (fetch_one): recomputable, downloaded again from the row's url.
Deletes: the spill directory .fetch_spill under --out at the end of the run (not a --temp-dir one): DuckDB's
  temporary files of this run.
"""

from __future__ import annotations

import argparse
import bz2
import copy
import csv
import datetime
import functools
import gzip
import hashlib
import io
import json
import logging
import os
import posixpath
import re
import shutil
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import zlib
import zipfile
from pathlib import Path

import requests
import urllib3
from requests.adapters import HTTPAdapter
from urllib3.util import Retry
from warcio.archiveiterator import ArchiveIterator
from warcio.bufferedreaders import ChunkedDataReader
from werkzeug.http import parse_content_range_header
from werkzeug.utils import secure_filename

DEFAULT_REPO = "Battam/agentic-env-index"
# the release tag this copy was published in, the default --revision; the projection writes it into tools/fetch.py
# (selecting.fetch_tool_text), and a copy with none written reads the main branch
RELEASE = "release-2026-11-11.6"
# #2144: a release tag (artpool.release_tag.TAG_RE), release-<YYYY-MM-DD>.<n>: the day of the release, from which on a
# fetch check reading is the release's own (release_day, fetch_note)
RELEASE_TAG_RE = re.compile(r"release-(\d{4}-\d{2}-\d{2})\.[1-9][0-9]*")
TIERS = ("yes", "conditional", "no", "unknown")
# hit classes of meta/bench_overlap.parquet that the default filter removes
OVERLAP_REMOVE = ("benchmark_copy", "task_file", "data_address")
# meta/catalog.parquet: one row per source with its domain codes (list) and its form (--domain, --form)
CATALOG = "meta/catalog.parquet"
# the catalog column that names, for each source, the repository paths of the data files that hold its rows; the rows
# are read from exactly those files, so no request lists the folders of data/ (Hugging Face counts every listing and
# every file read against an address's requests per 5 minutes)
DATA_FILES = "data_files"
# the folder of the repository that holds the data files (the catalog's column data_files names them under it); a
# data file's name in the tables is its path under it (row_file)
DATA_DIR = "data/"
# the catalog column that names, for each batch of a source, the data files that hold its rows ([{batch, file}]): with
# --tag only the files of the tagged batches are read
BATCH_FILES = "batch_files"
# #2006: the catalog column of the fetch check (#1577: level, rows, fetched, read_at; catalog_table), and its name in
# release-2026-11-09.1, fetch, a reserved word of DuckDB's parser, read quoted until a release with fetch_check is
# published
FETCH_CHECK, FETCH_CHECK_OLD = "fetch_check", "fetch"
# a revision whose catalog has no column data_files (older than #1746) names none of its data files, so it is not read:
# the message (older_catalog) asks for a newer revision
# a domain code (D<n> or D<n>.<m>) or one of the formal values, and a form id (lower-case words joined by "-")
DOMAIN_RE = re.compile(r"D[1-9][0-9]*(?:\.[1-9][0-9]*)?|multi|unclassified")
FORM_RE = re.compile(r"[a-z0-9]+(?:-[a-z0-9]+)*")
HASH_COLS = (("sha256", 32), ("sha1", 20), ("md5", 16), ("crc32", 4))
LICENSE_COLS = (("license_spdx", "spdx"), ("license_training_ok", "training_ok"),
                ("license_redistribution_ok", "redistribution_ok"), ("license_notes", "notes"))
ZIP_COLS = (("local_header_offset", "zip_local_header_offset"), ("compression_method", "zip_compression_method"),
            ("compressed_size", "zip_compressed_size"))
TRUNC_KEY = "content_truncated"
API_BODY_DEFAULT_FIELD = "items.0.body"
# the default User-Agent is built only from these three; tests compare the whole string against them
TOOL_NAME = "agentic-env-index-fetch"
TOOL_VERSION = "1"
DATASET_URL = f"https://huggingface.co/datasets/{DEFAULT_REPO}"
UA = f"{TOOL_NAME}/{TOOL_VERSION} (+{DATASET_URL})"
CHUNK = 1 << 20
UNKNOWN_SIZE_CAP = 100_000_000  # used only when a row carries no cap (a table without max_size_bytes)
RETRIES = 3
BACKOFF = 2.0
# DuckDB memory: the smaller of this and a quarter of the machine's memory, unless --memory-limit says otherwise
MEMORY_CAP = 4 << 30
# DuckDB threads: one per this much of the memory limit (a sort or join needs room per thread; with less, a query
# over a large selection fails with an out-of-memory error instead of spilling)
THREAD_MEMORY = 1 << 30
# the share of the memory limit one sorted part of the selection may take (see part_queries)
PART_SHARE = 0.25
SPILL_DIR = ".fetch_spill"
# DuckDB settings used when the tables are read over the network (hf:// or another URL). Hugging Face counts
# requests in 5-minute windows and answers 429 when a window is used up; DuckDB reads one file with several
# requests, and a full query touches thousands of files. Retries wait 2, 4, 8, ... 256 seconds (510 seconds
# in all), so the last retry comes after a whole window has passed; each request may take up to 120 seconds;
# fewer threads keep fewer requests in flight. These values are provisional: lower them if your reads never
# hit a limit, raise them if they still do.
HTTP_SETTINGS = {"http_retries": 8, "http_retry_wait_ms": 2000, "http_retry_backoff": 2, "http_timeout": 120}
REMOTE_THREADS = 4
# #2177: the host whose requests Hugging Face counts per 5 minutes, by class (hub_class); a run counts those it sent
# (hub_requests): DuckDB's in its own HTTP log, which connect enables for a remote read, and those of huggingface_hub's
# client and of the download session in HUB_SENT, by their libraries' hooks (main, make_session)
HUB_HOST = "huggingface.co"
HUB_SENT = {"resolver": 0, "api": 0, "other": 0}
# the longest a read of the index waits through its retries (510 seconds with HTTP_SETTINGS)
RETRY_SECONDS = round(sum(HTTP_SETTINGS["http_retry_wait_ms"] / 1000 * HTTP_SETTINGS["http_retry_backoff"] ** i
                          for i in range(HTTP_SETTINGS["http_retries"])))
# huggingface.co/docs/hub/rate-limits: an anonymous address gets fewer requests per 5 minutes than a signed-in user,
# and passing HF_TOKEN is the easy fix; HF_TOKEN overrides a token stored on the machine (connect reads only it)
ANONYMOUS = ("note: HF_TOKEN is not set, so the index is read anonymously; Hugging Face allows an anonymous address "
             "fewer requests per 5 minutes than a signed-in user, and once they are used up it answers 429 and each "
             f"read waits and retries (up to {RETRY_SECONDS} seconds a request). To read with your account, create a "
             "read token at https://huggingface.co/settings/tokens and set it in the environment (export "
             "HF_TOKEN=hf_... in a POSIX shell, $env:HF_TOKEN = 'hf_...' in PowerShell)")
HELP_ENV = ("environment:\n"
            "  HF_TOKEN   a Hugging Face access token; the index tables are read with it (a DuckDB huggingface\n"
            "             secret), so Hugging Face allows more requests per 5 minutes than to an anonymous address,\n"
            "             which runs into HTTP 429 sooner (each read then waits and retries). It overrides a token\n"
            "             stored on the machine. Without it the run says once that it reads anonymously. To set it,\n"
            "             create a read token at https://huggingface.co/settings/tokens, then\n"
            "             export HF_TOKEN=hf_... (PowerShell: $env:HF_TOKEN = 'hf_...')")
# writer side (#268): the tables under meta/ that a reader filters by source (batches, bench_overlap, bench_checked,
# tags) are written sorted by source in row groups of this many rows, so that a filtered read over
# HTTP touches only the row groups of the sources it reads
META_ROW_GROUP = 32_768
MANIFEST = "fetch_manifest.jsonl"
# what was read and with which arguments (to_pool.py copies it into _meta/delivery.json, local paths as
# placeholders)
RUN_FILE = "fetch_run.json"
# #1909: the selection file of the run, in the format of the data page's selection file (Get the data) with the sample
# count; filters records the options of SELECTION_OPTIONS the run was given (selection_filters), which choose its rows
SELECTION_JSON = "selection.json"
SELECTION_FORMAT = "agentic-env-selection/1"
SELECTION_OPTIONS = ("domain", "form", "kind", "tag", "ext", "unit", "tier", "min_size", "max_size_filter", "where",
                     "limit", "all", "keep_duplicates", "allow_benchmark", "allow_not_compared", "any_license",
                     "any_language", "allow_personal_data", "any_size")
SIZE_ONLY = "size only"
ROLLING_CHANGED = "rolling file, size changed"
NO_HASH_MEMBER = "the source publishes no hash for this member; sha256 computed on download"
# files the source regenerates in place, so the size in the index goes stale (source, collection); a row can
# also say so itself with source_meta.rolling
ROLLING_FILES = frozenset({("lichess", "puzzle"), ("lichess", "eval")})
# fields of source_meta copied into the manifest line as they are (rows built from a selection file)
CAMPAIGN_KEYS = ("campaign", "pool_domain", "pool_leaf", "pool_path", "pool_source", "pool_order",
                 "unit_group", "origin_kind", "agency", "derived_from", "rolling", "transform",
                 "upstream_sha256", "upstream_bytes", "unit_sha256", "unit_bytes", "content_sha256", "pool_fields",
                 "original_name", "generated_by", "expand", "expand_rule")
# a uri without a scheme that starts here names a file in the index repository, at the commit the tables are read at
REPO_FILES = "campaign_files/"


# ---------- SQL ----------

def sql_str(s: str) -> str:
    return "'" + str(s).replace("'", "''") + "'"


IS_ROW = "starts_with(coalesce(p.extra, ''), '{\"_row\":')"


def _absent(key: str) -> str:
    return f"coalesce(json_contains(json_extract(p.extra, '$._absent'), '\"{key}\"'), false)"


def tier_sql(field: str = "training_ok") -> str:
    """License tier of a row: the row's own license_override when it has one, otherwise the batch tier."""
    anycol = "(" + " OR ".join(f"p.{c} IS NOT NULL" for c, _ in LICENSE_COLS) + ")"
    own = (f"CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.license_override.{field}') "
           f"WHEN json_type(p.extra, '$.license_override') IS NOT NULL "
           f"THEN json_extract_string(p.extra, '$.license_override.{field}') "
           f"WHEN {anycol} THEN p.license_{field} "
           f"WHEN NOT {_absent('license_override')} THEN b.const_{field} END")
    v = f"coalesce(nullif({own}, ''), b.{field})"
    return f"(CASE WHEN {v} IN ('yes', 'conditional', 'no') THEN {v} ELSE 'unknown' END)"


def truncated_sql() -> str:
    """Why the stored content was cut short (NULL when it was not)."""
    own = (f"CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.source_meta.{TRUNC_KEY}') "
           f"WHEN json_type(p.extra, '$.source_meta') IS NOT NULL "
           f"THEN json_extract_string(p.extra, '$.source_meta.{TRUNC_KEY}') "
           f"WHEN NOT {_absent('source_meta')} THEN b.const_truncated END")
    return f"nullif(coalesce(p.truncated, {own}), '')"


def own_sql(key: str, const: str, *, text: bool = True) -> str:
    """A top-level field of the full pointer: the row's own value (in extra) when it has one, otherwise the
    source constant (a column of the batch table), unless the row lacks the field."""
    f = "json_extract_string" if text else "json_extract"
    return (f"(CASE WHEN {IS_ROW} THEN {f}(p.extra, '$._row.{key}') "
            f"WHEN json_type(p.extra, '$.{key}') IS NOT NULL THEN {f}(p.extra, '$.{key}') "
            f"WHEN NOT {_absent(key)} THEN {const} END)")


def source_meta_sql(key: str) -> str:
    """One key of source_meta; key is an SQL expression (a quoted name or a column such as b.meta_key)."""
    return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.source_meta.' || {key}) "
            f"WHEN json_type(p.extra, '$.source_meta') IS NOT NULL "
            f"THEN json_extract_string(p.extra, '$.source_meta.' || {key}) "
            f"WHEN NOT {_absent('source_meta')} THEN json_extract_string(b.const_source_meta, '$.' || {key}) END)")


def meta_value_sql() -> str:
    """The source_meta value that some tags depend on (forum instance, mailing list, site), see b.meta_key."""
    return f"(CASE WHEN b.meta_key IS NOT NULL THEN {source_meta_sql('b.meta_key')} END)"


def own_content_sql() -> str:
    """The row's own content categories as JSON text (NULL when the row takes them from its batch)."""
    return f"CAST({own_sql('content', 'b.const_content', text=False)} AS VARCHAR)"


def hash_scope_sql() -> str:
    """What the hashes cover: file (default), http_payload (a WARC record's payload) or api_body."""
    return f"coalesce({own_sql('hash_scope', 'b.const_hash_scope')}, 'file')"


def hash_sql(alg: str) -> str:
    """One hash of the row as lowercase hex (NULL when the row has none)."""
    hx = f"coalesce(json_contains(json_extract(p.extra, '$._hx'), '\"{alg}\"'), false)"
    return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.hashes.{alg}') "
            f"WHEN json_type(p.extra, '$.hashes.{alg}') IS NOT NULL THEN json_extract_string(p.extra, '$.hashes.{alg}') "
            f"WHEN {hx} THEN NULL ELSE lower(hex(p.{alg})) END)")


def uri_sql() -> str:
    """The pointer's uri before the address swap (the uri column holds the directly downloadable address)."""
    t, f, s = "b.uri_swap_to", "b.uri_swap_from", "b.uri_swap_suffix"
    return (f"(CASE WHEN {t} IS NOT NULL AND json_extract_string(p.extra, '$._uri_orig') IS NULL THEN "
            f"CASE WHEN starts_with(p.uri, {t}) AND ends_with(p.uri, {s}) AND length(p.uri) >= length({t}) + length({s}) "
            f"THEN {f} || substr(p.uri, length({t}) + 1, length(p.uri) - length({t}) - length({s})) END "
            f"ELSE p.uri END)")


def pid_sql() -> str:
    """pointer_id as written in meta/sources.json (layout.pointer_id), as one SQL expression."""
    par = "p.parent_pointer_id"
    rest = f"substr({par}, strpos({par}, ':') + strpos(substr({par}, strpos({par}, ':') + 1), ':') + 1)"
    head = "p.source || ':' || p.collection || ':'"
    tail = (f"array_to_string(list_slice(string_split({uri_sql()}, '/'), -b.pid_segments, -1), '/') || "
            f"CASE WHEN b.pid_at_offset THEN '@' || CAST(p.range_offset AS VARCHAR) ELSE '' END")
    return (f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.pointer_id') "
            f"WHEN {_absent('pointer_id')} THEN NULL "
            f"WHEN json_type(p.extra, '$.pointer_id') IS NOT NULL THEN json_extract_string(p.extra, '$.pointer_id') "
            f"WHEN json_type(p.extra, '$.pid') IS NOT NULL THEN {head} || json_extract_string(p.extra, '$.pid') "
            f"WHEN {par} IS NOT NULL AND p.member_path IS NOT NULL THEN "
            f"CASE WHEN length({par}) - length(replace({par}, ':', '')) >= 2 "
            f"THEN {head} || {rest} || '!/' || p.member_path END "
            f"WHEN b.pid_segments IS NOT NULL THEN {head} || {tail} END)")


def size_bucket_sql(col: str = "p.size_bytes") -> str:
    return (f"(CASE WHEN {col} IS NULL OR {col} < 0 THEN 'unknown' WHEN {col} < 10000 THEN '<10KB' "
            f"WHEN {col} < 1000000 THEN '10KB-1MB' WHEN {col} < 100000000 THEN '1MB-100MB' "
            f"WHEN {col} < 1000000000 THEN '100MB-1GB' ELSE '>1GB' END)")


def same_key(a: str, b: str = "p") -> str:
    return (f"{a}.source = {b}.source AND {a}.uri = {b}.uri AND {a}.range_offset IS NOT DISTINCT FROM {b}.range_offset "
            f"AND {a}.member_path IS NOT DISTINCT FROM {b}.member_path")


def row_file(rel: str) -> str:
    """#2286: row_file, the name of the data file at the repository path rel (as the catalog's column data_files names
    it): its path under data/ (DATA_DIR), such as npm/all/part-00060.parquet, _bucket/000/rows-00000.parquet, or
    sec-edgar-filings/rows-00000.parquet for a source laid out as a few large files (#1746). The one definition of the
    name: every writer of a table that carries row_file (meta/bench_checked.parquet) names a file by it, and every
    reader that joins on it reads it from the file's full path by row_file_sql."""
    return rel[len(DATA_DIR):]


def row_file_sql(root: str, path: str) -> str:
    """row_file in SQL: the name of the data file at path, an SQL expression for its full path under root
    (root/data/..., as source_files and files_sql give it; DuckDB's column filename holds a path as it was given), is
    what follows root/data/, with / between its parts."""
    return f"replace(substr({path}, length({sql_str(root + '/' + DATA_DIR)}) + 1), '\\', '/')"


def rows_from(root: str, files: str) -> str:
    """SELECT over the row tables files (an SQL list of their full paths under root) that adds where each row sits:
    row_file (the data file's path under data/, row_file_sql) and row_index (the row number in that file, from 0). The
    duplicate criterion orders rows by them as the last keys; reading them costs nothing extra."""
    return (f"SELECT * EXCLUDE (filename, file_row_number), {row_file_sql(root, 'filename')} AS row_file, "
            "file_row_number AS row_index "
            f"FROM read_parquet({files}, union_by_name = true, filename = true, file_row_number = true)")


# ---------- duplicates, resolved at read time ----------
# The duplicate criterion runs over the reader's own selection: the rows that pass every other criterion, with
# DuckDB window functions (dup_sql), so the copy kept is one the reader gets. A row is a duplicate for the first of
# DUP_REASONS that holds:
#   natural_key  another row has the same natural key (source, uri, range_offset, member_path) and was collected
#                later: of one natural key the newest version is kept, ordered by collection time, newest first: not
#                superseded, then the latest batch, then the latest part file of the batch (part-<n>.parquet are
#                numbered in the order they are written), then the last row
#                of the file (that row has natural_key_conflict true). #1300: a snapshot holds one row per key, so
#                this finds rows only in a revision written before that, where a corrected row went into a new part
#                file and its old version stayed; a selection pinned to such a revision still gets one version
#   superseded   the row belongs to a snapshot that a newer batch of the same unit replaces (SUPERSEDE: the
#                source_meta key that names the unit; newer by batch_date_sql, then "revised", then batch name)
#   same_sha256, same_sha1, same_md5
#                another row with the same hash and hash scope (md5 also the same size_bytes) comes first in keep
#                order: rows the first two reasons leave, then the source's registry order (registry_order of
#                meta/batches.parquet), then source, batch, uri, range_offset, member_path, row_file, row_index
DUP_REASONS = ("natural_key", "superseded", "same_sha256", "same_sha1", "same_md5")
DUP_HASHES = (("sha256", 64), ("sha1", 40), ("md5", 32))
NATURAL_KEY = ("source", "uri", "range_offset", "member_path")
# source -> the source_meta key that names the unit of a snapshot; of one unit only the newest batch is kept
SUPERSEDE = {"stackexchange-dump": "site"}
# the row's own columns the windows read (besides DUP_INPUTS)
DUP_ROW_COLS = ("source", "batch", "uri", "range_offset", "member_path", "row_file", "row_index", "size_bytes")
DUP_INPUTS = ("dup_scope",) + tuple(f"dup_{a}" for a, _ in DUP_HASHES) + ("dup_unit", "dup_ord", "dup_date",
                                                                           "dup_sdate")
# the working columns dup_sql adds and drops again
DUP_WORK = ("dup_rev", "dup_sup", "dup_nk_rank", "dup_nk_n") + tuple(f"dup_r_{a}" for a, _ in DUP_HASHES)
DUP_KEEP = ("dup_sup", "dup_nk_rank > 1", "dup_ord", "source", "batch", "uri", "range_offset", "member_path",
            "row_file", "row_index")


def batch_date_sql(x: str) -> str:
    """The date in the text x (a batch name) as YYYYMMDD, '' when it has none: the first match of
    YYYY[-]MM[-]DD."""
    return f"replace(regexp_extract(coalesce({x}, ''), '[0-9]{{4}}-?[0-9]{{2}}-?[0-9]{{2}}'), '-', '')"


def dup_inputs_sql() -> list:
    """The DUP_INPUTS as SELECT items over p JOIN b: what the hashes cover (hash_scope_sql), the three hashes as
    lowercase hex, the unit of a SUPERSEDE source, the source's registry order, the date of the batch name and, for
    a SUPERSEDE source, the date its supersession compares (the batch name's, else the one in source_meta.batch)."""
    unit = ("CASE p.source " + " ".join(f"WHEN {sql_str(s)} THEN nullif({source_meta_sql(sql_str(k))}, '')"
                                        for s, k in sorted(SUPERSEDE.items())) + " END")
    srcs = ", ".join(sql_str(s) for s in sorted(SUPERSEDE))
    d = batch_date_sql("p.batch")
    sd = (f"CASE WHEN p.source IN ({srcs}) THEN coalesce(nullif({d}, ''), "
          f"{batch_date_sql(source_meta_sql(sql_str('batch')))}) ELSE '' END")
    return ([f"{hash_scope_sql()} AS dup_scope"] + [f"{hash_sql(a)} AS dup_{a}" for a, _ in DUP_HASHES]
            + [f"{unit} AS dup_unit", "b.registry_order AS dup_ord", f"{d} AS dup_date", f"{sd} AS dup_sdate"])


def dup_sql(rows: str) -> str:
    """The rows of the relation rows (DUP_ROW_COLS, DUP_INPUTS and any other columns), each with duplicate_reason
    (the first of DUP_REASONS that holds, NULL for a row that is kept) and natural_key_conflict (true for the row
    kept of a natural key that other rows share), without DUP_INPUTS. Window functions only, over every row of rows:
    the caller gives the rows the other criteria keep, so the copy kept is one of them. A hash is used when it is
    lowercase hex of its length (md5 only with a size)."""
    valid = ", ".join(f"CASE WHEN length(dup_{a}) = {n} AND regexp_full_match(dup_{a}, '[0-9a-f]+')"
                      + (" AND size_bytes IS NOT NULL" if a == "md5" else "") + f" THEN dup_{a} END AS dup_{a}"
                      for a, n in DUP_HASHES)
    nk = ", ".join(NATURAL_KEY)
    keep = ", ".join(DUP_KEEP)
    ranks = ", ".join(f"CASE WHEN dup_{a} IS NOT NULL THEN row_number() OVER (PARTITION BY dup_scope, dup_{a}"
                      + (", size_bytes" if a == "md5" else "") + f" ORDER BY {keep}) END AS dup_r_{a}"
                      for a, _ in DUP_HASHES)
    nk_reason, sup_reason, *same = DUP_REASONS
    reason = (f"CASE WHEN dup_nk_rank > 1 THEN '{nk_reason}' WHEN dup_sup THEN '{sup_reason}' "
              + " ".join(f"WHEN dup_r_{a} > 1 THEN '{r}'" for (a, _), r in zip(DUP_HASHES, same)) + " END")
    s1 = f"SELECT * REPLACE ({valid}),\n  contains(lower(batch), 'revised') AS dup_rev\nFROM ({rows})"
    s2 = ("SELECT *, dup_unit IS NOT NULL AND batch <> arg_max(batch, struct_pack(d := dup_sdate, r := dup_rev, "
          f"b := batch)) OVER (PARTITION BY source, dup_unit) AS dup_sup\nFROM ({s1})")
    s3 = (f"SELECT *, row_number() OVER (PARTITION BY {nk} ORDER BY dup_sup, dup_date DESC, dup_rev DESC, "
          f"batch DESC, row_file DESC, row_index DESC) AS dup_nk_rank,\n  count(*) OVER (PARTITION BY {nk}) AS dup_nk_n\n"
          f"FROM ({s2})")
    s4 = f"SELECT *,\n  {ranks}\nFROM ({s3})"
    return (f"SELECT * EXCLUDE ({', '.join(DUP_INPUTS + DUP_WORK)}),\n  {reason} AS duplicate_reason,\n"
            f"  dup_nk_n > 1 AND dup_nk_rank = 1 AS natural_key_conflict\nFROM ({s4})")


def tag_key_sql() -> str:
    """Join condition between a row p and its lines in meta/tags.parquet (t)."""
    return ("t.source = p.source AND t.batch = p.batch AND t.collection IS NOT DISTINCT FROM p.collection "
            f"AND t.ext IS NOT DISTINCT FROM p.ext AND t.meta_value IS NOT DISTINCT FROM {meta_value_sql()} "
            f"AND t.content IS NOT DISTINCT FROM {own_content_sql()}")


def checked_sql(col: str = "checked") -> str:
    """True for a row whose file and collection pass column col of meta/bench_checked.parquet (view c): col
    checked says the rows were compared with the benchmark list, col default_keep says the default filter keeps
    them. Every published data file is listed (the release compares every file); a file not listed belongs to a
    revision older than that and does not pass. A collection listed with scope container (a collection whose name
    matches a benchmark and that awaits a ruling) must pass too."""
    return f"{checked_file_sql(col)} AND {not_pending_sql(col)}"


def checked_file_sql(col: str = "checked") -> str:
    """True for a row whose data file passes column col of meta/bench_checked.parquet (scope file): with col
    checked, the file was compared with the benchmark list."""
    return f"coalesce((SELECT bool_and(c.{col}) FROM c WHERE c.scope = 'file' AND c.row_file = p.row_file), false)"


def not_pending_sql(col: str = "checked") -> str:
    """True unless the row's collection is listed in meta/bench_checked.parquet with scope container and fails column
    col (a collection whose name matches a benchmark and that awaits a ruling)."""
    return (f"NOT EXISTS (SELECT 1 FROM c WHERE c.scope = 'container' AND NOT c.{col} AND c.source = p.source AND "
            f"c.collection = split_part(p.collection, '@', 1))")


def default_conditions() -> list:
    """The row conditions of the default filter, one (name, SQL condition) per rule: they remove copies of benchmark
    data (meta/bench_overlap.parquet) and the rows meta/bench_checked.parquet does not keep by default (column
    default_keep). The duplicate copies are removed after them, over the rows they keep (dup_sql). Tables: p rows,
    b batches, o bench_overlap, c bench_checked. License tiers, sizes and versions are not part of it."""
    rem = ", ".join(sql_str(c) for c in OVERLAP_REMOVE)
    return [("not_in_benchmark_row", f"NOT EXISTS (SELECT 1 FROM o WHERE o.scope = 'row' AND o.hit_class IN ({rem}) "
                                      f"AND {same_key('o')})"),
            ("not_in_benchmark_container", f"NOT EXISTS (SELECT 1 FROM o WHERE o.scope = 'container' AND "
                                            f"o.hit_class IN ({rem}) AND o.source = p.source AND "
                                            f"o.collection = split_part(p.collection, '@', 1))"),
            ("checked_for_benchmarks", checked_sql("default_keep"))]


def tag_condition(tags) -> str:
    vals = ", ".join(sql_str(t) for t in tags)
    return f"EXISTS (SELECT 1 FROM t WHERE {tag_key_sql()} AND t.tag IN ({vals}))"


# ---------- the default profile ----------

# The criteria of the default profile, in the order a removed unit is counted under (the first one it fails), each
# with the option that relaxes it and the reason a removed unit is reported with. --all turns them all off except the
# benchmark criteria (BENCHMARK_CRITERIA); --allow-benchmark also turns off "not compared". The duplicate criterion is
# judged last, over the units every other criterion keeps (dup_sql), so a unit it removes failed no other criterion and
# the copy it keeps is one the reader gets.
CRITERIA = ("duplicate", "benchmark", "not compared", "license", "language", "personal data", "size")
# #1891: the criteria --all leaves on. Rows that matched a benchmark or were not compared with the benchmark list yet
# come in only by their own options (fail-safe defaults: a permission, not an exclusion another option switches off),
# so evaluation data never enters a selection with a choice about how much to take.
BENCHMARK_CRITERIA = ("benchmark", "not compared")
RELAX = {"duplicate": "keep_duplicates", "benchmark": "allow_benchmark", "not compared": "allow_not_compared",
         "license": "any_license", "language": "any_language", "personal data": "allow_personal_data",
         "size": "any_size"}
REASONS = {"duplicate": "a duplicate copy of another row", "benchmark": "matched a benchmark",
           "not compared": "not compared with the benchmark list yet",
           "license": "the license does not let the files be shipped",
           "language": "recorded in a language other than English",
           "personal data": "marked as carrying personal data", "size": "above 20 MB"}
PROFILE_MAX_BYTES = 20_000_000  # the size criterion and the download cap under the profile (20 MB)
PII_REMOVE = ("present", "suspected")  # catalog pii.level values the personal-data criterion removes
PD_REMOVE = ("pseudonymous", "identifiable")  # pool_fields personal_data values it removes
# a natural-language code in source_meta.language: ISO 639-1 or 639-2 in lower case with optional subtags; several
# codes are separated by spaces, commas or semicolons. Capitalised values (Python, Go, COBOL) name programming
# languages and are not codes. en, eng: English; zxx: no linguistic content; und: undetermined (as if none).
LANG_CODE = r"[a-z]{2,3}(-[A-Za-z0-9]{2,8})*"
LANG_KEEP = ("en", "eng", "zxx", "und")
_LANG_EDGE = (r"(^|[\s,;])", r"($|[\s,;])")


def language_ok_sql() -> str:
    """True when the row records no natural-language code, or one of them is English or language-free. The code is
    source_meta.language, else source_meta.labels.language (the labels of collections built from the search's
    candidates)."""
    v = (f"coalesce({source_meta_sql(chr(39) + 'language' + chr(39))}, "
         f"{source_meta_sql(chr(39) + 'labels.language' + chr(39))}, '')")
    a, z = _LANG_EDGE
    keep = "|".join(LANG_KEEP)
    return (f"(NOT regexp_matches({v}, '{a}{LANG_CODE}{z}') "
            f"OR regexp_matches({v}, '{a}({keep})(-[A-Za-z0-9]{{2,8}})*{z}'))")


def personal_ok_sql() -> str:
    """True when neither the source (catalog pii.level, view s) nor the row (column sensitive, pool_fields
    personal_data) is marked as carrying personal data."""
    lv = ", ".join(sql_str(x) for x in PII_REMOVE)
    pf = f"coalesce({source_meta_sql(chr(39) + 'pool_fields' + chr(39))}, '')"
    pd = "|".join(PD_REMOVE)
    return (f"(p.sensitive IS NULL AND p.source NOT IN (SELECT s.source FROM s WHERE s.pii_level IN ({lv})) "
            f"AND NOT regexp_matches({pf}, '\"personal_data\",\\s*\"({pd})\"'))")


def profile_conditions(relaxed=()) -> list:
    """The criteria of the default profile that are on, [(name, SQL condition that is true when the row passes)], in
    CRITERIA order; the duplicate criterion has no row condition (None): cand_steps applies dup_sql over the rows the
    others keep. Tables: p rows, b batches, o bench_overlap, c bench_checked, s catalog."""
    dc = dict(default_conditions())
    sql = {"duplicate": None,
           "benchmark": " AND ".join(f"({x})" for x in (dc["not_in_benchmark_row"], dc["not_in_benchmark_container"],
                                                         not_pending_sql("default_keep"))),
           "not compared": checked_file_sql("default_keep"),
           "license": f"({tier_sql('training_ok')} = 'yes' AND {tier_sql('redistribution_ok')} IN ('yes', 'conditional'))",
           "language": language_ok_sql(),
           "personal data": personal_ok_sql(),
           "size": f"(p.size_bytes IS NULL OR p.size_bytes <= {PROFILE_MAX_BYTES})"}
    return [(n, sql[n]) for n in CRITERIA if n not in set(relaxed)]


def unit_sql() -> str:
    """The unit a row belongs to when its files are selected together: source_meta.unit_group (shared by the files of a
    unit), else the row itself (row_file#row_index; the row's natural key is the same row in a snapshot); NULL for a
    row of a collection without a unit_group (the source's README.md and LICENSE), which belongs to its source."""
    ug = f"nullif({source_meta_sql(chr(39) + 'unit_group' + chr(39))}, '')"
    camp = source_meta_sql(chr(39) + "campaign" + chr(39))
    return (f"(CASE WHEN {ug} IS NOT NULL THEN {ug} WHEN {camp} IS NOT NULL THEN NULL "
            f"ELSE p.row_file || '#' || CAST(p.row_index AS VARCHAR) END)")


def unit_id_sql() -> str:
    """unit_id (the Python unit_id) of a row in SQL: source_meta.unit_group, else (outside a collection) the row's uri,
    then @<range_offset> for a byte range, then !/<member_path> for an archive member; NULL for a row of a collection
    without a unit_group (the source's README.md and LICENSE). The uri is the one restore gives unit_id: the whole
    row's own for a row kept whole (_row), else the uri before the address swap (uri_sql), which for a file of the
    index repository is the path unit_id records as repo_uri. Needs the row's batch joined as b."""
    ug = f"nullif({source_meta_sql(chr(39) + 'unit_group' + chr(39))}, '')"
    camp = source_meta_sql(chr(39) + "campaign" + chr(39))
    uri = f"(CASE WHEN {IS_ROW} THEN json_extract_string(p.extra, '$._row.uri') ELSE {uri_sql()} END)"
    return (f"(CASE WHEN {ug} IS NOT NULL THEN {ug} WHEN {camp} IS NOT NULL THEN NULL "
            f"ELSE {uri} || coalesce('@' || CAST(p.range_offset AS VARCHAR), '') "
            "|| coalesce('!/' || nullif(p.member_path, ''), '') END)")


def unit_key_sql() -> str:
    """The fixed order of units (--sample, --limit) within a data file, the second of its two stages (#2035; the first
    is the data file's file_key, cand_select keyed): for a row of its own its fetch order (fetch_order, the order of
    earlier versions of this script), for a unit_group the sha256 of source and group."""
    ug = source_meta_sql(chr(39) + "unit_group" + chr(39))
    return f"(CASE WHEN {ug} IS NULL THEN {fetch_order()} ELSE sha256(p.source || chr(0) || {ug}) END)"


# #2035: the first stage of the fixed order of units (--limit, --sample): the data file that holds the unit, by its
# file_key; table fetch_files gives it for the row_file (rows_from) of each data file of the selection (file_keys_sql)
FILE_KEYS = "fetch_files"


def file_key(rel: str) -> str:
    """The order key of the data file at the repository path rel (as the catalog's column data_files names it, such as
    data/npm/all/part-00060.parquet): the sha256 of the path in hex, as DuckDB's sha256 gives it in file_keys_sql."""
    return hashlib.sha256(rel.encode("utf-8")).hexdigest()


def file_keys_sql(root: str, files: str) -> str:
    """The statement that makes table fetch_files (FILE_KEYS): one line per row_file (row_file_sql, as rows_from gives
    it) of the data files under root that files names (an SQL query with their repository paths in its column f, as
    the catalog's column data_files names them), with its file_key (the sha256 of that path)."""
    return (f"CREATE OR REPLACE TEMP TABLE {FILE_KEYS} AS SELECT {row_file_sql(root, sql_str(root + '/') + ' || f')} "
            f"AS row_file, min(sha256(f)) AS file_key FROM ({files}) GROUP BY ALL")


def domain_match_sql(col: str, domains) -> str:
    """True when the domain code in col matches one of domains: equal to it or, for a code D<n> or D<n>.<m>, one of
    its leaves (it starts with the code and a dot); multi and unclassified match only themselves."""
    out = []
    for d in domains:
        out.append(f"{col} = {sql_str(d)}")
        if d.startswith("D"):
            out.append(f"starts_with({col}, {sql_str(d + '.')})")
    return "(" + " OR ".join(out) + ")"


def catalog_select_sql(domains=(), forms=(), kinds=()) -> str:
    """The sources of view s that match: any domain entry matches one of domains (when given), the form is one
    of forms (when given) and the kind is one of kinds (when given)."""
    conds = []
    if domains:
        conds.append(f"s.source IN (SELECT e.source FROM (SELECT s.source, unnest(s.domain) AS code FROM s) e "
                     f"WHERE {domain_match_sql('e.code', domains)})")
    if forms:
        conds.append(f"s.form IN ({', '.join(sql_str(f) for f in forms)})")
    if kinds:
        conds.append(f"s.kind IN ({', '.join(sql_str(k) for k in kinds)})")
    return "SELECT DISTINCT s.source FROM s WHERE " + " AND ".join(conds)


def catalog_condition(domains=(), forms=(), kinds=()) -> str:
    """The row condition of --domain, --form and --kind: the row's source is one of the catalog sources that
    match."""
    return f"p.source IN ({catalog_select_sql(domains, forms, kinds)})"


def fetch_order() -> str:
    return ("sha256(concat_ws(chr(0), p.source, p.uri, coalesce(CAST(p.range_offset AS VARCHAR), ''), "
            "coalesce(p.member_path, '')))")


def build_where(*, tags=(), sources=(), tiers=None, min_size=None, max_size=None, where=None,
                max_size_filter=None, domains=(), forms=(), kinds=(), units=()) -> list:
    """Your own WHERE conditions of the selection (the default profile is apart: profile_conditions and cand_steps;
    --ext chooses units, not rows: cand_steps exts). max_size is accepted for older callers and ignored: a size cap
    applies when fetching (cand_steps), it does not remove rows. max_size_filter removes the rows whose known size
    is larger (rows of unknown size stay). domains, forms and kinds keep the rows of the sources that match them in
    meta/catalog.parquet (view s, catalog_condition). units (--unit) keep the rows of the units with these unit_ids
    and the files of their sources (README.md, LICENSE), which come with a unit taken."""
    conds = []
    if tiers is not None:
        conds.append(f"{tier_sql()} IN ({', '.join(sql_str(t) for t in tiers)})")
    if min_size is not None:
        conds.append(f"p.size_bytes >= {int(min_size)}")
    if max_size_filter is not None:
        conds.append(f"(p.size_bytes IS NULL OR p.size_bytes <= {int(max_size_filter)})")
    if tags:
        conds.append(tag_condition(tags))
    if sources:
        conds.append(f"p.source IN ({', '.join(sql_str(s) for s in sources)})")
    if domains or forms or kinds:
        conds.append(catalog_condition(domains, forms, kinds))
    if units:
        uid = unit_id_sql()
        conds.append(f"({uid} IN ({', '.join(sql_str(u) for u in units)}) OR {uid} IS NULL)")
    if where:
        conds.append(f"({where})")
    return conds


def _root(args) -> str:
    return args.data.rstrip("/") if args.data else f"hf://datasets/{args.repo}"


def file_list(paths) -> str:
    """The data files paths (full paths, source_files) as a DuckDB list literal for read_parquet."""
    return "[" + ", ".join(sql_str(p) for p in paths) + "]"


def batch_filter(batches) -> str:
    """The WHERE clause that keeps only the rows of the (source, batch) pairs batches (tag_batches): a data file may
    hold rows of other batches, so the pairs are matched by the rows' own columns, not by file paths."""
    return " WHERE " + " OR ".join(f"(source = {sql_str(s)} AND batch = {sql_str(b)})" for s, b in batches)


def files_sql(root: str, sources=(), batches=None) -> str:
    """The statement that sets the DuckDB variable data_files to the full paths of the data files the catalog's column
    data_files names for sources (every source when none is given), or with batches ((source, batch) pairs) those its
    column batch_files names for them: the one read of meta/catalog.parquet that the rows view p takes its files from
    (views_sql)."""
    if batches:
        pairs = " OR ".join(f"(source = {sql_str(s)} AND x.batch = {sql_str(b)})" for s, b in batches)
        pick = (f"SELECT DISTINCT x.file AS f FROM (SELECT source, unnest({BATCH_FILES}) AS x FROM "
                f"read_parquet({sql_str(root + '/' + CATALOG)})) WHERE {pairs}")
    else:
        where = f" WHERE source IN ({', '.join(sql_str(s) for s in sources)})" if sources else ""
        pick = f"SELECT DISTINCT unnest({DATA_FILES}) AS f FROM read_parquet({sql_str(root + '/' + CATALOG)}){where}"
    return f"SET VARIABLE {DATA_FILES} = (SELECT list({sql_str(root + '/')} || f ORDER BY f) FROM ({pick}))"


def views_sql(root: str, *, sources=(), batches=None, domains=(), forms=(), kinds=()) -> list:
    """The views p (rows), b, o, t, c, and s (meta/catalog.parquet: source, domain, form, pii_level, spdx, files,
    and kind when kinds are given),
    as --print-sql shows them (a run reads the same tables filtered to its sources, table_steps). p reads exactly the
    data files the catalog's column data_files names for the sources (files_sql), no listing of data/, and keeps the
    rows of those sources by their column source (a file may hold rows of others). batches:
    (source, batch) pairs (tag_batches); when given, p reads only the files the column batch_files names for them and
    holds only the rows of those batches, and o, t hold
    only the rows of their sources (every condition of the default filter and of the tags joins them on the row's
    source). Duplicates have no table: dup_sql finds them among the rows read."""
    names = sorted({s for s, _ in batches}) if batches else sorted(sources)
    mine = f" WHERE source IN ({', '.join(sql_str(s) for s in names)})" if names else ""
    keep = mine if batches else ""
    rows = rows_from(root, f"getvariable('{DATA_FILES}')") + (batch_filter(batches) if batches else mine)
    out = [files_sql(root, names, batches),
           f"CREATE OR REPLACE VIEW p AS {rows}",
           f"CREATE OR REPLACE VIEW b AS SELECT * FROM read_parquet({sql_str(root + '/meta/batches.parquet')})",
           f"CREATE OR REPLACE VIEW o AS SELECT * FROM read_parquet({sql_str(root + '/meta/bench_overlap.parquet')}){keep}",
           f"CREATE OR REPLACE VIEW t AS SELECT * FROM read_parquet({sql_str(root + '/meta/tags.parquet')}){keep}",
           f"CREATE OR REPLACE VIEW c AS SELECT * FROM read_parquet({sql_str(root + '/meta/bench_checked.parquet')})",
           f"CREATE OR REPLACE VIEW s AS SELECT source, domain, form, pii.level AS pii_level, license.spdx AS spdx, "
           f"files{', kind' if kinds else ''} FROM read_parquet({sql_str(root + '/' + CATALOG)})"]
    return out


# ---------- reading only what the selection needs ----------

# A selection whose sources hold at most this many rows (by the catalog's files column) is copied into memory with
# one read of its data files; a larger one is read in place (twice: to pick the rows, then to copy the picked ones).
# #2035: with --limit or --sample the same holds for the data files read_units reads, a round of files at a time, and a
# larger selection reads again only the files that hold the rows picked (picked_rows).
LOCAL_ROWS = 2_000_000
READ_JOBS = 8  # parallel reads of the tables (each is one or a few HTTP requests)
_SETUP: dict = {}  # id(connection) -> the session settings every cursor of it repeats (connect)


class UnknownName(Exception):
    """A source, kind, domain or form name that the catalog does not have (the message names the closest ones)."""


def catalog_table(con, root: str) -> dict:
    """meta/catalog.parquet read once into table s: source, domain (list of codes), form, pii_level, spdx, files,
    kind, (#1577) the fetch check fetch_level, fetch_rows, fetch_fetched, fetch_read_at (NULL where this revision of
    the catalog has no such column; #2006: from its column fetch_check, FETCH_CHECK, or in release-2026-11-09.1 from its
    column fetch), and (#1746) data_files and batch_files (DATA_FILES, BATCH_FILES: the repository
    paths of the source's data files, and of each batch's) only where this revision of the catalog has them
    (source_files). Every catalog column and struct field is read as a quoted identifier (col): fetch is a reserved word
    of DuckDB's parser, so an unquoted fetch.level does not parse. -> {column: present}, FETCH_CHECK for the fetch check
    under either name."""
    con.execute(f"CREATE OR REPLACE TABLE s_raw AS SELECT * FROM read_parquet({sql_str(root + '/' + CATALOG)})")
    have = {str(r[0]): str(r[1]) for r in con.execute("DESCRIBE s_raw").fetchall()}

    def col(path, name, typ, ok):
        expr = ".".join(f'"{p}"' for p in path.split("."))
        return f"{expr} AS {name}" if ok else f"CAST(NULL AS {typ}) AS {name}"

    # expand now, contract later: the read of the old name goes once a release with fetch_check is published
    fc = FETCH_CHECK if FETCH_CHECK in have else FETCH_CHECK_OLD
    fetch = "level" in have.get(fc, "")
    cols = ['"source"', col("domain", "domain", "VARCHAR[]", "domain" in have),
            col("form", "form", "VARCHAR", "form" in have),
            col("pii.level", "pii_level", "VARCHAR", "level" in have.get("pii", "")),
            col("license.spdx", "spdx", "VARCHAR", "spdx" in have.get("license", "")),
            col("files", "files", "BIGINT", "files" in have), col("kind", "kind", "VARCHAR", "kind" in have),
            col(f"{fc}.level", "fetch_level", "VARCHAR", fetch), col(f"{fc}.rows", "fetch_rows", "BIGINT", fetch),
            col(f"{fc}.fetched", "fetch_fetched", "BIGINT", fetch),
            col(f"{fc}.read_at", "fetch_read_at", "VARCHAR", fetch)]
    cols += [c for c in (DATA_FILES, BATCH_FILES) if c in have]
    con.execute(f"CREATE OR REPLACE TABLE s AS SELECT {', '.join(cols)} FROM s_raw")
    con.execute("DROP TABLE s_raw")
    return {**{k: k in have for k in ("domain", "form", "pii", "license", "files", "kind", DATA_FILES, BATCH_FILES)},
            FETCH_CHECK: fetch}


def source_files(con, root: str, sources=None, batches=None) -> dict:
    """{source: the full paths of the data files to read for it} for the sources of table s (every source when sources
    is None), under root; batches: (source, batch) pairs (tag_batches), then only the files that hold those batches,
    of their sources. The catalog's column data_files names a source's files and batch_files the files of each of its
    batches (#1746), so data/ is never listed. A revision whose catalog has no column data_files (older than #1746):
    IndexReadError (older_catalog). For a local copy only the files it holds. A source with no file is not in the
    result."""
    pairs = None if batches is None else {(str(s), str(b)) for s, b in batches}
    want = {s for s, _ in pairs} if pairs is not None else None if sources is None else set(sources)
    if DATA_FILES not in {str(r[0]) for r in con.execute("DESCRIBE s").fetchall()}:
        raise older_catalog(root)
    out = {}
    for s, rels, by in con.execute(f"SELECT source, {DATA_FILES}, {BATCH_FILES} FROM s ORDER BY source").fetchall():
        s = str(s)
        if want is not None and s not in want:
            continue
        rels = rels if pairs is None else [x["file"] for x in by or () if (s, x["batch"]) in pairs]
        paths = [f"{root}/{r}" for r in sorted(set(rels or ()))]
        if not is_remote(root):
            paths = [p for p in paths if Path(p).is_file()]
        if paths:
            out[s] = paths
    return out


def index_files(root: str, sources, batches=None) -> list:
    """The full paths of the data files of sources at root (of the (source, batch) pairs batches when given), sorted,
    for a reader that takes table_steps without main: one read of meta/catalog.parquet (catalog_table, source_files),
    so data/ is not listed."""
    con = connect(remote=is_remote(root))
    try:
        catalog_table(con, root)
        return sorted({p for ps in source_files(con, root, sources, batches).values() for p in ps})
    finally:
        con.close()


def catalog_names_files(root: str) -> bool:
    """Whether the catalog at root has the column data_files (#1746), from its schema alone (one read of the file's
    footer): --print-sql prints no statement for a revision without it (older_catalog)."""
    con = connect(remote=is_remote(root))
    try:
        cols = con.execute(f"DESCRIBE SELECT * FROM read_parquet({sql_str(root + '/' + CATALOG)})").fetchall()
        return DATA_FILES in {str(r[0]) for r in cols}
    finally:
        con.close()


def older_catalog(root: str) -> "IndexReadError":
    """#1769: the error for a revision whose catalog has no column data_files (older than #1746): its data files are
    named nowhere but in their paths, which this tool does not read."""
    return IndexReadError(f"{CATALOG} at {root} has no column {DATA_FILES}: this revision of the index is older than "
                          f"that column, which names the data files of each source, so it cannot be read; read a newer "
                          f"revision (a later --revision, or none for the current one)")


def _closest(name: str, names) -> str:
    import difflib

    near = difflib.get_close_matches(name, sorted(set(names)), n=3, cutoff=0.6)
    return ", ".join(near) if near else "none close"


def check_names(con, *, sources=(), domains=(), forms=(), kinds=(), has_form=True, where: str = "") -> None:
    """Every name given must be in table s: a source name, a domain code that a source carries (a top-level code
    counts when one of its leaves is carried), a form, a kind. Raises UnknownName with one line naming the closest
    names."""
    srcs = {str(r[0]) for r in con.execute("SELECT source FROM s").fetchall()}
    for s in sources:
        if s not in srcs:
            raise UnknownName(f"--source {s}: no such source in {CATALOG}{where}; closest: {_closest(s, srcs)}")
    if domains:
        codes = {str(r[0]) for r in con.execute("SELECT DISTINCT unnest(domain) FROM s").fetchall() if r[0]}
        codes |= {c.split(".")[0] for c in codes}
        for d in domains:
            if d not in codes:
                raise UnknownName(f"--domain {d}: no source in {CATALOG}{where} has this domain; closest: "
                                  f"{_closest(d, codes)}")
    if forms and has_form:
        fs = {str(r[0]) for r in con.execute("SELECT DISTINCT form FROM s").fetchall() if r[0]}
        for f in forms:
            if f not in fs:
                raise UnknownName(f"--form {f}: no source in {CATALOG}{where} has this form; closest: {_closest(f, fs)}")
    if kinds:
        ks = {str(r[0]) for r in con.execute("SELECT DISTINCT kind FROM s").fetchall() if r[0]}
        for k in kinds:
            if k not in ks:
                raise UnknownName(
                    f"--kind {k}: no source in {CATALOG}{where} has this kind; closest: {_closest(k, ks)}")


def resolve_sources(con, root: str, *, domains=(), forms=(), kinds=(), sources=()) -> list:
    """The sources of table s that match domains, forms and kinds (catalog_select_sql), limited to sources when
    given; every source when none of the four is given. Sorted. Sources whose catalog row names no data file (for a
    local copy: none it holds, source_files) are left out."""
    if domains or forms or kinds:
        sql = catalog_select_sql(domains, forms, kinds)
        if sources:
            sql += f" AND s.source IN ({', '.join(sql_str(s) for s in sources)})"
        found = sorted(str(s) for (s,) in con.execute(sql).fetchall() if s is not None)
    elif sources:
        found = sorted(set(sources))
    else:
        found = sorted(str(s) for (s,) in con.execute("SELECT source FROM s").fetchall())
    have = source_files(con, root, found)
    return [s for s in found if s in have]


def table_rows(root: str, files: list, sources, *, batches=None, everything: bool = False) -> str:
    """The SELECT of the selection's rows in the data files files (full paths under root, read one by one with no
    listing): the rows of sources (a file may also hold rows of other sources), with batches ((source, batch) pairs,
    tag_batches) only the rows of those batches, and every row when everything."""
    names = sorted({s for s, _ in batches}) if batches else sorted(sources)
    w = "" if everything else f" WHERE source IN ({', '.join(sql_str(s) for s in names) or 'NULL'})"
    return rows_from(root, file_list(files)) + (batch_filter(batches) if batches else w)


def table_steps(root: str, sources, files: list, *, batches=None, tags=(), everything: bool = False,
                local_rows: bool = False) -> dict:
    """{table: statement} that read only what the selection needs, run in parallel (read_parallel): p0 the rows (a
    table when local_rows, else a view; complete_rows then makes the view p over it), and of b, o, c (and t with
    tags) only the rows of sources. files: the full paths of the selected sources' data files (source_files; with
    batches only the files that hold those batches), read one by one with no listing (index_files gives them to a
    reader without main); a file may also hold rows of other sources, so p0 keeps only the rows of sources
    (table_rows).
    batches:
    (source, batch) pairs (tag_batches); when given, p0 holds only their rows. everything: every source is
    selected, so nothing is filtered."""
    names = sorted({s for s, _ in batches}) if batches else sorted(sources)
    w = "" if everything else f" WHERE source IN ({', '.join(sql_str(s) for s in names) or 'NULL'})"

    def meta(name):
        return f"SELECT * FROM read_parquet({sql_str(f'{root}/meta/{name}.parquet')}){w}"

    rows = table_rows(root, files, sources, batches=batches, everything=everything)
    out = {"p": f"CREATE OR REPLACE {'TABLE' if local_rows else 'VIEW'} p0 AS {rows}",
           "b": f"CREATE OR REPLACE TABLE b AS {meta('batches')}",
           "o": f"CREATE OR REPLACE TABLE o AS {meta('bench_overlap')}",
           "c": f"CREATE OR REPLACE TABLE c AS {meta('bench_checked')}"}
    if tags:
        out["t"] = f"CREATE OR REPLACE TABLE t AS {meta('tags')}"
    return out


def cursor(con):
    """A cursor of con with con's session settings (HTTP retries, proxy, token: connect)."""
    cur = con.cursor()
    for q in _SETUP.get(id(con), ()):
        cur.execute(q)
    return cur


# The optional row columns the conditions read, with their types: data files written before a column existed lack it,
# and p (complete_rows) gives it as NULL there, so a condition on it reads NULL instead of failing.
ROW_OPTIONAL = (("truncated", "VARCHAR"), ("license_spdx", "VARCHAR"), ("license_training_ok", "VARCHAR"),
                ("license_redistribution_ok", "VARCHAR"), ("license_notes", "VARCHAR"), ("sensitive", "VARCHAR"),
                ("member_path", "VARCHAR"), ("parent_pointer_id", "VARCHAR"), ("range_offset", "BIGINT"),
                ("range_length", "BIGINT"), ("media_type", "VARCHAR"), ("origin_url", "VARCHAR"),
                ("origin_time", "VARCHAR"), ("extra", "VARCHAR"), ("sha256", "BLOB"), ("sha1", "BLOB"),
                ("md5", "BLOB"), ("crc32", "BLOB"), ("zip_local_header_offset", "BIGINT"),
                ("zip_compression_method", "BIGINT"), ("zip_compressed_size", "BIGINT"))


def complete_rows(con) -> list:
    """View p over p0 (the rows read by table_steps) with every column of ROW_OPTIONAL that p0 lacks added as NULL.
    -> the columns added."""
    have = {str(r[0]) for r in con.execute("DESCRIBE p0").fetchall()}
    add = [(c, t) for c, t in ROW_OPTIONAL if c not in have]
    extra = "".join(f", CAST(NULL AS {t}) AS {c}" for c, t in add)
    con.execute(f"CREATE OR REPLACE VIEW p AS SELECT *{extra} FROM p0")
    return [c for c, _ in add]


def read_parallel(con, jobs: dict, bar=None) -> dict:
    """Run jobs ({name: SQL statement, or a function of a cursor}) on cursors of con in parallel threads (each read
    waits on the network); -> {name: the function's result or None}. The first failure is raised. bar (step_bar)
    ticks once per job done and is redrawn while they wait."""
    import concurrent.futures as cf

    def one(job):
        cur = cursor(con)
        try:
            return job(cur) if callable(job) else cur.execute(job) and None
        finally:
            cur.close()

    out = {}
    every = None if bar is None else REDRAW[sys.stderr.isatty()]
    with cf.ThreadPoolExecutor(max(1, min(READ_JOBS, len(jobs)))) as ex:
        futs = {name: ex.submit(one, job) for name, job in jobs.items()}
        pending = set(futs.values())
        while pending:
            done, pending = cf.wait(pending, timeout=every, return_when=cf.FIRST_COMPLETED)
            if bar is not None and done:
                bar.update(len(done))
            elif bar is not None:
                bar.refresh()
        for name, f in futs.items():
            out[name] = f.result()
    return out


# while one step of reading the index or planning the selection runs, its progress line is redrawn every this many
# seconds so that its elapsed time moves: on a terminal, and in a log (stderr not a terminal), where it adds a line
REDRAW = {True: 1.0, False: 60.0}


def step_bar(desc: str, unit: str, total: int, quiet: bool):
    """A tqdm progress line on stderr for reading the index or planning the selection: the steps done of the total
    and the time elapsed (no rate or estimate: one step may wait minutes on a rate limit). Off with quiet."""
    from tqdm import tqdm

    return tqdm(total=total, desc=desc, file=sys.stderr, disable=quiet,
                bar_format=f"{{desc}}: {{n_fmt}}/{{total_fmt}} {unit} done, {{elapsed}} elapsed")


def waiting(bar, con, fn, *args):
    """fn(*args) run in a thread while bar is redrawn every REDRAW seconds, so a step that waits on the network shows
    its elapsed time; -> its result. Ctrl-C interrupts the query running on con."""
    import concurrent.futures as cf

    every = REDRAW[sys.stderr.isatty()]
    ex = cf.ThreadPoolExecutor(1)
    fut = ex.submit(fn, *args)
    try:
        while True:
            try:
                return fut.result(timeout=every)
            except cf.TimeoutError:
                bar.refresh()
    except KeyboardInterrupt:
        con.interrupt()
        raise
    finally:
        ex.shutdown(wait=True)


def run_steps(con, steps: list, bar) -> None:
    """The SQL statements steps run on con in order, bar ticking once per statement (waiting)."""
    for s in steps:
        waiting(bar, con, con.execute, s)
        bar.update(1)


def tag_batches(con, root: str, tags, sources=()) -> list:
    """The (source, batch) pairs that carry any of the tags (meta/tags.parquet, three columns read), limited to
    sources when given. Pairs of a source with no data file of those batches (source_files; for a local copy: none it
    holds) are left out."""
    sql = (f"SELECT DISTINCT source, batch FROM read_parquet({sql_str(root + '/meta/tags.parquet')}) "
           f"WHERE tag IN ({', '.join(sql_str(t) for t in tags)})")
    if sources:
        sql += f" AND source IN ({', '.join(sql_str(s) for s in sources)})"
    pairs = [(str(s), str(b)) for s, b in con.execute(sql + " ORDER BY 1, 2").fetchall()]
    have = source_files(con, root, batches=pairs)
    return [(s, b) for s, b in pairs if s in have]


# the columns of fetch_cand that its later steps carry (cand_steps), with file_key after them when keyed
CAND_BASE = ("row_file", "row_index", "source", "unit", "unit_key", "fetch_key", "size_cap_bytes", "batch_cap_bytes")


def cand_select(conds: list, profile: list, max_size: int | None = None, size_cap: int | None = None, exts=(),
                keyed: bool = False) -> str:
    """The lines the selection starts from (cand_steps), as one SELECT over p and b: one line per row that passes
    conds (your own conditions) with where it sits, its unit (unit_sql, NULL for a file of its source), the unit's
    order key (unit_key_sql), its caps, fail (the 1-based number in CRITERIA of the first criterion of profile it
    fails; NULL: it passes all) and the columns dup_sql reads when profile has the duplicate criterion (else
    natural_key_conflict false); with exts, ext_ok. size_cap (the profile's 20 MB) lowers the cap of a row whose batch
    cap is larger; max_size replaces both. keyed (#2035, --limit and --sample): also file_key, the key of the row's
    data file (table fetch_files, file_keys_sql), the first stage of the fixed order of units."""
    if max_size is not None:
        cap = str(int(max_size))
    elif size_cap is not None:
        cap = f"least(b.max_size_bytes, {int(size_cap)})"
    else:
        cap = "b.max_size_bytes"
    whole = str(int(max_size)) if max_size is not None else "b.max_size_bytes"
    rank = {n: i + 1 for i, n in enumerate(CRITERIA)}
    rows = [(n, c) for n, c in profile if c is not None]
    fail = ("CASE " + " ".join(f"WHEN NOT coalesce({c}, false) THEN {rank[n]}" for n, c in rows) + " END"
            if rows else "CAST(NULL AS INTEGER)")
    head = (f"SELECT p.row_file, p.row_index, p.source, {unit_sql()} AS unit, "
            f"{unit_key_sql()} AS unit_key, {fetch_order()} AS fetch_key, {cap} AS size_cap_bytes, "
            f"{whole} AS batch_cap_bytes, {fail} AS fail")
    if keyed:
        head += ", fk.file_key"
    if len(rows) < len(profile):
        head += ", " + ", ".join([f"p.{c}" for c in DUP_ROW_COLS if c not in CAND_BASE] + dup_inputs_sql())
    else:
        head += ", false AS natural_key_conflict"
    if exts:
        head += f", lower(p.ext) IN ({', '.join(sql_str(e.lower().lstrip('.')) for e in exts)}) AS ext_ok"
    sel = f"{head} FROM p JOIN b ON b.source = p.source AND b.batch = p.batch"
    if keyed:
        sel += f" LEFT JOIN {FILE_KEYS} fk ON fk.row_file = p.row_file"
    if conds:
        sel += "\nWHERE " + "\n  AND ".join(conds)
    return sel


def cand_steps(conds: list, profile: list, max_size: int | None = None, size_cap: int | None = None,
               exts=(), *, keyed: bool = False, read: str | None = None) -> list:
    """The first part of the selection: table fetch_cand, the lines of cand_select (one per row that passes conds,
    with natural_key_conflict and fail, the 1-based number in CRITERIA of the first criterion of profile it fails;
    NULL: it passes all); then fetch_units, one line per unit with the first criterion any of its rows fails (and,
    keyed, the least file_key of its rows).
    exts (--ext) choose units, not rows: a unit stays when one of its files has one of the extensions, and
    then with all its rows; a file of a source stays when its source keeps such a unit.
    The duplicate criterion (in profile with no row condition) is judged last: fetch_cand0 holds the rows with the
    other criteria and the columns dup_sql reads, and dup_sql runs over the rows whose unit (or, for a file of a
    source, the row itself) fails none of them, so the copy kept is one the reader gets. A row it removes as an older
    version of a natural key leaves the selection: the newest version stands for it, so it is no file of its unit
    and does not fail it (#676: a corrected row is a new version; release-2026-11-03.1 lost every unit of a set whose
    rows were corrected); a row it removes for another reason fails the duplicate criterion.
    natural_key_conflict is true only for a row whose natural key the duplicate criterion removed from other rows.
    read (#2035): the table that already holds the lines of cand_select over the data files read so far (read_units);
    the first table is copied from it, so every criterion is judged again over all the lines read, and read stays as
    it is for the files read next."""
    rank = {n: i + 1 for i, n in enumerate(CRITERIA)}
    dedup = any(c is None for _, c in profile)
    first = "fetch_cand0" if dedup else "fetch_cand"
    src = f"SELECT * FROM {read}" if read else cand_select(conds, profile, max_size, size_cap, exts, keyed)
    out = [f"CREATE OR REPLACE TEMP TABLE {first} AS {src}"]
    if exts:
        out.append(f"DELETE FROM {first} WHERE NOT EXISTS (SELECT 1 FROM {first} k WHERE k.unit IS NOT NULL "
                   f"AND k.ext_ok AND k.source = {first}.source AND ({first}.unit IS NULL OR k.unit = {first}.unit))")
    if dedup:
        keep = ("c.fail IS NULL AND NOT EXISTS (SELECT 1 FROM fetch_cand0 f WHERE f.fail IS NOT NULL "
                "AND f.source = c.source AND f.unit = c.unit)")
        cols = ", ".join(CAND_BASE + (("file_key",) if keyed else ()))
        out += [f"CREATE OR REPLACE TEMP TABLE fetch_cand AS SELECT {cols}, natural_key_conflict, "
                f"CASE WHEN duplicate_reason IS NOT NULL THEN {rank['duplicate']} ELSE fail END AS fail "
                f"FROM ({dup_sql(f'SELECT c.* FROM fetch_cand0 c WHERE {keep}')})\n"
                f"WHERE duplicate_reason IS DISTINCT FROM '{DUP_REASONS[0]}'\n"
                f"UNION ALL SELECT {cols}, false, fail FROM fetch_cand0 c WHERE NOT ({keep})",
                "DROP TABLE fetch_cand0"]
    fk = ", min(file_key) AS file_key" if keyed else ""
    out.append(f"CREATE OR REPLACE TEMP TABLE fetch_units AS SELECT source, unit, min(unit_key) AS unit_key{fk}, "
               "min(fail) AS fail, count(*) AS files FROM fetch_cand WHERE unit IS NOT NULL GROUP BY source, unit")
    return out


def pick_steps(limit: int | None = None, sample: int | None = None, keyed: bool = False) -> list:
    """The second part's first statements: fetch_take, the units kept (every row passes), at most sample per source
    and limit in all; fetch_pick, their rows and the files of their sources (that pass). Each source's units are
    numbered by DuckDB's row_number() over the source in the fixed order of units (unit_key; keyed, #2035: file_key
    first, the key of the unit's data file): sample keeps the first sample of each source, and limit takes them from
    the sources in turn (#2144), the first unit of each source, then the second of each, and so on, the sources of one
    turn in the order of the sha256 of their names (source_turn), so that it spreads over the sources."""
    cols = "source, unit, unit_key" + (", file_key" if keyed else "")
    order = ("file_key, " if keyed else "") + "unit_key"
    inner = f"SELECT {cols} FROM fetch_units WHERE fail IS NULL"
    if sample is not None or limit is not None:
        inner = (f"SELECT {cols} FROM (SELECT {cols}, row_number() OVER (PARTITION BY source ORDER BY {order}, unit) "
                 f"AS n FROM fetch_units WHERE fail IS NULL)"
                 + (f" WHERE n <= {int(sample)}" if sample is not None else "")
                 + (f" ORDER BY n, sha256(source), source LIMIT {int(limit)}" if limit is not None else ""))
    take = f"CREATE OR REPLACE TEMP TABLE fetch_take AS {inner}"
    picked = ("k.unit IS NOT NULL OR (c.unit IS NULL AND c.fail IS NULL AND c.source IN "
              "(SELECT source FROM fetch_take))")
    pick = ("CREATE OR REPLACE TEMP TABLE fetch_pick AS SELECT c.row_file, c.row_index, "
            "coalesce(k.unit_key, c.fetch_key) AS fetch_key, c.size_cap_bytes, c.batch_cap_bytes, "
            "c.natural_key_conflict, c.unit FROM fetch_cand c LEFT JOIN fetch_take k ON k.source = c.source "
            f"AND k.unit = c.unit WHERE {picked}")
    return [take, pick]


def rows_steps() -> list:
    """The second part's last statements: fetch_rows, the rows of fetch_pick whole (from p), with
    fetch_source_file (true for a file of the source); then fetch_pick is dropped."""
    rows = ("CREATE OR REPLACE TEMP TABLE fetch_rows AS SELECT p.*, k.fetch_key, k.unit IS NULL AS fetch_source_file, "
            "k.size_cap_bytes, k.batch_cap_bytes, k.natural_key_conflict FROM p JOIN fetch_pick k "
            "ON k.row_file = p.row_file AND k.row_index = p.row_index")
    return [rows, "DROP TABLE fetch_pick"]


def take_steps(limit: int | None = None, sample: int | None = None, keyed: bool = False) -> list:
    """The second part: fetch_take and fetch_pick (pick_steps), then fetch_rows (rows_steps). part_queries returns
    fetch_rows in fetch order, one key range at a time (one query that both picks and sorts whole rows keeps every
    row in memory, and DuckDB cannot sort wide rows larger than its memory limit)."""
    return pick_steps(limit, sample, keyed) + rows_steps()


def select_steps(conds: list, limit: int | None = None, max_size: int | None = None) -> list:
    """The rows that pass conds with no profile and every row its own unit, as statements (cand_steps and
    take_steps; kept for callers of earlier versions)."""
    return cand_steps(conds, [], max_size) + take_steps(limit)


def source_turn(source: str) -> str:
    """#2144: the key of a source's place in a turn of --limit (pick_steps): the sha256 of its name in hex, as DuckDB's
    sha256 gives it."""
    return hashlib.sha256(source.encode("utf-8")).hexdigest()


def turn_files(mine: dict, seen: set, have: dict, turn: dict, limit: int, sample: int | None = None) -> list:
    """#2144: the data files the next round of read_units reads for --limit, the selected sources' data files taken in
    turn: the first file of each source, then the second of each, and so on (mine: {source: its data files in their
    fixed order}; seen: the files read), the sources of one turn in the order of turn ({source: source_turn}). have:
    {source: its units that pass in the files read}, each counted up to sample when given. -> the next files of the
    first turn with a file not read yet, of the sources that may still give a unit, at most as many as units are still
    missing to limit (a file holds at least one unit); none once limit units are known. A source whose files give no
    unit that passes is read one file a turn, as every other, so it never holds up the rest."""
    missing = limit - sum(min(have.get(s, 0), limit if sample is None else sample) for s in mine)
    queue = sorted((i, turn[s], p) for s in mine if sample is None or have.get(s, 0) < sample
                   for i, p in enumerate(mine[s]) if p not in seen)
    out: list = []
    for i, _, p in queue:
        if missing <= 0 or i > queue[0][0] or len(out) == missing:
            break
        if p not in out:
            out.append(p)
    return out


def read_units(con, root: str, by_source: dict, rows, cand: str, judge: list, bar, *, limit: int | None = None,
               sample: int | None = None, local: bool = False) -> tuple:
    """#2035: the selection's data files read in the fixed order of units, only as far as limit (--limit) and sample
    (--sample) need: whole files before their rows, in a fixed hash order so that it repeats (a block sample, as
    DuckDB's system sampling takes whole vectors). by_source: {source: the full paths of its data files under root}
    (source_files); each source's files are ordered by file_key, which table fetch_files (file_keys_sql) gives the
    rows. Each round reads the next files: with limit (#2144), the sources' files taken in turn (turn_files), the next
    turn's files not read yet, as many as units are missing; with sample alone, the next file not read yet of each
    source with fewer than sample units. rows(paths) is the SELECT of the selection's rows in those files (table_rows):
    a round copies them into table fetch_p<round> when local (a selection of at most LOCAL_ROWS rows) or makes that a
    view over them, makes p over it (complete_rows) and adds the lines cand (cand_select keyed) gives (table fetch_new)
    to table fetch_read. judge (cand_steps over fetch_read) then judges every criterion again over all the lines read:
    with sample alone after a round that can change which units pass, one that read a line passing every row criterion
    (a round with no such line changes none, as the rows of a unit lie in one data file: layout2_stream._pack_group
    keeps them together); with limit only once the units judged to pass before and the units whose rows all pass in the
    rounds since (at least as many as the units that pass) reach limit, the next files then chosen by the units judged.
    The lines of the rounds not judged are judged at the end. The rounds stop when enough units pass (limit in all,
    each source counted up to sample; else sample for every source) or no file is left, so a file is read only when
    the units of the files before it were not enough. bar (step_bar) counts the files read. -> (the paths read, in the
    order read; the number of rounds)."""
    rel = {p: p[len(root) + 1:] for ps in by_source.values() for p in ps}
    waiting(bar, con, con.execute, file_keys_sql(root, f"SELECT unnest({file_list(sorted(set(rel.values())))}) AS f"))
    key = {p: file_key(r) for p, r in rel.items()}
    mine = {s: sorted(ps, key=key.__getitem__) for s, ps in by_source.items()}
    turn = {s: source_turn(s) for s in mine}
    done: list = []
    seen: set = set()
    # {source: its units that pass, as last judged}, and with limit {source: its units whose rows all pass in the
    # rounds since}
    kept: dict = {}
    since: dict = {}
    rounds = 0
    stale = False
    while True:
        if limit is not None:
            nxt = turn_files(mine, seen, {s: kept.get(s, 0) + since.get(s, 0) for s in mine}, turn, limit, sample)
            if not nxt and stale:
                for q in judge:
                    waiting(bar, con, con.execute, q)
                kept = {str(s): int(n) for s, n in con.execute(
                    "SELECT source, count(*) FROM fetch_units WHERE fail IS NULL GROUP BY source").fetchall()}
                since, stale = {}, False
                continue
        else:
            short = {s for s in mine if sample is None or kept.get(s, 0) < sample}
            nxt = sorted({next((p for p in mine[s] if p not in seen), "") for s in short} - {""}, key=key.__getitem__)
        if not nxt:
            break
        part = f"fetch_p{rounds}"
        waiting(bar, con, con.execute, f"CREATE OR REPLACE {'TABLE' if local else 'VIEW'} {part} AS {rows(nxt)}")
        waiting(bar, con, con.execute, f"CREATE OR REPLACE VIEW p0 AS SELECT * FROM {part}")
        waiting(bar, con, complete_rows, con)
        waiting(bar, con, con.execute, f"CREATE OR REPLACE TEMP TABLE fetch_new AS {cand}")
        waiting(bar, con, con.execute, "INSERT INTO fetch_read SELECT * FROM fetch_new" if rounds else
                "CREATE OR REPLACE TEMP TABLE fetch_read AS SELECT * FROM fetch_new")
        passing = con.execute("SELECT count(*) FILTER (WHERE fail IS NULL) FROM fetch_new").fetchone()[0]
        done += nxt
        seen.update(nxt)
        rounds += 1
        bar.update(len(nxt))
        stale = True
        if limit is not None:
            for s, n in con.execute(
                    "SELECT source, count(*) FROM (SELECT source, unit FROM fetch_new WHERE unit IS NOT NULL "
                    "GROUP BY source, unit HAVING max(fail) IS NULL) GROUP BY source").fetchall():
                since[str(s)] = since.get(str(s), 0) + int(n)
        elif passing:
            for q in judge:
                waiting(bar, con, con.execute, q)
            kept = {str(s): int(n) for s, n in con.execute(
                "SELECT source, count(*) FROM fetch_units WHERE fail IS NULL GROUP BY source").fetchall()}
            stale = False
    if stale:
        for q in judge:
            waiting(bar, con, con.execute, q)
    return done, rounds


def picked_rows(con, root: str, rows, read: list, rounds: int, local: bool) -> None:
    """#2035: view p over what fetch_rows (rows_steps) takes whole after read_units read the data files read (full
    paths under root) in rounds and the units were picked (pick_steps): when local, the tables fetch_p<round> of its
    rounds, held in memory; else rows (table_rows) of the files read that hold a row of fetch_pick, read again, and of
    no other file."""
    if local:
        con.execute("CREATE OR REPLACE VIEW p0 AS "
                    + " UNION ALL BY NAME ".join(f"SELECT * FROM fetch_p{i}" for i in range(rounds)))
    else:
        need = [str(r[0]) for r in con.execute(
            f"SELECT f FROM (SELECT unnest({file_list(read)}) AS f) WHERE {row_file_sql(root, 'f')} IN "
            "(SELECT row_file FROM fetch_pick) ORDER BY f").fetchall()]
        con.execute(f"CREATE OR REPLACE VIEW p0 AS {rows(need)}")
    complete_rows(con)


def part_query(lo: str = "", hi: str = "") -> str:
    """The rows of fetch_rows whose fetch_key lies in [lo, hi) (an empty bound is open), in fetch order. The rows of
    a unit share its key, so they come together."""
    where = [f"p.fetch_key >= {sql_str(lo)}"] if lo else []
    where += [f"p.fetch_key < {sql_str(hi)}"] if hi else []
    return ("SELECT * EXCLUDE (fetch_key, fetch_source_file) FROM fetch_rows p"
            + ("\nWHERE " + " AND ".join(where) if where else "")
            + "\nORDER BY p.fetch_key, p.row_file, p.row_index")


def part_queries(con, memory_limit: str) -> list:
    """Queries that return fetch_rows in fetch order, split into key ranges so that each range holds at most
    PART_SHARE of the memory limit (the fetch key is a hex SHA-256, so equal ranges of its first four digits hold
    about equal numbers of rows). Sizes are the bytes of the text and binary values plus 8 for any other value."""
    lens = []
    for name, typ, *_ in con.execute("DESCRIBE fetch_rows").fetchall():
        col = '"' + name.replace('"', '""') + '"'
        lens.append(f"coalesce(strlen({col}), 0)" if typ == "VARCHAR"
                    else f"coalesce(octet_length({col}), 0)" if typ == "BLOB" else "8")
    total = con.execute(f"SELECT coalesce(sum({' + '.join(lens)}), 0) FROM fetch_rows").fetchone()[0]
    budget = max(1, int((memory_bytes(memory_limit) or MEMORY_CAP) * PART_SHARE))
    n = max(1, min(1 << 16, -(-int(total) // budget)))
    bounds = ["" if i in (0, n) else format(i * (1 << 16) // n, "04x") for i in range(n + 1)]
    return [part_query(bounds[i], bounds[i + 1]) for i in range(n)]


def is_remote(root: str) -> bool:
    return "://" in root


HF_DATASETS = "hf://datasets/"


# a tag or branch name, or (#1779) a pull request's ref refs/pr/<n>, read before it is merged by the publish job's audit
REF_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}|refs/pr/[1-9][0-9]{0,9}")


def repo_revision(repo: str, *, token: str | None = None, timeout: float = 30, ref: str = "main") -> str:
    """The commit a branch or tag of the dataset repo (ref, default main) points to now (huggingface_hub's repo_info,
    field sha). The token (or huggingface_hub's own, HF_TOKEN first, when none is given) is sent when there is one."""
    from huggingface_hub import HfApi

    if not REF_RE.fullmatch(ref) or ".." in ref:
        raise ValueError(f"not a branch or tag name: {ref[:60]!r}")
    sha = str(HfApi().repo_info(repo, repo_type="dataset", revision=ref, timeout=timeout, token=token).sha or "")
    if not re.fullmatch(r"[0-9a-f]{40}", sha):
        raise ValueError(f"the Hub API gave no commit for {repo}")
    return sha


def pin_root(root: str, *, revision=None, warn=None, ref_ok: bool = False) -> str:
    """hf://datasets/<owner>/<name>[/...] -> the same root at the current commit, hf://datasets/<owner>/<name>@<commit>
    [/...] (DuckDB reads hf:// paths at a revision given after @), so every file of a long query comes from one
    commit even when the repo gets new commits meanwhile. A root that already names a revision, and any other
    root, is returned as it is. When the commit cannot be read the root is returned as it is (the main branch is
    read) and warn gets one line saying why."""
    root = root.rstrip("/")
    if not root.startswith(HF_DATASETS):
        return root
    parts = root[len(HF_DATASETS):].split("/", 2)
    if len(parts) < 2 or not all(parts[:2]) or "@" in parts[0] or "@" in parts[1]:
        return root
    repo = f"{parts[0]}/{parts[1]}"
    try:
        sha = str((revision or repo_revision)(repo) or "")
        if not (re.fullmatch(r"[0-9a-f]{40}", sha) or (ref_ok and REF_RE.fullmatch(sha) and ".." not in sha)):
            raise ValueError(f"not a commit id: {sha[:60]!r}")
    except Exception as e:  # noqa: BLE001  any failure falls back to main
        (warn or _stderr)(f"could not read the current commit of {repo} ({type(e).__name__}: {e}); reading the "
                          f"main branch, which can change while the query runs")
        return root
    return f"{HF_DATASETS}{repo}@{sha}" + (f"/{parts[2]}" if len(parts) > 2 else "")


def _stderr(msg: str) -> None:
    print(f"warning: {msg}", file=sys.stderr)


DUCKDB_MAX_TEMP = "100GB"


def max_temp_size() -> str:
    return os.environ.get("DUCKDB_MAX_TEMP") or DUCKDB_MAX_TEMP


def _cgroup_limit() -> int | None:
    """The memory limit of this process's cgroup (v2 memory.max, else v1 memory.limit_in_bytes), when one is set."""
    for p in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):
        try:
            v = Path(p).read_text().strip()
        except OSError:
            continue
        if v.isdigit() and int(v) < 1 << 60:
            return int(v)
    return None


def default_memory_limit() -> str:
    """The DuckDB memory limit used when --memory-limit is not given: the smaller of MEMORY_CAP and a quarter of the
    memory this process may use (physical memory, or the cgroup limit when lower; MEMORY_CAP when neither can be
    read). DuckDB's own default is 80% of physical memory; a selection over a large local copy (a sort over every
    data file) then grows towards that instead of spilling to the temporary directory."""
    try:
        total = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES")
    except (AttributeError, ValueError, OSError):
        total = 0
    cg = _cgroup_limit()
    if cg is not None:
        total = min(total, cg) if total > 0 else cg
    limit = min(MEMORY_CAP, total // 4) if total > 0 else MEMORY_CAP
    return f"{max(limit >> 20, 256)}MiB"


def memory_bytes(limit: str):
    """A memory size such as 4GB, 512MiB or 8 GiB in bytes (GB = 1000^3, GiB = 1024^3, as DuckDB reads them);
    None for anything else."""
    m = re.fullmatch(r"\s*(\d+(?:\.\d+)?)\s*(?:([KMGT])(i?)B?)?\s*B?\s*", str(limit or ""), re.I)
    if not m:
        return None
    unit = (1024 if m.group(3) else 1000) ** " KMGT".index((m.group(2) or " ").upper())
    return int(float(m.group(1)) * unit)


def default_threads(memory_limit: str):
    """DuckDB threads for a memory limit: one per THREAD_MEMORY of it, at least 1, at most the CPU count (None when
    the limit cannot be read: DuckDB's own default then)."""
    n = memory_bytes(memory_limit)
    return None if n is None else max(1, min(os.cpu_count() or 1, n // THREAD_MEMORY))


def http_settings(con, threads: int = REMOTE_THREADS) -> None:
    """Retries, backoff and timeout for network reads (HTTP_SETTINGS), and fewer threads. A setting this DuckDB
    does not know is skipped with a note on stderr."""
    for key, value in [*HTTP_SETTINGS.items(), ("threads", threads)]:
        try:
            con.execute(f"SET {key} = {int(value)}")
        except Exception as e:  # noqa: BLE001 (an older DuckDB, or the httpfs extension could not be loaded)
            print(f"note: could not set {key}: {type(e).__name__}: {str(e).splitlines()[0][:200]}", file=sys.stderr)


def duckdb_proxy_sql(proxy) -> list:
    """The DuckDB settings that send its http(s):// and hf:// reads through proxy (an http:// proxy, with its user
    name and password). DuckDB has no SOCKS support: a socks proxy raises ValueError."""
    if not proxy:
        return []
    u = urllib.parse.urlsplit(proxy)
    if u.scheme.lower().startswith("socks"):
        raise ValueError(f"DuckDB cannot read through a SOCKS proxy ({redact_proxy(proxy)}): the table reads would "
                         f"go out directly. Use an http:// proxy, or download the tables first and pass the copy "
                         f"with --data")
    if u.scheme.lower() not in ("http", "https") or not u.hostname:
        raise ValueError(f"not a proxy address: {redact_proxy(proxy)}")
    hp = u.hostname + (f":{u.port}" if u.port else "")
    out = [f"SET http_proxy = {sql_str(hp)}"]
    if u.username:
        out.append(f"SET http_proxy_username = {sql_str(urllib.parse.unquote(u.username))}")
    if u.password:
        out.append(f"SET http_proxy_password = {sql_str(urllib.parse.unquote(u.password))}")
    return out


def connect(memory_limit: str | None = None, temp_dir: str | None = None, settings: dict | None = None, *,
            remote: bool = False, token: str | None = None, proxy: str | None = None):
    """A DuckDB connection. remote: the tables are read over the network (see HTTP_SETTINGS). token: the Hugging
    Face token to read with; without one the HF_TOKEN environment variable is used when set."""
    try:
        import duckdb
    except ImportError:
        sys.exit("fetch.py needs the duckdb package: pip install duckdb")
    con = duckdb.connect()
    merged = {"max_temp_directory_size": max_temp_size(), **(settings or {})}
    for key, value in merged.items():
        con.execute(f"SET {key} = {sql_str(value)}")
    if memory_limit:
        con.execute(f"SET memory_limit = {sql_str(memory_limit)}")
    if temp_dir:
        con.execute(f"SET temp_directory = {sql_str(temp_dir)}")
    setup = []
    if remote:
        con.execute("CALL enable_logging('HTTP', storage_buffer_size = 0)")  # #2177: hub_requests reads it
        http_settings(con)
        for key, value in HTTP_SETTINGS.items():
            setup.append(f"SET {key} = {int(value)}")
        for q in duckdb_proxy_sql(proxy):
            con.execute(q)
            setup.append(q)
    token = token or os.environ.get("HF_TOKEN")
    if token:
        try:
            con.execute(f"CREATE SECRET hf_token (TYPE huggingface, TOKEN {sql_str(token)})")
        except Exception as e:  # noqa: BLE001 (keep the token out of the message)
            raise RuntimeError(f"could not register the Hugging Face token: {type(e).__name__}: "
                               f"{str(e).replace(token, '***')}") from None
    _SETUP[id(con)] = [q for q in setup if _settable(con, q)]
    return con


def hub_class(url) -> str | None:
    """#2177: the class Hugging Face counts a request to url under: resolver (a /resolve/ URL: a file's bytes, or the
    HEAD that asks for its size), api (/api/) or other, for a URL of HUB_HOST; None for another host (an upstream site,
    or the storage a /resolve/ URL redirects to)."""
    u = urllib.parse.urlsplit(str(url))
    if (u.hostname or "").lower() != HUB_HOST:
        return None
    return "resolver" if "/resolve/" in u.path else "api" if u.path.startswith("/api/") else "other"


def count_sent(url) -> None:
    """#2177: one request to url, counted in HUB_SENT by its class (hub_class)."""
    k = hub_class(url)
    if k is not None:
        HUB_SENT[k] += 1


def hub_requests(con, remote: bool) -> dict:
    """#2177: the requests this run sent to the Hub, by class (hub_class): those of HUB_SENT and, for a remote read,
    those DuckDB's own HTTP log holds (connect enables it). -> {resolver, api, other}."""
    out = dict(HUB_SENT)
    if remote:
        for (url,) in con.execute("SELECT request.url FROM duckdb_logs_parsed('HTTP')").fetchall():
            k = hub_class(url)
            if k is not None:
                out[k] += 1
    return out


def _settable(con, q: str) -> bool:
    """False for a setting this DuckDB does not know (http_settings already said so), so cursors skip it."""
    try:
        con.cursor().execute(q).close()
    except Exception:  # noqa: BLE001
        return False
    return True


def load_specs(con, root: str) -> dict:
    text = con.execute(f"SELECT content FROM read_text({sql_str(root + '/meta/sources.json')})").fetchone()[0]
    return {s["source"]: s["layout"] for s in json.loads(text)["sources"]}


# ---------- one table row -> the full pointer ----------

def derive_pid(rule, source, collection, uri, offset):
    if not rule or not isinstance(source, str) or not isinstance(collection, str) or not isinstance(uri, str):
        return None
    tail = "/".join(uri.split("/")[-int(rule["segments"]):])
    if rule.get("at_offset"):
        if not (isinstance(offset, int) and not isinstance(offset, bool)):
            return None
        tail += f"@{offset}"
    return f"{source}:{collection}:{tail}"


def member_pid(source, collection, parent, member):
    if not all(isinstance(v, str) for v in (source, collection, parent, member)) or parent.count(":") < 2:
        return None
    return f"{source}:{collection}:{parent.split(':', 2)[2]}!/{member}"


def derive_alts(rule, uri):
    if not rule or not isinstance(uri, str):
        return None
    out = []
    for f, t, suf in rule["pairs"]:
        if not uri.startswith(f):
            return None
        out.append(t + uri[len(f):] + suf)
    return out


def derive_hash(seg, uri):
    if not isinstance(uri, str):
        return None
    parts = uri.split("/")
    k, j = seg
    if k > len(parts):
        return None
    return "".join(parts[-k:len(parts) - j])


def unswap(rule, stored):
    f, t, suf = rule["pairs"][0]
    if not isinstance(stored, str) or not stored.startswith(t) or not stored.endswith(suf) \
            or len(stored) < len(t) + len(suf):
        return None
    return f + stored[len(t):len(stored) - len(suf)]


def _hex(v):
    return v.hex() if isinstance(v, (bytes, bytearray)) else v


def restore(col: dict, spec: dict) -> dict:
    """One table row (column name -> value) and the source's layout from meta/sources.json -> the full pointer."""
    x = json.loads(col["extra"]) if col.get("extra") else {}
    if "_row" in x:
        return x["_row"]
    r = copy.deepcopy(spec["constants"])
    r["source"] = col["source"]
    for k in ("collection", "ext", "size_bytes"):
        r[k] = col.get(k)
    arule = spec.get("alt_uris")
    uri = col["uri"]
    if arule and arule["swap"] and not x.get("_uri_orig"):
        r["uri"] = unswap(arule, uri)
        r["alt_uris"] = derive_alts(arule, r["uri"])
    else:
        r["uri"] = uri
        if arule and not x.get("_uri_orig"):
            a = derive_alts(arule, uri)
            if a is not None:
                r["alt_uris"] = a
    r["hashes"] = {n: _hex(col[n]) for n, _ in HASH_COLS if col.get(n) is not None}
    for h, seg in (spec.get("hash_from_uri") or {}).items():
        v = derive_hash(seg, r["uri"])
        if v is not None:
            r["hashes"][h] = v
    for h in x.pop("_hx", []):
        r["hashes"].pop(h, None)
    r["hashes"].update(x.pop("hashes", {}))
    for k in ("media_type", "member_path", "parent_pointer_id"):
        if col.get(k) is not None:
            r[k] = col[k]
    if col.get("zip_local_header_offset") is not None:
        r["zip_entry"] = {k: col.get(c) for k, c in ZIP_COLS}
    if col.get("range_offset") is not None:
        r["range"] = {"offset": col["range_offset"], "length": col.get("range_length")}
    if col.get("origin_url") is not None:
        r["origin"] = {"url": col["origin_url"]}
        if col.get("origin_time") is not None:
            r["origin"]["captured_at"] = col["origin_time"]
    lo = {k: col[c] for c, k in LICENSE_COLS if col.get(c) is not None}
    if lo:
        r["license_override"] = lo
    if col.get("sensitive") is not None:
        r["sensitive"] = col["sensitive"]
    if "pointer_id" in x:
        pid = x.pop("pointer_id")
    elif "pid" in x:
        pid = f"{r['source']}:{r['collection']}:{x.pop('pid')}"
    elif col.get("parent_pointer_id") is not None and col.get("member_path") is not None:
        pid = member_pid(r["source"], r["collection"], col["parent_pointer_id"], col["member_path"])
    else:
        pid = derive_pid(spec.get("pointer_id"), r["source"], r["collection"], r["uri"], col.get("range_offset"))
    r["pointer_id"] = pid
    absent = x.pop("_absent", [])
    x.pop("_uri_orig", None)
    r.update(x)
    if col.get("truncated") is not None:
        sm = dict(r.get("source_meta") or {})
        sm[TRUNC_KEY] = col["truncated"]
        r["source_meta"] = sm
    for k in absent:
        r.pop(k, None)
    return r


# ---------- download and verify ----------

class Unsupported(Exception):
    pass


def to_http(uri: str):
    if uri.startswith(("https://", "http://")):
        return uri
    if uri.startswith("s3://"):
        bucket, _, key = uri[5:].partition("/")
        return f"https://s3.amazonaws.com/{bucket}/{urllib.parse.quote(key)}"
    if uri.startswith("hf://datasets/"):
        from huggingface_hub import hf_hub_url, parse_hf_uri

        u = parse_hf_uri(uri)  # a string parser, no request to the Hub
        return hf_hub_url(u.id, u.path_in_repo, repo_type=u.type, revision=u.revision)
    return None


def candidates(row: dict) -> list:
    out = []
    for u in [row.get("uri"), *(row.get("alt_uris") or [])]:
        h = to_http(u) if isinstance(u, str) else None
        if h and h not in out:
            out.append(h)
    first = to_http(row["uri"]) if isinstance(row.get("uri"), str) else None
    if str(row.get("uri")).startswith("s3://") and first in out and len(out) > 1:
        out.remove(first)
        out.append(first)
    return out


class UnsafePath(ValueError):
    """A row whose file would be written outside --out (or through a symbolic link); nothing is written for it."""


def _safe_parts(value, what: str) -> list:
    """One path value of a row (pointer_id tail, source or collection) as safe path parts: backslashes count as
    separators, empty and . parts are dropped, a .. part or a NUL character refuses the row."""
    s = str(value)
    if "\0" in s:
        raise UnsafePath(f"unsafe {what}: contains a NUL character")
    parts = [p for p in s.replace("\\", "/").split("/") if p not in ("", ".")]
    if not parts or ".." in parts or any(re.fullmatch(r"[A-Za-z]:", p) for p in parts[:1]):
        raise UnsafePath(f"unsafe {what}: {s[:200]!r}")
    return parts


def dest_path(root: Path, row: dict) -> Path:
    """Where the row's file is written: <root>/<the row's _dest_parts> when the run planned its place in the layout
    (layout_parts), else <root>/<source>/<collection>/<pointer_id tail>. Every segment is cleaned the same way
    (_safe_parts) and the resolved path must lie inside root; a path that leaves root (also through a symbolic link
    already on disk) raises UnsafePath."""
    if row.get("_dest_parts"):
        parts = [x for p in row["_dest_parts"] for x in _safe_parts(p, "path part")]
        return _inside(root, parts)
    pid = row.get("pointer_id")
    if isinstance(pid, str) and pid.count(":") >= 2:
        rel = pid.split(":", 2)[2]
    else:
        rel = _pid_fallback(row)
    parts = (_safe_parts(row.get("source"), "source") + _safe_parts(row.get("collection"), "collection")
             + _safe_parts(rel, "relative path"))
    return _inside(root, parts)


def _pid_fallback(row: dict) -> str:
    key = "\0".join(str(row.get(k)) for k in ("source", "uri", "range", "member_path"))
    return hashlib.sha256(key.encode("utf-8")).hexdigest()[:24]


def _inside(root: Path, parts: list) -> Path:
    dest = Path(root, *parts)
    top = Path(root).resolve()
    want = top.joinpath(*parts)
    real = want.resolve()
    if top not in real.parents:
        raise UnsafePath(f"unsafe path: {dest} is outside {root}")
    if real != want:
        raise UnsafePath(f"unsafe path: {dest} goes through a symbolic link")
    return dest


class Hasher:
    def __init__(self, size):
        self.h = {n: hashlib.new(n) for n in ("md5", "sha1", "sha256", "sha512")}
        self.git = hashlib.sha1(f"blob {size}\0".encode()) if size is not None else None
        self.crc = 0
        self.n = 0

    def update(self, b: bytes) -> None:
        for h in self.h.values():
            h.update(b)
        if self.git is not None:
            self.git.update(b)
        self.crc = zlib.crc32(b, self.crc)
        self.n += len(b)

    def digests(self) -> dict:
        out = {n: h.hexdigest() for n, h in self.h.items()}
        out["git_blob_sha1"] = self.git.hexdigest() if self.git else ""
        out["crc32"] = f"{self.crc & 0xFFFFFFFF:08x}"
        return out


def _etag_md5(etag):
    if not etag:
        return None
    e = str(etag).strip().strip('"').replace("&quot;", "")
    return e if len(e) == 32 and all(c in "0123456789abcdef" for c in e) else None


CHECKED_HASHES = ("crc32", "md5", "sha1", "sha256", "sha512", "git_blob_sha1")
# hash names that describe something other than the bytes written (or carry no value to compare)
NOT_CONTENT_HASHES = frozenset({"etag", "hash_source", "algorithm", "scope"})


def _want_hash(name: str, value) -> str:
    if name == "crc32" and isinstance(value, int):
        return f"{value & 0xFFFFFFFF:08x}"
    v = str(value or "").strip().lower()
    return v.zfill(8) if name == "crc32" and v and len(v) < 8 else v


def check_hashes(hashes: dict, got: dict, names=CHECKED_HASHES):
    """Compare every hash the row publishes with the computed digests: crc32, md5, sha1, sha256, sha512,
    git_blob_sha1 and a single-part etag (an md5). -> (reason or None, number checked)."""
    checked = 0
    for name in names:
        want = _want_hash(name, (hashes or {}).get(name))
        if want:
            checked += 1
            if not got.get(name) or got[name] != want:
                return f"{name} differs: expected {want}, got {got.get(name) or '(not computable)'}", checked
    et = _etag_md5((hashes or {}).get("etag"))
    if et:
        checked += 1
        if got["md5"] != et:
            return f"etag (single-part md5) differs: expected {et}, got {got['md5']}", checked
    return None, checked


def unchecked_hashes(row: dict) -> list:
    """The names of hashes the row publishes that this tool cannot compute (recorded in the manifest)."""
    return sorted(k for k, v in (row.get("hashes") or {}).items()
                  if v and k not in CHECKED_HASHES and k not in NOT_CONTENT_HASHES)


def verify(row: dict, size: int, got: dict, names=CHECKED_HASHES):
    """None when the size and every published hash match, otherwise the reason."""
    if row.get("size_bytes") is not None and size != row["size_bytes"]:
        return f"size differs: expected {row['size_bytes']}, got {size}"
    hashes = row.get("hashes") or {}
    if not hashes and row.get("hash_source") == "computed_on_fetch":
        return None
    why, checked = check_hashes(hashes, got, names)
    if why:
        return why
    return None if checked else "no hash that can be checked"


def is_rolling(row: dict) -> bool:
    """True for a file the source regenerates in place (ROLLING_FILES, or source_meta.rolling on the row)."""
    sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
    return bool(sm.get("rolling")) or (row.get("source"), row.get("collection")) in ROLLING_FILES


def no_hash_fields(row: dict, res: dict, sha256: str, note: str) -> dict:
    """The manifest fields of a row without hashes: unverified, the computed sha256, and checked "size only"
    when its size was checked."""
    if row.get("hashes"):
        return res
    res["unverified"] = note
    res["sha256"] = sha256
    if row.get("size_bytes") is not None:
        res["checked"] = SIZE_ONLY
    return res


def range_header(rng) -> str:
    """rng is (offset, length); offset None asks for the last length bytes."""
    if rng[0] is None:
        return f"bytes=-{rng[1]}"
    return f"bytes={rng[0]}-{rng[0] + rng[1] - 1}"


PROXY_SCHEMES = ("http", "https", "socks5", "socks5h", "socks4", "socks4a")


def redact_proxy(proxy: str) -> str:
    """A proxy address without its user name and password (for messages)."""
    u = urllib.parse.urlsplit(proxy or "")
    if not u.hostname:
        return str(proxy)
    return u._replace(netloc=u.hostname + (f":{u.port}" if u.port else "")).geturl()


def env_proxy(env=None):
    """The proxy named by the environment: HTTPS_PROXY, then HTTP_PROXY, then ALL_PROXY (either case)."""
    env = os.environ if env is None else env
    for k in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"):
        if env.get(k):
            return env[k]
    return None


RETRY_STATUS = (429, 500, 502, 503, 504)


def make_session(proxy=None):
    """The requests session every download uses: urllib3 Retry retries connection errors and RETRY_STATUS answers
    RETRIES more times, BACKOFF seconds doubling in between (or as long as a Retry-After header asks); plus proxy (an
    http://, https://, socks5://, socks5h://, socks4:// or socks4a:// address, SOCKS through requests[socks]) when
    given. proxy None means a direct connection."""
    ses = requests.Session()
    ses.trust_env = False
    ses.hooks["response"].append(lambda r, **kw: count_sent(r.url))  # each answer, a redirect's included
    adapter = HTTPAdapter(max_retries=Retry(
        total=RETRIES, backoff_factor=BACKOFF, status_forcelist=RETRY_STATUS, respect_retry_after_header=True,
        raise_on_status=False))
    ses.mount("https://", adapter)
    ses.mount("http://", adapter)
    if proxy:
        if urllib.parse.urlsplit(proxy).scheme.lower() not in PROXY_SCHEMES:
            raise SystemExit(f"error: unsupported proxy {redact_proxy(proxy)}; use one of "
                             + ", ".join(s + "://" for s in PROXY_SCHEMES))
        ses.proxies = {"http": proxy, "https": proxy}
    return ses


class _Net:
    """The network set_network configured: the session open_url uses, the User-Agent and the proxy."""
    session: requests.Session | None = None
    ua: str = UA
    proxy: str | None = None


_NET = _Net()


def user_agent(contact=None) -> str:
    """The User-Agent sent: UA, or with --contact the same product name and the caller's own contact."""
    return f"{UA} (contact: {contact})" if contact else UA


def set_network(proxy=None, contact=None) -> requests.Session:
    """Configure the proxy and the User-Agent (with the --contact address) that open_url and remote_file use."""
    ses = make_session(proxy)
    _NET.session, _NET.ua, _NET.proxy = ses, user_agent(contact), proxy
    return ses


def net_session() -> requests.Session:
    """The session set_network configured; configured from the environment's proxy when nothing called it yet."""
    ses = _NET.session
    if ses is None:
        ses = set_network(env_proxy())
    return ses


def open_url(url: str, timeout: float, rng=None, headers=None):
    """rng is (offset, length), offset None for the last length bytes. HTTP gets a Range header and must answer
    206. headers are extra request headers. Only http(s) addresses are opened; a local --data copy is read through
    local_file_opener, never through an address. -> the undecoded response body (urllib3), with status and
    headers."""
    if not url.startswith(("https://", "http://")):
        raise Unsupported(f"only http(s) addresses are fetched, not {url.split(':', 1)[0][:20]}://")
    ses = net_session()
    # the body is read undecoded (r.raw), so no content coding is asked for: requests sends Accept-Encoding gzip by
    # default, and a server that compresses a text file would hand back bytes whose size and hash are not the file's
    # (the channel's streams do the same, channel.Http._call)
    headers = {"User-Agent": _NET.ua, "Accept-Encoding": "identity", **(headers or {})}
    if rng:
        headers["Range"] = range_header(rng)
    r = ses.get(url, headers=headers, timeout=timeout, stream=True)
    try:
        r.raise_for_status()
        if rng and r.status_code != 206:
            raise Unsupported(f"the server ignored the Range request (HTTP {r.status_code})")
    except BaseException:
        r.close()
        raise
    return r.raw


class RangeIgnored(Unsupported):
    """A server answered a byte-range request of a remote file with the whole file (HTTP 200)."""


async def _range_honoured(resp) -> None:
    """aiohttp raise_for_status hook of remote_file: fsspec's HTTPFile takes a 200 answer to a Range request as the
    range when its Content-Length is no more than the range (async_fetch_range in fsspec/implementations/http.py),
    and reads the whole body for a range at offset 0; such an answer fails here instead."""
    if resp.status == 200 and "Range" in resp.request_info.headers:
        raise RangeIgnored(f"the server ignored the Range request of {resp.url.host} (HTTP 200)")


def remote_source(row: dict, url: str) -> str:
    """What remote_file reads for the row at url: the row's hf:// address whose HTTPS form is url (alt_uris
    included), the local copy when url is the row's _local_file, else url."""
    if row.get("_local_file") == url:
        return url
    for u in [row.get("uri"), *(row.get("alt_uris") or [])]:
        if isinstance(u, str) and u.startswith("hf://") and to_http(u) == url:
            return u
    return url


def remote_file(src: str, timeout: float, block_size: int):
    """A seekable read-only file over src (see remote_source), read by byte ranges of block_size: huggingface_hub's
    HfFileSystem for an hf:// address, the file itself for a local copy, else fsspec's HTTPFile with the proxy and
    User-Agent of set_network. A server that ignores the byte ranges fails the read (RangeIgnored); fsspec has no
    SOCKS client, so a SOCKS proxy fails the row (Unsupported)."""
    if src.startswith("hf://"):
        from huggingface_hub import HfFileSystem

        return HfFileSystem().open(src, "rb", block_size=block_size)
    if not src.startswith(("https://", "http://")):
        return open(src, "rb")
    import aiohttp
    import fsspec

    net_session()
    proxy = _NET.proxy
    if proxy and urllib.parse.urlsplit(proxy).scheme.lower().startswith("socks"):
        raise Unsupported("archive members are read by byte ranges through fsspec, which cannot use a SOCKS proxy")
    fs = fsspec.filesystem("http", skip_instance_cache=True, **({"proxy": proxy} if proxy else {}), client_kwargs={
        "raise_for_status": _range_honoured, "headers": {"User-Agent": _NET.ua},
        "timeout": aiohttp.ClientTimeout(sock_connect=timeout, sock_read=timeout)})
    return fs.open(src, "rb", block_size=block_size)


def local_file_opener(path):
    """An opener for one file of the local --data copy (a repository file a campaign row names). It ignores the
    address and reads only that file; index rows cannot name local files, only resolve_repo_uri sets this up."""

    def op(url, timeout, rng=None, headers=None):
        f = open(path, "rb")
        if not rng:
            return f
        with f:
            if rng[0] is None:
                f.seek(0, 2)
                f.seek(max(0, f.tell() - rng[1]))
            else:
                f.seek(rng[0])
            return io.BytesIO(f.read(rng[1]))
    return op


def transient(e: BaseException) -> bool:
    if isinstance(e, requests.HTTPError):
        return 500 <= e.response.status_code < 600
    return isinstance(e, (requests.ConnectionError, requests.Timeout, urllib3.exceptions.HTTPError, ConnectionError,
                          TimeoutError))


def _write(dest: Path, data: bytes) -> None:
    part = dest.with_name(dest.name + ".part")
    part.write_bytes(data)
    os.replace(part, dest)


def _rng(row: dict):
    r = row.get("range")
    return (r["offset"], r["length"]) if isinstance(r, dict) and r.get("offset") is not None else None


class TooLarge(Exception):
    """The item is larger than the row's cap; nothing is kept."""


def cap_of(row: dict) -> int:
    """The most bytes written for one row: its cap from the query (size_cap_bytes)."""
    v = row.get("_size_cap")
    return int(v) if v is not None else UNKNOWN_SIZE_CAP


def whole_cap_of(row: dict) -> int:
    """The most bytes downloaded or decoded on the way to one row (a whole package, a solid 7z block, a
    compressed member): the larger of the row's cap and its batch cap."""
    vals = [int(v) for v in (row.get("_size_cap"), row.get("_batch_cap")) if v is not None]
    return max(vals) if vals else UNKNOWN_SIZE_CAP


def marked_rolling(row: dict) -> bool:
    """True for a row that says itself it is rolling (source_meta.rolling), whole file, with hashes: a size or hash
    that differs from the row is recorded, not a failure."""
    sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
    return bool(sm.get("rolling")) and bool(row.get("hashes")) and _rng(row) is None


# #2144: an answer of these types (its Content-Type) to a download of a file the row records as not HTML (by its ext,
# none of HTML_EXTS, or its media_type) is a page standing where the file was: the upstream blocks scripts (a bot check
# or a sign-in page). HTML_EXTS also holds the extensions of pages a server makes, which are HTML when they are fetched
HTML_TYPES = ("text/html", "application/xhtml+xml")
HTML_EXTS = ("html", "htm", "xhtml", "shtml", "php", "asp", "aspx", "jsp", "cgi")
HTML_HEAD = 1 << 16  # the first bytes of an answer kept to read a page's title


def html_page(row: dict, content_type: str, head: bytes) -> dict | None:
    """#2144: the page an upstream answered with in place of the row's file when it blocks scripts: an answer whose
    Content-Type (content_type) is one of HTML_TYPES to a download of a file that the row records as not HTML (an ext
    not among HTML_EXTS, or a media_type not among HTML_TYPES; a row that records neither says nothing of it) ->
    {content_type, title: the page's title, read from its first bytes head by _text_of}; None otherwise. fetch_file
    asks only of bytes that failed the row's check."""
    kind = content_type.split(";", 1)[0].strip().lower()
    ext = str(row.get("ext") or "").lower().lstrip(".")
    media = str(row.get("media_type") or "").split(";", 1)[0].strip().lower()
    if kind not in HTML_TYPES or not (ext or media) or ext in HTML_EXTS or media in HTML_TYPES:
        return None
    return {"content_type": kind, "title": _text_of(head)[0][:120]}


def blocked_words(page: dict) -> str:
    """#2144: html_page in words, for the line of a file whose upstream answered with it."""
    title = f' ("{page["title"]}")' if page.get("title") else ""
    return f"the upstream answered with an HTML page{title} in place of the file: it blocks scripts such as this one"


def fetch_file(row, dest, url, timeout, opener):
    want = row.get("size_bytes")
    rolling = want is not None and not row.get("hashes") and _rng(row) is None and is_rolling(row)
    loose = marked_rolling(row)
    limit = (max(want, cap_of(row)) if want is not None else cap_of(row)) if rolling or loose \
        else want if want is not None else cap_of(row)
    h = Hasher(want)
    head = bytearray()
    part = dest.with_name(dest.name + ".part")
    # a whole file of known size resumes from the .part an interrupted download left (Range: bytes=n-); a server
    # that answers 200 instead of 206 sends the whole file, which then starts over
    resumable = _rng(row) is None and want is not None and not rolling and not loose
    have = part.stat().st_size if resumable and part.is_file() and not part.is_symlink() else 0
    if not 0 < have < (want or 0):
        have = 0
    try:
        if have:
            src = opener(url, timeout, None, headers={"Range": f"bytes={have}-"})
            status = getattr(src, "status", None) or getattr(src, "code", None) or 200
            crange = str((getattr(src, "headers", None) or {}).get("Content-Range") or "")
            cr = parse_content_range_header(crange)
            if status == 206 and (not cr or cr.units != "bytes" or cr.start != have):
                src.close()
                raise Unsupported(f"the server answered the resume request with Content-Range {crange[:80]!r}")
            if status == 206:
                with open(part, "rb") as old:
                    for b in iter(lambda: old.read(CHUNK), b""):
                        h.update(b)
                mode = "ab"
            else:
                mode = "wb"
        else:
            src, mode = opener(url, timeout, _rng(row)), "wb"
        content_type = str((getattr(src, "headers", None) or {}).get("Content-Type") or "")
        with src, open(part, mode) as out:
            while True:
                b = src.read(CHUNK)
                if not b:
                    break
                if len(head) < HTML_HEAD:
                    head += b[:HTML_HEAD - len(head)]
                h.update(b)
                out.write(b)
                if h.n > limit:
                    break
    except BaseException as e:
        if not (resumable and transient(e) and part.is_file()):
            part.unlink(missing_ok=True)
        raise
    if (want is None or rolling or loose) and h.n > limit:
        part.unlink(missing_ok=True)
        raise TooLarge(f"rolling file: grew past the cap of {limit} bytes" if rolling or loose
                       else f"unknown size: stopped after more than the cap of {limit} bytes")
    changed = rolling and h.n != want
    got = h.digests()
    why = verify({**row, "size_bytes": None} if changed else row, h.n, got)
    page = html_page(row, content_type, bytes(head)) if why or changed else None
    if page:
        part.unlink(missing_ok=True)
        return {"status": "failed", "reason": why or ROLLING_CHANGED, "html_page": page, "url": url, "got_bytes": h.n,
                "got_sha256": got["sha256"]}
    if loose:
        os.replace(part, dest)
        res = {"status": "ok", "path": str(dest), "bytes": h.n, "url": url, "sha256": got["sha256"],
               "retrieved": utc_today()}
        if why:
            res.update(differs_from_index=True, expected_bytes=want,
                       expected_sha256=(row.get("hashes") or {}).get("sha256"), reason=why)
        return res
    if why:
        part.unlink(missing_ok=True)
        return {"status": "failed", "reason": why, "url": url, "got_bytes": h.n, "got_sha256": got["sha256"]}
    os.replace(part, dest)
    res = no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": h.n, "url": url, "sha256": got["sha256"],
                               **({"resumed_from": have} if have and mode == "ab" else {})},
                         h.digests()["sha256"], "the source publishes no hash; sha256 computed on download")
    if changed:
        res["checked"] = ROLLING_CHANGED
        res["expected_bytes"] = want
    return res


# WARC / ARC records

def gunzip_bounded(raw: bytes, limit: int) -> bytes:
    """Decompress gzip data (one or more members, by gzip.GzipFile) without ever holding more than limit + 1 output
    bytes; more output than limit raises TooLarge (a small compressed input can expand without bound)."""
    out = gzip.GzipFile(fileobj=io.BytesIO(raw)).read(limit + 1)
    if len(out) > limit:
        raise TooLarge(f"the data decompresses to more than the cap of {limit} bytes")
    return out


def read_bounded(src, limit: int, what: str) -> bytes:
    """Read a whole response, at most limit bytes; a longer one raises TooLarge."""
    raw = src.read(limit + 1)
    if len(raw) > limit:
        raise TooLarge(f"{what} is larger than the cap of {limit} bytes")
    return raw


def parse_record(raw: bytes, limit: int | None = None) -> dict:
    """One WARC or ARC record (gzip or not), read by warcio (ARC turned into WARC) -> {"http_headers": lower-case
    name: value, "payload": the bytes after the HTTP headers, still chunked if they were sent so}. A payload over
    limit raises TooLarge."""
    limit = UNKNOWN_SIZE_CAP if limit is None else limit
    rec = next(iter(ArchiveIterator(io.BytesIO(raw), arc2warc=True)))
    payload = rec.raw_stream.read(limit + 1)
    if len(payload) > limit:
        raise TooLarge(f"the record's payload is larger than the cap of {limit} bytes")
    heads = rec.http_headers.headers if rec.http_headers else []
    return {"http_headers": {k.lower(): v for k, v in heads}, "payload": payload}


def dechunk(body: bytes) -> bytes:
    return ChunkedDataReader(io.BytesIO(body)).read()


def payload_variants(rec: dict) -> list:
    body = rec["payload"]
    if "chunked" in rec["http_headers"].get("transfer-encoding", "").lower():
        return [("dechunked_payload", dechunk(body)), ("payload", body)]
    return [("payload", body)]


def verify_payload(row: dict, data: bytes):
    want = row.get("payload_size_bytes")
    if want is not None and len(data) != want:
        return f"payload size differs: expected {want}, got {len(data)}"
    h = Hasher(len(data))
    h.update(data)
    why, checked = check_hashes(row.get("hashes") or {}, h.digests())
    return why if why or checked else "no hash that can be checked"


def fetch_payload(row, dest, url, timeout, opener):
    if _rng(row) is None or row.get("size_bytes") is None:
        raise Unsupported("a WARC record row needs a byte range and a size")
    with opener(url, timeout, _rng(row)) as src:
        raw = src.read(row["size_bytes"] + 1)
    if len(raw) != row["size_bytes"]:
        return {"status": "failed", "url": url, "reason": f"size differs: expected {row['size_bytes']}, got {len(raw)}"}
    try:
        rec = parse_record(raw, whole_cap_of(row))
    except TooLarge:
        raise
    except Exception as e:  # noqa: BLE001 (a cut or misplaced record)
        return {"status": "failed", "url": url, "reason": f"cannot parse the record: {type(e).__name__}: {e}"}
    whys = []
    for label, data in payload_variants(rec):
        why = verify_payload(row, data)
        if why is None:
            _write(dest, data)
            return {"status": "ok", "path": str(dest), "bytes": len(data), "matched_on": label, "url": url}
        whys.append(f"{label}: {why}")
    return {"status": "failed", "url": url, "reason": "; ".join(whys)}


# API responses

def extract_field(doc, path: str):
    cur = doc
    for part in path.split("."):
        if isinstance(cur, list) and part.isdigit():
            cur = cur[int(part)] if int(part) < len(cur) else None
        elif isinstance(cur, dict):
            cur = cur.get(part)
        else:
            return None
        if cur is None:
            return None
    return cur


def fetch_api_body(row, dest, url, timeout, opener):
    limit = whole_cap_of(row)
    with opener(url, timeout, None) as src:
        raw = read_bounded(src, limit, "the API response")
    if raw[:2] == b"\x1f\x8b":
        try:
            raw = gunzip_bounded(raw, limit)
        except (zlib.error, EOFError, gzip.BadGzipFile) as e:
            return {"status": "failed", "url": url, "reason": f"cannot decompress the API response: {e}"}
    try:
        doc = json.loads(raw.decode("utf-8"))
    except (UnicodeDecodeError, ValueError) as e:
        return {"status": "failed", "url": url, "reason": f"the API response is not JSON: {e}"}
    path = (row.get("source_meta") or {}).get("api_body_field") or API_BODY_DEFAULT_FIELD
    v = extract_field(doc, path)
    body = ("" if v is None else v if isinstance(v, str) else json.dumps(v, ensure_ascii=False)).encode("utf-8")
    h = Hasher(len(body))
    h.update(body)
    why = verify(row, len(body), h.digests())
    if why:
        return {"status": "failed", "url": url, "reason": f"{path}: {why}"}
    _write(dest, body)
    return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(body),
                                "matched_on": f"api_body:{path}", "url": url},
                          h.digests()["sha256"], "the source publishes no hash; sha256 computed on download")


# zip members

def _get_range(url, timeout, start, length, opener):
    with opener(url, timeout, (start, length)) as r:
        data = r.read(length + 1)
    if len(data) != length:
        raise Unsupported(f"range {start}+{length} returned {len(data)} bytes")
    return data


def member_limit(row: dict) -> int:
    """The most bytes kept for one member: its size when the row knows it (a longer result then fails the size
    check), otherwise the row's cap."""
    return row["size_bytes"] if row.get("size_bytes") is not None else cap_of(row)


def _too_large_unknown(row: dict, size: int, limit: int) -> None:
    if row.get("size_bytes") is None and size > limit:
        raise TooLarge(f"the member has {size} bytes, more than the cap of {limit} bytes")


def _finish(row, dest, data, url, matched_on, names=CHECKED_HASHES):
    """Check data against the row's size and hashes, write it to dest, -> the manifest fields."""
    h = Hasher(len(data))
    h.update(data)
    why = verify(row, len(data), h.digests(), names=names)
    if why:
        return {"status": "failed", "url": url, "reason": why}
    _write(dest, data)
    return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(data), "matched_on": matched_on,
                                "url": url},
                          h.digests()["sha256"], NO_HASH_MEMBER)


ZIP_BLOCK = CHUNK  # bytes per range request when a zip is read through remote_file


@functools.lru_cache(maxsize=4)
def zip_archive(src: str, timeout: float) -> tuple:
    """zipfile's view of the zip at src (see remote_source), kept for the next rows of the same archive ->
    (ZipFile, {local header offset: ZipInfo})."""
    zf = zipfile.ZipFile(remote_file(src, timeout, ZIP_BLOCK))
    return zf, {i.header_offset: i for i in zf.infolist()}


def _zip_read(row, dest, url, zf, zi, matched_on):
    """Read one member with zipfile (at most member_limit + 1 bytes; zipfile checks its CRC32 against the central
    directory when the whole member is read), check it against the row, write it."""
    limit = member_limit(row)
    _too_large_unknown(row, zi.file_size, limit)
    whole = whole_cap_of(row)
    if zi.compress_size > whole:
        raise TooLarge(f"the compressed member has {zi.compress_size} bytes, more than the cap of {whole} bytes")
    try:
        with zf.open(zi) as f:
            data = f.read(limit + 1)
    except NotImplementedError as e:
        raise Unsupported(f"zip member: {e}") from None
    except zipfile.BadZipFile as e:
        return {"status": "failed", "url": url, "reason": f"zip member: {e}"}
    return _finish(row, dest, data, url, matched_on)


def fetch_member(row, dest, url, timeout, opener):
    ze = row.get("zip_entry")
    if not isinstance(ze, dict) or ze.get("local_header_offset") is None:
        raise Unsupported("an archive member row without zip_entry")
    zf, at = zip_archive(remote_source(row, url), timeout)
    zi = at.get(ze["local_header_offset"])
    if zi is None:
        return {"status": "failed", "url": url,
                "reason": f"no member of the zip central directory starts at {ze['local_header_offset']}"}
    return _zip_read(row, dest, url, zf, zi, "zip_member")


# BEGIN GENERATED ARCHIVE FORMATS
# Generated from archive_formats.tsv when tools/fetch.py is built. Do not edit by hand: edit the table
# and rebuild. Every archive and compression decision in this script reads ARCHIVE_FORMATS only.
# Columns: format, class, extensions, magic (hex, empty = none), offset, inner (the format when it holds a tar)
ARCHIVE_FORMATS = (
    ('zip', 'multi_member_archive', ('.zip',), '504b0304', 0, ''),
    ('tar', 'multi_member_archive', ('.tar',), '7573746172', 257, ''),
    ('tar.gz', 'multi_member_archive', ('.tar.gz', '.tgz'), '', 0, ''),
    ('tar.bz2', 'multi_member_archive', ('.tar.bz2', '.tbz2', '.tbz'), '', 0, ''),
    ('tar.xz', 'multi_member_archive', ('.tar.xz', '.txz'), '', 0, ''),
    ('tar.zst', 'multi_member_archive', ('.tar.zst', '.tzst'), '', 0, ''),
    ('tar.lz4', 'multi_member_archive', ('.tar.lz4',), '', 0, ''),
    ('tar.Z', 'multi_member_archive', ('.tar.z', '.taz'), '', 0, ''),
    ('7z', 'multi_member_archive', ('.7z',), '377abcaf271c', 0, ''),
    ('rar', 'multi_member_archive', ('.rar',), '526172211a07', 0, ''),
    ('cab', 'multi_member_archive', ('.cab',), '4d534346', 0, ''),
    ('gz', 'single_file_compression', ('.gz',), '1f8b', 0, 'tar.gz'),
    ('bz2', 'single_file_compression', ('.bz2',), '425a68', 0, 'tar.bz2'),
    ('xz', 'single_file_compression', ('.xz',), 'fd377a585a00', 0, 'tar.xz'),
    ('zst', 'single_file_compression', ('.zst',), '28b52ffd', 0, 'tar.zst'),
    ('lz4', 'single_file_compression', ('.lz4',), '04224d18', 0, 'tar.lz4'),
    ('Z', 'single_file_compression', ('.z',), '1f9d', 0, 'tar.Z'),
    ('npz', 'zip_container', ('.npz',), '504b0304', 0, ''),
    ('xlsx', 'zip_container', ('.xlsx', '.xlsm', '.xltx', '.xltm'), '504b0304', 0, ''),
    ('docx', 'zip_container', ('.docx', '.docm', '.dotx'), '504b0304', 0, ''),
    ('pptx', 'zip_container', ('.pptx', '.pptm', '.potx'), '504b0304', 0, ''),
    ('odf', 'zip_container', ('.odt', '.ods', '.odp', '.odg'), '504b0304', 0, ''),
    ('epub', 'zip_container', ('.epub',), '504b0304', 0, ''),
    ('jar', 'zip_container', ('.jar', '.war', '.ear', '.aar'), '504b0304', 0, ''),
    ('whl', 'zip_container', ('.whl',), '504b0304', 0, ''),
    ('apk', 'zip_container', ('.apk',), '504b0304', 0, ''),
    ('kmz', 'zip_container', ('.kmz',), '504b0304', 0, ''),
    ('nupkg', 'zip_container', ('.nupkg', '.vsix'), '504b0304', 0, ''),
)
# END GENERATED ARCHIVE FORMATS


def format_extensions(*names) -> tuple:
    """The extensions ARCHIVE_FORMATS gives the named formats, longest first."""
    return tuple(sorted({e for f in ARCHIVE_FORMATS if f[0] in names for e in f[2]}, key=lambda e: (-len(e), e)))


# members of software packages: zip-based ones (wheel, jar, nupkg) through the central directory, tar-based
# ones (sdist, npm .tgz, .crate) by downloading the whole package within the cap. Which extensions mean which format
# comes from ARCHIVE_FORMATS; this script only names the formats it can read: the zip-based package formats, and
# the tar formats tarfile opens with the standard library (mode "r:*").

ZIP_PACKAGE_FORMATS = ("zip", "whl", "jar", "nupkg")
TAR_PACKAGE_FORMATS = ("tar", "tar.gz", "tar.bz2", "tar.xz")
EGG = ".egg"      # a Python egg: a zip package, not in the format table
CRATE = ".crate"  # a Cargo crate: a gzip tar under its own name, not in the format table
ZIP_SUFFIXES = format_extensions(*ZIP_PACKAGE_FORMATS) + (EGG,)
TAR_SUFFIXES = format_extensions(*TAR_PACKAGE_FORMATS) + (CRATE,)
SEVENZIP_SUFFIXES = format_extensions("7z")
PACKAGE_CACHE_BYTES = 1_000_000_000  # packages kept on disk during one run, oldest dropped first


def package_kind(uri) -> str | None:
    path = urllib.parse.urlsplit(str(uri or "")).path.lower()
    if path.endswith(ZIP_SUFFIXES):
        return "zip_package"
    if path.endswith(TAR_SUFFIXES):
        return "tar_package"
    if path.endswith(SEVENZIP_SUFFIXES):
        return "sevenzip_member"
    return None


def fetch_zip_package(row, dest, url, timeout, opener):
    name = row.get("member_path")
    zf, _ = zip_archive(remote_source(row, url), timeout)
    try:
        zi = zf.getinfo(name)
    except KeyError:
        return {"status": "failed", "url": url, "reason": f"{name} is not in the package's central directory"}
    return _zip_read(row, dest, url, zf, zi, "zip_package")


_PACKAGES: dict = {"dir": None, "files": {}}


def clear_package_cache() -> None:
    """Delete the packages downloaded during this run."""
    d, _PACKAGES["dir"] = _PACKAGES["dir"], None
    _PACKAGES["files"].clear()
    if d:
        shutil.rmtree(d, ignore_errors=True)


def download_package(url, timeout, opener, limit) -> Path:
    """Download a whole package into a temporary directory kept for this run (reused for its other members);
    stop with TooLarge after limit bytes."""
    files = _PACKAGES["files"]
    if url in files:
        return files[url]
    if _PACKAGES["dir"] is None:
        _PACKAGES["dir"] = tempfile.mkdtemp(prefix="fetch-packages-")
    path = Path(_PACKAGES["dir"], hashlib.sha256(url.encode("utf-8")).hexdigest()[:24])
    n = 0
    try:
        with opener(url, timeout, None) as src, open(path, "wb") as out:
            while True:
                b = src.read(CHUNK)
                if not b:
                    break
                n += len(b)
                if n > limit:
                    raise TooLarge(f"the package is larger than the cap of {limit} bytes; download stopped")
                out.write(b)
    except BaseException:
        path.unlink(missing_ok=True)
        raise
    while files and sum(p.stat().st_size for p in files.values()) + n > PACKAGE_CACHE_BYTES:
        old = next(iter(files))
        files.pop(old).unlink(missing_ok=True)
    files[url] = path
    return path


def _tar_lookup(tf, name: str):
    for n in (name, "./" + name, name[2:] if name.startswith("./") else None):
        if n:
            try:
                return tf.getmember(n)
            except KeyError:
                continue
    return None


def fetch_tar_package(row, dest, url, timeout, opener):
    path = download_package(url, timeout, opener, whole_cap_of(row))
    name = row.get("member_path")
    limit = member_limit(row)
    try:
        tf = tarfile.open(path, "r:*")
    except (tarfile.TarError, OSError, EOFError) as e:
        return {"status": "failed", "url": url, "reason": f"cannot open the package as a tar archive: {e}"}
    with tf:
        m = _tar_lookup(tf, name)
        if m is None:
            return {"status": "failed", "url": url, "reason": f"{name} is not in the package"}
        if not m.isfile():
            return {"status": "failed", "url": url, "reason": f"{name} is not a regular file in the package"}
        _too_large_unknown(row, m.size, limit)
        f = tf.extractfile(m)
        data = f.read(limit + 1) if f else b""
    return _finish(row, dest, data, url, "tar_package")


# 7z members: py7zr over remote_file (a solid block is decoded from its start up to the member)

SEVENZIP_BLOCK = 8 << 20  # bytes per range request when a 7z archive is read through remote_file


def fetch_sevenzip_member(row, dest, url, timeout, opener):
    import py7zr
    from py7zr.exceptions import DecompressionBombError, UnsupportedCompressionMethodError
    from py7zr.io import BytesIOFactory

    name = row.get("member_path")
    limit = member_limit(row)
    whole = whole_cap_of(row)
    factory = BytesIOFactory(limit + 1)
    try:
        with remote_file(remote_source(row, url), timeout, SEVENZIP_BLOCK) as f, \
                py7zr.SevenZipFile(f, max_extract_size=whole) as arc:
            e = next((x for x in arc.list() if x.filename == name and not x.is_directory), None)
            if e is None:
                return {"status": "failed", "url": url, "reason": f"{name} is not in the 7z directory"}
            _too_large_unknown(row, e.uncompressed, limit)
            arc.extract(targets=[name], factory=factory)
    except DecompressionBombError as x:
        raise TooLarge(f"7z block: {x}") from None
    except UnsupportedCompressionMethodError as x:
        raise Unsupported(f"7z block: {x}") from None
    except py7zr.Bad7zFile as x:
        return {"status": "failed", "url": url, "reason": f"7z: {type(x).__name__}: {x}"}
    out = factory.products.get(name)
    data = b""
    if out is not None:
        out.seek(0)
        data = out.read()
    return _finish(row, dest, data, url, "sevenzip_member")


# members of tar archives stored as gzip (the arXiv source bundles): the range is one gzip member

def fetch_gzip_member(row, dest, url, timeout, opener):
    rng = _rng(row)
    if rng is None or rng[1] is None:
        raise Unsupported("a gzip member row needs a byte range")
    limit = whole_cap_of(row)
    if rng[1] > limit:
        raise TooLarge(f"the gzip member has {rng[1]} compressed bytes, more than the cap of {limit} bytes")
    raw = _get_range(url, timeout, rng[0], rng[1], opener)
    try:  # GzipFile decompresses every member in turn and checks each one's CRC32 and length against its trailer
        data = gzip.GzipFile(fileobj=io.BytesIO(raw)).read(limit + 1)
    except EOFError:
        return {"status": "failed", "url": url, "reason": "the gzip member is incomplete"}
    except (zlib.error, gzip.BadGzipFile) as e:
        return {"status": "failed", "url": url, "reason": f"cannot decompress the gzip member: {e}"}
    if len(data) > limit:
        raise TooLarge(f"the member decompresses to more than the cap of {limit} bytes")
    want = row.get("payload_size_bytes")
    if want is not None and len(data) % (1 << 32) != int(want):
        return {"status": "failed", "url": url,
                "reason": f"decompressed size differs: expected {want} (modulo 2^32), got {len(data)}"}
    got = f"{zlib.crc32(data):08x}"
    want_crc = str((row.get("source_meta") or {}).get("crc32") or "").lower()
    if want_crc and got != want_crc:
        return {"status": "failed", "url": url, "reason": f"CRC32 differs: computed {got}, pointer {want_crc}"}
    hashes = row.get("hashes") or {}
    h = Hasher(len(data))
    h.update(data)
    dg = h.digests()
    why, _ = check_hashes(hashes, dg)
    if why:
        return {"status": "failed", "url": url, "reason": why}
    _write(dest, data)
    res = {"status": "ok", "path": str(dest), "bytes": len(data), "matched_on": "gzip_member", "crc32": got,
           "url": url}
    if not any(hashes.get(k) for k in ("md5", "sha1", "sha256")):
        res["unverified"] = "checked against the gzip CRC32 and length; sha256 computed on download"
        res["sha256"] = dg["sha256"]
    return res


# requester-pays S3 (the requester's own AWS account pays; credentials come from the environment)

AWS_REGION = "us-east-1"


def aws_credentials():
    """(access key, secret key, session token or None) from AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY and
    AWS_SESSION_TOKEN, or None when they are not set. The script never stores or prints them."""
    ak, sk = os.environ.get("AWS_ACCESS_KEY_ID"), os.environ.get("AWS_SECRET_ACCESS_KEY")
    return (ak, sk, os.environ.get("AWS_SESSION_TOKEN") or None) if ak and sk else None


@functools.lru_cache(maxsize=None)
def s3_client(region: str):
    """boto3's S3 client for region, with the credentials of the environment (aws_credentials) and the proxy of
    set_network; boto3 signs every request and retries what fails."""
    import boto3
    import botocore.config

    proxy = _NET.proxy
    return boto3.client("s3", region_name=region, config=botocore.config.Config(
        connect_timeout=60, read_timeout=120, retries={"max_attempts": RETRIES + 1, "mode": "standard"},
        **({"proxies": {"http": proxy, "https": proxy}} if proxy else {})))


def requester_pays_opener(opener, row: dict, region: str = AWS_REGION):
    """Wrap opener so that an address that is the HTTPS form of one of the row's s3:// addresses is read with boto3's
    get_object (RequestPayer requester, the byte range as Range): boto3 signs the request with the credentials of
    the environment. Any other address of the row goes out through opener, unsigned."""
    s3 = {to_http(u): u for u in [row.get("uri"), *(row.get("alt_uris") or [])]
          if isinstance(u, str) and u.startswith("s3://")}

    def op(url, timeout, rng=None, headers=None):
        if url not in s3:
            return opener(url, timeout, rng, headers=headers)
        bucket, _, key = s3[url][len("s3://"):].partition("/")
        got = s3_client(region).get_object(Bucket=bucket, Key=key, RequestPayer="requester",
                                           **({"Range": range_header(rng)} if rng else {}))
        return got["Body"]
    return op


# single lichess games (public export API; HTTP 429 waits as long as its Retry-After asks, see make_session)

LICHESS_BASE = "https://lichess.org"
LICHESS_NOT_GAMES = {"training", "practice", "streamer", "tutorial", "analysis", "features", "insights",
                     "tutorials", "variants"}
LICHESS_GAME_RE = re.compile(r"^https?://(?:www\.)?lichess\.org/([A-Za-z0-9]{8})(?:[A-Za-z0-9]{4})?"
                             r"(?:/(?:white|black))?/?(?:#\d*)?$")


def lichess_game_id(row: dict):
    """The 8-character game id of a row that points to one lichess game: source_meta.game_id, or a game page
    address (https://lichess.org/<id>, optionally with the 4 player characters, /white or /black, #ply)."""
    sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
    gid = sm.get("game_id")
    if gid is None:
        m = LICHESS_GAME_RE.match(str(row.get("uri") or ""))
        gid = m.group(1) if m and m.group(1).lower() not in LICHESS_NOT_GAMES else None
    return gid if isinstance(gid, str) and re.fullmatch(r"[A-Za-z0-9]{8}", gid) else None


def fetch_lichess_game(row, dest, url, timeout, opener):
    limit = member_limit(row)
    with opener(url, timeout, None, headers={"Accept": "application/x-chess-pgn"}) as src:
        data = src.read(limit + 1)
    _too_large_unknown(row, len(data), limit)
    if not data.strip():
        return {"status": "failed", "url": url, "reason": "the export returned no game"}
    h = Hasher(len(data))
    h.update(data)
    why = verify(row, len(data), h.digests())
    if why and (row.get("hashes") or row.get("size_bytes") is not None):
        return {"status": "failed", "url": url, "reason": why}
    _write(dest, data)
    return no_hash_fields(row, {"status": "ok", "path": str(dest), "bytes": len(data),
                                "matched_on": "lichess_game_export", "url": url},
                          h.digests()["sha256"], "single-game export; sha256 computed on download")


# decompressing a fetched .gz, .bz2 or .zst file (--decompress)

DECODERS = {"gz": "gzip", "bz2": "bz2", "zst": "zstd"}  # single-file compression format -> decoder this script has
DECOMPRESS = {e: DECODERS[f[0]] for f in ARCHIVE_FORMATS if f[0] in DECODERS for e in f[2]}


def decompress_target(path: Path, row: dict):
    """(kind, output path) for a compressed file, or (None, None)."""
    kind = DECOMPRESS.get(path.suffix.lower())
    if kind:
        return kind, path.with_suffix("")
    kind = DECOMPRESS.get("." + str(row.get("ext") or "").lower().lstrip("."))
    return (kind, path.with_name(path.name + ".decompressed")) if kind else (None, None)


def _decompressor(kind: str, f):
    if kind == "gzip":
        return gzip.GzipFile(fileobj=f)
    if kind == "bz2":
        return bz2.BZ2File(f)
    try:
        import zstandard
    except ImportError:
        raise Unsupported("decompressing .zst needs the zstandard package (pip install zstandard)") from None
    return zstandard.ZstdDecompressor().stream_reader(f, read_across_frames=True)


def decompress_file(path: Path, row: dict, limit: int):
    """Stream-decompress a fetched file next to it (every gzip member, bz2 stream or zstd frame), at most limit
    bytes. On success the compressed file is deleted; otherwise it is kept. -> manifest fields, or None when
    the file is not compressed."""
    kind, out = decompress_target(path, row)
    if kind is None:
        return None
    part = out.with_name(out.name + ".part")
    h = Hasher(None)
    try:
        with open(path, "rb") as f, _decompressor(kind, f) as src, open(part, "wb") as o:
            while True:
                b = src.read(CHUNK)
                if not b:
                    break
                h.update(b)
                if h.n > limit:
                    break
                o.write(b)
    except Unsupported as e:
        part.unlink(missing_ok=True)
        return {"status": "unsupported", "reason": str(e)}
    except Exception as e:  # noqa: BLE001 (any decoder error: the compressed file stays)
        part.unlink(missing_ok=True)
        return {"status": "failed", "reason": f"cannot decompress ({kind}): {type(e).__name__}: {e}"}
    if h.n > limit:
        part.unlink(missing_ok=True)
        return {"status": "too_large", "reason": f"decompressed size is more than the cap of {limit} bytes; "
                                                 "the compressed file is kept"}
    os.replace(part, out)
    path.unlink()
    return {"status": "ok", "path": str(out), "bytes": h.n, "sha256": h.digests()["sha256"],
            "compressed_path": str(path)}


def method_of(row: dict) -> str:
    if lichess_game_id(row):
        return "lichess_game"
    if row.get("zip_entry") is not None:
        return "zip_member"
    scope = row.get("hash_scope") or "file"
    if scope == "gzip_member":
        return "gzip_member"
    if row.get("member_path") is not None and not _rng(row):
        kind = package_kind(row.get("uri"))
        if kind:
            return kind
        path = urllib.parse.urlsplit(str(row.get("uri") or "")).path
        return f"unsupported:member of {posixpath.basename(path) or 'an unknown container'}"
    if scope == "http_payload":
        return "warc_record"
    if scope == "api_body":
        return "api_body"
    if scope != "file":
        return f"unsupported:{scope}"
    return "range" if _rng(row) else "file"


FETCHERS = {"file": fetch_file, "range": fetch_file, "warc_record": fetch_payload, "api_body": fetch_api_body,
            "zip_member": fetch_member, "zip_package": fetch_zip_package, "tar_package": fetch_tar_package,
            "sevenzip_member": fetch_sevenzip_member, "gzip_member": fetch_gzip_member,
            "lichess_game": fetch_lichess_game}


# access.needs_auth values that do not mark a row as needing a login
NOT_MARKED = (None, False, "no", "unknown", "")
AUTH_SKIP = {
    "guestbook": "the dataset asks for a guestbook form before download; not filled in, no request sent",
    "restricted": "restricted file; access must be requested from the dataset authors, no request sent",
    "gated": "gated repository; access must be requested on the Hub and the download needs your token, no request "
             "sent",
    "kaggle_token": "the source needs a Kaggle account and API token, which this script does not use; no request "
                    "sent",
}


def needs_auth(row: dict):
    """The row's access.needs_auth when it marks a login, a form or an access request, else None."""
    na = (row.get("access") or {}).get("needs_auth")
    return None if na in NOT_MARKED else na


def auth_key(na) -> str:
    """needs_auth value -> the key it is counted under in the summary."""
    return na if isinstance(na, str) else json.dumps(na)


def skip_reason(row: dict, today: str | None = None):
    """Why a row is skipped without a request (None: fetch it). Every needs_auth value other than NOT_MARKED is
    skipped, except requester_pays with AWS credentials set and embargoed from the day in access.embargo_until
    (an embargo without a date stays skipped)."""
    na = needs_auth(row)
    if na is None:
        return None
    if na == "requester_pays":
        if aws_credentials() is not None:
            return None
        return ("requester-pays bucket: set AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY (your own AWS account pays "
                "the request and transfer charges); no request sent")
    if na == "embargoed":
        until = str((row.get("access") or {}).get("embargo_until") or "")[:10]
        if until and until <= (today or utc_today()):
            return None
        return f"embargoed until {until or 'a date the source does not give'}; no request sent"
    return AUTH_SKIP.get(na) or f"the source marks this row as needing access ({auth_key(na)}); no request sent"


def already_present(row: dict, dest: Path, method: str):
    """The manifest fields of a whole file (or byte range) already at dest from an earlier run whose size and
    sha256 (and every other published hash) match the row, else None. Rolling files are always downloaded."""
    hashes = row.get("hashes") or {}
    want = row.get("size_bytes")
    if method not in ("file", "range") or want is None or not hashes.get("sha256") or is_rolling(row) \
            or marked_rolling(row) or dest.is_symlink() or not dest.is_file() or dest.stat().st_size != want:
        return None
    h = Hasher(want)
    with open(dest, "rb") as f:
        for b in iter(lambda: f.read(CHUNK), b""):
            h.update(b)
    got = h.digests()
    if verify(row, h.n, got):
        return None
    return {"status": "ok", "path": str(dest), "bytes": h.n, "sha256": got["sha256"], "already_present": True}


def _file_sha256(path: Path) -> str:
    h = hashlib.sha256()
    with open(path, "rb") as f:
        for b in iter(lambda: f.read(CHUNK), b""):
            h.update(b)
    return h.hexdigest()


# Local reuse (the build rule shared by this tool, to_pool and pool-build): before a whole file is fetched,
# look for a file with the same bytes under the local roots (ARTPOOL_LOCAL_ROOTS or --local-root, directories
# separated by os.pathsep) and in the staging directory (ARTPOOL_STAGING or --staging, where an outside fetch
# drops a file). A file whose size and every published hash match the row is used with no network request
# (obtained: reused, or staged for the staging directory); a candidate (same name or same size) whose hashes do
# not match is never used and is reported. A row with no local match is fetched (obtained: fetched).
LOCAL_ROOTS_ENV = "ARTPOOL_LOCAL_ROOTS"
STAGING_ENV = "ARTPOOL_STAGING"
# The record the staging step (artpool.stage_receive) appends one line to per request it streams into the staging
# directory: url, status, bytes, sha256, started_at and finished_at (UTC). A staged file's retrieved date is the
# date of that stream.
STAGING_RECORD = "staging_attempts.jsonl"
# Pool manifests (to_pool and pool-build both write <pool>/_meta/manifest.jsonl) whose retrieved dates count
# as the original fetch of a reused file; fetch manifests are MANIFEST (fetch_manifest.jsonl).
POOL_MANIFEST = "manifest.jsonl"
UNKNOWN = "unknown"


# The one wall clock of this tool, the staging step (artpool.stage_receive) and pool-build: every timestamp they
# write (reused_at, fetched_at, started_at, finished_at, run_id) and every "today" they default to is read through
# utc_now, in UTC whatever the machine's time zone. Timestamps are YYYY-MM-DDTHH:MM:SSZ (the Z says UTC), dates
# YYYY-MM-DD (the UTC date). It lives here, not in its own module, because this file is also published alone as fetch.py.
def utc_now() -> datetime.datetime:
    """The current time, timezone-aware, in UTC."""
    return datetime.datetime.now(datetime.timezone.utc)


def utc_stamp() -> str:
    """utc_now() as YYYY-MM-DDTHH:MM:SSZ."""
    return utc_now().strftime("%Y-%m-%dT%H:%M:%SZ")


def utc_today() -> str:
    """The UTC date of utc_now() as YYYY-MM-DD."""
    return utc_now().date().isoformat()


def _run_id_time(run_id) -> str | None:
    """A manifest line's run_id (%Y%m%dT%H%M%S.%fZ, the UTC start of its run) -> ISO time, None if not one."""
    try:
        t = datetime.datetime.strptime(str(run_id), "%Y%m%dT%H%M%S.%fZ")
    except ValueError:
        return None
    return t.replace(tzinfo=datetime.timezone.utc).isoformat().replace("+00:00", "Z")


class LocalFiles:
    """The files under the local roots and the staging directory, looked up by sha256 against a row."""

    def __init__(self, roots=(), staging=None, log=None):
        self.roots = [Path(r).expanduser() for r in roots if str(r)]
        self.staging = Path(staging).expanduser() if staging else None
        self.log = log or (lambda msg: print(msg, file=sys.stderr))
        self._files = None
        self._sha = {}
        self._prov = None
        self.counts = {"reused": 0, "staged": 0, "fetched": 0, "refused": 0}

    @classmethod
    def from_settings(cls, roots=None, staging=None, log=None):
        """From the arguments, else the environment variables; None when neither names a directory."""
        if roots is None:
            roots = [x for x in os.environ.get(LOCAL_ROOTS_ENV, "").split(os.pathsep) if x]
        staging = staging if staging is not None else (os.environ.get(STAGING_ENV) or None)
        if not roots and not staging:
            return None
        return cls(roots, staging, log)

    def _walk(self) -> list:
        if self._files is None:
            self._files = []
            dirs = [(r, "reused") for r in self.roots] + ([(self.staging, "staged")] if self.staging else [])
            for d, how in dirs:
                if not d.is_dir():
                    self.log(f"local reuse: {d} is not a directory, ignored")
                    continue
                for p in sorted(d.rglob("*")):
                    if p.is_file() and not p.is_symlink() and not p.name.endswith((".part", ".stale", ".bad")):
                        self._files.append((p, how, p.stat().st_size))
        return self._files

    def _records(self) -> dict:
        """sha256 -> the fetch records of those bytes found under the local roots and in the staging directory:
        fetch manifests (an ok line fetched by this tool: retrieved, else the date of its run_id; fetched_from its
        url), pool manifests (_meta/manifest.jsonl: retrieved, fetched_from) and the staging record (one line per
        streamed request: the date of finished_at). A line that itself reused or staged a file counts only with its
        own retrieved, which then is the original's. Each record: retrieved, fetched_from, fetched_at, route, record."""
        if self._prov is not None:
            return self._prov
        self._prov = {}

        def add(sha, rec):
            if sha and rec.get("retrieved"):
                self._prov.setdefault(str(sha).lower(), []).append(rec)

        def lines(p):
            try:
                with open(p, encoding="utf-8") as f:
                    for ln in f:
                        try:
                            x = json.loads(ln)
                        except ValueError:
                            continue
                        if isinstance(x, dict):
                            yield x
            except OSError as e:
                self.log(f"local reuse: {p} not read: {e}")

        for d in self.roots:
            if not d.is_dir():
                continue
            for p in sorted(d.rglob(MANIFEST)):
                for x in lines(p):
                    if x.get("status") != "ok" or not x.get("sha256"):
                        continue
                    if x.get("obtained") in ("reused", "staged"):
                        retrieved, at = x.get("retrieved"), x.get("fetched_at")
                    else:
                        at = x.get("fetched_at") or _run_id_time(x.get("run_id"))
                        retrieved = x.get("retrieved") or (at[:10] if at else None)
                    if retrieved == UNKNOWN:
                        continue
                    add(x["sha256"], {"retrieved": retrieved, "fetched_from": x.get("fetched_from") or x.get("url"),
                                      "fetched_at": at, "route": x.get("route"), "record": str(p)})
            for p in sorted(d.rglob(POOL_MANIFEST)):
                if p.parent.name != "_meta":
                    continue
                for x in lines(p):
                    if not x.get("retrieved") or x.get("retrieved") == UNKNOWN:
                        continue
                    rec = {"retrieved": x["retrieved"], "fetched_from": x.get("fetched_from") or x.get("url"),
                           "fetched_at": x.get("fetched_at"), "route": x.get("route"), "record": str(p)}
                    for k in ("sha256", "upstream_sha256"):
                        add(x.get(k), rec)
        if self.staging is not None and (self.staging / STAGING_RECORD).is_file():
            p = self.staging / STAGING_RECORD
            for x in lines(p):
                at = x.get("finished_at")
                if x.get("kept") and at and x.get("sha256"):
                    add(x["sha256"], {"retrieved": str(at)[:10], "fetched_from": x.get("url"), "fetched_at": at,
                                      "route": x.get("route") or "staged", "record": str(p)})
        return self._prov

    def provenance(self, sha256: str, how: str) -> dict:
        """The original fetch of these bytes -> retrieved (that day, never the day of this build), fetched_from,
        fetched_at, route and the record it was read from. A staged file takes it from the staging record only;
        a reused file from the earliest dated fetch or pool manifest record. With no record: retrieved unknown and
        retrieved_reason."""
        recs = self._records().get(str(sha256).lower(), [])
        staged = [r for r in recs if r["record"].endswith(STAGING_RECORD)]
        pick = staged if how == "staged" else [r for r in recs if r not in staged] or staged
        if not pick:
            where = "the staging record " + STAGING_RECORD if how == "staged" else \
                "any fetch manifest or pool manifest under the local roots"
            return {"retrieved": UNKNOWN, "retrieved_reason": f"no record of sha256 {sha256} in {where}"}
        r = min(pick, key=lambda r: (str(r["retrieved"]), str(r.get("fetched_at") or "")))
        return {k: v for k, v in r.items() if v is not None}

    def _digests(self, p: Path, size: int) -> tuple:
        if p not in self._sha:
            h = Hasher(size)
            with open(p, "rb") as f:
                for b in iter(lambda: f.read(CHUNK), b""):
                    h.update(b)
            self._sha[p] = (h.n, h.digests())
        return self._sha[p]

    def find(self, row: dict, name: str | None = None):
        """-> (path, "reused"|"staged") of a local file whose size and every published hash match the row, else None.
        Only whole files (or byte ranges) with a recorded sha256 and size; rolling files are always fetched."""
        hashes = row.get("hashes") or {}
        want, sha = row.get("size_bytes"), str(hashes.get("sha256") or "").lower()
        if want is None or not sha or is_rolling(row) or marked_rolling(row) \
                or method_of(row) not in ("file", "range"):
            return None
        name = name or posixpath.basename(str(row.get("path") or row.get("uri") or ""))
        for p, how, size in self._walk():
            if size != int(want) and p.name != name:
                continue
            n, got = self._digests(p, size)
            if n == int(want) and not verify(row, n, got):
                return p, how
            self.counts["refused"] += 1
            self.log(f"local reuse: {p} refused for {row.get('pointer_id') or name}: {n} bytes sha256 "
                     f"{got.get('sha256')}, the record wants {want} bytes sha256 {sha}")
        return None

    def take(self, row: dict, dest: Path, name: str | None = None):
        """Copy the matching local file to dest -> its manifest fields (bytes and sha256 computed again from the
        copy), or None when nothing local matches (the row is then fetched and counted so)."""
        hit = self.find(row, name)
        if hit is None:
            self.counts["fetched"] += 1
            return None
        src, how = hit
        dest.parent.mkdir(parents=True, exist_ok=True)
        part = dest.with_name(dest.name + ".part")
        shutil.copyfile(src, part)
        n = Hasher(part.stat().st_size)
        with open(part, "rb") as f:
            for b in iter(lambda: f.read(CHUNK), b""):
                n.update(b)
        got = n.digests()
        if verify(row, n.n, got):  # the file changed under us: never used
            part.unlink(missing_ok=True)
            self.counts["refused"] += 1
            self.counts["fetched"] += 1
            self.log(f"local reuse: {src} changed while copied, refused")
            return None
        os.replace(part, dest)
        self.counts[how] += 1
        prov = self.provenance(got["sha256"], how)
        if prov.get("retrieved_reason"):
            self.log(f"local reuse: {row.get('pointer_id') or name}: retrieved {UNKNOWN}, {prov['retrieved_reason']}")
        # retrieved, fetched_from, fetched_at, route: the original fetch of these bytes (no request is made now);
        # reused_at: when this build copied them (UTC, from utc_now)
        return {"status": "ok", "path": str(dest), "bytes": n.n, "sha256": got["sha256"], "obtained": how,
                "local_path": str(src), **{k: v for k, v in prov.items() if k != "record"},
                **({"provenance_record": prov["record"]} if prov.get("record") else {}),
                "reused_at": utc_stamp()}

    def summary(self) -> str:
        c = self.counts
        return (f"local reuse: {c['reused']} reused, {c['staged']} staged, {c['fetched']} fetched, "
                f"{c['refused']} refused")


LFS_POINTER_HEAD = b"version https://git-lfs.github.com/spec/v1"


def is_lfs_pointer(path: Path) -> bool:
    """True for a small text file that is a Git LFS pointer (what a repository holds in place of an LFS object)."""
    try:
        if path.stat().st_size > 1024:
            return False
        with open(path, "rb") as f:
            return f.read(len(LFS_POINTER_HEAD)) == LFS_POINTER_HEAD
    except OSError:
        return False


def fetch_one(row: dict, out: Path, **kw) -> dict:
    """Fetch one row into out -> its manifest line. Adds what the row expected (expected_size, expected_sha256),
    what was written (bytes, sha256), the published hashes this tool cannot check (unchecked_hashes); when the
    fetch fails, a file an earlier run left at the destination is renamed to <name>.stale (stale_path)."""
    res = _fetch_one(row, out, **kw)
    st = res.get("status")
    if st in ("skipped", "unsafe_path"):
        return res
    hashes = row.get("hashes") or {}
    if row.get("size_bytes") is not None:
        res["expected_size"] = row["size_bytes"]
    if hashes.get("sha256"):
        res.setdefault("expected_sha256", str(hashes["sha256"]).lower())
    uh = unchecked_hashes(row)
    if uh:
        res["unchecked_hashes"] = uh
    if st == "ok" and res.get("path") and "sha256" not in res and Path(res["path"]).is_file():
        res["sha256"] = _file_sha256(Path(res["path"]))
    if st == "ok" and res.get("path") and is_lfs_pointer(Path(res["path"])):
        Path(res["path"]).unlink(missing_ok=True)
        res = {**res, "status": "failed", "reason": "the download is a Git LFS pointer file, not the file it names; "
                                                    "nothing written"}
        res.pop("path", None)
        st = "failed"
    if st in ("failed", "too_large"):
        try:
            dest = dest_path(out, row)
        except UnsafePath:
            return res
        if dest.is_file() and not dest.is_symlink():
            stale = dest.with_name(dest.name + ".stale")
            os.replace(dest, stale)
            res["stale_path"] = str(stale)
    return res


def _fetch_one(row: dict, out: Path, *, timeout: float = 120, opener=open_url, skip_present: bool = False,
               local: LocalFiles | None = None) -> dict:
    base = {"pointer_id": row.get("pointer_id")}
    why = skip_reason(row)
    if why:
        return {**base, "status": "skipped", "reason": why, "needs_auth": needs_auth(row)}
    method = method_of(row)
    fn = FETCHERS.get(method)
    size, cap = row.get("size_bytes"), cap_of(row)
    if size is not None and int(size) > cap:
        return {**base, "status": "too_large", "method": method,
                "reason": f"size {int(size)} is more than the cap of {cap} bytes; not downloaded"}
    if method == "lichess_game":
        urls = [f"{LICHESS_BASE}/game/export/{lichess_game_id(row)}"]
    elif row.get("_local_file"):
        urls = [row["_local_file"]]
        opener = local_file_opener(row["_local_file"])
    else:
        urls = [u for u in candidates(row) if u.startswith(("https://", "http://"))]
    if fn is None or not urls:
        return {**base, "status": "unsupported", "method": method,
                "reason": "no supported address" if fn else f"fetch method {method}"}
    if (row.get("access") or {}).get("needs_auth") == "requester_pays":
        opener = requester_pays_opener(opener, row, (row.get("access") or {}).get("region") or AWS_REGION)
    try:
        dest = dest_path(out, row)
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest_path(out, row)  # again after mkdir: a directory created meanwhile must not be a link out of --out
    except (UnsafePath, OSError) as e:
        return {**base, "status": "unsafe_path", "method": method, "reason": f"{e}; nothing written"}
    pre = already_present(row, dest, method) if skip_present else None
    if pre:
        return {**base, "method": method, **pre}
    if local is not None and not row.get("_local_file"):
        hit = local.take(row, dest)
        if hit:
            # url: the address this file is fetched from, kept for the pool's fetched_from (nothing was requested)
            return {**base, "method": method, "url": hit.get("fetched_from") or urls[0], **hit}
        base["obtained"] = "fetched"
    errors = []
    for url in urls:
        try:
            res = fn(row, dest, url, timeout, opener)
        except TooLarge as e:
            return {**base, "status": "too_large", "method": method, "reason": str(e), "url": url}
        except Exception as e:  # noqa: BLE001 (Unsupported and network errors after urllib3's retries: the next address)
            errors.append(f"{url}: {e}" if isinstance(e, Unsupported) else f"{url}: {type(e).__name__}: {e}")
            continue
        return {**base, "method": method, **res}
    return {**base, "status": "failed", "method": method, "reason": "; ".join(errors) or "no address answered"}


# ---------- units stored inside a container ----------

# A row of a collection whose unit is stored inside another file (a member of a zip or tar archive, a compressed or
# encoded file) points at that upstream file: its size and hashes are the upstream file's, and source_meta.transform
# lists the steps that make the unit out of it (unzip:<member>, untar:<member>, gunzip and the others of
# transform.py), with unit_sha256 and unit_bytes for the unit (content_sha256 for the bytes before a final gzip
# step). fetch.py downloads and checks the upstream file, makes the unit with transform.py and checks it against
# unit_sha256 (or content_sha256); the unit is written under the unit's path and the upstream file is not kept.
# transform.py is taken from the artpool package, from next to this script, or else from tools/ of the index at the
# commit read (set by main).
_TRANSFORM = {"src": None, "mod": None}


def unit_steps(row: dict):
    """The transform steps of a unit stored inside another file (source_meta.transform), else None."""
    sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
    t = sm.get("transform")
    return [str(s) for s in t] if isinstance(t, list) and t else None


def _transform():
    if _TRANSFORM["mod"] is not None:
        return _TRANSFORM["mod"]
    try:
        from . import public_transform as t
    except ImportError:
        try:
            import transform as t
            if not (hasattr(t, "apply") and hasattr(t, "validate")):
                raise ImportError("transform is not transform.py")
        except ImportError:
            t = _transform_from_repo()
    _TRANSFORM["mod"] = t
    return t


def _transform_from_repo():
    import importlib.util

    src = _TRANSFORM["src"]
    if not src:
        raise Unsupported("units stored inside another file need transform.py next to this script")
    try:
        if "://" in src:
            d = tempfile.mkdtemp(prefix="fetch_transform_")
            path = Path(d, "transform.py")
            with open_url(src, 60) as r:
                path.write_bytes(read_bounded(r, 4 << 20, "transform.py"))
        else:
            path = Path(src)
        spec = importlib.util.spec_from_file_location("transform", str(path))
        mod = importlib.util.module_from_spec(spec)
        spec.loader.exec_module(mod)
    except Exception as e:  # noqa: BLE001
        raise Unsupported(f"units stored inside another file need transform.py; it is not next to this script and "
                          f"could not be read from {src}: {type(e).__name__}: {e}") from None
    return mod


def fetch_unit(row: dict, out: Path, **kw) -> dict:
    """fetch_one, and for a unit stored inside another file (unit_steps) the unit made out of the downloaded file
    and checked against the unit's recorded hash (extract_unit). A unit already at its path from an earlier run whose
    sha256 is unit_sha256 is kept without a download (already_present)."""
    steps = unit_steps(row)
    if steps is None:
        return fetch_one(row, out, **kw)
    sm = row["source_meta"]
    want = str(sm.get("unit_sha256") or "").lower()
    if kw.get("skip_present") and want:
        try:
            dest = dest_path(out, row)
        except UnsafePath:
            dest = None
        if dest is not None and dest.is_file() and not dest.is_symlink() and _file_sha256(dest) == want:
            return {"pointer_id": row.get("pointer_id"), "method": method_of(row), "status": "ok", "path": str(dest),
                    "bytes": dest.stat().st_size, "sha256": want, "already_present": True, "extracted": True,
                    "unit_verified": True}
    res = fetch_one(row, out, **kw)
    if res.get("status") != "ok" or not res.get("path"):
        return res
    return extract_unit(row, res, steps)


def extract_unit(row: dict, res: dict, steps: list) -> dict:
    """The downloaded upstream file at res["path"] -> the unit at the same path, made with the transform steps and
    checked against unit_sha256 (or content_sha256 when the last step is gzip, whose bytes depend on the zlib build).
    The result keeps the upstream file's size and sha256 as upstream_bytes and upstream_sha256 and gets bytes and
    sha256 of the unit, content_sha256, extracted and unit_verified (false when the row records no unit hash). A
    unit that cannot be made or does not match fails; the upstream file is then renamed to <name>.stale."""
    sm = row["source_meta"]
    want = str(sm.get("unit_sha256") or "").lower()
    want_c = str(sm.get("content_sha256") or "").lower()
    src = Path(res["path"])
    tmp = src.with_name(src.name + ".unit")
    ub = sm.get("unit_bytes")
    try:
        t = _transform()
        limit = max(t.MAX_BYTES, int(ub)) if isinstance(ub, int) else t.MAX_BYTES
        got = t.apply(src, steps, tmp, max_bytes=limit)
        why = None
        if (want or want_c) and not (got["sha256"] == want or (want_c and got["content_sha256"] == want_c)):
            why = (f"the unit made with {', '.join(steps)} has sha256 {got['sha256']}, the index records "
                   f"{want or want_c}")
    except (Unsupported, ValueError, OSError) as e:
        why = f"could not make the unit with {', '.join(steps)}: {e}"
    if why is not None:
        tmp.unlink(missing_ok=True)
        out = {**res, "status": "failed", "reason": why + "; the downloaded file is kept as <name>.stale"}
        out.pop("path", None)
        if src.is_file() and not src.is_symlink():
            stale = src.with_name(src.name + ".stale")
            os.replace(src, stale)
            out["stale_path"] = str(stale)
        return out
    os.replace(tmp, src)
    out = {**res, "upstream_bytes": res.get("bytes"), "upstream_sha256": res.get("sha256"), "bytes": got["bytes"],
           "sha256": got["sha256"], "content_sha256": got["content_sha256"], "extracted": True,
           "unit_verified": bool(want or want_c)}
    if want:
        out["expected_sha256"] = want
    if isinstance(ub, int):
        out["expected_size"] = ub
    return out


# ---------- content check ----------

CONTENT_CHECKS = ("scanned_pdf", "error_page", "ext_mismatch")
CHECK_TIMEOUT = 60
CHECK_READ = 200_000
PDF_PAGES_READ = 5
PDF_MIN_CHARS_PER_PAGE = 20
ERROR_BODY_SHORT = 3000
ERROR_BODY_HEAD = 1500
ERROR_WORDS = re.compile(
    r"\b(404|403|500|502|503)\b|not\s+found|page\s+cannot\s+be|cannot\s+be\s+(found|displayed)|\berror\b|"
    r"access\s+denied|forbidden|object\s+moved|has\s+moved|moved\s+permanently|no\s+longer\s+(available|exists)|"
    r"temporarily\s+unavailable|session\s+(has\s+)?expired|server\s+error|bad\s+request|invalid\s+(request|url)|"
    r"unauthori[sz]ed|redirect", re.I)
TEXT_EXTS = frozenset({"html", "htm", "xhtml", "txt", "text", "xml", "csv", "log", "kml", "sql"})
_OLE = frozenset({"application/cdfv2", "application/vnd.ms-office", "application/x-ole-storage",
                  "application/cdfv2-unknown"})
_TXT = frozenset({"text/plain", "text/html", "text/xml"})
_OOXML = "application/vnd.openxmlformats-officedocument."
EXT_MIME = {
    "pdf": {"application/pdf"},
    "html": _TXT, "htm": _TXT, "xhtml": _TXT | {"application/xhtml+xml"},
    "txt": _TXT | {"text/x-c", "text/x-c++", "text/x-fortran", "text/x-makefile", "text/x-shellscript", "text/x-tex",
                   "text/x-asm", "text/x-po", "text/x-java", "text/x-perl", "text/csv", "text/x-diff", "text/x-ruby",
                   "text/x-script.python", "text/rtf", "text/x-pascal", "text/troff", "text/x-lisp", "text/x-awk",
                   "text/x-msdos-batch", "application/csv", "application/json"},
    "text": _TXT, "log": {"text/plain"},
    "xml": _TXT | {"application/xml", "image/svg+xml"},
    "kml": _TXT | {"application/xml", "application/vnd.google-earth.kml+xml"},
    "csv": {"text/csv", "text/plain", "application/csv"},
    "json": {"application/json", "text/plain"},
    "sql": {"text/plain", "text/x-c", "text/x-c++"},
    "jpg": {"image/jpeg"}, "jpeg": {"image/jpeg"}, "gif": {"image/gif"}, "png": {"image/png"},
    "doc": {"application/msword"} | _OLE, "xls": {"application/vnd.ms-excel"} | _OLE,
    "ppt": {"application/vnd.ms-powerpoint"} | _OLE, "pps": {"application/vnd.ms-powerpoint"} | _OLE,
    "docx": {_OOXML + "wordprocessingml.document", "application/zip"},
    "xlsx": {_OOXML + "spreadsheetml.sheet", "application/zip"},
    "pptx": {_OOXML + "presentationml.presentation", "application/zip"},
    "ps": {"application/postscript"}, "eps": {"application/postscript", "image/x-eps"},
    "rtf": {"text/rtf"},
    "zip": {"application/zip"}, "gz": {"application/gzip", "application/x-gzip"},
    "swf": {"application/x-shockwave-flash"},
}


def run_tool(cmd: list, timeout: float = CHECK_TIMEOUT):
    """Run a system tool; returns (returncode, stdout) or None when the tool is not installed."""
    if shutil.which(cmd[0]) is None:
        return None
    try:
        r = subprocess.run(cmd, capture_output=True, timeout=timeout, check=False)
    except subprocess.TimeoutExpired:
        return -9, ""
    except OSError:
        return None
    return r.returncode, r.stdout.decode("utf-8", "replace")


def _text_of(data: bytes):
    s = data.decode("latin-1")
    m = re.search(r"<title[^>]*>(.*?)</title>", s, re.I | re.S)
    title = re.sub(r"\s+", " ", m.group(1)).strip() if m else ""
    body = re.sub(r"(?is)<(script|style)[^>]*>.*?</\1>", " ", s)
    body = re.sub(r"(?s)<[^>]+>", " ", body)
    body = re.sub(r"&nbsp;|&#160;", " ", body)
    return title, re.sub(r"\s+", " ", body).strip()


def _scanned_pdf(path: Path):
    """(result, detail, skip reason) for one PDF, read by pypdf: the text of its first PDF_PAGES_READ pages, and the
    fonts those pages set text in (the names their Tf operators select, form XObjects included), each seen by
    extract_text's visitor_operand_before. pypdf's warnings about a malformed file are not printed."""
    try:
        import pypdf
    except ImportError:
        return "skipped", {}, "pypdf not installed"
    logging.getLogger("pypdf").setLevel(logging.ERROR)
    fonts: set = set()

    def font(operator, operands, cm, tm):
        if operator == b"Tf":
            fonts.add(operands[0])

    try:
        pages = pypdf.PdfReader(path).pages[:PDF_PAGES_READ]
        text = "".join(page.extract_text(visitor_operand_before=font) for page in pages)
    except Exception:  # noqa: BLE001  pypdf raises many different types for a broken or encrypted file
        return "skipped", {}, "pypdf could not read the file"
    n_pages = max(1, len(pages))
    chars = len(re.sub(r"\s", "", text))
    detail = {"pdf_fonts": len(fonts), "pdf_text_chars": chars, "pdf_pages_read": n_pages}
    flagged = not fonts and chars < PDF_MIN_CHARS_PER_PAGE * n_pages
    return ("flagged" if flagged else "clean"), detail, None


def check_content(path: Path, ext: str | None = None) -> dict:
    """The three content checks for one downloaded file (see the module docstring)."""
    path = Path(path)
    ext = (ext or path.suffix).lower().lstrip(".")
    out: dict = {}
    skipped: dict = {}
    with open(path, "rb") as f:
        head = f.read(CHECK_READ)
    m = run_tool(["file", "-b", "--mime-type", str(path)])
    mime = m[1].strip().lower() if m and m[0] == 0 and m[1].strip() else None
    if mime:
        out["mime"] = mime
    is_pdf = mime == "application/pdf" if mime else head[:1024].lstrip().startswith(b"%PDF-")
    if is_pdf:
        res, detail, why = _scanned_pdf(path)
        out["scanned_pdf"] = res
        out.update(detail)
        if why:
            skipped["scanned_pdf"] = why
    else:
        out["scanned_pdf"] = "not_applicable"
    if ext in TEXT_EXTS or mime in ("text/html", "text/xml", "application/xhtml+xml"):
        title, body = _text_of(head)
        hit = bool(ERROR_WORDS.search(title)) or (
            len(body) < ERROR_BODY_SHORT and bool(ERROR_WORDS.search(body[:ERROR_BODY_HEAD])))
        out["error_page"] = "flagged" if hit else "clean"
        if hit:
            out["error_hint"] = (title + " | " + body[:200])[:300]
    else:
        out["error_page"] = "not_applicable"
    allowed = EXT_MIME.get(ext)
    if allowed is None:
        out["ext_mismatch"] = "not_applicable"
    elif path.stat().st_size == 0:
        out["ext_mismatch"] = "not_applicable"
        out["empty"] = True
    elif mime is None:
        out["ext_mismatch"] = "skipped"
        skipped["ext_mismatch"] = "file not installed" if m is None else "file could not read the file"
    else:
        out["ext_mismatch"] = "clean" if mime in allowed else "flagged"
    out["flags"] = [c for c in CONTENT_CHECKS if out[c] == "flagged"]
    if skipped:
        out["skipped"] = skipped
    return out


# ---------- the output layout ----------

META_OUT = "_meta"  # under --out: manifest.jsonl, sizes.tsv, fetch_manifest.jsonl, fetch_run.json, selection.json
LAYOUT_FIELDS = ("source", "path", "url", "sha256", "bytes", "spdx", "licence_url", "publisher", "retrieved",
                 "origin_kind", "leaf", "unit_id", "verified")
# a unit folder (unit_folder): at most this many characters of the cleaned last part of unit_id, then this many hex
# digits of the sha256 of unit_id, which keep two units apart (48 bits; a source holds far fewer units)
UNIT_NAME_MAX = 60
UNIT_HASH_HEX = 12


def unit_id(row: dict) -> str | None:
    """#1633: the key of the unit a row belongs to, unique within its source: the unit_group its rows share
    (source_meta.unit_group), else the row's natural key written as its uri, then @<range_offset> for a byte range, then
    !/<member_path> for an archive member; None for a row of a collection without a unit_group (the source's README.md
    and LICENSE), a file of its source. The uri is the one the index row records (repo_uri for a file of the index
    repository)."""
    sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
    if sm.get("unit_group"):
        return str(sm["unit_group"])
    if sm.get("campaign"):
        return None
    k = _key(row)
    return (str(row.get("repo_uri") or k["uri"]) + ("" if k["range_offset"] is None else f"@{k['range_offset']}")
            + (f"!/{k['member_path']}" if k["member_path"] else ""))


def unit_folder(uid: str) -> str:
    """#1633: the folder of the unit uid under its source: its last part made safe for a file name by werkzeug's
    secure_filename (at most UNIT_NAME_MAX characters, unit when nothing is left), a hyphen and the first UNIT_HASH_HEX
    hex digits of the sha256 of uid; the same on every run and every machine."""
    name = secure_filename(uid.rstrip("/").rsplit("/", 1)[-1])[:UNIT_NAME_MAX] or "unit"
    return f"{name}-{hashlib.sha256(uid.encode('utf-8')).hexdigest()[:UNIT_HASH_HEX]}"


def _pool_fields(sm: dict) -> dict:
    pf = sm.get("pool_fields")
    return {k: v for k, v in pf if isinstance(k, str)} if isinstance(pf, list) and all(
        isinstance(x, (list, tuple)) and len(x) == 2 for x in pf) else {}


class Layout:
    """Plans where each selected row goes under --out and writes _meta/manifest.jsonl and _meta/sizes.tsv. cat:
    {source: {"domain": [codes], "spdx": str}} from the catalog; entries: {source: its meta/sources.json entry}."""

    def __init__(self, out: Path, cat: dict, entries: dict):
        self.out, self.cat, self.entries = Path(out), cat, entries
        self.taken: dict = {}
        self.lines: list = []

    def leaf(self, row: dict) -> str:
        sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
        codes = (self.cat.get(row.get("source")) or {}).get("domain") or []
        return str(sm.get("pool_leaf") or (codes[0] if codes else "unclassified"))

    def domain_dir(self, row: dict) -> str:
        sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
        return str(sm.get("pool_domain") or self.leaf(row).split(".")[0])

    def parts(self, row: dict) -> list:
        """The row's path under --out as parts: [<domain>, <source>, <unit folder>, <file within the unit>...] for a
        file of a unit, [<domain>, <source>, <pool_path>...] for a file of its source (README.md, LICENSE)."""
        sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
        src = str(row.get("source"))
        pp = sm.get("pool_path")
        if isinstance(pp, str) and pp:
            rel = [x for x in pp.split("/") if x]
        else:
            pid = row.get("pointer_id")
            tail = pid.split(":", 2)[2] if isinstance(pid, str) and pid.count(":") >= 2 else _pid_fallback(row)
            rel = [str(row.get("collection") or "")] + tail.split("/")
        head = [self.domain_dir(row), src]
        uid = unit_id(row)
        if uid is not None:
            head.append(unit_folder(uid))
            ug = str(sm.get("unit_group") or "").strip("/")
            path = "/".join(rel)
            # #1633: a unit_group that is a file's path (the unit id of a unit whose first line is one file, such as a
            # migrated SEC review's filing) puts every file of the unit relative to that file's folder, so the filing
            # and the letters lie side by side at the top of the unit folder
            base = ug.rsplit("/", 1)[0] if "/" in ug else ""
            if ug and path.startswith(ug + "/"):
                rel = [x for x in path[len(ug) + 1:].split("/") if x]
            elif base and path.startswith(base + "/"):
                rel = [x for x in path[len(base) + 1:].split("/") if x]
            elif not ug or path == ug:
                rel = rel[-1:]
        out = head + rel
        key = "/".join(out)
        if key in self.taken and self.taken[key] != row.get("pointer_id"):
            out = head + [str(row.get("collection") or "_")] + rel  # another row already has this path
        self.taken["/".join(out)] = row.get("pointer_id")
        return out

    def line(self, row: dict, res: dict) -> dict:
        """The manifest.jsonl line of a fetched row (res: its fetch result with status ok)."""
        sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
        pf = _pool_fields(sm)
        e = self.entries.get(row.get("source")) or {}
        lic = e.get("license") if isinstance(e.get("license"), dict) else {}
        lo = row.get("license_override") if isinstance(row.get("license_override"), dict) else {}
        p = Path(res["path"])
        rel = p.resolve().relative_to(self.out.resolve()).as_posix()
        want = str((row.get("hashes") or {}).get("sha256") or "").lower()
        return {"source": row.get("source"), "path": rel, "url": res.get("url") or res.get("fetched_from"),
                "sha256": res.get("sha256"), "bytes": res.get("bytes"),
                "spdx": pf.get("spdx") or lo.get("spdx") or e.get("license_spdx")
                or (self.cat.get(row.get("source")) or {}).get("spdx"),
                "licence_url": pf.get("licence_url") or lic.get("url"), "publisher": pf.get("publisher"),
                "retrieved": res.get("retrieved") or utc_today(),
                "origin_kind": sm.get("origin_kind") or pf.get("origin_kind"), "leaf": self.leaf(row),
                "unit_id": unit_id(row),
                "verified": bool(res.get("unit_verified")) if res.get("extracted") else
                bool(want) and res.get("sha256") == want and not res.get("differs_from_index"),
                "_origin": (sm.get("pool_source") or {}).get("origin") if isinstance(sm.get("pool_source"), dict)
                else None, "_leaf_source": (sm.get("pool_source") or {}).get("leaf")
                if isinstance(sm.get("pool_source"), dict) else None}

    def write(self) -> dict:
        """Merge this run's lines into _meta/manifest.jsonl (by path; lines of earlier runs stay) and rewrite
        _meta/sizes.tsv from it. -> {files, sources}."""
        meta = self.out / META_OUT
        meta.mkdir(parents=True, exist_ok=True)
        mp = meta / "manifest.jsonl"
        old = {}
        if mp.is_file():
            with open(mp, encoding="utf-8") as f:
                for ln in f:
                    try:
                        x = json.loads(ln)
                    except ValueError:
                        continue
                    if isinstance(x, dict) and x.get("path") and (self.out / x["path"]).is_file():
                        old[x["path"]] = x
        extra = {}
        for x in self.lines:
            extra[x["path"]] = (x.pop("_origin"), x.pop("_leaf_source"))
            old[x["path"]] = x
        lines = [{k: x.get(k) for k in LAYOUT_FIELDS} for _, x in sorted(old.items())]
        mp.write_bytes("".join(json.dumps(x, ensure_ascii=False) + "\n" for x in lines).encode("utf-8"))
        by: dict = {}
        for x in lines:
            s = by.setdefault(x["source"], {"leaf": None, "origin": None, "bytes": 0, "spdx": None})
            o, lf = extra.get(x["path"], (None, None))
            s["bytes"] += int(x.get("bytes") or 0)
            if x.get("unit_id") is not None:
                s["leaf"] = s["leaf"] or lf or x.get("leaf")
                s["spdx"] = s["spdx"] or x.get("spdx")
                if s["origin"] is None:
                    u = urllib.parse.urlsplit(str(o or x.get("url") or ""))
                    s["origin"] = o or (f"{u.scheme}://{u.netloc}" if u.netloc else None)
        sp = meta / "sizes.tsv"
        rows = []
        if sp.is_file():  # sources of earlier runs keep their line unless this manifest recounts them
            with open(sp, encoding="utf-8", newline="") as f:
                for c in csv.reader(f, delimiter="\t", quoting=csv.QUOTE_NONE):
                    if len(c) == 5 and c[1] not in by:
                        rows.append(c)
        rows += [[str(v["leaf"] or ""), s, str(v["origin"] or ""), str(v["bytes"]), str(v["spdx"] or "")]
                 for s, v in by.items()]
        sp.write_bytes("".join("\t".join(r) + "\n" for r in sorted(rows, key=lambda r: (r[0], r[1]))).encode("utf-8"))
        return {"files": len(lines), "sources": len(rows)}


# ---------- command line ----------

def _key(row: dict) -> dict:
    rng = row.get("range") if isinstance(row.get("range"), dict) else {}
    return {"source": row.get("source"), "uri": row.get("uri"), "range_offset": rng.get("offset"),
            "member_path": row.get("member_path")}


def resolve_repo_uri(row: dict, root: str, public: str | None = None) -> dict:
    """A row whose uri names a file in the index repository (REPO_FILES, no scheme) -> the same row with uri read
    from root: hf://datasets/<repo>@<commit>/<path> on the Hub (fetched from, and recorded as, its absolute URL
    https://huggingface.co/datasets/<repo>/resolve/<commit>/<path>), root/<path> for a URL prefix. For a local --data
    copy the uri stays as it is and _local_file names the file inside root (read by local_file_opener; the file
    must lie inside root); public (hf://datasets/<repo>[@<revision>]) gives _public_url, the absolute URL the
    manifest records for it instead of the local path. The original value stays in repo_uri. Other rows come back
    unchanged."""
    uri = row.get("uri")
    if not isinstance(uri, str) or not uri.startswith(REPO_FILES) or "://" in uri:
        return row
    parts = uri.split("/")
    if any(p in ("", ".", "..") for p in parts) or "\\" in uri:
        return row
    if is_remote(root):
        return {**row, "uri": f"{root}/{uri}", "repo_uri": uri}
    top = Path(root).resolve()
    path = top.joinpath(*parts).resolve()
    if top not in path.parents:
        return row
    out = {**row, "_local_file": str(path), "repo_uri": uri}
    if public:
        out["_public_url"] = to_http(f"{public}/{uri}")
    return out


def campaign_fields(row: dict) -> dict:
    """The CAMPAIGN_KEYS of the row's source_meta, for the manifest line."""
    sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
    return {k: sm[k] for k in CAMPAIGN_KEYS if k in sm}


def selected_rows(con, sql: str, specs: dict):
    cur = con.execute(sql)
    names = [d[0] for d in cur.description]
    while True:
        batch = cur.fetchmany(1000)
        if not batch:
            break
        for t in batch:
            col = dict(zip(names, t))
            spec = specs.get(col["source"])
            if spec is None:
                yield {**_key({"source": col["source"], "uri": col["uri"], "member_path": col.get("member_path")}),
                       "status": "unsupported", "reason": "source missing from meta/sources.json"}, None
                continue
            row = {k: v for k, v in restore(col, spec).items() if not str(k).startswith("_")}
            row["_size_cap"] = col.get("size_cap_bytes")
            row["_batch_cap"] = col.get("batch_cap_bytes")
            row["_nk_conflict"] = bool(col.get("natural_key_conflict"))
            yield None, row


def parse_args(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawTextHelpFormatter,
                                 epilog=HELP_ENV)
    ap.add_argument("--repo", default=DEFAULT_REPO, help=f"dataset repository (default {DEFAULT_REPO})")
    ap.add_argument("--data", help="read the tables from this local copy or URL prefix instead of the repository")
    ap.add_argument("--revision",
                    help="read the repository at this commit (40 hex characters), tag or pull request ref refs/pr/<n>\n"
                         "(pinned to the commit it points to); default: the release this script was published in"
                         + (f" ({RELEASE})" if RELEASE else "") + ",\n"
                         "else the commit the main branch points to when the script starts.\n"
                         "Record it to repeat a selection later. With a local --data copy it only records the\n"
                         "commit that copy holds (not checked)")
    ap.add_argument("--tag", action="append",
                    help="collection tag campaign:<name> (repeatable; see meta/tags.parquet)")
    ap.add_argument("--domain", action="append",
                    help="domain code from meta/catalog.parquet (repeatable, any of them): D1 to D10 or a leaf\n"
                         "such as D1.6; a top-level code also matches its leaves (D3 matches D3.5), a leaf only\n"
                         "itself; multi and unclassified match only themselves. Codes: catalog/domains.yaml of\n"
                         "the pipeline repository, or the README of the index")
    ap.add_argument("--form", action="append",
                    help="form id from meta/catalog.parquet, such as test-suites (repeatable, any of them);\n"
                         "with --domain a source must match both")
    ap.add_argument("--kind", action="append",
                    help="layer from the column kind of meta/catalog.parquet: material_set or corpus (repeatable,\n"
                         "any of them); with --domain or --form a source must match those too")
    ap.add_argument("--ext", action="append",
                    help="file extension without the dot (repeatable, any of them): takes the units with a\n"
                         "file of that extension, each with all its files and its source's own files")
    ap.add_argument("--source", action="append", help="source name (repeatable)")
    ap.add_argument("--unit", action="append", metavar="UNIT_ID",
                    help="unit_id of a unit (repeatable, any of them; the unit_id of a file is in\n"
                         "_meta/manifest.jsonl): takes that unit, whole, with its source's own files; a unit_id is\n"
                         "unique within a source, so name the source with --source")
    ap.add_argument("--selection", metavar="FILE",
                    help="a selection file saved by the data page (JSON: sources, revision, filters): its sources\n"
                         "are read as --source and its revision as --revision; every run writes its own selection\n"
                         f"file as {META_OUT}/{SELECTION_JSON}, with the options that chose its rows and --sample")
    ap.add_argument("--inbox", metavar="DEST",
                    help=f"write the run's selection file into DEST in place of {META_OUT}/{SELECTION_JSON}: an rclone\n"
                         "path of a folder (remote:path), such as a line's folder pool_<line> of the inbox the\n"
                         "index's admission reads, as selection-<the first 16 hex digits of its sha256>.json, by\n"
                         "rclone rcat (rclone on PATH, signed in to DEST by its environment)")
    ap.add_argument("--tier", type=lambda s: [x for x in s.split(",") if x],
                    help="training license tiers, comma separated (default: all tiers)")
    ap.add_argument("--min-size", type=int, help="smallest size in bytes")
    ap.add_argument("--max-size", type=int,
                    help="size cap in bytes used when fetching, for every row (replaces the overall cap); it\n"
                         "does not remove rows from the selection")
    ap.add_argument("--max-size-filter", type=int,
                    help="leave out the rows whose published size is larger than this many bytes (rows of\n"
                         "unknown size stay; --max-size or the overall cap still bound what is downloaded)")
    ap.add_argument("--where", help="extra SQL condition on the row table p (and the batch table b)")
    ap.add_argument("--limit", type=int,
                    help="at most this many units over the whole selection, from the selected sources in turn (the\n"
                         "first unit of each source, then the second of each, ...), each source's in a fixed order\n"
                         "(by the sha256 of the path of the data file that holds the unit, then by the unit); the\n"
                         "sources' data files are read in turn in that order, only as far as these units need")
    ap.add_argument("--sample", type=int,
                    help="this many units per selected source, the same ones every run (the fixed order of --limit,\n"
                         "a source's data files read only as far as its units need); each unit whole, in a folder\n"
                         "of its own, with the source's own files (README.md, LICENSE)")
    ap.add_argument("--all", action="store_true",
                    help="turn off the default profile except its benchmark criteria: apply the conditions given\n"
                         "here, and still leave out rows that matched a benchmark or were not compared with the\n"
                         "benchmark list yet (only --allow-benchmark and --allow-not-compared keep those)")
    ap.add_argument("--no-default-filter", dest="all", action="store_true", help=argparse.SUPPRESS)
    ap.add_argument("--keep-duplicates", action="store_true", help="profile: keep duplicate copies")
    ap.add_argument("--allow-benchmark", action="store_true",
                    help="profile: keep rows that matched a benchmark (copies of benchmark data, collections\n"
                         "awaiting a ruling) and rows not compared with the benchmark list yet")
    ap.add_argument("--allow-not-compared", action="store_true",
                    help="profile: keep rows whose data file was not compared with the benchmark list yet (rows\n"
                         "that matched a benchmark stay out)")
    ap.add_argument("--any-license", "--any-licence", dest="any_license", action="store_true",
                    help="profile: keep rows whose license does not let the files be shipped")
    ap.add_argument("--any-language", action="store_true", help="profile: keep rows recorded in a language other "
                                                                 "than English")
    ap.add_argument("--allow-personal-data", action="store_true",
                    help="profile: keep rows of sources or rows marked as carrying personal data")
    ap.add_argument("--any-size", action="store_true",
                    help=f"profile: keep rows above {PROFILE_MAX_BYTES:,} bytes (the overall cap still bounds the\n"
                         f"download)")
    ap.add_argument("--out", default="fetched", help="directory for the files and _meta/ (default ./fetched)")
    ap.add_argument("--local-root", action="append",
                    help=f"reuse a file under this directory whose size and hashes match a row instead of downloading\n"
                         f"it (repeatable; default: the {LOCAL_ROOTS_ENV} variable, directories separated by\n"
                         f"{os.pathsep!r}); each manifest line records obtained: reused, staged or fetched")
    ap.add_argument("--staging",
                    help=f"directory where an outside fetch placed files; checked like a local root, recorded as\n"
                         f"staged (default: the {STAGING_ENV} variable)")
    ap.add_argument("--print-sql", action="store_true",
                    help="print the query and exit (over the whole selection; with --limit or --sample a run\n"
                         "judges it over the data files it reads, a round of files at a time)")
    ap.add_argument("--memory-limit",
                    help="DuckDB memory limit, for example 8GB (default: the smaller of 4GB and a quarter of the\n"
                         "memory available, the cgroup limit when lower); what does not fit is written to the\n"
                         "spill directory")
    ap.add_argument("--threads", type=int,
                    help="DuckDB threads (default: one per GB of the memory limit, at most the number of CPUs)")
    ap.add_argument("--temp-dir", help=f"DuckDB spill directory (default: {SPILL_DIR} under --out, removed at the end)")
    ap.add_argument("--decompress", action="store_true",
                    help="after a verified download, decompress .gz, .bz2 and .zst files (within the row's cap)\n"
                         "and delete the compressed file; .zst needs pip install zstandard")
    ap.add_argument("--check-content", action="store_true",
                    help="after a verified download, flag scanned PDFs, error pages saved as files and extensions\n"
                         "that do not match the content (manifest field content_check); needs the file command\n"
                         "and the pypdf package (in the script's dependency block), a missing one skips its check")
    ap.add_argument("--proxy",
                    help="proxy for every request: http://host:port, or socks5h://host:port\n"
                         "(a proxy login goes before the host as user:password followed by an at sign).\n"
                         "(DuckDB and the byte-range reads of archive members cannot use a socks proxy,\n"
                         "see --data).\n"
                         "Default: HTTPS_PROXY, HTTP_PROXY or ALL_PROXY from the environment")
    ap.add_argument("--contact",
                    help="your e-mail or URL, sent in the User-Agent so a site can reach you instead of blocking")
    ap.add_argument("--quiet", action="store_true",
                    help="no progress lines, and no line per source before the fetch or per file on stderr")
    ap.add_argument("--json", action="store_true",
                    help="end with the summary as one JSON object on stdout (the default when stdout is not a\n"
                         "terminal); on a terminal it is otherwise a few lines in words")
    ap.add_argument("--timeout", type=float, default=120,
                    help="seconds a download may wait to connect, or for its next bytes, before that address\n"
                         "fails (default 120); it does not bound a whole download. The reads of the index tables\n"
                         f"have their own: {HTTP_SETTINGS['http_timeout']} seconds a request, retried for up to "
                         f"{RETRY_SECONDS} seconds")
    a = ap.parse_args(argv)
    if a.contact is not None and not re.fullmatch(r"[^\x00-\x1f()\x7f]{1,200}", a.contact):
        ap.error("--contact takes one line of at most 200 characters without parentheses")
    for k in ("limit", "sample"):
        if getattr(a, k) is not None and getattr(a, k) < 1:
            ap.error(f"--{k} must be 1 or more")
    if a.threads is not None and a.threads < 1:
        ap.error("--threads must be 1 or more")
    for t in a.tier or ():
        if t not in TIERS:
            ap.error(f"unknown tier {t}; use {', '.join(TIERS)}")
    for d in a.domain or ():
        if not DOMAIN_RE.fullmatch(d):
            ap.error(f"--domain {d!r} is not a domain code; use D<n> or D<n>.<m> (such as D3 or D1.6), multi or "
                     f"unclassified")
    for f in a.form or ():
        if not FORM_RE.fullmatch(f):
            ap.error(f"--form {f!r} is not a form id; use lower-case words joined by '-' (such as test-suites)")
    if a.selection is not None:
        sel = json.loads(Path(a.selection).read_text(encoding="utf-8"))
        # a file without sources would select the whole index
        if not sel.get("sources"):
            ap.error(f"--selection {a.selection} lists no source")
        a.source = [*(a.source or ()), *sel["sources"]]
        if a.revision is None:
            a.revision = sel.get("revision")
        elif sel.get("revision") and a.revision.lower() != str(sel["revision"]).lower():
            ap.error(f"--revision {a.revision} differs from the revision of --selection {a.selection} ({sel['revision']})")
    if a.revision is None and a.data is None:
        a.revision = RELEASE or None
    if a.revision is not None:
        if re.fullmatch(r"[0-9A-Fa-f]{40}", a.revision):
            a.revision = a.revision.lower()
        elif not REF_RE.fullmatch(a.revision) or ".." in a.revision:
            ap.error("--revision takes a full commit id (40 hex characters), a tag name (letters, digits, . _ -) or "
                     "a pull request's ref refs/pr/<n>")
        if revision_of(_root(a)) is not None:
            ap.error("--data already names a revision (@...); drop --revision or the @ part")
    return a


def revision_of(root: str) -> str | None:
    """The revision an hf://datasets/<owner>/<name>@<revision>/... root names, else None."""
    if not root.startswith(HF_DATASETS):
        return None
    parts = root[len(HF_DATASETS):].split("/", 2)
    name = parts[1] if len(parts) > 1 else ""
    return (name.split("@", 1)[1] or None) if "@" in name else None


class IndexReadError(Exception):
    """The index tables could not be read or queried (the message says what to check)."""


def _index_error(e: BaseException, root: str) -> IndexReadError:
    first = (str(e).strip().splitlines() or [""])[0][:400]
    return IndexReadError(f"could not read the index at {root}: {type(e).__name__}: {first}\n"
                          f"check the --repo/--data path, your network or proxy (--proxy), and that --where, "
                          f"--tag and --source are spelled right")


def _file_line(res: dict) -> tuple:
    """-> (source, path, the per-file line): status, source and path (the pointer id without its batch name) and the
    size in short units (tqdm.format_sizeof) or the reason."""
    from tqdm import tqdm

    pid = res.get("pointer_id")
    if isinstance(pid, str) and pid.count(":") >= 2:
        src, _, path = pid.split(":", 2)
    else:
        src, path = str(res.get("source") or ""), str(res.get("member_path") or res.get("uri") or "")
    extra = str(res.get("reason") or (tqdm.format_sizeof(res["bytes"], "B") if res.get("bytes") is not None else ""))
    extra = extra[:200]
    if res.get("html_page"):
        extra = f"{blocked_words(res['html_page'])} ({extra})"
    return src, path, f"{res.get('status')} {src} {path}" + (f": {extra}" if extra else "")


def load_entries(con, root: str, names=None) -> dict:
    """{source: its meta/sources.json entry} (the layout rebuilds rows; the license gives licence_url), only names
    when given."""
    text = con.execute(f"SELECT content FROM read_text({sql_str(root + '/meta/sources.json')})").fetchone()[0]
    want = None if names is None else set(names)
    return {s["source"]: s for s in json.loads(text)["sources"] if want is None or s["source"] in want}


def _n(n: int, what: str) -> str:
    return f"{n:,} {what}{'' if n == 1 else 's'}"


def _keeps(n: str) -> str:
    return "--" + RELAX[n].replace("_", "-")


def report_counts(con, relaxed, given: str, scope: str = "") -> dict:
    """Prints on stderr how many units and files the selection had and how many units each criterion of the profile
    removed, with its reason (a unit is counted under the first criterion it fails); a selection that ends empty
    says why. The files are every file of the selection's units and the files of its sources (README.md, LICENSE).
    scope (#2035): where the rows were counted, such as the data files --limit or --sample read (read_units), said
    after the conditions given. -> the counts."""
    rank = {i + 1: n for i, n in enumerate(CRITERIA)}
    groups = con.execute("SELECT fail, count(*), sum(files) FROM fetch_units GROUP BY fail").fetchall()
    units = sum(int(n) for _, n, _ in groups)
    files = sum(int(f or 0) for _, _, f in groups)
    nsrc = con.execute("SELECT count(DISTINCT source) FROM fetch_units").fetchone()[0]
    own = con.execute("SELECT count(*) FROM fetch_cand WHERE unit IS NULL").fetchone()[0]
    removed = {rank[f]: int(n) for f, n, _ in groups if f is not None}
    kept = sum(int(n) for f, n, _ in groups if f is None)
    on = [n for n in CRITERIA if n not in set(relaxed)]
    say = lambda s: print(s, file=sys.stderr, flush=True)  # noqa: E731
    say(f"selection{given}{scope}: {_n(units, 'unit')} and {_n(files + own, 'file')} in {_n(nsrc, 'source')}"
        + (f" ({_n(own, 'file')} of the sources themselves among the files)" if own else ""))
    if not on:
        say("profile: off")
    for n in on:
        say(f"  removed by {n} ({REASONS[n]}): {removed.get(n, 0):,}"
            + (f"  ({_keeps(n)} keeps them)" if removed.get(n) else ""))
    if on and len(on) < len(CRITERIA):
        say("  not applied: " + ", ".join(n for n in CRITERIA if n not in on))
    say(f"  kept: {_n(kept, 'unit')}")
    out = {"units": units, "files": files + own, "unit_files": files, "source_files": own, "sources": nsrc,
           "removed": {n: removed.get(n, 0) for n in on}, "reasons": {n: REASONS[n] for n in on},
           "options": {n: _keeps(n) for n in on}, "kept": kept, "profile": on}
    if units == 0:
        say(f"nothing selected: no row matches the conditions given{given}")
        out["emptied_by"] = "conditions"
    elif kept == 0:
        last = [n for n in on if removed.get(n)][-1]
        say(f"nothing selected: the {last} criterion ({REASONS[last]}) removed the last "
            f"{_n(removed[last], 'unit')}; {_keeps(last)} keeps them")
        out["emptied_by"] = last
    return out


def _given(args) -> str:
    parts = [f"--source {s}" for s in args.source or ()] + [f"--domain {d}" for d in args.domain or ()]
    parts += [f"--form {f}" for f in args.form or ()] + [f"--kind {k}" for k in args.kind or ()]
    parts += [f"--tag {t}" for t in args.tag or ()]
    parts += [f"--unit {u}" for u in args.unit or ()]
    parts += [f"--ext {e}" for e in args.ext or ()]
    for k in ("tier", "min_size", "max_size_filter", "where"):
        v = getattr(args, k)
        if v is not None:
            parts.append(f"--{k.replace('_', '-')} {','.join(v) if isinstance(v, list) else v}")
    return f" ({' '.join(parts)})" if parts else ""


def selection_filters(args) -> dict:
    """#1909: the options of SELECTION_OPTIONS this run was given, as its selection file records them in filters:
    {name: value as parsed}, a list for a repeatable option and for --tier, true for a switch."""
    return {k: v for k in SELECTION_OPTIONS for v in [getattr(args, k)] if v not in (None, False, [], "")}


def selection_argv(doc: dict) -> list:
    """#1909: the options that choose the rows a selection file records again, to go with --selection FILE: each key of
    its filters as its option (a list as the option once per value, --tier as one comma-separated value, true as the
    switch alone), each value after = so that one starting with - stays a value, and its sample as --sample."""
    out = []
    for k, v in (doc.get("filters") or {}).items():
        opt = "--" + k.replace("_", "-")
        if v is True:
            out.append(opt)
        elif k == "tier":
            out.append(f"{opt}={','.join(v)}")
        elif isinstance(v, list):
            out += [f"{opt}={e}" for e in v]
        else:
            out.append(f"{opt}={v}")
    if doc.get("sample"):
        out.append(f"--sample={doc['sample']}")
    return out


def main(argv=None) -> int:
    from huggingface_hub import get_session
    from tqdm import tqdm

    t0 = time.monotonic()
    args = parse_args(argv)
    get_session().event_hooks["request"].append(lambda request: count_sent(request.url))  # #2177: hub_requests
    local = LocalFiles.from_settings(args.local_root, args.staging)
    proxy = args.proxy or env_proxy()
    set_network(proxy, args.contact)
    opener = open_url
    root = _root(args)
    domains, forms, kinds, tags = args.domain or (), args.form or (), args.kind or (), args.tag or ()
    relaxed = tuple(n for n in CRITERIA if getattr(args, RELAX[n]) or (args.all and n not in BENCHMARK_CRITERIA) or
                    (n == "not compared" and args.allow_benchmark))
    profile = profile_conditions(relaxed)
    size_cap = None if "size" in relaxed else PROFILE_MAX_BYTES
    conds = build_where(tags=tags, tiers=args.tier, min_size=args.min_size, where=args.where,
                        max_size_filter=args.max_size_filter, units=args.unit or ())
    exts = args.ext or ()
    tag_rev = args.revision if args.revision and not re.fullmatch(r"[0-9a-f]{40}", args.revision) else None
    if args.revision and not tag_rev:
        root = pin_root(root, revision=lambda repo: args.revision)
    # #2035: --limit and --sample take the first units in the two-stage fixed order (the data file's file_key, then
    # unit_key), reading the data files only as far as they need (read_units)
    keyed = args.limit is not None or args.sample is not None
    if args.print_sql:
        if tag_rev:
            root = pin_root(root, revision=lambda repo: tag_rev, ref_ok=True)
        sel = build_where(sources=args.source or (), domains=domains, forms=forms, kinds=kinds)
        if not catalog_names_files(root):
            raise older_catalog(root)
        print(";\n".join(views_sql(root, sources=args.source or (), domains=domains, forms=forms, kinds=kinds)) + ";")
        keys = [file_keys_sql(root, f"SELECT DISTINCT unnest({DATA_FILES}) AS f FROM "
                                    f"read_parquet({sql_str(root + '/' + CATALOG)})")] if keyed else []
        print(";\n".join([*keys, *cand_steps(sel + conds, profile, args.max_size, size_cap, exts, keyed=keyed),
                          *take_steps(args.limit, args.sample, keyed), part_query()]) + ";")
        return 0
    if root.startswith(HF_DATASETS) and not os.environ.get("HF_TOKEN"):
        print(ANONYMOUS, file=sys.stderr, flush=True)
    if tag_rev and root.startswith(HF_DATASETS):
        def _tag(repo):
            try:
                return repo_revision(repo, ref=tag_rev)
            except Exception as e:  # noqa: BLE001  pin the tag name itself
                _stderr(f"could not read the commit of tag {tag_rev} ({type(e).__name__}: {e}); reading the tag "
                        f"by name")
                return tag_rev
        root = pin_root(root, revision=_tag, ref_ok=True)
    root = pin_root(root)
    hub = root.startswith(HF_DATASETS)
    # a local copy (or another URL prefix) is not resolved: a given --revision is only recorded
    rev = revision_of(root) if hub else args.revision
    if rev and hub:
        print(f"reading {root} (commit {rev}); pass --revision {rev} to select the same rows later", file=sys.stderr)
    if is_remote(root):
        _TRANSFORM["src"] = to_http(f"{root}/tools/transform.py")
    elif Path(root, "tools", "transform.py").is_file():
        _TRANSFORM["src"] = str(Path(root, "tools", "transform.py"))
    out = Path(args.out)
    meta = out / META_OUT
    meta.mkdir(parents=True, exist_ok=True)
    spill = Path(args.temp_dir) if args.temp_dir else out / SPILL_DIR
    own_spill = not args.temp_dir
    limit = args.memory_limit or default_memory_limit()
    try:
        con = connect(limit, str(spill), remote=is_remote(root), proxy=proxy)
    except ValueError as e:
        raise IndexReadError(str(e)) from None
    threads = args.threads or default_threads(limit)
    if threads and not args.threads and is_remote(root):
        threads = min(threads, REMOTE_THREADS)
    if threads:
        con.execute(f"SET threads = {int(threads)}")
    counts: dict = {}
    auth_skipped: dict = {}
    selection: dict = {}
    run_id = utc_now().strftime("%Y%m%dT%H%M%S.%fZ")
    n_row = 0
    fetched_bytes = 0
    # on a terminal the per-file lines wait for the end of the run, sorted by source and path
    tty = sys.stderr.isatty()
    file_lines: list = []
    layout = None
    incomplete: dict = {}
    # {unit or source: {status: lines}} of this run (a file of a unit, a file of its source)
    file_kinds: dict = {}
    # #2144: {source: lines} of this run, and {source: {files, title}} of its lines whose upstream answered with an
    # HTML page (html_page)
    tried: dict = {}
    blocked: dict = {}
    given = _given(args)
    # the sources whose rows the run reads (#1909: the sources of its selection file)
    names: list = []
    # their data files ({source: full paths}, source_files) and whether their rows are few enough to copy into memory
    # (LOCAL_ROWS); #2035: with --limit or --sample, the files read_units read, its rounds and the seconds they took
    by_source: dict = {}
    local_rows = False
    read: list = []
    rounds = 0
    secs = 0.0
    try:
        queries, specs, entries, cat = [], {}, {}, {}
        try:
            with step_bar("reading the index", "tables", 1, args.quiet) as bar:
                has = waiting(bar, con, catalog_table, con, root)
                bar.update(1)
                for flag, col in ((forms, "form"), (domains, "domain")):
                    if flag and not has[col]:
                        raise IndexReadError(
                            f"{CATALOG} at {root} has no column {col}: this revision of the index is older than the "
                            f"columns domain and form, so --domain and --form cannot be used with it; read a newer "
                            f"revision (a later --revision, or none for the current one)")
                check_names(con, sources=args.source or (), domains=domains, forms=forms, kinds=kinds,
                            has_form=has["form"], where=f" at commit {rev}" if rev else "")
                everything = not (args.source or domains or forms or kinds or tags)
                sources = resolve_sources(con, root, domains=domains, forms=forms, kinds=kinds,
                                          sources=args.source or ())
                batches = None
                if tags and sources:
                    bar.total += 1
                    batches = waiting(bar, con, tag_batches, con, root, tags,
                                      sources if args.source or domains or forms or kinds else ())
                    bar.update(1)
                    everything = False
                cat = {str(s): {"domain": list(d or []), "spdx": sp, "files": f,
                                "fetch": {"level": lv, "rows": fr, "fetched": ff, "read_at": fd}}
                       for s, d, sp, f, lv, fr, ff, fd in con.execute(
                           "SELECT source, domain, spdx, files, fetch_level, fetch_rows, fetch_fetched, fetch_read_at "
                           "FROM s").fetchall()}
                if sources and batches != []:
                    names = sorted({s for s, _ in batches}) if batches else sources
                    rows = sum(int((cat.get(s) or {}).get("files") or 0) for s in names)
                    by_source = source_files(con, root, names, batches)
                    local_rows = rows <= LOCAL_ROWS
                    jobs = table_steps(root, sources, sorted({p for ps in by_source.values() for p in ps}),
                                       batches=batches, tags=tags, everything=everything, local_rows=local_rows)
                    if keyed:
                        # #2035: read_units reads the rows, a round of data files at a time
                        del jobs["p"]
                    jobs["specs"] = lambda cur: load_entries(cur, root, None if everything else names)
                    bar.total += len(jobs)
                    bar.set_description(f"reading the index ({_n(len(names), 'source')})")
                    entries = read_parallel(con, jobs, bar)["specs"]
                    if not keyed:
                        waiting(bar, con, complete_rows, con)
            if not sources or batches == []:
                why = "no source matches" if not sources else "no batch carries the tags"
                print(f"selection{given}: {why}; nothing selected", file=sys.stderr)
                selection = {"units": 0, "files": 0, "emptied_by": "conditions"}
            else:
                specs = {s: e["layout"] for s, e in entries.items()}
                if keyed:
                    t1 = time.monotonic()
                    rows_of = functools.partial(table_rows, root, sources=sources, batches=batches,
                                                everything=everything)
                    files = sorted({p for ps in by_source.values() for p in ps})
                    cand = cand_select(conds, profile, args.max_size, size_cap, exts, keyed=True)
                    judge = cand_steps(conds, profile, args.max_size, size_cap, exts, keyed=True, read="fetch_read")
                    with step_bar("reading the data files", "files", len(files), args.quiet) as bar:
                        read, rounds = read_units(con, root, by_source, rows_of, cand, judge, bar, limit=args.limit,
                                                  sample=args.sample, local=local_rows)
                    secs = time.monotonic() - t1
                    need = ([f"--sample {args.sample}"] if args.sample else []) + \
                           ([f"--limit {args.limit}"] if args.limit else [])
                    print(f"data files read: {len(read):,} of the selection's {len(files):,} in {secs:.1f} s (each "
                          f"source's in the order of the sha256 of their paths"
                          + (", the sources in turn" if args.limit else "") + f", as far as {' and '.join(need)} "
                          "needed)", file=sys.stderr, flush=True)
                else:
                    steps = cand_steps(conds, profile, args.max_size, size_cap, exts)
                    with step_bar("planning the selection", "steps", len(steps), args.quiet) as bar:
                        run_steps(con, steps, bar)
                selection = report_counts(con, relaxed, given,
                                          f" in the {_n(len(read), 'data file')} read" if keyed else "")
                if keyed:
                    selection.update(data_files=len(files), data_files_read=len(read), read_seconds=round(secs, 1))
                if selection["kept"]:
                    picks, whole = pick_steps(args.limit, args.sample, keyed), rows_steps()
                    with step_bar("picking the units", "steps", len(picks) + len(whole) + 1, args.quiet) as bar:
                        run_steps(con, picks, bar)
                        if keyed:
                            waiting(bar, con, picked_rows, con, root, rows_of, read, rounds, local_rows)
                        run_steps(con, whole, bar)
                        queries = waiting(bar, con, part_queries, con, limit)
                        bar.update(1)
                    tu = con.execute("SELECT count(*) FROM fetch_take").fetchone()[0]
                    tf, ts, tb, tn = con.execute(
                        "SELECT count(*), count(*) FILTER (WHERE fetch_source_file), coalesce(sum(size_bytes), 0), "
                        "count(*) FILTER (WHERE size_bytes IS NULL) FROM fetch_rows").fetchone()
                    selection.update(taken_units=int(tu), taken_files=int(tf), taken_source_files=int(ts),
                                     taken_bytes=int(tb), taken_unsized_files=int(tn))
                    if not args.quiet:
                        for line in source_lines(taken_sources(con)):
                            print(line, file=sys.stderr, flush=True)
                    how = (f" (--sample {args.sample} per source)" if args.sample else "") + \
                          (f" (--limit {args.limit})" if args.limit else "")
                    print(f"fetching: {_n(tu, 'unit')}{how}: {_n(tf, 'file')}"
                          + (f" ({_n(ts, 'file')} of the sources themselves among them)" if ts else "")
                          + f", {tqdm.format_sizeof(int(tb), 'B')}"
                          + (f" (and {_n(tn, 'file')} of unknown size)" if tn else ""),
                          file=sys.stderr, flush=True)
                    weak = fetch_note(cat, con.execute("SELECT DISTINCT source FROM fetch_rows").fetchall(),
                                      release_day(args.revision))
                    if weak:
                        print(weak, file=sys.stderr, flush=True)
        except UnknownName:
            raise
        except IndexReadError:
            raise
        except (urllib.error.URLError, OSError, ValueError, RuntimeError) as e:
            raise _index_error(e, root) from e
        except Exception as e:  # noqa: BLE001  duckdb.Error and its subclasses
            if type(e).__module__.split(".")[0] in ("duckdb", "_duckdb"):
                raise _index_error(e, root) from e
            raise
        layout = Layout(out, cat, entries)
        # a local --data copy: rows stored in the index repository are recorded with their public URL at the revision
        # the copy holds (--revision), not with a local path
        public = None
        if not is_remote(root):
            public = f"{HF_DATASETS}{args.repo}" + (f"@{args.revision}" if args.revision else "")
        warned = False
        total = selection.get("taken_files")
        with tqdm(total=total, unit="file", disable=True if args.quiet else None) as bar, \
                open(meta / MANIFEST, "a", encoding="utf-8") as man:
            for early, row in (r for q in queries for r in selected_rows(con, q, specs)):
                sm: dict = {}
                if row is not None:
                    row = resolve_repo_uri(row, root, public)
                    row["_dest_parts"] = layout.parts(row)
                    if row.get("_public_url") and not args.revision and not warned:
                        _stderr(f"files of the index repository read from the local copy are recorded with their URL "
                                f"on the main branch; pass --revision <the commit the copy holds> to record that one")
                        warned = True
                    sm = row["source_meta"] if isinstance(row.get("source_meta"), dict) else {}
                uid = unit_id(row) if row is not None else None
                kind = "source" if row is not None and uid is None else "unit"
                group = (row.get("source"), uid) if row is not None and sm.get("unit_group") else None
                if early is not None:
                    res = early
                else:
                    res = {**_key(row), **fetch_unit(row, out, timeout=args.timeout, opener=opener,
                                                     skip_present=True, local=local)}
                    if args.decompress and res.get("status") == "ok" and res.get("path"):
                        d = decompress_file(Path(res["path"]), row, cap_of(row))
                        if d is not None:
                            res["decompress"] = d
                            if d["status"] == "ok":
                                res["path"] = d["path"]
                    if args.check_content and res.get("status") == "ok" and res.get("path"):
                        p = Path(res["path"])
                        ext = None if res.get("decompress", {}).get("status") == "ok" else row.get("ext")
                        try:
                            res["content_check"] = check_content(p, ext)
                        except OSError as e:
                            res["content_check"] = {"skipped": {"all": f"could not read the file: {e}"}}
                if row is not None:
                    res.update(campaign_fields(row))
                    res["unit_id"] = uid
                    res["layout_path"] = "/".join(row["_dest_parts"])
                    # #1909: the row's full pointer, so a file not read whole is fetched again the same way
                    res["pointer"] = {k: v for k, v in row.items() if not str(k).startswith("_")}
                    if row.get("repo_uri"):
                        res["uri"] = row["repo_uri"]
                    if row.get("_public_url") and res.get("url") == row.get("_local_file"):
                        res["url"] = row["_public_url"]
                        res["read_from"] = "local copy"
                    if res.get("status") == "ok" and res.get("path"):
                        layout.lines.append(layout.line(row, res))
                    if group and res.get("status") != "ok":
                        incomplete.setdefault(group, res.get("status"))
                if row is not None and row.get("size_bytes") is None:
                    res["size_unknown"] = True
                if row is not None and row.get("_nk_conflict"):
                    res["natural_key_conflict"] = True
                if hub or rev:
                    res["revision"] = rev
                if res.get("status") == "skipped" and res.get("needs_auth") is not None:
                    k = auth_key(res["needs_auth"])
                    auth_skipped[k] = auth_skipped.get(k, 0) + 1
                counts[res["status"]] = counts.get(res["status"], 0) + 1
                by_kind = file_kinds.setdefault(kind, {})
                by_kind[res["status"]] = by_kind.get(res["status"], 0) + 1
                src = str(res.get("source") or "")
                tried[src] = tried.get(src, 0) + 1
                if res.get("html_page"):
                    blocked.setdefault(src, {"files": 0, "title": res["html_page"].get("title") or ""})["files"] += 1
                if res["status"] == "ok":
                    fetched_bytes += int(res.get("bytes") or 0)
                res["run_id"] = run_id
                man.write(json.dumps(res, ensure_ascii=False, sort_keys=True) + "\n")
                man.flush()
                n_row += 1
                bar.update(1)
                if not args.quiet:
                    line = _file_line(res)
                    if tty:
                        file_lines.append(line)
                    else:
                        print(line[2], file=sys.stderr, flush=True)
    finally:
        clear_package_cache()
        _SETUP.pop(id(con), None)
        sent = hub_requests(con, is_remote(root))
        con.close()
        if own_spill:
            shutil.rmtree(spill, ignore_errors=True)
    for _, _, line in sorted(file_lines, key=lambda x: (x[0], x[1])):
        print(line, file=sys.stderr)
    for src, b in sorted(blocked.items()):
        print(f"upstream blocks scripts: {src}: {b['files']:,} of its {_n(tried.get(src, 0), 'file')} in this run came "
              f"back as an HTML page" + (f' ("{b["title"]}")' if b["title"] else "") + " in place of the file; such "
              f"files can be downloaded in a web browser from the url of their lines in {META_OUT}/{MANIFEST}",
              file=sys.stderr)
    lay = layout.write() if layout is not None else None
    if incomplete:
        print(f"incomplete: {_n(len(incomplete), 'unit')} miss a file (the files fetched are kept; "
              f"_meta/fetch_manifest.jsonl says why): " + "; ".join(f"{s} {u} ({st})" for (s, u), st in
                                                                    list(incomplete.items())[:10]), file=sys.stderr)
    if hub:
        print(f"requests to the Hub: {sent['resolver']:,} resolver, {sent['api']:,} API, {sent['other']:,} other",
              file=sys.stderr)
    summary = {"manifest": str(meta / MANIFEST), "counts": counts, "files": file_kinds,
               "needs_auth_skipped": auth_skipped, "requests": sent,
               "run_id": run_id, "selection": selection, "seconds": round(time.monotonic() - t0, 1)}
    if any(k != "ok" for k in counts):
        summary["not_ok_query"] = not_ok_query(meta / MANIFEST, run_id)
    if incomplete:
        summary["incomplete_units"] = len(incomplete)
    if blocked:
        summary["blocked"] = blocked
    if lay is not None:
        summary["layout"] = {"manifest": str(meta / "manifest.jsonl"), **lay}
    if hub or rev:
        summary["revision"] = rev
    if local is not None:
        summary["local_reuse"] = dict(local.counts)
        print(local.summary(), file=sys.stderr)
    chosen = {"format": SELECTION_FORMAT, "dataset": args.repo, "revision": rev, "filters": selection_filters(args),
              "sources": sorted(names), "sample": args.sample}
    chosen_bytes = (json.dumps(chosen, ensure_ascii=False, indent=1) + "\n").encode("utf-8")
    if args.inbox:
        summary["inbox"] = to_inbox(chosen_bytes, args.inbox)
    run = {"repo": None if args.data else args.repo, "data": args.data, "revision": rev, "run_id": run_id,
           "fetch_args": list(sys.argv[1:] if argv is None else argv), "counts": counts, "selection": selection,
           "date": utc_today(), "summary": summary}
    (meta / RUN_FILE).write_text(json.dumps(run, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")
    if not args.inbox:
        (meta / SELECTION_JSON).write_bytes(chosen_bytes)
    if args.json or not sys.stdout.isatty():
        print(json.dumps(summary, sort_keys=True))
    else:
        print(summary_words(counts, fetched_bytes, out, meta, run_id, file_kinds))
    return 0 if not (counts.get("failed") or counts.get("unsafe_path")) else 1


def to_inbox(data: bytes, dest: str) -> str:
    """#2337: the run's selection file (data) written by rclone rcat into the folder dest, an rclone path, as
    selection-<the first 16 hex digits of its sha256>.json (--inbox) -> the path written."""
    path = f"{dest.rstrip('/')}/selection-{hashlib.sha256(data).hexdigest()[:16]}.json"
    subprocess.run(["rclone", "rcat", path], input=data, check=True)
    return path


# how the summaries name the files of a unit and the files of a source (README.md, LICENSE)
FILE_WORDS = {"unit": "files of units", "source": "files of the sources themselves"}


def fetch_words(f: dict | None) -> str | None:
    """#1577: a source's fetch check (the catalog column fetch_check: level, rows, fetched, read_at; index_projection
    fetch_reading) in words; None when the catalog has none or no row of the source is read yet."""
    if not f or f.get("level") in (None, "not read") or not f.get("rows"):
        return None
    return (f"fetch check: {int(f['fetched'] or 0):,} of {_n(int(f['rows']), 'sampled row')} read fetched and matched "
            f"their record (read {f.get('read_at') or 'on an unknown day'})")


def fetch_note(cat: dict, sources, since: str | None) -> str | None:
    """#1577: the line a run prints before fetching when some of the selected sources (sources, [(name,)]) have a fetch
    check (catalog column fetch_check) with level none or some read on the day since or later (#2144: the day of the
    release read, release_day; None: no reading counts, as for a run that reads no release tag): each such source
    with its reading, the sources whose upstream serves none of the rows read first; None when there is none. An older
    reading says nothing of what the upstream serves for this release (release-2026-11-09.2 named two sources from
    readings five days old, whose files fetched)."""
    named = []
    for (s,) in sources:
        f = (cat.get(str(s)) or {}).get("fetch") or {}
        if since and str(f.get("read_at") or "") >= since and f.get("level") in ("none", "some"):
            named.append((f["level"] != "none", str(s), fetch_words(f)))
    if not named:
        return None
    return ("upstream may not serve the files now (rows whose bytes do not match fail their check): "
            + "; ".join(f"{s}: {w}" for _, s, w in sorted(named)))


def release_day(revision: str | None) -> str | None:
    """#2144: the day of the release a run reads, from its tag (RELEASE_TAG_RE): revision (--revision) when it is a
    release tag, else RELEASE, the tag of the release this copy was published in; None when neither is one."""
    for tag in (revision, RELEASE):
        m = RELEASE_TAG_RE.fullmatch(str(tag or ""))
        if m:
            return m.group(1)
    return None


# #1525, #2144: what a run takes of each source (taken_sources), the lines it prints before its first download
# (source_lines)
TAKEN_KEYS = ("units", "unit_files", "source_files", "bytes", "unsized_files")


def taken_sources(con) -> dict:
    """#1525, #2144: {source: TAKEN_KEYS} of what the run takes, by DuckDB over fetch_take and fetch_rows (take_steps):
    the units taken from the source, their files, the source's own files (README.md, LICENSE: its companion files) and
    the size their rows record (the files whose rows record none counted apart)."""
    return {str(s): dict(zip(TAKEN_KEYS, (int(x) for x in v))) for s, *v in con.execute(
        "SELECT r.source, coalesce(any_value(t.units), 0), count(*) FILTER (WHERE NOT r.fetch_source_file), "
        "count(*) FILTER (WHERE r.fetch_source_file), coalesce(sum(r.size_bytes), 0), "
        "count(*) FILTER (WHERE r.size_bytes IS NULL) FROM fetch_rows r LEFT JOIN "
        "(SELECT source, count(*) AS units FROM fetch_take GROUP BY source) t ON t.source = r.source "
        "GROUP BY r.source ORDER BY r.source").fetchall()}


def source_lines(taken: dict) -> list:
    """#1525, #2144: the lines a run prints before its first download, one per source of what it takes (taken_sources),
    in the words of the line that starts the fetch with the total: its units, their files with the source's own files
    (README.md, LICENSE) among them, and the size their rows record."""
    from tqdm import tqdm

    return [f"from {s}: {_n(v['units'], 'unit')}: {_n(v['unit_files'] + v['source_files'], 'file')}"
            + (f" ({_n(v['source_files'], 'file')} of the source itself among them)" if v["source_files"] else "")
            + f", {tqdm.format_sizeof(v['bytes'], 'B')}"
            + (f" (and {_n(v['unsized_files'], 'file')} of unknown size)" if v["unsized_files"] else "")
            for s, v in taken.items()]


def not_ok_query(manifest: Path, run_id: str) -> str:
    """The DuckDB query that lists the lines of one run of the manifest whose status is not ok (each line is read as
    one JSON object, so lines of different fields do not conflict)."""
    return (f"SELECT json FROM read_json_objects({sql_str(manifest.as_posix())}) "
            f"WHERE json_extract_string(json, 'run_id') = {sql_str(run_id)} "
            f"AND json_extract_string(json, 'status') <> 'ok'")


def summary_words(counts: dict, fetched_bytes: int, out: Path, meta: Path, run_id: str,
                  kinds: dict | None = None) -> str:
    """The summary on a terminal: one line with the files fetched and checked, their total size, where they are and
    where the details are; a line with the files of units and of the sources themselves by status; a line with the
    run_id and its counts by status; and, when a fetched line is not ok, the DuckDB query that lists those lines."""
    from tqdm import tqdm

    head = (f"{_n(counts.get('ok', 0), 'file')} fetched and checked ({tqdm.format_sizeof(fetched_bytes, 'B')}) "
            f"into {out}")
    lines = [f"{head}; details in {meta / RUN_FILE}"]
    if kinds:
        lines.append("; ".join(
            f"{FILE_WORDS.get(k, k)}: " + ", ".join(f"{v:,} {s}" for s, v in sorted(kinds[k].items()))
            for k in FILE_WORDS if k in kinds))
    lines.append(f"run_id {run_id}: " + (", ".join(f"{v:,} {k}" for k, v in sorted(counts.items())) or "no line")
                 + f" (lines in {meta / MANIFEST})")
    if any(k != "ok" for k in counts):
        lines.append(f"its lines that are not ok, in DuckDB: {not_ok_query(meta / MANIFEST, run_id)}")
    return "\n".join(lines)


def cli(argv=None) -> int:
    """main with the errors a user can fix printed as one message (exit code 2) instead of a traceback."""
    try:
        return main(argv)
    except (IndexReadError, UnknownName) as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    except KeyboardInterrupt:
        print("stopped; the manifest keeps the rows finished so far, run again to resume", file=sys.stderr)
        return 130

if __name__ == "__main__":
    sys.exit(cli())