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
4 changes: 2 additions & 2 deletions src/forge_controller/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from .store import Store, TERMINAL
from .tools import SCHEMAS, ToolDenied, permitted, execute, execute_snapshot
from .examples import load_examples, retrieve
from .work_orders import HandoffError, preflight, task_arguments, validate_snapshot_result
from .work_orders import HandoffError, preflight, task_arguments, validate_snapshot_result, parse_json

class JsonFormatter(logging.Formatter):
def format(self, record):
Expand Down Expand Up @@ -125,7 +125,7 @@ async def run(self, task_id, owner, task, binding=None):
if binding:
order, sources = binding
try:
validate_snapshot_result(order, json.loads(content),
validate_snapshot_result(order, parse_json(content),
{'owner':owner,'agent':task.agent,'status':'succeeded','result':content,'audit':audit},sources,owner)
except (HandoffError, ValueError, TypeError):
raise ModelError('invalid_worker_result') from None
Expand Down
16 changes: 10 additions & 6 deletions src/forge_controller/work_orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class HandoffError(ValueError):
pass


def load_json(path, limit=65536):
def parse_json(data):
def unique(pairs):
result = {}
for key, value in pairs:
Expand All @@ -28,16 +28,20 @@ def unique(pairs):
return result
def invalid_constant(value):
raise HandoffError('invalid_json')
with Path(path).open('rb') as stream:
data = stream.read(limit+1)
if len(data)>limit:
raise HandoffError('input_too_large')
try:
return json.loads(data, object_pairs_hook=unique, parse_constant=invalid_constant)
except (ValueError, UnicodeError):
raise HandoffError('invalid_json') from None


def load_json(path, limit=65536):
with Path(path).open('rb') as stream:
data = stream.read(limit+1)
if len(data)>limit:
raise HandoffError('input_too_large')
return parse_json(data)


def shape(value, name):
schema = json.loads((ROOT/'contracts'/(name+'.v1.schema.json')).read_text())
if not Draft202012Validator(schema).is_valid(value):
Expand Down Expand Up @@ -129,7 +133,7 @@ def validate_snapshot_result(order, result, execution, sources, owner):
or not isinstance(execution.get('audit'), list)):
raise HandoffError('execution_mismatch')
try:
if json.loads(execution['result']) != result:
if parse_json(execution['result']) != result:
raise HandoffError('execution_result_mismatch')
except (KeyError, TypeError, ValueError):
raise HandoffError('execution_result_mismatch') from None
Expand Down
22 changes: 22 additions & 0 deletions tests/test_native_work_orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,3 +203,25 @@ async def test_worker_only_principal_cannot_issue_orders(assignment):
async with instance(settings,Worker(result)) as (client,app):
assert (await client.post('/v1/work-orders',json=order)).status_code==403
assert app.state.store.db.execute('SELECT count(*) FROM tasks').fetchone()[0]==0


@pytest.mark.parametrize('key', ['summary', 'claim'])
async def test_native_rejects_duplicate_worker_result_keys(assignment, key):
_, settings, order, result, _ = assignment
order['tools'].append('list_repository_files')

class DuplicateKeyWorker(Worker):
async def chat(self, messages, tools, **kwargs):
message = await super().chat(messages, tools, **kwargs)
if message.get('content'):
marker = json.dumps(key) + ':'
assert message['content'].count(marker) == 1
message['content'] = message['content'].replace(
marker, marker + '"discarded duplicate value",' + marker, 1)
return message

async with instance(settings, DuplicateKeyWorker(result)) as (client, app):
task = (await client.post('/v1/work-orders', json=order)).json()['id']
row = await terminal(client, task)
assert row['status'] == 'failed' and row['error'] == 'invalid_worker_result'
assert row['validation']['structure_valid'] is False
15 changes: 15 additions & 0 deletions tests/test_work_orders.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,21 @@
pytest.importorskip('jsonschema') # Included in the optional MCP tooling lock.
from scripts.work_orders import HandoffError, compile_task, load_json, validate_result
from forge_controller.config import Settings
from forge_controller.work_orders import parse_json


@pytest.mark.parametrize('raw', [
'{"a":1,"a":2}', '{"outer":[{"a":1,"a":2}]}',
'NaN', 'Infinity', '-Infinity', '{"a":NaN}',
])
def test_strict_worker_json_rejects_duplicates_and_constants(raw):
with pytest.raises(HandoffError, match='invalid_json'):
parse_json(raw)


def test_strict_worker_json_preserves_valid_nested_values():
assert parse_json('{"a":[null,true,2,"text",{"b":3}]}') == {
'a': [None, True, 2, 'text', {'b': 3}]}


@pytest.fixture
Expand Down
Loading