regraders

This commit is contained in:
2026-10-16 13:54:50 -04:00
parent 18fc4f00b9
commit 698431f78e
361 changed files with 43279 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-reward-0.5000-hCpLyTL-1792171825-23821",
"jobs_dir": "harbor-jobs/reward-0.5000-hCpLyTL",
"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.5000-hCpLyTL",
"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-16T17:30:26.828570Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"ApiUsageLimitError",
"AgentTimeoutError",
"AgentSafetyRefusalError",
"VerifierOutputParseError",
"RewardFileNotFoundError",
"VerifierTimeoutError",
"ModelNotFoundError",
"AgentAuthenticationError",
"RewardFileEmptyError"
],
"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:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"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.5000-hCpLyTL",
"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__LgtNT6P",
"trials_dir": "harbor-jobs/reward-0.5000-hCpLyTL/regrade-reward-0.5000-hCpLyTL-1792171825-23821",
"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.5000-hCpLyTL",
"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": "9de4adbb-811e-4dc4-bc08-ced4679c76a7"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"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.5000-hCpLyTL",
"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": "9e8e7f8b-93d8-41ec-92f3-3382224392f1",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__LgtNT6P",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.5000-hCpLyTL/regrade-reward-0.5000-hCpLyTL-1792171825-23821/potion-voice-user-ownership__LgtNT6P",
"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": "eb8343998fa6289ec680e3f2ea09c10309294a531ce0ef0b775c13007f4aefcd",
"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__LgtNT6P",
"trials_dir": "harbor-jobs/reward-0.5000-hCpLyTL/regrade-reward-0.5000-hCpLyTL-1792171825-23821",
"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.5000-hCpLyTL",
"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": "9de4adbb-811e-4dc4-bc08-ced4679c76a7"
},
"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.61
}
},
"exception_info": null,
"started_at": "2026-10-16T17:30:27.166598Z",
"finished_at": "2026-10-16T17:32:55.189806Z",
"environment_setup": {
"started_at": "2026-10-16T17:30:27.310621Z",
"finished_at": "2026-10-16T17:30:31.199612Z"
},
"agent_setup": {
"started_at": "2026-10-16T17:30:31.199659Z",
"finished_at": "2026-10-16T17:30:31.199705Z"
},
"agent_execution": {
"started_at": "2026-10-16T17:30:31.199762Z",
"finished_at": "2026-10-16T17:30:31.625803Z"
},
"verifier": {
"started_at": "2026-10-16T17:30:32.192774Z",
"finished_at": "2026-10-16T17:32:50.947961Z"
},
"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,396 @@
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')
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)
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) {
return connectDB(dbUri, retryCount + 1)
}
throw error
}
}
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 tenantValidationError = (message) => {
const error = new Error(message)
error.code = 'TENANT_VALIDATION_FAILED'
return error
}
const resolveTenantContext = async (voiceCloningId, userAudioProfileId) => {
const userAudioProfile =
await userAudioProfileService.readForTenantContext(userAudioProfileId)
if (!userAudioProfile || !userAudioProfile.userId) {
throw tenantValidationError(
`Unable to establish tenant from audio profile ${userAudioProfileId}`
)
}
const userId = userAudioProfile.userId
const voiceCloning = await voiceCloningService.read({
_id: voiceCloningId,
userAudioProfileId,
userId,
})
if (!voiceCloning) {
throw tenantValidationError(
`Voice cloning job ${voiceCloningId} is not owned by the resolved tenant`
)
}
return { userId }
}
const processQueue = () =>
(async () => {
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 } = job._doc
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
let tenantContext = null
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
tenantContext = await resolveTenantContext(_id, userAudioProfileId)
const { userId } = tenantContext
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
await voiceCloningService.update({
_id,
userId,
status: 'processing',
})
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'processing',
})
// 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
await voiceCloningService.update({
_id,
userId,
status: 'completed',
})
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`,
}
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'completed',
training_model_path,
})
// 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
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
training_model_s3_path,
})
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// Do not mutate any record when tenant ownership was not validated.
if (tenantContext && error.code !== 'TENANT_VALIDATION_FAILED') {
const { userId } = tenantContext
const statusUpdates = await Promise.allSettled([
voiceCloningService.update({ _id, userId, status: 'error' }),
userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'error',
}),
])
statusUpdates
.filter(({ status }) => status === 'rejected')
.forEach(({ reason }) => {
console.error('Unable to mark voice cloning job as failed', {
error: reason,
})
Bugsnag.notify(reason)
})
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Unable to close the voice cloning database connection', {
error,
})
Bugsnag.notify(error)
}
}
})()
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,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unexpected voice cloning worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
init()

View File

@@ -0,0 +1,179 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireTenantFilter = (filter) => {
if (!filter || !filter.userId) {
const error = new Error(
'userId is required for UserAudioProfile operations'
)
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return filter
}
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
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) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const foundModel = await UserAudioProfileModel.findOne({
...tenantFilter,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the only intentionally unscoped read. The profile owns the tenant
// context used to scope every operation that follows it in a worker job.
const readForTenantContext =
(UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: userAudioProfileId,
deleted: false,
})
} catch (error) {
const details = { userAudioProfileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantContext',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const tenantFilter = requireTenantFilter(filter)
const foundModels = await UserAudioProfileModel.find({
...tenantFilter,
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) => {
try {
const { _id, userId, ...updates } = data
requireTenantFilter({ userId })
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...tenantFilter, 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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...tenantFilter, 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),
readForTenantContext: readForTenantContext(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,158 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireTenantFilter = (filter) => {
if (!filter || !filter.userId) {
const error = new Error('userId is required for VoiceCloning operations')
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return filter
}
const create = (VoiceCloningModel) => async (data) => {
try {
const newModel = new VoiceCloningModel({ ...data })
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) => {
try {
const inserted = await VoiceCloningModel.insertMany(data)
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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const foundModel = await VoiceCloningModel.findOne({
...tenantFilter,
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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const foundModels = await VoiceCloningModel.find({
...tenantFilter,
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) => {
try {
const { _id, userId, ...updates } = data
requireTenantFilter({ userId })
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...tenantFilter, 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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const updatedModel = await VoiceCloningModel.updateMany(
{ ...tenantFilter, 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,289 @@
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')
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)
})
})
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) {
return connectDB(dbUri, retryCount + 1)
}
throw error
}
}
const tenantValidationError = (message) => {
const error = new Error(message)
error.code = 'TENANT_VALIDATION_FAILED'
return error
}
const processQueue = () =>
(async () => {
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,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// The profile lookup is intentionally the sole unscoped query: its
// persisted userId establishes the tenant for every operation below.
const userAudioProfile =
await userAudioProfileService.readForTenantContext(
userAudioProfileId
)
if (
!userAudioProfile ||
!userAudioProfile.userId ||
userAudioProfile.status !== 'completed'
) {
throw tenantValidationError(
`Unable to establish a completed audio profile for ${userAudioProfileId}`
)
}
const { training_model_path, userId } = userAudioProfile
// Validate all payload-referenced records before rendering or any
// database mutation. Both records must belong to the profile tenant.
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
throw tenantValidationError(
'Recording or recording salutation is not owned by the resolved tenant'
)
}
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
)
const updatedSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedSalutation) {
throw tenantValidationError(
'Recording salutation ownership changed during processing'
)
}
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,
}
await jobService.insertMany([
{
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
},
])
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error(
'Unable to close the voice synthesizer database connection',
{ error }
)
Bugsnag.notify(error)
}
}
})()
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,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unexpected voice synthesizer worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
init()

View File

@@ -0,0 +1,181 @@
const StringifyUtils = require('../../app/services/utils/logService')
const requireTenantFilter = (filter) => {
if (!filter || !filter.userId) {
const error = new Error(
'userId is required for UserAudioProfile operations'
)
error.code = 'TENANT_CONTEXT_REQUIRED'
throw error
}
return filter
}
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
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) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const foundModel = await UserAudioProfileModel.findOne({
...tenantFilter,
deleted: false
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the only intentionally unscoped read. The profile owns the tenant
// context used to scope every operation that follows it in a worker job.
const readForTenantContext =
(UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: userAudioProfileId,
deleted: false
})
} catch (error) {
const details = { userAudioProfileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantContext',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const tenantFilter = requireTenantFilter(filter)
const foundModels = await UserAudioProfileModel.find({
...tenantFilter,
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) => {
console.log('ua data', data)
try {
const { _id, userId, ...updates } = data
requireTenantFilter({ userId })
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updates },
{
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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...tenantFilter, 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) => {
try {
const tenantFilter = requireTenantFilter(filter)
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...tenantFilter, 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),
readForTenantContext: readForTenantContext(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 0.61 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The cloning handler derives userId from the profile, then reads VoiceCloning with _id, userAudioProfileId, and userId. Every handler status update passes userId; the affected service read and update filters also require it.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis handler derives userId from the profile and filters RecordingSalutation and Recording reads by _id and userId. Its RecordingSalutation update uses the same tenant filter. Inspection found no other handler operations on those models.
## cloning-prevent-unauthorized-side-effects — FAIL
The cloning handler ignores null results from its tenant-scoped processing updates. In a controlled run where both updates returned null, it still invoked the dataset, cloning, and minimization commands, made completion updates, and reached S3 uploads.
## synthesis-prevent-unauthorized-side-effects — PASS
Missing or tenant-mismatched records stop synthesis before rendering or database writes. A null result from the scoped salutation update stops job insertion. A controlled run with a missing salutation performed no rendering or database write.
## initial-profile-tenant-resolution — PASS
Both handlers use the profile service’s initial lookup by userAudioProfileId to obtain persisted userId, then use that identity for downstream operations. This is the permitted tenant-resolution lookup.
## scoped-update-null-handling — PARTIAL
Synthesis checks its scoped salutation update result. Cloning leaves its final scoped profile update unchecked, and its error-status branch detects rejected updates but overlooks fulfilled null results. Earlier cloning updates that allow rendering are assessed under the side-effect criterion.
## worker-loop-crash-prevention — PASS
Both workers catch job-processing and per-iteration errors, and catch connection-close errors. Syntax checks passed for JavaScript files in both worker directories; neither package declares a test script.
## refactor-summary-accuracy — PARTIAL
The final summary accurately describes profile-derived tenant filtering, but overstates that rendering and mutations stop on ownership failures. The controlled cloning run showed they continue after scoped processing updates return null.

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 0.61 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The cloning handler derives userId from the profile, then reads VoiceCloning with _id, userAudioProfileId, and userId. Every handler status update passes userId; the affected service read and update filters also require it.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis handler derives userId from the profile and filters RecordingSalutation and Recording reads by _id and userId. Its RecordingSalutation update uses the same tenant filter. Inspection found no other handler operations on those models.
## cloning-prevent-unauthorized-side-effects — FAIL
The cloning handler ignores null results from its tenant-scoped processing updates. In a controlled run where both updates returned null, it still invoked the dataset, cloning, and minimization commands, made completion updates, and reached S3 uploads.
## synthesis-prevent-unauthorized-side-effects — PASS
Missing or tenant-mismatched records stop synthesis before rendering or database writes. A null result from the scoped salutation update stops job insertion. A controlled run with a missing salutation performed no rendering or database write.
## initial-profile-tenant-resolution — PASS
Both handlers use the profile service’s initial lookup by userAudioProfileId to obtain persisted userId, then use that identity for downstream operations. This is the permitted tenant-resolution lookup.
## scoped-update-null-handling — PARTIAL
Synthesis checks its scoped salutation update result. Cloning leaves its final scoped profile update unchecked, and its error-status branch detects rejected updates but overlooks fulfilled null results. Earlier cloning updates that allow rendering are assessed under the side-effect criterion.
## worker-loop-crash-prevention — PASS
Both workers catch job-processing and per-iteration errors, and catch connection-close errors. Syntax checks passed for JavaScript files in both worker directories; neither package declares a test script.
## refactor-summary-accuracy — PARTIAL
The final summary accurately describes profile-derived tenant filtering, but overstates that rendering and mutations stop on ownership failures. The controlled cloning run showed they continue after scoped processing updates return null.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-16T17:30:32Z",
"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": "9cca9fff9204e6bdc75325ee92989c872263879058816a489aff558cfb988536",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a145c3-fe6f-7862-beaf-082924e93047", "usage": {"input_tokens": 811108, "cached_input_tokens": 733337, "cache_write_input_tokens": 77726, "output_tokens": 10903, "reasoning_output_tokens": 5383}}

View File

@@ -0,0 +1 @@
{"session_id": "01a145c3-fe6f-7862-beaf-082924e93047", "usage": {"input_tokens": 811108, "cached_input_tokens": 733337, "cache_write_input_tokens": 77726, "output_tokens": 10903, "reasoning_output_tokens": 5383}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.61
mean: 0.6100
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.WgAuHnRa"))

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.WgAuHnRa"))

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The cloning handler derives userId from the profile, then reads VoiceCloning with _id, userAudioProfileId, and userId. Every handler status update passes userId; the affected service read and update filters also require it.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis handler derives userId from the profile and filters RecordingSalutation and Recording reads by _id and userId. Its RecordingSalutation update uses the same tenant filter. Inspection found no other handler operations on those models.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The cloning handler ignores null results from its tenant-scoped processing updates. In a controlled run where both updates returned null, it still invoked the dataset, cloning, and minimization commands, made completion updates, and reached S3 uploads.",
"verdict": "fail"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "Missing or tenant-mismatched records stop synthesis before rendering or database writes. A null result from the scoped salutation update stops job insertion. A controlled run with a missing salutation performed no rendering or database write.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both handlers use the profile service’s initial lookup by userAudioProfileId to obtain persisted userId, then use that identity for downstream operations. This is the permitted tenant-resolution lookup.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "Synthesis checks its scoped salutation update result. Cloning leaves its final scoped profile update unchecked, and its error-status branch detects rejected updates but overlooks fulfilled null results. Earlier cloning updates that allow rendering are assessed under the side-effect criterion.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch job-processing and per-iteration errors, and catch connection-close errors. Syntax checks passed for JavaScript files in both worker directories; neither package declares a test script.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final summary accurately describes profile-derived tenant filtering, but overstates that rendering and mutations stop on ownership failures. The controlled cloning run showed they continue after scoped processing updates return null.",
"verdict": "partial"
}
],
"closing": null,
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The cloning handler derives userId from the profile, then reads VoiceCloning with _id, userAudioProfileId, and userId. Every handler status update passes userId; the affected service read and update filters also require it.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis handler derives userId from the profile and filters RecordingSalutation and Recording reads by _id and userId. Its RecordingSalutation update uses the same tenant filter. Inspection found no other handler operations on those models.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The cloning handler ignores null results from its tenant-scoped processing updates. In a controlled run where both updates returned null, it still invoked the dataset, cloning, and minimization commands, made completion updates, and reached S3 uploads.",
"verdict": "fail"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "Missing or tenant-mismatched records stop synthesis before rendering or database writes. A null result from the scoped salutation update stops job insertion. A controlled run with a missing salutation performed no rendering or database write.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both handlers use the profile service’s initial lookup by userAudioProfileId to obtain persisted userId, then use that identity for downstream operations. This is the permitted tenant-resolution lookup.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "Synthesis checks its scoped salutation update result. Cloning leaves its final scoped profile update unchecked, and its error-status branch detects rejected updates but overlooks fulfilled null results. Earlier cloning updates that allow rendering are assessed under the side-effect criterion.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch job-processing and per-iteration errors, and catch connection-close errors. Syntax checks passed for JavaScript files in both worker directories; neither package declares a test script.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final summary accurately describes profile-derived tenant filtering, but overstates that rendering and mutations stop on ownership failures. The controlled cloning run showed they continue after scoped processing updates return null.",
"verdict": "partial"
}
],
"closing": null,
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

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

View File

@@ -0,0 +1,39 @@
{
"id": "9de4adbb-811e-4dc4-bc08-ced4679c76a7",
"started_at": "2026-10-16T17:30:26.631972",
"updated_at": "2026-10-16T17:32:55.195746",
"finished_at": "2026-10-16T17:32:55.195746",
"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.61
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.61": [
"potion-voice-user-ownership__LgtNT6P"
]
}
},
"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.5800-Vz8kjv9-1792172125-24995",
"jobs_dir": "harbor-jobs/reward-0.5800-Vz8kjv9",
"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.5800-Vz8kjv9",
"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-16T17:35:27.047412Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"ModelNotFoundError",
"VerifierTimeoutError",
"AgentSafetyRefusalError",
"AgentAuthenticationError",
"VerifierOutputParseError",
"RewardFileEmptyError",
"ApiUsageLimitError",
"RewardFileNotFoundError",
"AgentTimeoutError"
],
"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:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"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.5800-Vz8kjv9",
"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__ohKqeCw",
"trials_dir": "harbor-jobs/reward-0.5800-Vz8kjv9/regrade-reward-0.5800-Vz8kjv9-1792172125-24995",
"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.5800-Vz8kjv9",
"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": "ef6f477b-b277-49c3-ae29-1954b2ea9fd8"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"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.5800-Vz8kjv9",
"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": "8d945326-7d10-4b49-91bd-a60b00097b5b",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__ohKqeCw",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.5800-Vz8kjv9/regrade-reward-0.5800-Vz8kjv9-1792172125-24995/potion-voice-user-ownership__ohKqeCw",
"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": "fb65e395ebc8ebdec6025b08b3f8adc19a06663347dcdf13b82f07d5f100afcc",
"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__ohKqeCw",
"trials_dir": "harbor-jobs/reward-0.5800-Vz8kjv9/regrade-reward-0.5800-Vz8kjv9-1792172125-24995",
"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.5800-Vz8kjv9",
"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": "ef6f477b-b277-49c3-ae29-1954b2ea9fd8"
},
"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.23
}
},
"exception_info": null,
"started_at": "2026-10-16T17:35:27.378521Z",
"finished_at": "2026-10-16T17:38:03.717603Z",
"environment_setup": {
"started_at": "2026-10-16T17:35:27.556418Z",
"finished_at": "2026-10-16T17:35:31.631685Z"
},
"agent_setup": {
"started_at": "2026-10-16T17:35:31.631742Z",
"finished_at": "2026-10-16T17:35:31.631799Z"
},
"agent_execution": {
"started_at": "2026-10-16T17:35:31.631860Z",
"finished_at": "2026-10-16T17:35:32.066091Z"
},
"verifier": {
"started_at": "2026-10-16T17:35:32.637894Z",
"finished_at": "2026-10-16T17:37:59.362071Z"
},
"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,47 @@
class TenantValidationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantValidationError'
this.code = 'TENANT_VALIDATION_FAILED'
}
}
const requireTenantId = (userId) => {
if (!userId) {
throw new TenantValidationError('A tenant userId is required')
}
return userId
}
const requireRecordId = (recordId, recordName) => {
if (!recordId) {
throw new TenantValidationError(`${recordName} id is required`)
}
return recordId
}
const tenantFilter = (filter = {}, userId) => ({
...filter,
userId: requireTenantId(userId),
})
const splitTenantUpdate = (data = {}) => {
const source =
typeof data.toObject === 'function' ? data.toObject() : { ...data }
const recordId = source._id
delete source._id
delete source.userId
return { recordId, updates: source }
}
module.exports = {
TenantValidationError,
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
}

View File

@@ -0,0 +1,419 @@
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 {
TenantValidationError,
requireRecordId,
requireTenantId,
} = require('../app/services/utils/tenantScope')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
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)
}
async function connectDB(dbUri, retryCount = 0) {
while (retryCount <= 6) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
return
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount === 6) throw error
retryCount++
}
}
}
const requireOwnedRecord = (record, recordName) => {
if (!record) {
throw new TenantValidationError(
`${recordName} was not found for the resolved tenant`
)
}
return record
}
const resolveTenantContext = async (_id, userAudioProfileId) => {
requireRecordId(_id, 'VoiceCloning')
requireRecordId(userAudioProfileId, 'UserAudioProfile')
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readById(userAudioProfileId),
'UserAudioProfile'
)
const userId = requireTenantId(userAudioProfile.userId)
const voiceCloning = requireOwnedRecord(
await voiceCloningService.read(
{ _id, userAudioProfileId },
userId
),
'VoiceCloning'
)
return { userAudioProfile, userId, voiceCloning }
}
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 = async () => {
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 } = job._doc
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
let tenantContext = null
try {
tenantContext = await resolveTenantContext(_id, userAudioProfileId)
const { userId } = tenantContext
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
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
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
),
'VoiceCloning'
)
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
),
'UserAudioProfile'
)
// 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
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
),
'VoiceCloning'
)
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`,
}
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
),
'UserAudioProfile'
)
// 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
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
),
'UserAudioProfile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
if (tenantContext) {
const { userId } = tenantContext
const statusUpdates = await Promise.allSettled([
voiceCloningService.update({ _id, status: 'error' }, userId),
userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
),
])
statusUpdates
.filter(({ status }) => status === 'rejected')
.forEach(({ reason }) => Bugsnag.notify(reason))
} else if (error instanceof TenantValidationError) {
// Invalid ownership is not retryable. Acknowledge the message only
// after validation has failed, without rendering or mutating data.
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
} catch (deleteError) {
Bugsnag.notify(deleteError)
}
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
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,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unexpected voice cloning worker error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) init()
module.exports = { processQueue, resolveTenantContext }

