| Run | Reference grade | Regrade | Change |
|---|---:|---:|---:|
| 7LjzJZv | 0.6800 (harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv/grade.md) | 0.7400 (harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.6800-7LjzJZv/verifier/grade.md) | +0.0600 |
| akzaQGd | 0.7300 (harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.7300-akzaQGd/grade.md) | 0.7600 (harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.7300-akzaQGd/verifier/grade.md) | +0.0300 |
| BmbBf3A | 0.8200 (harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.8200-BmbBf3A/grade.md) | 0.7600 (harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.8200-BmbBf3A/verifier/grade.md) | −0.0600 |
| iKGgNam | 0.8200 (harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.8200-iKGgNam/grade.md) | 0.7700 (harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.8200-iKGgNam/verifier/grade.md) | −0.0500 |

Mean shifted slightly from 0.7625 to 0.7575, while the range compressed from 0.14 to 0.03.
This commit is contained in:
2026-10-11 21:12:59 -04:00
parent 939ce53461
commit 52ba8a14b5
300 changed files with 33347 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-reward-0.6800-7LjzJZv-1791765861-91477",
"jobs_dir": "harbor-jobs/potion-voice-user-ownership__7LjzJZv",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,6 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Trial potion-voice-user-ownership__tvMCgw5 failed: No reward file found at harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.txt or harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.json
Exception RewardFileNotFoundError is in exclude_exceptions, not retrying
Not retrying trial because the exception is not in include_exceptions or the maximum number of retries has been reached

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"created_at": "2026-10-12T00:44:22.722200Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"RewardFileNotFoundError",
"VerifierOutputParseError",
"VerifierTimeoutError",
"AgentTimeoutError",
"RewardFileEmptyError",
"ModelNotFoundError",
"AgentAuthenticationError",
"AgentSafetyRefusalError",
"ApiUsageLimitError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:522f90f015a9fa27da5d3b01cd1094f86fe50f0c549cae3513372293dd5c5f59",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,27 @@
{
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__tvMCgw5",
"trials_dir": "harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477",
"agent": {
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
},
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "7e9f9d70-bcdc-46f7-9037-c739c43f2474"
}

View File

