File size: 222,047 Bytes
c4f91a4
196f3aa
ec5da4b
 
196f3aa
c4f91a4
 
196f3aa
 
 
 
 
ec5da4b
196f3aa
 
 
 
 
 
 
 
 
 
 
bbc317b
 
eb1f478
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
196f3aa
 
eb1f478
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
196f3aa
 
 
c4f91a4
196f3aa
c4f91a4
 
196f3aa
f3d92a2
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f3d92a2
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
ec5da4b
 
196f3aa
 
 
 
 
bbc317b
 
196f3aa
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc317b
 
f6053c3
 
 
 
 
 
 
196f3aa
eb1f478
 
 
 
c17887c
c4f91a4
 
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
 
 
 
 
 
 
ec5da4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
 
 
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
bbc317b
 
196f3aa
 
c4f91a4
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc317b
 
c4f91a4
 
 
 
 
 
bbc317b
 
 
 
f6053c3
 
 
 
 
 
bbc317b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6053c3
bbc317b
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
eb1f478
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
bbc317b
 
 
 
 
c4f91a4
bbc317b
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
 
 
eb1f478
bbc317b
 
 
eb1f478
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc317b
 
196f3aa
bbc317b
eb1f478
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
bbc317b
 
 
 
 
c4f91a4
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
bbc317b
 
196f3aa
bbc317b
196f3aa
bbc317b
196f3aa
 
 
bbc317b
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bbc317b
196f3aa
 
bbc317b
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
 
 
bbc317b
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
bbc317b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
bbc317b
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
eb1f478
196f3aa
 
 
 
eb1f478
 
 
 
196f3aa
 
 
 
 
 
 
 
eb1f478
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
eb1f478
196f3aa
 
 
 
 
 
bbc317b
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
 
 
ec5da4b
 
 
 
 
196f3aa
 
ec5da4b
c4f91a4
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
196f3aa
 
 
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
ec5da4b
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
c4f91a4
 
196f3aa
 
 
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
196f3aa
 
 
c4f91a4
 
196f3aa
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
196f3aa
c4f91a4
196f3aa
c4f91a4
 
196f3aa
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
c4f91a4
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
196f3aa
c4f91a4
196f3aa
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
196f3aa
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
196f3aa
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
c4f91a4
 
 
196f3aa
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17887c
196f3aa
c17887c
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
 
 
 
c4f91a4
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
 
 
196f3aa
 
 
c4f91a4
196f3aa
c4f91a4
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
c4f91a4
196f3aa
 
c4f91a4
 
 
196f3aa
c4f91a4
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
 
eb1f478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
c4f91a4
 
 
eb1f478
 
c4f91a4
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
f3d92a2
 
 
c4f91a4
 
 
 
196f3aa
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
eb1f478
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
eb1f478
 
 
196f3aa
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
c4f91a4
 
196f3aa
 
 
 
 
 
 
 
 
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
f3d92a2
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
c4f91a4
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
 
 
196f3aa
eb1f478
 
 
 
196f3aa
 
 
 
 
eb1f478
196f3aa
 
 
 
eb1f478
 
196f3aa
 
 
eb1f478
 
196f3aa
 
 
eb1f478
 
 
196f3aa
 
 
 
 
eb1f478
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ec5da4b
196f3aa
c4f91a4
196f3aa
ec5da4b
 
 
c4f91a4
196f3aa
eb1f478
 
196f3aa
 
 
bbc317b
196f3aa
 
 
c4f91a4
196f3aa
 
bbc317b
196f3aa
 
 
c4f91a4
196f3aa
 
 
ec5da4b
196f3aa
 
 
 
 
ec5da4b
196f3aa
 
 
 
 
 
 
eb1f478
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
c4f91a4
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb1f478
196f3aa
 
 
 
 
 
 
 
 
 
 
 
eb1f478
 
196f3aa
eb1f478
 
196f3aa
 
 
 
 
eb1f478
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c4f91a4
 
 
eb1f478
c4f91a4
 
eb1f478
c4f91a4
ec5da4b
eb1f478
 
c4f91a4
 
 
 
 
 
 
 
 
 
 
 
 
196f3aa
 
 
 
 
 
 
 
 
 
 
eb1f478
196f3aa
c4f91a4
 
 
 
196f3aa
 
 
 
 
c4f91a4
196f3aa
c4f91a4
196f3aa
 
 
 
