// test/claim-and-limits.js — two P0 audit fixes:
// (1) tasks carry limits + tier, and limits are part of the task identity
// (SPEC §4.1) while the result stays keyed by (codeHash, inputHash).
// (2) the `claim` op is a LEASED soft-lock that is actually CONSULTED before
// executing (it was previously written but never read — dead state).
const test = require('brittle')
const Corestore = require('corestore')
const tmp = require('test-tmp')
const { ComputeNode } = require('../lib/node')
const { taskId } = require('../lib/pool')
const codeHash = 'square-v1'
const inputHash = 'abc123'
const FOREIGN = 'ff'.repeat(32) // a worker id that is not ours
const square = { [codeHash]: async (i) => i.n * i.n }
test('limits are part of the task identity (SPEC §4.1), recorded on the task op', async (t) => {
const a = taskId(codeHash, inputHash, { fuel: 1, wallMs: 1, memPages: 1 })
const b = taskId(codeHash, inputHash, { fuel: 2, wallMs: 1, memPages: 1 })
t.not(a, b, 'a different budget is a different task id')
const node = await ComputeNode.create(await tmp(t), null, { executors: square })
await node.grantSelf('owner')
const sub = await node.submit(codeHash, inputHash, { n: 5 }, { limits: { fuel: 7, wallMs: 7, memPages: 7 }, tier: 'T1' })
const taskNode = await node.base.view.get('task/' + sub.id)
t.alike(taskNode.value.limits, { fuel: 7, wallMs: 7, memPages: 7 }, 'task records its limits')
t.is(taskNode.value.tier, 'T1', 'task records its tier')
await node.close()
})
test('an UNEXPIRED foreign claim blocks execution (claim is consulted, not dead state)', async (t) => {
const node = await ComputeNode.create(await tmp(t), null, { executors: square })
await node.grantSelf('owner')
const sub = await node.submit(codeHash, inputHash, { n: 6 })
// another worker holds a fresh lease on this task
await node.base.append({ type: 'claim', id: sub.id, worker: FOREIGN, at: Date.now(), leaseMs: 60000 })
const n = await node.runPendingTasks()
t.is(n, 0, 'task skipped while another worker holds an unexpired claim')
t.is(await node.lookup(codeHash, inputHash), null, 'no result produced')
await node.close()
})
test('an EXPIRED foreign claim does NOT block execution (lease recovery)', async (t) => {
const node = await ComputeNode.create(await tmp(t), null, { executors: square })
await node.grantSelf('owner')
const sub = await node.submit(codeHash, inputHash, { n: 6 })
// a stale lease: claimed far in the past, lease already elapsed
await node.base.append({ type: 'claim', id: sub.id, worker: FOREIGN, at: Date.now() - 120000, leaseMs: 60000 })
const n = await node.runPendingTasks()
t.is(n, 1, 'expired claim is ignored; task re-executed')
t.is(await node.lookup(codeHash, inputHash), 36, 'result produced (6*6)')
await node.close()
})