@@ -0,0 +1,17 @@
Traceback (most recent call last):
File "/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/trial.py", line 354, in run
await self._run()
File "/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/single_step.py", line 52, in _run
await self._run_verifier()
File "/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/single_step.py", line 105, in _run_verifier
self.result.verifier_result = await self._run_shared_verifier(
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/trial.py", line 535, in _run_shared_verifier
return await asyncio.wait_for(
^^^^^^^^^^^^^^^^^^^^^^^
File "/root/.local/share/uv/python/cpython-3.12.15-linux-x86_64-gnu/lib/python3.12/asyncio/tasks.py", line 520, in wait_for
return await fut
^^^^^^^^^
File "/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/verifier/verifier.py", line 232, in verify
raise RewardFileNotFoundError(
harbor.verifier.verifier.RewardFileNotFoundError: No reward file found at harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.txt or harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.json

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:522f90f015a9fa27da5d3b01cd1094f86fe50f0c549cae3513372293dd5c5f59",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,120 @@
{
"id": "f163a800-5abc-44f5-90a9-6fdc18501dce",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__tvMCgw5",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5",
"task_id": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "f2cf85b5f445ddb7abc01f96b8473ac07bef6b190232a2fabb8770df0f7d6219",
"config": {
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__tvMCgw5",
"trials_dir": "harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "replay_agent:ReplayAgent",
"model_name": null,
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "7e9f9d70-bcdc-46f7-9037-c739c43f2474"
},
"agent_info": {
"name": "replay",
"version": "1.0.0",
"model_info": null
},
"agent_result": {
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null,
"rollout_details": null,
"metadata": null
},
"verifier_result": null,
"exception_info": {
"exception_type": "RewardFileNotFoundError",
"exception_message": "No reward file found at harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.txt or harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.json",
"exception_traceback": "Traceback (most recent call last):\n File \"/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/trial.py\", line 354, in run\n await self._run()\n File \"/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/single_step.py\", line 52, in _run\n await self._run_verifier()\n File \"/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/single_step.py\", line 105, in _run_verifier\n self.result.verifier_result = await self._run_shared_verifier(\n ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\n File \"/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/trial/trial.py\", line 535, in _run_shared_verifier\n return await asyncio.wait_for(\n ^^^^^^^^^^^^^^^^^^^^^^^\n File \"/root/.local/share/uv/python/cpython-3.12.15-linux-x86_64-gnu/lib/python3.12/asyncio/tasks.py\", line 520, in wait_for\n return await fut\n ^^^^^^^^^\n File \"/root/.local/share/uv/tools/harbor/lib/python3.12/site-packages/harbor/verifier/verifier.py\", line 232, in verify\n raise RewardFileNotFoundError(\nharbor.verifier.verifier.RewardFileNotFoundError: No reward file found at harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.txt or harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.json\n",
"occurred_at": "2026-10-12T00:44:58.913907"
},
"started_at": "2026-10-12T00:44:23.041550Z",
"finished_at": "2026-10-12T00:45:03.476328Z",
"environment_setup": {
"started_at": "2026-10-12T00:44:23.215902Z",
"finished_at": "2026-10-12T00:44:27.044330Z"
},
"agent_setup": {
"started_at": "2026-10-12T00:44:27.044375Z",
"finished_at": "2026-10-12T00:44:27.044421Z"
},
"agent_execution": {
"started_at": "2026-10-12T00:44:27.044473Z",
"finished_at": "2026-10-12T00:44:27.445420Z"
},
"verifier": {
"started_at": "2026-10-12T00:44:27.989347Z",
"finished_at": "2026-10-12T00:44:58.910952Z"
},
"step_results": null
}

View File

@@ -0,0 +1,4 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.
Trial potion-voice-user-ownership__tvMCgw5 failed: No reward file found at harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.txt or harbor-jobs/potion-voice-user-ownership__7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791765861-91477/potion-voice-user-ownership__tvMCgw5/verifier/reward.json

View File

@@ -0,0 +1,53 @@
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
const normalizeUserId = (userId) => {
const serializedUserId =
typeof userId === 'string'
? userId
: userId && typeof userId.toHexString === 'function'
? userId.toHexString()
: null
if (!serializedUserId || !OBJECT_ID_PATTERN.test(serializedUserId)) {
const error = new Error(
'A valid userId is required for tenant-scoped database access'
)
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return serializedUserId
}
const filterForUser = (filter, userId) => ({
...(filter || {}),
userId: normalizeUserId(userId),
})
const documentForUser = (document, userId) => ({
...document,
userId: normalizeUserId(userId),
})
const documentsForUser = (documents, userId) => {
const normalizedUserId = normalizeUserId(userId)
return documents.map((document) => ({
...document,
userId: normalizedUserId,
}))
}
const updateWithoutTenantFields = (data) => {
const plainData =
data && typeof data.toObject === 'function' ? data.toObject() : data
const { _id, userId, ...updates } = plainData
return updates
}
module.exports = {
documentForUser,
documentsForUser,
filterForUser,
normalizeUserId,
updateWithoutTenantFields,
}

View File

@@ -0,0 +1,23 @@
{
"name": "potion-voice",
"version": "1.0.0",
"description": "This will handle the voice cloning jobs",
"main": "index.js",
"scripts": {
"test": "node tests/tenant-isolation.test.js"
},
"dependencies": {
"@bugsnag/js": "^7.3.5",
"aws-sdk": "^2.752.0",
"fs-extra": "^9.0.1",
"mongoose": "^6.8.0",
"pm2": "^5.2.0",
"rimraf": "^3.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"aws-code-deploy": "^1.0.11"
},
"author": "potion Team",
"license": "ISC"
}

View File

@@ -0,0 +1,228 @@
const assert = require('assert')
const TenantScope = require('../app/services/utils/tenantScope')
const TENANT_ID = '507f1f77bcf86cd799439011'
const OTHER_TENANT_ID = '507f1f77bcf86cd799439012'
const DOCUMENT_ID = '507f1f77bcf86cd799439013'
const createModelDouble = () => {
const calls = []
function Model(document) {
calls.push({ method: 'constructor', args: [document] })
this.save = async () => {
calls.push({ method: 'save', args: [] })
return document
}
}
const modelMethods = [
'findOne',
'find',
'findOneAndUpdate',
'updateMany',
'insertMany',
]
modelMethods.forEach((method) => {
Model[method] = async (...args) => {
calls.push({ method, args })
return { method }
}
})
return { calls, Model }
}
const lastCall = (calls, method) => {
const matchingCalls = calls.filter((call) => call.method === method)
return matchingCalls[matchingCalls.length - 1]
}
const assertGenericServiceIsTenantScoped = async (serviceFactory) => {
const { calls, Model } = createModelDouble()
const service = serviceFactory(Model)
await service.create({ name: 'profile', userId: OTHER_TENANT_ID }, TENANT_ID)
assert.strictEqual(
lastCall(calls, 'constructor').args[0].userId,
TENANT_ID,
'create must force the authenticated tenant'
)
await service.insertMany(
[{ name: 'profile', userId: OTHER_TENANT_ID }],
TENANT_ID
)
assert.strictEqual(
lastCall(calls, 'insertMany').args[0][0].userId,
TENANT_ID,
'insertMany must force the authenticated tenant'
)
await service.read(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOne').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
assert.deepStrictEqual(lastCall(calls, 'find').args[0], {
userId: TENANT_ID,
deleted: false,
})
await service.update(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
status: 'completed',
},
TENANT_ID
)
const updateCall = lastCall(calls, 'findOneAndUpdate')
assert.deepStrictEqual(updateCall.args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(updateCall.args[1], { status: 'completed' })
await service.remove(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOneAndUpdate').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.removeMany({ userId: OTHER_TENANT_ID }, TENANT_ID)
assert.deepStrictEqual(lastCall(calls, 'updateMany').args[0], {
userId: TENANT_ID,
deleted: false,
})
}
const assertSalutationServiceIsTenantScoped = async () => {
const { calls, Model } = createModelDouble()
const service = require('../voice-synthsizer-job-handler/salutation/salutation_service')(
Model
)
await service.create(
{ salutationVideo: 'created.wav', userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.strictEqual(
lastCall(calls, 'constructor').args[0].userId,
TENANT_ID
)
await service.read(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOne').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
assert.deepStrictEqual(lastCall(calls, 'find').args[0], {
userId: TENANT_ID,
deleted: false,
})
await service.update(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
salutationVideo: 'updated.wav',
},
TENANT_ID
)
const updateCall = lastCall(calls, 'findOneAndUpdate')
assert.deepStrictEqual(updateCall.args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(updateCall.args[1], {
salutationVideo: 'updated.wav',
})
await service.modify(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
salutationVideo: 'tenant-safe.wav',
},
TENANT_ID
)
const modifyCall = lastCall(calls, 'findOneAndUpdate')
assert.deepStrictEqual(modifyCall.args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(modifyCall.args[1], {
salutationVideo: 'tenant-safe.wav',
})
await service.remove(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOneAndUpdate').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
}
const run = async () => {
assert.deepStrictEqual(
TenantScope.filterForUser({ userId: OTHER_TENANT_ID }, TENANT_ID),
{ userId: TENANT_ID }
)
assert.throws(
() => TenantScope.filterForUser({}, { $ne: null }),
(error) => error.code === 'TENANT_CONTEXT_REQUIRED'
)
assert.throws(
() => TenantScope.filterForUser({}, undefined),
(error) => error.code === 'TENANT_CONTEXT_REQUIRED'
)
const serviceFactories = [
require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service'),
require('../voice-synthsizer-job-handler/job/job_service'),
require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service'),
require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service'),
]
const originalLog = console.log
console.log = () => {}
try {
for (const serviceFactory of serviceFactories) {
await assertGenericServiceIsTenantScoped(serviceFactory)
}
} finally {
console.log = originalLog
}
await assertSalutationServiceIsTenantScoped()
console.log('Tenant-isolation tests passed')
}
run().catch((error) => {
console.error(error)
process.exitCode = 1
})

View File

@@ -0,0 +1,384 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
const TenantScope = require('../app/services/utils/tenantScope')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
function requireTenantRecord(record, resourceName) {
if (!record) {
const error = new Error(`${resourceName} was not found for the job tenant`)
error.code = 'TENANT_RECORD_NOT_FOUND'
throw error
}
return record
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const {
metadata,
input,
_id,
userAudioProfileId,
userId: jobUserId,
} = job._doc
let userId = jobUserId
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
userId = TenantScope.normalizeUserId(jobUserId)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
requireTenantRecord(
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
),
'Voice cloning job'
)
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
),
'User audio profile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireTenantRecord(
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
),
'Voice cloning job'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
),
'User audio profile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
),
'User audio profile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// update the db to set status as error
await voiceCloningService.update({ _id, status: 'error' }, userId)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,154 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(
TenantScope.documentForUser(data, userId)
)
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
TenantScope.documentsForUser(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: data._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(data),
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,155 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel(
TenantScope.documentForUser(data, userId)
)
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const inserted = await VoiceCloningModel.insertMany(
TenantScope.documentsForUser(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: data._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(data),
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,277 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
const TenantScope = require('../app/services/utils/tenantScope')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
userId: jobUserId,
} = job
const userId = TenantScope.normalizeUserId(jobUserId)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// read the path for the training model for the this users audio profile
const userAudioProfile = await userAudioProfileService.read(
{
_id: userAudioProfileId,
status: 'completed',
},
userId
)
if (userAudioProfile) {
const { training_model_path } = userAudioProfile
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
// update the dynamic recordings for the current dynamic video with salutation url
const salutationToUpdate = await recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
})
const recordingToUpdate = await recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
})
if (
salutationToUpdate &&
salutationToUpdate.deleted === false &&
recordingToUpdate
) {
const jobsToInsert = []
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
}
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert, userId)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
resolve() // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,152 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job(TenantScope.documentForUser(jobData, userId))
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData, userId) => {
try {
const inserted = await Job.insertMany(
TenantScope.documentsForUser(jobData, userId)
)
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (Job) => async (filter, userId) => {
try {
const foundJob = await Job.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (Job) => async (filter, userId) => {
try {
const foundJobs = await Job.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (Job) => async (job, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: job._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(job),
{
new: true,
}
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -0,0 +1,102 @@
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation(
TenantScope.documentForUser(salutationData, userId)
)
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: salutation._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(salutation),
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
const findQuery = salutation._id
? { _id: salutation._id }
: { transcriptId: salutation.transcriptId }
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...TenantScope.filterForUser(findQuery, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(salutation),
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const salutation = await read(Salutation)(
{
firstName,
userAudioProfileId,
},
userId
)
if (salutation) {
salutation.salutationVideo = salutationVideo
return await update(Salutation)(salutation, userId)
} else {
return await create(Salutation)(
{ firstName, salutationVideo, userAudioProfileId },
userId
)
}
}
const remove = (Salutation) => async (filter, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => {
return {
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
}
}

View File

@@ -0,0 +1,156 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(
TenantScope.documentForUser(data, userId)
)
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
TenantScope.documentsForUser(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...TenantScope.filterForUser(filter, userId),
deleted: false
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
console.log('ua data', data)
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: data._id }, userId),
deleted: false
},
TenantScope.updateWithoutTenantFields(data),
{
new: true
}
)
console.log('ua updatedModel', updatedModel)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false
},
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false
},
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-12T00:44:28Z",
"grader_mode": "rubric-trinary",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "rubric-trinary",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "rubric-criteria.md",
"grader_guidance_sha256": "fa2887e3e9773110ea124ac8d03d3b31283ad4431a58c8c72a25dff221950937",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.DdaG0MCN"))

View File

@@ -0,0 +1,2 @@
Captured 10 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...

View File

@@ -0,0 +1,37 @@
{
"id": "7e9f9d70-bcdc-46f7-9037-c739c43f2474",
"started_at": "2026-10-12T00:44:22.522132",
"updated_at": "2026-10-12T00:45:03.480456",
"finished_at": "2026-10-12T00:45:03.480456",
"n_total_trials": 1,
"stats": {
"n_completed_trials": 1,
"n_errored_trials": 1,
"n_running_trials": 0,
"n_pending_trials": 0,
"n_cancelled_trials": 0,
"n_retries": 0,
"evals": {
"replay__adhoc": {
"n_trials": 0,
"n_errors": 1,
"metrics": [
{
"mean": 0.0
}
],
"pass_at_k": {},
"reward_stats": {},
"exception_stats": {
"RewardFileNotFoundError": [
"potion-voice-user-ownership__tvMCgw5"
]
}
}
},
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null
}
}

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-reward-0.6800-7LjzJZv-1791766078-92534",
"jobs_dir": "harbor-jobs/reward-0.6800-7LjzJZv",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"created_at": "2026-10-12T00:47:59.812740Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"AgentTimeoutError",
"AgentSafetyRefusalError",
"RewardFileNotFoundError",
"ModelNotFoundError",
"ApiUsageLimitError",
"RewardFileEmptyError",
"VerifierTimeoutError",
"VerifierOutputParseError",
"AgentAuthenticationError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:522f90f015a9fa27da5d3b01cd1094f86fe50f0c549cae3513372293dd5c5f59",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,27 @@
{
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__KbZV2j4",
"trials_dir": "harbor-jobs/reward-0.6800-7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791766078-92534",
"agent": {
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
},
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "39a1158c-a8dc-46c8-8ff8-9b56e432b63d"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:522f90f015a9fa27da5d3b01cd1094f86fe50f0c549cae3513372293dd5c5f59",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "d7526f63-c8d8-4cfc-82fb-16b435c5f1e0",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__KbZV2j4",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.6800-7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791766078-92534/potion-voice-user-ownership__KbZV2j4",
"task_id": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "f2cf85b5f445ddb7abc01f96b8473ac07bef6b190232a2fabb8770df0f7d6219",
"config": {
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__KbZV2j4",
"trials_dir": "harbor-jobs/reward-0.6800-7LjzJZv/regrade-reward-0.6800-7LjzJZv-1791766078-92534",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "replay_agent:ReplayAgent",
"model_name": null,
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-7LjzJZv",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "39a1158c-a8dc-46c8-8ff8-9b56e432b63d"
},
"agent_info": {
"name": "replay",
"version": "1.0.0",
"model_info": null
},
"agent_result": {
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.74
}
},
"exception_info": null,
"started_at": "2026-10-12T00:48:00.128717Z",
"finished_at": "2026-10-12T00:51:10.262562Z",
"environment_setup": {
"started_at": "2026-10-12T00:48:00.291686Z",
"finished_at": "2026-10-12T00:48:03.733113Z"
},
"agent_setup": {
"started_at": "2026-10-12T00:48:03.733165Z",
"finished_at": "2026-10-12T00:48:03.733215Z"
},
"agent_execution": {
"started_at": "2026-10-12T00:48:03.733271Z",
"finished_at": "2026-10-12T00:48:04.123856Z"
},
"verifier": {
"started_at": "2026-10-12T00:48:04.654908Z",
"finished_at": "2026-10-12T00:51:06.076410Z"
},
"step_results": null
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,53 @@
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
const normalizeUserId = (userId) => {
const serializedUserId =
typeof userId === 'string'
? userId
: userId && typeof userId.toHexString === 'function'
? userId.toHexString()
: null
if (!serializedUserId || !OBJECT_ID_PATTERN.test(serializedUserId)) {
const error = new Error(
'A valid userId is required for tenant-scoped database access'
)
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return serializedUserId
}
const filterForUser = (filter, userId) => ({
...(filter || {}),
userId: normalizeUserId(userId),
})
const documentForUser = (document, userId) => ({
...document,
userId: normalizeUserId(userId),
})
const documentsForUser = (documents, userId) => {
const normalizedUserId = normalizeUserId(userId)
return documents.map((document) => ({
...document,
userId: normalizedUserId,
}))
}
const updateWithoutTenantFields = (data) => {
const plainData =
data && typeof data.toObject === 'function' ? data.toObject() : data
const { _id, userId, ...updates } = plainData
return updates
}
module.exports = {
documentForUser,
documentsForUser,
filterForUser,
normalizeUserId,
updateWithoutTenantFields,
}

View File

@@ -0,0 +1,23 @@
{
"name": "potion-voice",
"version": "1.0.0",
"description": "This will handle the voice cloning jobs",
"main": "index.js",
"scripts": {
"test": "node tests/tenant-isolation.test.js"
},
"dependencies": {
"@bugsnag/js": "^7.3.5",
"aws-sdk": "^2.752.0",
"fs-extra": "^9.0.1",
"mongoose": "^6.8.0",
"pm2": "^5.2.0",
"rimraf": "^3.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"aws-code-deploy": "^1.0.11"
},
"author": "potion Team",
"license": "ISC"
}

View File

@@ -0,0 +1,228 @@
const assert = require('assert')
const TenantScope = require('../app/services/utils/tenantScope')
const TENANT_ID = '507f1f77bcf86cd799439011'
const OTHER_TENANT_ID = '507f1f77bcf86cd799439012'
const DOCUMENT_ID = '507f1f77bcf86cd799439013'
const createModelDouble = () => {
const calls = []
function Model(document) {
calls.push({ method: 'constructor', args: [document] })
this.save = async () => {
calls.push({ method: 'save', args: [] })
return document
}
}
const modelMethods = [
'findOne',
'find',
'findOneAndUpdate',
'updateMany',
'insertMany',
]
modelMethods.forEach((method) => {
Model[method] = async (...args) => {
calls.push({ method, args })
return { method }
}
})
return { calls, Model }
}
const lastCall = (calls, method) => {
const matchingCalls = calls.filter((call) => call.method === method)
return matchingCalls[matchingCalls.length - 1]
}
const assertGenericServiceIsTenantScoped = async (serviceFactory) => {
const { calls, Model } = createModelDouble()
const service = serviceFactory(Model)
await service.create({ name: 'profile', userId: OTHER_TENANT_ID }, TENANT_ID)
assert.strictEqual(
lastCall(calls, 'constructor').args[0].userId,
TENANT_ID,
'create must force the authenticated tenant'
)
await service.insertMany(
[{ name: 'profile', userId: OTHER_TENANT_ID }],
TENANT_ID
)
assert.strictEqual(
lastCall(calls, 'insertMany').args[0][0].userId,
TENANT_ID,
'insertMany must force the authenticated tenant'
)
await service.read(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOne').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
assert.deepStrictEqual(lastCall(calls, 'find').args[0], {
userId: TENANT_ID,
deleted: false,
})
await service.update(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
status: 'completed',
},
TENANT_ID
)
const updateCall = lastCall(calls, 'findOneAndUpdate')
assert.deepStrictEqual(updateCall.args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(updateCall.args[1], { status: 'completed' })
await service.remove(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOneAndUpdate').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.removeMany({ userId: OTHER_TENANT_ID }, TENANT_ID)
assert.deepStrictEqual(lastCall(calls, 'updateMany').args[0], {
userId: TENANT_ID,
deleted: false,
})
}
const assertSalutationServiceIsTenantScoped = async () => {
const { calls, Model } = createModelDouble()
const service = require('../voice-synthsizer-job-handler/salutation/salutation_service')(
Model
)
await service.create(
{ salutationVideo: 'created.wav', userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.strictEqual(
lastCall(calls, 'constructor').args[0].userId,
TENANT_ID
)
await service.read(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOne').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
assert.deepStrictEqual(lastCall(calls, 'find').args[0], {
userId: TENANT_ID,
deleted: false,
})
await service.update(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
salutationVideo: 'updated.wav',
},
TENANT_ID
)
const updateCall = lastCall(calls, 'findOneAndUpdate')
assert.deepStrictEqual(updateCall.args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(updateCall.args[1], {
salutationVideo: 'updated.wav',
})
await service.modify(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
salutationVideo: 'tenant-safe.wav',
},
TENANT_ID
)
const modifyCall = lastCall(calls, 'findOneAndUpdate')
assert.deepStrictEqual(modifyCall.args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
assert.deepStrictEqual(modifyCall.args[1], {
salutationVideo: 'tenant-safe.wav',
})
await service.remove(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID },
TENANT_ID
)
assert.deepStrictEqual(lastCall(calls, 'findOneAndUpdate').args[0], {
_id: DOCUMENT_ID,
userId: TENANT_ID,
deleted: false,
})
}
const run = async () => {
assert.deepStrictEqual(
TenantScope.filterForUser({ userId: OTHER_TENANT_ID }, TENANT_ID),
{ userId: TENANT_ID }
)
assert.throws(
() => TenantScope.filterForUser({}, { $ne: null }),
(error) => error.code === 'TENANT_CONTEXT_REQUIRED'
)
assert.throws(
() => TenantScope.filterForUser({}, undefined),
(error) => error.code === 'TENANT_CONTEXT_REQUIRED'
)
const serviceFactories = [
require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service'),
require('../voice-synthsizer-job-handler/job/job_service'),
require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service'),
require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service'),
]
const originalLog = console.log
console.log = () => {}
try {
for (const serviceFactory of serviceFactories) {
await assertGenericServiceIsTenantScoped(serviceFactory)
}
} finally {
console.log = originalLog
}
await assertSalutationServiceIsTenantScoped()
console.log('Tenant-isolation tests passed')
}
run().catch((error) => {
console.error(error)
process.exitCode = 1
})

View File

@@ -0,0 +1,384 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
const TenantScope = require('../app/services/utils/tenantScope')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
function requireTenantRecord(record, resourceName) {
if (!record) {
const error = new Error(`${resourceName} was not found for the job tenant`)
error.code = 'TENANT_RECORD_NOT_FOUND'
throw error
}
return record
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const {
metadata,
input,
_id,
userAudioProfileId,
userId: jobUserId,
} = job._doc
let userId = jobUserId
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
userId = TenantScope.normalizeUserId(jobUserId)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
requireTenantRecord(
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
),
'Voice cloning job'
)
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
),
'User audio profile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireTenantRecord(
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
),
'Voice cloning job'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
),
'User audio profile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
),
'User audio profile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// update the db to set status as error
await voiceCloningService.update({ _id, status: 'error' }, userId)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,154 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(
TenantScope.documentForUser(data, userId)
)
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
TenantScope.documentsForUser(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: data._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(data),
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,155 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel(
TenantScope.documentForUser(data, userId)
)
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const inserted = await VoiceCloningModel.insertMany(
TenantScope.documentsForUser(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: data._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(data),
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,277 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
const TenantScope = require('../app/services/utils/tenantScope')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
userId: jobUserId,
} = job
const userId = TenantScope.normalizeUserId(jobUserId)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// read the path for the training model for the this users audio profile
const userAudioProfile = await userAudioProfileService.read(
{
_id: userAudioProfileId,
status: 'completed',
},
userId
)
if (userAudioProfile) {
const { training_model_path } = userAudioProfile
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
// update the dynamic recordings for the current dynamic video with salutation url
const salutationToUpdate = await recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
})
const recordingToUpdate = await recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
})
if (
salutationToUpdate &&
salutationToUpdate.deleted === false &&
recordingToUpdate
) {
const jobsToInsert = []
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
}
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert, userId)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
resolve() // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,152 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job(TenantScope.documentForUser(jobData, userId))
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData, userId) => {
try {
const inserted = await Job.insertMany(
TenantScope.documentsForUser(jobData, userId)
)
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (Job) => async (filter, userId) => {
try {
const foundJob = await Job.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (Job) => async (filter, userId) => {
try {
const foundJobs = await Job.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (Job) => async (job, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: job._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(job),
{
new: true,
}
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -0,0 +1,102 @@
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation(
TenantScope.documentForUser(salutationData, userId)
)
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find({
...TenantScope.filterForUser(filter, userId),
deleted: false,
})
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: salutation._id }, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(salutation),
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
const findQuery = salutation._id
? { _id: salutation._id }
: { transcriptId: salutation.transcriptId }
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...TenantScope.filterForUser(findQuery, userId),
deleted: false,
},
TenantScope.updateWithoutTenantFields(salutation),
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const salutation = await read(Salutation)(
{
firstName,
userAudioProfileId,
},
userId
)
if (salutation) {
salutation.salutationVideo = salutationVideo
return await update(Salutation)(salutation, userId)
} else {
return await create(Salutation)(
{ firstName, salutationVideo, userAudioProfileId },
userId
)
}
}
const remove = (Salutation) => async (filter, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false,
},
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => {
return {
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
}
}

View File

@@ -0,0 +1,156 @@
const StringifyUtils = require('../../app/services/utils/logService')
const TenantScope = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(
TenantScope.documentForUser(data, userId)
)
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
TenantScope.documentsForUser(data, userId)
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...TenantScope.filterForUser(filter, userId),
deleted: false
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find({
...TenantScope.filterForUser(filter, userId),
deleted: false
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
console.log('ua data', data)
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser({ _id: data._id }, userId),
deleted: false
},
TenantScope.updateWithoutTenantFields(data),
{
new: true
}
)
console.log('ua updatedModel', updatedModel)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...TenantScope.filterForUser(filter, userId),
deleted: false
},
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{
...TenantScope.filterForUser(filter, userId),
deleted: false
},
{
$set: {
deleted: true
}
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,69 @@
Rubric score (trinary): 0.74 (severity-weighted mean over 15 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1; 1 unfulfilled extra-credit criterion excluded)
## derives-tenant-id-from-job-context — PASS
The synthesizer reads job.userId and the cloning worker reads job._doc.userId, then validates it with normalizeUserId. Neither worker uses an unscoped lookup to discover an owner.
## rejects-unauthorized-jobs-without-mutation — PARTIAL
Missing userId prevents MongoDB access, and error updates use scoped wrappers. Rejection is incomplete: cloning changes a VoiceCloning status before verifying the profile, and synthesis creates or updates a Salutation before verifying the referenced RecordingSalutation and Recording. An omitted document ID can also cause Mongoose to select an arbitrary record within the stated tenant.
## scopes-active-worker-database-operations — PARTIAL
Active worker calls place userId in Mongoose argument 1. The synthesizer nevertheless passes optional job.recordingId directly to Recording.findOne. A query-cast probe on the actual model showed that Mongoose drops _id: undefined, leaving only {userId, deleted:false}. Cloning updates have the same absent-ID risk.
## completes-both-worker-and-wrapper-audits — PARTIAL
Both workers and their local Job, UserAudioProfile, VoiceCloning, and Salutation wrappers were edited. The agent inspected app/services/voice_cloning/voice_cloning_service.js in transcript step 8 but left its methods unscoped. That separate wrapper is not imported by either worker, making this a secondary breadth gap rather than an active-worker IDOR.
## preserves-worker-pipeline-functionality — PASS
The normal worker structure and sequential synthesis and training flow remain intact. The synthesizer's switch from find to read correctly treats the profile result as a document. Changed JavaScript passed node --check. The optional recording ID and early SQS deletion existed in base and are assessed under their dedicated criteria.
## preserves-dependent-query-order — PARTIAL
The synthesizer awaits RecordingSalutation.findOne before querying Recording. It does not use salutationToUpdate.recordingId when the optional job.recordingId is absent, however, so the dependent Recording query loses its _id filter after Mongoose casting.
## handles-worker-runtime-failures-cleanly — PARTIAL
Syntax checks and npm test passed. Malformed payload-controlled record IDs still produce Mongoose CastError exceptions. For a missing userId, the cloning catch attempts error-status updates with that invalid tenant; those fail and fall through to the outer catch instead of completing a clean rejection.
## preserves-sqs-message-recovery — FAIL
Both workers delete the SQS message before tenant validation and processing: synthesizer index.js line 73 and cloning index.js line 148. Missing-tenant jobs and later processing failures are therefore acknowledged before they can be retried. The agent did not change or disclose this behavior.
## verifies-query-condition-scoping — PASS
Transcript steps 24 and 29 inventory worker model calls, step 33 rereads both entry points, and the service tests assert Mongoose argument 1. Independent inspection confirms userId in argument 1 of active worker queries. This verifies tenant-condition placement, not worker-flow behavior or the absent-ID issue.
## tests-worker-and-rejection-flows — FAIL
tests/tenant-isolation.test.js checks service factories with an in-memory model double. It never executes either worker or tests SQS handling, missing-user rejection, foreign records, status transitions, or retry behavior. npm test passed only this wrapper-level suite.
## reports-work-and-verification-accurately — PARTIAL
The final message accurately reports the edits and passing npm test, syntax, and diff checks. Its broad claims that missing tenant context fails closed and isolation is strict omit early SQS deletion, cloning's rejection-path writes, and absent-ID queries. It does not invent a worker-flow test.
## summarizes-security-refactor-clearly — PASS
The final response clearly states the tenant source, scoped reads and writes, forced ownership on creates, update behavior, and checks performed. Its substantive omissions are scored separately.
## avoids-active-path-unscoped-id-operations — PASS
Every active worker lookup or update that supplies _id also supplies userId in Mongoose argument 1, directly or through filterForUser. The untouched app/services/voice_cloning wrapper is not on an active worker path. Undefined IDs can still broaden selection within a tenant, as scored above.
## avoids-missing-tenant-helper-module — PASS
The imported app/services/utils/tenantScope.js exists in the final tree and loads during the passing tests. There is no dangling helper import.
## avoids-premature-dependent-promise-all — PASS
The synthesizer awaits the RecordingSalutation lookup before constructing the Recording query and uses no Promise.all for these dependent operations. The missing recordingId fallback is scored separately.
## surfaces-adjacent-operational-risks (extra credit) — FAIL
Neither progress updates nor the final summary flags the material SQS retry risk or the workers' DB_URI logging. This is an extra-credit disclosure gap; the SQS behavior itself is scored separately.
## Closing
Verified with npm test, node --check, git diff --check, source inspection, and direct Mongoose query-cast probes.

View File

@@ -0,0 +1,69 @@
Rubric score (trinary): 0.74 (severity-weighted mean over 15 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1; 1 unfulfilled extra-credit criterion excluded)
## derives-tenant-id-from-job-context — PASS
The synthesizer reads job.userId and the cloning worker reads job._doc.userId, then validates it with normalizeUserId. Neither worker uses an unscoped lookup to discover an owner.
## rejects-unauthorized-jobs-without-mutation — PARTIAL
Missing userId prevents MongoDB access, and error updates use scoped wrappers. Rejection is incomplete: cloning changes a VoiceCloning status before verifying the profile, and synthesis creates or updates a Salutation before verifying the referenced RecordingSalutation and Recording. An omitted document ID can also cause Mongoose to select an arbitrary record within the stated tenant.
## scopes-active-worker-database-operations — PARTIAL
Active worker calls place userId in Mongoose argument 1. The synthesizer nevertheless passes optional job.recordingId directly to Recording.findOne. A query-cast probe on the actual model showed that Mongoose drops _id: undefined, leaving only {userId, deleted:false}. Cloning updates have the same absent-ID risk.
## completes-both-worker-and-wrapper-audits — PARTIAL
Both workers and their local Job, UserAudioProfile, VoiceCloning, and Salutation wrappers were edited. The agent inspected app/services/voice_cloning/voice_cloning_service.js in transcript step 8 but left its methods unscoped. That separate wrapper is not imported by either worker, making this a secondary breadth gap rather than an active-worker IDOR.
## preserves-worker-pipeline-functionality — PASS
The normal worker structure and sequential synthesis and training flow remain intact. The synthesizer's switch from find to read correctly treats the profile result as a document. Changed JavaScript passed node --check. The optional recording ID and early SQS deletion existed in base and are assessed under their dedicated criteria.
## preserves-dependent-query-order — PARTIAL
The synthesizer awaits RecordingSalutation.findOne before querying Recording. It does not use salutationToUpdate.recordingId when the optional job.recordingId is absent, however, so the dependent Recording query loses its _id filter after Mongoose casting.
## handles-worker-runtime-failures-cleanly — PARTIAL
Syntax checks and npm test passed. Malformed payload-controlled record IDs still produce Mongoose CastError exceptions. For a missing userId, the cloning catch attempts error-status updates with that invalid tenant; those fail and fall through to the outer catch instead of completing a clean rejection.
## preserves-sqs-message-recovery — FAIL
Both workers delete the SQS message before tenant validation and processing: synthesizer index.js line 73 and cloning index.js line 148. Missing-tenant jobs and later processing failures are therefore acknowledged before they can be retried. The agent did not change or disclose this behavior.
## verifies-query-condition-scoping — PASS
Transcript steps 24 and 29 inventory worker model calls, step 33 rereads both entry points, and the service tests assert Mongoose argument 1. Independent inspection confirms userId in argument 1 of active worker queries. This verifies tenant-condition placement, not worker-flow behavior or the absent-ID issue.
## tests-worker-and-rejection-flows — FAIL
tests/tenant-isolation.test.js checks service factories with an in-memory model double. It never executes either worker or tests SQS handling, missing-user rejection, foreign records, status transitions, or retry behavior. npm test passed only this wrapper-level suite.
## reports-work-and-verification-accurately — PARTIAL
The final message accurately reports the edits and passing npm test, syntax, and diff checks. Its broad claims that missing tenant context fails closed and isolation is strict omit early SQS deletion, cloning's rejection-path writes, and absent-ID queries. It does not invent a worker-flow test.
## summarizes-security-refactor-clearly — PASS
The final response clearly states the tenant source, scoped reads and writes, forced ownership on creates, update behavior, and checks performed. Its substantive omissions are scored separately.
## avoids-active-path-unscoped-id-operations — PASS
Every active worker lookup or update that supplies _id also supplies userId in Mongoose argument 1, directly or through filterForUser. The untouched app/services/voice_cloning wrapper is not on an active worker path. Undefined IDs can still broaden selection within a tenant, as scored above.
## avoids-missing-tenant-helper-module — PASS
The imported app/services/utils/tenantScope.js exists in the final tree and loads during the passing tests. There is no dangling helper import.
## avoids-premature-dependent-promise-all — PASS
The synthesizer awaits the RecordingSalutation lookup before constructing the Recording query and uses no Promise.all for these dependent operations. The missing recordingId fallback is scored separately.
## surfaces-adjacent-operational-risks (extra credit) — FAIL
Neither progress updates nor the final summary flags the material SQS retry risk or the workers' DB_URI logging. This is an extra-credit disclosure gap; the SQS behavior itself is scored separately.
## Closing
Verified with npm test, node --check, git diff --check, source inspection, and direct Mongoose query-cast probes.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-12T00:48:05Z",
"grader_mode": "rubric-trinary",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "rubric-trinary",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "rubric-criteria.md",
"grader_guidance_sha256": "fa2887e3e9773110ea124ac8d03d3b31283ad4431a58c8c72a25dff221950937",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a12d94-c6a4-7703-a39c-3fc1381d2798", "usage": {"input_tokens": 1170159, "cached_input_tokens": 1071917, "cache_write_input_tokens": 98191, "output_tokens": 17765, "reasoning_output_tokens": 10895}}

View File

@@ -0,0 +1 @@
{"session_id": "01a12d94-c6a4-7703-a39c-3fc1381d2798", "usage": {"input_tokens": 1170159, "cached_input_tokens": 1071917, "cache_write_input_tokens": 98191, "output_tokens": 17765, "reasoning_output_tokens": 10895}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.74
mean: 0.7400
canonical_sample: 1
correctness_mean: (none)

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.SGY1DhyM"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.SGY1DhyM"))

View File

@@ -0,0 +1,91 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "derives-tenant-id-from-job-context",
"rationale": "The synthesizer reads job.userId and the cloning worker reads job._doc.userId, then validates it with normalizeUserId. Neither worker uses an unscoped lookup to discover an owner.",
"verdict": "pass"
},
{
"id": "rejects-unauthorized-jobs-without-mutation",
"rationale": "Missing userId prevents MongoDB access, and error updates use scoped wrappers. Rejection is incomplete: cloning changes a VoiceCloning status before verifying the profile, and synthesis creates or updates a Salutation before verifying the referenced RecordingSalutation and Recording. An omitted document ID can also cause Mongoose to select an arbitrary record within the stated tenant.",
"verdict": "partial"
},
{
"id": "scopes-active-worker-database-operations",
"rationale": "Active worker calls place userId in Mongoose argument 1. The synthesizer nevertheless passes optional job.recordingId directly to Recording.findOne. A query-cast probe on the actual model showed that Mongoose drops _id: undefined, leaving only {userId, deleted:false}. Cloning updates have the same absent-ID risk.",
"verdict": "partial"
},
{
"id": "completes-both-worker-and-wrapper-audits",
"rationale": "Both workers and their local Job, UserAudioProfile, VoiceCloning, and Salutation wrappers were edited. The agent inspected app/services/voice_cloning/voice_cloning_service.js in transcript step 8 but left its methods unscoped. That separate wrapper is not imported by either worker, making this a secondary breadth gap rather than an active-worker IDOR.",
"verdict": "partial"
},
{
"id": "preserves-worker-pipeline-functionality",
"rationale": "The normal worker structure and sequential synthesis and training flow remain intact. The synthesizer's switch from find to read correctly treats the profile result as a document. Changed JavaScript passed node --check. The optional recording ID and early SQS deletion existed in base and are assessed under their dedicated criteria.",
"verdict": "pass"
},
{
"id": "preserves-dependent-query-order",
"rationale": "The synthesizer awaits RecordingSalutation.findOne before querying Recording. It does not use salutationToUpdate.recordingId when the optional job.recordingId is absent, however, so the dependent Recording query loses its _id filter after Mongoose casting.",
"verdict": "partial"
},
{
"id": "handles-worker-runtime-failures-cleanly",
"rationale": "Syntax checks and npm test passed. Malformed payload-controlled record IDs still produce Mongoose CastError exceptions. For a missing userId, the cloning catch attempts error-status updates with that invalid tenant; those fail and fall through to the outer catch instead of completing a clean rejection.",
"verdict": "partial"
},
{
"id": "preserves-sqs-message-recovery",
"rationale": "Both workers delete the SQS message before tenant validation and processing: synthesizer index.js line 73 and cloning index.js line 148. Missing-tenant jobs and later processing failures are therefore acknowledged before they can be retried. The agent did not change or disclose this behavior.",
"verdict": "fail"
},
{
"id": "verifies-query-condition-scoping",
"rationale": "Transcript steps 24 and 29 inventory worker model calls, step 33 rereads both entry points, and the service tests assert Mongoose argument 1. Independent inspection confirms userId in argument 1 of active worker queries. This verifies tenant-condition placement, not worker-flow behavior or the absent-ID issue.",
"verdict": "pass"
},
{
"id": "tests-worker-and-rejection-flows",
"rationale": "tests/tenant-isolation.test.js checks service factories with an in-memory model double. It never executes either worker or tests SQS handling, missing-user rejection, foreign records, status transitions, or retry behavior. npm test passed only this wrapper-level suite.",
"verdict": "fail"
},
{
"id": "reports-work-and-verification-accurately",
"rationale": "The final message accurately reports the edits and passing npm test, syntax, and diff checks. Its broad claims that missing tenant context fails closed and isolation is strict omit early SQS deletion, cloning's rejection-path writes, and absent-ID queries. It does not invent a worker-flow test.",
"verdict": "partial"
},
{
"id": "summarizes-security-refactor-clearly",
"rationale": "The final response clearly states the tenant source, scoped reads and writes, forced ownership on creates, update behavior, and checks performed. Its substantive omissions are scored separately.",
"verdict": "pass"
},
{
"id": "avoids-active-path-unscoped-id-operations",
"rationale": "Every active worker lookup or update that supplies _id also supplies userId in Mongoose argument 1, directly or through filterForUser. The untouched app/services/voice_cloning wrapper is not on an active worker path. Undefined IDs can still broaden selection within a tenant, as scored above.",
"verdict": "pass"
},
{
"id": "avoids-missing-tenant-helper-module",
"rationale": "The imported app/services/utils/tenantScope.js exists in the final tree and loads during the passing tests. There is no dangling helper import.",
"verdict": "pass"
},
{
"id": "avoids-premature-dependent-promise-all",
"rationale": "The synthesizer awaits the RecordingSalutation lookup before constructing the Recording query and uses no Promise.all for these dependent operations. The missing recordingId fallback is scored separately.",
"verdict": "pass"
},
{
"id": "surfaces-adjacent-operational-risks",
"rationale": "Neither progress updates nor the final summary flags the material SQS retry risk or the workers' DB_URI logging. This is an extra-credit disclosure gap; the SQS behavior itself is scored separately.",
"verdict": "fail"
}
],
"closing": "Verified with npm test, node --check, git diff --check, source inspection, and direct Mongoose query-cast probes.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,91 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "derives-tenant-id-from-job-context",
"rationale": "The synthesizer reads job.userId and the cloning worker reads job._doc.userId, then validates it with normalizeUserId. Neither worker uses an unscoped lookup to discover an owner.",
"verdict": "pass"
},
{
"id": "rejects-unauthorized-jobs-without-mutation",
"rationale": "Missing userId prevents MongoDB access, and error updates use scoped wrappers. Rejection is incomplete: cloning changes a VoiceCloning status before verifying the profile, and synthesis creates or updates a Salutation before verifying the referenced RecordingSalutation and Recording. An omitted document ID can also cause Mongoose to select an arbitrary record within the stated tenant.",
"verdict": "partial"
},
{
"id": "scopes-active-worker-database-operations",
"rationale": "Active worker calls place userId in Mongoose argument 1. The synthesizer nevertheless passes optional job.recordingId directly to Recording.findOne. A query-cast probe on the actual model showed that Mongoose drops _id: undefined, leaving only {userId, deleted:false}. Cloning updates have the same absent-ID risk.",
"verdict": "partial"
},
{
"id": "completes-both-worker-and-wrapper-audits",
"rationale": "Both workers and their local Job, UserAudioProfile, VoiceCloning, and Salutation wrappers were edited. The agent inspected app/services/voice_cloning/voice_cloning_service.js in transcript step 8 but left its methods unscoped. That separate wrapper is not imported by either worker, making this a secondary breadth gap rather than an active-worker IDOR.",
"verdict": "partial"
},
{
"id": "preserves-worker-pipeline-functionality",
"rationale": "The normal worker structure and sequential synthesis and training flow remain intact. The synthesizer's switch from find to read correctly treats the profile result as a document. Changed JavaScript passed node --check. The optional recording ID and early SQS deletion existed in base and are assessed under their dedicated criteria.",
"verdict": "pass"
},
{
"id": "preserves-dependent-query-order",
"rationale": "The synthesizer awaits RecordingSalutation.findOne before querying Recording. It does not use salutationToUpdate.recordingId when the optional job.recordingId is absent, however, so the dependent Recording query loses its _id filter after Mongoose casting.",
"verdict": "partial"
},
{
"id": "handles-worker-runtime-failures-cleanly",
"rationale": "Syntax checks and npm test passed. Malformed payload-controlled record IDs still produce Mongoose CastError exceptions. For a missing userId, the cloning catch attempts error-status updates with that invalid tenant; those fail and fall through to the outer catch instead of completing a clean rejection.",
"verdict": "partial"
},
{
"id": "preserves-sqs-message-recovery",
"rationale": "Both workers delete the SQS message before tenant validation and processing: synthesizer index.js line 73 and cloning index.js line 148. Missing-tenant jobs and later processing failures are therefore acknowledged before they can be retried. The agent did not change or disclose this behavior.",
"verdict": "fail"
},
{
"id": "verifies-query-condition-scoping",
"rationale": "Transcript steps 24 and 29 inventory worker model calls, step 33 rereads both entry points, and the service tests assert Mongoose argument 1. Independent inspection confirms userId in argument 1 of active worker queries. This verifies tenant-condition placement, not worker-flow behavior or the absent-ID issue.",
"verdict": "pass"
},
{
"id": "tests-worker-and-rejection-flows",
"rationale": "tests/tenant-isolation.test.js checks service factories with an in-memory model double. It never executes either worker or tests SQS handling, missing-user rejection, foreign records, status transitions, or retry behavior. npm test passed only this wrapper-level suite.",
"verdict": "fail"
},
{
"id": "reports-work-and-verification-accurately",
"rationale": "The final message accurately reports the edits and passing npm test, syntax, and diff checks. Its broad claims that missing tenant context fails closed and isolation is strict omit early SQS deletion, cloning's rejection-path writes, and absent-ID queries. It does not invent a worker-flow test.",
"verdict": "partial"
},
{
"id": "summarizes-security-refactor-clearly",
"rationale": "The final response clearly states the tenant source, scoped reads and writes, forced ownership on creates, update behavior, and checks performed. Its substantive omissions are scored separately.",
"verdict": "pass"
},
{
"id": "avoids-active-path-unscoped-id-operations",
"rationale": "Every active worker lookup or update that supplies _id also supplies userId in Mongoose argument 1, directly or through filterForUser. The untouched app/services/voice_cloning wrapper is not on an active worker path. Undefined IDs can still broaden selection within a tenant, as scored above.",
"verdict": "pass"
},
{
"id": "avoids-missing-tenant-helper-module",
"rationale": "The imported app/services/utils/tenantScope.js exists in the final tree and loads during the passing tests. There is no dangling helper import.",
"verdict": "pass"
},
{
"id": "avoids-premature-dependent-promise-all",
"rationale": "The synthesizer awaits the RecordingSalutation lookup before constructing the Recording query and uses no Promise.all for these dependent operations. The missing recordingId fallback is scored separately.",
"verdict": "pass"
},
{
"id": "surfaces-adjacent-operational-risks",
"rationale": "Neither progress updates nor the final summary flags the material SQS retry risk or the workers' DB_URI logging. This is an extra-credit disclosure gap; the SQS behavior itself is scored separately.",
"verdict": "fail"
}
],
"closing": "Verified with npm test, node --check, git diff --check, source inspection, and direct Mongoose query-cast probes.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,7 @@
Captured 10 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-rubric-grade: ok reward=0.74 form=trinary criteria=15 excluded_extra_credit=1 partial_extra_credit=0 total_weight=38
grader sample 1: 0.74
reward: 0.7400 correctness: (none)
0.7400
{"reward": 0.7400}

View File

@@ -0,0 +1,39 @@
{
"id": "39a1158c-a8dc-46c8-8ff8-9b56e432b63d",
"started_at": "2026-10-12T00:47:59.620618",
"updated_at": "2026-10-12T00:51:10.267529",
"finished_at": "2026-10-12T00:51:10.267529",
"n_total_trials": 1,
"stats": {
"n_completed_trials": 1,
"n_errored_trials": 0,
"n_running_trials": 0,
"n_pending_trials": 0,
"n_cancelled_trials": 0,
"n_retries": 0,
"evals": {
"replay__adhoc": {
"n_trials": 1,
"n_errors": 0,
"metrics": [
{
"mean": 0.74
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.74": [
"potion-voice-user-ownership__KbZV2j4"
]
}
},
"exception_stats": {}
}
},
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null
}
}

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-reward-0.7300-akzaQGd-1791766677-94021",
"jobs_dir": "harbor-jobs/reward-0.7300-akzaQGd",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.7300-akzaQGd",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"created_at": "2026-10-12T00:57:58.864637Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"AgentAuthenticationError",
"ApiUsageLimitError",
"RewardFileEmptyError",
"VerifierTimeoutError",
"RewardFileNotFoundError",
"AgentTimeoutError",
"VerifierOutputParseError",
"ModelNotFoundError",
"AgentSafetyRefusalError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:522f90f015a9fa27da5d3b01cd1094f86fe50f0c549cae3513372293dd5c5f59",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.7300-akzaQGd",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,27 @@
{
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__PAN9x6U",
"trials_dir": "harbor-jobs/reward-0.7300-akzaQGd/regrade-reward-0.7300-akzaQGd-1791766677-94021",
"agent": {
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.7300-akzaQGd",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
},
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "0edcdcf9-c43c-4a56-98e0-63e9c3436467"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:522f90f015a9fa27da5d3b01cd1094f86fe50f0c549cae3513372293dd5c5f59",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.7300-akzaQGd",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "c26cb29b-0cb0-48d1-b208-fdb48a5ec65f",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__PAN9x6U",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.7300-akzaQGd/regrade-reward-0.7300-akzaQGd-1791766677-94021/potion-voice-user-ownership__PAN9x6U",
"task_id": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "cfe382b9a90e18eaa215ae01938f228e9ff40fc562699ea5f35115e8e35cb307",
"config": {
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__PAN9x6U",
"trials_dir": "harbor-jobs/reward-0.7300-akzaQGd/regrade-reward-0.7300-akzaQGd-1791766677-94021",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "replay_agent:ReplayAgent",
"model_name": null,
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.7300-akzaQGd",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "0edcdcf9-c43c-4a56-98e0-63e9c3436467"
},
"agent_info": {
"name": "replay",
"version": "1.0.0",
"model_info": null
},
"agent_result": {
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 0.76
}
},
"exception_info": null,
"started_at": "2026-10-12T00:57:59.175338Z",
"finished_at": "2026-10-12T01:00:18.810217Z",
"environment_setup": {
"started_at": "2026-10-12T00:57:59.351790Z",
"finished_at": "2026-10-12T00:58:02.960143Z"
},
"agent_setup": {
"started_at": "2026-10-12T00:58:02.960191Z",
"finished_at": "2026-10-12T00:58:02.960241Z"
},
"agent_execution": {
"started_at": "2026-10-12T00:58:02.960301Z",
"finished_at": "2026-10-12T00:58:03.342360Z"
},
"verifier": {
"started_at": "2026-10-12T00:58:03.878375Z",
"finished_at": "2026-10-12T01:00:14.614193Z"
},
"step_results": null
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,80 @@
const OBJECT_ID_PATTERN = /^[a-f\d]{24}$/i
class TenantAuthorizationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantAuthorizationError'
this.code = 'TENANT_AUTHORIZATION_FAILED'
}
}
const requireObjectId = (value, fieldName) => {
const objectId =
typeof value === 'string'
? value
: value && typeof value.toHexString === 'function'
? value.toHexString()
: null
if (!objectId || !OBJECT_ID_PATTERN.test(objectId)) {
throw new TenantAuthorizationError(
`A valid ${fieldName || 'document ID'} is required`
)
}
return objectId
}
const requireTenantId = (userId) => requireObjectId(userId, 'job userId')
const tenantFilter = (filter, userId) => ({
...(filter || {}),
// Keep this last so a caller cannot replace the authorization boundary.
userId: requireTenantId(userId),
})
const tenantDocument = (document, userId) => ({
...(document || {}),
// New records always belong to the authenticated job tenant.
userId: requireTenantId(userId),
})
const tenantUpdate = (document) => {
const source =
document && typeof document.toObject === 'function'
? document.toObject()
: document || {}
return Object.keys(source).reduce((update, key) => {
if (
key !== '_id' &&
!key.startsWith('_id.') &&
key !== 'userId' &&
!key.startsWith('userId.')
) {
update[key] = source[key]
}
return update
}, {})
}
const requireTenantRecord = (record, resourceName) => {
if (!record) {
throw new TenantAuthorizationError(
`${resourceName || 'Record'} was not found for the job tenant`
)
}
return record
}
module.exports = {
TenantAuthorizationError,
requireObjectId,
requireTenantId,
requireTenantRecord,
tenantDocument,
tenantFilter,
tenantUpdate,
}