c4f91a4
 
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
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.10"
# dependencies = ["duckdb>=1.1", "zstandard", "huggingface_hub>=2.0"]
# ///
"""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):

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

or, with Python 3.10 or newer: pip install duckdb huggingface_hub, 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, --domain, --form or --tag) from meta/catalog.parquet, then reads only those sources'
data files 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 and how
many each criterion of the profile removed; a selection that ends empty says which criterion emptied it. A
source, 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; --all turns all of them off, each has its own option):
  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 one row, or, for a collection whose rows carry roles (unit, companion, answer), the rows that share a
unit_group: a unit is removed when any of its unit or answer rows fails a criterion, and its answers go with it.
Companion files (README, LICENSE) of a source come with the first unit taken from it. Each criterion is reported
with its own count and reason (benchmark and not compared apart) and names the option that keeps what it removed.

Output (--out DIR):
  DIR/<domain>/<source>/<path>     units and companion files; <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); <path> is the row's pool_path, else
                                   <collection>/<the rest of its pointer_id>
  DIR/answer/<source>/<path>       answers and expected results (pool_path without its leading answer/)
  DIR/_meta/manifest.jsonl         one line per file on disk: source, path (relative to DIR), url, sha256, bytes,
                                   spdx, licence_url, publisher, retrieved, answer (for a unit: the path of its
                                   answer, a list when it has several), origin_kind, leaf, role (unit, companion or
                                   answer), unit_group, answer_for, 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 (appended, never rewritten);
                                   a --dry-run writes one line per file of the selection (see below)
  DIR/_meta/fetch_run.json         repository, commit, arguments and date of the last run
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, under the unit's path; 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 (the first N in a fixed order of their
sha256 keys), so a category can be tried within a few MB. --limit N takes N units over the whole selection, in
the same fixed order.

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, role, unit_group, answer_for, 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-with-answers --sample 3 --out ./data
    python fetch.py --source apache-arrow-testing --dry-run
    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 --dry-run
    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 --dry-run
    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).

--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.

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 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 and the summary (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, the duckdb package and the huggingface_hub package (pip install duckdb
huggingface_hub; huggingface_hub resolves the index commit and the hf:// addresses). Downloads use only the
standard library (plus sevenzip.py for 7z members, which is taken from next to this script or else from the
index repository at the commit read, and the zstandard package for --decompress of .zst).

What is read: meta/catalog.parquet (one row per source) first; then, for the sources it resolves, their data files
(data/<source>/*/*.parquet, or with --tag only the batches that carry the tags) 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.

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: it is
decompressed, the WARC and HTTP headers are removed and the payload hash is checked); members of zip
archives (the local header and the compressed bytes are read with Range requests, then inflated and checked
against size and CRC32); API responses (the body field is taken from the JSON response). Members of packages:
wheels, jars and other zip files through their central directory (Range requests); 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 with sevenzip.py next to this script (a solid block is
decoded from its start up to the member, within the cap). 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, one request per second and a full
minute of waiting after HTTP 429; 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, after every other criterion
(DuckDB window functions over the rows the others keep, so the copy kept is one you get). Of rows that share a
natural key (source, uri, range_offset, member_path) 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 and
part-tail.parquet holds the newest rows; a row corrected later is written into a new part file while its old
version stays), and its manifest line says natural_key_conflict; 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). The script
signs those requests itself (AWS Signature Version 4) and 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 with no fonts (pdffonts) whose
first five pages hold fewer than 20 characters of text per page (pdftotext), 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 a system tool it needs (file, pdffonts,
pdftotext from poppler-utils) 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.

A download whose size or hash does not match its row (a connection cut off mid-transfer can end early without
an error) is tried again, by default 2 more times (--verify-retries) after waiting 2 and then 4 seconds; network
errors that are likely to pass have their own retries. When a download had to be tried again, its manifest
line says how many times it was downloaded (attempts) and why each earlier try was refused (attempt_reasons).

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 headers all stop at the cap.
AWS signatures are sent only to S3 hosts, and any redirect to another host drops the Authorization and
x-amz-* headers.

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). 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).

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:// proxies need the PySocks package (pip install 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). --contact TEXT adds your contact (an email or URL) to the User-Agent, as some APIs ask.
API sources get at least one second between requests to the same host (more for hosts that ask for it).
One progress line per row is printed on stderr (--quiet turns them off).

The manifest status is one of ok, failed, too_large, skipped, unsafe_path, unsupported. A --dry-run downloads
nothing and writes one line for every file of the selection, as many as the files the summary counts
(selection.files: the files of every unit and the companion files): status selected for a file that would be
fetched, removed for a file of a unit (or a companion file) that a criterion of the profile removes (removed_by
names the criterion, reason says why, kept_with the option that keeps it), and not_taken for a unit left out by
--sample or --limit or a companion file of a source none of whose units is taken. 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 datetime
import gzip
import hashlib
import hmac
import http.client
import io
import json
import os
import posixpath
import re
import shutil
import socket
import struct
import subprocess
import sys
import tarfile
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
import zlib
from pathlib import Path

DEFAULT_REPO = "Battam/agentic-env-index"
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"
# 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
# a download whose size or hash does not match its row is tried this many more times (a connection that is cut
# off can end the body early without an error)
VERIFY_RETRIES = 2
MISMATCH = re.compile(r"(?:\b(?:size|sha256|sha1|sha512|md5|git_blob_sha1|crc32|CRC32)|etag \(single-part md5\)) "
                      r"differs|does not match the size and CRC32|gzip member is incomplete")
# 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
# 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
ZIP_LOCAL_SIG = b"PK\x03\x04"
ZIP_LOCAL_LEN = 30
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"
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", "role",
                 "unit_group", "answer_for", "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 rows_from(files: str) -> str:
    """SELECT over the row tables that adds where each row sits: row_file (the last three parts of the file path,
    <source>/<batch>/<part file>) 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 ("SELECT * EXCLUDE (filename, file_row_number), "
            "regexp_extract(replace(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, part-tail.parquet holds the newest rows; a corrected row is
#                written into a new part file and its old version stays), then the last row of the file (that row
#                has natural_key_conflict true)
#   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;
# --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")
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 role_sql() -> str:
    """The row's role in its collection (source_meta.role): unit, companion or answer; unit for a row without one."""
    return f"coalesce({source_meta_sql(chr(39) + 'role' + chr(39))}, 'unit')"


def unit_sql() -> str:
    """The unit a row belongs to: source_meta.unit_group (shared by a unit's files and its answers), else the row
    itself (row_file#row_index); NULL for a companion file, which belongs to its source."""
    ug = source_meta_sql(chr(39) + "unit_group" + chr(39))
    return (f"(CASE WHEN {role_sql()} = 'companion' THEN NULL "
            f"ELSE coalesce({ug}, p.row_file || '#' || CAST(p.row_index AS VARCHAR)) END)")


def unit_key_sql() -> str:
    """The fixed order of units (--sample, --limit): 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)"


def catalog_columns(domains=(), forms=()) -> list:
    """The columns of meta/catalog.parquet that a selection by domains and forms reads."""
    return ["source"] + (["domain"] if domains else []) + (["form"] if forms else [])


def catalog_view_sql(root: str, domains=(), forms=()) -> str:
    """The SELECT of view s: the catalog columns that domains and forms need, one row per source."""
    return (f"SELECT {', '.join(catalog_columns(domains, forms))} "
            f"FROM read_parquet({sql_str(root + '/' + CATALOG)})")


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=()) -> str:
    """The sources of view s that match: any domain entry matches one of domains (when given) and the form is one
    of forms (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)})")
    return "SELECT DISTINCT s.source FROM s WHERE " + " AND ".join(conds)


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


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=(), exts=(), sources=(), tiers=None, min_size=None, max_size=None, where=None,
                max_size_filter=None, domains=(), forms=()) -> list:
    """Your own WHERE conditions of the selection (the default profile is apart: profile_conditions and cand_steps).
    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 and
    forms keep the rows of the sources that match them in meta/catalog.parquet (view s, catalog_condition)."""
    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 exts:
        conds.append(f"lower(p.ext) IN ({', '.join(sql_str(e.lower().lstrip('.')) for e in exts)})")
    if sources:
        conds.append(f"p.source IN ({', '.join(sql_str(s) for s in sources)})")
    if domains or forms:
        conds.append(catalog_condition(domains, forms))
    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 _data_files(root: str, sources=()) -> str:
    if sources:
        return "[" + ", ".join(sql_str(f"{root}/data/{s}/*/*.parquet") for s in sources) + "]"
    return sql_str(f"{root}/data/*/*/*.parquet")


def _batch_files(root: str, batches) -> str:
    return "[" + ", ".join(sql_str(f"{root}/data/{s}/{b}/*.parquet") for s, b in batches) + "]"


def views_sql(root: str, *, sources=(), batches=None, domains=(), forms=()) -> list:
    """The views p (rows), b, o, t, c, and s (meta/catalog.parquet: source, domain, form, pii_level, spdx, files),
    as --print-sql shows them (a run reads the same tables filtered to its sources, table_steps). batches:
    (source, batch) pairs (tag_batches); when given, p reads only the data files 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."""
    rows = rows_from(_batch_files(root, batches) if batches else _data_files(root, sources))
    keep = ""
    if batches:
        keep = f" WHERE source IN ({', '.join(sql_str(s) for s in sorted({s for s, _ in batches}))})"
    out = [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 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).
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, 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
    (NULL where this revision of the catalog has no such column). -> {column: present}."""
    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(expr, name, typ, ok):
        return f"{expr} AS {name}" if ok else f"CAST(NULL AS {typ}) AS {name}"

    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)]
    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")}


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=(), 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. 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)}")


def resolve_sources(con, root: str, *, domains=(), forms=(), sources=()) -> list:
    """The sources of table s that match domains and forms (catalog_select_sql), limited to sources when given;
    every source when none of the three is given. Sorted. For a local copy, sources without data files are left
    out."""
    if domains or forms:
        sql = catalog_select_sql(domains, forms)
        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())
    if not is_remote(root):
        found = [s for s in found if any(Path(root, "data", s).glob("*/*.parquet"))]
    return found


def table_steps(root: str, sources, *, 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. batches:
    (source, batch) pairs (tag_batches); when given, p reads only their data files. 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}"

    files = _batch_files(root, batches) if batches else _data_files(root, () if everything else names)
    out = {"p": f"CREATE OR REPLACE {'TABLE' if local_rows else 'VIEW'} p0 AS {rows_from(files)}",
           "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) -> 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."""
    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 = {}
    with cf.ThreadPoolExecutor(max(1, min(READ_JOBS, len(jobs)))) as ex:
        futs = {name: ex.submit(one, job) for name, job in jobs.items()}
        for name, f in futs.items():
            out[name] = f.result()
    return out


