VibeCoding / src /modules /governance /resource_limits.py
dellweb3's picture
sol6.1 ERP稳定版本
115b94d verified
Raw History Blame Contribute Delete
4.29 kB
"""Small server-owned limits layered over the existing ledger and interpreter."""
import os
import time
from contextlib import contextmanager
from src.modules.skill.domain.models import SkillError
DEFAULTS={'version':'intranet-light-v1','max_features':3,'max_acceptance':5,
'max_model_calls':4,'max_tokens':120000,'max_repairs':1,'max_seconds':900,'scope_budget_percent':50,
'queue_seconds':900,'design_context':20000,'code_context':32000,'repair_context':32000,
'design_output':2048,'code_output':8192,'repair_output':12288}
def configured(overrides=None):
values={**DEFAULTS,**(overrides or {})}
if set(values)!=set(DEFAULTS) or values['version']!=DEFAULTS['version'] or any(type(v) is not int or v<=0 for k,v in values.items() if k!='version'):
raise ValueError('RESOURCE_LIMITS_REQUIRED')
if values['scope_budget_percent']>50 or values['max_seconds']>3600 or values['max_model_calls']>6 or values['max_tokens']>1000000 or values['max_repairs']>2:
raise ValueError('RESOURCE_LIMITS_POLICY_EXCEEDED')
return values
def time_remaining(run,now=None):
now=time.time() if now is None else now
used=run['active_seconds']+max(0,now-run.get('claim_started_at',now)) if run['status']=='running' else run['active_seconds']
return run['budget']['max_seconds']-used
def require_time(run,expected,now=None):
if run['request'].get('resource_limits') and time_remaining(run,now)<expected+5:
raise SkillError('RUN_TIME_BUDGET_EXCEEDED','下一阶段的配置执行时限无法放入剩余任务时间;尚未启动,等待确认。',409)
@contextmanager
def serial_slot(root,name,*,cancelled=lambda:False,timeout=900,on_wait=None):
"""OS file lock covers all processes sharing an instance; no TTL takeover.
Kernel releases on process exit. A restart never alters call reservations.
Only trusted names and the instance's server-owned data path are accepted.
"""
if name not in {'model','heavy','worker'}:raise ValueError('RESOURCE_SLOT_INVALID')
path=root/('resource-'+name+'.lock');path.parent.mkdir(parents=True,exist_ok=True)
with path.open('a+b') as handle:
if path.stat().st_size==0:handle.write(b'0');handle.flush()
start=time.monotonic();locked=False;notified=False
try:
while not locked:
if cancelled():raise SkillError('RUN_CANCELLED','排队已取消,未启动下一步。',409)
try:
handle.seek(0)
if os.name=='nt':
import msvcrt
msvcrt.locking(handle.fileno(),msvcrt.LK_NBLCK,1)
else:
import fcntl
fcntl.flock(handle.fileno(),fcntl.LOCK_EX|fcntl.LOCK_NB)
locked=True
except OSError:
if not notified and on_wait:on_wait();notified=True
if time.monotonic()-start>=timeout:raise SkillError('RESOURCE_QUEUE_TIMEOUT','资源排队达到上限,未启动新工作。',409)
time.sleep(.05)
yield time.monotonic()-start
finally:
if locked:
handle.seek(0)
if os.name=='nt':
import msvcrt
msvcrt.locking(handle.fileno(),msvcrt.LK_UNLCK,1)
else:
import fcntl
fcntl.flock(handle.fileno(),fcntl.LOCK_UN)
def timing_guidance(store):
"""Observed successful stage timings only; never silently extend a timeout."""
samples={}
with store.connect() as db:
rows=db.execute("SELECT id FROM web_jobs WHERE state='verified' ORDER BY rowid DESC LIMIT 20").fetchall()
for row in rows:
starts={}
for event in store.stages(row['id']):
stage=event['stage']
if event['status']=='started':starts[stage]=event['timestamp']
if event['status']=='completed' and stage in starts:
samples.setdefault(stage,[]).append(max(0,event['timestamp']-starts.pop(stage)))
return {stage:{'samples':len(values),'max_observed_seconds':max(values),
'suggested_seconds':int(max(values)*2+15),'applied':False} for stage,values in samples.items()}