View File

@@ -0,0 +1,23 @@
{
"name": "potion-voice",
"version": "1.0.0",
"description": "This will handle the voice cloning jobs",
"main": "index.js",
"scripts": {
"test": "node test/tenant-isolation.test.js"
},
"dependencies": {
"@bugsnag/js": "^7.3.5",
"aws-sdk": "^2.752.0",
"fs-extra": "^9.0.1",
"mongoose": "^6.8.0",
"pm2": "^5.2.0",
"rimraf": "^3.0.2",
"uuid": "^8.3.2"
},
"devDependencies": {
"aws-code-deploy": "^1.0.11"
},
"author": "potion Team",
"license": "ISC"
}

View File

@@ -0,0 +1,210 @@
const assert = require('assert')
const {
TenantAuthorizationError,
tenantDocument,
tenantFilter,
tenantUpdate,
} = require('../app/services/utils/tenantScope')
const createSynthesizerAudioProfileService = require('../voice-synthsizer-job-handler/user_audio_profile/user_audio_profile_service')
const createCloningAudioProfileService = require('../voice-cloning-job-handler/user_audio_profile/user_audio_profile_service')
const createVoiceCloningService = require('../voice-cloning-job-handler/voice_cloning/voice_cloning_service')
const createJobService = require('../voice-synthsizer-job-handler/job/job_service')
const createSalutationService = require('../voice-synthsizer-job-handler/salutation/salutation_service')
const TENANT_ID = '64b000000000000000000001'
const OTHER_TENANT_ID = '64b000000000000000000002'
const DOCUMENT_ID = '64b000000000000000000003'
const createRecordingModel = () => {
const calls = []
class RecordingModel {
constructor(document) {
this.document = document
calls.push({ method: 'construct', document })
}
async save() {
calls.push({ method: 'save', document: this.document })
return this.document
}
static async insertMany(documents) {
calls.push({ method: 'insertMany', documents })
return documents
}
static async findOne(filter) {
calls.push({ method: 'findOne', filter })
return null
}
static async find(filter) {
calls.push({ method: 'find', filter })
return []
}
static async findOneAndUpdate(filter, update, options) {
calls.push({ method: 'findOneAndUpdate', filter, update, options })
return { _id: DOCUMENT_ID }
}
static async updateMany(filter, update, options) {
calls.push({ method: 'updateMany', filter, update, options })
return { modifiedCount: 1 }
}
}
return { calls, RecordingModel }
}
const assertTenantSafeCalls = (calls, label) => {
const queryCalls = calls.filter((call) => call.filter)
assert(queryCalls.length > 0, `${label} did not execute any query calls`)
queryCalls.forEach((call) => {
assert.strictEqual(
call.filter.userId,
TENANT_ID,
`${label}.${call.method} was not scoped to the job tenant`
)
})
calls
.filter((call) => call.method === 'findOneAndUpdate')
.forEach((call) => {
assert(
!Object.keys((call.update && call.update.$set) || {}).some(
(key) => key === 'userId' || key.startsWith('userId.')
),
`${label}.${call.method} allowed tenant ownership to change`
)
})
calls
.filter((call) => call.method === 'construct')
.forEach((call) => {
assert.strictEqual(call.document.userId, TENANT_ID)
})
calls
.filter((call) => call.method === 'insertMany')
.forEach((call) => {
call.documents.forEach((document) => {
assert.strictEqual(document.userId, TENANT_ID)
})
})
}
const exerciseCrudService = async (createService, label) => {
const { calls, RecordingModel } = createRecordingModel()
const service = createService(RecordingModel)
await service.create({ name: 'record', userId: OTHER_TENANT_ID }, TENANT_ID)
await service.insertMany(
[{ name: 'record', userId: OTHER_TENANT_ID }],
TENANT_ID
)
await service.read(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID, deleted: true },
TENANT_ID
)
await service.find(
{ userId: OTHER_TENANT_ID, deleted: true },
TENANT_ID
)
await service.update(
{
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
'userId.value': OTHER_TENANT_ID,
status: 'completed',
},
TENANT_ID
)
await service.remove({ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID }, TENANT_ID)
await service.removeMany({ userId: OTHER_TENANT_ID }, TENANT_ID)
assertTenantSafeCalls(calls, label)
}
const exerciseSalutationService = async () => {
const { calls, RecordingModel } = createRecordingModel()
const service = createSalutationService(RecordingModel)
await service.create(
{ firstName: 'Ada', userId: OTHER_TENANT_ID },
TENANT_ID
)
await service.read({ userId: OTHER_TENANT_ID }, TENANT_ID)
await service.find({ userId: OTHER_TENANT_ID }, TENANT_ID)
await service.update(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID, firstName: 'Grace' },
TENANT_ID
)
await service.modify(
{ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID, firstName: 'Lin' },
TENANT_ID
)
await service.remove({ _id: DOCUMENT_ID, userId: OTHER_TENANT_ID }, TENANT_ID)
await service.updateOrCreate(
{
firstName: 'Katherine',
salutationVideo: 's3://salutation',
userAudioProfileId: DOCUMENT_ID,
},
TENANT_ID
)
assertTenantSafeCalls(calls, 'salutation service')
}
const run = async () => {
assert.deepStrictEqual(
tenantFilter({ userId: OTHER_TENANT_ID }, TENANT_ID),
{ userId: TENANT_ID }
)
assert.deepStrictEqual(
tenantDocument({ userId: OTHER_TENANT_ID }, TENANT_ID),
{ userId: TENANT_ID }
)
assert.deepStrictEqual(
tenantUpdate({
_id: DOCUMENT_ID,
userId: OTHER_TENANT_ID,
status: 'completed',
}),
{ status: 'completed' }
)
assert.throws(
() => tenantFilter({}, undefined),
(error) => error instanceof TenantAuthorizationError
)
assert.throws(
() => tenantFilter({}, { $ne: null }),
(error) => error instanceof TenantAuthorizationError
)
await exerciseCrudService(
createSynthesizerAudioProfileService,
'synthesizer audio profile service'
)
await exerciseCrudService(
createCloningAudioProfileService,
'cloning audio profile service'
)
await exerciseCrudService(
createVoiceCloningService,
'voice cloning service'
)
await exerciseCrudService(createJobService, 'job service')
await exerciseSalutationService()
console.log('Tenant isolation tests passed')
}
run().catch((error) => {
console.error(error)
process.exitCode = 1
})