def catalog_sources(con, root: str, domains=(), forms=(), sources=()) -> list:
    """The sources of meta/catalog.parquet that match domains and forms (catalog_select_sql; only the columns
    needed are read), limited to sources when given, sorted. For a local copy, sources without data files are
    left out. Raises IndexReadError when the catalog has no column that domains or forms need."""
    path = sql_str(root + "/" + CATALOG)
    have = {str(r[0]) for r in con.execute(f"DESCRIBE SELECT * FROM read_parquet({path})").fetchall()}
    missing = [c for c in catalog_columns(domains, forms) if c not in have]
    if missing:
        raise IndexReadError(
            f"{CATALOG} at {root} has no {'column' if len(missing) == 1 else 'columns'} {', '.join(missing)}: this "
            f"revision of the index is older than the columns domain and form, so --domain and --form cannot be "
            f"used with it; read a newer revision (a later --revision, or none for the current one)")
    sql = f"WITH s AS ({catalog_view_sql(root, domains, forms)}) {catalog_select_sql(domains, forms)}"
    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)
    if not is_remote(root):
        found = [s for s in found if any(Path(root, "data", s).glob("*/*.parquet"))]
    return found


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. For a local copy, pairs without data files 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()]
    if not is_remote(root):
        pairs = [(s, b) for s, b in pairs if any(Path(root, "data", s, b).glob("*.parquet"))]
    return pairs


def cand_steps(conds: list, profile: list, max_size: int | None = None, size_cap: int | None = None) -> list:
    """The first part of the selection: table fetch_cand, one line per row that passes conds (your own conditions)
    with where it sits, its unit (unit_sql, NULL for a companion), its role, the unit's order key (unit_key_sql), its
    caps, 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.
    size_cap (the profile's 20 MB) lowers the cap of a row whose batch cap is larger; max_size replaces both.
    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 companion
    file, the row itself) fails none of them, so the copy kept is one the reader gets; a row it removes fails the
    duplicate criterion. natural_key_conflict is true only for a row whose natural key the duplicate criterion
    removed from other rows."""
    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]
    dedup = len(rows) < len(profile)
    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)")
    base = ("row_file", "row_index", "source", "role", "unit", "unit_key", "fetch_key", "size_cap_bytes",
            "batch_cap_bytes")
    head = (f"SELECT p.row_file, p.row_index, p.source, {role_sql()} AS role, {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 dedup:
        head += ", " + ", ".join([f"p.{c}" for c in DUP_ROW_COLS if c not in base] + dup_inputs_sql())
    else:
        head += ", false AS natural_key_conflict"
    cand = (f"CREATE OR REPLACE TEMP TABLE {'fetch_cand0' if dedup else 'fetch_cand'} AS {head} "
            "FROM p JOIN b ON b.source = p.source AND b.batch = p.batch")
    if conds:
        cand += "\nWHERE " + "\n  AND ".join(conds)
    out = [cand]
    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(base)
        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"UNION ALL SELECT {cols}, false, fail FROM fetch_cand0 c WHERE NOT ({keep})",
                "DROP TABLE fetch_cand0"]
    out.append("CREATE OR REPLACE TEMP TABLE fetch_units AS SELECT source, unit, min(unit_key) AS unit_key, "
               "min(fail) AS fail, count(*) AS files FROM fetch_cand WHERE unit IS NOT NULL GROUP BY source, unit")
    return out

