Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions gpuqueue/control.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Local queue authority. Browser approvals are separate from scheduler snapshots."""
import time

from .core import Store, canonical, now, atomic_json, TERMINAL
from .core import Store, canonical, now, atomic_json, read_json, TERMINAL

LIVE = {'ready', 'queued', 'waiting_gpu', 'checking_resources'}
DELETABLE = {'completed', 'cancelled', 'stopped', 'failed', 'interrupted'}
Expand All @@ -14,6 +14,17 @@ def __init__(self, message, status=409):
class QueueChanged(ControlError):
pass

def ensure_stop_marker(store, task_id, digest, at):
path = store.root/'tasks'/task_id/'run/stop.json'
expected = {'task': task_id, 'digest': digest, 'at': at}
try:
marker = read_json(path)
except ValueError:
marker = None
if isinstance(marker, dict) and all(marker.get(key) == value for key, value in expected.items()):
return
atomic_json(path, expected)

class Control:
def __init__(self, store=None):
self.store = store or Store()
Expand Down Expand Up @@ -223,7 +234,7 @@ def stop(self, task_id, digest):
db.execute("UPDATE queue_meta SET value=CAST(value AS INTEGER)+1 WHERE key='revision'")
db.execute('INSERT INTO queue_audit(task_id,action,at) VALUES (?,?,?)', (task_id, 'browser_stop:'+digest, at))
# Live control marker, separate from the immutable approved code.
atomic_json(self.store.root/'tasks'/task_id/'run/stop.json', {'task':task_id,'digest':digest,'at':at})
ensure_stop_marker(self.store, task_id, digest, at)
return self.state()

def confirm_stop(self, task_id, digest):
Expand Down
40 changes: 30 additions & 10 deletions gpuqueue/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,34 @@ def fingerprint(path):
result['sha256'] = sha(path)
return result

def validate_step_paths(argv, cwd, project, files, source_paths, index):
# Use the runner's expansion order and cwd resolution without changing the
# submitted strings (or tying their digest to this temporary location).
from .runner import expand
with tempfile.TemporaryDirectory(prefix='gpuq-paths-') as temporary:
folder = Path(temporary).resolve()
code = folder / 'code'
effective_cwd = Path(expand(cwd, folder, {'project': str(project)})).resolve()
for argument in argv[1:]:
value = argument.split('=', 1)[1] if argument.startswith('-') and '=' in argument else argument
path = Path(expand(value, folder, {'project': str(project)}))
if not path.is_absolute():
path = effective_cwd / path
lexical = Path(os.path.normpath(path))
resolved = path.resolve()
if '{code}' in value:
if not resolved.is_relative_to(code):
raise ValueError(f'步骤 {index + 1} 的代码路径超出快照:{value}')
relative = str(resolved.relative_to(code))
if (relative != '.' and relative not in files and
not any(name.startswith(relative + '/') for name in files)):
raise ValueError(f'步骤 {index + 1} 引用了未加入快照的代码或配置:{relative}')
# Check both snapshot names and real targets: source symlinks can
# have different names, while the copied snapshot preserves its index.
if (resolved in source_paths or
lexical.is_relative_to(project) and str(lexical.relative_to(project)) in files):
raise ValueError('运行代码请引用 {code}/文件,避免执行 Agent 后续修改的源文件')

def normalize(manifest, source='Codex'):
if not isinstance(manifest, dict) or manifest.get('schema_version', 1) != 1:
raise ValueError('需要 schema_version=1 的 JSON 任务文件')
Expand Down Expand Up @@ -129,6 +157,7 @@ def string(value, field):
raise ValueError('steps 需要 1–50 个有序步骤')
normalized_steps = []
runtimes = {}
source_paths = {(project / name).resolve() for name in files}
for index, raw in enumerate(steps):
if not isinstance(raw, dict):
raise ValueError(f'步骤 {index + 1} 必须是对象')
Expand All @@ -145,11 +174,6 @@ def string(value, field):
executable = Path(argv[0])
if not executable.is_absolute() or not executable.is_file() or not os.access(executable, os.X_OK):
raise ValueError(f'步骤 {index + 1} 需要当前已存在的绝对可执行路径')
for argument in argv[1:]:
if argument.startswith('{code}/'):
relative = argument[len('{code}/'):]
if relative not in files and not any(name.startswith(relative.rstrip('/')+'/') for name in files):
raise ValueError(f'步骤 {index + 1} 引用了未加入快照的代码或配置:{relative}')
runtimes[str(executable)] = fingerprint(executable)
outputs = raw.get('outputs', [])
if not isinstance(outputs, list) or not all(isinstance(p, str) and p.startswith('{outputs}/') and '..' not in Path(p).parts for p in outputs):
Expand All @@ -161,11 +185,7 @@ def string(value, field):
raise ValueError('任务文件不保存凭据;使用本人私有环境配置')
if any(k in env for k in ['CUDA_VISIBLE_DEVICES', 'GPUQ_OUTPUT_DIR', 'GPUQ_TASK_ID']):
raise ValueError('GPU 设备与任务目录由执行器指定')
for a in argv[1:]:
# Match the project/home placeholders expanded by the runner.
a = a.replace('{project}', str(project)).replace('{home}', str(HOME))
if a.startswith(str(project) + '/') and Path(a).is_file() and str(Path(a).relative_to(project)) in files:
raise ValueError('运行代码请引用 {code}/文件,避免执行 Agent 后续修改的源文件')
validate_step_paths(argv, cwd, project, files, source_paths, index)
normalized_steps.append({'name': name or f'步骤 {index + 1}', 'argv': argv, 'cwd': cwd, 'outputs': outputs, 'env': env})
document = {'schema_version': 1, 'title': title, 'description': description, 'project': str(project), 'resources': resources, 'steps': normalized_steps, 'files': files, 'inputs': inputs, 'runtimes': list(runtimes.values()), 'submission_key': submission_key, 'runner_sha256': sha(Path(__file__).with_name('runner.py'))}
digest = hashlib.sha256(canonical(document).encode()).hexdigest()
Expand Down
15 changes: 11 additions & 4 deletions gpuqueue/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .feishu import FeishuAuthError
from .resources import published_resources

from .control import Control, QueueChanged
from .control import Control, QueueChanged, ensure_stop_marker

def redact(text):
text = re.sub(r'(?i)(bearer\s+)[A-Za-z0-9._~+/=-]+', r'\1[redacted]', text)
Expand Down Expand Up @@ -50,9 +50,16 @@ def __init__(self, config, store=None, platform=None):
self.remote_revision = None
self.error = None
self.checked_at = None
self._control = None

@property
def control(self):
if self._control is None:
self._control = Control(self.store)
return self._control

def remote(self, path, payload):
control = Control(self.store)
control = self.control
if path == '/api/worker/sync':
return control.sync(payload['heartbeat'])
if path == '/api/worker/claim':
Expand Down Expand Up @@ -100,7 +107,7 @@ def sync(self):
local['public']['events'].append('你在网页请求停止任务;已有产物保留,后续步骤不再执行')
if (local['internal'].get('stop_requested_at') != at or
not local['internal'].get('stop_confirmed') and remote['state'] not in ['completed', 'cancelled']):
atomic_json(self.store.root/'tasks'/local['id']/'run/stop.json', {'task':local['id'],'digest':local['digest'],'at':at})
ensure_stop_marker(self.store, local['id'], local['digest'], at)
local['internal']['stop_requested_at'] = at
if remote['state'] != 'completed':
phase = ('已移出队列' if remote['state']=='cancelled' else
Expand Down Expand Up @@ -361,7 +368,7 @@ def process_stop(self, task):
self.refresh_task(task)
if public['state'] == 'completed':
return
Control(self.store).confirm_stop(task['id'],task['digest'])
self.control.confirm_stop(task['id'],task['digest'])
internal['stop_confirmed'] = True
internal['terminal_reconciled'] = True
public.update(state='stopped',phase='任务已停止,已有产物保留')
Expand Down
Loading
Loading