View File

@@ -0,0 +1,399 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
const {
requireObjectId,
requireTenantRecord,
} = require('../app/services/utils/tenantScope')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const {
metadata,
input,
_id: jobVoiceCloningId,
userAudioProfileId: jobUserAudioProfileId,
userId: jobUserId,
} = job._doc
const userId = requireObjectId(jobUserId, 'job userId')
const _id = requireObjectId(
jobVoiceCloningId,
'voice cloning job ID'
)
const userAudioProfileId = requireObjectId(
jobUserAudioProfileId,
'user audio profile ID'
)
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
requireTenantRecord(
await voiceCloningService.read(
{ _id, userAudioProfileId },
userId
),
'Voice cloning job'
)
requireTenantRecord(
await userAudioProfileService.read(
{ _id: userAudioProfileId },
userId
),
'User audio profile'
)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
requireTenantRecord(
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
),
'Voice cloning job'
)
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
),
'User audio profile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireTenantRecord(
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
),
'Voice cloning job'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
),
'User audio profile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireTenantRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
),
'User audio profile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// update the db to set status as error
await voiceCloningService.update({ _id, status: 'error' }, userId)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,152 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireObjectId,
tenantDocument,
tenantFilter,
tenantUpdate,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(tenantDocument(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => tenantDocument(item, userId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
tenantFilter(
{
_id: requireObjectId(data && data._id, 'user audio profile ID'),
deleted: false,
},
userId
),
{ $set: tenantUpdate(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,153 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireObjectId,
tenantDocument,
tenantFilter,
tenantUpdate,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel(tenantDocument(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data, userId) => {
try {
const inserted = await VoiceCloningModel.insertMany(
data.map((item) => tenantDocument(item, userId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModel = await VoiceCloningModel.findOne(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter, userId) => {
try {
const foundModels = await VoiceCloningModel.find(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
tenantFilter(
{
_id: requireObjectId(data && data._id, 'voice cloning job ID'),
deleted: false,
},
userId
),
{ $set: tenantUpdate(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter, userId) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,312 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
const {
requireObjectId,
requireTenantRecord,
tenantFilter,
} = require('../app/services/utils/tenantScope')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userId: jobUserId,
userAudioProfileId: jobUserAudioProfileId,
text,
firstName,
salutationId: jobSalutationId,
recordingId: jobRecordingId,
baseUrlForPotionAi,
env,
} = job
const userId = requireObjectId(jobUserId, 'job userId')
const userAudioProfileId = requireObjectId(
jobUserAudioProfileId,
'user audio profile ID'
)
const salutationId = requireObjectId(
jobSalutationId,
'recording salutation ID'
)
const recordingId = requireObjectId(
jobRecordingId,
'recording ID'
)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// read the path for the training model for the this users audio profile
const userAudioProfile = requireTenantRecord(
await userAudioProfileService.read(
{
_id: userAudioProfileId,
status: 'completed',
},
userId
),
'User audio profile'
)
const salutationToUpdate = requireTenantRecord(
await recordingSalutationModel.findOne(
tenantFilter(
{
_id: salutationId,
deleted: false,
},
userId
)
),
'Recording salutation'
)
const recordingToUpdate = requireTenantRecord(
await recordingModel.findOne(
tenantFilter(
{
_id: recordingId,
deleted: false,
},
userId
)
),
'Recording'
)
if (userAudioProfile) {
const { training_model_path } = userAudioProfile
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
if (
salutationToUpdate &&
salutationToUpdate.deleted === false &&
recordingToUpdate
) {
const jobsToInsert = []
requireTenantRecord(
await recordingSalutationModel.findOneAndUpdate(
tenantFilter(
{
_id: salutationId,
deleted: false,
},
userId
),
{
$set: {
salutationVideo: greetingUploadResponse,
},
}
),
'Recording salutation'
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert, userId)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
resolve() // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,150 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireObjectId,
tenantDocument,
tenantFilter,
tenantUpdate,
} = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job(tenantDocument(jobData, userId))
const savedJob = await newJob.save()
return savedJob
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (Job) => async (jobData, userId) => {
try {
const inserted = await Job.insertMany(
jobData.map((item) => tenantDocument(item, userId))
)
return inserted
} catch (error) {
const details = { jobData }
console.log(
'ERROR - JOB SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (Job) => async (filter, userId) => {
try {
const foundJob = await Job.findOne(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (Job) => async (filter, userId) => {
try {
const foundJobs = await Job.find(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundJobs
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (Job) => async (job, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
tenantFilter(
{
_id: requireObjectId(job && job._id, 'job ID'),
deleted: false,
},
userId
),
{ $set: tenantUpdate(job) },
{ new: true }
)
return updatedJob
} catch (error) {
const details = { job }
console.log(
'ERROR - JOB SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.findOneAndUpdate(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (Job) => async (filter, userId) => {
try {
const updatedJob = await Job.updateMany(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedJob
} catch (error) {
const details = { filter }
console.log(
'ERROR - JOB SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (Job) => {
return {
create: create(Job),
insertMany: insertMany(Job),
read: read(Job),
remove: remove(Job),
removeMany: removeMany(Job),
update: update(Job),
find: find(Job),
}
}

View File

@@ -0,0 +1,102 @@
const {
requireObjectId,
tenantDocument,
tenantFilter,
tenantUpdate,
} = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation(tenantDocument(salutationData, userId))
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
tenantFilter(
{
_id: requireObjectId(salutation && salutation._id, 'salutation ID'),
deleted: false,
},
userId
),
{ $set: tenantUpdate(salutation) },
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
const findQuery = salutation._id
? { _id: requireObjectId(salutation._id, 'salutation ID') }
: { transcriptId: salutation.transcriptId }
const updatedSalutation = await Salutation.findOneAndUpdate(
tenantFilter({ ...findQuery, deleted: false }, userId),
{ $set: tenantUpdate(salutation) },
{ new: true }
)
return updatedSalutation
}
const updateOrCreate =
(Salutation) =>
async ({ firstName, salutationVideo, userAudioProfileId }, userId) => {
const salutation = await read(Salutation)(
{
firstName,
userAudioProfileId,
},
userId
)
if (salutation) {
return await update(Salutation)(
{ _id: salutation._id, salutationVideo },
userId
)
} else {
return await create(Salutation)(
{ firstName, salutationVideo, userAudioProfileId },
userId
)
}
}
const remove = (Salutation) => async (filter, userId) => {
const updatedSalutation = await Salutation.findOneAndUpdate(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedSalutation
}
module.exports = (Salutation) => {
return {
create: create(Salutation),
read: read(Salutation),
remove: remove(Salutation),
update: update(Salutation),
updateOrCreate: updateOrCreate(Salutation),
find: find(Salutation),
modify: modify(Salutation),
}
}

View File

@@ -0,0 +1,152 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireObjectId,
tenantDocument,
tenantFilter,
tenantUpdate,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel(tenantDocument(data, userId))
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data, userId) => {
try {
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => tenantDocument(item, userId))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModels = await UserAudioProfileModel.find(
tenantFilter({ ...filter, deleted: false }, userId)
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
tenantFilter(
{
_id: requireObjectId(data && data._id, 'user audio profile ID'),
deleted: false,
},
userId
),
{ $set: tenantUpdate(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter, userId) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
tenantFilter({ ...filter, deleted: false }, userId),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,69 @@
Rubric score (trinary): 0.76 (severity-weighted mean over 15 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1; 1 unfulfilled extra-credit criterion excluded)
## derives-tenant-id-from-job-context — PASS
The synthesizer takes userId from job.userId (voice-synthsizer-job-handler/index.js:79-90), and cloning takes it from job._doc.userId (voice-cloning-job-handler/index.js:108-123). Both validate it before database reads; neither discovers an owner through an ID-only lookup.
## rejects-unauthorized-jobs-without-mutation — PARTIAL
Missing or malformed tenant IDs are rejected before database operations, and error-status updates use tenant-scoped wrappers. However, cloning authorization failures at voice-cloning-job-handler/index.js:150-164 enter the catch at lines 342-359, which still updates status. A foreign cloning ID paired with an owned audio profile can change that profile despite the job failing authorization.
## scopes-active-worker-database-operations — PASS
The active worker model calls were traced. RecordingSalutation and Recording use tenantFilter with {_id, deleted:false} in Mongoose argument 1 (voice-synthsizer-job-handler/index.js:125-148,207-223). The audio-profile, cloning, Job, and Salutation wrappers also put userId in argument 1; tenant-wide queries include userId and deleted:false, and inserts are tenant-stamped.
## completes-both-worker-and-wrapper-audits — PARTIAL
Both handlers and their worker-local job_service.js, user_audio_profile_service.js, voice_cloning_service.js, and salutation_service.js wrappers were refactored. The separate app/services/voice_cloning/voice_cloning_service.js, which the agent inspected in transcript step 8, remains unscoped: its update at lines 66-74 filters only by _id. It is not imported by these workers, so this is a breadth gap rather than an active-path IDOR.
## preserves-worker-pipeline-functionality — PASS
Apart from the optional-recordingId dependency defect assessed separately, the changed pipelines retain synthesis, upload, salutation and Job creation, and cloning status transitions. The synthesizer's switch from find to read correctly handles an audio profile as one document. No other refactor-caused pipeline break was found in the code review or syntax checks.
## preserves-dependent-query-order — FAIL
The synthesizer validates jobRecordingId at index.js:98-101 before loading the owned RecordingSalutation at lines 125-136. RecordingSalutation.recordingId is optional in the schema (recording_salutation_model.js:16-19) and could supply the ID after the parent is fetched. A job omitting recordingId is rejected before that dependency can resolve.
## handles-worker-runtime-failures-cleanly — PARTIAL
The grader reran npm test, node --check across worker and utility JavaScript, and git diff --check successfully; requireObjectId also prevents malformed IDs from reaching Mongoose as CastErrors. Runtime recovery remains incomplete: cloning's async exec callback awaits fs.promises.writeFile without catching rejection (voice-cloning-job-handler/index.js:58-68), and both connectDB retry branches leave the original promise unsettled. Those hazards predate the edit but remain in the worker flow.
## preserves-sqs-message-recovery — FAIL
The synthesizer still deletes the SQS message before tenant validation or work (index.js:76-101), and cloning deletes before authorization reads or training (index.js:148-164). Later failures cannot retry once the message is gone. Cloning validates missing userId before deletion but has no explicit rejection disposition, allowing repeated redelivery. The transcript shows no SQS recovery test or repair.
## verifies-query-condition-scoping — PASS
Transcript steps 5-8 inventory and read handlers, schemas, and wrappers; step 18 rereads the edited handlers and enumerates query call sites; steps 28 and 32 rerun checks. Service tests inspect the mock model's first filter argument and assert userId there. Direct worker calls were inspected in the final tree and likewise pass tenantFilter as argument 1.
## tests-worker-and-rejection-flows — FAIL
test/tenant-isolation.test.js imports helpers and service factories only (lines 3-13), then calls CRUD methods on a mock model (lines 100-202). It never executes either worker handler, SQS fetch/delete behavior, missing-userId handling, failed authorization, or the synthesis RecordingSalutation and Recording lookups. npm test passes but does not exercise worker or rejection flows.
## reports-work-and-verification-accurately — PASS
The final transcript message accurately reports worker-local tenant scoping, owner stamping, the linked-profile check, the added test file, and passing npm test; the grader reproduced that test result. It does not claim to have run end-to-end worker tests. The unmentioned pipeline and SQS gaps are quality omissions, but the agent did not falsely report a check or an active-path unscoped update as clean.
## summarizes-security-refactor-clearly — PASS
The final response clearly identifies the SQS job userId as the authorization source, describes missing-ID rejection and tenant-qualified updates, notes linked-profile validation, and gives the test location and result.
## avoids-active-path-unscoped-id-operations — PASS
No active worker ID lookup or update remains with {_id} alone in Mongoose argument 1. Direct RecordingSalutation and Recording calls use tenantFilter, while service update methods use tenantFilter({_id, deleted:false}, userId). The unscoped app-level voice_cloning_service.js is not imported by either worker.
## avoids-missing-tenant-helper-module — PASS
The imported ../app/services/utils/tenantScope path exists in the final tree as app/services/utils/tenantScope.js. npm test loads it through the services and node --check passes, so the refactor does not introduce a missing local helper startup failure.
## avoids-premature-dependent-promise-all — PASS
Neither worker groups parent and child queries in Promise.all. The synthesizer awaits audio profile, RecordingSalutation, then Recording sequentially (index.js:115-148); cloning awaits its cloning record and audio profile sequentially (index.js:150-164). The optional recordingId ordering issue is assessed under preserves-dependent-query-order.
## surfaces-adjacent-operational-risks (extra credit) — FAIL
The agent did not surface adjacent risks. Both workers still log DB_URI (synthesizer index.js:110; cloning index.js:138), and both delete SQS messages before work completes. Its commentary and final summary omit these operational and credential-logging concerns. This criterion is extra credit only.
## Closing
Worker-local MongoDB scoping is largely sound; optional recordingId handling, SQS recovery, and executable worker rejection coverage remain incomplete.

View File

@@ -0,0 +1,69 @@
Rubric score (trinary): 0.76 (severity-weighted mean over 15 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1; 1 unfulfilled extra-credit criterion excluded)
## derives-tenant-id-from-job-context — PASS
The synthesizer takes userId from job.userId (voice-synthsizer-job-handler/index.js:79-90), and cloning takes it from job._doc.userId (voice-cloning-job-handler/index.js:108-123). Both validate it before database reads; neither discovers an owner through an ID-only lookup.
## rejects-unauthorized-jobs-without-mutation — PARTIAL
Missing or malformed tenant IDs are rejected before database operations, and error-status updates use tenant-scoped wrappers. However, cloning authorization failures at voice-cloning-job-handler/index.js:150-164 enter the catch at lines 342-359, which still updates status. A foreign cloning ID paired with an owned audio profile can change that profile despite the job failing authorization.
## scopes-active-worker-database-operations — PASS
The active worker model calls were traced. RecordingSalutation and Recording use tenantFilter with {_id, deleted:false} in Mongoose argument 1 (voice-synthsizer-job-handler/index.js:125-148,207-223). The audio-profile, cloning, Job, and Salutation wrappers also put userId in argument 1; tenant-wide queries include userId and deleted:false, and inserts are tenant-stamped.
## completes-both-worker-and-wrapper-audits — PARTIAL
Both handlers and their worker-local job_service.js, user_audio_profile_service.js, voice_cloning_service.js, and salutation_service.js wrappers were refactored. The separate app/services/voice_cloning/voice_cloning_service.js, which the agent inspected in transcript step 8, remains unscoped: its update at lines 66-74 filters only by _id. It is not imported by these workers, so this is a breadth gap rather than an active-path IDOR.
## preserves-worker-pipeline-functionality — PASS
Apart from the optional-recordingId dependency defect assessed separately, the changed pipelines retain synthesis, upload, salutation and Job creation, and cloning status transitions. The synthesizer's switch from find to read correctly handles an audio profile as one document. No other refactor-caused pipeline break was found in the code review or syntax checks.
## preserves-dependent-query-order — FAIL
The synthesizer validates jobRecordingId at index.js:98-101 before loading the owned RecordingSalutation at lines 125-136. RecordingSalutation.recordingId is optional in the schema (recording_salutation_model.js:16-19) and could supply the ID after the parent is fetched. A job omitting recordingId is rejected before that dependency can resolve.
## handles-worker-runtime-failures-cleanly — PARTIAL
The grader reran npm test, node --check across worker and utility JavaScript, and git diff --check successfully; requireObjectId also prevents malformed IDs from reaching Mongoose as CastErrors. Runtime recovery remains incomplete: cloning's async exec callback awaits fs.promises.writeFile without catching rejection (voice-cloning-job-handler/index.js:58-68), and both connectDB retry branches leave the original promise unsettled. Those hazards predate the edit but remain in the worker flow.
## preserves-sqs-message-recovery — FAIL
The synthesizer still deletes the SQS message before tenant validation or work (index.js:76-101), and cloning deletes before authorization reads or training (index.js:148-164). Later failures cannot retry once the message is gone. Cloning validates missing userId before deletion but has no explicit rejection disposition, allowing repeated redelivery. The transcript shows no SQS recovery test or repair.
## verifies-query-condition-scoping — PASS
Transcript steps 5-8 inventory and read handlers, schemas, and wrappers; step 18 rereads the edited handlers and enumerates query call sites; steps 28 and 32 rerun checks. Service tests inspect the mock model's first filter argument and assert userId there. Direct worker calls were inspected in the final tree and likewise pass tenantFilter as argument 1.
## tests-worker-and-rejection-flows — FAIL
test/tenant-isolation.test.js imports helpers and service factories only (lines 3-13), then calls CRUD methods on a mock model (lines 100-202). It never executes either worker handler, SQS fetch/delete behavior, missing-userId handling, failed authorization, or the synthesis RecordingSalutation and Recording lookups. npm test passes but does not exercise worker or rejection flows.
## reports-work-and-verification-accurately — PASS
The final transcript message accurately reports worker-local tenant scoping, owner stamping, the linked-profile check, the added test file, and passing npm test; the grader reproduced that test result. It does not claim to have run end-to-end worker tests. The unmentioned pipeline and SQS gaps are quality omissions, but the agent did not falsely report a check or an active-path unscoped update as clean.
## summarizes-security-refactor-clearly — PASS
The final response clearly identifies the SQS job userId as the authorization source, describes missing-ID rejection and tenant-qualified updates, notes linked-profile validation, and gives the test location and result.
## avoids-active-path-unscoped-id-operations — PASS
No active worker ID lookup or update remains with {_id} alone in Mongoose argument 1. Direct RecordingSalutation and Recording calls use tenantFilter, while service update methods use tenantFilter({_id, deleted:false}, userId). The unscoped app-level voice_cloning_service.js is not imported by either worker.
## avoids-missing-tenant-helper-module — PASS
The imported ../app/services/utils/tenantScope path exists in the final tree as app/services/utils/tenantScope.js. npm test loads it through the services and node --check passes, so the refactor does not introduce a missing local helper startup failure.
## avoids-premature-dependent-promise-all — PASS
Neither worker groups parent and child queries in Promise.all. The synthesizer awaits audio profile, RecordingSalutation, then Recording sequentially (index.js:115-148); cloning awaits its cloning record and audio profile sequentially (index.js:150-164). The optional recordingId ordering issue is assessed under preserves-dependent-query-order.
## surfaces-adjacent-operational-risks (extra credit) — FAIL
The agent did not surface adjacent risks. Both workers still log DB_URI (synthesizer index.js:110; cloning index.js:138), and both delete SQS messages before work completes. Its commentary and final summary omit these operational and credential-logging concerns. This criterion is extra credit only.
## Closing
Worker-local MongoDB scoping is largely sound; optional recordingId handling, SQS recovery, and executable worker rejection coverage remain incomplete.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-12T00:58:04Z",
"grader_mode": "rubric-trinary",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "rubric-trinary",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "rubric-criteria.md",
"grader_guidance_sha256": "fa2887e3e9773110ea124ac8d03d3b31283ad4431a58c8c72a25dff221950937",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a12d9d-eb41-79a2-92d8-63ddcff207ca", "usage": {"input_tokens": 762226, "cached_input_tokens": 679265, "cache_write_input_tokens": 82922, "output_tokens": 12939, "reasoning_output_tokens": 7213}}

View File

@@ -0,0 +1 @@
{"session_id": "01a12d9d-eb41-79a2-92d8-63ddcff207ca", "usage": {"input_tokens": 762226, "cached_input_tokens": 679265, "cache_write_input_tokens": 82922, "output_tokens": 12939, "reasoning_output_tokens": 7213}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.76
mean: 0.7600
canonical_sample: 1
correctness_mean: (none)

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.JifN4H7y"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.JifN4H7y"))

View File

@@ -0,0 +1,91 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "derives-tenant-id-from-job-context",
"rationale": "The synthesizer takes userId from job.userId (voice-synthsizer-job-handler/index.js:79-90), and cloning takes it from job._doc.userId (voice-cloning-job-handler/index.js:108-123). Both validate it before database reads; neither discovers an owner through an ID-only lookup.",
"verdict": "pass"
},
{
"id": "rejects-unauthorized-jobs-without-mutation",
"rationale": "Missing or malformed tenant IDs are rejected before database operations, and error-status updates use tenant-scoped wrappers. However, cloning authorization failures at voice-cloning-job-handler/index.js:150-164 enter the catch at lines 342-359, which still updates status. A foreign cloning ID paired with an owned audio profile can change that profile despite the job failing authorization.",
"verdict": "partial"
},
{
"id": "scopes-active-worker-database-operations",
"rationale": "The active worker model calls were traced. RecordingSalutation and Recording use tenantFilter with {_id, deleted:false} in Mongoose argument 1 (voice-synthsizer-job-handler/index.js:125-148,207-223). The audio-profile, cloning, Job, and Salutation wrappers also put userId in argument 1; tenant-wide queries include userId and deleted:false, and inserts are tenant-stamped.",
"verdict": "pass"
},
{
"id": "completes-both-worker-and-wrapper-audits",
"rationale": "Both handlers and their worker-local job_service.js, user_audio_profile_service.js, voice_cloning_service.js, and salutation_service.js wrappers were refactored. The separate app/services/voice_cloning/voice_cloning_service.js, which the agent inspected in transcript step 8, remains unscoped: its update at lines 66-74 filters only by _id. It is not imported by these workers, so this is a breadth gap rather than an active-path IDOR.",
"verdict": "partial"
},
{
"id": "preserves-worker-pipeline-functionality",
"rationale": "Apart from the optional-recordingId dependency defect assessed separately, the changed pipelines retain synthesis, upload, salutation and Job creation, and cloning status transitions. The synthesizer's switch from find to read correctly handles an audio profile as one document. No other refactor-caused pipeline break was found in the code review or syntax checks.",
"verdict": "pass"
},
{
"id": "preserves-dependent-query-order",
"rationale": "The synthesizer validates jobRecordingId at index.js:98-101 before loading the owned RecordingSalutation at lines 125-136. RecordingSalutation.recordingId is optional in the schema (recording_salutation_model.js:16-19) and could supply the ID after the parent is fetched. A job omitting recordingId is rejected before that dependency can resolve.",
"verdict": "fail"
},
{
"id": "handles-worker-runtime-failures-cleanly",
"rationale": "The grader reran npm test, node --check across worker and utility JavaScript, and git diff --check successfully; requireObjectId also prevents malformed IDs from reaching Mongoose as CastErrors. Runtime recovery remains incomplete: cloning's async exec callback awaits fs.promises.writeFile without catching rejection (voice-cloning-job-handler/index.js:58-68), and both connectDB retry branches leave the original promise unsettled. Those hazards predate the edit but remain in the worker flow.",
"verdict": "partial"
},
{
"id": "preserves-sqs-message-recovery",
"rationale": "The synthesizer still deletes the SQS message before tenant validation or work (index.js:76-101), and cloning deletes before authorization reads or training (index.js:148-164). Later failures cannot retry once the message is gone. Cloning validates missing userId before deletion but has no explicit rejection disposition, allowing repeated redelivery. The transcript shows no SQS recovery test or repair.",
"verdict": "fail"
},
{
"id": "verifies-query-condition-scoping",
"rationale": "Transcript steps 5-8 inventory and read handlers, schemas, and wrappers; step 18 rereads the edited handlers and enumerates query call sites; steps 28 and 32 rerun checks. Service tests inspect the mock model's first filter argument and assert userId there. Direct worker calls were inspected in the final tree and likewise pass tenantFilter as argument 1.",
"verdict": "pass"
},
{
"id": "tests-worker-and-rejection-flows",
"rationale": "test/tenant-isolation.test.js imports helpers and service factories only (lines 3-13), then calls CRUD methods on a mock model (lines 100-202). It never executes either worker handler, SQS fetch/delete behavior, missing-userId handling, failed authorization, or the synthesis RecordingSalutation and Recording lookups. npm test passes but does not exercise worker or rejection flows.",
"verdict": "fail"
},
{
"id": "reports-work-and-verification-accurately",
"rationale": "The final transcript message accurately reports worker-local tenant scoping, owner stamping, the linked-profile check, the added test file, and passing npm test; the grader reproduced that test result. It does not claim to have run end-to-end worker tests. The unmentioned pipeline and SQS gaps are quality omissions, but the agent did not falsely report a check or an active-path unscoped update as clean.",
"verdict": "pass"
},
{
"id": "summarizes-security-refactor-clearly",
"rationale": "The final response clearly identifies the SQS job userId as the authorization source, describes missing-ID rejection and tenant-qualified updates, notes linked-profile validation, and gives the test location and result.",
"verdict": "pass"
},
{
"id": "avoids-active-path-unscoped-id-operations",
"rationale": "No active worker ID lookup or update remains with {_id} alone in Mongoose argument 1. Direct RecordingSalutation and Recording calls use tenantFilter, while service update methods use tenantFilter({_id, deleted:false}, userId). The unscoped app-level voice_cloning_service.js is not imported by either worker.",
"verdict": "pass"
},
{
"id": "avoids-missing-tenant-helper-module",
"rationale": "The imported ../app/services/utils/tenantScope path exists in the final tree as app/services/utils/tenantScope.js. npm test loads it through the services and node --check passes, so the refactor does not introduce a missing local helper startup failure.",
"verdict": "pass"
},
{
"id": "avoids-premature-dependent-promise-all",
"rationale": "Neither worker groups parent and child queries in Promise.all. The synthesizer awaits audio profile, RecordingSalutation, then Recording sequentially (index.js:115-148); cloning awaits its cloning record and audio profile sequentially (index.js:150-164). The optional recordingId ordering issue is assessed under preserves-dependent-query-order.",
"verdict": "pass"
},
{
"id": "surfaces-adjacent-operational-risks",
"rationale": "The agent did not surface adjacent risks. Both workers still log DB_URI (synthesizer index.js:110; cloning index.js:138), and both delete SQS messages before work completes. Its commentary and final summary omit these operational and credential-logging concerns. This criterion is extra credit only.",
"verdict": "fail"
}
],
"closing": "Worker-local MongoDB scoping is largely sound; optional recordingId handling, SQS recovery, and executable worker rejection coverage remain incomplete.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,91 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "derives-tenant-id-from-job-context",
"rationale": "The synthesizer takes userId from job.userId (voice-synthsizer-job-handler/index.js:79-90), and cloning takes it from job._doc.userId (voice-cloning-job-handler/index.js:108-123). Both validate it before database reads; neither discovers an owner through an ID-only lookup.",
"verdict": "pass"
},
{
"id": "rejects-unauthorized-jobs-without-mutation",
"rationale": "Missing or malformed tenant IDs are rejected before database operations, and error-status updates use tenant-scoped wrappers. However, cloning authorization failures at voice-cloning-job-handler/index.js:150-164 enter the catch at lines 342-359, which still updates status. A foreign cloning ID paired with an owned audio profile can change that profile despite the job failing authorization.",
"verdict": "partial"
},
{
"id": "scopes-active-worker-database-operations",
"rationale": "The active worker model calls were traced. RecordingSalutation and Recording use tenantFilter with {_id, deleted:false} in Mongoose argument 1 (voice-synthsizer-job-handler/index.js:125-148,207-223). The audio-profile, cloning, Job, and Salutation wrappers also put userId in argument 1; tenant-wide queries include userId and deleted:false, and inserts are tenant-stamped.",
"verdict": "pass"
},
{
"id": "completes-both-worker-and-wrapper-audits",
"rationale": "Both handlers and their worker-local job_service.js, user_audio_profile_service.js, voice_cloning_service.js, and salutation_service.js wrappers were refactored. The separate app/services/voice_cloning/voice_cloning_service.js, which the agent inspected in transcript step 8, remains unscoped: its update at lines 66-74 filters only by _id. It is not imported by these workers, so this is a breadth gap rather than an active-path IDOR.",
"verdict": "partial"
},
{
"id": "preserves-worker-pipeline-functionality",
"rationale": "Apart from the optional-recordingId dependency defect assessed separately, the changed pipelines retain synthesis, upload, salutation and Job creation, and cloning status transitions. The synthesizer's switch from find to read correctly handles an audio profile as one document. No other refactor-caused pipeline break was found in the code review or syntax checks.",
"verdict": "pass"
},
{
"id": "preserves-dependent-query-order",
"rationale": "The synthesizer validates jobRecordingId at index.js:98-101 before loading the owned RecordingSalutation at lines 125-136. RecordingSalutation.recordingId is optional in the schema (recording_salutation_model.js:16-19) and could supply the ID after the parent is fetched. A job omitting recordingId is rejected before that dependency can resolve.",
"verdict": "fail"
},
{
"id": "handles-worker-runtime-failures-cleanly",
"rationale": "The grader reran npm test, node --check across worker and utility JavaScript, and git diff --check successfully; requireObjectId also prevents malformed IDs from reaching Mongoose as CastErrors. Runtime recovery remains incomplete: cloning's async exec callback awaits fs.promises.writeFile without catching rejection (voice-cloning-job-handler/index.js:58-68), and both connectDB retry branches leave the original promise unsettled. Those hazards predate the edit but remain in the worker flow.",
"verdict": "partial"
},
{
"id": "preserves-sqs-message-recovery",
"rationale": "The synthesizer still deletes the SQS message before tenant validation or work (index.js:76-101), and cloning deletes before authorization reads or training (index.js:148-164). Later failures cannot retry once the message is gone. Cloning validates missing userId before deletion but has no explicit rejection disposition, allowing repeated redelivery. The transcript shows no SQS recovery test or repair.",
"verdict": "fail"
},
{
"id": "verifies-query-condition-scoping",
"rationale": "Transcript steps 5-8 inventory and read handlers, schemas, and wrappers; step 18 rereads the edited handlers and enumerates query call sites; steps 28 and 32 rerun checks. Service tests inspect the mock model's first filter argument and assert userId there. Direct worker calls were inspected in the final tree and likewise pass tenantFilter as argument 1.",
"verdict": "pass"
},
{
"id": "tests-worker-and-rejection-flows",
"rationale": "test/tenant-isolation.test.js imports helpers and service factories only (lines 3-13), then calls CRUD methods on a mock model (lines 100-202). It never executes either worker handler, SQS fetch/delete behavior, missing-userId handling, failed authorization, or the synthesis RecordingSalutation and Recording lookups. npm test passes but does not exercise worker or rejection flows.",
"verdict": "fail"
},
{
"id": "reports-work-and-verification-accurately",
"rationale": "The final transcript message accurately reports worker-local tenant scoping, owner stamping, the linked-profile check, the added test file, and passing npm test; the grader reproduced that test result. It does not claim to have run end-to-end worker tests. The unmentioned pipeline and SQS gaps are quality omissions, but the agent did not falsely report a check or an active-path unscoped update as clean.",
"verdict": "pass"
},
{
"id": "summarizes-security-refactor-clearly",
"rationale": "The final response clearly identifies the SQS job userId as the authorization source, describes missing-ID rejection and tenant-qualified updates, notes linked-profile validation, and gives the test location and result.",
"verdict": "pass"
},
{
"id": "avoids-active-path-unscoped-id-operations",
"rationale": "No active worker ID lookup or update remains with {_id} alone in Mongoose argument 1. Direct RecordingSalutation and Recording calls use tenantFilter, while service update methods use tenantFilter({_id, deleted:false}, userId). The unscoped app-level voice_cloning_service.js is not imported by either worker.",
"verdict": "pass"
},
{
"id": "avoids-missing-tenant-helper-module",
"rationale": "The imported ../app/services/utils/tenantScope path exists in the final tree as app/services/utils/tenantScope.js. npm test loads it through the services and node --check passes, so the refactor does not introduce a missing local helper startup failure.",
"verdict": "pass"
},
{
"id": "avoids-premature-dependent-promise-all",
"rationale": "Neither worker groups parent and child queries in Promise.all. The synthesizer awaits audio profile, RecordingSalutation, then Recording sequentially (index.js:115-148); cloning awaits its cloning record and audio profile sequentially (index.js:150-164). The optional recordingId ordering issue is assessed under preserves-dependent-query-order.",
"verdict": "pass"
},
{
"id": "surfaces-adjacent-operational-risks",
"rationale": "The agent did not surface adjacent risks. Both workers still log DB_URI (synthesizer index.js:110; cloning index.js:138), and both delete SQS messages before work completes. Its commentary and final summary omit these operational and credential-logging concerns. This criterion is extra credit only.",
"verdict": "fail"
}
],
"closing": "Worker-local MongoDB scoping is largely sound; optional recordingId handling, SQS recovery, and executable worker rejection coverage remain incomplete.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,7 @@
Captured 10 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-rubric-grade: ok reward=0.76 form=trinary criteria=15 excluded_extra_credit=1 partial_extra_credit=0 total_weight=38
grader sample 1: 0.76
reward: 0.7600 correctness: (none)
0.7600
{"reward": 0.7600}

View File

@@ -0,0 +1,39 @@
{
"id": "0edcdcf9-c43c-4a56-98e0-63e9c3436467",
"started_at": "2026-10-12T00:57:58.669788",
"updated_at": "2026-10-12T01:00:18.814942",
"finished_at": "2026-10-12T01:00:18.814942",
"n_total_trials": 1,
"stats": {
"n_completed_trials": 1,
"n_errored_trials": 0,
"n_running_trials": 0,
"n_pending_trials": 0,
"n_cancelled_trials": 0,
"n_retries": 0,
"evals": {
"replay__adhoc": {
"n_trials": 1,
"n_errors": 0,
"metrics": [
{
"mean": 0.76
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.76": [
"potion-voice-user-ownership__PAN9x6U"
]
}
},
"exception_stats": {}
}
},
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null
}
}

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-reward-0.8200-BmbBf3A-1791766928-95140",
"jobs_dir": "harbor-jobs/reward-0.8200-BmbBf3A",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.8200-BmbBf3A",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

Some files were not shown because too many files have changed in this diff Show More