def take_steps(limit: int | None = None, sample: int | None = None, every: bool = False) -> list:
    """The second part: fetch_take, the units kept (every row passes), at most sample per source and limit in all,
    the first ones in unit_key order; fetch_pick, their rows and the companion files (that pass) of the sources
    they come from; fetch_rows, those rows whole. Then the narrow tables are dropped. 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). every (a dry run): fetch_pick
    and fetch_rows hold every row of fetch_cand, with dry_fate (selected: it would be fetched; removed: its unit,
    or the companion file itself, fails a criterion of the profile; not_taken: left out by sample or limit, or a
    companion file of a source none of whose units is taken) and dry_fail (the criterion's number in CRITERIA)."""
    inner = "SELECT source, unit, unit_key FROM fetch_units WHERE fail IS NULL"
    if sample is not None:
        inner = (f"SELECT source, unit, unit_key FROM (SELECT source, unit, unit_key, row_number() OVER "
                 f"(PARTITION BY source ORDER BY unit_key, unit) AS n FROM fetch_units WHERE fail IS NULL) "
                 f"WHERE n <= {int(sample)}")
    take = f"CREATE OR REPLACE TEMP TABLE fetch_take AS {inner}"
    if limit is not None:
        take += f" ORDER BY unit_key, source, unit LIMIT {int(limit)}"
    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))")
    if every:
        pick = ("CREATE OR REPLACE TEMP TABLE fetch_pick AS SELECT c.row_file, c.row_index, "
                "coalesce(k.unit_key, u.unit_key, c.fetch_key) AS fetch_key, c.size_cap_bytes, c.batch_cap_bytes, "
                f"c.natural_key_conflict, c.role, c.unit, CASE WHEN {picked} THEN 'selected' "
                "WHEN coalesce(u.fail, c.fail) IS NOT NULL THEN 'removed' ELSE 'not_taken' END AS dry_fate, "
                "CASE WHEN c.unit IS NULL THEN c.fail ELSE u.fail END AS dry_fail "
                "FROM fetch_cand c LEFT JOIN fetch_take k ON k.source = c.source AND k.unit = c.unit "
                "LEFT JOIN fetch_units u ON u.source = c.source AND u.unit = c.unit")
        rows = ("CREATE OR REPLACE TEMP TABLE fetch_rows AS SELECT p.*, k.fetch_key, k.size_cap_bytes, "
                "k.batch_cap_bytes, k.natural_key_conflict, k.dry_fate, k.dry_fail FROM p JOIN fetch_pick k "
                "ON k.row_file = p.row_file AND k.row_index = p.row_index")
        return [take, pick, rows, "DROP TABLE fetch_pick"]
    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.role, c.unit FROM fetch_cand c LEFT JOIN fetch_take k ON k.source = c.source "
            f"AND k.unit = c.unit WHERE {picked}")
    rows = ("CREATE OR REPLACE TEMP TABLE fetch_rows AS SELECT p.*, k.fetch_key, 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 [take, pick, rows, "DROP TABLE fetch_pick"]


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 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."""
    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) 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/"


REF_RE = re.compile(r"[A-Za-z0-9][A-Za-z0-9._-]{0,127}")


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:
        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 _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}"


SECRET_HEADERS = re.compile(r"^(authorization|x-amz-.*)$", re.I)


class SafeRedirect(urllib.request.HTTPRedirectHandler):
    """Follow redirects, but a redirect to another host or port (or from https to http) drops Authorization and
    every x-amz-* header: a signed request must not hand its signature or session token to a third host."""

    def redirect_request(self, req, fp, code, msg, headers, newurl):
        new = super().redirect_request(req, fp, code, msg, headers, newurl)
        if new is None:
            return None
        a, b = urllib.parse.urlsplit(req.full_url), urllib.parse.urlsplit(new.full_url)
        if (a.hostname or "").lower() != (b.hostname or "").lower() or a.port != b.port \
                or (a.scheme == "https" and b.scheme != "https"):
            for store in (new.headers, new.unredirected_hdrs):
                for k in [k for k in store if SECRET_HEADERS.match(k)]:
                    del store[k]
        return new


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


def _socks_handlers(proxy: str) -> list:
    """urllib handlers that connect through a SOCKS proxy (socks5h:// and socks4a:// let the proxy resolve host
    names). Needs the optional PySocks package; the standard library has no SOCKS client."""
    try:
        import socks  # PySocks, optional
    except ImportError:
        raise SystemExit(f"error: {redact_proxy(proxy)} is a SOCKS proxy and Python's standard library cannot use "
                         "SOCKS. Install the optional PySocks package (pip install pysocks), or use an HTTP proxy "
                         "(http://host:port).") from None
    import ssl
    u = urllib.parse.urlsplit(proxy)
    scheme = u.scheme.lower()
    kind = socks.SOCKS5 if scheme.startswith("socks5") else socks.SOCKS4
    rdns = scheme in ("socks5h", "socks4a")
    user = urllib.parse.unquote(u.username) if u.username else None
    pw = urllib.parse.unquote(u.password) if u.password else None

    def connect(host, port, timeout):
        return socks.create_connection((host, port), timeout=timeout, proxy_type=kind, proxy_addr=u.hostname,
                                       proxy_port=u.port or 1080, proxy_rdns=rdns, proxy_username=user,
                                       proxy_password=pw)

    class Conn(http.client.HTTPConnection):
        def connect(self):
            self.sock = connect(self.host, self.port, self.timeout)

    class SConn(http.client.HTTPSConnection):
        def connect(self):
            self.sock = self._context.wrap_socket(connect(self.host, self.port, self.timeout),
                                                  server_hostname=self.host)

    class H(urllib.request.HTTPHandler):
        def http_open(self, req):
            return self.do_open(Conn, req)

    class HS(urllib.request.HTTPSHandler):
        def https_open(self, req):
            return self.do_open(SConn, req, context=ssl.create_default_context())

    return [H(), HS()]


def make_url_opener(proxy=None):
    """The urllib opener every download uses: SafeRedirect, plus proxy (an http://, https://, socks5://,
    socks5h://, socks4:// or socks4a:// address) when given. proxy None means a direct connection."""
    handlers = [SafeRedirect()]
    if proxy:
        scheme = urllib.parse.urlsplit(proxy).scheme.lower()
        if scheme not in PROXY_SCHEMES:
            raise SystemExit(f"error: unsupported proxy {redact_proxy(proxy)}; use one of "
                             + ", ".join(s + "://" for s in PROXY_SCHEMES))
        if scheme.startswith("socks"):
            handlers += [urllib.request.ProxyHandler({})] + _socks_handlers(proxy)
        else:
            handlers.append(urllib.request.ProxyHandler({"http": proxy, "https": proxy}))
    else:
        handlers.append(urllib.request.ProxyHandler({}))
    return urllib.request.build_opener(*handlers)


_NET = {"opener": None, "ua": None, "proxy": None}


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) -> None:
    """Configure the proxy and the User-Agent (with the --contact address) that open_url uses."""
    _NET.update(opener=make_url_opener(proxy), ua=user_agent(contact), proxy=proxy)


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 (the signed headers of a requester-pays request). Only http(s)
    addresses are opened; a local --data copy is read through local_file_opener, never through an address."""
    if not url.startswith(("https://", "http://")):
        raise Unsupported(f"only http(s) addresses are fetched, not {url.split(':', 1)[0][:20]}://")
    if _NET["opener"] is None:
        set_network(env_proxy())
    headers = {"User-Agent": _NET["ua"] or UA, **(headers or {})}
    if rng:
        headers["Range"] = range_header(rng)
    r = _NET["opener"].open(urllib.request.Request(url, headers=headers), timeout=timeout)  # noqa: S310
    if rng and getattr(r, "status", 206) != 206:
        r.close()
        raise Unsupported(f"the server ignored the Range request (HTTP {getattr(r, 'status', '?')})")
    return r


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, urllib.error.HTTPError):
        return 500 <= e.code < 600
    if isinstance(e, urllib.error.URLError):
        r = e.reason
        return isinstance(r, (ConnectionError, TimeoutError, socket.timeout)) or (
            isinstance(r, str) and "timed out" in r)
    return isinstance(e, (ConnectionError, TimeoutError, socket.timeout, http.client.IncompleteRead))


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


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)
    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 "")
            if status == 206 and not crange.startswith(f"bytes {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"
        with src, open(part, mode) as out:
            while True:
                b = src.read(CHUNK)
                if not b:
                    break
                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)
    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 _split_head(block: bytes) -> tuple:
    a, b = block.find(b"\r\n\r\n"), block.find(b"\n\n")
    if a < 0 and b < 0:
        return block, b""
    if b < 0 or (0 <= a < b):
        return block[:a], block[a + 4:]
    return block[:b], block[b + 2:]


def _headers(text: bytes) -> dict:
    out = {}
    for line in text.decode("latin-1").splitlines()[1:]:
        k, sep, v = line.partition(":")
        if sep:
            out[k.strip().lower()] = v.strip()
    return out


def gunzip_bounded(raw: bytes, limit: int) -> bytes:
    """Decompress gzip data (one or more members) without ever holding more than limit + 1 output bytes; more
    output than limit raises TooLarge (a small compressed input can expand without bound)."""
    out, n, rest = [], 0, raw
    while rest:
        d = zlib.decompressobj(16 + zlib.MAX_WBITS)
        piece = d.decompress(rest, limit + 1 - n)
        n += len(piece)
        if n > limit or d.unconsumed_tail:
            raise TooLarge(f"the data decompresses to more than the cap of {limit} bytes")
        out.append(piece)
        if not d.eof:
            raise ValueError("the gzip data is incomplete")
        rest = d.unused_data
    return b"".join(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:
    data = gunzip_bounded(raw, UNKNOWN_SIZE_CAP if limit is None else limit)
    if data.startswith(b"WARC/"):
        head, _, rest = data.partition(b"\r\n\r\n")
        wh = _headers(head)
        block = rest[:int(wh.get("content-length", len(rest)))]
    else:
        first, _, rest = data.partition(b"\n")
        block = rest[:int(first.split()[-1])]
    http_head, payload = _split_head(block) if block.startswith(b"HTTP/") else (b"", block)
    return {"http_headers": _headers(http_head) if http_head else {}, "payload": payload}


def dechunk(body: bytes) -> bytes:
    out, pos = bytearray(), 0
    while pos < len(body):
        eol = body.find(b"\r\n", pos)
        if eol < 0:
            break
        n = int(body[pos:eol].split(b";")[0].strip() or b"0", 16)
        if n == 0:
            break
        out += body[eol + 2:eol + 2 + n]
        pos = eol + 2 + n + 2
    return bytes(out)


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, ValueError) 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)


def _zip_member_bytes(url, timeout, opener, loff, method, csize, limit, read_cap=None):
    """The bytes of one zip member (read with Range requests from its local header), at most limit + 1 of them;
    None when the local header signature is wrong. A compressed size above read_cap raises TooLarge before
    anything is read."""
    if read_cap is not None and csize > read_cap:
        raise TooLarge(f"the compressed member has {csize} bytes, more than the cap of {read_cap} bytes")
    head = _get_range(url, timeout, loff, ZIP_LOCAL_LEN, opener)
    if head[:4] != ZIP_LOCAL_SIG:
        return None
    n, m = struct.unpack_from("<HH", head, 26)
    start = loff + ZIP_LOCAL_LEN + n + m
    raw = _get_range(url, timeout, start, csize, opener) if csize else b""
    if method == 0:
        return raw[:limit + 1]
    if method == 8:
        d = zlib.decompressobj(-15)
        data = d.decompress(raw, limit + 1)
        if len(data) <= limit and not d.unconsumed_tail:
            data += d.flush()
        return data
    raise Unsupported(f"zip compression method {method}")


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")
    limit = member_limit(row)
    data = _zip_member_bytes(url, timeout, opener, ze["local_header_offset"], ze["compression_method"],
                             ze["compressed_size"], limit, whole_cap_of(row))
    if data is None:
        return {"status": "failed", "url": url, "reason": "the zip local header signature is wrong"}
    _too_large_unknown(row, len(data), limit)
    h = Hasher(len(data))
    h.update(data)
    why = verify(row, len(data), h.digests())
    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": "zip_member",
                                "url": url},
                          h.digests()["sha256"], NO_HASH_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")
ZIP_EOCD_SIG = b"PK\x05\x06"
ZIP64_LOCATOR_SIG = b"PK\x06\x07"
ZIP64_EOCD_SIG = b"PK\x06\x06"
ZIP_CD_SIG = b"PK\x01\x02"
ZIP_TAIL = 22 + 0xFFFF  # end record plus the longest comment
ZIP_CD_MAX = 64_000_000
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 zip_central_directory(url, timeout, opener) -> bytes:
    """The central directory of a remote zip: the end record is found in the last 64 KB (one Range request),
    zip64 archives through their locator. Some servers (files.pythonhosted.org) answer 416 when the file is
    shorter than the suffix asked for; the whole file is then read instead, as it is under 64 KB."""
    try:
        with opener(url, timeout, (None, ZIP_TAIL)) as r:
            tail = r.read(ZIP_TAIL + 1)
    except urllib.error.HTTPError as e:
        if e.code != 416:
            raise
        with opener(url, timeout, None) as r:
            tail = r.read(ZIP_TAIL + 1)
        if len(tail) > ZIP_TAIL:
            raise Unsupported("the server refused the 64 KB tail range of a file longer than 64 KB") from None
    i = tail.rfind(ZIP_EOCD_SIG)
    if i < 0 or len(tail) - i < 22:
        raise Unsupported("no zip end record in the last 64 KB")
    n_entries, cd_size, cd_off = struct.unpack_from("<HII", tail, i + 10)
    if n_entries == 0xFFFF or 0xFFFFFFFF in (cd_size, cd_off):
        j = i - 20
        if j < 0 or tail[j:j + 4] != ZIP64_LOCATOR_SIG:
            raise Unsupported("zip64 archive without a zip64 locator")
        rec = _get_range(url, timeout, struct.unpack_from("<Q", tail, j + 8)[0], 56, opener)
        if rec[:4] != ZIP64_EOCD_SIG:
            raise Unsupported("the zip64 end record signature is wrong")
        cd_size, cd_off = struct.unpack_from("<QQ", rec, 40)
    if cd_size > ZIP_CD_MAX:
        raise Unsupported(f"the zip central directory has {cd_size} bytes, more than {ZIP_CD_MAX}")
    return _get_range(url, timeout, cd_off, cd_size, opener) if cd_size else b""


def zip_find(cd: bytes, name: str):
    """-> {local_header_offset, compression_method, compressed_size, size, crc32} of the entry called name, or
    None."""
    pos = 0
    while pos + 46 <= len(cd):
        if cd[pos:pos + 4] != ZIP_CD_SIG:
            raise Unsupported("the zip central directory is damaged")
        flags, method = struct.unpack_from("<HH", cd, pos + 8)
        crc, csize, usize = struct.unpack_from("<III", cd, pos + 16)
        nlen, xlen, clen = struct.unpack_from("<HHH", cd, pos + 28)
        loff = struct.unpack_from("<I", cd, pos + 42)[0]
        raw = cd[pos + 46:pos + 46 + nlen]
        extra = cd[pos + 46 + nlen:pos + 46 + nlen + xlen]
        pos += 46 + nlen + xlen + clen
        if raw.decode("utf-8" if flags & 0x800 else "cp437", "replace") != name:
            continue
        if 0xFFFFFFFF in (usize, csize, loff):
            k = 0
            while k + 4 <= len(extra):
                hid, hlen = struct.unpack_from("<HH", extra, k)
                if hid == 1:
                    vals = list(struct.unpack_from(f"<{hlen // 8}Q", extra, k + 4))
                    if usize == 0xFFFFFFFF and vals:
                        usize = vals.pop(0)
                    if csize == 0xFFFFFFFF and vals:
                        csize = vals.pop(0)
                    if loff == 0xFFFFFFFF and vals:
                        loff = vals.pop(0)
                    break
                k += 4 + hlen
        return {"local_header_offset": loff, "compression_method": method, "compressed_size": csize,
                "size": usize, "crc32": crc}
    return None


def fetch_zip_package(row, dest, url, timeout, opener):
    name = row.get("member_path")
    e = zip_find(zip_central_directory(url, timeout, opener), name)
    if e is None:
        return {"status": "failed", "url": url, "reason": f"{name} is not in the package's central directory"}
    limit = member_limit(row)
    _too_large_unknown(row, e["size"], limit)
    data = _zip_member_bytes(url, timeout, opener, e["local_header_offset"], e["compression_method"],
                             e["compressed_size"], max(limit, min(e["size"], whole_cap_of(row))),
                             whole_cap_of(row))
    if data is None:
        return {"status": "failed", "url": url, "reason": "the zip local header signature is wrong"}
    if len(data) != e["size"] or zlib.crc32(data) & 0xFFFFFFFF != e["crc32"]:
        return {"status": "failed", "url": url,
                "reason": "the member does not match the size and CRC32 of the package's central directory"}
    return _finish(row, dest, data, url, "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 (the directory is read with Range requests; see sevenzip.py next to this script)

SEVENZIP_PIECE = 8 << 20
# where sevenzip.py is fetched from when it is not next to this script (uv run of the script alone): the tools/ folder
# of the index repository at the commit the run reads (set by main); the copy goes into a temporary folder
_SEVENZIP = {"url": None, "dir": None}


def _sevenzip():
    try:
        from . import sevenzip
    except ImportError:
        try:
            import sevenzip
        except ImportError:
            return _sevenzip_from_repo()
    return sevenzip


def _sevenzip_from_repo():
    url = _SEVENZIP["url"]
    if not url:
        raise Unsupported("7z members need sevenzip.py next to this script") from None
    try:
        if _SEVENZIP["dir"] is None:
            d = tempfile.mkdtemp(prefix="fetch_sevenzip_")
            with open_url(url, 60) as r:
                Path(d, "sevenzip.py").write_bytes(read_bounded(r, 4 << 20, "sevenzip.py"))
            _SEVENZIP["dir"] = d
        if _SEVENZIP["dir"] not in sys.path:
            sys.path.insert(0, _SEVENZIP["dir"])
        import sevenzip
    except Exception as e:  # noqa: BLE001
        raise Unsupported(f"7z members need sevenzip.py; it is not next to this script and could not be read from "
                          f"{url}: {type(e).__name__}: {e}") from None
    return sevenzip


def _range_pieces(url, timeout, opener, start, length):
    end = start + length
    for off in range(start, end, SEVENZIP_PIECE):
        yield _get_range(url, timeout, off, min(SEVENZIP_PIECE, end - off), opener)


def fetch_sevenzip_member(row, dest, url, timeout, opener):
    sz = _sevenzip()
    name = row.get("member_path")

    def read(off, ln):
        return _get_range(url, timeout, off, ln, opener)

    whole = whole_cap_of(row)
    try:
        sig = sz.parse_signature_header(read(0, sz.SIGNATURE_HEADER_LEN))
        if sig.next_header_size > whole:
            raise TooLarge(f"the 7z directory has {sig.next_header_size} bytes, more than the cap of {whole} bytes")
        arc = sz.parse_header(sig, read(sig.header_pos, sig.next_header_size), read, limit=whole)
    except sz.TooLarge7z as e:
        raise TooLarge(f"7z: {e}") from None
    except sz.Unsupported7z as e:
        raise Unsupported(f"7z directory: {e}") from None
    except sz.Format7zError as e:
        return {"status": "failed", "url": url, "reason": f"cannot read the 7z directory: {e}"}
    e = next((x for x in arc.entries if x.name == name and not x.is_dir), None)
    if e is None:
        return {"status": "failed", "url": url, "reason": f"{name} is not in the 7z directory"}
    limit = member_limit(row)
    _too_large_unknown(row, e.size, limit)
    if e.folder is None or e.size == 0:
        return _finish(row, dest, b"", url, "sevenzip_member")
    folder = arc.folders[e.folder]
    pstart, plen = arc.folder_pack(e.folder)
    need = e.offset_in_folder + e.size
    if need > max(whole, e.size if row.get("size_bytes") is not None else 0):
        raise TooLarge(f"the member ends {need} bytes into a solid 7z block, more than the cap of {whole} bytes")
    try:
        if folder.methods == ["copy"]:
            data = read(pstart + e.offset_in_folder, e.size)
            if e.crc32 is not None and zlib.crc32(data) & 0xFFFFFFFF != e.crc32:
                raise sz.Format7zError(f"{name}: CRC32 differs")
        else:
            try:
                data = b"".join(sz.iter_entry(folder, e, _range_pieces(url, timeout, opener, pstart, plen)))
            except sz.Unsupported7z:
                if plen > whole or folder.unpack_size > whole:
                    raise TooLarge(f"the 7z block ({folder.unpack_size} bytes, coders {','.join(folder.methods)}) "
                                   f"must be decoded whole and is larger than the cap of {whole} bytes") from None
                data = sz.extract(arc, sz.decode_folder(folder, read(pstart, plen), limit=whole), e)
    except sz.TooLarge7z as x:
        raise TooLarge(f"7z block: {x}") from None
    except sz.Unsupported7z as x:
        raise Unsupported(f"7z block: {x}") from None
    except sz.Format7zError as x:
        return {"status": "failed", "url": url, "reason": f"7z member: {x}"}
    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)
    parts, n, rest = [], 0, raw
    while True:  # a gzip file may hold several members; each is decompressed in turn
        d = zlib.decompressobj(16 + zlib.MAX_WBITS)
        try:
            piece = d.decompress(rest, limit + 1 - n)
            if not d.unconsumed_tail:
                piece += d.flush()
        except zlib.error as e:
            return {"status": "failed", "url": url, "reason": f"cannot decompress the gzip member: {e}"}
        n += len(piece)
        if n > limit:
            raise TooLarge(f"the member decompresses to more than the cap of {limit} bytes")
        if not d.eof:
            return {"status": "failed", "url": url, "reason": "the gzip member is incomplete"}
        parts.append(piece)
        rest = d.unused_data
        if not rest:
            break
    last = parts[-1]  # the gzip trailer (CRC32, length modulo 2^32) covers the last member only
    want = row.get("payload_size_bytes")
    if want is not None and len(last) % (1 << 32) != int(want):
        return {"status": "failed", "url": url,
                "reason": f"decompressed size differs: expected {want} (modulo 2^32), got {len(last)}"}
    got = f"{zlib.crc32(last) & 0xFFFFFFFF:08x}"
    tail = f"{struct.unpack('<I', raw[-8:-4])[0]:08x}"
    want_crc = str((row.get("source_meta") or {}).get("crc32") or "").lower()
    if got != tail or (want_crc and got != want_crc):
        return {"status": "failed", "url": url,
                "reason": f"CRC32 differs: computed {got}, gzip trailer {tail}, pointer {want_crc or '-'}"}
    data = b"".join(parts)
    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"
EMPTY_SHA256 = hashlib.sha256(b"").hexdigest()


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


def _hmac(key: bytes, msg: str) -> bytes:
    return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest()


def sigv4_headers(method: str, url: str, headers: dict, access_key: str, secret_key: str, *,
                  region: str = AWS_REGION, service: str = "s3", now=None, payload_hash: str = EMPTY_SHA256) -> dict:
    """AWS Signature Version 4: -> the request headers plus host, x-amz-date, x-amz-content-sha256 and
    Authorization. Every header given is signed; the path is encoded once, as S3 expects."""
    u = urllib.parse.urlsplit(url)
    now = now or datetime.datetime.now(datetime.timezone.utc)
    amz_date = now.strftime("%Y%m%dT%H%M%SZ")
    day = amz_date[:8]
    h = {k.lower(): " ".join(str(v).split()) for k, v in headers.items()}
    h["host"] = u.netloc
    h["x-amz-date"] = amz_date
    h["x-amz-content-sha256"] = payload_hash
    names = sorted(h)
    q = urllib.parse.parse_qsl(u.query, keep_blank_values=True)
    enc = lambda s, keep: urllib.parse.quote(s, safe="/~" if keep else "~")  # noqa: E731
    canon_q = "&".join(f"{enc(k, False)}={enc(v, False)}" for k, v in sorted(q))
    canon = "\n".join([method, enc(urllib.parse.unquote(u.path or "/"), True), canon_q,
                       "".join(f"{n}:{h[n]}\n" for n in names), ";".join(names), payload_hash])
    scope = f"{day}/{region}/{service}/aws4_request"
    to_sign = "\n".join(["AWS4-HMAC-SHA256", amz_date, scope, hashlib.sha256(canon.encode("utf-8")).hexdigest()])
    k = _hmac(_hmac(_hmac(_hmac(("AWS4" + secret_key).encode("utf-8"), day), region), service), "aws4_request")
    sig = hmac.new(k, to_sign.encode("utf-8"), hashlib.sha256).hexdigest()
    out = {n: h[n] for n in names}
    out["authorization"] = (f"AWS4-HMAC-SHA256 Credential={access_key}/{scope}, "
                            f"SignedHeaders={';'.join(names)}, Signature={sig}")
    return out


S3_HOST_RE = re.compile(r"^(?:[a-z0-9.\-]+\.)?s3(?:[.\-][a-z0-9\-]+)?(?:\.dualstack\.[a-z0-9\-]+)?\.amazonaws\.com$")


def is_s3_host(url: str) -> bool:
    """True for an https address on an Amazon S3 host (s3.amazonaws.com, <bucket>.s3.amazonaws.com,
    s3.<region>.amazonaws.com, s3-<region>.amazonaws.com and the bucket forms of those)."""
    u = urllib.parse.urlsplit(url)
    return u.scheme == "https" and u.port in (None, 443) and bool(S3_HOST_RE.match((u.hostname or "").lower()))


def requester_pays_opener(opener, creds, region: str = AWS_REGION):
    """Wrap opener so that every request to an S3 host is signed and carries x-amz-request-payer: requester.
    Requests to any other host (an alternative address of the row) go out unsigned, with no credential header;
    a redirect to another host drops the signature too (SafeRedirect)."""
    ak, sk, token = creds

    def op(url, timeout, rng=None, headers=None):
        if not is_s3_host(url):
            clean = {k: v for k, v in (headers or {}).items() if not SECRET_HEADERS.match(k)}
            return opener(url, timeout, rng, headers=clean)
        h = {"x-amz-request-payer": "requester", **(headers or {})}
        if rng:
            h["range"] = range_header(rng)
        if token:
            h["x-amz-security-token"] = token
        return opener(url, timeout, rng, headers=sigv4_headers("GET", url, h, ak, sk, region=region))
    return op


# single lichess games (public export API, one request at a time)

LICHESS_BASE = "https://lichess.org"
LICHESS_GAP = 1.0  # seconds between two requests
LICHESS_WAIT_429 = 60.0  # lichess asks clients to wait a full minute after HTTP 429
LICHESS_429_TRIES = 2
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*)?$")
_LICHESS = {"last": None}


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, *, sleep=time.sleep):
    limit = member_limit(row)
    for attempt in range(LICHESS_429_TRIES + 1):
        last = _LICHESS["last"]
        if last is not None:
            wait = LICHESS_GAP - (time.monotonic() - last)
            if wait > 0:
                sleep(wait)
        try:
            with opener(url, timeout, None, headers={"Accept": "application/x-chess-pgn"}) as src:
                data = src.read(limit + 1)
        except urllib.error.HTTPError as e:
            if e.code == 429 and attempt < LICHESS_429_TRIES:
                sleep(LICHESS_WAIT_429)
                continue
            raise
        finally:
            _LICHESS["last"] = time.monotonic()
        break
    _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 mismatch(res: dict) -> bool:
    """True for a fetch result that failed because the size or a hash of the download did not match its row."""
    return res.get("status") == "failed" and bool(MISMATCH.search(str(res.get("reason") or "")))


API_MIN_INTERVAL = 1.0  # seconds between two API requests to one host (provisional: no source states a limit)
# provisional per-host intervals from the hosts' published limits: NVD allows 5 requests in 30 s without an API key
API_HOST_INTERVAL = {"services.nvd.nist.gov": 6.0}
_HOST_LAST: dict = {}
_clock = time.monotonic


def host_wait(url: str, sleep=time.sleep) -> None:
    """Wait until API_MIN_INTERVAL (or the host's API_HOST_INTERVAL) has passed since the last API request to the
    same host."""
    host = (urllib.parse.urlsplit(url).hostname or "").lower()
    gap = API_HOST_INTERVAL.get(host, API_MIN_INTERVAL)
    last = _HOST_LAST.get(host)
    if last is not None:
        left = gap - (_clock() - last)
        if left > 0:
            sleep(left)
    _HOST_LAST[host] = _clock()


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, retries: int = RETRIES,
               backoff: float | None = None, sleep=time.sleep, verify_retries: int = VERIFY_RETRIES,
               skip_present: bool = False, local: LocalFiles | None = None) -> dict:
    backoff = BACKOFF if backoff is None else backoff
    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)}"]
        fn = (lambda f: lambda *a: f(*a, sleep=sleep))(fn)
    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, aws_credentials(), (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, n_retry, refused = [], 0, []
    for url in urls:
        k = 0
        while True:
            try:
                if method == "api_body":
                    host_wait(url, sleep)
                res = fn(row, dest, url, timeout, opener)
            except TooLarge as e:
                return {**base, "status": "too_large", "method": method, "reason": str(e), "url": url,
                        **({"retries": n_retry} if n_retry else {}), **_attempts(refused)}
            except Unsupported as e:
                errors.append(f"{url}: {e}")
                break
            except Exception as e:  # noqa: BLE001 (network errors: retry the transient ones, then the next address)
                if transient(e) and k < retries:
                    n_retry += 1
                    sleep(backoff * 2 ** k)
                    k += 1
                    continue
                errors.append(f"{url}: {type(e).__name__}: {e}")
                break
            if mismatch(res) and len(refused) < verify_retries:
                refused.append(str(res["reason"]))
                sleep(backoff * 2 ** (len(refused) - 1))
                continue
            if refused and mismatch(res):
                refused.append(str(res["reason"]))
                return {**base, "method": method, **res, **({"retries": n_retry} if n_retry else {}),
                        "attempts": len(refused), "attempt_reasons": refused}
            return {**base, "method": method, **res, **({"retries": n_retry} if n_retry else {}),
                    **_attempts(refused)}
    return {**base, "status": "failed", "method": method, "reason": "; ".join(errors) or "no address answered",
            **({"retries": n_retry} if n_retry else {})}


def _attempts(refused: list) -> dict:
    """Manifest fields of a row that was downloaded again after a size or hash mismatch: attempts (downloads in
    all) and attempt_reasons (why each refused download was refused)."""
    return {"attempts": len(refused) + 1, "attempt_reasons": list(refused)} if refused else {}


# ---------- 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), like sevenzip.py.
_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."""
    fonts = run_tool(["pdffonts", str(path)])
    if fonts is None:
        return "skipped", {}, "pdffonts not installed (poppler-utils)"
    if fonts[0] != 0:
        return "skipped", {}, "pdffonts could not read the file"
    text = run_tool(["pdftotext", "-l", str(PDF_PAGES_READ), "-q", str(path), "-"])
    if text is None:
        return "skipped", {}, "pdftotext not installed (poppler-utils)"
    if text[0] != 0:
        return "skipped", {}, "pdftotext could not read the file"
    n_fonts = max(0, len(fonts[1].strip().splitlines()) - 2)
    pages = max(1, min(PDF_PAGES_READ, text[1].count("\f")))
    chars = len(re.sub(r"\s", "", text[1]))
    detail = {"pdf_fonts": n_fonts, "pdf_text_chars": chars, "pdf_pages_read": pages}
    flagged = n_fonts == 0 and chars < PDF_MIN_CHARS_PER_PAGE * 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
ANSWER_DIR = "answer"
LAYOUT_FIELDS = ("source", "path", "url", "sha256", "bytes", "spdx", "licence_url", "publisher", "retrieved", "answer",
                 "origin_kind", "leaf", "role", "unit_group", "answer_for", "verified")


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>, ...] or [answer, <source>, ...]."""
        sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
        src = str(row.get("source"))
        role = sm.get("role") or "unit"
        pp = sm.get("pool_path")
        if isinstance(pp, str) and pp:
            rel = [x for x in pp.split("/") if x]
            if role == "answer" and rel[:1] == [ANSWER_DIR]:
                rel = rel[1:]
        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 = [ANSWER_DIR, src] if role == "answer" else [self.domain_dir(row), src]
        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(), "answer": None,
                "origin_kind": sm.get("origin_kind") or pf.get("origin_kind"), "leaf": self.leaf(row),
                "role": sm.get("role") or "unit", "unit_group": sm.get("unit_group"), "answer_for": sm.get("answer_for"),
                "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():
            for ln in mp.read_text(encoding="utf-8").splitlines():
                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
        answers: dict = {}
        for x in old.values():
            if x.get("role") == "answer" and x.get("unit_group"):
                answers.setdefault((x["source"], x["unit_group"]), []).append(x["path"])
        for x in old.values():
            if x.get("role") == "unit":
                a = sorted(answers.get((x["source"], x.get("unit_group")), []))
                x["answer"] = a[0] if len(a) == 1 else (a or None)
        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["role"] != "companion":
                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
            for ln in sp.read_text(encoding="utf-8").splitlines():
                c = ln.split("\t")
                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"))
            if "dry_fate" in col:
                row["_fate"], row["_fail"] = col["dry_fate"], col.get("dry_fail")
            yield None, row


def parse_args(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0], formatter_class=argparse.RawTextHelpFormatter)
    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) or tag (pinned to the commit the\n"
                         "tag points to); default: 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("--ext", action="append", help="file extension without the dot (repeatable)")
    ap.add_argument("--source", action="append", help="source name (repeatable)")
    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")
    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 (a fixed order)")
    ap.add_argument("--sample", type=int,
                    help="this many units per selected source, the same ones every run (a fixed order); with\n"
                         "their answers and the source's companion files")
    ap.add_argument("--all", action="store_true",
                    help="turn the default profile off: apply only the conditions given here")
    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("--dry-run", action="store_true",
                    help="print the counts and write _meta/fetch_manifest.jsonl with one line per file of the\n"
                         "selection (status selected, removed or not_taken), download nothing")
    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")
    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("--verify-retries", type=int, default=VERIFY_RETRIES,
                    help=f"download a file again this many times when its size or hash does not match its row\n"
                         f"(default {VERIFY_RETRIES}; waits 2, 4, ... seconds in between)")
    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 poppler-utils (pdffonts, pdftotext), a missing tool 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"
                         "(socks needs pip install PySocks; DuckDB cannot use a socks proxy, 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 per-row progress lines on stderr")
    ap.add_argument("--timeout", type=float, default=120)
    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")
    if a.verify_retries < 0:
        ap.error("--verify-retries must be 0 or more")
    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 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) or a tag name (letters, digits, . _ -)")
        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 _progress(n: int, res: dict) -> None:
    what = res.get("pointer_id") or res.get("uri") or ""
    extra = res.get("reason") or (f"{res['bytes']} bytes" if res.get("bytes") is not None else "")
    print(f"[{n}] {res.get('status')} {what}" + (f": {str(extra)[:200]}" if extra else ""), file=sys.stderr,
          flush=True)


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) -> 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 companion files of its sources (a dry run
    writes one manifest line for each). -> 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]
    comp = 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}: {_n(units, 'unit')} and {_n(files + comp, 'file')} in {_n(nsrc, 'source')}"
        + (f" ({_n(comp, 'companion file')} among the files)" if comp else ""))
    if not on:
        say("profile: off (--all)")
    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 + comp, "unit_files": files, "companions": comp, "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"--tag {t}" for t in args.tag 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 dry_reason(row: dict, args) -> dict:
    """The manifest fields that say why a row of a dry run is not fetched: removed_by (the criterion of the profile
    that its unit, or the companion file itself, fails), reason and kept_with (the option that keeps it); for a row
    left out otherwise (not_taken) the reason."""
    fate = row.get("_fate")
    if fate == "removed" and row.get("_fail") is not None:
        n = CRITERIA[int(row["_fail"]) - 1]
        return {"removed_by": n, "reason": REASONS[n], "kept_with": _keeps(n)}
    if fate == "not_taken":
        sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
        if sm.get("role") == "companion":
            return {"reason": "companion file of a source none of whose units is taken"}
        how = [f"--sample {args.sample}" if args.sample else "", f"--limit {args.limit}" if args.limit else ""]
        return {"reason": "left out by " + (" and ".join(h for h in how if h) or "the selection")}
    return {}


def main(argv=None) -> int:
    t0 = time.monotonic()
    args = parse_args(argv)
    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, tags = args.domain or (), args.form or (), args.tag or ()
    relaxed = CRITERIA if args.all else tuple(n for n in CRITERIA if getattr(args, RELAX[n]) 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, exts=args.ext or (), tiers=args.tier, min_size=args.min_size, where=args.where,
                        max_size_filter=args.max_size_filter)
    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)
    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)
        print(";\n".join(views_sql(root, sources=args.source or (), domains=domains, forms=forms)) + ";")
        print(";\n".join([*cand_steps(sel + conds, profile, args.max_size, size_cap),
                          *take_steps(args.limit, args.sample), part_query()]) + ";")
        return 0
    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):
        _SEVENZIP["url"] = to_http(f"{root}/tools/sevenzip.py")
        _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
    layout = None
    incomplete: dict = {}
    given = _given(args)
    try:
        queries, specs, entries, cat = [], {}, {}, {}
        try:
            has = catalog_table(con, root)
            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, has_form=has["form"],
                        where=f" at commit {rev}" if rev else "")
            everything = not (args.source or domains or forms or tags)
            sources = resolve_sources(con, root, domains=domains, forms=forms, sources=args.source or ())
            batches = None
            if tags and sources:
                batches = tag_batches(con, root, tags, sources if args.source or domains or forms else ())
                everything = False
            cat = {str(s): {"domain": list(d or []), "spdx": sp, "files": f}
                   for s, d, sp, f in con.execute("SELECT source, domain, spdx, files FROM s").fetchall()}
            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:
                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)
                jobs = table_steps(root, sources, batches=batches, tags=tags, everything=everything,
                                   local_rows=rows <= LOCAL_ROWS)
                jobs["specs"] = lambda cur: load_entries(cur, root, None if everything else names)
                entries = read_parallel(con, jobs)["specs"]
                complete_rows(con)
                specs = {s: e["layout"] for s, e in entries.items()}
                for s in cand_steps(conds, profile, args.max_size, size_cap):
                    con.execute(s)
                selection = report_counts(con, relaxed, given)
                if selection["kept"] or (args.dry_run and selection["files"]):
                    for s in take_steps(args.limit, args.sample, every=args.dry_run):
                        con.execute(s)
                    tu, tf = con.execute("SELECT (SELECT count(*) FROM fetch_take), (SELECT count(*) FROM fetch_rows"
                                         + (" WHERE dry_fate = 'selected'" if args.dry_run else "") + ")").fetchone()
                    selection.update(taken_units=int(tu), taken_files=int(tf))
                    how = (f" (--sample {args.sample} per source)" if args.sample else "") + \
                          (f" (--limit {args.limit})" if args.limit else "")
                    print(f"{'selected' if args.dry_run else 'fetching'}: {_n(tu, 'unit')}{how}, "
                          f"{_n(tf, 'file')} with their answers and companion files", file=sys.stderr, flush=True)
                    if args.dry_run:
                        print(f"dry run: {META_OUT}/{MANIFEST} gets one line for each of the "
                              f"{_n(selection['files'], 'file')} of the selection, with status selected, removed "
                              f"(removed_by names the criterion) or not_taken", file=sys.stderr, flush=True)
                    queries = part_queries(con, limit)
        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
        with 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)):
                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
                if early is not None:
                    res = early
                elif args.dry_run:
                    res = {**_key(row), "pointer_id": row.get("pointer_id"), "status": row.get("_fate") or "selected",
                           "method": method_of(row), "size_bytes": row.get("size_bytes"),
                           "size_cap_bytes": row.get("_size_cap")}
                    res.update(dry_reason(row, args))
                else:
                    res = {**_key(row), **fetch_unit(row, out, timeout=args.timeout, opener=opener,
                                                     verify_retries=args.verify_retries, 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["layout_path"] = "/".join(row["_dest_parts"])
                    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))
                    sm = row.get("source_meta") if isinstance(row.get("source_meta"), dict) else {}
                    if sm.get("unit_group") and res.get("status") not in ("ok", "selected") and not args.dry_run:
                        incomplete.setdefault((row.get("source"), sm["unit_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
                res["run_id"] = run_id
                man.write(json.dumps(res, ensure_ascii=False, sort_keys=True) + "\n")
                man.flush()
                n_row += 1
                if not args.quiet:
                    _progress(n_row, res)
    finally:
        clear_package_cache()
        _SETUP.pop(id(con), None)
        con.close()
        if own_spill:
            shutil.rmtree(spill, ignore_errors=True)
    lay = layout.write() if layout is not None and not args.dry_run 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)
    summary = {"manifest": str(meta / MANIFEST), "counts": counts, "needs_auth_skipped": auth_skipped,
               "run_id": run_id, "selection": selection, "seconds": round(time.monotonic() - t0, 1)}
    if incomplete:
        summary["incomplete_units"] = len(incomplete)
    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)
    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()}
    (meta / RUN_FILE).write_text(json.dumps(run, ensure_ascii=False, sort_keys=True) + "\n", encoding="utf-8")
    print(json.dumps(summary, sort_keys=True))
    return 0 if not (counts.get("failed") or counts.get("unsafe_path")) else 1


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())