"""Authored tiny structural safetensors subset. No framework/model/untrusted file loading."""
import struct,json,math,copy,hashlib,platform,re
SIZES={'F32':4,'I64':8}
def unique(pairs):
 d={}
 for k,v in pairs:
  if k in d:raise ValueError('duplicate JSON key')
  d[k]=v
 return d
def inspect(raw):
 if type(raw)is not bytes or not 8<=len(raw)<=12296:raise ValueError('file budget')
 n=struct.unpack('<Q',raw[:8])[0]
 if not 2<=n<=4096 or 8+n>len(raw):raise ValueError('header length')
 text=raw[8:8+n].decode('utf-8');data=raw[8+n:]
 if not text.startswith('{') or len(data)>8192:raise ValueError('header/payload')
 depth=0;containers=0;quoted=False;escaped=False
 for char in text:
  if quoted:
   if escaped:escaped=False
   elif char=='\\':escaped=True
   elif char=='"':quoted=False
  elif char=='"':quoted=True
  elif char in '{[':
   depth+=1;containers+=1
   if depth>8 or containers>128:raise ValueError('header nesting/container budget')
  elif char in '}]':depth-=1
 decoder=json.JSONDecoder(object_pairs_hook=unique,parse_constant=lambda x:(_ for _ in()).throw(ValueError('nonfinite JSON')))
 header,end=decoder.raw_decode(text)
 if text[end:].strip(' ')!='' or type(header)is not dict or len(header)>9:raise ValueError('header subset')
 result=[];positive=[]
 for name,h in header.items():
  if name=='__metadata__':
   if type(h)is not dict or any(type(k)is not str or type(v)is not str for k,v in h.items()):raise ValueError('string metadata')
   continue
  if not re.fullmatch('[A-Za-z][A-Za-z0-9_]{0,31}',name):raise ValueError('name outside subset')
  if type(h)is not dict or set(h)!={'dtype','shape','data_offsets'} or h['dtype']not in SIZES:raise ValueError('descriptor subset')
  shape=h['shape'];offsets=h['data_offsets']
  if type(shape)is not list or len(shape)>8 or any(type(d)is not int or not 0<=d<=32 for d in shape):raise ValueError('shape')
  count=math.prod(shape)
  if count>1024 or type(offsets)is not list or len(offsets)!=2 or any(type(v)is not int for v in offsets):raise ValueError('shape/offset budget')
  begin,end=offsets
  if not 0<=begin<=end<=len(data)or end-begin!=count*SIZES[h['dtype']]:raise ValueError('size/offset')
  if end>begin:positive.append((begin,end))
  result.append({'name':name,'dtype':h['dtype'],'shape':shape,'elements':count,'relative_offsets':offsets,'absolute_file_offsets':[8+n+begin,8+n+end],'bytes':end-begin})
 cursor=0
 for begin,end in sorted(positive):
  if begin!=cursor:raise ValueError('overlap or hole')
  cursor=end
 if cursor!=len(data):raise ValueError('unindexed trailing payload')
 return {'header_bytes':n,'data_bytes':len(data),'tensors':result,'metadata':header.get('__metadata__',{}),'sha256':hashlib.sha256(raw).hexdigest(),'structural_subset_only':True}
def make(header,data):
 h=json.dumps(header,separators=(',',':')).encode();return struct.pack('<Q',len(h))+h+data
def demo():
 header={'a':{'dtype':'F32','shape':[2],'data_offsets':[0,8]},'b':{'dtype':'I64','shape':[1],'data_offsets':[8,16]},'__metadata__':{'source':'authored'}}
 payload=struct.pack('<2fq',1.5,-2.0,3);raw=make(header,payload);out=inspect(raw)
 assert out['data_bytes']==16 and [x['elements']for x in out['tensors']]==[2,1]
 assert struct.unpack('<2f',payload[:8])==(1.5,-2.0)and struct.unpack('<q',payload[8:])==(3,)
 scalar=inspect(make({'s':{'dtype':'I64','shape':[],'data_offsets':[0,8]}},struct.pack('<q',7)));assert scalar['tensors'][0]['elements']==1
 empty=inspect(make({'e':{'dtype':'F32','shape':[0,3],'data_offsets':[0,0]}},b''));assert empty['data_bytes']==0
 invalid=[]
 for name,mut in [('wrong-shape',lambda h:h['a'].update(shape=[3])),('overlap',lambda h:h['b'].update(data_offsets=[4,12])),('hole',lambda h:h['a'].update(shape=[1],data_offsets=[0,4])),('outside',lambda h:h['b'].update(data_offsets=[16,24])),('nonstring-metadata',lambda h:h['__metadata__'].update(source=1)),('unsupported-dtype',lambda h:h['a'].update(dtype='F16'))]:
  h=copy.deepcopy(header);mut(h)
  try:inspect(make(h,payload))
  except ValueError:invalid.append(name)
  else:raise AssertionError(name)
 for name,b in [('duplicate-key',struct.pack('<Q',13)+b'{"a":1,"a":2}'),('truncated-header',struct.pack('<Q',200)+b'{}')]:
  try:inspect(b)
  except ValueError:invalid.append(name)
  else:raise AssertionError(name)
 return {'runtime':platform.python_version(),'original_header':header,'file_hex':raw.hex(),'inspection':out,'scalar_inspection':scalar,'empty_tensor_inspection':empty,'rejected_cases':invalid,'safetensors_or_torch_library_executed':False,'tensor_value_finiteness_or_publisher_authenticity_claimed':False,'all_assertions_passed':True}
if __name__=='__main__':print(json.dumps(demo(),indent=2))
