This commit is contained in:
2026-10-22 14:33:33 -04:00
parent 03b57dfc13
commit 9225540732
246 changed files with 28854 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-reward-0.7700-auZATkH-1792692770-12192",
"jobs_dir": "harbor-jobs/reward-0.7700-auZATkH",
"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.7700-auZATkH",
"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-22T18:12:50.758782Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"ModelNotFoundError",
"VerifierTimeoutError",
"AgentSafetyRefusalError",
"AgentTimeoutError",
"RewardFileEmptyError",
"RewardFileNotFoundError",
"AgentAuthenticationError",
"ApiUsageLimitError",
"VerifierOutputParseError"
],
"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:62f127e2d7acca7be9d2dc877aacfadc21a899b67287c828ba333fed7d7460bd",
"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.7700-auZATkH",
"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__BNwzyyX",
"trials_dir": "harbor-jobs/reward-0.7700-auZATkH/regrade-reward-0.7700-auZATkH-1792692770-12192",
"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.7700-auZATkH",
"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": "40152424-68a8-42a2-bb24-e355f220bc9f"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:62f127e2d7acca7be9d2dc877aacfadc21a899b67287c828ba333fed7d7460bd",
"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.7700-auZATkH",
"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": "df02c93f-5278-4778-98e1-b94165bb2577",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__BNwzyyX",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.7700-auZATkH/regrade-reward-0.7700-auZATkH-1792692770-12192/potion-voice-user-ownership__BNwzyyX",
"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": "7b10e5fac125435c52addc6043e81d08b04ef90e1a04bf71a3fb31635e3c5f34",
"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__BNwzyyX",
"trials_dir": "harbor-jobs/reward-0.7700-auZATkH/regrade-reward-0.7700-auZATkH-1792692770-12192",
"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.7700-auZATkH",
"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": "40152424-68a8-42a2-bb24-e355f220bc9f"
},
"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.98
}
},
"exception_info": null,
"started_at": "2026-10-22T18:12:51.014915Z",
"finished_at": "2026-10-22T18:15:31.741267Z",
"environment_setup": {
"started_at": "2026-10-22T18:12:51.114283Z",
"finished_at": "2026-10-22T18:12:54.479375Z"
},
"agent_setup": {
"started_at": "2026-10-22T18:12:54.479430Z",
"finished_at": "2026-10-22T18:12:54.479482Z"
},
"agent_execution": {
"started_at": "2026-10-22T18:12:54.479543Z",
"finished_at": "2026-10-22T18:12:54.832015Z"
},
"verifier": {
"started_at": "2026-10-22T18:12:55.365108Z",
"finished_at": "2026-10-22T18:15:27.576709Z"
},
"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,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 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 isObjectId = (value) =>
value instanceof mongoose.Types.ObjectId ||
(typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value))
class TenantValidationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantValidationError'
}
}
const requireTenantUpdate = (record, recordType) => {
if (!record) {
throw new TenantValidationError(
`Tenant-scoped ${recordType} update did not match a record`
)
}
return record
}
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 processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve) => {
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
const { metadata, input, _id, userAudioProfileId } = job._doc
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantValidated = false
let userAudioProfileFilter
let voiceCloningFilter
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
if (!isObjectId(_id) || !isObjectId(userAudioProfileId)) {
throw new TenantValidationError(
'Voice cloning job has invalid ownership identifiers'
)
}
// The profile lookup is the only unscoped query. Its persisted
// userId becomes the tenant context for every subsequent operation.
const userAudioProfile =
await userAudioProfileService.readByIdForTenantResolution(
userAudioProfileId
)
if (!userAudioProfile || !userAudioProfile.userId) {
throw new TenantValidationError(
'Unable to establish tenant from user audio profile'
)
}
const userId = userAudioProfile.userId
userAudioProfileFilter = {
_id: userAudioProfileId,
userId,
}
voiceCloningFilter = {
_id,
userId,
userAudioProfileId,
}
const voiceCloning = await voiceCloningService.read(
voiceCloningFilter
)
if (!voiceCloning) {
throw new TenantValidationError(
'Voice cloning job does not belong to the resolved tenant and profile'
)
}
tenantValidated = true
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
const [processingVoiceCloning, processingUserAudioProfile] =
await Promise.all([
voiceCloningService.update(voiceCloningFilter, {
status: 'processing',
}),
userAudioProfileService.update(userAudioProfileFilter, {
status: 'processing',
}),
])
requireTenantUpdate(processingVoiceCloning, 'voice cloning job')
requireTenantUpdate(
processingUserAudioProfile,
'user audio profile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireTenantUpdate(
await voiceCloningService.update(voiceCloningFilter, {
status: 'completed',
}),
'voice cloning job'
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
requireTenantUpdate(
await userAudioProfileService.update(userAudioProfileFilter, {
status: 'completed',
training_model_path,
}),
'user audio profile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireTenantUpdate(
await userAudioProfileService.update(userAudioProfileFilter, {
training_model_s3_path,
}),
'user audio profile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(error)
// Never mutate records after a failed ownership check. Operational
// failures after validation may only update the validated tenant.
if (tenantValidated && !(error instanceof TenantValidationError)) {
const errorUpdates = await Promise.allSettled([
voiceCloningService.update(voiceCloningFilter, {
status: 'error',
}),
userAudioProfileService.update(userAudioProfileFilter, {
status: 'error',
}),
])
errorUpdates
.filter((result) => result.status === 'rejected')
.forEach((result) => Bugsnag.notify(result.reason))
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
try {
if (mongoose.connection.readyState !== 0) {
await mongoose.connection.close()
}
} catch (error) {
console.error('Unable to close Mongo DB connection', { error })
Bugsnag.notify(error)
}
resolve()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue }

View File

@@ -0,0 +1,194 @@
const StringifyUtils = require('../../app/services/utils/logService')
const mongoose = require('mongoose')
const isObjectId = (value) =>
value instanceof mongoose.Types.ObjectId ||
(typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value))
const scopedFilter = (filter, operation) => {
if (!filter || !isObjectId(filter.userId)) {
throw new Error(
`A valid userId is required to ${operation} a user audio profile`
)
}
if (filter._id && !isObjectId(filter._id)) {
throw new Error(
`A valid _id is required to ${operation} a user audio profile`
)
}
return {
...filter,
deleted: false,
}
}
const safeUpdates = (updates = {}) => {
const fields = { ...updates }
delete fields._id
delete fields.userId
delete fields.deleted
return fields
}
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 foundModel = await UserAudioProfileModel.findOne(
scopedFilter(filter, 'read')
)
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 lookup. A worker uses the profile
// itself to resolve the trusted userId before accessing any other record.
const readByIdForTenantResolution = (UserAudioProfileModel) => async (_id) => {
try {
if (!isObjectId(_id)) {
throw new Error(
'A valid userAudioProfileId is required to resolve a tenant'
)
}
return await UserAudioProfileModel.findOne({ _id, deleted: false })
} catch (error) {
const details = { _id }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readByIdForTenantResolution',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find(
scopedFilter(filter, 'find')
)
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 (filter, updates) => {
try {
if (!filter || !isObjectId(filter._id)) {
throw new Error('A valid _id is required to update a user audio profile')
}
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopedFilter(filter, 'update'),
{ $set: safeUpdates(updates) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { filter, updates }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopedFilter(filter, 'remove'),
{
$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 updatedModel = await UserAudioProfileModel.updateMany(
scopedFilter(filter, 'remove'),
{
$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),
readByIdForTenantResolution:
readByIdForTenantResolution(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,182 @@
const StringifyUtils = require('../../app/services/utils/logService')
const mongoose = require('mongoose')
const isObjectId = (value) =>
value instanceof mongoose.Types.ObjectId ||
(typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value))
const scopedFilter = (filter, operation) => {
if (!filter || !isObjectId(filter.userId)) {
throw new Error(
`A valid userId is required to ${operation} a voice cloning job`
)
}
if (filter._id && !isObjectId(filter._id)) {
throw new Error(
`A valid _id is required to ${operation} a voice cloning job`
)
}
if (
filter.userAudioProfileId &&
!isObjectId(filter.userAudioProfileId)
) {
throw new Error(
`A valid userAudioProfileId is required to ${operation} a voice cloning job`
)
}
return {
...filter,
deleted: false,
}
}
const safeUpdates = (updates = {}) => {
const fields = { ...updates }
delete fields._id
delete fields.userId
delete fields.userAudioProfileId
delete fields.deleted
return fields
}
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 foundModel = await VoiceCloningModel.findOne(
scopedFilter(filter, 'read')
)
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 foundModels = await VoiceCloningModel.find(
scopedFilter(filter, 'find')
)
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (filter, updates) => {
try {
if (!filter || !isObjectId(filter._id)) {
throw new Error('A valid _id is required to update a voice cloning job')
}
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
scopedFilter(filter, 'update'),
{ $set: safeUpdates(updates) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { filter, updates }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
scopedFilter(filter, 'remove'),
{
$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 updatedModel = await VoiceCloningModel.updateMany(
scopedFilter(filter, 'remove'),
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,312 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
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')
const isObjectId = (value) =>
value instanceof mongoose.Types.ObjectId ||
(typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value))
class TenantValidationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantValidationError'
}
}
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 processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve) => {
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
if (
!isObjectId(userAudioProfileId) ||
!isObjectId(salutationId) ||
!isObjectId(recordingId)
) {
throw new TenantValidationError(
'Synthesis job has invalid ownership identifiers'
)
}
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
await connectDB(DB_URI)
// This profile-by-ID lookup is intentionally the only unscoped
// query. Its persisted userId establishes the tenant context.
const userAudioProfile =
await userAudioProfileService.readByIdForTenantResolution(
userAudioProfileId
)
if (
!userAudioProfile ||
!userAudioProfile.userId ||
userAudioProfile.status !== 'completed'
) {
throw new TenantValidationError(
'Unable to establish tenant from a completed user audio profile'
)
}
const { training_model_path, userId } = userAudioProfile
// Establish ownership of every queue-supplied target before audio
// rendering, uploads, or database mutations are allowed to begin.
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
throw new TenantValidationError(
'Recording or recording salutation does not belong to 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 || {}
if (
!voice_model_light_path ||
!voice_model_config_light_path ||
!voice_model_speakers_file_path
) {
throw new Error('Audio profile training model is incomplete')
}
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')
const updatedRecordingSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedRecordingSalutation) {
throw new TenantValidationError(
'Tenant ownership changed before recording salutation update'
)
}
// Create or update the reusable salutation only after all target
// ownership checks have succeeded.
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)
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
} finally {
try {
if (mongoose.connection.readyState !== 0) {
await mongoose.connection.close()
}
} catch (error) {
console.error('Unable to close Mongo DB connection', { error })
Bugsnag.notify(error)
}
resolve()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue }

View File

@@ -0,0 +1,194 @@
const StringifyUtils = require('../../app/services/utils/logService')
const mongoose = require('mongoose')
const isObjectId = (value) =>
value instanceof mongoose.Types.ObjectId ||
(typeof value === 'string' && /^[a-fA-F0-9]{24}$/.test(value))
const scopedFilter = (filter, operation) => {
if (!filter || !isObjectId(filter.userId)) {
throw new Error(
`A valid userId is required to ${operation} a user audio profile`
)
}
if (filter._id && !isObjectId(filter._id)) {
throw new Error(
`A valid _id is required to ${operation} a user audio profile`
)
}
return {
...filter,
deleted: false,
}
}
const safeUpdates = (updates = {}) => {
const fields = { ...updates }
delete fields._id
delete fields.userId
delete fields.deleted
return fields
}
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 foundModel = await UserAudioProfileModel.findOne(
scopedFilter(filter, 'read')
)
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 lookup. A worker uses the profile
// itself to resolve the trusted userId before accessing any other record.
const readByIdForTenantResolution = (UserAudioProfileModel) => async (_id) => {
try {
if (!isObjectId(_id)) {
throw new Error(
'A valid userAudioProfileId is required to resolve a tenant'
)
}
return await UserAudioProfileModel.findOne({ _id, deleted: false })
} catch (error) {
const details = { _id }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readByIdForTenantResolution',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find(
scopedFilter(filter, 'find')
)
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 (filter, updates) => {
try {
if (!filter || !isObjectId(filter._id)) {
throw new Error('A valid _id is required to update a user audio profile')
}
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopedFilter(filter, 'update'),
{ $set: safeUpdates(updates) },
{
new: true
}
)
return updatedModel
} catch (error) {
const details = { filter, updates }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
scopedFilter(filter, 'remove'),
{
$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 updatedModel = await UserAudioProfileModel.updateMany(
scopedFilter(filter, 'remove'),
{
$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),
readByIdForTenantResolution:
readByIdForTenantResolution(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.98 (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 includes it in its VoiceCloning and profile filters. All called reads and updates use those filters; the service helpers also require a valid userId. The sole ID-only read is the profile bootstrap.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis worker uses the profile-derived userId in RecordingSalutation and Recording reads, the RecordingSalutation update, and the called Salutation read/update path. The inserted Job carries the same userId. A caller search found no other model operations in the worker path.
## cloning-prevent-unauthorized-side-effects — PASS
The worker validates IDs, resolves the profile, and confirms the tenant-owned VoiceCloning record before filesystem work, training, or target-record updates. Its catch path skips status writes when tenant validation fails. Mocked missing-profile and ownership-miss runs produced no target updates or rendering.
## synthesis-prevent-unauthorized-side-effects — PASS
The worker verifies the profile and both tenant-owned target records before rendering, uploading, or writing records. Its failure path only reports the error. Mocked missing-profile and target-record misses produced no rendering, uploads, or database writes.
## initial-profile-tenant-resolution — PASS
Both workers use the explicit UserAudioProfile lookup by ID to obtain the persisted userId, then require that userId before downstream operations. The helper validates the ID shape.
## scoped-update-null-handling — PARTIAL
The cloning worker checks normal scoped update results, and synthesis checks the RecordingSalutation update result. However, Salutation.updateOrCreate can return null when its scoped update matches nothing; the synthesis worker ignores that result and still inserts a Job. An independent mocked worker run reproduced this. Cloning catch-block status updates also ignore fulfilled null results. These are post-bootstrap scoped-update defects.
## worker-loop-crash-prevention — PASS
Both workers catch per-message and outer polling errors, close MongoDB in finally, and resolve the polling iteration so their loops can continue. Mocked preflight failures returned normally.
## refactor-summary-accuracy — PARTIAL
The final summary accurately describes profile bootstrap, tenant filtering, and preflight protection. Its broad claim that mutations stop on ownership failure omits the null Salutation-update path, where synthesis still inserts a Job.
## Closing
All worker JavaScript files passed syntax checks, and git diff --check was clean. Runtime checks used mocked queues and models; no live MongoDB integration test was available.

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.98 (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 includes it in its VoiceCloning and profile filters. All called reads and updates use those filters; the service helpers also require a valid userId. The sole ID-only read is the profile bootstrap.
## synthesis-tenant-isolation-queries-updates — PASS
The synthesis worker uses the profile-derived userId in RecordingSalutation and Recording reads, the RecordingSalutation update, and the called Salutation read/update path. The inserted Job carries the same userId. A caller search found no other model operations in the worker path.
## cloning-prevent-unauthorized-side-effects — PASS
The worker validates IDs, resolves the profile, and confirms the tenant-owned VoiceCloning record before filesystem work, training, or target-record updates. Its catch path skips status writes when tenant validation fails. Mocked missing-profile and ownership-miss runs produced no target updates or rendering.
## synthesis-prevent-unauthorized-side-effects — PASS
The worker verifies the profile and both tenant-owned target records before rendering, uploading, or writing records. Its failure path only reports the error. Mocked missing-profile and target-record misses produced no rendering, uploads, or database writes.
## initial-profile-tenant-resolution — PASS
Both workers use the explicit UserAudioProfile lookup by ID to obtain the persisted userId, then require that userId before downstream operations. The helper validates the ID shape.
## scoped-update-null-handling — PARTIAL
The cloning worker checks normal scoped update results, and synthesis checks the RecordingSalutation update result. However, Salutation.updateOrCreate can return null when its scoped update matches nothing; the synthesis worker ignores that result and still inserts a Job. An independent mocked worker run reproduced this. Cloning catch-block status updates also ignore fulfilled null results. These are post-bootstrap scoped-update defects.
## worker-loop-crash-prevention — PASS
Both workers catch per-message and outer polling errors, close MongoDB in finally, and resolve the polling iteration so their loops can continue. Mocked preflight failures returned normally.
## refactor-summary-accuracy — PARTIAL
The final summary accurately describes profile bootstrap, tenant filtering, and preflight protection. Its broad claim that mutations stop on ownership failure omits the null Salutation-update path, where synthesis still inserts a Job.
## Closing
All worker JavaScript files passed syntax checks, and git diff --check was clean. Runtime checks used mocked queues and models; no live MongoDB integration test was available.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-22T18:12:55Z",
"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": "ce5ad0f6e94a9d26f691a6b835d34b8c0bfc61c801d916c2d5088fbdf36a66db",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a164d0-f00b-7c12-ab97-052d21d9169f", "usage": {"input_tokens": 1257954, "cached_input_tokens": 1181443, "cache_write_input_tokens": 76448, "output_tokens": 10518, "reasoning_output_tokens": 4717}}

View File

@@ -0,0 +1 @@
{"session_id": "01a164d0-f00b-7c12-ab97-052d21d9169f", "usage": {"input_tokens": 1257954, "cached_input_tokens": 1181443, "cache_write_input_tokens": 76448, "output_tokens": 10518, "reasoning_output_tokens": 4717}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.98
mean: 0.9800
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.8GrClzpk"))

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.8GrClzpk"))

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 includes it in its VoiceCloning and profile filters. All called reads and updates use those filters; the service helpers also require a valid userId. The sole ID-only read is the profile bootstrap.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis worker uses the profile-derived userId in RecordingSalutation and Recording reads, the RecordingSalutation update, and the called Salutation read/update path. The inserted Job carries the same userId. A caller search found no other model operations in the worker path.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The worker validates IDs, resolves the profile, and confirms the tenant-owned VoiceCloning record before filesystem work, training, or target-record updates. Its catch path skips status writes when tenant validation fails. Mocked missing-profile and ownership-miss runs produced no target updates or rendering.",
"verdict": "pass"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The worker verifies the profile and both tenant-owned target records before rendering, uploading, or writing records. Its failure path only reports the error. Mocked missing-profile and target-record misses produced no rendering, uploads, or database writes.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both workers use the explicit UserAudioProfile lookup by ID to obtain the persisted userId, then require that userId before downstream operations. The helper validates the ID shape.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The cloning worker checks normal scoped update results, and synthesis checks the RecordingSalutation update result. However, Salutation.updateOrCreate can return null when its scoped update matches nothing; the synthesis worker ignores that result and still inserts a Job. An independent mocked worker run reproduced this. Cloning catch-block status updates also ignore fulfilled null results. These are post-bootstrap scoped-update defects.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch per-message and outer polling errors, close MongoDB in finally, and resolve the polling iteration so their loops can continue. Mocked preflight failures returned normally.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final summary accurately describes profile bootstrap, tenant filtering, and preflight protection. Its broad claim that mutations stop on ownership failure omits the null Salutation-update path, where synthesis still inserts a Job.",
"verdict": "partial"
}
],
"closing": "All worker JavaScript files passed syntax checks, and git diff --check was clean. Runtime checks used mocked queues and models; no live MongoDB integration test was available.",
"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 includes it in its VoiceCloning and profile filters. All called reads and updates use those filters; the service helpers also require a valid userId. The sole ID-only read is the profile bootstrap.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The synthesis worker uses the profile-derived userId in RecordingSalutation and Recording reads, the RecordingSalutation update, and the called Salutation read/update path. The inserted Job carries the same userId. A caller search found no other model operations in the worker path.",
"verdict": "pass"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The worker validates IDs, resolves the profile, and confirms the tenant-owned VoiceCloning record before filesystem work, training, or target-record updates. Its catch path skips status writes when tenant validation fails. Mocked missing-profile and ownership-miss runs produced no target updates or rendering.",
"verdict": "pass"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The worker verifies the profile and both tenant-owned target records before rendering, uploading, or writing records. Its failure path only reports the error. Mocked missing-profile and target-record misses produced no rendering, uploads, or database writes.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both workers use the explicit UserAudioProfile lookup by ID to obtain the persisted userId, then require that userId before downstream operations. The helper validates the ID shape.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The cloning worker checks normal scoped update results, and synthesis checks the RecordingSalutation update result. However, Salutation.updateOrCreate can return null when its scoped update matches nothing; the synthesis worker ignores that result and still inserts a Job. An independent mocked worker run reproduced this. Cloning catch-block status updates also ignore fulfilled null results. These are post-bootstrap scoped-update defects.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch per-message and outer polling errors, close MongoDB in finally, and resolve the polling iteration so their loops can continue. Mocked preflight failures returned normally.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final summary accurately describes profile bootstrap, tenant filtering, and preflight protection. Its broad claim that mutations stop on ownership failure omits the null Salutation-update path, where synthesis still inserts a Job.",
"verdict": "partial"
}
],
"closing": "All worker JavaScript files passed syntax checks, and git diff --check was clean. Runtime checks used mocked queues and models; no live MongoDB integration test was available.",
"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.98 form=trinary criteria=8 excluded_extra_credit=0 partial_extra_credit=0 total_weight=66
grader sample 1: 0.98
reward: 0.9800 correctness: (none)
0.9800
{"reward": 0.9800}

View File

@@ -0,0 +1,39 @@
{
"id": "40152424-68a8-42a2-bb24-e355f220bc9f",
"started_at": "2026-10-22T18:12:50.667481",
"updated_at": "2026-10-22T18:15:31.746229",
"finished_at": "2026-10-22T18:15:31.746229",
"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.98
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.98": [
"potion-voice-user-ownership__BNwzyyX"
]
}
},
"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.8000-W5t25ZE-1792692989-13293",
"jobs_dir": "harbor-jobs/reward-0.8000-W5t25ZE",
"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.8000-W5t25ZE",
"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-22T18:16:30.592156Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"RewardFileNotFoundError",
"AgentTimeoutError",
"ApiUsageLimitError",
"VerifierTimeoutError",
"RewardFileEmptyError",
"AgentAuthenticationError",
"VerifierOutputParseError",
"AgentSafetyRefusalError",
"ModelNotFoundError"
],
"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:62f127e2d7acca7be9d2dc877aacfadc21a899b67287c828ba333fed7d7460bd",
"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.8000-W5t25ZE",
"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__qALtfzH",
"trials_dir": "harbor-jobs/reward-0.8000-W5t25ZE/regrade-reward-0.8000-W5t25ZE-1792692989-13293",
"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.8000-W5t25ZE",
"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": "94635fd0-fff3-4351-b4b2-ab8e54c1dde3"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:62f127e2d7acca7be9d2dc877aacfadc21a899b67287c828ba333fed7d7460bd",
"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.8000-W5t25ZE",
"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": "75733d30-a6d0-4504-a802-b3aa9a33de41",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__qALtfzH",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.8000-W5t25ZE/regrade-reward-0.8000-W5t25ZE-1792692989-13293/potion-voice-user-ownership__qALtfzH",
"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": "effc9a71f60be19883b98fff02f9f8534e48b286fba8eb2bf38fd772b95f6fa4",
"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__qALtfzH",
"trials_dir": "harbor-jobs/reward-0.8000-W5t25ZE/regrade-reward-0.8000-W5t25ZE-1792692989-13293",
"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.8000-W5t25ZE",
"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": "94635fd0-fff3-4351-b4b2-ab8e54c1dde3"
},
"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.95
}
},
"exception_info": null,
"started_at": "2026-10-22T18:16:30.838831Z",
"finished_at": "2026-10-22T18:21:14.146690Z",
"environment_setup": {
"started_at": "2026-10-22T18:16:30.946393Z",
"finished_at": "2026-10-22T18:16:34.407295Z"
},
"agent_setup": {
"started_at": "2026-10-22T18:16:34.407387Z",
"finished_at": "2026-10-22T18:16:34.407521Z"
},
"agent_execution": {
"started_at": "2026-10-22T18:16:34.407646Z",
"finished_at": "2026-10-22T18:16:34.812570Z"
},
"verifier": {
"started_at": "2026-10-22T18:16:35.357197Z",
"finished_at": "2026-10-22T18:21:09.929635Z"
},
"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,19 @@
class TenantValidationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantValidationError'
}
}
const requireUserId = (userId) => {
if (!userId) {
throw new TenantValidationError('Unable to establish record ownership')
}
return userId
}
module.exports = {
TenantValidationError,
requireUserId,
}

View File

@@ -0,0 +1,414 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
const {
TenantValidationError,
} = require('../app/services/utils/tenantValidation')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const requireOwnedRecord = (record, recordName) => {
if (!record) {
throw new TenantValidationError(
`${recordName} was not found for the resolved tenant`
)
}
return record
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId } = 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
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
// The profile lookup is the one unscoped lookup used to establish the
// tenant. Every subsequent read and write uses its persisted userId.
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readById(userAudioProfileId),
'UserAudioProfile'
)
if (!userAudioProfile.userId) {
throw new TenantValidationError(
'UserAudioProfile does not have an owner'
)
}
const userId = userAudioProfile.userId
requireOwnedRecord(
await voiceCloningService.read(
{ _id, userAudioProfileId },
userId
),
'VoiceCloning'
)
tenantContext = { userId }
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)
// Never perform fallback mutations unless both records were already
// validated against the same persisted tenant.
if (tenantContext && !(error instanceof TenantValidationError)) {
try {
await voiceCloningService.update(
{ _id, status: 'error' },
tenantContext.userId
)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
tenantContext.userId
)
} catch (statusUpdateError) {
console.error('Unable to update voice cloning error status', {
error: statusUpdateError,
})
Bugsnag.notify(statusUpdateError)
}
}
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,170 @@
const StringifyUtils = require('../../app/services/utils/logService')
const { requireUserId } = require('../../app/services/utils/tenantValidation')
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 readById = (UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: userAudioProfileId,
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 {
requireUserId(userId)
const foundModel = await UserAudioProfileModel.findOne({
...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 {
requireUserId(userId)
const foundModels = await UserAudioProfileModel.find({
...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 {
requireUserId(userId)
const updates = { ...data }
delete updates._id
delete updates.userId
delete updates.deleted
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id: data._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, userId) => {
try {
requireUserId(userId)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...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 {
requireUserId(userId)
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...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,154 @@
const StringifyUtils = require('../../app/services/utils/logService')
const { requireUserId } = require('../../app/services/utils/tenantValidation')
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 {
requireUserId(userId)
const foundModel = await VoiceCloningModel.findOne({
...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 {
requireUserId(userId)
const foundModels = await VoiceCloningModel.find({
...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 {
requireUserId(userId)
const updates = { ...data }
delete updates._id
delete updates.userId
delete updates.deleted
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ _id: data._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, userId) => {
try {
requireUserId(userId)
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...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 {
requireUserId(userId)
const updatedModel = await VoiceCloningModel.updateMany(
{ ...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,292 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
const {
TenantValidationError,
} = require('../app/services/utils/tenantValidation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const requireOwnedRecord = (record, recordName) => {
if (!record) {
throw new TenantValidationError(
`${recordName} was not found for the resolved tenant`
)
}
return record
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
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)
// This is the one unscoped lookup: the persisted profile establishes
// the tenant used by every subsequent database operation.
const userAudioProfile = requireOwnedRecord(
await userAudioProfileService.readById(userAudioProfileId),
'UserAudioProfile'
)
if (!userAudioProfile.userId) {
throw new TenantValidationError(
'UserAudioProfile does not have an owner'
)
}
if (userAudioProfile.status !== 'completed') {
throw new TenantValidationError(
'UserAudioProfile is not ready for synthesis'
)
}
const { training_model_path, userId } = userAudioProfile
// Establish ownership of every queue-supplied record before invoking
// the renderer, uploading audio, or mutating the database.
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')
if (!training_model_path) {
throw new TenantValidationError(
'UserAudioProfile does not have a training model'
)
}
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')
requireOwnedRecord(
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
),
'RecordingSalutation'
)
// Create or update the reusable salutation only after the scoped
// recording mutation confirms that ownership still matches.
await salutationService.updateOrCreate(
{
firstName: 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: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
// create the job for the ai to create processing
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)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,170 @@
const StringifyUtils = require('../../app/services/utils/logService')
const { requireUserId } = require('../../app/services/utils/tenantValidation')
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 readById = (UserAudioProfileModel) => async (userAudioProfileId) => {
try {
return await UserAudioProfileModel.findOne({
_id: userAudioProfileId,
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 {
requireUserId(userId)
const foundModel = await UserAudioProfileModel.findOne({
...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 {
requireUserId(userId)
const foundModels = await UserAudioProfileModel.find({
...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 {
requireUserId(userId)
const updates = { ...data }
delete updates._id
delete updates.userId
delete updates.deleted
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id: data._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, userId) => {
try {
requireUserId(userId)
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...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 {
requireUserId(userId)
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...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.95 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The cloning handler resolves userId from UserAudioProfile, then reads VoiceCloning by _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:148-165). Its normal and error-status writes pass the same userId (lines 175-190, 291-342, 355-367). The VoiceCloning and profile service read/find/update/remove predicates enforce userId and reject a missing tenant (voice_cloning_service.js:33-125; user_audio_profile_service.js:49-140). Independent mock query assertions and node --check passed.
## synthesis-tenant-isolation-queries-updates — PARTIAL
The active synthesis path scopes RecordingSalutation and Recording preflight reads by profile-derived userId and scopes the RecordingSalutation update (voice-synthsizer-job-handler/index.js:107-141,188-203). updateOrCreate passes userId into its Salutation read/update, and Job insertion includes userId (lines 207-246; salutation_service.js:45-61). However the exported Salutation read/find/modify methods still allow unscoped queries or updates (salutation_service.js:7-20,32-41), as do Job read/find/update/remove/removeMany (job_service.js:32-113). These unchanged service APIs leave the requested all-operations audit incomplete, although the current handler calls use scoped paths.
## cloning-prevent-unauthorized-side-effects — PASS
The cloning handler requires a profile and userId, then a VoiceCloning row matching both that userId and profile ID before directory creation, status writes, downloads, or Python execution (voice-cloning-job-handler/index.js:142-175,193-259). A failed preflight throws into the catch; tenantContext is assigned only after both checks, so the catch's status writes are skipped before ownership is established (lines 166,344-376).
## synthesis-prevent-unauthorized-side-effects — PASS
The synthesis handler requires a profile with userId and completed status, then requires tenant-scoped RecordingSalutation and Recording matches before invoking Python, uploading to S3, or writing database rows (voice-synthsizer-job-handler/index.js:107-165,173-246). Failed preflight checks enter a catch with no fallback database mutation (lines 250-256).
## initial-profile-tenant-resolution — PASS
Both handlers call readById(userAudioProfileId) as their bootstrap read (voice-cloning-job-handler/index.js:148-158; voice-synthsizer-job-handler/index.js:107-124). Each service's readById queries UserAudioProfile by _id and deleted:false, then the handler requires the returned record's persisted userId before downstream work (both user_audio_profile_service.js files:33-46).
## scoped-update-null-handling — PARTIAL
The handler checks null results from its main scoped cloning writes and RecordingSalutation update with requireOwnedRecord (voice-cloning-job-handler/index.js:175-190,291-342; voice-synthsizer-job-handler/index.js:188-203). But Salutation.updateOrCreate returns a null result from its tenant-scoped update without checking it (salutation_service.js:23-29,45-61), and the synthesis handler can then insert a Job (index.js:207-246). The cloning catch also ignores null results from scoped error-status updates (index.js:355-367). Independent mock assertions confirmed that these service updates can return null.
## worker-loop-crash-prevention — PASS
Both workers catch message-processing exceptions inside processQueue, resolve the polling iteration, and retain outer catches around fetch/parse failures; init continues calling processQueue in a loop (voice-cloning-job-handler/index.js:344-412; voice-synthsizer-job-handler/index.js:250-291). The validation errors therefore use the existing per-message exception boundary.
## refactor-summary-accuracy — PARTIAL
The agent's final message correctly describes profile-derived tenant context, pre-render ownership checks, and continued polling, and its reported syntax/query assertions appear in transcript steps 17, 20, and 22. Its statement that all relevant reads/updates include userId overstates the final tree: exported Salutation and Job read/update methods remain unscoped (voice-synthsizer-job-handler/salutation/salutation_service.js:7-41; job/job_service.js:32-113).
## Closing
Node syntax and independent mock query checks passed; no live MongoDB/SQS integration check was available.

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.95 (severity-weighted mean over 8 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
The cloning handler resolves userId from UserAudioProfile, then reads VoiceCloning by _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:148-165). Its normal and error-status writes pass the same userId (lines 175-190, 291-342, 355-367). The VoiceCloning and profile service read/find/update/remove predicates enforce userId and reject a missing tenant (voice_cloning_service.js:33-125; user_audio_profile_service.js:49-140). Independent mock query assertions and node --check passed.
## synthesis-tenant-isolation-queries-updates — PARTIAL
The active synthesis path scopes RecordingSalutation and Recording preflight reads by profile-derived userId and scopes the RecordingSalutation update (voice-synthsizer-job-handler/index.js:107-141,188-203). updateOrCreate passes userId into its Salutation read/update, and Job insertion includes userId (lines 207-246; salutation_service.js:45-61). However the exported Salutation read/find/modify methods still allow unscoped queries or updates (salutation_service.js:7-20,32-41), as do Job read/find/update/remove/removeMany (job_service.js:32-113). These unchanged service APIs leave the requested all-operations audit incomplete, although the current handler calls use scoped paths.
## cloning-prevent-unauthorized-side-effects — PASS
The cloning handler requires a profile and userId, then a VoiceCloning row matching both that userId and profile ID before directory creation, status writes, downloads, or Python execution (voice-cloning-job-handler/index.js:142-175,193-259). A failed preflight throws into the catch; tenantContext is assigned only after both checks, so the catch's status writes are skipped before ownership is established (lines 166,344-376).
## synthesis-prevent-unauthorized-side-effects — PASS
The synthesis handler requires a profile with userId and completed status, then requires tenant-scoped RecordingSalutation and Recording matches before invoking Python, uploading to S3, or writing database rows (voice-synthsizer-job-handler/index.js:107-165,173-246). Failed preflight checks enter a catch with no fallback database mutation (lines 250-256).
## initial-profile-tenant-resolution — PASS
Both handlers call readById(userAudioProfileId) as their bootstrap read (voice-cloning-job-handler/index.js:148-158; voice-synthsizer-job-handler/index.js:107-124). Each service's readById queries UserAudioProfile by _id and deleted:false, then the handler requires the returned record's persisted userId before downstream work (both user_audio_profile_service.js files:33-46).
## scoped-update-null-handling — PARTIAL
The handler checks null results from its main scoped cloning writes and RecordingSalutation update with requireOwnedRecord (voice-cloning-job-handler/index.js:175-190,291-342; voice-synthsizer-job-handler/index.js:188-203). But Salutation.updateOrCreate returns a null result from its tenant-scoped update without checking it (salutation_service.js:23-29,45-61), and the synthesis handler can then insert a Job (index.js:207-246). The cloning catch also ignores null results from scoped error-status updates (index.js:355-367). Independent mock assertions confirmed that these service updates can return null.
## worker-loop-crash-prevention — PASS
Both workers catch message-processing exceptions inside processQueue, resolve the polling iteration, and retain outer catches around fetch/parse failures; init continues calling processQueue in a loop (voice-cloning-job-handler/index.js:344-412; voice-synthsizer-job-handler/index.js:250-291). The validation errors therefore use the existing per-message exception boundary.
## refactor-summary-accuracy — PARTIAL
The agent's final message correctly describes profile-derived tenant context, pre-render ownership checks, and continued polling, and its reported syntax/query assertions appear in transcript steps 17, 20, and 22. Its statement that all relevant reads/updates include userId overstates the final tree: exported Salutation and Job read/update methods remain unscoped (voice-synthsizer-job-handler/salutation/salutation_service.js:7-41; job/job_service.js:32-113).
## Closing
Node syntax and independent mock query checks passed; no live MongoDB/SQS integration check was available.

View File

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

View File

@@ -0,0 +1 @@
{"session_id": "01a164d6-5c70-79b3-bf1c-33cea43ccd65", "usage": {"input_tokens": 979800, "cached_input_tokens": 897599, "cache_write_input_tokens": 82150, "output_tokens": 10716, "reasoning_output_tokens": 5500}}

View File

@@ -0,0 +1 @@
{"session_id": "01a164d6-5c70-79b3-bf1c-33cea43ccd65", "usage": {"input_tokens": 979800, "cached_input_tokens": 897599, "cache_write_input_tokens": 82150, "output_tokens": 10716, "reasoning_output_tokens": 5500}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.95
mean: 0.9500
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.H95sUREX"))

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

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The cloning handler resolves userId from UserAudioProfile, then reads VoiceCloning by _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:148-165). Its normal and error-status writes pass the same userId (lines 175-190, 291-342, 355-367). The VoiceCloning and profile service read/find/update/remove predicates enforce userId and reject a missing tenant (voice_cloning_service.js:33-125; user_audio_profile_service.js:49-140). Independent mock query assertions and node --check passed.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The active synthesis path scopes RecordingSalutation and Recording preflight reads by profile-derived userId and scopes the RecordingSalutation update (voice-synthsizer-job-handler/index.js:107-141,188-203). updateOrCreate passes userId into its Salutation read/update, and Job insertion includes userId (lines 207-246; salutation_service.js:45-61). However the exported Salutation read/find/modify methods still allow unscoped queries or updates (salutation_service.js:7-20,32-41), as do Job read/find/update/remove/removeMany (job_service.js:32-113). These unchanged service APIs leave the requested all-operations audit incomplete, although the current handler calls use scoped paths.",
"verdict": "partial"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The cloning handler requires a profile and userId, then a VoiceCloning row matching both that userId and profile ID before directory creation, status writes, downloads, or Python execution (voice-cloning-job-handler/index.js:142-175,193-259). A failed preflight throws into the catch; tenantContext is assigned only after both checks, so the catch's status writes are skipped before ownership is established (lines 166,344-376).",
"verdict": "pass"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The synthesis handler requires a profile with userId and completed status, then requires tenant-scoped RecordingSalutation and Recording matches before invoking Python, uploading to S3, or writing database rows (voice-synthsizer-job-handler/index.js:107-165,173-246). Failed preflight checks enter a catch with no fallback database mutation (lines 250-256).",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both handlers call readById(userAudioProfileId) as their bootstrap read (voice-cloning-job-handler/index.js:148-158; voice-synthsizer-job-handler/index.js:107-124). Each service's readById queries UserAudioProfile by _id and deleted:false, then the handler requires the returned record's persisted userId before downstream work (both user_audio_profile_service.js files:33-46).",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The handler checks null results from its main scoped cloning writes and RecordingSalutation update with requireOwnedRecord (voice-cloning-job-handler/index.js:175-190,291-342; voice-synthsizer-job-handler/index.js:188-203). But Salutation.updateOrCreate returns a null result from its tenant-scoped update without checking it (salutation_service.js:23-29,45-61), and the synthesis handler can then insert a Job (index.js:207-246). The cloning catch also ignores null results from scoped error-status updates (index.js:355-367). Independent mock assertions confirmed that these service updates can return null.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch message-processing exceptions inside processQueue, resolve the polling iteration, and retain outer catches around fetch/parse failures; init continues calling processQueue in a loop (voice-cloning-job-handler/index.js:344-412; voice-synthsizer-job-handler/index.js:250-291). The validation errors therefore use the existing per-message exception boundary.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The agent's final message correctly describes profile-derived tenant context, pre-render ownership checks, and continued polling, and its reported syntax/query assertions appear in transcript steps 17, 20, and 22. Its statement that all relevant reads/updates include userId overstates the final tree: exported Salutation and Job read/update methods remain unscoped (voice-synthsizer-job-handler/salutation/salutation_service.js:7-41; job/job_service.js:32-113).",
"verdict": "partial"
}
],
"closing": "Node syntax and independent mock query checks passed; no live MongoDB/SQS integration check was available.",
"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 resolves userId from UserAudioProfile, then reads VoiceCloning by _id, userAudioProfileId, and that userId (voice-cloning-job-handler/index.js:148-165). Its normal and error-status writes pass the same userId (lines 175-190, 291-342, 355-367). The VoiceCloning and profile service read/find/update/remove predicates enforce userId and reject a missing tenant (voice_cloning_service.js:33-125; user_audio_profile_service.js:49-140). Independent mock query assertions and node --check passed.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The active synthesis path scopes RecordingSalutation and Recording preflight reads by profile-derived userId and scopes the RecordingSalutation update (voice-synthsizer-job-handler/index.js:107-141,188-203). updateOrCreate passes userId into its Salutation read/update, and Job insertion includes userId (lines 207-246; salutation_service.js:45-61). However the exported Salutation read/find/modify methods still allow unscoped queries or updates (salutation_service.js:7-20,32-41), as do Job read/find/update/remove/removeMany (job_service.js:32-113). These unchanged service APIs leave the requested all-operations audit incomplete, although the current handler calls use scoped paths.",
"verdict": "partial"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The cloning handler requires a profile and userId, then a VoiceCloning row matching both that userId and profile ID before directory creation, status writes, downloads, or Python execution (voice-cloning-job-handler/index.js:142-175,193-259). A failed preflight throws into the catch; tenantContext is assigned only after both checks, so the catch's status writes are skipped before ownership is established (lines 166,344-376).",
"verdict": "pass"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The synthesis handler requires a profile with userId and completed status, then requires tenant-scoped RecordingSalutation and Recording matches before invoking Python, uploading to S3, or writing database rows (voice-synthsizer-job-handler/index.js:107-165,173-246). Failed preflight checks enter a catch with no fallback database mutation (lines 250-256).",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both handlers call readById(userAudioProfileId) as their bootstrap read (voice-cloning-job-handler/index.js:148-158; voice-synthsizer-job-handler/index.js:107-124). Each service's readById queries UserAudioProfile by _id and deleted:false, then the handler requires the returned record's persisted userId before downstream work (both user_audio_profile_service.js files:33-46).",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The handler checks null results from its main scoped cloning writes and RecordingSalutation update with requireOwnedRecord (voice-cloning-job-handler/index.js:175-190,291-342; voice-synthsizer-job-handler/index.js:188-203). But Salutation.updateOrCreate returns a null result from its tenant-scoped update without checking it (salutation_service.js:23-29,45-61), and the synthesis handler can then insert a Job (index.js:207-246). The cloning catch also ignores null results from scoped error-status updates (index.js:355-367). Independent mock assertions confirmed that these service updates can return null.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch message-processing exceptions inside processQueue, resolve the polling iteration, and retain outer catches around fetch/parse failures; init continues calling processQueue in a loop (voice-cloning-job-handler/index.js:344-412; voice-synthsizer-job-handler/index.js:250-291). The validation errors therefore use the existing per-message exception boundary.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The agent's final message correctly describes profile-derived tenant context, pre-render ownership checks, and continued polling, and its reported syntax/query assertions appear in transcript steps 17, 20, and 22. Its statement that all relevant reads/updates include userId overstates the final tree: exported Salutation and Job read/update methods remain unscoped (voice-synthsizer-job-handler/salutation/salutation_service.js:7-41; job/job_service.js:32-113).",
"verdict": "partial"
}
],
"closing": "Node syntax and independent mock query checks passed; no live MongoDB/SQS integration check was available.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,9 @@
Captured 6 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
WARN: grader sample 1 attempt 1 wrote no rubric-grade.json
WARN: re-grading sample 1 from scratch (attempt 2/3)
render-rubric-grade: ok reward=0.95 form=trinary criteria=8 excluded_extra_credit=0 partial_extra_credit=0 total_weight=66
grader sample 1: 0.95
reward: 0.9500 correctness: (none)
0.9500
{"reward": 0.9500}

View File

@@ -0,0 +1,39 @@
{
"id": "94635fd0-fff3-4351-b4b2-ab8e54c1dde3",
"started_at": "2026-10-22T18:16:30.495424",
"updated_at": "2026-10-22T18:21:14.154372",
"finished_at": "2026-10-22T18:21:14.154372",
"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.95
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.95": [
"potion-voice-user-ownership__qALtfzH"
]
}
},
"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.8700-bqMyPUM-1792693549-14949",
"jobs_dir": "harbor-jobs/reward-0.8700-bqMyPUM",
"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.8700-bqMyPUM",
"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-22T18:25:49.967330Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"AgentSafetyRefusalError",
"ApiUsageLimitError",
"RewardFileNotFoundError",
"AgentTimeoutError",
"AgentAuthenticationError",
"ModelNotFoundError",
"VerifierTimeoutError",
"RewardFileEmptyError",
"VerifierOutputParseError"
],
"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:62f127e2d7acca7be9d2dc877aacfadc21a899b67287c828ba333fed7d7460bd",
"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.8700-bqMyPUM",
"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__uz4SZdJ",
"trials_dir": "harbor-jobs/reward-0.8700-bqMyPUM/regrade-reward-0.8700-bqMyPUM-1792693549-14949",
"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.8700-bqMyPUM",
"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": "b5522b09-ec29-4019-9f32-8229f16a8a99"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:62f127e2d7acca7be9d2dc877aacfadc21a899b67287c828ba333fed7d7460bd",
"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.8700-bqMyPUM",
"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": "e4267127-1017-499a-9305-99202f9b7fd3",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__uz4SZdJ",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/reward-0.8700-bqMyPUM/regrade-reward-0.8700-bqMyPUM-1792693549-14949/potion-voice-user-ownership__uz4SZdJ",
"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": "197b45101b1067d7e919a4264109a3b56c80f4ed420d62cb5f3f5ddcd95b4010",
"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__uz4SZdJ",
"trials_dir": "harbor-jobs/reward-0.8700-bqMyPUM/regrade-reward-0.8700-bqMyPUM-1792693549-14949",
"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.8700-bqMyPUM",
"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": "b5522b09-ec29-4019-9f32-8229f16a8a99"
},
"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.95
}
},
"exception_info": null,
"started_at": "2026-10-22T18:25:50.245058Z",
"finished_at": "2026-10-22T18:28:31.500082Z",
"environment_setup": {
"started_at": "2026-10-22T18:25:50.354015Z",
"finished_at": "2026-10-22T18:25:54.157822Z"
},
"agent_setup": {
"started_at": "2026-10-22T18:25:54.157879Z",
"finished_at": "2026-10-22T18:25:54.157935Z"
},
"agent_execution": {
"started_at": "2026-10-22T18:25:54.158004Z",
"finished_at": "2026-10-22T18:25:54.562571Z"
},
"verifier": {
"started_at": "2026-10-22T18:25:55.145636Z",
"finished_at": "2026-10-22T18:28:27.222301Z"
},
"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,442 @@
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) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
class TenantValidationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantValidationError'
}
}
const requireUpdatedRecord = (record, recordName) => {
if (!record) {
throw new TenantValidationError(
`${recordName} no longer matches the validated tenant scope`
)
}
return record
}
const requireValidObjectIds = (identifiers) => {
const invalidIdentifier = Object.entries(identifiers).find(
([, value]) => !mongoose.isValidObjectId(value)
)
if (invalidIdentifier) {
throw new TenantValidationError(
`${invalidIdentifier[0]} is not a valid record identifier`
)
}
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId } = 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)
requireValidObjectIds({ _id, userAudioProfileId })
// The profile lookup establishes the tenant. Every subsequent read
// and update is constrained to the userId resolved from this record.
const userAudioProfile =
await userAudioProfileService.readForTenantResolution(
userAudioProfileId
)
if (
!userAudioProfile ||
!mongoose.isValidObjectId(userAudioProfile.userId)
) {
throw new TenantValidationError(
'Unable to establish tenant from the user audio profile'
)
}
const userId = userAudioProfile.userId
const voiceCloningScope = {
_id,
userId,
userAudioProfileId,
}
const userAudioProfileScope = {
_id: userAudioProfileId,
userId,
}
const voiceCloning = await voiceCloningService.read(
voiceCloningScope
)
if (!voiceCloning) {
throw new TenantValidationError(
'Voice cloning record does not belong to the resolved tenant and profile'
)
}
tenantContext = {
voiceCloningScope,
userAudioProfileScope,
}
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
requireUpdatedRecord(
await voiceCloningService.update(voiceCloningScope, {
status: 'processing',
}),
'Voice cloning record'
)
requireUpdatedRecord(
await userAudioProfileService.update(userAudioProfileScope, {
status: 'processing',
}),
'User audio profile'
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
requireUpdatedRecord(
await voiceCloningService.update(voiceCloningScope, {
status: 'completed',
}),
'Voice cloning record'
)
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`,
}
requireUpdatedRecord(
await userAudioProfileService.update(userAudioProfileScope, {
status: 'completed',
training_model_path,
}),
'User audio profile'
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
requireUpdatedRecord(
await userAudioProfileService.update(userAudioProfileScope, {
training_model_s3_path,
}),
'User audio profile'
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
if (error instanceof TenantValidationError) {
console.error('Voice cloning job rejected by tenant validation', {
message: error.message,
})
} else if (tenantContext) {
// Only records that passed the ownership gate may be marked as
// failed. These updates remain tenant-scoped in case ownership or
// deletion state changed while the job was running.
try {
await Promise.all([
voiceCloningService.update(
tenantContext.voiceCloningScope,
{ status: 'error' }
),
userAudioProfileService.update(
tenantContext.userAudioProfileScope,
{ status: 'error' }
),
])
} catch (statusError) {
console.error('Unable to mark voice cloning job as failed', {
error: statusError,
})
Bugsnag.notify(statusError)
}
}
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,179 @@
const StringifyUtils = require('../../app/services/utils/logService')
const mongoose = require('mongoose')
const immutableFields = ['_id', 'userId', 'deleted']
const mutableData = (data) =>
Object.fromEntries(
Object.entries(data).filter(([key]) => !immutableFields.includes(key))
)
const withTenantScope = (filter) => {
if (!filter || !mongoose.isValidObjectId(filter.userId)) {
throw new Error(
'A valid userId is required to access a user audio profile'
)
}
return {
...filter,
deleted: false,
}
}
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 foundModel = await UserAudioProfileModel.findOne(
withTenantScope(filter)
)
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 lookup. The worker uses the profile
// to establish the tenant before accessing any other records or doing work.
const readForTenantResolution = (UserAudioProfileModel) => async (_id) => {
try {
if (!mongoose.isValidObjectId(_id)) {
throw new Error('A valid userAudioProfileId is required')
}
return await UserAudioProfileModel.findOne({ _id, deleted: false })
} catch (error) {
const details = { _id }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantResolution',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find(
withTenantScope(filter)
)
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 (filter, data) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenantScope(filter),
{ $set: mutableData(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { filter, data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenantScope(filter),
{
$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 updatedModel = await UserAudioProfileModel.updateMany(
withTenantScope(filter),
{
$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),
readForTenantResolution: readForTenantResolution(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,156 @@
const StringifyUtils = require('../../app/services/utils/logService')
const mongoose = require('mongoose')
const immutableFields = ['_id', 'userId', 'userAudioProfileId', 'deleted']
const mutableData = (data) =>
Object.fromEntries(
Object.entries(data).filter(([key]) => !immutableFields.includes(key))
)
const withTenantScope = (filter) => {
if (!filter || !mongoose.isValidObjectId(filter.userId)) {
throw new Error(
'A valid userId is required to access a voice cloning record'
)
}
return {
...filter,
deleted: false,
}
}
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 foundModel = await VoiceCloningModel.findOne(withTenantScope(filter))
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 foundModels = await VoiceCloningModel.find(withTenantScope(filter))
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (filter, data) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
withTenantScope(filter),
{ $set: mutableData(data) },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { filter, data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
withTenantScope(filter),
{
$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 updatedModel = await VoiceCloningModel.updateMany(
withTenantScope(filter),
{
$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,324 @@
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) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
class TenantValidationError extends Error {
constructor(message) {
super(message)
this.name = 'TenantValidationError'
}
}
const requireValidObjectIds = (identifiers) => {
const invalidIdentifier = Object.entries(identifiers).find(
([, value]) => !mongoose.isValidObjectId(value)
)
if (invalidIdentifier) {
throw new TenantValidationError(
`${invalidIdentifier[0]} is not a valid record identifier`
)
}
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
requireValidObjectIds({
userAudioProfileId,
salutationId,
recordingId,
})
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// This one profile-by-id lookup establishes the tenant context. The
// queue payload's record ids are not trusted as proof of ownership.
const userAudioProfile =
await userAudioProfileService.readForTenantResolution(
userAudioProfileId
)
if (
!userAudioProfile ||
!mongoose.isValidObjectId(userAudioProfile.userId)
) {
throw new TenantValidationError(
'Unable to establish tenant from the user audio profile'
)
}
if (userAudioProfile.status !== 'completed') {
throw new Error('Audio profile training model is not completed')
}
const userId = userAudioProfile.userId
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
throw new TenantValidationError(
'Recording targets do not belong to the resolved tenant'
)
}
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = userAudioProfile.training_model_path || {}
if (
!voice_model_light_path ||
!voice_model_config_light_path ||
!voice_model_speakers_file_path
) {
throw new Error('Audio profile training model paths are missing')
}
// No rendering or other side effects occur before all tenant-owned
// records above have been validated.
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
)
// The update repeats the ownership predicate so a record cannot be
// mutated if its tenant or deletion state changed after validation.
const updatedSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedSalutation) {
throw new TenantValidationError(
'Recording salutation no longer matches the validated tenant scope'
)
}
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: updatedSalutation._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: updatedSalutation._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
// The downstream job inherits the profile-derived tenant, rather
// than any user identifier supplied by the queue payload.
await jobService.insertMany([
{
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: updatedSalutation._id,
metadata: jobData,
},
])
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
if (error instanceof TenantValidationError) {
console.error('Synthesis job rejected by tenant validation', {
message: error.message,
})
}
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
try {
while (true) {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
}
} catch (error) {
Bugsnag.notify(error)
}
}
init()

View File

@@ -0,0 +1,179 @@
const StringifyUtils = require('../../app/services/utils/logService')
const mongoose = require('mongoose')
const immutableFields = ['_id', 'userId', 'deleted']
const mutableData = (data) =>
Object.fromEntries(
Object.entries(data).filter(([key]) => !immutableFields.includes(key))
)
const withTenantScope = (filter) => {
if (!filter || !mongoose.isValidObjectId(filter.userId)) {
throw new Error(
'A valid userId is required to access a user audio profile'
)
}
return {
...filter,
deleted: false
}
}
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 foundModel = await UserAudioProfileModel.findOne(
withTenantScope(filter)
)
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 lookup. The worker uses the profile
// to establish the tenant before accessing any other records or doing work.
const readForTenantResolution = (UserAudioProfileModel) => async (_id) => {
try {
if (!mongoose.isValidObjectId(_id)) {
throw new Error('A valid userAudioProfileId is required')
}
return await UserAudioProfileModel.findOne({ _id, deleted: false })
} catch (error) {
const details = { _id }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > readForTenantResolution',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find(
withTenantScope(filter)
)
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 (filter, data) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenantScope(filter),
{ $set: mutableData(data) },
{
new: true
}
)
return updatedModel
} catch (error) {
const details = { filter, data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
withTenantScope(filter),
{
$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 updatedModel = await UserAudioProfileModel.updateMany(
withTenantScope(filter),
{
$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),
readForTenantResolution: readForTenantResolution(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel)
}
}

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.95 (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 initial profile lookup, then reads VoiceCloning with _id, userId, and userAudioProfileId and passes tenant scopes to every normal and error-status update (voice-cloning-job-handler/index.js:167-204, 213-224, 324-395). The VoiceCloning and UserAudioProfile service read/find/update/remove methods enforce userId through withTenantScope (voice_cloning_service.js:11-21, 53-142; user_audio_profile_service.js:11-21, 53-165). The profile-by-ID bootstrap is the permitted exception.
## synthesis-tenant-isolation-queries-updates — PARTIAL
The active synthesis path scopes RecordingSalutation and Recording reads and the RecordingSalutation update with the profile-derived userId; Salutation.updateOrCreate uses that userId for its read/update/create, and the new Job receives it (voice-synthsizer-job-handler/index.js:139-156, 210-273; salutation/salutation_service.js:45-62). But other exported synthesis service operations still allow unscoped reads or updates: Salutation.read/find accept filters without userId and modify filters only by _id or transcriptId (salutation_service.js:7-42); Job.read/find/update/remove/removeMany also lack a required userId (job/job_service.js:32-123). Thus the requested all-operations scope is incomplete, although those helpers are not called by this worker's current message path.
## cloning-prevent-unauthorized-side-effects — PASS
The cloning worker rejects invalid IDs or a missing/invalid profile userId before file creation, rendering, or Mongo mutations, and also rejects a missing tenant-scoped VoiceCloning record before those effects (index.js:160-224). Its catch block makes no status writes without established tenantContext, and later error-status writes retain tenant scopes (index.js:368-404). A VM probe of a missing profile recorded only SQS deletion and the profile read; SQS deletion is standard acknowledgment behavior.
## synthesis-prevent-unauthorized-side-effects — PASS
The synthesis worker resolves the profile and validates its userId, then requires tenant-scoped RecordingSalutation and Recording matches before mkdir, Python rendering, S3 upload, Salutation mutation, or Job creation (index.js:119-180). Missing-profile and missing-target VM probes reached no file creation, rendering, upload, or database mutation; only standard SQS deletion and reads occurred.
## initial-profile-tenant-resolution — PASS
Both workers call readForTenantResolution with userAudioProfileId first (cloning index.js:165-181; synthesis index.js:119-139). Each service performs the intentional UserAudioProfile.findOne({_id, deleted:false}) bootstrap lookup, then obtains userId from the returned profile (both user_audio_profile_service.js:69-85). This is the allowed unscoped initial query.
## scoped-update-null-handling — PARTIAL
The cloning worker checks each normal scoped update with requireUpdatedRecord (index.js:96-104, 213-224, 324-367), and synthesis checks the RecordingSalutation update result (index.js:221-240). However synthesis ignores the result of salutationService.updateOrCreate (index.js:210-217); its scoped Salutation.findOneAndUpdate can return null (salutation_service.js:23-29, 45-62), after which the worker still updates RecordingSalutation and inserts a Job. A mock-model run confirmed the helper returns null on a zero-match update. Cloning catch-block status updates and scoped removeMany helpers also do not inspect null/zero-match results, a smaller defensive gap.
## worker-loop-crash-prevention — PASS
Both workers catch per-message processing errors and outer queue errors, resolve processQueue, and call it again from their polling loops (cloning index.js:368-440; synthesis index.js:277-322). The missing-profile VM probes completed without an unhandled exception. Existing SQS acknowledgment occurs before processing and is permitted by the rubric.
## refactor-summary-accuracy — PARTIAL
The final transcript message correctly summarizes the profile-derived preflight, active worker predicates, ID validation, and worker catches; its syntax/diff and focused mock-test claims match transcript steps 19 and 24. Its unqualified claim that all affected reads/updates include userId overstates the result because unscoped Salutation and Job service methods remain. The claim that mutations stop on ownership failure also omits the unchecked null result from the scoped Salutation update before later writes.
## Closing
Final-tree syntax and diff checks passed; focused VM and mock-model probes passed. No repository test script or live AWS/Mongo integration was available.

View File

@@ -0,0 +1,37 @@
Rubric score (trinary): 0.95 (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 initial profile lookup, then reads VoiceCloning with _id, userId, and userAudioProfileId and passes tenant scopes to every normal and error-status update (voice-cloning-job-handler/index.js:167-204, 213-224, 324-395). The VoiceCloning and UserAudioProfile service read/find/update/remove methods enforce userId through withTenantScope (voice_cloning_service.js:11-21, 53-142; user_audio_profile_service.js:11-21, 53-165). The profile-by-ID bootstrap is the permitted exception.
## synthesis-tenant-isolation-queries-updates — PARTIAL
The active synthesis path scopes RecordingSalutation and Recording reads and the RecordingSalutation update with the profile-derived userId; Salutation.updateOrCreate uses that userId for its read/update/create, and the new Job receives it (voice-synthsizer-job-handler/index.js:139-156, 210-273; salutation/salutation_service.js:45-62). But other exported synthesis service operations still allow unscoped reads or updates: Salutation.read/find accept filters without userId and modify filters only by _id or transcriptId (salutation_service.js:7-42); Job.read/find/update/remove/removeMany also lack a required userId (job/job_service.js:32-123). Thus the requested all-operations scope is incomplete, although those helpers are not called by this worker's current message path.
## cloning-prevent-unauthorized-side-effects — PASS
The cloning worker rejects invalid IDs or a missing/invalid profile userId before file creation, rendering, or Mongo mutations, and also rejects a missing tenant-scoped VoiceCloning record before those effects (index.js:160-224). Its catch block makes no status writes without established tenantContext, and later error-status writes retain tenant scopes (index.js:368-404). A VM probe of a missing profile recorded only SQS deletion and the profile read; SQS deletion is standard acknowledgment behavior.
## synthesis-prevent-unauthorized-side-effects — PASS
The synthesis worker resolves the profile and validates its userId, then requires tenant-scoped RecordingSalutation and Recording matches before mkdir, Python rendering, S3 upload, Salutation mutation, or Job creation (index.js:119-180). Missing-profile and missing-target VM probes reached no file creation, rendering, upload, or database mutation; only standard SQS deletion and reads occurred.
## initial-profile-tenant-resolution — PASS
Both workers call readForTenantResolution with userAudioProfileId first (cloning index.js:165-181; synthesis index.js:119-139). Each service performs the intentional UserAudioProfile.findOne({_id, deleted:false}) bootstrap lookup, then obtains userId from the returned profile (both user_audio_profile_service.js:69-85). This is the allowed unscoped initial query.
## scoped-update-null-handling — PARTIAL
The cloning worker checks each normal scoped update with requireUpdatedRecord (index.js:96-104, 213-224, 324-367), and synthesis checks the RecordingSalutation update result (index.js:221-240). However synthesis ignores the result of salutationService.updateOrCreate (index.js:210-217); its scoped Salutation.findOneAndUpdate can return null (salutation_service.js:23-29, 45-62), after which the worker still updates RecordingSalutation and inserts a Job. A mock-model run confirmed the helper returns null on a zero-match update. Cloning catch-block status updates and scoped removeMany helpers also do not inspect null/zero-match results, a smaller defensive gap.
## worker-loop-crash-prevention — PASS
Both workers catch per-message processing errors and outer queue errors, resolve processQueue, and call it again from their polling loops (cloning index.js:368-440; synthesis index.js:277-322). The missing-profile VM probes completed without an unhandled exception. Existing SQS acknowledgment occurs before processing and is permitted by the rubric.
## refactor-summary-accuracy — PARTIAL
The final transcript message correctly summarizes the profile-derived preflight, active worker predicates, ID validation, and worker catches; its syntax/diff and focused mock-test claims match transcript steps 19 and 24. Its unqualified claim that all affected reads/updates include userId overstates the result because unscoped Salutation and Job service methods remain. The claim that mutations stop on ownership failure also omits the unchecked null result from the scoped Salutation update before later writes.
## Closing
Final-tree syntax and diff checks passed; focused VM and mock-model probes passed. No repository test script or live AWS/Mongo integration was available.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-22T18:25:55Z",
"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": "ce5ad0f6e94a9d26f691a6b835d34b8c0bfc61c801d916c2d5088fbdf36a66db",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a164dc-d66b-7c82-8df3-d02b0ff1168c", "usage": {"input_tokens": 1113669, "cached_input_tokens": 1033170, "cache_write_input_tokens": 80445, "output_tokens": 11863, "reasoning_output_tokens": 5900}}

View File

@@ -0,0 +1 @@
{"session_id": "01a164dc-d66b-7c82-8df3-d02b0ff1168c", "usage": {"input_tokens": 1113669, "cached_input_tokens": 1033170, "cache_write_input_tokens": 80445, "output_tokens": 11863, "reasoning_output_tokens": 5900}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 0.95
mean: 0.9500
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.uuVrjkW6"))

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

View File

@@ -0,0 +1,51 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "The cloning worker derives userId from the initial profile lookup, then reads VoiceCloning with _id, userId, and userAudioProfileId and passes tenant scopes to every normal and error-status update (voice-cloning-job-handler/index.js:167-204, 213-224, 324-395). The VoiceCloning and UserAudioProfile service read/find/update/remove methods enforce userId through withTenantScope (voice_cloning_service.js:11-21, 53-142; user_audio_profile_service.js:11-21, 53-165). The profile-by-ID bootstrap is the permitted exception.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The active synthesis path scopes RecordingSalutation and Recording reads and the RecordingSalutation update with the profile-derived userId; Salutation.updateOrCreate uses that userId for its read/update/create, and the new Job receives it (voice-synthsizer-job-handler/index.js:139-156, 210-273; salutation/salutation_service.js:45-62). But other exported synthesis service operations still allow unscoped reads or updates: Salutation.read/find accept filters without userId and modify filters only by _id or transcriptId (salutation_service.js:7-42); Job.read/find/update/remove/removeMany also lack a required userId (job/job_service.js:32-123). Thus the requested all-operations scope is incomplete, although those helpers are not called by this worker's current message path.",
"verdict": "partial"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The cloning worker rejects invalid IDs or a missing/invalid profile userId before file creation, rendering, or Mongo mutations, and also rejects a missing tenant-scoped VoiceCloning record before those effects (index.js:160-224). Its catch block makes no status writes without established tenantContext, and later error-status writes retain tenant scopes (index.js:368-404). A VM probe of a missing profile recorded only SQS deletion and the profile read; SQS deletion is standard acknowledgment behavior.",
"verdict": "pass"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The synthesis worker resolves the profile and validates its userId, then requires tenant-scoped RecordingSalutation and Recording matches before mkdir, Python rendering, S3 upload, Salutation mutation, or Job creation (index.js:119-180). Missing-profile and missing-target VM probes reached no file creation, rendering, upload, or database mutation; only standard SQS deletion and reads occurred.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both workers call readForTenantResolution with userAudioProfileId first (cloning index.js:165-181; synthesis index.js:119-139). Each service performs the intentional UserAudioProfile.findOne({_id, deleted:false}) bootstrap lookup, then obtains userId from the returned profile (both user_audio_profile_service.js:69-85). This is the allowed unscoped initial query.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The cloning worker checks each normal scoped update with requireUpdatedRecord (index.js:96-104, 213-224, 324-367), and synthesis checks the RecordingSalutation update result (index.js:221-240). However synthesis ignores the result of salutationService.updateOrCreate (index.js:210-217); its scoped Salutation.findOneAndUpdate can return null (salutation_service.js:23-29, 45-62), after which the worker still updates RecordingSalutation and inserts a Job. A mock-model run confirmed the helper returns null on a zero-match update. Cloning catch-block status updates and scoped removeMany helpers also do not inspect null/zero-match results, a smaller defensive gap.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch per-message processing errors and outer queue errors, resolve processQueue, and call it again from their polling loops (cloning index.js:368-440; synthesis index.js:277-322). The missing-profile VM probes completed without an unhandled exception. Existing SQS acknowledgment occurs before processing and is permitted by the rubric.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final transcript message correctly summarizes the profile-derived preflight, active worker predicates, ID validation, and worker catches; its syntax/diff and focused mock-test claims match transcript steps 19 and 24. Its unqualified claim that all affected reads/updates include userId overstates the result because unscoped Salutation and Job service methods remain. The claim that mutations stop on ownership failure also omits the unchecked null result from the scoped Salutation update before later writes.",
"verdict": "partial"
}
],
"closing": "Final-tree syntax and diff checks passed; focused VM and mock-model probes passed. No repository test script or live AWS/Mongo integration was available.",
"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 initial profile lookup, then reads VoiceCloning with _id, userId, and userAudioProfileId and passes tenant scopes to every normal and error-status update (voice-cloning-job-handler/index.js:167-204, 213-224, 324-395). The VoiceCloning and UserAudioProfile service read/find/update/remove methods enforce userId through withTenantScope (voice_cloning_service.js:11-21, 53-142; user_audio_profile_service.js:11-21, 53-165). The profile-by-ID bootstrap is the permitted exception.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The active synthesis path scopes RecordingSalutation and Recording reads and the RecordingSalutation update with the profile-derived userId; Salutation.updateOrCreate uses that userId for its read/update/create, and the new Job receives it (voice-synthsizer-job-handler/index.js:139-156, 210-273; salutation/salutation_service.js:45-62). But other exported synthesis service operations still allow unscoped reads or updates: Salutation.read/find accept filters without userId and modify filters only by _id or transcriptId (salutation_service.js:7-42); Job.read/find/update/remove/removeMany also lack a required userId (job/job_service.js:32-123). Thus the requested all-operations scope is incomplete, although those helpers are not called by this worker's current message path.",
"verdict": "partial"
},
{
"id": "cloning-prevent-unauthorized-side-effects",
"rationale": "The cloning worker rejects invalid IDs or a missing/invalid profile userId before file creation, rendering, or Mongo mutations, and also rejects a missing tenant-scoped VoiceCloning record before those effects (index.js:160-224). Its catch block makes no status writes without established tenantContext, and later error-status writes retain tenant scopes (index.js:368-404). A VM probe of a missing profile recorded only SQS deletion and the profile read; SQS deletion is standard acknowledgment behavior.",
"verdict": "pass"
},
{
"id": "synthesis-prevent-unauthorized-side-effects",
"rationale": "The synthesis worker resolves the profile and validates its userId, then requires tenant-scoped RecordingSalutation and Recording matches before mkdir, Python rendering, S3 upload, Salutation mutation, or Job creation (index.js:119-180). Missing-profile and missing-target VM probes reached no file creation, rendering, upload, or database mutation; only standard SQS deletion and reads occurred.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "Both workers call readForTenantResolution with userAudioProfileId first (cloning index.js:165-181; synthesis index.js:119-139). Each service performs the intentional UserAudioProfile.findOne({_id, deleted:false}) bootstrap lookup, then obtains userId from the returned profile (both user_audio_profile_service.js:69-85). This is the allowed unscoped initial query.",
"verdict": "pass"
},
{
"id": "scoped-update-null-handling",
"rationale": "The cloning worker checks each normal scoped update with requireUpdatedRecord (index.js:96-104, 213-224, 324-367), and synthesis checks the RecordingSalutation update result (index.js:221-240). However synthesis ignores the result of salutationService.updateOrCreate (index.js:210-217); its scoped Salutation.findOneAndUpdate can return null (salutation_service.js:23-29, 45-62), after which the worker still updates RecordingSalutation and inserts a Job. A mock-model run confirmed the helper returns null on a zero-match update. Cloning catch-block status updates and scoped removeMany helpers also do not inspect null/zero-match results, a smaller defensive gap.",
"verdict": "partial"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both workers catch per-message processing errors and outer queue errors, resolve processQueue, and call it again from their polling loops (cloning index.js:368-440; synthesis index.js:277-322). The missing-profile VM probes completed without an unhandled exception. Existing SQS acknowledgment occurs before processing and is permitted by the rubric.",
"verdict": "pass"
},
{
"id": "refactor-summary-accuracy",
"rationale": "The final transcript message correctly summarizes the profile-derived preflight, active worker predicates, ID validation, and worker catches; its syntax/diff and focused mock-test claims match transcript steps 19 and 24. Its unqualified claim that all affected reads/updates include userId overstates the result because unscoped Salutation and Job service methods remain. The claim that mutations stop on ownership failure also omits the unchecked null result from the scoped Salutation update before later writes.",
"verdict": "partial"
}
],
"closing": "Final-tree syntax and diff checks passed; focused VM and mock-model probes passed. No repository test script or live AWS/Mongo integration was available.",
"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.95 form=trinary criteria=8 excluded_extra_credit=0 partial_extra_credit=0 total_weight=66
grader sample 1: 0.95
reward: 0.9500 correctness: (none)
0.9500
{"reward": 0.9500}

View File

@@ -0,0 +1,39 @@
{
"id": "b5522b09-ec29-4019-9f32-8229f16a8a99",
"started_at": "2026-10-22T18:25:49.866026",
"updated_at": "2026-10-22T18:28:31.508096",
"finished_at": "2026-10-22T18:28:31.508096",
"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.95
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"0.95": [
"potion-voice-user-ownership__uz4SZdJ"
]
}
},
"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.8800-pdFfcXv-1792693811-16068",
"jobs_dir": "harbor-jobs/reward-0.8800-pdFfcXv",
"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.8800-pdFfcXv",
"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-22T18:30:11.896019Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"ModelNotFoundError",
"AgentSafetyRefusalError",
"AgentTimeoutError",
"AgentAuthenticationError",
"ApiUsageLimitError",
"RewardFileNotFoundError",
"VerifierOutputParseError",
"RewardFileEmptyError",
"VerifierTimeoutError"
],
"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:62f127e2d7acca7be9d2dc877aacfadc21a899b67287c828ba333fed7d7460bd",
"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.8800-pdFfcXv",
"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__SL2dss7",
"trials_dir": "harbor-jobs/reward-0.8800-pdFfcXv/regrade-reward-0.8800-pdFfcXv-1792693811-16068",
"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.8800-pdFfcXv",
"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": "b7d9459a-f146-4d9b-bf6b-50868ea64c1a"
}

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