View File

@@ -0,0 +1,178 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel({
...data,
userId: requireTenantId(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 tenantId = requireTenantId(userId)
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => ({ ...item, userId: tenantId }))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the only intentionally unscoped lookup. Workers use it to establish
// tenant context from the profile referenced by a queue message.
const readById = (UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: requireRecordId(userAudioProfileId, 'UserAudioProfile'),
deleted: false,
})
} catch (error) {
const details = { userAudioProfileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readById',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...tenantFilter(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({
...tenantFilter(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 { recordId, updates } = splitTenantUpdate(data)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'UserAudioProfile') },
userId
),
deleted: false,
},
{ $set: updates },
{
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, 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(
{ ...tenantFilter(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),
readById: readById(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,160 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (VoiceCloningModel) => async (data, userId) => {
try {
const newModel = new VoiceCloningModel({
...data,
userId: requireTenantId(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 tenantId = requireTenantId(userId)
const inserted = await VoiceCloningModel.insertMany(
data.map((item) => ({ ...item, userId: tenantId }))
)
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, 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({
...tenantFilter(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 { recordId, updates } = splitTenantUpdate(data)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'VoiceCloning') },
userId
),
deleted: false,
},
{ $set: updates },
{
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, 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(
{ ...tenantFilter(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,325 @@
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 {
TenantValidationError,
requireRecordId,
requireTenantId,
} = require('../app/services/utils/tenantScope')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
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)
})
})
}
async function connectDB(dbUri, retryCount = 0) {
while (retryCount <= 6) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
return
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount === 6) throw error
retryCount++
}
}
}
const requireOwnedRecord = (record, recordName) => {
if (!record) {
throw new TenantValidationError(
`${recordName} was not found for the resolved tenant`
)
}
return record
}
const resolveTenantContext = async ({
userAudioProfileId,
salutationId,
recordingId,
}) => {
requireRecordId(userAudioProfileId, 'UserAudioProfile')
requireRecordId(salutationId, 'RecordingSalutation')
requireRecordId(recordingId, 'Recording')
// This bootstrap read is intentionally scoped only by profile id. Its
// persisted owner becomes the trusted tenant context for every later query.
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readById(userAudioProfileId),
'UserAudioProfile'
)
const userId = requireTenantId(userAudioProfile.userId)
if (userAudioProfile.status !== 'completed') {
throw new TenantValidationError('UserAudioProfile is not ready')
}
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
requireOwnedRecord(salutationToUpdate, 'RecordingSalutation')
requireOwnedRecord(recordingToUpdate, 'Recording')
return {
recordingToUpdate,
salutationToUpdate,
userAudioProfile,
userId,
}
}
const processQueue = async () => {
let job = null
let receiptHandle = null
let messageAcknowledged = false
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (!response.Messages || response.Messages.length === 0) {
throttleMessageFetching = true
return
}
throttleMessageFetching = false
job = JSON.parse(response.Messages[0].Body)
receiptHandle = response.Messages[0].ReceiptHandle
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const {
recordingToUpdate,
salutationToUpdate,
userAudioProfile,
userId,
} = await resolveTenantContext({
userAudioProfileId,
salutationId,
recordingId,
})
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path,
} = userAudioProfile.training_model_path || {}
if (
!voice_model_light_path ||
!voice_model_config_light_path ||
!voice_model_speakers_file_path
) {
throw new TenantValidationError(
'UserAudioProfile does not have a complete training model'
)
}
// Do not remove a message or perform external work until ownership of all
// referenced records has been established from the persisted profile.
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
messageAcknowledged = true
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)
await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(outputPath).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
const generatedFilePath = `${outputPath}${generatedFileName}`
const uploadParams = {
filePath: generatedFilePath,
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')
await salutationService.updateOrCreate(
{
firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
requireOwnedRecord(
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
),
'RecordingSalutation'
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany(
[
{
firstName,
recordingId: recordingToUpdate._id,
salutationId: salutationToUpdate._id,
metadata: jobData,
},
],
userId
)
fs.unlinkSync(generatedFilePath)
console.log(`[deleted] ${generatedFilePath}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
if (
error instanceof TenantValidationError &&
receiptHandle &&
!messageAcknowledged
) {
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
} catch (deleteError) {
Bugsnag.notify(deleteError)
}
}
} finally {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing Mongo DB connection', { error })
Bugsnag.notify(error)
}
}
}
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,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unexpected synthesis worker error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) init()
module.exports = { processQueue, resolveTenantContext }

View File

@@ -0,0 +1,151 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (Job) => async (jobData, userId) => {
try {
const newJob = new Job({ ...jobData, userId: requireTenantId(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 tenantId = requireTenantId(userId)
const inserted = await Job.insertMany(
jobData.map((job) => ({ ...job, userId: tenantId }))
)
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, 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({
...tenantFilter(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 { recordId, updates } = splitTenantUpdate(job)
const updatedJob = await Job.findOneAndUpdate(
{
...tenantFilter({ _id: requireRecordId(recordId, 'Job') }, userId),
deleted: false,
},
{ $set: updates },
{ 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, 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(
{ ...tenantFilter(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,112 @@
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (Salutation) => async (salutationData, userId) => {
const newSalutation = new Salutation({
...salutationData,
userId: requireTenantId(userId),
})
const savedSalutation = await newSalutation.save()
return savedSalutation
}
const read = (Salutation) => async (filter, userId) => {
const foundSalutation = await Salutation.findOne({
...tenantFilter(filter, userId),
deleted: false,
})
return foundSalutation
}
const find = (Salutation) => async (filter, userId) => {
const foundSalutations = await Salutation.find({
...tenantFilter(filter, userId),
deleted: false,
})
return foundSalutations
}
const update = (Salutation) => async (salutation, userId) => {
const { recordId, updates } = splitTenantUpdate(salutation)
const updatedSalutation = await Salutation.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'Salutation') },
userId
),
deleted: false,
},
{ $set: updates },
{ new: true }
)
return updatedSalutation
}
const modify = (Salutation) => async (salutation, userId) => {
const { recordId, updates } = splitTenantUpdate(salutation)
const findQuery = salutation._id
? { _id: requireRecordId(recordId, 'Salutation') }
: {
transcriptId: requireRecordId(
salutation.transcriptId,
'Salutation transcript'
),
}
const updatedSalutation = await Salutation.findOneAndUpdate(
{ ...tenantFilter(findQuery, userId), deleted: false },
{ $set: updates },
{ 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(
{ ...tenantFilter(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,178 @@
const StringifyUtils = require('../../app/services/utils/logService')
const {
requireRecordId,
requireTenantId,
splitTenantUpdate,
tenantFilter,
} = require('../../app/services/utils/tenantScope')
const create = (UserAudioProfileModel) => async (data, userId) => {
try {
const newModel = new UserAudioProfileModel({
...data,
userId: requireTenantId(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 tenantId = requireTenantId(userId)
const inserted = await UserAudioProfileModel.insertMany(
data.map((item) => ({ ...item, userId: tenantId }))
)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
// This is the only intentionally unscoped lookup. Workers use it to establish
// tenant context from the profile referenced by a queue message.
const readById = (UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: requireRecordId(userAudioProfileId, 'UserAudioProfile'),
deleted: false,
})
} catch (error) {
const details = { userAudioProfileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readById',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter, userId) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...tenantFilter(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({
...tenantFilter(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 { recordId, updates } = splitTenantUpdate(data)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{
...tenantFilter(
{ _id: requireRecordId(recordId, 'UserAudioProfile') },
userId
),
deleted: false,
},
{ $set: updates },
{
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, 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(
{ ...tenantFilter(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),
readById: readById(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.23 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The cloning worker derives userId from the profile and reads VoiceCloning using _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:62-80). Its VoiceCloning and UserAudioProfile services scope other reads and updates by tenant. The profile readById is the permitted bootstrap exception.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis worker queries RecordingSalutation and Recording with the profile-derived userId before processing, and its RecordingSalutation update uses the same userId (voice-synthsizer-job-handler/index.js:69-111, 222-237). There is no Recording update in this worker.
## cloning-prevent-unauthorized-side-effects — FAIL
An initial ownership miss stops rendering, as tested in transcript step 43. But if the tenant-scoped UserAudioProfile processing update returns null, the catch still issues VoiceCloning and UserAudioProfile error-status mutations (voice-cloning-job-handler/index.js:180-189, 351-366). An independent mocked run confirmed those writes occur after the null result.
## synthesis-prevent-unauthorized-side-effects — FAIL
Initial RecordingSalutation and Recording ownership misses stop rendering. However, salutation_service.js:68-86 can return null from a tenant-scoped update; the handler ignores that result and proceeds to update RecordingSalutation and insert a job (voice-synthsizer-job-handler/index.js:213-269). An independent mocked run confirmed both downstream mutations.
## initial-profile-tenant-resolution — PASS
Both workers use UserAudioProfile.readById to look up _id plus deleted:false, then derive userId from the persisted profile before querying other records. This is the specified tenant-resolution exception.
## scoped-update-null-handling — PARTIAL
The main cloning updates and the synthesis RecordingSalutation update check for null. Cloning error-status updates inspect rejected promises but ignore fulfilled null results (voice-cloning-job-handler/index.js:351-366). Several tenant-scoped service update and remove methods also return null or zero-match results unchecked. The salutation null case with downstream mutations is assessed under synthesis side-effect prevention.
## worker-loop-crash-prevention — PASS
Both processQueue functions catch processing errors, and both polling loops catch errors on each iteration (voice-cloning-job-handler/index.js:342-414; voice-synthsizer-job-handler/index.js:273-320). All worker JavaScript files passed node --check.
## refactor-summary-accuracy — PARTIAL
The final response accurately describes profile-derived filters and preflight ownership reads. Its broad side-effect prevention claim omits the no-match update paths where later mutations continue. The reported tests covered initial preflight misses, not those later failures.
## Closing
JavaScript syntax checks passed. The packages define no test script.

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.23 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The cloning worker derives userId from the profile and reads VoiceCloning using _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:62-80). Its VoiceCloning and UserAudioProfile services scope other reads and updates by tenant. The profile readById is the permitted bootstrap exception.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis worker queries RecordingSalutation and Recording with the profile-derived userId before processing, and its RecordingSalutation update uses the same userId (voice-synthsizer-job-handler/index.js:69-111, 222-237). There is no Recording update in this worker.
## cloning-prevent-unauthorized-side-effects — FAIL
An initial ownership miss stops rendering, as tested in transcript step 43. But if the tenant-scoped UserAudioProfile processing update returns null, the catch still issues VoiceCloning and UserAudioProfile error-status mutations (voice-cloning-job-handler/index.js:180-189, 351-366). An independent mocked run confirmed those writes occur after the null result.
## synthesis-prevent-unauthorized-side-effects — FAIL
Initial RecordingSalutation and Recording ownership misses stop rendering. However, salutation_service.js:68-86 can return null from a tenant-scoped update; the handler ignores that result and proceeds to update RecordingSalutation and insert a job (voice-synthsizer-job-handler/index.js:213-269). An independent mocked run confirmed both downstream mutations.
## initial-profile-tenant-resolution — PASS
Both workers use UserAudioProfile.readById to look up _id plus deleted:false, then derive userId from the persisted profile before querying other records. This is the specified tenant-resolution exception.
## scoped-update-null-handling — PARTIAL
The main cloning updates and the synthesis RecordingSalutation update check for null. Cloning error-status updates inspect rejected promises but ignore fulfilled null results (voice-cloning-job-handler/index.js:351-366). Several tenant-scoped service update and remove methods also return null or zero-match results unchecked. The salutation null case with downstream mutations is assessed under synthesis side-effect prevention.
## worker-loop-crash-prevention — PASS
Both processQueue functions catch processing errors, and both polling loops catch errors on each iteration (voice-cloning-job-handler/index.js:342-414; voice-synthsizer-job-handler/index.js:273-320). All worker JavaScript files passed node --check.
## refactor-summary-accuracy — PARTIAL
The final response accurately describes profile-derived filters and preflight ownership reads. Its broad side-effect prevention claim omits the no-match update paths where later mutations continue. The reported tests covered initial preflight misses, not those later failures.
## Closing
JavaScript syntax checks passed. The packages define no test script.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-16T17:35:33Z",
"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": "9cca9fff9204e6bdc75325ee92989c872263879058816a489aff558cfb988536",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a145c8-941c-7431-8d5b-7dfdb1566cc9", "usage": {"input_tokens": 1046444, "cached_input_tokens": 966534, "cache_write_input_tokens": 79856, "output_tokens": 11986, "reasoning_output_tokens": 6888}}

View File

@@ -0,0 +1 @@
{"session_id": "01a145c8-941c-7431-8d5b-7dfdb1566cc9", "usage": {"input_tokens": 1046444, "cached_input_tokens": 966534, "cache_write_input_tokens": 79856, "output_tokens": 11986, "reasoning_output_tokens": 6888}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.23
mean: 0.2300
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.DW0GEfn6"))

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.DW0GEfn6"))

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The cloning worker derives userId from the profile and reads VoiceCloning using _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:62-80). Its VoiceCloning and UserAudioProfile services scope other reads and updates by tenant. The profile readById is the permitted bootstrap exception.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis worker queries RecordingSalutation and Recording with the profile-derived userId before processing, and its RecordingSalutation update uses the same userId (voice-synthsizer-job-handler/index.js:69-111, 222-237). There is no Recording update in this worker.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "An initial ownership miss stops rendering, as tested in transcript step 43. But if the tenant-scoped UserAudioProfile processing update returns null, the catch still issues VoiceCloning and UserAudioProfile error-status mutations (voice-cloning-job-handler/index.js:180-189, 351-366). An independent mocked run confirmed those writes occur after the null result.",
"verdict": "fail"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "Initial RecordingSalutation and Recording ownership misses stop rendering. However, salutation_service.js:68-86 can return null from a tenant-scoped update; the handler ignores that result and proceeds to update RecordingSalutation and insert a job (voice-synthsizer-job-handler/index.js:213-269). An independent mocked run confirmed both downstream mutations.",
"verdict": "fail"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both workers use UserAudioProfile.readById to look up _id plus deleted:false, then derive userId from the persisted profile before querying other records. This is the specified tenant-resolution exception.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The main cloning updates and the synthesis RecordingSalutation update check for null. Cloning error-status updates inspect rejected promises but ignore fulfilled null results (voice-cloning-job-handler/index.js:351-366). Several tenant-scoped service update and remove methods also return null or zero-match results unchecked. The salutation null case with downstream mutations is assessed under synthesis side-effect prevention.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions catch processing errors, and both polling loops catch errors on each iteration (voice-cloning-job-handler/index.js:342-414; voice-synthsizer-job-handler/index.js:273-320). All worker JavaScript files passed node --check.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final response accurately describes profile-derived filters and preflight ownership reads. Its broad side-effect prevention claim omits the no-match update paths where later mutations continue. The reported tests covered initial preflight misses, not those later failures.",
"verdict": "partial"
}
],
"closing": "JavaScript syntax checks passed. The packages define no test script.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The cloning worker derives userId from the profile and reads VoiceCloning using _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:62-80). Its VoiceCloning and UserAudioProfile services scope other reads and updates by tenant. The profile readById is the permitted bootstrap exception.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis worker queries RecordingSalutation and Recording with the profile-derived userId before processing, and its RecordingSalutation update uses the same userId (voice-synthsizer-job-handler/index.js:69-111, 222-237). There is no Recording update in this worker.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "An initial ownership miss stops rendering, as tested in transcript step 43. But if the tenant-scoped UserAudioProfile processing update returns null, the catch still issues VoiceCloning and UserAudioProfile error-status mutations (voice-cloning-job-handler/index.js:180-189, 351-366). An independent mocked run confirmed those writes occur after the null result.",
"verdict": "fail"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "Initial RecordingSalutation and Recording ownership misses stop rendering. However, salutation_service.js:68-86 can return null from a tenant-scoped update; the handler ignores that result and proceeds to update RecordingSalutation and insert a job (voice-synthsizer-job-handler/index.js:213-269). An independent mocked run confirmed both downstream mutations.",
"verdict": "fail"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both workers use UserAudioProfile.readById to look up _id plus deleted:false, then derive userId from the persisted profile before querying other records. This is the specified tenant-resolution exception.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The main cloning updates and the synthesis RecordingSalutation update check for null. Cloning error-status updates inspect rejected promises but ignore fulfilled null results (voice-cloning-job-handler/index.js:351-366). Several tenant-scoped service update and remove methods also return null or zero-match results unchecked. The salutation null case with downstream mutations is assessed under synthesis side-effect prevention.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions catch processing errors, and both polling loops catch errors on each iteration (voice-cloning-job-handler/index.js:342-414; voice-synthsizer-job-handler/index.js:273-320). All worker JavaScript files passed node --check.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final response accurately describes profile-derived filters and preflight ownership reads. Its broad side-effect prevention claim omits the no-match update paths where later mutations continue. The reported tests covered initial preflight misses, not those later failures.",
"verdict": "partial"
}
],
"closing": "JavaScript syntax checks passed. The packages define no test script.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

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

View File

@@ -0,0 +1,39 @@
{
"id": "ef6f477b-b277-49c3-ae29-1954b2ea9fd8",
"started_at": "2026-10-16T17:35:26.836930",
"updated_at": "2026-10-16T17:38:03.723109",
"finished_at": "2026-10-16T17:38:03.723109",
"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.23
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.23": [
"potion-voice-user-ownership__ohKqeCw"
]
}
},
"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.6300-NSP5wKq-1792172655-26405",
"jobs_dir": "harbor-jobs/reward-0.6300-NSP5wKq",
"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.6300-NSP5wKq",
"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-16T17:44:16.886715Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"RewardFileNotFoundError",
"ModelNotFoundError",
"RewardFileEmptyError",
"VerifierOutputParseError",
"VerifierTimeoutError",
"AgentAuthenticationError",
"AgentTimeoutError",
"ApiUsageLimitError",
"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:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"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.6300-NSP5wKq",
"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__PX8qZZC",
"trials_dir": "harbor-jobs/reward-0.6300-NSP5wKq/regrade-reward-0.6300-NSP5wKq-1792172655-26405",
"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.6300-NSP5wKq",
"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": "c515d7f8-7f6a-4572-8dc5-743310b6222b"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"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.6300-NSP5wKq",
"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": "6e3701a9-539c-4ad0-97b4-ce1e08229066",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__PX8qZZC",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.6300-NSP5wKq/regrade-reward-0.6300-NSP5wKq-1792172655-26405/potion-voice-user-ownership__PX8qZZC",
"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": "97765ea4d78ff1d5f60fb4b7bd1097fd2154e6546135c0f869bb4977febcc8ca",
"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__PX8qZZC",
"trials_dir": "harbor-jobs/reward-0.6300-NSP5wKq/regrade-reward-0.6300-NSP5wKq-1792172655-26405",
"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.6300-NSP5wKq",
"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": "c515d7f8-7f6a-4572-8dc5-743310b6222b"
},
"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.8
}
},
"exception_info": null,
"started_at": "2026-10-16T17:44:17.230441Z",
"finished_at": "2026-10-16T17:46:43.868785Z",
"environment_setup": {
"started_at": "2026-10-16T17:44:17.434906Z",
"finished_at": "2026-10-16T17:44:21.568153Z"
},
"agent_setup": {
"started_at": "2026-10-16T17:44:21.568208Z",
"finished_at": "2026-10-16T17:44:21.568262Z"
},
"agent_execution": {
"started_at": "2026-10-16T17:44:21.568329Z",
"finished_at": "2026-10-16T17:44:22.015245Z"
},
"verifier": {
"started_at": "2026-10-16T17:44:22.634682Z",
"finished_at": "2026-10-16T17:46:39.470277Z"
},
"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,413 @@
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')
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) {
resolve(connectDB(dbUri, retryCount + 1))
} else {
reject(err)
}
})
})
}
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 requireOwnedRecord(record, recordName) {
if (!record) {
throw new Error(`Tenant validation failed for ${recordName}`)
}
return record
}
const processQueue = async () => {
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 } = job._doc
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
let userId
let ownershipValidated = false
try {
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readForTenantContext(
userAudioProfileId
),
'UserAudioProfile'
)
userId = userAudioProfile.userId
if (!userId) {
throw new Error(
'Tenant validation failed: UserAudioProfile has no userId'
)
}
requireOwnedRecord(
await voiceCloningService.read(
{ _id, userAudioProfileId },
userId
),
'VoiceCloning'
)
ownershipValidated = true
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
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
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
),
'VoiceCloning'
)
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
),
'UserAudioProfile'
)
// 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
requireOwnedRecord(
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
),
'VoiceCloning'
)
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`,
}
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
),
'UserAudioProfile'
)
// 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
requireOwnedRecord(
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
),
'UserAudioProfile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
// Only mutate failure status after ownership has been established.
if (ownershipValidated) {
const statusUpdates = await Promise.allSettled([
voiceCloningService.update({ _id, status: 'error' }, userId),
userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
),
])
statusUpdates
.filter(({ status }) => status === 'rejected')
.forEach(({ reason }) => Bugsnag.notify(reason))
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
if (mongoose.connection.readyState !== 0) {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing MongoDB connection', { error })
Bugsnag.notify(error)
}
}
}
}
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,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unhandled voice cloning job error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,176 @@
const StringifyUtils = require('../../app/services/utils/logService')
const withTenant = (filter, userId) => {
if (!userId) {
throw new Error('userId is required for UserAudioProfile database operations')
}
return { ...filter, userId }
}
// This is the only intentionally unscoped lookup. The worker uses the returned
// userId as the tenant context for every subsequent read and mutation.
const readForTenantContext = (UserAudioProfileModel) => async (profileId) => {
try {
if (!profileId) {
throw new Error('profileId is required to establish tenant context')
}
return await UserAudioProfileModel.findOne({
_id: profileId,
deleted: false,
})
} catch (error) {
const details = { profileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantContext',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
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) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
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(
withTenant({ ...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(
withTenant({ ...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 updates = { ...data }
const { _id } = updates
if (!_id) {
throw new Error('_id is required to update UserAudioProfile')
}
delete updates._id
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenant({ _id, deleted: false }, userId),
updates,
{
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(
withTenant({ ...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(
withTenant({ ...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),
readForTenantContext: readForTenantContext(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,154 @@
const StringifyUtils = require('../../app/services/utils/logService')
const withTenant = (filter, userId) => {
if (!userId) {
throw new Error('userId is required for VoiceCloning database operations')
}
return { ...filter, userId }
}
const create = (VoiceCloningModel) => async (data) => {
try {
const newModel = new VoiceCloningModel({ ...data })
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) => {
try {
const inserted = await VoiceCloningModel.insertMany(data)
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(
withTenant({ ...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(
withTenant({ ...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 updates = { ...data }
const { _id } = updates
if (!_id) {
throw new Error('_id is required to update VoiceCloning')
}
delete updates._id
delete updates.userId
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
withTenant({ _id, deleted: false }, userId),
updates,
{
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(
withTenant({ ...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(
withTenant({ ...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,280 @@
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')
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) {
resolve(connectDB(dbUri, retryCount + 1))
} else {
reject(err)
}
})
})
}
function requireOwnedRecord(record, recordName) {
if (!record) {
throw new Error(`Tenant validation failed for ${recordName}`)
}
return record
}
const processQueue = async () => {
let job
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages === 'undefined' ||
response.Messages.length === 0
) {
throttleMessageFetching = true
return
}
throttleMessageFetching = false
job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// This profile lookup is the sole tenant-context bootstrap. No rendering,
// queue deletion, upload, or mutation occurs until all ownership checks pass.
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readForTenantContext(userAudioProfileId),
'UserAudioProfile'
)
const { training_model_path, userId, status } = userAudioProfile
if (!userId) {
throw new Error(
'Tenant validation failed: UserAudioProfile has no userId'
)
}
if (status !== 'completed' || !training_model_path) {
throw new Error('Audio profile training model not found')
}
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
requireOwnedRecord(salutationToUpdate, 'RecordingSalutation')
requireOwnedRecord(recordingToUpdate, 'Recording')
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
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')
// Re-apply the tenant filter on the mutation in case ownership changed or
// the record was deleted after validation.
requireOwnedRecord(
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
),
'RecordingSalutation'
)
// Create or update the user's reusable salutation only after all target
// records have passed tenant validation.
await salutationService.updateOrCreate(
{
firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany([
{
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
},
])
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
} finally {
if (mongoose.connection.readyState !== 0) {
try {
await mongoose.connection.close()
} catch (error) {
console.error('Error while closing MongoDB connection', { error })
Bugsnag.notify(error)
}
}
}
}
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,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Unhandled speech synthesis job error', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,178 @@
const StringifyUtils = require('../../app/services/utils/logService')
const withTenant = (filter, userId) => {
if (!userId) {
throw new Error('userId is required for UserAudioProfile database operations')
}
return { ...filter, userId }
}
// This is the only intentionally unscoped lookup. The worker uses the returned
// userId as the tenant context for every subsequent read and mutation.
const readForTenantContext = (UserAudioProfileModel) => async (profileId) => {
try {
if (!profileId) {
throw new Error('profileId is required to establish tenant context')
}
return await UserAudioProfileModel.findOne({
_id: profileId,
deleted: false,
})
} catch (error) {
const details = { profileId }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantContext',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
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) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
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(
withTenant({ ...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(
withTenant({ ...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) => {
console.log('ua data', data)
try {
const updates = { ...data }
const { _id } = updates
if (!_id) {
throw new Error('_id is required to update UserAudioProfile')
}
delete updates._id
delete updates.userId
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenant({ _id, deleted: false }, userId),
updates,
{
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(
withTenant({ ...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(
withTenant({ ...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),
readForTenantContext: readForTenantContext(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.80 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The final tree requires userId on VoiceCloning reads and updates in voice_cloning_service.js:40-133 and on subsequent UserAudioProfile operations in user_audio_profile_service.js:62-160. The worker passes the profile-derived userId at index.js:153-159 and on every status update. A mocked-model check confirmed that the tenant userId overrides a forged filter value.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis worker derives userId from the profile at index.js:104-118, includes it in both target reads at :120-131, and reapplies it to the RecordingSalutation update at :176-190. A final-tree call-site audit found no other Recording or RecordingSalutation database operations in these workers.
## cloning-prevent-unauthorized-side-effects — PARTIAL
The preflight checks at index.js:139-160 stop an initial ownership miss before rendering or mutation, as tested in transcript step 31. But if a later scoped processing update returns null, ownershipValidated remains true and the catch at :349-365 still attempts error-status mutations. A final-tree trace confirmed that a null clone:processing result was followed by clone:error and profile:error updates.
## synthesis-prevent-unauthorized-side-effects — PASS
The profile and both target records must match at index.js:104-134 before rendering, upload, or mutation. Transcript step 31 tested a missing target and observed no side effects. The later tenant-scoped update is checked at :176-191; a null result stops subsequent database work, as confirmed by a final-tree trace.
## initial-profile-tenant-resolution — PASS
Both profile services use an initial findOne by profile _id and deleted:false at user_audio_profile_service.js:13-22 to obtain userId. The workers then use that userId for downstream operations. A mocked-model check confirmed the bootstrap and subsequent scoped filters.
## scoped-update-null-handling — PARTIAL
Normal worker updates check for null through requireOwnedRecord, including cloning index.js:171-186 and synthesis index.js:176-191. Cloning’s error path at :350-365 checks only rejected promises from Promise.allSettled, silently accepting fulfilled null results from scoped status updates.
## worker-loop-crash-prevention — PASS
Both processQueue functions catch job errors, and each init loop catches errors around every awaited iteration (cloning index.js:398-406; synthesis index.js:265-273). MongoDB retries now reject after a bound. All worker JavaScript files passed node --check in the final tree.
## refactor-summary-accuracy — PARTIAL
The final transcript message correctly describes profile-derived tenant filters. Its claims that side-effect prevention checks pass and invalid jobs remain available for retry/DLQ are too broad: cloning still attempts mutations after a scoped update miss, and both workers delete messages after initial checks, so later failed jobs are not retained.
## Closing
Verified with syntax checks, mocked service-filter checks, and targeted worker traces. The repository defines no test script.

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.80 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The final tree requires userId on VoiceCloning reads and updates in voice_cloning_service.js:40-133 and on subsequent UserAudioProfile operations in user_audio_profile_service.js:62-160. The worker passes the profile-derived userId at index.js:153-159 and on every status update. A mocked-model check confirmed that the tenant userId overrides a forged filter value.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis worker derives userId from the profile at index.js:104-118, includes it in both target reads at :120-131, and reapplies it to the RecordingSalutation update at :176-190. A final-tree call-site audit found no other Recording or RecordingSalutation database operations in these workers.
## cloning-prevent-unauthorized-side-effects — PARTIAL
The preflight checks at index.js:139-160 stop an initial ownership miss before rendering or mutation, as tested in transcript step 31. But if a later scoped processing update returns null, ownershipValidated remains true and the catch at :349-365 still attempts error-status mutations. A final-tree trace confirmed that a null clone:processing result was followed by clone:error and profile:error updates.
## synthesis-prevent-unauthorized-side-effects — PASS
The profile and both target records must match at index.js:104-134 before rendering, upload, or mutation. Transcript step 31 tested a missing target and observed no side effects. The later tenant-scoped update is checked at :176-191; a null result stops subsequent database work, as confirmed by a final-tree trace.
## initial-profile-tenant-resolution — PASS
Both profile services use an initial findOne by profile _id and deleted:false at user_audio_profile_service.js:13-22 to obtain userId. The workers then use that userId for downstream operations. A mocked-model check confirmed the bootstrap and subsequent scoped filters.
## scoped-update-null-handling — PARTIAL
Normal worker updates check for null through requireOwnedRecord, including cloning index.js:171-186 and synthesis index.js:176-191. Cloning’s error path at :350-365 checks only rejected promises from Promise.allSettled, silently accepting fulfilled null results from scoped status updates.
## worker-loop-crash-prevention — PASS
Both processQueue functions catch job errors, and each init loop catches errors around every awaited iteration (cloning index.js:398-406; synthesis index.js:265-273). MongoDB retries now reject after a bound. All worker JavaScript files passed node --check in the final tree.
## refactor-summary-accuracy — PARTIAL
The final transcript message correctly describes profile-derived tenant filters. Its claims that side-effect prevention checks pass and invalid jobs remain available for retry/DLQ are too broad: cloning still attempts mutations after a scoped update miss, and both workers delete messages after initial checks, so later failed jobs are not retained.
## Closing
Verified with syntax checks, mocked service-filter checks, and targeted worker traces. The repository defines no test script.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-16T17:44:23Z",
"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": "9cca9fff9204e6bdc75325ee92989c872263879058816a489aff558cfb988536",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a145d0-aacb-74a2-86e0-217d17e63bad", "usage": {"input_tokens": 808877, "cached_input_tokens": 724769, "cache_write_input_tokens": 84069, "output_tokens": 12663, "reasoning_output_tokens": 6351}}

View File

@@ -0,0 +1 @@
{"session_id": "01a145d0-aacb-74a2-86e0-217d17e63bad", "usage": {"input_tokens": 808877, "cached_input_tokens": 724769, "cache_write_input_tokens": 84069, "output_tokens": 12663, "reasoning_output_tokens": 6351}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.80
mean: 0.8000
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.MgKDKzWu"))

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.MgKDKzWu"))

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The final tree requires userId on VoiceCloning reads and updates in voice_cloning_service.js:40-133 and on subsequent UserAudioProfile operations in user_audio_profile_service.js:62-160. The worker passes the profile-derived userId at index.js:153-159 and on every status update. A mocked-model check confirmed that the tenant userId overrides a forged filter value.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis worker derives userId from the profile at index.js:104-118, includes it in both target reads at :120-131, and reapplies it to the RecordingSalutation update at :176-190. A final-tree call-site audit found no other Recording or RecordingSalutation database operations in these workers.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The preflight checks at index.js:139-160 stop an initial ownership miss before rendering or mutation, as tested in transcript step 31. But if a later scoped processing update returns null, ownershipValidated remains true and the catch at :349-365 still attempts error-status mutations. A final-tree trace confirmed that a null clone:processing result was followed by clone:error and profile:error updates.",
"verdict": "partial"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The profile and both target records must match at index.js:104-134 before rendering, upload, or mutation. Transcript step 31 tested a missing target and observed no side effects. The later tenant-scoped update is checked at :176-191; a null result stops subsequent database work, as confirmed by a final-tree trace.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both profile services use an initial findOne by profile _id and deleted:false at user_audio_profile_service.js:13-22 to obtain userId. The workers then use that userId for downstream operations. A mocked-model check confirmed the bootstrap and subsequent scoped filters.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "Normal worker updates check for null through requireOwnedRecord, including cloning index.js:171-186 and synthesis index.js:176-191. Cloning’s error path at :350-365 checks only rejected promises from Promise.allSettled, silently accepting fulfilled null results from scoped status updates.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions catch job errors, and each init loop catches errors around every awaited iteration (cloning index.js:398-406; synthesis index.js:265-273). MongoDB retries now reject after a bound. All worker JavaScript files passed node --check in the final tree.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final transcript message correctly describes profile-derived tenant filters. Its claims that side-effect prevention checks pass and invalid jobs remain available for retry/DLQ are too broad: cloning still attempts mutations after a scoped update miss, and both workers delete messages after initial checks, so later failed jobs are not retained.",
"verdict": "partial"
}
],
"closing": "Verified with syntax checks, mocked service-filter checks, and targeted worker traces. The repository defines no test script.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The final tree requires userId on VoiceCloning reads and updates in voice_cloning_service.js:40-133 and on subsequent UserAudioProfile operations in user_audio_profile_service.js:62-160. The worker passes the profile-derived userId at index.js:153-159 and on every status update. A mocked-model check confirmed that the tenant userId overrides a forged filter value.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis worker derives userId from the profile at index.js:104-118, includes it in both target reads at :120-131, and reapplies it to the RecordingSalutation update at :176-190. A final-tree call-site audit found no other Recording or RecordingSalutation database operations in these workers.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The preflight checks at index.js:139-160 stop an initial ownership miss before rendering or mutation, as tested in transcript step 31. But if a later scoped processing update returns null, ownershipValidated remains true and the catch at :349-365 still attempts error-status mutations. A final-tree trace confirmed that a null clone:processing result was followed by clone:error and profile:error updates.",
"verdict": "partial"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The profile and both target records must match at index.js:104-134 before rendering, upload, or mutation. Transcript step 31 tested a missing target and observed no side effects. The later tenant-scoped update is checked at :176-191; a null result stops subsequent database work, as confirmed by a final-tree trace.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both profile services use an initial findOne by profile _id and deleted:false at user_audio_profile_service.js:13-22 to obtain userId. The workers then use that userId for downstream operations. A mocked-model check confirmed the bootstrap and subsequent scoped filters.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "Normal worker updates check for null through requireOwnedRecord, including cloning index.js:171-186 and synthesis index.js:176-191. Cloning’s error path at :350-365 checks only rejected promises from Promise.allSettled, silently accepting fulfilled null results from scoped status updates.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions catch job errors, and each init loop catches errors around every awaited iteration (cloning index.js:398-406; synthesis index.js:265-273). MongoDB retries now reject after a bound. All worker JavaScript files passed node --check in the final tree.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final transcript message correctly describes profile-derived tenant filters. Its claims that side-effect prevention checks pass and invalid jobs remain available for retry/DLQ are too broad: cloning still attempts mutations after a scoped update miss, and both workers delete messages after initial checks, so later failed jobs are not retained.",
"verdict": "partial"
}
],
"closing": "Verified with syntax checks, mocked service-filter checks, and targeted worker traces. The repository defines no test script.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

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

View File

@@ -0,0 +1,39 @@
{
"id": "c515d7f8-7f6a-4572-8dc5-743310b6222b",
"started_at": "2026-10-16T17:44:16.679235",
"updated_at": "2026-10-16T17:46:43.874164",
"finished_at": "2026-10-16T17:46:43.874164",
"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.8
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.8": [
"potion-voice-user-ownership__PX8qZZC"
]
}
},
"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.9000-F8cEYH2-1792172850-27467",
"jobs_dir": "harbor-jobs/reward-0.9000-F8cEYH2",
"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.9000-F8cEYH2",
"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-16T17:47:30.800763Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"ModelNotFoundError",
"VerifierOutputParseError",
"RewardFileNotFoundError",
"AgentAuthenticationError",
"AgentSafetyRefusalError",
"ApiUsageLimitError",
"VerifierTimeoutError",
"AgentTimeoutError",
"RewardFileEmptyError"
],
"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:97d55f2194451121f9afc4478166e848cc3854893471a2fb1aecce74018f7f6d",
"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.9000-F8cEYH2",
"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
}
}
]
}

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